@firstpick/pi-package-webui 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +21 -3
  2. package/bin/pi-webui.mjs +287 -32
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/thinking-stream-recovery.mjs +156 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/ui-layout-settings.mjs +254 -0
  8. package/package.json +5 -3
  9. package/public/app.js +3072 -142
  10. package/public/index.html +188 -39
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +1091 -39
  13. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  14. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  15. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  16. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  17. package/tests/browser/interaction-continuity.spec.mjs +187 -0
  18. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  19. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  20. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  21. package/tests/browser/stats-overlay.spec.mjs +265 -0
  22. package/tests/codex-fast-mode-static.test.mjs +2 -2
  23. package/tests/component-update-api-static.test.mjs +67 -0
  24. package/tests/component-update-state.test.mjs +80 -0
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  27. package/tests/fast-mode-client-static.test.mjs +2 -2
  28. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  29. package/tests/fixtures/fake-pi.mjs +180 -6
  30. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  31. package/tests/git-workflow-preferences.test.mjs +4 -2
  32. package/tests/http-endpoints-harness.test.mjs +88 -1
  33. package/tests/interaction-state-stability-static.test.mjs +24 -4
  34. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  35. package/tests/mobile-foundation-static.test.mjs +6 -4
  36. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  37. package/tests/mobile-static.test.mjs +34 -16
  38. package/tests/native-parity-harness.test.mjs +2 -0
  39. package/tests/open-issue-wizard-static.test.mjs +1 -1
  40. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  41. package/tests/questionnaire-dialog.test.mjs +511 -0
  42. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  43. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  44. package/tests/side-panel-resize-static.test.mjs +1 -0
  45. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  46. package/tests/sse-backpressure-harness.test.mjs +51 -12
  47. package/tests/stats-dashboard-static.test.mjs +266 -0
  48. package/tests/subagent-launch-slots.test.mjs +1 -1
  49. package/tests/thinking-stream-recovery.test.mjs +88 -0
  50. package/tests/ui-layout-settings.test.mjs +92 -0
  51. package/tests/webui-settings-locking.test.mjs +159 -0
@@ -1,7 +1,9 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
1
+ import { mkdir, open, readFile, readdir, rename, rm, rmdir } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
4
5
  import { normalizeSubagentLaunchSlots } from "./subagent-launch-slots.mjs";
6
+ import { normalizeUiLayout } from "./ui-layout-settings.mjs";
5
7
  import { normalizeOutputMode, OUTPUT_MODE_NORMAL } from "./webui-output-mode.mjs";
6
8
 
7
9
  export const GIT_WORKFLOW_SETUP_VERSION = 1;
@@ -24,8 +26,10 @@ export function supportedGitWorkflowThinkingLevels(model) {
24
26
  });
25
27
  }
26
28
 
27
- const WEBUI_SETTINGS_VERSION = 4;
29
+ const WEBUI_SETTINGS_VERSION = 6;
28
30
  const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
31
+ const WEBUI_SETTINGS_LOCK_TIMEOUT_MS = 2_000;
32
+ const WEBUI_SETTINGS_LOCK_RETRY_MS = 25;
29
33
  export const WEBUI_SIDE_PANEL_WIDTH_MIN_PX = 320;
30
34
  export const WEBUI_SIDE_PANEL_WIDTH_MAX_PX = 4096;
31
35
  const webuiSettingsUpdateQueues = new Map();
@@ -112,6 +116,10 @@ export function gitWorkflowPreferencesSummary(preferences) {
112
116
 
113
117
  export function webuiSettingsFile(env = process.env) {
114
118
  if (env[WEBUI_SETTINGS_FILE_ENV]) return path.resolve(String(env[WEBUI_SETTINGS_FILE_ENV]).replace(/^~(?=$|[\\/])/, homedir()));
119
+ return path.join(homedir(), ".pi", "webui", "settings.json");
120
+ }
121
+
122
+ export function legacyWebuiSettingsFile(env = process.env) {
115
123
  const configRoot = env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
116
124
  return path.join(configRoot, "pi-webui", "settings.json");
117
125
  }
@@ -169,24 +177,236 @@ export function normalizeWebuiSettings(value) {
169
177
  gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
170
178
  resourceDefaults: normalizeResourceDefaults(source.resourceDefaults),
171
179
  interfacePreferences: normalizeInterfacePreferences(source.interfacePreferences),
180
+ uiLayout: normalizeUiLayout(source.uiLayout),
172
181
  subagentLaunchSlots: normalizeSubagentLaunchSlots(source.subagentLaunchSlots),
173
182
  };
174
183
  }
175
184
 
176
- async function readRawWebuiSettings(storageFile) {
185
+ function settingsReadError(storageFile, error) {
186
+ const wrapped = new Error(`Cannot read Pi Web UI settings at ${storageFile}: ${error instanceof Error ? error.message : String(error)}`);
187
+ wrapped.code = "WEBUI_SETTINGS_READ_FAILED";
188
+ wrapped.cause = error;
189
+ return wrapped;
190
+ }
191
+
192
+ async function readRawWebuiSettings(storageFile, { missing = {} } = {}) {
193
+ let text;
194
+ try {
195
+ text = await readFile(storageFile, "utf8");
196
+ } catch (error) {
197
+ if (error?.code === "ENOENT") return missing;
198
+ throw settingsReadError(storageFile, error);
199
+ }
200
+ try {
201
+ const parsed = JSON.parse(text);
202
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("settings must contain a JSON object");
203
+ return parsed;
204
+ } catch (error) {
205
+ throw settingsReadError(storageFile, error);
206
+ }
207
+ }
208
+
209
+ function isDefaultSettingsTarget(storageFile, env = process.env) {
210
+ return !env[WEBUI_SETTINGS_FILE_ENV] && path.resolve(storageFile) === path.resolve(webuiSettingsFile(env));
211
+ }
212
+
213
+ async function ensurePrivateSettingsDirectory(storageFile) {
214
+ await mkdir(path.dirname(storageFile), { recursive: true, mode: 0o700 });
215
+ }
216
+
217
+ function lockDirectoryFor(storageFile) {
218
+ return `${storageFile}.lock`;
219
+ }
220
+
221
+ function lockOwnerIsDead(pid) {
222
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
177
223
  try {
178
- return settingsObject(JSON.parse(await readFile(storageFile, "utf8")));
224
+ process.kill(pid, 0);
225
+ return false;
179
226
  } catch (error) {
180
- if (error?.code === "ENOENT") return {};
181
- throw new Error(`Cannot read Pi Web UI settings at ${storageFile}: ${error instanceof Error ? error.message : String(error)}`);
227
+ return error?.code === "ESRCH";
182
228
  }
183
229
  }
184
230
 
231
+ async function readSettingsLockRecords(lockDirectory) {
232
+ const names = (await readdir(lockDirectory)).filter((name) => name.endsWith(".json")).sort();
233
+ return Promise.all(names.map(async (name) => {
234
+ const recordFile = path.join(lockDirectory, name);
235
+ try {
236
+ const value = JSON.parse(await readFile(recordFile, "utf8"));
237
+ const valid = Number.isSafeInteger(value?.pid)
238
+ && value.pid > 0
239
+ && typeof value?.token === "string"
240
+ && value.token.length > 0
241
+ && ["pending", "active"].includes(value?.state);
242
+ return { ...value, name, recordFile, valid };
243
+ } catch {
244
+ return { name, recordFile, valid: false };
245
+ }
246
+ }));
247
+ }
248
+
249
+ async function writeSettingsLockRecord(recordFile, value) {
250
+ const temporaryFile = `${recordFile}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
251
+ let handle;
252
+ try {
253
+ handle = await open(temporaryFile, "wx", 0o600);
254
+ await handle.writeFile(`${JSON.stringify(value)}\n`, "utf8");
255
+ await handle.sync();
256
+ await handle.close();
257
+ handle = undefined;
258
+ await rename(temporaryFile, recordFile);
259
+ } catch (error) {
260
+ await handle?.close().catch(() => {});
261
+ await rm(temporaryFile, { force: true }).catch(() => {});
262
+ throw error;
263
+ }
264
+ }
265
+
266
+ async function releaseSettingsLock(lockDirectory, recordFile) {
267
+ await rm(recordFile, { force: true });
268
+ await rmdir(lockDirectory).catch((error) => {
269
+ if (error?.code !== "ENOENT" && error?.code !== "ENOTEMPTY" && error?.code !== "EEXIST") throw error;
270
+ });
271
+ }
272
+
273
+ export async function withWebuiSettingsLock(storageFile, operation, {
274
+ timeoutMs = WEBUI_SETTINGS_LOCK_TIMEOUT_MS,
275
+ retryMs = WEBUI_SETTINGS_LOCK_RETRY_MS,
276
+ } = {}) {
277
+ await ensurePrivateSettingsDirectory(storageFile);
278
+ const lockDirectory = lockDirectoryFor(storageFile);
279
+ await mkdir(lockDirectory, { mode: 0o700 }).catch((error) => {
280
+ if (error?.code !== "EEXIST") throw error;
281
+ });
282
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
283
+ const recordFile = path.join(lockDirectory, `${token}.json`);
284
+ const ownRecord = { pid: process.pid, token, state: "pending" };
285
+ let handle;
286
+ try {
287
+ handle = await open(recordFile, "wx", 0o600);
288
+ await handle.writeFile(`${JSON.stringify(ownRecord)}\n`, "utf8");
289
+ await handle.sync();
290
+ await handle.close();
291
+ handle = undefined;
292
+ } catch (error) {
293
+ await handle?.close().catch(() => {});
294
+ await rm(recordFile, { force: true }).catch(() => {});
295
+ throw error;
296
+ }
297
+
298
+ const deadline = Date.now() + Math.max(0, timeoutMs);
299
+ let acquired = false;
300
+ try {
301
+ while (!acquired) {
302
+ let records = await readSettingsLockRecords(lockDirectory);
303
+ let removedDeadOwner = false;
304
+ for (const record of records) {
305
+ if (record.valid && lockOwnerIsDead(record.pid)) {
306
+ await rm(record.recordFile, { force: true });
307
+ removedDeadOwner = true;
308
+ }
309
+ }
310
+ if (removedDeadOwner) continue;
311
+
312
+ const active = records.filter((record) => record.valid && record.state === "active");
313
+ if (active.length === 1 && active[0].token === token) {
314
+ acquired = true;
315
+ break;
316
+ }
317
+ if (active.length === 0 && records[0]?.token === token && records[0]?.valid) {
318
+ ownRecord.state = "active";
319
+ await writeSettingsLockRecord(recordFile, ownRecord);
320
+ continue;
321
+ }
322
+ if (Date.now() >= deadline) {
323
+ const timeoutError = new Error("Timed out waiting for the Pi Web UI settings lock");
324
+ timeoutError.code = "WEBUI_SETTINGS_LOCK_TIMEOUT";
325
+ throw timeoutError;
326
+ }
327
+ await delay(Math.max(1, Math.min(retryMs, deadline - Date.now())));
328
+ }
329
+ return await operation();
330
+ } finally {
331
+ await releaseSettingsLock(lockDirectory, recordFile);
332
+ }
333
+ }
334
+
335
+ async function syncDirectoryBestEffort(directory) {
336
+ let handle;
337
+ try {
338
+ handle = await open(directory, "r");
339
+ await handle.sync();
340
+ } catch {
341
+ // Directory fsync is unsupported on some platforms/filesystems.
342
+ } finally {
343
+ await handle?.close().catch(() => {});
344
+ }
345
+ }
346
+
347
+ async function writePrivateAtomicSettings(storageFile, value) {
348
+ await ensurePrivateSettingsDirectory(storageFile);
349
+ const temporaryFile = path.join(
350
+ path.dirname(storageFile),
351
+ `.${path.basename(storageFile)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
352
+ );
353
+ let handle;
354
+ try {
355
+ handle = await open(temporaryFile, "wx", 0o600);
356
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
357
+ await handle.sync();
358
+ await handle.close();
359
+ handle = undefined;
360
+ await rename(temporaryFile, storageFile);
361
+ await syncDirectoryBestEffort(path.dirname(storageFile));
362
+ } catch (error) {
363
+ await handle?.close().catch(() => {});
364
+ await rm(temporaryFile, { force: true }).catch(() => {});
365
+ throw error;
366
+ }
367
+ }
368
+
369
+ export async function migrateLegacyWebuiSettings(targetFile, legacyFile) {
370
+ if (path.resolve(targetFile) === path.resolve(legacyFile)) return false;
371
+ try {
372
+ await readFile(targetFile, "utf8");
373
+ return false;
374
+ } catch (error) {
375
+ if (error?.code !== "ENOENT") throw settingsReadError(targetFile, error);
376
+ }
377
+ let legacy;
378
+ try {
379
+ legacy = await readRawWebuiSettings(legacyFile, { missing: null });
380
+ } catch {
381
+ return false;
382
+ }
383
+ if (!legacy) return false;
384
+ return withWebuiSettingsLock(targetFile, async () => {
385
+ try {
386
+ await readFile(targetFile, "utf8");
387
+ return false;
388
+ } catch (error) {
389
+ if (error?.code !== "ENOENT") throw settingsReadError(targetFile, error);
390
+ }
391
+ const { settings, persistLaunchSlots, persistedUiLayout } = mergeWebuiSettings(legacy, {});
392
+ const persisted = { ...settings, uiLayout: persistedUiLayout };
393
+ if (!persistLaunchSlots) delete persisted.subagentLaunchSlots;
394
+ await writePrivateAtomicSettings(targetFile, persisted);
395
+ return true;
396
+ });
397
+ }
398
+
399
+ async function ensureDefaultSettingsMigration(storageFile, env = process.env) {
400
+ if (!isDefaultSettingsTarget(storageFile, env)) return false;
401
+ return migrateLegacyWebuiSettings(storageFile, legacyWebuiSettingsFile(env));
402
+ }
403
+
185
404
  export async function readWebuiSettings(storageFile = webuiSettingsFile(), { reportInvalidOutputMode = false } = {}) {
405
+ await ensureDefaultSettingsMigration(storageFile);
186
406
  const raw = await readRawWebuiSettings(storageFile);
187
407
  const normalized = normalizeWebuiSettings(raw);
188
408
  if (reportInvalidOutputMode && raw.outputModeDefault !== undefined && normalized.outputModeDefault !== raw.outputModeDefault) {
189
- console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)} in ${storageFile}; using ${OUTPUT_MODE_NORMAL}.`);
409
+ console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)}; using ${OUTPUT_MODE_NORMAL}.`);
190
410
  }
191
411
  return normalized;
192
412
  }
@@ -214,6 +434,9 @@ function mergeWebuiSettings(rawCurrent, patch) {
214
434
  interfacePreferences: patchValue.interfacePreferences
215
435
  ? { ...current.interfacePreferences, ...patchValue.interfacePreferences }
216
436
  : current.interfacePreferences,
437
+ uiLayout: Object.hasOwn(patchValue, "uiLayout")
438
+ ? normalizeUiLayout(patchValue.uiLayout)
439
+ : current.uiLayout,
217
440
  };
218
441
  if (persistLaunchSlots) {
219
442
  source.subagentLaunchSlots = hasLaunchSlotPatch
@@ -224,17 +447,18 @@ function mergeWebuiSettings(rawCurrent, patch) {
224
447
  delete source.subagentLaunchSlots;
225
448
  source.version = Math.max(WEBUI_SETTINGS_VERSION, Number.isInteger(raw.version) ? raw.version : 0);
226
449
  }
227
- return { settings: normalizeWebuiSettings(source), persistLaunchSlots };
450
+ const settings = normalizeWebuiSettings(source);
451
+ const persistedUiLayout = !Object.hasOwn(patchValue, "uiLayout") && raw.uiLayout !== undefined
452
+ ? raw.uiLayout
453
+ : settings.uiLayout;
454
+ return { settings, persistLaunchSlots, persistedUiLayout };
228
455
  }
229
456
 
230
457
  async function writeMergedWebuiSettings(rawCurrent, patch, storageFile) {
231
- const { settings, persistLaunchSlots } = mergeWebuiSettings(rawCurrent, patch);
232
- const persisted = { ...settings };
458
+ const { settings, persistLaunchSlots, persistedUiLayout } = mergeWebuiSettings(rawCurrent, patch);
459
+ const persisted = { ...settings, uiLayout: persistedUiLayout };
233
460
  if (!persistLaunchSlots) delete persisted.subagentLaunchSlots;
234
- await mkdir(path.dirname(storageFile), { recursive: true });
235
- const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
236
- await writeFile(temporaryFile, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });
237
- await rename(temporaryFile, storageFile);
461
+ await writePrivateAtomicSettings(storageFile, persisted);
238
462
  return settings;
239
463
  }
240
464
 
@@ -246,11 +470,14 @@ export function updateWebuiSettings(updater, storageFile = webuiSettingsFile())
246
470
  const queueKey = path.resolve(storageFile);
247
471
  const previous = webuiSettingsUpdateQueues.get(queueKey) || Promise.resolve();
248
472
  const currentUpdate = previous.catch(() => {}).then(async () => {
249
- const rawCurrent = await readRawWebuiSettings(storageFile);
250
- const current = normalizeWebuiSettings(rawCurrent);
251
- const patch = await updater(current);
252
- if (patch === undefined) return current;
253
- return writeMergedWebuiSettings(rawCurrent, patch, storageFile);
473
+ await ensureDefaultSettingsMigration(storageFile);
474
+ return withWebuiSettingsLock(storageFile, async () => {
475
+ const rawCurrent = await readRawWebuiSettings(storageFile);
476
+ const current = normalizeWebuiSettings(rawCurrent);
477
+ const patch = await updater(current);
478
+ if (patch === undefined) return current;
479
+ return writeMergedWebuiSettings(rawCurrent, patch, storageFile);
480
+ });
254
481
  });
255
482
  webuiSettingsUpdateQueues.set(queueKey, currentUpdate);
256
483
  return currentUpdate.finally(() => {
@@ -0,0 +1,156 @@
1
+ const COMPLETED_RECOVERY_LIMIT = 128;
2
+
3
+ function text(value) {
4
+ return typeof value === "string" ? value : "";
5
+ }
6
+
7
+ function thinkingContentIndex(event = {}, update = event.assistantMessageEvent || {}) {
8
+ const value = update.contentIndex ?? event.contentIndex;
9
+ return Number.isInteger(value) && value >= 0 ? value : 0;
10
+ }
11
+
12
+ function thinkingPart(part) {
13
+ return !!(part && typeof part === "object" && (part.type === "thinking" || typeof part.thinking === "string"));
14
+ }
15
+
16
+ function thinkingPartText(part) {
17
+ if (!thinkingPart(part)) return "";
18
+ return text(part.thinking) || text(part.content) || text(part.text);
19
+ }
20
+
21
+ function messageThinkingAt(message, contentIndex) {
22
+ if (!Array.isArray(message?.content)) return "";
23
+ return thinkingPartText(message.content[contentIndex]);
24
+ }
25
+
26
+ function messageThinkingTemplateAt(message, contentIndex) {
27
+ if (!Array.isArray(message?.content)) return null;
28
+ const part = message.content[contentIndex];
29
+ return thinkingPart(part) ? part : null;
30
+ }
31
+
32
+ /**
33
+ * Prefer the longer value only when the two snapshots are prefix-compatible.
34
+ * Divergent authoritative content wins so provider corrections/redactions are
35
+ * never silently overwritten by an earlier stream accumulator.
36
+ */
37
+ export function reconcileThinkingSnapshot(accumulated, snapshot) {
38
+ const previous = text(accumulated);
39
+ const next = text(snapshot);
40
+ if (!previous) return next;
41
+ if (!next) return previous;
42
+ if (next.startsWith(previous)) return next;
43
+ if (previous.startsWith(next)) return previous;
44
+ return next;
45
+ }
46
+
47
+ function replaceThinkingAt(message, contentIndex, recovered, template = null) {
48
+ if (!message || message.role !== "assistant" || !Array.isArray(message.content) || !recovered) return message;
49
+ const current = message.content[contentIndex];
50
+ let replacement = null;
51
+ if (thinkingPart(current)) {
52
+ replacement = { ...current, type: current.type || "thinking", thinking: recovered };
53
+ } else if (thinkingPart(template) && contentIndex <= message.content.length) {
54
+ replacement = { ...template, type: template.type || "thinking", thinking: recovered };
55
+ }
56
+ if (!replacement) return message;
57
+ const content = [...message.content];
58
+ if (contentIndex < content.length) content[contentIndex] = replacement;
59
+ else content.push(replacement);
60
+ return { ...message, content };
61
+ }
62
+
63
+ function recoveryKey(timestamp, contentIndex) {
64
+ if (timestamp === undefined || timestamp === null || timestamp === "") return "";
65
+ return `${String(timestamp)}|${contentIndex}`;
66
+ }
67
+
68
+ export class ThinkingStreamRecovery {
69
+ #active = new Map();
70
+ #completed = new Map();
71
+
72
+ ingest(rawEvent) {
73
+ if (!rawEvent || typeof rawEvent !== "object") return rawEvent;
74
+ const event = rawEvent;
75
+ if (event.type === "message_start" && event.message?.role === "assistant") {
76
+ this.#active.clear();
77
+ return event;
78
+ }
79
+ if (event.type === "message_update") return this.#ingestUpdate(event);
80
+ if (event.type === "message_end" && event.message?.role === "assistant") return this.#ingestEnd(event);
81
+ return event;
82
+ }
83
+
84
+ applyToMessages(messages) {
85
+ if (!Array.isArray(messages) || this.#completed.size === 0) return messages;
86
+ let changed = false;
87
+ const recoveredMessages = messages.map((message) => {
88
+ if (message?.role !== "assistant") return message;
89
+ let recoveredMessage = message;
90
+ for (const record of this.#completed.values()) {
91
+ if (record.timestamp !== String(message.timestamp ?? "")) continue;
92
+ const authoritative = messageThinkingAt(recoveredMessage, record.contentIndex);
93
+ const recovered = reconcileThinkingSnapshot(record.text, authoritative);
94
+ if (recovered !== authoritative) {
95
+ recoveredMessage = replaceThinkingAt(recoveredMessage, record.contentIndex, recovered, record.template);
96
+ }
97
+ }
98
+ if (recoveredMessage !== message) changed = true;
99
+ return recoveredMessage;
100
+ });
101
+ return changed ? recoveredMessages : messages;
102
+ }
103
+
104
+ #ingestUpdate(event) {
105
+ const update = event.assistantMessageEvent;
106
+ if (!update || typeof update !== "object" || !["thinking_start", "thinking_delta", "thinking_end"].includes(update.type)) return event;
107
+ const contentIndex = thinkingContentIndex(event, update);
108
+ const existing = this.#active.get(contentIndex) || { text: "", template: null };
109
+ const partialText = messageThinkingAt(update.partial, contentIndex);
110
+ const direct = text(update.content) || text(update.thinking);
111
+ const delta = text(update.delta);
112
+ const template = messageThinkingTemplateAt(update.partial, contentIndex) || existing.template;
113
+ let recovered = existing.text;
114
+
115
+ if (update.type === "thinking_delta") {
116
+ const appended = recovered + delta;
117
+ recovered = partialText ? reconcileThinkingSnapshot(appended, partialText) : appended;
118
+ } else {
119
+ recovered = reconcileThinkingSnapshot(recovered, direct || partialText || delta);
120
+ }
121
+ this.#active.set(contentIndex, { text: recovered, template });
122
+
123
+ if (update.type !== "thinking_end" || !recovered) return event;
124
+ const authoritative = direct || partialText || delta;
125
+ if (recovered === authoritative && (!delta || delta === recovered)) return event;
126
+ const patchedUpdate = { ...update, content: recovered };
127
+ if (Object.prototype.hasOwnProperty.call(patchedUpdate, "delta")) patchedUpdate.delta = recovered;
128
+ if (update.partial) patchedUpdate.partial = replaceThinkingAt(update.partial, contentIndex, recovered, template);
129
+ return { ...event, assistantMessageEvent: patchedUpdate };
130
+ }
131
+
132
+ #ingestEnd(event) {
133
+ let message = event.message;
134
+ for (const [contentIndex, record] of this.#active) {
135
+ if (!record.text) continue;
136
+ const authoritative = messageThinkingAt(message, contentIndex);
137
+ const recovered = reconcileThinkingSnapshot(record.text, authoritative);
138
+ if (recovered !== authoritative) message = replaceThinkingAt(message, contentIndex, recovered, record.template);
139
+ const key = recoveryKey(message.timestamp, contentIndex);
140
+ if (key) this.#rememberCompleted(key, {
141
+ timestamp: String(message.timestamp),
142
+ contentIndex,
143
+ text: recovered,
144
+ template: record.template,
145
+ });
146
+ }
147
+ this.#active.clear();
148
+ return message === event.message ? event : { ...event, message };
149
+ }
150
+
151
+ #rememberCompleted(key, record) {
152
+ this.#completed.delete(key);
153
+ this.#completed.set(key, record);
154
+ while (this.#completed.size > COMPLETED_RECOVERY_LIMIT) this.#completed.delete(this.#completed.keys().next().value);
155
+ }
156
+ }
@@ -18,6 +18,7 @@ export const LOCALHOST_ONLY_POST_ROUTES = new Map([
18
18
  ["/api/recovery/plan", "Opening recovery plans is only allowed from localhost"],
19
19
  ["/api/restart", "Restart is only allowed from localhost"],
20
20
  ["/api/update", "Updating Pi from the Web UI is only allowed from localhost"],
21
+ ["/api/component-update", "Component updates are only allowed from localhost"],
21
22
  ["/api/shutdown", "Shutdown is only allowed from localhost"],
22
23
  ["/api/optional-feature-install", "Installing optional Web UI features is only allowed from localhost"],
23
24
  ["/api/skill-file", "Saving skill files is only allowed from localhost"],