Files
order-notification-automation/tests/assistant/management.test.cjs
T

587 lines
21 KiB
JavaScript

'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);
},
);