@firstpick/pi-package-webui 0.6.4 → 0.6.6

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.
@@ -0,0 +1,210 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import webuiRpcHelper from "../webui-rpc-helper.mjs";
6
+
7
+ class EventBus {
8
+ constructor() {
9
+ this.handlers = new Map();
10
+ }
11
+
12
+ on(name, handler) {
13
+ const handlers = this.handlers.get(name) || new Set();
14
+ handlers.add(handler);
15
+ this.handlers.set(name, handlers);
16
+ return () => {
17
+ handlers.delete(handler);
18
+ if (handlers.size === 0) this.handlers.delete(name);
19
+ };
20
+ }
21
+
22
+ emit(name, value) {
23
+ for (const handler of [...(this.handlers.get(name) || [])]) handler(value);
24
+ }
25
+ }
26
+
27
+ const bus = new EventBus();
28
+ const extensionHandlers = new Map();
29
+ const registeredCommands = new Map();
30
+ const statuses = [];
31
+ const notifications = [];
32
+ const pi = {
33
+ events: bus,
34
+ on(name, handler) {
35
+ const handlers = extensionHandlers.get(name) || [];
36
+ handlers.push(handler);
37
+ extensionHandlers.set(name, handlers);
38
+ },
39
+ registerCommand(name, command) { registeredCommands.set(name, command); },
40
+ getAllTools() { return []; },
41
+ getActiveTools() { return []; },
42
+ setActiveTools() {},
43
+ appendEntry() {},
44
+ };
45
+
46
+ const ctx = {
47
+ mode: "rpc",
48
+ hasUI: true,
49
+ cwd: "/tmp/subagent-helper-test",
50
+ sessionManager: {
51
+ getBranch() { return []; },
52
+ },
53
+ ui: {
54
+ setStatus(key, text) {
55
+ statuses.push({ key, text });
56
+ },
57
+ notify(message, type) {
58
+ notifications.push({ message, type });
59
+ },
60
+ },
61
+ };
62
+
63
+ const asyncRunDir = await mkdtemp(path.join(tmpdir(), "pi-webui-subagent-output-test-"));
64
+ const asyncSessionFile = path.join(asyncRunDir, "reviewer-session.jsonl");
65
+ await writeFile(asyncSessionFile, [
66
+ JSON.stringify({ type: "message", message: { role: "assistant", content: [{ type: "text", text: "REVIEWER STREAM 1 OF 18" }, { type: "toolCall", name: "bash", arguments: { command: "sleep 5" } }] } }),
67
+ JSON.stringify({ type: "message", message: { role: "toolResult", content: [{ type: "text", text: "(no output)\nreviewer tool output line" }] } }),
68
+ "",
69
+ ].join("\n"));
70
+ await writeFile(path.join(asyncRunDir, "status.json"), JSON.stringify({
71
+ runId: "run-a",
72
+ mode: "parallel",
73
+ state: "running",
74
+ startedAt: Date.now() - 1000,
75
+ lastUpdate: Date.now(),
76
+ steps: [
77
+ { agent: "reviewer", status: "running", sessionFile: asyncSessionFile, recentOutput: [], currentTool: "bash", currentToolArgs: "sleep 5" },
78
+ { agent: "scout", status: "running" },
79
+ ],
80
+ }));
81
+
82
+ const statusText = `Active async runs: 2
83
+
84
+ - run-a | running | active | parallel | 2/2 running | ~/repo
85
+ 1. reviewer | running | tool read
86
+ 2. scout | running | tool grep
87
+
88
+ - run-b | running | active | chain | step 2/2 | ~/repo
89
+ 1. planner | completed
90
+ 2. [Implementation] Apply fixes (worker) | running | tool edit
91
+ ↳ nested-oracle [nested-1] running | tool grep`;
92
+
93
+ webuiRpcHelper(pi);
94
+ const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
95
+ const text = request.params?.id === "run-a"
96
+ ? `Run: run-a\nState: running\nMode: parallel\nDir: ${asyncRunDir}`
97
+ : statusText;
98
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
99
+ version: 1,
100
+ requestId: request.requestId,
101
+ method: request.method,
102
+ success: true,
103
+ data: { text, details: { mode: "single", results: [] } },
104
+ });
105
+ });
106
+
107
+ for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "startup" }, ctx);
108
+ for (let attempt = 0; attempt < 20 && !statuses.some((entry) => entry.text?.startsWith("PI_WEBUI_SUBAGENTS_V1 ") && entry.text.includes("run-a")); attempt++) {
109
+ await new Promise((resolve) => setTimeout(resolve, 10));
110
+ }
111
+
112
+ function latestPayload() {
113
+ const entry = statuses.filter((item) => item.key === "webui-subagents").at(-1);
114
+ assert.ok(entry, "helper should publish the internal WebUI subagent status");
115
+ assert.match(entry.text, /^PI_WEBUI_SUBAGENTS_V1 /);
116
+ return JSON.parse(entry.text.slice("PI_WEBUI_SUBAGENTS_V1 ".length));
117
+ }
118
+
119
+ let payload = latestPayload();
120
+ assert.equal(payload.available, true, "successful pi-subagents RPC should mark status available");
121
+ assert.deepEqual(payload.runs.map((run) => run.id), ["run-a", "run-b"]);
122
+ assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.name, agent.currentTool]), [["reviewer", "read"], ["scout", "grep"]]);
123
+ assert.deepEqual(payload.runs[1].agents.map((agent) => [agent.name, agent.nested]), [["worker", false], ["nested-oracle", true]]);
124
+
125
+ const helperCommand = registeredCommands.get("webui-helper");
126
+ assert.ok(helperCommand?.handler, "Web UI helper command should be registered");
127
+ await helperCommand.handler(JSON.stringify({
128
+ requestId: "async-subagent-output-test",
129
+ action: "subagent-output",
130
+ payload: { runId: "run-a", agentId: "run-a:step:0:reviewer" },
131
+ }), ctx);
132
+ const asyncOutputNotice = notifications.find((entry) => entry.message.includes("async-subagent-output-test"));
133
+ assert.ok(asyncOutputNotice, "async subagent output helper action should return a response notification");
134
+ const asyncOutputResponse = JSON.parse(asyncOutputNotice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
135
+ assert.equal(asyncOutputResponse.ok, true);
136
+ assert.deepEqual(asyncOutputResponse.data.agent.recentOutput, [
137
+ "REVIEWER STREAM 1 OF 18",
138
+ "▶ bash {\"command\":\"sleep 5\"}",
139
+ "reviewer tool output line",
140
+ ], "async output should be recovered from the child session transcript when status recentOutput is empty");
141
+
142
+ for (const handler of extensionHandlers.get("tool_execution_start") || []) {
143
+ handler({
144
+ type: "tool_execution_start",
145
+ toolCallId: "foreground-call",
146
+ toolName: "subagent",
147
+ args: { tasks: [{ agent: "tester", task: "Run tests" }, { agent: "reviewer", task: "Review diff" }] },
148
+ }, ctx);
149
+ }
150
+ payload = latestPayload();
151
+ let foreground = payload.runs.find((run) => run.source === "foreground");
152
+ assert.deepEqual(foreground?.agents.map((agent) => agent.name), ["tester", "reviewer"], "foreground parallel children should appear while the tool runs");
153
+
154
+ for (const handler of extensionHandlers.get("tool_execution_update") || []) {
155
+ handler({
156
+ type: "tool_execution_update",
157
+ toolCallId: "foreground-call",
158
+ toolName: "subagent",
159
+ partialResult: {
160
+ details: {
161
+ mode: "parallel",
162
+ progress: [{
163
+ index: 0,
164
+ agent: "tester",
165
+ status: "running",
166
+ currentTool: "bash",
167
+ currentToolArgs: "npm test",
168
+ currentPath: "/tmp/subagent-helper-test",
169
+ recentTools: [{ tool: "read", args: "package.json", endMs: 1000 }],
170
+ recentOutput: ["Running focused tests", "12 assertions passed"],
171
+ turnCount: 2,
172
+ toolCount: 3,
173
+ tokens: 420,
174
+ }],
175
+ },
176
+ },
177
+ }, ctx);
178
+ }
179
+ payload = latestPayload();
180
+ foreground = payload.runs.find((run) => run.source === "foreground");
181
+ assert.deepEqual(foreground?.agents.map((agent) => agent.name), ["tester"], "foreground live updates should expose currently running children");
182
+
183
+ await helperCommand.handler(JSON.stringify({
184
+ requestId: "subagent-output-test",
185
+ action: "subagent-output",
186
+ payload: { runId: "foreground-call", agentId: "foreground-call:0:tester" },
187
+ }), ctx);
188
+ const outputNotice = notifications.find((entry) => {
189
+ if (!entry.message.startsWith("__PI_WEBUI_HELPER_RESPONSE__:")) return false;
190
+ return JSON.parse(entry.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length)).requestId === "subagent-output-test";
191
+ });
192
+ assert.ok(outputNotice, "subagent output helper action should return a response notification");
193
+ const outputResponse = JSON.parse(outputNotice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
194
+ assert.equal(outputResponse.ok, true);
195
+ assert.equal(outputResponse.data.agent.currentTool, "bash");
196
+ assert.equal(outputResponse.data.agent.currentToolArgs, "npm test");
197
+ assert.deepEqual(outputResponse.data.agent.recentOutput, ["Running focused tests", "12 assertions passed"]);
198
+ assert.deepEqual(outputResponse.data.agent.recentTools, [{ tool: "read", args: "package.json", endMs: 1000 }]);
199
+
200
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
201
+ handler({ type: "tool_execution_end", toolCallId: "foreground-call", toolName: "subagent" }, ctx);
202
+ }
203
+ payload = latestPayload();
204
+ assert.equal(payload.runs.some((run) => run.source === "foreground"), false, "foreground children should disappear when their tool finishes");
205
+
206
+ for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
207
+ unsubscribeRpc();
208
+ await rm(asyncRunDir, { recursive: true, force: true });
209
+
210
+ console.log("subagents-helper.test.mjs passed");
@@ -73,18 +73,18 @@ assert.match(
73
73
 
74
74
  // Persistence lives inside applyTheme's validated persist branch (matching light/dark
75
75
  // scheme slot + legacy key), reached only after setThemeByName found and classified
76
- // the theme. chooseTheme is the single persist:true entry point; applySchemeTheme
77
- // (init, mode switches, OS changes) never persists, so a degraded bundle load cannot
78
- // clobber stored picks.
76
+ // the theme. chooseTheme is the single theme persist:true entry point; unrelated
77
+ // browser preferences may use the same option name. applySchemeTheme (init, mode
78
+ // switches, OS changes) never persists, so a degraded bundle load cannot clobber picks.
79
79
  assert.match(
80
80
  app,
81
81
  /if \(persist\) \{\s*storeSchemeTheme\(isLight \? "light" : "dark", theme\.name\);\s*storeThemeName\(theme\.name\);\s*\}/,
82
82
  "applyTheme's persist branch must write the theme's matching scheme slot and the legacy key",
83
83
  );
84
84
  assert.equal(
85
- (app.match(/persist: true/g) || []).length,
85
+ (app.match(/setThemeByName\([^;]*persist: true/g) || []).length,
86
86
  1,
87
- "chooseTheme must be the only persist:true call site",
87
+ "chooseTheme must be the only theme persist:true call site",
88
88
  );
89
89
  assert.match(
90
90
  app,