import { expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import sharp from 'sharp'; import { loadWorkflowDir } from '../../../plugins/workflow-runner/src/discovery.js'; import { runScript } from '../../../plugins/workflow-runner/src/sandbox.js'; async function harness(questions?: string, recovery?: 'figure' | 'timeout') { const root = await mkdtemp(join(tmpdir(), 'wq-flow-')); const workflowDir = resolve( import.meta.dir, '..', ); const script = await loadWorkflowDir(workflowDir); if (!script.ok) throw Error(script.errors.join(';')); const path = join(root, 'context-with-neighbor.png'); await sharp({ create: { width: 1000, height: 300, channels: 3, background: '#ccc' }, }) .png() .toFile(path); const inventory = join(root, 'child-manifest.json'); await writeFile( inventory, JSON.stringify({ questions: ['5', '7', '10'].map((number, i) => ({ id: `q-${i + 1}`, number, section: '选择题', status: 'exported', content_status: number === '10' || recovery === 'timeout' ? 'source_truncated' : 'complete', missing_parts: number === '10' ? [{ kind: 'figure', reason: '原照片上缘未拍到完整数轴' }] : [], path, fragments: [{ path, canvas: { x: 0, y: 0, width: 1000, height: 300 } }], })), }), ); let children = 0; let recoveries = 0; const prompts: string[] = []; const tool = async (_n: string, v: { file_path: string; content: string }) => { const p = resolve(root, v.file_path); await mkdir(resolve(p, '..'), { recursive: true }); await writeFile(p, v.content); }; const execFile = async (_file: string, argv: string[]) => { const [action] = argv; if (action === 'render') return { exitCode: 0, stdout: JSON.stringify({ pdf: join(root, 'fake.pdf'), pages: [] }), stderr: '', }; const target = resolve(workflowDir, _file); const r = spawnSync(process.execPath, [target, ...argv], { cwd: root, encoding: 'utf8', }); return { exitCode: r.status, stdout: r.stdout, stderr: r.stderr }; }; const child = async (name: string, inputs: unknown) => { expect(name).toBe('question-crops'); expect(inputs).toEqual({ source: path, vision_timeout_seconds: 900 }); children++; return { workflow: name, result: { manifest: inventory }, artifacts: [] }; }; const llm = async ( prompt: string, opts: { isolated: boolean; images: unknown[] }, ) => { expect(opts.isolated).toBe(true); if (prompt.includes('\ngroups:')) return { groups: [{ id: 'g1', belongs_to_target: true, complete: true, cut_edges: false, reason: '', corrected_box: { x: 100, y: 100, width: 200, height: 200 } }] }; expect(opts.images).toHaveLength(1); prompts.push(prompt); const target = JSON.parse(prompt.split('目标绑定:')[1].split('\n')[0]); expect(prompt).toContain('邻题'); expect(prompt).toContain('第X题图'); if (recovery === 'timeout') throw new Error('recognition service timed out'); return { question_id: target.question_id, observed_number: target.printed_number === '7' ? '5' : target.printed_number, status: target.printed_number === '10' || recovery === 'figure' ? 'partial' : 'ready', reason: '缺少数轴图', type: 'short', blocks: [{ kind: 'text', text: `仅第${target.printed_number}题原文` }], figures: [], missing_parts: recovery === 'figure' ? [{ kind: 'figure', reason: '配图暂未定位', source_limited: false }] : target.printed_number === '10' ? [ { kind: 'figure', reason: '原照片上缘未拍到完整数轴', source_limited: true, }, ] : [], }; }; const wf = { input: { values: { source: path, questions }, resources: {} }, runtime: { workflowName: 'wrong-question-docx', workflowDir, cwd: root, sessionId: 'fixture', taskId: 'test', runId: 'run', rootRunId: 'run', goal: '', }, model: (() => { const mockAgent = async () => { recoveries++; return { fragments: [], detail: { question_id: recovery ? 'q-1' : 'q-2', observed_number: '5', status: 'ready', reason: '', type: 'short', blocks: [{ kind: 'text', text: recovery ? '恢复后完整题干' : '邻题不能替代' }], figures: recovery === 'figure' ? [{ id: 'g1', kind: 'figure', description: '目标题配图', members: ['图1'], box: { x: 100, y: 100, width: 200, height: 200 } }] : [], missing_parts: [] } }; }; return { generate: llm, agent: mockAgent, skill: async () => '', require: async () => undefined, // 与真实 wf.model.observe 同样的 recover?agent:llm 分流,供 workflow.mjs 的 // observe() 调用——真实实现的细节(图片包装、timeoutMs 等)不影响这份 mock // 里 llm/agent 各自校验的内容,这里只需还原分流本身。 observe: (prompt: string, schema: unknown, images: unknown[], opts: { recover?: boolean } = {}) => (opts.recover ? mockAgent : llm)(prompt, { schema, images, isolated: true }), }; })(), tools: { call: tool, callResult: async () => ({ content: '', images: [] }) }, exec: { shell: async () => ({ exitCode: 0, stdout: '', stderr: '' }), file: execFile }, fs: { exists: async () => true, readText: async (p: string) => readFile(p, 'utf8'), readJson: async (p: string) => JSON.parse(await readFile(p, 'utf8')), writeText: async () => undefined, writeJson: async () => undefined, mkdir: async () => undefined, }, flow: { pipeline: async () => ({ results: [], succeeded: 0, failed: 0 }), child, ask: async () => '等待指定题号' }, check: { verify: async () => ({ passed: true, summary: '', details: [] }) }, state: { budget: () => ({}), resetModelContext: () => undefined, addGoalSupplement: async () => undefined, syncManagedContract: async () => undefined }, output: { message: () => undefined, progress: () => undefined, artifact: () => undefined }, }; return { run: () => runScript(script.workflow, wf, 'test-bundle'), children: () => children, recoveries: () => recoveries, prompts, root, }; } test('逐题绑定目标:拒绝邻题替代,源图缺图保留题干,后题继续', async () => { const h = await harness('5,7,10,13'); const result = (await h.run()) as { manifest: string }; const m = JSON.parse(await readFile(result.manifest, 'utf8')); expect(h.children()).toBe(1); expect(h.recoveries()).toBe(1); // Mismatched q7 only; missing original q10 pixels are not retried. expect(h.prompts).toHaveLength(3); expect(m.questions.map((q: { status: string }) => q.status)).toEqual([ 'success', 'missing', 'partial', 'missing', ]); expect(m.success + m.partial + m.missing).toBe(4); expect(m.questions[1].reason).toContain('不匹配'); expect(m.questions[2].reason).toContain('数轴'); expect(m.questions[3].reason).toContain('未找到'); }); test('没有指定题号先询问,不调用子流程、不暗中全抄', async () => { const h = await harness(); const result = (await h.run()) as { status: string }; expect(result.status).toBe('awaiting_selection'); expect(h.children()).toBe(0); expect(h.prompts).toHaveLength(0); }); for (const scenario of ['figure', 'timeout'] as const) test(`恢复成功路径:${scenario}`, async () => { const h = await harness('5', scenario); const result = await h.run() as { manifest: string }; const manifest = JSON.parse(await readFile(result.manifest, 'utf8')); expect(h.recoveries()).toBe(1); expect(manifest.questions[0].status).toBe('success'); expect(manifest.success).toBe(1); }); test('零可整理题只交付清单和报告,不生成Word', async () => { const h = await harness('7,13'); const result = (await h.run()) as { manifest: string; docx?: string }; expect(result.docx).toBeUndefined(); const m = JSON.parse(await readFile(result.manifest, 'utf8')); expect(m.success).toBe(0); expect(m.missing).toBe(2); });