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: '已读取运行状态。
',
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('已读取运行状态。
', { 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('已读取运行状态。
', { 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(
'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);
},
);