@firstpick/pi-package-webui 0.8.0 → 0.8.1

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 (51) hide show
  1. package/README.md +22 -5
  2. package/bin/pi-webui.mjs +434 -100
  3. package/lib/npm-command.mjs +81 -0
  4. package/lib/queue-mutation.mjs +6 -0
  5. package/lib/workspace-files-live-watcher.mjs +138 -0
  6. package/package.json +8 -3
  7. package/public/app.js +2816 -314
  8. package/public/index.html +112 -27
  9. package/public/mobile-shell-state.mjs +166 -0
  10. package/public/service-worker.js +60 -13
  11. package/public/styles.css +1049 -371
  12. package/public/subagent-gate-visibility.mjs +16 -0
  13. package/public/subagent-launch-slot-state.mjs +16 -0
  14. package/public/transcript-renderer.mjs +433 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +739 -0
  17. package/tests/browser/mobile-foundation.spec.mjs +352 -0
  18. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  19. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  20. package/tests/codex-fast-mode-static.test.mjs +8 -5
  21. package/tests/compact-sections-static.test.mjs +20 -2
  22. package/tests/compaction-mutation-contract.test.mjs +18 -4
  23. package/tests/compaction-static.test.mjs +1 -0
  24. package/tests/completion-signal-contract.test.mjs +13 -2
  25. package/tests/fast-mode-client-static.test.mjs +7 -4
  26. package/tests/fixtures/fake-pi.mjs +181 -2
  27. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  28. package/tests/http-endpoints-harness.test.mjs +228 -2
  29. package/tests/interaction-state-stability-static.test.mjs +254 -0
  30. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  31. package/tests/mobile-foundation-static.test.mjs +69 -0
  32. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  33. package/tests/mobile-shell-state.test.mjs +69 -0
  34. package/tests/mobile-static.test.mjs +244 -38
  35. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  36. package/tests/npm-command.test.mjs +64 -1
  37. package/tests/open-issue-wizard-static.test.mjs +2 -1
  38. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  39. package/tests/queue-mutation-contract.test.mjs +22 -0
  40. package/tests/service-worker-lifecycle.test.mjs +120 -0
  41. package/tests/sse-backpressure-harness.test.mjs +98 -0
  42. package/tests/streaming-ui-coupling.test.mjs +7 -1
  43. package/tests/subagent-gate-visibility.test.mjs +18 -2
  44. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  45. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  46. package/tests/subagents-helper.test.mjs +90 -0
  47. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  48. package/tests/update-commands.test.mjs +4 -0
  49. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  50. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  51. package/webui-rpc-helper.mjs +175 -3
@@ -10,6 +10,22 @@ export function subagentGateIsTerminal(gate) {
10
10
  return gate?.status !== "running";
11
11
  }
12
12
 
13
+ export function subagentGateRunIds(tab) {
14
+ const runIds = new Set();
15
+ for (const gate of Array.isArray(tab?.gates) ? tab.gates : []) {
16
+ for (const attempt of Array.isArray(gate?.attempts) ? gate.attempts : []) {
17
+ const runId = String(attempt?.runId || "").trim();
18
+ if (runId) runIds.add(runId);
19
+ }
20
+ }
21
+ return runIds;
22
+ }
23
+
24
+ export function ungatedSubagentRuns(tab) {
25
+ const gatedRunIds = subagentGateRunIds(tab);
26
+ return (Array.isArray(tab?.runs) ? tab.runs : []).filter((run) => !gatedRunIds.has(String(run?.id || "").trim()));
27
+ }
28
+
13
29
  export function visibleSubagentGates(tab, dismissedGateKeys, now = Date.now(), retentionMs = SUBAGENT_GATE_RETENTION_MS) {
14
30
  const gates = Array.isArray(tab?.gates) ? tab.gates : [];
15
31
  return gates.filter((gate) => {
@@ -13,6 +13,22 @@ export function cloneLaunchSlotRoles(roles = {}) {
13
13
  ]));
14
14
  }
15
15
 
16
+ export function subagentLaunchSlotSaveState({
17
+ hasConfig = false,
18
+ hasDraft = false,
19
+ dirty = false,
20
+ loading = false,
21
+ saving = false,
22
+ activeConfigTab = false,
23
+ } = {}) {
24
+ if (saving) return { disabled: true, reason: "Saving agent models…" };
25
+ if (loading) return { disabled: true, reason: "Wait for agent models to finish loading." };
26
+ if (!hasConfig || !hasDraft) return { disabled: true, reason: "Agent model configuration is not available for this tab." };
27
+ if (!dirty) return { disabled: true, reason: "Change a model or thinking preset to enable saving." };
28
+ if (!activeConfigTab) return { disabled: true, reason: "Switch back to the tab where these changes were made to save them." };
29
+ return { disabled: false, reason: "Ready to save." };
30
+ }
31
+
16
32
  export function launchSlotRolesEqual(left, right) {
17
33
  const leftRoles = Object.keys(left || {}).sort();
18
34
  const rightRoles = Object.keys(right || {}).sort();
@@ -0,0 +1,433 @@
1
+ const DEFAULT_SURFACE_SELECTOR = "[data-transcript-surface], .markdown-body, .compact-live-text";
2
+ const DESTRUCTIVE_KINDS = new Set(["reconcile", "destructive", "authoritative"]);
3
+ const MUTATION_LOG_LIMIT = 80;
4
+
5
+ function normalizedKey(value, fallback = "") {
6
+ const key = String(value || "").trim();
7
+ return key || fallback;
8
+ }
9
+
10
+ function textOffset(surface, node, offset) {
11
+ if (!surface || !node || (node !== surface && !surface.contains(node))) return null;
12
+ const range = document.createRange();
13
+ try {
14
+ range.selectNodeContents(surface);
15
+ range.setEnd(node, offset);
16
+ return range.toString().length;
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ function textPoint(surface, offset, { forwardAffinity = false } = {}) {
23
+ const target = Math.max(0, Number(offset) || 0);
24
+ const walker = document.createTreeWalker(surface, NodeFilter.SHOW_TEXT);
25
+ let consumed = 0;
26
+ let last = null;
27
+ while (walker.nextNode()) {
28
+ const node = walker.currentNode;
29
+ const next = consumed + node.data.length;
30
+ if (target < next || (target === next && !forwardAffinity)) {
31
+ return { node, offset: Math.max(0, target - consumed) };
32
+ }
33
+ consumed = next;
34
+ last = node;
35
+ }
36
+ return last ? { node: last, offset: last.data.length } : { node: surface, offset: 0 };
37
+ }
38
+
39
+ function rangeForSnapshot(surface, snapshot) {
40
+ const backward = snapshot.anchorOffset > snapshot.focusOffset;
41
+ let anchorOffset = snapshot.anchorOffset;
42
+ let focusOffset = snapshot.focusOffset;
43
+
44
+ const resolve = () => {
45
+ const start = textPoint(surface, Math.min(anchorOffset, focusOffset), { forwardAffinity: true });
46
+ const end = textPoint(surface, Math.max(anchorOffset, focusOffset));
47
+ const anchor = backward ? end : start;
48
+ const focus = backward ? start : end;
49
+ const range = document.createRange();
50
+ try {
51
+ range.setStart(start.node, start.offset);
52
+ range.setEnd(end.node, end.offset);
53
+ } catch {
54
+ return null;
55
+ }
56
+ return range.toString() === snapshot.text ? { anchor, focus, range } : null;
57
+ };
58
+
59
+ const offsetMatch = resolve();
60
+ if (offsetMatch) return offsetMatch;
61
+
62
+ // Structural tool/Markdown changes can shift an unchanged selection within
63
+ // the same semantic surface. Remap only when its exact text occurs once;
64
+ // message/surface identity still prevents restoration into duplicate output.
65
+ const surfaceText = surface.textContent || "";
66
+ const exactStart = surfaceText.indexOf(snapshot.text);
67
+ if (exactStart < 0 || surfaceText.indexOf(snapshot.text, exactStart + 1) !== -1) return null;
68
+ const exactEnd = exactStart + snapshot.text.length;
69
+ anchorOffset = backward ? exactEnd : exactStart;
70
+ focusOffset = backward ? exactStart : exactEnd;
71
+ return resolve();
72
+ }
73
+
74
+ /**
75
+ * Owns transcript-local DOM mutations. The controller supplies rendering
76
+ * callbacks, while this module keeps semantic ownership, pointer selection
77
+ * sessions, exact selection fallback, and bounded streaming-tail state in one
78
+ * place. It intentionally does not own scroll/follow policy or Markdown
79
+ * syntax so existing visual rendering stays unchanged.
80
+ */
81
+ export function createTranscriptRenderer({ chat, contextKey = () => "", surfaceSelector = DEFAULT_SURFACE_SELECTOR } = {}) {
82
+ if (!chat) throw new Error("createTranscriptRenderer requires the transcript root");
83
+
84
+ const markdownStates = new WeakMap();
85
+ const deferredMutations = new Map();
86
+ const mutationLog = [];
87
+ let pointerSession = null;
88
+ let selectionSession = null;
89
+ let selectionIntentRevision = 0;
90
+ let flushTimer = null;
91
+
92
+ function semanticSurface(node) {
93
+ const element = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement;
94
+ const surface = element?.closest?.(surfaceSelector) || null;
95
+ return surface && chat.contains(surface) ? surface : null;
96
+ }
97
+
98
+ function surfaceKey(surface) {
99
+ return normalizedKey(surface?.dataset?.transcriptSurfaceKey, "");
100
+ }
101
+
102
+ function selectionSnapshot() {
103
+ const selection = window.getSelection?.();
104
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
105
+ const anchorSurface = semanticSurface(selection.anchorNode);
106
+ const focusSurface = semanticSurface(selection.focusNode);
107
+ // Cross-surface restoration is intentionally Phase 3. Retaining a range
108
+ // that never detaches still works natively; only fallback restoration is
109
+ // restricted to a single exact semantic surface.
110
+ if (!anchorSurface || anchorSurface !== focusSurface) return null;
111
+ const anchorOffset = textOffset(anchorSurface, selection.anchorNode, selection.anchorOffset);
112
+ const focusOffset = textOffset(anchorSurface, selection.focusNode, selection.focusOffset);
113
+ const text = selection.toString();
114
+ if (anchorOffset === null || focusOffset === null || !text) return null;
115
+ const bubble = anchorSurface.closest(".message");
116
+ return {
117
+ context: contextKey(),
118
+ source: anchorSurface,
119
+ messageKey: normalizedKey(bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey),
120
+ surfaceKey: surfaceKey(anchorSurface),
121
+ anchorOffset,
122
+ focusOffset,
123
+ text,
124
+ };
125
+ }
126
+
127
+ function selectionCandidates(snapshot) {
128
+ const candidates = [];
129
+ const add = (surface) => {
130
+ if (surface && chat.contains(surface) && !candidates.includes(surface)) candidates.push(surface);
131
+ };
132
+ add(snapshot.source?.isConnected ? snapshot.source : null);
133
+ if (snapshot.surfaceKey) {
134
+ for (const surface of chat.querySelectorAll("[data-transcript-surface-key]")) {
135
+ if (surface.dataset.transcriptSurfaceKey === snapshot.surfaceKey) add(surface);
136
+ }
137
+ }
138
+ if (snapshot.messageKey) {
139
+ for (const bubble of chat.querySelectorAll(".message[data-transcript-message-key], .message[data-item-key]")) {
140
+ const key = bubble.dataset.transcriptMessageKey || bubble.dataset.itemKey || "";
141
+ if (key !== snapshot.messageKey) continue;
142
+ for (const surface of bubble.querySelectorAll(surfaceSelector)) add(surface);
143
+ }
144
+ }
145
+ return candidates;
146
+ }
147
+
148
+ function restoreSelection(snapshot, { forceRemap = false } = {}) {
149
+ if (!snapshot || snapshot.context !== contextKey()) return false;
150
+ const selection = window.getSelection?.();
151
+ if (!selection) return false;
152
+ const currentText = selection.rangeCount && !selection.isCollapsed ? selection.toString() : "";
153
+ const currentAnchor = semanticSurface(selection.anchorNode);
154
+ const currentFocus = semanticSurface(selection.focusNode);
155
+ const candidates = selectionCandidates(snapshot);
156
+ if (!forceRemap && currentText === snapshot.text && currentAnchor === currentFocus && candidates.includes(currentAnchor)) return true;
157
+ // Never replace a later meaningful user selection with an older bookmark.
158
+ // During the synchronous destructive mutation that captured this bookmark,
159
+ // an equal native Range may be transiently attached to removed descendants;
160
+ // force a fresh semantic range before the browser collapses it asynchronously.
161
+ if (currentText && currentAnchor && currentFocus
162
+ && (!forceRemap || !candidates.includes(currentAnchor) || !candidates.includes(currentFocus))) return false;
163
+ for (const surface of candidates) {
164
+ const match = rangeForSnapshot(surface, snapshot);
165
+ if (!match) continue;
166
+ try {
167
+ selection.removeAllRanges();
168
+ if (snapshot.anchorOffset > snapshot.focusOffset && typeof selection.setBaseAndExtent === "function") {
169
+ selection.setBaseAndExtent(match.anchor.node, match.anchor.offset, match.focus.node, match.focus.offset);
170
+ } else {
171
+ // For forward selections, the already-validated Range is the exact
172
+ // browser representation. Rebuilding it with setBaseAndExtent can
173
+ // absorb an adjacent block-boundary newline in Chromium.
174
+ selection.addRange(match.range);
175
+ }
176
+ return true;
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+ return false;
182
+ }
183
+
184
+ function selectedSurfaceIntersects(surfaces = []) {
185
+ const snapshot = selectionSnapshot() || selectionSession?.snapshot;
186
+ const pointerSurface = pointerSession?.surface || null;
187
+ const selectedSurface = snapshot?.source || pointerSurface;
188
+ if (!selectedSurface) return false;
189
+ for (const candidate of surfaces) {
190
+ if (!candidate) continue;
191
+ if (candidate === chat || candidate === selectedSurface) return true;
192
+ if (candidate.contains?.(selectedSurface) || selectedSurface.contains?.(candidate)) return true;
193
+ }
194
+ return false;
195
+ }
196
+
197
+ function logMutation(entry) {
198
+ mutationLog.push({ at: Date.now(), ...entry });
199
+ if (mutationLog.length > MUTATION_LOG_LIMIT) mutationLog.splice(0, mutationLog.length - MUTATION_LOG_LIMIT);
200
+ }
201
+
202
+ function clearSelectionFor(surfaces) {
203
+ if (!selectedSurfaceIntersects(surfaces)) return false;
204
+ window.getSelection?.()?.removeAllRanges();
205
+ selectionSession = null;
206
+ return true;
207
+ }
208
+
209
+ function applyMutation({ key, context = contextKey(), kind = "append", surfaces = [], mutate, invalidateSelection = false }) {
210
+ if (context !== contextKey()) return { applied: false, stale: true };
211
+ const snapshot = selectionSnapshot() || selectionSession?.snapshot || null;
212
+ const intersectsSelection = selectedSurfaceIntersects(surfaces);
213
+ const invalidated = invalidateSelection && intersectsSelection;
214
+ const forceRemap = DESTRUCTIVE_KINDS.has(kind) && intersectsSelection;
215
+ const restoreIntentRevision = selectionIntentRevision;
216
+ mutate?.();
217
+ const restoredSelection = invalidated ? false : restoreSelection(snapshot, { forceRemap });
218
+ if (restoredSelection && forceRemap && typeof requestAnimationFrame === "function") {
219
+ // Chromium may apply its removed-descendant Range adjustment after the
220
+ // mutation callback returns. Reassert the exact semantic bookmark on the
221
+ // next frame; restoreSelection still rejects a newer meaningful range.
222
+ requestAnimationFrame(() => {
223
+ if (selectionIntentRevision !== restoreIntentRevision) return;
224
+ restoreSelection(snapshot, { forceRemap: true });
225
+ });
226
+ }
227
+ if (invalidated) clearSelectionFor(surfaces);
228
+ logMutation({ key, kind, deferred: false, invalidated, hadSelectionSnapshot: !!snapshot, restoredSelection, surfaces: surfaces.map(surfaceKey).filter(Boolean) });
229
+ return { applied: true, invalidated };
230
+ }
231
+
232
+ function flushDeferredMutations() {
233
+ flushTimer = null;
234
+ const pending = [...deferredMutations.values()];
235
+ deferredMutations.clear();
236
+ for (const entry of pending) applyMutation(entry);
237
+ }
238
+
239
+ function scheduleDeferredFlush() {
240
+ if (flushTimer !== null) return;
241
+ flushTimer = setTimeout(flushDeferredMutations, 0);
242
+ }
243
+
244
+ function commitTranscriptMutation({ key = "transcript", context = contextKey(), kind = "append", surfaces = [], mutate, invalidateSelection = false } = {}) {
245
+ const entry = { key, context, kind, surfaces, mutate, invalidateSelection };
246
+ const shouldDefer = DESTRUCTIVE_KINDS.has(kind)
247
+ && !invalidateSelection
248
+ && pointerSession
249
+ && pointerSession.context === context
250
+ && selectedSurfaceIntersects(surfaces);
251
+ if (shouldDefer) {
252
+ deferredMutations.set(key, entry);
253
+ logMutation({ key, kind, deferred: true, invalidated: false, surfaces: surfaces.map(surfaceKey).filter(Boolean) });
254
+ return { applied: false, deferred: true };
255
+ }
256
+ return applyMutation(entry);
257
+ }
258
+
259
+ function ownMessage(bubble, { key, role = "message" } = {}) {
260
+ if (!bubble) return "";
261
+ const messageKey = normalizedKey(key, bubble.dataset.itemKey || `live:${role}`);
262
+ bubble.dataset.transcriptMessageKey = messageKey;
263
+ bubble.dataset.transcriptRole = role;
264
+ return messageKey;
265
+ }
266
+
267
+ function ownSurface(surface, { messageKey, kind = "output", segment = "0" } = {}) {
268
+ if (!surface) return "";
269
+ const bubble = surface.closest?.(".message");
270
+ const owner = normalizedKey(messageKey, bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "live");
271
+ const surfaceIdentity = `${owner}:${normalizedKey(kind, "output")}:${normalizedKey(segment, "0")}`;
272
+ surface.dataset.transcriptSurface = kind;
273
+ surface.dataset.transcriptSurfaceKey = surfaceIdentity;
274
+ return surfaceIdentity;
275
+ }
276
+
277
+ function ownBlocks(nodes, { messageKey, kind, start = 0, tail = false } = {}) {
278
+ let index = start;
279
+ for (const node of nodes) {
280
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
281
+ const blockKey = tail ? "tail" : `block:${index++}`;
282
+ node.dataset.transcriptBlockKey = `${messageKey}:${kind}:${blockKey}`;
283
+ node.dataset.transcriptBlock = tail ? "mutable-tail" : "committed";
284
+ const nestedSurfaces = [
285
+ ...(node.matches?.("[data-transcript-surface]") ? [node] : []),
286
+ ...node.querySelectorAll?.("[data-transcript-surface]") || [],
287
+ ];
288
+ nestedSurfaces.forEach((surface, surfaceIndex) => ownSurface(surface, {
289
+ messageKey,
290
+ kind: surface.dataset.transcriptSurface || kind,
291
+ segment: `${blockKey}:${surfaceIndex}`,
292
+ }));
293
+ }
294
+ return index;
295
+ }
296
+
297
+ function reconcileMarkdownSurface({
298
+ key,
299
+ context = contextKey(),
300
+ surface,
301
+ messageKey,
302
+ kind = "assistant-final",
303
+ text = "",
304
+ stableBoundary,
305
+ renderInto,
306
+ } = {}) {
307
+ if (!surface || typeof stableBoundary !== "function" || typeof renderInto !== "function") return { applied: false, invalid: true };
308
+ const value = String(text || "");
309
+ let state = markdownStates.get(surface);
310
+ const diverged = !!state && !value.startsWith(state.stableText);
311
+ const replacesMutableTail = !!state?.tailNodes?.length;
312
+ return commitTranscriptMutation({
313
+ key: key || `markdown:${surfaceKey(surface)}`,
314
+ context,
315
+ // Removing/reparsing the open tail is destructive even for append-only
316
+ // transport data. It must wait for an intersecting native drag gesture.
317
+ kind: diverged || replacesMutableTail ? "reconcile" : "append",
318
+ surfaces: [surface],
319
+ invalidateSelection: diverged,
320
+ mutate: () => {
321
+ ownSurface(surface, { messageKey, kind });
322
+ state = markdownStates.get(surface);
323
+ if (!state || diverged) {
324
+ for (const node of [...surface.childNodes]) node.remove();
325
+ state = { stableText: "", tailNodes: [], committedBlocks: 0 };
326
+ markdownStates.set(surface, state);
327
+ }
328
+ for (const node of state.tailNodes) node.remove();
329
+ state.tailNodes = [];
330
+ const boundary = Math.max(state.stableText.length, Math.min(value.length, Number(stableBoundary(value)) || 0));
331
+ if (boundary > state.stableText.length) {
332
+ const fragment = document.createDocumentFragment();
333
+ renderInto(fragment, value.slice(state.stableText.length, boundary));
334
+ const nodes = [...fragment.childNodes];
335
+ state.committedBlocks = ownBlocks(nodes, { messageKey, kind, start: state.committedBlocks });
336
+ surface.append(fragment);
337
+ state.stableText = value.slice(0, boundary);
338
+ }
339
+ const tail = value.slice(state.stableText.length);
340
+ if (tail.trim()) {
341
+ const fragment = document.createDocumentFragment();
342
+ renderInto(fragment, tail);
343
+ state.tailNodes = [...fragment.childNodes];
344
+ ownBlocks(state.tailNodes, { messageKey, kind, tail: true });
345
+ surface.append(fragment);
346
+ }
347
+ },
348
+ });
349
+ }
350
+
351
+ function updateTextSurface({ key, context = contextKey(), surface, messageKey, kind = "compact-output", text = "" } = {}) {
352
+ if (!surface) return { applied: false, invalid: true };
353
+ const value = String(text || "");
354
+ return commitTranscriptMutation({
355
+ key: key || `text:${surfaceKey(surface)}`,
356
+ context,
357
+ kind: "append",
358
+ surfaces: [surface],
359
+ mutate: () => {
360
+ ownSurface(surface, { messageKey, kind });
361
+ let node = surface._transcriptTextNode;
362
+ if (!node?.isConnected || node.parentNode !== surface) {
363
+ node = surface.childNodes.length === 1 && surface.firstChild?.nodeType === Node.TEXT_NODE
364
+ ? surface.firstChild
365
+ : document.createTextNode("");
366
+ if (!node.isConnected) surface.append(node);
367
+ surface._transcriptTextNode = node;
368
+ }
369
+ if (value.startsWith(node.data)) node.appendData(value.slice(node.data.length));
370
+ else node.data = value;
371
+ },
372
+ });
373
+ }
374
+
375
+ function replaceChildren(target, ...nodes) {
376
+ target?.replaceChildren(...nodes);
377
+ }
378
+
379
+ function replaceHtml(target, html) {
380
+ if (!target) return;
381
+ const template = document.createElement("template");
382
+ template.innerHTML = String(html || "");
383
+ replaceChildren(target, template.content);
384
+ }
385
+
386
+ function invalidateSelection({ surfaces = [] } = {}) {
387
+ return clearSelectionFor(surfaces);
388
+ }
389
+
390
+ function endSelectionSession() {
391
+ pointerSession = null;
392
+ selectionSession = null;
393
+ scheduleDeferredFlush();
394
+ }
395
+
396
+ document.addEventListener("pointerdown", () => { selectionIntentRevision += 1; }, { capture: true, passive: true });
397
+ document.addEventListener("keydown", () => { selectionIntentRevision += 1; }, { capture: true });
398
+ chat.addEventListener("pointerdown", (event) => {
399
+ if (event.button !== undefined && event.button !== 0) return;
400
+ const surface = semanticSurface(event.target);
401
+ if (!surface) return;
402
+ pointerSession = { pointerId: event.pointerId, context: contextKey(), surface };
403
+ }, { capture: true, passive: true });
404
+ window.addEventListener("pointerup", (event) => {
405
+ if (!pointerSession || (event.pointerId !== undefined && event.pointerId !== pointerSession.pointerId)) return;
406
+ pointerSession = null;
407
+ selectionSession = { snapshot: selectionSnapshot() };
408
+ scheduleDeferredFlush();
409
+ }, { capture: true, passive: true });
410
+ window.addEventListener("pointercancel", () => endSelectionSession(), { capture: true, passive: true });
411
+ window.addEventListener("blur", () => endSelectionSession(), { passive: true });
412
+ document.addEventListener("selectionchange", () => {
413
+ const snapshot = selectionSnapshot();
414
+ if (snapshot) selectionSession = { snapshot };
415
+ else if (!pointerSession) selectionSession = null;
416
+ });
417
+ chat.addEventListener("copy", () => {
418
+ // Allow the browser to read the selected text before applying queued work.
419
+ endSelectionSession();
420
+ }, { capture: true });
421
+
422
+ return {
423
+ commitTranscriptMutation,
424
+ invalidateSelection,
425
+ mutationLog: () => mutationLog.slice(),
426
+ ownMessage,
427
+ ownSurface,
428
+ reconcileMarkdownSurface,
429
+ replaceChildren,
430
+ replaceHtml,
431
+ updateTextSurface,
432
+ };
433
+ }
@@ -57,7 +57,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
57
57
  reload: new FakeElement(),
58
58
  copyStatus: new FakeElement(),
59
59
  };
60
- const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=85", sheet: stylesheetLoaded ? {} : null });
60
+ const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=92", sheet: stylesheetLoaded ? {} : null });
61
61
  const listeners = new Map();
62
62
  const timers = new Map();
63
63
  let timerId = 0;
@@ -76,7 +76,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
76
76
  removeEventListener(name) { listeners.delete(name); },
77
77
  };
78
78
  const document = {
79
- currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=94" } }),
79
+ currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=103" } }),
80
80
  readyState: "complete",
81
81
  querySelector(selector) {
82
82
  return {
@@ -174,7 +174,7 @@ for (const moduleName of startupModuleNames) {
174
174
  assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
175
175
  }
176
176
  assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
177
- assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=94"), "the inline loader should own app module startup");
177
+ assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=103"), "the inline loader should own app module startup");
178
178
  assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
179
179
 
180
180
  console.log("boot-failure-diagnostics.test.mjs passed");