@tea-agent/loop-agent 0.54.0-next.1 → 0.54.0

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 (88) hide show
  1. package/CHANGELOG.md +27 -3
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/pi-sdk-executor.js +3 -3
  4. package/dist/infrastructure/console/app-data.js +17 -0
  5. package/dist/shared/package-metadata.js +33 -2
  6. package/dist/shared/pi-model-services.js +93 -0
  7. package/dist/worker/console/chat/pi-runtime.js +63 -15
  8. package/dist/worker/console/chat/routes.js +9 -0
  9. package/dist/worker/console/chat/session-catalog.js +2 -1
  10. package/dist/worker/console/chat/session-store.js +72 -6
  11. package/dist/worker/console/pi-credentials.js +3 -1
  12. package/dist/worker/console/pi-readiness.js +0 -1
  13. package/dist/worker/console/routes.js +32 -19
  14. package/dist/worker/console/server.js +18 -8
  15. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BQGQzeB4.js → abnfDiagram-N423BO3Z-C29lbS0T.js} +1 -1
  16. package/dist/worker/console/static/assets/{arc-VohM6k-u.js → arc--Vi-BzUR.js} +1 -1
  17. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B4aiPVwO.js → architectureDiagram-T3A2C74G-DwdFPJd-.js} +1 -1
  18. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BiOHLIjV.js → blockDiagram-VBNYF7ZC-BFuPq4yu.js} +1 -1
  19. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BeyEgSte.js → c4Diagram-5PPSVZJV-oKn9EfQa.js} +1 -1
  20. package/dist/worker/console/static/assets/channel-o_uspxIc.js +1 -0
  21. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BlHEbEDm.js → chunk-2GRJ4B5K-TwXtrEhU.js} +1 -1
  22. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-ABS6wshI.js → chunk-2Q5K7J3B-Cc3zFHjT.js} +1 -1
  23. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CfxvbyTL.js → chunk-5RXB4S5H-xJfu4YKo.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C5Le1PPI.js → chunk-5VM5RSS4-VBNdtRqb.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DniQmSFb.js → chunk-6Q2QTUOP-DxhJidW7.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-BBXIq87q.js → chunk-GF5L2VYU-P6N3qPX5.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CuZFyj4e.js → chunk-JWPE2WC7-LE21hHhq.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BqltI7Xa.js → chunk-KBJHAD2P-CZmtvzKZ.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-LYNDI4V3.js → chunk-RYQCIY6F-BQrw57-q.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-ehKC3TY6.js → chunk-XXDRQBXY-DSNQHlxO.js} +1 -1
  31. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +1 -0
  32. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +1 -0
  33. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BgLB7_Gs.js → cose-bilkent-JH36ORCC-Ckm2oC4s.js} +1 -1
  34. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-9_ELNaGh.js → cynefinDiagram-MW4NZA55-B7ecDXon.js} +1 -1
  35. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BQ2TK9_p.js → dagre-VZM6K2ZE-Cx_kCtwr.js} +1 -1
  36. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BkM26qk5.js → diagram-7IWD3JNH-DTqfz-9k.js} +1 -1
  37. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CrAzvppm.js → diagram-B4RE2ZJO-BH8nNNYl.js} +1 -1
  38. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-DpGT-pk8.js → diagram-LBJQPF4R-mwUmtiIR.js} +1 -1
  39. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-Diukaccq.js → diagram-Q27KOJAE-B6_cW-cc.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-UB23O5K3-C2B4xR64.js → diagram-UB23O5K3-D1sGiHf5.js} +1 -1
  41. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-ClHD75wJ.js → ebnfDiagram-BXEA7PRR-C07tYieV.js} +1 -1
  42. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BjDCis5U.js → erDiagram-JOGREHBK-eHwocxI1.js} +1 -1
  43. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-D8htdME5.js → flowDiagram-UKHOOZJN-B1B-mb0t.js} +1 -1
  44. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-jnfyRfrb.js → ganttDiagram-PKOTCBZU-B2fpno6f.js} +1 -1
  45. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bjbg88s7.js → gitGraphDiagram-DS77QQ5N-DcM98HR9.js} +1 -1
  46. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DOHcqlQa.js → infoDiagram-6WML65LV-edHmAaaC.js} +1 -1
  47. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BhFciWDX.js → ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js} +1 -1
  48. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-hdKB39Nb.js → journeyDiagram-NVQOT4AX-BqK30536.js} +1 -1
  49. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BdQwpama.js → kanban-definition-27J2QSJJ-DCvcYw-F.js} +1 -1
  50. package/dist/worker/console/static/assets/{linear-Duip0xUK.js → linear-4rMK0UAe.js} +1 -1
  51. package/dist/worker/console/static/assets/main-CBjwyx0a.js +654 -0
  52. package/dist/worker/console/static/assets/main-CGnkpKqw.css +1 -0
  53. package/dist/worker/console/static/assets/{mermaid.core-DRY-520_.js → mermaid.core-CIeuqFlz.js} +4 -4
  54. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CYtRHYwj.js → mindmap-definition-FAOFIHXS-isklXv_u.js} +1 -1
  55. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CK_Sgiks.js → pegDiagram-VL7TDLO6-DufJ3B32.js} +1 -1
  56. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BeOsa7QB.js → pieDiagram-7S7Q4E2Y-e-dscJOX.js} +1 -1
  57. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-D4D9CRa0.js → quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js} +1 -1
  58. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-4GuuCKY5.js → railroadDiagram-AXF67PYL-BkLHnA2m.js} +1 -1
  59. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BkIuekzP.js → requirementDiagram-LRYGKXZP-BzXmvm6l.js} +1 -1
  60. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-uX7nPf0J.js → sankeyDiagram-W5VNT64P-BZuur-BM.js} +1 -1
  61. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CnP16DIz.js → sequenceDiagram-SI44F4Z6-DbZxmtRn.js} +1 -1
  62. package/dist/worker/console/static/assets/{sheet-workbook-BpM2xbR-.js → sheet-workbook-D_6Enbgn.js} +1 -1
  63. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bjm5OhZY.js → sizeCapture-X5ZJPWSS-BHbP5ADt.js} +1 -1
  64. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DXZ2RYku.js → stateDiagram-OKZ733FA-CGNrvQQV.js} +1 -1
  65. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +1 -0
  66. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-B2mW_ryg.js → swimlanes-SLNWSIFB-BWNaMfHj.js} +2 -2
  67. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CylkK52a.js +8 -0
  68. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-eLhaZ_6G.js → timeline-definition-Z64GVDOM-BhI167N4.js} +1 -1
  69. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-tJh-1pOO.js → vennDiagram-T6HMQDX7-BFHqLPNk.js} +1 -1
  70. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-oQI6fAHm.js → wardleyDiagram-T6FBY63Y-D-ThxcCm.js} +1 -1
  71. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Bpg-EQfm.js → xychartDiagram-ELKLHX3M-CeUzoGed.js} +1 -1
  72. package/dist/worker/console/static/index.html +2 -2
  73. package/dist/worker/console/static-src/operator-chat/custom-background-store.js +374 -0
  74. package/dist/worker/console/static-src/operator-chat/custom-background.js +266 -0
  75. package/dist/worker/console/static-src/operator-chat/session-attention.js +34 -0
  76. package/dist/worker/console/static-src/operator-chat/tasks-model.js +24 -0
  77. package/dist/worker/console/workspace-context.js +19 -2
  78. package/dist/worker/observe/static/console-theme.css +22 -3
  79. package/dist/worker/observe/static/console-theme.js +2 -0
  80. package/package.json +9 -10
  81. package/scripts/patch-pi-sdk-windows-hide.mjs +4 -4
  82. package/dist/worker/console/static/assets/channel-vEMQugvb.js +0 -1
  83. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-Dk4zlu_w.js +0 -1
  84. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-Dk4zlu_w.js +0 -1
  85. package/dist/worker/console/static/assets/main-B3dqMT9t.css +0 -1
  86. package/dist/worker/console/static/assets/main-BxLSZyxc.js +0 -654
  87. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BYPZczKU.js +0 -1
  88. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-_6bzI4ly.js +0 -8
@@ -0,0 +1,374 @@
1
+ /**
2
+ * Custom background store — one observable state shared by the painter layer,
3
+ * the settings row preview, and the theme picker.
4
+ *
5
+ * Settings are synchronous (localStorage); a locally uploaded image is a Blob
6
+ * in IndexedDB, so its object URL arrives asynchronously. The store owns that
7
+ * lifecycle: one object URL at a time, revoked when replaced or cleared.
8
+ */
9
+ import { accentColorForSettings, applyCustomBackgroundToDocument, clearCustomBackgroundFromDocument, CUSTOM_BACKGROUND_STORAGE_KEY, deriveAccentActive, DEFAULT_AUTO_ACCENT, readCustomBackgroundSettings, writeCustomBackgroundSettings, MAX_CUSTOM_BACKGROUND_BYTES, matchesCustomBackgroundExtension, sniffCustomBackgroundMime, } from "./custom-background.js";
10
+ const DB_NAME = "loop-console-background";
11
+ const DB_VERSION = 1;
12
+ const STORE_NAME = "assets";
13
+ const IMAGE_KEY = "custom-background";
14
+ const listeners = new Set();
15
+ let objectUrl = null;
16
+ let initialized = false;
17
+ let initializing;
18
+ let state = {
19
+ settings: readCustomBackgroundSettings(typeof window === "undefined" ? null : window.localStorage),
20
+ imageUrl: null,
21
+ status: "loading",
22
+ error: null,
23
+ };
24
+ let accent = {
25
+ main: accentColorForSettings(state.settings),
26
+ active: deriveAccentActive(accentColorForSettings(state.settings)),
27
+ };
28
+ let accentRequest = 0;
29
+ /** Convert an average RGB to a readable accent: keep hue, clamp S/L. */
30
+ function rgbToAccent(r, g, b) {
31
+ const red = r / 255;
32
+ const green = g / 255;
33
+ const blue = b / 255;
34
+ const max = Math.max(red, green, blue);
35
+ const min = Math.min(red, green, blue);
36
+ const lightness = (max + min) / 2;
37
+ const delta = max - min;
38
+ const saturation = delta === 0 ? 0 : delta / (1 - Math.abs(2 * lightness - 1));
39
+ let hue = 0;
40
+ if (delta !== 0) {
41
+ if (max === red)
42
+ hue = ((green - blue) / delta) % 6;
43
+ else if (max === green)
44
+ hue = (blue - red) / delta + 2;
45
+ else
46
+ hue = (red - green) / delta + 4;
47
+ }
48
+ if (hue < 0)
49
+ hue += 6;
50
+ const clampedS = Math.min(0.78, Math.max(0.45, saturation));
51
+ const clampedL = Math.min(0.55, Math.max(0.42, lightness));
52
+ const chroma = (1 - Math.abs(2 * clampedL - 1)) * clampedS;
53
+ const x = chroma * (1 - Math.abs((hue % 2) - 1));
54
+ const m = clampedL - chroma / 2;
55
+ const [r1, g1, b1] = hue < 1 ? [chroma, x, 0] :
56
+ hue < 2 ? [x, chroma, 0] :
57
+ hue < 3 ? [0, chroma, x] :
58
+ hue < 4 ? [0, x, chroma] :
59
+ hue < 5 ? [x, 0, chroma] :
60
+ [chroma, 0, x];
61
+ const toHex = (value) => Math.round(Math.min(1, Math.max(0, value + m)) * 255).toString(16).padStart(2, "0");
62
+ return `#${toHex(r1)}${toHex(g1)}${toHex(b1)}`;
63
+ }
64
+ /** Sample a downscaled image; returns null when CORS/decode makes it unreadable. */
65
+ async function sampleImageAccent(url) {
66
+ if (typeof document === "undefined")
67
+ return null;
68
+ const image = new Image();
69
+ image.crossOrigin = "anonymous";
70
+ image.referrerPolicy = "no-referrer";
71
+ image.src = url;
72
+ try {
73
+ await image.decode();
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ const canvas = document.createElement("canvas");
79
+ const size = 32;
80
+ canvas.width = size;
81
+ canvas.height = size;
82
+ const context = canvas.getContext("2d", { willReadFrequently: true });
83
+ if (!context)
84
+ return null;
85
+ context.drawImage(image, 0, 0, size, size);
86
+ let red = 0;
87
+ let green = 0;
88
+ let blue = 0;
89
+ let weight = 0;
90
+ try {
91
+ const pixels = context.getImageData(0, 0, size, size).data;
92
+ for (let index = 0; index < pixels.length; index += 4) {
93
+ const r = pixels[index];
94
+ const g = pixels[index + 1];
95
+ const b = pixels[index + 2];
96
+ const alpha = pixels[index + 3];
97
+ if (alpha < 128)
98
+ continue;
99
+ const max = Math.max(r, g, b);
100
+ const min = Math.min(r, g, b);
101
+ const saturation = max === 0 ? 0 : (max - min) / max;
102
+ if (saturation < 0.2 || max < 40)
103
+ continue;
104
+ const w = saturation * (alpha / 255);
105
+ red += r * w;
106
+ green += g * w;
107
+ blue += b * w;
108
+ weight += w;
109
+ }
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ if (weight === 0)
115
+ return null;
116
+ return rgbToAccent(red / weight, green / weight, blue / weight);
117
+ }
118
+ /** Recompute the accent for the current settings/image; later requests win. */
119
+ async function refreshAccent(settings) {
120
+ const request = ++accentRequest;
121
+ if (settings.accent !== "auto") {
122
+ const main = accentColorForSettings(settings);
123
+ accent = { main, active: deriveAccentActive(main) };
124
+ apply(settings);
125
+ return;
126
+ }
127
+ accent = { main: DEFAULT_AUTO_ACCENT, active: deriveAccentActive(DEFAULT_AUTO_ACCENT) };
128
+ apply(settings);
129
+ const imageUrl = effectiveImageUrl(settings);
130
+ if (!imageUrl)
131
+ return;
132
+ const sampled = await sampleImageAccent(imageUrl);
133
+ if (request !== accentRequest || !sampled)
134
+ return;
135
+ accent = { main: sampled, active: deriveAccentActive(sampled) };
136
+ apply(settings);
137
+ }
138
+ function notify() {
139
+ for (const listener of listeners)
140
+ listener();
141
+ }
142
+ export function getCustomBackgroundState() {
143
+ return state;
144
+ }
145
+ export function subscribeCustomBackground(listener) {
146
+ listeners.add(listener);
147
+ return () => {
148
+ listeners.delete(listener);
149
+ };
150
+ }
151
+ function openDatabase() {
152
+ return new Promise((resolve, reject) => {
153
+ if (typeof indexedDB === "undefined") {
154
+ reject(new Error("IndexedDB unavailable"));
155
+ return;
156
+ }
157
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
158
+ request.onupgradeneeded = () => {
159
+ const db = request.result;
160
+ if (!db.objectStoreNames.contains(STORE_NAME))
161
+ db.createObjectStore(STORE_NAME);
162
+ };
163
+ request.onsuccess = () => resolve(request.result);
164
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed"));
165
+ });
166
+ }
167
+ async function readStoredImage() {
168
+ const db = await openDatabase();
169
+ try {
170
+ return await new Promise((resolve, reject) => {
171
+ const transaction = db.transaction(STORE_NAME, "readonly");
172
+ const request = transaction.objectStore(STORE_NAME).get(IMAGE_KEY);
173
+ request.onsuccess = () => resolve(request.result instanceof Blob ? request.result : undefined);
174
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB read failed"));
175
+ });
176
+ }
177
+ finally {
178
+ db.close();
179
+ }
180
+ }
181
+ async function writeStoredImage(blob) {
182
+ const db = await openDatabase();
183
+ try {
184
+ await new Promise((resolve, reject) => {
185
+ const transaction = db.transaction(STORE_NAME, "readwrite");
186
+ transaction.objectStore(STORE_NAME).put(blob, IMAGE_KEY);
187
+ transaction.oncomplete = () => resolve();
188
+ transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB write failed"));
189
+ });
190
+ }
191
+ finally {
192
+ db.close();
193
+ }
194
+ }
195
+ async function deleteStoredImage() {
196
+ try {
197
+ const db = await openDatabase();
198
+ try {
199
+ await new Promise((resolve, reject) => {
200
+ const transaction = db.transaction(STORE_NAME, "readwrite");
201
+ transaction.objectStore(STORE_NAME).delete(IMAGE_KEY);
202
+ transaction.oncomplete = () => resolve();
203
+ transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB delete failed"));
204
+ });
205
+ }
206
+ finally {
207
+ db.close();
208
+ }
209
+ }
210
+ catch {
211
+ /* Clearing a preference must succeed even when the store is unavailable. */
212
+ }
213
+ }
214
+ function revokeObjectUrl() {
215
+ if (objectUrl === null)
216
+ return;
217
+ try {
218
+ URL.revokeObjectURL(objectUrl);
219
+ }
220
+ catch {
221
+ /* best effort */
222
+ }
223
+ objectUrl = null;
224
+ }
225
+ function effectiveImageUrl(settings) {
226
+ if (settings.imageKind === "url")
227
+ return settings.url || null;
228
+ if (settings.imageKind === "upload")
229
+ return objectUrl;
230
+ return null;
231
+ }
232
+ function apply(settings) {
233
+ if (typeof document === "undefined")
234
+ return;
235
+ applyCustomBackgroundToDocument(document.documentElement, settings, Boolean(effectiveImageUrl(settings)), accent);
236
+ }
237
+ function commit(next) {
238
+ state = { ...state, settings: next, imageUrl: effectiveImageUrl(next), status: "ready", error: null };
239
+ writeCustomBackgroundSettings(typeof window === "undefined" ? null : window.localStorage, next);
240
+ void refreshAccent(next);
241
+ notify();
242
+ }
243
+ /**
244
+ * Load the persisted image and paint the initial state. Safe to call more than
245
+ * once; the first call's promise is shared so StrictMode double-mounting does
246
+ * not read/revoke the blob twice.
247
+ */
248
+ /** Mirror a settings write made by another tab; IndexedDB is already shared. */
249
+ async function syncFromExternalStorage() {
250
+ if (typeof window === "undefined")
251
+ return;
252
+ const settings = readCustomBackgroundSettings(window.localStorage);
253
+ const stored = settings.imageKind === "upload" ? await readStoredImage().catch(() => null) : null;
254
+ revokeObjectUrl();
255
+ if (stored)
256
+ objectUrl = URL.createObjectURL(stored);
257
+ state = {
258
+ settings,
259
+ imageUrl: effectiveImageUrl(settings),
260
+ status: "ready",
261
+ error: null,
262
+ };
263
+ void refreshAccent(settings);
264
+ notify();
265
+ }
266
+ let storageSyncInstalled = false;
267
+ function installStorageSync() {
268
+ if (typeof window === "undefined" || storageSyncInstalled)
269
+ return;
270
+ window.addEventListener("storage", (event) => {
271
+ if (event.key !== CUSTOM_BACKGROUND_STORAGE_KEY)
272
+ return;
273
+ void syncFromExternalStorage();
274
+ });
275
+ storageSyncInstalled = true;
276
+ }
277
+ export function initializeCustomBackground() {
278
+ if (initialized)
279
+ return initializing ?? Promise.resolve();
280
+ installStorageSync();
281
+ initializing = (async () => {
282
+ let settings = state.settings;
283
+ if (settings.imageKind === "upload") {
284
+ try {
285
+ const blob = await readStoredImage();
286
+ if (blob) {
287
+ revokeObjectUrl();
288
+ objectUrl = URL.createObjectURL(blob);
289
+ }
290
+ else {
291
+ // The setting outlived its blob (storage cleared): degrade to no image.
292
+ settings = { ...settings, imageKind: "none", url: "" };
293
+ }
294
+ }
295
+ catch {
296
+ settings = { ...settings, imageKind: "none", url: "" };
297
+ }
298
+ }
299
+ initialized = true;
300
+ state = {
301
+ settings,
302
+ imageUrl: effectiveImageUrl(settings),
303
+ status: "ready",
304
+ error: null,
305
+ };
306
+ void refreshAccent(settings);
307
+ notify();
308
+ })();
309
+ return initializing;
310
+ }
311
+ /** Apply a partial settings change (sliders, panel opacity, wallpaper blur). */
312
+ export function patchCustomBackgroundSettings(patch) {
313
+ commit({ ...state.settings, ...patch });
314
+ }
315
+ /**
316
+ * Slider hot path: repaint the live backdrop and preview from a draft without
317
+ * touching localStorage. The row calls `commitCustomBackgroundSettings()` once
318
+ * on release so one gesture is one write.
319
+ */
320
+ export function previewCustomBackgroundSettings(patch) {
321
+ const next = { ...state.settings, ...patch };
322
+ state = { ...state, settings: next, imageUrl: effectiveImageUrl(next), status: "ready" };
323
+ apply(next);
324
+ notify();
325
+ }
326
+ /** Persist the current draft (called once per slider gesture, on release). */
327
+ export function commitCustomBackgroundSettings() {
328
+ writeCustomBackgroundSettings(typeof window === "undefined" ? null : window.localStorage, state.settings);
329
+ }
330
+ /** Use a remote image URL; the stored upload is removed so the blobs do not pile up. */
331
+ export async function setCustomBackgroundUrl(url) {
332
+ await deleteStoredImage();
333
+ revokeObjectUrl();
334
+ commit({ ...state.settings, imageKind: "url", url: url.trim() });
335
+ }
336
+ /** Validate + store a local image and make it the active wallpaper. */
337
+ export async function setCustomBackgroundImage(file) {
338
+ if (file.size > MAX_CUSTOM_BACKGROUND_BYTES) {
339
+ state = { ...state, error: "图片超过 20MB 上限" };
340
+ notify();
341
+ throw new Error("图片超过 20MB 上限");
342
+ }
343
+ const bytes = new Uint8Array(await file.arrayBuffer());
344
+ const mime = sniffCustomBackgroundMime(bytes);
345
+ if (!mime) {
346
+ state = { ...state, error: "仅支持 JPG / PNG / WebP / GIF 图片" };
347
+ notify();
348
+ throw new Error("仅支持 JPG / PNG / WebP / GIF 图片");
349
+ }
350
+ if (!matchesCustomBackgroundExtension(file.name, mime)) {
351
+ state = { ...state, error: "文件扩展名与图片内容不一致" };
352
+ notify();
353
+ throw new Error("文件扩展名与图片内容不一致");
354
+ }
355
+ const blob = new Blob([bytes], { type: mime });
356
+ await writeStoredImage(blob);
357
+ revokeObjectUrl();
358
+ objectUrl = URL.createObjectURL(blob);
359
+ commit({ ...state.settings, imageKind: "upload", url: "" });
360
+ }
361
+ /** Remove the wallpaper and any stored upload; the theme returns to its bare palette. */
362
+ export async function clearCustomBackground() {
363
+ await deleteStoredImage();
364
+ revokeObjectUrl();
365
+ commit({ ...state.settings, imageKind: "none", url: "" });
366
+ if (typeof document !== "undefined")
367
+ clearCustomBackgroundFromDocument(document.documentElement);
368
+ state = { ...state, imageUrl: null };
369
+ notify();
370
+ }
371
+ /** Re-apply the current state (theme switch back to `custom`). */
372
+ export function repaintCustomBackground() {
373
+ apply(state.settings);
374
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Custom background theme — shared model, validation, and persistence keys.
3
+ *
4
+ * The feature is a client-local appearance preference (like the theme id and
5
+ * chat font sizes): the settings live in localStorage and the uploaded image
6
+ * lives in IndexedDB as a Blob. Keeping the image out of localStorage avoids
7
+ * its ~5 MB quota; keeping the whole feature client-side avoids opening an
8
+ * unauthenticated static-asset route on the Console origin.
9
+ */
10
+ export const CUSTOM_BACKGROUND_STORAGE_KEY = "loop-console.custom-background.v1";
11
+ /** Upload limits and accepted formats (GIF included; SVG deliberately not). */
12
+ export const MAX_CUSTOM_BACKGROUND_BYTES = 20 * 1024 * 1024;
13
+ export const CUSTOM_BACKGROUND_ACCEPT = "image/jpeg,image/png,image/webp,image/gif";
14
+ export const ACCENT_PRESETS = {
15
+ orange: "#f54e00",
16
+ blue: "#4f6bed",
17
+ violet: "#7c5cff",
18
+ teal: "#0f9d8f",
19
+ rose: "#d64570",
20
+ slate: "#6b7280",
21
+ };
22
+ /** Fallback when an image cannot be sampled (remote CORS, decode failure). */
23
+ export const DEFAULT_AUTO_ACCENT = "#4f6bed";
24
+ export const DEFAULT_CUSTOM_BACKGROUND = {
25
+ imageKind: "none",
26
+ url: "",
27
+ opacity: 100,
28
+ scrim: 25,
29
+ panelOpacity: 15,
30
+ blur: 16,
31
+ wallpaperBlur: 0,
32
+ fit: "cover",
33
+ scheme: "light",
34
+ offsetX: 0.5,
35
+ offsetY: 0.5,
36
+ accent: "auto",
37
+ };
38
+ function clamp(value, min, max, fallback) {
39
+ const parsed = typeof value === "number" ? value : Number(value);
40
+ if (!Number.isFinite(parsed))
41
+ return fallback;
42
+ return Math.min(max, Math.max(min, Math.round(parsed)));
43
+ }
44
+ /** Offset clamp keeps 3-decimal precision (pointer deltas produce float dust). */
45
+ function clampOffset(value) {
46
+ const parsed = typeof value === "number" ? value : Number(value);
47
+ if (!Number.isFinite(parsed))
48
+ return 0.5;
49
+ return Math.round(Math.min(1, Math.max(0, parsed)) * 1000) / 1000;
50
+ }
51
+ /** Parse one persisted/unknown value into a complete, bounded settings object. */
52
+ export function parseCustomBackgroundSettings(value) {
53
+ const record = value && typeof value === "object" && !Array.isArray(value)
54
+ ? value
55
+ : {};
56
+ const imageKind = record.imageKind === "upload" || record.imageKind === "url" ? record.imageKind : "none";
57
+ const storedUrl = typeof record.url === "string" ? record.url.trim().slice(0, 2048) : "";
58
+ const urlIsValid = isValidBackgroundImageUrl(storedUrl);
59
+ return {
60
+ // A URL source without a valid URL degrades to "none" rather than showing a broken theme.
61
+ imageKind: imageKind === "url" && !urlIsValid ? "none" : imageKind,
62
+ url: imageKind === "url" && !urlIsValid ? "" : storedUrl,
63
+ opacity: clamp(record.opacity, 0, 100, DEFAULT_CUSTOM_BACKGROUND.opacity),
64
+ scrim: clamp(record.scrim, 0, 100, DEFAULT_CUSTOM_BACKGROUND.scrim),
65
+ panelOpacity: clamp(record.panelOpacity, 0, 100, DEFAULT_CUSTOM_BACKGROUND.panelOpacity),
66
+ blur: clamp(record.blur, 0, 40, DEFAULT_CUSTOM_BACKGROUND.blur),
67
+ wallpaperBlur: clamp(record.wallpaperBlur, 0, 60, DEFAULT_CUSTOM_BACKGROUND.wallpaperBlur),
68
+ fit: record.fit === "contain" ? "contain" : "cover",
69
+ scheme: record.scheme === "dark" ? "dark" : "light",
70
+ offsetX: clampOffset(record.offsetX),
71
+ offsetY: clampOffset(record.offsetY),
72
+ accent: isCustomBackgroundAccent(record.accent) ? record.accent : "auto",
73
+ };
74
+ }
75
+ export function readCustomBackgroundSettings(storage) {
76
+ if (!storage)
77
+ return { ...DEFAULT_CUSTOM_BACKGROUND };
78
+ try {
79
+ const raw = storage.getItem(CUSTOM_BACKGROUND_STORAGE_KEY);
80
+ if (!raw)
81
+ return { ...DEFAULT_CUSTOM_BACKGROUND };
82
+ return parseCustomBackgroundSettings(JSON.parse(raw));
83
+ }
84
+ catch {
85
+ return { ...DEFAULT_CUSTOM_BACKGROUND };
86
+ }
87
+ }
88
+ export function writeCustomBackgroundSettings(storage, settings) {
89
+ try {
90
+ storage?.setItem(CUSTOM_BACKGROUND_STORAGE_KEY, JSON.stringify(settings));
91
+ }
92
+ catch {
93
+ /* A full/blocked store must not break the picker. */
94
+ }
95
+ }
96
+ /** Only http(s) image URLs are accepted; `data:`/`blob:`/`javascript:` are not. */
97
+ export function isValidBackgroundImageUrl(value) {
98
+ const trimmed = value.trim();
99
+ if (!trimmed || trimmed.length > 2048)
100
+ return false;
101
+ try {
102
+ const url = new URL(trimmed);
103
+ return (url.protocol === "http:" || url.protocol === "https:") && Boolean(url.hostname);
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ export function isCustomBackgroundAccent(value) {
110
+ return (value === "auto" ||
111
+ value === "orange" ||
112
+ value === "blue" ||
113
+ value === "violet" ||
114
+ value === "teal" ||
115
+ value === "rose" ||
116
+ value === "slate");
117
+ }
118
+ /** Resolve a configured accent to its hex value (auto falls back until sampled). */
119
+ export function accentColorForSettings(settings) {
120
+ return settings.accent === "auto"
121
+ ? DEFAULT_AUTO_ACCENT
122
+ : ACCENT_PRESETS[settings.accent];
123
+ }
124
+ /** Darker companion for hover/active states (86% of each RGB channel). */
125
+ export function deriveAccentActive(hex) {
126
+ const value = Number.parseInt(hex.replace(/^#/, ""), 16);
127
+ if (!Number.isFinite(value))
128
+ return hex;
129
+ const channels = [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff];
130
+ return `#${channels
131
+ .map((channel) => Math.round(channel * 0.86).toString(16).padStart(2, "0"))
132
+ .join("")}`;
133
+ }
134
+ function ascii(bytes, start, length) {
135
+ return String.fromCharCode(...bytes.subarray(start, start + length));
136
+ }
137
+ /**
138
+ * Detect the image type from its first bytes.
139
+ *
140
+ * The browser-reported `File.type` is user-controllable, so the stored blob's
141
+ * real format has to be proven. Returns undefined for anything outside the
142
+ * four accepted formats (including SVG).
143
+ */
144
+ export function sniffCustomBackgroundMime(bytes) {
145
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
146
+ return "image/jpeg";
147
+ }
148
+ if (bytes.length >= 8 &&
149
+ bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
150
+ bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
151
+ return "image/png";
152
+ }
153
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") {
154
+ return "image/webp";
155
+ }
156
+ if (bytes.length >= 6) {
157
+ const head = ascii(bytes, 0, 6);
158
+ if (head === "GIF87a" || head === "GIF89a")
159
+ return "image/gif";
160
+ }
161
+ return undefined;
162
+ }
163
+ /** Lowercase extension for a proven MIME (the IndexedDB value stores the MIME anyway). */
164
+ export function extensionForCustomBackgroundMime(mime) {
165
+ return mime === "image/jpeg" ? "jpg" : mime.slice("image/".length);
166
+ }
167
+ /** Filename extensions accepted for each proven MIME (reference triple-check). */
168
+ const MIME_EXTENSIONS = {
169
+ "image/jpeg": ["jpg", "jpeg"],
170
+ "image/png": ["png"],
171
+ "image/webp": ["webp"],
172
+ "image/gif": ["gif"],
173
+ };
174
+ /**
175
+ * The declared filename extension must agree with the sniffed format, so a
176
+ * `.png` whose bytes are JPEG is rejected instead of silently stored under a
177
+ * misleading name.
178
+ */
179
+ export function matchesCustomBackgroundExtension(fileName, mime) {
180
+ const lower = fileName.toLowerCase();
181
+ const dot = lower.lastIndexOf(".");
182
+ if (dot < 0 || dot === lower.length - 1)
183
+ return false;
184
+ return MIME_EXTENSIONS[mime].includes(lower.slice(dot + 1));
185
+ }
186
+ const CSS_VARIABLES = [
187
+ "--oc-bg-opacity",
188
+ "--oc-bg-scrim",
189
+ "--oc-bg-panel",
190
+ "--oc-bg-blur",
191
+ "--oc-bg-wallpaper-blur",
192
+ "--oc-bg-wallpaper-scale",
193
+ "--oc-bg-fit",
194
+ "--oc-bg-offset-x",
195
+ "--oc-bg-offset-y",
196
+ "--oc-bg-glass-alpha",
197
+ "--oc-bg-glass-saturate",
198
+ "--oc-bg-glass-brightness",
199
+ "--oc-bg-glass-sheen",
200
+ "--oc-bg-glass-sheen-mid",
201
+ "--oc-bg-accent",
202
+ "--oc-bg-accent-active",
203
+ ];
204
+ /**
205
+ * Project settings onto the document as CSS variables + the two gate
206
+ * attributes the stylesheet keys on:
207
+ *
208
+ * - `data-oc-bg="on"`: an image is rendered (frame columns go transparent).
209
+ * - `data-oc-bg-glass="on"`: the panels must be frosted (image present AND
210
+ * panelOpacity < 100).
211
+ */
212
+ export function applyCustomBackgroundToDocument(root, settings, hasImage, accent) {
213
+ root.style.setProperty("--oc-bg-opacity", String(settings.opacity / 100));
214
+ root.style.setProperty("--oc-bg-scrim", String(settings.scrim / 100));
215
+ root.style.setProperty("--oc-bg-panel", String(settings.panelOpacity / 100));
216
+ root.style.setProperty("--oc-bg-blur", `${settings.blur}px`);
217
+ root.style.setProperty("--oc-bg-wallpaper-blur", `${settings.wallpaperBlur}px`);
218
+ root.style.setProperty("--oc-bg-wallpaper-scale", (1 + settings.wallpaperBlur * 0.006).toFixed(4));
219
+ root.style.setProperty("--oc-bg-fit", settings.fit);
220
+ root.style.setProperty("--oc-bg-offset-x", String(settings.offsetX));
221
+ root.style.setProperty("--oc-bg-offset-y", String(settings.offsetY));
222
+ /*
223
+ * Glass fill curve mirrors the reference plugin: a floor alpha (never fully
224
+ * invisible) plus 85% of the slider, scaled by 0.8 for the light scheme.
225
+ * At the default 80% panel opacity this is ~58% white — visibly glass, still
226
+ * readable — instead of a near-opaque card.
227
+ */
228
+ const glassAlpha = (0.05 + (settings.panelOpacity / 100) * 0.85) * 0.8;
229
+ root.style.setProperty("--oc-bg-glass-alpha", glassAlpha.toFixed(3));
230
+ const saturate = settings.blur <= 0 ? 1 : Math.min(1.6, 1.1 + settings.blur * 0.02);
231
+ root.style.setProperty("--oc-bg-glass-saturate", String(Math.round(saturate * 1000) / 1000));
232
+ const dark = settings.scheme === "dark";
233
+ root.style.setProperty("--oc-bg-glass-brightness", dark ? "1.04" : "0.98");
234
+ root.style.setProperty("--oc-bg-glass-sheen", dark ? "0.16" : "0.07");
235
+ root.style.setProperty("--oc-bg-glass-sheen-mid", dark ? "0.05" : "0.02");
236
+ root.dataset.ocScheme = settings.scheme;
237
+ const accentMain = accent?.main ?? accentColorForSettings(settings);
238
+ root.style.setProperty("--oc-bg-accent", accentMain);
239
+ root.style.setProperty("--oc-bg-accent-active", accent?.active ?? deriveAccentActive(accentMain));
240
+ // The theme-color meta is a value, not CSS: repaint it when the custom
241
+ // theme's base scheme flips so an installed titlebar matches the palette.
242
+ if (root.dataset.consoleTheme === "custom") {
243
+ try {
244
+ document.querySelector('meta[name="theme-color"]')
245
+ ?.setAttribute("content", dark ? "#1c222a" : "#f4f2ee");
246
+ }
247
+ catch {
248
+ /* cosmetic */
249
+ }
250
+ }
251
+ if (hasImage)
252
+ root.dataset.ocBg = "on";
253
+ else
254
+ delete root.dataset.ocBg;
255
+ if (hasImage && settings.panelOpacity < 100)
256
+ root.dataset.ocBgGlass = "on";
257
+ else
258
+ delete root.dataset.ocBgGlass;
259
+ }
260
+ /** Restore the document to its pre-background state (theme switch / clear). */
261
+ export function clearCustomBackgroundFromDocument(root) {
262
+ for (const name of CSS_VARIABLES)
263
+ root.style.removeProperty(name);
264
+ delete root.dataset.ocBg;
265
+ delete root.dataset.ocBgGlass;
266
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Session attention transitions (DSH `completed` parity).
3
+ *
4
+ * A row earns the green "done" reminder only when a live Turn **finished while
5
+ * the operator was looking at another session**. Deriving it from the list
6
+ * projection keeps it honest: the server does not model unread state, and a
7
+ * timestamp comparison would flag renames or automation writes as "completed".
8
+ */
9
+ /**
10
+ * Session ids whose Turn went from running/stopping to idle in this update,
11
+ * excluding the session that is currently open.
12
+ */
13
+ export function collectCompletedTransitions(previousPhases, sessions, activeSessionId) {
14
+ const completed = [];
15
+ for (const session of sessions) {
16
+ const before = previousPhases.get(session.sessionId);
17
+ const wasRunning = before === "running" || before === "stopping";
18
+ if (!wasRunning)
19
+ continue;
20
+ if (session.turnPhase !== "idle")
21
+ continue;
22
+ if (session.sessionId === activeSessionId)
23
+ continue;
24
+ completed.push(session.sessionId);
25
+ }
26
+ return completed;
27
+ }
28
+ /** Snapshot the current phases for the next comparison. */
29
+ export function snapshotSessionPhases(sessions) {
30
+ const phases = new Map();
31
+ for (const session of sessions)
32
+ phases.set(session.sessionId, session.turnPhase);
33
+ return phases;
34
+ }