@adea-ai/app-framework 0.25.1 → 0.27.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 (128) hide show
  1. package/README.md +163 -21
  2. package/dist/app/application.d.ts +11 -4
  3. package/dist/app/application.js +24 -4
  4. package/dist/app/create-application.d.ts +9 -0
  5. package/dist/app/create-application.js +214 -143
  6. package/dist/app/private-group.d.ts +14 -0
  7. package/dist/app/private-group.js +39 -0
  8. package/dist/app/service-registry.d.ts +8 -4
  9. package/dist/app/service-registry.js +43 -6
  10. package/dist/appearance/custom-theme-import.d.ts +5 -7
  11. package/dist/appearance/custom-theme-import.js +66 -18
  12. package/dist/appearance/custom-theme-library.d.ts +51 -3
  13. package/dist/appearance/custom-theme-library.js +262 -33
  14. package/dist/appearance/editor.d.ts +3 -1
  15. package/dist/appearance/editor.js +37 -2
  16. package/dist/appearance/theme-file-importer.d.ts +7 -3
  17. package/dist/appearance/theme-file-importer.js +27 -7
  18. package/dist/appearance/theme-library-action-fence.d.ts +11 -0
  19. package/dist/appearance/theme-library-action-fence.js +29 -0
  20. package/dist/cli/framework-update-cli.js +16 -3
  21. package/dist/cli/release-step-cli.js +6 -1
  22. package/dist/desktop/application-command-client.d.ts +11 -1
  23. package/dist/desktop/application-command-client.js +66 -3
  24. package/dist/desktop/channel-handshake.d.ts +2 -1
  25. package/dist/desktop/channel-handshake.js +21 -5
  26. package/dist/desktop/client-asset-stream.d.ts +10 -0
  27. package/dist/desktop/client-asset-stream.js +97 -0
  28. package/dist/desktop/client-assets.d.ts +3 -1
  29. package/dist/desktop/client-assets.js +41 -6
  30. package/dist/desktop/desktop-client.d.ts +15 -1
  31. package/dist/desktop/desktop-client.js +235 -109
  32. package/dist/desktop/desktop-gateway.d.ts +2 -0
  33. package/dist/desktop/desktop-gateway.js +134 -22
  34. package/dist/desktop/desktop-host-websocket.d.ts +10 -0
  35. package/dist/desktop/desktop-host-websocket.js +28 -0
  36. package/dist/desktop/desktop-host.d.ts +9 -0
  37. package/dist/desktop/desktop-host.js +70 -61
  38. package/dist/desktop/desktop-port-file.d.ts +2 -0
  39. package/dist/desktop/desktop-port-file.js +23 -0
  40. package/dist/desktop/desktop-stream.d.ts +5 -0
  41. package/dist/desktop/desktop-stream.js +83 -15
  42. package/dist/desktop/gateway-limits.d.ts +2 -0
  43. package/dist/desktop/gateway-limits.js +6 -0
  44. package/dist/desktop/open-url-channel.d.ts +5 -3
  45. package/dist/desktop/open-url-channel.js +18 -5
  46. package/dist/desktop/typed-array-intrinsics.d.ts +6 -0
  47. package/dist/desktop/typed-array-intrinsics.js +19 -0
  48. package/dist/framework-source.json +1 -1
  49. package/dist/installer/installed-payload.js +1 -1
  50. package/dist/installer/installer-ci-bootstrap.js +2 -1
  51. package/dist/installer/installer-command.d.ts +13 -0
  52. package/dist/installer/installer-command.js +47 -0
  53. package/dist/installer/installer-extraction.js +27 -61
  54. package/dist/installer/installer-identity.d.ts +22 -3
  55. package/dist/installer/installer-identity.js +63 -72
  56. package/dist/installer/installer-image-mount.d.ts +48 -0
  57. package/dist/installer/installer-image-mount.js +347 -0
  58. package/dist/installer/installer-layout.d.ts +2 -0
  59. package/dist/installer/installer-layout.js +6 -2
  60. package/dist/installer/installer-process-cleanup.js +1 -1
  61. package/dist/installer/installer-renderer-evidence.js +6 -2
  62. package/dist/installer/upgrade-asset-download.js +30 -8
  63. package/dist/native/app-bundle.d.ts +2 -2
  64. package/dist/native/app-bundle.js +5 -4
  65. package/dist/native/cef-helper-download.d.ts +1 -0
  66. package/dist/native/cef-helper-download.js +35 -0
  67. package/dist/native/cef-helper.js +146 -61
  68. package/dist/native/exclusive-rename.d.ts +2 -0
  69. package/dist/native/exclusive-rename.js +52 -0
  70. package/dist/native/native-secret-store.js +5 -4
  71. package/dist/native/partitioned-window.d.ts +5 -2
  72. package/dist/native/partitioned-window.js +69 -9
  73. package/dist/native/sidecar-services.js +2 -2
  74. package/dist/native/sidecar.js +68 -25
  75. package/dist/native/window-bootstrap.js +2 -2
  76. package/dist/release/feed-state.js +2 -1
  77. package/dist/release/framework-update-lock.d.ts +2 -0
  78. package/dist/release/framework-update-lock.js +42 -0
  79. package/dist/release/framework-update.d.ts +6 -2
  80. package/dist/release/framework-update.js +165 -40
  81. package/dist/release/local-release.js +68 -39
  82. package/dist/release/release-config.js +1 -1
  83. package/dist/release/release-steps.d.ts +5 -0
  84. package/dist/release/release-steps.js +2 -1
  85. package/dist/shared/discard-stream.d.ts +4 -0
  86. package/dist/shared/discard-stream.js +9 -0
  87. package/dist/shell/app-shell.js +59 -7
  88. package/dist/shell/app-utilities.js +2 -2
  89. package/dist/shell/application-menu.d.ts +13 -0
  90. package/dist/shell/application-menu.js +21 -8
  91. package/dist/update-helper.bundle.js +40 -4
  92. package/dist/updates/channel-update-manager.d.ts +2 -0
  93. package/dist/updates/channel-update-manager.js +15 -3
  94. package/dist/updates/desktop-updater.d.ts +2 -0
  95. package/dist/updates/desktop-updater.js +36 -7
  96. package/dist/updates/linux-process-state.d.ts +2 -0
  97. package/dist/updates/linux-process-state.js +13 -0
  98. package/dist/updates/release-location.js +5 -4
  99. package/dist/updates/update-adapter.js +5 -0
  100. package/dist/updates/update-arm.d.ts +2 -0
  101. package/dist/updates/update-arm.js +58 -7
  102. package/dist/updates/update-discovery.js +2 -1
  103. package/dist/updates/update-download-cleanup.d.ts +7 -0
  104. package/dist/updates/update-download-cleanup.js +21 -0
  105. package/dist/updates/update-download.js +41 -20
  106. package/dist/updates/update-exclusive-rename.d.ts +3 -2
  107. package/dist/updates/update-exclusive-rename.js +3 -50
  108. package/dist/updates/update-extraction.js +1 -1
  109. package/dist/updates/update-manager.d.ts +17 -1
  110. package/dist/updates/update-manager.js +27 -8
  111. package/dist/updates/update-process-fence.js +18 -3
  112. package/dist/views/appearance-surface.js +51 -15
  113. package/package.json +8 -3
  114. package/src/app/application.tsx +49 -7
  115. package/src/appearance/custom-theme-import.ts +67 -7
  116. package/src/appearance/custom-theme-library.ts +391 -33
  117. package/src/appearance/editor.ts +49 -10
  118. package/src/appearance/theme-file-importer.ts +43 -12
  119. package/src/appearance/theme-library-action-fence.ts +28 -0
  120. package/src/desktop/client-asset-stream.ts +118 -0
  121. package/src/desktop/client-assets.ts +55 -5
  122. package/src/shell/app-shell.tsx +71 -8
  123. package/src/shell/app-utilities.tsx +2 -2
  124. package/src/updates/update-adapter.ts +5 -0
  125. package/src/views/appearance-surface.tsx +61 -29
  126. package/templates/application/README.md +5 -1
  127. package/templates/application/scripts/app-version.ts +7 -3
  128. package/templates/application/src/bun/index.ts +2 -0
@@ -1,4 +1,4 @@
1
- import { flatVariantTokens, setCustomThemes, validateThemeRegistry } from "./custom-theme-library.js";
1
+ import { flatVariantTokens, mutateCustomThemeLibrary, validateThemeRegistry } from "./custom-theme-library.js";
2
2
  import { colorToHex, contrastRatio, ensureContrast, parseColor } from "@adea-ai/ui/lib/accent-roles";
3
3
  import { defaultThemeRecord, editorRolesHex, oklchToHex, parseOklchColor, shadcnDestructiveProjection, shadcnVariables, syntaxRolesHex, toXtermTheme } from "@adea-ai/ui/lib/theme-projection";
4
4
  // src/appearance/custom-theme-import.ts
@@ -58,9 +58,33 @@ var SYNTAX_SOURCES = {
58
58
  diffHunk: "brightBlack",
59
59
  searchMatch: "yellow"
60
60
  };
61
+ var fallbackThemeIdSequence = 0;
61
62
  function slug(value) {
62
63
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32) || "theme";
63
64
  }
65
+ function uniqueThemeId(name, existing) {
66
+ const base = `custom-${slug(name)}-${Date.now().toString(36)}`;
67
+ const usedIds = new Set(existing.map((theme) => theme.id));
68
+ let suffix;
69
+ try {
70
+ const crypto = globalThis.crypto;
71
+ if (crypto?.getRandomValues) {
72
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
73
+ suffix = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
74
+ }
75
+ } catch {}
76
+ if (suffix === void 0) {
77
+ fallbackThemeIdSequence += 1;
78
+ suffix = `${Math.random().toString(36).slice(2)}-${fallbackThemeIdSequence.toString(36)}`;
79
+ }
80
+ let id = `${base}-${suffix}`;
81
+ let collision = 0;
82
+ while (usedIds.has(id)) {
83
+ collision += 1;
84
+ id = `${base}-${suffix}-${collision.toString(36)}`;
85
+ }
86
+ return id;
87
+ }
64
88
  function normalizeHex(value) {
65
89
  const parsed = parseColor(value);
66
90
  return parsed ? `#${[
@@ -177,7 +201,7 @@ function projectCanonical(theme) {
177
201
  * JSON: everything else normalizes, fills from the same-appearance default,
178
202
  * and reports what it had to adjust.
179
203
  */
180
- function importCustomTheme(text, storage, existing) {
204
+ function prepareCustomTheme(text, existing) {
181
205
  let source;
182
206
  try {
183
207
  source = JSON.parse(text);
@@ -209,6 +233,7 @@ function importCustomTheme(text, storage, existing) {
209
233
  for (const key of filled) colors[key] = base.colors[key];
210
234
  notes.push("Missing roles were filled from the default theme.");
211
235
  }
236
+ colors.foreground = repairToFloor(colors.foreground, colors.background, notes, "foreground");
212
237
  colors.text = repairToFloor(colors.text, colors.background, notes, "text");
213
238
  colors.textMuted = repairToFloor(colors.textMuted, colors.background, notes, "muted text");
214
239
  colors.textSubtle = repairToFloor(colors.textSubtle, colors.background, notes, "subtle text");
@@ -236,27 +261,50 @@ function importCustomTheme(text, storage, existing) {
236
261
  }
237
262
  variant = {
238
263
  ...variant,
239
- id: `custom-${slug(name)}-${Date.now().toString(36)}`,
264
+ id: uniqueThemeId(name, existing),
240
265
  name
241
266
  };
242
267
  const issues = validateThemeRegistry([variant]).filter((issue) => issue.severity === "error");
243
268
  for (const issue of issues) notes.push(`${issue.variantId}: ${issue.message}`);
244
- const stored = {
245
- id: variant.id,
246
- name: variant.name,
247
- appearance,
248
- importedAt: (/* @__PURE__ */ new Date()).toISOString(),
249
- variant,
250
- flatTokens: flatVariantTokens(variant),
251
- notes
252
- };
253
- if (!setCustomThemes([...existing, stored], storage)) return {
254
- ok: false,
255
- error: "The theme could not be saved. Check your storage and try again."
256
- };
257
269
  return {
258
270
  ok: true,
259
- theme: stored
271
+ theme: {
272
+ id: variant.id,
273
+ name: variant.name,
274
+ appearance,
275
+ importedAt: (/* @__PURE__ */ new Date()).toISOString(),
276
+ variant,
277
+ flatTokens: flatVariantTokens(variant),
278
+ notes
279
+ }
280
+ };
281
+ }
282
+ /** Parse and add a theme using the latest snapshot inside the shared mutation lock. */
283
+ async function importCustomThemeAtomically(text, storage, options = {}) {
284
+ const { canCommit, ...mutationOptions } = options;
285
+ const mutation = await mutateCustomThemeLibrary(storage, (existing) => {
286
+ if (canCommit && !canCommit()) return {
287
+ themes: existing,
288
+ commit: false,
289
+ value: {
290
+ ok: false,
291
+ error: "This import was superseded."
292
+ }
293
+ };
294
+ const result = prepareCustomTheme(text, existing);
295
+ if (!result.ok) return {
296
+ themes: existing,
297
+ commit: false,
298
+ value: result
299
+ };
300
+ return {
301
+ themes: [...existing, result.theme],
302
+ value: result
303
+ };
304
+ }, mutationOptions);
305
+ return mutation.ok ? mutation.value : {
306
+ ok: false,
307
+ error: mutation.error
260
308
  };
261
309
  }
262
310
  /** Direct host projection for inputs the canonical adapters reject. */
@@ -312,4 +360,4 @@ function projectHostFallback(name, appearance, colors, ansi) {
312
360
  }
313
361
  };
314
362
  }
315
- export { importCustomTheme };
363
+ export { importCustomThemeAtomically };
@@ -95,6 +95,30 @@ export type CustomThemeStored = Readonly<{
95
95
  notes: readonly string[];
96
96
  }>;
97
97
  export type AppearanceStorage = Pick<Storage, 'getItem' | 'setItem'>;
98
+ /** A cross-context lock used to serialize theme-library read/modify/write operations. */
99
+ export type ThemeLibraryAtomicLock = Readonly<{
100
+ withExclusiveLock<T>(name: string, operation: () => T): Promise<T>;
101
+ }>;
102
+ export type ThemeLibraryMutationOptions = Readonly<{
103
+ /** Override the browser lock provider in tests or embedder adapters. `null` means unavailable. */
104
+ lock?: ThemeLibraryAtomicLock | null;
105
+ }>;
106
+ export type ThemeLibraryMutation<T> = Readonly<{
107
+ themes: readonly CustomThemeStored[];
108
+ value: T;
109
+ /** Leave storage and subscribers untouched for rejected or idempotent operations. */
110
+ commit?: boolean;
111
+ }>;
112
+ export type ThemeLibraryMutationFailureReason = 'atomic_unavailable' | 'storage_failed' | 'recovery_unavailable' | 'changed_during_mutation';
113
+ export type ThemeLibraryMutationResult<T> = {
114
+ ok: true;
115
+ committed: boolean;
116
+ value: T;
117
+ } | {
118
+ ok: false;
119
+ reason: ThemeLibraryMutationFailureReason;
120
+ error: string;
121
+ };
98
122
  export declare const CUSTOM_THEME_LIBRARY_STORAGE_KEY = "appearance.library";
99
123
  /**
100
124
  * Where an unreadable library is quarantined. It is its own key: the library and
@@ -102,6 +126,10 @@ export declare const CUSTOM_THEME_LIBRARY_STORAGE_KEY = "appearance.library";
102
126
  * overwrite the other's capture.
103
127
  */
104
128
  export declare const CUSTOM_THEME_LIBRARY_RECOVERY_KEY = "appearance.library.recovery";
129
+ /** Origin-wide lock name shared by all cooperating framework builds. */
130
+ export declare const CUSTOM_THEME_LIBRARY_LOCK_NAME = "adea:appearance.library:mutation:v1";
131
+ export declare const CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE = "This app cannot safely save theme changes in this environment. Your library was not changed.";
132
+ export declare const CUSTOM_THEME_LIBRARY_MUTATION_FAILED = "The theme could not be saved. Check your storage and try again.";
105
133
  export type ValidationIssue = Readonly<{
106
134
  variantId: string;
107
135
  severity: 'error' | 'warning';
@@ -131,9 +159,11 @@ export declare function customThemeVariants(): readonly StoredThemeVariant[];
131
159
  export declare function customUiVariants(): readonly UiThemeVariant[];
132
160
  export declare function subscribeCustomThemes(listener: () => void): () => void;
133
161
  /**
134
- * Replace the imported-theme set, persist it, and tell subscribers. A theme whose id
135
- * is not custom-namespaced is namespaced here, so a library file can never shadow a
136
- * catalogue id.
162
+ * Replace the in-memory imported-theme set and tell subscribers. Durable mutations
163
+ * must use `mutateCustomThemeLibrary`; this deprecated synchronous API fails closed
164
+ * when a storage adapter is supplied because it cannot acquire the shared lock.
165
+ *
166
+ * @deprecated Use `mutateCustomThemeLibrary` for persisted read/modify/write operations.
137
167
  */
138
168
  export declare function setCustomThemes(themes: readonly CustomThemeStored[], storage: AppearanceStorage | undefined): boolean;
139
169
  /**
@@ -143,4 +173,22 @@ export declare function setCustomThemes(themes: readonly CustomThemeStored[], st
143
173
  * not fatal.
144
174
  */
145
175
  export declare function readCustomThemeLibrary(storage: AppearanceStorage | undefined): readonly CustomThemeStored[];
176
+ /**
177
+ * Coordinate a storage-backed library read/modify/write across cooperating contexts.
178
+ * The callback reads the current v1 record while holding an origin-wide IndexedDB
179
+ * read/write transaction (and a Web Lock where available), then writes and verifies
180
+ * the v1 record before updating this tab's in-memory registry. Older builds and
181
+ * direct `setCustomThemes` storage writes do not acquire these locks and can still
182
+ * race; this API does not claim cross-version atomicity. If IndexedDB is unavailable,
183
+ * durable mutations fail closed.
184
+ */
185
+ export declare function mutateCustomThemeLibrary<T>(storage: AppearanceStorage | undefined, update: (themes: readonly CustomThemeStored[]) => ThemeLibraryMutation<T>, options?: ThemeLibraryMutationOptions): Promise<ThemeLibraryMutationResult<T>>;
186
+ /** Remove from the latest persisted snapshot, not a possibly stale UI snapshot. */
187
+ export declare function removeCustomThemeAtomically(id: string, storage: AppearanceStorage | undefined, options?: ThemeLibraryMutationOptions): Promise<ThemeLibraryMutationResult<boolean>>;
188
+ /**
189
+ * Synchronous legacy removal for the in-memory library. Passing storage fails closed;
190
+ * use `removeCustomThemeAtomically` for persisted removals.
191
+ *
192
+ * @deprecated Use `removeCustomThemeAtomically` for persisted removals.
193
+ */
146
194
  export declare function removeCustomTheme(id: string, storage: AppearanceStorage | undefined): boolean;
@@ -1,4 +1,4 @@
1
- import { quarantineRecord } from "@adea-ai/ui/lib/preference-store";
1
+ import { defaultPreferenceStorage, quarantineRecord } from "@adea-ai/ui/lib/preference-store";
2
2
  import { contrastRatio } from "@adea-ai/ui/lib/accent-roles";
3
3
  import { defaultVariantFor } from "@adea-ai/ui/lib/theme-defaults";
4
4
  import { variantFromRecord } from "@adea-ai/ui/lib/theme-records";
@@ -12,6 +12,12 @@ var CUSTOM_THEME_LIBRARY_STORAGE_KEY = "appearance.library";
12
12
  var CUSTOM_THEME_LIBRARY_RECOVERY_KEY = "appearance.library.recovery";
13
13
  var CUSTOM_THEME_LIBRARY_VERSION = 1;
14
14
  var CUSTOM_THEME_ID_PREFIX = "custom-";
15
+ /** Origin-wide lock name shared by all cooperating framework builds. */
16
+ var CUSTOM_THEME_LIBRARY_LOCK_NAME = "adea:appearance.library:mutation:v1";
17
+ var CUSTOM_THEME_LIBRARY_LOCK_DB = "adea:appearance-library-coordination:v1";
18
+ var CUSTOM_THEME_LIBRARY_LOCK_STORE = "locks";
19
+ var CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE = "This app cannot safely save theme changes in this environment. Your library was not changed.";
20
+ var CUSTOM_THEME_LIBRARY_MUTATION_FAILED = "The theme could not be saved. Check your storage and try again.";
15
21
  function validateThemeRegistry(registry) {
16
22
  const issues = [];
17
23
  const seen = /* @__PURE__ */ new Set();
@@ -191,7 +197,8 @@ function library() {
191
197
  if (existing && Array.isArray(existing.themes) && existing.listeners) return existing;
192
198
  const created = {
193
199
  themes: [],
194
- listeners: existing?.listeners ?? /* @__PURE__ */ new Set()
200
+ listeners: existing?.listeners ?? /* @__PURE__ */ new Set(),
201
+ atomicMutationDepth: 0
195
202
  };
196
203
  libraryHost.__ADEA_THEME_LIBRARY__ = created;
197
204
  return created;
@@ -211,24 +218,55 @@ function customUiVariants() {
211
218
  state.uiVariants ??= Object.freeze(state.themes.map(toUiVariant));
212
219
  return state.uiVariants;
213
220
  }
221
+ function handlePersistentLibraryChange(event) {
222
+ if (event.key !== "appearance.library" && event.key !== null) return;
223
+ const storage = defaultPreferenceStorage();
224
+ if (!storage || event.storageArea !== storage) return;
225
+ readCustomThemeLibrary(storage);
226
+ }
227
+ function observePersistentLibraryChanges() {
228
+ const state = library();
229
+ if (state.storageEventTarget || typeof window === "undefined") return;
230
+ const target = window;
231
+ const listener = handlePersistentLibraryChange;
232
+ state.storageEventTarget = target;
233
+ state.storageEventListener = listener;
234
+ target.addEventListener("storage", listener);
235
+ }
214
236
  function subscribeCustomThemes(listener) {
237
+ observePersistentLibraryChanges();
215
238
  const { listeners } = library();
216
239
  listeners.add(listener);
217
240
  return () => listeners.delete(listener);
218
241
  }
219
242
  function notifyCustomThemes() {
220
- for (const listener of library().listeners) listener();
243
+ const { listeners } = library();
244
+ for (const listener of [...listeners]) {
245
+ if (!listeners.has(listener)) continue;
246
+ try {
247
+ Promise.resolve(listener()).catch(() => {});
248
+ } catch {}
249
+ }
221
250
  }
222
251
  function isCustomThemeId(id) {
223
252
  return id.startsWith(CUSTOM_THEME_ID_PREFIX);
224
253
  }
225
254
  /**
226
- * Replace the imported-theme set, persist it, and tell subscribers. A theme whose id
227
- * is not custom-namespaced is namespaced here, so a library file can never shadow a
228
- * catalogue id.
255
+ * Replace the in-memory imported-theme set and tell subscribers. Durable mutations
256
+ * must use `mutateCustomThemeLibrary`; this deprecated synchronous API fails closed
257
+ * when a storage adapter is supplied because it cannot acquire the shared lock.
258
+ *
259
+ * @deprecated Use `mutateCustomThemeLibrary` for persisted read/modify/write operations.
229
260
  */
230
261
  function setCustomThemes(themes, storage) {
231
- const safe = themes.map((theme) => {
262
+ if ((library().atomicMutationDepth ?? 0) > 0) return false;
263
+ if (storage) return false;
264
+ replaceThemes(namespaceCustomThemes(themes));
265
+ notifyCustomThemes();
266
+ return true;
267
+ }
268
+ function namespaceCustomThemes(themes) {
269
+ return themes.map((theme) => {
232
270
  if (isCustomThemeId(theme.id)) return theme;
233
271
  const id = `${CUSTOM_THEME_ID_PREFIX}${theme.id}`;
234
272
  return {
@@ -240,24 +278,6 @@ function setCustomThemes(themes, storage) {
240
278
  }
241
279
  };
242
280
  });
243
- try {
244
- if (storage) {
245
- const raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY);
246
- if (raw) {
247
- const result = parseLibrary(raw);
248
- if (result.reason && !preserveLibrary(storage, raw, result.reason)) throw new Error("Library recovery unavailable");
249
- }
250
- }
251
- storage?.setItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY, JSON.stringify({
252
- version: CUSTOM_THEME_LIBRARY_VERSION,
253
- themes: safe
254
- }));
255
- } catch {
256
- return false;
257
- }
258
- replaceThemes(safe);
259
- notifyCustomThemes();
260
- return true;
261
281
  }
262
282
  var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
263
283
  var fields = (value, names) => object(value) && names.every((name) => typeof value[name] === "string");
@@ -361,18 +381,227 @@ function preserveLibrary(storage, raw, reason) {
361
381
  */
362
382
  function readCustomThemeLibrary(storage) {
363
383
  if (!storage) return [];
384
+ const result = tryReadCustomThemeLibrary(storage);
385
+ if (result?.changed) notifyCustomThemes();
386
+ return result?.themes ?? [];
387
+ }
388
+ function sameThemeValue(left, right) {
389
+ if (Object.is(left, right)) return true;
390
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
391
+ if (Array.isArray(left) || Array.isArray(right)) {
392
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
393
+ if (Object.getPrototypeOf(left) !== Array.prototype) return false;
394
+ if (Reflect.ownKeys(left).length !== left.length + 1) return false;
395
+ for (let index = 0; index < left.length; index++) {
396
+ const entry = Object.getOwnPropertyDescriptor(left, index);
397
+ if (!entry || !entry.enumerable || !("value" in entry)) return false;
398
+ if (!sameThemeValue(entry.value, right[index])) return false;
399
+ }
400
+ return true;
401
+ }
402
+ if (Object.getPrototypeOf(left) !== Object.prototype) return false;
403
+ const leftKeys = Object.keys(left);
404
+ const rightKeys = Object.keys(right);
405
+ if (leftKeys.length !== rightKeys.length || Reflect.ownKeys(left).length !== leftKeys.length) return false;
406
+ const rightRecord = right;
407
+ return leftKeys.every((key) => {
408
+ const entry = Object.getOwnPropertyDescriptor(left, key);
409
+ return !!entry && "value" in entry && Object.hasOwn(rightRecord, key) && sameThemeValue(entry.value, rightRecord[key]);
410
+ });
411
+ }
412
+ /** A failed read must not be confused with a successfully read empty library. */
413
+ function tryReadCustomThemeLibrary(storage) {
414
+ const state = library();
415
+ const previousThemes = state.themes;
364
416
  try {
365
417
  const raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY);
366
- if (!raw) return [];
367
- const { themes, reason } = parseLibrary(raw);
368
- if (reason) preserveLibrary(storage, raw, reason);
369
- replaceThemes(themes);
370
- return themes;
418
+ const { themes, reason } = raw ? parseLibrary(raw) : { themes: [] };
419
+ if (raw && reason) preserveLibrary(storage, raw, reason);
420
+ let changed = true;
421
+ try {
422
+ changed = !sameThemeValue(previousThemes, themes);
423
+ } catch {}
424
+ if (storage.getItem("appearance.library") !== raw || library() !== state || state.themes !== previousThemes) return void 0;
425
+ if (changed) replaceThemes(themes);
426
+ return {
427
+ themes: changed ? themes : previousThemes,
428
+ changed
429
+ };
430
+ } catch {
431
+ return;
432
+ }
433
+ }
434
+ function withIndexedDbMutationLock(name, operation) {
435
+ const factory = globalThis.indexedDB;
436
+ if (!factory) return Promise.reject(/* @__PURE__ */ new Error("IndexedDB is unavailable"));
437
+ return new Promise((resolve, reject) => {
438
+ const open = factory.open(CUSTOM_THEME_LIBRARY_LOCK_DB, 1);
439
+ open.addEventListener("upgradeneeded", () => {
440
+ if (!open.result.objectStoreNames.contains(CUSTOM_THEME_LIBRARY_LOCK_STORE)) open.result.createObjectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE);
441
+ });
442
+ open.addEventListener("error", () => reject(open.error ?? /* @__PURE__ */ new Error("Could not open theme coordination database")));
443
+ open.addEventListener("success", () => {
444
+ const database = open.result;
445
+ database.addEventListener("versionchange", () => database.close());
446
+ let transaction;
447
+ try {
448
+ transaction = database.transaction(CUSTOM_THEME_LIBRARY_LOCK_STORE, "readwrite");
449
+ } catch (error) {
450
+ database.close();
451
+ reject(error);
452
+ return;
453
+ }
454
+ let result;
455
+ let ran = false;
456
+ let operationError;
457
+ const close = () => database.close();
458
+ transaction.addEventListener("complete", () => {
459
+ close();
460
+ if (operationError !== void 0) reject(operationError);
461
+ else if (ran) resolve(result);
462
+ else reject(/* @__PURE__ */ new Error("Theme library lock transaction did not run"));
463
+ });
464
+ transaction.addEventListener("abort", () => {
465
+ close();
466
+ if (ran) {
467
+ resolve(result);
468
+ return;
469
+ }
470
+ reject(operationError ?? transaction.error ?? /* @__PURE__ */ new Error("Theme library lock transaction aborted"));
471
+ });
472
+ try {
473
+ transaction.objectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE).get(name).addEventListener("success", () => {
474
+ try {
475
+ result = operation();
476
+ ran = true;
477
+ } catch (error) {
478
+ operationError = error;
479
+ transaction.abort();
480
+ }
481
+ });
482
+ } catch (error) {
483
+ operationError = error;
484
+ transaction.abort();
485
+ }
486
+ });
487
+ });
488
+ }
489
+ function browserThemeLibraryAtomicLock() {
490
+ if (!globalThis.indexedDB) return void 0;
491
+ const locks = globalThis.navigator?.locks;
492
+ return { withExclusiveLock: (name, operation) => locks && typeof locks.request === "function" ? locks.request(name, { mode: "exclusive" }, () => withIndexedDbMutationLock(name, operation)) : withIndexedDbMutationLock(name, operation) };
493
+ }
494
+ function mutationFailure(reason, error) {
495
+ return {
496
+ ok: false,
497
+ reason,
498
+ error
499
+ };
500
+ }
501
+ /**
502
+ * Coordinate a storage-backed library read/modify/write across cooperating contexts.
503
+ * The callback reads the current v1 record while holding an origin-wide IndexedDB
504
+ * read/write transaction (and a Web Lock where available), then writes and verifies
505
+ * the v1 record before updating this tab's in-memory registry. Older builds and
506
+ * direct `setCustomThemes` storage writes do not acquire these locks and can still
507
+ * race; this API does not claim cross-version atomicity. If IndexedDB is unavailable,
508
+ * durable mutations fail closed.
509
+ */
510
+ async function mutateCustomThemeLibrary(storage, update, options = {}) {
511
+ if (!storage) try {
512
+ const mutation = update(library().themes);
513
+ if (mutation.commit === false) return {
514
+ ok: true,
515
+ committed: false,
516
+ value: mutation.value
517
+ };
518
+ if (!setCustomThemes(namespaceCustomThemes(mutation.themes), void 0)) return mutationFailure("storage_failed", CUSTOM_THEME_LIBRARY_MUTATION_FAILED);
519
+ return {
520
+ ok: true,
521
+ committed: true,
522
+ value: mutation.value
523
+ };
524
+ } catch {
525
+ return mutationFailure("storage_failed", CUSTOM_THEME_LIBRARY_MUTATION_FAILED);
526
+ }
527
+ const lock = options.lock === void 0 ? browserThemeLibraryAtomicLock() : options.lock;
528
+ if (!lock) return mutationFailure("atomic_unavailable", CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE);
529
+ let enteredLock = false;
530
+ try {
531
+ return await lock.withExclusiveLock(CUSTOM_THEME_LIBRARY_LOCK_NAME, () => {
532
+ enteredLock = true;
533
+ const state = library();
534
+ state.atomicMutationDepth = (state.atomicMutationDepth ?? 0) + 1;
535
+ try {
536
+ let raw;
537
+ let themes;
538
+ try {
539
+ raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY);
540
+ const parsed = raw ? parseLibrary(raw) : { themes: [] };
541
+ themes = parsed.themes;
542
+ if (raw && parsed.reason && !preserveLibrary(storage, raw, parsed.reason)) return mutationFailure("recovery_unavailable", "The stored theme library could not be preserved, so this change was not saved.");
543
+ if (storage.getItem("appearance.library") !== raw) return mutationFailure("changed_during_mutation", "The theme library changed while it was being read. Try again.");
544
+ } catch {
545
+ return mutationFailure("storage_failed", CUSTOM_THEME_LIBRARY_MUTATION_FAILED);
546
+ }
547
+ let mutation;
548
+ try {
549
+ mutation = update(themes);
550
+ if (storage.getItem("appearance.library") !== raw) return mutationFailure("changed_during_mutation", "The theme library changed while this change was being prepared. Try again.");
551
+ } catch {
552
+ return mutationFailure("storage_failed", CUSTOM_THEME_LIBRARY_MUTATION_FAILED);
553
+ }
554
+ if (mutation.commit === false) return {
555
+ ok: true,
556
+ committed: false,
557
+ value: mutation.value
558
+ };
559
+ const safe = namespaceCustomThemes(mutation.themes);
560
+ const serialized = JSON.stringify({
561
+ version: CUSTOM_THEME_LIBRARY_VERSION,
562
+ themes: safe
563
+ });
564
+ try {
565
+ storage.setItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY, serialized);
566
+ if (storage.getItem("appearance.library") !== serialized) return mutationFailure("changed_during_mutation", "The theme library changed while it was being saved. Try again.");
567
+ } catch {
568
+ return mutationFailure("storage_failed", CUSTOM_THEME_LIBRARY_MUTATION_FAILED);
569
+ }
570
+ replaceThemes(safe);
571
+ notifyCustomThemes();
572
+ return {
573
+ ok: true,
574
+ committed: true,
575
+ value: mutation.value
576
+ };
577
+ } finally {
578
+ state.atomicMutationDepth = Math.max(0, (state.atomicMutationDepth ?? 1) - 1);
579
+ }
580
+ });
371
581
  } catch {
372
- return [];
582
+ return mutationFailure(enteredLock ? "storage_failed" : "atomic_unavailable", enteredLock ? CUSTOM_THEME_LIBRARY_MUTATION_FAILED : CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE);
373
583
  }
374
584
  }
585
+ /** Remove from the latest persisted snapshot, not a possibly stale UI snapshot. */
586
+ async function removeCustomThemeAtomically(id, storage, options = {}) {
587
+ return mutateCustomThemeLibrary(storage, (themes) => {
588
+ const remaining = themes.filter((theme) => theme.id !== id);
589
+ return {
590
+ themes: remaining,
591
+ value: true,
592
+ commit: remaining.length !== themes.length
593
+ };
594
+ }, options);
595
+ }
596
+ /**
597
+ * Synchronous legacy removal for the in-memory library. Passing storage fails closed;
598
+ * use `removeCustomThemeAtomically` for persisted removals.
599
+ *
600
+ * @deprecated Use `removeCustomThemeAtomically` for persisted removals.
601
+ */
375
602
  function removeCustomTheme(id, storage) {
376
- return setCustomThemes(readCustomThemeLibrary(storage).filter((theme) => theme.id !== id), storage);
603
+ if (storage) return false;
604
+ const themes = library().themes;
605
+ return setCustomThemes(themes.filter((theme) => theme.id !== id), storage);
377
606
  }
378
- export { CUSTOM_THEME_LIBRARY_RECOVERY_KEY, CUSTOM_THEME_LIBRARY_STORAGE_KEY, customThemeVariants, customUiVariants, flatVariantTokens, readCustomThemeLibrary, removeCustomTheme, setCustomThemes, storedVariantRecord, subscribeCustomThemes, toUiVariant, validateThemeRegistry };
607
+ export { CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE, CUSTOM_THEME_LIBRARY_LOCK_NAME, CUSTOM_THEME_LIBRARY_MUTATION_FAILED, CUSTOM_THEME_LIBRARY_RECOVERY_KEY, CUSTOM_THEME_LIBRARY_STORAGE_KEY, customThemeVariants, customUiVariants, flatVariantTokens, mutateCustomThemeLibrary, readCustomThemeLibrary, removeCustomTheme, removeCustomThemeAtomically, setCustomThemes, storedVariantRecord, subscribeCustomThemes, toUiVariant, validateThemeRegistry };
@@ -2,7 +2,7 @@ import { type AppearancePreferencesV2 } from './appearance-preferences';
2
2
  export type AppearanceEditor = Readonly<{
3
3
  /** The edited draft, reactive so dialog UI tracks every change. */
4
4
  draft: () => AppearancePreferencesV2;
5
- /** True when the draft differs from the snapshot the editor opened with. */
5
+ /** True when the draft differs from the opening snapshot or Reset was requested. */
6
6
  dirty: () => boolean;
7
7
  /** True when the draft differs from the shipped defaults. */
8
8
  differsFromDefaults: () => boolean;
@@ -14,6 +14,8 @@ export type AppearanceEditor = Readonly<{
14
14
  reset: () => void;
15
15
  /** Discard the draft; the committed snapshot is authoritative again. */
16
16
  revert: () => AppearancePreferencesV2;
17
+ /** Combine changed draft fields with current committed preferences without mutating the editor. */
18
+ merge: (current: AppearancePreferencesV2) => AppearancePreferencesV2;
17
19
  /** Commit the draft and clear the snapshot. */
18
20
  save: () => AppearancePreferencesV2;
19
21
  }>;
@@ -2,6 +2,15 @@ import { defaultAppearancePreferences, normalizeAppearancePreferences } from "./
2
2
  import { createSignal } from "solid-js";
3
3
  import { normalizeAppearanceEditorFontSettings } from "@adea-ai/ui/lib/appearance-font-settings";
4
4
  // src/appearance/editor.ts
5
+ var scalarFields = Object.keys({
6
+ mode: true,
7
+ lightThemeId: true,
8
+ darkThemeId: true,
9
+ terminalThemeId: true,
10
+ accent: true,
11
+ surface: true,
12
+ reduceTransparency: true
13
+ });
5
14
  function samePreferences(left, right) {
6
15
  const leftFonts = normalizeAppearanceEditorFontSettings(left.fonts).settings;
7
16
  const rightFonts = normalizeAppearanceEditorFontSettings(right.fonts).settings;
@@ -9,16 +18,18 @@ function samePreferences(left, right) {
9
18
  "ui",
10
19
  "content",
11
20
  "code"
12
- ].every((axis) => leftFonts[axis].family === rightFonts[axis].family && leftFonts[axis].size === rightFonts[axis].size) && left.mode === right.mode && left.lightThemeId === right.lightThemeId && left.darkThemeId === right.darkThemeId && left.terminalThemeId === right.terminalThemeId && left.accent === right.accent && left.surface === right.surface && left.reduceTransparency === right.reduceTransparency;
21
+ ].every((axis) => leftFonts[axis].family === rightFonts[axis].family && leftFonts[axis].size === rightFonts[axis].size) && scalarFields.every((field) => left[field] === right[field]);
13
22
  }
14
23
  function createAppearanceEditor(committed = defaultAppearancePreferences) {
15
24
  const [draft, setDraft] = createSignal(committed);
16
25
  const [snapshot, setSnapshot] = createSignal(committed);
26
+ const [resetAll, setResetAll] = createSignal(false);
17
27
  return {
18
28
  draft,
19
- dirty: () => !samePreferences(draft(), snapshot()),
29
+ dirty: () => resetAll() || !samePreferences(draft(), snapshot()),
20
30
  differsFromDefaults: () => !samePreferences(draft(), defaultAppearancePreferences),
21
31
  open: (value) => {
32
+ setResetAll(false);
22
33
  const normalized = normalizeAppearancePreferences(value).value;
23
34
  setSnapshot(normalized);
24
35
  setDraft(normalized);
@@ -32,13 +43,37 @@ function createAppearanceEditor(committed = defaultAppearancePreferences) {
32
43
  setDraft(next);
33
44
  },
34
45
  reset: () => {
46
+ setResetAll(true);
35
47
  setDraft(defaultAppearancePreferences);
36
48
  },
37
49
  revert: () => {
50
+ setResetAll(false);
38
51
  setDraft(snapshot());
39
52
  return snapshot();
40
53
  },
54
+ merge: (current) => {
55
+ const before = snapshot();
56
+ const after = draft();
57
+ if (resetAll()) return after;
58
+ const merged = { ...current };
59
+ for (const field of scalarFields) if (before[field] !== after[field]) Object.assign(merged, { [field]: after[field] });
60
+ const originalFonts = normalizeAppearanceEditorFontSettings(before.fonts).settings;
61
+ const draftFonts = normalizeAppearanceEditorFontSettings(after.fonts).settings;
62
+ const currentFonts = normalizeAppearanceEditorFontSettings(current.fonts).settings;
63
+ const fonts = { ...currentFonts };
64
+ for (const axis of [
65
+ "ui",
66
+ "content",
67
+ "code"
68
+ ]) fonts[axis] = {
69
+ family: originalFonts[axis].family === draftFonts[axis].family ? currentFonts[axis].family : draftFonts[axis].family,
70
+ size: originalFonts[axis].size === draftFonts[axis].size ? currentFonts[axis].size : draftFonts[axis].size
71
+ };
72
+ if (after.fonts !== void 0 || current.fonts !== void 0) merged.fonts = fonts;
73
+ return merged;
74
+ },
41
75
  save: () => {
76
+ setResetAll(false);
42
77
  setSnapshot(draft());
43
78
  return draft();
44
79
  }
@@ -3,15 +3,16 @@ import type { CustomThemeImportResult } from './custom-theme-import';
3
3
  export type ThemeFileImporterHost = Readonly<{
4
4
  /**
5
5
  * Loads the importer and returns the function that imports one file's text.
6
- * It runs after every await so the library it merges into is read fresh.
6
+ * The importer receives a freshness guard so queued writes can be dropped after
7
+ * a newer file or cancellation supersedes them.
7
8
  */
8
- load: () => Promise<(text: string) => CustomThemeImportResult>;
9
+ load: () => Promise<(text: string, canCommit: () => boolean) => CustomThemeImportResult | Promise<CustomThemeImportResult>>;
9
10
  onPending: (pending: boolean) => void;
10
11
  onStatus: (message: string) => void;
11
12
  onImported: (theme: CustomThemeStored) => void;
12
13
  }>;
13
14
  type ThemeFileImporter = Readonly<{
14
- importFile: (file: Pick<File, 'text'>) => Promise<void>;
15
+ importFile: (file: Pick<File, 'size' | 'text'>) => Promise<void>;
15
16
  /** Drops the run in flight, if any, and clears its pending status. */
16
17
  cancel: () => void;
17
18
  }>;
@@ -19,5 +20,8 @@ export declare const THEME_IMPORT_PENDING = "Importing theme\u2026";
19
20
  export declare const THEME_IMPORT_UNREADABLE = "That file could not be read.";
20
21
  export declare const THEME_IMPORT_UNAVAILABLE = "The theme importer could not be loaded. Reload the app and try again.";
21
22
  export declare const THEME_IMPORT_FAILED = "That theme could not be imported.";
23
+ /** A theme is a small JSON document; bound reads before allocating its text. */
24
+ export declare const MAX_THEME_FILE_BYTES: number;
25
+ export declare const THEME_IMPORT_TOO_LARGE = "That theme file is too large. Choose one 1 MiB or smaller.";
22
26
  export declare function createThemeFileImporter(host: ThemeFileImporterHost): ThemeFileImporter;
23
27
  export {};