@zhushanwen/pi-subagent-workflow 0.2.0 → 0.3.1

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.
Files changed (70) hide show
  1. package/README.md +56 -0
  2. package/agents/{scout.md → explorer.md} +1 -1
  3. package/agents/orchestrator.md +48 -0
  4. package/package.json +1 -1
  5. package/src/execution/__tests__/agent-registry.test.ts +3 -3
  6. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +484 -0
  7. package/src/execution/__tests__/channel-registry-handshake.test.ts +233 -0
  8. package/src/execution/__tests__/crash-recovery.test.ts +5 -1
  9. package/src/execution/__tests__/dialog-queue.test.ts +299 -0
  10. package/src/execution/__tests__/execute-nesting.test.ts +1 -1
  11. package/src/execution/__tests__/execute-options-mapper.test.ts +22 -3
  12. package/src/execution/__tests__/finalize-record.test.ts +173 -0
  13. package/src/execution/__tests__/gui-mode-dispatch.test.ts +2 -3
  14. package/src/execution/__tests__/helpers/spawn-mock.ts +209 -0
  15. package/src/execution/__tests__/host-mode.test.ts +87 -0
  16. package/src/execution/__tests__/index-session-start.test.ts +342 -0
  17. package/src/execution/__tests__/list-component.test.ts +1 -1
  18. package/src/execution/__tests__/notifier-flush.test.ts +78 -0
  19. package/src/execution/__tests__/path-encoding.test.ts +30 -1
  20. package/src/execution/__tests__/record-store.test.ts +86 -2
  21. package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
  22. package/src/execution/__tests__/rpc-mode.test.ts +89 -0
  23. package/src/execution/__tests__/run-spawn-edges.test.ts +157 -153
  24. package/src/execution/__tests__/run-spawn-integration.test.ts +85 -151
  25. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +193 -0
  26. package/src/execution/__tests__/session-file-gc.test.ts +46 -0
  27. package/src/execution/__tests__/session-start-reaper.test.ts +7 -1
  28. package/src/execution/__tests__/spawn-args.test.ts +14 -19
  29. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
  30. package/src/execution/__tests__/stdin-writer.test.ts +353 -0
  31. package/src/execution/__tests__/subagent-service.test.ts +73 -3
  32. package/src/execution/__tests__/tool-action.test.ts +4 -4
  33. package/src/execution/__tests__/ui-channels.test.ts +187 -0
  34. package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
  35. package/src/execution/__tests__/ui-request-handler-factory.test.ts +166 -0
  36. package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
  37. package/src/execution/__tests__/ui-request-observability.test.ts +101 -0
  38. package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
  39. package/src/execution/__tests__/worktree-manager.test.ts +1 -1
  40. package/src/execution/agent-registry.ts +1 -1
  41. package/src/execution/channel-registry-access.ts +138 -0
  42. package/src/execution/dialog-queue.ts +329 -0
  43. package/src/execution/execute-options-mapper.ts +5 -3
  44. package/src/execution/finalize-record.ts +160 -0
  45. package/src/execution/get-state-handshake.ts +104 -0
  46. package/src/execution/host-mode.ts +52 -0
  47. package/src/execution/manifest-store.ts +206 -0
  48. package/src/execution/notifier.ts +5 -1
  49. package/src/execution/path-encoding.ts +18 -0
  50. package/src/execution/pi-invocation.ts +1 -1
  51. package/src/execution/record-store.ts +108 -2
  52. package/src/execution/session-file-gc.ts +25 -3
  53. package/src/execution/session-runner.ts +216 -32
  54. package/src/execution/spawn-event-adapter.ts +219 -6
  55. package/src/execution/stdin-writer.ts +106 -0
  56. package/src/execution/subagent-service.ts +167 -197
  57. package/src/execution/types.ts +6 -6
  58. package/src/execution/ui-channels.ts +216 -0
  59. package/src/execution/ui-interaction-model.ts +48 -0
  60. package/src/execution/ui-request-handler-factory.ts +175 -0
  61. package/src/execution/ui-request-observability.ts +77 -0
  62. package/src/execution/ui-request-queue.ts +168 -0
  63. package/src/index.ts +90 -6
  64. package/src/interface/__tests__/detectors.test.ts +76 -0
  65. package/src/interface/__tests__/subagent-tool-prompt.test.ts +27 -4
  66. package/src/interface/__tests__/workflow-tool-prompt.test.ts +24 -2
  67. package/src/interface/format.ts +2 -0
  68. package/src/interface/subagent-actions.ts +21 -11
  69. package/src/interface/subagent-tool.ts +43 -10
  70. package/src/interface/tool-workflow.ts +58 -16
@@ -0,0 +1,189 @@
1
+ // src/__tests__/spawn-event-adapter-rpc.test.ts
2
+ //
3
+ // W1 红灯测试:spawn-event-adapter.ts 协议层重写 — Pi 原生格式 + method 平铺。
4
+ //
5
+ // 测试对象:extensions/subagent-workflow/src/execution/spawn-event-adapter.ts(改造)
6
+ // 契约来源:.fix-plans/00-master-summary.md §二(统一接口契约)+ §一冲突 2/判定顺序
7
+ //
8
+ // 核心改动:
9
+ // 1. isExtensionUiRequest 重写:判 type==="extension_ui_request" + id:string + method:string
10
+ // (删 jsonrpc==="2.0" 守卫 + params 守卫 — Pi 原生格式是平铺字段)
11
+ // 2. extension_ui_request 分支:从 {id, params:Record} 改为 {id, request: ExtensionUiRequest}
12
+ // request 按 method 平铺(title/options/message/... 与 Pi rpc-types.ts 1:1)
13
+ // 3. isRpcResponse 重写:判 type==="response" + command:string + success:boolean(SR-1 根因 1b)
14
+ // 4. 判定顺序:isExtensionUiRequest 必须在 event 分支之前(否则被 typeof obj.type===string 吞)
15
+ //
16
+ // 红灯原因:spawn-event-adapter.ts 当前用旧 JSON-RPC 2.0 守卫,对 Pi 原生格式样本
17
+ // 无法识别为 extension_ui_request(会落到 event 分支)。改造后这些断言才绿。
18
+
19
+ import { describe, expect, it } from "vitest";
20
+
21
+ import { parseSpawnLine } from "../spawn-event-adapter.ts";
22
+
23
+ // ── Pi 原生协议样本构造(来源:rpc-types.ts L230-265 真实类型) ──────────
24
+ // 10 种 method,全部 {type:"extension_ui_request", id, method, ...平铺字段}。
25
+ // 注意:无 jsonrpc 字段、无 params 包裹、method 在顶层(非 method:"extension_ui_request")。
26
+
27
+ function piLine(methodFields: Record<string, unknown>): string {
28
+ return JSON.stringify({ type: "extension_ui_request", id: "req-001", ...methodFields });
29
+ }
30
+
31
+ describe("parseSpawnLine — 10 种 method 真实样本分类(Pi 原生格式)", () => {
32
+ describe("dialog 类(select/confirm/input/editor)", () => {
33
+ it("select → kind=extension_ui_request + request.method=select + title/options 平铺", () => {
34
+ const result = parseSpawnLine(piLine({
35
+ method: "select", title: "Pick one", options: ["a", "b"], timeout: 30000,
36
+ }));
37
+ expect(result?.kind).toBe("extension_ui_request");
38
+ if (result?.kind !== "extension_ui_request") return;
39
+ expect(result.id).toBe("req-001");
40
+ expect(result.request.method).toBe("select");
41
+ expect(result.request.title).toBe("Pick one");
42
+ expect(result.request.options).toEqual(["a", "b"]);
43
+ });
44
+
45
+ it("confirm → request.method=confirm + title/message 平铺", () => {
46
+ const result = parseSpawnLine(piLine({
47
+ method: "confirm", title: "Sure?", message: "Proceed?", timeout: 10000,
48
+ }));
49
+ expect(result?.kind).toBe("extension_ui_request");
50
+ if (result?.kind !== "extension_ui_request") return;
51
+ expect(result.request.method).toBe("confirm");
52
+ expect(result.request.title).toBe("Sure?");
53
+ expect(result.request.message).toBe("Proceed?");
54
+ });
55
+
56
+ it("input → request.method=input + title + placeholder", () => {
57
+ const result = parseSpawnLine(piLine({
58
+ method: "input", title: "Name", placeholder: "type here",
59
+ }));
60
+ expect(result?.kind).toBe("extension_ui_request");
61
+ if (result?.kind !== "extension_ui_request") return;
62
+ expect(result.request.method).toBe("input");
63
+ expect(result.request.placeholder).toBe("type here");
64
+ });
65
+
66
+ it("editor → request.method=editor + title + prefill", () => {
67
+ const result = parseSpawnLine(piLine({
68
+ method: "editor", title: "Edit", prefill: "initial text",
69
+ }));
70
+ expect(result?.kind).toBe("extension_ui_request");
71
+ if (result?.kind !== "extension_ui_request") return;
72
+ expect(result.request.method).toBe("editor");
73
+ expect(result.request.prefill).toBe("initial text");
74
+ });
75
+ });
76
+
77
+ describe("fire-and-forget 类(notify/setStatus/setWidget/setTitle/set_editor_text)", () => {
78
+ it("notify → request.method=notify + message + notifyType", () => {
79
+ const result = parseSpawnLine(piLine({
80
+ method: "notify", message: "hi", notifyType: "info",
81
+ }));
82
+ expect(result?.kind).toBe("extension_ui_request");
83
+ if (result?.kind !== "extension_ui_request") return;
84
+ expect(result.request.method).toBe("notify");
85
+ expect(result.request.message).toBe("hi");
86
+ });
87
+
88
+ it("setStatus → request.method=setStatus + statusKey/statusText", () => {
89
+ const result = parseSpawnLine(piLine({
90
+ method: "setStatus", statusKey: "k", statusText: "running",
91
+ }));
92
+ expect(result?.kind).toBe("extension_ui_request");
93
+ if (result?.kind !== "extension_ui_request") return;
94
+ expect(result.request.method).toBe("setStatus");
95
+ expect(result.request.statusKey).toBe("k");
96
+ });
97
+
98
+ it("setWidget → request.method=setWidget + widgetKey/widgetLines/widgetPlacement", () => {
99
+ const result = parseSpawnLine(piLine({
100
+ method: "setWidget", widgetKey: "w1",
101
+ widgetLines: ["line1"], widgetPlacement: "aboveEditor",
102
+ }));
103
+ expect(result?.kind).toBe("extension_ui_request");
104
+ if (result?.kind !== "extension_ui_request") return;
105
+ expect(result.request.method).toBe("setWidget");
106
+ expect(result.request.widgetKey).toBe("w1");
107
+ expect(result.request.widgetPlacement).toBe("aboveEditor");
108
+ });
109
+
110
+ it("setTitle → request.method=setTitle + title", () => {
111
+ const result = parseSpawnLine(piLine({ method: "setTitle", title: "My Title" }));
112
+ expect(result?.kind).toBe("extension_ui_request");
113
+ if (result?.kind !== "extension_ui_request") return;
114
+ expect(result.request.method).toBe("setTitle");
115
+ expect(result.request.title).toBe("My Title");
116
+ });
117
+
118
+ it("set_editor_text → request.method=set_editor_text + text", () => {
119
+ const result = parseSpawnLine(piLine({ method: "set_editor_text", text: "body" }));
120
+ expect(result?.kind).toBe("extension_ui_request");
121
+ if (result?.kind !== "extension_ui_request") return;
122
+ expect(result.request.method).toBe("set_editor_text");
123
+ expect(result.request.text).toBe("body");
124
+ });
125
+ });
126
+ });
127
+
128
+ describe("parseSpawnLine — 旧 JSON-RPC 2.0 格式不再被识别(守卫已删)", () => {
129
+ it("jsonrpc+method:extension_ui_request+params 旧格式 → 不归类为 extension_ui_request", () => {
130
+ // 旧格式(错误假设):会被识别为 event 或 invalid,因为新守卫不认 jsonrpc
131
+ const oldFormat = JSON.stringify({
132
+ jsonrpc: "2.0", id: "x", method: "extension_ui_request", params: { foo: "bar" },
133
+ });
134
+ const result = parseSpawnLine(oldFormat);
135
+ // 旧格式的 method 字段值是 "extension_ui_request",无 type 字段 → invalid
136
+ // (这是有意的:强制对齐 Pi 原生格式)
137
+ expect(result?.kind).not.toBe("extension_ui_request");
138
+ });
139
+ });
140
+
141
+ describe("parseSpawnLine — 判定顺序:isExtensionUiRequest 先于 event 分支", () => {
142
+ it("extension_ui_request 不被 typeof obj.type===string 吞为 event", () => {
143
+ // 关键 bug:extension_ui_request 有 type 字段,若 event 分支在前会被当 event
144
+ const result = parseSpawnLine(piLine({ method: "notify", message: "x" }));
145
+ // 必须是 extension_ui_request,不能是 event
146
+ expect(result?.kind).toBe("extension_ui_request");
147
+ expect(result?.kind).not.toBe("event");
148
+ });
149
+ });
150
+
151
+ describe("parseSpawnLine — RPC response(isRpcResponse 重写,SR-1 根因 1b)", () => {
152
+ it("Pi response 格式 {type:response, command, success} → kind=response", () => {
153
+ const result = parseSpawnLine(JSON.stringify({
154
+ type: "response", id: "r1", command: "run_tool", success: true,
155
+ }));
156
+ expect(result?.kind).toBe("response");
157
+ if (result?.kind !== "response") return;
158
+ expect(result.id).toBe("r1");
159
+ expect(result.command).toBe("run_tool");
160
+ expect(result.success).toBe(true);
161
+ });
162
+
163
+ it("Pi response 失败 {type:response, command, success:false, error}", () => {
164
+ const result = parseSpawnLine(JSON.stringify({
165
+ type: "response", command: "run_tool", success: false, error: "boom",
166
+ }));
167
+ expect(result?.kind).toBe("response");
168
+ if (result?.kind !== "response") return;
169
+ expect(result.success).toBe(false);
170
+ expect(result.error).toBe("boom");
171
+ });
172
+
173
+ it("response 含 data 字段 → 保留", () => {
174
+ const result = parseSpawnLine(JSON.stringify({
175
+ type: "response", command: "read", success: true, data: { out: 42 },
176
+ }));
177
+ expect(result?.kind).toBe("response");
178
+ if (result?.kind !== "response") return;
179
+ expect(result.data).toEqual({ out: 42 });
180
+ });
181
+
182
+ it("旧 JSON-RPC 2.0 response(jsonrpc+id+result)→ 不再归类为 response", () => {
183
+ const oldRpc = JSON.stringify({
184
+ jsonrpc: "2.0", id: "x", result: { answers: [] },
185
+ });
186
+ const result = parseSpawnLine(oldRpc);
187
+ expect(result?.kind).not.toBe("response");
188
+ });
189
+ });
@@ -0,0 +1,353 @@
1
+ // src/execution/__tests__/stdin-writer.test.ts
2
+ //
3
+ // stdin-writer.ts 单元测试——覆盖 respond(UiResponse 4 分支 + 序列化降级)+
4
+ // sendPromptCommand + sendGetStateCommand + writeStdinLine 背压。
5
+ //
6
+ // stdin-writer 是 spawn 改造的叶子 helper,向 rpc 子进程 stdin 写 JSON 命令。
7
+ // 与 run-spawn-integration.test.ts 的集成视角不同:本文件只测「给定 child + 入参,
8
+ // stdin 收到的确切字节内容」,逐分支验证协议格式正确性。
9
+ //
10
+ // 测试策略:
11
+ // - 用 PassThrough 模拟 child.stdin(buffered,可事后读出 write 的字节)。
12
+ // - 用 minimal ChildProcess 形状({ stdin: PassThrough })作 respond/sendPrompt 入参。
13
+ // - respond 的 4 分支:value/confirmed/cancelled/ack。ack 不写 stdin(fire-and-forget)。
14
+ // - JSON.stringify 降级(#16):out.value 含循环引用 → 降级 cancelled + warn。
15
+ // - sendPromptCommand:写 {type:"prompt",message,id} 一行。
16
+ // - sendGetStateCommand:返回 reqId,写 {type:"get_state",id} 一行。
17
+ // - writeStdinLine 背压:mock child.stdin.write 返回 false → warn 但不 throw。
18
+
19
+ import type { ChildProcess } from "node:child_process";
20
+ import { PassThrough } from "node:stream";
21
+
22
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23
+
24
+ import { respond, sendGetStateCommand, sendPromptCommand } from "../stdin-writer.ts";
25
+
26
+ // ── helpers ──
27
+
28
+ /** 用 PassThrough 构造最小合法的 ChildProcess(只测 stdin 写入)。 */
29
+ function makeChild(overrides: Partial<Pick<ChildProcess, "stdin">> = {}): ChildProcess {
30
+ return {
31
+ stdin: new PassThrough(),
32
+ ...overrides,
33
+ } as unknown as ChildProcess;
34
+ }
35
+
36
+ /**
37
+ * 读出 child.stdin 已缓冲的全部字节(字符串)。
38
+ *
39
+ * PassThrough 默认是 flowing 模式,attach 'data' listener 后会 flush 缓冲。
40
+ * 这里用 readable 状态:pause + read 取出全部缓冲。
41
+ */
42
+ function readStdin(child: ChildProcess): string {
43
+ const stream = child.stdin as unknown as PassThrough;
44
+ stream.pause();
45
+ return stream.read()?.toString() ?? "";
46
+ }
47
+
48
+ /** 从 child.stdin 已缓冲内容按行拆分(去空行),返回 JSON.parse 后的对象数组。 */
49
+ function readStdinLines(child: ChildProcess): unknown[] {
50
+ const text = readStdin(child);
51
+ return text
52
+ .split("\n")
53
+ .map((l) => l.trim())
54
+ .filter((l) => l.length > 0)
55
+ .map((l) => JSON.parse(l));
56
+ }
57
+
58
+ let warnSpy: ReturnType<typeof vi.spyOn>;
59
+
60
+ beforeEach(() => {
61
+ // stdin-writer 在背压 / 序列化失败时 console.warn;测试 stub 避免 noise,且可断言调用。
62
+ // console.error(manifest 写失败路径)也 stub 静音,但测试不断言其调用。
63
+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
64
+ vi.spyOn(console, "error").mockImplementation(() => {});
65
+ });
66
+
67
+ afterEach(() => {
68
+ vi.restoreAllMocks();
69
+ });
70
+
71
+ // ============================================================
72
+ // respond:UiResponse 4 分支
73
+ // ============================================================
74
+
75
+ describe("respond — UiResponse 4 分支", () => {
76
+ describe("value 分支", () => {
77
+ it("out={value:'hello'} → stdin 收到 extension_ui_response 含 value 字段", () => {
78
+ const child = makeChild();
79
+ respond(child, "req-1", { value: "hello" });
80
+
81
+ const lines = readStdinLines(child);
82
+ expect(lines).toHaveLength(1);
83
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-1", value: "hello" });
84
+ });
85
+
86
+ it("value 为含 JSON 特殊字符的字符串 → 原样透传(不二次转义)", () => {
87
+ // out.value 是字符串,JSON.stringify({value: out.value}) 会正确序列化。
88
+ // 关键:out.value 本身不被 JSON.parse 二次处理——它就是字符串值。
89
+ const child = makeChild();
90
+ const payload = JSON.stringify({ q: "ans", n: 1 }); // 合法 JSON 字符串作为 value
91
+ respond(child, "req-2", { value: payload });
92
+
93
+ const lines = readStdinLines(child);
94
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-2", value: payload });
95
+ });
96
+ });
97
+
98
+ describe("confirmed 分支", () => {
99
+ it("out={confirmed:true} → stdin 收到 confirmed:true", () => {
100
+ const child = makeChild();
101
+ respond(child, "req-3", { confirmed: true });
102
+
103
+ const lines = readStdinLines(child);
104
+ expect(lines).toHaveLength(1);
105
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-3", confirmed: true });
106
+ });
107
+
108
+ it("out={confirmed:false} → stdin 收到 confirmed:false(用户拒绝 confirm)", () => {
109
+ const child = makeChild();
110
+ respond(child, "req-4", { confirmed: false });
111
+
112
+ const lines = readStdinLines(child);
113
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-4", confirmed: false });
114
+ });
115
+ });
116
+
117
+ describe("cancelled 分支", () => {
118
+ it("out={cancelled:true} → stdin 收到 cancelled:true", () => {
119
+ const child = makeChild();
120
+ respond(child, "req-5", { cancelled: true });
121
+
122
+ const lines = readStdinLines(child);
123
+ expect(lines).toHaveLength(1);
124
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-5", cancelled: true });
125
+ });
126
+ });
127
+
128
+ describe("ack 分支(fire-and-forget)", () => {
129
+ it("out={ack:true} → 不写 stdin(SR-5:fire-and-forget 不期待响应)", () => {
130
+ const child = makeChild();
131
+ respond(child, "req-6", { ack: true });
132
+
133
+ // ack 分支 line 保持 undefined → writeStdinLine 不被调 → stdin 无数据
134
+ expect(readStdin(child)).toBe("");
135
+ expect(warnSpy).not.toHaveBeenCalled();
136
+ });
137
+ });
138
+ });
139
+
140
+ // ============================================================
141
+ // respond:JSON.stringify 降级(#16)
142
+ // ============================================================
143
+
144
+ describe("respond — JSON.stringify 失败降级为 cancelled (#16)", () => {
145
+ it("out.value 含循环引用 → 降级 cancelled:true + warn,不让父进程崩溃", () => {
146
+ // 构造循环引用对象:JSON.stringify 会抛 Converting circular structure to JSON
147
+ const circular: Record<string, unknown> = { a: 1 };
148
+ circular.self = circular;
149
+
150
+ const child = makeChild();
151
+ respond(child, "req-circular", { value: circular } as never);
152
+
153
+ // 降级为 cancelled
154
+ const lines = readStdinLines(child);
155
+ expect(lines).toHaveLength(1);
156
+ expect(lines[0]).toEqual({
157
+ type: "extension_ui_response",
158
+ id: "req-circular",
159
+ cancelled: true,
160
+ });
161
+ // warn 被调用(含 request id)
162
+ expect(warnSpy).toHaveBeenCalledTimes(1);
163
+ const warnArg = warnSpy.mock.calls[0]?.[0] as string;
164
+ expect(warnArg).toContain("req-circular");
165
+ expect(warnArg).toContain("JSON.stringify failed");
166
+ });
167
+
168
+ it("out.value 含 BigInt → JSON.stringify 抛 → 降级 cancelled + warn", () => {
169
+ // BigInt 不可 JSON 序列化(JSON.stringify 抛 TypeError: Do not know how to serialize a BigInt)
170
+ const child = makeChild();
171
+ respond(child, "req-bigint", { value: BigInt(123) } as never);
172
+
173
+ const lines = readStdinLines(child);
174
+ expect(lines[0]).toEqual({
175
+ type: "extension_ui_response",
176
+ id: "req-bigint",
177
+ cancelled: true,
178
+ });
179
+ expect(warnSpy).toHaveBeenCalledTimes(1);
180
+ });
181
+
182
+ it("降级后的 cancelled 响应格式与正常 cancelled 分支一致(协议兼容)", () => {
183
+ // 确保降级走的是同一个 cancelled 格式(子进程解析逻辑无需区分「真取消」vs「序列化失败」)
184
+ const circular: Record<string, unknown> = {};
185
+ circular.self = circular;
186
+
187
+ const childFail = makeChild();
188
+ const childCancel = makeChild();
189
+ respond(childFail, "same-id", { value: circular } as never);
190
+ respond(childCancel, "same-id", { cancelled: true });
191
+
192
+ const failLine = readStdinLines(childFail)[0];
193
+ const cancelLine = readStdinLines(childCancel)[0];
194
+ expect(failLine).toEqual(cancelLine);
195
+ });
196
+ });
197
+
198
+ // ============================================================
199
+ // respond:signal.aborted 守卫
200
+ // ============================================================
201
+
202
+ describe("respond — signal 已 aborted 跳过写入", () => {
203
+ it("signal.aborted=true → 不写 stdin", () => {
204
+ const child = makeChild();
205
+ const controller = new AbortController();
206
+ controller.abort();
207
+
208
+ respond(child, "req-aborted", { value: "x" }, controller.signal);
209
+
210
+ expect(readStdin(child)).toBe("");
211
+ });
212
+
213
+ it("signal.aborted=false → 正常写入", () => {
214
+ const child = makeChild();
215
+ const controller = new AbortController();
216
+
217
+ respond(child, "req-active", { value: "x" }, controller.signal);
218
+
219
+ const lines = readStdinLines(child);
220
+ expect(lines).toHaveLength(1);
221
+ expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-active", value: "x" });
222
+ });
223
+ });
224
+
225
+ // ============================================================
226
+ // sendPromptCommand
227
+ // ============================================================
228
+
229
+ describe("sendPromptCommand", () => {
230
+ it("写入 {type:'prompt',message,id} 一行,message 含完整 task 文本", () => {
231
+ const child = makeChild();
232
+ const task = "Task: do something complex\nwith newline";
233
+ sendPromptCommand(child, task);
234
+
235
+ const lines = readStdinLines(child);
236
+ expect(lines).toHaveLength(1);
237
+ const cmd = lines[0] as { type: string; message: string; id: string };
238
+ expect(cmd.type).toBe("prompt");
239
+ expect(cmd.message).toBe(task); // 多行 task 原样透传
240
+ expect(typeof cmd.id).toBe("string");
241
+ expect(cmd.id.length).toBeGreaterThan(0); // crypto.randomUUID 生成
242
+ });
243
+
244
+ it("每次调用生成不同 id(crypto.randomUUID)", () => {
245
+ const child = makeChild();
246
+ sendPromptCommand(child, "task-1");
247
+ sendPromptCommand(child, "task-2");
248
+
249
+ const lines = readStdinLines(child);
250
+ expect(lines).toHaveLength(2);
251
+ const id1 = (lines[0] as { id: string }).id;
252
+ const id2 = (lines[1] as { id: string }).id;
253
+ expect(id1).not.toBe(id2);
254
+ });
255
+
256
+ it("写入以 \\n 结尾(rpc 子进程按行读 stdin)", () => {
257
+ const child = makeChild();
258
+ sendPromptCommand(child, "task");
259
+
260
+ // 直接查 raw 字节,验证末尾换行
261
+ const raw = readStdin(child);
262
+ expect(raw.endsWith("\n")).toBe(true);
263
+ });
264
+
265
+ it("child.stdin 已 destroyed → 静默跳过(guard 生效,不抛错)", () => {
266
+ const stdin = new PassThrough();
267
+ stdin.destroy();
268
+ const child = { stdin } as unknown as ChildProcess;
269
+
270
+ expect(() => sendPromptCommand(child, "task")).not.toThrow();
271
+ // destroyed 后 write 无效,但函数安全返回
272
+ });
273
+
274
+ it("child.stdin 为 null/undefined → 静默跳过(guard 生效)", () => {
275
+ const child = { stdin: null } as unknown as ChildProcess;
276
+ expect(() => sendPromptCommand(child, "task")).not.toThrow();
277
+ });
278
+ });
279
+
280
+ // ============================================================
281
+ // sendGetStateCommand
282
+ // ============================================================
283
+
284
+ describe("sendGetStateCommand", () => {
285
+ it("写入 {type:'get_state',id} 一行并返回相同 id(用于匹配 response)", () => {
286
+ const child = makeChild();
287
+ const returnedId = sendGetStateCommand(child);
288
+
289
+ const lines = readStdinLines(child);
290
+ expect(lines).toHaveLength(1);
291
+ const cmd = lines[0] as { type: string; id: string };
292
+ expect(cmd.type).toBe("get_state");
293
+ expect(cmd.id).toBe(returnedId); // 返回值与写入的 id 一致
294
+ expect(typeof cmd.id).toBe("string");
295
+ // get_state 命令不含其他字段(只有 type + id)
296
+ expect(Object.keys(cmd).sort()).toEqual(["id", "type"]);
297
+ });
298
+
299
+ it("写入以 \\n 结尾", () => {
300
+ const child = makeChild();
301
+ sendGetStateCommand(child);
302
+
303
+ const raw = readStdin(child);
304
+ expect(raw.endsWith("\n")).toBe(true);
305
+ });
306
+
307
+ it("每次调用返回不同 id(crypto.randomUUID)", () => {
308
+ const child = makeChild();
309
+ const id1 = sendGetStateCommand(child);
310
+ const id2 = sendGetStateCommand(child);
311
+ expect(id1).not.toBe(id2);
312
+ });
313
+ });
314
+
315
+ // ============================================================
316
+ // writeStdinLine 背压(间接经 respond 测)
317
+ // ============================================================
318
+
319
+ describe("writeStdinLine 背压 — write 返回 false 时 warn 不 throw", () => {
320
+ it("child.stdin.write 返回 false → warn 一次,函数正常返回(不 throw)", () => {
321
+ // 构造 write 永远返回 false 的假 stream(模拟内核缓冲满/HWM 到达)
322
+ const fakeStdin = {
323
+ write: vi.fn(() => false),
324
+ destroyed: false,
325
+ } as unknown as PassThrough;
326
+ const child = { stdin: fakeStdin } as unknown as ChildProcess;
327
+
328
+ expect(() => respond(child, "req-backpressure", { value: "x" })).not.toThrow();
329
+
330
+ // write 被调一次(写入 command 行)
331
+ expect(fakeStdin.write).toHaveBeenCalledTimes(1);
332
+ const writtenArg = fakeStdin.write.mock.calls[0]?.[0] as string;
333
+ expect(writtenArg).toContain("extension_ui_response");
334
+ expect(writtenArg).toContain("req-backpressure");
335
+ expect(writtenArg.endsWith("\n")).toBe(true);
336
+ // warn 被调(背压告警)
337
+ expect(warnSpy).toHaveBeenCalledTimes(1);
338
+ const warnMsg = warnSpy.mock.calls[0]?.[0] as string;
339
+ expect(warnMsg).toContain("backpressure");
340
+ });
341
+
342
+ it("child.stdin.write 返回 true → 不 warn(正常路径)", () => {
343
+ const fakeStdin = {
344
+ write: vi.fn(() => true),
345
+ destroyed: false,
346
+ } as unknown as PassThrough;
347
+ const child = { stdin: fakeStdin } as unknown as ChildProcess;
348
+
349
+ respond(child, "req-ok", { value: "x" });
350
+
351
+ expect(warnSpy).not.toHaveBeenCalled();
352
+ });
353
+ });
@@ -18,9 +18,10 @@ import * as path from "node:path";
18
18
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
19
19
 
20
20
  import { createRecord } from "../execution-record.ts";
21
+ import { ModelConfigService } from "../model-config-service.ts";
21
22
  import type { ModelInfo, ModelRegistryLike } from "../model-resolver.ts";
22
23
  import type { RecordStore } from "../record-store.ts";
23
- import { ModelConfigService } from "../model-config-service.ts";
24
+ import type { UiRequest, UiRequestHandler } from "../dialog-queue.ts";
24
25
  import type { PiLike } from "../subagent-service.ts";
25
26
  import { getSubagentService, setSubagentService,SubagentService } from "../subagent-service.ts";
26
27
  import type { ExecutionRecord } from "../types.ts";
@@ -314,6 +315,75 @@ describe("SubagentService", () => {
314
315
  });
315
316
  });
316
317
 
318
+ // ============================================================
319
+ // dispose uiRequestHandler stub(dispose-cleanup Minor 优化1)
320
+ // ============================================================
321
+ //
322
+ // [背景] Pi 单进程 session 串行接管。session A shutdown 发 SIGTERM 后、子进程彻底
323
+ // close 前(graceful shutdown 窗口几十~几百 ms),子进程的 trailing extension_ui_request
324
+ // 仍会被父进程 pump 解析,调到 A 的 handler 闭包(仍持有 A 的 ctx)。旧实现 dispose 不清
325
+ // uiRequestHandler,该闭包触发 ui-request-queue.ts catch 分支打 `[subagents] uiRequestHandler
326
+ // threw` 误导性 console.error。dispose 现注入 stub(始终返回 {cancelled:true}),让 trailing
327
+ // ui_request 干净降级,不再走旧 handler 闭包。
328
+ //
329
+ // 被测点是 SubagentService.dispose 内的 setUiRequestHandler(stub)。uiRequestHandler 是
330
+ // private 字段,用 Reflect.get 取(与 R0-D 块访问 store 同模式)。
331
+
332
+ describe("dispose uiRequestHandler stub (dispose-cleanup)", () => {
333
+ /** 从 service 取出 private uiRequestHandler(trailing ui_request 实际调用入口)。 */
334
+ function getHandler(service: SubagentService): UiRequestHandler | undefined {
335
+ return Reflect.get(service, "uiRequestHandler") as UiRequestHandler | undefined;
336
+ }
337
+
338
+ /** 最小 UiRequest(method 无关紧要——stub 不论 method 一律返回 cancelled)。 */
339
+ function makeTrailingRequest(id: string): UiRequest {
340
+ return { method: "notify", id };
341
+ }
342
+
343
+ it("dispose 后 uiRequestHandler 被 stub 替换,调用返回 {cancelled:true} 不抛错", async () => {
344
+ const service = new SubagentService({ cwd: agentDir, modelService });
345
+ service.initSession({ pi: makePi(), sessionId: "s1" });
346
+
347
+ service.dispose();
348
+
349
+ const handler = getHandler(service);
350
+ expect(handler).toBeDefined();
351
+ // 模拟 dispose 后子进程 trailing ui_request 被父进程 pump 调到 handler
352
+ await expect(handler!(makeTrailingRequest("trailing-1"))).resolves.toEqual({ cancelled: true });
353
+ });
354
+
355
+ it("dispose stub 覆盖旧 handler:trailing ui_request 不产生 [subagents] console.error 噪声", async () => {
356
+ // 模拟 session A 的真实 handler 闭包——在 ctx 已 disposed 后调用会抛错
357
+ const staleHandler: UiRequestHandler = async () => {
358
+ throw new Error("stale ctx");
359
+ };
360
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
361
+
362
+ const service = new SubagentService({ cwd: agentDir, modelService });
363
+ service.initSession({ pi: makePi(), sessionId: "s1" });
364
+ service.setUiRequestHandler(staleHandler);
365
+
366
+ service.dispose();
367
+
368
+ // dispose 后 handler 应被 stub 替换,不再是 staleHandler
369
+ const handler = getHandler(service);
370
+ expect(handler).not.toBe(staleHandler);
371
+
372
+ // trailing ui_request 调到的是 stub,不抛错、返回 cancelled
373
+ await expect(handler!(makeTrailingRequest("trailing-2"))).resolves.toEqual({ cancelled: true });
374
+
375
+ // 关键价值断言:无 "[subagents] uiRequestHandler threw" 误导性噪声
376
+ // (旧实现 dispose 不清 handler 时,trailing ui_request 走 staleHandler 抛错 →
377
+ // ui-request-queue.ts catch 打该日志。stub 覆盖后该路径不再触发。)
378
+ const subagentsErrors = errorSpy.mock.calls.filter(
379
+ (args: unknown[]) => typeof args[0] === "string" && args[0].includes("[subagents]"),
380
+ );
381
+ expect(subagentsErrors).toHaveLength(0);
382
+
383
+ errorSpy.mockRestore();
384
+ });
385
+ });
386
+
317
387
  // ============================================================
318
388
  // execute() worktree fail-fast 校验 [MF#7](commit 8e8e75966)
319
389
  // ============================================================
@@ -488,12 +558,12 @@ describe("SubagentService", () => {
488
558
  // worktree create 抛错在 kickOffBackground 之前(execute 同步 catch),返回 background 形状
489
559
  expect(handle.mode).toBe("background");
490
560
 
491
- // register emit:background mode → id 前缀 bg-
561
+ // register emit:background mode → id UUID 格式
492
562
  expect(pi.events.emit).toHaveBeenCalledWith(
493
563
  "pending:register",
494
564
  expect.objectContaining({
495
565
  type: "subagent",
496
- id: expect.stringMatching(/^bg-/),
566
+ id: expect.any(String),
497
567
  name: "general-purpose",
498
568
  }),
499
569
  );
@@ -5,8 +5,8 @@
5
5
 
6
6
  import { describe, expect, it, vi } from "vitest";
7
7
 
8
- import type { SubagentService } from "../subagent-service.ts";
9
8
  import { adapter, cancelHandler, listHandler, startHandler } from "../../interface/subagent-actions.ts";
9
+ import type { SubagentService } from "../subagent-service.ts";
10
10
  import type {
11
11
  ExecutionHandle,
12
12
  RecordSnapshot,
@@ -89,11 +89,11 @@ describe("startHandler", () => {
89
89
  await expect(startHandler(svc, { task: "ok", slug: " " }, undefined)).rejects.toThrow(/slug is required/);
90
90
  });
91
91
 
92
- it("slug 超 20 字符 → throw", async () => {
92
+ it("slug 超 35 字符 → throw", async () => {
93
93
  const svc = makeService();
94
94
  await expect(
95
- startHandler(svc, { task: "ok", slug: "a".repeat(21) }, undefined),
96
- ).rejects.toThrow(/≤20 chars/);
95
+ startHandler(svc, { task: "ok", slug: "a".repeat(36) }, undefined),
96
+ ).rejects.toThrow(/≤35 chars/);
97
97
  });
98
98
 
99
99
  it("background 启动 → kind=bg + bgResponse.message 含 detached", async () => {