@zhushanwen/pi-subagent-workflow 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/execution/__tests__/execute-nesting.test.ts +16 -0
- package/src/interface/__tests__/workflow-tool-prompt.test.ts +13 -2
- package/src/interface/commands.ts +30 -0
- package/src/interface/subagents.ts +33 -0
- package/src/interface/tool-workflow-script.ts +4 -3
- package/src/interface/tool-workflow.ts +7 -4
- package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +390 -0
- package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +347 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +76 -0
- package/src/orchestration/__tests__/workflows-e2e.test.ts +386 -0
- package/src/orchestration/error-recovery.ts +77 -13
- package/src/orchestration/worker-script-builder.ts +72 -16
- package/workflows/README.md +5 -3
- package/workflows/chain.js +2 -2
- package/workflows/map-reduce.js +10 -6
- package/workflows/parallel.js +17 -27
- package/workflows/scatter-gather.js +15 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhushanwen/pi-subagent-workflow",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"description": "Unified subagent execution and multi-agent workflow orchestration for Pi — spawned-process agent runtime with sync/background modes, stateful workflow management with persistence, state machine, and execution tracing.",
|
|
@@ -105,6 +105,22 @@ vi.mock("../finalized-marker.ts", () => ({
|
|
|
105
105
|
readFinalized: vi.fn(() => false),
|
|
106
106
|
}));
|
|
107
107
|
|
|
108
|
+
// manifest-store mock:writeManifest 用真实 fs.promises 写盘,但本文件 fs 同步方法已 mock
|
|
109
|
+
// (目录从不真实创建)→ open/rename/unlink 全 ENOENT → bestEffort 异步 console.debug。
|
|
110
|
+
// 这些延迟 console 通过 worker RPC(onUserConsoleLog)回流,与 vitest teardown 形成 race:
|
|
111
|
+
// "Closing rpc while onUserConsoleLog was pending" → unhandled rejection / exit 1(flaky)。
|
|
112
|
+
// 本组用例测编排逻辑(pool / depth / throttle),不测 manifest 持久化(有 manifest-store.test.ts
|
|
113
|
+
// 独立覆盖)。故 mock 成 no-op,消除 teardown race 的根因——异步 console 输出。
|
|
114
|
+
vi.mock("../manifest-store.ts", () => {
|
|
115
|
+
class FakeManifestStore {
|
|
116
|
+
writeManifest = vi.fn(async () => {});
|
|
117
|
+
readManifest = vi.fn(async () => null);
|
|
118
|
+
listAllSync = vi.fn(() => []);
|
|
119
|
+
recoverTmpFiles = vi.fn(async () => []);
|
|
120
|
+
}
|
|
121
|
+
return { ManifestStore: FakeManifestStore };
|
|
122
|
+
});
|
|
123
|
+
|
|
108
124
|
// temp-prompt:mock 掉真实 fs.promises I/O,消除 fake-timers 下的 flaky 竞态
|
|
109
125
|
// (详见 run-spawn-integration.test.ts 同名 mock 的注释)。
|
|
110
126
|
vi.mock("../temp-prompt.ts", () => ({
|
|
@@ -40,8 +40,8 @@ describe("U1: workflow tool prompt mentions built-in workflows", () => {
|
|
|
40
40
|
});
|
|
41
41
|
|
|
42
42
|
it("tool-workflow.ts promptGuidelines 含 run action 的正例", () => {
|
|
43
|
-
// 给出
|
|
44
|
-
expect(TOOL_WORKFLOW_SRC).
|
|
43
|
+
// 给出 run 调用的 JSON 示例,LLM 才知道参数格式(action/name/args 嵌套)。
|
|
44
|
+
expect(TOOL_WORKFLOW_SRC).toContain('{"action":"run","name":"');
|
|
45
45
|
});
|
|
46
46
|
|
|
47
47
|
it("promptGuidelines 含 JSON 调用正例(run/status/lifecycle)", () => {
|
|
@@ -69,4 +69,15 @@ describe("U1: workflow tool prompt mentions built-in workflows", () => {
|
|
|
69
69
|
// 反向交叉引用:list 的指引里要提到用 workflow tool 的 run action 启动脚本。
|
|
70
70
|
expect(TOOL_WORKFLOW_SCRIPT_SRC).toMatch(/workflow.*tool.*run|run.*workflow.*tool/i);
|
|
71
71
|
});
|
|
72
|
+
|
|
73
|
+
it("tool-workflow.ts promptGuidelines 强化 anti-generate(直接 run,不要 generate)", () => {
|
|
74
|
+
// session 证据:弱模型看到 workflow list 后倾向 workflow-script generate 而非直接 run。
|
|
75
|
+
// 提示词必须显式禁止对内置编排使用 generate。
|
|
76
|
+
expect(TOOL_WORKFLOW_SRC).toContain("NEVER use workflow-script action:generate");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("tool-workflow-script.ts promptGuidelines 强化 anti-generate(CRITICAL ANTI-PATTERN)", () => {
|
|
80
|
+
expect(TOOL_WORKFLOW_SCRIPT_SRC).toContain("CRITICAL ANTI-PATTERN");
|
|
81
|
+
expect(TOOL_WORKFLOW_SCRIPT_SRC).toContain("NEVER generate");
|
|
82
|
+
});
|
|
72
83
|
});
|
|
@@ -66,6 +66,36 @@ export function registerWorkflowsCommand(
|
|
|
66
66
|
): void {
|
|
67
67
|
api.registerCommand("workflows", {
|
|
68
68
|
description: "Open workflow panel. /workflows [runId] | /workflows pause|resume|abort <runId>",
|
|
69
|
+
getArgumentCompletions(prefix: string) {
|
|
70
|
+
const trimmed = prefix.trimStart();
|
|
71
|
+
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
72
|
+
|
|
73
|
+
// 第一级:lifecycle 动词(带尾随空格,选中后继续补 runId)
|
|
74
|
+
if (parts.length <= 1) {
|
|
75
|
+
return [
|
|
76
|
+
{ label: "pause", value: "pause ", description: "Pause a workflow run" },
|
|
77
|
+
{ label: "resume", value: "resume ", description: "Resume a paused workflow run" },
|
|
78
|
+
{ label: "abort", value: "abort ", description: "Abort a workflow run" },
|
|
79
|
+
].filter((opt) => opt.label.startsWith(trimmed.toLowerCase()));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 第二级:lifecycle 动词后补全当前 session 的 runId
|
|
83
|
+
if (parts[0] === "pause" || parts[0] === "resume" || parts[0] === "abort") {
|
|
84
|
+
try {
|
|
85
|
+
const runs = sortedRuns(getRuns());
|
|
86
|
+
if (runs.length === 0) return null;
|
|
87
|
+
return runs.map((r) => ({
|
|
88
|
+
label: r.runId,
|
|
89
|
+
value: r.runId,
|
|
90
|
+
description: `${r.spec.scriptName} [${r.state.status}]`,
|
|
91
|
+
}));
|
|
92
|
+
} catch {
|
|
93
|
+
// 拿不到运行时数据(getRuns 抛错)→ 静默降级,补全失败不影响 command
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
},
|
|
69
99
|
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
70
100
|
// ── RPC 模式(xyz-agent GUI):解析 lifecycle action 直接执行,不打开 TUI ──
|
|
71
101
|
// hasUI 在 TUI 和 RPC 都为 true,不能用于区分;用 ctx.mode === "rpc" 判定 GUI 通道。
|
|
@@ -9,12 +9,45 @@ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-c
|
|
|
9
9
|
|
|
10
10
|
import { getSubagentService } from "../execution/subagent-service.ts";
|
|
11
11
|
import { parseSubagentRpcCommand } from "./command-actions.ts";
|
|
12
|
+
import { LIST_LIMIT } from "./list-shared.ts";
|
|
12
13
|
import { createSubagentsView } from "./list-view.ts";
|
|
13
14
|
|
|
14
15
|
/** 注册 /subagents 命令(= list overlay)。 */
|
|
15
16
|
export function registerSubagentsCommand(pi: ExtensionAPI): void {
|
|
16
17
|
pi.registerCommand("subagents", {
|
|
17
18
|
description: "Subagents: /subagents [<id>] | /subagents cancel <id>",
|
|
19
|
+
getArgumentCompletions(prefix: string) {
|
|
20
|
+
const trimmed = prefix.trimStart();
|
|
21
|
+
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
22
|
+
|
|
23
|
+
// 第一级:cancel 动词(带尾随空格,选中后继续补 record id)
|
|
24
|
+
if (parts.length <= 1) {
|
|
25
|
+
return [
|
|
26
|
+
{ label: "cancel", value: "cancel ", description: "Cancel a running subagent" },
|
|
27
|
+
].filter((opt) => opt.label.startsWith(trimmed.toLowerCase()));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 第二级:cancel 后补全当前 session 的 record id
|
|
31
|
+
if (parts[0] === "cancel") {
|
|
32
|
+
try {
|
|
33
|
+
const service = getSubagentService();
|
|
34
|
+
if (!service) return null;
|
|
35
|
+
// collectRecords 合并内存(running) + 磁盘重建 record,按 session 过滤。
|
|
36
|
+
// cancel 只对 running 有效,但全部列出便于用户辨认(终态 record 会被 service 拒绝)。
|
|
37
|
+
const records = service.collectRecords(LIST_LIMIT);
|
|
38
|
+
if (records.length === 0) return null;
|
|
39
|
+
return records.map((r) => ({
|
|
40
|
+
label: r.id,
|
|
41
|
+
value: r.id,
|
|
42
|
+
description: `${r.agent} [${r.status}]`,
|
|
43
|
+
}));
|
|
44
|
+
} catch {
|
|
45
|
+
// 拿不到运行时数据(service disposed 等)→ 静默降级,补全失败不影响 command
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
},
|
|
18
51
|
handler: async (argsStr: string, ctx: ExtensionCommandContext) => {
|
|
19
52
|
const service = getSubagentService();
|
|
20
53
|
if (!service) {
|
|
@@ -178,9 +178,10 @@ export function registerWorkflowScriptTool(
|
|
|
178
178
|
"Use this to discover built-in workflows (chain/parallel/scatter-gather/map-reduce) " +
|
|
179
179
|
"and user-generated scripts before starting a run. After listing, start a script via " +
|
|
180
180
|
"the workflow tool with action:run and the script name.",
|
|
181
|
-
"ANTI-PATTERN:
|
|
182
|
-
"
|
|
183
|
-
"
|
|
181
|
+
"CRITICAL ANTI-PATTERN: NEVER generate scripts for chain/parallel/scatter-gather/map-reduce. " +
|
|
182
|
+
"These are BUILT-IN — use the workflow tool with action:run directly. " +
|
|
183
|
+
"generate is for NOVEL orchestration patterns ONLY. When in doubt, action:list first, " +
|
|
184
|
+
"then action:run — not action:generate.",
|
|
184
185
|
],
|
|
185
186
|
parameters: WorkflowScriptParams,
|
|
186
187
|
|
|
@@ -235,12 +235,12 @@ export function registerWorkflowTool(
|
|
|
235
235
|
promptSnippet: "Run, pause, resume, abort, or check workflow status",
|
|
236
236
|
promptGuidelines: [
|
|
237
237
|
"PRIORITY: When user says 'workflow', 'run workflow', try run action FIRST.",
|
|
238
|
-
"BUILT-IN workflows
|
|
239
|
-
"chain (analyze→transform→synthesize
|
|
238
|
+
"BUILT-IN workflows — run DIRECTLY with action:run, do NOT use workflow-script generate for these: " +
|
|
239
|
+
"chain (sequential 3-step: analyze→transform→synthesize; args: task), " +
|
|
240
240
|
"parallel (multi-perspective analysis; args: target, optional perspectives), " +
|
|
241
|
-
"scatter-gather (split→parallel
|
|
241
|
+
"scatter-gather (split→parallel→merge; args: task), " +
|
|
242
242
|
"map-reduce (parallel map→reduce; args: items/itemsJson + operation). " +
|
|
243
|
-
"Example:
|
|
243
|
+
"Example: {\"action\":\"run\",\"name\":\"parallel\",\"args\":{\"target\":\"src/auth.ts\"}}.",
|
|
244
244
|
"DISCOVERY: If unsure what workflows exist, call the workflow-script tool with " +
|
|
245
245
|
"action:list first — it returns all available scripts (built-in + user-generated) " +
|
|
246
246
|
"with source tags and descriptions. Then use this tool's run action to start one.",
|
|
@@ -251,6 +251,9 @@ export function registerWorkflowTool(
|
|
|
251
251
|
"- status: {\"action\":\"status\"}. " +
|
|
252
252
|
"- pause/resume/abort: {\"action\":\"pause\",\"runId\":\"<id>\"} (abort optional: ,\"error\":\"<reason>\"}).",
|
|
253
253
|
"Anti-patterns: Flattening args sub-fields (task/items/...) to the top level — they belong inside args. Calling {\"action\":\"run\"} without name.",
|
|
254
|
+
"CRITICAL: For chain/parallel/scatter-gather/map-reduce orchestration, ALWAYS use action:run with the built-in name. " +
|
|
255
|
+
"NEVER use workflow-script action:generate to create these patterns — they already exist. " +
|
|
256
|
+
"workflow-script generate is ONLY for novel patterns not covered by built-ins.",
|
|
254
257
|
],
|
|
255
258
|
parameters: WorkflowParams,
|
|
256
259
|
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
// src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts
|
|
2
|
+
//
|
|
3
|
+
// W2: 主线程层 postMessage 防御测试。
|
|
4
|
+
//
|
|
5
|
+
// 背景:主线程有 3 处 run.runtime?.worker.postMessage(...) 调用(经 helper 函数),
|
|
6
|
+
// 全部没有 try/catch。若 result 对象含不可克隆成员(function/Symbol/循环引用),
|
|
7
|
+
// postMessage 同步抛 DataCloneError:
|
|
8
|
+
// - postAgentResult:result 是 agent 返回值,不可克隆概率最高。DataCloneError 冒泡到
|
|
9
|
+
// dispatchAgentCall 的 .then 回调,中断后续 postBudgetUpdate/store.save/budget 检查,
|
|
10
|
+
// run 卡在 running。
|
|
11
|
+
// - postBudgetUpdate:payload 是 number,风险低但无兜底。
|
|
12
|
+
// - dispatchWorkflowCall 的 postResult:result 是子 workflow 任意返回值。
|
|
13
|
+
//
|
|
14
|
+
// 修复后三处均包 try/catch + fallback。本测试通过 mock worker.postMessage 抛
|
|
15
|
+
// DataCloneError,验证:
|
|
16
|
+
// 1. 调用方不抛错(流程不中断)
|
|
17
|
+
// 2. fallback result(纯字符串,必可克隆)被发送
|
|
18
|
+
// 3. console.error 记录诊断
|
|
19
|
+
|
|
20
|
+
import { readFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
|
|
24
|
+
import { describe, expect, it, vi } from "vitest";
|
|
25
|
+
|
|
26
|
+
import { handleWorkerMessage, postBudgetUpdate } from "../error-recovery.ts";
|
|
27
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
28
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
29
|
+
|
|
30
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
31
|
+
const ERROR_RECOVERY_SRC = readFileSync(
|
|
32
|
+
join(__dirname, "../error-recovery.ts"),
|
|
33
|
+
"utf-8",
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
/** flush microtask 队列,让 void .then().catch() 链路跑完。 */
|
|
39
|
+
async function flushMicrotasks(): Promise<void> {
|
|
40
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 构造一个 postMessage mock:前 n 次抛 DataCloneError,之后正常(模拟 fallback 成功)。 */
|
|
44
|
+
function makeFailingPostMessage(failTimes: number): ReturnType<typeof vi.fn> {
|
|
45
|
+
let calls = 0;
|
|
46
|
+
return vi.fn(() => {
|
|
47
|
+
calls += 1;
|
|
48
|
+
if (calls <= failTimes) {
|
|
49
|
+
const err = new Error("Could not clone object: function found");
|
|
50
|
+
err.name = "DataCloneError";
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
// fallback 成功路径:no-op
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 构造一个永远抛 DataCloneError 的 postMessage mock(fallback 也失败)。 */
|
|
58
|
+
function makeAlwaysFailingPostMessage(): ReturnType<typeof vi.fn> {
|
|
59
|
+
return vi.fn(() => {
|
|
60
|
+
const err = new Error("Could not clone object");
|
|
61
|
+
err.name = "DataCloneError";
|
|
62
|
+
throw err;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 构造 status="running" 的 mock WorkflowRun,postMessage 由调用方注入。 */
|
|
67
|
+
function makeRunningRun(postMessage: ReturnType<typeof vi.fn>): WorkflowRun {
|
|
68
|
+
return {
|
|
69
|
+
state: { status: "running" },
|
|
70
|
+
runtime: { worker: { postMessage } },
|
|
71
|
+
} as unknown as WorkflowRun;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** LifecycleDeps 只需 onWorkflowCall(dispatchWorkflowCall 唯一消费的 dep)。 */
|
|
75
|
+
function makeDeps(onWorkflowCall?: LifecycleDeps["onWorkflowCall"]): LifecycleDeps {
|
|
76
|
+
return { onWorkflowCall } as unknown as LifecycleDeps;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** WorkerHandlers 占位(workflow-call 路径不触发 handler 回调)。 */
|
|
80
|
+
function makeHandlers(): WorkerHandlers {
|
|
81
|
+
return {
|
|
82
|
+
onMessage: vi.fn(async () => {}),
|
|
83
|
+
onError: vi.fn(async () => {}),
|
|
84
|
+
onExit: vi.fn(async () => {}),
|
|
85
|
+
} as unknown as WorkerHandlers;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface PostedMsg {
|
|
89
|
+
type: string;
|
|
90
|
+
callId?: number;
|
|
91
|
+
result?: { content: string; error?: string };
|
|
92
|
+
budget?: { usedTokens: number; usedCost: number };
|
|
93
|
+
cached?: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 从 postMessage mock 取第 idx 次调用的第 0 参。 */
|
|
97
|
+
function postedAt(postMessage: ReturnType<typeof vi.fn>, idx: number): PostedMsg {
|
|
98
|
+
return postMessage.mock.calls[idx]![0] as PostedMsg;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 静默 console.error(防御路径会打印诊断,避免污染测试输出)。 */
|
|
102
|
+
function silenceConsoleError(): () => void {
|
|
103
|
+
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
104
|
+
return () => spy.mockRestore();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ── W2a: postBudgetUpdate try/catch ──
|
|
108
|
+
|
|
109
|
+
describe("W2a: postBudgetUpdate 防御 DataCloneError", () => {
|
|
110
|
+
it("postMessage 抛错时不向上传播(流程不中断)", () => {
|
|
111
|
+
const restore = silenceConsoleError();
|
|
112
|
+
try {
|
|
113
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
114
|
+
const run = {
|
|
115
|
+
state: {
|
|
116
|
+
status: "running",
|
|
117
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
118
|
+
},
|
|
119
|
+
runtime: { worker: { postMessage } },
|
|
120
|
+
} as unknown as WorkflowRun;
|
|
121
|
+
|
|
122
|
+
// 不应抛错——防御性兜底
|
|
123
|
+
expect(() => postBudgetUpdate(run)).not.toThrow();
|
|
124
|
+
} finally {
|
|
125
|
+
restore();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("postMessage 失败时记录 console.error 诊断", () => {
|
|
130
|
+
const restore = silenceConsoleError();
|
|
131
|
+
try {
|
|
132
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
133
|
+
const run = {
|
|
134
|
+
state: {
|
|
135
|
+
status: "running",
|
|
136
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
137
|
+
},
|
|
138
|
+
runtime: { worker: { postMessage } },
|
|
139
|
+
} as unknown as WorkflowRun;
|
|
140
|
+
|
|
141
|
+
postBudgetUpdate(run);
|
|
142
|
+
|
|
143
|
+
expect(console.error).toHaveBeenCalledTimes(1);
|
|
144
|
+
const diag = (console.error as ReturnType<typeof vi.fn>).mock.calls[0]![0] as string;
|
|
145
|
+
expect(diag).toContain("postBudgetUpdate failed");
|
|
146
|
+
expect(diag).toContain("Could not clone object");
|
|
147
|
+
} finally {
|
|
148
|
+
restore();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("正常 payload(纯 number)成功发送", () => {
|
|
153
|
+
const postMessage = vi.fn();
|
|
154
|
+
const run = {
|
|
155
|
+
state: {
|
|
156
|
+
status: "running",
|
|
157
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
158
|
+
},
|
|
159
|
+
runtime: { worker: { postMessage } },
|
|
160
|
+
} as unknown as WorkflowRun;
|
|
161
|
+
|
|
162
|
+
postBudgetUpdate(run);
|
|
163
|
+
|
|
164
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
165
|
+
expect(postedAt(postMessage, 0)).toEqual({
|
|
166
|
+
type: "budget-update",
|
|
167
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// ── W2b: dispatchWorkflowCall postResult 闭包防御 ──
|
|
173
|
+
|
|
174
|
+
describe("W2b: dispatchWorkflowCall postResult 防御 DataCloneError", () => {
|
|
175
|
+
it("result 不可克隆 → 回发纯字符串 fallback result", async () => {
|
|
176
|
+
const restore = silenceConsoleError();
|
|
177
|
+
try {
|
|
178
|
+
// 第 1 次 postMessage 抛 DataCloneError(原始 result 不可克隆),
|
|
179
|
+
// 第 2 次(fallback)成功。
|
|
180
|
+
const postMessage = makeFailingPostMessage(1);
|
|
181
|
+
const onWorkflowCall = vi.fn(async () => ({ nonCloneable: () => {} }));
|
|
182
|
+
const run = makeRunningRun(postMessage);
|
|
183
|
+
const deps = makeDeps(onWorkflowCall);
|
|
184
|
+
|
|
185
|
+
await handleWorkerMessage(
|
|
186
|
+
run,
|
|
187
|
+
{ type: "workflow-call", callId: 9, name: "sub", args: {} },
|
|
188
|
+
deps,
|
|
189
|
+
makeHandlers(),
|
|
190
|
+
);
|
|
191
|
+
await flushMicrotasks();
|
|
192
|
+
|
|
193
|
+
// 调用两次:1 原始(失败)+ 1 fallback(成功)
|
|
194
|
+
expect(postMessage).toHaveBeenCalledTimes(2);
|
|
195
|
+
const fallback = postedAt(postMessage, 1);
|
|
196
|
+
expect(fallback.type).toBe("workflow-result");
|
|
197
|
+
expect(fallback.callId).toBe(9);
|
|
198
|
+
expect(fallback.result?.content).toBe("");
|
|
199
|
+
expect(fallback.result?.error).toContain("Workflow result serialization failed");
|
|
200
|
+
} finally {
|
|
201
|
+
restore();
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("postResult 不抛错到调用方(不中断 onWorkflowCall 链路)", async () => {
|
|
206
|
+
const restore = silenceConsoleError();
|
|
207
|
+
try {
|
|
208
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
209
|
+
const onWorkflowCall = vi.fn(async () => ({ bad: () => {} }));
|
|
210
|
+
const run = makeRunningRun(postMessage);
|
|
211
|
+
const deps = makeDeps(onWorkflowCall);
|
|
212
|
+
|
|
213
|
+
// handleWorkerMessage 自身不应抛——postResult 内部已 catch
|
|
214
|
+
await expect(
|
|
215
|
+
handleWorkerMessage(
|
|
216
|
+
run,
|
|
217
|
+
{ type: "workflow-call", callId: 10, name: "sub", args: {} },
|
|
218
|
+
deps,
|
|
219
|
+
makeHandlers(),
|
|
220
|
+
),
|
|
221
|
+
).resolves.toBeUndefined();
|
|
222
|
+
await flushMicrotasks();
|
|
223
|
+
} finally {
|
|
224
|
+
restore();
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("fallback 也失败 → console.error 记录 worker pending 将挂起", async () => {
|
|
229
|
+
const restore = silenceConsoleError();
|
|
230
|
+
try {
|
|
231
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
232
|
+
const onWorkflowCall = vi.fn(async () => ({ bad: () => {} }));
|
|
233
|
+
const run = makeRunningRun(postMessage);
|
|
234
|
+
const deps = makeDeps(onWorkflowCall);
|
|
235
|
+
|
|
236
|
+
await handleWorkerMessage(
|
|
237
|
+
run,
|
|
238
|
+
{ type: "workflow-call", callId: 11, name: "sub", args: {} },
|
|
239
|
+
deps,
|
|
240
|
+
makeHandlers(),
|
|
241
|
+
);
|
|
242
|
+
await flushMicrotasks();
|
|
243
|
+
|
|
244
|
+
// 至少 2 次尝试(原始 + fallback),fallback 失败也记日志
|
|
245
|
+
expect(postMessage.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
246
|
+
const errorCalls = (console.error as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0] as string);
|
|
247
|
+
expect(errorCalls.some((s) => s.includes("fallback also failed"))).toBe(true);
|
|
248
|
+
} finally {
|
|
249
|
+
restore();
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// ── W2c: postAgentResult 防御(经 handleWorkerMessage 触发) ──
|
|
255
|
+
//
|
|
256
|
+
// postAgentResult 是私有函数,通过 workflow-call 路径无法触发。但它可经 agent-call
|
|
257
|
+
// 路径的「cached replay」分支触发:dispatchAgentCall 发现 run.state.calls.get(callId)
|
|
258
|
+
// 已是 done 时,直接 postAgentResult(run, callId, cached.result, true)(无需 spawn
|
|
259
|
+
// 子进程)。利用这一点构造行为测试——往 cached.result 里塞不可克隆值(function),
|
|
260
|
+
// mock postMessage 在首次发送 agent-result 时抛 DataCloneError,验证 fallback 路径。
|
|
261
|
+
//
|
|
262
|
+
// 另外补充:验证 error-recovery.ts 源码中三处 postMessage 调用点都有 try/catch 包裹,
|
|
263
|
+
// 防止未来重构误删防御(类似 worker-script-builder.test.ts 的源码字符串断言模式)。
|
|
264
|
+
|
|
265
|
+
/** 构造 status="running" 且 calls 已含一个 done 结果(含不可克隆成员)的 mock run。
|
|
266
|
+
* 触发 dispatchAgentCall 的 cached replay 分支(line ~234),直接走 postAgentResult。 */
|
|
267
|
+
function makeRunningRunWithCachedDone(
|
|
268
|
+
postMessage: ReturnType<typeof vi.fn>,
|
|
269
|
+
callId: number,
|
|
270
|
+
result: unknown,
|
|
271
|
+
): WorkflowRun {
|
|
272
|
+
const calls = new Map();
|
|
273
|
+
calls.set(callId, { status: "done", result });
|
|
274
|
+
return {
|
|
275
|
+
state: {
|
|
276
|
+
status: "running",
|
|
277
|
+
calls,
|
|
278
|
+
trace: { append: vi.fn(), update: vi.fn() },
|
|
279
|
+
budget: { isExceeded: vi.fn(() => false) },
|
|
280
|
+
},
|
|
281
|
+
runtime: { worker: { postMessage } },
|
|
282
|
+
} as unknown as WorkflowRun;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
describe("W2c: postAgentResult 行为测试(cached replay 路径)", () => {
|
|
286
|
+
it("result 不可克隆 → 回发纯字符串 fallback result(cached: false)", async () => {
|
|
287
|
+
const restore = silenceConsoleError();
|
|
288
|
+
try {
|
|
289
|
+
// 第 1 次 postMessage 抛 DataCloneError(原始 cached.result 含 function 不可克隆),
|
|
290
|
+
// 第 2 次(fallback)成功。
|
|
291
|
+
const postMessage = makeFailingPostMessage(1);
|
|
292
|
+
// cached.result 含 function 成员 → 模拟 agent 返回不可克隆值({ bad: () => {} })
|
|
293
|
+
const run = makeRunningRunWithCachedDone(postMessage, 7, { bad: () => {} });
|
|
294
|
+
const deps = makeDeps();
|
|
295
|
+
|
|
296
|
+
await handleWorkerMessage(
|
|
297
|
+
run,
|
|
298
|
+
{ type: "agent-call", callId: 7, opts: { prompt: "noop" } },
|
|
299
|
+
deps,
|
|
300
|
+
makeHandlers(),
|
|
301
|
+
);
|
|
302
|
+
await flushMicrotasks();
|
|
303
|
+
|
|
304
|
+
// 调用两次:1 原始 agent-result(失败)+ 1 fallback(成功)
|
|
305
|
+
expect(postMessage).toHaveBeenCalledTimes(2);
|
|
306
|
+
|
|
307
|
+
// 第 1 次:原始 agent-result,result 透传原值,cached 为 replay 的 true
|
|
308
|
+
const original = postedAt(postMessage, 0);
|
|
309
|
+
expect(original.type).toBe("agent-result");
|
|
310
|
+
expect(original.callId).toBe(7);
|
|
311
|
+
expect(original.cached).toBe(true);
|
|
312
|
+
|
|
313
|
+
// 第 2 次:fallback agent-result,result 形状为 {content:"", error:"Result serialization failed: ..."},
|
|
314
|
+
// 且 cached 固定为 false(fallback result 非缓存命中,透传原值含义失真)
|
|
315
|
+
const fallback = postedAt(postMessage, 1);
|
|
316
|
+
expect(fallback.type).toBe("agent-result");
|
|
317
|
+
expect(fallback.callId).toBe(7);
|
|
318
|
+
expect(fallback.result?.content).toBe("");
|
|
319
|
+
expect(fallback.result?.error).toContain("Result serialization failed");
|
|
320
|
+
expect(fallback.result?.error).toContain("Could not clone object");
|
|
321
|
+
expect(fallback.cached).toBe(false);
|
|
322
|
+
} finally {
|
|
323
|
+
restore();
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("fallback 也失败 → 不向上抛错,记录 worker pending 将挂起", async () => {
|
|
328
|
+
const restore = silenceConsoleError();
|
|
329
|
+
try {
|
|
330
|
+
// postMessage 永远抛 DataCloneError(原始 + fallback 均失败)
|
|
331
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
332
|
+
const run = makeRunningRunWithCachedDone(postMessage, 8, { bad: () => {} });
|
|
333
|
+
const deps = makeDeps();
|
|
334
|
+
|
|
335
|
+
// handleWorkerMessage 自身不应抛——postAgentResult 内部已 catch
|
|
336
|
+
await expect(
|
|
337
|
+
handleWorkerMessage(
|
|
338
|
+
run,
|
|
339
|
+
{ type: "agent-call", callId: 8, opts: { prompt: "noop" } },
|
|
340
|
+
deps,
|
|
341
|
+
makeHandlers(),
|
|
342
|
+
),
|
|
343
|
+
).resolves.toBeUndefined();
|
|
344
|
+
await flushMicrotasks();
|
|
345
|
+
|
|
346
|
+
// 至少 2 次尝试(原始 + fallback),fallback 失败也记日志
|
|
347
|
+
expect(postMessage.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
348
|
+
const errorCalls = (console.error as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0] as string);
|
|
349
|
+
expect(errorCalls.some((s) => s.includes("postAgentResult failed"))).toBe(true);
|
|
350
|
+
expect(errorCalls.some((s) => s.includes("fallback also failed"))).toBe(true);
|
|
351
|
+
} finally {
|
|
352
|
+
restore();
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
describe("W2c: postAgentResult 防御(源码结构断言)", () => {
|
|
358
|
+
/** 校验:给定函数体内的 postMessage 调用被 try/catch 包裹。
|
|
359
|
+
* 简化策略——在函数体片段中确认存在 try { ... postMessage ... } catch。 */
|
|
360
|
+
function hasTryCatchAroundPostMessage(funcBody: string): boolean {
|
|
361
|
+
return /try\s*\{[\s\S]*?postMessage[\s\S]*?\}\s*catch/.test(funcBody);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
it("postAgentResult 包含 try/catch + fallback result", () => {
|
|
365
|
+
const match = ERROR_RECOVERY_SRC.match(/function postAgentResult\([\s\S]*?\n\}/);
|
|
366
|
+
expect(match, "postAgentResult 函数定义应存在").toBeTruthy();
|
|
367
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
368
|
+
// fallback 通过共享工厂 makeSerializeFailedResult 构造纯字符串 result(必可克隆)
|
|
369
|
+
expect(match![0]).toContain('result: makeSerializeFailedResult("Result serialization failed"');
|
|
370
|
+
expect(match![0]).toContain("Result serialization failed");
|
|
371
|
+
// 原 result 不可克隆时 cached 透传原值含义失真 → fallback 固定 cached: false
|
|
372
|
+
expect(match![0]).toContain("cached: false");
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it("postBudgetUpdate 包含 try/catch", () => {
|
|
376
|
+
const match = ERROR_RECOVERY_SRC.match(/export function postBudgetUpdate\([\s\S]*?\n\}/);
|
|
377
|
+
expect(match, "postBudgetUpdate 函数定义应存在").toBeTruthy();
|
|
378
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it("dispatchWorkflowCall postResult 闭包包含 try/catch + fallback", () => {
|
|
382
|
+
// postResult 是 const 闭包,匹配到下一个 }; 结尾
|
|
383
|
+
const match = ERROR_RECOVERY_SRC.match(/const postResult = \(result[\s\S]*?\n \};/);
|
|
384
|
+
expect(match, "postResult 闭包定义应存在").toBeTruthy();
|
|
385
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
386
|
+
expect(match![0]).toContain("Workflow result serialization failed");
|
|
387
|
+
// 防御变量名遮蔽:错误变量用 err 而非 msg(外层参数名 msg)
|
|
388
|
+
expect(match![0]).toMatch(/catch \(err\)/);
|
|
389
|
+
});
|
|
390
|
+
});
|