@firstpick/pi-package-webui 0.9.1 → 0.9.3

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 (107) hide show
  1. package/README.md +31 -9
  2. package/bin/pi-webui-launcher.mjs +23 -12
  3. package/bin/pi-webui.mjs +729 -93
  4. package/index.ts +266 -1
  5. package/lib/agent-run-adapters.mjs +500 -0
  6. package/lib/agent-run-protocol.mjs +262 -0
  7. package/lib/agent-run-registry.mjs +339 -0
  8. package/lib/git-workflow-preferences.mjs +18 -28
  9. package/lib/intercom-conversations.mjs +491 -0
  10. package/lib/intercom-transcript-filter.mjs +99 -0
  11. package/lib/resource-selection.mjs +140 -0
  12. package/lib/trust-boundaries.mjs +2 -0
  13. package/lib/ui-layout-settings.mjs +172 -28
  14. package/lib/update/package-layout.mjs +50 -0
  15. package/lib/update/plan.mjs +11 -0
  16. package/package.json +2 -2
  17. package/public/app.js +2276 -419
  18. package/public/index.html +142 -72
  19. package/public/service-worker.js +2 -1
  20. package/public/stream-output-controller.mjs +15 -0
  21. package/public/styles.css +764 -92
  22. package/public/syntax-highlight.mjs +622 -0
  23. package/tests/agent-run-adapters.test.mjs +217 -0
  24. package/tests/agent-run-launcher.test.mjs +41 -0
  25. package/tests/agent-run-protocol.test.mjs +82 -0
  26. package/tests/agent-run-registry.test.mjs +102 -0
  27. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  28. package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
  29. package/tests/browser/controls-layout.spec.mjs +122 -0
  30. package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
  31. package/tests/browser/interaction-continuity.spec.mjs +161 -0
  32. package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
  33. package/tests/browser/mobile-foundation.spec.mjs +26 -0
  34. package/tests/browser/model-search-focus.spec.mjs +96 -0
  35. package/tests/browser/optimistic-prompt.spec.mjs +22 -0
  36. package/tests/browser/persistent-ui-layout.spec.mjs +285 -66
  37. package/tests/browser/resource-profiles.spec.mjs +200 -0
  38. package/tests/browser/subagent-observability.spec.mjs +116 -0
  39. package/tests/codex-fast-mode-static.test.mjs +7 -6
  40. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  41. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  42. package/tests/component-update-api-static.test.mjs +2 -1
  43. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  44. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  45. package/tests/control-deck-component-updates-static.test.mjs +6 -0
  46. package/tests/control-deck-side-panels-static.test.mjs +68 -0
  47. package/tests/controls-layout-static.test.mjs +22 -0
  48. package/tests/fast-mode-client-static.test.mjs +2 -2
  49. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  50. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  51. package/tests/file-tree-git-ignored-static.test.mjs +152 -0
  52. package/tests/file-tree-search-layout-static.test.mjs +2 -1
  53. package/tests/file-viewer-image-static.test.mjs +69 -0
  54. package/tests/fixtures/fake-pi.mjs +147 -12
  55. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  56. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  57. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  58. package/tests/git-workflow-preferences.test.mjs +55 -6
  59. package/tests/http-endpoints-harness.test.mjs +295 -14
  60. package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
  61. package/tests/intercom-conversations-http.test.mjs +252 -0
  62. package/tests/intercom-conversations.test.mjs +374 -0
  63. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  64. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  65. package/tests/intercom-transcript-filter.test.mjs +98 -0
  66. package/tests/main-output-loading-static.test.mjs +59 -0
  67. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  68. package/tests/mobile-compact-layout.test.mjs +2 -3
  69. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  70. package/tests/mobile-foundation-static.test.mjs +3 -3
  71. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  72. package/tests/mobile-static.test.mjs +76 -42
  73. package/tests/native-parity.test.mjs +8 -7
  74. package/tests/open-issue-wizard-static.test.mjs +2 -2
  75. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  76. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  77. package/tests/persistent-ui-layout-static.test.mjs +13 -13
  78. package/tests/questionnaire-dialog.test.mjs +3 -3
  79. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  80. package/tests/resource-defaults-helper.test.mjs +60 -6
  81. package/tests/resource-selection.test.mjs +114 -0
  82. package/tests/resource-tui-extension.test.mjs +23 -0
  83. package/tests/session-sampling-ui-static.test.mjs +3 -3
  84. package/tests/side-panel-context-menu-static.test.mjs +1 -1
  85. package/tests/side-panel-resize-static.test.mjs +26 -16
  86. package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
  87. package/tests/side-panel-section-reorder-static.test.mjs +16 -70
  88. package/tests/stream-output-controller.test.mjs +8 -0
  89. package/tests/stream-output-isolation-static.test.mjs +2 -2
  90. package/tests/streaming-ui-coupling.test.mjs +5 -0
  91. package/tests/subagent-gate-visibility.test.mjs +2 -1
  92. package/tests/subagent-launch-slots.test.mjs +1 -1
  93. package/tests/subagent-observability-static.test.mjs +32 -0
  94. package/tests/subagent-reliability-integration.test.mjs +183 -0
  95. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  96. package/tests/subagents-helper.test.mjs +548 -5
  97. package/tests/syntax-highlight.test.mjs +235 -0
  98. package/tests/syntax-highlighting-static.test.mjs +84 -0
  99. package/tests/terminal-tabs-resize-static.test.mjs +35 -0
  100. package/tests/theme-customizer-static.test.mjs +5 -5
  101. package/tests/thinking-format-parser.test.mjs +64 -0
  102. package/tests/ui-layout-settings.test.mjs +104 -32
  103. package/tests/update-api-harness.test.mjs +24 -10
  104. package/tests/update-package-layout.test.mjs +38 -0
  105. package/tests/update-plan.test.mjs +11 -1
  106. package/tests/webui-settings-locking.test.mjs +33 -3
  107. package/webui-rpc-helper.mjs +700 -89
@@ -36,6 +36,7 @@ let branchEntries = [];
36
36
  let idle = true;
37
37
  let subagentStatusRequestCount = 0;
38
38
  let subagentRpcReplyHook = null;
39
+ let setStatusFailures = 0;
39
40
  const pi = {
40
41
  events: bus,
41
42
  on(name, handler) {
@@ -77,6 +78,10 @@ const ctx = {
77
78
  },
78
79
  ui: {
79
80
  setStatus(key, text) {
81
+ if (setStatusFailures > 0) {
82
+ setStatusFailures -= 1;
83
+ throw new Error("simulated status delivery failure");
84
+ }
80
85
  statuses.push({ key, text });
81
86
  },
82
87
  notify(message, type) {
@@ -116,6 +121,21 @@ await writeFile(asyncStatusFile, JSON.stringify({
116
121
  { agent: "reviewer", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" },
117
122
  ],
118
123
  }));
124
+ const gateAsyncRunDir = await mkdtemp(path.join(asyncRunDir, "gate-"));
125
+ const gateSessionFile = path.join(gateAsyncRunDir, "scout-session.jsonl");
126
+ await writeFile(gateSessionFile, `${JSON.stringify({
127
+ type: "message",
128
+ timestamp: "2026-07-19T12:00:10.000Z",
129
+ message: { role: "assistant", content: [{ type: "text", text: "Gate child output is live." }] },
130
+ })}\n`);
131
+ await writeFile(path.join(gateAsyncRunDir, "status.json"), JSON.stringify({
132
+ runId: "recovered-gate-run",
133
+ mode: "single",
134
+ state: "running",
135
+ startedAt: Date.now() - 500,
136
+ lastUpdate: Date.now(),
137
+ steps: [{ agent: "scout", status: "running", sessionFile: gateSessionFile, currentTool: "read", model: "openai-codex/gpt-5.6-terra:xhigh", thinking: "xhigh" }],
138
+ }));
119
139
 
120
140
  const statusText = `Active async runs: 2
121
141
 
@@ -134,8 +154,10 @@ const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
134
154
  subagentStatusRequestCount += 1;
135
155
  const text = request.params?.id === "run-a"
136
156
  ? `Run: run-a\nState: running\nMode: parallel\nDir: ${asyncRunDir}`
137
- : statusText;
138
- subagentRpcReplyHook?.(request);
157
+ : request.params?.id === "recovered-gate-run"
158
+ ? `Run: recovered-gate-run\nState: running\nMode: single\nDir: ${gateAsyncRunDir}`
159
+ : statusText;
160
+ if (subagentRpcReplyHook?.(request) === true) return;
139
161
  bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
140
162
  version: 1,
141
163
  requestId: request.requestId,
@@ -184,6 +206,18 @@ function latestPayload() {
184
206
  return JSON.parse(entry.text.slice("PI_WEBUI_SUBAGENTS_V1 ".length));
185
207
  }
186
208
 
209
+ /** v1 delivery accounting must stay independent of the separate canonical v2 status key. */
210
+ function legacyStatusCount() {
211
+ return statuses.filter((item) => item.key === "webui-subagents").length;
212
+ }
213
+
214
+ function latestCanonicalPayload() {
215
+ const entry = statuses.filter((item) => item.key === "webui-subagents-v2").at(-1);
216
+ assert.ok(entry, "helper should publish the canonical WebUI agent-run status");
217
+ assert.match(entry.text, /^PI_WEBUI_SUBAGENTS_V2 /);
218
+ return JSON.parse(entry.text.slice("PI_WEBUI_SUBAGENTS_V2 ".length));
219
+ }
220
+
187
221
  function helperResponse(requestId) {
188
222
  const notice = notifications.findLast((entry) => entry.message.startsWith("__PI_WEBUI_HELPER_RESPONSE__:")
189
223
  && JSON.parse(entry.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length)).requestId === requestId);
@@ -199,6 +233,109 @@ assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.name, agent.curren
199
233
  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");
200
234
  assert.deepEqual(payload.runs[1].agents.map((agent) => [agent.name, agent.nested]), [["worker", false], ["nested-oracle", true]]);
201
235
 
236
+ const fleetStartedAt = Date.now() - 500;
237
+ subagentRpcReplyHook = (request) => {
238
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
239
+ subagentRpcReplyHook = null;
240
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
241
+ version: 1,
242
+ requestId: request.requestId,
243
+ method: request.method,
244
+ success: true,
245
+ data: {
246
+ text: statusText,
247
+ details: { mode: "single", results: [] },
248
+ fleet: {
249
+ version: 1,
250
+ entries: [
251
+ { key: "fleet-reviewer-1", agent: "reviewer", startedAt: fleetStartedAt, tokens: { input: 0, output: 0, total: 0 } },
252
+ { key: "fleet-reviewer-2", agent: "reviewer", startedAt: fleetStartedAt + 1, tokens: { input: 0, output: 0, total: 0 } },
253
+ { key: "fleet-worker", agent: "worker", startedAt: fleetStartedAt + 2, tokens: { input: 0, output: 0, total: 0 } },
254
+ { key: "fleet-nested", agent: "nested-oracle", startedAt: fleetStartedAt + 3, tokens: { input: 0, output: 0, total: 0 } },
255
+ { key: "fleet-recovered", agent: "scout", role: "Recovery scout", model: "openai-codex/gpt-5.6-terra:xhigh", effort: "xhigh", startedAt: fleetStartedAt + 4, tokens: { input: 0, output: 0, total: 0 } },
256
+ ],
257
+ totalActive: 5,
258
+ omitted: 0,
259
+ },
260
+ },
261
+ });
262
+ return true;
263
+ };
264
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
265
+ await new Promise((resolve) => setTimeout(resolve, 0));
266
+ payload = latestPayload();
267
+ assert.equal(payload.runs.filter((run) => run.id === "run-a").length, 1, "fleet recovery must not duplicate a text-parsed run");
268
+ assert.equal(payload.runs.find((run) => run.id === "run-a")?.agents.length, 2, "fleet recovery must match repeated same-role children one-to-one");
269
+ const recoveredFleetRun = payload.runs.find((run) => run.id === "fleet:fleet-recovered");
270
+ assert.deepEqual(recoveredFleetRun && {
271
+ source: recoveredFleetRun.source,
272
+ provisional: recoveredFleetRun.provisional,
273
+ controllable: recoveredFleetRun.controllable,
274
+ agents: recoveredFleetRun.agents.map((agent) => [agent.name, agent.model, agent.thinking]),
275
+ }, {
276
+ source: "recovered",
277
+ provisional: true,
278
+ controllable: false,
279
+ agents: [["Recovery scout", "openai-codex/gpt-5.6-terra:xhigh", "xhigh"]],
280
+ }, "unmatched authoritative fleet children should publish a bounded non-controllable provisional row");
281
+ const recoveredCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "fleet:fleet-recovered");
282
+ assert.deepEqual(recoveredCanonical && {
283
+ open: recoveredCanonical.capabilities.open,
284
+ refresh: recoveredCanonical.capabilities.refresh,
285
+ cancel: recoveredCanonical.capabilities.cancel,
286
+ outputKind: recoveredCanonical.outputRef.kind,
287
+ }, { open: true, refresh: true, cancel: false, outputKind: "helper" }, "recovered pi-subagents rows should expose a read-only helper-owned output view without lifecycle controls");
288
+ assert.deepEqual(payload.fleet, { version: 1, totalActive: 5, omitted: 0 }, "fleet recovery should publish only bounded aggregate recovery metadata");
289
+
290
+ subagentRpcReplyHook = (request) => {
291
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
292
+ subagentRpcReplyHook = null;
293
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
294
+ version: 1,
295
+ requestId: request.requestId,
296
+ method: request.method,
297
+ success: true,
298
+ data: {
299
+ text: statusText,
300
+ details: { mode: "single", results: [] },
301
+ fleet: { version: 1, entries: "malformed", totalActive: 99, omitted: 99 },
302
+ },
303
+ });
304
+ return true;
305
+ };
306
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
307
+ await new Promise((resolve) => setTimeout(resolve, 0));
308
+ payload = latestPayload();
309
+ assert.equal("fleet" in payload, false, "a successful poll with malformed fleet data should clear stale aggregate metadata");
310
+ assert.ok(payload.runs.some((run) => run.id === "fleet:fleet-recovered" && run.status === "running"), "malformed fleet data must not prune or finish a previously recovered live row");
311
+
312
+ const retryGate = {
313
+ version: 1,
314
+ id: "gate-delivery-retry",
315
+ status: "running",
316
+ requiredSuccesses: 1,
317
+ qualifyingSuccesses: 0,
318
+ requireDistinctProviders: false,
319
+ startedAt: Date.now(),
320
+ updatedAt: Date.now(),
321
+ attempts: [],
322
+ };
323
+ const statusesBeforeFailedDelivery = legacyStatusCount();
324
+ setStatusFailures = 1;
325
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
326
+ assert.equal(legacyStatusCount(), statusesBeforeFailedDelivery, "a failed setStatus delivery should not appear successful");
327
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
328
+ assert.equal(legacyStatusCount(), statusesBeforeFailedDelivery + 1, "an unchanged snapshot should retry after setStatus throws");
329
+ const statusesBeforeHeartbeat = legacyStatusCount();
330
+ const realDateNow = Date.now;
331
+ Date.now = () => realDateNow() + 16_000;
332
+ try {
333
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
334
+ } finally {
335
+ Date.now = realDateNow;
336
+ }
337
+ assert.equal(legacyStatusCount(), statusesBeforeHeartbeat + 1, "an unchanged snapshot should republish after the bounded heartbeat interval");
338
+
202
339
  bus.emit("webui:subagent-gate:v1:update", {
203
340
  version: 1,
204
341
  id: "gate-a",
@@ -214,9 +351,10 @@ bus.emit("webui:subagent-gate:v1:update", {
214
351
  ],
215
352
  });
216
353
  payload = latestPayload();
217
- assert.equal(payload.gates.length, 1, "helper should publish retry gate lifecycle alongside running children");
218
- assert.equal(payload.gates[0].qualifyingSuccesses, 1);
219
- assert.deepEqual(payload.gates[0].attempts.map((attempt) => [attempt.status, attempt.failureKind]), [["succeeded", undefined], ["failed", "transient-provider"]]);
354
+ assert.equal(payload.gates.length, 2, "helper should publish retry gate lifecycle alongside running children");
355
+ const publishedGate = payload.gates.find((gate) => gate.id === "gate-a");
356
+ assert.equal(publishedGate?.qualifyingSuccesses, 1);
357
+ assert.deepEqual(publishedGate?.attempts.map((attempt) => [attempt.status, attempt.failureKind]), [["succeeded", undefined], ["failed", "transient-provider"]]);
220
358
 
221
359
  const workflowRunId = "workflow:run-42";
222
360
  const workflowAgentId = "workflow:run-42:phase:implement:call:call-0123456789abcdef";
@@ -241,6 +379,9 @@ const workflowSnapshot = {
241
379
  }],
242
380
  };
243
381
  bus.emit("firstpick:workflow-subagents:v1", workflowSnapshot);
382
+ const canonicalPublishesAfterWorkflow = statuses.filter((item) => item.key === "webui-subagents-v2").length;
383
+ bus.emit("firstpick:workflow-subagents:v1", workflowSnapshot);
384
+ assert.equal(statuses.filter((item) => item.key === "webui-subagents-v2").length, canonicalPublishesAfterWorkflow, "unchanged active snapshots must respect the bounded canonical publish heartbeat");
244
385
  payload = latestPayload();
245
386
  const workflowRun = payload.runs.find((run) => run.id === workflowRunId);
246
387
  assert.deepEqual(workflowRun && {
@@ -265,6 +406,142 @@ assert.ok(payload.runs.some((run) => run.id === workflowRunId), "pi-subagents po
265
406
 
266
407
  const helperCommand = registeredCommands.get("webui-helper");
267
408
  assert.ok(helperCommand?.handler, "Web UI helper command should be registered");
409
+ await helperCommand.handler(JSON.stringify({
410
+ requestId: "recovered-subagent-output-test",
411
+ action: "subagent-output",
412
+ payload: { outputId: recoveredCanonical.outputRef.id },
413
+ }), ctx);
414
+ const recoveredOutputResponse = helperResponse("recovered-subagent-output-test");
415
+ assert.equal(recoveredOutputResponse.ok, true, "a recovered fleet row should open through its opaque helper handle");
416
+ assert.equal(recoveredOutputResponse.data.source, "recovered");
417
+ assert.equal(recoveredOutputResponse.data.agent.unavailable, true);
418
+ assert.match(recoveredOutputResponse.data.agent.unavailableReason, /recovered from aggregate fleet metadata/, "the read-only recovered view should explain why detailed output is not yet available");
419
+
420
+ for (const handler of extensionHandlers.get("tool_execution_update") || []) {
421
+ handler({
422
+ type: "tool_execution_update",
423
+ toolCallId: "recovered-foreground-call",
424
+ toolName: "subagent",
425
+ partialResult: {
426
+ details: {
427
+ runId: "recovered-foreground-run",
428
+ mode: "single",
429
+ progress: [{
430
+ index: 0,
431
+ agent: "scout",
432
+ status: "running",
433
+ currentTool: "read",
434
+ recentOutput: ["Recovered child output is live again"],
435
+ }],
436
+ },
437
+ },
438
+ }, ctx);
439
+ }
440
+ payload = latestPayload();
441
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-recovered"), false, "a recovered fleet placeholder should be replaced when its live tool update arrives");
442
+ const recoveredForegroundRun = payload.runs.find((run) => run.id === "recovered-foreground-run");
443
+ assert.deepEqual(recoveredForegroundRun && {
444
+ source: recoveredForegroundRun.source,
445
+ controllable: recoveredForegroundRun.controllable,
446
+ agents: recoveredForegroundRun.agents.map((agent) => [agent.name, agent.model, agent.thinking]),
447
+ }, {
448
+ source: "foreground",
449
+ controllable: undefined,
450
+ agents: [["scout", "openai-codex/gpt-5.6-terra:xhigh", "xhigh"]],
451
+ }, "a live update without a preceding start event should promote recovered metadata into a normal foreground run even when the fleet display role differs from the agent identity");
452
+ const recoveredForegroundCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "recovered-foreground-run");
453
+ await helperCommand.handler(JSON.stringify({
454
+ requestId: "recovered-foreground-live-output-test",
455
+ action: "subagent-output",
456
+ payload: { outputId: recoveredForegroundCanonical.outputRef.id },
457
+ }), ctx);
458
+ const recoveredForegroundOutput = helperResponse("recovered-foreground-live-output-test");
459
+ assert.equal(recoveredForegroundOutput.ok, true);
460
+ assert.equal(recoveredForegroundOutput.data.source, "foreground");
461
+ assert.equal(recoveredForegroundOutput.data.agent.unavailable, undefined);
462
+ assert.deepEqual(recoveredForegroundOutput.data.agent.recentOutput, ["Recovered child output is live again"], "promoted recovered runs should expose subsequent live output");
463
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
464
+ handler({ type: "tool_execution_end", toolCallId: "recovered-foreground-call", toolName: "subagent" }, ctx);
465
+ }
466
+ await helperCommand.handler(JSON.stringify({
467
+ requestId: "dismiss-recovered-foreground-run",
468
+ action: "subagent-dismiss",
469
+ payload: { runId: "recovered-foreground-run" },
470
+ }), ctx);
471
+ assert.equal(helperResponse("dismiss-recovered-foreground-run").ok, true, "a promoted recovered run should follow the normal foreground completion lifecycle");
472
+
473
+ const gateRecoveredStartedAt = Date.now() - 500;
474
+ subagentRpcReplyHook = (request) => {
475
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
476
+ subagentRpcReplyHook = null;
477
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
478
+ version: 1,
479
+ requestId: request.requestId,
480
+ method: request.method,
481
+ success: true,
482
+ data: {
483
+ text: statusText,
484
+ details: { mode: "single", results: [] },
485
+ fleet: {
486
+ version: 1,
487
+ entries: [{
488
+ key: "fleet-gate-recovered",
489
+ agent: "scout",
490
+ role: "Gate recovery scout",
491
+ model: "openai-codex/gpt-5.6-terra:xhigh",
492
+ effort: "xhigh",
493
+ startedAt: gateRecoveredStartedAt,
494
+ tokens: { input: 0, output: 0, total: 0 },
495
+ }],
496
+ totalActive: 1,
497
+ omitted: 0,
498
+ },
499
+ },
500
+ });
501
+ return true;
502
+ };
503
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
504
+ await new Promise((resolve) => setTimeout(resolve, 0));
505
+ assert.ok(latestPayload().runs.some((run) => run.id === "fleet:fleet-gate-recovered"), "an unmatched gate child should begin as an aggregate fleet placeholder");
506
+ bus.emit("webui:subagent-gate:v1:update", {
507
+ version: 1,
508
+ id: "gate-live-output",
509
+ status: "running",
510
+ requiredSuccesses: 1,
511
+ qualifyingSuccesses: 0,
512
+ requireDistinctProviders: false,
513
+ startedAt: gateRecoveredStartedAt,
514
+ updatedAt: Date.now(),
515
+ attempts: [{
516
+ id: "gate-live-output:0:1",
517
+ taskIndex: 0,
518
+ attempt: 1,
519
+ maxAttempts: 1,
520
+ agent: "scout",
521
+ label: "Gate recovery scout",
522
+ retrySafety: "read-only",
523
+ runId: "recovered-gate-run",
524
+ model: "openai-codex/gpt-5.6-terra:xhigh",
525
+ provider: "openai-codex",
526
+ status: "running",
527
+ startedAt: gateRecoveredStartedAt,
528
+ }],
529
+ });
530
+ assert.equal(latestPayload().runs.some((run) => run.id === "fleet:fleet-gate-recovered"), false, "a running gate attempt with a real run id should replace its aggregate fleet placeholder");
531
+ const gateTrackedRun = latestPayload().runs.find((run) => run.id === "recovered-gate-run");
532
+ assert.equal(gateTrackedRun?.source, "async", "gate-owned children should become normal output-capable async runs");
533
+ const gateTrackedCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "recovered-gate-run");
534
+ await helperCommand.handler(JSON.stringify({
535
+ requestId: "recovered-gate-live-output-test",
536
+ action: "subagent-output",
537
+ payload: { outputId: gateTrackedCanonical.outputRef.id },
538
+ }), ctx);
539
+ const recoveredGateOutput = helperResponse("recovered-gate-live-output-test");
540
+ assert.equal(recoveredGateOutput.ok, true);
541
+ assert.equal(recoveredGateOutput.data.source, "async");
542
+ assert.equal(recoveredGateOutput.data.agent.unavailable, undefined, "a gate child with a run locator must not retain the aggregate-fleet warning");
543
+ assert.deepEqual(recoveredGateOutput.data.agent.recentOutput, ["Gate child output is live."], "a recovered gate child should resolve its session transcript through the real run locator");
544
+
268
545
  const requestsBeforeWorkflowOutput = subagentStatusRequestCount;
269
546
  await helperCommand.handler(JSON.stringify({
270
547
  requestId: "workflow-subagent-output-test",
@@ -483,6 +760,31 @@ let foreground = payload.runs.find((run) => run.source === "foreground");
483
760
  assert.deepEqual(foreground?.agents.map((agent) => agent.name), ["tester", "reviewer"], "foreground parallel children should appear while the tool runs");
484
761
  assert.deepEqual(foreground?.agents.map((agent) => [agent.model, agent.thinking]), [["openai-codex/gpt-5.6-terra:xhigh", "xhigh"], ["anthropic/claude-opus-4-8:high", "high"]], "foreground overview should preserve run-level defaults and per-child model/reasoning overrides");
485
762
 
763
+ for (const handler of extensionHandlers.get("tool_execution_start") || []) {
764
+ handler({
765
+ type: "tool_execution_start",
766
+ toolCallId: "workflow-script-provisional",
767
+ toolName: "subagent",
768
+ args: { workflowScript: "return runs.run('implementation', { agent: 'worker', task: 'Implement it' })", async: false },
769
+ }, ctx);
770
+ }
771
+ payload = latestPayload();
772
+ const provisionalWorkflow = payload.runs.find((run) => run.id === "workflow-script-provisional");
773
+ assert.deepEqual(provisionalWorkflow && {
774
+ source: provisionalWorkflow.source,
775
+ status: provisionalWorkflow.status,
776
+ agents: provisionalWorkflow.agents.map((agent) => agent.name),
777
+ }, {
778
+ source: "foreground",
779
+ status: "running",
780
+ agents: ["workflow"],
781
+ }, "a direct workflowScript lifecycle start should publish a provisional row before child details arrive");
782
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
783
+ handler({ type: "tool_execution_end", toolCallId: "workflow-script-provisional", toolName: "subagent" }, ctx);
784
+ }
785
+ payload = latestPayload();
786
+ assert.equal(payload.runs.some((run) => run.id === "workflow-script-provisional"), false, "a workflow-only provisional row should not enter retained terminal history");
787
+
486
788
  for (const handler of extensionHandlers.get("tool_execution_update") || []) {
487
789
  handler({
488
790
  type: "tool_execution_update",
@@ -746,6 +1048,31 @@ assert.deepEqual(completedAsync && {
746
1048
  agentStatuses: ["done", "done"],
747
1049
  }, "async completion should retain a final run rather than deleting it");
748
1050
 
1051
+ bus.emit("subagent:async-started", { id: "run-authoritative-absence", mode: "single", agent: "absence-tester" });
1052
+ const replyWithEmptyAuthoritativeFleet = () => {
1053
+ subagentRpcReplyHook = (request) => {
1054
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
1055
+ subagentRpcReplyHook = null;
1056
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
1057
+ version: 1,
1058
+ requestId: request.requestId,
1059
+ method: request.method,
1060
+ success: true,
1061
+ data: { text: "No active async runs.", details: { mode: "management", results: [] }, fleet: { version: 1, entries: [], totalActive: 0, omitted: 0 } },
1062
+ });
1063
+ return true;
1064
+ };
1065
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
1066
+ };
1067
+ replyWithEmptyAuthoritativeFleet();
1068
+ await new Promise((resolve) => setTimeout(resolve, 0));
1069
+ payload = latestPayload();
1070
+ assert.equal(payload.runs.find((run) => run.id === "run-authoritative-absence")?.status, "running", "one authoritative omission must not finish a tracked run");
1071
+ replyWithEmptyAuthoritativeFleet();
1072
+ await new Promise((resolve) => setTimeout(resolve, 0));
1073
+ payload = latestPayload();
1074
+ assert.equal(payload.runs.find((run) => run.id === "run-authoritative-absence")?.status, "done", "repeated authoritative absence in one generation should finish a tracked run");
1075
+
749
1076
  const persistedSnapshot = branchEntries.at(-1);
750
1077
  assert.equal(persistedSnapshot?.customType, "webui-subagent-retained-runs-v1", "the latest parent-session custom entry should own retained run state");
751
1078
  assert.equal(persistedSnapshot?.data?.version, 1);
@@ -765,6 +1092,51 @@ assert.equal(restoredOutput.ok, true, "retained async output should remain acces
765
1092
  assert.equal(restoredOutput.data.agent.status, "cancelled");
766
1093
  assert.equal(restoredOutput.data.agent.telemetry.inputTokens, 300, "retained runs should re-read bounded telemetry from a still-available child session locator");
767
1094
 
1095
+ let staleGenerationRequest = null;
1096
+ let replacementGenerationRequest = null;
1097
+ subagentRpcReplyHook = (request) => {
1098
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
1099
+ if (!staleGenerationRequest) {
1100
+ staleGenerationRequest = request;
1101
+ return true;
1102
+ }
1103
+ replacementGenerationRequest = request;
1104
+ subagentRpcReplyHook = null;
1105
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
1106
+ version: 1,
1107
+ requestId: request.requestId,
1108
+ method: request.method,
1109
+ success: true,
1110
+ data: { text: "No active async runs.", details: { mode: "management", results: [] }, fleet: { version: 1, entries: [], totalActive: 0, omitted: 0 } },
1111
+ });
1112
+ return true;
1113
+ };
1114
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
1115
+ await new Promise((resolve) => setTimeout(resolve, 0));
1116
+ assert.ok(staleGenerationRequest, "the stale-generation regression should hold an old poll response");
1117
+ for (const handler of extensionHandlers.get("session_tree") || []) await handler({ reason: "stale-poll-switch" }, ctx);
1118
+ for (let attempt = 0; attempt < 20 && !replacementGenerationRequest; attempt++) await new Promise((resolve) => setTimeout(resolve, 10));
1119
+ assert.ok(replacementGenerationRequest, "session_tree should immediately poll the replacement generation");
1120
+ bus.emit(`subagents:rpc:v1:reply:${staleGenerationRequest.requestId}`, {
1121
+ version: 1,
1122
+ requestId: staleGenerationRequest.requestId,
1123
+ method: staleGenerationRequest.method,
1124
+ success: true,
1125
+ data: {
1126
+ text: "No active async runs.",
1127
+ details: { mode: "management", results: [] },
1128
+ fleet: {
1129
+ version: 1,
1130
+ entries: [{ key: "fleet-stale", agent: "stale-agent", startedAt: Date.now(), tokens: { input: 0, output: 0, total: 0 } }],
1131
+ totalActive: 1,
1132
+ omitted: 0,
1133
+ },
1134
+ },
1135
+ });
1136
+ await new Promise((resolve) => setTimeout(resolve, 0));
1137
+ payload = latestPayload();
1138
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-stale"), false, "a pre-session_tree response must not overwrite the replacement generation");
1139
+
768
1140
  const retainedParentBranch = branchEntries;
769
1141
  branchEntries = [];
770
1142
  for (const handler of extensionHandlers.get("session_tree") || []) await handler({ reason: "different-branch" }, ctx);
@@ -798,6 +1170,177 @@ for (let index = 0; index < 17; index += 1) {
798
1170
  payload = latestPayload();
799
1171
  assert.ok(payload.runs.filter((run) => run.source !== "workflow" && run.status !== "running").length <= 16, "ordinary retained runs should enforce the 16-run finished retention cap");
800
1172
 
1173
+ // --- canonical agent-run protocol (v2) ---------------------------------------
1174
+
1175
+ for (const handler of extensionHandlers.get("tool_execution_start") || []) {
1176
+ handler({ type: "tool_execution_start", toolCallId: "canon-run", toolName: "subagent", args: { agent: "reviewer" } }, ctx);
1177
+ }
1178
+ let canonical = latestCanonicalPayload();
1179
+ assert.equal(canonical.version, 2, "the canonical status key should carry the v2 envelope");
1180
+ const canonicalAgent = canonical.instances.find((instance) => instance.runId === "canon-run");
1181
+ assert.ok(canonicalAgent, "a live pi-subagents run should project a canonical instance");
1182
+ assert.equal(canonicalAgent.version, 1, "canonical instances stay on protocol version 1");
1183
+ assert.equal(canonicalAgent.launcher, "pi-subagents");
1184
+ assert.equal(canonicalAgent.provider, "pi-subagents");
1185
+ assert.equal(canonicalAgent.status, "running");
1186
+ assert.equal(canonicalAgent.capabilities.cancel, true, "the owning pi-subagents lifecycle keeps cancel authority");
1187
+ assert.equal(canonicalAgent.capabilities.steer, false, "v1 never advertises steer");
1188
+ assert.equal(canonicalAgent.outputRef.kind, "helper");
1189
+ assert.match(canonicalAgent.outputRef.id, /^h-[0-9a-f]{32}$/, "helper output handles must be opaque");
1190
+ assert.equal(JSON.stringify(canonical).includes(asyncRunDir), false, "canonical snapshots must not disclose host paths");
1191
+
1192
+ await helperCommand.handler(JSON.stringify({
1193
+ requestId: "canon-output",
1194
+ action: "subagent-output",
1195
+ payload: { outputId: canonicalAgent.outputRef.id },
1196
+ }), ctx);
1197
+ const canonicalOutput = helperResponse("canon-output");
1198
+ assert.equal(canonicalOutput.ok, true, "an opaque helper handle should resolve output");
1199
+ assert.equal(canonicalOutput.data.runId, "canon-run");
1200
+
1201
+ await helperCommand.handler(JSON.stringify({
1202
+ requestId: "canon-output-unknown",
1203
+ action: "subagent-output",
1204
+ payload: { outputId: "h-00000000000000000000000000000000" },
1205
+ }), ctx);
1206
+ assert.equal(helperResponse("canon-output-unknown").ok, false, "an unknown output handle must be rejected, not guessed");
1207
+
1208
+ const providerInstance = (overrides = {}) => ({
1209
+ version: 1,
1210
+ instanceId: "sdk-instance-1",
1211
+ runId: "sdk-run-1",
1212
+ launcher: "sdk",
1213
+ provider: "webui-registry",
1214
+ name: "sdk worker",
1215
+ status: "running",
1216
+ startedAt: Date.now() - 1000,
1217
+ updatedAt: Date.now(),
1218
+ endedAt: null,
1219
+ ...overrides,
1220
+ });
1221
+
1222
+ bus.emit("firstpick:webui-agent-runs:v1", {
1223
+ version: 1,
1224
+ producerId: "custom-alpha",
1225
+ complete: true,
1226
+ instances: [providerInstance()],
1227
+ });
1228
+ canonical = latestCanonicalPayload();
1229
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "sdk-instance-1"), "a valid provider snapshot should be ingested");
1230
+ assert.ok(canonical.producers.includes("custom-alpha"));
1231
+
1232
+ bus.emit("firstpick:webui-agent-runs:v1", {
1233
+ version: 1,
1234
+ producerId: "custom-beta",
1235
+ complete: true,
1236
+ instances: [providerInstance({ instanceId: "beta-instance-1", runId: "beta-run-1", launcher: "pi-print" })],
1237
+ });
1238
+ canonical = latestCanonicalPayload();
1239
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "sdk-instance-1"), "a complete snapshot must only clear its own producer's rows");
1240
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "beta-instance-1"));
1241
+
1242
+ const instancesBeforeMalformed = canonical.instances.length;
1243
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 1, producerId: "custom-alpha", complete: true, instances: [{ version: 1, instanceId: "../escape" }] });
1244
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 9, producerId: "custom-alpha", complete: true, instances: [] });
1245
+ canonical = latestCanonicalPayload();
1246
+ assert.equal(canonical.instances.length, instancesBeforeMalformed, "a malformed snapshot must not clear valid rows");
1247
+ assert.ok(canonical.diagnostics.some((entry) => entry.code === "invalid-provider-snapshot"), "malformed snapshots should surface a bounded diagnostic");
1248
+
1249
+ const countBeforeDuplicate = canonical.instances.length;
1250
+ bus.emit("firstpick:webui-agent-runs:v1", {
1251
+ version: 1,
1252
+ producerId: "custom-duplicate",
1253
+ complete: true,
1254
+ instances: [providerInstance({
1255
+ instanceId: canonicalAgent.instanceId,
1256
+ runId: canonicalAgent.runId,
1257
+ launcher: "custom",
1258
+ provider: "custom-duplicate",
1259
+ capabilities: { open: true, refresh: true, cancel: true, steer: true },
1260
+ })],
1261
+ });
1262
+ canonical = latestCanonicalPayload();
1263
+ assert.equal(canonical.instances.length, countBeforeDuplicate, "a second observer of the same instance must not add a count");
1264
+ const deduplicated = canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId);
1265
+ assert.equal(deduplicated.provider, "pi-subagents", "the owning provider keeps the row");
1266
+ assert.equal(deduplicated.capabilities.steer, false, "a foreign producer must not seize capabilities");
1267
+
1268
+ const instancesBeforeGate = canonical.instances.length;
1269
+ bus.emit("webui:subagent-gate:v1:update", {
1270
+ version: 1,
1271
+ id: "canon-gate",
1272
+ status: "running",
1273
+ requiredSuccesses: 1,
1274
+ qualifyingSuccesses: 0,
1275
+ requireDistinctProviders: false,
1276
+ startedAt: Date.now() - 500,
1277
+ updatedAt: Date.now(),
1278
+ attempts: [
1279
+ { id: "canon-gate:0:1", taskIndex: 0, attempt: 1, maxAttempts: 1, agent: "reviewer", retrySafety: "read-only", runId: "canon-run", status: "running" },
1280
+ { id: "canon-gate:1:1", taskIndex: 1, attempt: 1, maxAttempts: 1, agent: "reviewer", retrySafety: "read-only", runId: "never-launched", status: "failed", failureKind: "pre-launch" },
1281
+ ],
1282
+ });
1283
+ canonical = latestCanonicalPayload();
1284
+ assert.equal(canonical.instances.length, instancesBeforeGate, "gate attempts must never add canonical agent counts");
1285
+ const resolvedReference = canonical.gateReferences.find((reference) => reference.attemptId === "canon-gate:0:1");
1286
+ assert.ok(resolvedReference?.resolved, "a gate attempt should reference its canonical child");
1287
+ assert.deepEqual(resolvedReference.instanceIds, [canonicalAgent.instanceId]);
1288
+ assert.equal(canonical.gateReferences.find((reference) => reference.attemptId === "canon-gate:1:1")?.resolved, false, "a pre-launch failure stays gate history only");
1289
+ assert.equal(canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId)?.launcher, "gate", "a gate-launched child reports the gate launch family");
1290
+
1291
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
1292
+ handler({ type: "tool_execution_end", toolCallId: "canon-run", toolName: "subagent" }, ctx);
1293
+ }
1294
+ canonical = latestCanonicalPayload();
1295
+ const retainedCanonical = canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId);
1296
+ assert.equal(retainedCanonical.status, "done", "a terminal run keeps an explicit terminal status");
1297
+ assert.ok(Number.isSafeInteger(retainedCanonical.endedAt), "terminal instances carry endedAt");
1298
+ assert.equal(retainedCanonical.capabilities.cancel, false, "a finished run stops advertising cancel");
1299
+ assert.equal(retainedCanonical.capabilities.open, true, "retained rows stay openable");
1300
+
1301
+ bus.emit("firstpick:webui-agent-runs:v1", {
1302
+ version: 1,
1303
+ producerId: "custom-duplicate",
1304
+ complete: true,
1305
+ instances: [providerInstance({
1306
+ instanceId: canonicalAgent.instanceId,
1307
+ runId: canonicalAgent.runId,
1308
+ launcher: "custom",
1309
+ provider: "custom-duplicate",
1310
+ status: "done",
1311
+ updatedAt: retainedCanonical.endedAt,
1312
+ endedAt: retainedCanonical.endedAt,
1313
+ capabilities: { open: true, refresh: true, cancel: false, steer: false },
1314
+ })],
1315
+ });
1316
+ await helperCommand.handler(JSON.stringify({
1317
+ requestId: "dismiss-terminal-duplicate-projection",
1318
+ action: "subagent-dismiss",
1319
+ payload: { runId: "canon-run" },
1320
+ }), ctx);
1321
+ assert.equal(helperResponse("dismiss-terminal-duplicate-projection").ok, true, "the terminal owning run should accept dismissal");
1322
+ canonical = latestCanonicalPayload();
1323
+ assert.equal(canonical.instances.some((instance) => instance.instanceId === canonicalAgent.instanceId), false, "dismissal should suppress a terminal run still present in a duplicate provider snapshot");
1324
+
1325
+ bus.emit("firstpick:webui-agent-runs:v1", {
1326
+ version: 1,
1327
+ producerId: "custom-duplicate",
1328
+ complete: true,
1329
+ instances: [providerInstance({
1330
+ instanceId: canonicalAgent.instanceId,
1331
+ runId: canonicalAgent.runId,
1332
+ launcher: "custom",
1333
+ provider: "custom-duplicate",
1334
+ status: "running",
1335
+ startedAt: retainedCanonical.endedAt + 1,
1336
+ updatedAt: retainedCanonical.endedAt + 1,
1337
+ endedAt: null,
1338
+ })],
1339
+ });
1340
+ canonical = latestCanonicalPayload();
1341
+ assert.equal(canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId)?.status, "running", "a newer provider lifecycle should release the local dismissal tombstone");
1342
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 1, producerId: "custom-duplicate", complete: true, instances: [] });
1343
+
801
1344
  for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
802
1345
  unsubscribeRpc();
803
1346
  delete process.env.PI_WEBUI_SETTINGS_FILE;