@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.
- package/README.md +34 -5
- package/bin/pi-webui.mjs +606 -102
- package/lib/component-update-state.mjs +126 -0
- package/lib/npm-command.mjs +81 -0
- package/lib/queue-mutation.mjs +6 -0
- package/lib/trust-boundaries.mjs +1 -0
- package/lib/workspace-files-live-watcher.mjs +138 -0
- package/package.json +8 -3
- package/public/app.js +4231 -376
- package/public/index.html +265 -52
- package/public/mobile-shell-state.mjs +166 -0
- package/public/service-worker.js +60 -13
- package/public/styles.css +1790 -383
- package/public/subagent-gate-visibility.mjs +16 -0
- package/public/subagent-launch-slot-state.mjs +16 -0
- package/public/transcript-renderer.mjs +433 -0
- package/tests/boot-failure-diagnostics.test.mjs +63 -5
- package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
- package/tests/browser/interaction-continuity.spec.mjs +897 -0
- package/tests/browser/mobile-foundation.spec.mjs +363 -0
- package/tests/browser/optimistic-prompt.spec.mjs +130 -0
- package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
- package/tests/browser/stats-overlay.spec.mjs +265 -0
- package/tests/chat-scroll-intent-static.test.mjs +6 -1
- package/tests/codex-fast-mode-static.test.mjs +8 -5
- package/tests/compact-sections-static.test.mjs +20 -2
- package/tests/compaction-mutation-contract.test.mjs +18 -4
- package/tests/compaction-static.test.mjs +1 -0
- package/tests/completion-signal-contract.test.mjs +13 -2
- package/tests/component-update-api-static.test.mjs +67 -0
- package/tests/component-update-state.test.mjs +80 -0
- package/tests/control-deck-component-updates-static.test.mjs +251 -0
- package/tests/fast-mode-client-static.test.mjs +7 -4
- package/tests/fixtures/fake-pi.mjs +305 -2
- package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
- package/tests/git-panel-gitignore-static.test.mjs +104 -0
- package/tests/http-endpoints-harness.test.mjs +228 -2
- package/tests/interaction-state-stability-static.test.mjs +271 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
- package/tests/mobile-foundation-static.test.mjs +71 -0
- package/tests/mobile-phone-experience-static.test.mjs +65 -0
- package/tests/mobile-shell-state.test.mjs +69 -0
- package/tests/mobile-static.test.mjs +246 -39
- package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
- package/tests/native-parity-harness.test.mjs +2 -0
- package/tests/npm-command.test.mjs +64 -1
- package/tests/open-issue-wizard-static.test.mjs +2 -1
- package/tests/queue-edit-reorder-static.test.mjs +9 -1
- package/tests/queue-mutation-contract.test.mjs +22 -0
- package/tests/service-worker-lifecycle.test.mjs +120 -0
- package/tests/side-panel-section-reorder-static.test.mjs +68 -0
- package/tests/sse-backpressure-harness.test.mjs +137 -0
- package/tests/stats-dashboard-static.test.mjs +266 -0
- package/tests/streaming-ui-coupling.test.mjs +7 -1
- package/tests/subagent-gate-visibility.test.mjs +18 -2
- package/tests/subagent-launch-slot-state.test.mjs +32 -0
- package/tests/subagent-launch-slots-static.test.mjs +8 -2
- package/tests/subagents-helper.test.mjs +90 -0
- package/tests/terminal-tab-workspace-static.test.mjs +1 -1
- package/tests/update-commands.test.mjs +4 -0
- package/tests/workspace-files-live-updates-static.test.mjs +76 -0
- package/tests/workspace-files-live-watcher.test.mjs +95 -0
- 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
|
+
}
|
|
@@ -48,7 +48,15 @@ class FakeResponse {
|
|
|
48
48
|
async json() { return this._json; }
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
function makeEnvironment({
|
|
51
|
+
function makeEnvironment({
|
|
52
|
+
importApp,
|
|
53
|
+
stylesheetLoaded = true,
|
|
54
|
+
stylesheetStatus = 200,
|
|
55
|
+
workflowModuleStatus = 404,
|
|
56
|
+
manifestStatus = 200,
|
|
57
|
+
manifestText = '{"name":"Pi Web UI"}',
|
|
58
|
+
hangingHealth = false,
|
|
59
|
+
} = {}) {
|
|
52
60
|
const elements = {
|
|
53
61
|
panel: new FakeElement({ hidden: true }),
|
|
54
62
|
reason: new FakeElement(),
|
|
@@ -57,7 +65,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
|
|
|
57
65
|
reload: new FakeElement(),
|
|
58
66
|
copyStatus: new FakeElement(),
|
|
59
67
|
};
|
|
60
|
-
const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=
|
|
68
|
+
const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=93", sheet: stylesheetLoaded ? {} : null });
|
|
61
69
|
const listeners = new Map();
|
|
62
70
|
const timers = new Map();
|
|
63
71
|
let timerId = 0;
|
|
@@ -76,7 +84,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
|
|
|
76
84
|
removeEventListener(name) { listeners.delete(name); },
|
|
77
85
|
};
|
|
78
86
|
const document = {
|
|
79
|
-
currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=
|
|
87
|
+
currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=104" } }),
|
|
80
88
|
readyState: "complete",
|
|
81
89
|
querySelector(selector) {
|
|
82
90
|
return {
|
|
@@ -94,10 +102,14 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
|
|
|
94
102
|
|
|
95
103
|
async function fetch(input) {
|
|
96
104
|
const url = String(input);
|
|
97
|
-
if (url.includes("/api/health"))
|
|
105
|
+
if (url.includes("/api/health")) {
|
|
106
|
+
if (hangingHealth) return new Promise(() => {});
|
|
107
|
+
return new FakeResponse(url, 200, { type: "application/json", json: { ok: true, webuiVersion: "0.7.6", remoteAuthPin: "1234" } });
|
|
108
|
+
}
|
|
98
109
|
if (url.includes("/app.js")) return new FakeResponse(url, 200, { type: "text/javascript", text: 'import "./workflow-status-stack.mjs";\nimport "./fast-output-live.mjs";' });
|
|
99
110
|
if (url.includes("workflow-status-stack.mjs")) return new FakeResponse(url, workflowModuleStatus, { type: workflowModuleStatus === 200 ? "text/javascript" : "application/json" });
|
|
100
111
|
if (url.includes("fast-output-live.mjs")) return new FakeResponse(url, 200, { type: "text/javascript" });
|
|
112
|
+
if (url.includes("manifest.webmanifest")) return new FakeResponse(url, manifestStatus, { type: manifestStatus === 200 ? "application/manifest+json" : "text/html", text: manifestText });
|
|
101
113
|
if (url.includes("styles.css")) return new FakeResponse(url, stylesheetStatus, { type: "text/css" });
|
|
102
114
|
return new FakeResponse(url, 404);
|
|
103
115
|
}
|
|
@@ -124,6 +136,12 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
|
|
|
124
136
|
elements,
|
|
125
137
|
listeners,
|
|
126
138
|
timers,
|
|
139
|
+
fireTimers() {
|
|
140
|
+
for (const [id, callback] of [...timers]) {
|
|
141
|
+
timers.delete(id);
|
|
142
|
+
callback();
|
|
143
|
+
}
|
|
144
|
+
},
|
|
127
145
|
copied: () => copied,
|
|
128
146
|
reloaded: () => reloaded,
|
|
129
147
|
};
|
|
@@ -168,13 +186,53 @@ await settleAsyncWork();
|
|
|
168
186
|
assert.equal(stylesheetFailure.elements.panel.hidden, false, "a missing critical stylesheet should expose the boot-failure panel");
|
|
169
187
|
assert.match(stylesheetFailure.elements.report.value, /Critical stylesheet returned HTTP 404/);
|
|
170
188
|
|
|
189
|
+
const syntaxFailureWithManifestNoise = makeEnvironment({
|
|
190
|
+
importApp: async () => {
|
|
191
|
+
const error = new Error("Unexpected token '}'");
|
|
192
|
+
error.name = "SyntaxError";
|
|
193
|
+
throw error;
|
|
194
|
+
},
|
|
195
|
+
workflowModuleStatus: 200,
|
|
196
|
+
manifestText: "<!doctype html><title>wrong response</title>",
|
|
197
|
+
});
|
|
198
|
+
vm.runInNewContext(loaderSource, syntaxFailureWithManifestNoise.context, { filename: "webui-boot-loader.js" });
|
|
199
|
+
await settleAsyncWork();
|
|
200
|
+
assert.match(syntaxFailureWithManifestNoise.elements.reason.textContent, /JavaScript failed during startup: SyntaxError: Unexpected token/);
|
|
201
|
+
assert.match(syntaxFailureWithManifestNoise.elements.report.value, /entry module: HTTP 200 text\/javascript/);
|
|
202
|
+
assert.match(syntaxFailureWithManifestNoise.elements.report.value, /optional web manifest: HTTP 200 application\/manifest\+json.*invalid JSON/);
|
|
203
|
+
assert.match(syntaxFailureWithManifestNoise.elements.report.value, /web manifest has a separate problem.*does not execute or block app\.js startup/i, "manifest parse noise should be identified as non-blocking");
|
|
204
|
+
|
|
205
|
+
const stalledBoot = makeEnvironment({
|
|
206
|
+
importApp: async () => new Promise(() => {}),
|
|
207
|
+
workflowModuleStatus: 200,
|
|
208
|
+
});
|
|
209
|
+
vm.runInNewContext(loaderSource, stalledBoot.context, { filename: "webui-boot-loader.js" });
|
|
210
|
+
stalledBoot.fireTimers();
|
|
211
|
+
await settleAsyncWork();
|
|
212
|
+
assert.match(stalledBoot.elements.reason.textContent, /WebUI startup stalled even though the current HTTP checks succeeded/);
|
|
213
|
+
assert.match(stalledBoot.elements.report.value, /Error: Error: Startup watchdog timed out/);
|
|
214
|
+
|
|
215
|
+
const hangingDiagnostic = makeEnvironment({
|
|
216
|
+
importApp: async () => { throw new Error("Startup module failed before diagnostics"); },
|
|
217
|
+
workflowModuleStatus: 200,
|
|
218
|
+
hangingHealth: true,
|
|
219
|
+
});
|
|
220
|
+
vm.runInNewContext(loaderSource, hangingDiagnostic.context, { filename: "webui-boot-loader.js" });
|
|
221
|
+
await settleAsyncWork();
|
|
222
|
+
hangingDiagnostic.fireTimers();
|
|
223
|
+
await settleAsyncWork();
|
|
224
|
+
assert.equal(hangingDiagnostic.elements.panel.hidden, false, "the failure panel should remain usable while a diagnostic request hangs");
|
|
225
|
+
assert.doesNotMatch(hangingDiagnostic.elements.report.value, /Collecting diagnostics/, "bounded probes must always replace the collecting placeholder");
|
|
226
|
+
assert.match(hangingDiagnostic.elements.reason.textContent, /diagnostic check timed out while probing \/api\/health/i);
|
|
227
|
+
assert.match(hangingDiagnostic.elements.report.value, /backend health: diagnostic timed out after 3 seconds/);
|
|
228
|
+
|
|
171
229
|
const startupModuleNames = [...new Set([...app.matchAll(/(?:\bfrom\s+|\bimport\s*(?:\(\s*)?)["']\.\/([^"'?]+)(?:\?[^"']*)?["']/g)].map((match) => match[1]))];
|
|
172
230
|
assert.ok(startupModuleNames.length >= 1, "the startup-module invariant should discover app.js imports");
|
|
173
231
|
for (const moduleName of startupModuleNames) {
|
|
174
232
|
assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
|
|
175
233
|
}
|
|
176
234
|
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=
|
|
235
|
+
assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=104"), "the inline loader should own app module startup");
|
|
178
236
|
assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
|
|
179
237
|
|
|
180
238
|
console.log("boot-failure-diagnostics.test.mjs passed");
|