chore: baseline Agent Workbench 1.0.0
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { fixture, launchWorkbench, compatibleFixture, until, assertToolPairs } from './helpers.mjs';
|
||||
|
||||
test('the bundled local service enforces host, origin, token and JSON object contracts', async t => {
|
||||
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
||||
assert.equal((await fetch(server.url + '/api/health')).status, 200);
|
||||
assert.equal((await fetch(server.url + '/api/sessions')).status, 403);
|
||||
assert.equal((await fetch(server.url + '/api/bootstrap', { headers: { Origin: 'https://example.invalid' } })).status, 403);
|
||||
const badHostStatus = await new Promise((resolve, reject) => {
|
||||
http.get(server.url + '/api/health', { headers: { Host: 'example.invalid' } }, response => { response.resume(); resolve(response.statusCode); }).on('error', reject);
|
||||
});
|
||||
assert.equal(badHostStatus, 421);
|
||||
await assert.rejects(server.api('/sessions', null), { status: 400 });
|
||||
assert.equal(server.bootstrap.capabilities.commands, 'per-call-approval');
|
||||
const page = await fetch(server.url); assert.equal(page.status, 200); assert.match(await page.text(), /Agent Workbench/);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
test('API review applies verified content, detects conflicts, exports sessions and keeps keys in memory', async t => {
|
||||
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
||||
const project = await server.api('/projects', { root: f.projectRoot });
|
||||
const session = await server.api('/sessions', { projectId: project.id });
|
||||
const file = await server.api('/projects/' + project.id + '/file?path=README.md');
|
||||
const proposed = await server.api('/sessions/' + session.id + '/proposals', { path: 'README.md', content: '# API suggestion\n', base_sha256: file.sha256 });
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'README.md'), 'utf8'), file.content);
|
||||
const changed = await server.api('/sessions/' + session.id + '/changes/' + proposed.changes[0].id + '/apply', {});
|
||||
assert.equal(changed.changes[0].status, 'applied'); assert.ok(changed.revision > proposed.revision);
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'README.md'), 'utf8'), '# API suggestion\n');
|
||||
const next = await server.api('/sessions/' + session.id + '/proposals', { path: 'README.md', content: '# Another suggestion\n' });
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'README.md'), '# External edit\n');
|
||||
await assert.rejects(server.api('/sessions/' + session.id + '/changes/' + next.changes.at(-1).id + '/apply', {}), { status: 409 });
|
||||
const conflicted = await server.api('/sessions/' + session.id);
|
||||
assert.equal(conflicted.changes.at(-1).status, 'conflict');
|
||||
await server.api('/sessions/' + session.id + '/changes/' + next.changes.at(-1).id + '/reject', {});
|
||||
const model = await compatibleFixture(t, () => ({ data: [{ id: 'fixture-model' }] }));
|
||||
await server.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture-model', apiKey: 'fixture-api-saved-key' });
|
||||
await server.api('/config/models', { baseUrl: model.baseUrl, apiKey: 'fixture-tentative-key' });
|
||||
assert.equal(model.requests[0].headers.authorization, 'Bearer fixture-tentative-key');
|
||||
const bootstrap = await server.api('/bootstrap'); assert.equal(bootstrap.config.hasKey, true);
|
||||
assert.ok(!fs.readFileSync(path.join(f.data, 'config.json'), 'utf8').includes('fixture-api-saved-key'));
|
||||
const exported = await server.api('/sessions/' + session.id + '/export');
|
||||
assert.equal(exported.schemaVersion, 1); assert.equal(exported.session.id, session.id);
|
||||
assert.ok(!JSON.stringify(exported).includes('fixture-api-saved-key'));
|
||||
assertToolPairs(exported.session.providerMessages);
|
||||
await server.close();
|
||||
const restarted = await launchWorkbench(t, f.data); f.onCleanup(restarted.close);
|
||||
assert.equal(restarted.bootstrap.config.hasKey, false);
|
||||
assert.equal(restarted.bootstrap.config.model, 'fixture-model');
|
||||
assert.equal((await restarted.api('/sessions/' + session.id)).changes[0].status, 'applied');
|
||||
await restarted.close();
|
||||
});
|
||||
|
||||
test('a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume', async t => {
|
||||
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
||||
const session = await server.api('/sessions', { projectId: f.project.id });
|
||||
await server.api('/sessions/' + session.id + '/messages', { content: 'Run the offline workflow on this fixture.' });
|
||||
let waiting;
|
||||
await until(async () => { waiting = await server.api('/sessions/' + session.id); return waiting.status === 'awaiting_approval'; });
|
||||
const oldApproval = waiting.approvals[0], proposal = waiting.changes[0];
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, proposal.path)), false);
|
||||
assert.equal(waiting.events.find(event => event.tool === 'run_command').executedAt, undefined);
|
||||
server.child.kill('SIGKILL');
|
||||
await until(() => server.child.exitCode !== null || server.child.signalCode !== null);
|
||||
const restarted = await launchWorkbench(t, f.data); f.onCleanup(restarted.close);
|
||||
const recovered = await restarted.api('/sessions/' + session.id);
|
||||
assert.equal(recovered.status, 'paused'); assert.ok(recovered.recoveryNotice);
|
||||
assert.equal(recovered.approvals[0].status, 'interrupted');
|
||||
assert.equal(recovered.changes[0].id, proposal.id); assert.equal(recovered.changes[0].status, 'pending');
|
||||
assert.equal(recovered.events.find(event => event.tool === 'run_command').phase, 'interrupted');
|
||||
await assert.rejects(restarted.api('/sessions/' + session.id + '/approvals/' + oldApproval.id, { allow: true }), { status: 409 });
|
||||
await restarted.api('/sessions/' + session.id + '/resume', {});
|
||||
await until(async () => { waiting = await restarted.api('/sessions/' + session.id); return waiting.status === 'awaiting_approval'; });
|
||||
const freshApproval = waiting.approvals.find(item => item.status === 'pending');
|
||||
assert.notEqual(freshApproval.id, oldApproval.id);
|
||||
assert.equal(waiting.approvals.find(item => item.id === oldApproval.id).status, 'interrupted');
|
||||
await restarted.api('/sessions/' + session.id + '/approvals/' + freshApproval.id, { allow: false });
|
||||
await until(async () => { const current = await restarted.api('/sessions/' + session.id); return current.status === 'needs_review'; });
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, proposal.path)), false);
|
||||
await restarted.close();
|
||||
});
|
||||
|
||||
test('runtime diagnostics and model-response validation use actual records and preserve the saved connection', async t => {
|
||||
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
||||
const model = await compatibleFixture(t, (url, input) => url === '/v1/models'
|
||||
? { data: [{ id: 'saved-model' }] }
|
||||
: { choices: [{ message: { role: 'assistant', content: input.model === 'tentative-model' ? 'OK' : 'Unexpected model' }, finish_reason: 'stop' }] });
|
||||
await server.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'saved-model', apiKey: 'fixture-saved-connection' });
|
||||
const testResult = await server.api('/config/test', { model: 'tentative-model', apiKey: 'fixture-tentative-connection' });
|
||||
assert.equal(testResult.ok, true); assert.equal(model.requests[0].headers.authorization, 'Bearer fixture-tentative-connection');
|
||||
const bootstrap = await (await fetch(server.url + '/api/bootstrap')).json();
|
||||
assert.equal(bootstrap.config.model, 'saved-model'); assert.equal(bootstrap.config.hasKey, true);
|
||||
const diagnostic = await server.api('/diagnostics?session=' + f.session.id);
|
||||
assert.equal(diagnostic.version, '1.0.0'); assert.equal(diagnostic.session.project.root, f.project.root);
|
||||
assert.equal(diagnostic.environment.encoding, 'UTF-8'); assert.equal(diagnostic.connection.lastRequest.status, 'completed');
|
||||
assert.ok(!JSON.stringify(diagnostic).includes('fixture-saved-connection')); assert.ok(!JSON.stringify(diagnostic).includes('fixture-tentative-connection'));
|
||||
await server.api('/config/models', {}); assert.equal(model.requests[1].headers.authorization, 'Bearer fixture-saved-connection');
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Provider, toolDefinitions, projectContext } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { sessionSnapshot } from '../src/server/diagnostics.mjs';
|
||||
import { fixture, compatibleFixture, call, completion, until, assertToolPairs } from './helpers.mjs';
|
||||
|
||||
const policy = { attempts: 3, delays: [1, 2], timeoutMs: 1000, totalTimeoutMs: 3000 };
|
||||
const response = result => new Response(JSON.stringify(result), { headers: { 'Content-Type': 'application/json' } });
|
||||
const disconnected = () => new TypeError('fetch failed', { cause: Object.assign(new Error('connection reset'), { code: 'ECONNRESET' }) });
|
||||
const configure = f => f.store.saveConfig({ mode: 'compatible', baseUrl: 'http://127.0.0.1:1/v1', model: 'fixture-agent' });
|
||||
|
||||
test('a question about the previous workbench error receives local error context and current change states', async t => {
|
||||
const f = fixture(t);
|
||||
f.session.changes.push({ id: 'impl', path: 'src/catalog.js', status: 'applied' }, { id: 'tests', path: 'tests/catalog.test.mjs', status: 'applied' });
|
||||
f.store.message(f.session, 'system', 'fetch failed');
|
||||
f.store.event(f.session, { kind: 'error', label: '任务需要处理', phase: 'failed', output: 'fetch failed' });
|
||||
const provider = new Provider();
|
||||
let round = 0;
|
||||
provider.complete = async (_config, messages) => {
|
||||
assert.match(messages[0].content, /model_connection/);
|
||||
assert.match(messages[0].content, /inspect_session/);
|
||||
assert.match(messages[0].content, /"status":"applied"/);
|
||||
if (++round === 1) return { message: completion([call('inspect', 'inspect_session', {})]).choices[0].message };
|
||||
const result = JSON.parse(messages.findLast(message => message.role === 'tool').content);
|
||||
assert.equal(result.lastFailure.source, 'model_connection');
|
||||
assert.equal(result.lastFailure.stage, 'model_request');
|
||||
assert.equal(result.lastFailure.historical, true);
|
||||
assert.deepEqual(result.changes.map(change => change.status), ['applied', 'applied']);
|
||||
assert.ok(result.environment.shell); assert.equal(result.environment.encoding, 'UTF-8');
|
||||
return { message: { role: 'assistant', content: 'The recorded failure is a model request failure.' } };
|
||||
};
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, '刚才工作台的 fetch failed 怎么回事?'); await runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'completed'); assert.equal(round, 2);
|
||||
assert.equal(f.session.events.filter(event => event.tool === 'search_files').length, 0);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
assert.ok(toolDefinitions.some(tool => tool.function.name === 'inspect_session'));
|
||||
});
|
||||
|
||||
test('a transient model failure after an approved command retries only the model request', async t => {
|
||||
const f = fixture(t); configure(f);
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'counter.mjs'), "import fs from 'node:fs'; const previous = fs.existsSync('count.txt') ? Number(fs.readFileSync('count.txt','utf8')) : 0; fs.writeFileSync('count.txt', String(previous + 1));\n");
|
||||
let requests = 0;
|
||||
const provider = new Provider({ retryPolicy: policy, fetch: async (_url, input) => {
|
||||
const messages = JSON.parse(input.body).messages; assertToolPairs(messages);
|
||||
if (++requests === 1) return response(completion([call('command', 'run_command', { command: 'node counter.mjs', reason: 'Controlled one-time command' })]));
|
||||
if (requests === 2) throw disconnected();
|
||||
return response(completion([], 'Done'));
|
||||
} });
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'Run the controlled counter.'); const done = runtime.active.get(f.session.id).promise;
|
||||
await until(() => f.session.status === 'awaiting_approval'); runtime.decide(f.session.id, f.session.approvals[0].id, true);
|
||||
await done;
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'count.txt'), 'utf8'), '1');
|
||||
assert.equal(requests, 3); assert.equal(f.session.status, 'completed');
|
||||
assert.equal(f.session.approvals.length, 1);
|
||||
assert.equal(f.session.events.filter(event => event.tool === 'run_command').length, 1);
|
||||
assert.equal(f.session.events.filter(event => event.kind === 'model').at(-1).attempts, 2);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('exhausted model retries preserve tool results, and explicit resume adds no new user turn or replay', async t => {
|
||||
const f = fixture(t); configure(f);
|
||||
let requests = 0, fail = true;
|
||||
const provider = new Provider({ retryPolicy: { ...policy, attempts: 2 }, fetch: async (_url, input) => {
|
||||
const messages = JSON.parse(input.body).messages; assertToolPairs(messages);
|
||||
if (++requests === 1) return response(completion([call('read', 'read_file', { path: 'README.md' })]));
|
||||
if (fail) throw disconnected();
|
||||
assert.equal(messages.at(-1).role, 'tool'); return response(completion([], 'Recovered'));
|
||||
} });
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'Read the fixture.'); await runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'failed');
|
||||
assert.equal(f.session.failure.source, 'model_connection'); assert.equal(f.session.failure.code, 'ECONNRESET');
|
||||
assert.equal(f.session.failure.attempts, 2);
|
||||
const userTurns = f.session.providerMessages.filter(message => message.role === 'user').length;
|
||||
fail = false; runtime.resume(f.session.id); await runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'completed');
|
||||
assert.equal(f.session.providerMessages.filter(message => message.role === 'user').length, userTurns);
|
||||
assert.equal(f.session.events.filter(event => event.tool === 'read_file').length, 1);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('stopping during model backoff cancels further requests and clears the running request state', async t => {
|
||||
const f = fixture(t); configure(f); let requests = 0;
|
||||
const provider = new Provider({ retryPolicy: { ...policy, delays: [500, 500] }, fetch: async () => { requests++; throw disconnected(); } });
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'test'); await until(() => f.session.events.some(event => event.phase === 'retrying'));
|
||||
await runtime.stop(f.session.id);
|
||||
assert.equal(requests, 1); assert.equal(f.session.status, 'paused');
|
||||
assert.equal(f.session.events.find(event => event.kind === 'model').phase, 'interrupted');
|
||||
assert.equal(provider.lastRequest.status, 'interrupted');
|
||||
assert.equal(provider.lastRequest.attempts, 1);
|
||||
assert.equal(Object.hasOwn(provider.lastRequest, 'kind'), false);
|
||||
});
|
||||
|
||||
test('HTTP authentication errors are classified, redacted and never automatically retried', async t => {
|
||||
const model = await compatibleFixture(t, () => ({ status: 401, body: { error: { message: 'Rejected fixture-private-key' } } }));
|
||||
const provider = new Provider({ retryPolicy: policy }); provider.setKey('fixture-private-key');
|
||||
await assert.rejects(provider.complete({ mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture' }, [], null), error => {
|
||||
assert.equal(error.diagnostic.kind, 'authentication'); assert.equal(error.diagnostic.httpStatus, 401);
|
||||
assert.equal(error.diagnostic.attempts, 1); assert.equal(error.diagnostic.retryable, false);
|
||||
assert.ok(error.message.includes('[已隐藏]')); assert.ok(!JSON.stringify(error.diagnostic).includes('fixture-private-key')); return true;
|
||||
});
|
||||
assert.equal(model.requests.length, 1);
|
||||
});
|
||||
|
||||
test('temporary HTTP service errors retry and recover with recorded attempt counts', async t => {
|
||||
const model = await compatibleFixture(t, (_url, _input, requests) => requests.length === 1
|
||||
? { status: 503, body: { error: { message: 'Temporary fixture outage' } } } : completion([], 'Recovered'));
|
||||
const provider = new Provider({ retryPolicy: policy }), progress = [];
|
||||
const result = await provider.complete({ mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture' }, [], null, undefined, value => progress.push(value));
|
||||
assert.equal(result.message.content, 'Recovered'); assert.equal(model.requests.length, 2);
|
||||
assert.ok(progress.some(item => item.phase === 'retrying')); assert.equal(provider.lastRequest.attempts, 2);
|
||||
});
|
||||
|
||||
test('invalid and oversized protocol responses fail once with a useful response-format diagnosis', async () => {
|
||||
for (const content of ['not JSON', 'x'.repeat(4 * 1024 * 1024 + 1)]) {
|
||||
let requests = 0;
|
||||
const provider = new Provider({ retryPolicy: policy, fetch: async () => { requests++; return new Response(content); } });
|
||||
await assert.rejects(provider.complete({ mode: 'compatible', baseUrl: 'http://127.0.0.1:1/v1', model: 'fixture' }, [], null), error => error.diagnostic.kind === 'protocol' && !error.diagnostic.retryable);
|
||||
assert.equal(requests, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('HTTP rate limits expose their source and obey the service retry interval before recovery', async t => {
|
||||
const timestamps = [];
|
||||
const model = await compatibleFixture(t, () => {
|
||||
timestamps.push(Date.now());
|
||||
return timestamps.length === 1 ? { status: 429, headers: { 'Retry-After': '1' }, body: { error: { message: 'Controlled rate limit' } } }
|
||||
: completion([], 'Limit recovered');
|
||||
});
|
||||
const provider = new Provider({ retryPolicy: policy }), progress = [];
|
||||
const result = await provider.complete({ mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture' }, [], null, undefined, value => progress.push(value));
|
||||
assert.equal(result.message.content, 'Limit recovered'); assert.equal(model.requests.length, 2);
|
||||
assert.ok(timestamps[1] - timestamps[0] >= 950, 'The service retry interval must be respected.');
|
||||
const retry = progress.find(value => value.phase === 'retrying');
|
||||
assert.equal(retry.diagnostic.kind, 'rate_limit'); assert.equal(retry.diagnostic.httpStatus, 429);
|
||||
assert.equal(retry.waitMs, 1000); assert.equal(provider.lastRequest.status, 'completed');
|
||||
});
|
||||
|
||||
test('Windows commands preserve Chinese through a PowerShell pipeline into Node', { skip: process.platform !== 'win32' }, async t => {
|
||||
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
|
||||
const command = "@'\nconsole.log(JSON.stringify({ message: '工具·中文完成', value: 2 + 3 }));\n'@ | node --input-type=module\nexit $LASTEXITCODE";
|
||||
const result = await runtime.executeCommand(command, f.projectRoot, new AbortController().signal, () => {});
|
||||
assert.equal(result.status, 'completed', result.stderr); assert.equal(result.exit_code, 0);
|
||||
assert.deepEqual(JSON.parse(result.stdout), { message: '工具·中文完成', value: 5 });
|
||||
assert.ok(!result.stdout.includes('�')); assert.match(projectContext(f.project), /PowerShell 5\.1/);
|
||||
});
|
||||
|
||||
test('Windows shell syntax errors stay readable and native command exit codes are retained', { skip: process.platform !== 'win32' }, async t => {
|
||||
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
|
||||
const invalid = await runtime.executeCommand("Write-Output '未执行的中文' && Write-Output 'ok'", f.projectRoot, new AbortController().signal, () => {});
|
||||
assert.equal(invalid.status, 'failed'); assert.equal(invalid.stdout, ''); assert.match(invalid.stderr, /&&/);
|
||||
assert.ok(!invalid.stderr.includes('�'));
|
||||
const failed = await runtime.executeCommand("node -e 'process.exit(7)'", f.projectRoot, new AbortController().signal, () => {});
|
||||
assert.equal(failed.status, 'failed'); assert.equal(failed.exit_code, 7);
|
||||
});
|
||||
|
||||
test('review and completed states do not turn a generic continue click into a new model request', async t => {
|
||||
const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
let requests = 0; provider.complete = async () => { requests++; throw new Error('Should not be requested'); };
|
||||
for (const status of ['needs_review', 'completed']) {
|
||||
f.session.status = status; assert.throws(() => runtime.resume(f.session.id), { status: 409 });
|
||||
}
|
||||
assert.equal(requests, 0); assert.equal(f.session.providerMessages.length, 0);
|
||||
});
|
||||
|
||||
test('old session data receives a truthful historical connection diagnosis without rewriting history', async t => {
|
||||
const f = fixture(t);
|
||||
f.store.message(f.session, 'system', 'fetch failed'); f.store.event(f.session, { kind: 'error', phase: 'failed', output: 'fetch failed' });
|
||||
const originalMessages = structuredClone(f.session.messages), reloaded = new Store(f.data);
|
||||
const session = reloaded.session(f.session.id), visible = reloaded.publicSession(session);
|
||||
assert.equal(visible.lastFailure.source, 'model_connection'); assert.equal(visible.lastFailure.historical, true);
|
||||
assert.deepEqual(session.messages, originalMessages); assert.equal(Object.hasOwn(visible, 'providerMessages'), false);
|
||||
const snapshot = sessionSnapshot(session, f.project, f.store.config);
|
||||
assert.match(snapshot.lastFailure.detail, /没有保存底层/);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { safePath, readText, readLines, listFiles, searchFiles, proposeFile, applyChange, hash } from '../src/server/files.mjs';
|
||||
import { fixture } from './helpers.mjs';
|
||||
|
||||
test('proposals preserve project bytes until review; apply backs up the exact original bytes', t => {
|
||||
const { store, session, projectRoot, project, data } = fixture(t);
|
||||
const original = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from('原文\r\n第二行\r\n')]);
|
||||
fs.writeFileSync(path.join(projectRoot, 'notes.md'), original);
|
||||
const file = readText(project, 'notes.md');
|
||||
const proposed = proposeFile(store, session, { path: 'notes.md', content: '修改后\n第二行\n', reason: 'Test review', base_sha256: file.sha256 });
|
||||
assert.equal(proposed.status, 'awaiting_review');
|
||||
assert.deepEqual(fs.readFileSync(path.join(projectRoot, 'notes.md')), original);
|
||||
session.status = 'needs_review';
|
||||
const applied = applyChange(store, session, proposed.change_id);
|
||||
assert.equal(applied.status, 'applied');
|
||||
assert.equal(session.status, 'completed');
|
||||
assert.equal(fs.readFileSync(path.join(projectRoot, 'notes.md'), 'utf8'), '修改后\n第二行\n');
|
||||
assert.deepEqual(fs.readFileSync(path.join(data, 'backups', session.id, proposed.change_id + '.txt')), original);
|
||||
assert.throws(() => applyChange(store, session, proposed.change_id));
|
||||
});
|
||||
|
||||
test('new nested files are created only on apply and unchanged content creates no proposal', t => {
|
||||
const { store, session, projectRoot, project } = fixture(t);
|
||||
const current = readText(project, 'README.md');
|
||||
assert.equal(proposeFile(store, session, { path: current.path, content: current.content }).status, 'unchanged');
|
||||
const proposed = proposeFile(store, session, { path: 'docs/new.md', content: '# New\n', base_sha256: null });
|
||||
assert.equal(fs.existsSync(path.join(projectRoot, 'docs')), false);
|
||||
applyChange(store, session, proposed.change_id);
|
||||
assert.equal(fs.readFileSync(path.join(projectRoot, 'docs', 'new.md'), 'utf8'), '# New\n');
|
||||
});
|
||||
|
||||
test('stale reads and changed baselines are rejected without overwriting external edits', t => {
|
||||
const { store, session, projectRoot, project } = fixture(t);
|
||||
const original = readText(project, 'README.md');
|
||||
const change = proposeFile(store, session, { path: 'README.md', content: '# Suggestion\n', base_sha256: original.sha256 });
|
||||
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# External change\n');
|
||||
assert.throws(() => proposeFile(store, session, { path: 'README.md', content: 'replacement', base_sha256: original.sha256 }), { status: 409 });
|
||||
assert.throws(() => applyChange(store, session, change.change_id), { status: 409 });
|
||||
assert.equal(session.changes[0].status, 'conflict');
|
||||
assert.equal(fs.readFileSync(path.join(projectRoot, 'README.md'), 'utf8'), '# External change\n');
|
||||
});
|
||||
|
||||
test('file paths reject traversal, absolute paths, credentials and outside junctions', t => {
|
||||
const { store, session, project, projectRoot, root } = fixture(t);
|
||||
for (const target of ['../outside.txt', 'a/../../outside.txt', 'C:\\Windows\\win.ini', '/etc/passwd', '.env', '.env.local', '.GiT/config', 'data:stream', 'a\0b']) {
|
||||
assert.throws(() => safePath(project, target, true), target);
|
||||
}
|
||||
const outside = path.join(root, 'outside'); fs.mkdirSync(outside);
|
||||
fs.writeFileSync(path.join(outside, 'outside.txt'), 'outside');
|
||||
fs.symlinkSync(outside, path.join(projectRoot, 'link'), process.platform === 'win32' ? 'junction' : 'dir');
|
||||
assert.throws(() => readText(project, 'link/outside.txt'));
|
||||
assert.throws(() => proposeFile(store, session, { path: 'link/new.txt', content: 'must not write' }));
|
||||
assert.ok(!listFiles(project).files.some(file => file.path.startsWith('link')));
|
||||
assert.equal(fs.readFileSync(path.join(outside, 'outside.txt'), 'utf8'), 'outside');
|
||||
});
|
||||
|
||||
test('read and search expose bounded text scopes and reject non UTF-8 / oversized files', t => {
|
||||
const { projectRoot, project } = fixture(t);
|
||||
fs.writeFileSync(path.join(projectRoot, 'lines.txt'), Array.from({ length: 500 }, (_, index) => 'TODO line ' + (index + 1)).join('\n'));
|
||||
const lines = readLines(project, { path: 'lines.txt', start_line: 2, end_line: 500 });
|
||||
assert.equal(lines.start_line, 2); assert.equal(lines.end_line, 301); assert.equal(lines.truncated, true);
|
||||
const results = searchFiles(project, { query: 'TODO' });
|
||||
assert.equal(results.matches.length, 80); assert.equal(results.truncated, true);
|
||||
fs.writeFileSync(path.join(projectRoot, 'binary.bin'), Buffer.from([0, 1]));
|
||||
fs.writeFileSync(path.join(projectRoot, 'invalid.txt'), Buffer.from([0xff, 0xfe]));
|
||||
fs.writeFileSync(path.join(projectRoot, 'large.txt'), 'a'.repeat(1024 * 1024 + 1));
|
||||
for (const file of ['binary.bin', 'invalid.txt', 'large.txt']) assert.throws(() => readText(project, file));
|
||||
assert.equal(hash(Buffer.from('abc')), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
# Legacy Workbench fixture
|
||||
|
||||
`dist-server/server.mjs` is the original Agent Workbench 0.1.0 server bundle created in this project. It is retained as a standalone compatibility fixture so the in-place upgrade test can run from an extracted source package.
|
||||
|
||||
It contains the project's own original implementation and bundled dependencies whose license texts are included in the source release. It contains no user sessions, configuration, API keys, or third-party client recovery artifacts. Tests launch it with an isolated data directory.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,107 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
|
||||
export const workspace = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const fixtureRoot = path.join(workspace, '.qa');
|
||||
|
||||
export function fixture(t) {
|
||||
fs.mkdirSync(fixtureRoot, { recursive: true });
|
||||
const root = fs.mkdtempSync(path.join(fixtureRoot, 'test-'));
|
||||
const projectRoot = path.join(root, 'project');
|
||||
fs.mkdirSync(projectRoot);
|
||||
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Fixture project\n\nA local test project with TODO work.\n');
|
||||
const data = path.join(root, 'data');
|
||||
const store = new Store(data);
|
||||
const project = store.addProject(projectRoot);
|
||||
const session = store.createSession(project.id);
|
||||
const disposers = [];
|
||||
t.after(async () => {
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
const resolved = path.resolve(root);
|
||||
assert.ok(resolved.startsWith(path.resolve(fixtureRoot) + path.sep) && path.basename(resolved).startsWith('test-'));
|
||||
fs.rmSync(resolved, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
||||
});
|
||||
return { root, projectRoot, data, store, project, session, onCleanup: dispose => disposers.push(dispose) };
|
||||
}
|
||||
|
||||
export async function until(predicate, timeout = 8000) {
|
||||
const deadline = Date.now() + timeout;
|
||||
while (!(await predicate())) {
|
||||
if (Date.now() > deadline) throw new Error('Timed out waiting for test state.');
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
}
|
||||
|
||||
export async function compatibleFixture(t, respond) {
|
||||
const requests = [];
|
||||
const server = http.createServer(async (request, response) => {
|
||||
try {
|
||||
const chunks = [];
|
||||
for await (const chunk of request) chunks.push(chunk);
|
||||
const input = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
|
||||
requests.push({ url: request.url, headers: request.headers, input });
|
||||
const result = await respond(request.url, input, requests);
|
||||
response.writeHead(result.status ?? 200, { 'Content-Type': 'application/json', ...result.headers });
|
||||
response.end(JSON.stringify(result.body ?? result));
|
||||
} catch (error) {
|
||||
response.writeHead(500, { 'Content-Type': 'application/json' });
|
||||
response.end(JSON.stringify({ error: { message: error.message } }));
|
||||
}
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
|
||||
return { baseUrl: 'http://127.0.0.1:' + server.address().port + '/v1', requests };
|
||||
}
|
||||
|
||||
export const call = (id, name, args) => ({ id, type: 'function', function: { name, arguments: typeof args === 'string' ? args : JSON.stringify(args) } });
|
||||
export const completion = (calls = [], content = '') => ({ choices: [{ message: { role: 'assistant', content, ...(calls.length ? { tool_calls: calls } : {}) }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 123, completion_tokens: 45 } });
|
||||
|
||||
export function assertToolPairs(messages) {
|
||||
for (let index = 0; index < messages.length; index++) {
|
||||
const message = messages[index];
|
||||
assert.notEqual(message.role, 'tool', 'Orphan tool message');
|
||||
if (!message.tool_calls?.length) continue;
|
||||
const expected = new Set(message.tool_calls.map(call => call.id));
|
||||
for (let count = 0; count < message.tool_calls.length; count++) {
|
||||
const result = messages[++index];
|
||||
assert.equal(result?.role, 'tool');
|
||||
assert.ok(expected.delete(result.tool_call_id), 'Tool result ID mismatch or duplicate');
|
||||
}
|
||||
assert.equal(expected.size, 0);
|
||||
}
|
||||
}
|
||||
|
||||
export async function launchWorkbench(t, data, extraEnv = {}) {
|
||||
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: workspace, AGENT_WORKBENCH_DATA_DIR: data, AGENT_WORKBENCH_PORT: '0', ...extraEnv };
|
||||
delete env.AGENT_WORKBENCH_API_KEY;
|
||||
const child = spawn(process.execPath, [path.join(workspace, 'dist-server', 'server.mjs')], { cwd: workspace, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let output = '', errors = '', url = '';
|
||||
child.stdout.on('data', bytes => {
|
||||
output += bytes.toString('utf8');
|
||||
for (const line of output.split('\n')) { try { const parsed = JSON.parse(line); if (parsed.ready) url = parsed.url; } catch {} }
|
||||
});
|
||||
child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
|
||||
await until(() => url || child.exitCode !== null);
|
||||
assert.ok(url, 'Workbench launch failed: ' + errors);
|
||||
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token },
|
||||
...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw Object.assign(new Error(result.error), { status: response.status });
|
||||
return result;
|
||||
};
|
||||
const close = async () => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
try { await api('/shutdown', {}); await until(() => child.exitCode !== null || child.signalCode !== null, 5000); }
|
||||
finally { if (child.exitCode === null && child.signalCode === null) child.kill(); }
|
||||
};
|
||||
t.after(close);
|
||||
return { child, url, bootstrap, api, close };
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Provider, projectMessages } from '../src/server/provider.mjs';
|
||||
import { Runtime, validateToolArgs } from '../src/server/runtime.mjs';
|
||||
import { fixture, compatibleFixture, call, completion, until, assertToolPairs } from './helpers.mjs';
|
||||
|
||||
function commandProvider(command) {
|
||||
const provider = new Provider();
|
||||
provider.complete = async (_config, messages) => {
|
||||
const latestUser = messages.findLastIndex(message => message.role === 'user');
|
||||
if (!messages.slice(latestUser + 1).some(message => message.role === 'tool')) {
|
||||
return { message: { role: 'assistant', content: '', tool_calls: [call('command-' + latestUser, 'run_command', { command, reason: 'Controlled fixture command' })] }, usage: null };
|
||||
}
|
||||
return { message: { role: 'assistant', content: 'Fixture finished.' }, usage: null };
|
||||
};
|
||||
return provider;
|
||||
}
|
||||
|
||||
test('the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands', async t => {
|
||||
const f = fixture(t);
|
||||
const command = 'node -e "require(\'node:fs\').writeFileSync(\'approved.txt\',\'ok\'); console.log(\'fixture-command\')"';
|
||||
let round = 0;
|
||||
const model = await compatibleFixture(t, (_url, input) => {
|
||||
assert.equal(input.model, 'fixture-agent'); assert.equal(input.stream, false);
|
||||
assert.ok(input.tools.some(tool => tool.function.name === 'propose_file'));
|
||||
assertToolPairs(input.messages);
|
||||
round++;
|
||||
if (round === 1) return completion([
|
||||
call('list', 'list_files', { path: '', depth: 2 }),
|
||||
call('malformed', 'search_files', '{invalid'),
|
||||
call('unknown', 'unknown_tool', {}),
|
||||
]);
|
||||
if (round === 2) {
|
||||
assert.equal(JSON.parse(input.messages.find(item => item.tool_call_id === 'malformed').content).status, 'error');
|
||||
assert.equal(JSON.parse(input.messages.find(item => item.tool_call_id === 'unknown').content).status, 'error');
|
||||
return completion([call('read', 'read_file', { path: 'README.md' })]);
|
||||
}
|
||||
if (round === 3) return completion([
|
||||
call('proposal', 'propose_file', { path: 'FIXTURE-NOTES.md', content: '# Fixture notes\n', reason: 'Controlled proposal' }),
|
||||
call('command', 'run_command', { command, reason: 'Controlled fixture command' }),
|
||||
]);
|
||||
return completion([], 'Fixture task completed.');
|
||||
});
|
||||
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture-agent' });
|
||||
const provider = new Provider(); provider.setKey('fixture-only-secret');
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'Read the fixture and prepare a change.');
|
||||
const promise = runtime.active.get(f.session.id).promise;
|
||||
await until(() => f.session.status === 'awaiting_approval');
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, 'approved.txt')), false);
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, 'FIXTURE-NOTES.md')), false);
|
||||
assert.equal(f.session.events.find(event => event.toolCallId === 'command').phase, 'waiting');
|
||||
const approval = f.session.approvals[0];
|
||||
runtime.decide(f.session.id, approval.id, true);
|
||||
assert.throws(() => runtime.decide(f.session.id, approval.id, true), { status: 409 });
|
||||
await promise;
|
||||
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'approved.txt'), 'utf8'), 'ok');
|
||||
assert.equal(f.session.status, 'needs_review');
|
||||
assert.equal(f.session.usage.prompt_tokens, 123);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
assert.match(f.session.events.find(event => event.toolCallId === 'command').output, /fixture-command/);
|
||||
assert.equal(runtime.isActive(f.session.id), false);
|
||||
assert.ok(model.requests.every(request => request.headers.authorization === 'Bearer fixture-only-secret'));
|
||||
for (const name of fs.readdirSync(path.join(f.data, 'sessions'))) assert.ok(!fs.readFileSync(path.join(f.data, 'sessions', name), 'utf8').includes('fixture-only-secret'));
|
||||
assert.ok(!fs.readFileSync(path.join(f.data, 'config.json'), 'utf8').includes('fixture-only-secret'));
|
||||
});
|
||||
|
||||
test('denial prevents command execution and produces a paired denied result', async t => {
|
||||
const f = fixture(t), runtime = new Runtime(f.store, commandProvider('node --version'));
|
||||
f.onCleanup(() => runtime.stopAll());
|
||||
let executions = 0; runtime.executeCommand = () => { executions++; throw new Error('Must not execute'); };
|
||||
runtime.start(f.session.id, 'test'); const promise = runtime.active.get(f.session.id).promise;
|
||||
await until(() => f.session.status === 'awaiting_approval');
|
||||
assert.throws(() => runtime.start(f.session.id, 'overlap'), { status: 409 });
|
||||
runtime.decide(f.session.id, f.session.approvals[0].id, false); await promise;
|
||||
assert.equal(executions, 0); assert.equal(f.session.events[0].phase, 'denied');
|
||||
assert.equal(f.session.approvals[0].status, 'denied');
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('stopping during approval interrupts pending calls without executing or replaying them', async t => {
|
||||
const f = fixture(t), runtime = new Runtime(f.store, commandProvider('node --version'));
|
||||
f.onCleanup(() => runtime.stopAll());
|
||||
let executions = 0; runtime.executeCommand = () => { executions++; throw new Error('Must not execute'); };
|
||||
runtime.start(f.session.id, 'test');
|
||||
await until(() => f.session.status === 'awaiting_approval');
|
||||
const approvalId = f.session.approvals[0].id;
|
||||
await runtime.stop(f.session.id);
|
||||
assert.equal(executions, 0); assert.equal(f.session.status, 'paused');
|
||||
assert.equal(f.session.approvals[0].status, 'interrupted');
|
||||
assert.equal(f.session.events[0].phase, 'interrupted');
|
||||
assert.throws(() => runtime.decide(f.session.id, approvalId, true), { status: 409 });
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('stopping a running fixture command terminates its own process tree and retains uncertain state', async t => {
|
||||
const f = fixture(t);
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'wait.mjs'), "import fs from 'node:fs'; console.log('fixture-started'); setTimeout(() => { fs.writeFileSync('late.txt', 'late') }, 20000);\n");
|
||||
const runtime = new Runtime(f.store, commandProvider('node wait.mjs')); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'test');
|
||||
await until(() => f.session.status === 'awaiting_approval');
|
||||
runtime.decide(f.session.id, f.session.approvals[0].id, true);
|
||||
await until(() => f.session.events.some(event => event.output?.includes('fixture-started')));
|
||||
const start = Date.now(); await runtime.stop(f.session.id);
|
||||
assert.ok(Date.now() - start < 8000);
|
||||
assert.equal(f.session.status, 'paused'); assert.equal(f.session.events[0].phase, 'interrupted');
|
||||
assert.ok(f.session.events[0].executedAt); assert.equal(fs.existsSync(path.join(f.projectRoot, 'late.txt')), false);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('command output decodes split UTF-8 and excludes the workbench key from child environment', async t => {
|
||||
const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider);
|
||||
f.onCleanup(() => runtime.stopAll());
|
||||
fs.writeFileSync(path.join(f.projectRoot, 'utf8.mjs'), "const bytes = Buffer.from('中文完成'); for (const byte of bytes) { process.stdout.write(Buffer.from([byte])); await new Promise(r => setTimeout(r, 8)); } console.log(''); console.log(process.env.AGENT_WORKBENCH_API_KEY ? 'key-present' : 'key-absent');\n");
|
||||
const previous = process.env.AGENT_WORKBENCH_API_KEY;
|
||||
process.env.AGENT_WORKBENCH_API_KEY = 'fixture-child-environment-key';
|
||||
try {
|
||||
const result = await runtime.executeCommand('node utf8.mjs', f.projectRoot, new AbortController().signal, () => {});
|
||||
assert.equal(result.status, 'completed'); assert.match(result.stdout, /中文完成/);
|
||||
assert.match(result.stdout, /key-absent/); assert.ok(!result.stdout.includes('�'));
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.AGENT_WORKBENCH_API_KEY; else process.env.AGENT_WORKBENCH_API_KEY = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('model-list testing uses a tentative key without changing the saved connection and redacts service errors', async t => {
|
||||
const model = await compatibleFixture(t, (url, _input, requests) => {
|
||||
if (url === '/v1/models') return { data: [{ id: 'fixture-model' }] };
|
||||
return { status: 401, body: { error: { message: 'Rejected fixture-saved-key' } } };
|
||||
});
|
||||
const provider = new Provider(); provider.setKey('fixture-saved-key');
|
||||
const config = { mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture-model', maxOutputTokens: 256 };
|
||||
assert.deepEqual(await provider.models(config, 'fixture-tentative-key'), ['fixture-model']);
|
||||
assert.equal(provider.apiKey, 'fixture-saved-key');
|
||||
assert.equal(model.requests[0].headers.authorization, 'Bearer fixture-tentative-key');
|
||||
await assert.rejects(provider.complete(config, [{ role: 'user', content: 'test' }], null), error => error.message.includes('[已隐藏]') && !error.message.includes('fixture-saved-key'));
|
||||
});
|
||||
|
||||
test('truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities', async t => {
|
||||
const f = fixture(t);
|
||||
const model = await compatibleFixture(t, () => ({ choices: [{ message: { role: 'assistant', tool_calls: [call('cut', 'run_command', { command: 'node --version', reason: 'test' })] }, finish_reason: 'length' }] }));
|
||||
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'fixture-model' });
|
||||
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, 'test'); await runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'failed'); assert.equal(f.session.approvals.length, 0);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
assert.throws(() => validateToolArgs('__proto__', {}));
|
||||
assert.throws(() => validateToolArgs('read_file', { path: 123 }));
|
||||
assert.throws(() => validateToolArgs('list_files', { path: '', depth: -1 }));
|
||||
const repeatedProvider = new Provider();
|
||||
repeatedProvider.complete = async () => ({ message: { role: 'assistant', content: '', tool_calls: [call('same', 'list_files', { path: '' })] }, usage: null });
|
||||
const other = new Runtime(f.store, repeatedProvider); f.onCleanup(() => other.stopAll());
|
||||
other.start(f.session.id, 'another task'); await other.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'failed'); assert.match(f.session.messages.at(-1).content, /重复/);
|
||||
assertToolPairs(f.session.providerMessages);
|
||||
});
|
||||
|
||||
test('request projection keeps tool pairs and complete recent user instructions while preserving disk history', () => {
|
||||
const messages = [];
|
||||
for (let index = 0; index < 8; index++) {
|
||||
messages.push({ role: 'user', content: index === 7 ? '最新指令'.repeat(2500) : 'User turn ' + index });
|
||||
messages.push({ role: 'assistant', content: 'Answer', tool_calls: [call('read-' + index, 'read_file', { path: 'README.md', historical: 'x'.repeat(14000) })] });
|
||||
messages.push({ role: 'tool', tool_call_id: 'read-' + index, content: 'result'.repeat(7000) });
|
||||
}
|
||||
const original = structuredClone(messages), projected = projectMessages(messages, 16000);
|
||||
assert.equal(projected.projected, true); assert.ok(projected.estimatedTokens < projected.beforeTokens);
|
||||
assertToolPairs(projected.messages);
|
||||
assert.equal(projected.messages.findLast(message => message.role === 'user').content, messages.findLast(message => message.role === 'user').content);
|
||||
assert.deepEqual(messages, original);
|
||||
for (const message of projected.messages) for (const tool of message.tool_calls ?? []) assert.doesNotThrow(() => JSON.parse(tool.function.arguments));
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Store, atomicJson, readJson, repairToolPairs, now } from '../src/server/store.mjs';
|
||||
import { proposeFile } from '../src/server/files.mjs';
|
||||
import { fixture, call, assertToolPairs } from './helpers.mjs';
|
||||
|
||||
test('JSON state keeps an atomic backup and preserves corrupt primary files', t => {
|
||||
const { root } = fixture(t), file = path.join(root, 'atomic.json');
|
||||
atomicJson(file, { revision: 1 }); atomicJson(file, { revision: 2 });
|
||||
assert.deepEqual(readJson(file, null), { revision: 2 });
|
||||
fs.writeFileSync(file, '{incomplete');
|
||||
assert.deepEqual(readJson(file, null), { revision: 1 });
|
||||
assert.ok(fs.readdirSync(root).some(name => name.startsWith('atomic.json.corrupt-')));
|
||||
});
|
||||
|
||||
test('tool-pair recovery fills missing results and drops orphan or duplicate results', () => {
|
||||
const repaired = repairToolPairs([
|
||||
{ role: 'tool', tool_call_id: 'orphan', content: '{}' },
|
||||
{ role: 'assistant', content: '', tool_calls: [call('a', 'read_file', { path: 'README.md' }), call('b', 'run_command', { command: 'node --version', reason: 'test' })] },
|
||||
{ role: 'tool', tool_call_id: 'a', content: '{"status":"completed"}' },
|
||||
{ role: 'tool', tool_call_id: 'a', content: 'duplicate' },
|
||||
{ role: 'tool', tool_call_id: 'wrong', content: '{}' },
|
||||
]);
|
||||
assert.equal(repaired.interrupted, 1); assert.equal(repaired.changed, true);
|
||||
assertToolPairs(repaired.messages);
|
||||
assert.equal(JSON.parse(repaired.messages.at(-1).content).requires_verification, true);
|
||||
});
|
||||
|
||||
test('restart pauses unfinished work, retains proposals and never replays a command', t => {
|
||||
const { store, session, data, projectRoot } = fixture(t);
|
||||
const proposal = proposeFile(store, session, { path: 'new.md', content: '# Pending\n' });
|
||||
session.status = 'awaiting_approval';
|
||||
session.providerMessages = [{ role: 'user', content: 'test' }, { role: 'assistant', content: '', tool_calls: [call('unfinished', 'run_command', { command: 'node --version', reason: 'test' })] }];
|
||||
session.events.push({ id: 'interrupted-event', phase: 'running', executedAt: now() });
|
||||
session.approvals.push({ id: 'approval', status: 'pending', command: 'node --version' });
|
||||
store.save(session); const previousRevision = session.revision;
|
||||
const recoveredStore = new Store(data), recovered = recoveredStore.session(session.id);
|
||||
assert.equal(recovered.status, 'paused');
|
||||
assert.equal(recovered.events[0].phase, 'interrupted');
|
||||
assert.match(recovered.events[0].output, /进入执行阶段/);
|
||||
assert.doesNotMatch(recovered.events[0].output, /命令已开始/);
|
||||
assert.equal(recovered.approvals[0].status, 'interrupted');
|
||||
assert.equal(recovered.changes[0].id, proposal.change_id);
|
||||
assert.equal(recovered.changes[0].status, 'pending');
|
||||
assert.equal(fs.existsSync(path.join(projectRoot, 'new.md')), false);
|
||||
assert.ok(recovered.revision > previousRevision); assertToolPairs(recovered.providerMessages);
|
||||
assert.equal(JSON.parse(recovered.providerMessages.at(-1).content).status, 'interrupted');
|
||||
});
|
||||
|
||||
test('public snapshots carry increasing revisions without the private provider transcript or config key', t => {
|
||||
const { store, session, data } = fixture(t);
|
||||
const initial = store.publicSession(session);
|
||||
store.message(session, 'user', 'saved');
|
||||
const updated = store.publicSession(session);
|
||||
assert.ok(updated.revision > initial.revision);
|
||||
assert.equal(Object.hasOwn(updated, 'providerMessages'), false);
|
||||
assert.equal(store.listSessions()[0].revision, updated.revision);
|
||||
store.saveConfig({ apiKey: 'fixture-secret-key', mode: 'demo' });
|
||||
assert.equal(Object.hasOwn(store.config, 'apiKey'), false);
|
||||
assert.ok(!fs.readFileSync(path.join(data, 'config.json'), 'utf8').includes('fixture-secret-key'));
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fixture, compatibleFixture, until, workspace } from './helpers.mjs';
|
||||
import { upgradeRunning } from '../scripts/upgrade-running.mjs';
|
||||
|
||||
test('the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection', { timeout: 30000 }, async t => {
|
||||
const f = fixture(t);
|
||||
const oldRoot = path.join(workspace, 'tests', 'fixtures', 'legacy-workbench-0.1');
|
||||
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: oldRoot, AGENT_WORKBENCH_DATA_DIR: f.data, AGENT_WORKBENCH_PORT: '0' };
|
||||
delete env.AGENT_WORKBENCH_API_KEY;
|
||||
const child = spawn(process.execPath, [path.join(oldRoot, 'dist-server', 'server.mjs')], { cwd: oldRoot, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let url = '', output = '', stderr = '';
|
||||
child.stdout.on('data', bytes => { output += bytes.toString('utf8'); for (const line of output.split('\n')) { try { const result = JSON.parse(line); if (result.ready) url = result.url; } catch {} } });
|
||||
child.stderr.on('data', bytes => { stderr += bytes.toString('utf8'); });
|
||||
await until(() => url || child.exitCode !== null); assert.ok(url, stderr);
|
||||
let bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
const api = async (route, input) => {
|
||||
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) });
|
||||
const value = await response.json(); assert.ok(response.ok, value.error); return value;
|
||||
};
|
||||
f.onCleanup(async () => { try { if (child.exitCode === null && child.signalCode === null) { await api('/shutdown', {}); await until(() => child.exitCode !== null, 5000); } } finally { if (child.exitCode === null && child.signalCode === null) child.kill(); } });
|
||||
const model = await compatibleFixture(t, () => ({ data: [{ id: 'upgrade-fixture' }] }));
|
||||
await api('/config', { mode: 'compatible', model: 'upgrade-fixture', baseUrl: model.baseUrl, apiKey: 'fixture-upgrade-memory-key' });
|
||||
await api('/sessions/' + f.session.id + '/proposals', { path: 'UPGRADE-NOTE.md', content: '# Preserve this verified change\n', reason: 'Fixture before in-place upgrade' });
|
||||
const proposed = await api('/sessions/' + f.session.id); await api('/sessions/' + f.session.id + '/changes/' + proposed.changes[0].id + '/apply', {});
|
||||
const beforeBytes = fs.readFileSync(path.join(f.projectRoot, 'UPGRADE-NOTE.md'));
|
||||
const result = await upgradeRunning({ url, pid: child.pid, currentRoot: oldRoot, newRoot: workspace });
|
||||
assert.equal(result.version, '1.0.0'); assert.equal(result.pid, child.pid); assert.equal(result.verified, true);
|
||||
assert.equal(result.hasKey, true); bootstrap = await (await fetch(url + '/api/bootstrap')).json();
|
||||
assert.equal(bootstrap.config.hasKey, true); assert.equal(bootstrap.config.model, 'upgrade-fixture');
|
||||
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'UPGRADE-NOTE.md')), beforeBytes);
|
||||
assert.equal((await api('/sessions/' + f.session.id)).changes[0].status, 'applied');
|
||||
assert.equal((await api('/diagnostics?session=' + f.session.id)).version, '1.0.0');
|
||||
assert.deepEqual((await api('/config/models', {})).models, ['upgrade-fixture']);
|
||||
assert.equal(model.requests[0].headers.authorization, 'Bearer fixture-upgrade-memory-key');
|
||||
assert.ok(!fs.readFileSync(path.join(f.data, 'config.json'), 'utf8').includes('fixture-upgrade-memory-key'));
|
||||
const health = await (await fetch(url + '/api/health')).json(); assert.equal(health.pid, child.pid);
|
||||
await assert.rejects(fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) }));
|
||||
});
|
||||
Reference in New Issue
Block a user