pi-ate-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/README.en.md +2 -0
- package/README.md +2 -0
- package/agents.ts +2 -0
- package/index.ts +97 -18
- package/intercom-bridge.ts +53 -0
- package/package.json +59 -48
- package/paths.ts +7 -0
- package/research-scan.ts +113 -65
- package/research-utils.ts +118 -107
- package/research.ts +53 -52
- package/subagent-model.ts +82 -0
- package/subagent-session.ts +132 -0
- package/subagent-spawn-once.ts +83 -81
- package/subagent-spawn-visible.ts +106 -119
- package/subagent-utils.ts +130 -3
- package/subagent.ts +49 -10
- package/term-backend.ts +33 -0
- package/term-tmux.ts +86 -0
- package/term-wezterm.ts +112 -0
- package/tests/create-visible-taskdir.test.ts +76 -0
- package/tests/intercom-bridge.test.ts +67 -0
- package/tests/output-constraints.test.ts +34 -0
- package/tests/research-analysis.test.ts +6 -6
- package/tests/research.test.ts +2 -1
- package/tests/smoke.subagent.test.ts +1 -2
- package/tests/spawn-once-extra-env.test.ts +91 -0
- package/tests/subagent-api.test.ts +81 -40
- package/tests/subagent-model.test.ts +90 -0
- package/tests/subagent-session.test.ts +83 -0
- package/tests/subagent-spawn-visible.test.ts +69 -59
- package/tests/test-helpers.ts +2 -2
- package/tests/timeout-config.test.ts +74 -0
- package/timeout-config.ts +55 -0
- package/tsconfig.json +10 -0
- package/vitest.config.ts +15 -21
- package/agent-loader.ts +0 -88
- package/tests/agent-loader.test.ts +0 -183
|
@@ -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<
|
|
11
|
-
readFileSync: vi.fn<
|
|
12
|
-
writeFileSync: vi.fn<
|
|
13
|
-
mkdirSync: vi.fn<
|
|
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.
|
|
89
|
+
expect.stringMatching(/[\\/]docs[\\/]research/),
|
|
90
90
|
);
|
|
91
91
|
expect(mockFs.mkdirSync).toHaveBeenCalledWith(
|
|
92
|
-
expect.
|
|
92
|
+
expect.stringMatching(/[\\/]docs[\\/]research/),
|
|
93
93
|
{ recursive: true },
|
|
94
94
|
);
|
|
95
95
|
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
|
package/tests/research.test.ts
CHANGED
|
@@ -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
|
-
|
|
416
|
+
// Windows: path.join produces backslashes
|
|
417
|
+
expect(dir.replace(/\\/g, "/")).toBe("/home/user/project/docs/research");
|
|
417
418
|
});
|
|
418
419
|
});
|
|
@@ -40,7 +40,6 @@ describe("smoke: barrel export", () => {
|
|
|
40
40
|
const files = [
|
|
41
41
|
"subagent.ts",
|
|
42
42
|
"subagent-utils.ts",
|
|
43
|
-
"agent-loader.ts",
|
|
44
43
|
"widget.ts",
|
|
45
44
|
"output.ts",
|
|
46
45
|
"types.ts",
|
|
@@ -60,7 +59,7 @@ describe("smoke: barrel export", () => {
|
|
|
60
59
|
|
|
61
60
|
// 验证导出语句
|
|
62
61
|
expect(content).toContain('export { runSubagent } from "./subagent"');
|
|
63
|
-
expect(content).toContain('export {
|
|
62
|
+
expect(content).toContain('export { type AgentDef, loadAgentDef } from "@pi-atelier/shared-utils"');
|
|
64
63
|
expect(content).toContain('export { createSubagentWidget } from "./widget"');
|
|
65
64
|
expect(content).toContain('export { saveSubagentOutput, readSubagentOutput } from "./output"');
|
|
66
65
|
expect(content).toContain('export type { SubagentResult, SubagentEvent } from "./types"');
|
|
@@ -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:
|
|
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
|
|
7
|
-
vi.mock("
|
|
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 {
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
+
});
|