/** * plugins/workflow-runner/test/wechatReadingShots.test.ts * —— 加载真实 ESM 工作流入口,用 `wf` stub 验证**控制流** * * 为什么值得单开一个文件:`wechat-reading-shots` 依赖 ComputerUse,而 * `plugins/computer_use` 目前只吃 macOS —— 在 Windows 上**跑不了端到端**。 * 但这条工作流真正容易错的地方全在控制流上,而控制流可以脱离桌面自动化测: * * · 模型没按约定「只回一行 JSON」时,参数还提不提得出来 * · `OPEN=ok` 用精确取值还是 `includes('ok')`(后者会把「ok 的路子都走不通」判成成功) * · 翻页收敛循环会不会在到位后停 * · 撞到书末能不能提前收工 * · 截图张数是不是由引擎的 for 循环保证(而不是问模型) * * 这个模式对**任何**依赖外部环境的工作流都适用:把宿主能力全 stub 掉, * 只跑脚本本身的控制流。见 references/patterns.md 的「给工作流写单元测试」。 */ import { describe, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { runScript } from '../../../plugins/workflow-runner/src/sandbox.js'; import { validateScript } from '../../../plugins/workflow-runner/src/scriptGuard.mjs'; import type { WorkflowScript } from '../../../plugins/workflow-runner/src/types.js'; const ROOT = join(import.meta.dir, '..', '..', '..'); const SCRIPT_PATH = join( ROOT, 'workflows', 'wechat-reading-shots', 'workflow.mjs', ); function loadScript(): WorkflowScript { const source = readFileSync(SCRIPT_PATH, 'utf8'); const v = validateScript(source); if (!v.ok || v.bodyOffset === undefined) { throw new Error(`工作流脚本本身不合法:${v.errors.join('; ')}`); } return { name: 'wechat-reading-shots', dir: join(ROOT, 'workflows', 'wechat-reading-shots'), scriptPath: SCRIPT_PATH, source, meta: { apiVersion: 2, description: String(v.meta?.description ?? '') }, bodyOffset: v.bodyOffset, }; } /** 一次模拟运行的剧本:按 label 决定每次 agent/tool 调用返回什么。 */ interface Script { /** 参数收集步返回的原始文本(可以带前言/围栏,测提取鲁棒性)。 */ paramsText?: string; /** 打开正文步的返回(含 OPEN= 令牌)。 */ openText?: string; /** 每轮读页码的返回,按顺序取;用尽后重复最后一条。 */ pageReads?: string[]; /** 第几次翻页开始返回「变化很小」(1-based);不设则永不撞墙。 */ edgeAtShot?: number; } interface RunLog { agents: string[]; tools: { name: string; input: Record }[]; echoes: string[]; declared: string[]; } async function runWith(script: Script, args: Record) { const log: RunLog = { agents: [], tools: [], echoes: [], declared: [] }; let pageIdx = 0; let shotCount = 0; const agent = async (_prompt: string, opts: { label?: string } = {}) => { const label = opts.label ?? ''; log.agents.push(label); if (label.includes('收齐参数')) return script.paramsText ?? ''; if (label.includes('打开正文')) return script.openText ?? 'OPEN=ok'; if (label.includes('读页码')) { const reads = script.pageReads ?? ['PAGE=1 2']; return reads[Math.min(pageIdx++, reads.length - 1)]; } if (label.includes('翻页')) return '已按键'; if (label.includes('评估')) return '评估:成功。'; return ''; }; const tool = async (name: string, input: Record = {}) => { log.tools.push({ name, input }); return 'ok'; }; const toolResult = async (name: string, input: Record = {}) => { log.tools.push({ name, input }); if (input.action === 'observe') { shotCount++; return { content: 'observed', images: [`/tmp/shot_${shotCount}.png`], metadata: undefined, }; } if (input.action === 'key') { const hitEdge = script.edgeAtShot !== undefined && shotCount >= script.edgeAtShot; return { content: hitEdge ? '画面变化很小' : '画面变化 18%', images: [], metadata: undefined, }; } return { content: 'ok', images: [], metadata: undefined }; }; const wf = { input: { values: args, resources: {} }, runtime: { workflowName: 'wechat-reading-shots', workflowDir: join(ROOT, 'workflows', 'wechat-reading-shots'), cwd: ROOT, sessionId: 's', taskId: 't', runId: 'r', rootRunId: 'r', goal: '', }, model: { generate: async () => '', agent, skill: async () => '', require: async () => undefined }, tools: { call: tool, callResult: toolResult }, exec: { shell: async () => ({ stdout: '', stderr: '', exitCode: 0, raw: '' }), file: async () => ({ stdout: '', stderr: '', exitCode: 0, raw: '' }) }, fs: { exists: async () => true, readText: async (p: string) => readFileSync(resolve(ROOT, p), 'utf8'), readJson: async () => null, writeText: async () => undefined, writeJson: async () => undefined, mkdir: async () => undefined, }, flow: { pipeline: async () => ({ results: [], succeeded: 0, failed: 0 }), child: async () => ({}), ask: async () => '继续执行 (推荐)' }, check: { verify: async () => ({ passed: true, summary: '', details: [] }) }, state: { budget: () => ({}), resetModelContext: () => undefined, addGoalSupplement: async () => undefined, syncManagedContract: async () => undefined }, output: { message: (m: string) => log.echoes.push(m), progress: () => undefined, artifact: (p: string) => log.declared.push(p), }, }; const result = await runScript(loadScript(), wf, 'test-bundle'); return { result: result as Record, log }; } const OK_PARAMS = '{"book":"深度学习","page":12,"shots":3}'; describe('参数收集:模型不按约定输出时也要能提取', () => { test('★ 带前言的 JSON —— 「只回一行 JSON」这种约定没法强制', async () => { // 实测模型会在前面加一句「三项参数都已给出:…」。裸 parseJson 拿到整段就炸, // 而炸的表现是参数为空 → 报「参数没收齐」,文案完全指不向真因。 const { result } = await runWith( { paramsText: `三项参数都已给出:\n${OK_PARAMS}`, pageReads: ['PAGE=12 13'], }, { book: '', start_page: 0, shots: 0 }, ); expect(result.book).toBe('深度学习'); expect(result.targetPage).toBe(12); }); test('★ 带 markdown 围栏的 JSON', async () => { const { result } = await runWith( { paramsText: `好的,参数如下:\n\`\`\`json\n${OK_PARAMS}\n\`\`\`\n请确认。`, pageReads: ['PAGE=12 13'], }, { book: '', start_page: 0, shots: 0 }, ); expect(result.book).toBe('深度学习'); }); test('参数不全 → 抛错并把模型原话带上(便于排查)', async () => { await expect( runWith( { paramsText: '我不知道该问什么' }, { book: '', start_page: 0, shots: 0 }, ), ).rejects.toThrow(/参数没收齐/); }); }); describe('打开正文:协议令牌必须精确取值', () => { test('★ 「ok 的路子都走不通」不得被判成成功', async () => { // 这是实测踩过的:用 includes('ok') 在自由文本里找关键词会判真放行。 await expect( runWith( { paramsText: OK_PARAMS, openText: '试了几次,ok 的路子都走不通。\nOPEN=fail', }, {}, ), ).rejects.toThrow(/没能停到/); }); test('OPEN=ok 才放行', async () => { const { result } = await runWith( { paramsText: OK_PARAMS, openText: '已进入正文。\nOPEN=ok', pageReads: ['PAGE=12 13'], }, {}, ); expect(result.landing).toBe('PAGE=12 13'); }); }); describe('翻页收敛:到位即停', () => { test('目标页落在左页 → 命中', async () => { const { log } = await runWith( { paramsText: OK_PARAMS, pageReads: ['PAGE=12 13'] }, {}, ); // 一次都不该翻页(第一次读就到位了) expect(log.agents.filter((a) => a.includes('翻页'))).toHaveLength(0); }); test('★ 目标页落在右页也算到位(双页对开)', async () => { const { log } = await runWith( { paramsText: OK_PARAMS, pageReads: ['PAGE=11 12'] }, {}, ); expect(log.agents.filter((a) => a.includes('翻页'))).toHaveLength(0); }); test('★ PAGE=112 113 不得因含子串「12」被误判到位', async () => { // yaml 版为此专门写了 extract 精确取数而不是 includes。 const { log } = await runWith( { paramsText: OK_PARAMS, pageReads: ['PAGE=112 113', 'PAGE=12 13'] }, {}, ); // 第一轮没命中 → 翻一次页;第二轮命中 → 停 expect(log.agents.filter((a) => a.includes('翻页'))).toHaveLength(1); }); test('逐轮收敛:三轮后到位', async () => { const { log, result } = await runWith( { paramsText: OK_PARAMS, pageReads: ['PAGE=84 85', 'PAGE=40 41', 'PAGE=12 13'], }, {}, ); expect(log.agents.filter((a) => a.includes('翻页'))).toHaveLength(2); expect(result.landing).toBe('PAGE=12 13'); }); test('★ 始终读不到页码 → 诚实报错,不静默继续', async () => { await expect( runWith({ paramsText: OK_PARAMS, pageReads: ['PAGE=0 0'] }, {}), ).rejects.toThrow(/没能翻到第 12 页/); }); }); describe('截图循环:张数由引擎保证', () => { test('★ 请求几张就拍几张 —— 不问模型,for 循环说了算', async () => { const { result, log } = await runWith( { paramsText: '{"book":"深度学习","page":12,"shots":5}', pageReads: ['PAGE=12 13'], }, {}, ); expect(result.requested).toBe(5); expect(result.actual).toBe(5); const observes = log.tools.filter((t) => t.input.action === 'observe'); expect(observes).toHaveLength(5); }); test('★ 撞到书末提前收工,并如实报告实际张数', async () => { // 继续拍只会得到 N 张一模一样的最后一页。 const { result } = await runWith( { paramsText: '{"book":"深度学习","page":12,"shots":10}', pageReads: ['PAGE=12 13'], edgeAtShot: 3, }, {}, ); expect(result.hitEdge).toBe(true); expect(result.actual).toBe(3); expect(result.requested).toBe(10); }); test('★ 截图路径被登记为产物,并输出给用户', async () => { // yaml 版把截图路径 capture 了却从没输出 —— 用户拿不到图在哪。 const { result, log } = await runWith( { paramsText: '{"book":"深度学习","page":12,"shots":2}', pageReads: ['PAGE=12 13'], }, {}, ); expect(result.shots).toEqual(['/tmp/shot_1.png', '/tmp/shot_2.png']); expect(log.declared).toEqual(['/tmp/shot_1.png', '/tmp/shot_2.png']); expect(log.echoes.join('\n')).toContain('/tmp/shot_1.png'); }); test('每次 observe 都带页码特写(否则 10 张图无法核对是哪几页)', async () => { const { log } = await runWith( { paramsText: '{"book":"深度学习","page":12,"shots":2}', pageReads: ['PAGE=12 13'], }, {}, ); for (const t of log.tools.filter((x) => x.input.action === 'observe')) { expect(t.input.magnify).toBeDefined(); // 坐标必须相对窗口 —— 窗口常常不是全屏,全屏坐标写死必然框偏 expect(t.input.magnifyAnchor).toBe('window'); } }); }); describe('宿主能力切片', () => { test('★ 每次 ComputerUse 调用都显式声明 uses:[computer](最小权限)', async () => { // 不声明的话,宿主不会把电脑操控能力转给这次调用,工具会失败。 // 这条也防止「顺手给全权」——一份无人值守的脚本隐式拿到全权是危险的。 const source = readFileSync(SCRIPT_PATH, 'utf8'); const computerCalls = source.match(/'ComputerUse'/g) ?? []; expect(computerCalls.length).toBeGreaterThan(0); // 每处 ComputerUse 调用后面都应跟着 NEEDS_COMPUTER expect(source).toContain("NEEDS_COMPUTER = { uses: ['computer'] }"); const withoutSlice = source .split('\n') .filter((l) => l.includes("'ComputerUse'") && !l.includes('//')); expect(withoutSlice.length).toBeGreaterThan(0); }); });