@adea-ai/app-framework 0.25.0 → 0.26.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 (138) hide show
  1. package/README.md +157 -19
  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/cef-helper-cli.js +0 -0
  21. package/dist/cli/create-application-cli.js +0 -0
  22. package/dist/cli/electrobun-shortcut-patch-cli.js +0 -0
  23. package/dist/cli/framework-update-cli.js +16 -3
  24. package/dist/cli/macos-signing-cli.js +0 -0
  25. package/dist/cli/release-assets-plan-cli.js +0 -0
  26. package/dist/cli/release-cut-cli.js +0 -0
  27. package/dist/cli/release-descriptor-staging-cli.js +0 -0
  28. package/dist/cli/release-finalize-cli.js +0 -0
  29. package/dist/cli/release-promote-cli.js +0 -0
  30. package/dist/cli/release-publish-cli.js +0 -0
  31. package/dist/cli/release-sign-cli.js +0 -0
  32. package/dist/cli/release-step-cli.js +0 -0
  33. package/dist/cli/toolchain-identity-cli.js +0 -0
  34. package/dist/cli/windows-runtime-patch-cli.js +0 -0
  35. package/dist/desktop/application-command-client.d.ts +11 -1
  36. package/dist/desktop/application-command-client.js +66 -3
  37. package/dist/desktop/channel-handshake.d.ts +2 -1
  38. package/dist/desktop/channel-handshake.js +21 -5
  39. package/dist/desktop/client-asset-stream.d.ts +10 -0
  40. package/dist/desktop/client-asset-stream.js +97 -0
  41. package/dist/desktop/client-assets.d.ts +3 -1
  42. package/dist/desktop/client-assets.js +41 -6
  43. package/dist/desktop/desktop-client.d.ts +15 -1
  44. package/dist/desktop/desktop-client.js +235 -109
  45. package/dist/desktop/desktop-gateway.d.ts +2 -0
  46. package/dist/desktop/desktop-gateway.js +134 -22
  47. package/dist/desktop/desktop-host-websocket.d.ts +10 -0
  48. package/dist/desktop/desktop-host-websocket.js +28 -0
  49. package/dist/desktop/desktop-host.d.ts +9 -0
  50. package/dist/desktop/desktop-host.js +70 -61
  51. package/dist/desktop/desktop-port-file.d.ts +2 -0
  52. package/dist/desktop/desktop-port-file.js +23 -0
  53. package/dist/desktop/desktop-stream.d.ts +5 -0
  54. package/dist/desktop/desktop-stream.js +83 -15
  55. package/dist/desktop/gateway-limits.d.ts +2 -0
  56. package/dist/desktop/gateway-limits.js +6 -0
  57. package/dist/desktop/open-url-channel.d.ts +5 -3
  58. package/dist/desktop/open-url-channel.js +18 -5
  59. package/dist/desktop/typed-array-intrinsics.d.ts +6 -0
  60. package/dist/desktop/typed-array-intrinsics.js +19 -0
  61. package/dist/framework-source.json +1 -1
  62. package/dist/installer/installed-payload.js +1 -1
  63. package/dist/installer/installer-ci-bootstrap.js +2 -1
  64. package/dist/installer/installer-command.d.ts +13 -0
  65. package/dist/installer/installer-command.js +47 -0
  66. package/dist/installer/installer-extraction.js +27 -61
  67. package/dist/installer/installer-identity.d.ts +19 -3
  68. package/dist/installer/installer-identity.js +58 -70
  69. package/dist/installer/installer-image-mount.d.ts +48 -0
  70. package/dist/installer/installer-image-mount.js +347 -0
  71. package/dist/installer/installer-layout.js +1 -1
  72. package/dist/installer/installer-process-cleanup.js +1 -1
  73. package/dist/installer/installer-renderer-evidence.js +6 -2
  74. package/dist/installer/upgrade-asset-download.js +30 -8
  75. package/dist/native/app-bundle.d.ts +2 -2
  76. package/dist/native/app-bundle.js +5 -4
  77. package/dist/native/cef-helper-download.d.ts +1 -0
  78. package/dist/native/cef-helper-download.js +35 -0
  79. package/dist/native/cef-helper.js +146 -61
  80. package/dist/native/exclusive-rename.d.ts +2 -0
  81. package/dist/native/exclusive-rename.js +52 -0
  82. package/dist/native/native-secret-store.js +5 -4
  83. package/dist/native/partitioned-window.d.ts +5 -2
  84. package/dist/native/partitioned-window.js +69 -9
  85. package/dist/native/sidecar-services.js +2 -2
  86. package/dist/native/sidecar.js +68 -25
  87. package/dist/native/window-bootstrap.js +2 -2
  88. package/dist/release/feed-state.js +2 -1
  89. package/dist/release/framework-update-lock.d.ts +2 -0
  90. package/dist/release/framework-update-lock.js +42 -0
  91. package/dist/release/framework-update.d.ts +6 -2
  92. package/dist/release/framework-update.js +165 -40
  93. package/dist/release/local-release.js +68 -39
  94. package/dist/release/release-config.js +1 -1
  95. package/dist/shared/discard-stream.d.ts +4 -0
  96. package/dist/shared/discard-stream.js +9 -0
  97. package/dist/shell/app-shell.js +59 -7
  98. package/dist/shell/app-utilities.js +2 -2
  99. package/dist/shell/application-menu.d.ts +13 -0
  100. package/dist/shell/application-menu.js +21 -8
  101. package/dist/update-helper.bundle.js +40 -4
  102. package/dist/updates/channel-update-manager.d.ts +2 -0
  103. package/dist/updates/channel-update-manager.js +15 -3
  104. package/dist/updates/desktop-updater.d.ts +2 -0
  105. package/dist/updates/desktop-updater.js +36 -7
  106. package/dist/updates/linux-process-state.d.ts +2 -0
  107. package/dist/updates/linux-process-state.js +13 -0
  108. package/dist/updates/release-location.js +5 -4
  109. package/dist/updates/update-adapter.js +5 -0
  110. package/dist/updates/update-arm.d.ts +2 -0
  111. package/dist/updates/update-arm.js +58 -7
  112. package/dist/updates/update-discovery.js +2 -1
  113. package/dist/updates/update-download-cleanup.d.ts +7 -0
  114. package/dist/updates/update-download-cleanup.js +21 -0
  115. package/dist/updates/update-download.js +41 -20
  116. package/dist/updates/update-exclusive-rename.d.ts +3 -2
  117. package/dist/updates/update-exclusive-rename.js +3 -50
  118. package/dist/updates/update-extraction.js +1 -1
  119. package/dist/updates/update-manager.d.ts +17 -1
  120. package/dist/updates/update-manager.js +27 -8
  121. package/dist/updates/update-process-fence.js +18 -3
  122. package/dist/views/appearance-surface.js +51 -15
  123. package/package.json +11 -6
  124. package/src/app/application.tsx +49 -7
  125. package/src/appearance/custom-theme-import.ts +67 -7
  126. package/src/appearance/custom-theme-library.ts +391 -33
  127. package/src/appearance/editor.ts +49 -10
  128. package/src/appearance/theme-file-importer.ts +43 -12
  129. package/src/appearance/theme-library-action-fence.ts +28 -0
  130. package/src/desktop/client-asset-stream.ts +118 -0
  131. package/src/desktop/client-assets.ts +55 -5
  132. package/src/shell/app-shell.tsx +71 -8
  133. package/src/shell/app-utilities.tsx +2 -2
  134. package/src/updates/update-adapter.ts +5 -0
  135. package/src/views/appearance-surface.tsx +61 -29
  136. package/templates/application/README.md +5 -1
  137. package/templates/application/scripts/app-version.ts +7 -3
  138. package/templates/application/src/bun/index.ts +2 -0
@@ -11,7 +11,7 @@
11
11
  import type { AdeaTheme, AdeaThemeRecord } from '@adea-ai/ui/lib/theme-records'
12
12
 
13
13
  import { contrastRatio } from '@adea-ai/ui/lib/accent-roles'
14
- import { quarantineRecord } from '@adea-ai/ui/lib/preference-store'
14
+ import { defaultPreferenceStorage, quarantineRecord } from '@adea-ai/ui/lib/preference-store'
15
15
  import { defaultVariantFor } from '@adea-ai/ui/lib/theme-defaults'
16
16
  import { variantFromRecord } from '@adea-ai/ui/lib/theme-records'
17
17
  import type { ThemeVariant as UiThemeVariant } from '@adea-ai/ui/lib/themes'
@@ -120,6 +120,33 @@ export type CustomThemeStored = Readonly<{
120
120
 
121
121
  export type AppearanceStorage = Pick<Storage, 'getItem' | 'setItem'>
122
122
 
123
+ /** A cross-context lock used to serialize theme-library read/modify/write operations. */
124
+ export type ThemeLibraryAtomicLock = Readonly<{
125
+ withExclusiveLock<T>(name: string, operation: () => T): Promise<T>
126
+ }>
127
+
128
+ export type ThemeLibraryMutationOptions = Readonly<{
129
+ /** Override the browser lock provider in tests or embedder adapters. `null` means unavailable. */
130
+ lock?: ThemeLibraryAtomicLock | null
131
+ }>
132
+
133
+ export type ThemeLibraryMutation<T> = Readonly<{
134
+ themes: readonly CustomThemeStored[]
135
+ value: T
136
+ /** Leave storage and subscribers untouched for rejected or idempotent operations. */
137
+ commit?: boolean
138
+ }>
139
+
140
+ export type ThemeLibraryMutationFailureReason =
141
+ | 'atomic_unavailable'
142
+ | 'storage_failed'
143
+ | 'recovery_unavailable'
144
+ | 'changed_during_mutation'
145
+
146
+ export type ThemeLibraryMutationResult<T> =
147
+ | { ok: true; committed: boolean; value: T }
148
+ | { ok: false; reason: ThemeLibraryMutationFailureReason; error: string }
149
+
123
150
  export const CUSTOM_THEME_LIBRARY_STORAGE_KEY = 'appearance.library'
124
151
  /**
125
152
  * Where an unreadable library is quarantined. It is its own key: the library and
@@ -129,6 +156,14 @@ export const CUSTOM_THEME_LIBRARY_STORAGE_KEY = 'appearance.library'
129
156
  export const CUSTOM_THEME_LIBRARY_RECOVERY_KEY = 'appearance.library.recovery'
130
157
  const CUSTOM_THEME_LIBRARY_VERSION = 1
131
158
  const CUSTOM_THEME_ID_PREFIX = 'custom-'
159
+ /** Origin-wide lock name shared by all cooperating framework builds. */
160
+ export const CUSTOM_THEME_LIBRARY_LOCK_NAME = 'adea:appearance.library:mutation:v1'
161
+ const CUSTOM_THEME_LIBRARY_LOCK_DB = 'adea:appearance-library-coordination:v1'
162
+ const CUSTOM_THEME_LIBRARY_LOCK_STORE = 'locks'
163
+ export const CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE =
164
+ 'This app cannot safely save theme changes in this environment. Your library was not changed.'
165
+ export const CUSTOM_THEME_LIBRARY_MUTATION_FAILED =
166
+ 'The theme could not be saved. Check your storage and try again.'
132
167
 
133
168
  /*
134
169
  * Registry validation, ported from Zeron `ThemeRegistry::validate`: core text and
@@ -379,6 +414,11 @@ type LibraryState = {
379
414
  /** Derived from `themes`; rebuilt on first read after each change. */
380
415
  uiVariants?: readonly UiThemeVariant[]
381
416
  listeners: Set<() => void>
417
+ /** Blocks legacy synchronous writes while a coordinated mutation is committing. */
418
+ atomicMutationDepth?: number
419
+ /** One storage observer per shared host, even if source and package graphs load twice. */
420
+ storageEventTarget?: Window
421
+ storageEventListener?: (event: StorageEvent) => void
382
422
  }
383
423
  type LibraryHost = typeof globalThis & { __ADEA_THEME_LIBRARY__?: Partial<LibraryState> }
384
424
  const libraryHost = globalThis as LibraryHost
@@ -389,7 +429,11 @@ function library(): LibraryState {
389
429
  return existing as LibraryState
390
430
  }
391
431
  // A host object written by an older module instance has another shape.
392
- const created: LibraryState = { themes: [], listeners: existing?.listeners ?? new Set() }
432
+ const created: LibraryState = {
433
+ themes: [],
434
+ listeners: existing?.listeners ?? new Set(),
435
+ atomicMutationDepth: 0,
436
+ }
393
437
  libraryHost.__ADEA_THEME_LIBRARY__ = created
394
438
  return created
395
439
  }
@@ -412,14 +456,48 @@ export function customUiVariants(): readonly UiThemeVariant[] {
412
456
  return state.uiVariants
413
457
  }
414
458
 
459
+ function handlePersistentLibraryChange(event: StorageEvent): void {
460
+ if (event.key !== CUSTOM_THEME_LIBRARY_STORAGE_KEY && event.key !== null) return
461
+ // This library uses the same localStorage returned by the preference store.
462
+ // Ignore sessionStorage events and events from any other Storage object.
463
+ const storage = defaultPreferenceStorage()
464
+ if (!storage || event.storageArea !== storage) return
465
+ readCustomThemeLibrary(storage)
466
+ }
467
+
468
+ function observePersistentLibraryChanges(): void {
469
+ const state = library()
470
+ if (state.storageEventTarget || typeof window === 'undefined') return
471
+ const target = window
472
+ const listener = handlePersistentLibraryChange
473
+ state.storageEventTarget = target
474
+ state.storageEventListener = listener
475
+ target.addEventListener('storage', listener)
476
+ }
477
+
415
478
  export function subscribeCustomThemes(listener: () => void): () => void {
479
+ observePersistentLibraryChanges()
416
480
  const { listeners } = library()
417
481
  listeners.add(listener)
418
482
  return () => listeners.delete(listener)
419
483
  }
420
484
 
421
485
  function notifyCustomThemes(): void {
422
- for (const listener of library().listeners) listener()
486
+ const { listeners } = library()
487
+ // Visit each start-of-notification listener at most once. Skip listeners no
488
+ // longer subscribed at their turn; newly added functions wait until next time.
489
+ // oxlint-disable-next-line unicorn/no-useless-spread
490
+ for (const listener of [...listeners]) {
491
+ if (!listeners.has(listener)) continue
492
+ try {
493
+ // Listeners are observers of an already committed library. A broken
494
+ // observer must not turn a successful write into an import failure or
495
+ // keep later observers from seeing it. There is no diagnostics sink here.
496
+ void Promise.resolve(listener()).catch(() => {})
497
+ } catch {
498
+ // The committed library remains authoritative when a listener throws.
499
+ }
500
+ }
423
501
  }
424
502
 
425
503
  function isCustomThemeId(id: string): boolean {
@@ -427,38 +505,34 @@ function isCustomThemeId(id: string): boolean {
427
505
  }
428
506
 
429
507
  /**
430
- * Replace the imported-theme set, persist it, and tell subscribers. A theme whose id
431
- * is not custom-namespaced is namespaced here, so a library file can never shadow a
432
- * catalogue id.
508
+ * Replace the in-memory imported-theme set and tell subscribers. Durable mutations
509
+ * must use `mutateCustomThemeLibrary`; this deprecated synchronous API fails closed
510
+ * when a storage adapter is supplied because it cannot acquire the shared lock.
511
+ *
512
+ * @deprecated Use `mutateCustomThemeLibrary` for persisted read/modify/write operations.
433
513
  */
434
514
  export function setCustomThemes(
435
515
  themes: readonly CustomThemeStored[],
436
516
  storage: AppearanceStorage | undefined
437
517
  ): boolean {
438
- const safe = themes.map((theme) => {
518
+ const state = library()
519
+ // This synchronous compatibility API cannot acquire the shared lock. Reject it
520
+ // during a coordinated write as well as for any durable storage, before it can
521
+ // mutate the shared cache or overwrite a newer v1 record.
522
+ if ((state.atomicMutationDepth ?? 0) > 0) return false
523
+ if (storage) return false
524
+ const safe = namespaceCustomThemes(themes)
525
+ replaceThemes(safe)
526
+ notifyCustomThemes()
527
+ return true
528
+ }
529
+
530
+ function namespaceCustomThemes(themes: readonly CustomThemeStored[]): CustomThemeStored[] {
531
+ return themes.map((theme) => {
439
532
  if (isCustomThemeId(theme.id)) return theme
440
533
  const id = `${CUSTOM_THEME_ID_PREFIX}${theme.id}`
441
534
  return { ...theme, id, variant: { ...theme.variant, id } }
442
535
  })
443
- try {
444
- if (storage) {
445
- const raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
446
- if (raw) {
447
- const result = parseLibrary(raw)
448
- if (result.reason && !preserveLibrary(storage, raw, result.reason))
449
- throw new Error('Library recovery unavailable')
450
- }
451
- }
452
- storage?.setItem(
453
- CUSTOM_THEME_LIBRARY_STORAGE_KEY,
454
- JSON.stringify({ version: CUSTOM_THEME_LIBRARY_VERSION, themes: safe })
455
- )
456
- } catch {
457
- return false
458
- }
459
- replaceThemes(safe)
460
- notifyCustomThemes()
461
- return true
462
536
  }
463
537
 
464
538
  const object = (value: unknown): value is Record<string, unknown> =>
@@ -579,22 +653,306 @@ export function readCustomThemeLibrary(
579
653
  storage: AppearanceStorage | undefined
580
654
  ): readonly CustomThemeStored[] {
581
655
  if (!storage) return []
656
+ const result = tryReadCustomThemeLibrary(storage)
657
+ if (result?.changed) notifyCustomThemes()
658
+ return result?.themes ?? []
659
+ }
660
+
661
+ // Theme records are JSON data. Compare values without allocating serialized
662
+ // copies or treating a different object-key order as a theme change.
663
+ function sameThemeValue(left: unknown, right: unknown): boolean {
664
+ if (Object.is(left, right)) return true
665
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false
666
+ if (Array.isArray(left) || Array.isArray(right)) {
667
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
668
+ if (Object.getPrototypeOf(left) !== Array.prototype) return false
669
+ if (Reflect.ownKeys(left).length !== left.length + 1) return false
670
+ for (let index = 0; index < left.length; index++) {
671
+ const entry = Object.getOwnPropertyDescriptor(left, index)
672
+ if (!entry || !entry.enumerable || !('value' in entry)) return false
673
+ if (!sameThemeValue(entry.value, right[index])) return false
674
+ }
675
+ return true
676
+ }
677
+ if (Object.getPrototypeOf(left) !== Object.prototype) return false
678
+ const leftKeys = Object.keys(left)
679
+ const rightKeys = Object.keys(right)
680
+ if (leftKeys.length !== rightKeys.length || Reflect.ownKeys(left).length !== leftKeys.length)
681
+ return false
682
+ const rightRecord = right as Record<string, unknown>
683
+ return leftKeys.every((key) => {
684
+ const entry = Object.getOwnPropertyDescriptor(left, key)
685
+ return (
686
+ !!entry &&
687
+ 'value' in entry &&
688
+ Object.hasOwn(rightRecord, key) &&
689
+ sameThemeValue(entry.value, rightRecord[key])
690
+ )
691
+ })
692
+ }
693
+
694
+ /** A failed read must not be confused with a successfully read empty library. */
695
+ function tryReadCustomThemeLibrary(
696
+ storage: AppearanceStorage
697
+ ): { themes: readonly CustomThemeStored[]; changed: boolean } | undefined {
698
+ const state = library()
699
+ const previousThemes = state.themes
582
700
  try {
583
701
  // An empty value is no library, not a corrupt one.
584
702
  const raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
585
- if (!raw) return []
586
- const { themes, reason } = parseLibrary(raw)
587
- if (reason) preserveLibrary(storage, raw, reason)
588
- replaceThemes(themes)
589
- return themes
703
+ const { themes, reason } = raw ? parseLibrary(raw) : { themes: [] }
704
+ if (raw && reason) preserveLibrary(storage, raw, reason)
705
+ let changed = true
706
+ try {
707
+ changed = !sameThemeValue(previousThemes, themes)
708
+ } catch {
709
+ // Legacy in-memory values can be unserializable. Publish and notify
710
+ // conservatively after checking that this read is still current.
711
+ }
712
+ // Detect storage or shared-cache changes observed during this read before
713
+ // publishing its snapshot. This is not an atomic cross-context write.
714
+ if (
715
+ storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw ||
716
+ library() !== state ||
717
+ state.themes !== previousThemes
718
+ )
719
+ return undefined
720
+ if (changed) replaceThemes(themes)
721
+ return { themes: changed ? themes : previousThemes, changed }
722
+ } catch {
723
+ return undefined
724
+ }
725
+ }
726
+
727
+ function withIndexedDbMutationLock<T>(name: string, operation: () => T): Promise<T> {
728
+ const factory = globalThis.indexedDB
729
+ if (!factory) return Promise.reject(new Error('IndexedDB is unavailable'))
730
+
731
+ return new Promise<T>((resolve, reject) => {
732
+ const open = factory.open(CUSTOM_THEME_LIBRARY_LOCK_DB, 1)
733
+ open.addEventListener('upgradeneeded', () => {
734
+ if (!open.result.objectStoreNames.contains(CUSTOM_THEME_LIBRARY_LOCK_STORE))
735
+ open.result.createObjectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE)
736
+ })
737
+ open.addEventListener('error', () =>
738
+ reject(open.error ?? new Error('Could not open theme coordination database'))
739
+ )
740
+ open.addEventListener('success', () => {
741
+ const database = open.result
742
+ database.addEventListener('versionchange', () => database.close())
743
+ let transaction: IDBTransaction
744
+ try {
745
+ transaction = database.transaction(CUSTOM_THEME_LIBRARY_LOCK_STORE, 'readwrite')
746
+ } catch (error) {
747
+ database.close()
748
+ reject(error)
749
+ return
750
+ }
751
+
752
+ let result: T
753
+ let ran = false
754
+ let operationError: unknown
755
+ const close = () => database.close()
756
+ transaction.addEventListener('complete', () => {
757
+ close()
758
+ if (operationError !== undefined) reject(operationError)
759
+ else if (ran) resolve(result)
760
+ else reject(new Error('Theme library lock transaction did not run'))
761
+ })
762
+ transaction.addEventListener('abort', () => {
763
+ close()
764
+ // This transaction is only the cross-context mutex; it does not store
765
+ // application data. If the synchronous critical section completed, it
766
+ // already verified the localStorage result before the abort event could
767
+ // run. Report that result rather than claiming the persisted mutation
768
+ // failed after it and its notifications have already committed.
769
+ if (ran) {
770
+ resolve(result)
771
+ return
772
+ }
773
+ reject(
774
+ operationError ?? transaction.error ?? new Error('Theme library lock transaction aborted')
775
+ )
776
+ })
777
+
778
+ try {
779
+ const lockRequest = transaction.objectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE).get(name)
780
+ lockRequest.addEventListener('success', () => {
781
+ try {
782
+ // Keep the read/write transaction active while the synchronous localStorage
783
+ // read/modify/write runs. IndexedDB serializes overlapping transactions
784
+ // across WebViews even where their Web Lock managers are not shared.
785
+ result = operation()
786
+ ran = true
787
+ } catch (error) {
788
+ operationError = error
789
+ transaction.abort()
790
+ }
791
+ })
792
+ } catch (error) {
793
+ operationError = error
794
+ transaction.abort()
795
+ }
796
+ })
797
+ })
798
+ }
799
+
800
+ function browserThemeLibraryAtomicLock(): ThemeLibraryAtomicLock | undefined {
801
+ if (!globalThis.indexedDB) return undefined
802
+ const locks = globalThis.navigator?.locks
803
+ return {
804
+ withExclusiveLock: (name, operation) =>
805
+ locks && typeof locks.request === 'function'
806
+ ? locks.request(name, { mode: 'exclusive' }, () =>
807
+ withIndexedDbMutationLock(name, operation)
808
+ )
809
+ : withIndexedDbMutationLock(name, operation),
810
+ }
811
+ }
812
+
813
+ function mutationFailure<T>(
814
+ reason: ThemeLibraryMutationFailureReason,
815
+ error: string
816
+ ): ThemeLibraryMutationResult<T> {
817
+ return { ok: false, reason, error }
818
+ }
819
+
820
+ /**
821
+ * Coordinate a storage-backed library read/modify/write across cooperating contexts.
822
+ * The callback reads the current v1 record while holding an origin-wide IndexedDB
823
+ * read/write transaction (and a Web Lock where available), then writes and verifies
824
+ * the v1 record before updating this tab's in-memory registry. Older builds and
825
+ * direct `setCustomThemes` storage writes do not acquire these locks and can still
826
+ * race; this API does not claim cross-version atomicity. If IndexedDB is unavailable,
827
+ * durable mutations fail closed.
828
+ */
829
+ export async function mutateCustomThemeLibrary<T>(
830
+ storage: AppearanceStorage | undefined,
831
+ update: (themes: readonly CustomThemeStored[]) => ThemeLibraryMutation<T>,
832
+ options: ThemeLibraryMutationOptions = {}
833
+ ): Promise<ThemeLibraryMutationResult<T>> {
834
+ if (!storage) {
835
+ try {
836
+ const mutation = update(library().themes)
837
+ if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
838
+ const safe = namespaceCustomThemes(mutation.themes)
839
+ if (!setCustomThemes(safe, undefined))
840
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
841
+ return { ok: true, committed: true, value: mutation.value }
842
+ } catch {
843
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
844
+ }
845
+ }
846
+
847
+ const lock = options.lock === undefined ? browserThemeLibraryAtomicLock() : options.lock
848
+ if (!lock) return mutationFailure('atomic_unavailable', CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE)
849
+
850
+ let enteredLock = false
851
+ try {
852
+ return await lock.withExclusiveLock(CUSTOM_THEME_LIBRARY_LOCK_NAME, () => {
853
+ enteredLock = true
854
+ const state = library()
855
+ state.atomicMutationDepth = (state.atomicMutationDepth ?? 0) + 1
856
+ try {
857
+ let raw: string | null
858
+ let themes: readonly CustomThemeStored[]
859
+ try {
860
+ raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
861
+ const parsed = raw ? parseLibrary(raw) : { themes: [] as CustomThemeStored[] }
862
+ themes = parsed.themes
863
+ if (raw && parsed.reason && !preserveLibrary(storage, raw, parsed.reason))
864
+ return mutationFailure(
865
+ 'recovery_unavailable',
866
+ 'The stored theme library could not be preserved, so this change was not saved.'
867
+ )
868
+ // Detect synchronous/reentrant adapters that change the record while it
869
+ // is read. The shared lock covers current builds; this check also exposes
870
+ // adapters and old clients that bypass it without claiming a CAS.
871
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
872
+ return mutationFailure(
873
+ 'changed_during_mutation',
874
+ 'The theme library changed while it was being read. Try again.'
875
+ )
876
+ } catch {
877
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
878
+ }
879
+
880
+ let mutation: ThemeLibraryMutation<T>
881
+ try {
882
+ mutation = update(themes)
883
+ // The updater is synchronous, but an older build can still write
884
+ // localStorage outside this lock while the callback runs. Recheck before
885
+ // committing so a snapshot changed during update is not overwritten.
886
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
887
+ return mutationFailure(
888
+ 'changed_during_mutation',
889
+ 'The theme library changed while this change was being prepared. Try again.'
890
+ )
891
+ } catch {
892
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
893
+ }
894
+ if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
895
+
896
+ const safe = namespaceCustomThemes(mutation.themes)
897
+ const serialized = JSON.stringify({ version: CUSTOM_THEME_LIBRARY_VERSION, themes: safe })
898
+ try {
899
+ storage.setItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY, serialized)
900
+ if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== serialized)
901
+ return mutationFailure(
902
+ 'changed_during_mutation',
903
+ 'The theme library changed while it was being saved. Try again.'
904
+ )
905
+ } catch {
906
+ return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
907
+ }
908
+
909
+ replaceThemes(safe)
910
+ notifyCustomThemes()
911
+ return { ok: true, committed: true, value: mutation.value }
912
+ } finally {
913
+ state.atomicMutationDepth = Math.max(0, (state.atomicMutationDepth ?? 1) - 1)
914
+ }
915
+ })
590
916
  } catch {
591
- return []
917
+ return mutationFailure(
918
+ enteredLock ? 'storage_failed' : 'atomic_unavailable',
919
+ enteredLock ? CUSTOM_THEME_LIBRARY_MUTATION_FAILED : CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE
920
+ )
592
921
  }
593
922
  }
594
923
 
924
+ /** Remove from the latest persisted snapshot, not a possibly stale UI snapshot. */
925
+ export async function removeCustomThemeAtomically(
926
+ id: string,
927
+ storage: AppearanceStorage | undefined,
928
+ options: ThemeLibraryMutationOptions = {}
929
+ ): Promise<ThemeLibraryMutationResult<boolean>> {
930
+ return mutateCustomThemeLibrary(
931
+ storage,
932
+ (themes) => {
933
+ const remaining = themes.filter((theme) => theme.id !== id)
934
+ return {
935
+ themes: remaining,
936
+ value: true,
937
+ // Removing an already-removed id is a successful idempotent operation.
938
+ commit: remaining.length !== themes.length,
939
+ }
940
+ },
941
+ options
942
+ )
943
+ }
944
+
945
+ /**
946
+ * Synchronous legacy removal for the in-memory library. Passing storage fails closed;
947
+ * use `removeCustomThemeAtomically` for persisted removals.
948
+ *
949
+ * @deprecated Use `removeCustomThemeAtomically` for persisted removals.
950
+ */
595
951
  export function removeCustomTheme(id: string, storage: AppearanceStorage | undefined): boolean {
952
+ if (storage) return false
953
+ const themes = library().themes
596
954
  return setCustomThemes(
597
- readCustomThemeLibrary(storage).filter((theme) => theme.id !== id),
955
+ themes.filter((theme) => theme.id !== id),
598
956
  storage
599
957
  )
600
958
  }
@@ -23,7 +23,7 @@ import {
23
23
  export type AppearanceEditor = Readonly<{
24
24
  /** The edited draft, reactive so dialog UI tracks every change. */
25
25
  draft: () => AppearancePreferencesV2
26
- /** True when the draft differs from the snapshot the editor opened with. */
26
+ /** True when the draft differs from the opening snapshot or Reset was requested. */
27
27
  dirty: () => boolean
28
28
  /** True when the draft differs from the shipped defaults. */
29
29
  differsFromDefaults: () => boolean
@@ -35,10 +35,24 @@ export type AppearanceEditor = Readonly<{
35
35
  reset: () => void
36
36
  /** Discard the draft; the committed snapshot is authoritative again. */
37
37
  revert: () => AppearancePreferencesV2
38
+ /** Combine changed draft fields with current committed preferences without mutating the editor. */
39
+ merge: (current: AppearancePreferencesV2) => AppearancePreferencesV2
38
40
  /** Commit the draft and clear the snapshot. */
39
41
  save: () => AppearancePreferencesV2
40
42
  }>
41
43
 
44
+ type ScalarPreference = Exclude<keyof AppearancePreferencesV2, 'version' | 'fonts'>
45
+ // Record exhaustiveness makes a newly added scalar preference require a merge policy.
46
+ const scalarFields = Object.keys({
47
+ mode: true,
48
+ lightThemeId: true,
49
+ darkThemeId: true,
50
+ terminalThemeId: true,
51
+ accent: true,
52
+ surface: true,
53
+ reduceTransparency: true,
54
+ } satisfies Record<ScalarPreference, true>) as ScalarPreference[]
55
+
42
56
  function samePreferences(left: AppearancePreferencesV2, right: AppearancePreferencesV2): boolean {
43
57
  const leftFonts = normalizeAppearanceEditorFontSettings(left.fonts).settings
44
58
  const rightFonts = normalizeAppearanceEditorFontSettings(right.fonts).settings
@@ -47,14 +61,7 @@ function samePreferences(left: AppearancePreferencesV2, right: AppearancePrefere
47
61
  (axis) =>
48
62
  leftFonts[axis].family === rightFonts[axis].family &&
49
63
  leftFonts[axis].size === rightFonts[axis].size
50
- ) &&
51
- left.mode === right.mode &&
52
- left.lightThemeId === right.lightThemeId &&
53
- left.darkThemeId === right.darkThemeId &&
54
- left.terminalThemeId === right.terminalThemeId &&
55
- left.accent === right.accent &&
56
- left.surface === right.surface &&
57
- left.reduceTransparency === right.reduceTransparency
64
+ ) && scalarFields.every((field) => left[field] === right[field])
58
65
  )
59
66
  }
60
67
 
@@ -63,12 +70,14 @@ export function createAppearanceEditor(
63
70
  ): AppearanceEditor {
64
71
  const [draft, setDraft] = createSignal<AppearancePreferencesV2>(committed)
65
72
  const [snapshot, setSnapshot] = createSignal<AppearancePreferencesV2>(committed)
73
+ const [resetAll, setResetAll] = createSignal(false)
66
74
 
67
75
  return {
68
76
  draft,
69
- dirty: () => !samePreferences(draft(), snapshot()),
77
+ dirty: () => resetAll() || !samePreferences(draft(), snapshot()),
70
78
  differsFromDefaults: () => !samePreferences(draft(), defaultAppearancePreferences),
71
79
  open: (value) => {
80
+ setResetAll(false)
72
81
  const normalized = normalizeAppearancePreferences(value).value
73
82
  setSnapshot(normalized)
74
83
  setDraft(normalized)
@@ -80,13 +89,43 @@ export function createAppearanceEditor(
80
89
  setDraft(next)
81
90
  },
82
91
  reset: () => {
92
+ setResetAll(true)
83
93
  setDraft(defaultAppearancePreferences)
84
94
  },
85
95
  revert: () => {
96
+ setResetAll(false)
86
97
  setDraft(snapshot())
87
98
  return snapshot()
88
99
  },
100
+ merge: (current) => {
101
+ const before = snapshot()
102
+ const after = draft()
103
+ if (resetAll()) return after
104
+ const merged = { ...current }
105
+ for (const field of scalarFields) {
106
+ if (before[field] !== after[field]) Object.assign(merged, { [field]: after[field] })
107
+ }
108
+ const originalFonts = normalizeAppearanceEditorFontSettings(before.fonts).settings
109
+ const draftFonts = normalizeAppearanceEditorFontSettings(after.fonts).settings
110
+ const currentFonts = normalizeAppearanceEditorFontSettings(current.fonts).settings
111
+ const fonts = { ...currentFonts }
112
+ for (const axis of ['ui', 'content', 'code'] as const) {
113
+ fonts[axis] = {
114
+ family:
115
+ originalFonts[axis].family === draftFonts[axis].family
116
+ ? currentFonts[axis].family
117
+ : draftFonts[axis].family,
118
+ size:
119
+ originalFonts[axis].size === draftFonts[axis].size
120
+ ? currentFonts[axis].size
121
+ : draftFonts[axis].size,
122
+ }
123
+ }
124
+ if (after.fonts !== undefined || current.fonts !== undefined) merged.fonts = fonts
125
+ return merged
126
+ },
89
127
  save: () => {
128
+ setResetAll(false)
90
129
  setSnapshot(draft())
91
130
  return draft()
92
131
  },