pi-ate-workflow 0.1.0 → 0.2.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.
@@ -7,10 +7,10 @@
7
7
  import { describe, it, expect, vi, beforeEach } from "vitest";
8
8
 
9
9
  const mockFs = vi.hoisted(() => ({
10
- existsSync: vi.fn<[string], boolean>(),
11
- readFileSync: vi.fn<[string, string], string>(),
12
- writeFileSync: vi.fn<[string, string, string], void>(),
13
- mkdirSync: vi.fn<[string, object], void>(),
10
+ existsSync: vi.fn<(path: string) => boolean>(),
11
+ readFileSync: vi.fn<(path: string, encoding: string) => string>(),
12
+ writeFileSync: vi.fn<(path: string, data: string, encoding: string) => void>(),
13
+ mkdirSync: vi.fn<(path: string, options: object) => void>(),
14
14
  }));
15
15
 
16
16
  vi.mock("node:fs", () => mockFs);
@@ -86,10 +86,10 @@ describe("saveAnalysis", () => {
86
86
  saveAnalysis("/test/project", state);
87
87
 
88
88
  expect(mockFs.existsSync).toHaveBeenCalledWith(
89
- expect.stringContaining("docs/research"),
89
+ expect.stringMatching(/[\\/]docs[\\/]research/),
90
90
  );
91
91
  expect(mockFs.mkdirSync).toHaveBeenCalledWith(
92
- expect.stringContaining("docs/research"),
92
+ expect.stringMatching(/[\\/]docs[\\/]research/),
93
93
  { recursive: true },
94
94
  );
95
95
  expect(mockFs.writeFileSync).toHaveBeenCalledWith(
@@ -413,6 +413,7 @@ describe("getTopicDir", () => {
413
413
  // getTopicDir 是向后兼容别名,返回 getResearchDir(cwd) = cwd/docs/research
414
414
  it("should return getResearchDir(cwd) (backward compat alias)", () => {
415
415
  const dir = getTopicDir("/home/user/project", "test-slug");
416
- expect(dir).toBe("/home/user/project/docs/research");
416
+ // Windows: path.join produces backslashes
417
+ expect(dir.replace(/\\/g, "/")).toBe("/home/user/project/docs/research");
417
418
  });
418
419
  });
@@ -1,15 +1,17 @@
1
1
  import { describe, it, expect } from "vitest";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
+ import * as api from "../index";
4
5
 
5
6
  // ============================================================
6
- // Smoke Test: barrel export + package.json 检查
7
+ // Smoke Test: 包契约检查
8
+ // 断言稳定契约(运行时导出可用、关键字段),不匹配内部源码文本,
9
+ // 避免改名/重构后断言过期长期红(2026-09-04 事故教训)。
7
10
  // ============================================================
8
11
 
9
- describe("smoke: barrel export", () => {
10
- it("所有公共 API 从 index.ts barrel export 成功", () => {
11
- // 验证 barrel export 的 API 名称列表与 plan 一致
12
- const exports = [
12
+ describe("smoke: 运行时导出", () => {
13
+ it("所有公共 API 函数可从 index.ts 导入", () => {
14
+ const functions = [
13
15
  "runSubagent",
14
16
  "loadAgentDef",
15
17
  "createSubagentWidget",
@@ -19,109 +21,33 @@ describe("smoke: barrel export", () => {
19
21
  "createUIUpdater",
20
22
  "registerWorkflowTool",
21
23
  ];
22
- const expectedTypeExports = [
23
- "AgentDef",
24
- "SubagentResult",
25
- "SubagentEvent",
26
- "ActionDef",
27
- ];
28
-
29
- // 验证函数名列表完整
30
- expect(exports).toHaveLength(8);
31
- expect(expectedTypeExports).toHaveLength(4);
32
-
33
- // 全部函数名存在且无重复
34
- const allNames = [...exports, ...expectedTypeExports];
35
- const uniqueNames = new Set(allNames);
36
- expect(uniqueNames.size).toBe(allNames.length);
37
-
38
- // 验证 index.ts 中每个函数都有对应的子模块文件
39
- const workflowDir = path.resolve(__dirname, "..");
40
- const files = [
41
- "subagent.ts",
42
- "subagent-utils.ts",
43
- "agent-loader.ts",
44
- "widget.ts",
45
- "output.ts",
46
- "types.ts",
47
- "state.ts",
48
- "workflow.ts",
49
- "index.ts",
50
- ];
51
- for (const file of files) {
52
- const filePath = path.join(workflowDir, file);
53
- expect(fs.existsSync(filePath)).toBe(true);
24
+ for (const name of functions) {
25
+ expect(api, `缺少导出: ${name}`).toHaveProperty(name);
26
+ expect((api as Record<string, unknown>)[name], `${name} 应为函数`).toBeTypeOf("function");
54
27
  }
55
28
  });
29
+ });
56
30
 
57
- it("index.ts 包含所有 barrel export 语句", () => {
58
- const indexPath = path.resolve(__dirname, "..", "index.ts");
59
- const content = fs.readFileSync(indexPath, "utf-8");
60
-
61
- // 验证导出语句
62
- expect(content).toContain('export { runSubagent } from "./subagent"');
63
- expect(content).toContain('export { loadAgentDef, type AgentDef } from "./agent-loader"');
64
- expect(content).toContain('export { createSubagentWidget } from "./widget"');
65
- expect(content).toContain('export { saveSubagentOutput, readSubagentOutput } from "./output"');
66
- expect(content).toContain('export type { SubagentResult, SubagentEvent } from "./types"');
67
- expect(content).toContain('export { createStateManager, createUIUpdater } from "./state"');
68
- expect(content).toContain('export { registerWorkflowTool, type ActionDef } from "./workflow"');
69
- });
70
-
71
- it("package.json 字段完整", () => {
72
- const pkgPath = path.resolve(__dirname, "..", "package.json");
73
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
31
+ describe("smoke: package.json 稳定字段", () => {
32
+ const pkgPath = path.resolve(__dirname, "..", "package.json");
33
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
74
34
 
75
- expect(pkg.name).toBe("workflow");
76
- expect(pkg.version).toBe("1.0.0");
77
- expect(pkg.type).toBe("commonjs");
35
+ it("包名与入口符合发布契约", () => {
36
+ expect(pkg.name).toBe("pi-ate-workflow");
78
37
  expect(pkg.main).toBe("index.ts");
79
-
80
- // dependencies 为空
81
- expect(pkg.dependencies).toEqual({});
82
-
83
- // peerDependencies 包含 pi-core 依赖
84
- expect(pkg.peerDependencies?.["@earendil-works/pi-coding-agent"]).toBe("*");
85
- expect(pkg.peerDependencies?.["@earendil-works/pi-tui"]).toBe("*");
86
- expect(pkg.peerDependencies?.["typebox"]).toBe("*");
87
-
88
- // devDependencies
89
- expect(pkg.devDependencies?.["vitest"]).toBeDefined();
90
- expect(pkg.devDependencies?.["@types/node"]).toBeDefined();
91
- });
92
-
93
- it("vitest.config.ts 存在且格式正确", () => {
94
- const configPath = path.resolve(__dirname, "..", "vitest.config.ts");
95
- const content = fs.readFileSync(configPath, "utf-8");
96
-
97
- expect(content).toContain("defineConfig");
98
- expect(content).toContain("tests/**/*.test.ts");
38
+ expect(pkg.type).toBe("commonjs");
99
39
  });
100
40
 
101
- it("所有 .ts 文件行数不超过 200 行", () => {
102
- const workflowDir = path.resolve(__dirname, "..");
103
- const tsFiles = fs.readdirSync(workflowDir).filter(f => f.endsWith(".ts") && f !== "vitest.config.ts");
104
-
105
- for (const file of tsFiles) {
106
- const lines = fs.readFileSync(path.join(workflowDir, file), "utf-8").split("\n").length;
107
- expect(
108
- lines,
109
- `${file} 行数 ${lines} 超过 200 行`,
110
- ).toBeLessThanOrEqual(200);
111
- }
41
+ it("peerDependencies 含 pi SDK", () => {
42
+ expect(pkg.peerDependencies?.["@earendil-works/pi-coding-agent"]).toBeDefined();
112
43
  });
44
+ });
113
45
 
114
- it("types.ts 只导出 SubagentResult + SubagentEvent,不含 PV 专用类型", () => {
46
+ describe("smoke: types.ts 不含 PV 专用类型", () => {
47
+ it("types.ts 保持通用", () => {
115
48
  const typesPath = path.resolve(__dirname, "..", "types.ts");
116
49
  const content = fs.readFileSync(typesPath, "utf-8");
117
50
 
118
- // types.ts 不应包含 PV 专用类型
119
51
  expect(content).not.toContain("PlanVerifyState");
120
- expect(content).not.toContain("Phase");
121
- expect(content).not.toContain("Issue");
122
-
123
- // 应包含通用类型
124
- expect(content).toContain("SubagentResult");
125
- expect(content).toContain("SubagentEvent");
126
52
  });
127
53
  });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 测试 spawnOnce — extraEnv 参数透传
3
+ */
4
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
5
+
6
+ vi.mock("../subagent-utils", () => ({
7
+ getPiCommand: vi.fn(() => ({ command: "node", args: ["/usr/local/bin/pi"] })),
8
+ }));
9
+
10
+ import { EventEmitter } from "node:events";
11
+
12
+ let mockProc: any;
13
+ const spawnCalls: any[][] = [];
14
+
15
+ vi.mock("node:child_process", async (importOriginal) => {
16
+ const actual = await importOriginal() as any;
17
+ return {
18
+ ...actual,
19
+ spawn: (...args: any[]) => {
20
+ spawnCalls.push(args);
21
+ return mockProc;
22
+ },
23
+ };
24
+ });
25
+
26
+ import { spawnOnce } from "../subagent-spawn-once";
27
+
28
+ function createMockProcess() {
29
+ const proc = new EventEmitter() as any;
30
+ proc.stdout = new EventEmitter();
31
+ proc.stderr = new EventEmitter();
32
+ proc.kill = vi.fn();
33
+ proc.killed = false;
34
+ return proc;
35
+ }
36
+
37
+ describe("spawnOnce — extraEnv 透传", () => {
38
+ beforeEach(() => {
39
+ vi.useFakeTimers();
40
+ mockProc = createMockProcess();
41
+ spawnCalls.length = 0;
42
+ });
43
+
44
+ afterEach(() => {
45
+ vi.useRealTimers();
46
+ });
47
+
48
+ it("不传 extraEnv 时 spawn env 为 process.env", async () => {
49
+ const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] });
50
+ mockProc.emit("close", 0);
51
+ await resultPromise;
52
+
53
+ const spawnOpts = spawnCalls[0][2];
54
+ expect(spawnOpts.env).toBe(process.env);
55
+ });
56
+
57
+ it("传 extraEnv 时合并到 spawn env", async () => {
58
+ const extraEnv = {
59
+ PI_SUBAGENT_ORCHESTRATOR_TARGET: "my-session",
60
+ PI_SUBAGENT_RUN_ID: "run-abc123",
61
+ PI_SUBAGENT_CHILD_AGENT: "pv-executor",
62
+ PI_SUBAGENT_CHILD_INDEX: "1",
63
+ };
64
+ const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, extraEnv);
65
+ mockProc.emit("close", 0);
66
+ await resultPromise;
67
+
68
+ const spawnOpts = spawnCalls[0][2];
69
+ expect(spawnOpts.env).toEqual(expect.objectContaining(extraEnv));
70
+ expect(spawnOpts.env).toEqual(expect.objectContaining(process.env));
71
+ });
72
+
73
+ it("extraEnv 的值覆盖 process.env 中同名 key", async () => {
74
+ const extraEnv = { PATH: "/custom/path" };
75
+ const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, extraEnv);
76
+ mockProc.emit("close", 0);
77
+ await resultPromise;
78
+
79
+ const spawnOpts = spawnCalls[0][2];
80
+ expect(spawnOpts.env.PATH).toBe("/custom/path");
81
+ });
82
+
83
+ it("extraEnv 为空对象时仍包含 process.env", async () => {
84
+ const resultPromise = spawnOnce("task", "/cwd", "/tmp/prompt.md", { tools: ["read"] }, undefined, undefined, undefined, undefined, undefined, {});
85
+ mockProc.emit("close", 0);
86
+ await resultPromise;
87
+
88
+ const spawnOpts = spawnCalls[0][2];
89
+ expect(spawnOpts.env).toEqual(expect.objectContaining(process.env));
90
+ });
91
+ });
@@ -1,11 +1,27 @@
1
1
  /**
2
- * 测试 subagent.ts:validateOutputConstraints + runSubagent
2
+ * 测试 subagent.ts:runSubagent(spawn 路径选择 / 超时解析 / 桥接注入 / 约束重试)
3
+ * validateOutputConstraints 的测试在 output-constraints.test.ts
3
4
  */
4
5
  import { describe, it, expect, vi, beforeEach } from "vitest";
5
6
 
6
- // mock agent-loader
7
- vi.mock("../agent-loader", () => ({
7
+ // mock shared-utils (loadAgentDef 已收敛到 shared-utils)
8
+ vi.mock("@pi-atelier/shared-utils", () => ({
8
9
  loadAgentDef: vi.fn(),
10
+ getEffectiveConfig: vi.fn(() => ({ config: {}, sources: {} })),
11
+ }));
12
+
13
+ // mock 超时解析(runSubagent 内部调用)
14
+ vi.mock("../timeout-config", () => ({
15
+ resolveSubagentTimeout: vi.fn(() => 30 * 60 * 1000),
16
+ DEFAULT_SUBAGENT_TIMEOUT_MS: 30 * 60 * 1000,
17
+ SUBAGENT_TIMEOUT_DEFAULTS: { timeoutMs: 1800000, agentTimeouts: {} },
18
+ }));
19
+
20
+ // mock 桥接(runSubagent 内部调用)
21
+ vi.mock("../intercom-bridge", () => ({
22
+ buildIntercomBridge: vi.fn(() => ({ PI_SUBAGENT_RUN_ID: "run-test" })),
23
+ resolveOrchestratorName: vi.fn(async () => undefined),
24
+ setOrchestratorNameResolver: vi.fn(),
9
25
  }));
10
26
 
11
27
  // mock subagent-utils
@@ -23,50 +39,22 @@ vi.mock("../subagent-spawn-visible", () => ({
23
39
  spawnVisible: vi.fn(),
24
40
  }));
25
41
 
26
- import { validateOutputConstraints } from "../subagent";
27
- import { loadAgentDef } from "../agent-loader";
42
+ import { loadAgentDef } from "@pi-atelier/shared-utils";
28
43
  import { spawnOnce } from "../subagent-spawn-once";
29
44
  import { spawnVisible } from "../subagent-spawn-visible";
30
-
31
- describe("validateOutputConstraints", () => {
32
- it("无约束时返回空列表", () => {
33
- expect(validateOutputConstraints("hello", [])).toEqual([]);
34
- });
35
-
36
- it("全部通过返回空列表", () => {
37
- const constraints = [
38
- { rule: "必须是 JSON", validate: (s: string) => (s.startsWith("{") ? null : "not json") },
39
- ];
40
- expect(validateOutputConstraints('{"ok":true}', constraints)).toEqual([]);
41
- });
42
-
43
- it("有不通过的返回错误列表", () => {
44
- const constraints = [
45
- { rule: "必须是 JSON", validate: (s: string) => (s.startsWith("{") ? null : "not json") },
46
- { rule: "包含 ok", validate: (s: string) => (s.includes("ok") ? null : "missing ok") },
47
- ];
48
- expect(validateOutputConstraints("plain text", constraints)).toEqual(["not json", "missing ok"]);
49
- });
50
-
51
- it("部分通过只返回不通过的", () => {
52
- const constraints = [
53
- { rule: "包含 ok", validate: (s: string) => (s.includes("ok") ? null : "missing ok") },
54
- { rule: "包含 err", validate: (s: string) => (s.includes("err") ? null : "missing err") },
55
- ];
56
- expect(validateOutputConstraints("has ok but not e", constraints)).toEqual(["missing err"]);
57
- });
58
- });
45
+ import { resolveSubagentTimeout } from "../timeout-config";
46
+ import { runSubagent } from "../subagent";
59
47
 
60
48
  describe("runSubagent", () => {
61
49
  beforeEach(() => {
62
50
  vi.clearAllMocks();
63
- // 默认模拟 TMUX 不存在,走 spawnOnce
51
+ // 默认模拟无分屏终端,走 spawnOnce
64
52
  delete process.env.TMUX;
53
+ delete process.env.WEZTERM_PANE;
65
54
  });
66
55
 
67
56
  it("agentDef 未找到时抛错", async () => {
68
57
  (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue(null);
69
- const { runSubagent } = await import("../subagent");
70
58
  await expect(runSubagent("nonexistent", "task", "/cwd")).rejects.toThrow("未找到");
71
59
  });
72
60
 
@@ -82,10 +70,48 @@ describe("runSubagent", () => {
82
70
  stderr: "",
83
71
  });
84
72
 
85
- const { runSubagent } = await import("../subagent");
86
73
  const result = await runSubagent("test-agent", "do something", "/cwd", undefined, undefined, undefined, undefined, undefined, false);
87
74
  expect(result.output).toBe("done");
88
75
  expect(result.exitCode).toBe(0);
76
+ // 后台模式默认注入桥接环境变量
77
+ const spawnArgs = (spawnOnce as ReturnType<typeof vi.fn>).mock.calls[0];
78
+ expect(spawnArgs[9]).toEqual(expect.objectContaining({ PI_SUBAGENT_RUN_ID: "run-test" }));
79
+ });
80
+
81
+ it("extraEnv 与桥接变量合并,extraEnv 优先", async () => {
82
+ (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue({
83
+ name: "test-agent",
84
+ tools: ["read"],
85
+ systemPrompt: "You are a test agent",
86
+ });
87
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
88
+ exitCode: 0,
89
+ output: "done",
90
+ stderr: "",
91
+ });
92
+
93
+ await runSubagent("test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, undefined, false, { PI_SUBAGENT_RUN_ID: "run-custom" });
94
+ const spawnArgs = (spawnOnce as ReturnType<typeof vi.fn>).mock.calls[0];
95
+ expect(spawnArgs[9]).toEqual({ PI_SUBAGENT_RUN_ID: "run-custom" });
96
+ });
97
+
98
+ it("超时未显式传参时经配置链解析后传给 spawn", async () => {
99
+ (resolveSubagentTimeout as ReturnType<typeof vi.fn>).mockReturnValue(123456);
100
+ (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue({
101
+ name: "test-agent",
102
+ tools: ["read"],
103
+ systemPrompt: "You are a test agent",
104
+ });
105
+ (spawnOnce as ReturnType<typeof vi.fn>).mockResolvedValue({
106
+ exitCode: 0,
107
+ output: "done",
108
+ stderr: "",
109
+ });
110
+
111
+ await runSubagent("test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, undefined, false);
112
+ expect(resolveSubagentTimeout).toHaveBeenCalledWith("test-agent", "/cwd", undefined);
113
+ const spawnArgs = (spawnOnce as ReturnType<typeof vi.fn>).mock.calls.at(-1)!;
114
+ expect(spawnArgs[6]).toBe(123456);
89
115
  });
90
116
 
91
117
  it("有 TMUX 时走 spawnVisible", async () => {
@@ -101,13 +127,30 @@ describe("runSubagent", () => {
101
127
  stderr: "",
102
128
  });
103
129
 
104
- const { runSubagent } = await import("../subagent");
105
130
  const result = await runSubagent("test-agent", "do something", "/cwd");
106
131
  expect(spawnVisible).toHaveBeenCalled();
107
132
  expect(result.output).toBe("visible done");
108
133
  delete process.env.TMUX;
109
134
  });
110
135
 
136
+ it("有 WEZTERM_PANE 时也走 spawnVisible", async () => {
137
+ process.env.WEZTERM_PANE = "7";
138
+ (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue({
139
+ name: "test-agent",
140
+ tools: ["read"],
141
+ systemPrompt: "You are a test agent",
142
+ });
143
+ (spawnVisible as ReturnType<typeof vi.fn>).mockResolvedValue({
144
+ exitCode: 0,
145
+ output: "wez done",
146
+ stderr: "",
147
+ });
148
+
149
+ await runSubagent("test-agent", "do something", "/cwd");
150
+ expect(spawnVisible).toHaveBeenCalled();
151
+ delete process.env.WEZTERM_PANE;
152
+ });
153
+
111
154
  it("约束不通过时重试", async () => {
112
155
  (loadAgentDef as ReturnType<typeof vi.fn>).mockReturnValue({
113
156
  name: "test-agent",
@@ -125,7 +168,6 @@ describe("runSubagent", () => {
125
168
  validate: (s: string) => s.includes("GOOD") ? null : "缺少 GOOD",
126
169
  }];
127
170
 
128
- const { runSubagent } = await import("../subagent");
129
171
  const result = await runSubagent("test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, constraints, false);
130
172
  expect(spawnOnce).toHaveBeenCalledTimes(2);
131
173
  expect(result.output).toBe("GOOD format");
@@ -150,7 +192,6 @@ describe("runSubagent", () => {
150
192
  validate: (s: string) => s.includes("GOOD") ? null : "缺少 GOOD",
151
193
  }];
152
194
 
153
- const { runSubagent } = await import("../subagent");
154
195
  const result = await runSubagent("test-agent", "task", "/cwd", undefined, undefined, undefined, undefined, constraints, false);
155
196
  expect(spawnOnce).toHaveBeenCalledTimes(3); // initial + 2 retries
156
197
  expect(result.output).toBe("always bad");
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 测试 subagent-model.ts — 模型持久化(安全读写路径)
3
+ *
4
+ * 读:getEffectiveConfig 三层合并;写:patchSettingsSectionWithBackup
5
+ * 禁止裸 readFileSync/writeFileSync 整文件读写。
6
+ */
7
+ import { describe, it, expect, vi, beforeEach } from "vitest";
8
+
9
+ const { patchMock } = vi.hoisted(() => ({
10
+ patchMock: vi.fn(),
11
+ }));
12
+
13
+ vi.mock("@pi-atelier/shared-utils", () => ({
14
+ getEffectiveConfig: vi.fn(),
15
+ getSettingsValue: vi.fn(),
16
+ patchSettingsSectionWithBackup: patchMock,
17
+ }));
18
+
19
+ import {
20
+ getSubagentModel,
21
+ setSubagentModel,
22
+ restoreSubagentModel,
23
+ isSubagentModelRestored,
24
+ setSubagentModelRestored,
25
+ } from "../subagent-model";
26
+ import { getEffectiveConfig, getSettingsValue } from "@pi-atelier/shared-utils";
27
+
28
+ describe("subagent-model 持久化", () => {
29
+ beforeEach(() => {
30
+ vi.clearAllMocks();
31
+ setSubagentModelRestored(false);
32
+ });
33
+
34
+ it("restore 从 subagent.defaultModel 读取(getEffectiveConfig)", () => {
35
+ (getEffectiveConfig as ReturnType<typeof vi.fn>).mockReturnValue({
36
+ config: { defaultModel: "zai/glm-5.2" },
37
+ sources: {},
38
+ });
39
+ restoreSubagentModel("/proj");
40
+ expect(getEffectiveConfig).toHaveBeenCalledWith(
41
+ "subagent", expect.any(Object), "/proj",
42
+ );
43
+ expect(getSubagentModel()).toBe("zai/glm-5.2");
44
+ expect(isSubagentModelRestored()).toBe(true);
45
+ });
46
+
47
+ it("未配置时回退 defaultProvider/defaultModel 组合", () => {
48
+ (getEffectiveConfig as ReturnType<typeof vi.fn>).mockReturnValue({
49
+ config: { defaultModel: "" },
50
+ sources: {},
51
+ });
52
+ (getSettingsValue as ReturnType<typeof vi.fn>)
53
+ .mockReturnValueOnce("zai")
54
+ .mockReturnValueOnce("glm-4.6");
55
+ restoreSubagentModel();
56
+ expect(getSubagentModel()).toBe("zai/glm-4.6");
57
+ });
58
+
59
+ it("set 写入走 patchSettingsSectionWithBackup(带锁)", () => {
60
+ (getEffectiveConfig as ReturnType<typeof vi.fn>).mockReturnValue({
61
+ config: { defaultModel: "" },
62
+ sources: {},
63
+ });
64
+ setSubagentModel("deepseek/deepseek-v4-flash");
65
+ expect(patchMock).toHaveBeenCalledWith(
66
+ "subagent",
67
+ { defaultModel: "deepseek/deepseek-v4-flash" },
68
+ expect.any(Object),
69
+ );
70
+ expect(getSubagentModel()).toBe("deepseek/deepseek-v4-flash");
71
+ });
72
+
73
+ it("读取异常时安全降级为空串", () => {
74
+ (getEffectiveConfig as ReturnType<typeof vi.fn>).mockImplementation(() => {
75
+ throw new Error("settings broken");
76
+ });
77
+ restoreSubagentModel();
78
+ expect(getSubagentModel()).toBe("");
79
+ });
80
+
81
+ it("写入异常不阻塞主流程", () => {
82
+ patchMock.mockImplementation(() => { throw new Error("lock fail"); });
83
+ (getEffectiveConfig as ReturnType<typeof vi.fn>).mockReturnValue({
84
+ config: { defaultModel: "" },
85
+ sources: {},
86
+ });
87
+ expect(() => setSubagentModel("x/y")).not.toThrow();
88
+ expect(getSubagentModel()).toBe("x/y");
89
+ });
90
+ });
@@ -0,0 +1,83 @@
1
+ /**
2
+ * 测试 SubagentSession — 输出收集 / 事件解析 / 退出控制
3
+ */
4
+ import { describe, it, expect } from "vitest";
5
+ import { SubagentSession } from "../subagent-session";
6
+
7
+ describe("SubagentSession", () => {
8
+ it("collectTexts 收集 assistant 文本,忽略其他角色", () => {
9
+ const s = new SubagentSession();
10
+ s.collectTexts({ role: "user", content: [{ type: "text", text: "hi" }] });
11
+ s.collectTexts({ role: "assistant", content: [{ type: "text", text: "answer" }] });
12
+ s.collectTexts({ role: "assistant", content: [{ type: "toolCall", id: "t1" }] });
13
+ expect(s.formatOutput("fallback")).toBe("answer");
14
+ });
15
+
16
+ it("formatOutput 去重重复文本块", () => {
17
+ const s = new SubagentSession();
18
+ s.collectTexts({ role: "assistant", content: [{ type: "text", text: "same" }] });
19
+ s.collectTexts({ role: "assistant", content: [{ type: "text", text: "same" }] });
20
+ expect(s.formatOutput("fallback")).toBe("same");
21
+ });
22
+
23
+ it("无收集文本时返回 fallback", () => {
24
+ const s = new SubagentSession();
25
+ expect(s.formatOutput("(no output)")).toBe("(no output)");
26
+ });
27
+
28
+ it("parseStreamEvent 捕获 session id(仅首次)", () => {
29
+ const s = new SubagentSession();
30
+ s.parseStreamEvent({ type: "session", version: 1, id: "sess-1" });
31
+ s.parseStreamEvent({ type: "session", version: 1, id: "sess-2" });
32
+ expect(s.capturedSessionId).toBe("sess-1");
33
+ });
34
+
35
+ it("parseStreamEvent 转发 tool / thinking 事件", () => {
36
+ const events: any[] = [];
37
+ const s = new SubagentSession({ onEvent: (e) => events.push(e) });
38
+ s.parseStreamEvent({ type: "tool_execution_start", toolName: "read", args: {} });
39
+ s.parseStreamEvent({ type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "hi" } });
40
+ expect(events).toEqual([
41
+ { type: "tool", toolName: "read", toolArgs: {} },
42
+ { type: "thinking", text: "hi" },
43
+ ]);
44
+ });
45
+
46
+ it("parseStreamEvent message_end / agent_end 收集文本", () => {
47
+ const s = new SubagentSession();
48
+ s.parseStreamEvent({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "a" }] } });
49
+ s.parseStreamEvent({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "b" }] }] });
50
+ expect(s.formatOutput("")).toBe("a\n\n---\n\nb");
51
+ });
52
+
53
+ it("parseSessionLine 解析 message / tool / agent_end", () => {
54
+ const events: any[] = [];
55
+ const s = new SubagentSession({ onEvent: (e) => events.push(e) });
56
+ s.parseSessionLine({ type: "session", id: "s1" });
57
+ s.parseSessionLine({ type: "message", message: { role: "assistant", content: [{ type: "text", text: "txt" }] } });
58
+ s.parseSessionLine({ type: "tool_execution_start", toolName: "bash", args: {} });
59
+ s.parseSessionLine({ type: "agent_end", messages: [] });
60
+ expect(s.capturedSessionId).toBe("s1");
61
+ expect(s.formatOutput("")).toBe("txt");
62
+ expect(events).toEqual([{ type: "tool", toolName: "bash", toolArgs: {} }]);
63
+ });
64
+
65
+ it("resolveOnce 只生效一次,并自动附加 capturedSessionId", async () => {
66
+ const s = new SubagentSession();
67
+ s.parseStreamEvent({ type: "session", version: 1, id: "sess-9" });
68
+ s.resolveOnce({ exitCode: 0, output: "x", stderr: "" });
69
+ s.resolveOnce({ exitCode: 1, output: "y", stderr: "" });
70
+ const result = await s.result;
71
+ expect(result.output).toBe("x");
72
+ expect(result.subSessionId).toBe("sess-9");
73
+ expect(s.isDone).toBe(true);
74
+ });
75
+
76
+ it("beforeResolve 在 resolve 前被调用(如注入 parentSession)", async () => {
77
+ const calls: string[] = [];
78
+ const s = new SubagentSession({ beforeResolve: () => calls.push("before") });
79
+ s.resolveOnce({ exitCode: 0, output: "x", stderr: "" });
80
+ await s.result;
81
+ expect(calls).toEqual(["before"]);
82
+ });
83
+ });