249 lines
9.7 KiB
JavaScript
249 lines
9.7 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs/promises';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import test from 'node:test';
|
|
import { lockProjectSession } from '../src/production-goal.mjs';
|
|
import { openProductionOperations } from '../src/production-operations.mjs';
|
|
import { ProjectStore } from '../src/store.mjs';
|
|
import { openAgent } from './fake-canvas.mjs';
|
|
import { piInfo, piProject } from './pi-compat-fixture.mjs';
|
|
|
|
const cleanup = dir => fs.rm(dir, { recursive: true, force: true });
|
|
|
|
function productionStore(dir) {
|
|
return {
|
|
dir,
|
|
root: dir,
|
|
identity: { project: 'fixture-project', account: 'fixture-account', scope: 'fixture-scope' },
|
|
appendEvent: async () => {},
|
|
};
|
|
}
|
|
|
|
test('Wave 2A: image worker first turn sends reference index and critical attachments only, while read_slot_images fetches all', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-w2a-worker-'));
|
|
t.after(() => cleanup(dir));
|
|
|
|
const refs = ['p1', 'p2', 'p3', 'p4'].map(data => ({ type: 'image', mimeType: 'image/jpeg', data }));
|
|
const layout = { type: 'image', mimeType: 'image/jpeg', data: 'layout-base' };
|
|
const observed = [];
|
|
|
|
const host = {
|
|
store: productionStore(dir),
|
|
productionGoal: { outputId: 'detail', variantId: 'oak' },
|
|
canvas: {
|
|
workflowRead: async () => ({
|
|
available: true,
|
|
canvasFirst: true,
|
|
outputId: 'detail',
|
|
productVariantId: 'oak',
|
|
template: { contentHash: 'tpl-1', production: { referenceMode: 'template-base' } },
|
|
productEvidence: {
|
|
brief: {
|
|
name: '实木餐桌',
|
|
images: [
|
|
{ id: 'img-1', name: 'front.jpg', label: '主视图' },
|
|
{ id: 'img-2', name: 'leg.jpg', label: '桌腿特写' },
|
|
{ id: 'img-3', name: 'corner.jpg', label: '倒角细节' },
|
|
{ id: 'img-4', name: 'scene.jpg', label: '场景图' },
|
|
],
|
|
},
|
|
},
|
|
totalSlots: 1,
|
|
slots: [{ id: 'slot-1', fieldId: 'D01', label: '桌腿结构', candidates: [] }],
|
|
}),
|
|
detailCopyFields: async () => ({ fields: [] }),
|
|
detailImages: async (_slotId, _candidateId, opts) => ({
|
|
referenceCount: refs.length,
|
|
layoutCount: opts?.includeTemplateReference === false ? 0 : 1,
|
|
referenceBindings: ['P02'],
|
|
images: opts?.includeTemplateReference === false ? refs : [...refs, layout],
|
|
}),
|
|
imageRequest: async () => [],
|
|
delta: async () => {},
|
|
},
|
|
async runDetailAgent(slotId, instructions, prompt, tools, images, _scope, captions) {
|
|
const parsed = JSON.parse(prompt);
|
|
const readTool = tools.find(tool => tool.name === 'read_slot_images');
|
|
const fullRead = await readTool.execute('read-all', {});
|
|
observed.push({ slotId, instructions, parsed, images, captions, fullRead });
|
|
},
|
|
};
|
|
|
|
const ops = await openProductionOperations(host);
|
|
t.after(() => ops.close());
|
|
await ops.delegate_image_slots({ jobs: [{ slotId: 'D01', goal: '展示加厚桌腿' }] });
|
|
await ops.await_image_slots({ slotIds: ['D01'] });
|
|
|
|
assert.equal(observed.length, 1);
|
|
const [{ parsed, images, captions, fullRead }] = observed;
|
|
assert.deepEqual(parsed.productReferences, ['P01', 'P02', 'P03', 'P04']);
|
|
assert.deepEqual(parsed.productReferenceIndex, [
|
|
{ id: 'P01', fileName: 'front.jpg', purpose: '主视图' },
|
|
{ id: 'P02', fileName: 'leg.jpg', purpose: '桌腿特写' },
|
|
{ id: 'P03', fileName: 'corner.jpg', purpose: '倒角细节' },
|
|
{ id: 'P04', fileName: 'scene.jpg', purpose: '场景图' },
|
|
]);
|
|
assert.deepEqual(images, [refs[1], layout]);
|
|
assert.deepEqual(captions, ['P02', '模板构图参考']);
|
|
assert.deepEqual(fullRead.content.slice(1), [...refs, layout]);
|
|
});
|
|
|
|
test('Wave 2A: worker session enables context compaction instead of hard-disabling it', async t => {
|
|
const store = await piProject(t);
|
|
const info = piInfo(store);
|
|
const host = await openAgent({
|
|
store,
|
|
transport: {
|
|
info,
|
|
stream: () => {
|
|
throw Error('unexpected stream');
|
|
},
|
|
},
|
|
});
|
|
t.after(() => host.dispose());
|
|
const compaction = host.session.settingsManager.getCompactionSettings(host.session.model);
|
|
assert.equal(compaction.enabled, true);
|
|
const agentSource = await fs.readFile(new URL('../src/agent.mjs', import.meta.url), 'utf8');
|
|
assert.doesNotMatch(agentSource, /workerSettings\s*=\s*SettingsManager\.inMemory\([^)]*compaction:\s*\{\s*enabled:\s*false\s*\}/);
|
|
});
|
|
|
|
test('Wave 2A: production operations cache liveSlots/current/progressSummary across reads and invalidate on write', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-w2a-cache-'));
|
|
t.after(() => cleanup(dir));
|
|
|
|
let workflowReads = 0;
|
|
let slotPageReads = 0;
|
|
let copyReads = 0;
|
|
let retired = false;
|
|
const slots = () => [
|
|
{
|
|
id: 'slot-1',
|
|
fieldId: 'D01',
|
|
label: '首图',
|
|
candidates: retired ? [] : [{ id: 'cand-1', status: 'complete' }],
|
|
},
|
|
];
|
|
|
|
const host = {
|
|
store: productionStore(dir),
|
|
productionGoal: { outputId: 'detail', variantId: 'oak' },
|
|
canvas: {
|
|
workflowRead: async args => {
|
|
workflowReads++;
|
|
if (args?.section !== 'overview') slotPageReads++;
|
|
return {
|
|
available: true,
|
|
canvasFirst: true,
|
|
outputId: 'detail',
|
|
productVariantId: 'oak',
|
|
revisions: { creation: 1, slots: retired ? 2 : 1 },
|
|
template: { contentHash: 'tpl-cache' },
|
|
totalSlots: 1,
|
|
slots: slots(),
|
|
};
|
|
},
|
|
detailCopyFields: async ({ includeFilled } = {}) => {
|
|
if (includeFilled) copyReads++;
|
|
return { fields: [], progressSummary: { ready: true } };
|
|
},
|
|
detailRetire: async () => {
|
|
retired = true;
|
|
return { status: 'retired' };
|
|
},
|
|
imageRequest: async () => [],
|
|
delta: async () => {},
|
|
},
|
|
};
|
|
|
|
const ops = await openProductionOperations(host);
|
|
t.after(() => ops.close());
|
|
const initialSlotPageReads = slotPageReads;
|
|
|
|
await ops.review_image_slots({});
|
|
await ops.review_image_slots({ slotIds: ['D01'] });
|
|
assert.equal(slotPageReads, initialSlotPageReads, 'consecutive reads at same revision should reuse cached slots');
|
|
await ops.plan_production({});
|
|
assert.equal(copyReads, 3, 'plan_production should use a single copySnapshot call for fieldConflicts and progressSummary');
|
|
|
|
await ops.retire_production_image({ slotId: 'D01', candidateId: 'cand-1', reason: '重做' });
|
|
const afterRetire = await ops.review_image_slots({ slotIds: ['D01'] });
|
|
assert.ok(slotPageReads > initialSlotPageReads, 'write should invalidate cached slots');
|
|
assert.equal(afterRetire.pictures[0].candidates.length, 0);
|
|
});
|
|
|
|
test('Wave 2A: lockProjectSession uses single lock file without claim lock and blocks concurrent writers', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-w2a-lock-'));
|
|
t.after(() => cleanup(dir));
|
|
const root = path.join(dir, 'project');
|
|
await fs.mkdir(root, { recursive: true });
|
|
|
|
const unlock = await lockProjectSession(root);
|
|
await assert.rejects(fs.stat(root + '.lock.claim'), { code: 'ENOENT' });
|
|
await assert.rejects(lockProjectSession(root), /已有本地Agent/);
|
|
unlock();
|
|
|
|
const unlock2 = await lockProjectSession(root);
|
|
unlock2();
|
|
await assert.rejects(fs.stat(root + '.lock'), { code: 'ENOENT' });
|
|
});
|
|
|
|
test('Wave 2A: unknown image outcome preserves original requestId and blocks duplicate dispatch on same slot', async t => {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-w2a-reqid-'));
|
|
t.after(() => cleanup(dir));
|
|
|
|
const dispatches = [];
|
|
const pending = [];
|
|
let seq = 0;
|
|
const requests = new Map();
|
|
|
|
const host = {
|
|
store: productionStore(dir),
|
|
productionGoal: { outputId: 'detail', variantId: 'oak' },
|
|
canvas: {
|
|
workflowRead: async () => ({
|
|
available: true,
|
|
canvasFirst: true,
|
|
outputId: 'detail',
|
|
productVariantId: 'oak',
|
|
template: { contentHash: 'tpl-dedup' },
|
|
totalSlots: 1,
|
|
slots: [{ id: 'slot-1', fieldId: 'D01', label: '首图', candidates: [] }],
|
|
}),
|
|
detailCopyFields: async () => ({ fields: [] }),
|
|
imageRequest: async (action, args = {}) => {
|
|
if (action === 'pending') return pending;
|
|
if (action === 'prepare') {
|
|
const requestId = `req-${++seq}`;
|
|
const row = { requestId, slotId: args.slotId, templateHash: 'tpl-dedup', outputId: 'detail', variantId: 'oak', phase: 'prepared', revision: 1, requestSpecHash: 'h1' };
|
|
requests.set(requestId, row);
|
|
return row;
|
|
}
|
|
if (action === 'read') return requests.get(args.requestId);
|
|
if (action === 'dispatch') {
|
|
dispatches.push(args.requestId);
|
|
pending.push({ outputId: 'detail', variantId: 'oak', slotId: args.slotId, candidateId: args.requestId, operationId: args.requestId, status: 'unknown' });
|
|
return { id: args.requestId, status: 'unknown', message: '网关超时,结果未知' };
|
|
}
|
|
return [];
|
|
},
|
|
delta: async () => {},
|
|
},
|
|
};
|
|
|
|
const ops = await openProductionOperations(host);
|
|
t.after(() => ops.close());
|
|
|
|
const prep1 = await ops.prepare_image_request({ slotId: 'D01', prompt: '第一版提示词' });
|
|
await ops.dispatch_image_request({ requestId: prep1.requestId });
|
|
const waited = await ops.await_image_slots({ slotIds: ['D01'] });
|
|
assert.equal(waited.generation[0].phase, 'unknown');
|
|
assert.equal(waited.generation[0].operationId, prep1.requestId);
|
|
|
|
const prep2 = await ops.prepare_image_request({ slotId: 'D01', prompt: '重复提交' });
|
|
const second = await ops.dispatch_image_request({ requestId: prep2.requestId });
|
|
assert.equal(second.phase, 'unknown');
|
|
assert.equal(second.pendingOriginal, prep1.requestId);
|
|
assert.deepEqual(dispatches, [prep1.requestId]);
|
|
});
|