@firstpick/pi-package-webui 0.7.5 → 0.7.7

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 (40) hide show
  1. package/README.md +37 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +518 -0
  3. package/bin/pi-webui.mjs +1003 -82
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +301 -0
  6. package/lib/rpc-supervisor-protocol.mjs +236 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +2 -2
  10. package/public/app.js +1243 -87
  11. package/public/index.html +334 -24
  12. package/public/service-worker.js +6 -1
  13. package/public/styles.css +642 -41
  14. package/public/subagent-gate-visibility.mjs +36 -0
  15. package/public/workflow-status-stack.mjs +69 -0
  16. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  17. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  18. package/tests/compact-sections-static.test.mjs +111 -0
  19. package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
  20. package/tests/fast-mode-client-static.test.mjs +2 -2
  21. package/tests/fixtures/compacting-pi.mjs +0 -0
  22. package/tests/fixtures/fake-pi.mjs +81 -2
  23. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  24. package/tests/http-endpoints-harness.test.mjs +458 -33
  25. package/tests/mobile-static.test.mjs +77 -9
  26. package/tests/native-parity-harness.test.mjs +2 -1
  27. package/tests/native-parity.test.mjs +11 -0
  28. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  29. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  30. package/tests/prompt-routing-tab-status.test.mjs +103 -0
  31. package/tests/rpc-supervisor-host.test.mjs +275 -0
  32. package/tests/rpc-supervisor-protocol.test.mjs +67 -0
  33. package/tests/rpc-supervisor-state.test.mjs +62 -0
  34. package/tests/run-all.mjs +4 -1
  35. package/tests/streaming-ui-coupling.test.mjs +15 -0
  36. package/tests/subagent-gate-visibility.test.mjs +66 -0
  37. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  38. package/tests/subagents-helper.test.mjs +145 -8
  39. package/tests/workflow-status-stack.test.mjs +87 -0
  40. package/webui-rpc-helper.mjs +164 -4
@@ -30,6 +30,7 @@ const extensionHandlers = new Map();
30
30
  const registeredCommands = new Map();
31
31
  const statuses = [];
32
32
  const notifications = [];
33
+ let subagentStatusRequestCount = 0;
33
34
  const pi = {
34
35
  events: bus,
35
36
  on(name, handler) {
@@ -94,23 +95,24 @@ await writeFile(asyncStatusFile, JSON.stringify({
94
95
  lastUpdate: Date.now(),
95
96
  steps: [
96
97
  { agent: "reviewer", status: "running", sessionFile: asyncSessionFile, recentOutput: [], currentTool: "bash", currentToolArgs: "sleep 5", model: "anthropic/claude-opus-4-8:high", thinking: "high" },
97
- { agent: "scout", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" },
98
+ { agent: "reviewer", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" },
98
99
  ],
99
100
  }));
100
101
 
101
102
  const statusText = `Active async runs: 2
102
103
 
103
- - run-a | running | active | parallel | 2/2 running | ~/repo
104
- 1. reviewer | running | tool read
105
- 2. scout | running | tool grep
104
+ - run-a | running | active | parallel [fresh] | 2/2 running | ~/repo
105
+ 1. reviewer [fresh] | running | tool read
106
+ 2. reviewer [fresh] | running | tool grep
106
107
 
107
- - run-b | running | active | chain | step 2/2 | ~/repo
108
- 1. planner | completed
109
- 2. [Implementation] Apply fixes (worker) | running | tool edit
108
+ - run-b | running | active | chain [mixed] | step 2/2 | ~/repo
109
+ 1. planner [fresh] | completed
110
+ 2. [Implementation] Apply fixes (worker) [fork] | running | tool edit
110
111
  ↳ nested-oracle [nested-1] running | tool grep`;
111
112
 
112
113
  webuiRpcHelper(pi);
113
114
  const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
115
+ subagentStatusRequestCount += 1;
114
116
  const text = request.params?.id === "run-a"
115
117
  ? `Run: run-a\nState: running\nMode: parallel\nDir: ${asyncRunDir}`
116
118
  : statusText;
@@ -165,7 +167,8 @@ function latestPayload() {
165
167
  let payload = latestPayload();
166
168
  assert.equal(payload.available, true, "successful pi-subagents RPC should mark status available");
167
169
  assert.deepEqual(payload.runs.map((run) => run.id), ["run-a", "run-b"]);
168
- assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.name, agent.currentTool]), [["reviewer", "read"], ["scout", "grep"]]);
170
+ assert.deepEqual(payload.runs.map((run) => run.mode), ["parallel", "chain"], "async overview should ignore fleet context badges when parsing run modes");
171
+ assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.name, agent.currentTool]), [["reviewer", "read"], ["reviewer", "grep"]], "async overview should ignore fleet context badges while preserving same-role child indexes");
169
172
  assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.model, agent.thinking]), [["anthropic/claude-opus-4-8:high", "high"], ["openai-codex/gpt-5.6-sol", "high"]], "async overview should publish effective lifecycle model and reasoning metadata");
170
173
  assert.deepEqual(payload.runs[1].agents.map((agent) => [agent.name, agent.nested]), [["worker", false], ["nested-oracle", true]]);
171
174
 
@@ -188,8 +191,90 @@ assert.equal(payload.gates.length, 1, "helper should publish retry gate lifecycl
188
191
  assert.equal(payload.gates[0].qualifyingSuccesses, 1);
189
192
  assert.deepEqual(payload.gates[0].attempts.map((attempt) => [attempt.status, attempt.failureKind]), [["succeeded", undefined], ["failed", "transient-provider"]]);
190
193
 
194
+ const workflowRunId = "workflow:run-42";
195
+ const workflowAgentId = "workflow:run-42:phase:implement:call:call-0123456789abcdef";
196
+ const workflowSnapshot = {
197
+ version: 1,
198
+ updatedAt: "2026-07-26T12:00:05.000Z",
199
+ runs: [{
200
+ id: workflowRunId,
201
+ source: "workflow",
202
+ name: "Workflow build",
203
+ status: "running",
204
+ startedAt: "2026-07-26T12:00:00.000Z",
205
+ agents: [{
206
+ id: workflowAgentId,
207
+ name: "Implementation worker",
208
+ status: "running",
209
+ index: 0,
210
+ activityState: "stdout",
211
+ model: "openai-codex/gpt-5.6-terra:xhigh",
212
+ recentOutput: ["Inspecting helper contract", "Implementing local output route"],
213
+ }],
214
+ }],
215
+ };
216
+ bus.emit("firstpick:workflow-subagents:v1", workflowSnapshot);
217
+ payload = latestPayload();
218
+ const workflowRun = payload.runs.find((run) => run.id === workflowRunId);
219
+ assert.deepEqual(workflowRun && {
220
+ id: workflowRun.id,
221
+ source: workflowRun.source,
222
+ name: workflowRun.name,
223
+ agents: workflowRun.agents.map((agent) => [agent.id, agent.name, agent.activityState, agent.model, agent.thinking]),
224
+ }, {
225
+ id: workflowRunId,
226
+ source: "workflow",
227
+ name: "Workflow build",
228
+ agents: [[workflowAgentId, "Implementation worker", "stdout", "openai-codex/gpt-5.6-terra:xhigh", undefined]],
229
+ }, "workflow snapshots should preserve stable IDs, source, name, activity, model, and unknown thinking alongside ordinary rows");
230
+ assert.ok(payload.runs.some((run) => run.id === "run-a") && payload.runs.some((run) => run.id === "run-b"), "workflow rows should coexist with ordinary async rows");
231
+
232
+ const requestsBeforeWorkflowPoll = subagentStatusRequestCount;
233
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
234
+ await new Promise((resolve) => setTimeout(resolve, 0));
235
+ payload = latestPayload();
236
+ assert.ok(subagentStatusRequestCount > requestsBeforeWorkflowPoll, "ordinary pi-subagents polling should still run after workflow snapshots arrive");
237
+ assert.ok(payload.runs.some((run) => run.id === workflowRunId), "pi-subagents polling must not reconcile away workflow rows");
238
+
191
239
  const helperCommand = registeredCommands.get("webui-helper");
192
240
  assert.ok(helperCommand?.handler, "Web UI helper command should be registered");
241
+ const requestsBeforeWorkflowOutput = subagentStatusRequestCount;
242
+ await helperCommand.handler(JSON.stringify({
243
+ requestId: "workflow-subagent-output-test",
244
+ action: "subagent-output",
245
+ payload: { runId: workflowRunId, agentId: workflowAgentId },
246
+ }), ctx);
247
+ const workflowOutputNotice = notifications.find((entry) => entry.message.startsWith("__PI_WEBUI_HELPER_RESPONSE__:")
248
+ && JSON.parse(entry.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length)).requestId === "workflow-subagent-output-test");
249
+ assert.ok(workflowOutputNotice, "workflow output should return a local helper response");
250
+ const workflowOutputResponse = JSON.parse(workflowOutputNotice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
251
+ assert.equal(workflowOutputResponse.ok, true);
252
+ assert.equal("thinking" in workflowOutputResponse.data.agent, false, "workflow output must leave unknown thinking metadata absent rather than infer it from the model");
253
+ assert.deepEqual(workflowOutputResponse.data, {
254
+ version: 1,
255
+ runId: workflowRunId,
256
+ source: "workflow",
257
+ mode: "single",
258
+ startedAt: Date.parse("2026-07-26T12:00:00.000Z"),
259
+ updatedAt: Date.parse("2026-07-26T12:00:05.000Z"),
260
+ agent: {
261
+ id: workflowAgentId,
262
+ name: "Implementation worker",
263
+ index: 0,
264
+ nested: false,
265
+ status: "running",
266
+ activityState: "stdout",
267
+ model: "openai-codex/gpt-5.6-terra:xhigh",
268
+ recentTools: [],
269
+ recentOutput: ["Inspecting helper contract", "Implementing local output route"],
270
+ transcript: [],
271
+ },
272
+ }, "workflow output should use only cached bounded workflow fields");
273
+ assert.equal(subagentStatusRequestCount, requestsBeforeWorkflowOutput, "workflow output must not request pi-subagents status or filesystem data");
274
+
275
+ assert.doesNotThrow(() => bus.emit("firstpick:workflow-subagents:v1", { version: 1, runs: "not-an-array" }), "malformed workflow payloads must not crash the helper");
276
+ payload = latestPayload();
277
+ assert.ok(payload.runs.some((run) => run.id === workflowRunId), "malformed workflow payloads must not clear the prior valid snapshot");
193
278
  await helperCommand.handler(JSON.stringify({
194
279
  requestId: "async-subagent-output-test",
195
280
  action: "subagent-output",
@@ -358,6 +443,58 @@ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
358
443
  payload = latestPayload();
359
444
  assert.equal(payload.runs.some((run) => run.source === "foreground"), false, "foreground children should disappear when their tool finishes");
360
445
 
446
+ const boundedWorkflowSnapshot = {
447
+ version: 1,
448
+ updatedAt: "2026-07-26T12:01:00.000Z",
449
+ runs: Array.from({ length: 33 }, (_unused, runIndex) => ({
450
+ id: `workflow:bounded-run-${runIndex}`,
451
+ source: "workflow",
452
+ name: `Bounded workflow ${runIndex}`,
453
+ status: "running",
454
+ startedAt: "2026-07-26T12:00:00.000Z",
455
+ agents: Array.from({ length: 33 }, (_agentUnused, agentIndex) => ({
456
+ id: `workflow:bounded-run-${runIndex}:phase:phase-${agentIndex}:call:call-${agentIndex}`,
457
+ name: `Bounded worker ${agentIndex}`,
458
+ status: "running",
459
+ index: agentIndex,
460
+ activityState: "x".repeat(200),
461
+ model: "m".repeat(300),
462
+ recentOutput: Array.from({ length: 9 }, (_lineUnused, lineIndex) => `line-${lineIndex}:${"o".repeat(700)}`),
463
+ })),
464
+ })),
465
+ };
466
+ assert.doesNotThrow(() => bus.emit("firstpick:workflow-subagents:v1", boundedWorkflowSnapshot), "oversized workflow snapshots should be bounded safely at ingress");
467
+ payload = latestPayload();
468
+ const boundedWorkflowRuns = payload.runs.filter((run) => run.source === "workflow");
469
+ assert.equal(boundedWorkflowRuns.length, 32, "workflow ingress should cap the number of cached runs");
470
+ assert.equal(boundedWorkflowRuns[0].agents.length, 32, "workflow ingress should cap agents per run");
471
+ assert.equal(boundedWorkflowRuns[0].agents[0].activityState.length, 80, "workflow ingress should bound activity text");
472
+ assert.equal(boundedWorkflowRuns[0].agents[0].model.length, 240, "workflow ingress should bound model text");
473
+
474
+ const boundedWorkflowRun = boundedWorkflowRuns[0];
475
+ const boundedWorkflowAgent = boundedWorkflowRun.agents[0];
476
+ await helperCommand.handler(JSON.stringify({
477
+ requestId: "bounded-workflow-subagent-output-test",
478
+ action: "subagent-output",
479
+ payload: { runId: boundedWorkflowRun.id, agentId: boundedWorkflowAgent.id },
480
+ }), ctx);
481
+ const boundedWorkflowOutputNotice = notifications.find((entry) => entry.message.startsWith("__PI_WEBUI_HELPER_RESPONSE__:")
482
+ && JSON.parse(entry.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length)).requestId === "bounded-workflow-subagent-output-test");
483
+ assert.ok(boundedWorkflowOutputNotice, "bounded workflow output should return a local helper response");
484
+ const boundedWorkflowOutput = JSON.parse(boundedWorkflowOutputNotice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
485
+ assert.equal(boundedWorkflowOutput.data.agent.recentOutput.length, 8, "workflow ingress should cap cached output lines");
486
+ assert.equal(boundedWorkflowOutput.data.agent.recentOutput[0].length, 500, "workflow ingress should cap cached output line length");
487
+ assert.match(boundedWorkflowOutput.data.agent.recentOutput[0], /^line-1:/, "workflow ingress should retain the bounded output tail");
488
+
489
+ bus.emit("firstpick:workflow-subagents:v1", {
490
+ version: 1,
491
+ updatedAt: "2026-07-26T12:02:00.000Z",
492
+ runs: [],
493
+ });
494
+ payload = latestPayload();
495
+ assert.equal(payload.runs.some((run) => run.source === "workflow"), false, "an empty workflow snapshot should clear only workflow rows");
496
+ assert.ok(payload.runs.some((run) => run.id === "run-a") && payload.runs.some((run) => run.id === "run-b"), "workflow cleanup must preserve ordinary async rows");
497
+
361
498
  for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
362
499
  unsubscribeRpc();
363
500
  delete process.env.PI_WEBUI_SETTINGS_FILE;
@@ -0,0 +1,87 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ groupConsecutiveWorkflowStatusItems,
7
+ isCompletedWorkflowStatusExecution,
8
+ workflowStatusSnapshot,
9
+ } from "../public/workflow-status-stack.mjs";
10
+
11
+ function statusItem(id, status = "running", patch = {}) {
12
+ return {
13
+ messageIndex: Number(id.replace(/\D/g, "")) || 0,
14
+ order: Number(id.replace(/\D/g, "")) || 0,
15
+ message: {
16
+ role: "toolExecution",
17
+ toolName: "workflow_status",
18
+ toolCallId: id,
19
+ timestamp: `2026-07-26T19:00:0${id.at(-1)}Z`,
20
+ arguments: {},
21
+ result: { content: [{ type: "text", text: `Workflow: release\nRun: run-1\nStatus: ${status}\nTasks: 1/3 completed` }] },
22
+ ...patch,
23
+ },
24
+ };
25
+ }
26
+
27
+ assert.equal(isCompletedWorkflowStatusExecution(statusItem("call-1").message), true, "completed workflow_status executions should be eligible");
28
+ assert.equal(isCompletedWorkflowStatusExecution(statusItem("call-1", "running", { isPartial: true }).message), false, "partial workflow_status executions should remain standalone");
29
+ assert.equal(isCompletedWorkflowStatusExecution(statusItem("call-1", "completed", { live: true }).message), false, "live workflow_status executions should remain standalone until persisted");
30
+ assert.equal(isCompletedWorkflowStatusExecution({ ...statusItem("call-1").message, toolName: "workflow_run" }), false, "other workflow tools should remain standalone");
31
+
32
+ const one = groupConsecutiveWorkflowStatusItems([statusItem("call-1")]);
33
+ assert.equal(one.length, 1, "a single status update should not gain stack chrome");
34
+ assert.equal(one[0].message.role, "toolExecution");
35
+
36
+ const stacked = groupConsecutiveWorkflowStatusItems([statusItem("call-1"), statusItem("call-2", "completed")]);
37
+ assert.equal(stacked.length, 1, "adjacent completed status updates should collapse into one transcript item");
38
+ assert.equal(stacked[0].message.role, "workflowStatusStack");
39
+ assert.equal(stacked[0].message.workflowStatusUpdates.length, 2);
40
+ assert.equal(stacked[0].message.workflowStatusUpdates[0].toolCallId, "call-1", "stack members should remain chronological");
41
+ assert.equal(stacked[0].message.workflowStatusUpdates.at(-1).toolCallId, "call-2", "the latest update should remain last");
42
+ assert.match(stacked[0].transcriptKey, /^workflow-status-stack:call-1$/, "the first tool call should provide a stable stack key");
43
+ const noIdStack = groupConsecutiveWorkflowStatusItems([
44
+ { ...statusItem("call-1"), messageIndex: 0, message: { ...statusItem("call-1").message, toolCallId: "" } },
45
+ { ...statusItem("call-2"), messageIndex: 1, message: { ...statusItem("call-2").message, toolCallId: "" } },
46
+ ]);
47
+ assert.equal(noIdStack[0].transcriptKey, "workflow-status-stack:m:0", "zero-valued message indices should remain valid collision-resistant fallback keys");
48
+
49
+ const barrier = { messageIndex: 2, order: 2, message: { role: "user", content: "continue" } };
50
+ const separated = groupConsecutiveWorkflowStatusItems([statusItem("call-1"), barrier, statusItem("call-2")]);
51
+ assert.equal(separated.length, 3, "non-status transcript items should break a stack");
52
+ assert.deepEqual(separated.map((item) => item.message.role), ["toolExecution", "user", "toolExecution"]);
53
+
54
+ const withLiveBoundary = groupConsecutiveWorkflowStatusItems([
55
+ statusItem("call-1"),
56
+ statusItem("call-2", "running", { isPartial: true }),
57
+ statusItem("call-3"),
58
+ ]);
59
+ assert.equal(withLiveBoundary.length, 3, "a live status update should be a hard stack boundary");
60
+
61
+ const errored = groupConsecutiveWorkflowStatusItems([
62
+ statusItem("call-1"),
63
+ statusItem("call-2", "failed", { isError: true, result: { isError: true, content: [{ type: "text", text: "Status: failed" }] } }),
64
+ ]);
65
+ assert.equal(errored[0].message.isError, true, "a member error should mark the aggregate stack");
66
+
67
+ assert.deepEqual(
68
+ workflowStatusSnapshot("Workflow: release\nRun: run-1\nStatus: completed\nTasks: 3/3 completed"),
69
+ { workflow: "release", run: "run-1", status: "completed", tasks: "3/3 completed", fallback: "Workflow: release" },
70
+ "the latest workflow result should produce a concise structured snapshot",
71
+ );
72
+ assert.equal(workflowStatusSnapshot("No workflow run has been recorded in this session.").fallback, "No workflow run has been recorded in this session.");
73
+
74
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
75
+ const [app, css] = await Promise.all([
76
+ readFile(join(root, "public", "app.js"), "utf8"),
77
+ readFile(join(root, "public", "styles.css"), "utf8"),
78
+ ]);
79
+ assert.match(app, /function workflowStatusExecutionFromTranscriptItem\(item, toolResults\)[\s\S]*visibleMessages\.length !== 1[\s\S]*toolCall\.toolName !== "workflow_status"[\s\S]*toolResults instanceof Map[\s\S]*toolExecutionMessageFromCall/, "app integration should project only isolated, completed workflow_status calls using the prebuilt result map");
80
+ assert.match(app, /function groupWorkflowStatusTranscriptItems\(items, toolResults\)[\s\S]*compactOutputActive\(\)[\s\S]*groupConsecutiveWorkflowStatusItems\(projected\)/, "compact mode should remain unchanged and normal transcript items should group before reconciliation");
81
+ assert.match(app, /function toolExecutionMessageFromCall\([\s\S]*function appendTranscriptMessage[\s\S]*toolExecutionMessageFromCall\(displayMessage\)/, "normal and stacked transcript paths should share tool-call projection");
82
+ assert.match(app, /function renderWorkflowStatusStack\(parent, message\)[\s\S]*snapshotFields[\s\S]*make\("details", "workflow-status-stack-details"\)[\s\S]*make\("summary", "workflow-status-stack-summary"\)[\s\S]*aria-label[\s\S]*renderSingleToolExecution\(memberBody, update\)/, "the stack should use an accessible native disclosure and retain the normal renderer for every member");
83
+ assert.doesNotMatch(app.match(/function renderWorkflowStatusStack\(parent, message\)[\s\S]*?\n\}/)?.[0] || "", /aria-live/, "historical status stacks should not create repetitive live-region announcements");
84
+ assert.match(css, /\.workflow-status-stack-summary:focus-visible[\s\S]*outline:/, "the stack disclosure should expose keyboard focus");
85
+ assert.match(css, /\.workflow-status-stack-members[\s\S]*max-height:[\s\S]*overflow:\s*auto/, "expanded status history should remain bounded and scrollable");
86
+
87
+ console.log("workflow-status-stack.test.mjs passed");
@@ -22,6 +22,19 @@ const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
22
22
  const SUBAGENT_RPC_REPLY_PREFIX = "subagents:rpc:v1:reply:";
23
23
  const SUBAGENT_ASYNC_STARTED_EVENT = "subagent:async-started";
24
24
  const SUBAGENT_ASYNC_COMPLETE_EVENT = "subagent:async-complete";
25
+ const WORKFLOW_SUBAGENTS_EVENT = "firstpick:workflow-subagents:v1";
26
+ const WORKFLOW_SUBAGENTS_VERSION = 1;
27
+ const WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS = {
28
+ runs: 32,
29
+ agentsPerRun: 32,
30
+ runIdentifierLength: 160,
31
+ agentIdentifierLength: 240,
32
+ nameLength: 160,
33
+ activityLength: 80,
34
+ modelLength: 240,
35
+ recentOutputLines: 8,
36
+ recentOutputLineLength: 500,
37
+ };
25
38
  const SUBAGENT_STATUS_POLL_MS = 1500;
26
39
  const SUBAGENT_STATUS_RPC_TIMEOUT_MS = 900;
27
40
  const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
@@ -239,7 +252,9 @@ function subagentAgentName(value) {
239
252
  }
240
253
 
241
254
  function subagentAgentFromDisplay(value) {
242
- const display = subagentText(value, 240).replace(/^\[[^\]]+\]\s*/, "");
255
+ const display = subagentText(value, 240)
256
+ .replace(/^\[[^\]]+\]\s*/, "")
257
+ .replace(/\s+\[(?:fork|fresh|mixed)\]$/i, "");
243
258
  const labeled = display.match(/\(([^()]*)\)$/);
244
259
  return subagentAgentName(labeled?.[1] || display);
245
260
  }
@@ -255,6 +270,76 @@ function subagentOutputLines(value) {
255
270
  .map((line) => String(line ?? "").replace(/\r/g, "").slice(0, SUBAGENT_OUTPUT_LINE_LENGTH));
256
271
  }
257
272
 
273
+ function workflowSubagentText(value, maxLength) {
274
+ return typeof value === "string" ? value.slice(0, maxLength).replace(/\r/g, "") : "";
275
+ }
276
+
277
+ function workflowSubagentIdentifier(value, maxLength) {
278
+ if (typeof value !== "string" || !value.trim() || value.length > maxLength) return "";
279
+ return value;
280
+ }
281
+
282
+ function workflowSubagentTimestamp(value) {
283
+ if (typeof value !== "string" || value.length > 128) return undefined;
284
+ const timestamp = Date.parse(value);
285
+ return Number.isFinite(timestamp) ? timestamp : undefined;
286
+ }
287
+
288
+ function workflowSubagentRun(value, updatedAt) {
289
+ if (!value || typeof value !== "object" || value.source !== "workflow") return undefined;
290
+ const id = workflowSubagentIdentifier(value.id, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.runIdentifierLength);
291
+ const name = workflowSubagentText(value.name, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.nameLength).trim();
292
+ const startedAt = workflowSubagentTimestamp(value.startedAt);
293
+ if (!id || !name || startedAt === undefined || typeof value.status !== "string") return undefined;
294
+
295
+ const agents = [];
296
+ const agentIds = new Set();
297
+ for (const [fallbackIndex, agent] of (Array.isArray(value.agents) ? value.agents : []).slice(0, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.agentsPerRun).entries()) {
298
+ if (!agent || typeof agent !== "object" || agent.status !== "running") continue;
299
+ const agentId = workflowSubagentIdentifier(agent.id, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.agentIdentifierLength);
300
+ const agentName = workflowSubagentText(agent.name, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.nameLength).trim();
301
+ if (!agentId || !agentName || agentIds.has(agentId)) continue;
302
+ agentIds.add(agentId);
303
+ const recentOutput = (Array.isArray(agent.recentOutput) ? agent.recentOutput : [])
304
+ .slice(-WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.recentOutputLines)
305
+ .flatMap((line) => typeof line === "string"
306
+ ? [workflowSubagentText(line, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.recentOutputLineLength)]
307
+ : []);
308
+ agents.push({
309
+ id: agentId,
310
+ name: agentName,
311
+ status: "running",
312
+ index: Number.isInteger(agent.index) && agent.index >= 0 ? agent.index : fallbackIndex,
313
+ activityState: workflowSubagentText(agent.activityState, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.activityLength).trim() || undefined,
314
+ model: workflowSubagentText(agent.model, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.modelLength).trim() || undefined,
315
+ recentOutput,
316
+ nested: false,
317
+ });
318
+ }
319
+
320
+ return {
321
+ id,
322
+ source: "workflow",
323
+ name,
324
+ mode: agents.length > 1 ? "parallel" : "single",
325
+ status: "running",
326
+ startedAt,
327
+ updatedAt,
328
+ agents,
329
+ };
330
+ }
331
+
332
+ function workflowSubagentSnapshot(value) {
333
+ if (!value || typeof value !== "object" || value.version !== WORKFLOW_SUBAGENTS_VERSION || !Array.isArray(value.runs)) return undefined;
334
+ const updatedAt = workflowSubagentTimestamp(value.updatedAt) || Date.now();
335
+ const runs = new Map();
336
+ for (const candidate of value.runs.slice(0, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.runs)) {
337
+ const run = workflowSubagentRun(candidate, updatedAt);
338
+ if (run) runs.set(run.id, run);
339
+ }
340
+ return runs;
341
+ }
342
+
258
343
  function subagentRecentTools(value) {
259
344
  return (Array.isArray(value) ? value : []).slice(-20).map((entry) => ({
260
345
  tool: subagentText(entry?.tool, 120),
@@ -490,7 +575,7 @@ function parseSubagentStatusText(text, previousRuns = new Map()) {
490
575
  if (runMatch) {
491
576
  const id = subagentText(runMatch[1], 160);
492
577
  const segments = rawLine.split(" | ").map((part) => part.trim());
493
- const mode = segments.find((part) => ["single", "parallel", "chain"].includes(part));
578
+ const mode = segments.map((part) => part.match(/^(single|parallel|chain)\b/)?.[1]).find(Boolean);
494
579
  const previous = previousRuns.get(id);
495
580
  current = {
496
581
  id,
@@ -554,10 +639,11 @@ export default function webuiRpcHelper(pi) {
554
639
  let lastPublishedSubagentSignature = "";
555
640
  const asyncSubagentRuns = new Map();
556
641
  const foregroundSubagentRuns = new Map();
642
+ const workflowSubagentRuns = new Map();
557
643
  const subagentGates = new Map();
558
644
 
559
645
  function publicSubagentRuns() {
560
- return [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()]
646
+ const ordinaryRuns = [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()]
561
647
  .map((run) => ({
562
648
  id: subagentText(run.id, 160),
563
649
  source: run.source === "foreground" ? "foreground" : "async",
@@ -578,7 +664,28 @@ export default function webuiRpcHelper(pi) {
578
664
  thinking: subagentThinking(agent.thinking) || subagentThinkingFromModel(agent.model) || undefined,
579
665
  nested: agent.nested === true,
580
666
  })),
581
- }))
667
+ }));
668
+ const workflowRuns = [...workflowSubagentRuns.values()]
669
+ .map((run) => ({
670
+ id: run.id,
671
+ source: "workflow",
672
+ name: run.name,
673
+ mode: subagentMode(run.mode),
674
+ status: "running",
675
+ startedAt: run.startedAt,
676
+ agents: run.agents.map((agent) => ({
677
+ id: agent.id,
678
+ name: agent.name,
679
+ status: "running",
680
+ index: agent.index,
681
+ activityState: agent.activityState,
682
+ model: agent.model,
683
+ // Workflow snapshots do not publish thinking metadata, so unknown must remain unknown.
684
+ thinking: undefined,
685
+ nested: false,
686
+ })),
687
+ }));
688
+ return [...ordinaryRuns, ...workflowRuns]
582
689
  .filter((run) => run.id && run.agents.length > 0)
583
690
  .sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
584
691
  }
@@ -667,6 +774,39 @@ export default function webuiRpcHelper(pi) {
667
774
  return { run, agent };
668
775
  }
669
776
 
777
+ function findWorkflowSubagent(runId, agentId) {
778
+ const run = workflowSubagentRuns.get(runId);
779
+ if (!run) return undefined;
780
+ const agent = run.agents.find((candidate) => candidate.id === agentId);
781
+ if (!agent) throw new Error(`Running subagent not found: ${agentId}`);
782
+ return { run, agent };
783
+ }
784
+
785
+ function workflowSubagentOutputSnapshot(run, agent) {
786
+ return {
787
+ version: 1,
788
+ runId: run.id,
789
+ source: "workflow",
790
+ mode: subagentMode(run.mode),
791
+ startedAt: run.startedAt,
792
+ updatedAt: run.updatedAt,
793
+ agent: {
794
+ id: agent.id,
795
+ name: agent.name,
796
+ index: agent.index,
797
+ nested: false,
798
+ status: "running",
799
+ activityState: agent.activityState,
800
+ model: agent.model,
801
+ // Workflow snapshots do not carry reasoning data.
802
+ thinking: undefined,
803
+ recentTools: [],
804
+ recentOutput: agent.recentOutput,
805
+ transcript: [],
806
+ },
807
+ };
808
+ }
809
+
670
810
  function subagentAsyncDirFromStatusText(text) {
671
811
  const match = String(text || "").match(/^Dir:\s+(.+)$/m);
672
812
  const value = String(match?.[1] || "").trim();
@@ -750,6 +890,13 @@ export default function webuiRpcHelper(pi) {
750
890
  }
751
891
 
752
892
  async function subagentOutputSnapshot(payload = {}) {
893
+ const workflowRunId = workflowSubagentIdentifier(payload.runId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.runIdentifierLength);
894
+ const workflowAgentId = workflowSubagentIdentifier(payload.agentId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.agentIdentifierLength);
895
+ if (workflowRunId && workflowAgentId) {
896
+ const workflow = findWorkflowSubagent(workflowRunId, workflowAgentId);
897
+ if (workflow) return workflowSubagentOutputSnapshot(workflow.run, workflow.agent);
898
+ }
899
+
753
900
  const runId = subagentText(payload.runId, 160);
754
901
  const agentId = subagentText(payload.agentId, 240);
755
902
  if (!runId || !agentId) throw new Error("Subagent output requires runId and agentId");
@@ -834,6 +981,17 @@ export default function webuiRpcHelper(pi) {
834
981
  }
835
982
 
836
983
  const subagentEventUnsubscribers = [
984
+ pi.events.on(WORKFLOW_SUBAGENTS_EVENT, (value) => {
985
+ try {
986
+ const nextRuns = workflowSubagentSnapshot(value);
987
+ if (!nextRuns) return;
988
+ workflowSubagentRuns.clear();
989
+ for (const [id, run] of nextRuns) workflowSubagentRuns.set(id, run);
990
+ publishSubagentStatus();
991
+ } catch {
992
+ // Ignore malformed cross-extension events without disrupting current live rows.
993
+ }
994
+ }),
837
995
  pi.events.on(SUBAGENT_RPC_READY_EVENT, () => {
838
996
  subagentBridgeAvailable = true;
839
997
  publishSubagentStatus();
@@ -1076,6 +1234,7 @@ export default function webuiRpcHelper(pi) {
1076
1234
  subagentPollGeneration += 1;
1077
1235
  foregroundSubagentRuns.clear();
1078
1236
  asyncSubagentRuns.clear();
1237
+ workflowSubagentRuns.clear();
1079
1238
  subagentGates.clear();
1080
1239
  lastPublishedSubagentSignature = "";
1081
1240
  publishSubagentStatus();
@@ -1153,6 +1312,7 @@ export default function webuiRpcHelper(pi) {
1153
1312
  subagentPollTimer = null;
1154
1313
  foregroundSubagentRuns.clear();
1155
1314
  asyncSubagentRuns.clear();
1315
+ workflowSubagentRuns.clear();
1156
1316
  subagentGates.clear();
1157
1317
  for (const unsubscribe of subagentEventUnsubscribers) unsubscribe();
1158
1318
  });