@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
@@ -37,7 +37,7 @@ const forbiddenSinks = [
37
37
  ".focus(", "scrollIntoView", "fetch(", "api(",
38
38
  ];
39
39
 
40
- assert.match(app, /import \{ classifyTranscriptStreamEvent, createStreamOutputController \} from "\.\/stream-output-controller\.mjs";/);
40
+ assert.match(app, /import \{[^}]*classifyTranscriptStreamEvent[^}]*createStreamOutputController[^}]*\} from "\.\/stream-output-controller\.mjs";/);
41
41
  assert.match(controller, /export function classifyTranscriptStreamEvent/);
42
42
  assert.match(controller, /export function createStreamOutputController/);
43
43
  assert.match(controller, /let frameHandle = null;[\s\S]*?let pending = \[\];[\s\S]*?let pendingBytes = 0;/, "controller should retain one cancellable bounded queue");
@@ -70,7 +70,7 @@ assert.doesNotMatch(rawMessageHandler, /setRunIndicatorActivity|scheduleLiveTodo
70
70
  assert.match(rawMessageHandler, /compactOutputActive\(\) && handleCompactMessageUpdate\(event\)/, "normal and compact modes should share the isolated controller sink");
71
71
  assert.match(toolUpdate, /renderLiveToolRun\(run, \{ scroll: false \}\)/, "isolated tool updates should render in the controller frame rather than queue another tool frame");
72
72
  assert.doesNotMatch(toolUpdate, /scheduleLiveToolRunRender/, "isolated tool updates must not create a parallel render queue");
73
- assert.match(app, /applyToolExecutionUpdate: \(event\) => \{\s+if \(!compactOutputActive\(\)\) applyTranscriptToolExecutionUpdate\(event\);/, "raw tool execution updates should use only the transcript sink");
73
+ assert.match(app, /applyToolExecutionUpdate: \(event\) => \{\s+if \(!compactOutputActive\(\) && !isIntercomTransportToolName\(event\?\.toolName\)\) applyTranscriptToolExecutionUpdate\(event\);/, "raw non-Intercom tool execution updates should use only the transcript sink");
74
74
  assert.doesNotMatch(app.slice(app.indexOf("const streamOutputController"), app.indexOf("let assistantErrorSurfacedThisRun")), /renderWidgets|renderFooter|renderTabs|renderStatus|renderFeedbackTray|setRunIndicatorActivity|scheduleLiveTodoProgressWidgetSync|addEvent|fetch\(|api\(/, "controller integration must inject transcript-only sinks");
75
75
  const connectEvents = functionBody(app, "connectEvents");
76
76
  assert.match(connectEvents, /streamOutputController\.cancel\(\);[\s\S]*?resetCompactLiveOutput\(\);/, "reconnect and tab switches should cancel retained raw frames before resetting live output");
@@ -92,6 +92,8 @@ const scrollChatToBottom = findFunctionBody(app, "scrollChatToBottom");
92
92
  const stripTodoProgressLines = findFunctionBody(app, "stripTodoProgressLines");
93
93
  const liveTodoProgressWidgetLinesFromText = findFunctionBody(app, "liveTodoProgressWidgetLinesFromText");
94
94
  const syncStreamingThinkingFormat = findFunctionBody(app, "syncStreamingThinkingFormat");
95
+ const setStreamThinkingRawText = findFunctionBody(app, "setStreamThinkingRawText");
96
+ const syncStreamingThinkingFromUpdate = findFunctionBody(app, "syncStreamingThinkingFromUpdate");
95
97
  const renderStreamingAssistantText = findFunctionBody(app, "renderStreamingAssistantText");
96
98
  const renderStreamingMarkdown = findFunctionBody(app, "renderStreamingMarkdown");
97
99
  const setRunIndicatorActivity = findFunctionBody(app, "setRunIndicatorActivity");
@@ -133,6 +135,9 @@ assert.match(styles, /\.chat > \.message:first-of-type \{ margin-top:\s*0; \}/,
133
135
  assert.doesNotMatch(styles, /\.chat > \.message:first-of-type \{ margin-top:\s*auto; \}/, "short transcripts must not follow the moving composer edge while the user types");
134
136
  assert.match(appendOptimisticUserPrompt, /renderAllMessages\(\);[\s\S]*?scrollChatToBottom\(\{ force:\s*true \}\);/, "submitting a prompt should explicitly resume bottom-follow for the new turn");
135
137
  assert.doesNotMatch(appendOptimisticUserPrompt, /if \(autoFollowChat \|\| isChatNearBottom\(\)\)/, "a paused reader position should not leave a newly submitted turn off-screen");
138
+ assert.match(app, /import \{[^}]*reconcileTranscriptThinkingSnapshot[^}]*\} from "\.\/stream-output-controller\.mjs";/, "the browser should import the tested thinking-snapshot reconciler");
139
+ assert.match(setStreamThinkingRawText, /reconcile\s*\?\s*reconcileTranscriptThinkingSnapshot\(streamThinkingRawText, snapshot\)/, "thinking state should support prefix-safe snapshot reconciliation");
140
+ assert.match(syncStreamingThinkingFromUpdate, /update\.type === "thinking_end"[\s\S]*?setStreamThinkingRawText\(delta, \{ reconcile: true \}\)[\s\S]*?setStreamThinkingRawText\(fallback, \{ reconcile: true \}\)/, "thinking_end snapshots and fallbacks must not cut off an already-rendered compatible tail");
136
141
 
137
142
  futureInvariant("theory #1: message_update streaming hot path must not call immediate scroll/layout work", () => {
138
143
  assert.doesNotMatch(handleMessageUpdate, /scrollChatToBottom\s*\(/, "handleMessageUpdate should schedule/coalesce follow-scroll instead of calling scrollChatToBottom() directly");
@@ -71,7 +71,8 @@ const [app, css, serviceWorker, server, pkgRaw] = await Promise.all([
71
71
  const pkg = JSON.parse(pkgRaw);
72
72
 
73
73
  assert.match(app, /from "\.\/subagent-gate-visibility\.mjs"/, "the browser should load the retry-gate visibility policy");
74
- assert.match(app, /function subagentTabsWithRunningAgents\(\)[\s\S]*latestSubagents\?\.updatedAt[\s\S]*visibleSubagentGates\(tab, dismissedSubagentGateKeys, now\)[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*displayRuns/, "the side panel should filter retry-gated runs while retaining the gate attempts as their only rows");
74
+ assert.match(app, /function subagentOverviewGroups[\s\S]*Number\(data\?\.version\) === 2[\s\S]*displayRuns: runs/, "the side panel should render canonical v2 runs without recounting gate references");
75
+ assert.match(app, /const gates = visibleSubagentGates\(tab, dismissedSubagentGateKeys, now\);[\s\S]*const displayRuns = ungatedSubagentRuns\(tab\);[\s\S]*displayRuns,/, "the v1 fallback should retain gate-owned run filtering before deriving count-neutral workflow totals");
75
76
  assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*subagentGateIsTerminal\(gate\)[\s\S]*Hide finished retry gate[\s\S]*dismissedSubagentGateKeys\.add\(key\)[\s\S]*renderSubagents\(\)[\s\S]*event\.detail === 0[\s\S]*focusTarget\?\.focus/, "terminal gate cards should expose an accessible hide button and preserve keyboard focus after rerendering");
76
77
  assert.match(app, /pruneDismissedSubagentGateKeys\(latestSubagents\?\.tabs, dismissedSubagentGateKeys\)/, "polling should prune stale dismissal keys");
77
78
  assert.match(css, /\.subagent-gate-actions[\s\S]*\.subagent-gate-close[\s\S]*min-width:\s*1\.45rem[\s\S]*background:\s*transparent[\s\S]*\.subagent-gate-close:hover,[\s\S]*\.subagent-gate-close:focus-visible/, "the close control should remain minimal, compact, and keyboard-visible");
@@ -125,7 +125,7 @@ try {
125
125
  await writeFile(settingsFile, `${JSON.stringify({ version: 4, unrelated: { preserve: true }, remoteAuthEnabled: true }, null, 2)}\n`, "utf8");
126
126
  await writeWebuiSettings({ subagentLaunchSlots: config }, settingsFile);
127
127
  const persisted = JSON.parse(await readFile(settingsFile, "utf8"));
128
- assert.equal(persisted.version, 6, "persisted launch-slot settings must retain the current version-6 envelope");
128
+ assert.equal(persisted.version, 8, "persisted launch-slot settings must retain the current version-8 envelope");
129
129
  assert.deepEqual(persisted.unrelated, { preserve: true }, "launch-slot saves must preserve unrelated WebUI settings");
130
130
  assert.deepEqual((await readWebuiSettings(settingsFile)).subagentLaunchSlots.projects[projectKey].roles, defaultRoles);
131
131
 
@@ -0,0 +1,32 @@
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
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, html, css, worker] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "index.html"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
12
+ ]);
13
+
14
+ assert.match(app, /function subagentOverviewGroups[\s\S]*Number\(data\?\.version\) === 2[\s\S]*Array\.isArray\(data\?\.groups\)[\s\S]*Array\.isArray\(data\?\.tabs\)/, "browser should prefer v2 groups while retaining a v1 tabs fallback");
15
+ for (const label of ["SDK", "Pi RPC", "Pi JSON", "Pi print", "Pi session", "tmux", "pi-subagents", "scheduled", "gate", "workflow", "custom"]) assert.ok(app.includes(`"${label}"`), `launcher label ${label} should be present`);
16
+ for (const state of ["queued", "running", "stale", "lost", "done", "failed", "cancelled"]) {
17
+ assert.ok(app.includes(`"${state}"`), `lifecycle ${state} should be normalized`);
18
+ assert.match(css, new RegExp(`\\.subagent-state-dot\\.${state}`), `lifecycle ${state} should have a distinct CSS state`);
19
+ }
20
+ assert.match(app, /function subagentRunAgentCounts[\s\S]*function renderSubagents\(\)[\s\S]*activeTabs\.reduce\(\(count, tab\) => count \+ Number\(tab\.agentCount \|\| 0\), 0\)[\s\S]*activeTabs\.reduce\(\(count, tab\) => count \+ Number\(tab\.runningAgents \|\| 0\), 0\)[\s\S]*activeTabs\.reduce\(\(count, tab\) => count \+ Number\(tab\.staleAgents \|\| 0\), 0\)/, "visible retained-inclusive agent totals should exclude count-neutral workflow controllers while preserving running and stale breakdowns");
21
+ assert.match(app, /URLSearchParams\(\{ group: selection\.groupId, run: selection\.runId, agent: selection\.agentId \}\)/, "overlay should use the unified group/run/agent output query");
22
+ assert.match(app, /URLSearchParams\(\{ group: view\.groupId, run: view\.runId, agent: view\.agentId \}\)/, "view-only tab should use the unified group/run/agent output query");
23
+ assert.match(app, /subagentRunCanRefresh[\s\S]*subagentRunCanCancel[\s\S]*subagentRunCanDismiss/, "controls should be capability-aware");
24
+ assert.match(app, /function subagentRunIsAttachedProjection[\s\S]*source === "explicit-attach"[\s\S]*function subagentRunCanDismiss[\s\S]*provider === "webui-registry"/, "terminal registry rows should clear while stale explicit attaches remain manually detachable");
25
+ assert.match(app, /function finishedSubagentRunSelections[\s\S]*subagentRunIsTerminal\(run\) && subagentRunCanDismiss\(run\)/, "Auto-Clear should not immediately remove stale attached sessions");
26
+ assert.match(app, /agent\.unavailableReason[\s\S]*Output is unavailable for this registered agent/, "output views should show truthful unavailable evidence");
27
+ assert.match(css, /\.subagent-source-badge[\s\S]*text-overflow: ellipsis[\s\S]*@media \(max-width: 720px\)/, "source badges should remain compact and responsive");
28
+ assert.match(html, /Managed and registered Pi agent runs[\s\S]*External agents/, "help should explain managed, registered, and external groups");
29
+ assert.match(html, /styles\.css\?v=123[\s\S]*app\.js\?v=146/, "browser assets should use the WS-D revisions");
30
+ assert.match(worker, /pi-webui-pwa-v108/, "PWA cache identity should advance with WS-D browser assets");
31
+
32
+ console.log("subagent-observability-static.test.mjs passed");
@@ -0,0 +1,183 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import vm from "node:vm";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [server, app, helper] = await Promise.all([
9
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8").then((value) => value.replace(/\r\n/g, "\n")),
10
+ readFile(join(root, "public", "app.js"), "utf8").then((value) => value.replace(/\r\n/g, "\n")),
11
+ readFile(join(root, "webui-rpc-helper.mjs"), "utf8").then((value) => value.replace(/\r\n/g, "\n")),
12
+ ]);
13
+
14
+ function sourceBetween(text, start, end) {
15
+ const startIndex = text.indexOf(start);
16
+ const endIndex = text.indexOf(end, startIndex);
17
+ assert.ok(startIndex >= 0 && endIndex > startIndex, `expected source boundaries: ${start} -> ${end}`);
18
+ return text.slice(startIndex, endIndex);
19
+ }
20
+
21
+ const normalizationSource = sourceBetween(
22
+ server,
23
+ "function normalizeWebuiSubagentText(",
24
+ "\nfunction rememberWebuiSubagentsStatusEvent(",
25
+ );
26
+ const normalizationContext = {
27
+ WEBUI_SUBAGENT_RUN_LIMIT: 128,
28
+ WEBUI_SUBAGENT_AGENT_LIMIT: 256,
29
+ WEBUI_SUBAGENT_GATE_LIMIT: 32,
30
+ WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT: 100,
31
+ };
32
+ vm.runInNewContext(`${normalizationSource}\nthis.normalizePayload = normalizeWebuiSubagentPayload; this.filterStartup = filterStartupInactiveRows;`, normalizationContext);
33
+ const normalized = normalizationContext.normalizePayload({
34
+ version: 1,
35
+ available: true,
36
+ updatedAt: 100,
37
+ fleet: {
38
+ version: 1,
39
+ totalActive: 4,
40
+ omitted: 3,
41
+ entries: [{ key: "private-key", prompt: "private prompt", cwd: "C:/private" }],
42
+ privatePath: "C:/private",
43
+ },
44
+ privatePrompt: "do not expose",
45
+ runs: [{
46
+ id: "fleet:opaque",
47
+ source: "recovered",
48
+ provisional: true,
49
+ controllable: false,
50
+ status: "running",
51
+ startedAt: 10,
52
+ prompt: "private child prompt",
53
+ agents: [{ id: "fleet:opaque:agent", name: "Recovery scout", status: "running", model: "provider/model", thinking: "high", currentPath: "C:/private" }],
54
+ }],
55
+ });
56
+ assert.deepEqual(JSON.parse(JSON.stringify(normalized.fleet)), { version: 1, totalActive: 4, omitted: 3 }, "server should expose only bounded fleet aggregates");
57
+ const ordinary = normalizationContext.normalizePayload({
58
+ version: 1,
59
+ runs: [{ id: "run-ordinary", source: "async", status: "running", agents: [{ name: "worker", status: "running" }] }],
60
+ });
61
+ assert.equal(Object.hasOwn(ordinary.runs[0], "provisional"), false, "ordinary payload v1 rows should not gain recovery-only provisional metadata");
62
+ assert.equal(Object.hasOwn(ordinary.runs[0], "controllable"), false, "ordinary payload v1 rows should not gain recovery-only control metadata");
63
+ const startupTab = {};
64
+ const firstStartupSnapshot = normalizationContext.filterStartup(startupTab, {
65
+ runs: [
66
+ { id: "active-before-start", status: "running" },
67
+ { id: "done-before-start", status: "done" },
68
+ ],
69
+ }, { rowsKey: "runs", stateKey: "fixtureStartup" });
70
+ assert.deepEqual(Array.from(firstStartupSnapshot.runs, (run) => run.id), ["active-before-start"], "the first helper snapshot should suppress pre-existing inactive runs");
71
+ const currentGenerationSnapshot = normalizationContext.filterStartup(startupTab, {
72
+ runs: [
73
+ { id: "done-before-start", status: "done" },
74
+ { id: "done-after-start", status: "done" },
75
+ ],
76
+ }, { rowsKey: "runs", stateKey: "fixtureStartup" });
77
+ assert.deepEqual(Array.from(currentGenerationSnapshot.runs, (run) => run.id), ["done-after-start"], "later terminal runs should remain visible while startup-suppressed identities stay hidden");
78
+ const reactivatedSnapshot = normalizationContext.filterStartup(startupTab, {
79
+ runs: [{ id: "done-before-start", status: "running" }],
80
+ }, { rowsKey: "runs", stateKey: "fixtureStartup" });
81
+ assert.deepEqual(Array.from(reactivatedSnapshot.runs, (run) => run.id), ["done-before-start"], "an active transition should release startup suppression");
82
+ assert.match(server, /filterStartupInactiveRows\(tab, payload,[\s\S]*rowsKey: "instances"[\s\S]*filterStartupInactiveRows\(tab, payload,[\s\S]*rowsKey: "runs"[\s\S]*startupSuppressedAgentRunProjectionKeys\.has\(key\)[\s\S]*!agentRunIsActive\(record\.instance\)/, "helper snapshots and startup registry records should both exclude pre-existing inactive rows");
83
+ assert.deepEqual(JSON.parse(JSON.stringify(normalized.runs[0])), {
84
+ id: "fleet:opaque",
85
+ source: "recovered",
86
+ provisional: true,
87
+ controllable: false,
88
+ mode: "single",
89
+ status: "running",
90
+ startedAt: 10,
91
+ agents: [{
92
+ id: "fleet:opaque:agent",
93
+ name: "Recovery scout",
94
+ status: "running",
95
+ index: 0,
96
+ model: "provider/model",
97
+ thinking: "high",
98
+ nested: false,
99
+ }],
100
+ }, "server should preserve public recovery flags without leaking prompt, path, or raw fleet-entry fields");
101
+ assert.equal(normalizationContext.normalizePayload({ version: 1, fleet: { version: 1, totalActive: 1, omitted: 2 }, runs: [] }).fleet, null, "invalid aggregate counts should be discarded");
102
+
103
+ const canonicalProjectionSource = sourceBetween(
104
+ helper,
105
+ "function canonicalInstancesFromPublicRun(",
106
+ "\n /**\n * Canonical, deduplicated projection",
107
+ );
108
+ assert.match(canonicalProjectionSource, /Number\.isFinite\(run\.endedAt\) \? run\.endedAt : startedAt/, "a terminal run without endedAt should use one stable fallback timestamp");
109
+ assert.doesNotMatch(canonicalProjectionSource, /endedAt[^\n]*Date\.now\(\)/, "terminal projection timestamps must not change on every status poll");
110
+ assert.match(canonicalProjectionSource, /open: true,[\s\S]*refresh: true,[\s\S]*cancel: status === "running" && !workflow && !recovered[\s\S]*outputRef: \{ kind: "helper"/, "recovered fleet rows should expose a read-only helper output view while lifecycle control remains blocked");
111
+ assert.match(server, /unavailable: rawAgent\.unavailable === true[\s\S]*unavailableReason: rawAgent\.unavailable === true/, "server normalization should preserve truthful recovered-output unavailability metadata");
112
+
113
+ const interactionSource = sourceBetween(
114
+ server,
115
+ "function webuiSubagentRunSupportsInteraction(",
116
+ "\nfunction restorableTabDescriptor(",
117
+ );
118
+ assert.match(interactionSource, /source !== "recovered"[\s\S]*provisional !== true[\s\S]*controllable !== false/, "server should treat every unsupported recovery signal as non-interactive");
119
+ assert.match(interactionSource, /requireInteractiveWebuiSubagentRun[\s\S]*!webuiSubagentRunSupportsInteraction\(run\)[\s\S]*webuiSubagentOutputData[\s\S]*requireInteractiveWebuiSubagentRun/, "output lookup should reject unsupported rows before helper dispatch");
120
+ assert.match(server, /\/api\/subagents\/cancel[\s\S]*rejectUnsupportedWebuiSubagentRun\(tab, body\.runId\)[\s\S]*\/api\/subagents\/dismiss[\s\S]*rejectUnsupportedWebuiSubagentRun\(tab, body\.runId\)/, "cancel and dismiss routes should reject unsupported recovered rows before helper dispatch");
121
+
122
+ const renderAgentSource = sourceBetween(app, "function renderSubagentAgent(", "\nfunction renderSubagentRun(");
123
+ assert.match(renderAgentSource, /make\(interactive \? "button" : "div"[\s\S]*metadata-only[\s\S]*if \(interactive\)[\s\S]*openSubagentOutput[\s\S]*output is unavailable from this provider/, "unsupported rows should use truthful non-button rendering with no output affordance");
124
+ const materializationSource = sourceBetween(app, "function materializeRetainedSubagentTerminalViews(", "\nfunction subagentTerminalViewGroups(");
125
+ assert.match(materializationSource, /subagentAgentStatus\(run\)[\s\S]*ensureSubagentTerminalView/, "only terminal open-capable rows should materialize retained terminal views");
126
+ assert.match(app, /function subagentRunCanCancel[\s\S]*capabilities\.cancel === true/, "canonical capability ownership should gate cancellation");
127
+ assert.match(app, /function subagentRunIsTerminal[\s\S]*\["done", "failed", "cancelled"\]/, "clear-finished should select only explicit terminal lifecycle states");
128
+ assert.match(app, /function subagentRunIsAttachedProjection[\s\S]*source === "explicit-attach"[\s\S]*\["stale", "lost"\]/, "stale explicit attached sessions should be manually detachable");
129
+ assert.match(app, /function subagentRunCanDismiss[\s\S]*subagentRunIsAttachedProjection\(run\)[\s\S]*provider === "webui-registry"/, "terminal registry projections and explicit attaches should expose the appropriate manual dismissal control");
130
+ assert.match(app, /function finishedSubagentRunSelections[\s\S]*subagentRunIsTerminal\(run\) && subagentRunCanDismiss\(run\)/, "auto-clear should remain limited to genuinely terminal rows");
131
+ assert.match(server, /function agentRunProjectionCanBeDismissed[\s\S]*origin === "explicit-attach"[\s\S]*dismissedAgentRunProjectionKeys\.has\(key\)[\s\S]*agentRunProjectionCanBeDismissed\(record\.instance\)[\s\S]*selection\.kind === "registry"[\s\S]*registrySelections[\s\S]*dismissAgentRunProjection\(candidate\.instance\)/, "registry dismissal should retain bounded tombstones only for terminal or explicit-attach WebUI projections");
132
+ const viewSyncSource = sourceBetween(app, "function syncSubagentTerminalViewsFromOverview(", "\nfunction materializeRetainedSubagentTerminalViews(");
133
+ assert.match(viewSyncSource, /run && !subagentRunCanOpen\(run,[\s\S]*subagentTerminalViews\.delete/, "a row that loses open capability should close an existing terminal output view");
134
+ assert.match(viewSyncSource, /run && !subagentRunCanOpen\(run,[\s\S]*subagentOverlaySelection = null/, "a row that loses open capability should close an existing output overlay");
135
+ assert.match(app, /async function openSubagentOverlay\(tab, run, agent\)[\s\S]*!subagentRunCanOpen\(run, agent\)/, "direct overlay entry should reject unsupported rows");
136
+ assert.match(app, /function subagentGateAttemptTarget\(tab, attempt\)[\s\S]*subagentRunCanOpen\(run, agent\)/, "retry-gate output entry should reject unsupported rows");
137
+
138
+ const refreshSource = sourceBetween(app, "async function refreshSubagents(", "\nfunction scheduleRefreshSubagents(");
139
+ let resolveFirst;
140
+ let resolveSecond;
141
+ let apiCalls = 0;
142
+ const firstResponse = new Promise((resolve) => { resolveFirst = resolve; });
143
+ const secondResponse = new Promise((resolve) => { resolveSecond = resolve; });
144
+ const refreshContext = {
145
+ subagentsRefreshPromise: null,
146
+ subagentsRefreshQueued: false,
147
+ subagentsLoading: false,
148
+ latestSubagents: null,
149
+ subagentsError: null,
150
+ dismissedSubagentGateKeys: new Set(),
151
+ subagentOverlaySelection: null,
152
+ activeTabId: "tab-a",
153
+ activeSubagentTerminalId: null,
154
+ subagentAutoClearEnabled: false,
155
+ renderSubagents() {},
156
+ pruneDismissedSubagentGateKeys() {},
157
+ syncSubagentTerminalViewsFromOverview() { return false; },
158
+ materializeRetainedSubagentTerminalViews() { return false; },
159
+ renderWidgets() {},
160
+ renderSubagentTerminalView() {},
161
+ scheduleSubagentTerminalRefresh() {},
162
+ renderTabs() {},
163
+ finishedSubagentRunSelections() { return []; },
164
+ async clearFinishedSubagentRuns() {},
165
+ api() {
166
+ apiCalls += 1;
167
+ return apiCalls === 1 ? firstResponse : secondResponse;
168
+ },
169
+ };
170
+ vm.runInNewContext(`${refreshSource}\nthis.runRefreshSubagents = refreshSubagents;`, refreshContext);
171
+ const initialRefresh = refreshContext.runRefreshSubagents();
172
+ const overlappingRefresh = refreshContext.runRefreshSubagents();
173
+ assert.equal(apiCalls, 1, "an overlapping refresh should coalesce while the first request is in flight");
174
+ resolveFirst({ data: { revision: "stale" } });
175
+ await new Promise((resolve) => setImmediate(resolve));
176
+ assert.equal(apiCalls, 2, "an overlapping request should guarantee one trailing authoritative refresh");
177
+ resolveSecond({ data: { revision: "authoritative" } });
178
+ await Promise.all([initialRefresh, overlappingRefresh]);
179
+ assert.equal(refreshContext.latestSubagents?.revision, "authoritative", "the trailing refresh should own final browser state");
180
+ assert.equal(refreshContext.subagentsLoading, false, "coalesced refresh should release its loading guard");
181
+ assert.equal(refreshContext.subagentsRefreshPromise, null, "coalesced refresh should clear its shared promise");
182
+
183
+ console.log("subagent-reliability-integration.test.mjs passed");
@@ -0,0 +1,67 @@
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 vm from "node:vm";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, css, readme, technical] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "README.md"), "utf8"),
12
+ readFile(join(root, "TECHNICAL.md"), "utf8"),
13
+ ]);
14
+
15
+ function appFunctionSource(name, nextName) {
16
+ const start = app.indexOf(`function ${name}(`);
17
+ const nextStarts = [
18
+ app.indexOf(`\nfunction ${nextName}(`, start),
19
+ app.indexOf(`\nasync function ${nextName}(`, start),
20
+ ].filter((index) => index > start);
21
+ const end = nextStarts.length ? Math.min(...nextStarts) : -1;
22
+ assert.ok(start >= 0 && end > start, `${name} should remain a standalone frontend helper`);
23
+ return app.slice(start, end);
24
+ }
25
+
26
+ const workflowControllerSource = appFunctionSource("subagentIsWorkflowController", "subagentCapabilities");
27
+ const workflowRenderSource = appFunctionSource("renderSubagentWorkflow", "renderSubagentAgent");
28
+ const renderRunSource = appFunctionSource("renderSubagentRun", "subagentGateStatusLabel");
29
+ const renderOverviewSource = appFunctionSource("renderSubagents", "refreshSubagents");
30
+ const retainedMaterializationSource = appFunctionSource("materializeRetainedSubagentTerminalViews", "subagentTerminalViewGroups");
31
+
32
+ assert.match(workflowControllerSource, /launcher === "pi-subagents"[\s\S]*function subagentRunAgents[\s\S]*function subagentRunAgentCounts/, "pi-subagents workflow controllers should be separated from model-powered child agents");
33
+ const workflowCountContext = {
34
+ subagentAgentStatus(run, agent) { return String(agent?.status || run?.status || "running").toLowerCase(); },
35
+ };
36
+ vm.runInNewContext(`${workflowControllerSource}\nthis.isWorkflowController = subagentIsWorkflowController; this.workflowAgents = subagentRunAgents; this.workflowCounts = subagentRunAgentCounts; this.runPresentations = subagentRunPresentations; this.workflowStatus = subagentWorkflowPresentationStatus;`, workflowCountContext);
37
+ const syntheticWorkflowRun = {
38
+ launcher: "pi-subagents",
39
+ status: "running",
40
+ agents: [
41
+ { id: "run:workflow", name: "workflow", status: "running" },
42
+ { id: "run:worker", name: "worker", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" },
43
+ ],
44
+ };
45
+ assert.equal(workflowCountContext.isWorkflowController(syntheticWorkflowRun, syntheticWorkflowRun.agents[0]), true);
46
+ assert.deepEqual(JSON.parse(JSON.stringify(workflowCountContext.workflowAgents(syntheticWorkflowRun).map((agent) => agent.name))), ["worker"]);
47
+ assert.deepEqual(JSON.parse(JSON.stringify(workflowCountContext.workflowCounts([syntheticWorkflowRun]))), { total: 1, running: 1, stale: 0 });
48
+ assert.equal(workflowCountContext.isWorkflowController(syntheticWorkflowRun, { name: "workflow", launcher: "pi-subagents", model: "provider/real-model", thinking: "high" }), false, "a real model-powered agent named workflow must remain an agent row");
49
+
50
+ const recoveredWorkflowRuns = [
51
+ { id: "fleet:23", source: "recovered", launcher: "pi-subagents", status: "done", agents: [{ id: "fleet:23:agent", name: "workflow", status: "done" }] },
52
+ { id: "fleet:24", source: "recovered", launcher: "pi-subagents", status: "running", agents: [{ id: "fleet:24:agent", name: "worker", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" }] },
53
+ ];
54
+ const recoveredPresentations = workflowCountContext.runPresentations(recoveredWorkflowRuns);
55
+ assert.equal(recoveredPresentations.length, 1, "adjacent recovered workflow controller and worker runs should form one presentation section");
56
+ assert.equal(recoveredPresentations[0].agents[0].run.id, "fleet:24", "nested recovered workers should retain their original run for output selection");
57
+ assert.equal(workflowCountContext.workflowStatus(recoveredPresentations[0].run, recoveredPresentations[0].agents), "running", "a running recovered worker should keep its workflow section running");
58
+
59
+ assert.match(workflowRenderSource, /const status = subagentWorkflowPresentationStatus\(run, agents\);[\s\S]*make\("details", `subagent-workflow[\s\S]*details\.open = !collapsedSubagentWorkflowRunKeys\.has\(key\)[\s\S]*make\("summary", "subagent-workflow-header"\)[\s\S]*renderSubagentAgent\(tab, entry\.run, entry\.agent\)/, "workflow controllers should render as native disclosures using the aggregate presentation lifecycle while preserving each child run");
60
+ assert.match(renderRunSource, /subagentWorkflowController\(run\)[\s\S]*subagentRunAgents\(run\)[\s\S]*renderSubagentWorkflow\(tab, run, controller, presentedAgents\)/, "workflow runs should route through the hierarchical renderer");
61
+ assert.match(renderOverviewSource, /activeTabs\.reduce\(\(count, tab\) => count \+ Number\(tab\.agentCount \|\| 0\), 0\)[\s\S]*activeTabs\.reduce\(\(count, tab\) => count \+ Number\(tab\.runningAgents \|\| 0\), 0\)/, "overview totals should use count-neutral workflow projections");
62
+ assert.match(retainedMaterializationSource, /for \(const agent of subagentRunAgents\(run\)\)/, "retained terminal views should materialize child agents without creating a view for the workflow controller");
63
+ assert.match(css, /\.subagent-workflow \{[\s\S]*\.subagent-workflow-header \{[\s\S]*list-style: none;[\s\S]*\.subagent-workflow:not\(\[open\]\)[\s\S]*\.subagent-workflow-agents \{[\s\S]*border-left:/, "workflow disclosures should have a distinct header and nested child-agent rail");
64
+ assert.match(readme, /workflow[^\n]*collapsible/i, "the user guide should explain collapsible workflow groups");
65
+ assert.match(technical, /workflow controller[^\n]*count/i, "the technical reference should explain count-neutral workflow controllers");
66
+
67
+ console.log("subagent workflow section static tests passed");