feat(assistant): complete controlled management attachments and native schedules
This commit is contained in:
1 parent
d0bc4b0da2
commit
8341986067
119 files changed
+20519
-1618
No files matched your search
@@ -1,78 +1,432 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
|
||||
const admin={user:{id:'admin',username:'admin',role:'admin'},sessionId:'admin-session'},operator={user:{id:'operator',username:'operator',role:'operator'},sessionId:'operator-session'},viewer={user:{id:'viewer',username:'viewer',role:'viewer'},sessionId:'viewer-session'};
|
||||
async function fixture(t,runtime){
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs');
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-assistant-')),store=new AssistantStore(dir);let checks=0,scans=0,archives=0;
|
||||
const connections=[{id:'own',owner:'operator',name:'Own BPM',status:'connected',identity:'PRIVATE_IDENTITY'},{id:'other',owner:'other',name:'Other BPM',status:'connected'}];
|
||||
const workspace={snapshot:()=>({connections,exceptions:[{id:'e1',owner:'operator',title:'扫描失败',status:'open',description:'password=PRIVATE_PASSWORD Cookie=PRIVATE_COOKIE'}]}),getConnection:id=>connections.find(c=>c.id===id),record(){}};
|
||||
const storage={store:{servers:()=>[{id:'server',name:'Archive',enabled:true,username:'SECRET_USER',password:'PRIVATE_PASSWORD',state:{readable:true,writable:true,message:'open C:/PRIVATE_FOLDER/file.txt'}}],archives:()=>[{id:'archive',status:'error',serverId:'server',jobId:'pdf',baseDirectory:'产业A',error:'共享不可用'}]},check:async()=>{checks++;return {state:{readable:true,writable:true}};},archive:async()=>{archives++;return {status:'success',relativePath:'产业A/123456/file.pdf'};}};
|
||||
const scanner={store:{status:()=>({config:{enabled:true},runs:[{connectionId:'own',status:'success'},{connectionId:'other',status:'error',message:'Cookie=PRIVATE_COOKIE'}]})},scan:async()=>{scans++;return {seen:2,added:0};}};
|
||||
const dashboard={jobs:()=>[{jobId:'pdf',status:'success',path:'C:/PRIVATE_PATH/file.pdf',metadata:{order:'123456'}}]};
|
||||
const service=new AssistantService({store,workspace,storage,scanner,dashboard,runtime:runtime||{probe:async()=>({available:true,version:'3.14.3'}),chat:async()=>JSON.stringify({reply:'已查询状态',actions:[]})}});
|
||||
t.after(async()=>{await service.stop();store.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'test-model',apiKey:'PRIVATE_API_KEY',allowActions:true});
|
||||
return {dir,store,service,workspace,counters:()=>({checks,scans,archives})};
|
||||
const { test } = require('node:test'),
|
||||
assert = require('node:assert/strict'),
|
||||
fs = require('node:fs/promises'),
|
||||
os = require('node:os'),
|
||||
path = require('node:path');
|
||||
const admin = {
|
||||
user: { id: 'admin', username: 'admin', role: 'admin' },
|
||||
sessionId: 'admin-session',
|
||||
},
|
||||
operator = {
|
||||
user: { id: 'operator', username: 'operator', role: 'operator' },
|
||||
sessionId: 'operator-session',
|
||||
},
|
||||
viewer = {
|
||||
user: { id: 'viewer', username: 'viewer', role: 'viewer' },
|
||||
sessionId: 'viewer-session',
|
||||
};
|
||||
async function fixture(t, runtime) {
|
||||
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
|
||||
{ AssistantService } = require('../../src/modules/assistant/service.cjs');
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'order-assistant-')),
|
||||
store = new AssistantStore(dir);
|
||||
let checks = 0,
|
||||
scans = 0,
|
||||
archives = 0;
|
||||
const connections = [
|
||||
{
|
||||
id: 'own',
|
||||
owner: 'operator',
|
||||
name: 'Own BPM',
|
||||
status: 'connected',
|
||||
identity: 'PRIVATE_IDENTITY',
|
||||
},
|
||||
{ id: 'other', owner: 'other', name: 'Other BPM', status: 'connected' },
|
||||
];
|
||||
const workspace = {
|
||||
snapshot: () => ({
|
||||
connections,
|
||||
exceptions: [
|
||||
{
|
||||
id: 'e1',
|
||||
owner: 'operator',
|
||||
title: '扫描失败',
|
||||
status: 'open',
|
||||
description: 'password=PRIVATE_PASSWORD Cookie=PRIVATE_COOKIE',
|
||||
},
|
||||
],
|
||||
}),
|
||||
getConnection: (id) => connections.find((c) => c.id === id),
|
||||
record() {},
|
||||
};
|
||||
const storage = {
|
||||
store: {
|
||||
servers: () => [
|
||||
{
|
||||
id: 'server',
|
||||
name: 'Archive',
|
||||
enabled: true,
|
||||
username: 'SECRET_USER',
|
||||
password: 'PRIVATE_PASSWORD',
|
||||
state: { readable: true, writable: true, message: 'open C:/PRIVATE_FOLDER/file.txt' },
|
||||
},
|
||||
],
|
||||
archives: () => [
|
||||
{
|
||||
id: 'archive',
|
||||
status: 'error',
|
||||
serverId: 'server',
|
||||
jobId: 'pdf',
|
||||
baseDirectory: '产业A',
|
||||
error: '共享不可用',
|
||||
},
|
||||
],
|
||||
},
|
||||
check: async () => {
|
||||
checks++;
|
||||
return { state: { readable: true, writable: true } };
|
||||
},
|
||||
archive: async () => {
|
||||
archives++;
|
||||
return { status: 'success', relativePath: '产业A/123456/file.pdf' };
|
||||
},
|
||||
};
|
||||
const scanner = {
|
||||
store: {
|
||||
status: () => ({
|
||||
config: { enabled: true },
|
||||
runs: [
|
||||
{ connectionId: 'own', status: 'success' },
|
||||
{ connectionId: 'other', status: 'error', message: 'Cookie=PRIVATE_COOKIE' },
|
||||
],
|
||||
}),
|
||||
},
|
||||
scan: async () => {
|
||||
scans++;
|
||||
return { seen: 2, added: 0 };
|
||||
},
|
||||
};
|
||||
const dashboard = {
|
||||
jobs: () => [
|
||||
{
|
||||
jobId: 'pdf',
|
||||
status: 'success',
|
||||
path: 'C:/PRIVATE_PATH/file.pdf',
|
||||
metadata: { order: '123456' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const service = new AssistantService({
|
||||
store,
|
||||
workspace,
|
||||
storage,
|
||||
scanner,
|
||||
dashboard,
|
||||
runtime: runtime || {
|
||||
probe: async () => ({ available: true, version: '3.14.3' }),
|
||||
chat: async () => JSON.stringify({ reply: '已查询状态', actions: [] }),
|
||||
},
|
||||
});
|
||||
t.after(async () => {
|
||||
await service.stop();
|
||||
store.close();
|
||||
await fs.rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
store.saveSettings({
|
||||
...store.settings(),
|
||||
enabled: true,
|
||||
runtimePath: process.execPath,
|
||||
apiBase: 'https://models.example/v1',
|
||||
model: 'test-model',
|
||||
apiKey: 'PRIVATE_API_KEY',
|
||||
allowActions: true,
|
||||
});
|
||||
return { dir, store, service, workspace, counters: () => ({ checks, scans, archives }) };
|
||||
}
|
||||
|
||||
test('nested JSON and complete credential headers are absent from runtime inputs and persisted history',async t=>{
|
||||
const calls=[],payload='{"nested":{"password":"dummy p a s s","cookie":"dummy=a; dummy2=b","authorization":"Basic dummy credential"}}\nCookie: dummySession=x; dummyCsrf=y\nAuthorization: Custom dummy auth value\nC:/local/private.txt';
|
||||
const {store,service}=await fixture(t,{chat:async input=>{calls.push(input);return JSON.stringify({reply:payload,actions:[]});}}),conversation=store.create(admin.user.id);
|
||||
for(const text of [payload,'follow up']){const turn=service.send(conversation.id,admin,text);await service.running.get(turn.id).task;}
|
||||
const actual=JSON.stringify({inputs:calls.map(({config,signal,...input})=>input),persisted:store.conversation(conversation.id,admin.user.id)});
|
||||
for(const secret of ['dummy p a s s','dummy=a','dummy2=b','dummy credential','dummySession=x','dummyCsrf=y','dummy auth value','local/private.txt'])assert.equal(actual.includes(secret),false,secret);
|
||||
test('configured DSH is usable without a separate enable switch', async (t) => {
|
||||
const { store, service } = await fixture(t);
|
||||
store.saveSettings({ ...store.settings(), enabled: false });
|
||||
const conversation = store.create(admin.user.id);
|
||||
const turn = service.send(conversation.id, admin, '测试配置');
|
||||
await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(conversation.id, admin.user.id).turns[0].status, 'success');
|
||||
});
|
||||
|
||||
test('structured credential values at arbitrary depth and escaped JSON logs are removed before runtime and store',async t=>{
|
||||
const calls=[],deep={password:{a:{b:{c:'FAKE_DEEP_SECRET'}}},nested:[{cookie:[{a:[{b:'FAKE_ARRAY_SECRET'}]}]}],variants:{access_token:'FAKE_ACCESS_SECRET',refreshToken:'FAKE_REFRESH_SECRET','CLIENT-SECRET':'FAKE_CLIENT_SECRET',secret:'FAKE_BARE_SECRET','session_cookie':'FAKE_SESSION_SECRET'}},escaped={payload:{token:{a:{b:{c:'FAKE_ESCAPED_SECRET'}}}}};
|
||||
const payloads=[JSON.stringify(deep,null,2),'debug '+JSON.stringify(JSON.stringify(escaped))];
|
||||
const {store,service}=await fixture(t,{chat:async input=>{calls.push(input);return JSON.stringify({reply:payloads.join('\n'),actions:[]});}}),conversation=store.create(admin.user.id);
|
||||
for(const text of payloads){const turn=service.send(conversation.id,admin,text);await service.running.get(turn.id).task;}
|
||||
const actual=JSON.stringify({inputs:calls.map(({config,signal,...input})=>input),persisted:store.conversation(conversation.id,admin.user.id)});
|
||||
assert.doesNotMatch(actual,/FAKE_(?:DEEP|ARRAY|ESCAPED|ACCESS|REFRESH|CLIENT|BARE|SESSION)_SECRET/);
|
||||
test('nested JSON and complete credential headers are absent from runtime inputs and persisted history', async (t) => {
|
||||
const calls = [],
|
||||
payload =
|
||||
'{"nested":{"password":"dummy p a s s","cookie":"dummy=a; dummy2=b","authorization":"Basic dummy credential"}}\nCookie: dummySession=x; dummyCsrf=y\nAuthorization: Custom dummy auth value\nC:/local/private.txt';
|
||||
const { store, service } = await fixture(t, {
|
||||
chat: async (input) => {
|
||||
calls.push(input);
|
||||
return JSON.stringify({ reply: payload, actions: [] });
|
||||
},
|
||||
}),
|
||||
conversation = store.create(admin.user.id);
|
||||
for (const text of [payload, 'follow up']) {
|
||||
const turn = service.send(conversation.id, admin, text);
|
||||
await service.running.get(turn.id).task;
|
||||
}
|
||||
const actual = JSON.stringify({
|
||||
inputs: calls.map(({ config, signal, ...input }) => input),
|
||||
persisted: store.conversation(conversation.id, admin.user.id),
|
||||
});
|
||||
for (const secret of [
|
||||
'dummy p a s s',
|
||||
'dummy=a',
|
||||
'dummy2=b',
|
||||
'dummy credential',
|
||||
'dummySession=x',
|
||||
'dummyCsrf=y',
|
||||
'dummy auth value',
|
||||
'local/private.txt',
|
||||
])
|
||||
assert.equal(actual.includes(secret), false, secret);
|
||||
});
|
||||
test('assistant conversations are private, encrypted and survive restart without exposing the API key',async t=>{
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{dir,store,service}=await fixture(t),c=store.create(admin.user.id);const turn=service.send(c.id,admin,'PRIVATE_CHAT_MESSAGE');await service.running.get(turn.id).task;
|
||||
assert.throws(()=>store.conversation(c.id,operator.user.id),e=>e.status===404);assert.deepEqual(store.conversations(operator.user.id),[]);assert.equal(store.settings().hasApiKey,true);assert.equal(store.settings().apiKey,undefined);
|
||||
const restart=new AssistantStore(dir);try{assert.equal(restart.conversation(c.id,admin.user.id).turns[0].text,'PRIVATE_CHAT_MESSAGE');assert.equal(restart.secretSettings().apiKey,'PRIVATE_API_KEY');}finally{restart.close();}
|
||||
for(const name of await fs.readdir(dir))if(name.includes('.sqlite')){const bytes=await fs.readFile(path.join(dir,name));assert.equal(bytes.includes(Buffer.from('PRIVATE_CHAT_MESSAGE')),false);assert.equal(bytes.includes(Buffer.from('PRIVATE_API_KEY')),false);}
|
||||
|
||||
test('structured credential values at arbitrary depth and escaped JSON logs are removed before runtime and store', async (t) => {
|
||||
const calls = [],
|
||||
deep = {
|
||||
password: { a: { b: { c: 'FAKE_DEEP_SECRET' } } },
|
||||
nested: [{ cookie: [{ a: [{ b: 'FAKE_ARRAY_SECRET' }] }] }],
|
||||
variants: {
|
||||
access_token: 'FAKE_ACCESS_SECRET',
|
||||
refreshToken: 'FAKE_REFRESH_SECRET',
|
||||
'CLIENT-SECRET': 'FAKE_CLIENT_SECRET',
|
||||
secret: 'FAKE_BARE_SECRET',
|
||||
'session_cookie': 'FAKE_SESSION_SECRET',
|
||||
},
|
||||
},
|
||||
escaped = { payload: { token: { a: { b: { c: 'FAKE_ESCAPED_SECRET' } } } } };
|
||||
const payloads = [
|
||||
JSON.stringify(deep, null, 2),
|
||||
'debug ' + JSON.stringify(JSON.stringify(escaped)),
|
||||
];
|
||||
const { store, service } = await fixture(t, {
|
||||
chat: async (input) => {
|
||||
calls.push(input);
|
||||
return JSON.stringify({ reply: payloads.join('\n'), actions: [] });
|
||||
},
|
||||
}),
|
||||
conversation = store.create(admin.user.id);
|
||||
for (const text of payloads) {
|
||||
const turn = service.send(conversation.id, admin, text);
|
||||
await service.running.get(turn.id).task;
|
||||
}
|
||||
const actual = JSON.stringify({
|
||||
inputs: calls.map(({ config, signal, ...input }) => input),
|
||||
persisted: store.conversation(conversation.id, admin.user.id),
|
||||
});
|
||||
assert.doesNotMatch(
|
||||
actual,
|
||||
/FAKE_(?:DEEP|ARRAY|ESCAPED|ACCESS|REFRESH|CLIENT|BARE|SESSION)_SECRET/,
|
||||
);
|
||||
});
|
||||
test('model gets only permitted diagnostic fields and unsupported actions never execute',async t=>{
|
||||
let request;const runtime={chat:async input=>{request=input;return JSON.stringify({reply:'状态已读取',actions:[{kind:'shell',targetId:'server'}]});}};const {store,service,counters}=await fixture(t,runtime),c=store.create(operator.user.id),turn=service.send(c.id,operator,'分析失败');await service.running.get(turn.id).task;
|
||||
const context=JSON.stringify(request.context);assert.doesNotMatch(context,/PRIVATE_|SECRET_USER|C:\/|Other BPM|other"/);assert.equal(store.conversation(c.id,operator.user.id).turns[0].status,'error');assert.deepEqual(counters(),{checks:0,scans:0,archives:0});
|
||||
test('assistant conversations are private, encrypted and survive restart without exposing the API key', async (t) => {
|
||||
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
|
||||
{ dir, store, service } = await fixture(t),
|
||||
c = store.create(admin.user.id);
|
||||
const turn = service.send(c.id, admin, 'PRIVATE_CHAT_MESSAGE');
|
||||
await service.running.get(turn.id).task;
|
||||
assert.throws(
|
||||
() => store.conversation(c.id, operator.user.id),
|
||||
(e) => e.status === 404,
|
||||
);
|
||||
assert.deepEqual(store.conversations(operator.user.id), []);
|
||||
assert.equal(store.settings().hasApiKey, true);
|
||||
assert.equal(store.settings().apiKey, undefined);
|
||||
const restart = new AssistantStore(dir);
|
||||
try {
|
||||
assert.equal(restart.conversation(c.id, admin.user.id).turns[0].text, 'PRIVATE_CHAT_MESSAGE');
|
||||
assert.equal(restart.secretSettings().apiKey, 'PRIVATE_API_KEY');
|
||||
} finally {
|
||||
restart.close();
|
||||
}
|
||||
for (const name of await fs.readdir(dir))
|
||||
if (name.includes('.sqlite')) {
|
||||
const bytes = await fs.readFile(path.join(dir, name));
|
||||
assert.equal(bytes.includes(Buffer.from('PRIVATE_CHAT_MESSAGE')), false);
|
||||
assert.equal(bytes.includes(Buffer.from('PRIVATE_API_KEY')), false);
|
||||
}
|
||||
});
|
||||
test('fixed action cards require opt-in and current role, check ownership and are single use',async t=>{
|
||||
const runtime={chat:async()=>JSON.stringify({reply:'建议检查共享',actions:[{kind:'check_storage',targetId:'server'},{kind:'scan_bpm',targetId:'own'},{kind:'retry_archive',targetId:'archive'}]})};const {store,service,counters}=await fixture(t,runtime),c=store.create(admin.user.id),turn=service.send(c.id,admin,'检查情况');await service.running.get(turn.id).task;
|
||||
let saved=store.conversation(c.id,admin.user.id).turns[0];assert.deepEqual(counters(),{checks:0,scans:0,archives:0});assert.equal(saved.actions.length,3);
|
||||
await assert.rejects(service.executeAction(c.id,saved.actions[0].id,{...viewer,user:{...viewer.user,id:admin.user.id}}),e=>e.status===403);
|
||||
for(const action of saved.actions)await service.executeAction(c.id,action.id,admin);
|
||||
assert.deepEqual(counters(),{checks:1,scans:1,archives:1});await assert.rejects(service.executeAction(c.id,saved.actions[0].id,admin),e=>e.status===409);
|
||||
store.saveSettings({...store.settings(),apiKey:'',allowActions:false});saved=store.conversation(c.id,admin.user.id).turns[0];assert.ok(saved.actions.every(a=>a.status==='success'));
|
||||
test('model gets only permitted diagnostic fields and unsupported actions never execute', async (t) => {
|
||||
let request;
|
||||
const runtime = {
|
||||
chat: async (input) => {
|
||||
request = input;
|
||||
return JSON.stringify({
|
||||
reply: '状态已读取',
|
||||
actions: [{ kind: 'shell', targetId: 'server' }],
|
||||
});
|
||||
},
|
||||
};
|
||||
const { store, service, counters } = await fixture(t, runtime),
|
||||
c = store.create(operator.user.id),
|
||||
turn = service.send(c.id, operator, '分析失败');
|
||||
await service.running.get(turn.id).task;
|
||||
const context = JSON.stringify(request.context);
|
||||
assert.doesNotMatch(context, /PRIVATE_|SECRET_USER|C:\/|Other BPM|other"/);
|
||||
assert.equal(store.conversation(c.id, operator.user.id).turns[0].status, 'error');
|
||||
assert.deepEqual(counters(), { checks: 0, scans: 0, archives: 0 });
|
||||
});
|
||||
test('unauthorized BPM targets are rejected, and disabling actions also blocks previously proposed cards',async t=>{
|
||||
let other=true;const {store,service,counters}=await fixture(t,{chat:async()=>JSON.stringify({reply:'建议扫描',actions:[{kind:'scan_bpm',targetId:other?'other':'own'}]})}),c=store.create(operator.user.id);let turn=service.send(c.id,operator,'扫描');await service.running.get(turn.id).task;assert.equal(store.conversation(c.id,operator.user.id).turns[0].status,'error');other=false;
|
||||
turn=service.send(c.id,operator,'扫描我的连接');await service.running.get(turn.id).task;const action=store.conversation(c.id,operator.user.id).turns.at(-1).actions[0];store.saveSettings({...store.settings(),apiKey:'',allowActions:false});await assert.rejects(service.executeAction(c.id,action.id,operator),e=>e.status===403);assert.equal(counters().scans,0);
|
||||
test('fixed action cards require opt-in and current role, check ownership and are single use', async (t) => {
|
||||
const runtime = {
|
||||
chat: async () =>
|
||||
JSON.stringify({
|
||||
reply: '建议检查共享',
|
||||
actions: [
|
||||
{ kind: 'check_storage', targetId: 'server' },
|
||||
{ kind: 'scan_bpm', targetId: 'own' },
|
||||
{ kind: 'retry_archive', targetId: 'archive' },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const { store, service, counters } = await fixture(t, runtime),
|
||||
c = store.create(admin.user.id),
|
||||
turn = service.send(c.id, admin, '检查情况');
|
||||
await service.running.get(turn.id).task;
|
||||
let saved = store.conversation(c.id, admin.user.id).turns[0];
|
||||
assert.deepEqual(counters(), { checks: 0, scans: 0, archives: 0 });
|
||||
assert.equal(saved.actions.length, 3);
|
||||
await assert.rejects(
|
||||
service.executeAction(c.id, saved.actions[0].id, {
|
||||
...viewer,
|
||||
user: { ...viewer.user, id: admin.user.id },
|
||||
}),
|
||||
(e) => e.status === 403,
|
||||
);
|
||||
for (const action of saved.actions) await service.executeAction(c.id, action.id, admin);
|
||||
assert.deepEqual(counters(), { checks: 1, scans: 1, archives: 1 });
|
||||
await assert.rejects(
|
||||
service.executeAction(c.id, saved.actions[0].id, admin),
|
||||
(e) => e.status === 409,
|
||||
);
|
||||
store.saveSettings({ ...store.settings(), apiKey: '', allowActions: false });
|
||||
saved = store.conversation(c.id, admin.user.id).turns[0];
|
||||
assert.ok(saved.actions.every((a) => a.status === 'success'));
|
||||
});
|
||||
test('cancellation, per-conversation serialization and daily limits retain truthful task states',async t=>{
|
||||
const {store,service}=await fixture(t,{chat:({signal})=>new Promise((resolve,reject)=>{if(signal.aborted)reject(signal.reason);else signal.addEventListener('abort',()=>reject(signal.reason),{once:true});})}),c=store.create(admin.user.id);store.saveSettings({...store.settings(),apiKey:'',dailyLimit:1});const turn=service.send(c.id,admin,'分析');assert.throws(()=>service.send(c.id,admin,'重复'),e=>e.status===409);service.cancel(c.id,admin);await service.running.get(turn.id).task;assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'cancelled');assert.throws(()=>service.send(c.id,admin,'第二次'),e=>e.status===429);
|
||||
test('unauthorized BPM targets are rejected, and disabling actions also blocks previously proposed cards', async (t) => {
|
||||
let other = true;
|
||||
const { store, service, counters } = await fixture(t, {
|
||||
chat: async () =>
|
||||
JSON.stringify({
|
||||
reply: '建议扫描',
|
||||
actions: [{ kind: 'scan_bpm', targetId: other ? 'other' : 'own' }],
|
||||
}),
|
||||
}),
|
||||
c = store.create(operator.user.id);
|
||||
let turn = service.send(c.id, operator, '扫描');
|
||||
await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id, operator.user.id).turns[0].status, 'error');
|
||||
other = false;
|
||||
turn = service.send(c.id, operator, '扫描我的连接');
|
||||
await service.running.get(turn.id).task;
|
||||
const action = store.conversation(c.id, operator.user.id).turns.at(-1).actions[0];
|
||||
store.saveSettings({ ...store.settings(), apiKey: '', allowActions: false });
|
||||
await assert.rejects(service.executeAction(c.id, action.id, operator), (e) => e.status === 403);
|
||||
assert.equal(counters().scans, 0);
|
||||
});
|
||||
test('a failing diagnostic source does not leave an un-cancellable running turn',async t=>{
|
||||
const {store,service}=await fixture(t),c=store.create(admin.user.id),status=service.deps.scanner.store.status;service.deps.scanner.store.status=()=>{throw new Error('damaged source');};
|
||||
assert.throws(()=>service.send(c.id,admin,'分析'));assert.equal(store.conversation(c.id,admin.user.id).turns.length,0);
|
||||
service.deps.scanner.store.status=status;const turn=service.send(c.id,admin,'再次分析');await service.running.get(turn.id).task;assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'success');
|
||||
test('cancellation, per-conversation serialization and daily limits retain truthful task states', async (t) => {
|
||||
const { store, service } = await fixture(t, {
|
||||
chat: ({ signal }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (signal.aborted) reject(signal.reason);
|
||||
else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
}),
|
||||
}),
|
||||
c = store.create(admin.user.id);
|
||||
store.saveSettings({ ...store.settings(), apiKey: '', dailyLimit: 1 });
|
||||
const turn = service.send(c.id, admin, '分析');
|
||||
assert.throws(
|
||||
() => service.send(c.id, admin, '重复'),
|
||||
(e) => e.status === 409,
|
||||
);
|
||||
service.cancel(c.id, admin);
|
||||
await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id, admin.user.id).turns[0].status, 'cancelled');
|
||||
assert.throws(
|
||||
() => service.send(c.id, admin, '第二次'),
|
||||
(e) => e.status === 429,
|
||||
);
|
||||
});
|
||||
test('a known API key pasted into an earlier message never reappears in follow-up model history',async t=>{
|
||||
const calls=[],{store,service}=await fixture(t,{chat:async input=>{calls.push(input);return JSON.stringify({reply:'已读取状态',actions:[]});}}),c=store.create(admin.user.id);
|
||||
let turn=service.send(c.id,admin,'PRIVATE_API_KEY');await service.running.get(turn.id).task;store.saveSettings({...store.settings(),apiKey:'NEW_API_KEY',apiBase:'https://new-models.example/v1'});turn=service.send(c.id,admin,'继续'+'字'.repeat(2998));await service.running.get(turn.id).task;
|
||||
assert.doesNotMatch(JSON.stringify(calls.map(({config,...rest})=>rest)),/PRIVATE_API_KEY/);assert.match(calls[1].history[0].user,/已隐藏/);assert.equal(calls[1].text.length,3000);assert.equal(store.conversation(c.id,admin.user.id).turns.at(-1).text.length,3000);
|
||||
test('a failing diagnostic source does not leave an un-cancellable running turn', async (t) => {
|
||||
const { store, service } = await fixture(t),
|
||||
c = store.create(admin.user.id),
|
||||
status = service.deps.scanner.store.status;
|
||||
service.deps.scanner.store.status = () => {
|
||||
throw new Error('damaged source');
|
||||
};
|
||||
assert.throws(() => service.send(c.id, admin, '分析'));
|
||||
assert.equal(store.conversation(c.id, admin.user.id).turns.length, 0);
|
||||
service.deps.scanner.store.status = status;
|
||||
const turn = service.send(c.id, admin, '再次分析');
|
||||
await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id, admin.user.id).turns[0].status, 'success');
|
||||
});
|
||||
test('a cancellation signal alone cannot label an unconfirmed runtime failure as stopped',async t=>{
|
||||
const {store,service}=await fixture(t,{chat:({signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(new Error('cleanup failed')),{once:true}))}),c=store.create(admin.user.id),turn=service.send(c.id,admin,'分析');
|
||||
await new Promise(resolve=>setImmediate(resolve));service.cancel(c.id,admin);await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'error');
|
||||
test('a known API key pasted into an earlier message never reappears in follow-up model history', async (t) => {
|
||||
const calls = [],
|
||||
{ store, service } = await fixture(t, {
|
||||
chat: async (input) => {
|
||||
calls.push(input);
|
||||
return JSON.stringify({ reply: '已读取状态', actions: [] });
|
||||
},
|
||||
}),
|
||||
c = store.create(admin.user.id);
|
||||
let turn = service.send(c.id, admin, 'PRIVATE_API_KEY');
|
||||
await service.running.get(turn.id).task;
|
||||
store.saveSettings({
|
||||
...store.settings(),
|
||||
apiKey: 'NEW_API_KEY',
|
||||
apiBase: 'https://new-models.example/v1',
|
||||
});
|
||||
turn = service.send(c.id, admin, '继续' + '字'.repeat(2998));
|
||||
await service.running.get(turn.id).task;
|
||||
assert.doesNotMatch(JSON.stringify(calls.map(({ config, ...rest }) => rest)), /PRIVATE_API_KEY/);
|
||||
assert.match(calls[1].history[0].user, /已隐藏/);
|
||||
assert.equal(calls[1].text.length, 3000);
|
||||
assert.equal(store.conversation(c.id, admin.user.id).turns.at(-1).text.length, 3000);
|
||||
});
|
||||
test('only a pinned DSH runtime is discovered without enabling a model',async t=>{
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs');
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'order-dsh-discovery-')),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=root;t.after(async()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;await fs.rm(root,{recursive:true,force:true});});
|
||||
const base=path.join(root,'OrderNotificationAutomationRuntimes/dsh-0.2.1-rc.2/node_modules/@deepseek-ai/dsh'),runtimePath=path.join(base,'lib/bin.js');await fs.mkdir(path.dirname(runtimePath),{recursive:true});await fs.writeFile(runtimePath,'fixture');await fs.writeFile(path.join(base,'package.json'),JSON.stringify({name:'@deepseek-ai/dsh',version:'0.2.1-rc.2'}));
|
||||
const store=new AssistantStore(path.join(root,'assistant'));assert.equal(store.settings().runtimePath,runtimePath);assert.equal(store.settings().enabled,false);assert.equal(store.settings().hasApiKey,false);store.close();await fs.writeFile(path.join(base,'package.json'),JSON.stringify({name:'@deepseek-ai/dsh',version:'unverified'}));const changed=new AssistantStore(path.join(root,'assistant'));try{assert.equal(changed.settings().runtimePath,'');}finally{changed.close();}
|
||||
test('a cancellation signal alone cannot label an unconfirmed runtime failure as stopped', async (t) => {
|
||||
const { store, service } = await fixture(t, {
|
||||
chat: ({ signal }) =>
|
||||
new Promise((resolve, reject) =>
|
||||
signal.addEventListener('abort', () => reject(new Error('cleanup failed')), {
|
||||
once: true,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
c = store.create(admin.user.id),
|
||||
turn = service.send(c.id, admin, '分析');
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
service.cancel(c.id, admin);
|
||||
await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id, admin.user.id).turns[0].status, 'error');
|
||||
});
|
||||
test('only a pinned DSH runtime is discovered without enabling a model', async (t) => {
|
||||
const { AssistantStore } = require('../../src/modules/assistant/store.cjs');
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'order-dsh-discovery-')),
|
||||
old = process.env.LOCALAPPDATA;
|
||||
process.env.LOCALAPPDATA = root;
|
||||
t.after(async () => {
|
||||
if (old === undefined) delete process.env.LOCALAPPDATA;
|
||||
else process.env.LOCALAPPDATA = old;
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
const base = path.join(
|
||||
root,
|
||||
'OrderNotificationAutomationRuntimes/dsh-0.2.1-rc.2/node_modules/@deepseek-ai/dsh',
|
||||
),
|
||||
runtimePath = path.join(base, 'lib/bin.js');
|
||||
await fs.mkdir(path.dirname(runtimePath), { recursive: true });
|
||||
await fs.writeFile(runtimePath, 'fixture');
|
||||
await fs.writeFile(
|
||||
path.join(base, 'package.json'),
|
||||
JSON.stringify({ name: '@deepseek-ai/dsh', version: '0.2.1-rc.2' }),
|
||||
);
|
||||
const store = new AssistantStore(path.join(root, 'assistant'));
|
||||
assert.equal(store.settings().runtimePath, runtimePath);
|
||||
assert.equal(store.settings().enabled, false);
|
||||
assert.equal(store.settings().hasApiKey, false);
|
||||
store.close();
|
||||
await fs.writeFile(
|
||||
path.join(base, 'package.json'),
|
||||
JSON.stringify({ name: '@deepseek-ai/dsh', version: 'unverified' }),
|
||||
);
|
||||
const changed = new AssistantStore(path.join(root, 'assistant'));
|
||||
try {
|
||||
assert.equal(changed.settings().runtimePath, '');
|
||||
} finally {
|
||||
changed.close();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user