171 lines
14 KiB
JavaScript
171 lines
14 KiB
JavaScript
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';
|
|
import { createSessionPublisher } from '../src/server/app.mjs';
|
|
|
|
test('large source receipts use cursor-preserving invalidation without filling the event stream or changing the session', () => {
|
|
const session = { id: 'owned-session', projectId: 'owned-project', revision: 10, eventSeq: 42, source: '汉'.repeat(24000) };
|
|
let queued = 0, destroyed = false; const chunks = [];
|
|
const response = { get writableLength() { return queued; }, write(value) { queued += Buffer.byteLength(value); chunks.push(value); }, destroy() { destroyed = true; } };
|
|
const publish = createSessionPublisher(new Set([response]));
|
|
for (let i = 0; i < 100; i++) publish(session);
|
|
assert.equal(destroyed, false); assert.ok(queued < 64 * 1024);
|
|
assert.ok(chunks.every(value => value.startsWith('id: 42\ndata: ')));
|
|
assert.deepEqual(JSON.parse(chunks[0].split('\ndata: ')[1]), { kind: 'session_changed', seq: 42, sessionId: session.id, projectId: session.projectId, revision: 10 });
|
|
assert.equal(session.source, '汉'.repeat(24000)); assert.equal(session.eventSeq, 42);
|
|
});
|
|
|
|
test('small event updates retain the current session and actual cursor', () => {
|
|
const session = { id: 'owned-small', projectId: 'owned-project', revision: 3, eventSeq: 7, status: 'awaiting_approval' }, chunks = [];
|
|
createSessionPublisher(new Set([{ write(value) { chunks.push(value); } }]))(session);
|
|
assert.deepEqual(JSON.parse(chunks[0].split('\ndata: ')[1]), { kind: 'session', seq: 7, session });
|
|
assert.ok(chunks[0].startsWith('id: 7\n'));
|
|
});
|
|
|
|
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(), /<title>Orven · AI 开发工作台<\/title>/);
|
|
assert.equal(page.headers.get('x-frame-options'), 'DENY');
|
|
assert.equal(page.headers.get('referrer-policy'), 'no-referrer');
|
|
assert.match(page.headers.get('content-security-policy'), /script-src 'self'/);
|
|
assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/);
|
|
await server.close();
|
|
});
|
|
|
|
test('an in-flight connection probe prevents configuration changes and another probe until its actual result returns', async t => {
|
|
const f = fixture(t), host = await launchWorkbench(t, f.data); f.onCleanup(host.close);
|
|
let release;
|
|
const model = await compatibleFixture(t, async () => { await new Promise(resolve => { release = resolve; }); return { choices: [{ message: { role: 'assistant', content: 'OK' } }] }; });
|
|
await host.api('/config', { mode: 'compatible', model: 'owned-probe-model', baseUrl: model.baseUrl, apiKey: 'owned-probe-fixture' });
|
|
const probing = host.api('/config/test', {});
|
|
await until(() => !!release);
|
|
await assert.rejects(host.api('/config', { mode: 'demo' }), { status: 409 });
|
|
await assert.rejects(host.api('/config/test', {}), { status: 409 });
|
|
await assert.rejects(host.api('/model-center/connections', { name: 'Blocked', model: 'owned-model', baseUrl: model.baseUrl }), { status: 409 });
|
|
assert.equal(model.requests.length, 1); assert.equal((await host.api('/bootstrap')).config.model, 'owned-probe-model');
|
|
release(); assert.equal((await probing).ok, true);
|
|
assert.equal((await host.api('/config', { mode: 'demo', model: 'owned-probe-model', baseUrl: model.baseUrl })).mode, 'demo');
|
|
});
|
|
|
|
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, bootstrap.version); 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');
|
|
});
|
|
|
|
test('persistent event replay is read-only and keeps run/artifact identity across reconnects', async t => {
|
|
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
|
const cursor = server.bootstrap.eventCursor;
|
|
await server.api('/sessions/' + f.session.id + '/messages', { content: 'Use the controlled offline fixture' });
|
|
let waiting;
|
|
await until(async () => { waiting = await server.api('/sessions/' + f.session.id); return waiting.status === 'awaiting_approval'; }, 12000);
|
|
await server.api('/sessions/' + f.session.id + '/approvals/' + waiting.approvals[0].id, { allow: false });
|
|
let ended;
|
|
await until(async () => { ended = await server.api('/sessions/' + f.session.id); return ended.status === 'needs_review'; }, 12000);
|
|
const history = await server.api('/events/history?after=' + cursor + '&session=' + f.session.id + '&limit=3');
|
|
assert.equal(history.events.length, 3); assert.equal(history.hasMore, true);
|
|
assert.ok(history.events.every(value => value.taskId === ended.execution.task.id && value.runId === ended.execution.run.id));
|
|
const artifact = ended.execution.artifacts.find(value => value.kind === 'tool-result');
|
|
const result = await server.api('/artifacts/' + artifact.id + '?session=' + f.session.id);
|
|
assert.equal(result.sha256, artifact.sha256); assert.ok(result.content);
|
|
const other = await server.api('/sessions', { projectId: f.project.id });
|
|
await assert.rejects(server.api('/artifacts/' + artifact.id + '?session=' + other.id), { status: 404 });
|
|
const stop = new AbortController();
|
|
const stream = await fetch(server.url + '/api/events?token=' + encodeURIComponent(server.bootstrap.token) + '&after=' + cursor,
|
|
{ headers: { 'Last-Event-ID': String(history.nextCursor) }, signal: stop.signal });
|
|
const reader = stream.body.getReader(); const bytes = await reader.read(); const text = Buffer.from(bytes.value).toString('utf8');
|
|
stop.abort(); await reader.cancel().catch(() => {});
|
|
assert.match(text, /session_changed/); assert.match(text, /id: \d+/);
|
|
const replayedIds = [...text.matchAll(/^id: (\d+)$/gm)].map(match => Number(match[1]));
|
|
assert.ok(replayedIds.every(value => value > history.nextCursor));
|
|
const after = await server.api('/sessions/' + f.session.id);
|
|
assert.equal(after.runId, ended.runId); assert.equal(after.approvals.length, ended.approvals.length);
|
|
assert.deepEqual(after.changes, ended.changes); assert.equal(after.execution.run.toolCalls, ended.execution.run.toolCalls);
|
|
});
|