@zhushanwen/pi-subagent-workflow 0.1.0 → 0.2.0
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/agents/context-builder.md +1 -3
- package/agents/oracle.md +2 -2
- package/agents/planner.md +1 -3
- package/agents/researcher.md +0 -2
- package/agents/reviewer.md +2 -2
- package/agents/scout.md +13 -3
- package/agents/worker.md +0 -2
- package/package.json +5 -3
- package/skills/workflow-script-format/SKILL.md +6 -6
- package/src/execution/__tests__/agent-result-mapper.test.ts +24 -2
- package/src/execution/__tests__/concurrency-pool.test.ts +33 -0
- package/src/execution/__tests__/execute-options-mapper.test.ts +40 -8
- package/src/execution/__tests__/gui-mode-dispatch.test.ts +60 -0
- package/src/execution/__tests__/sdk-contract.test.ts +5 -2
- package/src/execution/__tests__/session-reconstructor.test.ts +20 -0
- package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
- package/src/execution/__tests__/subprocess-agent-runner.test.ts +72 -3
- package/src/execution/__tests__/tool-action.test.ts +26 -4
- package/src/execution/agent-result-mapper.ts +4 -1
- package/src/execution/concurrency-pool.ts +38 -6
- package/src/execution/execute-options-mapper.ts +21 -4
- package/src/execution/execution-record.ts +5 -0
- package/src/execution/record-store.ts +2 -0
- package/src/execution/session-reconstructor.ts +11 -0
- package/src/execution/session-runner.ts +12 -0
- package/src/execution/stream-sink.ts +83 -0
- package/src/execution/subagent-service.ts +68 -43
- package/src/execution/subprocess-agent-runner.ts +16 -4
- package/src/execution/types.ts +23 -3
- package/src/index.ts +15 -2
- package/src/interface/__tests__/subagent-tool-prompt.test.ts +84 -0
- package/src/interface/__tests__/workflow-state-file-exposure.test.ts +38 -0
- package/src/interface/__tests__/workflow-tool-prompt.test.ts +50 -0
- package/src/interface/command-actions.ts +77 -0
- package/src/interface/commands.ts +40 -4
- package/src/interface/gui-mappers.ts +83 -0
- package/src/interface/helpers.ts +52 -9
- package/src/interface/list-component.ts +3 -1
- package/src/interface/subagent-actions.ts +35 -22
- package/src/interface/subagent-tool.ts +54 -23
- package/src/interface/subagents.ts +45 -5
- package/src/interface/tool-render.ts +16 -5
- package/src/interface/tool-workflow-script.ts +113 -15
- package/src/interface/tool-workflow.ts +92 -34
- package/src/interface/views/WorkflowsView.ts +13 -4
- package/src/interface/views/__tests__/detail-content-session-file.test.ts +70 -0
- package/src/interface/views/detail-content.ts +20 -0
- package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +208 -0
- package/src/orchestration/__tests__/agent-call-stream.test.ts +157 -0
- package/src/orchestration/__tests__/error-recovery-handlers.test.ts +2 -0
- package/src/orchestration/__tests__/execute-agent-call.test.ts +171 -0
- package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +177 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +15 -0
- package/src/orchestration/agent-opts-resolver.ts +11 -2
- package/src/orchestration/error-recovery.ts +131 -23
- package/src/orchestration/execute-agent-call.ts +12 -3
- package/src/orchestration/jsonl-run-store.ts +10 -0
- package/src/orchestration/lifecycle.ts +1 -1
- package/src/orchestration/models/agent-call.ts +7 -0
- package/src/orchestration/models/ports.ts +15 -2
- package/src/orchestration/models/run-spec.ts +6 -0
- package/src/orchestration/models/trace.ts +1 -0
- package/src/orchestration/models/types.ts +19 -0
- package/src/orchestration/node-ops.ts +2 -0
- package/src/orchestration/worker-script-builder.ts +1 -0
- package/workflows/README.md +58 -0
- package/workflows/chain.js +107 -0
- package/workflows/map-reduce.js +142 -0
- package/workflows/parallel.js +131 -0
- package/workflows/scatter-gather.js +146 -0
- package/examples/README.md +0 -43
- package/examples/chain.example.js +0 -92
- package/examples/map-reduce.example.js +0 -99
- package/examples/parallel.example.js +0 -82
- package/examples/scatter-gather.example.js +0 -106
- package/src/interface/gui-adapter.ts +0 -136
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// src/interface/views/__tests__/detail-content-session-file.test.ts
|
|
2
|
+
//
|
|
3
|
+
// TUI 渲染测试:buildDetailContent 在 agent 终态时渲染 session: 路径行。
|
|
4
|
+
//
|
|
5
|
+
// 防的 bug:node.sessionFile 有值但 TUI detail 不显示——用户在交互面板里
|
|
6
|
+
// 看不到 agent 的 session jsonl 路径,无法定位文件做后续查看。
|
|
7
|
+
|
|
8
|
+
import { describe, expect, it } from "vitest";
|
|
9
|
+
|
|
10
|
+
import { buildDetailContent } from "../detail-content.ts";
|
|
11
|
+
import type { ThemeLike } from "../format.ts";
|
|
12
|
+
import type { ExecutionTraceNode } from "../../../orchestration/models/types.ts";
|
|
13
|
+
import type { WorkflowRun } from "../../../orchestration/models/workflow-run.ts";
|
|
14
|
+
|
|
15
|
+
/** plain theme: fg/bold 直接返回原文,无 ANSI 色码——测试断言纯文本。 */
|
|
16
|
+
const plainTheme: ThemeLike = {
|
|
17
|
+
fg: (_tag: string, text: string) => text,
|
|
18
|
+
bold: (text: string) => text,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function makeNode(overrides: Partial<ExecutionTraceNode> = {}): ExecutionTraceNode {
|
|
22
|
+
return {
|
|
23
|
+
stepIndex: 0,
|
|
24
|
+
agent: "worker",
|
|
25
|
+
task: "do something",
|
|
26
|
+
model: "default",
|
|
27
|
+
status: "completed",
|
|
28
|
+
...overrides,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 最小 WorkflowRun——buildDetailContent 只读 run.state.errorLogs。 */
|
|
33
|
+
function makeRun(): WorkflowRun {
|
|
34
|
+
return {
|
|
35
|
+
state: { errorLogs: [] },
|
|
36
|
+
} as unknown as WorkflowRun;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe("buildDetailContent session 路径行渲染", () => {
|
|
40
|
+
it("node.sessionFile 有值 → 详情末尾渲染 session: <路径>", () => {
|
|
41
|
+
const sessionPath = "/abs/.pi/agent/subagents/enc/sessions/2026-07-15T_session-abc.jsonl";
|
|
42
|
+
const node = makeNode({
|
|
43
|
+
status: "completed",
|
|
44
|
+
sessionFile: sessionPath,
|
|
45
|
+
result: { content: "done" },
|
|
46
|
+
});
|
|
47
|
+
const lines = buildDetailContent(node, { promptExpanded: false }, makeRun(), plainTheme, 120, Date.now());
|
|
48
|
+
const sessionLine = lines.find((l) => l.includes("session:"));
|
|
49
|
+
expect(sessionLine).toBeDefined();
|
|
50
|
+
expect(sessionLine).toContain(sessionPath);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("node.sessionFile undefined(窗口期)→ 不渲染 session: 行", () => {
|
|
54
|
+
const node = makeNode({ status: "completed", sessionFile: undefined, result: { content: "done" } });
|
|
55
|
+
const lines = buildDetailContent(node, { promptExpanded: false }, makeRun(), plainTheme, 120, Date.now());
|
|
56
|
+
const sessionLine = lines.find((l) => l.includes("session:"));
|
|
57
|
+
expect(sessionLine).toBeUndefined();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("长路径截断到 mainWidth(防溢出)", () => {
|
|
61
|
+
const longPath = "/very/long/path/" + "x".repeat(200) + "/session.jsonl";
|
|
62
|
+
const node = makeNode({ status: "completed", sessionFile: longPath, result: { content: "done" } });
|
|
63
|
+
const narrowWidth = 60;
|
|
64
|
+
const lines = buildDetailContent(node, { promptExpanded: false }, makeRun(), plainTheme, narrowWidth, Date.now());
|
|
65
|
+
const sessionLine = lines.find((l) => l.includes("session:"));
|
|
66
|
+
expect(sessionLine).toBeDefined();
|
|
67
|
+
// 截断后行宽不超过 mainWidth + 边框余量
|
|
68
|
+
expect(sessionLine!.length).toBeLessThanOrEqual(narrowWidth);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
@@ -87,6 +87,7 @@ export function buildDetailContent(
|
|
|
87
87
|
renderPromptSection(rightLines, node, state, theme);
|
|
88
88
|
renderActivitySection(rightLines, node, mainWidth, theme);
|
|
89
89
|
renderOutcomeSection(rightLines, node, mainWidth, theme);
|
|
90
|
+
renderSessionSection(rightLines, node, mainWidth, theme);
|
|
90
91
|
return rightLines;
|
|
91
92
|
}
|
|
92
93
|
|
|
@@ -296,3 +297,22 @@ function renderOutcomeSection(
|
|
|
296
297
|
}
|
|
297
298
|
}
|
|
298
299
|
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 渲染 session jsonl 路径行(agent 级)。
|
|
303
|
+
*
|
|
304
|
+
* 对齐 subagents list-component 的 `session:` 行渲染(dim 色 + 截断)。
|
|
305
|
+
* sessionFile 是绝对路径,可能很长——截断到 mainWidth 防溢出。
|
|
306
|
+
* 窗口期(session 尚未创建)sessionFile 为 undefined,整段不渲染。
|
|
307
|
+
*/
|
|
308
|
+
function renderSessionSection(
|
|
309
|
+
rightLines: string[],
|
|
310
|
+
node: ExecutionTraceNode,
|
|
311
|
+
mainWidth: number,
|
|
312
|
+
theme: ThemeLike,
|
|
313
|
+
): void {
|
|
314
|
+
if (!node.sessionFile) return;
|
|
315
|
+
rightLines.push("");
|
|
316
|
+
const line = `session: ${node.sessionFile}`.slice(0, mainWidth - BOX_BORDER_CHARS);
|
|
317
|
+
rightLines.push(theme.fg("dim", ` ${line}`));
|
|
318
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// src/orchestration/__tests__/agent-call-catch-fallback.test.ts
|
|
2
|
+
//
|
|
3
|
+
// U7: dispatchAgentCall catch 分支回发 agent-result 给 worker(吞错兜底)
|
|
4
|
+
//
|
|
5
|
+
// 场景:executeAgentCall(或 gate.withSlot)抛非 Abort 异常时,原 catch 块仅
|
|
6
|
+
// console.error,worker 内对应 callId 的 pending Promise 永不 resolve → agent()
|
|
7
|
+
// 永久 await → worker 脚本挂死。修复后 catch 块构造 failed AgentResult 并
|
|
8
|
+
// postAgentResult 回 worker,使 pending Promise 能 resolve(结果为 error)。
|
|
9
|
+
//
|
|
10
|
+
// 通过 handleWorkerMessage 触发 dispatchAgentCall(内部函数不 export)。
|
|
11
|
+
// Mock 构造模式参考 agent-call-stream.test.ts。
|
|
12
|
+
|
|
13
|
+
import { describe, expect, it, vi } from "vitest";
|
|
14
|
+
|
|
15
|
+
import { handleWorkerMessage } from "../error-recovery.ts";
|
|
16
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
17
|
+
import { Trace } from "../models/trace.ts";
|
|
18
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
19
|
+
import type { AgentResult } from "../models/types.ts";
|
|
20
|
+
|
|
21
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/** 构造 status="running" 的 mock WorkflowRun,含 trace/budget/calls/runtime。
|
|
24
|
+
* worker.postMessage 为 vi.fn spy,便于断言回发内容。gate.withSlot 直接 await fn()
|
|
25
|
+
* 让异常透传到外层 .catch(模拟 executeAgentCall 抛错的真实链路)。 */
|
|
26
|
+
function makeRunningRun(runId: string): WorkflowRun {
|
|
27
|
+
const trace = new Trace();
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
return {
|
|
30
|
+
runId,
|
|
31
|
+
spec: { scriptName: "test-wf", scriptSource: "agent('hi')", args: {}, runId, slug: undefined },
|
|
32
|
+
state: {
|
|
33
|
+
status: "running" as const,
|
|
34
|
+
reason: undefined,
|
|
35
|
+
trace,
|
|
36
|
+
budget: {
|
|
37
|
+
usedTokens: 0,
|
|
38
|
+
usedCost: 0,
|
|
39
|
+
totalCallCount: 0,
|
|
40
|
+
consume: vi.fn(),
|
|
41
|
+
isExceeded: vi.fn(() => false),
|
|
42
|
+
incrementCallCount: vi.fn(),
|
|
43
|
+
},
|
|
44
|
+
calls: new Map(),
|
|
45
|
+
scriptResult: undefined,
|
|
46
|
+
},
|
|
47
|
+
meta: { startedAt: new Date().toISOString(), workerErrorCount: 0, scriptErrorCount: 0 },
|
|
48
|
+
runtime: {
|
|
49
|
+
controller,
|
|
50
|
+
worker: { postMessage: vi.fn() },
|
|
51
|
+
gate: {
|
|
52
|
+
// 直接 await fn():executeAgentCall 内 runner.run reject 会沿 withSlot → 外层 .catch
|
|
53
|
+
withSlot: vi.fn(async (fn: () => Promise<void>, _signal: AbortSignal) => {
|
|
54
|
+
await fn();
|
|
55
|
+
}),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
transition: vi.fn(),
|
|
59
|
+
replaceRuntime: vi.fn(),
|
|
60
|
+
} as unknown as WorkflowRun;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** LifecycleDeps mock,runner.run 可配置为 reject 指定 error。 */
|
|
64
|
+
function makeDeps(opts: { runnerError?: Error } = {}): LifecycleDeps {
|
|
65
|
+
const runnerRun = vi.fn(async () => {
|
|
66
|
+
if (opts.runnerError) throw opts.runnerError;
|
|
67
|
+
return { content: "OK", durationMs: 10, error: undefined, toolCalls: [] } as AgentResult;
|
|
68
|
+
});
|
|
69
|
+
return {
|
|
70
|
+
store: { save: vi.fn(async () => {}) },
|
|
71
|
+
workerHost: { start: vi.fn() },
|
|
72
|
+
runner: { run: runnerRun },
|
|
73
|
+
runs: new Map(),
|
|
74
|
+
eventBus: { emit: vi.fn() },
|
|
75
|
+
onRunDone: vi.fn(),
|
|
76
|
+
log: vi.fn(),
|
|
77
|
+
// streamSink 不设 = undefined(本测试不关心 stream)
|
|
78
|
+
} as unknown as LifecycleDeps;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function makeHandlers(): WorkerHandlers {
|
|
82
|
+
return {
|
|
83
|
+
onMessage: vi.fn(async () => {}),
|
|
84
|
+
onError: vi.fn(async () => {}),
|
|
85
|
+
onExit: vi.fn(async () => {}),
|
|
86
|
+
} as unknown as WorkerHandlers;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** agent-call 消息 */
|
|
90
|
+
function makeAgentCallMsg(callId: number): unknown {
|
|
91
|
+
return {
|
|
92
|
+
type: "agent-call",
|
|
93
|
+
callId,
|
|
94
|
+
phase: "test-phase",
|
|
95
|
+
opts: { prompt: "test task", agent: "worker", description: "test-slug" },
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 从 postMessage spy 的所有调用中找 type:"agent-result" 且 callId 匹配的参数。 */
|
|
100
|
+
function findAgentResultPost(
|
|
101
|
+
postMessage: ReturnType<typeof vi.fn>,
|
|
102
|
+
callId: number,
|
|
103
|
+
): { type: string; callId: number; result: AgentResult; cached: boolean } | undefined {
|
|
104
|
+
for (const call of postMessage.mock.calls) {
|
|
105
|
+
const msg = call[0] as { type?: string; callId?: number; result?: AgentResult; cached?: boolean };
|
|
106
|
+
if (msg?.type === "agent-result" && msg.callId === callId) return msg as never;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 静默 console.error(catch 块会打印失败日志,避免污染测试输出)。 */
|
|
112
|
+
function silenceConsoleError(): () => void {
|
|
113
|
+
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
114
|
+
return () => spy.mockRestore();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ── U7a: 非 Abort 异常 → postAgentResult 回发 failed result ──
|
|
118
|
+
|
|
119
|
+
describe("U7a: catch 分支兜底回发 agent-result(非 Abort 异常)", () => {
|
|
120
|
+
it("runner.run reject 'runner exploded' → worker 收到 {success:false, error:'runner exploded'}", async () => {
|
|
121
|
+
const restore = silenceConsoleError();
|
|
122
|
+
try {
|
|
123
|
+
const deps = makeDeps({ runnerError: new Error("runner exploded") });
|
|
124
|
+
const run = makeRunningRun("wf-catch-001");
|
|
125
|
+
const handlers = makeHandlers();
|
|
126
|
+
const postMessage = run.runtime!.worker.postMessage as ReturnType<typeof vi.fn>;
|
|
127
|
+
|
|
128
|
+
await handleWorkerMessage(run, makeAgentCallMsg(2), deps, handlers);
|
|
129
|
+
|
|
130
|
+
// dispatchAgentCall 内 void withSlot(...)(fire-and-forget),需等微任务完成
|
|
131
|
+
await vi.waitFor(() => {
|
|
132
|
+
expect(findAgentResultPost(postMessage, 2)).toBeDefined();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
const posted = findAgentResultPost(postMessage, 2)!;
|
|
136
|
+
expect(posted.type).toBe("agent-result");
|
|
137
|
+
expect(posted.callId).toBe(2);
|
|
138
|
+
expect(posted.cached).toBe(false);
|
|
139
|
+
// AgentResult.error 字段承载错误信息(与 resolveAgentOpts 失败路径一致)
|
|
140
|
+
expect(posted.result.error).toBe("runner exploded");
|
|
141
|
+
expect(posted.result.content).toBe("");
|
|
142
|
+
|
|
143
|
+
// state 一致性三件套(review should_fix):
|
|
144
|
+
// trace node 标 failed(不遗留 running 幽灵节点)
|
|
145
|
+
const traceNode = run.state.trace.find(2);
|
|
146
|
+
expect(traceNode?.status).toBe("failed");
|
|
147
|
+
expect(traceNode?.result?.error).toBe("runner exploded");
|
|
148
|
+
// node.live 清除(防内存泄漏)
|
|
149
|
+
expect(traceNode?.live).toBeUndefined();
|
|
150
|
+
// 持久化(catch 是最需留证的场景)
|
|
151
|
+
expect(deps.store.save).toHaveBeenCalled();
|
|
152
|
+
} finally {
|
|
153
|
+
restore();
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("非 Error 值 reject(字符串)→ error 字段为该字符串", async () => {
|
|
158
|
+
const restore = silenceConsoleError();
|
|
159
|
+
try {
|
|
160
|
+
const deps = makeDeps({ runnerError: "string failure" as unknown as Error });
|
|
161
|
+
const run = makeRunningRun("wf-catch-002");
|
|
162
|
+
const handlers = makeHandlers();
|
|
163
|
+
const postMessage = run.runtime!.worker.postMessage as ReturnType<typeof vi.fn>;
|
|
164
|
+
|
|
165
|
+
await handleWorkerMessage(run, makeAgentCallMsg(7), deps, handlers);
|
|
166
|
+
|
|
167
|
+
await vi.waitFor(() => {
|
|
168
|
+
expect(findAgentResultPost(postMessage, 7)).toBeDefined();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const posted = findAgentResultPost(postMessage, 7)!;
|
|
172
|
+
expect(posted.result.error).toBe("string failure");
|
|
173
|
+
} finally {
|
|
174
|
+
restore();
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// ── U7b: AbortError → 不回发(预期路径,吞掉) ──
|
|
180
|
+
|
|
181
|
+
describe("U7b: AbortError 不回发 agent-result", () => {
|
|
182
|
+
it("runner.run reject AbortError → postAgentResult 不被调用", async () => {
|
|
183
|
+
const restore = silenceConsoleError();
|
|
184
|
+
try {
|
|
185
|
+
const abortErr = new Error("aborted");
|
|
186
|
+
abortErr.name = "AbortError";
|
|
187
|
+
const deps = makeDeps({ runnerError: abortErr });
|
|
188
|
+
const run = makeRunningRun("wf-catch-003");
|
|
189
|
+
const handlers = makeHandlers();
|
|
190
|
+
const postMessage = run.runtime!.worker.postMessage as ReturnType<typeof vi.fn>;
|
|
191
|
+
|
|
192
|
+
await handleWorkerMessage(run, makeAgentCallMsg(3), deps, handlers);
|
|
193
|
+
|
|
194
|
+
// 等待 fire-and-forget 链路稳定:无 agent-result 回发。
|
|
195
|
+
// 先 flush 微任务队列(多次确保 withSlot promise 已 settle),
|
|
196
|
+
// 再断言断言期内无 agent-result。vi.waitFor 用反向断言会一满足就 return,
|
|
197
|
+
// 故采用:跑若干 microtask tick 后静态断言。
|
|
198
|
+
for (let i = 0; i < 5; i++) {
|
|
199
|
+
// eslint-disable-next-line no-await-in-loop
|
|
200
|
+
await Promise.resolve();
|
|
201
|
+
}
|
|
202
|
+
const posted = findAgentResultPost(postMessage, 3);
|
|
203
|
+
expect(posted).toBeUndefined();
|
|
204
|
+
} finally {
|
|
205
|
+
restore();
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
});
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// src/orchestration/__tests__/agent-call-stream.test.ts
|
|
2
|
+
//
|
|
3
|
+
// U4: dispatchAgentCall 创建 SubagentStream 并在 agent call 结束后 dispose
|
|
4
|
+
// U5: dispatchAgentCall widgetKey 格式 = subagent-stream-<runId>-<stepIndex>
|
|
5
|
+
// U6: streamSink 为 undefined 时 dispatchAgentCall 不创建 stream 不报错
|
|
6
|
+
//
|
|
7
|
+
// 通过 handleWorkerMessage 触发 dispatchAgentCall(内部函数不 export)。
|
|
8
|
+
|
|
9
|
+
import { describe, expect, it, vi } from "vitest";
|
|
10
|
+
|
|
11
|
+
import { handleWorkerMessage } from "../error-recovery.ts";
|
|
12
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
13
|
+
import { Trace } from "../models/trace.ts";
|
|
14
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
15
|
+
import type { AgentResult } from "../models/types.ts";
|
|
16
|
+
|
|
17
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
function makeMockResult(): AgentResult {
|
|
20
|
+
return { content: "OK", durationMs: 10, error: undefined, toolCalls: [] };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 构造 status="running" 的 mock WorkflowRun,含 trace/budget/calls/runtime */
|
|
24
|
+
function makeRunningRun(runId: string): WorkflowRun {
|
|
25
|
+
const trace = new Trace();
|
|
26
|
+
const controller = new AbortController();
|
|
27
|
+
return {
|
|
28
|
+
runId,
|
|
29
|
+
spec: { scriptName: "test-wf", scriptSource: "agent('hi')", args: {}, runId, slug: undefined },
|
|
30
|
+
state: {
|
|
31
|
+
status: "running" as const,
|
|
32
|
+
reason: undefined,
|
|
33
|
+
trace,
|
|
34
|
+
budget: {
|
|
35
|
+
usedTokens: 0,
|
|
36
|
+
usedCost: 0,
|
|
37
|
+
totalCallCount: 0,
|
|
38
|
+
consume: vi.fn(),
|
|
39
|
+
isExceeded: vi.fn(() => false),
|
|
40
|
+
incrementCallCount: vi.fn(),
|
|
41
|
+
},
|
|
42
|
+
calls: new Map(),
|
|
43
|
+
scriptResult: undefined,
|
|
44
|
+
},
|
|
45
|
+
meta: { startedAt: new Date().toISOString(), workerErrorCount: 0, scriptErrorCount: 0 },
|
|
46
|
+
runtime: {
|
|
47
|
+
controller,
|
|
48
|
+
worker: { postMessage: vi.fn() },
|
|
49
|
+
gate: {
|
|
50
|
+
withSlot: vi.fn(async (fn: () => Promise<void>, _signal: AbortSignal) => {
|
|
51
|
+
await fn();
|
|
52
|
+
}),
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
transition: vi.fn(),
|
|
56
|
+
replaceRuntime: vi.fn(),
|
|
57
|
+
} as unknown as WorkflowRun;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** LifecycleDeps mock,runner.run 可控制返回值,streamSink 可配置 */
|
|
61
|
+
function makeDeps(opts: {
|
|
62
|
+
streamSink?: { setWidget: ReturnType<typeof vi.fn> };
|
|
63
|
+
runnerResult?: AgentResult;
|
|
64
|
+
} = {}): LifecycleDeps {
|
|
65
|
+
return {
|
|
66
|
+
store: { save: vi.fn(async () => {}) },
|
|
67
|
+
workerHost: { start: vi.fn() },
|
|
68
|
+
runner: { run: vi.fn(async () => opts.runnerResult ?? makeMockResult()) },
|
|
69
|
+
runs: new Map(),
|
|
70
|
+
eventBus: { emit: vi.fn() },
|
|
71
|
+
onRunDone: vi.fn(),
|
|
72
|
+
log: vi.fn(),
|
|
73
|
+
streamSink: opts.streamSink,
|
|
74
|
+
} as unknown as LifecycleDeps;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function makeHandlers(): WorkerHandlers {
|
|
78
|
+
return {
|
|
79
|
+
onMessage: vi.fn(async () => {}),
|
|
80
|
+
onError: vi.fn(async () => {}),
|
|
81
|
+
onExit: vi.fn(async () => {}),
|
|
82
|
+
} as unknown as WorkerHandlers;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** agent-call 消息 */
|
|
86
|
+
function makeAgentCallMsg(callId: number): unknown {
|
|
87
|
+
return {
|
|
88
|
+
type: "agent-call",
|
|
89
|
+
callId,
|
|
90
|
+
phase: "test-phase",
|
|
91
|
+
opts: { prompt: "test task", agent: "worker", description: "test-slug" },
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── U4: dispatchAgentCall 创建 SubagentStream 并 dispose ──
|
|
96
|
+
|
|
97
|
+
describe("U4: dispatchAgentCall stream dispose", () => {
|
|
98
|
+
it("agent call 结束后 stream.dispose 被调用(setWidget 末次 lines=undefined)", async () => {
|
|
99
|
+
const setWidget = vi.fn();
|
|
100
|
+
const deps = makeDeps({ streamSink: { setWidget } });
|
|
101
|
+
const run = makeRunningRun("wf-test-123");
|
|
102
|
+
const handlers = makeHandlers();
|
|
103
|
+
|
|
104
|
+
await handleWorkerMessage(run, makeAgentCallMsg(0), deps, handlers);
|
|
105
|
+
// dispatchAgentCall 内部 void withSlot(...)(fire-and-forget),需等 microtask 完成
|
|
106
|
+
await vi.waitFor(() => {
|
|
107
|
+
expect(setWidget.mock.calls.length).toBeGreaterThanOrEqual(1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const calls = setWidget.mock.calls;
|
|
111
|
+
const lastCall = calls[calls.length - 1];
|
|
112
|
+
expect(lastCall[1]).toBeUndefined();
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// ── U5: widgetKey 格式 ──
|
|
117
|
+
|
|
118
|
+
describe("U5: widgetKey 格式", () => {
|
|
119
|
+
it("widgetKey = subagent-stream-<runId>-<stepIndex>", async () => {
|
|
120
|
+
const setWidget = vi.fn();
|
|
121
|
+
const deps = makeDeps({ streamSink: { setWidget } });
|
|
122
|
+
const run = makeRunningRun("wf-test-123");
|
|
123
|
+
const handlers = makeHandlers();
|
|
124
|
+
|
|
125
|
+
await handleWorkerMessage(run, makeAgentCallMsg(2), deps, handlers);
|
|
126
|
+
await vi.waitFor(() => {
|
|
127
|
+
expect(setWidget.mock.calls.length).toBeGreaterThanOrEqual(1);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const widgetKey = setWidget.mock.calls[0][0] as string;
|
|
131
|
+
expect(widgetKey).toBe("subagent-stream-wf-test-123-2");
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// ── U6: streamSink 为 undefined 时不报错 ──
|
|
136
|
+
|
|
137
|
+
describe("U6: streamSink undefined 降级", () => {
|
|
138
|
+
it("streamSink=undefined → runner.run 仍被调用,无异常", async () => {
|
|
139
|
+
const runnerRun = vi.fn(async () => makeMockResult());
|
|
140
|
+
const deps = {
|
|
141
|
+
store: { save: vi.fn(async () => {}) },
|
|
142
|
+
workerHost: { start: vi.fn() },
|
|
143
|
+
runner: { run: runnerRun },
|
|
144
|
+
runs: new Map(),
|
|
145
|
+
eventBus: { emit: vi.fn() },
|
|
146
|
+
onRunDone: vi.fn(),
|
|
147
|
+
log: vi.fn(),
|
|
148
|
+
// streamSink 不设 = undefined
|
|
149
|
+
} as unknown as LifecycleDeps;
|
|
150
|
+
const run = makeRunningRun("wf-test-456");
|
|
151
|
+
const handlers = makeHandlers();
|
|
152
|
+
|
|
153
|
+
await handleWorkerMessage(run, makeAgentCallMsg(0), deps, handlers);
|
|
154
|
+
|
|
155
|
+
expect(runnerRun).toHaveBeenCalledTimes(1);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// src/orchestration/__tests__/execute-agent-call.test.ts
|
|
2
|
+
//
|
|
3
|
+
// U2: executeAgentCall 透传 stream 给 runner.run
|
|
4
|
+
// U3: executeAgentCall retry 递归也透传 stream(不丢、不重建)
|
|
5
|
+
|
|
6
|
+
import { describe, expect, it, vi } from "vitest";
|
|
7
|
+
|
|
8
|
+
import { executeAgentCall } from "../execute-agent-call.ts";
|
|
9
|
+
import { AgentCall } from "../models/agent-call.ts";
|
|
10
|
+
import { Budget } from "../models/budget.ts";
|
|
11
|
+
import type { AgentRunner } from "../models/ports.ts";
|
|
12
|
+
import { Trace } from "../models/trace.ts";
|
|
13
|
+
import type { ExecutionTraceNode } from "../models/types.ts";
|
|
14
|
+
import type { AgentCallOpts, AgentResult } from "../models/types.ts";
|
|
15
|
+
|
|
16
|
+
// ── 测试辅助 ──
|
|
17
|
+
|
|
18
|
+
function makeMockResult(overrides: Partial<AgentResult> = {}): AgentResult {
|
|
19
|
+
return {
|
|
20
|
+
content: "OK",
|
|
21
|
+
durationMs: 100,
|
|
22
|
+
error: undefined,
|
|
23
|
+
toolCalls: [],
|
|
24
|
+
...overrides,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function makeBaseOpts(): AgentCallOpts {
|
|
29
|
+
return {
|
|
30
|
+
prompt: "test task",
|
|
31
|
+
agent: "worker",
|
|
32
|
+
cwd: "/some/path",
|
|
33
|
+
} as AgentCallOpts;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 构造一个 traceNode(ExecutionTraceNode 最小子集) */
|
|
37
|
+
function makeTraceNode(stepIndex = 0): ExecutionTraceNode {
|
|
38
|
+
return {
|
|
39
|
+
stepIndex,
|
|
40
|
+
agent: "test-agent",
|
|
41
|
+
task: "test task",
|
|
42
|
+
model: "default",
|
|
43
|
+
status: "pending",
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 构造 AgentCall + 关联的 Trace(call.id 与 trace 节点 stepIndex 对齐) */
|
|
48
|
+
function makeAgentCallAndTrace(): { call: AgentCall; trace: Trace } {
|
|
49
|
+
const trace = new Trace();
|
|
50
|
+
const traceNode = makeTraceNode(0);
|
|
51
|
+
trace.append(traceNode);
|
|
52
|
+
const call = new AgentCall(0, makeBaseOpts(), traceNode);
|
|
53
|
+
return { call, trace };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 创建 mock AgentRunner(只实现 run) */
|
|
57
|
+
function createMockRunner(impl?: ReturnType<typeof vi.fn>): AgentRunner & { run: ReturnType<typeof vi.fn> } {
|
|
58
|
+
const run = impl ?? vi.fn().mockResolvedValue(makeMockResult());
|
|
59
|
+
return { run } as unknown as AgentRunner & { run: ReturnType<typeof vi.fn> };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ── U2: executeAgentCall 透传 stream 给 runner.run ──
|
|
63
|
+
|
|
64
|
+
describe("U2: executeAgentCall 透传 stream", () => {
|
|
65
|
+
it("executeAgentCall 传 stream → runner.run 第 4 参收到同一 stream", async () => {
|
|
66
|
+
let capturedStream: unknown;
|
|
67
|
+
const runner = createMockRunner(
|
|
68
|
+
vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
|
|
69
|
+
capturedStream = stream;
|
|
70
|
+
return Promise.resolve(makeMockResult());
|
|
71
|
+
}),
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
const fakeStream = { onDelta: vi.fn(), dispose: vi.fn() };
|
|
75
|
+
const { call, trace } = makeAgentCallAndTrace();
|
|
76
|
+
const budget = new Budget();
|
|
77
|
+
|
|
78
|
+
await executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, fakeStream as never);
|
|
79
|
+
|
|
80
|
+
expect(capturedStream).toBe(fakeStream);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("executeAgentCall 不传 stream → runner.run 第 4 参为 undefined", async () => {
|
|
84
|
+
let capturedStream: unknown = "sentinel";
|
|
85
|
+
const runner = createMockRunner(
|
|
86
|
+
vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
|
|
87
|
+
capturedStream = stream;
|
|
88
|
+
return Promise.resolve(makeMockResult());
|
|
89
|
+
}),
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
const { call, trace } = makeAgentCallAndTrace();
|
|
93
|
+
const budget = new Budget();
|
|
94
|
+
|
|
95
|
+
await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
|
|
96
|
+
|
|
97
|
+
expect(capturedStream).toBeUndefined();
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// ── U1: finalizeCall 透传 sessionFile 到 trace 节点(方案 A)──
|
|
102
|
+
|
|
103
|
+
describe("U1: finalizeCall sessionFile → trace 节点", () => {
|
|
104
|
+
it("runner.run 返回带 sessionFile 的 result → trace 节点携带 sessionFile", async () => {
|
|
105
|
+
const sessionFilePath = "/abs/.pi/agent/subagents/enc/sessions/2026-07-15T_session-abc.jsonl";
|
|
106
|
+
const runner = createMockRunner(
|
|
107
|
+
vi.fn().mockResolvedValue(
|
|
108
|
+
makeMockResult({ sessionId: "session-abc", sessionFile: sessionFilePath }),
|
|
109
|
+
),
|
|
110
|
+
);
|
|
111
|
+
const { call, trace } = makeAgentCallAndTrace();
|
|
112
|
+
const budget = new Budget();
|
|
113
|
+
|
|
114
|
+
await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
|
|
115
|
+
|
|
116
|
+
const node = trace.find(0);
|
|
117
|
+
expect(node).toBeDefined();
|
|
118
|
+
expect(node!.sessionFile).toBe(sessionFilePath);
|
|
119
|
+
expect(node!.sessionId).toBe("session-abc");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("runner.run 返回无 sessionFile 的 result → trace 节点 sessionFile undefined", async () => {
|
|
123
|
+
const runner = createMockRunner(
|
|
124
|
+
vi.fn().mockResolvedValue(makeMockResult({ sessionId: "session-xyz" })),
|
|
125
|
+
);
|
|
126
|
+
const { call, trace } = makeAgentCallAndTrace();
|
|
127
|
+
const budget = new Budget();
|
|
128
|
+
|
|
129
|
+
await executeAgentCall(call, runner, budget, new AbortController().signal, trace);
|
|
130
|
+
|
|
131
|
+
const node = trace.find(0);
|
|
132
|
+
expect(node).toBeDefined();
|
|
133
|
+
expect(node!.sessionFile).toBeUndefined();
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// ── U3: retry 递归也透传 stream ──
|
|
138
|
+
|
|
139
|
+
describe("U3: executeAgentCall retry 透传 stream", () => {
|
|
140
|
+
it("首次 runner.run 返回 error → retry 时第 4 参仍是同一 stream", async () => {
|
|
141
|
+
vi.useFakeTimers();
|
|
142
|
+
|
|
143
|
+
const capturedStreams: unknown[] = [];
|
|
144
|
+
const runner = createMockRunner(
|
|
145
|
+
vi.fn().mockImplementation((_opts, _sig, _onEvt, stream) => {
|
|
146
|
+
capturedStreams.push(stream);
|
|
147
|
+
// 首次 error,第二次成功
|
|
148
|
+
if (capturedStreams.length === 1) {
|
|
149
|
+
return Promise.resolve(makeMockResult({ error: "transient error" }));
|
|
150
|
+
}
|
|
151
|
+
return Promise.resolve(makeMockResult());
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
const fakeStream = { onDelta: vi.fn(), dispose: vi.fn() };
|
|
156
|
+
const { call, trace } = makeAgentCallAndTrace();
|
|
157
|
+
const budget = new Budget();
|
|
158
|
+
|
|
159
|
+
const promise = executeAgentCall(call, runner, budget, new AbortController().signal, trace, undefined, fakeStream as never);
|
|
160
|
+
// 推进 retry 退避定时器(BACKOFF_BASE_MS = 1000,首退避 1s)
|
|
161
|
+
await vi.advanceTimersByTimeAsync(2000);
|
|
162
|
+
await promise;
|
|
163
|
+
|
|
164
|
+
expect(runner.run).toHaveBeenCalledTimes(2);
|
|
165
|
+
// 两次调用的第 4 参都是同一 stream 对象
|
|
166
|
+
expect(capturedStreams[0]).toBe(fakeStream);
|
|
167
|
+
expect(capturedStreams[1]).toBe(fakeStream);
|
|
168
|
+
|
|
169
|
+
vi.useRealTimers();
|
|
170
|
+
});
|
|
171
|
+
});
|