gongxiangp2/apps/detail-agent-pi/test/thin-speed-124.test.mjs

241 lines
12 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { buildSubagentKnowledgeSlice, productionImageWorker } from '../src/production-image-worker.mjs';
import { foldSupersededProductionReads } from '../src/context-usage.mjs';
import { openProductionOperations } from '../src/production-operations.mjs';
import { delegatePool } from '../src/production-delegate.mjs';
import { resolveRoleModelSelection } from '../src/agent.mjs';
import { productionStore } from './production-store-fixture.mjs';
test('buildSubagentKnowledgeSlice keeps the byte budget and points to truncated source documents', () => {
const memoryFiles = new Map([
['规则/SKILL.md', Buffer.from('# 模板指引\n保持木纹一致')],
['规则/无人值守补充说明.md', Buffer.from('补充:实拍优先')],
['共用/模板原图换商品.md', Buffer.from('换商品规则:' + '要点。'.repeat(200))],
['规则/字段映射.json', Buffer.from('{"fields":' + 'x'.repeat(500_000) + '}')],
['规则/超大文档.md', Buffer.from('冗长说明:' + '段落。'.repeat(25_000))],
]);
const productionSkills = {
memoryFiles,
execution: {
entrypoint: '规则/SKILL.md',
supplement: '规则/无人值守补充说明.md',
docPaths: ['共用/模板原图换商品.md', '规则/超大文档.md'],
},
};
const slot = {
id: 'slot-1',
fieldId: 'S01-I01',
label: '首屏主图',
aspectRatio: '3:4',
sourcePolicy: 'generate',
productionRule: { source: 'generate', focus: '突出实木纹理' },
requirements: '保持椅背弧度一致',
};
const slice = buildSubagentKnowledgeSlice(productionSkills, slot);
const bytes = Buffer.byteLength(JSON.stringify(slice), 'utf8');
assert.ok(bytes <= 36 * 1024, `expected <= 36 KiB, got ${bytes}`);
assert.match(slice.docs.find(doc=>doc.path==='规则/超大文档.md').content,/已截断,用 read 读取 规则\/超大文档\.md/);
assert.doesNotMatch(slice.docs[0].content,/已截断/);
assert.equal(slice.slotRule.fieldId, 'S01-I01');
assert.equal(slice.slotRule.requirements, '保持椅背弧度一致');
assert.ok(slice.docs.some(d => d.path === '规则/SKILL.md'));
assert.ok(slice.docs.some(d => d.path === '规则/无人值守补充说明.md'));
assert.ok(!slice.docs.some(d => d.path.endsWith('.json')));
});
test('foldSupersededProductionReads trims historical screens and large tool results under 150KB while preserving userCanvasChanges', () => {
const messages = [];
for (let i = 0; i < 14; i++) {
messages.push({
role: 'assistant',
content: [{ type: 'toolCall', id: `call-${i}`, name: 'read_output_screen', arguments: { page: i } }],
});
messages.push({
role: 'toolResult',
toolCallId: `call-${i}`,
toolName: 'read_output_screen',
details: { outputId: 'detail', variantId: 'oak', page: i, screenFingerprint: `fp-${i}` },
content: [
{ type: 'text', text: JSON.stringify({ page: i, screenFingerprint: `fp-${i}`, textClipping: 0, payload: 'x'.repeat(12_000) }) },
...(i === 3 ? [{ type: 'text', text: JSON.stringify({ userCanvasChanges: [{ slotId: 'S04-I01', manual: true }] }) }] : []),
],
});
}
const folded = foldSupersededProductionReads(messages);
const totalBytes = Buffer.byteLength(JSON.stringify(folded), 'utf8');
assert.ok(totalBytes < 150 * 1024, `expected folded context < 150KB, got ${totalBytes}`);
const preservedTurn = folded.find(m => m.toolCallId === 'call-3');
assert.ok(preservedTurn.content.some(b => b.text.includes('userCanvasChanges')));
const newestTurn = folded.find(m => m.toolCallId === 'call-13');
assert.ok(newestTurn.content[0].text.includes('payload'));
});
test('read_copy_fields attaches field requirements and plan_production avoids repeating full product brief', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-copy-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const mapping = {
fields: [
{ field_id: 'S01-T01', purpose: '核心卖点', fill_requirements: '不超过12字', ps_location: { layer_id: 101 } },
],
};
const host = {
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak' },
productionSkills: {
snapshot: { manifest: { bindings: { detail: { mapping: '规则/字段映射.json' } } } },
memoryFiles: new Map([['规则/字段映射.json', Buffer.from(JSON.stringify(mapping))]]),
},
canvas: {
workflowRead: async () => ({
available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', totalSlots: 1,
template: { id: 'tpl', contentHash: 'hash1' },
productEvidence: { brief: { name: '实木餐椅', spu: 'CHR-01', note: '长备注'.repeat(500) } },
slots: [{ id: 'slot-1', fieldId: 'S01-I01', label: '主图' }],
}),
detailCopyFields: async () => ({
revision: 1,
pages: ['P01'],
fields: [{ field: 'S01-T01', layer: 101, label: '标题', currentText: '原样例' }],
}),
imageRequest: async () => [],
},
};
const ops = await openProductionOperations(host);
const copyRes = await ops.read_copy_fields({});
assert.equal(copyRes.fields[0].requirements, '核心卖点\n不超过12字');
const firstPlan = await ops.plan_production({});
assert.ok(firstPlan.product.note);
const secondPlan = await ops.plan_production({});
assert.equal(secondPlan.productEarlier, true);
assert.equal(secondPlan.product, undefined);
assert.equal(secondPlan.productSummary.name, '实木餐椅');
});
test('delegatePool releases slot during dispatchEnqueued wait and await_image_slots supports incremental updates & autoAdopt', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-pool-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const poolHost = {};
const pool = delegatePool(poolHost, 1);
const ac = new AbortController();
const release1 = await pool.acquire(ac.signal);
let secondStarted = false;
const p2 = pool.acquire(ac.signal).then(rel => { secondStarted = true; rel(); });
assert.equal(secondStarted, false);
release1();
await p2;
assert.equal(secondStarted, true);
// Test worker permit release before dispatchEnqueued
const enqueueGate = Promise.withResolvers();
let permitReleased = false;
const worker = productionImageWorker({
slot: { id: 'slot-1', fieldId: 'S01', label: '主图' },
goal: '生成主图',
outputId: 'detail',
variantId: 'oak',
row: { step: '正在准备' },
readCandidate: async () => ({}),
findSlot: () => ({ id: 'slot-1' }),
current: async () => ({ revisions: {} }),
getReferenceMode: () => 'none',
getSlotRecord: () => undefined,
readSlot: async () => ({ id: 'slot-1' }),
readImages: async () => ({ images: [] }),
listProjectImages: async () => [],
liveSlot: async () => ({ id: 'slot-1' }),
slotDrawStatus: () => ({ generationAttempts: 0, maxGenerationAttempts: 4, remainingGenerationAttempts: 4, drawLimitReached: false }),
liveSlotCopy: async () => [],
notice: () => {},
recordLocalCandidate: () => {},
recordNoCandidate: () => {},
dispatchEnqueued: () => enqueueGate.promise,
preparedRequest: async () => ({ requestId: 'req-1', phase: 'prepared' }),
queueDispatch: async () => ({ requestId: 'req-1', operationId: 'req-1', phase: 'accepted' }),
runDetailAgent: async (_inst, _prompt, tools) => {
const dispatchTool = tools.find(t => t.name === 'dispatch_image_request');
const runPromise = dispatchTool.execute('id', { requestId: 'req-1' }, ac.signal);
await new Promise(r => setTimeout(r, 20));
assert.equal(permitReleased, true, 'permit should be released before dispatchEnqueued resolves');
enqueueGate.resolve();
await runPromise;
},
}, ac.signal);
await worker.run({ release: () => { permitReleased = true; } });
});
test('liveSlots reads fresh canvas state and autoAdopt checks the sole candidate before placing it', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-124-live-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
let currentSlot = { id: 'slot-1', fieldId: 'S01', label: '主图', candidates: [] };
let adoptedCalls = 0;
let reviews = 0;
const image={type:'image',mimeType:'image/png',data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='};
const host = {
async runDetailAgent(_id,_system,_prompt,[tool]){
reviews++;
await tool.execute('',{verdict:'pass',reason:'与实拍相符',checks:{structure:true,color:true,composition:true,evidence:true}});
},
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak' },
canvas: {
read: async () => ({ revision: 10 }),
requestWrite: async () => ({ allowed: true, revision: 10 }),
workflowRead: async () => ({
available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', totalSlots: 1,
revisions: { creation: 1, slots: 1, canvas: 1 },
template: { id: 'tpl', contentHash: 'hash1' },
slots: [currentSlot],
}),
detailCopyFields: async () => ({ revision: 1, pages: ['P01'], fields: [] }),
detailImages: async (_slotId,candidateId) => ({candidateId,referenceCount:1,images:[image,image]}),
detailCandidateScreen: async () => { throw Error('候选图位不是智能图层'); },
imageRequest: async () => [],
workflowExecute: async args => {
if (args.intent === 'adopt_candidate') {
assert.equal(reviews,1);
adoptedCalls++;
currentSlot = { ...currentSlot, selectedCandidateId: args.candidateId };
return { operationId: args.operationId, phase: 'complete', candidateId: args.candidateId };
}
return { operationId: args.operationId, phase: 'complete' };
},
},
};
const ops = await openProductionOperations(host);
// External canvas change without any JS invalidation call
currentSlot = { id: 'slot-1', fieldId: 'S01', label: '主图', candidates: [{ id: 'cand-1', status: 'complete' }] };
const waited = await ops.await_image_slots({ slotIds: ['slot-1'], autoAdopt: true });
assert.equal(waited.incrementalUpdates.length, 1);
assert.equal(waited.incrementalUpdates[0].candidateId, 'cand-1');
assert.equal(waited.autoAdopted?.length, 1, JSON.stringify(waited.checks));
assert.equal(waited.autoAdopted[0].candidateId, 'cand-1');
assert.equal(adoptedCalls, 1);
});
test('resolveRoleModelSelection falls back transparently and routes configured roles', () => {
const base = { id: 'claude-sonnet', protocol: 'anthropic-messages', contextWindow: 200_000, contextWindowSource: 'catalog' };
assert.equal(resolveRoleModelSelection({ model: base }, 'imageDelegate'), base);
assert.equal(resolveRoleModelSelection({ model: base, roleModels: {} }, 'review'), base);
const info = {
model: base,
roleModels: {
imageDelegate: { id: 'glm-flash', protocol: 'openai-chat' },
review: { id: 'gemini-pro', protocol: 'google-generative-ai', contextWindow: 1_000_000, contextWindowSource: 'explicit' },
},
};
const delegateModel = resolveRoleModelSelection(info, 'imageDelegate');
assert.equal(delegateModel.id, 'glm-flash');
assert.equal(delegateModel.protocol, 'openai-chat');
assert.equal(delegateModel.contextWindow, undefined);
const reviewModel = resolveRoleModelSelection(info, 'review');
assert.equal(reviewModel.id, 'gemini-pro');
assert.equal(reviewModel.contextWindow, 1_000_000);
});