pi-ate-workflow 0.1.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 (46) hide show
  1. package/README.en.md +102 -0
  2. package/README.md +104 -0
  3. package/agent-loader.ts +88 -0
  4. package/index.ts +18 -0
  5. package/output.ts +89 -0
  6. package/package.json +50 -0
  7. package/research-analysis.ts +64 -0
  8. package/research-catalog.ts +33 -0
  9. package/research-scan.ts +65 -0
  10. package/research-state.ts +46 -0
  11. package/research-types.ts +53 -0
  12. package/research-utils.ts +107 -0
  13. package/research.ts +52 -0
  14. package/state.ts +121 -0
  15. package/subagent-spawn-once.ts +164 -0
  16. package/subagent-spawn-visible.ts +194 -0
  17. package/subagent-utils.ts +38 -0
  18. package/subagent.ts +93 -0
  19. package/tests/agent-loader.test.ts +183 -0
  20. package/tests/agent-schema-extra.test.ts +107 -0
  21. package/tests/agent-schema.test.ts +116 -0
  22. package/tests/output.test.ts +107 -0
  23. package/tests/research-analysis.test.ts +155 -0
  24. package/tests/research-extra.test.ts +175 -0
  25. package/tests/research.test.ts +418 -0
  26. package/tests/smoke.subagent.test.ts +127 -0
  27. package/tests/state-manager.test.ts +245 -0
  28. package/tests/state.test.ts +298 -0
  29. package/tests/subagent-api.test.ts +158 -0
  30. package/tests/subagent-spawn-once.test.ts +154 -0
  31. package/tests/subagent-spawn-visible.test.ts +139 -0
  32. package/tests/subagent-utils.test.ts +124 -0
  33. package/tests/test-helpers.ts +40 -0
  34. package/tests/ui-updater.test.ts +129 -0
  35. package/tests/utils-find-session.test.ts +114 -0
  36. package/tests/utils-status-summary.test.ts +158 -0
  37. package/tests/utils.test.ts +48 -0
  38. package/tests/widget.test.ts +114 -0
  39. package/tests/workflow-execution.test.ts +165 -0
  40. package/tests/workflow-registration.test.ts +155 -0
  41. package/tests/workflow.test.ts +207 -0
  42. package/types.ts +24 -0
  43. package/utils.ts +74 -0
  44. package/vitest.config.ts +21 -0
  45. package/widget.ts +104 -0
  46. package/workflow.ts +113 -0
@@ -0,0 +1,114 @@
1
+ /**
2
+ * utils.ts 测试 — findSessionFile
3
+ *
4
+ * 依赖 node:os / node:fs,需要 mock。
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from "vitest";
8
+ import * as path from "node:path";
9
+
10
+ const mockHomedir = vi.hoisted(() => vi.fn());
11
+ const mockExistsSync = vi.hoisted(() => vi.fn());
12
+ const mockReaddirSync = vi.hoisted(() => vi.fn());
13
+ const mockStatSync = vi.hoisted(() => vi.fn());
14
+
15
+ vi.mock("node:os", () => ({ homedir: mockHomedir }));
16
+ vi.mock("node:fs", () => ({
17
+ existsSync: mockExistsSync,
18
+ readdirSync: mockReaddirSync,
19
+ statSync: mockStatSync,
20
+ }));
21
+
22
+ import { findSessionFile } from "../utils";
23
+
24
+ describe("findSessionFile", () => {
25
+ beforeEach(() => {
26
+ vi.clearAllMocks();
27
+ });
28
+
29
+ it("should_return_undefined_when_session_dir_does_not_exist", () => {
30
+ mockHomedir.mockReturnValue("/home/test");
31
+ mockExistsSync.mockReturnValue(false);
32
+
33
+ const result = findSessionFile("session-123");
34
+ expect(result).toBeUndefined();
35
+ });
36
+
37
+ it("should_return_undefined_when_session_dir_is_empty", () => {
38
+ mockHomedir.mockReturnValue("/home/test");
39
+ mockExistsSync.mockReturnValue(true);
40
+ mockReaddirSync.mockReturnValue([]);
41
+
42
+ const result = findSessionFile("session-123");
43
+ expect(result).toBeUndefined();
44
+ });
45
+
46
+ it("should_skip_non_directory_entries_in_session_dir", () => {
47
+ mockHomedir.mockReturnValue("/home/test");
48
+ mockExistsSync.mockReturnValue(true);
49
+ mockReaddirSync.mockReturnValue(["file.txt"]);
50
+ mockStatSync.mockReturnValue({ isDirectory: () => false });
51
+
52
+ const result = findSessionFile("session-123");
53
+ expect(result).toBeUndefined();
54
+ });
55
+
56
+ it("should_return_path_when_matching_file_found", () => {
57
+ mockHomedir.mockReturnValue("/home/test");
58
+ mockExistsSync.mockReturnValue(true);
59
+ mockReaddirSync.mockReturnValueOnce(["project1"]);
60
+ mockStatSync.mockReturnValue({ isDirectory: () => true });
61
+ mockReaddirSync.mockReturnValueOnce(["session-123.jsonl"]);
62
+
63
+ const result = findSessionFile("session-123");
64
+ expect(result).toBe(
65
+ path.join("/home/test", ".pi", "agent", "sessions", "project1", "session-123.jsonl"),
66
+ );
67
+ });
68
+
69
+ it("should_return_undefined_when_no_file_in_project_dirs_matches", () => {
70
+ mockHomedir.mockReturnValue("/home/test");
71
+ mockExistsSync.mockReturnValue(true);
72
+ mockReaddirSync.mockReturnValueOnce(["project1"]);
73
+ mockStatSync.mockReturnValue({ isDirectory: () => true });
74
+ mockReaddirSync.mockReturnValueOnce(["other-session.jsonl"]);
75
+
76
+ const result = findSessionFile("session-123");
77
+ expect(result).toBeUndefined();
78
+ });
79
+
80
+ it("should_search_across_multiple_project_dirs", () => {
81
+ mockHomedir.mockReturnValue("/home/test");
82
+ mockExistsSync.mockReturnValue(true);
83
+ mockReaddirSync.mockReturnValueOnce(["proj-a", "proj-b"]);
84
+ mockStatSync.mockReturnValue({ isDirectory: () => true });
85
+ mockReaddirSync
86
+ .mockReturnValueOnce(["other.jsonl"])
87
+ .mockReturnValueOnce(["session-456.jsonl"]);
88
+
89
+ const result = findSessionFile("session-456");
90
+ expect(result).toBe(
91
+ path.join("/home/test", ".pi", "agent", "sessions", "proj-b", "session-456.jsonl"),
92
+ );
93
+ });
94
+
95
+ it("should_match_partial_session_id_in_filename", () => {
96
+ mockHomedir.mockReturnValue("/home/test");
97
+ mockExistsSync.mockReturnValue(true);
98
+ mockReaddirSync.mockReturnValueOnce(["project1"]);
99
+ mockStatSync.mockReturnValue({ isDirectory: () => true });
100
+ mockReaddirSync.mockReturnValueOnce(["abc-session-123-xyz.jsonl"]);
101
+
102
+ const result = findSessionFile("session-123");
103
+ expect(result).toBe(
104
+ path.join(
105
+ "/home/test",
106
+ ".pi",
107
+ "agent",
108
+ "sessions",
109
+ "project1",
110
+ "abc-session-123-xyz.jsonl",
111
+ ),
112
+ );
113
+ });
114
+ });
@@ -0,0 +1,158 @@
1
+ /**
2
+ * utils.ts 测试 — getSubagentStatusSummary
3
+ *
4
+ * 依赖 node:os / node:fs,需要 mock。
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from "vitest";
8
+
9
+ const mockHomedir = vi.hoisted(() => vi.fn());
10
+ const mockExistsSync = vi.hoisted(() => vi.fn());
11
+ const mockReaddirSync = vi.hoisted(() => vi.fn());
12
+ const mockStatSync = vi.hoisted(() => vi.fn());
13
+ const mockReadFileSync = vi.hoisted(() => vi.fn());
14
+
15
+ vi.mock("node:os", () => ({ homedir: mockHomedir }));
16
+ vi.mock("node:fs", () => ({
17
+ existsSync: mockExistsSync,
18
+ readdirSync: mockReaddirSync,
19
+ statSync: mockStatSync,
20
+ readFileSync: mockReadFileSync,
21
+ }));
22
+
23
+ import { getSubagentStatusSummary } from "../utils";
24
+
25
+ function setupBasicMock() {
26
+ mockHomedir.mockReturnValue("/home/test");
27
+ mockExistsSync.mockReturnValue(true);
28
+ mockReaddirSync.mockReturnValueOnce(["project1"]);
29
+ mockStatSync.mockReturnValue({ isDirectory: () => true });
30
+ mockReaddirSync.mockReturnValueOnce(["session-123.jsonl"]);
31
+ }
32
+
33
+ describe("getSubagentStatusSummary", () => {
34
+ beforeEach(() => {
35
+ vi.clearAllMocks();
36
+ });
37
+
38
+ it("should_return_undefined_when_session_file_not_found", () => {
39
+ mockHomedir.mockReturnValue("/home/test");
40
+ mockExistsSync.mockReturnValue(false);
41
+
42
+ const result = getSubagentStatusSummary("session-123");
43
+ expect(result).toBeUndefined();
44
+ });
45
+
46
+ it("should_return_formatted_summary_for_valid_session", () => {
47
+ setupBasicMock();
48
+ mockReadFileSync.mockReturnValue(
49
+ JSON.stringify({
50
+ type: "message",
51
+ message: { role: "assistant" },
52
+ timestamp: "2024-01-01T12:00:00Z",
53
+ }) + "\n",
54
+ );
55
+
56
+ const result = getSubagentStatusSummary("session-123");
57
+ expect(result).toBe("1条消息 (12:00:00) [0KB]");
58
+ });
59
+
60
+ it("should_include_tool_name_in_summary", () => {
61
+ setupBasicMock();
62
+ mockReadFileSync.mockReturnValue(
63
+ JSON.stringify({
64
+ type: "message",
65
+ message: {
66
+ role: "assistant",
67
+ content: [{ type: "toolCall", name: "read_file" }],
68
+ },
69
+ timestamp: "2024-01-01T12:00:00Z",
70
+ }) + "\n",
71
+ );
72
+
73
+ const result = getSubagentStatusSummary("session-123");
74
+ expect(result).toContain("最近动作: read_file");
75
+ });
76
+
77
+ it("should_count_only_assistant_role_messages", () => {
78
+ setupBasicMock();
79
+ mockReadFileSync.mockReturnValue(
80
+ [
81
+ JSON.stringify({ type: "message", message: { role: "user" } }),
82
+ JSON.stringify({ type: "message", message: { role: "assistant" } }),
83
+ JSON.stringify({ type: "message", message: { role: "assistant" } }),
84
+ ].join("\n") + "\n",
85
+ );
86
+
87
+ const result = getSubagentStatusSummary("session-123");
88
+ expect(result).toContain("2条消息");
89
+ });
90
+
91
+ it("should_use_last_tool_and_timestamp_from_multiple_messages", () => {
92
+ setupBasicMock();
93
+ mockReadFileSync.mockReturnValue(
94
+ [
95
+ JSON.stringify({
96
+ type: "message",
97
+ message: { role: "assistant", content: [{ type: "toolCall", name: "first_tool" }] },
98
+ timestamp: "2024-01-01T12:01:00Z",
99
+ }),
100
+ JSON.stringify({
101
+ type: "message",
102
+ message: { role: "assistant", content: [{ type: "toolCall", name: "second_tool" }] },
103
+ timestamp: "2024-01-01T12:02:00Z",
104
+ }),
105
+ ].join("\n") + "\n",
106
+ );
107
+
108
+ const result = getSubagentStatusSummary("session-123");
109
+ expect(result).toContain("2条消息");
110
+ expect(result).toContain("最近动作: second_tool");
111
+ expect(result).toContain("(12:02:00)");
112
+ });
113
+
114
+ it("should_skip_malformed_json_lines_gracefully", () => {
115
+ setupBasicMock();
116
+ mockReadFileSync.mockReturnValue(
117
+ [
118
+ "{invalid json}",
119
+ JSON.stringify({ type: "message", message: { role: "assistant" } }),
120
+ "",
121
+ ].join("\n") + "\n",
122
+ );
123
+
124
+ const result = getSubagentStatusSummary("session-123");
125
+ expect(result).toContain("1条消息");
126
+ });
127
+
128
+ it("should_return_undefined_when_file_read_throws", () => {
129
+ setupBasicMock();
130
+ mockReadFileSync.mockImplementation(() => {
131
+ throw new Error("read error");
132
+ });
133
+
134
+ const result = getSubagentStatusSummary("session-123");
135
+ expect(result).toBeUndefined();
136
+ });
137
+
138
+ it("should_show_zero_messages_when_no_assistant_found", () => {
139
+ setupBasicMock();
140
+ mockReadFileSync.mockReturnValue(
141
+ JSON.stringify({
142
+ type: "message",
143
+ message: { role: "user", content: [{ type: "text", text: "hi" }] },
144
+ }) + "\n",
145
+ );
146
+
147
+ const result = getSubagentStatusSummary("session-123");
148
+ expect(result).toBe("0条消息 [0KB]");
149
+ });
150
+
151
+ it("should_show_kb_size_in_summary", () => {
152
+ setupBasicMock();
153
+ mockReadFileSync.mockReturnValue("x".repeat(2048) + "\n");
154
+
155
+ const result = getSubagentStatusSummary("session-123");
156
+ expect(result).toContain("[2KB]");
157
+ });
158
+ });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * utils.ts 测试 — isSubagentSuccess(纯逻辑,无需 mock)
3
+ */
4
+
5
+ import { describe, it, expect } from "vitest";
6
+ import { isSubagentSuccess } from "../utils";
7
+
8
+ describe("isSubagentSuccess", () => {
9
+ it("should_return_true_for_exit_0_no_error", () => {
10
+ expect(isSubagentSuccess({ exitCode: 0, output: "done" })).toBe(true);
11
+ });
12
+
13
+ it("should_return_true_for_exit_0_with_empty_error", () => {
14
+ expect(isSubagentSuccess({ exitCode: 0, output: "done", error: "" })).toBe(true);
15
+ });
16
+
17
+ it("should_return_false_for_nonzero_exit_with_short_output", () => {
18
+ expect(isSubagentSuccess({ exitCode: 1, output: "fail" })).toBe(false);
19
+ });
20
+
21
+ it("should_return_true_for_nonzero_exit_with_long_output", () => {
22
+ expect(isSubagentSuccess({ exitCode: 1, output: "x".repeat(200) })).toBe(true);
23
+ });
24
+
25
+ it("should_return_false_for_no_output_string", () => {
26
+ expect(isSubagentSuccess({ exitCode: 1, output: "(no output)" })).toBe(false);
27
+ });
28
+
29
+ it("should_return_false_for_timeout", () => {
30
+ expect(isSubagentSuccess({ exitCode: 0, output: "ok", timedOut: true })).toBe(false);
31
+ });
32
+
33
+ it("should_return_false_for_error_string", () => {
34
+ expect(isSubagentSuccess({ exitCode: 0, output: "ok", error: "crashed" })).toBe(false);
35
+ });
36
+
37
+ it("should_return_true_for_exit_0_with_explicit_timedOut_false", () => {
38
+ expect(isSubagentSuccess({ exitCode: 0, output: "ok", timedOut: false })).toBe(true);
39
+ });
40
+
41
+ it("should_return_false_when_timedOut_is_true_even_with_long_output", () => {
42
+ expect(isSubagentSuccess({ exitCode: 0, output: "x".repeat(200), timedOut: true })).toBe(false);
43
+ });
44
+
45
+ it("should_return_false_for_nonzero_exit_long_output_but_timedOut", () => {
46
+ expect(isSubagentSuccess({ exitCode: 1, output: "x".repeat(200), timedOut: true })).toBe(false);
47
+ });
48
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * 测试 widget.ts:createSubagentWidget
3
+ */
4
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
5
+
6
+ // mock pi-tui
7
+ vi.mock("@earendil-works/pi-tui", () => ({
8
+ truncateToWidth: vi.fn((s: string) => s),
9
+ }));
10
+
11
+ // mock pi SDK
12
+ vi.mock("@earendil-works/pi-coding-agent", () => ({}));
13
+
14
+ import { createSubagentWidget } from "../widget";
15
+
16
+ function createMockCtx() {
17
+ return {
18
+ ui: {
19
+ setWidget: vi.fn(),
20
+ setStatus: vi.fn(),
21
+ },
22
+ };
23
+ }
24
+
25
+ describe("createSubagentWidget", () => {
26
+ beforeEach(() => { vi.useFakeTimers(); });
27
+ afterEach(() => { vi.useRealTimers(); });
28
+
29
+ it("tool 事件添加工具行", () => {
30
+ const ctx = createMockCtx();
31
+ const widget = createSubagentWidget(ctx as any);
32
+
33
+ widget.onEvent({ type: "tool", toolName: "read" });
34
+
35
+ // 触发 scheduleWidgetUpdate 的 setTimeout
36
+ vi.advanceTimersByTime(400);
37
+
38
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
39
+ const renderFn = ctx.ui.setWidget.mock.calls[ctx.ui.setWidget.mock.calls.length - 1][1];
40
+ // setWidget 第二个参数是 widget 定义对象
41
+ expect(renderFn).toBeDefined();
42
+ });
43
+
44
+ it("连续相同工具名替换上一行", () => {
45
+ const ctx = createMockCtx();
46
+ const widget = createSubagentWidget(ctx as any);
47
+
48
+ widget.onEvent({ type: "tool", toolName: "read" });
49
+ widget.onEvent({ type: "tool", toolName: "read" });
50
+
51
+ vi.advanceTimersByTime(400);
52
+ // 只触发了一次 setWidget(因为 debounce)
53
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
54
+ });
55
+
56
+ it("thinking 事件显示思考状态", () => {
57
+ const ctx = createMockCtx();
58
+ const widget = createSubagentWidget(ctx as any);
59
+
60
+ widget.onEvent({ type: "thinking", text: "hmm..." });
61
+
62
+ vi.advanceTimersByTime(400);
63
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
64
+ });
65
+
66
+ it("message 事件显示生成状态并清除 thinking", () => {
67
+ const ctx = createMockCtx();
68
+ const widget = createSubagentWidget(ctx as any);
69
+
70
+ widget.onEvent({ type: "thinking", text: "..." });
71
+ widget.onEvent({ type: "message", message: {} });
72
+
73
+ vi.advanceTimersByTime(400);
74
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
75
+ });
76
+
77
+ it("cleanup 清除 widget", () => {
78
+ const ctx = createMockCtx();
79
+ const widget = createSubagentWidget(ctx as any);
80
+
81
+ widget.onEvent({ type: "tool", toolName: "read" });
82
+ widget.cleanup();
83
+
84
+ // 最后一次 setWidget 调用应该是清除(undefined)
85
+ const lastCall = ctx.ui.setWidget.mock.calls[ctx.ui.setWidget.mock.calls.length - 1];
86
+ expect(lastCall[0]).toBe("subagent-activity");
87
+ expect(lastCall[1]).toBeUndefined();
88
+ });
89
+
90
+ it("自定义 options 生效", () => {
91
+ const ctx = createMockCtx();
92
+ const widget = createSubagentWidget(ctx as any, {
93
+ title: "自定义标题",
94
+ icon: "⚡",
95
+ maxLines: 2,
96
+ });
97
+
98
+ widget.onEvent({ type: "tool", toolName: "bash" });
99
+
100
+ vi.advanceTimersByTime(400);
101
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
102
+ });
103
+
104
+ it("tool 后 thinking 重新触发思考显示", () => {
105
+ const ctx = createMockCtx();
106
+ const widget = createSubagentWidget(ctx as any);
107
+
108
+ widget.onEvent({ type: "tool", toolName: "read" });
109
+ widget.onEvent({ type: "thinking", text: "analyzing..." });
110
+
111
+ vi.advanceTimersByTime(400);
112
+ expect(ctx.ui.setWidget).toHaveBeenCalled();
113
+ });
114
+ });
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Tests: workflow.ts — registerWorkflowTool action 执行
3
+ *
4
+ * 测试场景(5 用例):
5
+ * 1) 匹配的 action 调用对应 handler
6
+ * 2) handler 执行后自动 persist + updateUI
7
+ * 3) handler 抛异常时 persist 后向上传播
8
+ * 4) 多个 action 按调用顺序执行
9
+ * 5) handler A 修改 state → handler B 可见
10
+ */
11
+
12
+ import { describe, it, expect, vi } from "vitest";
13
+ import type { ExtensionContext, ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
15
+ import { createMockContext } from "./test-helpers";
16
+
17
+ // ============================================================
18
+ // Types
19
+ // ============================================================
20
+
21
+ interface ActionDef<T> {
22
+ description: string;
23
+ handler: (params: any, state: T, ctx: ExtensionContext, signal?: AbortSignal, onUpdate?: any) => Promise<AgentToolResult<any>>;
24
+ gate?: (state: T) => { pass: boolean; reason?: string };
25
+ }
26
+ interface StateManager<T> { get(): T; set(s: T): void; reset(): void; persist(ctx: ExtensionContext): void; restore(ctx: ExtensionContext): void }
27
+ interface UIUpdater<T> { update(ctx: ExtensionContext, state: T): void; clear(ctx: ExtensionContext): void }
28
+
29
+ // ============================================================
30
+ // Inline implementation (same as workflow-registration.test.ts)
31
+ // ============================================================
32
+
33
+ function registerWorkflowTool<T>(pi: ExtensionAPI, options: {
34
+ name: string; description: string; promptSnippet?: string; promptGuidelines?: string[];
35
+ actions: Record<string, ActionDef<T>>; stateManager: StateManager<T>; uiUpdater: UIUpdater<T>;
36
+ }): void {
37
+ const actionNames = Object.keys(options.actions);
38
+ pi.registerTool({
39
+ name: options.name, label: options.name, description: options.description,
40
+ parameters: { type: "object", properties: { action: { type: "string", enum: actionNames } }, required: ["action"] },
41
+ execute: async (_tcId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx: ExtensionContext): Promise<AgentToolResult<any>> => {
42
+ const { action, ...actionParams } = params;
43
+ const actionDef = options.actions[action as string];
44
+ if (!actionDef) return { content: [{ type: "text" as const, text: `未知 action: "${action}"` }], details: { error: `unknown_action: ${action}` }, terminate: false };
45
+ if (actionDef.gate) {
46
+ const g = actionDef.gate(options.stateManager.get());
47
+ if (!g.pass) return { content: [{ type: "text" as const, text: `Gate 阻止: ${g.reason}` }], details: { error: `gate_blocked: ${g.reason}` }, terminate: false };
48
+ }
49
+ try {
50
+ const r = await actionDef.handler(actionParams, options.stateManager.get(), ctx, signal, onUpdate);
51
+ options.stateManager.persist(ctx);
52
+ options.uiUpdater.update(ctx, options.stateManager.get());
53
+ return r;
54
+ } catch (err) {
55
+ options.stateManager.persist(ctx);
56
+ options.uiUpdater.update(ctx, options.stateManager.get());
57
+ throw err;
58
+ }
59
+ },
60
+ } as any);
61
+ }
62
+
63
+ // ============================================================
64
+ // Fixtures
65
+ // ============================================================
66
+
67
+ interface TestState { phase: string; items: string[]; round: number }
68
+ const INITIAL: TestState = { phase: "idle", items: [], round: 0 };
69
+
70
+ function mockSM(): StateManager<TestState> {
71
+ let s: TestState = { ...INITIAL };
72
+ return { get: vi.fn(() => s), set: vi.fn((v: TestState) => { s = v; }), reset: vi.fn(() => { s = { ...INITIAL }; }), persist: vi.fn(), restore: vi.fn() };
73
+ }
74
+ function mockUI(): UIUpdater<TestState> { return { update: vi.fn(), clear: vi.fn() }; }
75
+ function mockAPI(): ExtensionAPI {
76
+ return { on: vi.fn(), registerTool: vi.fn(), registerCommand: vi.fn(), registerShortcut: vi.fn(), registerFlag: vi.fn(), getFlag: vi.fn(), registerMessageRenderer: vi.fn(), sendMessage: vi.fn(), sendUserMessage: vi.fn(), appendEntry: vi.fn(), setSessionName: vi.fn(), getSessionName: vi.fn(), setLabel: vi.fn(), getActiveTools: vi.fn().mockReturnValue([]), getAllTools: vi.fn().mockReturnValue([]), setActiveTools: vi.fn(), refreshTools: vi.fn(), getCommands: vi.fn().mockReturnValue([]), setModel: vi.fn(), getThinkingLevel: vi.fn(), setThinkingLevel: vi.fn(), exec: vi.fn() } as any;
77
+ }
78
+
79
+ // ============================================================
80
+ // Tests: action 路由
81
+ // ============================================================
82
+
83
+ describe("registerWorkflowTool — action 路由", () => {
84
+ it("匹配的 action 调用对应 handler,传递正确的 params", async () => {
85
+ const api = mockAPI();
86
+ const sm = mockSM();
87
+ const ui = mockUI();
88
+ const planHandler = vi.fn().mockResolvedValue({ content: [{ type: "text" as const, text: "plan ok" }], details: {} });
89
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { plan: { description: "plan", handler: planHandler }, execute: { description: "exec", handler: vi.fn() } }, stateManager: sm, uiUpdater: ui });
90
+ const def = (api.registerTool as any).mock.calls[0][0];
91
+ const ctx = createMockContext();
92
+ const r = await def.execute("c1", { action: "plan", task: "test" }, undefined, undefined, ctx);
93
+ expect(planHandler).toHaveBeenCalledWith({ task: "test" }, sm.get(), ctx, undefined, undefined);
94
+ expect(r).toEqual({ content: [{ type: "text", text: "plan ok" }], details: {} });
95
+ });
96
+ });
97
+
98
+ // ============================================================
99
+ // Tests: 自动 persist + UI 更新
100
+ // ============================================================
101
+
102
+ describe("registerWorkflowTool — 自动 persist + UI 更新", () => {
103
+ const handler = () => Promise.resolve({ content: [{ type: "text" as const, text: "ok" }], details: {} });
104
+
105
+ it("handler 执行后自动 persist + updateUI", async () => {
106
+ const api = mockAPI();
107
+ const sm = mockSM();
108
+ const ui = mockUI();
109
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { plan: { description: "plan", handler } }, stateManager: sm, uiUpdater: ui });
110
+ const def = (api.registerTool as any).mock.calls[0][0];
111
+ await def.execute("c1", { action: "plan" }, undefined, undefined, createMockContext());
112
+ expect(sm.persist).toHaveBeenCalledTimes(1);
113
+ expect(ui.update).toHaveBeenCalledTimes(1);
114
+ });
115
+
116
+ it("handler 抛异常时 persist + updateUI,然后传播错误", async () => {
117
+ const api = mockAPI();
118
+ const sm = mockSM();
119
+ const ui = mockUI();
120
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: { plan: { description: "plan", handler: () => Promise.reject(new Error("写入失败")) } }, stateManager: sm, uiUpdater: ui });
121
+ const def = (api.registerTool as any).mock.calls[0][0];
122
+ await expect(def.execute("c1", { action: "plan" }, undefined, undefined, createMockContext())).rejects.toThrow("写入失败");
123
+ expect(sm.persist).toHaveBeenCalledTimes(1);
124
+ expect(ui.update).toHaveBeenCalledTimes(1);
125
+ });
126
+ });
127
+
128
+ // ============================================================
129
+ // Tests: 多 action 顺序 + state 可见性
130
+ // ============================================================
131
+
132
+ describe("registerWorkflowTool — 多 action + state 可见性", () => {
133
+ it("多个 action 按调用顺序执行", async () => {
134
+ const api = mockAPI();
135
+ const order: string[] = [];
136
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: {
137
+ plan: { description: "plan", handler: vi.fn().mockImplementation(async () => { order.push("plan"); return { content: [{ type: "text" as const, text: "ok" }], details: {} }; }) },
138
+ review: { description: "review", handler: vi.fn().mockImplementation(async () => { order.push("review"); return { content: [{ type: "text" as const, text: "ok" }], details: {} }; }) },
139
+ execute: { description: "exec", handler: vi.fn().mockImplementation(async () => { order.push("execute"); return { content: [{ type: "text" as const, text: "ok" }], details: {} }; }) },
140
+ }, stateManager: mockSM(), uiUpdater: mockUI() });
141
+ const def = (api.registerTool as any).mock.calls[0][0];
142
+ const ctx = createMockContext();
143
+ await def.execute("c1", { action: "plan" }, undefined, undefined, ctx);
144
+ await def.execute("c2", { action: "review" }, undefined, undefined, ctx);
145
+ await def.execute("c3", { action: "execute" }, undefined, undefined, ctx);
146
+ expect(order).toEqual(["plan", "review", "execute"]);
147
+ });
148
+
149
+ it("handler A 修改 state 后 handler B 可见", async () => {
150
+ const api = mockAPI();
151
+ const sm = mockSM();
152
+ registerWorkflowTool(api, { name: "pv", description: "PV", actions: {
153
+ plan: { description: "plan", handler: vi.fn().mockImplementation(async (_p, state) => { state.phase = "planned"; state.items.push("step1"); return { content: [{ type: "text" as const, text: "ok" }], details: {} }; }) },
154
+ review: { description: "review", handler: vi.fn().mockImplementation(async (_p, state) => { state.phase = "reviewed"; state.items.push("step2"); return { content: [{ type: "text" as const, text: "ok" }], details: {} }; }) },
155
+ }, stateManager: sm, uiUpdater: mockUI() });
156
+ const def = (api.registerTool as any).mock.calls[0][0];
157
+ const ctx = createMockContext();
158
+ await def.execute("c1", { action: "plan" }, undefined, undefined, ctx);
159
+ expect(sm.get().phase).toBe("planned");
160
+ expect(sm.get().items).toEqual(["step1"]);
161
+ await def.execute("c2", { action: "review" }, undefined, undefined, ctx);
162
+ expect(sm.get().phase).toBe("reviewed");
163
+ expect(sm.get().items).toEqual(["step1", "step2"]);
164
+ });
165
+ });