@firstpick/pi-package-webui 0.8.0 → 0.8.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 (63) hide show
  1. package/README.md +34 -5
  2. package/bin/pi-webui.mjs +606 -102
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/npm-command.mjs +81 -0
  5. package/lib/queue-mutation.mjs +6 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +8 -3
  9. package/public/app.js +4231 -376
  10. package/public/index.html +265 -52
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1790 -383
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  18. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  19. package/tests/browser/interaction-continuity.spec.mjs +897 -0
  20. package/tests/browser/mobile-foundation.spec.mjs +363 -0
  21. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  22. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  23. package/tests/browser/stats-overlay.spec.mjs +265 -0
  24. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  25. package/tests/codex-fast-mode-static.test.mjs +8 -5
  26. package/tests/compact-sections-static.test.mjs +20 -2
  27. package/tests/compaction-mutation-contract.test.mjs +18 -4
  28. package/tests/compaction-static.test.mjs +1 -0
  29. package/tests/completion-signal-contract.test.mjs +13 -2
  30. package/tests/component-update-api-static.test.mjs +67 -0
  31. package/tests/component-update-state.test.mjs +80 -0
  32. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  33. package/tests/fast-mode-client-static.test.mjs +7 -4
  34. package/tests/fixtures/fake-pi.mjs +305 -2
  35. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  36. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  37. package/tests/http-endpoints-harness.test.mjs +228 -2
  38. package/tests/interaction-state-stability-static.test.mjs +271 -0
  39. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  40. package/tests/mobile-foundation-static.test.mjs +71 -0
  41. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  42. package/tests/mobile-shell-state.test.mjs +69 -0
  43. package/tests/mobile-static.test.mjs +246 -39
  44. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  45. package/tests/native-parity-harness.test.mjs +2 -0
  46. package/tests/npm-command.test.mjs +64 -1
  47. package/tests/open-issue-wizard-static.test.mjs +2 -1
  48. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  49. package/tests/queue-mutation-contract.test.mjs +22 -0
  50. package/tests/service-worker-lifecycle.test.mjs +120 -0
  51. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  52. package/tests/sse-backpressure-harness.test.mjs +137 -0
  53. package/tests/stats-dashboard-static.test.mjs +266 -0
  54. package/tests/streaming-ui-coupling.test.mjs +7 -1
  55. package/tests/subagent-gate-visibility.test.mjs +18 -2
  56. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  57. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  58. package/tests/subagents-helper.test.mjs +90 -0
  59. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  60. package/tests/update-commands.test.mjs +4 -0
  61. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  62. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  63. package/webui-rpc-helper.mjs +175 -3
@@ -0,0 +1,34 @@
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 = await readFile(join(root, "public", "app.js"), "utf8");
8
+ const TAB_COUNT = 10;
9
+ const MESSAGES_PER_TAB = 30;
10
+ const TOOL_OUTPUT_BYTES = 128 * 1024;
11
+ const DEFER_NO_GO_BYTES = 32 * 1024 * 1024;
12
+
13
+ // This matches the current cache's retained shape: a complete messages array
14
+ // per open tab. Use unique tool output per message so JavaScript cannot hide
15
+ // the multi-tab payload behind one shared string reference.
16
+ const cache = new Map();
17
+ const heapBefore = process.memoryUsage().heapUsed;
18
+ for (let tabIndex = 0; tabIndex < TAB_COUNT; tabIndex += 1) {
19
+ const messages = Array.from({ length: MESSAGES_PER_TAB }, (_, messageIndex) => ({
20
+ role: "toolExecution",
21
+ toolName: "fixture-tool",
22
+ result: `${tabIndex}:${messageIndex}:${"x".repeat(TOOL_OUTPUT_BYTES - 32)}`,
23
+ }));
24
+ cache.set(`tab-${tabIndex}`, { messages, sessionKey: `tab-${tabIndex}|fixture-session` });
25
+ }
26
+ const retainedBytes = Buffer.byteLength(JSON.stringify([...cache.values()].flatMap((entry) => entry.messages)));
27
+ const heapDelta = Math.max(0, process.memoryUsage().heapUsed - heapBefore);
28
+
29
+ assert.match(app, /const tabMessagesCache = new Map\(\)/, "the characterization must cover the real per-tab cache");
30
+ assert.match(app, /function cacheMessagesForTab[\s\S]*?tabMessagesCache\.set\(tabId, \{ messages, sessionKey: resolvedSessionKey \}\)/, "the current cache retains complete message arrays by tab");
31
+ assert.ok(retainedBytes >= DEFER_NO_GO_BYTES, "the 10-tab long-tool fixture must cross the documented defer/no-go threshold");
32
+ assert.equal(cache.size, TAB_COUNT);
33
+
34
+ console.log(`mobile transcript characterization: ${TAB_COUNT} tabs × ${MESSAGES_PER_TAB} long tool messages retained ${Math.round(retainedBytes / (1024 * 1024))} MiB serialized; heap delta ${Math.round(heapDelta / (1024 * 1024))} MiB. Defer in-memory bounding until it preserves every authoritative final answer and transcript; ${DEFER_NO_GO_BYTES / (1024 * 1024)} MiB retained serialized payload is the follow-up threshold.`);
@@ -42,7 +42,9 @@ assert.equal(isLocalRequest(remoteReq), false);
42
42
 
43
43
  assert.throws(() => requireLocalhost(remoteReq, "blocked"), (error) => error.statusCode === 403);
44
44
  assert.throws(() => requireLocalhostRoute(remoteReq, "/api/update"), (error) => error.statusCode === 403);
45
+ assert.throws(() => requireLocalhostRoute(remoteReq, "/api/component-update"), (error) => error.statusCode === 403);
45
46
  assert.doesNotThrow(() => requireLocalhostRoute(localReq, "/api/update"));
47
+ assert.doesNotThrow(() => requireLocalhostRoute(localReq, "/api/component-update"));
46
48
  assert.ok(LOCALHOST_ONLY_POST_ROUTES.has("/api/workflow-policy"), "workflow policy mutation must stay in the canonical localhost route registry");
47
49
 
48
50
  for (const pathname of LOCALHOST_ONLY_POST_ROUTES.keys()) {
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import path from "node:path";
3
- import { resolveNpmCommandInvocation } from "../lib/npm-command.mjs";
3
+ import { prependPathDirectory, prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
4
4
 
5
5
  const windowsExecPath = "C:\\PortableNode\\node.exe";
6
6
  const bundledCli = "C:\\PortableNode\\node_modules\\npm\\bin\\npm-cli.js";
@@ -26,12 +26,75 @@ const fromPath = resolveNpmCommandInvocation(["root", "-g"], {
26
26
  });
27
27
  assert.deepEqual(fromPath.args, [pathCli, "root", "-g"], "Windows resolution should find npm-cli.js beside an npm directory on PATH");
28
28
 
29
+ const selectedPiDirectory = "C:\\PortablePi";
30
+ const selectedPi = `${selectedPiDirectory}\\pi`;
31
+ const selectedPiNpmCli = `${selectedPiDirectory}\\node_modules\\npm\\bin\\npm-cli.js`;
32
+ const staleNpmDirectory = "C:\\Users\\Example\\AppData\\Roaming\\npm";
33
+ const selectedDirectory = resolveCommandDirectory("pi", {
34
+ platform: "win32",
35
+ env: { PATH: `${staleNpmDirectory};${selectedPiDirectory}` },
36
+ existsSync: (candidate) => path.win32.normalize(candidate) === path.win32.normalize(selectedPi),
37
+ });
38
+ assert.equal(selectedDirectory, selectedPiDirectory, "Pi should be resolved from its actual PATH entry, not an unrelated earlier npm directory");
39
+ assert.equal(
40
+ prependPathDirectory(selectedDirectory, { platform: "win32", env: { PATH: `${staleNpmDirectory};${selectedPiDirectory}` } }),
41
+ `${selectedPiDirectory};${staleNpmDirectory}`,
42
+ "the selected Pi installation should lead PATH while its update runs",
43
+ );
44
+ assert.deepEqual(
45
+ prependedPathEnvironment(selectedDirectory, { platform: "win32", env: { Path: `${staleNpmDirectory};${selectedPiDirectory}` } }),
46
+ { Path: `${selectedPiDirectory};${staleNpmDirectory}` },
47
+ "Windows updates should preserve the existing Path key casing",
48
+ );
49
+
50
+ const fromSelectedPi = resolveNpmCommandInvocation(["install"], {
51
+ platform: "win32",
52
+ execPath: windowsExecPath,
53
+ env: { PATH: `${staleNpmDirectory};${selectedPiDirectory}` },
54
+ preferredDirectories: [selectedDirectory],
55
+ existsSync: (candidate) => path.win32.normalize(candidate) === path.win32.normalize(selectedPiNpmCli),
56
+ });
57
+ assert.deepEqual(fromSelectedPi.args, [selectedPiNpmCli, "install"], "package updates should use npm bundled beside the selected Pi installation");
58
+
59
+ const selectedPiNode = `${selectedPiDirectory}\\node.exe`;
60
+ const selectedPiCli = `${selectedPiDirectory}\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js`;
61
+ const explicitPi = resolvePiCommandInvocation(selectedPi, ["update", "--help"], {
62
+ platform: "win32",
63
+ execPath: windowsExecPath,
64
+ env: { PATH: staleNpmDirectory },
65
+ existsSync: (candidate) => [selectedPi, selectedPiNode, selectedPiCli].some((expected) => path.win32.normalize(candidate) === path.win32.normalize(expected)),
66
+ });
67
+ assert.equal(explicitPi.command, selectedPiNode, "an explicit Windows Pi shim should run through Node from the same installation");
68
+ assert.deepEqual(explicitPi.args, [selectedPiCli, "update", "--help"], "an explicit Windows Pi shim should resolve to that installation's CLI script");
69
+
70
+ const selectedPiCmd = `${selectedPiDirectory}\\pi.cmd`;
71
+ const extensionResolvedPi = resolvePiCommandInvocation(selectedPi, ["--version"], {
72
+ platform: "win32",
73
+ execPath: windowsExecPath,
74
+ env: { PATH: staleNpmDirectory, PATHEXT: ".exe;.cmd" },
75
+ existsSync: (candidate) => [selectedPiCmd, selectedPiNode, selectedPiCli].some((expected) => path.win32.normalize(candidate) === path.win32.normalize(expected)),
76
+ });
77
+ assert.equal(extensionResolvedPi.command, selectedPiNode, "an extensionless explicit path should resolve a matching pi.cmd through PATHEXT");
78
+ assert.deepEqual(extensionResolvedPi.args, [selectedPiCli, "--version"]);
79
+
80
+ const customPiExecutable = `${selectedPiDirectory}\\custom-pi.exe`;
81
+ assert.deepEqual(
82
+ resolvePiCommandInvocation(customPiExecutable, ["--version"], {
83
+ platform: "win32",
84
+ execPath: windowsExecPath,
85
+ existsSync: (candidate) => [customPiExecutable, selectedPiCli].some((expected) => path.win32.normalize(candidate) === path.win32.normalize(expected)),
86
+ }),
87
+ { command: customPiExecutable, args: ["--version"], source: "command" },
88
+ "explicit custom Pi executables should not be replaced by npm-shim normalization",
89
+ );
90
+
29
91
  const configuredShim = "E:\\CustomNode\\npm.cmd";
30
92
  const configuredCli = "E:\\CustomNode\\node_modules\\npm\\bin\\npm-cli.js";
31
93
  const configured = resolveNpmCommandInvocation(["--version"], {
32
94
  platform: "win32",
33
95
  execPath: windowsExecPath,
34
96
  env: { PI_WEBUI_NPM_BIN: configuredShim, PATH: "" },
97
+ preferredDirectories: [selectedPiDirectory],
35
98
  existsSync: (candidate) => path.win32.normalize(candidate) === path.win32.normalize(configuredCli),
36
99
  });
37
100
  assert.equal(configured.command, windowsExecPath, "a configured npm.cmd shim should be normalized to its npm CLI");
@@ -68,7 +68,8 @@ assert.match(server, /"issue-wizard-state\.mjs"/, "the static allowlist must con
68
68
  assert.match(server, /"issue-bot-client\.mjs"/, "the static allowlist must serve the browser client module");
69
69
  assert.match(serviceWorker, /"\/issue-wizard-state\.mjs"/, "the PWA shell must keep caching the pure wizard module");
70
70
  assert.match(serviceWorker, /"\/issue-bot-client\.mjs"/, "the PWA shell must cache the browser client module");
71
- assert.match(serviceWorker, /pi-webui-pwa-v50/, "the PWA cache name must change with browser wiring updates");
71
+ // Intent preserved: changing the public startup graph advances the PWA cache identity.
72
+ assert.match(serviceWorker, /pi-webui-pwa-v62/, "the PWA cache name must change with browser wiring updates");
72
73
  assert.match(packageJson, /node --check public\/issue-wizard-state\.mjs/, "the package check must keep syntax-checking the pure wizard module");
73
74
  assert.match(packageJson, /node --check public\/issue-bot-client\.mjs/, "the package check must syntax-check the browser client module");
74
75
 
@@ -17,6 +17,10 @@ assert.match(
17
17
  "the composer should expose a count trigger and accessible non-modal follow-up queue overlay",
18
18
  );
19
19
  assert.match(css, /\.follow-up-queue-overlay \{[\s\S]*position:\s*absolute;[\s\S]*bottom:\s*calc\(100% \+ 0\.42rem\);[\s\S]*max-height:\s*min\(32rem, calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\)\)/, "the queue overlay should float upward without changing composer layout and be bounded by the visual viewport");
20
+ assert.match(css, /\.follow-up-queue-trigger \{[\s\S]*justify-content:\s*center;[\s\S]*min-width:\s*5\.25rem;/, "the queue trigger should reserve a predictable width for its label and three-digit count");
21
+ assert.match(css, /body:not\(\.mobile-keyboard-open\) \.composer-input-row:has\(\.composer-workflow-mode-dock:not\(\[hidden\]\)\) \.follow-up-queue-trigger \{\s*right:\s*calc\(3\.55rem \+ 2\.25rem \+ 0\.4rem\);\s*\}/, "the queue trigger should move left of the visible Workflow control instead of overlapping it");
22
+ assert.match(css, /\.composer-input-row:has\(\.follow-up-queue-trigger:not\(\[hidden\]\)\) \.composer-context-tags \{\s*max-width:\s*max\(0px, calc\(100% - 9\.7rem\)\);\s*\}/, "visible queues should reserve prompt-frame space so feature and context tags cannot overlap the queue trigger");
23
+ assert.match(css, /body:not\(\.mobile-keyboard-open\) \.composer-input-row:has\(\.composer-workflow-mode-dock:not\(\[hidden\]\)\):has\(\.follow-up-queue-trigger:not\(\[hidden\]\)\) \.composer-context-tags \{\s*max-width:\s*max\(0px, calc\(100% - 12\.6rem\)\);\s*\}/, "context tags should reserve the combined Workflow and queue dock width");
20
24
  assert.match(css, /body\.mobile-keyboard-open \.follow-up-queue-trigger:not\(\[hidden\]\) \{ display: inline-flex; \}/, "the queue trigger should remain usable while the mobile keyboard is open");
21
25
  assert.match(css, /@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\.follow-up-queue-overlay,[\s\S]*\.follow-up-queue-row \{ transition: none; \}/, "the queue overlay should suppress motion for reduced-motion users");
22
26
 
@@ -48,6 +52,8 @@ assert.deepEqual(compactionMutation, {
48
52
  const runtimeMutation = JSON.parse(vm.runInNewContext(`${mutationBodySource}\nJSON.stringify(queueMutationBody({ source: "pi-runtime", steering: [], followUp: ["old"] }, { type: "edit", index: 0, expectedText: "old", text: "new" }))`));
49
53
  assert.equal(Object.hasOwn(runtimeMutation, "revision"), false, "Pi-runtime mutations must omit the compaction-only revision field");
50
54
  assert.deepEqual(runtimeMutation.expected, { steering: [], followUp: ["old"] }, "Pi-runtime mutations should send the complete B1 expected snapshot");
55
+ const deleteMutation = JSON.parse(vm.runInNewContext(`${mutationBodySource}\nJSON.stringify(queueMutationBody({ source: "webui-compaction", revision: 4, steering: ["steer"], followUp: ["remove me"] }, { type: "delete", index: 0, expectedText: "remove me" }))`));
56
+ assert.deepEqual(deleteMutation.operation, { type: "delete", index: 0, expectedText: "remove me" }, "queue deletion should use the same source-aware full-snapshot mutation contract");
51
57
 
52
58
  const draftHelperStart = app.indexOf("function preservedFocusedFollowUpQueueDraft(draft, followUps) {");
53
59
  const draftHelperEnd = app.indexOf("\nfunction focusedFollowUpQueueDraft", draftHelperStart);
@@ -90,12 +96,14 @@ assert.match(app, /const textarea = make\("textarea", "follow-up-queue-textarea"
90
96
  assert.match(app, /row\.draggable = false;[\s\S]*dragHandle\.draggable = !unavailable;[\s\S]*row\.addEventListener\("dragstart", \(event\) => \{[\s\S]*event\.target\?\.closest\?\.\("\.follow-up-queue-drag-handle"\) !== dragHandle[\s\S]*application\/x-pi-webui-follow-up[\s\S]*row\.addEventListener\("dragover"[\s\S]*event\.stopPropagation\(\)[\s\S]*row\.addEventListener\("drop"[\s\S]*type: "move", from: drag\.index, to: index/, "native drag/drop should begin only from its visible handle, persist the final-index permutation, and isolate row drag events");
91
97
  assert.match(app, /function handleComposerDragOver\(event\) \{\n\s*if \(event\.target\?\.closest\?\.\("#followUpQueueOverlay"\) \|\| !isFileDrag\(event\)\) return;[\s\S]*function handleComposerDrop\(event\) \{\n\s*if \(event\.target\?\.closest\?\.\("#followUpQueueOverlay"\) \|\| !isFileDrag\(event\)\) return;/, "composer attachment drops should ignore queue-row drag events");
92
98
  assert.match(app, /Moved queued follow-up \$\{operation\.from \+ 1\} to position \$\{operation\.to \+ 1\}[\s\S]*Move queued follow-up \$\{index \+ 1\} up[\s\S]*Move queued follow-up \$\{index \+ 1\} down/, "move controls should provide labelled keyboard/touch parity and live reorder announcements");
99
+ assert.match(app, /const remove = make\("button", "follow-up-queue-remove-button", "Remove"\)[\s\S]*type: "delete", index, expectedText: message/, "every composer queue row should expose an accessible remove control backed by the unified mutation contract");
100
+ assert.match(css, /\.follow-up-queue-remove-button \{[\s\S]*color:\s*var\(--ctp-red\)/, "queue removal should have a distinct destructive visual treatment");
93
101
  assert.match(app, /setFollowUpQueueOpen\(false, \{ restoreFocus: true \}\)/, "outside close and Escape should request queue-focus restoration");
94
102
  assert.match(app, /function setFollowUpQueueOpen\([\s\S]*followUpQueueRestoreFocus[\s\S]*requestAnimationFrame\(\(\) => focusTarget\?\.focus\(\{ preventScroll: true \}\)\)/, "queue close should restore focus to the saved trigger context");
95
103
  assert.match(app, /function setFollowUpQueueOpen[\s\S]*setComposerActionsOpen\(false\)[\s\S]*setPublishMenuOpen\(false\)[\s\S]*setNativeCommandMenuOpen\(false\)[\s\S]*setAppRunnerMenuOpen\(false\)[\s\S]*setOptionsMenuOpen\(false\)[\s\S]*setConversationVoiceMenuOpen\(false\)[\s\S]*setBusyPromptBehaviorMenuOpen\(false\)[\s\S]*setNewTabMenuOpen\(false\)/, "opening the queue should close competing dropdown surfaces");
96
104
  assert.match(app, /function renderFollowUpQueueOverlay\(\) \{\n\s*if \(deferUiRenderDuringPointerActivation\("follow-up-queue", renderFollowUpQueueOverlay\)\) return;/, "queue rendering should defer during pointer activation");
97
105
  assert.match(app, /function switchTab\(tabId\)[\s\S]*setFollowUpQueueOpen\(false\)[\s\S]*setFollowUpQueueStatus\(""\)/, "switching tabs should close queue UI and clear its tab-local status before the new context renders");
98
- assert.match(app, /renderQueueGroup\("Follow-up", followUp, "follow-up", \{ removable: snapshot\.source === "pi-runtime", tabId \}\)/, "Control Deck removal must stay gated to Pi-runtime snapshots");
106
+ assert.match(app, /renderQueueGroup\("Follow-up", followUp, "follow-up", \{ removable: !snapshot\.draining, tabId \}\)/, "Control Deck removal should support every mutable queue source");
99
107
  assert.doesNotMatch(app, /nextQueuedFollowUpPrompt|sticky-user-follow-up-prompt|Next follow-up prompt:/, "the sticky last/current prompt control must no longer expose queued follow-up preview content");
100
108
 
101
109
  console.log("queue edit/reorder static tests passed");
@@ -47,6 +47,15 @@ function moveRequest(session, from, to, expectedText = session._followUpMessages
47
47
  };
48
48
  }
49
49
 
50
+ function deleteRequest(session, index, expectedText = session._followUpMessages[index]) {
51
+ return {
52
+ source: "pi-runtime",
53
+ kind: "followUp",
54
+ expected: expected(session),
55
+ operation: { type: "delete", index, expectedText },
56
+ };
57
+ }
58
+
50
59
  {
51
60
  const { session, eventCount } = fixture();
52
61
  const beforeMessage = session.agent.followUpQueue.messages[1];
@@ -76,6 +85,17 @@ function moveRequest(session, from, to, expectedText = session._followUpMessages
76
85
  assert.equal(eventCount(), 1, "successful move emits exactly one queue update");
77
86
  }
78
87
 
88
+ {
89
+ const { session, eventCount } = fixture();
90
+ const removedMessage = session.agent.followUpQueue.messages[1];
91
+ const result = mutatePiRuntimeFollowUpQueue(session, deleteRequest(session, 1));
92
+ assert.equal(result.mutated, true);
93
+ assert.deepEqual(session._followUpMessages, ["first", "third"], "delete removes the selected tracked follow-up");
94
+ assert.deepEqual(session.agent.followUpQueue.messages.map((message) => message.content[0].text), ["first", "third"], "delete keeps the remaining message objects paired with their tracking strings");
95
+ assert.equal(session.agent.followUpQueue.messages.includes(removedMessage), false, "delete removes the matching queued message object");
96
+ assert.equal(eventCount(), 1, "successful delete emits exactly one queue update");
97
+ }
98
+
79
99
  {
80
100
  const { session, eventCount } = fixture({ followUp: ["same", "same"] });
81
101
  const result = mutatePiRuntimeFollowUpQueue(session, editRequest(session, 1, "changed"));
@@ -115,6 +135,8 @@ for (const requestFor of [
115
135
  (session) => editRequest(session, 99, "edited"),
116
136
  (session) => moveRequest(session, 0, 0),
117
137
  (session) => moveRequest(session, 0, 99),
138
+ (session) => deleteRequest(session, 99),
139
+ (session) => deleteRequest(session, 1, "different"),
118
140
  (session) => ({ ...editRequest(session, 1, "edited"), source: "webui-compaction" }),
119
141
  (session) => ({ ...editRequest(session, 1, "edited"), kind: "steering" }),
120
142
  ]) {
@@ -0,0 +1,120 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import vm from "node:vm";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const rawSource = await readFile(join(root, "public", "service-worker.js"), "utf8");
9
+ assert.match(rawSource, /const APP_SHELL_NETWORK_TIMEOUT_MS = 8_000;/, "app-shell requests need a bounded network timeout");
10
+ const source = rawSource.replace(
11
+ "const APP_SHELL_NETWORK_TIMEOUT_MS = 8_000;",
12
+ "const APP_SHELL_NETWORK_TIMEOUT_MS = 20;",
13
+ );
14
+ const handlers = new Map();
15
+ let releaseCacheWrite;
16
+ const cacheWrite = new Promise((resolve) => { releaseCacheWrite = resolve; });
17
+ let cachePutCount = 0;
18
+ let cacheMatchResult;
19
+ const cache = {
20
+ async addAll() {},
21
+ put: async () => {
22
+ cachePutCount += 1;
23
+ await cacheWrite;
24
+ },
25
+ };
26
+ const networkResponse = { ok: true, source: "network", clone() { return this; } };
27
+ let fetchImpl = async () => networkResponse;
28
+ const focusedMessages = [];
29
+ const client = {
30
+ url: "https://webui.test/",
31
+ async focus() { return this; },
32
+ postMessage(message) { focusedMessages.push(message); },
33
+ };
34
+ const context = {
35
+ self: {
36
+ location: { origin: "https://webui.test" },
37
+ addEventListener(name, handler) { handlers.set(name, handler); },
38
+ skipWaiting: async () => {},
39
+ clients: {
40
+ async claim() {},
41
+ async matchAll() { return [client]; },
42
+ async openWindow(url) { return { url }; },
43
+ },
44
+ },
45
+ caches: {
46
+ async open() { return cache; },
47
+ async keys() { return []; },
48
+ async delete() { return true; },
49
+ async match() { return cacheMatchResult; },
50
+ },
51
+ fetch: (...args) => fetchImpl(...args),
52
+ AbortController,
53
+ setTimeout,
54
+ clearTimeout,
55
+ URL,
56
+ Promise,
57
+ RegExp,
58
+ Object,
59
+ String,
60
+ console,
61
+ };
62
+ vm.runInNewContext(source, context, { filename: "service-worker.js" });
63
+
64
+ let fetchResponse;
65
+ let fetchLifetime;
66
+ const fetchEvent = {
67
+ request: { method: "GET", url: "https://webui.test/app.js", mode: "cors" },
68
+ respondWith(promise) { fetchResponse = promise; },
69
+ waitUntil(promise) { fetchLifetime = promise; },
70
+ };
71
+ handlers.get("fetch")(fetchEvent);
72
+ assert.ok(fetchResponse, "app-shell fetch should be intercepted");
73
+ assert.ok(fetchLifetime, "runtime cache writes should extend the fetch-event lifetime");
74
+ assert.equal(await fetchResponse, networkResponse, "a usable network response must not wait for CacheStorage");
75
+ await new Promise((resolve) => setImmediate(resolve));
76
+ assert.equal(cachePutCount, 1, "network responses should begin a cache write");
77
+ let lifetimeSettled = false;
78
+ fetchLifetime.then(() => { lifetimeSettled = true; });
79
+ await new Promise((resolve) => setImmediate(resolve));
80
+ assert.equal(lifetimeSettled, false, "the event lifetime should still track an unfinished cache write");
81
+ releaseCacheWrite();
82
+ await fetchLifetime;
83
+ assert.equal(lifetimeSettled, true, "the event lifetime should settle after the cache write");
84
+
85
+ const cachedResponse = { ok: true, source: "cache" };
86
+ cacheMatchResult = cachedResponse;
87
+ fetchImpl = (_request, { signal }) => new Promise((_resolve, reject) => {
88
+ signal.addEventListener("abort", () => {
89
+ const error = new Error("network request timed out");
90
+ error.name = "AbortError";
91
+ reject(error);
92
+ }, { once: true });
93
+ });
94
+ let timeoutResponse;
95
+ let timeoutLifetime;
96
+ const timeoutEvent = {
97
+ request: { method: "GET", url: "https://webui.test/styles.css", mode: "cors" },
98
+ respondWith(promise) { timeoutResponse = promise; },
99
+ waitUntil(promise) { timeoutLifetime = promise; },
100
+ };
101
+ handlers.get("fetch")(timeoutEvent);
102
+ assert.equal(await timeoutResponse, cachedResponse, "a timed-out app-shell request should use the offline cache");
103
+ await timeoutLifetime;
104
+
105
+ let notificationWork;
106
+ const notificationEvent = {
107
+ notification: {
108
+ data: { target: { v: 1, route: "activity", tabId: "tab_12345678", runId: "run_12345678" } },
109
+ close() {},
110
+ },
111
+ waitUntil(promise) { notificationWork = promise; },
112
+ };
113
+ handlers.get("notificationclick")(notificationEvent);
114
+ await notificationWork;
115
+ assert.deepEqual(JSON.parse(JSON.stringify(focusedMessages)), [{
116
+ type: "pi-webui:navigate:v1",
117
+ target: { v: 1, route: "activity", tabId: "tab_12345678", runId: "run_12345678" },
118
+ }], "an existing active client should receive only the validated opaque navigation target");
119
+
120
+ console.log("service-worker-lifecycle.test.mjs passed");
@@ -0,0 +1,68 @@
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 [html, app, css, serviceWorker] = await Promise.all([
8
+ readFile(join(root, "public", "index.html"), "utf8"),
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
12
+ ]);
13
+
14
+ assert.match(
15
+ app,
16
+ /const SIDE_PANEL_SECTION_ORDER_STORAGE_KEY = "pi-webui-side-panel-section-order-v1";[\s\S]*const SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX = 6;/,
17
+ "side-panel order should use versioned browser storage and the same six-pixel pointer threshold as model ordering",
18
+ );
19
+ assert.match(
20
+ app,
21
+ /function readStoredSidePanelSectionOrder\(\)[\s\S]*JSON\.parse\(localStorage\.getItem\(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY\)[\s\S]*new Set\([\s\S]*function persistSidePanelSectionOrder\(\)[\s\S]*sidePanelSectionRecords\(\)\.map\(\(\{ id \}\) => id\)/,
22
+ "stored order should be deduplicated and persist the complete current section order",
23
+ );
24
+ assert.match(
25
+ app,
26
+ /function restoreSidePanelSectionOrder\(\)[\s\S]*rank = new Map\([\s\S]*Number\.MAX_SAFE_INTEGER[\s\S]*parent\.append\(section\)/,
27
+ "restore should rank known IDs while appending newly introduced sections in their existing order",
28
+ );
29
+ assert.match(
30
+ app,
31
+ /function moveSidePanelSectionRelative\(fromId, targetRecord, insertBefore\)[\s\S]*parent\.insertBefore\(sourceRecord\.section, targetRecord\.section\)[\s\S]*targetRecord\.section\.nextSibling[\s\S]*persistSidePanelSectionOrder\(\)/,
32
+ "reordering should move the complete section before or after its target and persist immediately",
33
+ );
34
+ assert.match(
35
+ app,
36
+ /function updateSidePanelSectionPointerDrag\(event\)[\s\S]*Math\.hypot[\s\S]*SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX[\s\S]*sidePanelSectionToggleFromPoint[\s\S]*getBoundingClientRect\(\)[\s\S]*moveSidePanelSectionRelative/,
37
+ "pointer dragging should activate only after the threshold and use header midpoint placement",
38
+ );
39
+ assert.match(
40
+ app,
41
+ /function endSidePanelSectionPointerDrag\(event\)[\s\S]*sidePanelSectionSuppressClickUntil = Date\.now\(\) \+ 250[\s\S]*focus\(\{ preventScroll: true \}\)/,
42
+ "a completed drag should suppress the accidental toggle click and restore focus",
43
+ );
44
+ assert.match(
45
+ app,
46
+ /function bindSidePanelSectionToggles\(\)[\s\S]*Date\.now\(\) < sidePanelSectionSuppressClickUntil[\s\S]*event\.altKey[\s\S]*event\.key !== "ArrowUp"[\s\S]*moveSidePanelSectionByOffset[\s\S]*beginSidePanelSectionPointerDrag/,
47
+ "section headers should retain click toggling while supporting Alt+Arrow keyboard and pointer reordering",
48
+ );
49
+ assert.match(
50
+ app,
51
+ /restoreSidePanelSectionOrder\(\);\s*restoreSidePanelSectionVisibility\(\);\s*restoreSidePanelSectionState\(\);/,
52
+ "saved order should restore before visibility and accordion state",
53
+ );
54
+ assert.match(
55
+ app,
56
+ /event\.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY\) restoreSidePanelSectionOrder\(\)/,
57
+ "other tabs should apply stored side-panel order changes",
58
+ );
59
+ assert.match(
60
+ css,
61
+ /\.side-panel-section-toggle\[data-side-panel-section-toggle\][\s\S]*cursor: grab[\s\S]*touch-action: none[\s\S]*\.side-panel-section\.dragging[\s\S]*cursor: grabbing[\s\S]*\.drag-over-before[\s\S]*\.drag-over-after/,
62
+ "section headers should expose model-picker-style grab, dragging, and insertion-marker affordances",
63
+ );
64
+ assert.match(html, /styles\.css\?v=93/, "changed side-panel styles should advance the stylesheet revision");
65
+ assert.match(html, /app\.js\?v=104/, "changed side-panel behavior should advance the app revision");
66
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v62"/, "changed browser assets should advance the PWA cache identity");
67
+
68
+ console.log("side-panel-section-reorder-static.test.mjs passed");
@@ -0,0 +1,137 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { connect, createServer } from "node:net";
4
+ import { mkdtemp, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { dirname, join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
12
+ const serverScript = join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
14
+
15
+ async function freePort() {
16
+ const server = createServer();
17
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
18
+ const { port } = server.address();
19
+ await new Promise((resolve) => server.close(resolve));
20
+ return port;
21
+ }
22
+
23
+ const port = await freePort();
24
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-sse-backpressure-"));
25
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
26
+ stdio: ["ignore", "pipe", "pipe"],
27
+ env: {
28
+ ...process.env,
29
+ PI_WEBUI_RPC_SUPERVISOR: "0",
30
+ PI_CODING_AGENT_DIR: join(cwd, "agent"),
31
+ PI_WEBUI_SETTINGS_FILE: join(cwd, "settings.json"),
32
+ FAKE_PI_SSE_FLOOD: "1",
33
+ },
34
+ });
35
+ let output = "";
36
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
37
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
38
+
39
+ async function json(pathname, options = {}) {
40
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
41
+ ...options,
42
+ headers: options.body ? { "content-type": "application/json", ...(options.headers || {}) } : options.headers,
43
+ body: options.body ? JSON.stringify(options.body) : undefined,
44
+ signal: AbortSignal.timeout(5_000),
45
+ });
46
+ return { status: response.status, body: await response.json() };
47
+ }
48
+
49
+ try {
50
+ let health;
51
+ for (let attempt = 0; attempt < 80; attempt += 1) {
52
+ if (child.exitCode !== null) break;
53
+ try {
54
+ health = await json("/api/health");
55
+ if (health.status === 200) break;
56
+ } catch {
57
+ // Wait for the real server and fake Pi child.
58
+ }
59
+ await delay(100);
60
+ }
61
+ assert.equal(health?.status, 200, `server should start for backpressure test:\n${output}`);
62
+ const tabs = await json("/api/tabs");
63
+ const tabId = tabs.body?.data?.tabs?.[0]?.id;
64
+ assert.ok(tabId, "fixture server should expose an initial tab");
65
+
66
+ // Undici continues draining the transport even when application code has not
67
+ // consumed response.body. A >2MiB burst must therefore survive transient
68
+ // ServerResponse backpressure instead of being mistaken for a dead client.
69
+ const flowing = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: AbortSignal.timeout(15_000) });
70
+ assert.equal(flowing.status, 200);
71
+ const flowingFlood = await json("/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture sse flood" } });
72
+ assert.equal(flowingFlood.status, 200, "flood fixture should dispatch through the real server");
73
+ await delay(500);
74
+ const flowingTabs = await json("/api/tabs");
75
+ assert.equal(flowingTabs.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount, 1, "a transport-draining SSE client must survive transient backpressure");
76
+ await flowing.body?.cancel();
77
+
78
+ for (let attempt = 0; attempt < 50; attempt += 1) {
79
+ const refreshed = await json("/api/tabs");
80
+ if (refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount === 0) break;
81
+ await delay(50);
82
+ }
83
+
84
+ // A paused raw socket does not drain the HTTP transport. It must be evicted
85
+ // within the bounded queue/timeout policy, but with a complete final chunk so
86
+ // Chromium does not surface ERR_INCOMPLETE_CHUNKED_ENCODING on reconnection.
87
+ const stalled = connect({ host: "127.0.0.1", port });
88
+ let stalledResponse = "";
89
+ stalled.on("data", (chunk) => { stalledResponse += String(chunk); });
90
+ stalled.pause();
91
+ await new Promise((resolve, reject) => {
92
+ stalled.once("connect", resolve);
93
+ stalled.once("error", reject);
94
+ });
95
+ stalled.write(`GET /api/events?tab=${encodeURIComponent(tabId)} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: keep-alive\r\n\r\n`);
96
+
97
+ let connected = false;
98
+ for (let attempt = 0; attempt < 50; attempt += 1) {
99
+ const refreshed = await json("/api/tabs");
100
+ if (refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount === 1) {
101
+ connected = true;
102
+ break;
103
+ }
104
+ await delay(50);
105
+ }
106
+ assert.equal(connected, true, "the paused raw SSE client should connect before the flood");
107
+ const stalledFlood = await json("/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture sse stall flood" } });
108
+ assert.equal(stalledFlood.status, 200, "stalled-client flood should dispatch through the real server");
109
+
110
+ let evicted = false;
111
+ for (let attempt = 0; attempt < 240; attempt += 1) {
112
+ const refreshed = await json("/api/tabs");
113
+ const clientCount = refreshed.body?.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount;
114
+ if (clientCount === 0) {
115
+ evicted = true;
116
+ break;
117
+ }
118
+ await delay(50);
119
+ }
120
+ assert.equal(evicted, true, "a transport-stalled SSE client must be evicted instead of accumulating an unbounded semantic-event queue");
121
+ stalled.resume();
122
+ for (let attempt = 0; attempt < 100 && !stalledResponse.includes("\r\n0\r\n\r\n"); attempt += 1) await delay(50);
123
+ assert.match(stalledResponse, /\r\n0\r\n\r\n/, "backpressure eviction must complete the chunked SSE response without truncating it");
124
+ stalled.destroy();
125
+
126
+ const reconnected = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: AbortSignal.timeout(5_000) });
127
+ const firstFrame = await reconnected.body.getReader().read();
128
+ assert.equal(firstFrame.done, false, "a client can reconnect after slow-client eviction");
129
+ assert.match(new TextDecoder().decode(firstFrame.value), /webui_connected/, "reconnection should receive an authoritative connection snapshot");
130
+ await reconnected.body?.cancel().catch(() => {});
131
+ } finally {
132
+ child.kill("SIGTERM");
133
+ await new Promise((resolve) => child.once("exit", resolve));
134
+ await rm(cwd, { recursive: true, force: true });
135
+ }
136
+
137
+ console.log("sse-backpressure-harness.test.mjs passed");