@zhushanwen/pi-subagent-workflow 0.2.0 → 0.3.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.
Files changed (64) 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 +1 -1
  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 +1 -1
  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/finalize-record.ts +160 -0
  44. package/src/execution/get-state-handshake.ts +104 -0
  45. package/src/execution/host-mode.ts +52 -0
  46. package/src/execution/manifest-store.ts +206 -0
  47. package/src/execution/notifier.ts +5 -1
  48. package/src/execution/path-encoding.ts +18 -0
  49. package/src/execution/pi-invocation.ts +1 -1
  50. package/src/execution/record-store.ts +108 -2
  51. package/src/execution/session-file-gc.ts +25 -3
  52. package/src/execution/session-runner.ts +216 -32
  53. package/src/execution/spawn-event-adapter.ts +219 -6
  54. package/src/execution/stdin-writer.ts +106 -0
  55. package/src/execution/subagent-service.ts +167 -197
  56. package/src/execution/ui-channels.ts +216 -0
  57. package/src/execution/ui-interaction-model.ts +48 -0
  58. package/src/execution/ui-request-handler-factory.ts +175 -0
  59. package/src/execution/ui-request-observability.ts +77 -0
  60. package/src/execution/ui-request-queue.ts +168 -0
  61. package/src/index.ts +90 -6
  62. package/src/interface/format.ts +2 -0
  63. package/src/interface/subagent-actions.ts +9 -2
  64. package/src/interface/subagent-tool.ts +9 -8
@@ -0,0 +1,173 @@
1
+ // doFinalizeRecord — manifest status 透传测试(M3: 4 态方案)。
2
+ //
3
+ // 验证 finalize-record.ts 的 status 映射:done→completed, failed→failed, cancelled→cancelled
4
+ // (cancelled 不再归并 failed)。crashed 不进 finalize 入参(TS 签名锁定 done/failed/cancelled)。
5
+ //
6
+ // 测试策略:record 不带 sessionFile/worktreeHandle,跳过 Step 0 (collectPatch) 和 Step 3
7
+ // (finalized/tombstone/aliveMarker/worktree cleanup) 的文件操作,聚焦 Step 4 writeManifest
8
+ // 的 status 产出。FinalizeDeps 用 stub 注入(manifestStore 为真实实例,指向 tmpDir)。
9
+
10
+ import * as fs from "node:fs";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
+
15
+ import { doFinalizeRecord } from "../finalize-record.ts";
16
+ import { ManifestStore } from "../manifest-store.ts";
17
+ import type { AgentResult, ExecutionRecord } from "../types.ts";
18
+
19
+ function makeMinimalRecord(overrides: Partial<ExecutionRecord> = {}): ExecutionRecord {
20
+ return {
21
+ id: "finalize-test",
22
+ agent: "worker",
23
+ model: "test/model",
24
+ thinkingLevel: undefined,
25
+ mode: "background",
26
+ task: "test",
27
+ slug: "test",
28
+ startedAt: 1000,
29
+ rootSessionId: "session-main",
30
+ parentRecordId: undefined,
31
+ depth: 0,
32
+ status: "running",
33
+ turns: [],
34
+ turnCount: 0,
35
+ totalTokens: 0,
36
+ lastError: undefined,
37
+ endedAt: undefined,
38
+ result: undefined,
39
+ error: undefined,
40
+ agentResult: undefined,
41
+ sessionFile: undefined,
42
+ controller: undefined,
43
+ ...overrides,
44
+ } as ExecutionRecord;
45
+ }
46
+
47
+ function makeMinimalResult(): AgentResult {
48
+ return {
49
+ text: "done",
50
+ turns: 1,
51
+ durationMs: 100,
52
+ success: true,
53
+ sessionId: "sess-1",
54
+ toolCalls: [],
55
+ };
56
+ }
57
+
58
+ describe("doFinalizeRecord — manifest status 透传 (M3 4 态)", () => {
59
+ let tmpDir: string;
60
+ let manifestStore: ManifestStore;
61
+
62
+ beforeEach(() => {
63
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "finalize-test-"));
64
+ manifestStore = new ManifestStore(tmpDir);
65
+ });
66
+
67
+ afterEach(() => {
68
+ fs.rmSync(tmpDir, { recursive: true, force: true });
69
+ });
70
+
71
+ /** 构造最小 FinalizeDeps:record 无 sessionFile/worktreeHandle,跳过 Step 0/3 文件操作。 */
72
+ function makeDeps() {
73
+ return {
74
+ manifestStore,
75
+ worktreeManager: {} as never,
76
+ store: { archive: vi.fn() } as never,
77
+ modelService: {} as never,
78
+ pi: { appendEntry: vi.fn() },
79
+ clearThrottle: vi.fn(),
80
+ emitUnregister: vi.fn(),
81
+ };
82
+ }
83
+
84
+ it("status=cancelled → manifest 写 cancelled(不再归并 failed)", async () => {
85
+ const record = makeMinimalRecord({ id: "rec-cancelled" });
86
+ await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "cancelled");
87
+
88
+ const manifest = await manifestStore.readManifest("rec-cancelled");
89
+ expect(manifest).not.toBeNull();
90
+ // 关键断言:cancelled 直接透传,不是 "failed"
91
+ expect(manifest?.status).toBe("cancelled");
92
+ });
93
+
94
+ it("status=done → manifest 写 completed", async () => {
95
+ const record = makeMinimalRecord({ id: "rec-done" });
96
+ await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "done");
97
+
98
+ const manifest = await manifestStore.readManifest("rec-done");
99
+ expect(manifest?.status).toBe("completed");
100
+ });
101
+
102
+ it("status=failed → manifest 写 failed", async () => {
103
+ const record = makeMinimalRecord({ id: "rec-failed" });
104
+ await doFinalizeRecord(makeDeps(), record, makeMinimalResult(), "failed");
105
+
106
+ const manifest = await manifestStore.readManifest("rec-failed");
107
+ expect(manifest?.status).toBe("failed");
108
+ });
109
+
110
+ it("manifest write 抛错时 cleanup-first 顺序仍执行(Step 3 before Step 4 throw)", async () => {
111
+ // record 带 sessionFile 让 Step 3 finalized/aliveMarker 走真实路径;
112
+ // 不设 worktreeHandle → Step 0 (collectPatch) 和 Step 3 worktree cleanup 都跳过。
113
+ const sessionFile = path.join(tmpDir, "session.jsonl");
114
+ const record = makeMinimalRecord({ id: "rec-cleanup-first", sessionFile });
115
+
116
+ // 预写 .alive marker(让 removeAliveMarker 真实生效;不预写因 ENOENT 静默也 OK,
117
+ // 但预写后用 fs.existsSync 验证更直观)。
118
+ fs.writeFileSync(
119
+ `${sessionFile}.alive`,
120
+ `${JSON.stringify({ pid: 99999, id: "rec-cleanup-first", startedAt: 1000 })}\n`,
121
+ "utf-8",
122
+ );
123
+
124
+ // mock writeManifest 抛错(模拟 disk full)。在 mock 内捕获「writeManifest 被调用时
125
+ // finalized marker 是否已存在」——这是 cleanup-first 顺序的关键断言:若有人把
126
+ // manifest write 前移到 cleanup 之前,本标志会是 false([Critical #1] 反例)。
127
+ const finalizedBeforeManifestWrite = { value: false };
128
+ vi.spyOn(manifestStore, "writeManifest").mockImplementation(async () => {
129
+ finalizedBeforeManifestWrite.value = fs.existsSync(`${sessionFile}.finalized`);
130
+ throw new Error("disk full");
131
+ });
132
+ const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
133
+
134
+ const deps = makeDeps();
135
+
136
+ // ── 核心 claim 1:不抛错(cleanup-first → manifest write 失败不 throw)──
137
+ await expect(
138
+ doFinalizeRecord(deps, record, makeMinimalResult(), "done"),
139
+ ).resolves.toBeUndefined();
140
+
141
+ // ── 核心 claim 2:Step 3 cleanup 先执行 —— finalized marker 真实写入 ──
142
+ expect(fs.existsSync(`${sessionFile}.finalized`)).toBe(true);
143
+
144
+ // ── 核心 claim 3:Step 3 aliveMarker 被移除(预写的 .alive 不再存在)──
145
+ expect(fs.existsSync(`${sessionFile}.alive`)).toBe(false);
146
+
147
+ // ── 核心 claim 4:pending-notifications 注销仍触发(emitUnregister)──
148
+ expect(deps.emitUnregister).toHaveBeenCalledWith("rec-cleanup-first", "done");
149
+
150
+ // ── 核心 claim 5:manifest 写失败被 console.error 记录(含 record id + error)──
151
+ expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("manifest 写入失败"));
152
+ const errMsg = consoleErrorSpy.mock.calls[0]?.[0];
153
+ expect(errMsg).toContain("rec-cleanup-first");
154
+ expect(errMsg).toContain("disk full");
155
+
156
+ // ── 核心 claim 6:pi.appendEntry 记录 "subagent:manifest-write-failed" 事件 ──
157
+ expect(deps.pi.appendEntry).toHaveBeenCalledWith(
158
+ "subagent:manifest-write-failed",
159
+ expect.objectContaining({ id: "rec-cleanup-first", error: "disk full" }),
160
+ );
161
+
162
+ // ── 核心 claim 7:manifest 实际未写入(writeManifest 抛错被吞咽)──
163
+ expect(await manifestStore.readManifest("rec-cleanup-first")).toBeNull();
164
+
165
+ // ── 核心 claim 8:[Critical #1] cleanup 在 manifest 写之前 —— 顺序锁定 ──
166
+ // 若有人把 manifest write 前移到 cleanup 之前,本标志会是 false(mock 捕获时刻
167
+ // .finalized 尚未被 Step 3 写入),保护 Critical #1 时序不变量。
168
+ expect(finalizedBeforeManifestWrite.value).toBe(true);
169
+
170
+ // 清理 spy 防止污染其他测试
171
+ consoleErrorSpy.mockRestore();
172
+ });
173
+ });
@@ -8,12 +8,11 @@
8
8
  // adapter() 是纯函数,ctx.mode === "rpc" → details.__gui__ 被附加,
9
9
  // ctx.mode === "tui"/"json"/"print" → details.__gui__ 为 undefined。
10
10
 
11
- import { describe, expect, it } from "vitest";
12
-
13
11
  import type { GuiContext } from "@xyz-agent/extension-protocol";
12
+ import { describe, expect, it } from "vitest";
14
13
 
15
- import { adapter } from "../../interface/subagent-actions.ts";
16
14
  import type { AdapterInput } from "../../interface/subagent-actions.ts";
15
+ import { adapter } from "../../interface/subagent-actions.ts";
17
16
 
18
17
  function makeStartInput(): AdapterInput {
19
18
  return {
@@ -0,0 +1,209 @@
1
+ // src/execution/__tests__/helpers/spawn-mock.ts
2
+ //
3
+ // run-spawn-* 三文件(integration/edges/rpc-mode)共享的 FakeChild + 工具函数。
4
+ //
5
+ // 背景:vitest 的 vi.mock 会被提升到文件顶部,工厂函数体内**不能引用顶层 import 的变量**
6
+ //(vitest 官方文档明确警告)。例外:async 工厂内可用 `await import()`(在模块需求时执行,
7
+ // 此时所有模块已加载)。故本 helper 不导出「mock 工厂函数」(无法被 vi.mock 顶层引用),
8
+ // 而是导出 **FakeChild class + 工具函数**,让各测试文件的 vi.mock 工厂用 `await import`
9
+ // 动态取回 FakeChild。这样每个 vi.mock 工厂从 ~15 行(定义 class + vi.fn)缩到 ~4 行,
10
+ // 且 FakeChild 定义只有一个权威来源。
11
+ //
12
+ // 共享内容(原 ~80 行 × 3 重复):
13
+ // - FakeChild:EventEmitter + PassThrough stdout/stderr/stdin + kill 记录(class 定义)
14
+ // - lastSpawnedChild(mockSpawn):从 mock.results 取回最近 spawn 返回的 FakeChild
15
+ // - waitForSpawn(mockSpawn):轮询等 spawn 被调(比 vi.waitFor 在该 vitest 版本下可靠)
16
+ // - emitStdoutLine / sessionHeader:构造 stdout 行的辅助
17
+ // - makeRecord / makeOpts / makeCtx:构造最小合法的 record/opts/ctx(3 文件一致)
18
+ //
19
+ // 各测试文件 vi.mock 模式(每文件独立声明,vitest 的 vi.mock 是文件作用域):
20
+ // ```ts
21
+ // vi.mock("node:child_process", async () => {
22
+ // const { EventEmitter } = await import("node:events");
23
+ // const events = { EventEmitter }; // 兼容旧注释
24
+ // const { FakeChild } = await import("./helpers/spawn-mock.ts");
25
+ // return {
26
+ // spawn: vi.fn(() => new FakeChild()),
27
+ // execFileSync: vi.fn(() => ""),
28
+ // };
29
+ // });
30
+ // vi.mock("node:fs", async () => {
31
+ // const actual = await import("node:fs");
32
+ // return {
33
+ // default: { ...actual, mkdirSync: vi.fn(), existsSync: vi.fn(() => false),
34
+ // appendFileSync: vi.fn(), writeFileSync: vi.fn(), readdirSync: vi.fn(() => []) },
35
+ // mkdirSync: vi.fn(), existsSync: vi.fn(() => false),
36
+ // appendFileSync: vi.fn(), writeFileSync: vi.fn(), readdirSync: vi.fn(() => []),
37
+ // promises: actual.promises,
38
+ // };
39
+ // });
40
+ // vi.mock("../alive-store.ts", () => ({ writeAliveMarker: vi.fn() }));
41
+ // vi.mock("../temp-prompt.ts", () => ({
42
+ // writePromptToTempFile: vi.fn(async (agent: string) => {
43
+ // const safeName = agent.replace(/[^\w.-]+/g, "_");
44
+ // return { dir: `/tmp/fake-${safeName}`, filePath: `/tmp/fake-${safeName}/prompt-${safeName}.md` };
45
+ // }),
46
+ // cleanupTempPrompt: vi.fn(async () => {}),
47
+ // }));
48
+ // ```
49
+
50
+ import type { ChildProcess } from "node:child_process";
51
+ import { EventEmitter } from "node:events";
52
+ import { PassThrough } from "node:stream";
53
+
54
+ import { createRecord } from "../../execution-record.ts";
55
+ import type { RunOptions, SessionRunnerContext } from "../../session-runner.ts";
56
+
57
+ /**
58
+ * FakeChild:模拟 ChildProcess(EventEmitter + PassThrough streams)。
59
+ *
60
+ * 测试通过 mockSpawn.mock.results.at(-1).value 取回实例,控制 emit data/close/error 时序。
61
+ *
62
+ * 导出 class(而非只在工厂内部定义)是为了:
63
+ * 1. vi.mock 工厂内 `await import("./helpers/spawn-mock.ts")` 后 `new FakeChild()` 与
64
+ * 测试侧 `instanceof FakeChild` / 类型断言用同一个 class。
65
+ * 2. C13 e2e 测试可直接 `new FakeChild()` 手动构造 child 喂给 ui-request-queue(不经 spawn)。
66
+ */
67
+ export class FakeChild extends EventEmitter {
68
+ pid = 12345;
69
+ stdout = new PassThrough();
70
+ stderr = new PassThrough();
71
+ stdin = new PassThrough();
72
+ killed = false;
73
+ killSignal: string | undefined;
74
+ kill(sig?: string): boolean {
75
+ this.killed = true;
76
+ this.killSignal = sig;
77
+ return true;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * spawn mock 返回的 fake child 类型(结构子集)。
83
+ *
84
+ * 测试文件优先 import { FakeChild } 用真实 class 类型;此 interface 仅为兼容现有
85
+ * describe 块内 `child: FakeChild` 的类型注解风格(与原代码一致,降低 diff 噪声)。
86
+ */
87
+ export interface FakeChildLike {
88
+ pid: number;
89
+ stdout: PassThrough;
90
+ stderr: PassThrough;
91
+ stdin: PassThrough;
92
+ killed: boolean;
93
+ killSignal: string | undefined;
94
+ kill(sig?: string): boolean;
95
+ emit(event: string, ...args: unknown[]): boolean;
96
+ }
97
+
98
+ /**
99
+ * 从最近一次 spawn 调用取回返回的 FakeChild(测试控制器)。
100
+ *
101
+ * @param mockSpawn 调用方用 `vi.mocked(spawn)` 取回的 mock 引用
102
+ */
103
+ export function lastSpawnedChild<
104
+ T extends { mock: { results: Array<{ value: ChildProcess | unknown }> } },
105
+ >(mockSpawn: T): FakeChild {
106
+ const result = mockSpawn.mock.results.at(-1);
107
+ if (!result) throw new Error("spawn was not called yet");
108
+ return result.value as FakeChild;
109
+ }
110
+
111
+ /**
112
+ * 等待 runSpawn 内部调到 spawn(拿到 child 控制器)。
113
+ *
114
+ * runSpawn 是 async,spawn 在 mkdirSync + writePromptToTempFile 之后才调(均有微任务/
115
+ * I/O 延迟)。用 setTimeout 轮询 mockSpawn.mock.results,比 vi.waitFor 在该 vitest 版本
116
+ * 下更可靠(vi.waitFor 偶发过早 resolve 导致后续读取竞态)。
117
+ *
118
+ * @param mockSpawn 调用方用 `vi.mocked(spawn)` 取回的 mock 引用
119
+ */
120
+ export async function waitForSpawn<
121
+ T extends { mock: { results: unknown[] } },
122
+ >(mockSpawn: T, timeoutMs = 1000): Promise<void> {
123
+ const start = Date.now();
124
+ while (mockSpawn.mock.results.length === 0) {
125
+ if (Date.now() - start > timeoutMs) {
126
+ throw new Error(`spawn was not called within ${timeoutMs}ms`);
127
+ }
128
+ await new Promise((r) => setTimeout(r, 5));
129
+ }
130
+ }
131
+
132
+ /** 向 stdout 写一行(自动补换行,runSpawn 按 \n split 行)。 */
133
+ export function emitStdoutLine(child: FakeChild, obj: Record<string, unknown>): void {
134
+ child.stdout.write(`${JSON.stringify(obj)}\n`);
135
+ }
136
+
137
+ /** 构造 session header 行(stdout 首行)。 */
138
+ export function sessionHeader(id = "sess-abc"): Record<string, unknown> {
139
+ return {
140
+ type: "session",
141
+ id,
142
+ timestamp: "2026-07-03T12-00-00-000Z",
143
+ cwd: "/tmp/test",
144
+ };
145
+ }
146
+
147
+ /**
148
+ * 让 sessionFile 存在校验通过——runSpawn 在进程退出后用 existsSync(record.sessionFile)
149
+ * 判断是否补写 identity。默认 mock existsSync 返回 false(兜底查找),此 helper 在指定
150
+ * 路径返回 true。
151
+ */
152
+ export function mockSessionFileExists(
153
+ mockExistsSync: { mockImplementation: (fn: (p: unknown) => boolean) => void },
154
+ sessionFilePath: string,
155
+ ): void {
156
+ mockExistsSync.mockImplementation((p: unknown) => String(p) === sessionFilePath);
157
+ }
158
+
159
+ // ── record / opts / ctx 构造(3 文件一致的最小合法形状)──
160
+
161
+ /** 构造最小合法的 ExecutionRecord(runSpawn 入参)。 */
162
+ export function makeRecord() {
163
+ return createRecord("run-1", {
164
+ agent: "general-purpose",
165
+ model: "test-model",
166
+ mode: "sync",
167
+ task: "do something",
168
+ startedAt: 1_000_000,
169
+ rootSessionId: "root-session",
170
+ parentRecordId: undefined,
171
+ depth: 0,
172
+ });
173
+ }
174
+
175
+ /** 构造最小合法的 RunOptions(runSpawn 入参,可 override 关键字段)。 */
176
+ export function makeOpts(overrides: Partial<RunOptions> = {}): RunOptions {
177
+ return {
178
+ resolved: {
179
+ model: {
180
+ id: "test-model",
181
+ name: "Test Model",
182
+ provider: "test",
183
+ reasoning: false,
184
+ },
185
+ thinkingLevel: undefined,
186
+ },
187
+ agentConfig: undefined,
188
+ appendSystemPrompt: undefined,
189
+ skillPath: undefined,
190
+ schema: undefined,
191
+ maxTurns: undefined,
192
+ graceTurns: undefined,
193
+ signal: undefined,
194
+ onEvent: undefined,
195
+ ...overrides,
196
+ };
197
+ }
198
+
199
+ /** 构造最小合法的 SessionRunnerContext(runSpawn 入参,可 override 关键字段)。 */
200
+ export function makeCtx(overrides: Partial<SessionRunnerContext> = {}): SessionRunnerContext {
201
+ return {
202
+ cwd: "/tmp/test",
203
+ agentDir: "/tmp/test/agents",
204
+ skillDirs: [],
205
+ mainCwd: "/tmp/test",
206
+ mainSessionFile: undefined,
207
+ ...overrides,
208
+ };
209
+ }
@@ -0,0 +1,87 @@
1
+ // src/__tests__/host-mode.test.ts
2
+ //
3
+ // W1 红灯测试:host-mode.ts 主进程运行模式分类工具。
4
+ //
5
+ // 测试对象:extensions/subagent-workflow/src/execution/host-mode.ts(新建)
6
+ // 契约来源:.fix-plans/00-master-summary.md §一 冲突 4 + §2.5(W4 守卫消费点)
7
+ //
8
+ // 三个导出:
9
+ // - resolveHostMode(mode): ExtensionMode | undefined → "tui" | "gui" | "headless"
10
+ // - willRespondToAskUser(mode): boolean(tui/gui → true,headless → false)
11
+ // - hasInteractiveUI(mode): boolean(非 headless → true)
12
+ //
13
+ // 红灯原因:host-mode.ts 尚未创建,import 失败。
14
+
15
+ import { describe, expect, it } from "vitest";
16
+
17
+ import {
18
+ hasInteractiveUI,
19
+ resolveHostMode,
20
+ willRespondToAskUser,
21
+ } from "../host-mode.ts";
22
+
23
+ describe("resolveHostMode — ExtensionMode 聚合为 HostMode", () => {
24
+ it('"tui" → "tui"(纯 Pi TUI,ctx.ui.custom 可用)', () => {
25
+ expect(resolveHostMode("tui")).toBe("tui");
26
+ });
27
+
28
+ it('"rpc" → "gui"(xyz-agent GUI,sidecar 通道)', () => {
29
+ expect(resolveHostMode("rpc")).toBe("gui");
30
+ });
31
+
32
+ it('"json" → "headless"(无交互通道)', () => {
33
+ expect(resolveHostMode("json")).toBe("headless");
34
+ });
35
+
36
+ it('"print" → "headless"(无交互通道)', () => {
37
+ expect(resolveHostMode("print")).toBe("headless");
38
+ });
39
+
40
+ it('undefined → "headless"(向后兼容:mode 未穿透时按 headless)', () => {
41
+ expect(resolveHostMode(undefined)).toBe("headless");
42
+ });
43
+ });
44
+
45
+ describe("willRespondToAskUser — 主进程是否响应子进程 ask_user", () => {
46
+ it("tui → true(冲突 3 裁决:TUI 必须注入 handler)", () => {
47
+ expect(willRespondToAskUser("tui")).toBe(true);
48
+ });
49
+
50
+ it("rpc → true(GUI 透传所有 UI)", () => {
51
+ expect(willRespondToAskUser("rpc")).toBe(true);
52
+ });
53
+
54
+ it("json → false(headless 无 UI 通道)", () => {
55
+ expect(willRespondToAskUser("json")).toBe(false);
56
+ });
57
+
58
+ it("print → false(headless 无 UI 通道)", () => {
59
+ expect(willRespondToAskUser("print")).toBe(false);
60
+ });
61
+
62
+ it("undefined → false(向后兼容)", () => {
63
+ expect(willRespondToAskUser(undefined)).toBe(false);
64
+ });
65
+ });
66
+
67
+ describe("hasInteractiveUI — 是否有交互 UI 通道", () => {
68
+ it("tui → true", () => {
69
+ expect(hasInteractiveUI("tui")).toBe(true);
70
+ });
71
+
72
+ it("rpc → true", () => {
73
+ expect(hasInteractiveUI("rpc")).toBe(true);
74
+ });
75
+
76
+ it("json → false", () => {
77
+ expect(hasInteractiveUI("json")).toBe(false);
78
+ });
79
+
80
+ it("print → false", () => {
81
+ expect(hasInteractiveUI("print")).toBe(false);
82
+ });
83
+
84
+ it("undefined → false", () => {
85
+ expect(hasInteractiveUI(undefined)).toBe(false);
86
+ });
87
+ });