299 lines
11 KiB
JavaScript
299 lines
11 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 { 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('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('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('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), /请选择订单号来源/);
|
|
});
|