Files
Agent-Workbench/tests/file-proposal-drafts.test.mjs

97 lines
8.5 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, compatibleFixture, completion, call, until } from './helpers.mjs';
import { proposeFileChunk, discardFileDraft, pendingFileDrafts } from '../src/core/workspaces/file-proposal-drafts.mjs';
import { hash, applyChange } from '../src/server/files.mjs';
import { Store } from '../src/server/store.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
const start = t => { const f = fixture(t); f.store.beginRun(f.session, 'Create a complete file.', false, f.store.config); return f; };
const input = (content, extra = {}) => ({ path: 'long.html', content, reason: 'Owned long file', offset: 0, complete: false, base_sha256: null, ...extra });
const next = (result, content, complete = false) => input(content, { draft_id: result.draft_id, offset: result.next_offset, expected_sha256: result.draft_sha256, complete });
test('fragments persist across restart, reject duplicate/out-of-order appends, and create exactly one whole review proposal', t => {
const f = start(t), first = proposeFileChunk(f.store, f.session, input('<html>中文😀\r\n'));
assert.equal(f.session.changes.length, 0); assert.equal(fs.existsSync(path.join(f.projectRoot, 'long.html')), false);
assert.throws(() => applyChange(f.store, f.session, first.draft_id));
assert.throws(() => proposeFileChunk(f.store, f.session, { ...next(first, 'duplicate'), offset: 0 }), /offset或SHA/);
f.store.close();
const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
const session = reopened.sessions.get(f.session.id);
const last = proposeFileChunk(reopened, session, next(first, '</html>\n', true));
assert.equal(session.changes.length, 1); assert.equal(session.changes[0].content, '<html>中文😀\r\n</html>\n');
assert.equal(session.changes[0].sha256, hash(Buffer.from(session.changes[0].content)));
assert.equal(last.change_id, session.changes[0].id); assert.equal(pendingFileDrafts(session).length, 0);
assert.throws(() => proposeFileChunk(reopened, session, next(first, '</html>', true)), /已结束/);
assert.equal(session.changes.length, 1); assert.equal(fs.existsSync(path.join(f.projectRoot, 'long.html')), false);
});
test('source edits, foreign tasks, malformed input, oversize text and changed fragment identities cannot finalize', t => {
const f = start(t), target = path.join(f.projectRoot, 'README.md'), base = hash(fs.readFileSync(target));
const first = proposeFileChunk(f.store, f.session, input('New start', { path: 'README.md', base_sha256: base }));
fs.appendFileSync(target, 'External change\n');
assert.throws(() => proposeFileChunk(f.store, f.session, { ...next(first, 'tail', true), path: 'README.md', base_sha256: base }), /原文件已变化/);
assert.match(fs.readFileSync(target, 'utf8'), /External change/); assert.equal(f.session.changes.length, 0);
const draft = proposeFileChunk(f.store, f.session, input('Original draft', { path: 'new.txt' }));
for (const malformed of [input('x', { path: '../outside.txt' }), input('\ud800'), input('\0'), input('x'.repeat(512001)), input('x', { complete: 'true' })]) assert.throws(() => proposeFileChunk(f.store, f.session, malformed));
const fragment = f.store.core.artifact.get(pendingFileDrafts(f.session).find(row => row.id === draft.draft_id).chunks[0].id), originalSha = fragment.sha256;
fragment.sha256 = '0'.repeat(64);
assert.throws(() => proposeFileChunk(f.store, f.session, { ...next(draft, 'tail', true), path: 'new.txt' }), /片段身份/); fragment.sha256 = originalSha;
const oldTask = f.session.taskId; f.session.taskId = '00000000-0000-0000-0000-000000000000';
assert.throws(() => proposeFileChunk(f.store, f.session, { ...next(draft, 'tail', true), path: 'new.txt' })); f.session.taskId = oldTask;
discardFileDraft(f.store, f.session, { draft_id: draft.draft_id, expected_sha256: draft.draft_sha256, reason: 'Replan the file' });
assert.equal(f.session.fileDrafts.find(row => row.id === draft.draft_id).status, 'discarded');
});
test('a truncated continuation cannot append half JSON; recovery continues the original draft and produces one complete file', async t => {
const f = fixture(t), pieces = ['<html>\n' + '中文😀\n'.repeat(200), '<p>Body</p>\n', '</html>\n'];
let receipt, count = 0;
const server = await compatibleFixture(t, (_url, body) => {
count++;
const tools = body.messages.filter(row => row.role === 'tool').map(row => JSON.parse(row.content));
receipt = tools.findLast(row => row.draft_id) ?? receipt;
if (count === 1) return completion([call('chunk-a', 'propose_file_chunk', input(pieces[0]))]);
if (count === 2) return { ...completion([call('never-append', 'propose_file_chunk', '{"path":"long.html","content":"PARTIAL')]), choices: [{ message: { role: 'assistant', content: '', tool_calls: [call('never-append', 'propose_file_chunk', '{"path":"long.html","content":"PARTIAL')] }, finish_reason: 'length' }] };
if (count === 3) return completion([call('chunk-final', 'propose_file_chunk', next(receipt, pieces[1] + pieces[2], true))]);
return completion([], 'The complete proposal is ready for review.');
});
const provider = new Provider(), hub = provider.modelHub(f.store), c = hub.upsert({ name: 'Owned small output', model: 'owned', baseUrl: server.baseUrl, requiresKey: false, maxOutputTokens: 2048 });
hub.select({ type: 'connection', id: c.id }); const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Create long.html using reviewable proposals, no tests requested.'); await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(f.session.status, 'needs_review', JSON.stringify(f.session.events.slice(-6))); assert.equal(count, 4);
assert.equal(f.session.changes.length, 1); assert.equal(f.session.changes[0].content, pieces.join(''));
assert.equal(f.session.fileDrafts[0].chunks.length, 2); assert.equal(f.session.fileDrafts[0].status, 'finalized');
assert.equal(f.session.events.filter(event => event.toolCallId === 'never-append').length, 0);
assert.ok(f.session.providerMessages.some(row => row.role === 'user' && row.content.includes('propose_file_chunk')));
assert.equal(fs.existsSync(path.join(f.projectRoot, 'long.html')), false);
});
test('an unfinished draft cannot be described as a completed task', async t => {
const f = fixture(t), server = await compatibleFixture(t, (_url, body) => body.messages.some(row => row.role === 'tool') ? completion([], 'Done.') : completion([call('partial', 'propose_file_chunk', input('Only the beginning'))]));
const provider = new Provider(), hub = provider.modelHub(f.store), c = hub.upsert({ name: 'Owned partial', model: 'owned', baseUrl: server.baseUrl, requiresKey: false });
hub.select({ type: 'connection', id: c.id }); const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Prepare the project.'); await until(() => !runtime.isActive(f.session.id), 15000);
assert.equal(f.session.status, 'paused', JSON.stringify(f.session.events.slice(-6))); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'file_draft_incomplete');
assert.equal(f.session.changes.length, 0); assert.equal(pendingFileDrafts(f.session).length, 1);
});
test('a failed final save preserves the last successful receipt and cannot publish half a finalized proposal', t => {
const f = start(t), first = proposeFileChunk(f.store, f.session, input('Original fragment\n'));
const save = f.store.storage.save;
f.store.storage.save = () => { throw new Error('Owned storage failure'); };
assert.throws(() => proposeFileChunk(f.store, f.session, next(first, 'Final fragment\n', true)), /Owned storage failure/);
f.store.storage.save = save;
assert.equal(f.session.changes.length, 0);
assert.equal(pendingFileDrafts(f.session)[0].sha256, first.draft_sha256);
assert.equal(pendingFileDrafts(f.session)[0].chunks.length, 1);
const final = proposeFileChunk(f.store, f.session, next(first, 'Final fragment\n', true));
assert.equal(f.session.changes.length, 1); assert.equal(final.change_id, f.session.changes[0].id);
f.store.close(); const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
const session = reopened.session(f.session.id);
assert.equal(session.changes.length, 1); assert.equal(session.changes[0].content, 'Original fragment\nFinal fragment\n');
assert.equal(pendingFileDrafts(session).length, 0); assert.equal(fs.existsSync(path.join(f.projectRoot, 'long.html')), false);
});