feat(assistant): complete controlled management attachments and native schedules

This commit is contained in:
abaishu0730 committed 2026-10-29 09:22:15 +08:00
1 parent d0bc4b0da2
commit 8341986067
119 files changed
+20519 -1618

No files matched your search

@@ -0,0 +1,56 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
test(
'empty sampling and missing historical result details explain what actually happened',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const { page, open, store, users } = await managementFixture(t, { browser: true }),
owner = users.users()[0].id,
c = store.create(owner),
turn = store.beginTurn(c.id, owner, '核对操作结果');
store.updateTurn(turn.id, 'success', {
reply: '操作结果已返回。',
actions: [
{
id: 'zero-samples',
kind: 'collect_field_samples',
targetId: 'source',
label: '采集字段样本',
status: 'success',
result: {
scope: 'configuration',
total: 0,
completed: 0,
captured: 0,
failed: 0,
items: [],
missing: ['仍缺样本的流程'],
link: '#rule-fields',
},
},
{
id: 'legacy-result',
kind: 'scan_bpm',
targetId: 'source',
label: '历史扫描',
status: 'success',
result: {},
},
],
});
await open();
await page.getByRole('button', { name: '查看操作(2)', exact: true }).click();
const zero = page.locator('[data-action-card="zero-samples"]');
await zero.getByText('未采集到样本', { exact: true }).waitFor();
await zero.locator('summary').filter({ hasText: '结果详情' }).click();
assert.match(await zero.innerText(), /仍缺样本的流程/);
assert.match(await zero.innerText(), /没有找到可补采/);
const legacy = page.locator('[data-action-card="legacy-result"]');
await legacy.locator('summary').filter({ hasText: '结果详情' }).click();
assert.match(await legacy.innerText(), /没有保存结果明细/);
assert.doesNotMatch(await legacy.innerText(), /\{\s*\}/);
},
);
+387 -52
View File
@@ -1,56 +1,391 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
async function fixture(t){
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'assistant-http-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');users.addUser({username:'viewer',role:'viewer',password:'Test-password-123'},'admin');const store=new AssistantStore(path.join(dir,'assistant'));let checks=0;
const storage={store:{servers:()=>[{id:'server',name:'测试存储',enabled:true,state:{readable:true,writable:true,message:'正常'}}],archives:()=>[]},check:async()=>{checks++;return {state:{readable:true,writable:true}};}};
const runtime={probe:async()=>({available:true,version:'3.14.3',message:'运行包已就绪'}),chat:async({text,signal,config})=>{if(text.includes('挂起'))return new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));return JSON.stringify({reply:'已读取运行状态。<img src=x onerror=alert(1)>',actions:config.allowActions?[{kind:'check_storage',targetId:'server'}]:[]});}};
const assistant=new AssistantService({store,runtime,storage,dashboard:users}),server=createDashboard({store:users,assistant,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{await assistant.stop();server.closeAllConnections();await new Promise(r=>server.close(r));store.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async name=>(await call('/api/login',{username:name,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,store,assistant,checks:()=>checks};
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
async function fixture(t) {
const { Store } = require('../../src/modules/dashboard/store.cjs'),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
{ createDashboard } = require('../../src/app/dashboard.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'assistant-http-')),
users = new Store(path.join(dir, 'users'));
users.bootstrap('admin', 'Test-password-123');
users.addUser({ username: 'viewer', role: 'viewer', password: 'Test-password-123' }, 'admin');
const store = new AssistantStore(path.join(dir, 'assistant'));
let checks = 0;
const storage = {
store: {
servers: () => [
{
id: 'server',
name: '测试存储',
enabled: true,
state: { readable: true, writable: true, message: '正常' },
},
],
archives: () => [],
},
check: async () => {
checks++;
return { state: { readable: true, writable: true } };
},
};
const runtime = {
probe: async () => ({ available: true, version: '3.14.3', message: '运行包已就绪' }),
chat: async ({ text, signal, config }) => {
if (text.includes('挂起'))
return new Promise((resolve, reject) =>
signal.addEventListener('abort', () => reject(signal.reason), { once: true }),
);
return JSON.stringify({
reply: '已读取运行状态。<img src=x onerror=alert(1)>',
actions: config.allowActions ? [{ kind: 'check_storage', targetId: 'server' }] : [],
});
},
};
const assistant = new AssistantService({ store, runtime, storage, dashboard: users }),
server = createDashboard({ store: users, assistant, outputDir: dir });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(async () => {
await assistant.stop();
server.closeAllConnections();
await new Promise((r) => server.close(r));
store.close();
await fs.rm(dir, { recursive: true, force: true });
});
const base = 'http://127.0.0.1:' + server.address().port;
const call = (route, body, cookie, origin = base) =>
fetch(base + route, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(body === undefined ? {} : { 'Content-Type': 'application/json', Origin: origin }),
...(cookie ? { Cookie: cookie } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
}),
login = async (name) =>
(await call('/api/login', { username: name, password: 'Test-password-123' })).headers
.get('set-cookie')
.split(';')[0];
return { base, call, login, store, assistant, checks: () => checks };
}
test('assistant HTTP enforces authentication, ownership, body validation and role constraints',async t=>{
const {call,login,store,assistant}=await fixture(t);assert.equal((await call('/api/assistant')).status,401);const admin=await login('admin'),viewer=await login('viewer');
const settings={...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_HTTP_KEY',allowActions:true};
assert.equal((await call('/api/assistant/settings',settings,viewer)).status,403);assert.equal((await call('/api/assistant/settings',settings,admin,'https://evil.example')).status,403);assert.equal((await call('/api/assistant/settings',settings,admin)).status,200);
assert.doesNotMatch(await(await call('/api/assistant',undefined,admin)).text(),/PRIVATE_HTTP_KEY/);
const created=await call('/api/assistant/conversations',{},admin);assert.equal(created.status,201);const c=await created.json();assert.equal((await call('/api/assistant/conversations/'+c.id,undefined,viewer)).status,404);
assert.equal((await call('/api/assistant/conversations/'+c.id+'/messages',{text:'hello',command:'shell'},admin)).status,400);
const sent=await call('/api/assistant/conversations/'+c.id+'/messages',{text:'分析状态'},admin);assert.equal(sent.status,202);const turn=await sent.json();await assistant.running.get(turn.id)?.task;
const saved=await(await call('/api/assistant/conversations/'+c.id,undefined,admin)).json();assert.equal(saved.turns[0].status,'success');assert.equal((await call('/api/assistant/conversations/'+c.id+'/actions/'+saved.turns[0].actions[0].id+'/execute',{},viewer)).status,403);
});
test('chat UI persists conversations, shows escaped messages and explicit fixed action results, and cancels a running reply',{timeout:120000},async t=>{
const {base,store,checks}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_UI_KEY',allowActions:true});
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
await page.getByLabel('发送给 DSH',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0);
await page.getByRole('button',{name:'查看操作(1)',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();
await page.getByLabel('发送给 DSH',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor();
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/zcode-chat-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
test('assistant HTTP enforces authentication, ownership, body validation and role constraints', async (t) => {
const { call, login, store, assistant } = await fixture(t);
assert.equal((await call('/api/assistant')).status, 401);
const admin = await login('admin'),
viewer = await login('viewer');
const settings = {
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://models.example/v1',
model: 'fixture',
apiKey: 'PRIVATE_HTTP_KEY',
allowActions: true,
};
assert.equal((await call('/api/assistant/settings', settings, viewer)).status, 403);
assert.equal(
(await call('/api/assistant/settings', settings, admin, 'https://evil.example')).status,
403,
);
assert.equal((await call('/api/assistant/settings', settings, admin)).status, 200);
assert.doesNotMatch(
await (await call('/api/assistant', undefined, admin)).text(),
/PRIVATE_HTTP_KEY/,
);
const created = await call('/api/assistant/conversations', {}, admin);
assert.equal(created.status, 201);
const c = await created.json();
assert.equal((await call('/api/assistant/conversations/' + c.id, undefined, viewer)).status, 404);
assert.equal(
(
await call(
'/api/assistant/conversations/' + c.id + '/messages',
{ text: 'hello', command: 'shell' },
admin,
)
).status,
400,
);
const sent = await call(
'/api/assistant/conversations/' + c.id + '/messages',
{ text: '分析状态' },
admin,
);
assert.equal(sent.status, 202);
const turn = await sent.json();
await assistant.running.get(turn.id)?.task;
const saved = await (await call('/api/assistant/conversations/' + c.id, undefined, admin)).json();
assert.equal(saved.turns[0].status, 'success');
assert.equal(
(
await call(
'/api/assistant/conversations/' +
c.id +
'/actions/' +
saved.turns[0].actions[0].id +
'/execute',
{},
viewer,
)
).status,
403,
);
});
test(
'chat UI persists conversations, shows escaped messages and explicit fixed action results, and cancels a running reply',
{ timeout: 120000 },
async (t) => {
const { base, store, checks } = await fixture(t);
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://models.example/v1',
model: 'fixture',
apiKey: 'PRIVATE_UI_KEY',
allowActions: true,
});
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }),
errors = [];
page.on('pageerror', (e) => errors.push(e.message));
page.setDefaultTimeout(15000);
await page.goto(base + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
await page.getByRole('button', { name: '新建对话', exact: true }).click();
await page.getByLabel('发送给 DSH', { exact: true }).fill('分析订单运行状态');
await page.getByRole('button', { name: '发送', exact: true }).click();
await page
.locator('.assistant-reply')
.getByText('已读取运行状态。<img src=x onerror=alert(1)>', { exact: true })
.waitFor();
assert.equal(await page.locator('.assistant-reply img').count(), 0);
assert.equal(checks(), 0);
await page.getByRole('button', { name: '查看操作(1)', exact: true }).click();
await page.getByRole('button', { name: '执行:检查存储连接', exact: true }).click();
await page.getByText('操作已完成', { exact: true }).waitFor();
assert.equal(checks(), 1);
await page.reload();
await page
.locator('.assistant-reply')
.getByText('已读取运行状态。<img src=x onerror=alert(1)>', { exact: true })
.waitFor();
await page.getByLabel('发送给 DSH', { exact: true }).fill('挂起诊断');
await page.getByRole('button', { name: '发送', exact: true }).click();
await page.getByRole('button', { name: '停止回复', exact: true }).click();
await page.getByText('已停止本轮回复。', { exact: true }).waitFor();
await fs.mkdir('output/verification', { recursive: true });
await page.screenshot({ path: 'output/verification/zcode-chat-desktop.png', fullPage: true });
await page.setViewportSize({ width: 390, height: 844 });
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
assert.deepEqual(errors, []);
},
);
test('a long action displays persisted sampling progress before its POST completes',{timeout:60000},async t=>{
const {base,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_PROGRESS_KEY',allowActions:true});
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(8000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 DSH',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'查看操作(1)',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor();
let started=false,finished=false,release;const gate=new Promise(resolve=>release=resolve);t.after(()=>release());
await page.route('**/api/assistant/conversations/*',async route=>{const response=await route.fetch(),data=await response.json();if(started)for(const turn of data.turns)for(const action of turn.actions||[])Object.assign(action,{status:finished?'success':'running',progress:{completed:1,total:3,captured:1,failed:0}});await route.fulfill({json:data});});
await page.route('**/api/assistant/conversations/*/actions/*/execute',async route=>{started=true;await gate;finished=true;await route.fulfill({json:{status:'success'}});});
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();
await page.getByText('采样进度 1 / 3,成功 1,受阻 0',{exact:true}).waitFor({timeout:4500});assert.equal(finished,false);
release();await page.getByText('操作已完成',{exact:true}).waitFor();
});
test(
'a long action displays persisted sampling progress before its POST completes',
{ timeout: 60000 },
async (t) => {
const { base, store } = await fixture(t);
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://models.example/v1',
model: 'fixture',
apiKey: 'PRIVATE_PROGRESS_KEY',
allowActions: true,
});
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage();
page.setDefaultTimeout(8000);
await page.goto(base + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
await page.getByRole('button', { name: '新建对话', exact: true }).click();
await page.getByLabel('发送给 DSH', { exact: true }).fill('读取状态');
await page.getByRole('button', { name: '发送', exact: true }).click();
await page.getByRole('button', { name: '查看操作(1)', exact: true }).click();
await page.getByRole('button', { name: '执行:检查存储连接', exact: true }).waitFor();
let started = false,
finished = false,
release;
const gate = new Promise((resolve) => (release = resolve));
t.after(() => release());
await page.route('**/api/assistant/conversations/*', async (route) => {
const response = await route.fetch(),
data = await response.json();
if (started)
for (const turn of data.turns)
for (const action of turn.actions || [])
Object.assign(action, {
status: finished ? 'success' : 'running',
progress: { completed: 1, total: 3, captured: 1, failed: 0 },
});
await route.fulfill({ json: data });
});
await page.route('**/api/assistant/conversations/*/actions/*/execute', async (route) => {
started = true;
await gate;
finished = true;
await route.fulfill({ json: { status: 'success' } });
});
await page.getByRole('button', { name: '执行:检查存储连接', exact: true }).click();
await page
.getByText('采样进度 1 / 3,成功 1,受阻 0', { exact: true })
.waitFor({ timeout: 4500 });
assert.equal(finished, false);
release();
await page.getByText('操作已完成', { exact: true }).waitFor();
},
);
test('personal conversation UI archives, pages and restores evidence without sending a model request',{timeout:60000},async t=>{
const {base,store}=await fixture(t);const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(10000);
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
await page.getByRole('button',{name:'归档会话',exact:true}).click();await page.getByRole('button',{name:'归档会话',exact:true}).waitFor({state:'hidden'});
await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('archived');await page.locator('[data-assistant-conversation]').first().click();
await page.getByRole('button',{name:'恢复会话',exact:true}).click();await page.getByRole('button',{name:'恢复会话',exact:true}).waitFor({state:'hidden'});
await page.getByRole('button',{name:'会话列表',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-assistant-conversation]').first().waitFor();
assert.equal(store.listConversations(store.db.prepare('SELECT owner FROM conversations').get().owner,{scope:'archived'}).total,0);assert.equal(store.usage().calls,0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
});
test('admin reviews selected code changes before isolated repair and sees the rollback result',{timeout:120000},async t=>{
const {base,store,assistant}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/anthropic',model:'fixture',apiKey:'PRIVATE_REPAIR_KEY',allowActions:true,allowCodeRepair:true,repairRepository:process.cwd()});let runs=0;assistant.repairFactory=()=>({readSources:paths=>{assert.deepEqual(paths,['src/demo.cjs']);return {baselineCommit:'a'.repeat(40),files:[{path:'src/demo.cjs',content:'BEFORE'}]};},run:async()=>{runs++;return {operationId:'repair-test',status:'rolled_back',previousCommit:'a'.repeat(40),resultCommit:'b'.repeat(40),testOutcome:'failed'};}});assistant.runtime.chat=async()=>JSON.stringify({reply:'修复建议',actions:[],repair:{files:[{path:'src/demo.cjs',content:'AFTER'}]}});
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}});await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('tab',{name:'记录',exact:true}).click();await page.getByText('提出代码修复',{exact:true}).click();await page.locator('#repair-paths').fill('src/demo.cjs');await page.locator('#repair-goal').fill('修复问题');await page.getByRole('button',{name:'生成修复建议',exact:true}).click();await page.getByText('修复建议',{exact:true}).waitFor();assert.equal(runs,0);await page.getByText('src/demo.cjs · 查看修改前后',{exact:true}).click();await page.getByText('BEFORE',{exact:true}).waitFor();await page.getByText('AFTER',{exact:true}).waitFor();await page.getByRole('button',{name:'执行:审查并执行隔离代码修复',exact:true}).click();await page.getByText('测试未通过,已回退',{exact:true}).waitFor();assert.equal(runs,1);
});
test('operation history loads older audit events instead of hiding everything beyond the newest hundred',{timeout:120000},async t=>{const {base,assistant}=await fixture(t);const events=Array.from({length:125},(_,i)=>({id:125-i,operationId:'op-'+i,actor:'admin-fixture',createdAt:'2026-10-27T01:00:00Z',step:'model',status:'success',detail:'TRACE-'+i}));assistant.journal={list:({beforeId})=>events.filter(e=>!beforeId||e.id<beforeId).slice(0,100)};const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('tab',{name:'记录',exact:true}).click();await page.getByText('TRACE-0',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-124',{exact:true}).count(),0);await page.getByRole('button',{name:'加载更早记录',exact:true}).click();await page.getByText('TRACE-124',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-0',{exact:true}).count(),1);});
test(
'personal conversation UI archives, pages and restores evidence without sending a model request',
{ timeout: 60000 },
async (t) => {
const { base, store } = await fixture(t);
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
page.setDefaultTimeout(10000);
await page.goto(base + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
await page.getByRole('button', { name: '会话列表', exact: true }).click();
await page.getByRole('button', { name: '新建对话', exact: true }).click();
await page.getByRole('button', { name: '归档会话', exact: true }).click();
await page.getByRole('button', { name: '归档会话', exact: true }).waitFor({ state: 'hidden' });
await page.getByRole('button', { name: '会话列表', exact: true }).click();
await page.getByLabel('会话范围', { exact: true }).selectOption('archived');
await page.locator('[data-assistant-conversation]').first().click();
await page.getByRole('button', { name: '恢复会话', exact: true }).click();
await page.getByRole('button', { name: '恢复会话', exact: true }).waitFor({ state: 'hidden' });
await page.getByRole('button', { name: '会话列表', exact: true }).click();
await page.getByLabel('会话范围', { exact: true }).selectOption('active');
await page.locator('[data-assistant-conversation]').first().waitFor();
assert.equal(
store.listConversations(store.db.prepare('SELECT owner FROM conversations').get().owner, {
scope: 'archived',
}).total,
0,
);
assert.equal(store.usage().calls, 0);
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
},
);
test(
'admin reviews selected code changes before isolated repair and sees the rollback result',
{ timeout: 120000 },
async (t) => {
const { base, store, assistant } = await fixture(t);
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://models.example/anthropic',
model: 'fixture',
apiKey: 'PRIVATE_REPAIR_KEY',
allowActions: true,
allowCodeRepair: true,
repairRepository: process.cwd(),
});
let runs = 0;
assistant.repairFactory = () => ({
readSources: (paths) => {
assert.deepEqual(paths, ['src/demo.cjs']);
return {
baselineCommit: 'a'.repeat(40),
files: [{ path: 'src/demo.cjs', content: 'BEFORE' }],
};
},
run: async () => {
runs++;
return {
operationId: 'repair-test',
status: 'rolled_back',
previousCommit: 'a'.repeat(40),
resultCommit: 'b'.repeat(40),
testOutcome: 'failed',
};
},
});
assistant.runtime.chat = async () =>
JSON.stringify({
reply: '修复建议',
actions: [],
repair: { files: [{ path: 'src/demo.cjs', content: 'AFTER' }] },
});
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
await page.goto(base + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
await page.getByRole('tab', { name: '记录', exact: true }).click();
await page.getByText('提出代码修复', { exact: true }).click();
await page.locator('#repair-paths').fill('src/demo.cjs');
await page.locator('#repair-goal').fill('修复问题');
await page.getByRole('button', { name: '生成修复建议', exact: true }).click();
await page.getByText('修复建议', { exact: true }).waitFor();
assert.equal(runs, 0);
await page.getByText('src/demo.cjs · 查看修改前后', { exact: true }).click();
await page.getByText('BEFORE', { exact: true }).waitFor();
await page.getByText('AFTER', { exact: true }).waitFor();
await page.getByRole('button', { name: '执行:审查并执行隔离代码修复', exact: true }).click();
await page.getByText('测试未通过,已回退', { exact: true }).waitFor();
assert.equal(runs, 1);
},
);
test(
'operation history loads older audit events instead of hiding everything beyond the newest hundred',
{ timeout: 120000 },
async (t) => {
const { base, assistant } = await fixture(t);
const events = Array.from({ length: 125 }, (_, i) => ({
id: 125 - i,
operationId: 'op-' + i,
actor: 'admin-fixture',
createdAt: '2026-10-27T01:00:00Z',
step: 'model',
status: 'success',
detail: 'TRACE-' + i,
}));
assistant.journal = {
list: ({ beforeId }) => events.filter((e) => !beforeId || e.id < beforeId).slice(0, 100),
};
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage();
await page.goto(base + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
await page.getByRole('tab', { name: '记录', exact: true }).click();
await page.getByText('TRACE-0', { exact: true }).waitFor();
assert.equal(await page.getByText('TRACE-124', { exact: true }).count(), 0);
await page.getByRole('button', { name: '加载更早记录', exact: true }).click();
await page.getByText('TRACE-124', { exact: true }).waitFor();
assert.equal(await page.getByText('TRACE-0', { exact: true }).count(), 1);
},
);
+73 -7
View File
@@ -1,8 +1,74 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
test('backup restore preserves provider credentials, event/request AAD, conversation model and quota',{timeout:90000},async t=>{
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{createBackup}=require('../../src/platform/backup/snapshot.cjs'),{restoreBackup}=require('../../src/platform/backup/restore.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'assistant-provider-restore-')),state=path.join(dir,'state'),pdf=path.join(dir,'pdf'),bundle=path.join(dir,'backup'),restored=path.join(dir,'restored');fs.mkdirSync(pdf);let store=new AssistantStore(path.join(state,'assistant'));t.after(()=>{try{store?.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});
store.saveSettings({...store.settings(),apiKey:'TEST_BACKUP_KEY',enabled:true,model:'legacy-test'});const custom=store.providers.save({version:0,name:'Custom',preset:'custom',protocol:'openai-responses',apiBase:'https://gateway.example/v1',apiKey:'TEST_CUSTOM_BACKUP_KEY',enabled:true,models:[{id:'backup-model',name:'Backup Model'}]}),p=custom.providers.find(p=>p.name==='Custom');store.providers.chooseDefault({version:custom.version,providerId:p.id,modelId:'backup-model'});const c=store.create('owner');store.setModel(c.id,'owner',{version:c.version,providerId:p.id,modelId:'backup-model'});const turn=store.beginTurn(c.id,'owner','question',{requestId:'saved-request',requestPayload:{text:'question'}});store.updateTurn(turn.id,'success',{reply:'preserved'});store.close();store=null;
await createBackup({stateDir:state,outputDir:pdf,destination:bundle});await restoreBackup({source:bundle,destination:restored});store=new AssistantStore(path.join(restored,'assistant'));assert.equal(store.providers.resolve().apiKey,'TEST_CUSTOM_BACKUP_KEY');assert.equal(store.conversation(c.id,'owner').modelSelection.modelId,'backup-model');assert.equal(store.events(c.id,'owner',{}).events.at(-1).kind,'completed');assert.equal(store.requestTurn(c.id,'owner','saved-request',{text:'question'}).reply,'preserved');assert.equal(store.usage().calls,1);
});
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
test(
'backup restore preserves provider credentials, event/request AAD, conversation model and quota',
{ timeout: 90000 },
async (t) => {
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ createBackup } = require('../../src/platform/backup/snapshot.cjs'),
{ restoreBackup } = require('../../src/platform/backup/restore.cjs');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'assistant-provider-restore-')),
state = path.join(dir, 'state'),
pdf = path.join(dir, 'pdf'),
bundle = path.join(dir, 'backup'),
restored = path.join(dir, 'restored');
fs.mkdirSync(pdf);
let store = new AssistantStore(path.join(state, 'assistant'));
t.after(() => {
try {
store?.close();
} catch {}
fs.rmSync(dir, { recursive: true, force: true });
});
store.saveSettings({
...store.settings(),
apiKey: 'TEST_BACKUP_KEY',
enabled: true,
model: 'legacy-test',
});
const custom = store.providers.save({
version: 0,
name: 'Custom',
preset: 'custom',
protocol: 'openai-responses',
apiBase: 'https://gateway.example/v1',
apiKey: 'TEST_CUSTOM_BACKUP_KEY',
enabled: true,
models: [{ id: 'backup-model', name: 'Backup Model' }],
}),
p = custom.providers.find((p) => p.name === 'Custom');
store.providers.chooseDefault({
version: custom.version,
providerId: p.id,
modelId: 'backup-model',
});
const c = store.create('owner');
store.setModel(c.id, 'owner', {
version: c.version,
providerId: p.id,
modelId: 'backup-model',
});
const turn = store.beginTurn(c.id, 'owner', 'question', {
requestId: 'saved-request',
requestPayload: { text: 'question' },
});
store.updateTurn(turn.id, 'success', { reply: 'preserved' });
store.close();
store = null;
await createBackup({ stateDir: state, outputDir: pdf, destination: bundle });
await restoreBackup({ source: bundle, destination: restored });
store = new AssistantStore(path.join(restored, 'assistant'));
assert.equal(store.providers.resolve().apiKey, 'TEST_CUSTOM_BACKUP_KEY');
assert.equal(store.conversation(c.id, 'owner').modelSelection.modelId, 'backup-model');
assert.equal(store.events(c.id, 'owner', {}).events.at(-1).kind, 'completed');
assert.equal(
store.requestTurn(c.id, 'owner', 'saved-request', { text: 'question' }).reply,
'preserved',
);
assert.equal(store.usage().calls, 1);
},
);
+418 -64
View File
@@ -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();
}
});
+98
View File
@@ -0,0 +1,98 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
test(
'attachment upload is private and local, send consumes references once and preserves follow-up context',
{ timeout: 120000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
{ store, assistant } = f,
admin = await f.login(),
viewer = await f.login('viewer');
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_ATTACHMENT_KEY',
allowActions: true,
});
let seen = [],
calls = 0;
assistant.runtime.chat = async (input) => {
seen.push(input);
calls++;
return JSON.stringify({ reply: '附件中数量为 12。', actions: [] });
};
const file = {
name: '订单.csv',
data: Buffer.from(
'型号,数量\nABC,12\npassword=PRIVATE_FILE_PASSWORD\n' +
'重复内容'.repeat(700) +
'TAIL_EVIDENCE',
).toString('base64'),
};
assert.equal((await f.call('/assistant/attachments', file)).status, 401);
const upload = await f.call('/assistant/attachments', file, admin);
assert.equal(upload.status, 201);
const attachment = await upload.json();
assert.equal(calls, 0);
assert.match(attachment.preview, /ABC,12/);
const other = await (await f.call('/assistant/conversations', {}, viewer)).json();
assert.equal(
(
await f.call(
'/assistant/conversations/' + other.id + '/messages',
{ text: '读取附件', attachments: [attachment.id] },
viewer,
)
).status,
404,
);
assert.equal(calls, 0);
const c = await (await f.call('/assistant/conversations', {}, admin)).json();
const payload = { text: '', attachments: [attachment.id], requestId: 'attachment-request' };
const first = await f.call('/assistant/conversations/' + c.id + '/messages', payload, admin);
assert.equal(first.status, 202);
const turn = await first.json();
await assistant.running.get(turn.id)?.task;
assert.equal(calls, 1);
assert.match(seen[0].context.attachments[0].content, /ABC,12/);
assert.match(seen[0].context.attachments[0].content, /TAIL_EVIDENCE/);
assert.doesNotMatch(JSON.stringify(seen[0].context), /PRIVATE_FILE_PASSWORD/);
const retry = await f.call('/assistant/conversations/' + c.id + '/messages', payload, admin);
assert.equal(retry.status, 202);
assert.equal(calls, 1);
assert.equal((await retry.json()).id, turn.id);
const follow = await (
await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '继续分析附件' },
admin,
)
).json();
await assistant.running.get(follow.id)?.task;
assert.match(seen[1].context.attachments[0].content, /ABC,12/);
const gone = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '再引用已消费的附件', attachments: [attachment.id] },
admin,
);
assert.equal(gone.status, 404);
const upload2 = await (
await f.call(
'/assistant/attachments',
{ name: 'remove.log', data: Buffer.from('remove-me').toString('base64') },
admin,
)
).json();
assert.equal(
(await f.call('/assistant/attachments/' + upload2.id + '/remove', {}, viewer)).status,
404,
);
assert.equal(
(await f.call('/assistant/attachments/' + upload2.id + '/remove', {}, admin)).status,
200,
);
},
);
+100
View File
@@ -0,0 +1,100 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
test(
'attachments preview/remove locally, send without extra text and show verified visual capability',
{ timeout: 120000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true }),
{ page, open, store, assistant } = f;
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_ATTACHMENT_UI_KEY',
});
const row = store.providers.read('deepseek'),
directory = store.providers.save({
...row,
models: [
{
id: 'vision-fixture',
name: '供应商确认支持图像输入的完整长模型名称',
inputModalities: ['text', 'image'],
},
],
});
store.providers.chooseDefault({
version: directory.version,
providerId: 'deepseek',
modelId: 'vision-fixture',
});
let calls = 0,
inputs = [];
assistant.runtime.chat = async (input) => {
calls++;
inputs.push(input);
return JSON.stringify({ reply: '附件型号 ABC,数量 12。', actions: [] });
};
await open();
await page.getByRole('button', { name: /选择模型.*视觉/ }).waitFor();
await page.setViewportSize({ width: 390, height: 844 });
const label = page.locator('#assistant-model-picker');
assert.match(await label.innerText(), /供应商确认支持图像输入的完整长模型名称/);
await page.waitForFunction(() => {
const e = document.querySelector('#assistant-model-picker');
return e && e.scrollWidth <= e.clientWidth;
});
assert.equal(await label.evaluate((e) => e.scrollWidth <= e.clientWidth), true);
await page.setViewportSize({ width: 1440, height: 1000 });
const send = page.getByRole('button', { name: '发送', exact: true });
assert.equal(await send.isDisabled(), true);
const file = {
name: 'sample.csv',
mimeType: 'text/csv',
buffer: Buffer.from('型号,数量\nABC,12'),
};
await page.locator('#assistant-files').setInputFiles(file);
await page.getByText('已解析', { exact: false }).waitFor();
assert.equal(calls, 0);
await page.waitForFunction(() => !document.querySelector('#assistant-send').disabled);
await page.setViewportSize({ width: 390, height: 844 });
const out = require('node:path').resolve(__dirname, '../../output/verification/dsh-settings');
await require('node:fs/promises').mkdir(out, { recursive: true });
await page.screenshot({
path: require('node:path').join(out, 'attachment-mobile.png'),
fullPage: true,
});
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: '预览附件 sample.csv', exact: true }).click();
await page.getByText('型号,数量\nABC,12', { exact: true }).waitFor();
await page
.getByRole('dialog', { name: '预览附件 sample.csv', exact: true })
.getByRole('button', { name: '关闭', exact: true })
.click();
store.db.prepare('UPDATE assistant_attachments SET expires_at=0').run();
await page.getByRole('button', { name: '移除附件 sample.csv', exact: true }).click();
await page
.getByRole('button', { name: '移除附件 sample.csv', exact: true })
.waitFor({ state: 'hidden' });
assert.equal(await send.isDisabled(), true);
await page.locator('#assistant-files').setInputFiles(file);
await page.getByText('已解析', { exact: false }).waitFor();
assert.equal(await send.isEnabled(), true);
await send.click();
await page.getByText('附件型号 ABC,数量 12。', { exact: true }).waitFor();
assert.equal(calls, 1);
assert.match(inputs[0].context.attachments[0].content, /ABC,12/);
assert.equal(await page.locator('#assistant-attachment-list').innerText(), '');
await page.getByLabel('发送给 DSH', { exact: true }).fill('继续分析');
await send.click();
await page
.locator('.assistant-answer')
.nth(1)
.getByText('附件型号 ABC,数量 12。', { exact: true })
.waitFor();
assert.equal(calls, 2);
assert.match(inputs[1].context.attachments[0].content, /ABC,12/);
},
);
+59
View File
@@ -0,0 +1,59 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { parse } = require('../../src/modules/assistant/attachments.cjs');
function pdf(text) {
const stream = 'BT /F1 12 Tf 72 720 Td (' + text + ') Tj ET',
parts = ['%PDF-1.4\n'],
objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
'<< /Length ' + stream.length + ' >>\nstream\n' + stream + '\nendstream',
];
const offsets = [0];
for (const [i, obj] of objects.entries()) {
offsets.push(Buffer.byteLength(parts.join('')));
parts.push(i + 1 + ' 0 obj\n' + obj + '\nendobj\n');
}
const xref = Buffer.byteLength(parts.join(''));
parts.push(
'xref\n0 6\n0000000000 65535 f \n' +
offsets
.slice(1)
.map((x) => String(x).padStart(10, '0') + ' 00000 n \n')
.join('') +
'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n' +
xref +
'\n%%EOF',
);
return Buffer.from(parts.join(''));
}
module.exports = { pdf };
test(
'attachments parse local text/CSV and real PDF, reject binary, oversized and malformed files',
{ timeout: 30000 },
async () => {
const upload = (name, bytes) => parse({ name, data: bytes.toString('base64') });
assert.equal(
(await upload('中文日志.log', Buffer.from('设备正常\nA=1'))).content,
'设备正常\nA=1',
);
assert.match((await upload('表格.csv', Buffer.from('型号,数量\nABC,12'))).content, /ABC,12/);
const result = await upload('evidence.pdf', pdf('Attachment PDF Evidence'));
assert.match(result.content, /Attachment PDF Evidence/);
assert.equal(result.kind, 'pdf');
await assert.rejects(upload('scan.pdf', pdf('')), /没有可提取的文字/);
for (const [name, bytes] of [
['file.exe', Buffer.from('a')],
['binary.txt', Buffer.from([0, 0, 1, 2])],
['bad.pdf', Buffer.from('not PDF')],
['huge.txt', Buffer.from('x'.repeat(20001))],
['large.log', Buffer.alloc(2 * 1024 * 1024 + 1, 65)],
])
await assert.rejects(upload(name, bytes));
await assert.rejects(parse({ name: '../secret.txt', data: 'YWJj' }));
await assert.rejects(parse({ name: 'file.txt', data: 'not-base64' }));
},
);
@@ -0,0 +1,163 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
path = require('node:path');
const { managementFixture } = require('./management-fixture.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test(
'configuration HTTP requires scoped review token, preserves audit and refuses replay and stale approval',
{ timeout: 180000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
{ store, users, assistant } = f,
cookie = await f.login(),
journalFile = path.join(
require('node:os').tmpdir(),
'approval-audit-' + require('node:crypto').randomUUID() + '.sqlite',
),
journal = new OperationJournal({ file: journalFile });
assistant.journal = journal;
t.after(() => {
journal.close();
require('node:fs').rmSync(journalFile, { force: true });
});
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_SETTINGS_AUTH_KEY',
allowActions: true,
});
let observed;
assistant.runtime.chat = async (input) => {
observed = input.context;
return JSON.stringify({
reply: '建议调整发送时间',
actions: [
{
kind: 'update_configuration',
targetId: 'schedule',
changes: { times: ['10:00', '18:00'] },
},
],
});
};
const c = await (await f.call('/assistant/conversations', {}, cookie)).json();
async function suggestion() {
const res = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '把发送时间改为10点和18点' },
cookie,
);
assert.equal(res.status, 202);
const turn = await res.json();
await assistant.running.get(turn.id)?.task;
const saved = store
.conversation(c.id, users.users().find((u) => u.username === 'admin').id)
.turns.at(-1);
assert.equal(saved.status, 'success', saved.error);
return saved.actions[0];
}
const before = users.settings(),
a = await suggestion();
assert.ok(observed.configuration.some((x) => x.id === 'schedule'));
assert.deepEqual(users.settings(), before);
const base = '/assistant/conversations/' + c.id + '/actions/' + a.id;
assert.equal((await f.call(base + '/execute', {}, cookie)).status, 403);
assert.deepEqual(users.settings(), before);
const reviewed = await f.call(base + '/review', {}, cookie);
assert.equal(reviewed.status, 200);
const review = await reviewed.json();
assert.ok(review.diff.length);
assert.ok(review.risks.length);
assert.doesNotMatch(JSON.stringify(review), /TEST_SETTINGS_AUTH_KEY/);
assert.equal(
(await f.call(base + '/execute', { approvalToken: 'forged' }, cookie)).status,
403,
);
assert.equal(
(await f.call(base + '/execute', { approvalToken: review.approvalToken }, await f.login()))
.status,
403,
);
const applied = await f.call(
base + '/execute',
{ approvalToken: review.approvalToken },
cookie,
);
assert.equal(applied.status, 200);
assert.deepEqual(users.settings().schedule.times, ['10:00', '18:00']);
const version = users.settings().version;
assert.equal(
(await f.call(base + '/execute', { approvalToken: review.approvalToken }, cookie)).status,
409,
);
assert.equal(users.settings().version, version);
assert.ok(
journal.list({ actor: users.users()[0].id }).some((e) => e.step === 'configuration_saved'),
);
users.saveSettings(
{ schedule: { ...users.settings().schedule, times: ['09:00', '17:00'] } },
users.settings().version,
'admin',
);
const b = await suggestion(),
bpath = '/assistant/conversations/' + c.id + '/actions/' + b.id,
br = await (await f.call(bpath + '/review', {}, cookie)).json();
users.saveSettings(
{ schedule: { ...users.settings().schedule, weekends: true } },
users.settings().version,
'admin',
);
assert.equal(
(await f.call(bpath + '/execute', { approvalToken: br.approvalToken }, cookie)).status,
409,
);
assert.deepEqual(users.settings().schedule.times, ['09:00', '17:00']);
const d = await suggestion(),
dpath = '/assistant/conversations/' + c.id + '/actions/' + d.id,
dr = await (await f.call(dpath + '/review', {}, cookie)).json();
store.db.prepare('UPDATE assistant_configuration_approvals SET expires_at=0').run();
assert.equal(
(await f.call(dpath + '/execute', { approvalToken: dr.approvalToken }, cookie)).status,
403,
);
assert.deepEqual(users.settings().schedule.times, ['09:00', '17:00']);
assert.equal((await f.call(dpath + '/review', {}, await f.login('viewer'))).status, 403);
assert.equal((await f.call(dpath + '/reject', {}, cookie)).status, 200);
assert.equal(
(await f.call(dpath + '/execute', { approvalToken: dr.approvalToken }, cookie)).status,
409,
);
const e = await suggestion(),
epath = '/assistant/conversations/' + c.id + '/actions/' + e.id,
er = await (await f.call(epath + '/review', {}, cookie)).json(),
append = journal.append.bind(journal);
journal.append = () => {
throw Error('audit unavailable');
};
assert.equal(
(await f.call(epath + '/execute', { approvalToken: er.approvalToken }, cookie)).status,
500,
);
assert.deepEqual(users.settings().schedule.times, ['09:00', '17:00']);
journal.append = (event) => {
if (event.step === 'configuration_saved') throw Error('post-save audit failure');
return append(event);
};
assert.equal(
(await f.call(epath + '/execute', { approvalToken: er.approvalToken }, cookie)).status,
502,
);
assert.deepEqual(users.settings().schedule.times, ['10:00', '18:00']);
assert.equal(
store.conversation(c.id, users.users()[0].id).turns.at(-1).actions[0].status,
'needs_review',
);
journal.append = append;
assert.equal(
(await f.call(epath + '/execute', { approvalToken: er.approvalToken }, cookie)).status,
409,
);
},
);
+140
View File
@@ -0,0 +1,140 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test(
'composer uses an accessible icon and settings save only after risk acknowledgement',
{ timeout: 180000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true }),
{ page, open, store, users, assistant } = f,
file = path.join(os.tmpdir(), 'dsh-review-' + crypto.randomUUID() + '.sqlite'),
journal = new OperationJournal({ file });
assistant.journal = journal;
t.after(() => {
journal.close();
fs.rmSync(file, { force: true });
});
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_REVIEW_UI_KEY',
allowActions: true,
});
assistant.runtime.chat = async () =>
JSON.stringify({
reply: '建议调整发送时间,请审查风险。',
actions: [
{
kind: 'update_configuration',
targetId: 'schedule',
changes: { times: ['10:00', '18:00'] },
},
],
});
const output = path.resolve(__dirname, '../../output/verification/dsh-settings');
await fs.promises.mkdir(output, { recursive: true });
await open();
const send = page.getByRole('button', { name: '发送', exact: true }),
input = page.getByRole('textbox', { name: '发送给 DSH', exact: true });
await input.waitFor();
assert.equal(await send.isDisabled(), true);
await input.fill(' ');
assert.equal(await send.isDisabled(), true);
await input.fill('调整发送计划');
assert.equal(await send.isEnabled(), true);
assert.ok(await send.locator('svg').count());
await send.click();
await page.getByRole('button', { name: '查看操作(1)', exact: true }).click();
await page.getByRole('button', { name: '审查修改', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '审查设置修改', exact: true });
await dialog.waitFor();
assert.match(await dialog.innerText(), /09:00/);
assert.match(await dialog.innerText(), /10:00/);
assert.match(await dialog.innerText(), /风险/);
const authorize = dialog.getByRole('button', { name: '授权并保存', exact: true });
assert.equal(await authorize.isDisabled(), true);
await page.screenshot({ path: path.join(output, 'review-desktop.png'), fullPage: true });
const before = users.settings();
await dialog.getByRole('button', { name: '取消', exact: true }).click();
assert.deepEqual(users.settings(), before);
await page.getByRole('button', { name: '审查修改', exact: true }).click();
await dialog
.getByRole('checkbox', { name: '我已阅读以上差异和风险,授权本次修改', exact: true })
.check();
await authorize.click();
await page.getByText('配置已保存', { exact: true }).waitFor();
assert.deepEqual(users.settings().schedule.times, ['10:00', '18:00']);
await page.setViewportSize({ width: 390, height: 844 });
const box = await send.boundingBox();
assert.ok(box.width >= 40 && box.height >= 40);
assert.ok(box.x + box.width <= 390);
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
await page.screenshot({ path: path.join(output, 'mobile.png'), fullPage: true });
assistant.runtime.chat = ({ signal }) =>
new Promise((resolve, reject) =>
signal.addEventListener('abort', () => reject(signal.reason), { once: true }),
);
await input.fill('测试停止回复');
await send.click();
const stop = page.getByRole('button', { name: '停止回复', exact: true });
await stop.waitFor();
assert.equal(await stop.locator('svg rect').count(), 1);
await stop.click();
await page.getByText('已停止', { exact: true }).waitFor();
assert.equal(await send.isDisabled(), true);
await page.setViewportSize({ width: 390, height: 844 });
await page.evaluate(() => {
const picker = document.querySelector('#assistant-model-picker');
AssistantModelPicker;
picker.textContent = 'DeepSeek / skyworth-deepseek-v4.1-flash-with-complete-long-model-name';
});
const model = page.locator('#assistant-model-picker');
const full = await model.evaluate((e) => ({
clipped: e.scrollWidth > e.clientWidth,
whiteSpace: getComputedStyle(e).whiteSpace,
text: e.textContent,
}));
assert.equal(full.clipped, false);
assert.notEqual(full.whiteSpace, 'nowrap');
assert.match(full.text, /complete-long-model-name/);
assistant.runtime.chat = async () =>
JSON.stringify({
reply: Array.from(
{ length: 80 },
(_, i) => '第' + i + '段,供阅读历史消息的滚动测试。',
).join('\n\n'),
actions: [],
});
await input.fill('生成长回答以验证滚动到底部');
await send.click();
await page
.locator('.assistant-turn')
.last()
.getByRole('button', { name: '复制回答', exact: true })
.waitFor();
await page.locator('#assistant-messages').evaluate((e) => {
e.scrollTop = 0;
e.dispatchEvent(new Event('scroll'));
});
const latest = page.getByRole('button', { name: '滚动到底部', exact: true });
await latest.waitFor();
await latest.click();
assert.equal(
await page
.locator('#assistant-messages')
.evaluate((e) => e.scrollHeight - e.clientHeight - e.scrollTop < 10),
true,
);
await latest.waitFor({ state: 'hidden' });
},
);
+227
View File
@@ -0,0 +1,227 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { Store } = require('../../src/modules/dashboard/store.cjs'),
{ MailStore } = require('../../src/modules/mail/store.cjs'),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs');
const config = require('../../src/modules/assistant/configuration.cjs');
const admin = { id: 'admin', username: 'admin', role: 'admin' };
test(
'configuration changes use safe snapshots, validated patches and current versions',
{ timeout: 180000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-config-')),
dashboard = new Store(path.join(root, 'dashboard')),
mailStore = new MailStore(path.join(root, 'mail')),
store = new AssistantStore(path.join(root, 'assistant'));
t.after(() => {
store.close();
mailStore.close();
fs.rmSync(root, { recursive: true, force: true });
});
const channel = mailStore.saveChannel({
name: '测试邮箱',
email: 'orders@example.test',
password: 'MAIL_PRIVATE_SECRET',
receiveEnabled: true,
enabled: false,
senders: ['templates@example.test'],
smtp: { host: 'smtp.example.test' },
imap: { host: 'imap.example.test' },
}),
deps = { dashboard, mail: { store: mailStore, busy: () => false } };
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'MODEL_PRIVATE_SECRET',
});
const snapshot = config.snapshot(deps, store, admin);
assert.doesNotMatch(
JSON.stringify(snapshot),
/MAIL_PRIVATE_SECRET|MODEL_PRIVATE_SECRET|runtimePath|password|apiKey/,
);
assert.deepEqual(config.snapshot(deps, store, { ...admin, role: 'viewer' }), []);
const proposal = config.propose(
{
targetId: 'mail:' + channel.id,
changes: { name: '新邮箱名', 'smtp.port': 587, 'smtp.security': 'starttls' },
},
snapshot,
deps,
store,
admin,
);
assert.equal(mailStore.publicChannel(channel.id).name, '测试邮箱');
assert.equal(proposal.diff.find((d) => d.field === 'smtp.port').before, 465);
assert.ok(proposal.risks.length);
config.apply(proposal, deps, store, admin);
assert.equal(mailStore.publicChannel(channel.id).smtp.port, 587);
assert.equal(mailStore.channelSecret(channel.id).smtp.password, 'MAIL_PRIVATE_SECRET');
assert.throws(
() => config.apply(proposal, deps, store, admin),
(e) => e.status === 409,
);
for (const changes of [
{ 'smtp.host': 'evil.test' },
{ password: 'bad' },
{ 'smtp.port': 0 },
{ 'smtp.security': 'none' },
{ allowActions: true },
{ name: '\u0000bad' },
])
assert.throws(() =>
config.propose(
{ targetId: 'mail:' + channel.id, changes },
config.snapshot(deps, store, admin),
deps,
store,
admin,
),
);
const schedule = config.propose(
{ targetId: 'schedule', changes: { times: ['10:00', '18:00'] } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
config.apply(schedule, deps, store, admin);
assert.deepEqual(dashboard.settings().schedule.times, ['10:00', '18:00']);
assert.equal(dashboard.settings().schedule.timezone, 'Asia/Shanghai');
const runtime = config.propose(
{ targetId: 'assistant', changes: { dailyLimit: 55 } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
config.apply(runtime, deps, store, admin);
assert.equal(store.settings().dailyLimit, 55);
assert.equal(store.secretSettings().apiKey, 'MODEL_PRIVATE_SECRET');
assert.throws(
() => config.apply(runtime, deps, store, { ...admin, role: 'operator' }),
(e) => e.status === 403,
);
assert.throws(() =>
config.propose(
{ targetId: 'assistant', changes: { allowCodeRepair: true } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
),
);
const directory = store.providers.save({
version: 0,
name: '第二供应商',
preset: 'custom',
protocol: 'openai-completions',
apiBase: 'https://models.example.test/v1',
apiKey: 'SECOND_MODEL_SECRET',
enabled: true,
models: [{ id: 'second-model' }],
}),
provider = directory.providers.find((p) => p.name === '第二供应商');
const prior = store.providers.resolve(),
existing = store.create('historical-owner');
const selection = config.propose(
{ targetId: 'model', changes: { providerId: provider.id, modelId: 'second-model' } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
config.apply(selection, deps, store, admin);
assert.equal(store.providers.resolve().model, 'second-model');
assert.equal(store.providers.resolve().apiKey, 'SECOND_MODEL_SECRET');
assert.deepEqual(store.conversation(existing.id, 'historical-owner').modelSelection, {
providerId: prior.providerId,
modelId: prior.model,
});
assert.equal(
store.providers.resolve(store.conversation(existing.id, 'historical-owner').modelSelection)
.apiKey,
'MODEL_PRIVATE_SECRET',
);
const expired = config.propose(
{ targetId: 'assistant', changes: { dailyLimit: 60 } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
expired.expiresAt = 0;
assert.throws(
() => config.apply(expired, deps, store, admin),
(e) => e.status === 409,
);
assert.equal(store.settings().dailyLimit, 55);
const busy = config.propose(
{ targetId: 'mail:' + channel.id, changes: { name: '正在使用' } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
deps.mail.busy = () => true;
assert.throws(
() => config.apply(busy, deps, store, admin),
(e) => e.status === 409,
);
assert.equal(mailStore.publicChannel(channel.id).name, '新邮箱名');
const existingUnavailable = store.create('prior-unavailable');
const disabled = store.providers.read(provider.id);
store.providers.save({ ...disabled, enabled: false, apiKey: '' });
const replacement = config.propose(
{ targetId: 'model', changes: { providerId: 'deepseek', modelId: prior.model } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
config.apply(replacement, deps, store, admin);
assert.deepEqual(
store.conversation(existingUnavailable.id, 'prior-unavailable').modelSelection,
{ providerId: provider.id, modelId: 'second-model' },
);
const historical = store.create('removed-default-history'),
historyTurn = store.beginTurn(historical.id, 'removed-default-history', '旧供应商历史', {
modelSelection: { providerId: 'deepseek', modelId: prior.model },
});
store.updateTurn(historyTurn.id, 'success', { reply: '旧回复' });
const ambiguous = store.create('ambiguous-legacy'),
ambiguousTurn = store.beginTurn(ambiguous.id, 'ambiguous-legacy', '没有模型记录的旧历史');
store.updateTurn(ambiguousTurn.id, 'success', { reply: '旧回复' });
store.providers.remove('deepseek', { version: store.providers.read('deepseek').version });
store.providers.save({ ...store.providers.read(provider.id), enabled: true, apiKey: '' });
const noDefault = config.propose(
{ targetId: 'model', changes: { providerId: provider.id, modelId: 'second-model' } },
config.snapshot(deps, store, admin),
deps,
store,
admin,
);
assert.throws(
() => config.apply(noDefault, deps, store, admin),
(e) => e.status === 409,
);
assert.equal(store.providers.list().defaultSelection, null);
assert.equal(store.conversation(historical.id, 'removed-default-history').modelSelection, null);
store.setModel(ambiguous.id, 'ambiguous-legacy', {
version: store.conversation(ambiguous.id, 'ambiguous-legacy').version,
providerId: provider.id,
modelId: 'second-model',
});
config.apply(noDefault, deps, store, admin);
assert.deepEqual(store.conversation(historical.id, 'removed-default-history').modelSelection, {
providerId: 'deepseek',
modelId: prior.model,
});
},
);
+189 -9
View File
@@ -1,10 +1,190 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{OperationJournal}=require('../../src/modules/assistant/operation-journal.cjs');
const admin={user:{id:'u1',username:'admin',role:'admin'}},viewer={user:{id:'u2',username:'viewer',role:'viewer'}};
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'controlled-ai-')),store=new AssistantStore(dir),journal=new OperationJournal({file:path.join(dir,'ops.sqlite')});t.after(async()=>{await service.stop();journal.close();store.close();fs.rmSync(dir,{recursive:true,force:true});});store.saveSettings({...store.settings(),apiKey:'TEST-KEY-PRIVATE',enabled:true,runtimePath:path.join(dir,'runtime.js'),apiBase:'https://example.test/anthropic',model:'fixture',allowActions:true,allowCodeRepair:true,repairRepository:dir});let called=0;const repair={readSources:()=>({baselineCommit:'a'.repeat(40),files:[{path:'src/a.cjs',content:'module.exports=1;'}]}),run:async input=>{called++;assert.equal(input.expectedCommit,'a'.repeat(40));return {operationId:'repair-1',status:'rolled_back',previousCommit:input.expectedCommit,resultCommit:'b'.repeat(40),testOutcome:'failed'};}};const runtime={probe:async()=>({available:true}),chat:async input=>{assert.equal(input.context.repair.files[0].path,'src/a.cjs');return JSON.stringify({reply:'修复建议',actions:[],repair:{files:[{path:'src/a.cjs',content:'module.exports=2;'}]}});}};const service=new AssistantService({store,runtime,journal,repairFactory:()=>repair});return {store,journal,service,calls:()=>called};}
test('admin selected source becomes a reviewed repair proposal; execution and rollback result remain auditable',async t=>{const f=fixture(t),c=f.store.create('u1'),turn=f.service.sendRepair(c.id,admin,'修复测试',['src/a.cjs']);await f.service.running.get(turn.id).task;const saved=f.store.conversation(c.id,'u1').turns[0];assert.equal(saved.status,'success',saved.error);assert.equal(f.calls(),0);const action=saved.actions[0];assert.equal(action.kind,'repair_code');assert.equal(action.beforeFiles[0].content,'module.exports=1;');const result=await f.service.executeAction(c.id,action.id,admin);assert.equal(result.result.status,'rolled_back');assert.equal(f.calls(),1);assert(f.service.operations(admin).length>=4);assert.deepEqual(f.service.operations(viewer),[]);assert.doesNotMatch(JSON.stringify(f.service.operations(admin)),/TEST-KEY-PRIVATE/);await assert.rejects(f.service.executeAction(c.id,action.id,admin),e=>e.status===409);});
test('repair permission is checked again at execution and viewers cannot request code',async t=>{const f=fixture(t),c=f.store.create('u1'),turn=f.service.sendRepair(c.id,admin,'修复测试',['src/a.cjs']);await f.service.running.get(turn.id).task;const a=f.store.conversation(c.id,'u1').turns[0].actions[0];f.store.saveSettings({...f.store.settings(),apiKey:'',allowCodeRepair:false});await assert.rejects(f.service.executeAction(c.id,a.id,admin),e=>e.status===403);assert.equal(f.calls(),0);assert.throws(()=>f.service.sendRepair(c.id,viewer,'修改',['src/a.cjs']),e=>e.status===403);});
test('repair response cannot change unselected paths or expose the configured model key',()=>{const {parseRepairResponse}=require('../../src/modules/assistant/repair-response.cjs'),context={baselineCommit:'a'.repeat(40),files:[{path:'src/a.cjs',content:'old'}]};for(const file of [{path:'src/b.cjs',content:'new'},{path:'src/a.cjs',content:'SECRET-CONFIG-KEY'}])assert.throws(()=>parseRepairResponse(JSON.stringify({reply:'proposal',actions:[],repair:{files:[file]}}),{},admin.user,context,'SECRET-CONFIG-KEY'));assert.throws(()=>parseRepairResponse(JSON.stringify({reply:'proposal',actions:[],repair:{files:[{path:'src/a.cjs',content:'new'}]}}),{},admin.user,null,''));});
test('audit failure stops before calling the model and leaves a recoverable error turn',async t=>{const f=fixture(t),c=f.store.create('u1');f.journal.append=()=>{throw Error('journal unavailable');};assert.throws(()=>f.service.sendRepair(c.id,admin,'repair',['src/a.cjs']),e=>e.status===503);assert.equal(f.store.conversation(c.id,'u1').turns[0].status,'error');assert.equal(f.service.running.size,0);});
test('business diagnosis includes authorized automatic orders and blockers without fields or frozen mail bodies',()=>{const {snapshot}=require('../../src/modules/assistant/policy.cjs'),rows={orders:[{id:'own',sample:{connectionId:'a',fields:{secret:'PRIVATE-FIELD'}},event:{orderNo:'123',connectionId:'a',processName:'流程',nodeName:'通知'},status:'pending',archive:{files:[{}]}},{id:'hidden',sample:{connectionId:'b'},event:{orderNo:'999'},status:'failed'}],batches:[], 'execution-tasks':[{id:'task',connectionId:'a',status:'blocked',error:'missing field',row:{processName:'流程',nodeName:'通知'}}]},workspace={snapshot:()=>({connections:[{id:'a',owner:'operator'},{id:'b',owner:'other'}],exceptions:[]}),recordSources:()=>[{id:'a',owner:'operator'},{id:'b',owner:'other'}]},s=snapshot({workspace,orderRules:{all:k=>rows[k]||[]}},{id:'op',username:'operator',role:'operator'});assert.equal(s.business.orders.length,1);assert.equal(s.business.blockers[0].id,'task');assert.doesNotMatch(JSON.stringify(s.business),/PRIVATE-FIELD|999/);});
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
const admin = { user: { id: 'u1', username: 'admin', role: 'admin' } },
viewer = { user: { id: 'u2', username: 'viewer', role: 'viewer' } };
function fixture(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'controlled-ai-')),
store = new AssistantStore(dir),
journal = new OperationJournal({ file: path.join(dir, 'ops.sqlite') });
t.after(async () => {
await service.stop();
journal.close();
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
store.saveSettings({
...store.settings(),
apiKey: 'TEST-KEY-PRIVATE',
enabled: true,
runtimePath: path.join(dir, 'runtime.js'),
apiBase: 'https://example.test/anthropic',
model: 'fixture',
allowActions: true,
allowCodeRepair: true,
repairRepository: dir,
});
let called = 0;
const repair = {
readSources: () => ({
baselineCommit: 'a'.repeat(40),
files: [{ path: 'src/a.cjs', content: 'module.exports=1;' }],
}),
run: async (input) => {
called++;
assert.equal(input.expectedCommit, 'a'.repeat(40));
return {
operationId: 'repair-1',
status: 'rolled_back',
previousCommit: input.expectedCommit,
resultCommit: 'b'.repeat(40),
testOutcome: 'failed',
};
},
};
const runtime = {
probe: async () => ({ available: true }),
chat: async (input) => {
assert.equal(input.context.repair.files[0].path, 'src/a.cjs');
return JSON.stringify({
reply: '修复建议',
actions: [],
repair: { files: [{ path: 'src/a.cjs', content: 'module.exports=2;' }] },
});
},
};
const service = new AssistantService({ store, runtime, journal, repairFactory: () => repair });
return { store, journal, service, calls: () => called };
}
test('admin selected source becomes a reviewed repair proposal; execution and rollback result remain auditable', async (t) => {
const f = fixture(t),
c = f.store.create('u1'),
turn = f.service.sendRepair(c.id, admin, '修复测试', ['src/a.cjs']);
await f.service.running.get(turn.id).task;
const saved = f.store.conversation(c.id, 'u1').turns[0];
assert.equal(saved.status, 'success', saved.error);
assert.equal(f.calls(), 0);
const action = saved.actions[0];
assert.equal(action.kind, 'repair_code');
assert.equal(action.beforeFiles[0].content, 'module.exports=1;');
const result = await f.service.executeAction(c.id, action.id, admin);
assert.equal(result.result.status, 'rolled_back');
assert.equal(f.calls(), 1);
assert(f.service.operations(admin).length >= 4);
assert.deepEqual(f.service.operations(viewer), []);
assert.doesNotMatch(JSON.stringify(f.service.operations(admin)), /TEST-KEY-PRIVATE/);
await assert.rejects(f.service.executeAction(c.id, action.id, admin), (e) => e.status === 409);
});
test('repair permission is checked again at execution and viewers cannot request code', async (t) => {
const f = fixture(t),
c = f.store.create('u1'),
turn = f.service.sendRepair(c.id, admin, '修复测试', ['src/a.cjs']);
await f.service.running.get(turn.id).task;
const a = f.store.conversation(c.id, 'u1').turns[0].actions[0];
f.store.saveSettings({ ...f.store.settings(), apiKey: '', allowCodeRepair: false });
await assert.rejects(f.service.executeAction(c.id, a.id, admin), (e) => e.status === 403);
assert.equal(f.calls(), 0);
assert.throws(
() => f.service.sendRepair(c.id, viewer, '修改', ['src/a.cjs']),
(e) => e.status === 403,
);
});
test('repair response cannot change unselected paths or expose the configured model key', () => {
const { parseRepairResponse } = require('../../src/modules/assistant/repair-response.cjs'),
context = { baselineCommit: 'a'.repeat(40), files: [{ path: 'src/a.cjs', content: 'old' }] };
for (const file of [
{ path: 'src/b.cjs', content: 'new' },
{ path: 'src/a.cjs', content: 'SECRET-CONFIG-KEY' },
])
assert.throws(() =>
parseRepairResponse(
JSON.stringify({ reply: 'proposal', actions: [], repair: { files: [file] } }),
{},
admin.user,
context,
'SECRET-CONFIG-KEY',
),
);
assert.throws(() =>
parseRepairResponse(
JSON.stringify({
reply: 'proposal',
actions: [],
repair: { files: [{ path: 'src/a.cjs', content: 'new' }] },
}),
{},
admin.user,
null,
'',
),
);
});
test('audit failure stops before calling the model and leaves a recoverable error turn', async (t) => {
const f = fixture(t),
c = f.store.create('u1');
f.journal.append = () => {
throw Error('journal unavailable');
};
assert.throws(
() => f.service.sendRepair(c.id, admin, 'repair', ['src/a.cjs']),
(e) => e.status === 503,
);
assert.equal(f.store.conversation(c.id, 'u1').turns[0].status, 'error');
assert.equal(f.service.running.size, 0);
});
test('business diagnosis includes authorized automatic orders and blockers without fields or frozen mail bodies', () => {
const { snapshot } = require('../../src/modules/assistant/policy.cjs'),
rows = {
orders: [
{
id: 'own',
sample: { connectionId: 'a', fields: { secret: 'PRIVATE-FIELD' } },
event: { orderNo: '123', connectionId: 'a', processName: '流程', nodeName: '通知' },
status: 'pending',
archive: { files: [{}] },
},
{
id: 'hidden',
sample: { connectionId: 'b' },
event: { orderNo: '999' },
status: 'failed',
},
],
batches: [],
'execution-tasks': [
{
id: 'task',
connectionId: 'a',
status: 'blocked',
error: 'missing field',
row: { processName: '流程', nodeName: '通知' },
},
],
},
workspace = {
snapshot: () => ({
connections: [
{ id: 'a', owner: 'operator' },
{ id: 'b', owner: 'other' },
],
exceptions: [],
}),
recordSources: () => [
{ id: 'a', owner: 'operator' },
{ id: 'b', owner: 'other' },
],
},
s = snapshot(
{ workspace, orderRules: { all: (k) => rows[k] || [] } },
{ id: 'op', username: 'operator', role: 'operator' },
);
assert.equal(s.business.orders.length, 1);
assert.equal(s.business.blockers[0].id, 'task');
assert.doesNotMatch(JSON.stringify(s.business), /PRIVATE-FIELD|999/);
});
+84 -18
View File
@@ -1,22 +1,88 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'conversation-lifecycle-')),store=new AssistantStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
test('archiving releases active conversation quota, preserves history and remains owner scoped',t=>{
const store=fixture(t),items=Array.from({length:50},()=>store.create('owner'));
assert.equal(typeof store.archive,'function');assert.throws(()=>store.create('owner'),{status:409});assert.throws(()=>store.archive(items[0].id,'other',{version:1}),{status:404});
const archived=store.archive(items[0].id,'owner',{version:1});assert.equal(archived.archived,true);store.create('owner');assert.equal(store.conversations('owner').length,50);assert.equal(store.listConversations('owner',{scope:'archived'}).total,1);
assert.throws(()=>store.restore(items[0].id,'owner',{version:archived.version}),{status:409});store.archive(items[1].id,'owner',{version:1});assert.equal(store.restore(items[0].id,'owner',{version:archived.version}).archived,false);
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { AssistantStore } = require('../../src/modules/assistant/store.cjs');
function fixture(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'conversation-lifecycle-')),
store = new AssistantStore(dir);
t.after(() => {
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
return store;
}
test('archiving releases active conversation quota, preserves history and remains owner scoped', (t) => {
const store = fixture(t),
items = Array.from({ length: 50 }, () => store.create('owner'));
assert.equal(typeof store.archive, 'function');
assert.throws(() => store.create('owner'), { status: 409 });
assert.throws(() => store.archive(items[0].id, 'other', { version: 1 }), { status: 404 });
const archived = store.archive(items[0].id, 'owner', { version: 1 });
assert.equal(archived.archived, true);
store.create('owner');
assert.equal(store.conversations('owner').length, 50);
assert.equal(store.listConversations('owner', { scope: 'archived' }).total, 1);
assert.throws(() => store.restore(items[0].id, 'owner', { version: archived.version }), {
status: 409,
});
store.archive(items[1].id, 'owner', { version: 1 });
assert.equal(store.restore(items[0].id, 'owner', { version: archived.version }).archived, false);
});
test('running turns cannot be archived and archived conversations cannot execute or accept messages',t=>{
const store=fixture(t),conversation=store.create('owner');assert.equal(typeof store.archive,'function');const turn=store.beginTurn(conversation.id,'owner','synthetic message');
assert.throws(()=>store.archive(conversation.id,'owner',{version:store.conversation(conversation.id,'owner').version}),{status:409});store.updateTurn(turn.id,'success',{reply:'synthetic answer'});
const saved=store.archive(conversation.id,'owner',{version:store.conversation(conversation.id,'owner').version});assert.throws(()=>store.beginTurn(conversation.id,'owner','new'),{status:409});assert.throws(()=>store.action(conversation.id,'owner','none',()=>{}),{status:409});assert.equal(store.conversation(conversation.id,'owner').turns[0].reply,'synthetic answer');assert.equal(saved.archived,true);
test('running turns cannot be archived and archived conversations cannot execute or accept messages', (t) => {
const store = fixture(t),
conversation = store.create('owner');
assert.equal(typeof store.archive, 'function');
const turn = store.beginTurn(conversation.id, 'owner', 'synthetic message');
assert.throws(
() =>
store.archive(conversation.id, 'owner', {
version: store.conversation(conversation.id, 'owner').version,
}),
{ status: 409 },
);
store.updateTurn(turn.id, 'success', { reply: 'synthetic answer' });
const saved = store.archive(conversation.id, 'owner', {
version: store.conversation(conversation.id, 'owner').version,
});
assert.throws(() => store.beginTurn(conversation.id, 'owner', 'new'), { status: 409 });
assert.throws(() => store.action(conversation.id, 'owner', 'none', () => {}), { status: 409 });
assert.equal(store.conversation(conversation.id, 'owner').turns[0].reply, 'synthetic answer');
assert.equal(saved.archived, true);
});
test('a full conversation continues once with a bounded private history and retains action evidence',t=>{
const store=fixture(t),parent=store.create('owner');assert.equal(typeof store.continueConversation,'function');
for(let i=0;i<100;i++){const id=crypto.randomUUID();store.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(id,parent.id,'success',store.encode(id,{text:'line-'+i,reply:'answer-'+i,actions:i===0?[{id:'evidence',status:'success',result:{verified:true}}]:[],evidence:[]}), '2020-01-01','2020-01-01T00:00:00Z');}
const next=store.continueConversation(parent.id,'owner',{version:1});assert.equal(next.continuationOf,parent.id);assert.equal(next.turns.length,0);assert.equal(store.conversation(parent.id,'owner').archived,true);assert.equal(store.conversation(parent.id,'owner').turns[0].actions[0].result.verified,true);
assert.equal(store.continueConversation(parent.id,'owner',{version:1}).id,next.id);const history=store.history(next.id,'owner');assert.equal(history.length,3);assert.equal(history[0].text,'line-97');
store.beginTurn(next.id,'owner','follow up');assert.equal(store.conversation(next.id,'owner').continuationOf,parent.id);assert.throws(()=>store.history(next.id,'other'),{status:404});
test('a full conversation continues once with a bounded private history and retains action evidence', (t) => {
const store = fixture(t),
parent = store.create('owner');
assert.equal(typeof store.continueConversation, 'function');
for (let i = 0; i < 100; i++) {
const id = crypto.randomUUID();
store.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(
id,
parent.id,
'success',
store.encode(id, {
text: 'line-' + i,
reply: 'answer-' + i,
actions: i === 0 ? [{ id: 'evidence', status: 'success', result: { verified: true } }] : [],
evidence: [],
}),
'2020-01-01',
'2020-01-01T00:00:00Z',
);
}
const next = store.continueConversation(parent.id, 'owner', { version: 1 });
assert.equal(next.continuationOf, parent.id);
assert.equal(next.turns.length, 0);
assert.equal(store.conversation(parent.id, 'owner').archived, true);
assert.equal(store.conversation(parent.id, 'owner').turns[0].actions[0].result.verified, true);
assert.equal(store.continueConversation(parent.id, 'owner', { version: 1 }).id, next.id);
const history = store.history(next.id, 'owner');
assert.equal(history.length, 3);
assert.equal(history[0].text, 'line-97');
store.beginTurn(next.id, 'owner', 'follow up');
assert.equal(store.conversation(next.id, 'owner').continuationOf, parent.id);
assert.throws(() => store.history(next.id, 'other'), { status: 404 });
});
+54 -5
View File
@@ -1,6 +1,55 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict');const {managementFixture}=require('./management-fixture.cjs');
test('conversation row menus archive, restore and delete through an explicit recycle bin',{timeout:120000},async t=>{
const f=await managementFixture(t,{browser:true}),{page,open,store}=f;const owner=f.users.users().find(u=>u.username==='admin').id,c=store.create(owner),turn=store.beginTurn(c.id,owner,'待管理的测试对话');store.updateTurn(turn.id,'success',{reply:'历史保留'});await open();
const row=page.locator('[data-conversation-row]').filter({hasText:'待管理的测试对话'});await row.getByRole('button',{name:'会话操作',exact:true}).click();await page.getByRole('button',{name:'归档',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('archived');await page.locator('[data-conversation-row]').filter({hasText:'待管理的测试对话'}).getByRole('button',{name:'会话操作',exact:true}).click();await page.getByRole('button',{name:'恢复会话',exact:true}).last().click();await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-conversation-row]').filter({hasText:'待管理的测试对话'}).getByRole('button',{name:'会话操作',exact:true}).click();await page.getByRole('button',{name:'移至回收站',exact:true}).click();await page.getByLabel('会话范围',{exact:true}).selectOption('deleted');await page.locator('[data-assistant-conversation]').filter({hasText:'待管理的测试对话'}).click();assert.equal(await page.getByRole('button',{name:'发送',exact:true}).isDisabled(),true);await page.getByRole('button',{name:'永久删除',exact:true}).click();await page.getByRole('dialog',{name:'永久删除会话',exact:true}).waitFor();await require('node:fs/promises').mkdir('output/verification/dsh-providers',{recursive:true});await page.screenshot({path:'output/verification/dsh-providers/trash-confirmation.png',fullPage:true});await page.getByRole('button',{name:'取消',exact:true}).click();assert.equal(store.listConversations(owner,{scope:'deleted'}).total,1);await page.getByRole('button',{name:'永久删除',exact:true}).click();await page.getByRole('button',{name:'确认永久删除',exact:true}).click();await page.getByText('没有匹配会话。',{exact:true}).waitFor();assert.equal(store.usage().calls,1);
});
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
test(
'conversation row menus archive, restore and delete through an explicit recycle bin',
{ timeout: 120000 },
async (t) => {
const f = await managementFixture(t, { browser: true }),
{ page, open, store } = f;
const owner = f.users.users().find((u) => u.username === 'admin').id,
c = store.create(owner),
turn = store.beginTurn(c.id, owner, '待管理的测试对话');
store.updateTurn(turn.id, 'success', { reply: '历史保留' });
await open();
const row = page.locator('[data-conversation-row]').filter({ hasText: '待管理的测试对话' });
await row.getByRole('button', { name: '会话操作', exact: true }).click();
await page.getByRole('button', { name: '归档', exact: true }).click();
await page.getByLabel('会话范围', { exact: true }).selectOption('archived');
await page
.locator('[data-conversation-row]')
.filter({ hasText: '待管理的测试对话' })
.getByRole('button', { name: '会话操作', exact: true })
.click();
await page.getByRole('button', { name: '恢复会话', exact: true }).last().click();
await page.getByLabel('会话范围', { exact: true }).selectOption('active');
await page
.locator('[data-conversation-row]')
.filter({ hasText: '待管理的测试对话' })
.getByRole('button', { name: '会话操作', exact: true })
.click();
await page.getByRole('button', { name: '移至回收站', exact: true }).click();
await page.getByLabel('会话范围', { exact: true }).selectOption('deleted');
await page
.locator('[data-assistant-conversation]')
.filter({ hasText: '待管理的测试对话' })
.click();
assert.equal(await page.getByRole('button', { name: '发送', exact: true }).isDisabled(), true);
await page.getByRole('button', { name: '永久删除', exact: true }).click();
await page.getByRole('dialog', { name: '永久删除会话', exact: true }).waitFor();
await require('node:fs/promises').mkdir('output/verification/dsh-providers', {
recursive: true,
});
await page.screenshot({
path: 'output/verification/dsh-providers/trash-confirmation.png',
fullPage: true,
});
await page.getByRole('button', { name: '取消', exact: true }).click();
assert.equal(store.listConversations(owner, { scope: 'deleted' }).total, 1);
await page.getByRole('button', { name: '永久删除', exact: true }).click();
await page.getByRole('button', { name: '确认永久删除', exact: true }).click();
await page.getByText('没有匹配会话。', { exact: true }).waitFor();
assert.equal(store.usage().calls, 1);
},
);
+145 -19
View File
@@ -1,27 +1,153 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs');
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'assistant-trash-')),store=new AssistantStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
test('trashed conversations leave normal lists, retain read-only history, restore original archive state',t=>{
const store=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','keep history');store.updateTurn(turn.id,'success',{reply:'retained'});let current=store.conversation(c.id,'alice');current=store.archive(c.id,'alice',{version:current.version});const deleted=store.trash(c.id,'alice',{version:current.version});
assert.equal(store.listConversations('alice',{scope:'active'}).total,0);assert.equal(store.listConversations('alice',{scope:'archived'}).total,0);assert.equal(store.listConversations('alice',{scope:'deleted'}).total,1);assert.throws(()=>store.conversation(c.id,'alice'),e=>e.status===404);assert.equal(store.conversation(c.id,'alice',{includeDeleted:true}).turns[0].reply,'retained');assert.throws(()=>store.beginTurn(c.id,'alice','no replay'),e=>e.status===404);
const restored=store.restoreDeleted(c.id,'alice',{version:deleted.version});assert.equal(restored.archived,true);assert.equal(restored.deletedAt,null);assert.equal(store.listConversations('alice',{scope:'archived'}).total,1);
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { AssistantStore } = require('../../src/modules/assistant/store.cjs');
function fixture(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'assistant-trash-')),
store = new AssistantStore(dir);
t.after(() => {
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
return store;
}
test('trashed conversations leave normal lists, retain read-only history, restore original archive state', (t) => {
const store = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'keep history');
store.updateTurn(turn.id, 'success', { reply: 'retained' });
let current = store.conversation(c.id, 'alice');
current = store.archive(c.id, 'alice', { version: current.version });
const deleted = store.trash(c.id, 'alice', { version: current.version });
assert.equal(store.listConversations('alice', { scope: 'active' }).total, 0);
assert.equal(store.listConversations('alice', { scope: 'archived' }).total, 0);
assert.equal(store.listConversations('alice', { scope: 'deleted' }).total, 1);
assert.throws(
() => store.conversation(c.id, 'alice'),
(e) => e.status === 404,
);
assert.equal(
store.conversation(c.id, 'alice', { includeDeleted: true }).turns[0].reply,
'retained',
);
assert.throws(
() => store.beginTurn(c.id, 'alice', 'no replay'),
(e) => e.status === 404,
);
const restored = store.restoreDeleted(c.id, 'alice', { version: deleted.version });
assert.equal(restored.archived, true);
assert.equal(restored.deletedAt, null);
assert.equal(store.listConversations('alice', { scope: 'archived' }).total, 1);
});
test('delete operations enforce owner/version/idle and require explicit purge confirmation',t=>{
const store=fixture(t),c=store.create('alice'),running=store.beginTurn(c.id,'alice','running');assert.throws(()=>store.trash(c.id,'bob',{version:2}),e=>e.status===404);assert.throws(()=>store.trash(c.id,'alice',{version:2}),e=>e.status===409);store.updateTurn(running.id,'success',{reply:'ok'});const current=store.conversation(c.id,'alice');assert.throws(()=>store.trash(c.id,'alice',{version:current.version-1}),e=>e.status===409);const deleted=store.trash(c.id,'alice',{version:current.version});assert.throws(()=>store.purge(c.id,'alice',{version:deleted.version}),e=>e.status===400);assert.throws(()=>store.purge(c.id,'bob',{version:deleted.version,confirm:'delete'}),e=>e.status===404);store.purge(c.id,'alice',{version:deleted.version,confirm:'delete'});assert.equal(store.listConversations('alice',{scope:'deleted'}).total,0);
test('delete operations enforce owner/version/idle and require explicit purge confirmation', (t) => {
const store = fixture(t),
c = store.create('alice'),
running = store.beginTurn(c.id, 'alice', 'running');
assert.throws(
() => store.trash(c.id, 'bob', { version: 2 }),
(e) => e.status === 404,
);
assert.throws(
() => store.trash(c.id, 'alice', { version: 2 }),
(e) => e.status === 409,
);
store.updateTurn(running.id, 'success', { reply: 'ok' });
const current = store.conversation(c.id, 'alice');
assert.throws(
() => store.trash(c.id, 'alice', { version: current.version - 1 }),
(e) => e.status === 409,
);
const deleted = store.trash(c.id, 'alice', { version: current.version });
assert.throws(
() => store.purge(c.id, 'alice', { version: deleted.version }),
(e) => e.status === 400,
);
assert.throws(
() => store.purge(c.id, 'bob', { version: deleted.version, confirm: 'delete' }),
(e) => e.status === 404,
);
store.purge(c.id, 'alice', { version: deleted.version, confirm: 'delete' });
assert.equal(store.listConversations('alice', { scope: 'deleted' }).total, 0);
});
test('purging messages/events/request identities never refunds the durable daily quota',t=>{
const store=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','call',{requestId:'one',requestPayload:{text:'call'}});store.updateTurn(turn.id,'success',{reply:'done'});const quota=store.usage().calls,deleted=store.trash(c.id,'alice',{version:store.conversation(c.id,'alice').version});store.purge(c.id,'alice',{version:deleted.version,confirm:'delete'});assert.equal(store.usage().calls,quota);for(const table of ['turns','conversation_events','assistant_requests'])assert.equal(store.db.prepare('SELECT COUNT(*) n FROM '+table).get().n,0);
test('purging messages/events/request identities never refunds the durable daily quota', (t) => {
const store = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'call', {
requestId: 'one',
requestPayload: { text: 'call' },
});
store.updateTurn(turn.id, 'success', { reply: 'done' });
const quota = store.usage().calls,
deleted = store.trash(c.id, 'alice', { version: store.conversation(c.id, 'alice').version });
store.purge(c.id, 'alice', { version: deleted.version, confirm: 'delete' });
assert.equal(store.usage().calls, quota);
for (const table of ['turns', 'conversation_events', 'assistant_requests'])
assert.equal(store.db.prepare('SELECT COUNT(*) n FROM ' + table).get().n, 0);
});
test('continuation keeps its inherited context after its parent is permanently deleted',t=>{
const store=fixture(t),parent=store.create('alice'),turn=store.beginTurn(parent.id,'alice','original question');store.updateTurn(turn.id,'success',{reply:'original answer'});const child=store.continueConversation(parent.id,'alice',{version:store.conversation(parent.id,'alice').version});const deleted=store.trash(parent.id,'alice',{version:store.conversation(parent.id,'alice').version});store.purge(parent.id,'alice',{version:deleted.version,confirm:'delete'});const history=store.history(child.id,'alice');assert.equal(history[0].text,'original question');assert.equal(history[0].reply,'original answer');assert.equal(store.conversation(child.id,'alice').continuationOf,parent.id);
test('continuation keeps its inherited context after its parent is permanently deleted', (t) => {
const store = fixture(t),
parent = store.create('alice'),
turn = store.beginTurn(parent.id, 'alice', 'original question');
store.updateTurn(turn.id, 'success', { reply: 'original answer' });
const child = store.continueConversation(parent.id, 'alice', {
version: store.conversation(parent.id, 'alice').version,
});
const deleted = store.trash(parent.id, 'alice', {
version: store.conversation(parent.id, 'alice').version,
});
store.purge(parent.id, 'alice', { version: deleted.version, confirm: 'delete' });
const history = store.history(child.id, 'alice');
assert.equal(history[0].text, 'original question');
assert.equal(history[0].reply, 'original answer');
assert.equal(store.conversation(child.id, 'alice').continuationOf, parent.id);
});
test('a running action blocks trash even after model reply completed',t=>{
const store=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','call');store.updateTurn(turn.id,'success',{reply:'done',actions:[{id:'action-one',status:'running'}]});assert.throws(()=>store.trash(c.id,'alice',{version:store.conversation(c.id,'alice').version}),e=>e.status===409);
test('a running action blocks trash even after model reply completed', (t) => {
const store = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'call');
store.updateTurn(turn.id, 'success', {
reply: 'done',
actions: [{ id: 'action-one', status: 'running' }],
});
assert.throws(
() => store.trash(c.id, 'alice', { version: store.conversation(c.id, 'alice').version }),
(e) => e.status === 409,
);
});
test('continuation response exposes the model actually inherited by the next request',t=>{
const store=fixture(t);store.saveSettings({...store.settings(),apiKey:'TEST_INHERITED_MODEL_KEY'});const c=store.create('alice'),chosen=store.setModel(c.id,'alice',{version:c.version,providerId:'deepseek',modelId:store.settings().model}),child=store.continueConversation(c.id,'alice',{version:chosen.version});assert.deepEqual(child.modelSelection,{providerId:'deepseek',modelId:store.settings().model});
test('continuation response exposes the model actually inherited by the next request', (t) => {
const store = fixture(t);
store.saveSettings({ ...store.settings(), apiKey: 'TEST_INHERITED_MODEL_KEY' });
const c = store.create('alice'),
chosen = store.setModel(c.id, 'alice', {
version: c.version,
providerId: 'deepseek',
modelId: store.settings().model,
}),
child = store.continueConversation(c.id, 'alice', { version: chosen.version });
assert.deepEqual(child.modelSelection, {
providerId: 'deepseek',
modelId: store.settings().model,
});
});
test('a removed continuation has an explicit recycle-bin outcome and can be recreated after permanent deletion',t=>{
const store=fixture(t),parent=store.create('alice'),child=store.continueConversation(parent.id,'alice',{version:parent.version}),deleted=store.trash(child.id,'alice',{version:child.version});const latest=store.conversation(parent.id,'alice');assert.throws(()=>store.continueConversation(parent.id,'alice',{version:latest.version}),e=>e.status===409&&/回收站/.test(e.message));store.purge(child.id,'alice',{version:deleted.version,confirm:'delete'});assert.throws(()=>store.continueConversation(parent.id,'alice',{version:parent.version}),e=>e.status===409);const next=store.continueConversation(parent.id,'alice',{version:latest.version});assert.notEqual(next.id,child.id);assert.equal(next.continuationOf,parent.id);
test('a removed continuation has an explicit recycle-bin outcome and can be recreated after permanent deletion', (t) => {
const store = fixture(t),
parent = store.create('alice'),
child = store.continueConversation(parent.id, 'alice', { version: parent.version }),
deleted = store.trash(child.id, 'alice', { version: child.version });
const latest = store.conversation(parent.id, 'alice');
assert.throws(
() => store.continueConversation(parent.id, 'alice', { version: latest.version }),
(e) => e.status === 409 && /回收站/.test(e.message),
);
store.purge(child.id, 'alice', { version: deleted.version, confirm: 'delete' });
assert.throws(
() => store.continueConversation(parent.id, 'alice', { version: parent.version }),
(e) => e.status === 409,
);
const next = store.continueConversation(parent.id, 'alice', { version: latest.version });
assert.notEqual(next.id, child.id);
assert.equal(next.continuationOf, parent.id);
});
+272 -42
View File
@@ -1,44 +1,274 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
async function fixture(t){
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-workspace-ui-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');const store=new AssistantStore(path.join(dir,'assistant'));let calls=0;
const assistant=new AssistantService({store,dashboard:users,runtime:{chat:async({onEvent})=>{calls++;onEvent?.({kind:'model',data:{phase:'step_start'}});await new Promise(r=>setTimeout(r,150));return JSON.stringify({reply:'## 诊断结论\n\n连接状态正常。\n\n| 项目 | 结果 |\n|---|---|\n| 存储 | 正常 |',actions:[]});}}});
const server=createDashboard({store:users,assistant,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1366,height:768}});page.setDefaultTimeout(10000);
t.after(async()=>{await browser.close();server.closeAssistantStreams?.();await assistant.stop();server.closeAllConnections();await new Promise(r=>server.close(r));store.close();await fs.rm(dir,{recursive:true,force:true});});
await page.goto('http://127.0.0.1:'+server.address().port+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
return {page,store,assistant,calls:()=>calls};
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
async function fixture(t) {
const { Store } = require('../../src/modules/dashboard/store.cjs'),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
{ createDashboard } = require('../../src/app/dashboard.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-workspace-ui-')),
users = new Store(path.join(dir, 'users'));
users.bootstrap('admin', 'Test-password-123');
const store = new AssistantStore(path.join(dir, 'assistant'));
let calls = 0;
const assistant = new AssistantService({
store,
dashboard: users,
runtime: {
chat: async ({ onEvent }) => {
calls++;
onEvent?.({ kind: 'model', data: { phase: 'step_start' } });
await new Promise((r) => setTimeout(r, 150));
return JSON.stringify({
reply: '## 诊断结论\n\n连接状态正常。\n\n| 项目 | 结果 |\n|---|---|\n| 存储 | 正常 |',
actions: [],
});
},
},
});
const server = createDashboard({ store: users, assistant, outputDir: dir });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs'),
browser = await loadPlaywright().chromium.launch(browserOptions());
const page = await browser.newPage({ viewport: { width: 1366, height: 768 } });
page.setDefaultTimeout(10000);
t.after(async () => {
await browser.close();
server.closeAssistantStreams?.();
await assistant.stop();
server.closeAllConnections();
await new Promise((r) => server.close(r));
store.close();
await fs.rm(dir, { recursive: true, force: true });
});
await page.goto('http://127.0.0.1:' + server.address().port + '/#assistant');
await page.getByLabel('账号', { exact: true }).fill('admin');
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
return { page, store, assistant, calls: () => calls };
}
test('three-column workspace keeps input visible and diagnostic commands have no hidden side effects',{timeout:90000},async t=>{
const {page,calls}=await fixture(t);await page.locator('.assistant-workspace').waitFor();const input=page.getByLabel('发送给 DSH',{exact:true}),rect=await input.boundingBox();assert.ok(rect.y+rect.height<=768);
await input.fill('/help');await input.press('Enter');await page.getByText('固定诊断命令',{exact:true}).waitFor();assert.equal(calls(),0);
await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();assert.equal(calls(),0);
await input.fill('/shell');await input.press('Enter');await page.locator('#assistant-error').filter({hasText:'此命令未开放'}).waitFor();assert.equal(await input.inputValue(),'/shell');assert.equal(calls(),0);
await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();await fs.mkdir('output/verification/dsh-workspace',{recursive:true});for(const [width,height]of [[1600,900],[1366,768],[1024,768],[390,844]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:`output/verification/dsh-workspace/workspace-${width}.png`,fullPage:true});}
});
test('replies render structured content and preserve DOM nodes across context refresh',{timeout:90000},async t=>{
const {page,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload();
const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('诊断连接');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-answer table').waitFor();assert.equal(await page.locator('.assistant-answer h2').textContent(),'诊断结论');
await page.locator('.assistant-answer').evaluate(node=>{node.dataset.identity='retained';});await page.getByRole('button',{name:'刷新概况',exact:true}).click();assert.equal(await page.locator('.assistant-answer').getAttribute('data-identity'),'retained');
await page.getByRole('button',{name:'诊断依据',exact:true}).click();await page.locator('#aw-panel-evidence').filter({hasText:'实际用于该轮分析'}).waitFor();await input.fill('未发送的草稿');await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.locator('#assistant-title').filter({hasText:'新对话'}).waitFor();assert.match(await page.locator('#aw-panel-evidence').textContent(),/点击回答/);await input.fill('另一个草稿');await page.locator('[data-assistant-conversation]').filter({hasText:'诊断连接'}).click();assert.equal(await input.inputValue(),'未发送的草稿');
});
test('native-style action presentation keeps unknown and blocked results distinct from success',{timeout:90000},async t=>{
const {page}=await fixture(t);const labels=await page.evaluate(()=>({unknown:AssistantConversation.actionState({status:'needs_review'}),blocked:AssistantConversation.actionState({status:'success',result:{status:'blocked'}})}));assert.equal(labels.unknown,'结果待核验');assert.equal(labels.blocked,'操作受阻');
});
test('a failed late submission cannot replace the draft or error of a newer conversation',{timeout:90000},async t=>{
const {page,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload();await page.getByRole('button',{name:'新建对话',exact:true}).click();
let release;const gate=new Promise(r=>release=r);t.after(()=>release());await page.route('**/api/assistant/conversations/*/messages',async route=>{await gate;await route.fulfill({status:503,json:{error:'OLD_REQUEST_FAILED'}});});
const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('旧会话请求');const started=page.waitForRequest(r=>r.url().endsWith('/messages'));await page.getByRole('button',{name:'发送',exact:true}).click();await started;await page.getByRole('button',{name:'新建对话',exact:true}).click();await input.fill('新会话草稿');const returned=page.waitForResponse(r=>r.url().endsWith('/messages')&&r.status()===503);release();await returned;await page.evaluate(()=>new Promise(r=>setTimeout(r,100)));assert.equal(await input.inputValue(),'新会话草稿');assert.equal(await page.locator('#assistant-error').textContent(),'');
});
test('local status commands clear an old diagnostic target before the next ordinary question',{timeout:90000},async t=>{
const {page,store,assistant}=await fixture(t);assistant.deps.workspace={snapshot:()=>({connections:[{id:'bpm-a',name:'测试连接 A',owner:'admin',status:'connected'}],exceptions:[]}),getConnection:()=>({id:'bpm-a',owner:'admin'})};store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});await page.reload();
const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('/bpm');await input.press('Enter');await page.getByRole('option',{name:/测试连接 A/}).click();await input.fill('/status');await input.press('Enter');await page.getByRole('heading',{name:'诊断概况',exact:true}).waitFor();await input.fill('查看全部运行状态');const submitted=page.waitForRequest(r=>r.url().endsWith('/messages'));await page.getByRole('button',{name:'发送',exact:true}).click();assert.equal((await submitted).postDataJSON().diagnostic,undefined);
});
test('assistant Markdown keeps text and safe links without loading images or executable HTML',{timeout:90000},async t=>{
const {page}=await fixture(t);const result=await page.evaluate(()=>{const host=document.createElement('div'),escape=value=>String(value).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));host.innerHTML=AssistantConversation.markdown('<img src=x onerror=alert(1)>\n\n[bad](javascript:alert%281%29) ![remote](https://example.invalid/track.png) [safe](https://example.com/docs)\n\n```html\n<script>alert(1)</script>\n```',escape);return {images:host.querySelectorAll('img').length,scripts:host.querySelectorAll('script').length,links:[...host.querySelectorAll('a')].map(a=>({href:a.href,rel:a.rel})),text:host.textContent};});assert.equal(result.images,0);assert.equal(result.scripts,0);assert.deepEqual(result.links,[{href:'https://example.com/docs',rel:'noopener noreferrer'}]);assert.match(result.text,/<img src=x onerror=alert\(1\)>/);
});
test('a stream authorization change clears the entire old workspace until identity is reloaded',{timeout:90000},async t=>{
const {page,store}=await fixture(t);const owner=store.db.prepare('SELECT owner FROM conversations LIMIT 1').get()?.owner;const me=await(await page.request.get(new URL('/api/me',page.url()).href)).json(),id=owner||me.user.id;store.create(id);
await page.route('**/api/assistant/conversations/*/stream?*',route=>route.fulfill({contentType:'text/event-stream',body:'event: auth_required\ndata: {"status":401}\n\n'}));await page.reload();await page.getByRole('button',{name:'重新加载',exact:true}).waitFor();assert.equal(await page.locator('.assistant-workspace').count(),0);
});
test(
'three-column workspace keeps input visible and diagnostic commands have no hidden side effects',
{ timeout: 90000 },
async (t) => {
const { page, calls } = await fixture(t);
await page.locator('.assistant-workspace').waitFor();
const input = page.getByLabel('发送给 DSH', { exact: true }),
rect = await input.boundingBox();
assert.ok(rect.y + rect.height <= 768);
await input.fill('/help');
await input.press('Enter');
await page.getByText('固定诊断命令', { exact: true }).waitFor();
assert.equal(calls(), 0);
await input.fill('/status');
await input.press('Enter');
await page.getByRole('heading', { name: '诊断概况', exact: true }).waitFor();
assert.equal(calls(), 0);
await input.fill('/shell');
await input.press('Enter');
await page.locator('#assistant-error').filter({ hasText: '此命令未开放' }).waitFor();
assert.equal(await input.inputValue(), '/shell');
assert.equal(calls(), 0);
await input.fill('/status');
await input.press('Enter');
await page.getByRole('heading', { name: '诊断概况', exact: true }).waitFor();
await fs.mkdir('output/verification/dsh-workspace', { recursive: true });
for (const [width, height] of [
[1600, 900],
[1366, 768],
[1024, 768],
[390, 844],
]) {
await page.setViewportSize({ width, height });
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
await page.screenshot({
path: `output/verification/dsh-workspace/workspace-${width}.png`,
fullPage: true,
});
}
},
);
test(
'replies render structured content and preserve DOM nodes across context refresh',
{ timeout: 90000 },
async (t) => {
const { page, store } = await fixture(t);
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://fixture.example/anthropic',
model: 'fixture',
apiKey: 'TEST_ONLY_KEY',
allowActions: false,
});
await page.reload();
const input = page.getByLabel('发送给 DSH', { exact: true });
await input.fill('诊断连接');
await page.getByRole('button', { name: '发送', exact: true }).click();
await page.locator('.assistant-answer table').waitFor();
assert.equal(await page.locator('.assistant-answer h2').textContent(), '诊断结论');
await page.locator('.assistant-answer').evaluate((node) => {
node.dataset.identity = 'retained';
});
await page.getByRole('button', { name: '刷新概况', exact: true }).click();
assert.equal(await page.locator('.assistant-answer').getAttribute('data-identity'), 'retained');
await page.getByRole('button', { name: '诊断依据', exact: true }).click();
await page.locator('#aw-panel-evidence').filter({ hasText: '实际用于该轮分析' }).waitFor();
await input.fill('未发送的草稿');
await page.getByRole('button', { name: '新建对话', exact: true }).click();
await page.locator('#assistant-title').filter({ hasText: '新对话' }).waitFor();
assert.match(await page.locator('#aw-panel-evidence').textContent(), /点击回答/);
await input.fill('另一个草稿');
await page.locator('[data-assistant-conversation]').filter({ hasText: '诊断连接' }).click();
assert.equal(await input.inputValue(), '未发送的草稿');
},
);
test(
'native-style action presentation keeps unknown and blocked results distinct from success',
{ timeout: 90000 },
async (t) => {
const { page } = await fixture(t);
const labels = await page.evaluate(() => ({
unknown: AssistantConversation.actionState({ status: 'needs_review' }),
blocked: AssistantConversation.actionState({
status: 'success',
result: { status: 'blocked' },
}),
}));
assert.equal(labels.unknown, '结果待核验');
assert.equal(labels.blocked, '操作受阻');
},
);
test(
'a failed late submission cannot replace the draft or error of a newer conversation',
{ timeout: 90000 },
async (t) => {
const { page, store } = await fixture(t);
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://fixture.example/anthropic',
model: 'fixture',
apiKey: 'TEST_ONLY_KEY',
allowActions: false,
});
await page.reload();
await page.getByRole('button', { name: '新建对话', exact: true }).click();
let release;
const gate = new Promise((r) => (release = r));
t.after(() => release());
await page.route('**/api/assistant/conversations/*/messages', async (route) => {
await gate;
await route.fulfill({ status: 503, json: { error: 'OLD_REQUEST_FAILED' } });
});
const input = page.getByLabel('发送给 DSH', { exact: true });
await input.fill('旧会话请求');
const started = page.waitForRequest((r) => r.url().endsWith('/messages'));
await page.getByRole('button', { name: '发送', exact: true }).click();
await started;
await page.getByRole('button', { name: '新建对话', exact: true }).click();
await input.fill('新会话草稿');
const returned = page.waitForResponse(
(r) => r.url().endsWith('/messages') && r.status() === 503,
);
release();
await returned;
await page.evaluate(() => new Promise((r) => setTimeout(r, 100)));
assert.equal(await input.inputValue(), '新会话草稿');
assert.equal(await page.locator('#assistant-error').textContent(), '');
},
);
test(
'local status commands clear an old diagnostic target before the next ordinary question',
{ timeout: 90000 },
async (t) => {
const { page, store, assistant } = await fixture(t);
assistant.deps.workspace = {
snapshot: () => ({
connections: [{ id: 'bpm-a', name: '测试连接 A', owner: 'admin', status: 'connected' }],
exceptions: [],
}),
getConnection: () => ({ id: 'bpm-a', owner: 'admin' }),
};
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://fixture.example/anthropic',
model: 'fixture',
apiKey: 'TEST_ONLY_KEY',
allowActions: false,
});
await page.reload();
const input = page.getByLabel('发送给 DSH', { exact: true });
await input.fill('/bpm');
await input.press('Enter');
await page.getByRole('option', { name: /测试连接 A/ }).click();
await input.fill('/status');
await input.press('Enter');
await page.getByRole('heading', { name: '诊断概况', exact: true }).waitFor();
await input.fill('查看全部运行状态');
const submitted = page.waitForRequest((r) => r.url().endsWith('/messages'));
await page.getByRole('button', { name: '发送', exact: true }).click();
assert.equal((await submitted).postDataJSON().diagnostic, undefined);
},
);
test(
'assistant Markdown keeps text and safe links without loading images or executable HTML',
{ timeout: 90000 },
async (t) => {
const { page } = await fixture(t);
const result = await page.evaluate(() => {
const host = document.createElement('div'),
escape = (value) =>
String(value).replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
);
host.innerHTML = AssistantConversation.markdown(
'<img src=x onerror=alert(1)>\n\n[bad](javascript:alert%281%29) ![remote](https://example.invalid/track.png) [safe](https://example.com/docs)\n\n```html\n<script>alert(1)</script>\n```',
escape,
);
return {
images: host.querySelectorAll('img').length,
scripts: host.querySelectorAll('script').length,
links: [...host.querySelectorAll('a')].map((a) => ({ href: a.href, rel: a.rel })),
text: host.textContent,
};
});
assert.equal(result.images, 0);
assert.equal(result.scripts, 0);
assert.deepEqual(result.links, [
{ href: 'https://example.com/docs', rel: 'noopener noreferrer' },
]);
assert.match(result.text, /<img src=x onerror=alert\(1\)>/);
},
);
test(
'a stream authorization change clears the entire old workspace until identity is reloaded',
{ timeout: 90000 },
async (t) => {
const { page, store } = await fixture(t);
const owner = store.db.prepare('SELECT owner FROM conversations LIMIT 1').get()?.owner;
const me = await (await page.request.get(new URL('/api/me', page.url()).href)).json(),
id = owner || me.user.id;
store.create(id);
await page.route('**/api/assistant/conversations/*/stream?*', (route) =>
route.fulfill({
contentType: 'text/event-stream',
body: 'event: auth_required\ndata: {"status":401}\n\n',
}),
);
await page.reload();
await page.getByRole('button', { name: '重新加载', exact: true }).waitFor();
assert.equal(await page.locator('.assistant-workspace').count(), 0);
},
);
+122 -27
View File
@@ -1,32 +1,127 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const events=()=>require('../../src/modules/assistant/dsh-events.cjs');
test('incremental NDJSON accepts split UTF8, CRLF and final unterminated line without leaking native payloads',()=>{
const {createDecoder}=events(),seen=[],decoder=createDecoder(e=>seen.push(e));
const text=[{type:'session',sessionId:'PRIVATE_SESSION',cwd:'C:/PRIVATE_PATH'},{type:'status',phase:'turn_start',sessionId:'PRIVATE_SESSION'},{type:'thinking',text:'PRIVATE_THINKING'},{type:'status',phase:'step_start',step:1,secret:'PRIVATE_STATUS'},{type:'text',text:'{"reply":"unvalidated"}'},{type:'status',phase:'turn_end',reason:{kind:'completed'}},{type:'final',text:'{"reply":"中文","actions":[]}'}].map(JSON.stringify).join('\r\n');
const bytes=Buffer.from(text);for(let i=0;i<bytes.length;i++)decoder.write(bytes.subarray(i,i+1));assert.equal(decoder.end(),'{"reply":"中文","actions":[]}');assert.deepEqual(seen.map(e=>e.data.phase),['turn_start','step_start','turn_end']);assert.doesNotMatch(JSON.stringify(seen),/PRIVATE_|unvalidated|中文/);
const test = require('node:test'),
assert = require('node:assert/strict');
const events = () => require('../../src/modules/assistant/dsh-events.cjs');
test('incremental NDJSON accepts split UTF8, CRLF and final unterminated line without leaking native payloads', () => {
const { createDecoder } = events(),
seen = [],
decoder = createDecoder((e) => seen.push(e));
const text = [
{ type: 'session', sessionId: 'PRIVATE_SESSION', cwd: 'C:/PRIVATE_PATH' },
{ type: 'status', phase: 'turn_start', sessionId: 'PRIVATE_SESSION' },
{ type: 'thinking', text: 'PRIVATE_THINKING' },
{ type: 'status', phase: 'step_start', step: 1, secret: 'PRIVATE_STATUS' },
{ type: 'text', text: '{"reply":"unvalidated"}' },
{ type: 'status', phase: 'turn_end', reason: { kind: 'completed' } },
{ type: 'final', text: '{"reply":"中文","actions":[]}' },
]
.map(JSON.stringify)
.join('\r\n');
const bytes = Buffer.from(text);
for (let i = 0; i < bytes.length; i++) decoder.write(bytes.subarray(i, i + 1));
assert.equal(decoder.end(), '{"reply":"中文","actions":[]}');
assert.deepEqual(
seen.map((e) => e.data.phase),
['turn_start', 'step_start', 'turn_end'],
);
assert.doesNotMatch(JSON.stringify(seen), /PRIVATE_|unvalidated|中文/);
});
test('native tools, unknown events, invalid statuses, duplicate final and incomplete results fail closed',()=>{
const {createDecoder}=events();for(const event of [{type:'tool_call',name:'shell'},{type:'tool_result',result:'private'},{type:'error',message:'PRIVATE_PROVIDER'},{type:'unknown'},{type:'status',phase:'new_phase'},{type:'status',phase:'turn_start',version:2}]){const decoder=createDecoder();assert.throws(()=>{decoder.write(Buffer.from(JSON.stringify(event)+'\n'));decoder.end();},e=>e.status===502&&!e.message.includes('PRIVATE_PROVIDER'));}
for(const output of ['{"type":"final","text":"partial"}','{"type":"final","reason":{"kind":"completed"},"text":"ok"}\n{"type":"final","reason":{"kind":"completed"},"text":"again"}','{"type":"status","phase":"turn_end","reason":{"kind":"cancelled"}}\n{"type":"final","reason":{"kind":"completed"},"text":"ok"}']){const decoder=createDecoder();assert.throws(()=>{decoder.write(Buffer.from(output));decoder.end();});}
const decoder=createDecoder();assert.throws(()=>decoder.write(Buffer.from('x'.repeat(1024*1024+1))),{status:502});
test('native tools, unknown events, invalid statuses, duplicate final and incomplete results fail closed', () => {
const { createDecoder } = events();
for (const event of [
{ type: 'tool_call', name: 'shell' },
{ type: 'tool_result', result: 'private' },
{ type: 'error', message: 'PRIVATE_PROVIDER' },
{ type: 'unknown' },
{ type: 'status', phase: 'new_phase' },
{ type: 'status', phase: 'turn_start', version: 2 },
]) {
const decoder = createDecoder();
assert.throws(
() => {
decoder.write(Buffer.from(JSON.stringify(event) + '\n'));
decoder.end();
},
(e) => e.status === 502 && !e.message.includes('PRIVATE_PROVIDER'),
);
}
for (const output of [
'{"type":"final","text":"partial"}',
'{"type":"final","reason":{"kind":"completed"},"text":"ok"}\n{"type":"final","reason":{"kind":"completed"},"text":"again"}',
'{"type":"status","phase":"turn_end","reason":{"kind":"cancelled"}}\n{"type":"final","reason":{"kind":"completed"},"text":"ok"}',
]) {
const decoder = createDecoder();
assert.throws(() => {
decoder.write(Buffer.from(output));
decoder.end();
});
}
const decoder = createDecoder();
assert.throws(() => decoder.write(Buffer.from('x'.repeat(1024 * 1024 + 1))), { status: 502 });
});
test('terminal turn_end only permits its final and never permits renewed model activity',()=>{
const {createDecoder}=events(),terminal={type:'status',phase:'turn_end',reason:{kind:'completed'}},final={type:'final',text:'checked'};
for(const later of [{type:'status',phase:'turn_start'},{type:'status',phase:'step_start',step:2},{type:'status',phase:'step_end',step:2},{type:'text',text:'unfinished response'},{type:'thinking',text:'unfinished reasoning'},{type:'session',sessionId:'later-session'}]){
const seen=[],decoder=createDecoder(event=>seen.push(event));decoder.write(Buffer.from(JSON.stringify(terminal)+'\n'));
assert.throws(()=>decoder.write(Buffer.from([later,final].map(JSON.stringify).join('\n')+'\n')),{status:502},later.type+':'+(later.phase||''));
assert.deepEqual(seen,[{kind:'model',data:{phase:'turn_end'}}]);
}
const completed=createDecoder();completed.write(Buffer.from([terminal,final].map(JSON.stringify).join('\n')+'\n'));
assert.throws(()=>completed.write(Buffer.from('{"type":"text","text":"extra response"}\n')),{status:502});
test('terminal turn_end only permits its final and never permits renewed model activity', () => {
const { createDecoder } = events(),
terminal = { type: 'status', phase: 'turn_end', reason: { kind: 'completed' } },
final = { type: 'final', text: 'checked' };
for (const later of [
{ type: 'status', phase: 'turn_start' },
{ type: 'status', phase: 'step_start', step: 2 },
{ type: 'status', phase: 'step_end', step: 2 },
{ type: 'text', text: 'unfinished response' },
{ type: 'thinking', text: 'unfinished reasoning' },
{ type: 'session', sessionId: 'later-session' },
]) {
const seen = [],
decoder = createDecoder((event) => seen.push(event));
decoder.write(Buffer.from(JSON.stringify(terminal) + '\n'));
assert.throws(
() => decoder.write(Buffer.from([later, final].map(JSON.stringify).join('\n') + '\n')),
{ status: 502 },
later.type + ':' + (later.phase || ''),
);
assert.deepEqual(seen, [{ kind: 'model', data: { phase: 'turn_end' } }]);
}
const completed = createDecoder();
completed.write(Buffer.from([terminal, final].map(JSON.stringify).join('\n') + '\n'));
assert.throws(() => completed.write(Buffer.from('{"type":"text","text":"extra response"}\n')), {
status: 502,
});
});
test('runtime publishes sanitized native status before child exit and rejects a forbidden tool immediately',async t=>{
const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),{invoke,environment}=require('../../src/modules/assistant/dsh-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-progress-'));
t.after(()=>fs.rm(dir,{recursive:true,force:true}));const file=path.join(dir,'child.cjs'),controller=new AbortController(),seen=[];
await fs.writeFile(file,"process.stdout.write(JSON.stringify({type:'status',phase:'step_start',step:1,path:'PRIVATE_PATH',text:'PRIVATE_JSON'})+'\\n');setInterval(()=>{},1000);");
await assert.rejects(invoke(file,[],{cwd:dir,env:environment(dir),ndjson:true,signal:controller.signal,timeout:3000,onEvent:event=>{seen.push(event);controller.abort();}}),{status:499});
assert.deepEqual(seen,[{kind:'model',data:{phase:'step_start',step:1}}]);
await fs.writeFile(file,"process.stdout.write(JSON.stringify({type:'tool_call',tool:'shell',input:'PRIVATE_ARGS'})+'\\n');setInterval(()=>{},1000);");
await assert.rejects(invoke(file,[],{cwd:dir,env:environment(dir),ndjson:true,timeout:3000}),error=>error.status===502&&!error.message.includes('PRIVATE_ARGS'));
test('runtime publishes sanitized native status before child exit and rejects a forbidden tool immediately', async (t) => {
const fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path'),
{ invoke, environment } = require('../../src/modules/assistant/dsh-runtime.cjs'),
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-progress-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const file = path.join(dir, 'child.cjs'),
controller = new AbortController(),
seen = [];
await fs.writeFile(
file,
"process.stdout.write(JSON.stringify({type:'status',phase:'step_start',step:1,path:'PRIVATE_PATH',text:'PRIVATE_JSON'})+'\\n');setInterval(()=>{},1000);",
);
await assert.rejects(
invoke(file, [], {
cwd: dir,
env: environment(dir),
ndjson: true,
signal: controller.signal,
timeout: 3000,
onEvent: (event) => {
seen.push(event);
controller.abort();
},
}),
{ status: 499 },
);
assert.deepEqual(seen, [{ kind: 'model', data: { phase: 'step_start', step: 1 } }]);
await fs.writeFile(
file,
"process.stdout.write(JSON.stringify({type:'tool_call',tool:'shell',input:'PRIVATE_ARGS'})+'\\n');setInterval(()=>{},1000);",
);
await assert.rejects(
invoke(file, [], { cwd: dir, env: environment(dir), ndjson: true, timeout: 3000 }),
(error) => error.status === 502 && !error.message.includes('PRIVATE_ARGS'),
);
});
+27 -5
View File
@@ -1,7 +1,29 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),path=require('node:path'),{spawnSync}=require('node:child_process');
test('DSH installer read-only check verifies the pinned installed runtime',t=>{
if(!require('../../src/modules/assistant/dsh-runtime.cjs').installedRuntime())return t.skip('Pinned DSH runtime is not installed');
const result=spawnSync(process.execPath,[path.resolve(__dirname,'../../scripts/install-dsh-runtime.cjs'),'--check'],{encoding:'utf8',windowsHide:true});assert.equal(result.status,0,result.stderr);const value=JSON.parse(result.stdout);assert.equal(value.version,'0.2.1-rc.2');assert.equal(value.package,'@deepseek-ai/dsh');assert.equal(value.available,true);assert.ok(value.runtimePath.endsWith(path.join('dsh','lib','bin.js')));
const test = require('node:test'),
assert = require('node:assert/strict'),
path = require('node:path'),
{ spawnSync } = require('node:child_process');
test('DSH installer read-only check verifies the pinned installed runtime', (t) => {
if (!require('../../src/modules/assistant/dsh-runtime.cjs').installedRuntime())
return t.skip('Pinned DSH runtime is not installed');
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, '../../scripts/install-dsh-runtime.cjs'), '--check'],
{ encoding: 'utf8', windowsHide: true },
);
assert.equal(result.status, 0, result.stderr);
const value = JSON.parse(result.stdout);
assert.equal(value.version, '0.2.1-rc.2');
assert.equal(value.package, '@deepseek-ai/dsh');
assert.equal(value.available, true);
assert.ok(value.runtimePath.endsWith(path.join('dsh', 'lib', 'bin.js')));
});
test('DSH installer rejects unknown options before installation', () => {
const result = spawnSync(
process.execPath,
[path.resolve(__dirname, '../../scripts/install-dsh-runtime.cjs'), '--unsafe'],
{ encoding: 'utf8', windowsHide: true },
);
assert.equal(result.status, 1);
assert.match(result.stderr, /Unsupported option/);
});
test('DSH installer rejects unknown options before installation',()=>{const result=spawnSync(process.execPath,[path.resolve(__dirname,'../../scripts/install-dsh-runtime.cjs'),'--unsafe'],{encoding:'utf8',windowsHide:true});assert.equal(result.status,1);assert.match(result.stderr,/Unsupported option/);});
+158 -33
View File
@@ -1,38 +1,163 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http');
const adapter=()=>require('../../src/modules/assistant/dsh-runtime.cjs');
test('NDJSON requires one successful final and never returns reasoning',()=>{
const {parseOutput}=adapter();
assert.equal(parseOutput('{"type":"thinking","text":"secret reasoning"}\n{"type":"status","phase":"turn_end","reason":{"kind":"completed"}}\n{"type":"final","text":"{\\"reply\\":\\"ok\\",\\"actions\\":[]}"}\n'),'{"reply":"ok","actions":[]}');
for(const value of ['garbage','{"type":"thinking","text":"private"}','{"type":"final","reason":"max_tokens","text":"partial"}','{"type":"error","message":"provider secret"}\n{"type":"final","reason":{"kind":"completed"},"text":"ok"}'])assert.throws(()=>parseOutput(value));
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path'),
http = require('node:http');
const adapter = () => require('../../src/modules/assistant/dsh-runtime.cjs');
test('NDJSON requires one successful final and never returns reasoning', () => {
const { parseOutput } = adapter();
assert.equal(
parseOutput(
'{"type":"thinking","text":"secret reasoning"}\n{"type":"status","phase":"turn_end","reason":{"kind":"completed"}}\n{"type":"final","text":"{\\"reply\\":\\"ok\\",\\"actions\\":[]}"}\n',
),
'{"reply":"ok","actions":[]}',
);
for (const value of [
'garbage',
'{"type":"thinking","text":"private"}',
'{"type":"final","reason":"max_tokens","text":"partial"}',
'{"type":"error","message":"provider secret"}\n{"type":"final","reason":{"kind":"completed"},"text":"ok"}',
])
assert.throws(() => parseOutput(value));
});
test('environment drops ambient secrets, proxy, node injection and DSH profile overrides',()=>{
const {environment}=adapter();process.env.NODE_OPTIONS='--inspect';process.env.DSH_SYSTEM_PROMPT='override';process.env.HTTP_PROXY='http://bad';
try{const env=environment('C:/isolated','key-only-child');assert.equal(env.NODE_OPTIONS,undefined);assert.equal(env.DSH_SYSTEM_PROMPT,undefined);assert.equal(env.HTTP_PROXY,undefined);assert.equal(env.DEEPSEEK_API_KEY,'key-only-child');assert.equal(env.DSH_HOME,path.join('C:/isolated','.dsh'));}finally{delete process.env.NODE_OPTIONS;delete process.env.DSH_SYSTEM_PROMPT;delete process.env.HTTP_PROXY;}
});
function sse(text){return [
{type:'message_start',message:{id:'local-test',type:'message',role:'assistant',model:'deepseek-flash',content:[],usage:{input_tokens:3,output_tokens:0}}},
{type:'content_block_start',index:0,content_block:{type:'text',text}},
{type:'content_block_stop',index:0},
{type:'message_delta',delta:{stop_reason:'end_turn'},usage:{output_tokens:5}},
{type:'message_stop'}].map(e=>`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join('');}
test('installed official DSH calls local Messages endpoint without native tools and cleans profile',{timeout:90000},async t=>{
const {DshRuntime,installedRuntime}=adapter();const entry=installedRuntime();if(!entry)return t.skip('Pinned DSH runtime is not installed');
const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-real-test-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
const requests=[];const server=http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{requests.push({url:req.url,headers:req.headers,body:JSON.parse(body)});res.writeHead(200,{'content-type':'text/event-stream'});res.end(sse('{"reply":"local model works","actions":[]}'));});});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
const runtime=new DshRuntime({stateDir:root});assert.equal((await runtime.probe(entry)).available,true);
const answer=await runtime.chat({config:{runtimePath:entry,apiBase:`http://127.0.0.1:${server.address().port}/anthropic`,apiKey:'local-test-secret',model:'deepseek-flash',timeoutSeconds:45,allowActions:false},text:'诊断',history:[],context:{status:'test'},signal:new AbortController().signal});
assert.equal(JSON.parse(answer).reply,'local model works');assert.equal(requests.length,1);assert.equal(requests[0].url,'/anthropic/v1/messages');assert.deepEqual(requests[0].body.tools??[],[]);assert.equal(requests[0].headers['x-api-key'],'local-test-secret');assert.deepEqual(await fs.readdir(runtime.runs),[]);
test('environment drops ambient secrets, proxy, node injection and DSH profile overrides', () => {
const { environment } = adapter();
process.env.NODE_OPTIONS = '--inspect';
process.env.DSH_SYSTEM_PROMPT = 'override';
process.env.HTTP_PROXY = 'http://bad';
try {
const env = environment('C:/isolated', 'key-only-child');
assert.equal(env.NODE_OPTIONS, undefined);
assert.equal(env.DSH_SYSTEM_PROMPT, undefined);
assert.equal(env.HTTP_PROXY, undefined);
assert.equal(env.DEEPSEEK_API_KEY, 'key-only-child');
assert.equal(env.DSH_HOME, path.join('C:/isolated', '.dsh'));
} finally {
delete process.env.NODE_OPTIONS;
delete process.env.DSH_SYSTEM_PROMPT;
delete process.env.HTTP_PROXY;
}
});
function sse(text) {
return [
{
type: 'message_start',
message: {
id: 'local-test',
type: 'message',
role: 'assistant',
model: 'deepseek-flash',
content: [],
usage: { input_tokens: 3, output_tokens: 0 },
},
},
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 5 } },
{ type: 'message_stop' },
]
.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`)
.join('');
}
test(
'installed official DSH calls local Messages endpoint without native tools and cleans profile',
{ timeout: 90000 },
async (t) => {
const { DshRuntime, installedRuntime } = adapter();
const entry = installedRuntime();
if (!entry) return t.skip('Pinned DSH runtime is not installed');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-real-test-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const requests = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
requests.push({ url: req.url, headers: req.headers, body: JSON.parse(body) });
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.end(sse('{"reply":"local model works","actions":[]}'));
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => server.close(r)));
const runtime = new DshRuntime({ stateDir: root });
assert.equal((await runtime.probe(entry)).available, true);
const answer = await runtime.chat({
config: {
runtimePath: entry,
apiBase: `http://127.0.0.1:${server.address().port}/anthropic`,
apiKey: 'local-test-secret',
model: 'deepseek-flash',
timeoutSeconds: 45,
allowActions: false,
},
text: '诊断',
history: [],
context: { status: 'test' },
signal: new AbortController().signal,
});
assert.equal(JSON.parse(answer).reply, 'local model works');
assert.equal(requests.length, 1);
assert.equal(requests[0].url, '/anthropic/v1/messages');
assert.deepEqual(requests[0].body.tools ?? [], []);
assert.equal(requests[0].headers['x-api-key'], 'local-test-secret');
assert.deepEqual(await fs.readdir(runtime.runs), []);
},
);
test('timeout terminates the Windows descendant tree and bounds output and cancellation',{timeout:20000},async t=>{
const {invoke,environment}=adapter();const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-child-test-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
const childFile=path.join(root,'child.cjs');await fs.writeFile(childFile,"const fs=require('fs'),{spawn}=require('child_process');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore',windowsHide:true});fs.writeFileSync('pid',String(child.pid));setInterval(()=>{},1000);");
await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),timeout:800}),e=>e.status===504);const pid=Number(await fs.readFile(path.join(root,'pid'),'utf8'));assert.throws(()=>process.kill(pid,0));
await fs.writeFile(childFile,"process.stdout.write('x'.repeat(2048));setInterval(()=>{},1000)");await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),maxBytes:1024,timeout:3000}),e=>e.status===502);
const controller=new AbortController();controller.abort();await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),signal:controller.signal}),e=>e.status===499);
});
test('profile never persists the model key and only approved repair content is included',()=>{
const {profilePatch,prompt}=adapter(),config={apiBase:'https://example.com/anthropic',model:'deepseek-flash',apiKey:'sensitive-key',timeoutSeconds:30,allowActions:false};assert.ok(!profilePatch(config).includes('sensitive-key'));
const content='x'.repeat(4000);const text=prompt({config,text:'review',history:[],context:{repair:{files:[{path:'src/test.cjs',content}]}}});assert.ok(text.includes(content));assert.ok(text.includes('repair:{files:'));
test(
'timeout terminates the Windows descendant tree and bounds output and cancellation',
{ timeout: 20000 },
async (t) => {
const { invoke, environment } = adapter();
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-child-test-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const childFile = path.join(root, 'child.cjs');
await fs.writeFile(
childFile,
"const fs=require('fs'),{spawn}=require('child_process');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore',windowsHide:true});fs.writeFileSync('pid',String(child.pid));setInterval(()=>{},1000);",
);
await assert.rejects(
invoke(childFile, [], { cwd: root, env: environment(root), timeout: 800 }),
(e) => e.status === 504,
);
const pid = Number(await fs.readFile(path.join(root, 'pid'), 'utf8'));
assert.throws(() => process.kill(pid, 0));
await fs.writeFile(
childFile,
"process.stdout.write('x'.repeat(2048));setInterval(()=>{},1000)",
);
await assert.rejects(
invoke(childFile, [], { cwd: root, env: environment(root), maxBytes: 1024, timeout: 3000 }),
(e) => e.status === 502,
);
const controller = new AbortController();
controller.abort();
await assert.rejects(
invoke(childFile, [], { cwd: root, env: environment(root), signal: controller.signal }),
(e) => e.status === 499,
);
},
);
test('profile never persists the model key and only approved repair content is included', () => {
const { profilePatch, prompt } = adapter(),
config = {
apiBase: 'https://example.com/anthropic',
model: 'deepseek-flash',
apiKey: 'sensitive-key',
timeoutSeconds: 30,
allowActions: false,
};
assert.ok(!profilePatch(config).includes('sensitive-key'));
const content = 'x'.repeat(4000);
const text = prompt({
config,
text: 'review',
history: [],
context: { repair: { files: [{ path: 'src/test.cjs', content }] } },
});
assert.ok(text.includes(content));
assert.ok(text.includes('repair:{files:'));
});
+296 -23
View File
@@ -1,31 +1,304 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');
const source=fs.readFileSync('web/modules/assistant/events-client.js','utf8');
const settle=async()=>{for(let i=0;i<15;i++)await Promise.resolve();};
test('event transport falls back after stream failures, resumes by cursor and never posts messages',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0,changes=0;const accepted=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{fetches++;throw new TypeError('disconnected');}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async route=>{assert.match(route,/\/events\?after=0$/);polls++;return {events:[{conversationId:'own',seq:1,kind:'completed'}],nextCursor:1,hasMore:false};},onEvents:rows=>accepted.push(...rows),onChange:async()=>{changes++;}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(fetches,3);assert.equal(polls,1);assert.equal(client.cursor,1);assert.equal(changes,1);assert.equal(accepted.length,1);client.dispose();t.mock.timers.tick(120000);await settle();assert.equal(polls,1);
const { test } = require('node:test'),
assert = require('node:assert/strict'),
vm = require('node:vm'),
fs = require('node:fs');
const source = fs.readFileSync(
require('node:path').resolve(__dirname, '../../web/modules/assistant/events-client.js'),
'utf8',
);
const settle = async () => {
for (let i = 0; i < 15; i++) await Promise.resolve();
};
test('event transport falls back after stream failures, resumes by cursor and never posts messages', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let fetches = 0,
polls = 0,
changes = 0;
const accepted = [],
scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async () => {
fetches++;
throw new TypeError('disconnected');
},
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
api: async (route) => {
assert.match(route, /\/events\?after=0$/);
polls++;
return {
events: [{ conversationId: 'own', seq: 1, kind: 'completed' }],
nextCursor: 1,
hasMore: false,
};
},
onEvents: (rows) => accepted.push(...rows),
onChange: async () => {
changes++;
},
});
await settle();
t.mock.timers.tick(1000);
await settle();
t.mock.timers.tick(2000);
await settle();
assert.equal(fetches, 3);
assert.equal(polls, 1);
assert.equal(client.cursor, 1);
assert.equal(changes, 1);
assert.equal(accepted.length, 1);
client.dispose();
t.mock.timers.tick(120000);
await settle();
assert.equal(polls, 1);
});
test('event transport treats login failure as terminal instead of reconnecting forever',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let failures=0,requests=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{requests++;return new Response('{}',{status:401});}};vm.runInNewContext(source,scope);scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('no fallback after auth failure'),onEvents:()=>assert.fail('no data'),onChange:async()=>{},onAuth:error=>{assert.equal(error.status,401);failures++;}});await settle();t.mock.timers.tick(60000);await settle();assert.equal(failures,1);assert.equal(requests,1);
test('event transport treats login failure as terminal instead of reconnecting forever', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let failures = 0,
requests = 0;
const scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async () => {
requests++;
return new Response('{}', { status: 401 });
},
};
vm.runInNewContext(source, scope);
scope.window.AssistantEvents.connect({
id: 'own',
api: async () => assert.fail('no fallback after auth failure'),
onEvents: () => assert.fail('no data'),
onChange: async () => {},
onAuth: (error) => {
assert.equal(error.status, 401);
failures++;
},
});
await settle();
t.mock.timers.tick(60000);
await settle();
assert.equal(failures, 1);
assert.equal(requests, 1);
});
test('SSE parsing tolerates chunk boundaries and ignores replayed sequence IDs',async()=>{
const received=[];let controller,changed=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>new Response(new ReadableStream({start(c){controller=c;options.signal.addEventListener('abort',()=>c.close(),{once:true});}}),{headers:{'Content-Type':'text/event-stream'}})};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',cursor:1,api:async()=>assert.fail('no polling on a healthy stream'),onEvents:rows=>received.push(...rows),onChange:async()=>{changed++;}});await settle();const encoder=new TextEncoder(),frame=seq=>'event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq,kind:'completed'})+'\n\n';controller.enqueue(encoder.encode(frame(1)+frame(2).slice(0,20)));controller.enqueue(encoder.encode(frame(2).slice(20)));await settle();assert.equal(received.length,1);assert.equal(received[0].seq,2);assert.equal(changed,1);client.dispose();
test('SSE parsing tolerates chunk boundaries and ignores replayed sequence IDs', async () => {
const received = [];
let controller,
changed = 0;
const scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async (_url, options) =>
new Response(
new ReadableStream({
start(c) {
controller = c;
options.signal.addEventListener('abort', () => c.close(), { once: true });
},
}),
{ headers: { 'Content-Type': 'text/event-stream' } },
),
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
cursor: 1,
api: async () => assert.fail('no polling on a healthy stream'),
onEvents: (rows) => received.push(...rows),
onChange: async () => {
changed++;
},
});
await settle();
const encoder = new TextEncoder(),
frame = (seq) =>
'event: assistant_event\ndata: ' +
JSON.stringify({ conversationId: 'own', seq, kind: 'completed' }) +
'\n\n';
controller.enqueue(encoder.encode(frame(1) + frame(2).slice(0, 20)));
controller.enqueue(encoder.encode(frame(2).slice(20)));
await settle();
assert.equal(received.length, 1);
assert.equal(received[0].seq, 2);
assert.equal(changed, 1);
client.dispose();
});
test('a failed authoritative reload does not acknowledge the final event before recovery',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let streamCount=0,reloads=0;const cursors=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async url=>{cursors.push(url);streamCount++;return new Response(new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq:1,kind:'completed'})+'\n\n'));}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{reloads++;if(reloads===1)throw Error('temporary GET failure');}});await settle();assert.equal(client.cursor,0);t.mock.timers.tick(1000);await settle();assert.equal(streamCount,2);assert.match(cursors[1],/after=0$/);assert.equal(client.cursor,1);client.dispose();
test('a failed authoritative reload does not acknowledge the final event before recovery', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let streamCount = 0,
reloads = 0;
const cursors = [],
scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async (url) => {
cursors.push(url);
streamCount++;
return new Response(
new ReadableStream({
start(c) {
c.enqueue(
new TextEncoder().encode(
'event: assistant_event\ndata: ' +
JSON.stringify({ conversationId: 'own', seq: 1, kind: 'completed' }) +
'\n\n',
),
);
},
}),
{ headers: { 'Content-Type': 'text/event-stream' } },
);
},
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
api: async () => assert.fail('not polling yet'),
onEvents: () => {},
onChange: async () => {
reloads++;
if (reloads === 1) throw Error('temporary GET failure');
},
});
await settle();
assert.equal(client.cursor, 0);
t.mock.timers.tick(1000);
await settle();
assert.equal(streamCount, 2);
assert.match(cursors[1], /after=0$/);
assert.equal(client.cursor, 1);
client.dispose();
});
test('a failed SSE probe does not start a second outstanding polling loop',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{throw Error('offline');}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return await new Promise(resolve=>releases.push(()=>resolve({events:[],nextCursor:0,hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle();
test('a failed SSE probe does not start a second outstanding polling loop', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let polls = 0;
const releases = [],
scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async () => {
throw Error('offline');
},
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
api: async () => {
polls++;
return await new Promise((resolve) =>
releases.push(() => resolve({ events: [], nextCursor: 0, hasMore: false })),
);
},
onEvents: () => {},
onChange: async () => {},
});
await settle();
t.mock.timers.tick(1000);
await settle();
t.mock.timers.tick(2000);
await settle();
assert.equal(polls, 1);
t.mock.timers.tick(60000);
await settle();
assert.equal(polls, 1);
client.dispose();
for (const release of releases) release();
await settle();
});
test('stream negotiation is bounded even when the proxy never returns headers',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let signal;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>{signal=options.signal;return await new Promise((_resolve,reject)=>signal.addEventListener('abort',()=>reject(Error('connection timed out')),{once:true}));}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(45000);await settle();assert.equal(signal.aborted,true);client.dispose();
test('stream negotiation is bounded even when the proxy never returns headers', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let signal;
const scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async (_url, options) => {
signal = options.signal;
return await new Promise((_resolve, reject) =>
signal.addEventListener('abort', () => reject(Error('connection timed out')), {
once: true,
}),
);
},
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
api: async () => assert.fail('not polling yet'),
onEvents: () => {},
onChange: async () => {},
});
await settle();
t.mock.timers.tick(45000);
await settle();
assert.equal(signal.aborted, true);
client.dispose();
});
test('a probe that connects then ends cannot overlap the pending polling owner',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{if(++fetches<=3)throw Error('offline');return new Response(new ReadableStream({start(c){c.close();}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return new Promise(resolve=>releases.push(()=>resolve({events:[],hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(fetches,4);assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle();
test('a probe that connects then ends cannot overlap the pending polling owner', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
let fetches = 0,
polls = 0;
const releases = [],
scope = {
window: {},
setTimeout,
clearTimeout,
AbortController,
TextDecoder,
fetch: async () => {
if (++fetches <= 3) throw Error('offline');
return new Response(
new ReadableStream({
start(c) {
c.close();
},
}),
{ headers: { 'Content-Type': 'text/event-stream' } },
);
},
};
vm.runInNewContext(source, scope);
const client = scope.window.AssistantEvents.connect({
id: 'own',
api: async () => {
polls++;
return new Promise((resolve) => releases.push(() => resolve({ events: [], hasMore: false })));
},
onEvents: () => {},
onChange: async () => {},
});
await settle();
t.mock.timers.tick(1000);
await settle();
t.mock.timers.tick(2000);
await settle();
assert.equal(polls, 1);
t.mock.timers.tick(60000);
await settle();
assert.equal(fetches, 4);
assert.equal(polls, 1);
client.dispose();
for (const release of releases) release();
await settle();
});
+223 -48
View File
@@ -1,57 +1,232 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const principal={user:{id:'admin',username:'admin',role:'admin'},sessionId:'test-session'};
function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'field-skill-')),store=new RuleStore(dir,{clock:()=>new Date('2026-10-20T02:00:00Z')});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
const row={source:'todo',instanceId:'1',taskId:'1',revision:'1',processName:'备损订单评审',processVersion:'2.0',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-01T02:00:00Z',title:'订单号:123机芯号:ABC客户简称:PRIVATE_CUSTOMER总数量:0',serialNum:'TEST'};
let captures=0;const provider={scan:async()=>[row,{...row,taskId:'2',instanceId:'2'}],captureFields:async(c,p,r)=>{captures++;return {sample:{...r,connectionId:c.id,fields:{'Order.Number':'123','Order.Quantity':'0','Order.Amount':'999'}},snapshot:{purpose:'field-mapping',processVersion:r.processVersion,fields:[{path:'Order.Number',label:'订单号',value:'123'},{path:'Order.Quantity',label:'数量',value:'0'},{path:'Order.Amount',label:'总金额',value:'999'}]}};}};
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive:{},mail:{},clock:()=>new Date('2026-10-20T02:00:00Z')});
return {deps:{workspace,orderRules:store,orderExecution:execution},store,connection,captures:()=>captures};
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { RuleStore } = require('../../src/modules/order-rules/store.cjs');
const { OrderExecutionCoordinator } = require('../../src/modules/order-execution/coordinator.cjs');
const principal = {
user: { id: 'admin', username: 'admin', role: 'admin' },
sessionId: 'test-session',
};
function fixture(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'field-skill-')),
store = new RuleStore(dir, { clock: () => new Date('2026-10-20T02:00:00Z') });
t.after(() => {
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
const connection = { id: 'c1', owner: 'admin', status: 'connected' },
workspace = {
getConnection: () => connection,
snapshot: () => ({ connections: [connection] }),
};
const row = {
source: 'todo',
instanceId: '1',
taskId: '1',
revision: '1',
processName: '备损订单评审',
processVersion: '2.0',
nodeName: '订单专员(订单通知书)',
receivedAt: '2026-10-01T02:00:00Z',
title: '订单号:123机芯号:ABC客户简称:PRIVATE_CUSTOMER总数量:0',
serialNum: 'TEST',
};
let captures = 0;
const provider = {
scan: async () => [row, { ...row, taskId: '2', instanceId: '2' }],
captureFields: async (c, p, r) => {
captures++;
return {
sample: {
...r,
connectionId: c.id,
fields: { 'Order.Number': '123', 'Order.Quantity': '0', 'Order.Amount': '999' },
},
snapshot: {
purpose: 'field-mapping',
processVersion: r.processVersion,
fields: [
{ path: 'Order.Number', label: '订单号', value: '123' },
{ path: 'Order.Quantity', label: '数量', value: '0' },
{ path: 'Order.Amount', label: '总金额', value: '999' },
],
},
};
},
};
const execution = new OrderExecutionCoordinator({
store,
workspace,
provider,
archive: {},
mail: {},
clock: () => new Date('2026-10-20T02:00:00Z'),
});
return {
deps: { workspace, orderRules: store, orderExecution: execution },
store,
connection,
captures: () => captures,
};
}
test('ZCode project skill collects one sample per missing version and only prepares checked drafts',async t=>{
const skill=require('../../src/modules/assistant/field-skill.cjs'),f=fixture(t),progress=[];
const report=await skill.collect(f.deps,'c1',principal,'action1',p=>progress.push(p));
assert.equal(report.captured,1);assert.equal(f.captures(),1);assert.equal(progress.at(-1).completed,1);
const sample=f.store.all('capture-samples')[0],guard=skill.guardMapping(f.deps,sample.id,principal.user);
const result=await skill.prepare(f.deps,sample.id,principal,'prepare1',guard);
assert.equal(result.status,'checked');assert.equal(f.store.all('field-mapping-drafts').length,1);
assert.equal(f.store.all('field-adapters').length,0);assert.deepEqual(f.store.all('orders'),[]);assert.deepEqual(f.store.all('batches'),[]);
const context=skill.coverage(f.deps,principal.user);assert.deepEqual(context.samples,[{id:sample.id,connectionId:'c1',processName:sample.processName,version:sample.processVersion}]);
// Opaque sample hashes may contain "999"; inspect the permitted metadata,
// whose exact sample shape above also excludes raw fields and evidence.
assert.doesNotMatch(JSON.stringify(context,(key,value)=>key==='id'?undefined:value),/PRIVATE_CUSTOMER|Order\.Number|999|订单号:123/);
assert.equal((await skill.collect(f.deps,'c1',principal,'action2',()=>{})).captured,0);assert.equal(f.captures(),1);
await assert.rejects(skill.prepare(f.deps,sample.id,principal,'stale',guard),e=>e.status===409);
f.connection.status='disabled';assert.throws(()=>skill.guardMapping(f.deps,sample.id,principal.user),e=>e.status===403);
test('ZCode project skill collects one sample per missing version and only prepares checked drafts', async (t) => {
const skill = require('../../src/modules/assistant/field-skill.cjs'),
f = fixture(t),
progress = [];
const report = await skill.collect(f.deps, 'c1', principal, 'action1', (p) => progress.push(p));
assert.equal(report.captured, 1);
assert.equal(f.captures(), 1);
assert.equal(progress.at(-1).completed, 1);
const sample = f.store.all('capture-samples')[0],
guard = skill.guardMapping(f.deps, sample.id, principal.user);
const result = await skill.prepare(f.deps, sample.id, principal, 'prepare1', guard);
assert.equal(result.status, 'checked');
assert.equal(f.store.all('field-mapping-drafts').length, 1);
assert.equal(f.store.all('field-adapters').length, 0);
assert.deepEqual(f.store.all('orders'), []);
assert.deepEqual(f.store.all('batches'), []);
const context = skill.coverage(f.deps, principal.user);
assert.deepEqual(context.samples, [
{
id: sample.id,
connectionId: 'c1',
processName: sample.processName,
version: sample.processVersion,
},
]);
// Opaque sample hashes may contain "999"; inspect the permitted metadata,
// whose exact sample shape above also excludes raw fields and evidence.
assert.doesNotMatch(
JSON.stringify(context, (key, value) => (key === 'id' ? undefined : value)),
/PRIVATE_CUSTOMER|Order\.Number|999|订单号:123/,
);
assert.equal((await skill.collect(f.deps, 'c1', principal, 'action2', () => {})).captured, 0);
assert.equal(f.captures(), 1);
await assert.rejects(
skill.prepare(f.deps, sample.id, principal, 'stale', guard),
(e) => e.status === 409,
);
f.connection.status = 'disabled';
assert.throws(
() => skill.guardMapping(f.deps, sample.id, principal.user),
(e) => e.status === 403,
);
});
test('mapping recommendations keep ambiguous fields unresolved and never mix amount and quantity',()=>{
const {recommend}=require('../../src/modules/assistant/field-skill.cjs');
const r=recommend([{path:'A.Order',label:'订单号',value:'123'},{path:'B.Order',label:'订单号',value:'123'},{path:'Amount',label:'总金额',value:'10'},{path:'Qty',label:'数量',value:'0'}]);
assert.equal(r.sources.orderNo,undefined);assert.equal(r.sources.quantity.path,'Qty');assert.equal(r.sources.totalAmount.path,'Amount');assert.ok(r.issues.length);
assert.equal(recommend([{path:'ProductRequirement.Antennanum',label:'数量',value:'2'}]).sources.quantity,undefined);
test('mapping recommendations keep ambiguous fields unresolved and never mix amount and quantity', () => {
const { recommend } = require('../../src/modules/assistant/field-skill.cjs');
const r = recommend([
{ path: 'A.Order', label: '订单号', value: '123' },
{ path: 'B.Order', label: '订单号', value: '123' },
{ path: 'Amount', label: '总金额', value: '10' },
{ path: 'Qty', label: '数量', value: '0' },
]);
assert.equal(r.sources.orderNo, undefined);
assert.equal(r.sources.quantity.path, 'Qty');
assert.equal(r.sources.totalAmount.path, 'Amount');
assert.ok(r.issues.length);
assert.equal(
recommend([{ path: 'ProductRequirement.Antennanum', label: '数量', value: '2' }]).sources
.quantity,
undefined,
);
});
test('application skill is versioned, injected into prompt and cannot enable native tools',()=>{
const {projectSkills}=require('../../src/modules/assistant/skills.cjs'),{prompt,runtimeConfig}=require('../../src/modules/assistant/zcode-runtime.cjs');
const skills=projectSkills();assert.equal(skills[0].id,'bpm-field-mapping');assert.match(skills[0].sha256,/^[a-f0-9]{64}$/);
const input=prompt({text:'采集字段样本',history:[],context:{},config:{allowActions:true}});
assert.match(input,/BPM 信息识别技能/);assert.match(input,/collect_field_samples/);assert.match(input,/HA/);
const config=runtimeConfig({timeoutSeconds:30},'test');assert.equal(config.features.skill,false);assert.ok(config.permission.disallowedTools.includes('Skill'));
test('application skill is versioned, injected into prompt and cannot enable native tools', () => {
const { projectSkills } = require('../../src/modules/assistant/skills.cjs'),
{ prompt, runtimeConfig } = require('../../src/modules/assistant/zcode-runtime.cjs');
const skills = projectSkills();
assert.equal(skills[0].id, 'bpm-field-mapping');
assert.match(skills[0].sha256, /^[a-f0-9]{64}$/);
const input = prompt({
text: '采集字段样本',
history: [],
context: {},
config: { allowActions: true },
});
assert.match(input, /BPM 信息识别技能/);
assert.match(input, /collect_field_samples/);
assert.match(input, /HA/);
const config = runtimeConfig({ timeoutSeconds: 30 }, 'test');
assert.equal(config.features.skill, false);
assert.ok(config.permission.disallowedTools.includes('Skill'));
});
test('historical evidence can check a mapping while real notification matching still rejects history',async t=>{
const f=fixture(t),{recommend}=require('../../src/modules/assistant/field-skill.cjs'),row={source:'history',configurationOnly:true,instanceId:'1',taskId:'1',revision:0,connectionId:'c1',processName:'备损订单评审',processVersion:'2.0',nodeName:'历史查看(未提供办理节点)',receivedAt:'2026-10-01T00:00:00Z',timestampType:'process-start',serialNum:'TEST',title:'订单号:123机芯号:ABC',fields:{order:'123'}},snapshot={purpose:'field-mapping',processVersion:'2.0',fields:[{path:'order',label:'订单号',value:'123'}]};
const sample=f.store.recordCapture({sample:row,snapshot,taskId:'h1'}),draft=f.store.saveMapping({processName:row.processName,processVersion:row.processVersion,sampleId:sample.id,sources:recommend(snapshot.fields).sources,version:0,idempotencyKey:'draft'},principal.user);
const result=f.store.checkMapping({id:draft.id,version:draft.version,sampleId:sample.id,idempotencyKey:'check'},principal.user);
assert.equal(result.valid,true);assert.equal(result.result.configurationOnly,true);assert.ok(result.result.warnings.length);
assert.equal(f.store.capturedPreview(sample.id).valid,false);
test('historical evidence can check a mapping while real notification matching still rejects history', async (t) => {
const f = fixture(t),
{ recommend } = require('../../src/modules/assistant/field-skill.cjs'),
row = {
source: 'history',
configurationOnly: true,
instanceId: '1',
taskId: '1',
revision: 0,
connectionId: 'c1',
processName: '备损订单评审',
processVersion: '2.0',
nodeName: '历史查看(未提供办理节点)',
receivedAt: '2026-10-01T00:00:00Z',
timestampType: 'process-start',
serialNum: 'TEST',
title: '订单号:123机芯号:ABC',
fields: { order: '123' },
},
snapshot = {
purpose: 'field-mapping',
processVersion: '2.0',
fields: [{ path: 'order', label: '订单号', value: '123' }],
};
const sample = f.store.recordCapture({ sample: row, snapshot, taskId: 'h1' }),
draft = f.store.saveMapping(
{
processName: row.processName,
processVersion: row.processVersion,
sampleId: sample.id,
sources: recommend(snapshot.fields).sources,
version: 0,
idempotencyKey: 'draft',
},
principal.user,
);
const result = f.store.checkMapping(
{ id: draft.id, version: draft.version, sampleId: sample.id, idempotencyKey: 'check' },
principal.user,
);
assert.equal(result.valid, true);
assert.equal(result.result.configurationOnly, true);
assert.ok(result.result.warnings.length);
assert.equal(f.store.capturedPreview(sample.id).valid, false);
});
test('assistant prepares the same active-only selection as page preview and never activates or publishes it',async t=>{
const f=fixture(t),skill=require('../../src/modules/assistant/field-skill.cjs');await skill.collect(f.deps,'c1',principal,'collect-consistent',()=>{});const sample=f.store.all('capture-samples')[0];
f.store.put('field-adapters',{id:'legacy-selected',processName:sample.processName,processVersion:sample.processVersion,verified:true,version:2,sources:{orderNo:{type:'form',path:'Order.Number'},brief:{type:'title'}}});
const proposal=f.store.proposeMapping({sampleId:sample.id}),before=f.store.all('rules');assert.equal(proposal.mapping.basis,'active');assert.equal(proposal.mapping.sources.quantity,undefined);
const result=await skill.prepare(f.deps,sample.id,principal,'prepare-consistent',skill.guardMapping(f.deps,sample.id,principal.user));assert.equal(result.status,'checked');const draft=f.store.all('field-mapping-drafts')[0];assert.equal(draft.sources.quantity,undefined);assert.deepEqual(f.store.all('rules'),before);assert.equal(f.store.all('field-adapters').length,1);assert.equal(f.store.settings().enabled,false);
test('assistant prepares the same active-only selection as page preview and never activates or publishes it', async (t) => {
const f = fixture(t),
skill = require('../../src/modules/assistant/field-skill.cjs');
await skill.collect(f.deps, 'c1', principal, 'collect-consistent', () => {});
const sample = f.store.all('capture-samples')[0];
f.store.put('field-adapters', {
id: 'legacy-selected',
processName: sample.processName,
processVersion: sample.processVersion,
verified: true,
version: 2,
sources: { orderNo: { type: 'form', path: 'Order.Number' }, brief: { type: 'title' } },
});
const proposal = f.store.proposeMapping({ sampleId: sample.id }),
before = f.store.all('rules');
assert.equal(proposal.mapping.basis, 'active');
assert.equal(proposal.mapping.sources.quantity, undefined);
const result = await skill.prepare(
f.deps,
sample.id,
principal,
'prepare-consistent',
skill.guardMapping(f.deps, sample.id, principal.user),
);
assert.equal(result.status, 'checked');
const draft = f.store.all('field-mapping-drafts')[0];
assert.equal(draft.sources.quantity, undefined);
assert.deepEqual(f.store.all('rules'), before);
assert.equal(f.store.all('field-adapters').length, 1);
assert.equal(f.store.settings().enabled, false);
});
+71 -10
View File
@@ -1,12 +1,73 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {BpmHistoryClient,normalizeHistory,HISTORY_ROUTES}=require('../../src/modules/bpm/history-client.cjs');
const raw=(version='1.4',id='21')=>({processName:'备损订单更改评审',processInstanceId:id,processVersion:version,startTime:'2026-10-20T10:00:00',serialNum:'TEST',subject:'订单号:123',businessKey:'https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent('https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid='+id)+'&todo_token=FIXTURE&todo_account=test'});
test('history client queries only observed readonly sources and keeps latest version alternatives',async()=>{
const calls=[];let disposed=false;
const client=new BpmHistoryClient({requestFactory:async()=>({get:async(route,options)=>{calls.push({route,options});return {status:()=>200,body:async()=>Buffer.from(route==='/'?"Yiez.clientId='fixture';":JSON.stringify({total:4,children:[raw(),raw('1.3','22'),raw('1.4','23'),{...raw('1.5','24'),processName:'其他流程'}]}))};},dispose:async()=>{disposed=true;}})});
const rows=await client.scan({},['备损订单更改评审']);assert.equal(rows.length,2);assert.equal(rows[0].source,'history');assert.equal(rows[0].configurationOnly,true);assert.equal(rows[0].timestampType,'process-start');assert.match(rows[0].nodeName,/未提供/);assert.equal(rows[0].receivedAt,'2026-10-20T02:00:00.000Z');
assert.deepEqual(calls.map(c=>c.route),['/',HISTORY_ROUTES[0]]);assert.equal(calls[1].options.params.year,-1);assert.equal(calls[1].options.params.limit,100);assert.equal(disposed,true);
assert.throws(()=>normalizeHistory({...raw(),processInstanceId:'22'}),e=>e.status===403);
assert.throws(()=>normalizeHistory({...raw(),processVersion:''}),e=>e.status===502);
const test = require('node:test'),
assert = require('node:assert/strict');
const {
BpmHistoryClient,
normalizeHistory,
HISTORY_ROUTES,
} = require('../../src/modules/bpm/history-client.cjs');
const raw = (version = '1.4', id = '21') => ({
processName: '备损订单更改评审',
processInstanceId: id,
processVersion: version,
startTime: '2026-10-20T10:00:00',
serialNum: 'TEST',
subject: '订单号:123',
businessKey:
'https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl=' +
encodeURIComponent('https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid=' + id) +
'&todo_token=FIXTURE&todo_account=test',
});
test('history client queries only observed readonly sources and keeps latest version alternatives', async () => {
const calls = [];
let disposed = false;
const client = new BpmHistoryClient({
requestFactory: async () => ({
get: async (route, options) => {
calls.push({ route, options });
return {
status: () => 200,
body: async () =>
Buffer.from(
route === '/'
? "Yiez.clientId='fixture';"
: JSON.stringify({
total: 4,
children: [
raw(),
raw('1.3', '22'),
raw('1.4', '23'),
{ ...raw('1.5', '24'), processName: '其他流程' },
],
}),
),
};
},
dispose: async () => {
disposed = true;
},
}),
});
const rows = await client.scan({}, ['备损订单更改评审']);
assert.equal(rows.length, 2);
assert.equal(rows[0].source, 'history');
assert.equal(rows[0].configurationOnly, true);
assert.equal(rows[0].timestampType, 'process-start');
assert.match(rows[0].nodeName, /未提供/);
assert.equal(rows[0].receivedAt, '2026-10-20T02:00:00.000Z');
assert.deepEqual(
calls.map((c) => c.route),
['/', HISTORY_ROUTES[0]],
);
assert.equal(calls[1].options.params.year, -1);
assert.equal(calls[1].options.params.limit, 100);
assert.equal(disposed, true);
assert.throws(
() => normalizeHistory({ ...raw(), processInstanceId: '22' }),
(e) => e.status === 403,
);
assert.throws(
() => normalizeHistory({ ...raw(), processVersion: '' }),
(e) => e.status === 502,
);
});
@@ -0,0 +1,26 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ createCanvas } = require('@napi-rs/canvas');
const { parse } = require('../../src/modules/assistant/attachments.cjs');
test(
'image attachment validates pixels and type and remains image data rather than text',
{ timeout: 15000 },
async () => {
const canvas = createCanvas(40, 20);
canvas.getContext('2d').fillRect(0, 0, 40, 20);
const bytes = canvas.toBuffer('image/png'),
file = await parse({ name: 'evidence.png', data: bytes.toString('base64') });
assert.equal(file.kind, 'image');
assert.equal(file.mediaType, 'image/png');
assert.equal(file.width, 40);
assert.ok(file.imageData.length);
assert.equal(file.characters, 0);
await assert.rejects(
parse({ name: 'fake.png', data: Buffer.from('fake image').toString('base64') }),
);
const huge = Buffer.from(bytes);
huge.writeUInt32BE(100000, 16);
await assert.rejects(parse({ name: 'huge.png', data: huge.toString('base64') }));
},
);
+87
View File
@@ -0,0 +1,87 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ createCanvas } = require('@napi-rs/canvas');
const { managementFixture } = require('./management-fixture.cjs');
test(
'image send requires selected model support, keeps binary out of transcripts and preserves private follow-up',
{ timeout: 120000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
{ store, assistant } = f,
admin = await f.login(),
viewer = await f.login('viewer');
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_IMAGE_KEY',
});
let calls = [];
assistant.runtime.chat = async (input) => {
calls.push(input);
return JSON.stringify({ reply: '已读取图片。', actions: [] });
};
const png = createCanvas(40, 20).toBuffer('image/png');
const upload = await f.call(
'/assistant/attachments',
{ name: 'picture.png', data: png.toString('base64') },
admin,
);
assert.equal(upload.status, 201);
const file = await upload.json();
assert.equal(file.imageData, undefined);
assert.match(file.previewImage, /^data:image\/png;base64,/);
const c = await (await f.call('/assistant/conversations', {}, admin)).json(),
base = '/assistant/conversations/' + c.id;
assert.equal(
(await f.call(base + '/messages', { text: '分析图片', attachments: [file.id] }, admin))
.status,
415,
);
assert.equal(store.usage().calls, 0);
assert.equal(calls.length, 0);
const row = store.providers.read('deepseek');
store.providers.save({
...row,
models: row.models.map((m) => ({ ...m, inputModalities: ['text', 'image'] })),
});
const sent = await (
await f.call(base + '/messages', { text: '分析图片', attachments: [file.id] }, admin)
).json();
await assistant.running.get(sent.id)?.task;
assert.equal(calls.length, 1);
assert.equal(calls[0].images[0].mediaType, 'image/png');
assert.ok(calls[0].images[0].data.length);
assert.doesNotMatch(JSON.stringify(calls[0].context), /imageData|iVBORw0KGgo/);
const transcript = await (await f.call(base, undefined, admin)).json();
assert.doesNotMatch(JSON.stringify(transcript), /imageData|iVBORw0KGgo/);
const preview = base + '/attachments/' + file.id + '/preview';
assert.equal((await f.call(preview, undefined, viewer)).status, 404);
const mine = await f.call(preview, undefined, admin);
assert.equal(mine.status, 200);
assert.match(mine.headers.get('content-type'), /image\/png/);
assert.ok((await mine.arrayBuffer()).byteLength);
const follow = await (await f.call(base + '/messages', { text: '继续看图' }, admin)).json();
await assistant.running.get(follow.id)?.task;
assert.equal(calls[1].images.length, 1);
const vision = store.providers.read('deepseek');
store.providers.save({
...vision,
models: vision.models.map((m) => ({ ...m, inputModalities: ['text'] })),
});
const plain = await (await f.call(base + '/messages', { text: '只分析文字' }, admin)).json();
await assistant.running.get(plain.id)?.task;
assert.equal(calls[2].images.length, 0);
assert.match(calls[2].context.attachmentNote, /历史图片/);
const owner = f.users.users().find((u) => u.username === 'admin').id;
const archived = store.trash(c.id, owner, { version: store.conversation(c.id, owner).version });
store.purge(c.id, owner, { version: archived.version, confirm: 'delete' });
assert.equal(
store.db
.prepare('SELECT COUNT(*) AS n FROM assistant_attachments WHERE conversation_id=?')
.get(c.id).n,
0,
);
},
);
+73
View File
@@ -0,0 +1,73 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ createCanvas } = require('@napi-rs/canvas');
const { managementFixture } = require('./management-fixture.cjs');
test(
'composer hides nonvisual capability labels, uses SVG and adapts picture input to selected model',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true }),
{ page, open, store, assistant } = f;
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_IMAGE_UI_KEY',
});
const row = store.providers.read('deepseek'),
dir = store.providers.save({
...row,
models: [{ id: 'plain-model' }, { id: 'vision-model', inputModalities: ['text', 'image'] }],
});
store.providers.chooseDefault({
version: dir.version,
providerId: 'deepseek',
modelId: 'plain-model',
});
let inputs = [];
assistant.runtime.chat = async (input) => {
inputs.push(input);
return JSON.stringify({ reply: '已通过图像内容收到图片。', actions: [] });
};
await open();
const picker = page.getByRole('button', { name: /选择模型/ }),
send = page.getByRole('button', { name: '发送', exact: true });
await picker.waitFor();
assert.doesNotMatch(await picker.innerText(), /能力未知|视觉/);
assert.equal(await page.locator('#assistant-attach svg').count(), 1);
assert.doesNotMatch(await page.locator('#assistant-files').getAttribute('accept'), /\.png/);
const file = {
name: 'picture.png',
mimeType: 'image/png',
buffer: createCanvas(40, 20).toBuffer('image/png'),
};
await page.locator('#assistant-files').setInputFiles(file);
await page.getByText('当前模型不支持图片,请先选择视觉模型。', { exact: true }).waitFor();
assert.equal(inputs.length, 0);
await picker.click();
await page.getByRole('option', { name: 'vision-model', exact: true }).click();
await page.waitForFunction(() =>
document.querySelector('#assistant-files').accept.includes('.png'),
);
await page.locator('#assistant-files').setInputFiles(file);
await page.getByRole('button', { name: '预览附件 picture.png', exact: true }).waitFor();
await page.getByRole('button', { name: '预览附件 picture.png', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '预览附件 picture.png', exact: true });
await dialog.getByRole('img', { name: 'picture.png', exact: true }).waitFor();
await dialog.getByRole('button', { name: '关闭', exact: true }).click();
await picker.click();
await page.getByRole('option', { name: 'plain-model', exact: true }).click();
await page
.getByText('当前模型不支持图片,请选择视觉模型或移除图片。', { exact: true })
.waitFor();
assert.equal(await send.isDisabled(), true);
await picker.click();
await page.getByRole('option', { name: 'vision-model', exact: true }).click();
await page.waitForFunction(() => !document.querySelector('#assistant-send').disabled);
await send.click();
await page.getByText('已通过图像内容收到图片。', { exact: true }).waitFor();
assert.equal(inputs[0].images.length, 1);
await page.waitForFunction(() => document.querySelector('.aw-sent-image')?.naturalWidth > 0);
},
);
+83 -11
View File
@@ -1,13 +1,85 @@
'use strict';
const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
async function managementFixture(t,{browser=false}={}){
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-management-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');users.addUser({username:'viewer',password:'Test-password-123',role:'viewer'},'admin');const store=new AssistantStore(path.join(dir,'assistant'));let calls=0,lastConfig;
const assistant=new AssistantService({store,dashboard:users,runtime:{probe:async()=>({available:true,version:'0.2.1-rc.2',message:'运行包已就绪'}),chat:async({config})=>{calls++;lastConfig=config;return JSON.stringify({reply:'使用模型 '+config.model,actions:[]});}}}),server=createDashboard({store:users,assistant,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
const call=(route,body,cookie)=>fetch(base+'/api'+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async(username='admin')=>(await call('/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
let engine,page;if(browser){const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');engine=await loadPlaywright().chromium.launch(browserOptions());page=await engine.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(10000);}
t.after(async()=>{await engine?.close();server.closeAssistantStreams?.();await assistant.stop();server.closeAllConnections();await new Promise(r=>server.close(r));store.close();await fs.rm(dir,{recursive:true,force:true});});
async function open(route='#assistant',username='admin'){await page.goto(base+'/'+route);await page.waitForFunction(()=>!!document.querySelector('#username')||!!document.querySelector('#logout'));if(await page.getByLabel('账号',{exact:true}).count()){await page.getByLabel('账号',{exact:true}).fill(username);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();}}
return {base,page,open,store,users,assistant,call,login,calls:()=>calls,lastConfig:()=>lastConfig};
const fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
async function managementFixture(t, { browser = false } = {}) {
const { Store } = require('../../src/modules/dashboard/store.cjs'),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
{ createDashboard } = require('../../src/app/dashboard.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-management-')),
users = new Store(path.join(dir, 'users'));
users.bootstrap('admin', 'Test-password-123');
users.addUser({ username: 'viewer', password: 'Test-password-123', role: 'viewer' }, 'admin');
const store = new AssistantStore(path.join(dir, 'assistant'));
let calls = 0,
lastConfig;
const assistant = new AssistantService({
store,
dashboard: users,
runtime: {
probe: async () => ({ available: true, version: '0.2.1-rc.2', message: '运行包已就绪' }),
chat: async ({ config }) => {
calls++;
lastConfig = config;
return JSON.stringify({ reply: '使用模型 ' + config.model, actions: [] });
},
},
}),
server = createDashboard({ store: users, assistant, outputDir: dir });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const base = 'http://127.0.0.1:' + server.address().port;
const call = (route, body, cookie) =>
fetch(base + '/api' + route, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(body === undefined ? {} : { Origin: base, 'Content-Type': 'application/json' }),
...(cookie ? { Cookie: cookie } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
}),
login = async (username = 'admin') =>
(await call('/login', { username, password: 'Test-password-123' })).headers
.get('set-cookie')
.split(';')[0];
let engine, page;
if (browser) {
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs');
engine = await loadPlaywright().chromium.launch(browserOptions());
page = await engine.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
}
t.after(async () => {
await engine?.close();
server.closeAssistantStreams?.();
await assistant.stop();
server.closeAllConnections();
await new Promise((r) => server.close(r));
store.close();
await fs.rm(dir, { recursive: true, force: true });
});
async function open(route = '#assistant', username = 'admin') {
await page.goto(base + '/' + route);
await page.waitForFunction(
() => !!document.querySelector('#username') || !!document.querySelector('#logout'),
);
if (await page.getByLabel('账号', { exact: true }).count()) {
await page.getByLabel('账号', { exact: true }).fill(username);
await page.getByLabel('密码', { exact: true }).fill('Test-password-123');
await page.getByRole('button', { name: '登录', exact: true }).click();
}
}
return {
base,
page,
open,
store,
users,
assistant,
call,
login,
calls: () => calls,
lastConfig: () => lastConfig,
};
}
module.exports={managementFixture};
module.exports = { managementFixture };
+586
View File
@@ -0,0 +1,586 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { managementFixture } = require('./management-fixture.cjs');
async function setup(t, browser = false) {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser }),
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ai-management-')),
{ WorkspaceStore } = require('../../src/modules/workspace/store.cjs'),
{ MailStore } = require('../../src/modules/mail/store.cjs'),
{ RuleStore } = require('../../src/modules/order-rules/store.cjs');
f.workspace = new WorkspaceStore(path.join(dir, 'workspace'));
f.mail = new MailStore(path.join(dir, 'mail'));
f.rules = new RuleStore(path.join(dir, 'rules'));
t.after(() => {
f.assistant.journal?.close();
f.workspace.db.close();
f.mail.close();
f.rules.close();
fs.rmSync(dir, { recursive: true, force: true });
});
f.users.addUser(
{ username: 'operator', password: 'Test-password-123', role: 'operator' },
'admin',
);
f.users.addUser({ username: 'other', password: 'Test-password-123', role: 'operator' }, 'admin');
const members = f.users.users(),
admin = members.find((u) => u.username === 'admin');
f.mine = f.workspace.createConnection({ name: '本人的连接', owner: 'operator' }, admin, members);
f.foreign = f.workspace.createConnection(
{ name: '其他人的连接', owner: 'other' },
admin,
members,
);
f.mail.saveChannel({
name: '托管邮箱',
email: 'mail@example.test',
password: 'MAIL_NEVER_EXPOSE_9187',
receiveEnabled: false,
enabled: false,
senders: [],
smtp: { host: 'smtp.example.test' },
});
Object.assign(f.assistant.deps, {
workspace: f.workspace,
mail: { store: f.mail, busy: () => false },
orderRules: f.rules,
});
f.store.saveSettings({
...f.store.settings(),
runtimePath: process.execPath,
apiKey: 'MODEL_NEVER_EXPOSE_6172',
allowActions: false,
});
return f;
}
test(
'management directory and typed queries enforce current roles, ownership, projections and page limits',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
admin = await f.login(),
operator = await f.login('operator'),
viewer = await f.login('viewer');
assert.equal((await f.call('/assistant/management')).status, 401);
const directory = await (await f.call('/assistant/management', undefined, operator)).json();
assert.ok(directory.resources.some((r) => r.id === 'connections' && r.allowed));
assert.ok(directory.resources.some((r) => r.id === 'users' && !r.allowed));
assert.ok(directory.boundaries.some((r) => r.id === 'credentials' && r.mode === 'manual'));
const mine = await (
await f.call('/assistant/management/query', { resource: 'connections', limit: 1 }, operator)
).json();
assert.equal(mine.total, 1);
assert.equal(mine.items[0].id, f.mine.id);
const foreign = await (
await f.call(
'/assistant/management/query',
{ resource: 'connections', id: f.foreign.id },
operator,
)
).json();
assert.equal(foreign.total, 0);
for (const cookie of [operator, viewer])
for (const resource of ['users', 'mail', 'configuration'])
assert.equal(
(await f.call('/assistant/management/query', { resource }, cookie)).status,
403,
);
for (const body of [
{ resource: 'users', role: 'admin' },
{ resource: 'users', url: 'http://evil.test' },
{ resource: 'users', limit: 1000 },
{ resource: 'users', offset: -1 },
{ resource: 'shell', command: 'whoami' },
])
assert.equal((await f.call('/assistant/management/query', body, admin)).status, 400);
for (const resource of ['users', 'mail', 'models', 'configuration', 'system']) {
const response = await f.call('/assistant/management/query', { resource }, admin);
assert.equal(response.status, 200);
assert.doesNotMatch(
JSON.stringify(await response.json()),
/MAIL_NEVER_EXPOSE|MODEL_NEVER_EXPOSE|passwordHash|passwordVersion|imageData|access_token|cookie/i,
);
}
const first = await (
await f.call('/assistant/management/query', { resource: 'users', limit: 1 }, admin)
).json();
assert.equal(first.items.length, 1);
assert.equal(first.hasMore, true);
assert.equal(first.nextOffset, 1);
f.users.updateUser(
f.users.users().find((u) => u.username === 'operator').id,
{
version: f.users.users().find((u) => u.username === 'operator').version,
enabled: false,
role: 'operator',
},
f.users.users()[0],
);
assert.equal(
(await f.call('/assistant/management/query', { resource: 'connections' }, operator)).status,
401,
);
},
);
test(
'AI requests scoped management reads then answers from returned data, charging each model call',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
cookie = await f.login('operator'),
user = f.users.users().find((u) => u.username === 'operator'),
c = f.store.create(user.id);
let calls = 0;
f.assistant.runtime.chat = async (input) => {
calls++;
if (calls === 1) {
assert.ok(
input.context.management.resources.some((r) => r.id === 'connections' && r.allowed),
);
return JSON.stringify({
reply: '查询连接',
actions: [],
queries: [{ resource: 'connections', limit: 10 }],
});
}
assert.equal(input.context.managementResults[0].items[0].id, f.mine.id);
assert.doesNotMatch(JSON.stringify(input.context.managementResults), /其他人的连接/);
return JSON.stringify({ reply: '查询到本人的连接。', actions: [] });
};
const before = f.store.usage().calls,
response = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '查询我负责的连接' },
cookie,
);
assert.equal(response.status, 202);
const turn = await response.json();
await f.assistant.running.get(turn.id)?.task;
const saved = f.store.conversation(c.id, user.id).turns[0];
assert.equal(saved.status, 'success', saved.error);
assert.equal(saved.reply, '查询到本人的连接。');
assert.equal(calls, 2);
assert.equal(f.store.usage().calls - before, 2);
assert.equal(saved.diagnosticSnapshot.managementResults[0].total, 1);
},
);
test(
'additional management model calls stop at quota and cannot combine queries with writes',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
cookie = await f.login(),
user = f.users.users()[0],
c = f.store.create(user.id);
f.store.saveSettings({ version: f.store.settings().version, dailyLimit: 1 });
let calls = 0;
f.assistant.runtime.chat = async () => {
calls++;
return JSON.stringify({ reply: '查询', actions: [], queries: [{ resource: 'users' }] });
};
const response = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '查成员' },
cookie,
),
turn = await response.json();
await f.assistant.running.get(turn.id)?.task;
assert.equal(calls, 1);
assert.equal(f.store.conversation(c.id, user.id).turns[0].status, 'error');
assert.equal(f.store.usage().calls, 1);
const management = require('../../src/modules/assistant/management.cjs');
assert.throws(
() =>
management.requested(
JSON.stringify({
reply: '查询并修改',
queries: [{ resource: 'users' }],
actions: [
{ kind: 'update_configuration', targetId: 'assistant', changes: { dailyLimit: 100 } },
],
}),
),
/查询与修改/,
);
},
);
test(
'calendar and category recipient drafts stay scoped, versioned and administrator-only',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
configuration = require('../../src/modules/assistant/configuration.cjs'),
user = f.users.users()[0],
deps = f.assistant.deps,
observed = () => configuration.snapshot(deps, f.store, user),
day = { date: '2026-11-01', kind: 'pause', scan: false, send: false, note: '单日暂停' };
let p = configuration.propose(
{ targetId: 'calendar', changes: { override: day } },
observed(),
deps,
f.store,
user,
);
assert.equal(p.diff[0].before, null);
assert.ok(p.risks.some((s) => /采集|发送/.test(s)));
assert.equal(f.workspace.meta('calendar').overrides.length, 0);
configuration.apply(p, deps, f.store, user);
assert.deepEqual(f.workspace.meta('calendar').overrides, [day]);
assert.throws(
() => configuration.apply(p, deps, f.store, user),
(e) => e.status === 409,
);
p = configuration.propose(
{ targetId: 'calendar', changes: { removeDate: day.date } },
observed(),
deps,
f.store,
user,
);
assert.deepEqual(p.diff[0].before, day);
configuration.apply(p, deps, f.store, user);
assert.equal(f.workspace.meta('calendar').overrides.length, 0);
const record = f.rules.all('rules')[0],
target = 'rule-recipients:' + record.id,
patch = { to: ['receiver@example.test'], cc: [] };
p = configuration.propose(
{ targetId: target, changes: patch },
observed(),
deps,
f.store,
user,
);
assert.ok(p.risks.some((s) => /收件/.test(s)));
const published = record.published;
configuration.apply(p, deps, f.store, user);
assert.deepEqual(f.rules.get('rules', record.id).draft.to, patch.to);
assert.deepEqual(f.rules.get('rules', record.id).published, published);
assert.deepEqual(f.users.settings().groups, []);
assert.throws(
() =>
configuration.propose({ targetId: target, changes: patch }, observed(), deps, f.store, {
...user,
role: 'operator',
}),
(e) => e.status === 403,
);
assert.throws(() =>
configuration.propose(
{ targetId: 'calendar', changes: { enabled: true } },
observed(),
deps,
f.store,
user,
),
);
assert.throws(() =>
configuration.propose(
{ targetId: 'calendar', changes: { override: { ...day, role: 'admin' } } },
observed(),
deps,
f.store,
user,
),
);
assert.throws(() =>
configuration.propose(
{ targetId: target, changes: { to: ['bad-address'] } },
observed(),
deps,
f.store,
user,
),
);
assert.throws(() =>
configuration.propose(
{ targetId: 'recipients', changes: { groups: [] } },
observed(),
deps,
f.store,
user,
),
);
},
);
test(
'new management writes require a scoped risk review token before applying changes',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
f.assistant.journal = new OperationJournal({
file: path.join(f.workspace.db.location(), '../operations.sqlite'),
});
f.store.saveSettings({ version: f.store.settings().version, allowActions: true });
const cookie = await f.login(),
user = f.users.users()[0],
c = f.store.create(user.id),
root = '/assistant/conversations/' + c.id;
f.assistant.runtime.chat = async () =>
JSON.stringify({
reply: '请审查单日日历变更。',
actions: [
{
kind: 'update_configuration',
targetId: 'calendar',
changes: {
override: {
date: '2026-11-02',
kind: 'pause',
scan: false,
send: false,
note: '测试覆盖',
},
},
},
],
});
const response = await f.call(root + '/messages', { text: '建议暂停指定日期' }, cookie),
turn = await response.json();
await f.assistant.running.get(turn.id)?.task;
const saved = f.store.conversation(c.id, user.id).turns[0];
assert.equal(saved.status, 'success', saved.error);
const action = saved.actions[0],
endpoint = root + '/actions/' + action.id;
assert.equal(f.workspace.meta('calendar').overrides.length, 0);
assert.equal((await f.call(endpoint + '/execute', {}, cookie)).status, 403);
const review = await (await f.call(endpoint + '/review', {}, cookie)).json();
assert.ok(review.diff.length);
assert.ok(review.risks.length);
assert.equal(
(await f.call(endpoint + '/execute', { approvalToken: review.approvalToken }, cookie)).status,
200,
);
assert.equal(f.workspace.meta('calendar').overrides.length, 1);
assert.equal(
(await f.call(endpoint + '/execute', { approvalToken: review.approvalToken }, cookie)).status,
409,
);
},
);
test(
'management reads recheck the role after a model response and reject a revoked privilege',
{ timeout: 90000 },
async (t) => {
const f = await setup(t);
f.users.addUser(
{ username: 'secondadmin', password: 'Test-password-123', role: 'admin' },
'admin',
);
const cookie = await f.login('secondadmin'),
u = f.users.users().find((x) => x.username === 'secondadmin'),
c = f.store.create(u.id);
let calls = 0;
f.assistant.runtime.chat = async (input) => {
if (++calls === 1) {
f.users.updateUser(
u.id,
{ version: u.version, enabled: true, role: 'operator' },
f.users.users()[0],
);
return JSON.stringify({ reply: '读取成员', actions: [], queries: [{ resource: 'users' }] });
}
assert.equal(input.context.management.role, 'operator');
assert.equal(input.context.managementResults[0].status, 403);
assert.equal(input.context.managementResults[0].items, undefined);
return JSON.stringify({ reply: '当前权限不足。', actions: [] });
};
const response = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '查询成员' },
cookie,
),
turn = await response.json();
await f.assistant.running.get(turn.id)?.task;
assert.equal(f.store.conversation(c.id, u.id).turns[0].reply, '当前权限不足。');
assert.equal(calls, 2);
},
);
test(
'permission panel shows resource scopes, authorization requirements and manual boundaries',
{ timeout: 90000 },
async (t) => {
const f = await setup(t, true);
await f.open();
await f.page.getByRole('button', { name: 'AI 管理权限', exact: true }).click();
const dialog = f.page.getByRole('dialog', { name: 'AI 管理权限', exact: true });
await dialog.getByText('只读管理查询', { exact: true }).waitFor();
await dialog.getByRole('cell', { name: '成员目录', exact: true }).waitFor();
await dialog.getByText('凭据与登录会话 · 仅人工', { exact: true }).waitFor();
await dialog.getByText('本人定时任务维护 · 逐次授权', { exact: true }).waitFor();
const output = path.resolve(__dirname, '../../output/verification/dsh-management');
fs.mkdirSync(output, { recursive: true });
await f.page.screenshot({ path: path.join(output, 'permissions-desktop.png'), fullPage: true });
await f.page.setViewportSize({ width: 390, height: 844 });
assert.equal(
await f.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
await f.page.screenshot({ path: path.join(output, 'permissions-mobile.png'), fullPage: true });
},
);
test(
'management queries find older jobs and audit events and disclose bounded recent sources',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
f.assistant.journal = new OperationJournal({
file: path.join(f.workspace.db.location(), '../query-operations.sqlite'),
});
const cookie = await f.login(),
user = f.users.users()[0];
for (let i = 0; i < 205; i++)
f.users.recordJob({
jobId: 'job-' + i,
status: 'success',
connectionId: f.mine.id,
filename: 'file-' + i + '.pdf',
});
for (let i = 0; i < 105; i++)
f.assistant.journal.append({
operationId: 'operation-' + i,
actor: user.id,
step: 'test',
status: 'success',
detail: 'event ' + i,
});
const job = await (
await f.call('/assistant/management/query', { resource: 'jobs', id: 'job-0' }, cookie)
).json();
assert.equal(job.total, 1);
assert.equal(job.items[0].id, 'job-0');
assert.equal(job.scope.totalIsExact, true);
const operation = await (
await f.call(
'/assistant/management/query',
{ resource: 'operations', id: 'operation-0' },
cookie,
)
).json();
assert.equal(operation.total, 1);
assert.equal(operation.items[0].operationId, 'operation-0');
const page = await (
await f.call(
'/assistant/management/query',
{ resource: 'operations', offset: 100, limit: 10 },
cookie,
)
).json();
assert.equal(page.total, 105);
assert.equal(page.items.length, 5);
f.assistant.deps.scanner = { store: { status: () => ({ runs: [] }) } };
const scan = await (
await f.call('/assistant/management/query', { resource: 'scans' }, cookie)
).json();
assert.deepEqual(scan.scope, { recentOnly: true, sourceLimit: 30, totalIsExact: false });
},
);
test(
'large allowed query pages fit the whole turn and preserve bounded pagination',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
cookie = await f.login(),
user = f.users.users()[0],
c = f.store.create(user.id);
for (let i = 0; i < 40; i++)
f.workspace.createException(
{
title: '大型记录' + i,
description: '说明内容'.repeat(1000),
component: 'system',
priority: 'normal',
owner: 'operator',
},
user,
f.users.users(),
);
let calls = 0;
f.assistant.runtime.chat = async (input) => {
calls++;
require('../../src/modules/assistant/dsh-runtime.cjs').prompt(input);
if (calls === 1)
return JSON.stringify({
reply: '分页查询',
actions: [],
queries: [0, 5, 10].map((offset) => ({ resource: 'exceptions', offset, limit: 20 })),
});
if (calls === 2) {
assert.ok(input.context.managementResults.every((r) => r.hasMore === true || r.error));
return JSON.stringify({
reply: '继续分页',
actions: [],
queries: [15, 20, 25].map((offset) => ({ resource: 'exceptions', offset, limit: 20 })),
});
}
assert.ok(JSON.stringify(input.context.managementResults).length <= 48000);
return JSON.stringify({ reply: '已读取授权范围内的部分记录。', actions: [] });
};
const response = await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: '分页查询异常' },
cookie,
),
turn = await response.json();
await f.assistant.running.get(turn.id)?.task;
const saved = f.store.conversation(c.id, user.id).turns[0];
assert.equal(saved.status, 'success', saved.error);
assert.equal(calls, 3);
assert.equal(f.store.usage().calls, 3);
},
);
test(
'recipient review includes every change caused by the existing rule validator',
{ timeout: 90000 },
async (t) => {
const f = await setup(t),
configuration = require('../../src/modules/assistant/configuration.cjs'),
user = f.users.users()[0],
record = f.rules.all('rules')[0];
f.rules.saveRule(
{
id: record.id,
categoryId: record.draft.categoryId,
version: record.draft.version,
to: ['a@example.test'],
cc: ['b@example.test'],
},
user.username,
);
const p = configuration.propose(
{ targetId: 'rule-recipients:' + record.id, changes: { to: ['b@example.test'] } },
configuration.snapshot(f.assistant.deps, f.store, user),
f.assistant.deps,
f.store,
user,
);
assert.deepEqual(p.diff.map((d) => d.field).sort(), ['cc', 'to']);
assert.deepEqual(p.diff.find((d) => d.field === 'cc').after, []);
configuration.apply(p, f.assistant.deps, f.store, user);
const saved = f.rules.get('rules', record.id).draft;
for (const d of p.diff) assert.deepEqual(saved[d.field], d.after);
},
);
test(
'the visible quota refreshes after a management turn makes multiple model calls',
{ timeout: 90000 },
async (t) => {
const f = await setup(t, true);
let calls = 0;
f.assistant.runtime.chat = async () =>
++calls === 1
? JSON.stringify({ reply: '查询状态', actions: [], queries: [{ resource: 'system' }] })
: JSON.stringify({ reply: '只读查询完成。', actions: [] });
await f.open();
await f.page.getByLabel('发送给 DSH', { exact: true }).fill('查询系统状态');
await f.page.getByRole('button', { name: '发送', exact: true }).click();
await f.page.getByText('只读查询完成。', { exact: true }).waitFor();
await f.page.locator('.aw-usage').getByText('今日 2 / 100', { exact: true }).waitFor();
assert.equal(calls, 2);
},
);
@@ -0,0 +1,14 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { modelRows } = require('../../src/modules/assistant/providers.cjs');
test('model capability metadata preserves confirmed image input and never infers from its name', () => {
assert.deepEqual(modelRows([{ id: 'vision-sounding-name' }]), [
{ id: 'vision-sounding-name', name: 'vision-sounding-name' },
]);
assert.deepEqual(
modelRows([{ id: 'real', inputModalities: ['text', 'image'] }])[0].inputModalities,
['text', 'image'],
);
assert.throws(() => modelRows([{ id: 'bad', inputModalities: ['tools'] }]));
});
+219
View File
@@ -0,0 +1,219 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs');
const { OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
const { NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs');
const until = async (predicate) => {
const end = Date.now() + 6000;
while (!(await predicate())) {
if (Date.now() > end) throw Error('Schedule condition did not settle');
await new Promise((r) => setTimeout(r, 20));
}
};
test(
'native DSH reminders persist, deliver once to original owner and retain approval boundaries',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
{ store, assistant, users } = f,
file = path.join(os.tmpdir(), 'schedule-audit-' + crypto.randomUUID() + '.sqlite'),
journal = new OperationJournal({ file });
assistant.journal = journal;
t.after(() => {
journal.close();
fs.rmSync(file, { force: true });
});
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_NATIVE_SCHEDULE_KEY',
allowActions: true,
});
let modelCalls = 0,
operations = 0;
assistant.deps.storage = {
store: {
servers: () => [{ id: 'server', name: 'Fixture', enabled: true, state: {} }],
archives: () => [],
},
check: async () => {
operations++;
},
};
assistant.runtime.chat = async () => {
modelCalls++;
return JSON.stringify({
reply: '定时提醒已收到。',
actions: [{ kind: 'check_storage', targetId: 'server' }],
});
};
const principal = {
user: users.users().find((u) => u.username === 'admin'),
sessionId: 'interactive-admin',
},
c = store.create(principal.user.id);
let schedules = await NativeSchedules.create({ assistant });
assistant.schedules = schedules;
await assert.rejects(
schedules.createTask(c.id, principal, {
request: { title: '未确认', prompt: 'test', after_seconds: 60 },
}),
(e) => e.status === 403,
);
assert.equal((await schedules.list(c.id, principal)).tasks.length, 0);
await assert.rejects(
schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '过频', prompt: 'test', every_seconds: 30 },
}),
(e) => e.status === 400,
);
const daily = await schedules.createTask(c.id, principal, {
confirm: true,
request: {
title: '北京时间每日',
prompt: '查看状态',
daily: { time: '09:00:00', time_zone: 'Asia/Shanghai' },
},
});
assert.equal(daily.kind, 'daily');
assert.equal(daily.timeZone, 'Asia/Shanghai');
await assert.rejects(
schedules.list(c.id, {
user: users.users().find((u) => u.username === 'viewer'),
sessionId: 'viewer',
}),
(e) => e.status === 404,
);
const updated = await schedules.updateTask(c.id, daily.id, principal, {
confirm: true,
expected: daily,
changes: { title: '改名' },
});
assert.equal(updated.record.title, '改名');
await assert.rejects(
schedules.updateTask(c.id, daily.id, principal, {
confirm: true,
expected: daily,
changes: { title: '过期修改' },
}),
(e) => e.status === 409,
);
const task = await schedules.createTask(c.id, principal, {
confirm: true,
request: {
title: '一次原生提醒',
prompt: '检查状态并提出建议,不执行操作',
after_seconds: 1,
},
});
await until(async () => {
const list = await schedules.list(c.id, principal);
return list.history.some((h) => h.taskId === task.id && h.status === 'success');
});
assert.equal(modelCalls, 1);
assert.equal(operations, 0);
const turns = store.conversation(c.id, principal.user.id).turns;
assert.equal(turns.at(-1).actions[0].status, 'proposed');
await schedules.stop();
const row = store.db
.prepare('SELECT payload FROM assistant_schedule_tasks WHERE id=?')
.get(task.id),
old = store.decode('schedule-task:' + task.id, row.payload),
lostAck = {
sessionId: old.sessionId,
record: old.record,
status: 'active',
deliveryHistory: { records: [], earlierRecordsUnavailable: false },
};
store.db
.prepare('UPDATE assistant_schedule_tasks SET payload=? WHERE id=?')
.run(store.encode('schedule-task:' + task.id, lostAck), task.id);
schedules = await NativeSchedules.create({ assistant });
assistant.schedules = schedules;
await until(
async () =>
(await schedules.list(c.id, principal)).tasks.find((x) => x.id === task.id)?.status ===
'inactive',
);
assert.equal(modelCalls, 1);
await schedules.deleteTask(c.id, daily.id, principal, { confirm: true });
assert.equal(
(await schedules.list(c.id, principal)).tasks.some((x) => x.id === daily.id),
false,
);
const at = new Date(Date.now() + 1500).toISOString();
const paired = await Promise.all(
['甲', '乙'].map((name) =>
schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '同刻原生提醒' + name, prompt: 'check ' + name, at },
}),
),
);
await until(async () => {
const h = (await schedules.list(c.id, principal)).history;
return paired.every((t) => h.some((r) => r.taskId === t.id && r.status === 'success'));
});
assert.equal(modelCalls, 3);
assert.equal(operations, 0);
for (const t of paired) await schedules.deleteTask(c.id, t.id, principal, { confirm: true });
for (const request of [
{ title: '原生间隔', prompt: 'check', every_seconds: 3600 },
{
title: '原生Cron',
prompt: 'check',
cron: { expression: '0 9 * * *', time_zone: 'Asia/Shanghai' },
},
]) {
const result = await schedules.createTask(c.id, principal, { confirm: true, request });
assert.ok(['every', 'cron'].includes(result.kind));
await schedules.deleteTask(c.id, result.id, principal, { confirm: true });
}
const originalRecord = assistant.record.bind(assistant);
assistant.record = (id, actor, step, status, detail) => {
if (step === 'schedule_create' && status === 'success')
throw Error('audit failed after save');
return originalRecord(id, actor, step, status, detail);
};
await assert.rejects(
schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '核实未知结果', prompt: 'check', after_seconds: 3600 },
}),
(e) => e.status === 502 && e.mutationApplied === true,
);
assistant.record = originalRecord;
const uncertain = (await schedules.list(c.id, principal)).tasks.filter(
(t) => t.title === '核实未知结果',
);
assert.equal(uncertain.length, 1);
await schedules.deleteTask(c.id, uncertain[0].id, principal, { confirm: true });
for (let i = 0; i < 29; i++)
await schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '并发限制' + i, prompt: 'check', after_seconds: 3600 },
});
const raced = await Promise.allSettled(
[0, 1].map((i) =>
schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '竞争' + i, prompt: 'check', after_seconds: 3600 },
}),
),
);
assert.equal(raced.filter((r) => r.status === 'fulfilled').length, 1);
assert.equal((await schedules.native.list({ sessionId: c.id })).length, 30);
await schedules.stopSession(c.id);
assert.equal(
(await schedules.list(c.id, principal)).tasks.some((x) => x.status === 'active'),
false,
);
},
);
+123 -20
View File
@@ -1,22 +1,125 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),path=require('node:path');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t){
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.route('https://synthetic.invalid/**',route=>route.fulfill({body:'<div id="fixture"></div>',contentType:'text/html'}));await page.goto('https://synthetic.invalid/');for(const name of ['dsh-native','layout','conversation','commands','context-panel','events-client','providers','model-picker','view'])await page.addScriptTag({path:path.resolve('web/modules/assistant/'+name+'.js')});
await page.evaluate(async()=>{
window.requests=[];window.failNext=false;window.hold=false;window.release=null;
const items=Array.from({length:26},(_,i)=>({id:'active-'+i,title:'Active '+i,updatedAt:'2026-10-21',version:1}));
const api=async route=>{
if(route==='/assistant')return {settings:{enabled:false},usage:{calls:0,limit:100},conversations:items};
if(route==='/assistant/providers')return {providers:[],defaultSelection:null};if(route==='/assistant/context')return {connections:[],servers:[],archives:[],runs:[]};if(route.includes('/events?'))return {events:[],nextCursor:0,hasMore:false};if(route.includes('?')){const url=new URL(route,location.origin),scope=url.searchParams.get('scope'),page=Number(url.searchParams.get('page'));window.requests.push(scope+':'+page);if(window.hold&&scope==='active'&&page===2)await new Promise((resolve,reject)=>{window.release=()=>reject(Error('Stale failure'));});if(window.failNext){window.failNext=false;throw Error('Synthetic page failure');}const list=scope==='active'?items:[{id:'archived',title:'Archived only',updatedAt:'2026-10-21'}];return {items:list.slice((page-1)*25,page*25),page,total:list.length};}
return {id:route.split('/').at(-1),title:'Synthetic',version:1,turns:[],archived:route.endsWith('archived')};
};
window.AssistantViews.configure({api,esc:String,formatDate:String,notify:()=>{},user:{username:'synthetic',role:'admin'}});await window.AssistantViews.render(document.querySelector('#fixture'));
});return page;
const test = require('node:test'),
assert = require('node:assert/strict'),
path = require('node:path');
const { loadPlaywright, browserOptions } = require('../../src/platform/browser.cjs');
async function fixture(t) {
const browser = await loadPlaywright().chromium.launch(browserOptions());
t.after(() => browser.close());
const page = await browser.newPage();
await page.route('https://synthetic.invalid/**', (route) =>
route.fulfill({ body: '<div id="fixture"></div>', contentType: 'text/html' }),
);
await page.goto('https://synthetic.invalid/');
for (const name of [
'dsh-native',
'layout',
'conversation',
'commands',
'context-panel',
'events-client',
'providers',
'model-picker',
'view',
])
await page.addScriptTag({
path: path.resolve(__dirname, '../../web/modules/assistant/' + name + '.js'),
});
await page.evaluate(async () => {
window.requests = [];
window.failNext = false;
window.hold = false;
window.release = null;
const items = Array.from({ length: 26 }, (_, i) => ({
id: 'active-' + i,
title: 'Active ' + i,
updatedAt: '2026-10-21',
version: 1,
}));
const api = async (route) => {
if (route === '/assistant')
return {
settings: { enabled: false },
usage: { calls: 0, limit: 100 },
conversations: items,
};
if (route === '/assistant/providers') return { providers: [], defaultSelection: null };
if (route === '/assistant/context')
return { connections: [], servers: [], archives: [], runs: [] };
if (route.includes('/events?')) return { events: [], nextCursor: 0, hasMore: false };
if (route.includes('?')) {
const url = new URL(route, location.origin),
scope = url.searchParams.get('scope'),
page = Number(url.searchParams.get('page'));
window.requests.push(scope + ':' + page);
if (window.hold && scope === 'active' && page === 2)
await new Promise((resolve, reject) => {
window.release = () => reject(Error('Stale failure'));
});
if (window.failNext) {
window.failNext = false;
throw Error('Synthetic page failure');
}
const list =
scope === 'active'
? items
: [{ id: 'archived', title: 'Archived only', updatedAt: '2026-10-21' }];
return { items: list.slice((page - 1) * 25, page * 25), page, total: list.length };
}
return {
id: route.split('/').at(-1),
title: 'Synthetic',
version: 1,
turns: [],
archived: route.endsWith('archived'),
};
};
window.AssistantViews.configure({
api,
esc: String,
formatDate: String,
notify: () => {},
user: { username: 'synthetic', role: 'admin' },
});
await window.AssistantViews.render(document.querySelector('#fixture'));
});
return page;
}
test('failed assistant page restores navigation and retries the same page',{timeout:30000},async t=>{
const page=await fixture(t);await page.evaluate(()=>{window.failNext=true;});await page.locator('#assistant-next').click();await page.getByText('Synthetic page failure',{exact:true}).waitFor();assert.equal(await page.locator('#assistant-next').isDisabled(),false);assert.equal(await page.locator('#assistant-prev').isDisabled(),true);await page.locator('#assistant-next').click();await page.locator('#assistant-page').filter({hasText:'2 / 2'}).waitFor();assert.deepEqual(await page.evaluate(()=>requests),['active:1','active:2','active:2']);assert.equal(await page.locator('[data-assistant-conversation]').count(),1);
});
test('stale failed page cannot roll back the new scope or disable its navigation',{timeout:30000},async t=>{
const page=await fixture(t);await page.evaluate(()=>{window.hold=true;});await page.locator('#assistant-next').click();await page.waitForFunction(()=>!!window.release);await page.locator('#assistant-scope').selectOption('archived');await page.getByText('Archived only',{exact:true}).waitFor();await page.evaluate(()=>window.release());await page.evaluate(()=>new Promise(r=>setTimeout(r,0)));assert.equal(await page.locator('#assistant-error').textContent(),'');assert.equal(await page.locator('#assistant-page').textContent(),'1 / 1');assert.equal(await page.locator('#assistant-next').isDisabled(),true);assert.equal(await page.locator('#assistant-prev').isDisabled(),true);
});
test(
'failed assistant page restores navigation and retries the same page',
{ timeout: 30000 },
async (t) => {
const page = await fixture(t);
await page.evaluate(() => {
window.failNext = true;
});
await page.locator('#assistant-next').click();
await page.getByText('Synthetic page failure', { exact: true }).waitFor();
assert.equal(await page.locator('#assistant-next').isDisabled(), false);
assert.equal(await page.locator('#assistant-prev').isDisabled(), true);
await page.locator('#assistant-next').click();
await page.locator('#assistant-page').filter({ hasText: '2 / 2' }).waitFor();
assert.deepEqual(await page.evaluate(() => requests), ['active:1', 'active:2', 'active:2']);
assert.equal(await page.locator('[data-assistant-conversation]').count(), 1);
},
);
test(
'stale failed page cannot roll back the new scope or disable its navigation',
{ timeout: 30000 },
async (t) => {
const page = await fixture(t);
await page.evaluate(() => {
window.hold = true;
});
await page.locator('#assistant-next').click();
await page.waitForFunction(() => !!window.release);
await page.locator('#assistant-scope').selectOption('archived');
await page.getByText('Archived only', { exact: true }).waitFor();
await page.evaluate(() => window.release());
await page.evaluate(() => new Promise((r) => setTimeout(r, 0)));
assert.equal(await page.locator('#assistant-error').textContent(), '');
assert.equal(await page.locator('#assistant-page').textContent(), '1 / 1');
assert.equal(await page.locator('#assistant-next').isDisabled(), true);
assert.equal(await page.locator('#assistant-prev').isDisabled(), true);
},
);
+334 -23
View File
@@ -1,33 +1,344 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict');const {managementFixture}=require('./management-fixture.cjs');
const provider=()=>({version:0,name:'Fixture OpenAI',preset:'openai',protocol:'openai-completions',apiBase:'https://models.example/v1',apiKey:'TEST_PROVIDER_PRIVATE_KEY',enabled:true,models:[{id:'model-a',name:'Model A'},{id:'model-b',name:'Model B'}]});
test('provider administration is authenticated, admin-only, versioned and never returns keys',async t=>{
const f=await managementFixture(t),admin=await f.login(),viewer=await f.login('viewer');assert.equal((await f.call('/assistant/providers')).status,401);assert.equal((await f.call('/assistant/providers',provider(),viewer)).status,403);const result=await f.call('/assistant/providers',provider(),admin);assert.equal(result.status,201);const list=await result.json();assert.doesNotMatch(JSON.stringify(list),/TEST_PROVIDER_PRIVATE_KEY|"apiKey":/);assert.ok(list.providers.some(p=>p.name==='Fixture OpenAI'));const publicList=await(await f.call('/assistant/providers',undefined,viewer)).json();assert.equal(publicList.providers.length,1);assert.equal(publicList.providers[0].apiBase,undefined);
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
const provider = () => ({
version: 0,
name: 'Fixture OpenAI',
preset: 'openai',
protocol: 'openai-completions',
apiBase: 'https://models.example/v1',
apiKey: 'TEST_PROVIDER_PRIVATE_KEY',
enabled: true,
models: [
{ id: 'model-a', name: 'Model A' },
{ id: 'model-b', name: 'Model B' },
],
});
test('default/per-conversation model routing is used and frozen into each accepted turn',async t=>{
const f=await managementFixture(t),cookie=await f.login(),list=await(await f.call('/assistant/providers',provider(),cookie)).json(),p=list.providers.find(row=>row.name==='Fixture OpenAI');
assert.equal((await f.call('/assistant/providers/default',{version:list.version,providerId:p.id,modelId:'model-a'},cookie)).status,200);const runtime={version:f.store.settings().version,runtimePath:process.execPath,enabled:true,allowActions:false,allowCodeRepair:false,repairRepository:'',timeoutSeconds:30,dailyLimit:100};assert.equal((await f.call('/assistant/settings',runtime,cookie)).status,200);
const c=await(await f.call('/assistant/conversations',{},cookie)).json();const selected=await f.call('/assistant/conversations/'+c.id+'/model',{version:c.version,providerId:p.id,modelId:'model-b'},cookie);assert.equal(selected.status,200);const sent=await(await f.call('/assistant/conversations/'+c.id+'/messages',{text:'diagnose',requestId:'fixed-model'},cookie)).json();await f.assistant.running.get(sent.id)?.task;assert.equal(f.lastConfig().model,'model-b');const saved=await(await f.call('/assistant/conversations/'+c.id,undefined,cookie)).json();assert.equal(saved.turns[0].modelSelection.providerId,p.id);assert.equal(saved.turns[0].modelSelection.modelId,'model-b');assert.doesNotMatch(JSON.stringify(saved),/TEST_PROVIDER_PRIVATE_KEY/);
test('provider administration is authenticated, admin-only, versioned and never returns keys', async (t) => {
const f = await managementFixture(t),
admin = await f.login(),
viewer = await f.login('viewer');
assert.equal((await f.call('/assistant/providers')).status, 401);
assert.equal((await f.call('/assistant/providers', provider(), viewer)).status, 403);
const result = await f.call('/assistant/providers', provider(), admin);
assert.equal(result.status, 201);
const list = await result.json();
assert.doesNotMatch(JSON.stringify(list), /TEST_PROVIDER_PRIVATE_KEY|"apiKey":/);
assert.ok(list.providers.some((p) => p.name === 'Fixture OpenAI'));
const publicList = await (await f.call('/assistant/providers', undefined, viewer)).json();
assert.equal(publicList.providers.length, 1);
assert.equal(publicList.providers[0].apiBase, undefined);
});
test('known credentials of every provider are scrubbed before another provider receives a message',async t=>{
const f=await managementFixture(t),cookie=await f.login();let list=await(await f.call('/assistant/providers',provider(),cookie)).json();const first=list.providers.find(p=>p.name==='Fixture OpenAI');list=await(await f.call('/assistant/providers',{...provider(),name:'Second',apiKey:'SECOND_PROVIDER_SECRET_RAW_VALUE'},cookie)).json();await f.call('/assistant/providers/default',{version:list.version,providerId:first.id,modelId:'model-a'},cookie);f.store.saveSettings({version:f.store.settings().version,enabled:true,runtimePath:process.execPath,allowActions:false});let input;f.assistant.runtime.chat=async value=>{input=value;return JSON.stringify({reply:'ok',actions:[]});};const c=await(await f.call('/assistant/conversations',{},cookie)).json(),sent=await(await f.call('/assistant/conversations/'+c.id+'/messages',{text:'diagnose SECOND_PROVIDER_SECRET_RAW_VALUE'},cookie)).json();await f.assistant.running.get(sent.id)?.task;assert.doesNotMatch(input.text,/SECOND_PROVIDER_SECRET_RAW_VALUE/);assert.doesNotMatch(JSON.stringify(f.store.conversation(c.id,f.users.users().find(u=>u.username==='admin').id)),/SECOND_PROVIDER_SECRET_RAW_VALUE/);
test('default/per-conversation model routing is used and frozen into each accepted turn', async (t) => {
const f = await managementFixture(t),
cookie = await f.login(),
list = await (await f.call('/assistant/providers', provider(), cookie)).json(),
p = list.providers.find((row) => row.name === 'Fixture OpenAI');
assert.equal(
(
await f.call(
'/assistant/providers/default',
{ version: list.version, providerId: p.id, modelId: 'model-a' },
cookie,
)
).status,
200,
);
const runtime = {
version: f.store.settings().version,
runtimePath: process.execPath,
enabled: true,
allowActions: false,
allowCodeRepair: false,
repairRepository: '',
timeoutSeconds: 30,
dailyLimit: 100,
};
assert.equal((await f.call('/assistant/settings', runtime, cookie)).status, 200);
const c = await (await f.call('/assistant/conversations', {}, cookie)).json();
const selected = await f.call(
'/assistant/conversations/' + c.id + '/model',
{ version: c.version, providerId: p.id, modelId: 'model-b' },
cookie,
);
assert.equal(selected.status, 200);
const sent = await (
await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: 'diagnose', requestId: 'fixed-model' },
cookie,
)
).json();
await f.assistant.running.get(sent.id)?.task;
assert.equal(f.lastConfig().model, 'model-b');
const saved = await (await f.call('/assistant/conversations/' + c.id, undefined, cookie)).json();
assert.equal(saved.turns[0].modelSelection.providerId, p.id);
assert.equal(saved.turns[0].modelSelection.modelId, 'model-b');
assert.doesNotMatch(JSON.stringify(saved), /TEST_PROVIDER_PRIVATE_KEY/);
});
test('selected repair sources containing another provider credential are rejected before accepting a turn',async t=>{
const f=await managementFixture(t);f.store.providers.save(provider());f.store.providers.save({...provider(),name:'Second',apiKey:'SECOND_PROVIDER_SECRET_RAW_VALUE'});const dir=f.store.providers.list(),first=dir.providers.find(p=>p.name==='Fixture OpenAI');f.store.providers.chooseDefault({version:dir.version,providerId:first.id,modelId:'model-a'});f.store.saveSettings({version:f.store.settings().version,enabled:true,runtimePath:process.execPath,allowActions:true,allowCodeRepair:true,repairRepository:process.cwd()});f.assistant.repairFactory=()=>({readSources:()=>({baselineCommit:'a'.repeat(40),files:[{path:'src/demo.cjs',content:'const value="SECOND_PROVIDER_SECRET_RAW_VALUE";'}]})});const user=f.users.users().find(u=>u.username==='admin'),c=f.store.create(user.id);assert.throws(()=>f.assistant.sendRepair(c.id,{user,sessionId:'fixture'},'fix',['src/demo.cjs']),/凭据/);assert.equal(f.store.usage().calls,0);
test('known credentials of every provider are scrubbed before another provider receives a message', async (t) => {
const f = await managementFixture(t),
cookie = await f.login();
let list = await (await f.call('/assistant/providers', provider(), cookie)).json();
const first = list.providers.find((p) => p.name === 'Fixture OpenAI');
list = await (
await f.call(
'/assistant/providers',
{ ...provider(), name: 'Second', apiKey: 'SECOND_PROVIDER_SECRET_RAW_VALUE' },
cookie,
)
).json();
await f.call(
'/assistant/providers/default',
{ version: list.version, providerId: first.id, modelId: 'model-a' },
cookie,
);
f.store.saveSettings({
version: f.store.settings().version,
enabled: true,
runtimePath: process.execPath,
allowActions: false,
});
let input;
f.assistant.runtime.chat = async (value) => {
input = value;
return JSON.stringify({ reply: 'ok', actions: [] });
};
const c = await (await f.call('/assistant/conversations', {}, cookie)).json(),
sent = await (
await f.call(
'/assistant/conversations/' + c.id + '/messages',
{ text: 'diagnose SECOND_PROVIDER_SECRET_RAW_VALUE' },
cookie,
)
).json();
await f.assistant.running.get(sent.id)?.task;
assert.doesNotMatch(input.text, /SECOND_PROVIDER_SECRET_RAW_VALUE/);
assert.doesNotMatch(
JSON.stringify(
f.store.conversation(c.id, f.users.users().find((u) => u.username === 'admin').id),
),
/SECOND_PROVIDER_SECRET_RAW_VALUE/,
);
});
test('legacy credentials migrate into the provider vault once and deleting the provider removes the legacy copy',async t=>{
const f=await managementFixture(t);f.store.saveSettings({...f.store.settings(),apiKey:'LEGACY_ONLY_PRIVATE_KEY',enabled:false});const row=f.store.db.prepare('SELECT * FROM config WHERE id=1').get();assert.equal(f.store.decode('config',row.payload).apiKey,'');assert.equal(f.store.secretSettings().apiKey,'LEGACY_ONLY_PRIVATE_KEY');const legacy=f.store.providers.list().providers.find(p=>p.id==='deepseek');f.store.providers.remove(legacy.id,{version:legacy.version});assert.equal(f.store.secretSettings().apiKey,'');assert.equal(f.store.settings().hasApiKey,false);
test('selected repair sources containing another provider credential are rejected before accepting a turn', async (t) => {
const f = await managementFixture(t);
f.store.providers.save(provider());
f.store.providers.save({
...provider(),
name: 'Second',
apiKey: 'SECOND_PROVIDER_SECRET_RAW_VALUE',
});
const dir = f.store.providers.list(),
first = dir.providers.find((p) => p.name === 'Fixture OpenAI');
f.store.providers.chooseDefault({
version: dir.version,
providerId: first.id,
modelId: 'model-a',
});
f.store.saveSettings({
version: f.store.settings().version,
enabled: true,
runtimePath: process.execPath,
allowActions: true,
allowCodeRepair: true,
repairRepository: process.cwd(),
});
f.assistant.repairFactory = () => ({
readSources: () => ({
baselineCommit: 'a'.repeat(40),
files: [{ path: 'src/demo.cjs', content: 'const value="SECOND_PROVIDER_SECRET_RAW_VALUE";' }],
}),
});
const user = f.users.users().find((u) => u.username === 'admin'),
c = f.store.create(user.id);
assert.throws(
() => f.assistant.sendRepair(c.id, { user, sessionId: 'fixture' }, 'fix', ['src/demo.cjs']),
/凭据/,
);
assert.equal(f.store.usage().calls, 0);
});
test('changing a conversation selection only changes the next request, not the running turn',async t=>{
const f=await managementFixture(t),cookie=await f.login(),list=await(await f.call('/assistant/providers',provider(),cookie)).json(),p=list.providers.find(p=>p.name==='Fixture OpenAI');await f.call('/assistant/providers/default',{version:list.version,providerId:p.id,modelId:'model-a'},cookie);f.store.saveSettings({version:f.store.settings().version,enabled:true,runtimePath:process.execPath,allowActions:false});let release,started;f.assistant.runtime.chat=async input=>{started=input.config.model;return new Promise(r=>release=()=>r(JSON.stringify({reply:'done',actions:[]})));};const c=await(await f.call('/assistant/conversations',{},cookie)).json(),turn=await(await f.call('/assistant/conversations/'+c.id+'/messages',{text:'pending'},cookie)).json();await new Promise(r=>setImmediate(r));const current=f.store.conversation(c.id,f.users.users().find(u=>u.username==='admin').id);assert.equal((await f.call('/assistant/conversations/'+c.id+'/model',{version:current.version,providerId:p.id,modelId:'model-b'},cookie)).status,200);assert.equal(started,'model-a');assert.equal((await f.call('/assistant/providers/'+p.id+'/delete',{version:p.version},cookie)).status,409);release();await f.assistant.running.get(turn.id)?.task;assert.equal(f.store.conversation(c.id,f.users.users().find(u=>u.username==='admin').id).turns[0].modelSelection.modelId,'model-a');
test('legacy credentials migrate into the provider vault once and deleting the provider removes the legacy copy', async (t) => {
const f = await managementFixture(t);
f.store.saveSettings({
...f.store.settings(),
apiKey: 'LEGACY_ONLY_PRIVATE_KEY',
enabled: false,
});
const row = f.store.db.prepare('SELECT * FROM config WHERE id=1').get();
assert.equal(f.store.decode('config', row.payload).apiKey, '');
assert.equal(f.store.secretSettings().apiKey, 'LEGACY_ONLY_PRIVATE_KEY');
const legacy = f.store.providers.list().providers.find((p) => p.id === 'deepseek');
f.store.providers.remove(legacy.id, { version: legacy.version });
assert.equal(f.store.secretSettings().apiKey, '');
assert.equal(f.store.settings().hasApiKey, false);
});
test('recycle-bin API cannot act on another owner or refund model usage',async t=>{
const f=await managementFixture(t),admin=await f.login(),viewer=await f.login('viewer'),c=await(await f.call('/assistant/conversations',{},admin)).json();const owner=f.users.users().find(u=>u.username==='admin').id,t1=f.store.beginTurn(c.id,owner,'used');f.store.updateTurn(t1.id,'success',{reply:'done'});const current=f.store.conversation(c.id,owner);
assert.equal((await f.call('/assistant/conversations/'+c.id+'/delete',{version:current.version},viewer)).status,404);const response=await f.call('/assistant/conversations/'+c.id+'/delete',{version:current.version},admin);assert.equal(response.status,200);const removed=await response.json();assert.equal((await f.call('/assistant/conversations/'+c.id,undefined,admin)).status,404);assert.equal((await f.call('/assistant/conversations/'+c.id+'?scope=deleted',undefined,admin)).status,200);assert.equal((await f.call('/assistant/conversations/'+c.id+'/purge',{version:removed.version},admin)).status,400);assert.equal((await f.call('/assistant/conversations/'+c.id+'/purge',{version:removed.version,confirm:'delete'},admin)).status,200);assert.equal(f.store.usage().calls,1);
test('changing a conversation selection only changes the next request, not the running turn', async (t) => {
const f = await managementFixture(t),
cookie = await f.login(),
list = await (await f.call('/assistant/providers', provider(), cookie)).json(),
p = list.providers.find((p) => p.name === 'Fixture OpenAI');
await f.call(
'/assistant/providers/default',
{ version: list.version, providerId: p.id, modelId: 'model-a' },
cookie,
);
f.store.saveSettings({
version: f.store.settings().version,
enabled: true,
runtimePath: process.execPath,
allowActions: false,
});
let release, started;
f.assistant.runtime.chat = async (input) => {
started = input.config.model;
return new Promise((r) => (release = () => r(JSON.stringify({ reply: 'done', actions: [] }))));
};
const c = await (await f.call('/assistant/conversations', {}, cookie)).json(),
turn = await (
await f.call('/assistant/conversations/' + c.id + '/messages', { text: 'pending' }, cookie)
).json();
await new Promise((r) => setImmediate(r));
const current = f.store.conversation(
c.id,
f.users.users().find((u) => u.username === 'admin').id,
);
assert.equal(
(
await f.call(
'/assistant/conversations/' + c.id + '/model',
{ version: current.version, providerId: p.id, modelId: 'model-b' },
cookie,
)
).status,
200,
);
assert.equal(started, 'model-a');
assert.equal(
(await f.call('/assistant/providers/' + p.id + '/delete', { version: p.version }, cookie))
.status,
409,
);
release();
await f.assistant.running.get(turn.id)?.task;
assert.equal(
f.store.conversation(c.id, f.users.users().find((u) => u.username === 'admin').id).turns[0]
.modelSelection.modelId,
'model-a',
);
});
test('deleting a subscribed conversation sends a terminal removed event instead of endless reconnect',async t=>{
const f=await managementFixture(t),cookie=await f.login(),c=await(await f.call('/assistant/conversations',{},cookie)).json(),stream=await f.call('/assistant/conversations/'+c.id+'/stream?after=0',undefined,cookie),reader=stream.body.getReader();await f.call('/assistant/conversations/'+c.id+'/delete',{version:c.version},cookie);let text='';while(true){const {done,value}=await reader.read();if(done)break;text+=new TextDecoder().decode(value);}assert.match(text,/conversation_removed/);
test('recycle-bin API cannot act on another owner or refund model usage', async (t) => {
const f = await managementFixture(t),
admin = await f.login(),
viewer = await f.login('viewer'),
c = await (await f.call('/assistant/conversations', {}, admin)).json();
const owner = f.users.users().find((u) => u.username === 'admin').id,
t1 = f.store.beginTurn(c.id, owner, 'used');
f.store.updateTurn(t1.id, 'success', { reply: 'done' });
const current = f.store.conversation(c.id, owner);
assert.equal(
(
await f.call(
'/assistant/conversations/' + c.id + '/delete',
{ version: current.version },
viewer,
)
).status,
404,
);
const response = await f.call(
'/assistant/conversations/' + c.id + '/delete',
{ version: current.version },
admin,
);
assert.equal(response.status, 200);
const removed = await response.json();
assert.equal((await f.call('/assistant/conversations/' + c.id, undefined, admin)).status, 404);
assert.equal(
(await f.call('/assistant/conversations/' + c.id + '?scope=deleted', undefined, admin)).status,
200,
);
assert.equal(
(
await f.call(
'/assistant/conversations/' + c.id + '/purge',
{ version: removed.version },
admin,
)
).status,
400,
);
assert.equal(
(
await f.call(
'/assistant/conversations/' + c.id + '/purge',
{ version: removed.version, confirm: 'delete' },
admin,
)
).status,
200,
);
assert.equal(f.store.usage().calls, 1);
});
test('an idle subscribed conversation observes model selection changed from another client',{timeout:15000},async t=>{
const f=await managementFixture(t),cookie=await f.login();f.store.saveSettings({...f.store.settings(),apiKey:'TEST_METADATA_STREAM_KEY'});const c=await(await f.call('/assistant/conversations',{},cookie)).json(),stream=await f.call('/assistant/conversations/'+c.id+'/stream?after=0',undefined,cookie),reader=stream.body.getReader();f.store.setModel(c.id,f.users.users().find(u=>u.username==='admin').id,{version:c.version,providerId:'deepseek',modelId:f.store.settings().model});let text='',timer;try{await Promise.race([(async()=>{while(!/conversation_updated/.test(text)||!text.includes('"version":2')){const part=await reader.read();if(part.done)break;text+=new TextDecoder().decode(part.value);}assert.match(text,/conversation_updated/);assert.ok(text.includes('"version":2'));})(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('model update was not published')),3000);})]);}finally{clearTimeout(timer);await reader.cancel();}
test('deleting a subscribed conversation sends a terminal removed event instead of endless reconnect', async (t) => {
const f = await managementFixture(t),
cookie = await f.login(),
c = await (await f.call('/assistant/conversations', {}, cookie)).json(),
stream = await f.call(
'/assistant/conversations/' + c.id + '/stream?after=0',
undefined,
cookie,
),
reader = stream.body.getReader();
await f.call('/assistant/conversations/' + c.id + '/delete', { version: c.version }, cookie);
let text = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
text += new TextDecoder().decode(value);
}
assert.match(text, /conversation_removed/);
});
test(
'an idle subscribed conversation observes model selection changed from another client',
{ timeout: 15000 },
async (t) => {
const f = await managementFixture(t),
cookie = await f.login();
f.store.saveSettings({ ...f.store.settings(), apiKey: 'TEST_METADATA_STREAM_KEY' });
const c = await (await f.call('/assistant/conversations', {}, cookie)).json(),
stream = await f.call(
'/assistant/conversations/' + c.id + '/stream?after=0',
undefined,
cookie,
),
reader = stream.body.getReader();
f.store.setModel(c.id, f.users.users().find((u) => u.username === 'admin').id, {
version: c.version,
providerId: 'deepseek',
modelId: f.store.settings().model,
});
let text = '',
timer;
try {
await Promise.race([
(async () => {
while (!/conversation_updated/.test(text) || !text.includes('"version":2')) {
const part = await reader.read();
if (part.done) break;
text += new TextDecoder().decode(part.value);
}
assert.match(text, /conversation_updated/);
assert.ok(text.includes('"version":2'));
})(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(Error('model update was not published')), 3000);
}),
]);
} finally {
clearTimeout(timer);
await reader.cancel();
}
},
);
+328 -12
View File
@@ -1,13 +1,329 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http');
const adapter=()=>require('../../src/modules/assistant/dsh-runtime.cjs');
const config=(patch={})=>({providerId:'fixture',preset:'custom',protocol:'openai-completions',providerName:'Fixture',apiBase:'https://example.test/v1',apiKey:'TEST_KEY',model:'fixture-model',contextWindow:32768,maxTokens:1024,timeoutSeconds:30,allowActions:false,...patch});
test('resolved unspecified model capacity retains repair budget and clamps small contexts',async t=>{const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-provider-capacity-')),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{ProviderRegistry}=require('../../src/modules/assistant/providers.cjs'),store=new AssistantStore(dir);t.after(async()=>{store.close();await fs.rm(dir,{recursive:true,force:true});});store.secretSettings=()=>({apiBase:'https://api.deepseek.com/anthropic',model:'migrated-legacy',apiKey:'LOCAL_LEGACY_KEY'});store.db.exec('DELETE FROM assistant_providers;DELETE FROM assistant_provider_defaults');const registry=new ProviderRegistry(store),legacy=registry.resolve(),{profilePatch}=adapter(),official=repairMode=>JSON.parse(profilePatch({...legacy,timeoutSeconds:30,repairMode}))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(legacy.maxTokens,32768);assert.equal(official(false).maxTokens,8192);assert.equal(official(true).maxTokens,32768);const row=registry.save({version:0,name:'Native',preset:'custom',protocol:'openai-completions',apiBase:'https://example.test/v1',apiKey:'LOCAL_NATIVE_KEY',enabled:true,models:[{id:'unbounded'},{id:'small',contextWindow:4096},{id:'explicit',contextWindow:65536,maxTokens:1024}]}).providers.find(p=>p.id!=='deepseek');for(const [modelId,capacity] of [['unbounded',32768],['small',4096],['explicit',1024]]){const selected=registry.resolve({providerId:row.id,modelId});assert.equal(selected.maxTokens,capacity);const native=JSON.parse(profilePatch({...selected,timeoutSeconds:30,repairMode:true}))[0].insert.find(p=>p.id==='llm-selected').config.providers['order-assistant-selected'];assert.equal(native.models[0].maxTokens,capacity);}});
test('selected DeepSeek official adapter honors configured caps while old config keeps legacy defaults',()=>{const {profilePatch}=adapter(),selected=JSON.parse(profilePatch(config({preset:'deepseek',protocol:'anthropic-messages'})))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(selected.maxTokens,1024);assert.equal(selected.defaultContextWindow,32768);const old=JSON.parse(profilePatch({apiBase:'https://api.deepseek.com/anthropic',model:'legacy',timeoutSeconds:30}))[0].insert.find(p=>p.id==='llm-deepseek').config;assert.equal(old.maxTokens,8192);assert.equal(old.defaultContextWindow,131072);});
test('selected profiles mount only chosen native protocol with private explicit credential',()=>{const {profilePatch,environment}=adapter();for(const protocol of ['openai-completions','openai-responses','anthropic-messages']){const selected=config({protocol}),patch=profilePatch(selected);assert.match(patch,/dsh-llm-pi-ai/);assert.doesNotMatch(patch,/TEST_KEY|dsh-llm-deepseek-api-key|oauth|authorization/i);const rows=JSON.parse(patch)[0].insert,provider=rows.find(p=>p.name==='@deepseek-ai/dsh-llm-pi-ai').config.providers;assert.deepEqual(Object.keys(provider),['order-assistant-selected']);assert.equal(provider['order-assistant-selected'].api,protocol);assert.equal(provider['order-assistant-selected'].models.length,1);assert.equal(provider['order-assistant-selected'].models[0].maxTokens,1024);const env=environment('C:/isolated','TEST_KEY',selected);assert.equal(env.ORDER_ASSISTANT_API_KEY,'TEST_KEY');assert.equal(env.DEEPSEEK_API_KEY,undefined);assert.equal(env.OPENAI_API_KEY,undefined);}assert.match(profilePatch(config({preset:'deepseek',protocol:'anthropic-messages'})),/dsh-llm-deepseek-api-key/);});
const output='{"reply":"local provider works","actions":[]}';
function messageSse(){return [{type:'message_start',message:{id:'local',type:'message',role:'assistant',model:'fixture-model',content:[],usage:{input_tokens:3,output_tokens:0}}},{type:'content_block_start',index:0,content_block:{type:'text',text:output}},{type:'content_block_stop',index:0},{type:'message_delta',delta:{stop_reason:'end_turn'},usage:{output_tokens:8}},{type:'message_stop'}].map(e=>`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join('');}
function chatSse(){return [{id:'local',object:'chat.completion.chunk',created:1,model:'fixture-model',choices:[{index:0,delta:{role:'assistant',content:output},finish_reason:null}]},{id:'local',object:'chat.completion.chunk',created:1,model:'fixture-model',choices:[{index:0,delta:{},finish_reason:'stop'}],usage:{prompt_tokens:3,completion_tokens:8,total_tokens:11}}].map(e=>'data: '+JSON.stringify(e)+'\n\n').join('')+'data: [DONE]\n\n';}
function responseSse(){const item={id:'msg_local',type:'message',role:'assistant',status:'completed',content:[{type:'output_text',text:output,annotations:[]}]},response={id:'resp_local',object:'response',created_at:1,model:'fixture-model',status:'completed',output:[item],usage:{input_tokens:3,output_tokens:8,total_tokens:11}};return [{type:'response.created',response:{...response,status:'in_progress',output:[]}},{type:'response.output_item.added',output_index:0,item:{...item,status:'in_progress',content:[]}},{type:'response.content_part.added',item_id:item.id,output_index:0,content_index:0,part:{type:'output_text',text:'',annotations:[]}},{type:'response.output_text.delta',item_id:item.id,output_index:0,content_index:0,delta:output},{type:'response.output_text.done',item_id:item.id,output_index:0,content_index:0,text:output},{type:'response.output_item.done',output_index:0,item},{type:'response.completed',response}].map((e,i)=>`event: ${e.type}\ndata: ${JSON.stringify({...e,sequence_number:i})}\n\n`).join('');}
for(const protocol of ['openai-completions','openai-responses','anthropic-messages'])test('actual pinned DSH '+protocol+' sends only selected key/model without tools',{timeout:90000},async t=>{const {DshRuntime,installedRuntime}=adapter(),entry=installedRuntime();if(!entry)return t.skip('Pinned DSH runtime is not installed');const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-provider-runtime-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));const requests=[];const server=http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{requests.push({url:req.url,headers:req.headers,body:JSON.parse(body)});res.writeHead(200,{'content-type':'text/event-stream'});res.end(protocol==='anthropic-messages'?messageSse():protocol==='openai-responses'?responseSse():chatSse());});});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const runtime=new DshRuntime({stateDir:root}),selected=config({protocol,runtimePath:entry,apiBase:`http://127.0.0.1:${server.address().port}`+(protocol==='anthropic-messages'?'':'/v1')});const old=process.env.OPENAI_API_KEY;process.env.OPENAI_API_KEY='AMBIENT_MUST_NOT_LEAK';try{const answer=await runtime.chat({config:selected,text:'test',history:[],context:{},signal:new AbortController().signal});assert.equal(JSON.parse(answer).reply,'local provider works');}finally{if(old===undefined)delete process.env.OPENAI_API_KEY;else process.env.OPENAI_API_KEY=old;}assert.equal(requests.length,1);assert.equal(new URL(requests[0].url,'http://local.test').pathname,protocol==='anthropic-messages'?'/v1/messages':protocol==='openai-responses'?'/v1/responses':'/v1/chat/completions');assert.equal(requests[0].body.model,'fixture-model');assert.equal(requests[0].body.max_tokens??requests[0].body.max_completion_tokens??requests[0].body.max_output_tokens,1024);assert.deepEqual(requests[0].body.tools??[],[]);assert.equal(requests[0].headers[protocol==='anthropic-messages'?'x-api-key':'authorization'],protocol==='anthropic-messages'?'TEST_KEY':'Bearer TEST_KEY');assert.equal(JSON.stringify(requests).includes('AMBIENT_MUST_NOT_LEAK'),false);assert.deepEqual(await fs.readdir(runtime.runs),[]);});
test('native selected stream cancellation cleans private profile',{timeout:90000},async t=>{const {DshRuntime,installedRuntime}=adapter(),entry=installedRuntime();if(!entry)return t.skip('Pinned DSH runtime is not installed');const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-provider-cancel-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));const controller=new AbortController();let requested;const arrived=new Promise(r=>requested=r);const server=http.createServer((req,res)=>{res.writeHead(200,{'content-type':'text/event-stream'});res.write('data: {"id":"local","object":"chat.completion.chunk","choices":[]}\n\n');requested();});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>{server.closeAllConnections();server.close(r);}));const runtime=new DshRuntime({stateDir:root});const pending=runtime.chat({config:config({runtimePath:entry,apiBase:`http://127.0.0.1:${server.address().port}/v1`}),text:'test',context:{},signal:controller.signal});await arrived;controller.abort();await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(runtime.runs),[]);});
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path'),
http = require('node:http');
const adapter = () => require('../../src/modules/assistant/dsh-runtime.cjs');
const config = (patch = {}) => ({
providerId: 'fixture',
preset: 'custom',
protocol: 'openai-completions',
providerName: 'Fixture',
apiBase: 'https://example.test/v1',
apiKey: 'TEST_KEY',
model: 'fixture-model',
contextWindow: 32768,
maxTokens: 1024,
timeoutSeconds: 30,
allowActions: false,
...patch,
});
test('resolved unspecified model capacity retains repair budget and clamps small contexts', async (t) => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-provider-capacity-')),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ ProviderRegistry } = require('../../src/modules/assistant/providers.cjs'),
store = new AssistantStore(dir);
t.after(async () => {
store.close();
await fs.rm(dir, { recursive: true, force: true });
});
store.secretSettings = () => ({
apiBase: 'https://api.deepseek.com/anthropic',
model: 'migrated-legacy',
apiKey: 'LOCAL_LEGACY_KEY',
});
store.db.exec('DELETE FROM assistant_providers;DELETE FROM assistant_provider_defaults');
const registry = new ProviderRegistry(store),
legacy = registry.resolve(),
{ profilePatch } = adapter(),
official = (repairMode) =>
JSON.parse(profilePatch({ ...legacy, timeoutSeconds: 30, repairMode }))[0].insert.find(
(p) => p.id === 'llm-deepseek',
).config;
assert.equal(legacy.maxTokens, 32768);
assert.equal(official(false).maxTokens, 8192);
assert.equal(official(true).maxTokens, 32768);
const row = registry
.save({
version: 0,
name: 'Native',
preset: 'custom',
protocol: 'openai-completions',
apiBase: 'https://example.test/v1',
apiKey: 'LOCAL_NATIVE_KEY',
enabled: true,
models: [
{ id: 'unbounded' },
{ id: 'small', contextWindow: 4096 },
{ id: 'explicit', contextWindow: 65536, maxTokens: 1024 },
],
})
.providers.find((p) => p.id !== 'deepseek');
for (const [modelId, capacity] of [
['unbounded', 32768],
['small', 4096],
['explicit', 1024],
]) {
const selected = registry.resolve({ providerId: row.id, modelId });
assert.equal(selected.maxTokens, capacity);
const native = JSON.parse(
profilePatch({ ...selected, timeoutSeconds: 30, repairMode: true }),
)[0].insert.find((p) => p.id === 'llm-selected').config.providers['order-assistant-selected'];
assert.equal(native.models[0].maxTokens, capacity);
}
});
test('selected DeepSeek official adapter honors configured caps while old config keeps legacy defaults', () => {
const { profilePatch } = adapter(),
selected = JSON.parse(
profilePatch(config({ preset: 'deepseek', protocol: 'anthropic-messages' })),
)[0].insert.find((p) => p.id === 'llm-deepseek').config;
assert.equal(selected.maxTokens, 1024);
assert.equal(selected.defaultContextWindow, 32768);
const old = JSON.parse(
profilePatch({
apiBase: 'https://api.deepseek.com/anthropic',
model: 'legacy',
timeoutSeconds: 30,
}),
)[0].insert.find((p) => p.id === 'llm-deepseek').config;
assert.equal(old.maxTokens, 8192);
assert.equal(old.defaultContextWindow, 131072);
});
test('selected profiles mount only chosen native protocol with private explicit credential', () => {
const { profilePatch, environment } = adapter();
for (const protocol of ['openai-completions', 'openai-responses', 'anthropic-messages']) {
const selected = config({ protocol }),
patch = profilePatch(selected);
assert.match(patch, /dsh-llm-pi-ai/);
assert.doesNotMatch(patch, /TEST_KEY|dsh-llm-deepseek-api-key|oauth|authorization/i);
const rows = JSON.parse(patch)[0].insert,
provider = rows.find((p) => p.name === '@deepseek-ai/dsh-llm-pi-ai').config.providers;
assert.deepEqual(Object.keys(provider), ['order-assistant-selected']);
assert.equal(provider['order-assistant-selected'].api, protocol);
assert.equal(provider['order-assistant-selected'].models.length, 1);
assert.equal(provider['order-assistant-selected'].models[0].maxTokens, 1024);
const env = environment('C:/isolated', 'TEST_KEY', selected);
assert.equal(env.ORDER_ASSISTANT_API_KEY, 'TEST_KEY');
assert.equal(env.DEEPSEEK_API_KEY, undefined);
assert.equal(env.OPENAI_API_KEY, undefined);
}
assert.match(
profilePatch(config({ preset: 'deepseek', protocol: 'anthropic-messages' })),
/dsh-llm-deepseek-api-key/,
);
});
const output = '{"reply":"local provider works","actions":[]}';
function messageSse() {
return [
{
type: 'message_start',
message: {
id: 'local',
type: 'message',
role: 'assistant',
model: 'fixture-model',
content: [],
usage: { input_tokens: 3, output_tokens: 0 },
},
},
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: output } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 8 } },
{ type: 'message_stop' },
]
.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`)
.join('');
}
function chatSse() {
return (
[
{
id: 'local',
object: 'chat.completion.chunk',
created: 1,
model: 'fixture-model',
choices: [{ index: 0, delta: { role: 'assistant', content: output }, finish_reason: null }],
},
{
id: 'local',
object: 'chat.completion.chunk',
created: 1,
model: 'fixture-model',
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
usage: { prompt_tokens: 3, completion_tokens: 8, total_tokens: 11 },
},
]
.map((e) => 'data: ' + JSON.stringify(e) + '\n\n')
.join('') + 'data: [DONE]\n\n'
);
}
function responseSse() {
const item = {
id: 'msg_local',
type: 'message',
role: 'assistant',
status: 'completed',
content: [{ type: 'output_text', text: output, annotations: [] }],
},
response = {
id: 'resp_local',
object: 'response',
created_at: 1,
model: 'fixture-model',
status: 'completed',
output: [item],
usage: { input_tokens: 3, output_tokens: 8, total_tokens: 11 },
};
return [
{ type: 'response.created', response: { ...response, status: 'in_progress', output: [] } },
{
type: 'response.output_item.added',
output_index: 0,
item: { ...item, status: 'in_progress', content: [] },
},
{
type: 'response.content_part.added',
item_id: item.id,
output_index: 0,
content_index: 0,
part: { type: 'output_text', text: '', annotations: [] },
},
{
type: 'response.output_text.delta',
item_id: item.id,
output_index: 0,
content_index: 0,
delta: output,
},
{
type: 'response.output_text.done',
item_id: item.id,
output_index: 0,
content_index: 0,
text: output,
},
{ type: 'response.output_item.done', output_index: 0, item },
{ type: 'response.completed', response },
]
.map((e, i) => `event: ${e.type}\ndata: ${JSON.stringify({ ...e, sequence_number: i })}\n\n`)
.join('');
}
for (const protocol of ['openai-completions', 'openai-responses', 'anthropic-messages'])
test(
'actual pinned DSH ' + protocol + ' sends only selected key/model without tools',
{ timeout: 90000 },
async (t) => {
const { DshRuntime, installedRuntime } = adapter(),
entry = installedRuntime();
if (!entry) return t.skip('Pinned DSH runtime is not installed');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-provider-runtime-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const requests = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
requests.push({ url: req.url, headers: req.headers, body: JSON.parse(body) });
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.end(
protocol === 'anthropic-messages'
? messageSse()
: protocol === 'openai-responses'
? responseSse()
: chatSse(),
);
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => server.close(r)));
const runtime = new DshRuntime({ stateDir: root }),
selected = config({
protocol,
runtimePath: entry,
apiBase:
`http://127.0.0.1:${server.address().port}` +
(protocol === 'anthropic-messages' ? '' : '/v1'),
});
const old = process.env.OPENAI_API_KEY;
process.env.OPENAI_API_KEY = 'AMBIENT_MUST_NOT_LEAK';
try {
const answer = await runtime.chat({
config: selected,
text: 'test',
history: [],
context: {},
signal: new AbortController().signal,
});
assert.equal(JSON.parse(answer).reply, 'local provider works');
} finally {
if (old === undefined) delete process.env.OPENAI_API_KEY;
else process.env.OPENAI_API_KEY = old;
}
assert.equal(requests.length, 1);
assert.equal(
new URL(requests[0].url, 'http://local.test').pathname,
protocol === 'anthropic-messages'
? '/v1/messages'
: protocol === 'openai-responses'
? '/v1/responses'
: '/v1/chat/completions',
);
assert.equal(requests[0].body.model, 'fixture-model');
assert.equal(
requests[0].body.max_tokens ??
requests[0].body.max_completion_tokens ??
requests[0].body.max_output_tokens,
1024,
);
assert.deepEqual(requests[0].body.tools ?? [], []);
assert.equal(
requests[0].headers[protocol === 'anthropic-messages' ? 'x-api-key' : 'authorization'],
protocol === 'anthropic-messages' ? 'TEST_KEY' : 'Bearer TEST_KEY',
);
assert.equal(JSON.stringify(requests).includes('AMBIENT_MUST_NOT_LEAK'), false);
assert.deepEqual(await fs.readdir(runtime.runs), []);
},
);
test(
'native selected stream cancellation cleans private profile',
{ timeout: 90000 },
async (t) => {
const { DshRuntime, installedRuntime } = adapter(),
entry = installedRuntime();
if (!entry) return t.skip('Pinned DSH runtime is not installed');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-provider-cancel-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const controller = new AbortController();
let requested;
const arrived = new Promise((r) => (requested = r));
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.write('data: {"id":"local","object":"chat.completion.chunk","choices":[]}\n\n');
requested();
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(
() =>
new Promise((r) => {
server.closeAllConnections();
server.close(r);
}),
);
const runtime = new DshRuntime({ stateDir: root });
const pending = runtime.chat({
config: config({
runtimePath: entry,
apiBase: `http://127.0.0.1:${server.address().port}/v1`,
}),
text: 'test',
context: {},
signal: controller.signal,
});
await arrived;
controller.abort();
await assert.rejects(pending, (e) => e.status === 499);
assert.deepEqual(await fs.readdir(runtime.runs), []);
},
);
+221 -25
View File
@@ -1,28 +1,224 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict');const {managementFixture}=require('./management-fixture.cjs');
test('assistant settings manage providers and default models without exposing a saved key',{timeout:120000},async t=>{
const {page,open,calls}=await managementFixture(t,{browser:true});await open('#assistant-settings');await page.getByRole('button',{name:'添加供应商',exact:true}).click();await page.getByLabel('供应商类型',{exact:true}).selectOption('openai');await page.getByLabel('供应商名称',{exact:true}).fill('测试供应商');await page.getByLabel('API 根地址',{exact:true}).fill('https://models.example/v1');await page.getByLabel('API 密钥',{exact:true}).fill('TEST_PROVIDER_UI_KEY');await page.getByLabel('模型列表',{exact:true}).fill('test-a|测试模型 A\ntest-b|测试模型 B');await page.getByRole('button',{name:'保存供应商',exact:true}).click();await page.getByText('测试供应商',{exact:true}).waitFor();assert.equal(calls(),0);assert.doesNotMatch(await page.locator('body').innerText(),/TEST_PROVIDER_UI_KEY/);
await page.getByLabel('默认模型',{exact:true}).selectOption({label:'测试供应商 / 测试模型 A'});await page.getByRole('button',{name:'保存默认模型',exact:true}).click();await page.getByText('默认模型已保存。',{exact:true}).waitFor();await page.getByLabel('启用 DSH 对话诊断',{exact:true}).check();await page.getByRole('button',{name:'保存助手设置',exact:true}).click();await require('node:fs/promises').mkdir('output/verification/dsh-providers',{recursive:true});await page.evaluate(()=>scrollTo(0,0));await page.screenshot({path:'output/verification/dsh-providers/settings-desktop.png',fullPage:true});await page.goto(new URL('/#assistant',page.url()).href);await page.getByRole('button',{name:/选择模型/}).click();await page.getByRole('option',{name:'测试模型 B',exact:true}).click();await page.getByLabel('发送给 DSH',{exact:true}).fill('分析当前状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByText('使用模型 test-b',{exact:true}).waitFor();assert.equal(calls(),1);await page.screenshot({path:'output/verification/dsh-providers/assistant-model-selected.png',fullPage:true});await page.setViewportSize({width:390,height:844});await page.screenshot({path:'output/verification/dsh-providers/assistant-mobile.png',fullPage:true});
const { test } = require('node:test'),
assert = require('node:assert/strict');
const { managementFixture } = require('./management-fixture.cjs');
test(
'assistant settings manage providers and default models without exposing a saved key',
{ timeout: 120000 },
async (t) => {
const { page, open, calls } = await managementFixture(t, { browser: true });
await open('#assistant-settings');
await page.getByRole('button', { name: '添加供应商', exact: true }).click();
await page.getByLabel('供应商类型', { exact: true }).selectOption('openai');
await page.getByLabel('供应商名称', { exact: true }).fill('测试供应商');
await page.getByLabel('API 根地址', { exact: true }).fill('https://models.example/v1');
await page.getByLabel('API 密钥', { exact: true }).fill('TEST_PROVIDER_UI_KEY');
await page.getByLabel('模型列表', { exact: true }).fill('test-a|测试模型 A\ntest-b|测试模型 B');
await page.getByRole('button', { name: '保存供应商', exact: true }).click();
await page.getByText('测试供应商', { exact: true }).waitFor();
assert.equal(calls(), 0);
assert.doesNotMatch(await page.locator('body').innerText(), /TEST_PROVIDER_UI_KEY/);
await page
.getByLabel('默认模型', { exact: true })
.selectOption({ label: '测试供应商 / 测试模型 A' });
await page.getByRole('button', { name: '保存默认模型', exact: true }).click();
await page.getByText('默认模型已保存。', { exact: true }).waitFor();
await page.getByRole('button', { name: '保存助手设置', exact: true }).click();
await require('node:fs/promises').mkdir('output/verification/dsh-providers', {
recursive: true,
});
await page.evaluate(() => scrollTo(0, 0));
await page.screenshot({
path: 'output/verification/dsh-providers/settings-desktop.png',
fullPage: true,
});
await page.goto(new URL('/#assistant', page.url()).href);
await page.getByRole('button', { name: /选择模型/ }).click();
await page.getByRole('option', { name: '测试模型 B', exact: true }).click();
await page.getByLabel('发送给 DSH', { exact: true }).fill('分析当前状态');
await page.getByRole('button', { name: '发送', exact: true }).click();
await page.getByText('使用模型 test-b', { exact: true }).waitFor();
assert.equal(calls(), 1);
await page.screenshot({
path: 'output/verification/dsh-providers/assistant-model-selected.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
await page.screenshot({
path: 'output/verification/dsh-providers/assistant-mobile.png',
fullPage: true,
});
},
);
test(
'the tool return button is prominent on desktop and mobile and returns to the tools section',
{ timeout: 90000 },
async (t) => {
const { page, open } = await managementFixture(t, { browser: true });
await open();
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 900 });
const back = page.getByRole('link', { name: '返回工具', exact: true });
await back.waitFor();
const box = await back.boundingBox();
assert.ok(box.height >= 40);
assert.ok(box.width >= 100);
assert.equal(await back.getAttribute('href'), '#tools');
}
await page.getByRole('link', { name: '返回工具', exact: true }).click();
await page.getByRole('navigation', { name: '工具导航' }).waitFor();
assert.equal(await page.locator('.assistant-workspace').count(), 0);
},
);
test(
'opening another provider editor never silently discards an unsaved key or name',
{ timeout: 90000 },
async (t) => {
const { page, open } = await managementFixture(t, { browser: true });
await open('#assistant-settings');
await page.getByRole('button', { name: '添加供应商', exact: true }).click();
await page.getByLabel('供应商名称', { exact: true }).fill('未保存供应商');
await page.getByLabel('API 密钥', { exact: true }).fill('UNSAVED_TEST_KEY');
await page.getByRole('button', { name: '编辑', exact: true }).first().click();
await page.getByRole('dialog', { name: '未保存的修改', exact: true }).waitFor();
await page.getByRole('button', { name: '留在此页', exact: true }).click();
assert.equal(await page.getByLabel('供应商名称', { exact: true }).inputValue(), '未保存供应商');
assert.equal(
await page.getByLabel('API 密钥', { exact: true }).inputValue(),
'UNSAVED_TEST_KEY',
);
},
);
test(
'choosing the first model starts conversation updates and an external trash clears its draft',
{ timeout: 90000 },
async (t) => {
const f = await managementFixture(t, { browser: true }),
{ page, open, store } = f;
store.saveSettings({ ...store.settings(), apiKey: 'TEST_FIRST_MODEL_KEY' });
await open();
await page.getByRole('button', { name: /选择模型/ }).click();
const stream = page.waitForRequest((r) => r.url().includes('/stream?'), { timeout: 5000 });
await page.getByRole('option', { name: 'deepseek-flash', exact: true }).click();
await stream;
await page.getByRole('button', { name: '归档会话', exact: true }).waitFor();
const input = page.getByLabel('发送给 DSH', { exact: true });
await input.fill('UNSENT_DRAFT');
const owner = f.users.users().find((u) => u.username === 'admin').id,
c = store.listConversations(owner).items[0];
store.trash(c.id, owner, { version: store.conversation(c.id, owner).version });
await page.waitForFunction(() => document.querySelector('#assistant-input')?.value === '');
assert.equal(await page.locator('[data-assistant-conversation]').count(), 0);
},
);
test(
'provider save locks mutable fields until its acknowledged response completes',
{ timeout: 90000 },
async (t) => {
const { page, open, store } = await managementFixture(t, { browser: true });
await open('#assistant-settings');
await page.getByRole('button', { name: '添加供应商', exact: true }).click();
await page.getByLabel('供应商名称', { exact: true }).fill('NAME_SUBMITTED');
await page.getByLabel('API 密钥', { exact: true }).fill('TEST_PENDING_PROVIDER_KEY');
let release;
const gate = new Promise((r) => (release = r));
t.after(() => release());
await page.route('**/api/assistant/providers', async (route) => {
if (route.request().method() === 'POST') {
await gate;
await route.continue();
} else await route.continue();
});
const started = page.waitForRequest(
(r) => r.url().endsWith('/providers') && r.method() === 'POST',
);
await page.getByRole('button', { name: '保存供应商', exact: true }).click();
await started;
assert.equal(await page.getByLabel('供应商名称', { exact: true }).isDisabled(), true);
assert.equal(await page.getByLabel('API 密钥', { exact: true }).isDisabled(), true);
release();
await page.getByText('NAME_SUBMITTED', { exact: true }).waitFor();
assert.ok(store.providers.list().providers.some((p) => p.name === 'NAME_SUBMITTED'));
},
);
test('provider cancel asks once before discarding a dirty draft', { timeout: 90000 }, async (t) => {
const { page, open } = await managementFixture(t, { browser: true });
await open('#assistant-settings');
await page.getByRole('button', { name: '添加供应商', exact: true }).click();
await page.getByLabel('供应商名称', { exact: true }).fill('UNSAVED_NAME');
await page.getByRole('button', { name: '取消', exact: true }).click();
await page.getByRole('dialog', { name: '未保存的修改', exact: true }).waitFor();
await page.getByRole('button', { name: '放弃并继续', exact: true }).click();
await page.locator('#provider-edit-form').waitFor({ state: 'hidden' });
assert.equal(await page.getByRole('dialog', { name: '未保存的修改', exact: true }).count(), 0);
});
test('the tool return button is prominent on desktop and mobile and returns to the tools section',{timeout:90000},async t=>{
const {page,open}=await managementFixture(t,{browser:true});await open();for(const width of [1440,390]){await page.setViewportSize({width,height:900});const back=page.getByRole('link',{name:'返回工具',exact:true});await back.waitFor();const box=await back.boundingBox();assert.ok(box.height>=44);assert.ok(box.width>=100);assert.equal(await back.getAttribute('href'),'#tools');}await page.getByRole('link',{name:'返回工具',exact:true}).click();await page.getByRole('navigation',{name:'工具导航'}).waitFor();assert.equal(await page.locator('.assistant-workspace').count(),0);
});
test('opening another provider editor never silently discards an unsaved key or name',{timeout:90000},async t=>{
const {page,open}=await managementFixture(t,{browser:true});await open('#assistant-settings');await page.getByRole('button',{name:'添加供应商',exact:true}).click();await page.getByLabel('供应商名称',{exact:true}).fill('未保存供应商');await page.getByLabel('API 密钥',{exact:true}).fill('UNSAVED_TEST_KEY');await page.getByRole('button',{name:'编辑',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改',exact:true}).waitFor();await page.getByRole('button',{name:'留在此页',exact:true}).click();assert.equal(await page.getByLabel('供应商名称',{exact:true}).inputValue(),'未保存供应商');assert.equal(await page.getByLabel('API 密钥',{exact:true}).inputValue(),'UNSAVED_TEST_KEY');
});
test('choosing the first model starts conversation updates and an external trash clears its draft',{timeout:90000},async t=>{
const f=await managementFixture(t,{browser:true}),{page,open,store}=f;store.saveSettings({...store.settings(),apiKey:'TEST_FIRST_MODEL_KEY'});await open();await page.getByRole('button',{name:/选择模型/}).click();const stream=page.waitForRequest(r=>r.url().includes('/stream?'),{timeout:5000});await page.getByRole('option',{name:'deepseek-flash',exact:true}).click();await stream;await page.getByRole('button',{name:'归档会话',exact:true}).waitFor();const input=page.getByLabel('发送给 DSH',{exact:true});await input.fill('UNSENT_DRAFT');const owner=f.users.users().find(u=>u.username==='admin').id,c=store.listConversations(owner).items[0];store.trash(c.id,owner,{version:store.conversation(c.id,owner).version});await page.waitForFunction(()=>document.querySelector('#assistant-input')?.value==='');assert.equal(await page.locator('[data-assistant-conversation]').count(),0);
});
test('provider save locks mutable fields until its acknowledged response completes',{timeout:90000},async t=>{
const {page,open,store}=await managementFixture(t,{browser:true});await open('#assistant-settings');await page.getByRole('button',{name:'添加供应商',exact:true}).click();await page.getByLabel('供应商名称',{exact:true}).fill('NAME_SUBMITTED');await page.getByLabel('API 密钥',{exact:true}).fill('TEST_PENDING_PROVIDER_KEY');let release;const gate=new Promise(r=>release=r);t.after(()=>release());await page.route('**/api/assistant/providers',async route=>{if(route.request().method()==='POST'){await gate;await route.continue();}else await route.continue();});const started=page.waitForRequest(r=>r.url().endsWith('/providers')&&r.method()==='POST');await page.getByRole('button',{name:'保存供应商',exact:true}).click();await started;assert.equal(await page.getByLabel('供应商名称',{exact:true}).isDisabled(),true);assert.equal(await page.getByLabel('API 密钥',{exact:true}).isDisabled(),true);release();await page.getByText('NAME_SUBMITTED',{exact:true}).waitFor();assert.ok(store.providers.list().providers.some(p=>p.name==='NAME_SUBMITTED'));
});
test('provider cancel asks once before discarding a dirty draft',{timeout:90000},async t=>{
const {page,open}=await managementFixture(t,{browser:true});await open('#assistant-settings');await page.getByRole('button',{name:'添加供应商',exact:true}).click();await page.getByLabel('供应商名称',{exact:true}).fill('UNSAVED_NAME');await page.getByRole('button',{name:'取消',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改',exact:true}).waitFor();await page.getByRole('button',{name:'放弃并继续',exact:true}).click();await page.locator('#provider-edit-form').waitFor({state:'hidden'});assert.equal(await page.getByRole('dialog',{name:'未保存的修改',exact:true}).count(),0);
});
test('paused assistant explains why send is unavailable and reuses the model directory',{timeout:90000},async t=>{
const {page,open}=await managementFixture(t,{browser:true});let providerGets=0;
await page.route('**/api/assistant/providers',async route=>{if(route.request().method()==='GET')providerGets++;await route.continue();});
await open();await page.getByRole('button',{name:/选择模型/}).click();await page.getByRole('button',{name:/选择模型/}).press('Escape');await page.getByRole('button',{name:/选择模型/}).click();
assert.equal(providerGets,1);assert.equal(await page.getByRole('button',{name:'发送',exact:true}).isDisabled(),true);
await page.getByRole('link',{name:'启用助手设置',exact:true}).waitFor();assert.match(await page.getByText('助手已暂停',{exact:false}).innerText(),/助手已暂停/);
test(
'configured assistant sends without a separate enable switch and reuses the model directory',
{ timeout: 90000 },
async (t) => {
const { page, open, store } = await managementFixture(t, { browser: true });
store.saveSettings({
...store.settings(),
apiKey: 'TEST_CONFIGURED_ASSISTANT_KEY',
enabled: false,
});
let providerGets = 0;
await page.route('**/api/assistant/providers', async (route) => {
if (route.request().method() === 'GET') providerGets++;
await route.continue();
});
await open();
await page.getByRole('button', { name: /选择模型/ }).click();
await page.getByRole('button', { name: /选择模型/ }).press('Escape');
await page.getByRole('button', { name: /选择模型/ }).click();
await page.getByLabel('发送给 DSH', { exact: true }).fill('已配置可发送');
assert.equal(providerGets, 1);
assert.equal(await page.getByRole('button', { name: '发送', exact: true }).isDisabled(), false);
assert.equal(await page.getByRole('link', { name: '打开助手设置', exact: true }).count(), 0);
},
);
test(
'model directory failure offers an inline retry without losing the composer',
{ timeout: 90000 },
async (t) => {
const { page, open, store } = await managementFixture(t, { browser: true });
store.saveSettings({ ...store.settings(), apiKey: 'TEST_MODEL_DIRECTORY_KEY' });
let attempts = 0;
await page.route('**/api/assistant/providers', async (route) => {
if (route.request().method() === 'GET' && ++attempts === 1)
return route.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ error: '暂时不可用' }),
});
await route.continue();
});
await open();
await page.getByRole('button', { name: '重试加载模型', exact: true }).waitFor();
const input = page.getByLabel('发送给 DSH', { exact: true });
await input.fill('保留这段草稿');
await page.getByRole('button', { name: '重试加载模型', exact: true }).click();
await page.getByRole('option', { name: 'deepseek-flash', exact: true }).waitFor();
assert.equal(await input.inputValue(), '保留这段草稿');
assert.equal(attempts, 2);
},
);
test('conversation list failure offers a retry in place', { timeout: 90000 }, async (t) => {
const { page, open } = await managementFixture(t, { browser: true });
let attempts = 0;
await open();
await page.route('**/api/assistant/conversations**', async (route) => {
if (route.request().method() === 'GET' && ++attempts === 1)
return route.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ error: '暂时不可用' }),
});
await route.continue();
});
await page.getByPlaceholder('搜索会话标题').fill('触发失败');
await page.getByRole('button', { name: '重试加载会话', exact: true }).waitFor();
await page.getByRole('button', { name: '重试加载会话', exact: true }).click();
await page.getByText('没有匹配会话。', { exact: true }).waitFor();
assert.equal(attempts, 2);
});
+359 -15
View File
@@ -1,16 +1,360 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http');
function fixture(t,legacy={apiBase:'https://api.deepseek.com/anthropic',model:'legacy',apiKey:'LEGACY_SECRET'}){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'assistant-providers-'));const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{ProviderRegistry}=require('../../src/modules/assistant/providers.cjs');const store=new AssistantStore(dir);store.secretSettings=()=>({...legacy});if(store.db.prepare("SELECT 1 FROM sqlite_master WHERE name='assistant_providers'").get())store.db.exec('DELETE FROM assistant_providers; DELETE FROM assistant_provider_defaults;');const registry=new ProviderRegistry(store);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,registry,dir};}
const input=(patch={})=>({version:0,name:'Local gateway',preset:'custom',protocol:'openai-completions',apiBase:'https://example.test/v1',apiKey:'CUSTOM_SECRET',enabled:true,models:[{id:'test-model',name:'Test model',contextWindow:32768,maxTokens:1024}],...patch});
test('migrates legacy secret/default once and isolates encrypted provider rows',t=>{const {store,registry,dir}=fixture(t);assert.equal(registry.resolve().model,'legacy');assert.equal(registry.resolve().apiKey,'LEGACY_SECRET');const saved=registry.save(input());assert.ok(saved.providers.find(p=>p.id!=='deepseek'));assert.equal(JSON.stringify(saved).includes('SECRET'),false);const other=saved.providers.find(p=>p.id!=='deepseek');registry.chooseDefault({version:saved.version,providerId:other.id,modelId:'test-model'});registry.syncLegacy({apiBase:'https://api.deepseek.com/anthropic',model:'new-legacy',apiKey:'UPDATED_LEGACY'});assert.equal(registry.resolve().providerId,other.id);assert.equal(registry.resolve({providerId:'deepseek',modelId:'new-legacy'}).apiKey,'UPDATED_LEGACY');assert.equal(store.decode('provider:'+other.id,store.db.prepare('SELECT payload FROM assistant_providers WHERE id=?').get(other.id).payload).apiKey,'CUSTOM_SECRET');for(const f of fs.readdirSync(dir).filter(f=>f.startsWith('assistant.sqlite')))assert.equal(fs.readFileSync(path.join(dir,f)).includes(Buffer.from('CUSTOM_SECRET')),false);});
test('requires fresh key for changed destination/protocol; versions and invalid selections fail',t=>{const {registry}=fixture(t);const row=registry.save(input()).providers.find(p=>p.id!=='deepseek');assert.throws(()=>registry.save(input({...row,version:0,apiKey:''})),e=>e.status===409);assert.throws(()=>registry.save(input({...row,apiBase:'https://changed.test/v1',apiKey:''})));assert.throws(()=>registry.save(input({...row,protocol:'openai-responses',apiKey:''})));const next=registry.save(input({...row,apiKey:''})).providers.find(p=>p.id===row.id);assert.equal(registry.resolve({providerId:row.id,modelId:'test-model'}).apiKey,'CUSTOM_SECRET');assert.throws(()=>registry.resolve({providerId:row.id,modelId:'missing'}),e=>e.status===409);registry.save(input({...next,enabled:false,apiKey:''}));assert.throws(()=>registry.resolve({providerId:row.id,modelId:'test-model'}),e=>e.status===409);assert.throws(()=>registry.save(input({apiBase:'http://outside.test'})));assert.throws(()=>registry.save(input({models:[{id:'x'},{id:'x'}]})));});
test('default guard is independent; deleting chosen provider clears selection',t=>{const {registry}=fixture(t);const first=registry.save(input()),row=first.providers.find(p=>p.id!=='deepseek');registry.chooseDefault({version:first.version,providerId:row.id,modelId:'test-model'});assert.throws(()=>registry.chooseDefault({version:first.version,providerId:'deepseek',modelId:'legacy'}),e=>e.status===409);registry.remove(row.id,{version:row.version});assert.equal(registry.list().defaultSelection,null);assert.throws(()=>registry.resolve(),e=>e.status===409);});
test('migration is one-time: deleted legacy stays deleted after reopening registry',t=>{const {store,registry}=fixture(t);const legacy=registry.list().providers.find(p=>p.id==='deepseek');registry.remove('deepseek',{version:legacy.version});const {ProviderRegistry}=require('../../src/modules/assistant/providers.cjs'),reopened=new ProviderRegistry(store);assert.deepEqual(reopened.list().providers,[]);assert.equal(reopened.list().defaultSelection,null);reopened.syncLegacy({apiBase:'https://api.deepseek.com/anthropic',model:'explicit',apiKey:'KEY'});assert.equal(reopened.list().providers[0].id,'deepseek');assert.equal(reopened.list().defaultSelection,null);});
test('public catalogue reuses installed generated metadata and never exposes auth',t=>{const {registry}=fixture(t);const {installedRuntime}=require('../../src/modules/assistant/dsh-runtime.cjs'),catalog=registry.list().catalog;assert.deepEqual(catalog.protocols,['openai-completions','openai-responses','anthropic-messages']);assert.deepEqual(catalog.presets.map(p=>p.id),['deepseek','openai','anthropic','custom']);if(installedRuntime())assert.ok(catalog.presets.find(p=>p.id==='openai').models.length>0);assert.equal(JSON.stringify(catalog).includes('apiKeyEnv'),false);});
test('legacy recreation preserves version watermark across deletion and registry reopen',t=>{const {store,registry}=fixture(t);let previous=registry.list().providers.find(p=>p.id==='deepseek');for(let i=0;i<3;i++)previous=registry.save({...previous,apiKey:''}).providers.find(p=>p.id==='deepseek');registry.remove('deepseek',{version:previous.version});const {ProviderRegistry}=require('../../src/modules/assistant/providers.cjs'),reopened=new ProviderRegistry(store);const recreated=reopened.syncLegacy({apiBase:'https://api.deepseek.com/anthropic',model:'recreated',apiKey:'NEW_SECRET'}).providers.find(p=>p.id==='deepseek');assert.ok(recreated.version>previous.version);assert.throws(()=>reopened.save({...previous,apiKey:''}),e=>e.status===409);assert.throws(()=>reopened.remove('deepseek',{version:previous.version}),e=>e.status===409);});
test('legacy recreation at provider limit fails atomically',t=>{const {registry}=fixture(t),legacy=registry.list().providers.find(p=>p.id==='deepseek');registry.remove('deepseek',{version:legacy.version});for(let i=0;i<30;i++)registry.save(input({name:'Custom '+i}));const before=registry.list();assert.throws(()=>registry.syncLegacy({model:'overflow',apiKey:'NEW_SECRET'}),e=>e.status===409);assert.equal(registry.list().version,before.version);assert.equal(registry.list().providers.length,30);assert.equal(registry.list().providers.some(p=>p.id==='deepseek'),false);});
test('discovery from deleted legacy incarnation cannot pass after recreation',{timeout:20000},async t=>{let release;const server=http.createServer((req,res)=>{release=()=>res.end(JSON.stringify({data:[{id:'stale-candidate'}]}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>{server.closeAllConnections();server.close(r);}));const apiBase=`http://127.0.0.1:${server.address().port}/anthropic`;const {registry}=fixture(t,{apiBase,model:'legacy',apiKey:'LOCAL_SECRET'}),row=registry.list().providers.find(p=>p.id==='deepseek');const pending=registry.discover('deepseek',{version:row.version});while(!release)await new Promise(r=>setImmediate(r));registry.remove('deepseek',{version:row.version});registry.syncLegacy({apiBase,model:'recreated',apiKey:'RECREATED_SECRET'});release();await assert.rejects(pending,e=>e.status===409);});
test('early rejected discovery promptly cancels error and oversized response bodies',{timeout:20000},async t=>{const {registry}=fixture(t);let mode='large',closed=false;const server=http.createServer((req,res)=>{closed=false;res.on('close',()=>closed=true);res.writeHead(mode==='error'?503:200,{'content-type':'application/json',...(mode==='large'?{'content-length':String(2*1024*1024)}:{})});res.write('{"data":[');});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>{server.closeAllConnections();server.close(r);}));const row=registry.save(input({apiBase:`http://127.0.0.1:${server.address().port}/v1`})).providers.find(p=>p.id!=='deepseek');for(const current of ['large','error']){mode=current;await assert.rejects(registry.discover(row.id,{version:row.version}),e=>e.status===502);await new Promise(r=>setTimeout(r,150));assert.equal(closed,true,current+' response should close immediately after rejection');}});
test('provider/model limits and bounds reject invalid drafts without mutation',t=>{const {registry}=fixture(t);for(const patch of [{models:Array.from({length:101},(_,i)=>({id:'m'+i}))},{models:[{id:'m',maxTokens:0}]},{models:[{id:'m',contextWindow:100,maxTokens:101}]},{apiBase:'https://user:pass@example.test'},{apiKey:'bad\nkey'},{name:'x'.repeat(201)}])assert.throws(()=>registry.save(input(patch)));for(let i=0;i<29;i++)registry.save(input({name:'Provider '+i}));assert.equal(registry.list().providers.length,30);assert.throws(()=>registry.save(input()),e=>e.status===409);});
test('model discovery bounds streamed response and honors explicit cancellation',{timeout:20000},async t=>{const {registry}=fixture(t);let mode='large';const server=http.createServer((req,res)=>{res.writeHead(200,{'content-type':'application/json'});if(mode==='large')res.end('x'.repeat(1024*1024+1));else res.write('{"data":[');});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>{server.closeAllConnections();server.close(r);}));const row=registry.save(input({apiBase:`http://127.0.0.1:${server.address().port}/v1`})).providers.find(p=>p.id!=='deepseek');await assert.rejects(registry.discover(row.id,{version:row.version}),e=>e.status===502);mode='hold';const controller=new AbortController(),pending=registry.discover(row.id,{version:row.version,signal:controller.signal});controller.abort();await assert.rejects(pending,e=>e.status===499);assert.equal(registry.list().providers.find(p=>p.id===row.id).models[0].id,'test-model');});
test('explicit model discovery uses saved provider credentials, never saves, rejects redirect and stale results',{timeout:20000},async t=>{const {registry}=fixture(t);let received,mode='ok',release;const server=http.createServer((req,res)=>{received={url:req.url,headers:req.headers};if(mode==='redirect'){res.writeHead(302,{location:'http://127.0.0.1:1/steal'});return res.end();}if(mode==='hold'){release=()=>{res.setHeader('content-type','application/json');res.end(JSON.stringify({data:[{id:'new'}]}));};return;}res.setHeader('content-type','application/json');res.end(JSON.stringify(mode==='bad'?{oops:[]}:{data:[{id:'new',name:'New',context_window:4096}]}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const row=registry.save(input({apiBase:`http://127.0.0.1:${server.address().port}/v1`})).providers.find(p=>p.id!=='deepseek');const result=await registry.discover(row.id,{version:row.version});assert.deepEqual(result.models,[{id:'new',name:'New',contextWindow:4096}]);assert.equal(received.url,'/v1/models');assert.equal(received.headers.authorization,'Bearer CUSTOM_SECRET');assert.equal(registry.list().providers.find(p=>p.id===row.id).models[0].id,'test-model');mode='redirect';await assert.rejects(registry.discover(row.id,{version:row.version}));mode='bad';await assert.rejects(registry.discover(row.id,{version:row.version}));mode='hold';const pending=registry.discover(row.id,{version:row.version});while(!release)await new Promise(r=>setImmediate(r));registry.save(input({...row,apiKey:''}));release();await assert.rejects(pending,e=>e.status===409);});
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
http = require('node:http');
function fixture(
t,
legacy = {
apiBase: 'https://api.deepseek.com/anthropic',
model: 'legacy',
apiKey: 'LEGACY_SECRET',
},
) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'assistant-providers-'));
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ ProviderRegistry } = require('../../src/modules/assistant/providers.cjs');
const store = new AssistantStore(dir);
store.secretSettings = () => ({ ...legacy });
if (store.db.prepare("SELECT 1 FROM sqlite_master WHERE name='assistant_providers'").get())
store.db.exec('DELETE FROM assistant_providers; DELETE FROM assistant_provider_defaults;');
const registry = new ProviderRegistry(store);
t.after(() => {
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
return { store, registry, dir };
}
const input = (patch = {}) => ({
version: 0,
name: 'Local gateway',
preset: 'custom',
protocol: 'openai-completions',
apiBase: 'https://example.test/v1',
apiKey: 'CUSTOM_SECRET',
enabled: true,
models: [{ id: 'test-model', name: 'Test model', contextWindow: 32768, maxTokens: 1024 }],
...patch,
});
test('migrates legacy secret/default once and isolates encrypted provider rows', (t) => {
const { store, registry, dir } = fixture(t);
assert.equal(registry.resolve().model, 'legacy');
assert.equal(registry.resolve().apiKey, 'LEGACY_SECRET');
const saved = registry.save(input());
assert.ok(saved.providers.find((p) => p.id !== 'deepseek'));
assert.equal(JSON.stringify(saved).includes('SECRET'), false);
const other = saved.providers.find((p) => p.id !== 'deepseek');
registry.chooseDefault({ version: saved.version, providerId: other.id, modelId: 'test-model' });
registry.syncLegacy({
apiBase: 'https://api.deepseek.com/anthropic',
model: 'new-legacy',
apiKey: 'UPDATED_LEGACY',
});
assert.equal(registry.resolve().providerId, other.id);
assert.equal(
registry.resolve({ providerId: 'deepseek', modelId: 'new-legacy' }).apiKey,
'UPDATED_LEGACY',
);
assert.equal(
store.decode(
'provider:' + other.id,
store.db.prepare('SELECT payload FROM assistant_providers WHERE id=?').get(other.id).payload,
).apiKey,
'CUSTOM_SECRET',
);
for (const f of fs.readdirSync(dir).filter((f) => f.startsWith('assistant.sqlite')))
assert.equal(fs.readFileSync(path.join(dir, f)).includes(Buffer.from('CUSTOM_SECRET')), false);
});
test('requires fresh key for changed destination/protocol; versions and invalid selections fail', (t) => {
const { registry } = fixture(t);
const row = registry.save(input()).providers.find((p) => p.id !== 'deepseek');
assert.throws(
() => registry.save(input({ ...row, version: 0, apiKey: '' })),
(e) => e.status === 409,
);
assert.throws(() =>
registry.save(input({ ...row, apiBase: 'https://changed.test/v1', apiKey: '' })),
);
assert.throws(() => registry.save(input({ ...row, protocol: 'openai-responses', apiKey: '' })));
const next = registry.save(input({ ...row, apiKey: '' })).providers.find((p) => p.id === row.id);
assert.equal(
registry.resolve({ providerId: row.id, modelId: 'test-model' }).apiKey,
'CUSTOM_SECRET',
);
assert.throws(
() => registry.resolve({ providerId: row.id, modelId: 'missing' }),
(e) => e.status === 409,
);
registry.save(input({ ...next, enabled: false, apiKey: '' }));
assert.throws(
() => registry.resolve({ providerId: row.id, modelId: 'test-model' }),
(e) => e.status === 409,
);
assert.throws(() => registry.save(input({ apiBase: 'http://outside.test' })));
assert.throws(() => registry.save(input({ models: [{ id: 'x' }, { id: 'x' }] })));
});
test('default guard is independent; deleting chosen provider clears selection', (t) => {
const { registry } = fixture(t);
const first = registry.save(input()),
row = first.providers.find((p) => p.id !== 'deepseek');
registry.chooseDefault({ version: first.version, providerId: row.id, modelId: 'test-model' });
assert.throws(
() =>
registry.chooseDefault({ version: first.version, providerId: 'deepseek', modelId: 'legacy' }),
(e) => e.status === 409,
);
registry.remove(row.id, { version: row.version });
assert.equal(registry.list().defaultSelection, null);
assert.throws(
() => registry.resolve(),
(e) => e.status === 409,
);
});
test('migration is one-time: deleted legacy stays deleted after reopening registry', (t) => {
const { store, registry } = fixture(t);
const legacy = registry.list().providers.find((p) => p.id === 'deepseek');
registry.remove('deepseek', { version: legacy.version });
const { ProviderRegistry } = require('../../src/modules/assistant/providers.cjs'),
reopened = new ProviderRegistry(store);
assert.deepEqual(reopened.list().providers, []);
assert.equal(reopened.list().defaultSelection, null);
reopened.syncLegacy({
apiBase: 'https://api.deepseek.com/anthropic',
model: 'explicit',
apiKey: 'KEY',
});
assert.equal(reopened.list().providers[0].id, 'deepseek');
assert.equal(reopened.list().defaultSelection, null);
});
test('public catalogue reuses installed generated metadata and never exposes auth', (t) => {
const { registry } = fixture(t);
const { installedRuntime } = require('../../src/modules/assistant/dsh-runtime.cjs'),
catalog = registry.list().catalog;
assert.deepEqual(catalog.protocols, [
'openai-completions',
'openai-responses',
'anthropic-messages',
]);
assert.deepEqual(
catalog.presets.map((p) => p.id),
['deepseek', 'openai', 'anthropic', 'custom'],
);
if (installedRuntime())
assert.ok(catalog.presets.find((p) => p.id === 'openai').models.length > 0);
assert.equal(JSON.stringify(catalog).includes('apiKeyEnv'), false);
});
test('legacy recreation preserves version watermark across deletion and registry reopen', (t) => {
const { store, registry } = fixture(t);
let previous = registry.list().providers.find((p) => p.id === 'deepseek');
for (let i = 0; i < 3; i++)
previous = registry
.save({ ...previous, apiKey: '' })
.providers.find((p) => p.id === 'deepseek');
registry.remove('deepseek', { version: previous.version });
const { ProviderRegistry } = require('../../src/modules/assistant/providers.cjs'),
reopened = new ProviderRegistry(store);
const recreated = reopened
.syncLegacy({
apiBase: 'https://api.deepseek.com/anthropic',
model: 'recreated',
apiKey: 'NEW_SECRET',
})
.providers.find((p) => p.id === 'deepseek');
assert.ok(recreated.version > previous.version);
assert.throws(
() => reopened.save({ ...previous, apiKey: '' }),
(e) => e.status === 409,
);
assert.throws(
() => reopened.remove('deepseek', { version: previous.version }),
(e) => e.status === 409,
);
});
test('legacy recreation at provider limit fails atomically', (t) => {
const { registry } = fixture(t),
legacy = registry.list().providers.find((p) => p.id === 'deepseek');
registry.remove('deepseek', { version: legacy.version });
for (let i = 0; i < 30; i++) registry.save(input({ name: 'Custom ' + i }));
const before = registry.list();
assert.throws(
() => registry.syncLegacy({ model: 'overflow', apiKey: 'NEW_SECRET' }),
(e) => e.status === 409,
);
assert.equal(registry.list().version, before.version);
assert.equal(registry.list().providers.length, 30);
assert.equal(
registry.list().providers.some((p) => p.id === 'deepseek'),
false,
);
});
test(
'discovery from deleted legacy incarnation cannot pass after recreation',
{ timeout: 20000 },
async (t) => {
let release;
const server = http.createServer((req, res) => {
release = () => res.end(JSON.stringify({ data: [{ id: 'stale-candidate' }] }));
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(
() =>
new Promise((r) => {
server.closeAllConnections();
server.close(r);
}),
);
const apiBase = `http://127.0.0.1:${server.address().port}/anthropic`;
const { registry } = fixture(t, { apiBase, model: 'legacy', apiKey: 'LOCAL_SECRET' }),
row = registry.list().providers.find((p) => p.id === 'deepseek');
const pending = registry.discover('deepseek', { version: row.version });
while (!release) await new Promise((r) => setImmediate(r));
registry.remove('deepseek', { version: row.version });
registry.syncLegacy({ apiBase, model: 'recreated', apiKey: 'RECREATED_SECRET' });
release();
await assert.rejects(pending, (e) => e.status === 409);
},
);
test(
'early rejected discovery promptly cancels error and oversized response bodies',
{ timeout: 20000 },
async (t) => {
const { registry } = fixture(t);
let mode = 'large',
closed = false;
const server = http.createServer((req, res) => {
closed = false;
res.on('close', () => (closed = true));
res.writeHead(mode === 'error' ? 503 : 200, {
'content-type': 'application/json',
...(mode === 'large' ? { 'content-length': String(2 * 1024 * 1024) } : {}),
});
res.write('{"data":[');
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(
() =>
new Promise((r) => {
server.closeAllConnections();
server.close(r);
}),
);
const row = registry
.save(input({ apiBase: `http://127.0.0.1:${server.address().port}/v1` }))
.providers.find((p) => p.id !== 'deepseek');
for (const current of ['large', 'error']) {
mode = current;
await assert.rejects(
registry.discover(row.id, { version: row.version }),
(e) => e.status === 502,
);
await new Promise((r) => setTimeout(r, 150));
assert.equal(closed, true, current + ' response should close immediately after rejection');
}
},
);
test('provider/model limits and bounds reject invalid drafts without mutation', (t) => {
const { registry } = fixture(t);
for (const patch of [
{ models: Array.from({ length: 101 }, (_, i) => ({ id: 'm' + i })) },
{ models: [{ id: 'm', maxTokens: 0 }] },
{ models: [{ id: 'm', contextWindow: 100, maxTokens: 101 }] },
{ apiBase: 'https://user:pass@example.test' },
{ apiKey: 'bad\nkey' },
{ name: 'x'.repeat(201) },
])
assert.throws(() => registry.save(input(patch)));
for (let i = 0; i < 29; i++) registry.save(input({ name: 'Provider ' + i }));
assert.equal(registry.list().providers.length, 30);
assert.throws(
() => registry.save(input()),
(e) => e.status === 409,
);
});
test(
'model discovery bounds streamed response and honors explicit cancellation',
{ timeout: 20000 },
async (t) => {
const { registry } = fixture(t);
let mode = 'large';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
if (mode === 'large') res.end('x'.repeat(1024 * 1024 + 1));
else res.write('{"data":[');
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(
() =>
new Promise((r) => {
server.closeAllConnections();
server.close(r);
}),
);
const row = registry
.save(input({ apiBase: `http://127.0.0.1:${server.address().port}/v1` }))
.providers.find((p) => p.id !== 'deepseek');
await assert.rejects(
registry.discover(row.id, { version: row.version }),
(e) => e.status === 502,
);
mode = 'hold';
const controller = new AbortController(),
pending = registry.discover(row.id, { version: row.version, signal: controller.signal });
controller.abort();
await assert.rejects(pending, (e) => e.status === 499);
assert.equal(registry.list().providers.find((p) => p.id === row.id).models[0].id, 'test-model');
},
);
test(
'explicit model discovery uses saved provider credentials, never saves, rejects redirect and stale results',
{ timeout: 20000 },
async (t) => {
const { registry } = fixture(t);
let received,
mode = 'ok',
release;
const server = http.createServer((req, res) => {
received = { url: req.url, headers: req.headers };
if (mode === 'redirect') {
res.writeHead(302, { location: 'http://127.0.0.1:1/steal' });
return res.end();
}
if (mode === 'hold') {
release = () => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ data: [{ id: 'new' }] }));
};
return;
}
res.setHeader('content-type', 'application/json');
res.end(
JSON.stringify(
mode === 'bad'
? { oops: [] }
: { data: [{ id: 'new', name: 'New', context_window: 4096 }] },
),
);
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => server.close(r)));
const row = registry
.save(input({ apiBase: `http://127.0.0.1:${server.address().port}/v1` }))
.providers.find((p) => p.id !== 'deepseek');
const result = await registry.discover(row.id, { version: row.version });
assert.deepEqual(result.models, [{ id: 'new', name: 'New', contextWindow: 4096 }]);
assert.equal(received.url, '/v1/models');
assert.equal(received.headers.authorization, 'Bearer CUSTOM_SECRET');
assert.equal(registry.list().providers.find((p) => p.id === row.id).models[0].id, 'test-model');
mode = 'redirect';
await assert.rejects(registry.discover(row.id, { version: row.version }));
mode = 'bad';
await assert.rejects(registry.discover(row.id, { version: row.version }));
mode = 'hold';
const pending = registry.discover(row.id, { version: row.version });
while (!release) await new Promise((r) => setImmediate(r));
registry.save(input({ ...row, apiKey: '' }));
release();
await assert.rejects(pending, (e) => e.status === 409);
},
);
+304 -38
View File
@@ -1,41 +1,307 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{execFileSync}=require('node:child_process');
const {OperationJournal}=require('../../src/modules/assistant/operation-journal.cjs');
const {CodeRepairRunner}=require('../../src/modules/assistant/code-repair.cjs');
function fixture(t,code='process.exit(0)'){
const base=fs.mkdtempSync(path.join(os.tmpdir(),'repair-test-')),repo=path.join(base,'repo'),repairs=path.join(base,'repairs');fs.mkdirSync(repo);fs.mkdirSync(path.join(repo,'src'));fs.writeFileSync(path.join(repo,'src','app.cjs'),'original');
const git=(...args)=>execFileSync('git',['-c','user.name=Test','-c','user.email=test@example.invalid',...args],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();git('init');git('add','.');git('commit','-m','baseline');
const journal=new OperationJournal({file:path.join(base,'audit.sqlite'),secrets:['private-test-secret']});
const runner=new CodeRepairRunner({repoRoot:repo,repairRoot:repairs,journal,validator:{command:process.execPath,args:['-e',code],timeoutMs:1000}});
t.after(()=>{journal.close();fs.rmSync(base,{recursive:true,force:true});});return {base,repo,repairs,git,journal,runner};
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
{ execFileSync } = require('node:child_process');
const { OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
const { CodeRepairRunner } = require('../../src/modules/assistant/code-repair.cjs');
function fixture(t, code = 'process.exit(0)') {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'repair-test-')),
repo = path.join(base, 'repo'),
repairs = path.join(base, 'repairs');
fs.mkdirSync(repo);
fs.mkdirSync(path.join(repo, 'src'));
fs.writeFileSync(path.join(repo, 'src', 'app.cjs'), 'original');
const git = (...args) =>
execFileSync(
'git',
['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', ...args],
{ cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
).trim();
git('init');
git('add', '.');
git('commit', '-m', 'baseline');
const journal = new OperationJournal({
file: path.join(base, 'audit.sqlite'),
secrets: ['private-test-secret'],
});
const runner = new CodeRepairRunner({
repoRoot: repo,
repairRoot: repairs,
journal,
validator: { command: process.execPath, args: ['-e', code], timeoutMs: 1000 },
});
t.after(() => {
journal.close();
fs.rmSync(base, { recursive: true, force: true });
});
return { base, repo, repairs, git, journal, runner };
}
const request={actor:'admin',isAdmin:true,files:[{path:'src/app.cjs',content:'changed'}]};
test('successful validation keeps active checkout untouched and leaves committed proposal',async t=>{const f=fixture(t),baseline=f.git('rev-parse','HEAD'),r=await f.runner.run(request);assert.equal(r.status,'ready_for_review');assert.notEqual(r.resultCommit,baseline);assert.equal(f.git('rev-parse','HEAD'),baseline);assert.equal(fs.readFileSync(path.join(f.repo,'src/app.cjs'),'utf8'),'original');assert.equal(f.git('show',r.resultCommit+':src/app.cjs'),'changed');assert.match(r.diff,/changed/);});
test('failed validation rolls isolated files back and retains proposal evidence',async t=>{const f=fixture(t,'process.exit(2)'),r=await f.runner.run(request);assert.equal(r.status,'rolled_back');assert.equal(fs.readFileSync(path.join(r.worktree,'src/app.cjs'),'utf8'),'original');assert.equal(f.git('show',r.resultCommit+':src/app.cjs'),'changed');assert.equal(f.git('rev-parse',r.branch),r.resultCommit);});
test('rejects traversal, reserved files, credentials and non-admin callers before changes',async t=>{const f=fixture(t);for(const name of ['src/../app.cjs','src/.git/config','src/node_modules/a.js','src/.env','src/output/a.js','package.json','src/CON.js','src/foo:bar.js'])await assert.rejects(f.runner.run({...request,files:[{path:name,content:'x'}]}));await assert.rejects(f.runner.run({...request,isAdmin:false}));assert.equal(f.git('status','--porcelain'),'');});
test('dirty active checkout is rejected',async t=>{const f=fixture(t);fs.writeFileSync(path.join(f.repo,'src/app.cjs'),'unsaved');await assert.rejects(f.runner.run(request),/dirty/i);});
test('journal redacts secrets, enforces actor scope and records restart uncertainty',t=>{const f=fixture(t);f.journal.append({operationId:'one',actor:'alice',step:'repair',status:'running',detail:'token=abc private-test-secret'});f.journal.append({operationId:'two',actor:'bob',step:'repair',status:'done'});assert.equal(f.journal.list({actor:'alice'}).length,1);assert.equal(f.journal.list({actor:'root',isAdmin:true}).length,2);assert.doesNotMatch(JSON.stringify(f.journal.list({actor:'alice'})),/abc|private-test-secret/);f.journal.recoverRunning();assert.equal(f.journal.list({actor:'alice'})[0].status,'needs_review');assert.equal(f.journal.list({actor:'alice'}).length,2);});
test('timeout is uncertain, never falsely reported as rollback',async t=>{const f=fixture(t,'setTimeout(()=>{},10000)'),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');assert.equal(fs.readFileSync(path.join(r.worktree,'src/app.cjs'),'utf8'),'changed');});
test('parallel requests cannot start a second repair',async t=>{const f=fixture(t,'setTimeout(()=>process.exit(0),150)'),pending=f.runner.run(request);await assert.rejects(f.runner.run(request),/already running/);assert.equal((await pending).status,'ready_for_review');});
test('symlink or junction source ancestors cannot be proposed',async t=>{const f=fixture(t),external=path.join(f.base,'external');fs.mkdirSync(external);fs.writeFileSync(path.join(external,'example.js'),'outside');fs.symlinkSync(external,path.join(f.repo,'src','linked'),process.platform==='win32'?'junction':'dir');f.git('add','.');f.git('commit','-m','link');await assert.rejects(f.runner.run({...request,files:[{path:'src/linked/example.js',content:'bad'}]}),/Symlinks/);assert.equal(fs.readFileSync(path.join(external,'example.js'),'utf8'),'outside');});
test('validator tampering with worktree git pointer requires manual review without following it',async t=>{const f=fixture(t,"require('node:fs').unlinkSync('.git');require('node:fs').writeFileSync('.git','gitdir: missing-git')"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');});
test('validator moving HEAD cannot produce a ready result for the original proposal',async t=>{const f=fixture(t,"require('node:child_process').execFileSync('git',['-c','core.hooksPath=/dev/null','reset','--hard','HEAD~1'])"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');});
test('unrelated untracked drafts survive while proposal collision is rejected',async t=>{const f=fixture(t);fs.mkdirSync(path.join(f.repo,'docs'));fs.writeFileSync(path.join(f.repo,'docs/draft.md'),'user draft');assert.equal((await f.runner.run(request)).status,'ready_for_review');assert.equal(fs.readFileSync(path.join(f.repo,'docs/draft.md'),'utf8'),'user draft');await assert.rejects(f.runner.run({...request,files:[{path:'docs/draft.md',content:'overwrite'}]}),/untracked/i);});
test('source reads are bounded tracked allowlisted files with baseline and stale proposals rejected',async t=>{const f=fixture(t),snapshot=f.runner.readSources(['src/app.cjs']);assert.equal(snapshot.baselineCommit,f.git('rev-parse','HEAD'));assert.deepEqual(snapshot.files,[{path:'src/app.cjs',content:'original'}]);fs.writeFileSync(path.join(f.repo,'src/draft.js'),'untracked');assert.throws(()=>f.runner.readSources(['src/draft.js']),/tracked/i);await assert.rejects(f.runner.run({...request,expectedCommit:'0'.repeat(40)}),/stale/i);});
test('source reads do not silently truncate source code',t=>{const f=fixture(t),content='// example\n'.repeat(1000);fs.writeFileSync(path.join(f.repo,'src/app.cjs'),content);f.git('add','.');f.git('commit','-m','long source');assert.equal(f.runner.readSources(['src/app.cjs']).files[0].content,content);});
test('journal prevents rewriting audit history and redacts quoted credentials',t=>{const f=fixture(t);f.journal.append({operationId:'quoted',actor:'alice',step:'test',status:'done',detail:'{"password":"sensitive-value"}'});assert.doesNotMatch(JSON.stringify(f.journal.list({actor:'alice'})),/sensitive-value/);assert.throws(()=>f.journal.db.exec('DELETE FROM operation_events'),/append-only/);assert.throws(()=>f.journal.db.exec("UPDATE operation_events SET actor='bob'"),/append-only/);});
test('timeout terminates validator child and grandchild processes on Windows',{skip:process.platform!=='win32'},async t=>{
const f=fixture(t),receipt=path.join(f.base,'pids.txt');
const grandchild="require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');setInterval(()=>{},1000)";
const child="require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e',"+JSON.stringify(grandchild)+"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)";
f.runner.validator.args=['-e',"require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e',"+JSON.stringify(child)+"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)"];
f.runner.validator.timeoutMs=2000;
t.after(()=>{if(fs.existsSync(receipt))for(const pid of fs.readFileSync(receipt,'utf8').trim().split(/\s+/).map(Number))try{process.kill(pid);}catch{}});
const result=await f.runner.run(request),pids=fs.readFileSync(receipt,'utf8').trim().split(/\s+/).map(Number);assert.equal(pids.length,3);assert.equal(result.status,'needs_review');assert.equal(result.recovery,'manual_review');assert.equal(result.processCleanup.method,'taskkill-tree');assert.equal(result.processCleanup.commandSucceeded,true);assert.equal(result.processCleanup.rootExited,true);assert.ok(fs.existsSync(f.runner.lockPath));for(const pid of pids)assert.throws(()=>process.kill(pid,0),{code:'ESRCH'});
const request = {
actor: 'admin',
isAdmin: true,
files: [{ path: 'src/app.cjs', content: 'changed' }],
};
test('successful validation keeps active checkout untouched and leaves committed proposal', async (t) => {
const f = fixture(t),
baseline = f.git('rev-parse', 'HEAD'),
r = await f.runner.run(request);
assert.equal(r.status, 'ready_for_review');
assert.notEqual(r.resultCommit, baseline);
assert.equal(f.git('rev-parse', 'HEAD'), baseline);
assert.equal(fs.readFileSync(path.join(f.repo, 'src/app.cjs'), 'utf8'), 'original');
assert.equal(f.git('show', r.resultCommit + ':src/app.cjs'), 'changed');
assert.match(r.diff, /changed/);
});
test('failed validation rolls isolated files back and retains proposal evidence', async (t) => {
const f = fixture(t, 'process.exit(2)'),
r = await f.runner.run(request);
assert.equal(r.status, 'rolled_back');
assert.equal(fs.readFileSync(path.join(r.worktree, 'src/app.cjs'), 'utf8'), 'original');
assert.equal(f.git('show', r.resultCommit + ':src/app.cjs'), 'changed');
assert.equal(f.git('rev-parse', r.branch), r.resultCommit);
});
test('rejects traversal, reserved files, credentials and non-admin callers before changes', async (t) => {
const f = fixture(t);
for (const name of [
'src/../app.cjs',
'src/.git/config',
'src/node_modules/a.js',
'src/.env',
'src/output/a.js',
'package.json',
'src/CON.js',
'src/foo:bar.js',
])
await assert.rejects(f.runner.run({ ...request, files: [{ path: name, content: 'x' }] }));
await assert.rejects(f.runner.run({ ...request, isAdmin: false }));
assert.equal(f.git('status', '--porcelain'), '');
});
test('dirty active checkout is rejected', async (t) => {
const f = fixture(t);
fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), 'unsaved');
await assert.rejects(f.runner.run(request), /dirty/i);
});
test('journal redacts secrets, enforces actor scope and records restart uncertainty', (t) => {
const f = fixture(t);
f.journal.append({
operationId: 'one',
actor: 'alice',
step: 'repair',
status: 'running',
detail: 'token=abc private-test-secret',
});
f.journal.append({ operationId: 'two', actor: 'bob', step: 'repair', status: 'done' });
assert.equal(f.journal.list({ actor: 'alice' }).length, 1);
assert.equal(f.journal.list({ actor: 'root', isAdmin: true }).length, 2);
assert.doesNotMatch(
JSON.stringify(f.journal.list({ actor: 'alice' })),
/abc|private-test-secret/,
);
f.journal.recoverRunning();
assert.equal(f.journal.list({ actor: 'alice' })[0].status, 'needs_review');
assert.equal(f.journal.list({ actor: 'alice' }).length, 2);
});
test('timeout is uncertain, never falsely reported as rollback', async (t) => {
const f = fixture(t, 'setTimeout(()=>{},10000)'),
r = await f.runner.run(request);
assert.equal(r.status, 'needs_review');
assert.equal(r.recovery, 'manual_review');
assert.equal(fs.readFileSync(path.join(r.worktree, 'src/app.cjs'), 'utf8'), 'changed');
});
test('parallel requests cannot start a second repair', async (t) => {
const f = fixture(t, 'setTimeout(()=>process.exit(0),150)'),
pending = f.runner.run(request);
await assert.rejects(f.runner.run(request), /already running/);
assert.equal((await pending).status, 'ready_for_review');
});
test('symlink or junction source ancestors cannot be proposed', async (t) => {
const f = fixture(t),
external = path.join(f.base, 'external');
fs.mkdirSync(external);
fs.writeFileSync(path.join(external, 'example.js'), 'outside');
fs.symlinkSync(
external,
path.join(f.repo, 'src', 'linked'),
process.platform === 'win32' ? 'junction' : 'dir',
);
f.git('add', '.');
f.git('commit', '-m', 'link');
await assert.rejects(
f.runner.run({ ...request, files: [{ path: 'src/linked/example.js', content: 'bad' }] }),
/Symlinks/,
);
assert.equal(fs.readFileSync(path.join(external, 'example.js'), 'utf8'), 'outside');
});
test('validator tampering with worktree git pointer requires manual review without following it', async (t) => {
const f = fixture(
t,
"require('node:fs').unlinkSync('.git');require('node:fs').writeFileSync('.git','gitdir: missing-git')",
),
r = await f.runner.run(request);
assert.equal(r.status, 'needs_review');
assert.equal(r.recovery, 'manual_review');
});
test('validator moving HEAD cannot produce a ready result for the original proposal', async (t) => {
const f = fixture(
t,
"require('node:child_process').execFileSync('git',['-c','core.hooksPath=/dev/null','reset','--hard','HEAD~1'])",
),
r = await f.runner.run(request);
assert.equal(r.status, 'needs_review');
assert.equal(r.recovery, 'manual_review');
});
test('unrelated untracked drafts survive while proposal collision is rejected', async (t) => {
const f = fixture(t);
fs.mkdirSync(path.join(f.repo, 'docs'));
fs.writeFileSync(path.join(f.repo, 'docs/draft.md'), 'user draft');
assert.equal((await f.runner.run(request)).status, 'ready_for_review');
assert.equal(fs.readFileSync(path.join(f.repo, 'docs/draft.md'), 'utf8'), 'user draft');
await assert.rejects(
f.runner.run({ ...request, files: [{ path: 'docs/draft.md', content: 'overwrite' }] }),
/untracked/i,
);
});
test('source reads are bounded tracked allowlisted files with baseline and stale proposals rejected', async (t) => {
const f = fixture(t),
snapshot = f.runner.readSources(['src/app.cjs']);
assert.equal(snapshot.baselineCommit, f.git('rev-parse', 'HEAD'));
assert.deepEqual(snapshot.files, [{ path: 'src/app.cjs', content: 'original' }]);
fs.writeFileSync(path.join(f.repo, 'src/draft.js'), 'untracked');
assert.throws(() => f.runner.readSources(['src/draft.js']), /tracked/i);
await assert.rejects(f.runner.run({ ...request, expectedCommit: '0'.repeat(40) }), /stale/i);
});
test('source reads do not silently truncate source code', (t) => {
const f = fixture(t),
content = '// example\n'.repeat(1000);
fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), content);
f.git('add', '.');
f.git('commit', '-m', 'long source');
assert.equal(f.runner.readSources(['src/app.cjs']).files[0].content, content);
});
test('journal prevents rewriting audit history and redacts quoted credentials', (t) => {
const f = fixture(t);
f.journal.append({
operationId: 'quoted',
actor: 'alice',
step: 'test',
status: 'done',
detail: '{"password":"sensitive-value"}',
});
assert.doesNotMatch(JSON.stringify(f.journal.list({ actor: 'alice' })), /sensitive-value/);
assert.throws(() => f.journal.db.exec('DELETE FROM operation_events'), /append-only/);
assert.throws(() => f.journal.db.exec("UPDATE operation_events SET actor='bob'"), /append-only/);
});
test(
'timeout terminates validator child and grandchild processes on Windows',
{ skip: process.platform !== 'win32' },
async (t) => {
const f = fixture(t),
receipt = path.join(f.base, 'pids.txt');
const grandchild =
"require('node:fs').appendFileSync(" +
JSON.stringify(receipt) +
",process.pid+'\\n');setInterval(()=>{},1000)";
const child =
"require('node:fs').appendFileSync(" +
JSON.stringify(receipt) +
",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e'," +
JSON.stringify(grandchild) +
"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)";
f.runner.validator.args = [
'-e',
"require('node:fs').appendFileSync(" +
JSON.stringify(receipt) +
",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e'," +
JSON.stringify(child) +
"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)",
];
f.runner.validator.timeoutMs = 2000;
t.after(() => {
if (fs.existsSync(receipt))
for (const pid of fs.readFileSync(receipt, 'utf8').trim().split(/\s+/).map(Number))
try {
process.kill(pid);
} catch {}
});
const result = await f.runner.run(request),
pids = fs.readFileSync(receipt, 'utf8').trim().split(/\s+/).map(Number);
assert.equal(pids.length, 3);
assert.equal(result.status, 'needs_review');
assert.equal(result.recovery, 'manual_review');
assert.equal(result.processCleanup.method, 'taskkill-tree');
assert.equal(result.processCleanup.commandSucceeded, true);
assert.equal(result.processCleanup.rootExited, true);
assert.ok(fs.existsSync(f.runner.lockPath));
for (const pid of pids) assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' });
},
);
test('validator cannot install rollback hooks unnoticed', async (t) => {
const f = fixture(
t,
"require('node:fs').writeFileSync(require('node:path').join('..','.disabled-hooks','post-checkout'),'#!/bin/sh\\nexit 0\\n')",
),
r = await f.runner.run(request);
assert.equal(r.status, 'needs_review');
assert.ok(fs.existsSync(f.runner.lockPath));
});
test('source requiring redaction is rejected instead of returned as altered complete code', (t) => {
const f = fixture(t);
for (const content of [
'module.exports={password:input.password};',
'const example="private-test-secret";',
]) {
fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), content);
f.git('add', '.');
f.git('commit', '-m', 'source requiring review');
assert.throws(() => f.runner.readSources(['src/app.cjs']), /sensitive|redaction/i);
}
});
test('journal cursor pages older actor-scoped history without overlaps', (t) => {
const f = fixture(t);
for (let i = 0; i < 125; i++) {
f.journal.append({
operationId: 'alice-operation',
actor: 'alice',
step: 'event',
status: 'done',
});
f.journal.append({ operationId: 'bob-operation', actor: 'bob', step: 'event', status: 'done' });
}
const first = f.journal.list({ actor: 'alice' });
assert.equal(first.length, 100);
const beforeId = first.at(-1).id,
second = f.journal.list({ actor: 'alice', operationId: 'alice-operation', beforeId });
assert.equal(second.length, 25);
assert.equal(new Set([...first, ...second].map((row) => row.id)).size, 125);
assert.ok(second.every((row) => row.id < beforeId && row.actor === 'alice'));
assert.deepEqual(f.journal.list({ actor: 'alice', operationId: 'bob-operation', beforeId }), []);
for (const cursor of [0, -1, 1.5, '2', null, NaN, Number.MAX_SAFE_INTEGER + 1])
assert.throws(() => f.journal.list({ actor: 'alice', beforeId: cursor }), /cursor/i);
});
test('repair journal names file changes, Git commit, validation and review steps', async (t) => {
const f = fixture(t),
r = await f.runner.run(request),
steps = f.journal
.list({ actor: request.actor })
.filter((e) => e.operationId === r.operationId)
.map((e) => e.step);
for (const step of ['prepare', 'files_written', 'commit', 'validate', 'review'])
assert(steps.includes(step), step);
});
test('long validation logs retain the final test summary in the audit record', async (t) => {
const f = fixture(t, "console.log('x'.repeat(24000));console.log('FINAL_TEST_SUMMARY passed')"),
r = await f.runner.run(request),
last = f.journal
.list({ actor: request.actor })
.find((e) => e.operationId === r.operationId && e.step === 'review');
assert.match(last.detail, /FINAL_TEST_SUMMARY passed/);
});
test('explicit administrator-selected repository works without global safe-directory configuration', (t) => {
const f = fixture(t);
f.runner.env.GIT_TEST_ASSUME_DIFFERENT_OWNER = '1';
const read = f.runner.readSources(['src/app.cjs']);
assert.equal(read.files[0].content, 'original');
});
test('validator cannot install rollback hooks unnoticed',async t=>{const f=fixture(t,"require('node:fs').writeFileSync(require('node:path').join('..','.disabled-hooks','post-checkout'),'#!/bin/sh\\nexit 0\\n')"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.ok(fs.existsSync(f.runner.lockPath));});
test('source requiring redaction is rejected instead of returned as altered complete code',t=>{const f=fixture(t);for(const content of ['module.exports={password:input.password};','const example="private-test-secret";']){fs.writeFileSync(path.join(f.repo,'src/app.cjs'),content);f.git('add','.');f.git('commit','-m','source requiring review');assert.throws(()=>f.runner.readSources(['src/app.cjs']),/sensitive|redaction/i);}});
test('journal cursor pages older actor-scoped history without overlaps',t=>{const f=fixture(t);for(let i=0;i<125;i++){f.journal.append({operationId:'alice-operation',actor:'alice',step:'event',status:'done'});f.journal.append({operationId:'bob-operation',actor:'bob',step:'event',status:'done'});}const first=f.journal.list({actor:'alice'});assert.equal(first.length,100);const beforeId=first.at(-1).id,second=f.journal.list({actor:'alice',operationId:'alice-operation',beforeId});assert.equal(second.length,25);assert.equal(new Set([...first,...second].map(row=>row.id)).size,125);assert.ok(second.every(row=>row.id<beforeId&&row.actor==='alice'));assert.deepEqual(f.journal.list({actor:'alice',operationId:'bob-operation',beforeId}),[]);for(const cursor of [0,-1,1.5,'2',null,NaN,Number.MAX_SAFE_INTEGER+1])assert.throws(()=>f.journal.list({actor:'alice',beforeId:cursor}),/cursor/i);});
test('repair journal names file changes, Git commit, validation and review steps',async t=>{const f=fixture(t),r=await f.runner.run(request),steps=f.journal.list({actor:request.actor}).filter(e=>e.operationId===r.operationId).map(e=>e.step);for(const step of ['prepare','files_written','commit','validate','review'])assert(steps.includes(step),step);});
test('long validation logs retain the final test summary in the audit record',async t=>{const f=fixture(t,"console.log('x'.repeat(24000));console.log('FINAL_TEST_SUMMARY passed')"),r=await f.runner.run(request),last=f.journal.list({actor:request.actor}).find(e=>e.operationId===r.operationId&&e.step==='review');assert.match(last.detail,/FINAL_TEST_SUMMARY passed/);});
test('explicit administrator-selected repository works without global safe-directory configuration',t=>{const f=fixture(t);f.runner.env.GIT_TEST_ASSUME_DIFFERENT_OWNER='1';const read=f.runner.readSources(['src/app.cjs']);assert.equal(read.files[0].content,'original');});
+78 -21
View File
@@ -1,24 +1,81 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{execFileSync,spawnSync}=require('node:child_process');
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
{ execFileSync, spawnSync } = require('node:child_process');
test('host repair validator runs fixed and changed tests in a foreign-owned isolated checkout',t=>{
const base=fs.mkdtempSync(path.join(os.tmpdir(),'repair-validator-'));
t.after(()=>fs.rmSync(base,{recursive:true,force:true}));
const host=path.join(base,'host'),repo=path.join(base,'repo'),checkout=path.join(base,'checkout'),validator=path.join(host,'src','modules','assistant','repair-validator.cjs');
fs.mkdirSync(path.dirname(validator),{recursive:true});fs.mkdirSync(path.join(repo,'tests'),{recursive:true});
fs.copyFileSync(path.resolve(__dirname,'../../src/modules/assistant/repair-validator.cjs'),validator);
fs.writeFileSync(path.join(host,'package.json'),JSON.stringify({scripts:{'test:business':'node --test --test-concurrency=1 tests/fixed.test.cjs'}}));
const git=(cwd,...args)=>execFileSync('git',['-c','user.name=Test','-c','user.email=test@example.invalid',...args],{cwd,encoding:'utf8',stdio:['ignore','pipe','pipe']});
const receipt=path.join(base,'ran-tests.txt'),testSource=name=>"require('node:test')("+JSON.stringify(name)+",()=>require('node:fs').appendFileSync("+JSON.stringify(receipt)+","+JSON.stringify(name+'\n')+"));";
fs.writeFileSync(path.join(repo,'tests/fixed.test.cjs'),testSource('fixed manifest test'));
git(repo,'init');git(repo,'add','.');git(repo,'commit','-m','baseline');git(repo,'worktree','add','--detach',checkout);
fs.writeFileSync(path.join(checkout,'tests/changed.test.cjs'),testSource('changed repair test'));
git(checkout,'add','.');git(checkout,'commit','-m','proposal');
const env={...process.env,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_TEST_ASSUME_DIFFERENT_OWNER:'1'};
delete env.NODE_TEST_CONTEXT; // Production runner also excludes test-runner internals.
const result=spawnSync(process.execPath,[validator],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.equal(result.status,0,result.stderr);assert.deepEqual(fs.readFileSync(receipt,'utf8').trim().split('\n').sort(),['changed repair test','fixed manifest test']);
// Trust applies to this one invocation; it must not persist globally or locally.
const untrusted=spawnSync('git',['rev-parse','HEAD'],{cwd:checkout,env,encoding:'utf8',windowsHide:true});
assert.notEqual(untrusted.status,0);assert.match(untrusted.stderr,/dubious ownership/);
test('host repair validator runs fixed and changed tests in a foreign-owned isolated checkout', (t) => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), 'repair-validator-'));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const host = path.join(base, 'host'),
repo = path.join(base, 'repo'),
checkout = path.join(base, 'checkout'),
validator = path.join(host, 'src', 'modules', 'assistant', 'repair-validator.cjs');
fs.mkdirSync(path.dirname(validator), { recursive: true });
fs.mkdirSync(path.join(repo, 'tests'), { recursive: true });
fs.copyFileSync(
path.resolve(__dirname, '../../src/modules/assistant/repair-validator.cjs'),
validator,
);
fs.writeFileSync(
path.join(host, 'package.json'),
JSON.stringify({
scripts: { 'test:business': 'node --test --test-concurrency=1 tests/fixed.test.cjs' },
}),
);
const git = (cwd, ...args) =>
execFileSync(
'git',
['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', ...args],
{ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
);
const receipt = path.join(base, 'ran-tests.txt'),
testSource = (name) =>
"require('node:test')(" +
JSON.stringify(name) +
",()=>require('node:fs').appendFileSync(" +
JSON.stringify(receipt) +
',' +
JSON.stringify(name + '\n') +
'));';
fs.writeFileSync(path.join(repo, 'tests/fixed.test.cjs'), testSource('fixed manifest test'));
git(repo, 'init');
git(repo, 'add', '.');
git(repo, 'commit', '-m', 'baseline');
git(repo, 'worktree', 'add', '--detach', checkout);
fs.writeFileSync(
path.join(checkout, 'tests/changed.test.cjs'),
testSource('changed repair test'),
);
git(checkout, 'add', '.');
git(checkout, 'commit', '-m', 'proposal');
const env = {
...process.env,
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null',
GIT_TEST_ASSUME_DIFFERENT_OWNER: '1',
};
delete env.NODE_TEST_CONTEXT; // Production runner also excludes test-runner internals.
const result = spawnSync(process.execPath, [validator], {
cwd: checkout,
env,
encoding: 'utf8',
windowsHide: true,
});
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(fs.readFileSync(receipt, 'utf8').trim().split('\n').sort(), [
'changed repair test',
'fixed manifest test',
]);
// Trust applies to this one invocation; it must not persist globally or locally.
const untrusted = spawnSync('git', ['rev-parse', 'HEAD'], {
cwd: checkout,
env,
encoding: 'utf8',
windowsHide: true,
});
assert.notEqual(untrusted.status, 0);
assert.match(untrusted.stderr, /dubious ownership/);
});
+167
View File
@@ -0,0 +1,167 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs'),
{ NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
async function fixture(t, browser = false) {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser }),
file = path.join(os.tmpdir(), 'task-manager-' + crypto.randomUUID() + '.sqlite');
f.assistant.journal = new OperationJournal({ file });
t.after(() => {
f.assistant.journal.close();
fs.rmSync(file, { force: true });
});
await NativeSchedules.create({ assistant: f.assistant });
return f;
}
test(
'host catalog shows own tasks across sessions and never another owners tasks',
{ timeout: 90000 },
async (t) => {
const f = await fixture(t),
cookie = await f.login(),
other = await f.login('viewer'),
user = f.users.users().find((u) => u.username === 'admin'),
c1 = f.store.create(user.id),
c2 = f.store.create(user.id),
principal = { user, sessionId: 'test-admin' };
for (const c of [c1, c2])
await f.assistant.schedules.createTask(c.id, principal, {
confirm: true,
request: { title: '任务 ' + c.id, prompt: 'check', after_seconds: 3600 },
});
assert.equal((await f.call('/assistant/schedules')).status, 401);
const response = await f.call('/assistant/schedules', undefined, cookie);
assert.equal(response.status, 200);
const result = await response.json();
assert.equal(result.tasks.length, 2);
assert.deepEqual(new Set(result.tasks.map((x) => x.sessionId)), new Set([c1.id, c2.id]));
assert.equal(result.conversations.length, 2);
assert.ok(result.tasks.every((x) => typeof x.conversationTitle === 'string'));
assert.equal(
(await (await f.call('/assistant/schedules', undefined, other)).json()).tasks.length,
0,
);
},
);
test(
'task manager exposes cross-session search detail create edit delete and preserves chat draft',
{ timeout: 90000 },
async (t) => {
const f = await fixture(t, true),
{ page, store, assistant } = f,
user = f.users.users().find((u) => u.username === 'admin'),
c1 = store.create(user.id),
c2 = store.create(user.id),
principal = { user, sessionId: 'test-admin' };
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_TASK_MANAGER_KEY',
});
const t1 = await assistant.schedules.createTask(c1.id, principal, {
confirm: true,
request: { title: '别的会话任务甲', prompt: '甲的提醒内容', after_seconds: 3600 },
});
await assistant.schedules.createTask(c2.id, principal, {
confirm: true,
request: { title: '任务乙', prompt: '乙的提醒内容', after_seconds: 7200 },
});
await f.open();
await page.getByLabel('发送给 DSH', { exact: true }).fill('未发送的原始草稿');
await page.getByRole('button', { name: '定时任务', exact: true }).click();
const manager = page.getByRole('region', { name: '定时任务管理', exact: true });
await manager.waitFor();
await manager
.locator('[data-task-list]')
.getByText('别的会话任务甲', { exact: true })
.waitFor();
await manager.locator('[data-task-list]').getByText('任务乙', { exact: true }).waitFor();
await manager.getByRole('button', { name: '已结束', exact: true }).click();
await manager.getByText('没有匹配的任务', { exact: true }).waitFor();
await manager.getByRole('button', { name: '进行中', exact: true }).click();
await manager.locator('[data-task-list]').getByText('任务乙', { exact: true }).waitFor();
await manager.getByLabel('搜索定时任务', { exact: true }).fill('甲');
await manager
.locator('[data-task-list]')
.getByText('任务乙', { exact: true })
.waitFor({ state: 'hidden' });
await manager.getByRole('button', { name: '查看任务 别的会话任务甲', exact: true }).click();
const details = page.getByRole('dialog', { name: '定时任务详情', exact: true });
await details.getByText(t1.id, { exact: true }).waitFor();
await details.getByText('甲的提醒内容', { exact: true }).waitFor();
await details.getByRole('button', { name: '关闭', exact: true }).click();
await manager.getByRole('button', { name: '编辑任务 别的会话任务甲', exact: true }).click();
let form = page.getByRole('dialog', { name: '编辑定时任务', exact: true });
await form.getByLabel('任务名称', { exact: true }).fill('跨会话改名甲');
await form.getByRole('checkbox').check();
await form.getByRole('button', { name: '确认保存', exact: true }).click();
await manager.locator('[data-task-list]').getByText('跨会话改名甲', { exact: true }).waitFor();
assert.equal((await assistant.schedules.list(c1.id, principal)).tasks[0].title, '跨会话改名甲');
await manager.getByRole('button', { name: '删除任务 跨会话改名甲', exact: true }).click();
await page
.getByRole('dialog', { name: '删除定时任务', exact: true })
.getByRole('button', { name: '确认删除任务', exact: true })
.click();
await manager
.locator('[data-task-list]')
.getByText('跨会话改名甲', { exact: true })
.waitFor({ state: 'hidden' });
await manager.getByLabel('搜索定时任务', { exact: true }).fill('');
await manager.getByRole('button', { name: '新建定时任务', exact: true }).click();
form = page.getByRole('dialog', { name: '新建定时任务', exact: true });
await form.getByLabel('所属会话', { exact: true }).selectOption(c1.id);
await form.getByLabel('任务名称', { exact: true }).fill('面板新建任务');
await form.getByLabel('任务内容', { exact: true }).fill('新任务内容');
await form.getByRole('checkbox').check();
await form.getByRole('button', { name: '确认保存', exact: true }).click();
await manager.locator('[data-task-list]').getByText('面板新建任务', { exact: true }).waitFor();
assert.equal((await assistant.schedules.list(c1.id, principal)).tasks[0].title, '面板新建任务');
await page.route('**/api/assistant/schedules', (r) =>
r.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ error: 'fixture unavailable' }),
}),
);
await manager.getByRole('button', { name: '刷新任务', exact: true }).click();
await manager
.getByRole('status')
.getByText(/任务列表读取失败/)
.waitFor();
assert.equal(
await manager.getByRole('button', { name: '新建定时任务', exact: true }).isDisabled(),
true,
);
assert.equal(
await manager
.getByRole('button', { name: '编辑任务 面板新建任务', exact: true })
.isDisabled(),
true,
);
await manager.locator('[data-task-list]').getByText('面板新建任务', { exact: true }).waitFor();
await page.unroute('**/api/assistant/schedules');
await manager.getByRole('button', { name: '刷新任务', exact: true }).click();
await page.waitForFunction(() => !document.querySelector('[data-task-create]').disabled);
const output = path.resolve(__dirname, '../../output/verification/dsh-schedule-manager');
fs.mkdirSync(output, { recursive: true });
await page.screenshot({ path: path.join(output, 'desktop.png'), fullPage: true });
await page.setViewportSize({ width: 390, height: 844 });
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
await page.screenshot({ path: path.join(output, 'mobile.png'), fullPage: true });
await manager.getByRole('button', { name: '返回对话', exact: true }).click();
assert.equal(
await page.getByLabel('发送给 DSH', { exact: true }).inputValue(),
'未发送的原始草稿',
);
},
);
@@ -0,0 +1,81 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
path = require('node:path'),
os = require('node:os'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs'),
{ NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test(
'AI schedule create/update/delete suggestions require scoped risk review before native changes',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
{ store, assistant } = f,
file = path.join(os.tmpdir(), 'schedule-proposals-' + crypto.randomUUID() + '.sqlite');
assistant.journal = new OperationJournal({ file });
t.after(() => {
assistant.journal.close();
fs.rmSync(file, { force: true });
});
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_SCHEDULE_AI_KEY',
allowActions: false,
});
await NativeSchedules.create({ assistant });
const cookie = await f.login(),
c = await (await f.call('/assistant/conversations', {}, cookie)).json(),
root = '/assistant/conversations/' + c.id;
let targetId = 'current';
for (const [operation, request, status] of [
['create', { title: '提醒测试', prompt: '提醒我核对状态', after_seconds: 3600 }, 'scheduled'],
['update', { title: '修改后的提醒' }, 'schedule_updated'],
['delete', {}, 'schedule_deleted'],
]) {
assistant.runtime.chat = async (input) => {
assert.ok(Array.isArray(input.context.schedules));
return JSON.stringify({
reply: '请审查任务建议。',
actions: [{ kind: 'manage_schedule', operation, targetId, request }],
});
};
const response = await f.call(root + '/messages', { text: '管理定时任务' }, cookie);
assert.equal(response.status, 202);
const turn = await response.json();
await assistant.running.get(turn.id)?.task;
const saved = store.conversation(c.id, f.users.users()[0].id).turns.at(-1);
assert.equal(saved.status, 'success', saved.error);
assert.equal(saved.actions.length, 1);
const action = saved.actions[0],
base = root + '/actions/' + action.id;
assert.equal((await f.call(base + '/execute', {}, cookie)).status, 403);
const reviewResponse = await f.call(base + '/review', {}, cookie);
assert.equal(reviewResponse.status, 200);
const review = await reviewResponse.json();
assert.ok(review.risks.length);
const result = await f.call(
base + '/execute',
{ approvalToken: review.approvalToken },
cookie,
);
assert.equal(result.status, 200);
const value = await result.json();
assert.equal(value.result.status, status);
if (operation === 'create') targetId = value.result.taskId;
assert.equal(
(await f.call(base + '/execute', { approvalToken: review.approvalToken }, cookie)).status,
409,
);
}
assert.equal(
(await assistant.schedules.list(c.id, { user: f.users.users()[0], sessionId: 'x' })).tasks
.length,
0,
);
},
);
+132
View File
@@ -0,0 +1,132 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
path = require('node:path'),
os = require('node:os'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs'),
{ NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test(
'schedule HTTP uses native rules, requires confirmation and protects ownership and update versions',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t),
file = path.join(os.tmpdir(), 'native-http-' + crypto.randomUUID() + '.sqlite');
f.assistant.journal = new OperationJournal({ file });
t.after(() => {
f.assistant.journal.close();
fs.rmSync(file, { force: true });
});
await NativeSchedules.create({ assistant: f.assistant });
const admin = await f.login(),
viewer = await f.login('viewer'),
c = await (await f.call('/assistant/conversations', {}, admin)).json(),
base = '/assistant/conversations/' + c.id + '/schedules';
assert.equal((await f.call(base)).status, 401);
assert.equal((await f.call(base, undefined, viewer)).status, 404);
assert.equal(
(
await f.call(
base,
{ request: { title: '未确认', prompt: '检查', after_seconds: 600 } },
admin,
)
).status,
403,
);
const created = await f.call(
base,
{
confirm: true,
request: {
title: '原生每周提醒',
prompt: '检查状态',
weekly: { time: '09:00:00', time_zone: 'Asia/Shanghai', weekdays: [1, 3, 5] },
},
},
admin,
);
assert.equal(created.status, 201);
const task = await created.json();
assert.equal(task.kind, 'weekly');
let listed = await (await f.call(base, undefined, admin)).json();
assert.equal(listed.tasks.length, 1);
assert.equal(listed.history.length, 0);
assert.equal(
(
await f.call(
base + '/' + task.id + '/update',
{ confirm: true, expected: task, changes: { title: '新标题' } },
admin,
)
).status,
200,
);
assert.equal(
(
await f.call(
base + '/' + task.id + '/update',
{ confirm: true, expected: task, changes: { title: '旧版本修改' } },
admin,
)
).status,
409,
);
assert.equal((await f.call(base + '/' + task.id + '/delete', {}, admin)).status, 403);
assert.equal(
(await f.call(base + '/' + task.id + '/delete', { confirm: true }, admin)).status,
200,
);
listed = await (await f.call(base, undefined, admin)).json();
assert.equal(listed.tasks.length, 0);
await f.call(
base,
{ confirm: true, request: { title: '延续前任务', prompt: '检查', after_seconds: 3600 } },
admin,
);
await f.call('/assistant/conversations/' + c.id + '/continue', { version: c.version }, admin);
assert.equal((await (await f.call(base, undefined, admin)).json()).tasks.length, 0);
const current = await (
await f.call('/assistant/conversations/' + c.id, undefined, admin)
).json();
const trashed = await (
await f.call(
'/assistant/conversations/' + c.id + '/delete',
{ version: current.version },
admin,
)
).json();
f.store.db
.prepare(
'INSERT INTO assistant_schedule_inbox(id,conversation_id,owner,task_id,status,payload,created_at) VALUES(?,?,?,?,?,?,?)',
)
.run(
'purge-test',
c.id,
f.store.db.prepare('SELECT owner FROM conversations WHERE id=?').get(c.id).owner,
'old',
'success',
f.store.encode('schedule-inbox:purge-test', { prompt: 'private prompt' }),
new Date().toISOString(),
);
assert.equal(
(
await f.call(
'/assistant/conversations/' + c.id + '/purge',
{ version: trashed.version, confirm: 'delete' },
admin,
)
).status,
200,
);
assert.equal(
f.store.db
.prepare('SELECT COUNT(*) n FROM assistant_schedule_inbox WHERE conversation_id=?')
.get(c.id).n,
0,
);
},
);
+129
View File
@@ -0,0 +1,129 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
crypto = require('node:crypto');
const { managementFixture } = require('./management-fixture.cjs'),
{ NativeSchedules } = require('../../src/modules/assistant/native-schedules.cjs'),
{ OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs');
test(
'schedule panel creates edits deletes native tasks and shows a due model reply',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true }),
{ page, open, store, assistant } = f,
file = path.join(os.tmpdir(), 'schedule-ui-' + crypto.randomUUID() + '.sqlite');
assistant.journal = new OperationJournal({ file });
t.after(() => {
assistant.journal.close();
fs.rmSync(file, { force: true });
});
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_SCHEDULE_UI_KEY',
});
await NativeSchedules.create({ assistant });
let calls = 0;
assistant.runtime.chat = async () => {
calls++;
return JSON.stringify({ reply: '原生定时提醒的模型回复。', actions: [] });
};
await open();
await page.getByRole('tab', { name: '任务', exact: true }).click();
await page.getByRole('button', { name: '新建定时任务', exact: true }).click();
let dialog = page.getByRole('dialog', { name: '新建定时任务', exact: true });
await dialog.getByLabel('任务名称', { exact: true }).fill('可编辑提醒');
await dialog.getByLabel('任务内容', { exact: true }).fill('提醒我检查状态');
await dialog.getByLabel('延时(秒)', { exact: true }).fill('3600');
assert.equal(
await dialog.getByRole('button', { name: '确认保存', exact: true }).isDisabled(),
true,
);
await dialog
.getByRole('checkbox', {
name: '我确认按此规则定时调用模型,其他操作仍需另行授权',
exact: true,
})
.check();
await dialog.getByRole('button', { name: '确认保存', exact: true }).click();
await page.getByText('可编辑提醒', { exact: true }).waitFor();
assert.equal(calls, 0);
await page.getByRole('button', { name: '编辑任务 可编辑提醒', exact: true }).click();
dialog = page.getByRole('dialog', { name: '编辑定时任务', exact: true });
await dialog.getByLabel('任务名称', { exact: true }).fill('修改后的提醒');
await dialog
.getByRole('checkbox', {
name: '我确认按此规则定时调用模型,其他操作仍需另行授权',
exact: true,
})
.check();
await dialog.getByRole('button', { name: '确认保存', exact: true }).click();
await page.getByText('修改后的提醒', { exact: true }).waitFor();
await page.getByRole('button', { name: '删除任务 修改后的提醒', exact: true }).click();
await page
.getByRole('dialog', { name: '删除定时任务', exact: true })
.getByRole('button', { name: '确认删除任务', exact: true })
.click();
await page.getByText('修改后的提醒', { exact: true }).waitFor({ state: 'hidden' });
const record = assistant.record.bind(assistant);
assistant.record = (id, principal, step, status, detail) => {
if (step === 'schedule_create' && status === 'success')
throw Error('audit failure after native commit');
return record(id, principal, step, status, detail);
};
await page.getByRole('button', { name: '新建定时任务', exact: true }).click();
dialog = page.getByRole('dialog', { name: '新建定时任务', exact: true });
await dialog.getByLabel('任务名称', { exact: true }).fill('未知提交核实');
await dialog.getByLabel('任务内容', { exact: true }).fill('检查状态');
await dialog.getByRole('checkbox').check();
await dialog.getByRole('button', { name: '确认保存', exact: true }).click();
await dialog
.getByRole('alert')
.getByText(/勿重复提交/)
.waitFor();
await dialog.getByRole('checkbox').uncheck();
await dialog.getByRole('checkbox').check();
assert.equal(
await dialog.getByRole('button', { name: '确认保存', exact: true }).isDisabled(),
true,
);
assistant.record = record;
await dialog.getByRole('button', { name: '取消', exact: true }).click();
await page.getByRole('button', { name: '刷新任务', exact: true }).click();
await page.getByText('未知提交核实', { exact: true }).waitFor();
assert.equal(store.db.prepare('SELECT COUNT(*) n FROM assistant_schedule_tasks').get().n, 1);
await page.getByRole('button', { name: '删除任务 未知提交核实', exact: true }).click();
await page.getByRole('button', { name: '确认删除任务', exact: true }).click();
await page.getByText('未知提交核实', { exact: true }).waitFor({ state: 'hidden' });
await page.getByRole('button', { name: '新建定时任务', exact: true }).click();
dialog = page.getByRole('dialog', { name: '新建定时任务', exact: true });
await dialog.getByLabel('任务名称', { exact: true }).fill('短延时提醒');
await dialog.getByLabel('任务内容', { exact: true }).fill('提醒我检查状态');
await dialog.getByLabel('延时(秒)', { exact: true }).fill('1');
await dialog
.getByRole('checkbox', {
name: '我确认按此规则定时调用模型,其他操作仍需另行授权',
exact: true,
})
.check();
await dialog.getByRole('button', { name: '确认保存', exact: true }).click();
await page.getByText('原生定时提醒的模型回复。', { exact: true }).waitFor();
await page.locator('[data-schedule-history]').getByText('已回复', { exact: true }).waitFor();
assert.equal(calls, 1);
const output = path.resolve(__dirname, '../../output/verification/dsh-schedules');
await fs.promises.mkdir(output, { recursive: true });
await page.screenshot({ path: path.join(output, 'desktop.png'), fullPage: true });
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole('button', { name: '右侧栏', exact: true }).click();
await page.getByRole('tab', { name: '任务', exact: true }).click();
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
true,
);
await page.screenshot({ path: path.join(output, 'mobile.png'), fullPage: true });
},
);
@@ -0,0 +1,92 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
path = require('node:path');
const { managementFixture } = require('./management-fixture.cjs');
test(
'toolbar controls align and operation sidebar can collapse from inside on desktop and mobile',
{ timeout: 90000 },
async (t) => {
require('../fixtures/isolated-vault-key.cjs')(t);
const f = await managementFixture(t, { browser: true }),
{ page, open, store, users } = f;
store.saveSettings({
...store.settings(),
runtimePath: process.execPath,
apiKey: 'TEST_UI_LAYOUT_KEY',
});
const row = store.providers.read('deepseek');
store.providers.save({
...row,
models: row.models.map((m) => ({ ...m, name: 'skyworth-deepseek-v4.1-flash' })),
});
const owner = users.users()[0].id,
c = store.create(owner),
turn = store.beginTurn(c.id, owner, '测试查看操作');
store.updateTurn(turn.id, 'success', {
reply: '待确认操作已准备。',
actions: [
{
id: 'layout-fixture',
kind: 'check_storage',
targetId: 'server-fixture',
label: '检查存储连接',
status: 'proposed',
},
],
});
await open();
await page.getByRole('button', { name: '查看操作(1)', exact: true }).waitFor();
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 844 });
await page.getByRole('button', { name: '查看操作(1)', exact: true }).click();
const panel = page.getByRole('complementary', { name: '诊断详情', exact: true });
await panel.waitFor();
const openOutput = path.resolve(__dirname, '../../output/verification/dsh-ui-polish');
await fs.mkdir(openOutput, { recursive: true });
await page.screenshot({
path: path.join(openOutput, 'sidebar-open-' + width + '.png'),
fullPage: true,
});
await panel.getByRole('button', { name: '收起右侧栏', exact: true }).click();
await panel.waitFor({ state: 'hidden' });
const toggle = page.getByRole('button', { name: '右侧栏', exact: true });
assert.equal(await toggle.getAttribute('aria-expanded'), 'false');
await toggle.click();
await panel.waitFor();
await panel.getByRole('button', { name: '收起右侧栏', exact: true }).click();
const dimensions = await page.evaluate(() => {
const sizes = (selectors) =>
selectors.map((s) => document.querySelector(s).getBoundingClientRect().height);
return {
bottom: sizes([
'#assistant-attach',
'#assistant-commands',
'#assistant-model-picker',
'#assistant-send',
]),
top: sizes(['[data-aw-left]', '.aw-back', '[data-aw-right]']),
rightLabel: document.querySelector('[data-aw-right]').textContent.trim(),
};
});
assert.ok(
Math.max(...dimensions.bottom) - Math.min(...dimensions.bottom) <= 1,
JSON.stringify(dimensions),
);
assert.ok(
Math.max(...dimensions.top) - Math.min(...dimensions.top) <= 1,
JSON.stringify(dimensions),
);
assert.equal(dimensions.rightLabel, '');
assert.equal(await page.locator('.aw-back svg').count(), 1);
assert.equal(await toggle.locator('svg').count(), 1);
const output = path.resolve(__dirname, '../../output/verification/dsh-ui-polish');
await fs.mkdir(output, { recursive: true });
await page.screenshot({
path: path.join(output, 'workspace-' + width + '.png'),
fullPage: true,
});
}
},
);
+112
View File
@@ -0,0 +1,112 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
http = require('node:http'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path'),
{ createCanvas } = require('@napi-rs/canvas');
const { chatSse, messageSse, responseSse } = require('../fixtures/provider-streams.cjs');
for (const variant of [
{ protocol: 'openai-completions' },
{ protocol: 'openai-responses' },
{ protocol: 'anthropic-messages' },
{ protocol: 'anthropic-messages', preset: 'deepseek' },
])
test(
'official DSH sends actual image blocks through ' +
(variant.preset || 'native') +
' ' +
variant.protocol +
' without native tools',
{ timeout: 90000 },
async (t) => {
const protocol = variant.protocol;
require('../fixtures/isolated-vault-key.cjs')(t);
const {
DshRuntime,
installedRuntime,
} = require('../../src/modules/assistant/dsh-runtime.cjs'),
entry = installedRuntime();
if (!entry) return t.skip('Pinned runtime absent');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vision-runtime-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const bytes = createCanvas(10, 10).toBuffer('image/png'),
images = [{ name: 'picture.png', mediaType: 'image/png', data: bytes.toString('base64') }],
requests = [];
const server = http.createServer((req, res) => {
let text = '';
req.on('data', (c) => (text += c));
req.on('end', () => {
requests.push({ url: req.url, headers: req.headers, body: JSON.parse(text) });
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.end(
protocol === 'anthropic-messages'
? messageSse()
: protocol === 'openai-responses'
? responseSse()
: chatSse(),
);
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => server.close(r)));
const runtime = new DshRuntime({ stateDir: root }),
config = {
runtimePath: entry,
preset: variant.preset || 'custom',
providerName: 'Vision fixture',
protocol,
apiBase:
'http://127.0.0.1:' +
server.address().port +
(variant.preset === 'deepseek'
? '/anthropic'
: protocol === 'anthropic-messages'
? ''
: '/v1'),
apiKey: 'REAL_VISION_KEY',
model: 'fixture-model',
inputModalities: ['text', 'image'],
timeoutSeconds: 30,
allowActions: false,
};
const answer = await runtime.chat({
config,
images,
text: '分析图片',
context: { attachments: [{ name: 'picture.png', kind: 'image' }] },
history: [],
signal: new AbortController().signal,
});
assert.equal(JSON.parse(answer).reply, 'local provider works');
assert.equal(requests.length, 1);
const body = requests[0].body,
blocks = (protocol === 'openai-responses' ? body.input : body.messages)
.filter((m) => m.role === 'user')
.at(-1).content;
assert.ok(
blocks.some(
(b) =>
b.type ===
(protocol === 'anthropic-messages'
? 'image'
: protocol === 'openai-responses'
? 'input_image'
: 'image_url'),
),
);
assert.equal(
blocks
.filter((b) => b.type === 'text' || b.type === 'input_text')
.some((b) => b.text.includes(images[0].data)),
false,
);
assert.deepEqual(body.tools || [], []);
assert.equal(
requests[0].headers[protocol === 'anthropic-messages' ? 'x-api-key' : 'authorization'],
protocol === 'anthropic-messages' ? 'REAL_VISION_KEY' : 'Bearer REAL_VISION_KEY',
);
assert.deepEqual(await fs.readdir(runtime.runs), []);
},
);
+154
View File
@@ -0,0 +1,154 @@
'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
http = require('node:http');
const { injectImages, startBridge } = require('../../src/modules/assistant/vision-transport.cjs');
const image = {
name: 'pixel.png',
mediaType: 'image/png',
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aN00AAAAASUVORK5CYII=',
};
test('image blocks use each selected protocol rather than embedding base64 in text', () => {
const chat = injectImages(
'openai-completions',
{ messages: [{ role: 'user', content: '请看图' }] },
[image],
);
assert.equal(chat.messages[0].content[1].type, 'image_url');
assert.equal(chat.messages[0].content[1].image_url.url, 'data:image/png;base64,' + image.data);
const response = injectImages('openai-responses', { input: '请看图' }, [image]);
assert.equal(response.input[0].content[1].type, 'input_image');
const anthropic = injectImages(
'anthropic-messages',
{ messages: [{ role: 'user', content: [{ type: 'text', text: '请看图' }] }] },
[image],
);
assert.deepEqual(anthropic.messages[0].content[1], {
type: 'image',
source: { type: 'base64', media_type: 'image/png', data: image.data },
});
});
test(
'image bridge restricts model, credential, tools and path; closes after cancellation',
{ timeout: 20000 },
async (t) => {
let received = [];
const upstream = http.createServer((req, res) => {
let data = '';
req.on('data', (c) => (data += c));
req.on('end', () => {
received.push({ url: req.url, auth: req.headers.authorization, body: JSON.parse(data) });
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.end('data: [DONE]\n\n');
});
});
await new Promise((r) => upstream.listen(0, '127.0.0.1', r));
t.after(() => new Promise((r) => upstream.close(r)));
const bridge = await startBridge(
{
apiBase: 'http://127.0.0.1:' + upstream.address().port + '/v1',
protocol: 'openai-completions',
apiKey: 'REAL_UPSTREAM_KEY',
model: 'vision-fixture',
timeoutSeconds: 10,
},
[image],
);
t.after(() => bridge.close());
const request = (body, token = bridge.apiKey, path = '/chat/completions') =>
fetch(bridge.apiBase + path, {
method: 'POST',
headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' },
body: JSON.stringify(body),
});
assert.equal(
(
await request(
{ model: 'vision-fixture', messages: [{ role: 'user', content: 'test' }] },
'wrong',
)
).status,
401,
);
assert.equal((await request({ model: 'other', messages: [] })).status, 400);
assert.equal(
(await request({ model: 'vision-fixture', messages: [], tools: [{ type: 'function' }] }))
.status,
400,
);
assert.equal(
(await request({ model: 'vision-fixture' }, bridge.apiKey, '/elsewhere')).status,
404,
);
assert.equal(received.length, 0);
const response = await request({
model: 'vision-fixture',
messages: [{ role: 'user', content: '看图' }],
tools: [],
});
assert.equal(response.status, 200);
await response.text();
assert.equal(received[0].auth, 'Bearer REAL_UPSTREAM_KEY');
assert.equal(received[0].body.messages[0].content[1].type, 'image_url');
assert.notEqual(bridge.apiKey, 'REAL_UPSTREAM_KEY');
await bridge.close();
await assert.rejects(request({ model: 'vision-fixture' }));
},
);
module.exports = { image };
test(
'aborting a visual turn closes the pending upstream image request',
{ timeout: 15000 },
async (t) => {
const controller = new AbortController();
let closeUpstream;
const upstreamClosed = new Promise((r) => (closeUpstream = r)),
server = http.createServer((req, res) => {
req.resume();
req.on('end', () => {
res.on('close', closeUpstream);
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.write('data: {"pending":true}\n\n');
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => {
server.closeAllConnections();
return new Promise((r) => server.close(r));
});
const bridge = await startBridge(
{
apiBase: 'http://127.0.0.1:' + server.address().port + '/v1',
protocol: 'openai-completions',
apiKey: 'UPSTREAM',
model: 'vision',
timeoutSeconds: 10,
},
[image],
controller.signal,
);
t.after(() => bridge.close());
const response = await fetch(bridge.apiBase + '/chat/completions', {
method: 'POST',
headers: { authorization: 'Bearer ' + bridge.apiKey, 'content-type': 'application/json' },
body: JSON.stringify({ model: 'vision', messages: [{ role: 'user', content: '图像' }] }),
});
const reader = response.body.getReader();
await reader.read();
controller.abort();
let timer;
try {
await Promise.race([
upstreamClosed,
new Promise(
(_, reject) =>
(timer = setTimeout(() => reject(Error('image request did not stop')), 2000)),
),
]);
} finally {
clearTimeout(timer);
await reader.cancel().catch(() => {});
}
await bridge.close();
},
);
+290 -51
View File
@@ -1,59 +1,298 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs');
const principal={user:{id:'alice',username:'alice',role:'admin'}};
function fixture(t,runtime){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workspace-events-')),store=new AssistantStore(dir),service=new AssistantService({store,runtime:runtime||{chat:async()=>'{"reply":"checked","actions":[]}'}});t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,store,service};}
function enable(store){store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://example.test',model:'fixture',apiKey:'PRIVATE_MODEL_KEY',allowActions:false});}
test('durable events are ordered, encrypted, owner scoped, and cursor checked',t=>{
const {store,dir}=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','PRIVATE_QUESTION');
const before=store.eventCursor(c.id,'alice');assert.equal(before,1);
store.stage(turn.id,'model',{phase:'step_start',step:1,text:'PRIVATE_RAW_JSON',path:'C:/PRIVATE_PATH',apiKey:'PRIVATE_MODEL_KEY'});
store.updateTurn(turn.id,'success',{reply:'PRIVATE_REPLY'});
const page=store.events(c.id,'alice',{after:before,limit:1});assert.equal(page.events.length,1);assert.equal(page.hasMore,true);assert.equal(page.nextCursor,before+1);
assert.deepEqual(page.events[0].data,{phase:'step_start',step:1});
const all=store.events(c.id,'alice',{}).events;assert.deepEqual(all.map(e=>e.seq),[1,2,3]);assert.equal(all.at(-1).kind,'completed');assert.equal(store.conversation(c.id,'alice').eventCursor,3);
assert.throws(()=>store.events(c.id,'bob',{}),{status:404});for(const after of [-1,1.5,4,'0'])assert.throws(()=>store.events(c.id,'alice',{after}),{status:400});
for(const name of fs.readdirSync(dir).filter(n=>n.includes('.sqlite')))assert.doesNotMatch(fs.readFileSync(path.join(dir,name)).toString(),/PRIVATE_QUESTION|PRIVATE_REPLY|step_start|PRIVATE_RAW_JSON|PRIVATE_MODEL_KEY/);
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path');
const { AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs');
const principal = { user: { id: 'alice', username: 'alice', role: 'admin' } };
function fixture(t, runtime) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-events-')),
store = new AssistantStore(dir),
service = new AssistantService({
store,
runtime: runtime || { chat: async () => '{"reply":"checked","actions":[]}' },
});
t.after(async () => {
await service.stop();
store.close();
fs.rmSync(dir, { recursive: true, force: true });
});
return { dir, store, service };
}
function enable(store) {
store.saveSettings({
...store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://example.test',
model: 'fixture',
apiKey: 'PRIVATE_MODEL_KEY',
allowActions: false,
});
}
test('durable events are ordered, encrypted, owner scoped, and cursor checked', (t) => {
const { store, dir } = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'PRIVATE_QUESTION');
const before = store.eventCursor(c.id, 'alice');
assert.equal(before, 1);
store.stage(turn.id, 'model', {
phase: 'step_start',
step: 1,
text: 'PRIVATE_RAW_JSON',
path: 'C:/PRIVATE_PATH',
apiKey: 'PRIVATE_MODEL_KEY',
});
store.updateTurn(turn.id, 'success', { reply: 'PRIVATE_REPLY' });
const page = store.events(c.id, 'alice', { after: before, limit: 1 });
assert.equal(page.events.length, 1);
assert.equal(page.hasMore, true);
assert.equal(page.nextCursor, before + 1);
assert.deepEqual(page.events[0].data, { phase: 'step_start', step: 1 });
const all = store.events(c.id, 'alice', {}).events;
assert.deepEqual(
all.map((e) => e.seq),
[1, 2, 3],
);
assert.equal(all.at(-1).kind, 'completed');
assert.equal(store.conversation(c.id, 'alice').eventCursor, 3);
assert.throws(() => store.events(c.id, 'bob', {}), { status: 404 });
for (const after of [-1, 1.5, 4, '0'])
assert.throws(() => store.events(c.id, 'alice', { after }), { status: 400 });
for (const name of fs.readdirSync(dir).filter((n) => n.includes('.sqlite')))
assert.doesNotMatch(
fs.readFileSync(path.join(dir, name)).toString(),
/PRIVATE_QUESTION|PRIVATE_REPLY|step_start|PRIVATE_RAW_JSON|PRIVATE_MODEL_KEY/,
);
});
test('state and events rollback together and terminal slots survive progress flooding',t=>{
const {store}=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','diagnose'),before=store.eventCursor(c.id,'alice');
assert.throws(()=>store.transaction(()=>{store.updateTurn(turn.id,'success',{reply:'rolled back'});throw Error('rollback');}));
assert.equal(store.conversation(c.id,'alice').turns[0].status,'running');assert.equal(store.eventCursor(c.id,'alice'),before);
for(let i=0;i<250;i++)store.stage(turn.id,'model',{phase:'step_start',step:i});
store.stage(turn.id,'cancel_requested');store.updateTurn(turn.id,'cancelled',{finishedAt:new Date().toISOString()});
const events=store.events(c.id,'alice',{limit:100}).events.concat(store.events(c.id,'alice',{after:100}).events);
assert.ok(events.length<=128);assert.equal(events.at(-1).kind,'cancelled');assert.ok(events.some(e=>e.kind==='cancel_requested'));
test('state and events rollback together and terminal slots survive progress flooding', (t) => {
const { store } = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'diagnose'),
before = store.eventCursor(c.id, 'alice');
assert.throws(() =>
store.transaction(() => {
store.updateTurn(turn.id, 'success', { reply: 'rolled back' });
throw Error('rollback');
}),
);
assert.equal(store.conversation(c.id, 'alice').turns[0].status, 'running');
assert.equal(store.eventCursor(c.id, 'alice'), before);
for (let i = 0; i < 250; i++) store.stage(turn.id, 'model', { phase: 'step_start', step: i });
store.stage(turn.id, 'cancel_requested');
store.updateTurn(turn.id, 'cancelled', { finishedAt: new Date().toISOString() });
const events = store
.events(c.id, 'alice', { limit: 100 })
.events.concat(store.events(c.id, 'alice', { after: 100 }).events);
assert.ok(events.length <= 128);
assert.equal(events.at(-1).kind, 'cancelled');
assert.ok(events.some((e) => e.kind === 'cancel_requested'));
});
test('subscribers only see committed events and observer failure cannot roll back state',t=>{
const {store}=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','diagnose'),seen=[];
const unsubscribe=store.subscribe(event=>{seen.push({event,cursor:store.conversation(c.id,'alice').eventCursor});});store.subscribe(()=>{throw Error('offline subscriber');});
assert.throws(()=>store.transaction(()=>{store.stage(turn.id,'model',{phase:'step_start'});assert.equal(seen.length,0);throw Error('rollback');}));assert.equal(seen.length,0);
store.updateTurn(turn.id,'success',{reply:'checked'});assert.equal(seen.length,1);assert.equal(seen[0].event.kind,'completed');assert.equal(seen[0].cursor,seen[0].event.seq);assert.equal(store.conversation(c.id,'alice').turns[0].status,'success');unsubscribe();
test('subscribers only see committed events and observer failure cannot roll back state', (t) => {
const { store } = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'diagnose'),
seen = [];
const unsubscribe = store.subscribe((event) => {
seen.push({ event, cursor: store.conversation(c.id, 'alice').eventCursor });
});
store.subscribe(() => {
throw Error('offline subscriber');
});
assert.throws(() =>
store.transaction(() => {
store.stage(turn.id, 'model', { phase: 'step_start' });
assert.equal(seen.length, 0);
throw Error('rollback');
}),
);
assert.equal(seen.length, 0);
store.updateTurn(turn.id, 'success', { reply: 'checked' });
assert.equal(seen.length, 1);
assert.equal(seen[0].event.kind, 'completed');
assert.equal(seen[0].cursor, seen[0].event.seq);
assert.equal(store.conversation(c.id, 'alice').turns[0].status, 'success');
unsubscribe();
});
test('restart persists interruption and marks unfinished actions needs_review without replay',t=>{
const {store,dir}=fixture(t),c=store.create('alice'),turn=store.beginTurn(c.id,'alice','diagnose');store.updateTurn(turn.id,'running',{actions:[{id:'action-1',status:'running',kind:'scan_bpm'}]});
const reopened=new AssistantStore(dir);try{reopened.recover();reopened.recover();const saved=reopened.conversation(c.id,'alice');assert.equal(saved.turns[0].status,'interrupted');assert.equal(saved.turns[0].actions[0].status,'needs_review');assert.equal(reopened.events(c.id,'alice',{}).events.filter(e=>e.kind==='interrupted').length,1);assert.ok(reopened.events(c.id,'alice',{}).events.some(e=>e.kind==='action_result'&&e.data.status==='needs_review'));}finally{reopened.close();}
test('restart persists interruption and marks unfinished actions needs_review without replay', (t) => {
const { store, dir } = fixture(t),
c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'diagnose');
store.updateTurn(turn.id, 'running', {
actions: [{ id: 'action-1', status: 'running', kind: 'scan_bpm' }],
});
const reopened = new AssistantStore(dir);
try {
reopened.recover();
reopened.recover();
const saved = reopened.conversation(c.id, 'alice');
assert.equal(saved.turns[0].status, 'interrupted');
assert.equal(saved.turns[0].actions[0].status, 'needs_review');
assert.equal(
reopened.events(c.id, 'alice', {}).events.filter((e) => e.kind === 'interrupted').length,
1,
);
assert.ok(
reopened
.events(c.id, 'alice', {})
.events.some((e) => e.kind === 'action_result' && e.data.status === 'needs_review'),
);
} finally {
reopened.close();
}
});
test('request identities deduplicate pending and completed work before busy or quota checks',async t=>{
let release,calls=0,input;const {store,service,dir}=fixture(t,{chat:async value=>{calls++;input=value;value.onEvent?.({kind:'model',data:{phase:'step_start',step:1,secret:'PRIVATE_INTERNAL'}});return new Promise((resolve,reject)=>{release=resolve;value.signal.addEventListener('abort',()=>reject(value.signal.reason),{once:true});});}});service.deps.workspace={snapshot:()=>({connections:[{id:'source-1',owner:'alice',name:'Fixture BPM',status:'connected'}],exceptions:[]})};enable(store);const c=store.create('alice');
const turn=service.send(c.id,principal,'diagnose',{requestId:'request-1',diagnostic:{command:'bpm',targetId:'source-1'}});
assert.equal(service.send(c.id,principal,'diagnose',{requestId:'request-1',diagnostic:{command:'bpm',targetId:'source-1'}}).id,turn.id);
assert.throws(()=>service.send(c.id,principal,'changed',{requestId:'request-1',diagnostic:{command:'bpm',targetId:'source-1'}}),{status:409});
await new Promise(r=>setImmediate(r));release('{"reply":"checked","actions":[]}');await service.running.get(turn.id).task;
assert.equal(calls,1);const saved=store.conversation(c.id,'alice').turns[0];assert.deepEqual(saved.diagnosticSnapshot,input.context);assert.equal(saved.status,'success');assert.equal(service.send(c.id,principal,'diagnose',{requestId:'request-1',diagnostic:{command:'bpm',targetId:'source-1'}}).status,'success');
const reopened=new AssistantStore(dir);try{const resumed=new AssistantService({store:reopened,runtime:{chat:()=>{throw Error('must not call');}}});assert.equal(resumed.send(c.id,principal,'diagnose',{requestId:'request-1',diagnostic:{command:'bpm',targetId:'source-1'}}).id,turn.id);}finally{reopened.close();}
assert.doesNotMatch(JSON.stringify(store.events(c.id,'alice',{})),/PRIVATE_INTERNAL|checked/);
test('request identities deduplicate pending and completed work before busy or quota checks', async (t) => {
let release,
calls = 0,
input;
const { store, service, dir } = fixture(t, {
chat: async (value) => {
calls++;
input = value;
value.onEvent?.({
kind: 'model',
data: { phase: 'step_start', step: 1, secret: 'PRIVATE_INTERNAL' },
});
return new Promise((resolve, reject) => {
release = resolve;
value.signal.addEventListener('abort', () => reject(value.signal.reason), { once: true });
});
},
});
service.deps.workspace = {
snapshot: () => ({
connections: [{ id: 'source-1', owner: 'alice', name: 'Fixture BPM', status: 'connected' }],
exceptions: [],
}),
};
enable(store);
const c = store.create('alice');
const turn = service.send(c.id, principal, 'diagnose', {
requestId: 'request-1',
diagnostic: { command: 'bpm', targetId: 'source-1' },
});
assert.equal(
service.send(c.id, principal, 'diagnose', {
requestId: 'request-1',
diagnostic: { command: 'bpm', targetId: 'source-1' },
}).id,
turn.id,
);
assert.throws(
() =>
service.send(c.id, principal, 'changed', {
requestId: 'request-1',
diagnostic: { command: 'bpm', targetId: 'source-1' },
}),
{ status: 409 },
);
await new Promise((r) => setImmediate(r));
release('{"reply":"checked","actions":[]}');
await service.running.get(turn.id).task;
assert.equal(calls, 1);
const saved = store.conversation(c.id, 'alice').turns[0];
assert.deepEqual(saved.diagnosticSnapshot, input.context);
assert.equal(saved.status, 'success');
assert.equal(
service.send(c.id, principal, 'diagnose', {
requestId: 'request-1',
diagnostic: { command: 'bpm', targetId: 'source-1' },
}).status,
'success',
);
const reopened = new AssistantStore(dir);
try {
const resumed = new AssistantService({
store: reopened,
runtime: {
chat: () => {
throw Error('must not call');
},
},
});
assert.equal(
resumed.send(c.id, principal, 'diagnose', {
requestId: 'request-1',
diagnostic: { command: 'bpm', targetId: 'source-1' },
}).id,
turn.id,
);
} finally {
reopened.close();
}
assert.doesNotMatch(JSON.stringify(store.events(c.id, 'alice', {})), /PRIVATE_INTERNAL|checked/);
});
test('cancellation remains pending until child exit and uncertain stop stays needs_review',async t=>{
let rejectRun;const {store,service}=fixture(t,{chat:()=>new Promise((_resolve,reject)=>{rejectRun=reject;})});enable(store);const c=store.create('alice'),turn=service.send(c.id,principal,'diagnose');await new Promise(r=>setImmediate(r));service.cancel(c.id,principal);
const pending=store.conversation(c.id,'alice').turns[0];rejectRun(Object.assign(Error('stop uncertain'),{status:502,stopUnconfirmed:true}));await service.running.get(turn.id).task;
assert.equal(pending.status,'running');assert.equal(pending.cancelRequested,true);const saved=store.conversation(c.id,'alice').turns[0];assert.equal(saved.status,'needs_review');assert.equal(saved.cancelRequested,false);assert.equal(store.events(c.id,'alice',{}).events.at(-1).kind,'needs_review');
test('cancellation remains pending until child exit and uncertain stop stays needs_review', async (t) => {
let rejectRun;
const { store, service } = fixture(t, {
chat: () =>
new Promise((_resolve, reject) => {
rejectRun = reject;
}),
});
enable(store);
const c = store.create('alice'),
turn = service.send(c.id, principal, 'diagnose');
await new Promise((r) => setImmediate(r));
service.cancel(c.id, principal);
const pending = store.conversation(c.id, 'alice').turns[0];
rejectRun(Object.assign(Error('stop uncertain'), { status: 502, stopUnconfirmed: true }));
await service.running.get(turn.id).task;
assert.equal(pending.status, 'running');
assert.equal(pending.cancelRequested, true);
const saved = store.conversation(c.id, 'alice').turns[0];
assert.equal(saved.status, 'needs_review');
assert.equal(saved.cancelRequested, false);
assert.equal(store.events(c.id, 'alice', {}).events.at(-1).kind, 'needs_review');
});
test('an ambiguous real mapping preparation keeps needs-selection in its durable action result',async t=>{
const {store,service}=fixture(t);enable(store);store.saveSettings({...store.settings(),apiKey:'',allowActions:true});
const sample={id:'sample-1',evidenceHash:'evidence-hash',processName:'fixture-process',processVersion:'1',sample:{connectionId:'source-1'}};
Object.assign(service.deps,{workspace:{getConnection:()=>({status:'connected'}),record(){}},orderExecution:{},orderRules:{get:kind=>kind==='capture-samples'?sample:undefined,proposeMapping:()=>({mapping:{sources:{}},blockedReasons:['请选择订单号来源'],fields:[{state:'ambiguous'}]})}});
const c=store.create('alice'),turn=store.beginTurn(c.id,'alice','prepare mapping');store.updateTurn(turn.id,'success',{reply:'review proposal',actions:[{id:'mapping-action',kind:'prepare_field_mapping',targetId:'sample-1',status:'proposed',guard:{sampleHash:'evidence-hash',draftVersion:0}}]});
const result=await service.executeAction(c.id,'mapping-action',{...principal,sessionId:'fixture-session'});assert.equal(result.status,'success');assert.equal(result.result.status,'needs-selection');
const event=store.events(c.id,'alice',{}).events.find(e=>e.kind==='action_result');assert.equal(event.actionId,'mapping-action');assert.equal(event.data.status,'success');assert.equal(event.data.resultStatus,'needs-selection');assert.doesNotMatch(JSON.stringify(event),/请选择订单号来源/);
test('an ambiguous real mapping preparation keeps needs-selection in its durable action result', async (t) => {
const { store, service } = fixture(t);
enable(store);
store.saveSettings({ ...store.settings(), apiKey: '', allowActions: true });
const sample = {
id: 'sample-1',
evidenceHash: 'evidence-hash',
processName: 'fixture-process',
processVersion: '1',
sample: { connectionId: 'source-1' },
};
Object.assign(service.deps, {
workspace: { getConnection: () => ({ status: 'connected' }), record() {} },
orderExecution: {},
orderRules: {
get: (kind) => (kind === 'capture-samples' ? sample : undefined),
proposeMapping: () => ({
mapping: { sources: {} },
blockedReasons: ['请选择订单号来源'],
fields: [{ state: 'ambiguous' }],
}),
},
});
const c = store.create('alice'),
turn = store.beginTurn(c.id, 'alice', 'prepare mapping');
store.updateTurn(turn.id, 'success', {
reply: 'review proposal',
actions: [
{
id: 'mapping-action',
kind: 'prepare_field_mapping',
targetId: 'sample-1',
status: 'proposed',
guard: { sampleHash: 'evidence-hash', draftVersion: 0 },
},
],
});
const result = await service.executeAction(c.id, 'mapping-action', {
...principal,
sessionId: 'fixture-session',
});
assert.equal(result.status, 'success');
assert.equal(result.result.status, 'needs-selection');
const event = store.events(c.id, 'alice', {}).events.find((e) => e.kind === 'action_result');
assert.equal(event.actionId, 'mapping-action');
assert.equal(event.data.status, 'success');
assert.equal(event.data.resultStatus, 'needs-selection');
assert.doesNotMatch(JSON.stringify(event), /请选择订单号来源/);
});
+316 -60
View File
@@ -1,69 +1,325 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
async function fixture(t){
const {Store}=require('../../src/modules/dashboard/store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-workspace-http-')),users=new Store(path.join(dir,'users'));users.bootstrap('admin','Test-password-123');users.addUser({username:'member',role:'operator',password:'Test-password-123'},'admin');
const store=new AssistantStore(path.join(dir,'assistant'));let calls=0,checks=0;
const connections=[{id:'own',name:'Member connection',owner:'member',status:'connected'},{id:'foreign',name:'Foreign connection',owner:'someone',status:'connected'}];
const workspace={snapshot:()=>({connections,exceptions:[]}),getConnection:id=>connections.find(c=>c.id===id)};
const assistant=new AssistantService({store,workspace,dashboard:users,storage:{store:{servers:()=>[{id:'shared',name:'Shared storage',state:{readable:true},enabled:true}],archives:()=>[]},check:()=>{checks++;}},runtime:{chat:async()=>{calls++;return JSON.stringify({reply:'diagnosed',actions:[]});}}});
const server=createDashboard({store:users,assistant,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{server.closeAssistantStreams?.();await assistant.stop();server.closeAllConnections();await new Promise(r=>server.close(r));store.close();await fs.rm(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port;
const call=(route,body,cookie,extra={})=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{}),...extra},body:body===undefined?undefined:JSON.stringify(body)});
const login=async name=>(await call('/api/login',{username:name,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
return {store,assistant,server,users,call,login,base,calls:()=>calls,checks:()=>checks};
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
async function fixture(t) {
const { Store } = require('../../src/modules/dashboard/store.cjs'),
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
{ createDashboard } = require('../../src/app/dashboard.cjs');
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-workspace-http-')),
users = new Store(path.join(dir, 'users'));
users.bootstrap('admin', 'Test-password-123');
users.addUser({ username: 'member', role: 'operator', password: 'Test-password-123' }, 'admin');
const store = new AssistantStore(path.join(dir, 'assistant'));
let calls = 0,
checks = 0;
const connections = [
{ id: 'own', name: 'Member connection', owner: 'member', status: 'connected' },
{ id: 'foreign', name: 'Foreign connection', owner: 'someone', status: 'connected' },
];
const workspace = {
snapshot: () => ({ connections, exceptions: [] }),
getConnection: (id) => connections.find((c) => c.id === id),
};
const assistant = new AssistantService({
store,
workspace,
dashboard: users,
storage: {
store: {
servers: () => [
{ id: 'shared', name: 'Shared storage', state: { readable: true }, enabled: true },
],
archives: () => [],
},
check: () => {
checks++;
},
},
runtime: {
chat: async () => {
calls++;
return JSON.stringify({ reply: 'diagnosed', actions: [] });
},
},
});
const server = createDashboard({ store: users, assistant, outputDir: dir });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(async () => {
server.closeAssistantStreams?.();
await assistant.stop();
server.closeAllConnections();
await new Promise((r) => server.close(r));
store.close();
await fs.rm(dir, { recursive: true, force: true });
});
const base = 'http://127.0.0.1:' + server.address().port;
const call = (route, body, cookie, extra = {}) =>
fetch(base + route, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(body === undefined ? {} : { Origin: base, 'Content-Type': 'application/json' }),
...(cookie ? { Cookie: cookie } : {}),
...extra,
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const login = async (name) =>
(await call('/api/login', { username: name, password: 'Test-password-123' })).headers
.get('set-cookie')
.split(';')[0];
return {
store,
assistant,
server,
users,
call,
login,
base,
calls: () => calls,
checks: () => checks,
};
}
test('context reads authorized diagnostics without calling a model or live service',async t=>{
const f=await fixture(t),cookie=await f.login('member');assert.equal((await f.call('/api/assistant/context')).status,401);
const r=await f.call('/api/assistant/context',undefined,cookie);assert.equal(r.status,200);const data=await r.json();
assert.deepEqual(data.connections.map(c=>c.id),['own']);assert.ok(data.observedAt);assert.equal(f.calls(),0);assert.equal(f.checks(),0);assert.doesNotMatch(JSON.stringify(data),/Foreign connection|password|apiKey/);
test('context reads authorized diagnostics without calling a model or live service', async (t) => {
const f = await fixture(t),
cookie = await f.login('member');
assert.equal((await f.call('/api/assistant/context')).status, 401);
const r = await f.call('/api/assistant/context', undefined, cookie);
assert.equal(r.status, 200);
const data = await r.json();
assert.deepEqual(
data.connections.map((c) => c.id),
['own'],
);
assert.ok(data.observedAt);
assert.equal(f.calls(), 0);
assert.equal(f.checks(), 0);
assert.doesNotMatch(JSON.stringify(data), /Foreign connection|password|apiKey/);
});
test('diagnosis and recovery cannot use another connection owner\'s export or archive',async t=>{
const f=await fixture(t),cookie=await f.login('member');f.assistant.deps.dashboard={jobs:()=>[{jobId:'own-pdf',connectionId:'own'},{jobId:'other-pdf',connectionId:'foreign'}]};
f.assistant.deps.storage.store.archives=()=>[{id:'mine',jobId:'own-pdf',serverId:'shared',status:'error'},{id:'secret',jobId:'other-pdf',serverId:'shared',status:'error'}];
const data=await(await f.call('/api/assistant/context',undefined,cookie)).json();assert.deepEqual(data.jobs.map(x=>x.jobId),['own-pdf']);assert.deepEqual(data.archives.map(x=>x.id),['mine']);
assert.throws(()=>require('../../src/modules/assistant/policy.cjs').checkAction({kind:'retry_archive',targetId:'secret'},f.assistant.deps,{username:'member',role:'operator'}),e=>e.status===403);
test("diagnosis and recovery cannot use another connection owner's export or archive", async (t) => {
const f = await fixture(t),
cookie = await f.login('member');
f.assistant.deps.dashboard = {
jobs: () => [
{ jobId: 'own-pdf', connectionId: 'own' },
{ jobId: 'other-pdf', connectionId: 'foreign' },
],
};
f.assistant.deps.storage.store.archives = () => [
{ id: 'mine', jobId: 'own-pdf', serverId: 'shared', status: 'error' },
{ id: 'secret', jobId: 'other-pdf', serverId: 'shared', status: 'error' },
];
const data = await (await f.call('/api/assistant/context', undefined, cookie)).json();
assert.deepEqual(
data.jobs.map((x) => x.jobId),
['own-pdf'],
);
assert.deepEqual(
data.archives.map((x) => x.id),
['mine'],
);
assert.throws(
() =>
require('../../src/modules/assistant/policy.cjs').checkAction(
{ kind: 'retry_archive', targetId: 'secret' },
f.assistant.deps,
{ username: 'member', role: 'operator' },
),
(e) => e.status === 403,
);
});
test('archive authorization is independent of diagnostic recent-list truncation',async t=>{
const f=await fixture(t),user={username:'member',role:'operator'},target={id:'older',jobId:'old-job',serverId:'shared',status:'error'};f.assistant.deps.dashboard={recentJobs:()=>[],job:id=>id==='old-job'?{jobId:id,connectionId:'own'}:null};
f.assistant.deps.storage.store.archives=()=>[...Array.from({length:16},(_,i)=>({id:'new-'+i,connectionId:'own',serverId:'shared',status:'error'})),target];
assert.doesNotThrow(()=>require('../../src/modules/assistant/policy.cjs').checkAction({kind:'retry_archive',targetId:'older'},f.assistant.deps,user));
assert.deepEqual(require('../../src/modules/assistant/diagnostic-context.cjs').validateDiagnostic({command:'archive',targetId:'older'},f.assistant.deps,user),{command:'archive',targetId:'older'});
const cookie=await f.login('member'),c=await(await f.call('/api/assistant/conversations',{},cookie)).json();let actual;f.assistant.runtime.chat=async input=>{actual=input.context;return JSON.stringify({reply:'diagnosed',actions:[]});};f.store.saveSettings({...f.store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'fixture',apiKey:'TEST_ONLY_KEY',allowActions:false});const sent=await f.call('/api/assistant/conversations/'+c.id+'/messages',{text:'分析旧归档',diagnostic:{command:'archive',targetId:'older'}},cookie);assert.equal(sent.status,202);const turn=await sent.json();await f.assistant.running.get(turn.id)?.task;assert.equal(actual.selectedTarget.id,'older');
test('archive authorization is independent of diagnostic recent-list truncation', async (t) => {
const f = await fixture(t),
user = { username: 'member', role: 'operator' },
target = { id: 'older', jobId: 'old-job', serverId: 'shared', status: 'error' };
f.assistant.deps.dashboard = {
recentJobs: () => [],
job: (id) => (id === 'old-job' ? { jobId: id, connectionId: 'own' } : null),
};
f.assistant.deps.storage.store.archives = () => [
...Array.from({ length: 16 }, (_, i) => ({
id: 'new-' + i,
connectionId: 'own',
serverId: 'shared',
status: 'error',
})),
target,
];
assert.doesNotThrow(() =>
require('../../src/modules/assistant/policy.cjs').checkAction(
{ kind: 'retry_archive', targetId: 'older' },
f.assistant.deps,
user,
),
);
assert.deepEqual(
require('../../src/modules/assistant/diagnostic-context.cjs').validateDiagnostic(
{ command: 'archive', targetId: 'older' },
f.assistant.deps,
user,
),
{ command: 'archive', targetId: 'older' },
);
const cookie = await f.login('member'),
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
let actual;
f.assistant.runtime.chat = async (input) => {
actual = input.context;
return JSON.stringify({ reply: 'diagnosed', actions: [] });
};
f.store.saveSettings({
...f.store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://fixture.example/anthropic',
model: 'fixture',
apiKey: 'TEST_ONLY_KEY',
allowActions: false,
});
const sent = await f.call(
'/api/assistant/conversations/' + c.id + '/messages',
{ text: '分析旧归档', diagnostic: { command: 'archive', targetId: 'older' } },
cookie,
);
assert.equal(sent.status, 202);
const turn = await sent.json();
await f.assistant.running.get(turn.id)?.task;
assert.equal(actual.selectedTarget.id, 'older');
});
test('diagnostic command targets are validated at the API rather than trusted from display names',async t=>{
const f=await fixture(t),cookie=await f.login('member'),created=await(await f.call('/api/assistant/conversations',{},cookie)).json();
f.store.saveSettings({...f.store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://fixture.example/anthropic',model:'test',apiKey:'TEST_ONLY_KEY',allowActions:false});
const route='/api/assistant/conversations/'+created.id+'/messages';
assert.equal((await f.call(route,{text:'analyze',diagnostic:{command:'bpm',targetId:'foreign'}},cookie)).status,403);
assert.equal((await f.call(route,{text:'analyze',diagnostic:{command:'shell'}},cookie)).status,400);
const sent=await f.call(route,{text:'analyze',diagnostic:{command:'bpm',targetId:'own'},requestId:'diagnostic-test'},cookie);assert.equal(sent.status,202);
const turn=await sent.json();await f.assistant.running.get(turn.id)?.task;assert.equal(f.calls(),1);
test('diagnostic command targets are validated at the API rather than trusted from display names', async (t) => {
const f = await fixture(t),
cookie = await f.login('member'),
created = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
f.store.saveSettings({
...f.store.settings(),
enabled: true,
runtimePath: process.execPath,
apiBase: 'https://fixture.example/anthropic',
model: 'test',
apiKey: 'TEST_ONLY_KEY',
allowActions: false,
});
const route = '/api/assistant/conversations/' + created.id + '/messages';
assert.equal(
(
await f.call(
route,
{ text: 'analyze', diagnostic: { command: 'bpm', targetId: 'foreign' } },
cookie,
)
).status,
403,
);
assert.equal(
(await f.call(route, { text: 'analyze', diagnostic: { command: 'shell' } }, cookie)).status,
400,
);
const sent = await f.call(
route,
{
text: 'analyze',
diagnostic: { command: 'bpm', targetId: 'own' },
requestId: 'diagnostic-test',
},
cookie,
);
assert.equal(sent.status, 202);
const turn = await sent.json();
await f.assistant.running.get(turn.id)?.task;
assert.equal(f.calls(), 1);
});
test('durable event HTTP rejects cross-owner and invalid cursors and SSE can resume then close',async t=>{
const f=await fixture(t),cookie=await f.login('admin'),other=await f.login('member'),c=await(await f.call('/api/assistant/conversations',{},cookie)).json();
const turn=f.store.beginTurn(c.id,f.users.users().find(u=>u.username==='admin').id,'sample');f.store.updateTurn(turn.id,'success',{reply:'answer'});
const prefix='/api/assistant/conversations/'+c.id;
assert.equal((await f.call(prefix+'/events?after=0',undefined,other)).status,404);
for(const query of ['-1','1.5','999999','bad'])assert.equal((await f.call(prefix+'/events?after='+query,undefined,cookie)).status,400);
const response=await f.call(prefix+'/events?after=0',undefined,cookie);assert.equal(response.status,200);const replay=await response.json();assert.ok(replay.events.length>=2);
const stream=await f.call(prefix+'/stream?after=0',undefined,cookie,{'Last-Event-ID':String(replay.events[0].seq)});assert.equal(stream.status,200);assert.match(stream.headers.get('content-type'),/text\/event-stream/);assert.equal(stream.headers.get('x-accel-buffering'),'no');
const reader=stream.body.getReader(),first=await reader.read();assert.match(new TextDecoder().decode(first.value),/assistant_event/);await reader.cancel();
const state=await(await f.call(prefix,undefined,cookie)).json();assert.equal(state.eventCursor,replay.nextCursor);
test('durable event HTTP rejects cross-owner and invalid cursors and SSE can resume then close', async (t) => {
const f = await fixture(t),
cookie = await f.login('admin'),
other = await f.login('member'),
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
const turn = f.store.beginTurn(
c.id,
f.users.users().find((u) => u.username === 'admin').id,
'sample',
);
f.store.updateTurn(turn.id, 'success', { reply: 'answer' });
const prefix = '/api/assistant/conversations/' + c.id;
assert.equal((await f.call(prefix + '/events?after=0', undefined, other)).status, 404);
for (const query of ['-1', '1.5', '999999', 'bad'])
assert.equal((await f.call(prefix + '/events?after=' + query, undefined, cookie)).status, 400);
const response = await f.call(prefix + '/events?after=0', undefined, cookie);
assert.equal(response.status, 200);
const replay = await response.json();
assert.ok(replay.events.length >= 2);
const stream = await f.call(prefix + '/stream?after=0', undefined, cookie, {
'Last-Event-ID': String(replay.events[0].seq),
});
assert.equal(stream.status, 200);
assert.match(stream.headers.get('content-type'), /text\/event-stream/);
assert.equal(stream.headers.get('x-accel-buffering'), 'no');
const reader = stream.body.getReader(),
first = await reader.read();
assert.match(new TextDecoder().decode(first.value), /assistant_event/);
await reader.cancel();
const state = await (await f.call(prefix, undefined, cookie)).json();
assert.equal(state.eventCursor, replay.nextCursor);
});
test('SSE refuses excess streams and releases resources on shutdown',async t=>{
const f=await fixture(t),cookie=await f.login('admin'),c=await(await f.call('/api/assistant/conversations',{},cookie)).json(),route='/api/assistant/conversations/'+c.id+'/stream?after=0';
const a=await f.call(route,undefined,cookie),b=await f.call(route,undefined,cookie);assert.equal(a.status,200);assert.equal(b.status,200);assert.equal((await f.call(route,undefined,cookie)).status,429);
f.server.closeAssistantStreams();await a.body.cancel();await b.body.cancel();
test('SSE refuses excess streams and releases resources on shutdown', async (t) => {
const f = await fixture(t),
cookie = await f.login('admin'),
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json(),
route = '/api/assistant/conversations/' + c.id + '/stream?after=0';
const a = await f.call(route, undefined, cookie),
b = await f.call(route, undefined, cookie);
assert.equal(a.status, 200);
assert.equal(b.status, 200);
assert.equal((await f.call(route, undefined, cookie)).status, 429);
f.server.closeAssistantStreams();
await a.body.cancel();
await b.body.cancel();
});
test('an open SSE stream terminates after its login cookie is revoked',{timeout:30000},async t=>{
const f=await fixture(t),cookie=await f.login('admin'),c=await(await f.call('/api/assistant/conversations',{},cookie)).json();
const response=await f.call('/api/assistant/conversations/'+c.id+'/stream?after=0',undefined,cookie),reader=response.body.getReader();await f.call('/api/logout',{},cookie);let text='';while(true){const part=await reader.read();if(part.done)break;text+=new TextDecoder().decode(part.value);}assert.match(text,/auth_required/);
});
test('title search reaches beyond the visible page and remains owner scoped',async t=>{
const f=await fixture(t),cookie=await f.login('admin'),owner=f.users.users().find(u=>u.username==='admin').id,other=f.users.users().find(u=>u.username==='member').id;
for(let i=0;i<27;i++){const c=f.store.create(owner);f.store.beginTurn(c.id,owner,i===0?'UNIQUE_OLDER_TITLE':'Ordinary '+i);}
const foreign=f.store.create(other);f.store.beginTurn(foreign.id,other,'UNIQUE_OLDER_TITLE');
const response=await f.call('/api/assistant/conversations?scope=active&page=1&pageSize=25&query=unique_older_title',undefined,cookie);assert.equal(response.status,200);const result=await response.json();assert.equal(result.total,1);assert.equal(result.items[0].title,'UNIQUE_OLDER_TITLE');assert.notEqual(result.items[0].id,foreign.id);assert.equal(result.search.truncated,false);
test(
'an open SSE stream terminates after its login cookie is revoked',
{ timeout: 30000 },
async (t) => {
const f = await fixture(t),
cookie = await f.login('admin'),
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
const response = await f.call(
'/api/assistant/conversations/' + c.id + '/stream?after=0',
undefined,
cookie,
),
reader = response.body.getReader();
await f.call('/api/logout', {}, cookie);
let text = '';
while (true) {
const part = await reader.read();
if (part.done) break;
text += new TextDecoder().decode(part.value);
}
assert.match(text, /auth_required/);
},
);
test('title search reaches beyond the visible page and remains owner scoped', async (t) => {
const f = await fixture(t),
cookie = await f.login('admin'),
owner = f.users.users().find((u) => u.username === 'admin').id,
other = f.users.users().find((u) => u.username === 'member').id;
for (let i = 0; i < 27; i++) {
const c = f.store.create(owner);
f.store.beginTurn(c.id, owner, i === 0 ? 'UNIQUE_OLDER_TITLE' : 'Ordinary ' + i);
}
const foreign = f.store.create(other);
f.store.beginTurn(foreign.id, other, 'UNIQUE_OLDER_TITLE');
const response = await f.call(
'/api/assistant/conversations?scope=active&page=1&pageSize=25&query=unique_older_title',
undefined,
cookie,
);
assert.equal(response.status, 200);
const result = await response.json();
assert.equal(result.total, 1);
assert.equal(result.items[0].title, 'UNIQUE_OLDER_TITLE');
assert.notEqual(result.items[0].id, foreign.id);
assert.equal(result.search.truncated, false);
});
+117 -24
View File
@@ -1,25 +1,118 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),http=require('node:http'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs');
test('pinned official ZCode calls a local model with no native tools and cannot execute unsolicited tool calls',{skip:!process.env.ORDER_TEST_ZCODE_CLI,timeout:180000},async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-official-zcode-')),runtime=new ZcodeRuntime({stateDir:dir}),requests=[];let attack=false,attackSent=0,attackRequests=0;
t.after(()=>fs.rm(dir,{recursive:true,force:true}));
const canary=path.join(dir,'must-not-exist.txt');
const server=http.createServer(async(req,res)=>{let raw='';for await(const chunk of req)raw+=chunk;const body=JSON.parse(raw);requests.push({path:req.url,auth:req.headers.authorization,body});
if(attack)attackRequests++;
// Write's published schema uses file_path/content; no shell quoting is involved.
const delta=attack&&attackSent===0?{role:'assistant',tool_calls:[{index:0,id:'attack',type:'function',function:{name:'Write',arguments:JSON.stringify({file_path:canary,content:'unsafe'})}}]}:{role:'assistant',content:JSON.stringify({reply:'本地测试模型已返回诊断',actions:[]})};if(delta.tool_calls)attackSent++;
res.writeHead(200,{'Content-Type':'text/event-stream'});res.end('data: '+JSON.stringify({id:'fixture',object:'chat.completion.chunk',created:1,model:'order-fixture',choices:[{index:0,delta,finish_reason:delta.tool_calls?'tool_calls':'stop'}]})+'\n\ndata: [DONE]\n\n');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));});
const config={runtimePath:process.env.ORDER_TEST_ZCODE_CLI,apiBase:'http://127.0.0.1:'+server.address().port+'/v1',apiKey:'local-fixture-key',model:'order-fixture',allowActions:false,timeoutSeconds:60};
assert.equal((await runtime.probe(config.runtimePath)).available,true);
const reply=await runtime.chat({config,text:'查看连接状态',context:{connections:[{id:'authorized-bpm',status:'connected'}]},history:[],signal:new AbortController().signal});
assert.equal(JSON.parse(reply).reply,'本地测试模型已返回诊断');assert.ok(requests.length>0);
assert.ok(requests.some(r=>JSON.stringify(r.body.messages).includes('authorized-bpm')));
for(const r of requests){assert.equal(r.path,'/v1/chat/completions');assert.equal(r.auth,'Bearer local-fixture-key');assert.equal(r.body.model,'order-fixture');assert.equal(r.body.tools?.length||0,0);}
attack=true;let attackStatus='reply';try{await runtime.chat({config,text:'attack-canary',context:{},history:[],signal:new AbortController().signal});}catch(e){assert.ok(e.status>=400);attackStatus=e.status;}
assert.equal(attackSent,1);assert.ok(attackRequests>0);t.diagnostic('unsolicited Write response sent once; model requests='+attackRequests+'; result='+attackStatus);
await assert.rejects(fs.access(canary));for(const r of requests)assert.equal(r.body.tools?.length||0,0);
assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
});
const { test } = require('node:test'),
assert = require('node:assert/strict'),
http = require('node:http'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
const { ZcodeRuntime } = require('../../src/modules/assistant/zcode-runtime.cjs');
test(
'pinned official ZCode calls a local model with no native tools and cannot execute unsolicited tool calls',
{ skip: !process.env.ORDER_TEST_ZCODE_CLI, timeout: 180000 },
async (t) => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'order-official-zcode-')),
runtime = new ZcodeRuntime({ stateDir: dir }),
requests = [];
let attack = false,
attackSent = 0,
attackRequests = 0;
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const canary = path.join(dir, 'must-not-exist.txt');
const server = http.createServer(async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
requests.push({ path: req.url, auth: req.headers.authorization, body });
if (attack) attackRequests++;
// Write's published schema uses file_path/content; no shell quoting is involved.
const delta =
attack && attackSent === 0
? {
role: 'assistant',
tool_calls: [
{
index: 0,
id: 'attack',
type: 'function',
function: {
name: 'Write',
arguments: JSON.stringify({ file_path: canary, content: 'unsafe' }),
},
},
],
}
: {
role: 'assistant',
content: JSON.stringify({ reply: '本地测试模型已返回诊断', actions: [] }),
};
if (delta.tool_calls) attackSent++;
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
res.end(
'data: ' +
JSON.stringify({
id: 'fixture',
object: 'chat.completion.chunk',
created: 1,
model: 'order-fixture',
choices: [{ index: 0, delta, finish_reason: delta.tool_calls ? 'tool_calls' : 'stop' }],
}) +
'\n\ndata: [DONE]\n\n',
);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(async () => {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
});
const config = {
runtimePath: process.env.ORDER_TEST_ZCODE_CLI,
apiBase: 'http://127.0.0.1:' + server.address().port + '/v1',
apiKey: 'local-fixture-key',
model: 'order-fixture',
allowActions: false,
timeoutSeconds: 60,
};
assert.equal((await runtime.probe(config.runtimePath)).available, true);
const reply = await runtime.chat({
config,
text: '查看连接状态',
context: { connections: [{ id: 'authorized-bpm', status: 'connected' }] },
history: [],
signal: new AbortController().signal,
});
assert.equal(JSON.parse(reply).reply, '本地测试模型已返回诊断');
assert.ok(requests.length > 0);
assert.ok(requests.some((r) => JSON.stringify(r.body.messages).includes('authorized-bpm')));
for (const r of requests) {
assert.equal(r.path, '/v1/chat/completions');
assert.equal(r.auth, 'Bearer local-fixture-key');
assert.equal(r.body.model, 'order-fixture');
assert.equal(r.body.tools?.length || 0, 0);
}
attack = true;
let attackStatus = 'reply';
try {
await runtime.chat({
config,
text: 'attack-canary',
context: {},
history: [],
signal: new AbortController().signal,
});
} catch (e) {
assert.ok(e.status >= 400);
attackStatus = e.status;
}
assert.equal(attackSent, 1);
assert.ok(attackRequests > 0);
t.diagnostic(
'unsolicited Write response sent once; model requests=' +
attackRequests +
'; result=' +
attackStatus,
);
await assert.rejects(fs.access(canary));
for (const r of requests) assert.equal(r.body.tools?.length || 0, 0);
assert.deepEqual(await fs.readdir(path.join(dir, 'runs')), []);
},
);
+91 -12
View File
@@ -1,15 +1,94 @@
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
test('ZCode bridge uses fixed permissions, isolated profile and filtered environment; secrets are not command arguments',async t=>{
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-driver-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));process.env.PRIVATE_TEST_KEY='must-not-reach-zcode';t.after(()=>delete process.env.PRIVATE_TEST_KEY);
const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'NEVER-IN-ARGV',timeoutSeconds:15,allowActions:false};
assert.equal((await runtime.probe(config.runtimePath)).available,true);
const result=JSON.parse(await runtime.chat({config,text:'hello $() `shell`',history:[],context:{servers:[]},signal:new AbortController().signal}));assert.equal(result.observed.privateEnv,undefined);assert.equal(result.observed.args[result.observed.args.indexOf('--mode')+1],'plan');assert.ok(result.observed.args.includes('--disallowed-tools'));assert.doesNotMatch(JSON.stringify(result.observed.args),/NEVER-IN-ARGV/);assert.equal(result.observed.config.plugins.enabled,false);assert.equal(result.observed.config.features.mcp,false);assert.equal(result.observed.config.features.subagent,false);assert.match(result.observed.cwd,/zcode-driver/);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs/promises'),
os = require('node:os'),
path = require('node:path');
test('ZCode bridge uses fixed permissions, isolated profile and filtered environment; secrets are not command arguments', async (t) => {
const { ZcodeRuntime } = require('../../src/modules/assistant/zcode-runtime.cjs'),
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'zcode-driver-')),
runtime = new ZcodeRuntime({ stateDir: dir });
t.after(() => fs.rm(dir, { recursive: true, force: true }));
process.env.PRIVATE_TEST_KEY = 'must-not-reach-zcode';
t.after(() => delete process.env.PRIVATE_TEST_KEY);
const config = {
runtimePath: path.resolve('tests/fixtures/zcode-fixture.cjs'),
model: 'fixture',
apiBase: 'https://models.example/v1',
apiKey: 'NEVER-IN-ARGV',
timeoutSeconds: 15,
allowActions: false,
};
assert.equal((await runtime.probe(config.runtimePath)).available, true);
const result = JSON.parse(
await runtime.chat({
config,
text: 'hello $() `shell`',
history: [],
context: { servers: [] },
signal: new AbortController().signal,
}),
);
assert.equal(result.observed.privateEnv, undefined);
assert.equal(result.observed.args[result.observed.args.indexOf('--mode') + 1], 'plan');
assert.ok(result.observed.args.includes('--disallowed-tools'));
assert.doesNotMatch(JSON.stringify(result.observed.args), /NEVER-IN-ARGV/);
assert.equal(result.observed.config.plugins.enabled, false);
assert.equal(result.observed.config.features.mcp, false);
assert.equal(result.observed.config.features.subagent, false);
assert.match(result.observed.cwd, /zcode-driver/);
assert.deepEqual(await fs.readdir(path.join(dir, 'runs')), []);
});
test('ZCode cancellation and excessive output terminate the invocation and clean private profiles',async t=>{
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-abort-')),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));const config={runtimePath:path.resolve('tests/fixtures/zcode-fixture.cjs'),model:'fixture',apiBase:'https://models.example/v1',apiKey:'secret',timeoutSeconds:15};
const controller=new AbortController(),pending=runtime.chat({config,text:'FIXTURE_HANG',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),350);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
await assert.rejects(runtime.chat({config,text:'FIXTURE_OVERFLOW',history:[],context:{},signal:new AbortController().signal}),e=>e.status===502);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
test('ZCode cancellation and excessive output terminate the invocation and clean private profiles', async (t) => {
const { ZcodeRuntime } = require('../../src/modules/assistant/zcode-runtime.cjs'),
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'zcode-abort-')),
runtime = new ZcodeRuntime({ stateDir: dir });
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const config = {
runtimePath: path.resolve('tests/fixtures/zcode-fixture.cjs'),
model: 'fixture',
apiBase: 'https://models.example/v1',
apiKey: 'secret',
timeoutSeconds: 15,
};
const controller = new AbortController(),
pending = runtime.chat({
config,
text: 'FIXTURE_HANG',
history: [],
context: {},
signal: controller.signal,
});
setTimeout(() => controller.abort(Object.assign(new Error('cancelled'), { status: 499 })), 350);
await assert.rejects(pending, (e) => e.status === 499);
assert.deepEqual(await fs.readdir(path.join(dir, 'runs')), []);
await assert.rejects(
runtime.chat({
config,
text: 'FIXTURE_OVERFLOW',
history: [],
context: {},
signal: new AbortController().signal,
}),
(e) => e.status === 502,
);
assert.deepEqual(await fs.readdir(path.join(dir, 'runs')), []);
});
test('cancelling during runtime discovery interrupts the probe and cleans its profile',async t=>{
const {ZcodeRuntime}=require('../../src/modules/assistant/zcode-runtime.cjs'),dir=await fs.mkdtemp(path.join(os.tmpdir(),'zcode-probe-abort-')),entry=path.join(dir,'slow-probe.cjs'),runtime=new ZcodeRuntime({stateDir:dir});t.after(()=>fs.rm(dir,{recursive:true,force:true}));await fs.writeFile(entry,"setInterval(()=>{},1000);");const controller=new AbortController();const pending=runtime.chat({config:{runtimePath:entry,timeoutSeconds:15},text:'hello',history:[],context:{},signal:controller.signal});setTimeout(()=>controller.abort(Object.assign(new Error('cancelled'),{status:499})),500);await assert.rejects(pending,e=>e.status===499);assert.deepEqual(await fs.readdir(path.join(dir,'runs')),[]);
test('cancelling during runtime discovery interrupts the probe and cleans its profile', async (t) => {
const { ZcodeRuntime } = require('../../src/modules/assistant/zcode-runtime.cjs'),
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'zcode-probe-abort-')),
entry = path.join(dir, 'slow-probe.cjs'),
runtime = new ZcodeRuntime({ stateDir: dir });
t.after(() => fs.rm(dir, { recursive: true, force: true }));
await fs.writeFile(entry, 'setInterval(()=>{},1000);');
const controller = new AbortController();
const pending = runtime.chat({
config: { runtimePath: entry, timeoutSeconds: 15 },
text: 'hello',
history: [],
context: {},
signal: controller.signal,
});
setTimeout(() => controller.abort(Object.assign(new Error('cancelled'), { status: 499 })), 500);
await assert.rejects(pending, (e) => e.status === 499);
assert.deepEqual(await fs.readdir(path.join(dir, 'runs')), []);
});
+15
View File
@@ -0,0 +1,15 @@
'use strict';
// The attachment tests exercise real AES-GCM + SQLite; only the OS key-provider
// boundary is replaced so that unrelated Windows ACL/DPAPI latency cannot mask
// file ownership, request replay and upload validation regressions.
module.exports = function fixtureKeys(t) {
const { BpmVault } = require('../../src/platform/security/vault.cjs'),
crypto = require('node:crypto'),
seed = crypto.randomBytes(32);
t.mock.method(BpmVault.prototype, 'ensureKey', function () {
if (!this.key)
this.key = crypto.createHmac('sha256', seed).update(this.stateDir.toLowerCase()).digest();
return this.key;
});
t.after(() => seed.fill(0));
};
+99
View File
@@ -0,0 +1,99 @@
'use strict';
const output = '{"reply":"local provider works","actions":[]}';
function messageSse() {
return [
{
type: 'message_start',
message: {
id: 'local',
type: 'message',
role: 'assistant',
model: 'fixture-model',
content: [],
usage: { input_tokens: 3, output_tokens: 0 },
},
},
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: output } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 8 } },
{ type: 'message_stop' },
]
.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`)
.join('');
}
function chatSse() {
return (
[
{
id: 'local',
object: 'chat.completion.chunk',
created: 1,
model: 'fixture-model',
choices: [{ index: 0, delta: { role: 'assistant', content: output }, finish_reason: null }],
},
{
id: 'local',
object: 'chat.completion.chunk',
created: 1,
model: 'fixture-model',
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
usage: { prompt_tokens: 3, completion_tokens: 8, total_tokens: 11 },
},
]
.map((e) => 'data: ' + JSON.stringify(e) + '\n\n')
.join('') + 'data: [DONE]\n\n'
);
}
function responseSse() {
const item = {
id: 'msg_local',
type: 'message',
role: 'assistant',
status: 'completed',
content: [{ type: 'output_text', text: output, annotations: [] }],
},
response = {
id: 'resp_local',
object: 'response',
created_at: 1,
model: 'fixture-model',
status: 'completed',
output: [item],
usage: { input_tokens: 3, output_tokens: 8, total_tokens: 11 },
};
return [
{ type: 'response.created', response: { ...response, status: 'in_progress', output: [] } },
{
type: 'response.output_item.added',
output_index: 0,
item: { ...item, status: 'in_progress', content: [] },
},
{
type: 'response.content_part.added',
item_id: item.id,
output_index: 0,
content_index: 0,
part: { type: 'output_text', text: '', annotations: [] },
},
{
type: 'response.output_text.delta',
item_id: item.id,
output_index: 0,
content_index: 0,
delta: output,
},
{
type: 'response.output_text.done',
item_id: item.id,
output_index: 0,
content_index: 0,
text: output,
},
{ type: 'response.output_item.done', output_index: 0, item },
{ type: 'response.completed', response },
]
.map((e, i) => `event: ${e.type}\ndata: ${JSON.stringify({ ...e, sequence_number: i })}\n\n`)
.join('');
}
module.exports = { messageSse, chatSse, responseSse };