@zhushanwen/pi-subagent-workflow 0.4.0 → 0.4.2
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 +6 -6
- package/src/execution/__tests__/bg-notify-render.test.ts +1 -1
- package/src/execution/__tests__/crash-recovery.test.ts +3 -3
- package/src/execution/__tests__/execute-nesting.test.ts +16 -0
- package/src/execution/__tests__/helpers/mock-extension-api.ts +1 -1
- package/src/execution/__tests__/index-session-start.test.ts +4 -4
- package/src/execution/__tests__/sdk-contract.test.ts +1 -1
- package/src/execution/__tests__/session-start-reaper.test.ts +3 -3
- package/src/execution/__tests__/ui-request-handler-factory.test.ts +1 -1
- package/src/execution/host-mode.ts +1 -1
- package/src/execution/session-runner.ts +1 -1
- package/src/execution/subagent-service.ts +1 -1
- package/src/execution/ui-request-handler-factory.ts +2 -2
- package/src/execution/ui-request-observability.ts +1 -1
- package/src/index.ts +3 -3
- package/src/interface/__tests__/workflow-tool-prompt.test.ts +13 -2
- package/src/interface/bg-notify-render.ts +1 -1
- package/src/interface/commands.ts +1 -1
- package/src/interface/helpers.ts +1 -1
- package/src/interface/list-view.ts +1 -1
- package/src/interface/subagent-actions.ts +1 -1
- package/src/interface/subagent-tool.ts +2 -2
- package/src/interface/subagents.ts +1 -1
- package/src/interface/tool-render.ts +1 -1
- package/src/interface/tool-workflow-script.ts +7 -6
- package/src/interface/tool-workflow.ts +10 -7
- package/src/interface/views/WorkflowsView.ts +2 -2
- package/src/interface/views/detail-content.ts +1 -1
- package/src/interface/views/format.ts +1 -1
- package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +390 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +74 -0
- package/src/orchestration/config-loader.ts +1 -1
- package/src/orchestration/error-recovery.ts +77 -13
- package/src/orchestration/jsonl-run-store.ts +2 -2
- package/src/orchestration/worker-script-builder.ts +49 -8
- 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
|
@@ -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
|
+
});
|
|
@@ -55,3 +55,77 @@ describe("buildWorkerScript — agent() skill field in task/agent branch", () =>
|
|
|
55
55
|
expect(taskAgentBranch![0]).toContain("skill: firstArg.skill");
|
|
56
56
|
});
|
|
57
57
|
});
|
|
58
|
+
|
|
59
|
+
// ── W1: postMessage 防御 + parallel() 降级类型安全 ──
|
|
60
|
+
|
|
61
|
+
describe("buildWorkerScript — W1 postMessage defense & parallel degrade", () => {
|
|
62
|
+
const script = buildWorkerScript("// noop user script");
|
|
63
|
+
|
|
64
|
+
describe("_safePost wrapper", () => {
|
|
65
|
+
it("injects _safePost function", () => {
|
|
66
|
+
expect(script).toContain("function _safePost(msg, context)");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("_safePost wraps postMessage in try/catch", () => {
|
|
70
|
+
expect(script).toMatch(/_safePost[\s\S]*?try \{ parentPort\.postMessage\(msg\)/);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("_safePost logs failure with context to workerLogs", () => {
|
|
74
|
+
expect(script).toContain('_pushWorkerLog("error"');
|
|
75
|
+
expect(script).toContain('"[postMessage failed:" + context + "]"');
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe("agent() uses _safePost", () => {
|
|
80
|
+
it("agent-call postMessage guarded by _safePost", () => {
|
|
81
|
+
expect(script).toContain("_safePost({ type: \"agent-call\"");
|
|
82
|
+
expect(script).toContain('"agent-call"');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("agent() throws on postMessage failure", () => {
|
|
86
|
+
expect(script).toContain("postMessage failed for agent-call");
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("workflow() uses _safePost", () => {
|
|
91
|
+
it("workflow-call postMessage guarded by _safePost", () => {
|
|
92
|
+
expect(script).toContain("_safePost({ type: \"workflow-call\"");
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe("return/error use _safePost", () => {
|
|
97
|
+
it("return postMessage uses _safePost", () => {
|
|
98
|
+
expect(script).toContain('_safePost({ type: "return"');
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("error postMessage uses _safePost", () => {
|
|
102
|
+
expect(script).toContain('_safePost({ type: "error"');
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe("parallel() degrade returns object", () => {
|
|
107
|
+
it("rejected results become {status:failed,error} objects", () => {
|
|
108
|
+
expect(script).toContain('status: "failed"');
|
|
109
|
+
expect(script).toMatch(/parallel[\s\S]*?status: "failed"/);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("non-object fulfilled values wrapped as failed", () => {
|
|
113
|
+
expect(script).toContain("agent returned non-object result");
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("object fulfilled values pass through unchanged", () => {
|
|
117
|
+
expect(script).toContain("!Array.isArray(v)");
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("pipeline() error observability", () => {
|
|
122
|
+
it("single-arg mode logs stage errors before re-throwing", () => {
|
|
123
|
+
expect(script).toContain("[pipeline stage ");
|
|
124
|
+
expect(script).toContain("_pushWorkerLog(\"error\"");
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("cartesian mode logs stage errors instead of silent swallow", () => {
|
|
128
|
+
expect(script).toContain("[pipeline cartesian stage failed");
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
});
|
|
@@ -14,7 +14,7 @@ import { resolve } from "node:path";
|
|
|
14
14
|
import type { WorkflowMeta, WorkflowSource } from "./models/workflow-script.ts";
|
|
15
15
|
export type { WorkflowMeta, WorkflowSource };
|
|
16
16
|
|
|
17
|
-
import { getAgentDir } from "@
|
|
17
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
18
18
|
|
|
19
19
|
import {
|
|
20
20
|
discoverResources,
|
|
@@ -427,6 +427,19 @@ function dispatchAgentCall(
|
|
|
427
427
|
});
|
|
428
428
|
}
|
|
429
429
|
|
|
430
|
+
/**
|
|
431
|
+
* postMessage 序列化失败时回发的 fallback result(必可克隆),让 worker pending resolve。
|
|
432
|
+
*
|
|
433
|
+
* postResult(workflow-call)与 postAgentResult(agent-call)各自前缀不同,故 prefix 参数化,
|
|
434
|
+
* 共享返回类型与构造逻辑,避免字面量重复导致形状漂移。
|
|
435
|
+
*/
|
|
436
|
+
function makeSerializeFailedResult(
|
|
437
|
+
prefix: string,
|
|
438
|
+
errMsg: string,
|
|
439
|
+
): { content: string; error: string } {
|
|
440
|
+
return { content: "", error: `${prefix}: ${errMsg}` };
|
|
441
|
+
}
|
|
442
|
+
|
|
430
443
|
/**
|
|
431
444
|
* 派发 workflow 嵌套调用:调 deps.onWorkflowCall 获取子 workflow 结果,
|
|
432
445
|
* 异步 postMessage(workflow-result) 回 worker。
|
|
@@ -449,11 +462,31 @@ function dispatchWorkflowCall(
|
|
|
449
462
|
|
|
450
463
|
const postResult = (result: unknown): void => {
|
|
451
464
|
if (run.state.status !== "running") return;
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
465
|
+
// W2 主线程防御:result 是子 workflow 任意返回值,可能含不可克隆成员(function/
|
|
466
|
+
// Symbol/循环引用)→ postMessage 同步抛 DataCloneError。内部 try/catch + 回发
|
|
467
|
+
// 纯字符串 fallback result,让 worker 内 workflow() pending Promise resolve。
|
|
468
|
+
// 注意:错误变量用 err(外层 dispatchWorkflowCall 参数名为 msg,避免遮蔽)。
|
|
469
|
+
try {
|
|
470
|
+
run.runtime?.worker.postMessage({
|
|
471
|
+
type: "workflow-result",
|
|
472
|
+
callId: msg.callId,
|
|
473
|
+
result,
|
|
474
|
+
});
|
|
475
|
+
} catch (err) {
|
|
476
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
477
|
+
console.error(`[workflow] postResult (workflow-call callId=${msg.callId}) failed: ${errMsg}. Sending error fallback.`);
|
|
478
|
+
// 回发纯字符串 fallback result(必可克隆),让 worker pending resolve
|
|
479
|
+
try {
|
|
480
|
+
run.runtime?.worker.postMessage({
|
|
481
|
+
type: "workflow-result",
|
|
482
|
+
callId: msg.callId,
|
|
483
|
+
result: makeSerializeFailedResult("Workflow result serialization failed", errMsg),
|
|
484
|
+
});
|
|
485
|
+
} catch {
|
|
486
|
+
// fallback 也失败——worker 此 callId 的 pending 只能靠 timeout 兜底
|
|
487
|
+
console.error(`[workflow] postResult fallback also failed (callId=${msg.callId}): worker pending will hang until timeout`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
457
490
|
};
|
|
458
491
|
|
|
459
492
|
if (!deps.onWorkflowCall) {
|
|
@@ -477,6 +510,12 @@ function dispatchWorkflowCall(
|
|
|
477
510
|
|
|
478
511
|
/**
|
|
479
512
|
* 回发 agent-result 给 worker(worker 内 pending Promise 据此 resolve)。
|
|
513
|
+
*
|
|
514
|
+
* W2 主线程防御:result 是 agent 返回值,含不可克隆成员(function/Symbol/循环引用)时
|
|
515
|
+
* postMessage 同步抛 DataCloneError。若冒泡到 dispatchAgentCall 的 .then 回调,会中断
|
|
516
|
+
* 后续 postBudgetUpdate/store.save/budget 检查,run 卡在 running。故内部 try/catch:
|
|
517
|
+
* 失败时记录诊断 + 回发纯字符串 fallback result(必可克隆),让 worker pending resolve。
|
|
518
|
+
* 函数签名不变(所有调用点无需改动),仅用 console.error 记日志(deps 不在手边)。
|
|
480
519
|
*/
|
|
481
520
|
function postAgentResult(
|
|
482
521
|
run: WorkflowRun,
|
|
@@ -484,7 +523,25 @@ function postAgentResult(
|
|
|
484
523
|
result: AgentResult,
|
|
485
524
|
cached: boolean,
|
|
486
525
|
): void {
|
|
487
|
-
|
|
526
|
+
try {
|
|
527
|
+
run.runtime?.worker.postMessage({ type: "agent-result", callId, result, cached });
|
|
528
|
+
} catch (err) {
|
|
529
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
530
|
+
console.error(`[workflow] postAgentResult failed (callId=${callId}): ${msg}. Result likely contains non-cloneable value.`);
|
|
531
|
+
// 回发纯字符串 fallback result(必可克隆),让 worker pending resolve(避免永久挂起)
|
|
532
|
+
try {
|
|
533
|
+
run.runtime?.worker.postMessage({
|
|
534
|
+
type: "agent-result",
|
|
535
|
+
callId,
|
|
536
|
+
result: makeSerializeFailedResult("Result serialization failed", msg),
|
|
537
|
+
// 原 result 不可克隆时 cached 透传原值含义失真(fallback result 非缓存命中)→ 固定 false
|
|
538
|
+
cached: false,
|
|
539
|
+
});
|
|
540
|
+
} catch {
|
|
541
|
+
// fallback 也失败——worker 此 callId 的 pending 只能靠 timeout/exit 兜底
|
|
542
|
+
console.error(`[workflow] postAgentResult fallback also failed (callId=${callId}): worker pending will hang until timeout`);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
488
545
|
}
|
|
489
546
|
|
|
490
547
|
/**
|
|
@@ -496,13 +553,20 @@ function postAgentResult(
|
|
|
496
553
|
* (dispatch 后同步 worker $BUDGET)——单一实现,避免消息形状漂移。
|
|
497
554
|
*/
|
|
498
555
|
export function postBudgetUpdate(run: WorkflowRun): void {
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
556
|
+
try {
|
|
557
|
+
run.runtime?.worker.postMessage({
|
|
558
|
+
type: "budget-update",
|
|
559
|
+
budget: {
|
|
560
|
+
usedTokens: run.state.budget.usedTokens,
|
|
561
|
+
usedCost: run.state.budget.usedCost,
|
|
562
|
+
},
|
|
563
|
+
});
|
|
564
|
+
} catch (err) {
|
|
565
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
566
|
+
// budget 是纯 number 不太可能失败,但防御性兜底——budget 同步非关键(worker 仍可
|
|
567
|
+
// 基于 $BUDGET.spent() 自行累计),失败仅记日志,不中断调用方流程。
|
|
568
|
+
console.error(`[workflow] postBudgetUpdate failed: ${msg}. Budget sync to worker skipped (non-critical).`);
|
|
569
|
+
}
|
|
506
570
|
}
|
|
507
571
|
|
|
508
572
|
/**
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* 职责:持久化 WorkflowRun 聚合根到 JSONL 文件 + 跨 session 重水合。
|
|
7
7
|
*
|
|
8
8
|
* 层归属:Infra(D-12)。implements Engine 层的 RunStore port。
|
|
9
|
-
* 依赖 @
|
|
9
|
+
* 依赖 @earendil-works/pi-coding-agent 的 ExtensionAPI/ExtensionContext(Infra 允许 Pi SDK)。
|
|
10
10
|
*
|
|
11
11
|
* 设计:
|
|
12
12
|
* - JsonlRunStore implements RunStore(而非散落的 persist/reconstruct 自由函数)。
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
import * as fs from "node:fs";
|
|
27
27
|
import * as path from "node:path";
|
|
28
28
|
|
|
29
|
-
import type { ExtensionAPI, ExtensionContext } from "@
|
|
29
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
30
30
|
|
|
31
31
|
import { AgentCall } from "./models/agent-call.ts";
|
|
32
32
|
import { Budget } from "./models/budget.ts";
|