@firstpick/pi-package-webui 0.9.1 → 0.9.2

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 (70) hide show
  1. package/README.md +21 -5
  2. package/bin/pi-webui-launcher.mjs +23 -12
  3. package/bin/pi-webui.mjs +479 -60
  4. package/lib/agent-run-adapters.mjs +500 -0
  5. package/lib/agent-run-protocol.mjs +262 -0
  6. package/lib/agent-run-registry.mjs +339 -0
  7. package/lib/git-workflow-preferences.mjs +11 -4
  8. package/lib/trust-boundaries.mjs +2 -0
  9. package/lib/ui-layout-settings.mjs +172 -28
  10. package/lib/update/package-layout.mjs +50 -0
  11. package/lib/update/plan.mjs +11 -0
  12. package/package.json +1 -1
  13. package/public/app.js +1261 -314
  14. package/public/index.html +113 -68
  15. package/public/service-worker.js +1 -1
  16. package/public/styles.css +371 -93
  17. package/tests/agent-run-adapters.test.mjs +217 -0
  18. package/tests/agent-run-launcher.test.mjs +41 -0
  19. package/tests/agent-run-protocol.test.mjs +82 -0
  20. package/tests/agent-run-registry.test.mjs +102 -0
  21. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  22. package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
  23. package/tests/browser/controls-layout.spec.mjs +122 -0
  24. package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
  25. package/tests/browser/interaction-continuity.spec.mjs +127 -0
  26. package/tests/browser/mobile-foundation.spec.mjs +26 -0
  27. package/tests/browser/model-search-focus.spec.mjs +96 -0
  28. package/tests/browser/optimistic-prompt.spec.mjs +22 -0
  29. package/tests/browser/persistent-ui-layout.spec.mjs +224 -66
  30. package/tests/browser/subagent-observability.spec.mjs +87 -0
  31. package/tests/codex-fast-mode-static.test.mjs +2 -2
  32. package/tests/component-update-api-static.test.mjs +2 -1
  33. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  34. package/tests/control-deck-component-updates-static.test.mjs +2 -0
  35. package/tests/control-deck-side-panels-static.test.mjs +68 -0
  36. package/tests/controls-layout-static.test.mjs +22 -0
  37. package/tests/fast-mode-client-static.test.mjs +1 -1
  38. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  39. package/tests/file-tree-git-ignored-static.test.mjs +152 -0
  40. package/tests/file-tree-search-layout-static.test.mjs +2 -1
  41. package/tests/fixtures/fake-pi.mjs +43 -7
  42. package/tests/git-workflow-preferences.test.mjs +55 -6
  43. package/tests/http-endpoints-harness.test.mjs +173 -14
  44. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  45. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  46. package/tests/mobile-foundation-static.test.mjs +3 -3
  47. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  48. package/tests/mobile-static.test.mjs +13 -3
  49. package/tests/open-issue-wizard-static.test.mjs +2 -2
  50. package/tests/persistent-ui-layout-static.test.mjs +13 -13
  51. package/tests/questionnaire-dialog.test.mjs +3 -3
  52. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  53. package/tests/session-sampling-ui-static.test.mjs +3 -3
  54. package/tests/side-panel-context-menu-static.test.mjs +1 -1
  55. package/tests/side-panel-resize-static.test.mjs +26 -16
  56. package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
  57. package/tests/side-panel-section-reorder-static.test.mjs +16 -70
  58. package/tests/subagent-gate-visibility.test.mjs +2 -1
  59. package/tests/subagent-launch-slots.test.mjs +1 -1
  60. package/tests/subagent-observability-static.test.mjs +32 -0
  61. package/tests/subagent-reliability-integration.test.mjs +161 -0
  62. package/tests/subagents-helper.test.mjs +344 -4
  63. package/tests/terminal-tabs-resize-static.test.mjs +35 -0
  64. package/tests/theme-customizer-static.test.mjs +1 -1
  65. package/tests/ui-layout-settings.test.mjs +104 -32
  66. package/tests/update-api-harness.test.mjs +24 -10
  67. package/tests/update-package-layout.test.mjs +38 -0
  68. package/tests/update-plan.test.mjs +11 -1
  69. package/tests/webui-settings-locking.test.mjs +33 -3
  70. package/webui-rpc-helper.mjs +417 -28
@@ -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) {
@@ -135,7 +140,7 @@ const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
135
140
  const text = request.params?.id === "run-a"
136
141
  ? `Run: run-a\nState: running\nMode: parallel\nDir: ${asyncRunDir}`
137
142
  : statusText;
138
- subagentRpcReplyHook?.(request);
143
+ if (subagentRpcReplyHook?.(request) === true) return;
139
144
  bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
140
145
  version: 1,
141
146
  requestId: request.requestId,
@@ -184,6 +189,18 @@ function latestPayload() {
184
189
  return JSON.parse(entry.text.slice("PI_WEBUI_SUBAGENTS_V1 ".length));
185
190
  }
186
191
 
192
+ /** v1 delivery accounting must stay independent of the separate canonical v2 status key. */
193
+ function legacyStatusCount() {
194
+ return statuses.filter((item) => item.key === "webui-subagents").length;
195
+ }
196
+
197
+ function latestCanonicalPayload() {
198
+ const entry = statuses.filter((item) => item.key === "webui-subagents-v2").at(-1);
199
+ assert.ok(entry, "helper should publish the canonical WebUI agent-run status");
200
+ assert.match(entry.text, /^PI_WEBUI_SUBAGENTS_V2 /);
201
+ return JSON.parse(entry.text.slice("PI_WEBUI_SUBAGENTS_V2 ".length));
202
+ }
203
+
187
204
  function helperResponse(requestId) {
188
205
  const notice = notifications.findLast((entry) => entry.message.startsWith("__PI_WEBUI_HELPER_RESPONSE__:")
189
206
  && JSON.parse(entry.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length)).requestId === requestId);
@@ -199,6 +216,102 @@ assert.deepEqual(payload.runs[0].agents.map((agent) => [agent.name, agent.curren
199
216
  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
217
  assert.deepEqual(payload.runs[1].agents.map((agent) => [agent.name, agent.nested]), [["worker", false], ["nested-oracle", true]]);
201
218
 
219
+ const fleetStartedAt = Date.now() - 500;
220
+ subagentRpcReplyHook = (request) => {
221
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
222
+ subagentRpcReplyHook = null;
223
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
224
+ version: 1,
225
+ requestId: request.requestId,
226
+ method: request.method,
227
+ success: true,
228
+ data: {
229
+ text: statusText,
230
+ details: { mode: "single", results: [] },
231
+ fleet: {
232
+ version: 1,
233
+ entries: [
234
+ { key: "fleet-reviewer-1", agent: "reviewer", startedAt: fleetStartedAt, tokens: { input: 0, output: 0, total: 0 } },
235
+ { key: "fleet-reviewer-2", agent: "reviewer", startedAt: fleetStartedAt + 1, tokens: { input: 0, output: 0, total: 0 } },
236
+ { key: "fleet-worker", agent: "worker", startedAt: fleetStartedAt + 2, tokens: { input: 0, output: 0, total: 0 } },
237
+ { key: "fleet-nested", agent: "nested-oracle", startedAt: fleetStartedAt + 3, tokens: { input: 0, output: 0, total: 0 } },
238
+ { 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 } },
239
+ ],
240
+ totalActive: 5,
241
+ omitted: 0,
242
+ },
243
+ },
244
+ });
245
+ return true;
246
+ };
247
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
248
+ await new Promise((resolve) => setTimeout(resolve, 0));
249
+ payload = latestPayload();
250
+ assert.equal(payload.runs.filter((run) => run.id === "run-a").length, 1, "fleet recovery must not duplicate a text-parsed run");
251
+ assert.equal(payload.runs.find((run) => run.id === "run-a")?.agents.length, 2, "fleet recovery must match repeated same-role children one-to-one");
252
+ const recoveredFleetRun = payload.runs.find((run) => run.id === "fleet:fleet-recovered");
253
+ assert.deepEqual(recoveredFleetRun && {
254
+ source: recoveredFleetRun.source,
255
+ provisional: recoveredFleetRun.provisional,
256
+ controllable: recoveredFleetRun.controllable,
257
+ agents: recoveredFleetRun.agents.map((agent) => [agent.name, agent.model, agent.thinking]),
258
+ }, {
259
+ source: "recovered",
260
+ provisional: true,
261
+ controllable: false,
262
+ agents: [["Recovery scout", "openai-codex/gpt-5.6-terra:xhigh", "xhigh"]],
263
+ }, "unmatched authoritative fleet children should publish a bounded non-controllable provisional row");
264
+ assert.deepEqual(payload.fleet, { version: 1, totalActive: 5, omitted: 0 }, "fleet recovery should publish only bounded aggregate recovery metadata");
265
+
266
+ subagentRpcReplyHook = (request) => {
267
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
268
+ subagentRpcReplyHook = null;
269
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
270
+ version: 1,
271
+ requestId: request.requestId,
272
+ method: request.method,
273
+ success: true,
274
+ data: {
275
+ text: statusText,
276
+ details: { mode: "single", results: [] },
277
+ fleet: { version: 1, entries: "malformed", totalActive: 99, omitted: 99 },
278
+ },
279
+ });
280
+ return true;
281
+ };
282
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
283
+ await new Promise((resolve) => setTimeout(resolve, 0));
284
+ payload = latestPayload();
285
+ assert.equal("fleet" in payload, false, "a successful poll with malformed fleet data should clear stale aggregate metadata");
286
+ 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");
287
+
288
+ const retryGate = {
289
+ version: 1,
290
+ id: "gate-delivery-retry",
291
+ status: "running",
292
+ requiredSuccesses: 1,
293
+ qualifyingSuccesses: 0,
294
+ requireDistinctProviders: false,
295
+ startedAt: Date.now(),
296
+ updatedAt: Date.now(),
297
+ attempts: [],
298
+ };
299
+ const statusesBeforeFailedDelivery = legacyStatusCount();
300
+ setStatusFailures = 1;
301
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
302
+ assert.equal(legacyStatusCount(), statusesBeforeFailedDelivery, "a failed setStatus delivery should not appear successful");
303
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
304
+ assert.equal(legacyStatusCount(), statusesBeforeFailedDelivery + 1, "an unchanged snapshot should retry after setStatus throws");
305
+ const statusesBeforeHeartbeat = legacyStatusCount();
306
+ const realDateNow = Date.now;
307
+ Date.now = () => realDateNow() + 16_000;
308
+ try {
309
+ bus.emit("webui:subagent-gate:v1:update", retryGate);
310
+ } finally {
311
+ Date.now = realDateNow;
312
+ }
313
+ assert.equal(legacyStatusCount(), statusesBeforeHeartbeat + 1, "an unchanged snapshot should republish after the bounded heartbeat interval");
314
+
202
315
  bus.emit("webui:subagent-gate:v1:update", {
203
316
  version: 1,
204
317
  id: "gate-a",
@@ -214,9 +327,10 @@ bus.emit("webui:subagent-gate:v1:update", {
214
327
  ],
215
328
  });
216
329
  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"]]);
330
+ assert.equal(payload.gates.length, 2, "helper should publish retry gate lifecycle alongside running children");
331
+ const publishedGate = payload.gates.find((gate) => gate.id === "gate-a");
332
+ assert.equal(publishedGate?.qualifyingSuccesses, 1);
333
+ assert.deepEqual(publishedGate?.attempts.map((attempt) => [attempt.status, attempt.failureKind]), [["succeeded", undefined], ["failed", "transient-provider"]]);
220
334
 
221
335
  const workflowRunId = "workflow:run-42";
222
336
  const workflowAgentId = "workflow:run-42:phase:implement:call:call-0123456789abcdef";
@@ -241,6 +355,9 @@ const workflowSnapshot = {
241
355
  }],
242
356
  };
243
357
  bus.emit("firstpick:workflow-subagents:v1", workflowSnapshot);
358
+ const canonicalPublishesAfterWorkflow = statuses.filter((item) => item.key === "webui-subagents-v2").length;
359
+ bus.emit("firstpick:workflow-subagents:v1", workflowSnapshot);
360
+ assert.equal(statuses.filter((item) => item.key === "webui-subagents-v2").length, canonicalPublishesAfterWorkflow, "unchanged active snapshots must respect the bounded canonical publish heartbeat");
244
361
  payload = latestPayload();
245
362
  const workflowRun = payload.runs.find((run) => run.id === workflowRunId);
246
363
  assert.deepEqual(workflowRun && {
@@ -483,6 +600,31 @@ let foreground = payload.runs.find((run) => run.source === "foreground");
483
600
  assert.deepEqual(foreground?.agents.map((agent) => agent.name), ["tester", "reviewer"], "foreground parallel children should appear while the tool runs");
484
601
  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
602
 
603
+ for (const handler of extensionHandlers.get("tool_execution_start") || []) {
604
+ handler({
605
+ type: "tool_execution_start",
606
+ toolCallId: "workflow-script-provisional",
607
+ toolName: "subagent",
608
+ args: { workflowScript: "return runs.run('implementation', { agent: 'worker', task: 'Implement it' })", async: false },
609
+ }, ctx);
610
+ }
611
+ payload = latestPayload();
612
+ const provisionalWorkflow = payload.runs.find((run) => run.id === "workflow-script-provisional");
613
+ assert.deepEqual(provisionalWorkflow && {
614
+ source: provisionalWorkflow.source,
615
+ status: provisionalWorkflow.status,
616
+ agents: provisionalWorkflow.agents.map((agent) => agent.name),
617
+ }, {
618
+ source: "foreground",
619
+ status: "running",
620
+ agents: ["workflow"],
621
+ }, "a direct workflowScript lifecycle start should publish a provisional row before child details arrive");
622
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
623
+ handler({ type: "tool_execution_end", toolCallId: "workflow-script-provisional", toolName: "subagent" }, ctx);
624
+ }
625
+ payload = latestPayload();
626
+ assert.equal(payload.runs.some((run) => run.id === "workflow-script-provisional"), false, "a workflow-only provisional row should not enter retained terminal history");
627
+
486
628
  for (const handler of extensionHandlers.get("tool_execution_update") || []) {
487
629
  handler({
488
630
  type: "tool_execution_update",
@@ -746,6 +888,31 @@ assert.deepEqual(completedAsync && {
746
888
  agentStatuses: ["done", "done"],
747
889
  }, "async completion should retain a final run rather than deleting it");
748
890
 
891
+ bus.emit("subagent:async-started", { id: "run-authoritative-absence", mode: "single", agent: "absence-tester" });
892
+ const replyWithEmptyAuthoritativeFleet = () => {
893
+ subagentRpcReplyHook = (request) => {
894
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
895
+ subagentRpcReplyHook = null;
896
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
897
+ version: 1,
898
+ requestId: request.requestId,
899
+ method: request.method,
900
+ success: true,
901
+ data: { text: "No active async runs.", details: { mode: "management", results: [] }, fleet: { version: 1, entries: [], totalActive: 0, omitted: 0 } },
902
+ });
903
+ return true;
904
+ };
905
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
906
+ };
907
+ replyWithEmptyAuthoritativeFleet();
908
+ await new Promise((resolve) => setTimeout(resolve, 0));
909
+ payload = latestPayload();
910
+ assert.equal(payload.runs.find((run) => run.id === "run-authoritative-absence")?.status, "running", "one authoritative omission must not finish a tracked run");
911
+ replyWithEmptyAuthoritativeFleet();
912
+ await new Promise((resolve) => setTimeout(resolve, 0));
913
+ payload = latestPayload();
914
+ assert.equal(payload.runs.find((run) => run.id === "run-authoritative-absence")?.status, "done", "repeated authoritative absence in one generation should finish a tracked run");
915
+
749
916
  const persistedSnapshot = branchEntries.at(-1);
750
917
  assert.equal(persistedSnapshot?.customType, "webui-subagent-retained-runs-v1", "the latest parent-session custom entry should own retained run state");
751
918
  assert.equal(persistedSnapshot?.data?.version, 1);
@@ -765,6 +932,51 @@ assert.equal(restoredOutput.ok, true, "retained async output should remain acces
765
932
  assert.equal(restoredOutput.data.agent.status, "cancelled");
766
933
  assert.equal(restoredOutput.data.agent.telemetry.inputTokens, 300, "retained runs should re-read bounded telemetry from a still-available child session locator");
767
934
 
935
+ let staleGenerationRequest = null;
936
+ let replacementGenerationRequest = null;
937
+ subagentRpcReplyHook = (request) => {
938
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
939
+ if (!staleGenerationRequest) {
940
+ staleGenerationRequest = request;
941
+ return true;
942
+ }
943
+ replacementGenerationRequest = request;
944
+ subagentRpcReplyHook = null;
945
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
946
+ version: 1,
947
+ requestId: request.requestId,
948
+ method: request.method,
949
+ success: true,
950
+ data: { text: "No active async runs.", details: { mode: "management", results: [] }, fleet: { version: 1, entries: [], totalActive: 0, omitted: 0 } },
951
+ });
952
+ return true;
953
+ };
954
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
955
+ await new Promise((resolve) => setTimeout(resolve, 0));
956
+ assert.ok(staleGenerationRequest, "the stale-generation regression should hold an old poll response");
957
+ for (const handler of extensionHandlers.get("session_tree") || []) await handler({ reason: "stale-poll-switch" }, ctx);
958
+ for (let attempt = 0; attempt < 20 && !replacementGenerationRequest; attempt++) await new Promise((resolve) => setTimeout(resolve, 10));
959
+ assert.ok(replacementGenerationRequest, "session_tree should immediately poll the replacement generation");
960
+ bus.emit(`subagents:rpc:v1:reply:${staleGenerationRequest.requestId}`, {
961
+ version: 1,
962
+ requestId: staleGenerationRequest.requestId,
963
+ method: staleGenerationRequest.method,
964
+ success: true,
965
+ data: {
966
+ text: "No active async runs.",
967
+ details: { mode: "management", results: [] },
968
+ fleet: {
969
+ version: 1,
970
+ entries: [{ key: "fleet-stale", agent: "stale-agent", startedAt: Date.now(), tokens: { input: 0, output: 0, total: 0 } }],
971
+ totalActive: 1,
972
+ omitted: 0,
973
+ },
974
+ },
975
+ });
976
+ await new Promise((resolve) => setTimeout(resolve, 0));
977
+ payload = latestPayload();
978
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-stale"), false, "a pre-session_tree response must not overwrite the replacement generation");
979
+
768
980
  const retainedParentBranch = branchEntries;
769
981
  branchEntries = [];
770
982
  for (const handler of extensionHandlers.get("session_tree") || []) await handler({ reason: "different-branch" }, ctx);
@@ -798,6 +1010,134 @@ for (let index = 0; index < 17; index += 1) {
798
1010
  payload = latestPayload();
799
1011
  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
1012
 
1013
+ // --- canonical agent-run protocol (v2) ---------------------------------------
1014
+
1015
+ for (const handler of extensionHandlers.get("tool_execution_start") || []) {
1016
+ handler({ type: "tool_execution_start", toolCallId: "canon-run", toolName: "subagent", args: { agent: "reviewer" } }, ctx);
1017
+ }
1018
+ let canonical = latestCanonicalPayload();
1019
+ assert.equal(canonical.version, 2, "the canonical status key should carry the v2 envelope");
1020
+ const canonicalAgent = canonical.instances.find((instance) => instance.runId === "canon-run");
1021
+ assert.ok(canonicalAgent, "a live pi-subagents run should project a canonical instance");
1022
+ assert.equal(canonicalAgent.version, 1, "canonical instances stay on protocol version 1");
1023
+ assert.equal(canonicalAgent.launcher, "pi-subagents");
1024
+ assert.equal(canonicalAgent.provider, "pi-subagents");
1025
+ assert.equal(canonicalAgent.status, "running");
1026
+ assert.equal(canonicalAgent.capabilities.cancel, true, "the owning pi-subagents lifecycle keeps cancel authority");
1027
+ assert.equal(canonicalAgent.capabilities.steer, false, "v1 never advertises steer");
1028
+ assert.equal(canonicalAgent.outputRef.kind, "helper");
1029
+ assert.match(canonicalAgent.outputRef.id, /^h-[0-9a-f]{32}$/, "helper output handles must be opaque");
1030
+ assert.equal(JSON.stringify(canonical).includes(asyncRunDir), false, "canonical snapshots must not disclose host paths");
1031
+
1032
+ await helperCommand.handler(JSON.stringify({
1033
+ requestId: "canon-output",
1034
+ action: "subagent-output",
1035
+ payload: { outputId: canonicalAgent.outputRef.id },
1036
+ }), ctx);
1037
+ const canonicalOutput = helperResponse("canon-output");
1038
+ assert.equal(canonicalOutput.ok, true, "an opaque helper handle should resolve output");
1039
+ assert.equal(canonicalOutput.data.runId, "canon-run");
1040
+
1041
+ await helperCommand.handler(JSON.stringify({
1042
+ requestId: "canon-output-unknown",
1043
+ action: "subagent-output",
1044
+ payload: { outputId: "h-00000000000000000000000000000000" },
1045
+ }), ctx);
1046
+ assert.equal(helperResponse("canon-output-unknown").ok, false, "an unknown output handle must be rejected, not guessed");
1047
+
1048
+ const providerInstance = (overrides = {}) => ({
1049
+ version: 1,
1050
+ instanceId: "sdk-instance-1",
1051
+ runId: "sdk-run-1",
1052
+ launcher: "sdk",
1053
+ provider: "webui-registry",
1054
+ name: "sdk worker",
1055
+ status: "running",
1056
+ startedAt: Date.now() - 1000,
1057
+ updatedAt: Date.now(),
1058
+ endedAt: null,
1059
+ ...overrides,
1060
+ });
1061
+
1062
+ bus.emit("firstpick:webui-agent-runs:v1", {
1063
+ version: 1,
1064
+ producerId: "custom-alpha",
1065
+ complete: true,
1066
+ instances: [providerInstance()],
1067
+ });
1068
+ canonical = latestCanonicalPayload();
1069
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "sdk-instance-1"), "a valid provider snapshot should be ingested");
1070
+ assert.ok(canonical.producers.includes("custom-alpha"));
1071
+
1072
+ bus.emit("firstpick:webui-agent-runs:v1", {
1073
+ version: 1,
1074
+ producerId: "custom-beta",
1075
+ complete: true,
1076
+ instances: [providerInstance({ instanceId: "beta-instance-1", runId: "beta-run-1", launcher: "pi-print" })],
1077
+ });
1078
+ canonical = latestCanonicalPayload();
1079
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "sdk-instance-1"), "a complete snapshot must only clear its own producer's rows");
1080
+ assert.ok(canonical.instances.some((instance) => instance.instanceId === "beta-instance-1"));
1081
+
1082
+ const instancesBeforeMalformed = canonical.instances.length;
1083
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 1, producerId: "custom-alpha", complete: true, instances: [{ version: 1, instanceId: "../escape" }] });
1084
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 9, producerId: "custom-alpha", complete: true, instances: [] });
1085
+ canonical = latestCanonicalPayload();
1086
+ assert.equal(canonical.instances.length, instancesBeforeMalformed, "a malformed snapshot must not clear valid rows");
1087
+ assert.ok(canonical.diagnostics.some((entry) => entry.code === "invalid-provider-snapshot"), "malformed snapshots should surface a bounded diagnostic");
1088
+
1089
+ const countBeforeDuplicate = canonical.instances.length;
1090
+ bus.emit("firstpick:webui-agent-runs:v1", {
1091
+ version: 1,
1092
+ producerId: "custom-duplicate",
1093
+ complete: true,
1094
+ instances: [providerInstance({
1095
+ instanceId: canonicalAgent.instanceId,
1096
+ runId: canonicalAgent.runId,
1097
+ launcher: "custom",
1098
+ provider: "custom-duplicate",
1099
+ capabilities: { open: true, refresh: true, cancel: true, steer: true },
1100
+ })],
1101
+ });
1102
+ canonical = latestCanonicalPayload();
1103
+ assert.equal(canonical.instances.length, countBeforeDuplicate, "a second observer of the same instance must not add a count");
1104
+ const deduplicated = canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId);
1105
+ assert.equal(deduplicated.provider, "pi-subagents", "the owning provider keeps the row");
1106
+ assert.equal(deduplicated.capabilities.steer, false, "a foreign producer must not seize capabilities");
1107
+
1108
+ const instancesBeforeGate = canonical.instances.length;
1109
+ bus.emit("webui:subagent-gate:v1:update", {
1110
+ version: 1,
1111
+ id: "canon-gate",
1112
+ status: "running",
1113
+ requiredSuccesses: 1,
1114
+ qualifyingSuccesses: 0,
1115
+ requireDistinctProviders: false,
1116
+ startedAt: Date.now() - 500,
1117
+ updatedAt: Date.now(),
1118
+ attempts: [
1119
+ { id: "canon-gate:0:1", taskIndex: 0, attempt: 1, maxAttempts: 1, agent: "reviewer", retrySafety: "read-only", runId: "canon-run", status: "running" },
1120
+ { id: "canon-gate:1:1", taskIndex: 1, attempt: 1, maxAttempts: 1, agent: "reviewer", retrySafety: "read-only", runId: "never-launched", status: "failed", failureKind: "pre-launch" },
1121
+ ],
1122
+ });
1123
+ canonical = latestCanonicalPayload();
1124
+ assert.equal(canonical.instances.length, instancesBeforeGate, "gate attempts must never add canonical agent counts");
1125
+ const resolvedReference = canonical.gateReferences.find((reference) => reference.attemptId === "canon-gate:0:1");
1126
+ assert.ok(resolvedReference?.resolved, "a gate attempt should reference its canonical child");
1127
+ assert.deepEqual(resolvedReference.instanceIds, [canonicalAgent.instanceId]);
1128
+ assert.equal(canonical.gateReferences.find((reference) => reference.attemptId === "canon-gate:1:1")?.resolved, false, "a pre-launch failure stays gate history only");
1129
+ assert.equal(canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId)?.launcher, "gate", "a gate-launched child reports the gate launch family");
1130
+
1131
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
1132
+ handler({ type: "tool_execution_end", toolCallId: "canon-run", toolName: "subagent" }, ctx);
1133
+ }
1134
+ canonical = latestCanonicalPayload();
1135
+ const retainedCanonical = canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId);
1136
+ assert.equal(retainedCanonical.status, "done", "a terminal run keeps an explicit terminal status");
1137
+ assert.ok(Number.isSafeInteger(retainedCanonical.endedAt), "terminal instances carry endedAt");
1138
+ assert.equal(retainedCanonical.capabilities.cancel, false, "a finished run stops advertising cancel");
1139
+ assert.equal(retainedCanonical.capabilities.open, true, "retained rows stay openable");
1140
+
801
1141
  for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
802
1142
  unsubscribeRpc();
803
1143
  delete process.env.PI_WEBUI_SETTINGS_FILE;
@@ -0,0 +1,35 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import test from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
8
+ const html = fs.readFileSync(path.join(root, "public/index.html"), "utf8");
9
+ const css = fs.readFileSync(path.join(root, "public/styles.css"), "utf8");
10
+ const app = fs.readFileSync(path.join(root, "public/app.js"), "utf8");
11
+
12
+ test("active desktop terminal rail exposes an accessible resize separator", () => {
13
+ assert.match(html, /id="terminalTabsResizeHandle"[^>]*role="separator"[^>]*aria-orientation="vertical"[^>]*aria-label="Resize terminal sidebar width"[^>]*tabindex="0"/);
14
+ assert.match(css, /--terminal-tabs-sidebar-width:\s*clamp\(13rem, 18vw, 19rem\)/);
15
+ assert.match(css, /body\.terminal-tabs-left \.chat-panel \{[\s\S]*grid-template-columns:\s*minmax\(0, 1fr\) minmax\(13rem, var\(--terminal-tabs-sidebar-width\)\)/);
16
+ assert.match(css, /\.terminal-tabs-resize-handle \{[\s\S]*left:\s*-0\.78rem/);
17
+ });
18
+
19
+ test("terminal rail supports bounded pointer and keyboard resizing", () => {
20
+ assert.match(app, /function terminalTabsSidebarResizeAvailable\(\)[\s\S]*terminalTabsLayout !== "left"[\s\S]*isSidePanelOverlayView\(\)/);
21
+ assert.match(app, /function terminalTabsSidebarMaxWidth\(\)[\s\S]*transcriptMinWidth = 320[\s\S]*panelWidth \* 0\.72/);
22
+ assert.match(app, /function beginTerminalTabsSidebarResize\(event\)[\s\S]*setPointerCapture[\s\S]*pointermove[\s\S]*pointercancel/);
23
+ assert.match(app, /function updateTerminalTabsSidebarResize\(event\)[\s\S]*terminal-tabs-sidebar-start[\s\S]*delta/);
24
+ assert.match(app, /function handleTerminalTabsSidebarResizeKeydown\(event\)[\s\S]*ArrowLeft[\s\S]*ArrowRight[\s\S]*Home[\s\S]*End/);
25
+ assert.match(app, /elements\.terminalTabsResizeHandle\?\.addEventListener\("pointerdown", beginTerminalTabsSidebarResize\);\nelements\.terminalTabsResizeHandle\?\.addEventListener\("keydown", handleTerminalTabsSidebarResizeKeydown\);/);
26
+ });
27
+
28
+ test("terminal rail width is locally cached and durably restored", () => {
29
+ assert.match(app, /const TERMINAL_TABS_SIDEBAR_WIDTH_STORAGE_KEY = "pi-webui-terminal-tabs-sidebar-width"/);
30
+ assert.match(app, /function persistTerminalTabsSidebarWidth\(width\)[\s\S]*localStorage\.setItem\(TERMINAL_TABS_SIDEBAR_WIDTH_STORAGE_KEY[\s\S]*markDurableUiLayoutDirty\("terminalTabs", "sidebarWidth"\)/);
31
+ assert.match(app, /function collectDurableTerminalTabsLayout\(\)[\s\S]*sidebarWidth: readStoredTerminalTabsSidebarWidth\(\)/);
32
+ assert.match(app, /function applyDurableTerminalTabsLayout\(value\)[\s\S]*value\.sidebarWidth[\s\S]*restoreTerminalTabsSidebarWidthPreference\(\)/);
33
+ assert.match(app, /window\.addEventListener\("storage"[\s\S]*TERMINAL_TABS_SIDEBAR_WIDTH_STORAGE_KEY\) restoreTerminalTabsSidebarWidthPreference\(\)/);
34
+ assert.match(app, /restoreFileViewerWidthPreference\(\);\nrestoreTerminalTabsSidebarWidthPreference\(\);/);
35
+ });
@@ -34,7 +34,7 @@ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "ov
34
34
 
35
35
  assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
36
36
  assert.match(serviceWorker, /"\/theme-contract\.mjs"/, "the PWA app shell should cache the startup-critical theme contract");
37
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v84"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
37
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v94"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
38
  assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
39
39
  assert.match(app, /function themeDraftFromCatalog\(theme, name = theme\?\.name\)[\s\S]*colors: cloneThemeDraft\(theme\?\.colors \|\| \{\}\)/, "catalog metadata should be projected into a schema-only editable draft");
40
40
  assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");