@adea-ai/app-framework 0.25.1 → 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 +8 -3
  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
@@ -4,8 +4,10 @@
4
4
  * Appearance never downloads the importer.
5
5
  *
6
6
  * A newer selection, a closed dialog and a disposed panel each supersede an
7
- * import still in flight: the result of a superseded run is dropped before
8
- * anything is stored, selected or reported.
7
+ * import still in flight: a queued storage mutation checks the current run again
8
+ * under its shared mutation lock before writing. If cancellation occurs during the synchronous
9
+ * storage commit, storage already written is retained but stale status and
10
+ * selection are dropped.
9
11
  */
10
12
  import type { CustomThemeStored } from './custom-theme-library'
11
13
 
@@ -14,16 +16,22 @@ import type { CustomThemeImportResult } from './custom-theme-import'
14
16
  export type ThemeFileImporterHost = Readonly<{
15
17
  /**
16
18
  * Loads the importer and returns the function that imports one file's text.
17
- * It runs after every await so the library it merges into is read fresh.
19
+ * The importer receives a freshness guard so queued writes can be dropped after
20
+ * a newer file or cancellation supersedes them.
18
21
  */
19
- load: () => Promise<(text: string) => CustomThemeImportResult>
22
+ load: () => Promise<
23
+ (
24
+ text: string,
25
+ canCommit: () => boolean
26
+ ) => CustomThemeImportResult | Promise<CustomThemeImportResult>
27
+ >
20
28
  onPending: (pending: boolean) => void
21
29
  onStatus: (message: string) => void
22
30
  onImported: (theme: CustomThemeStored) => void
23
31
  }>
24
32
 
25
33
  type ThemeFileImporter = Readonly<{
26
- importFile: (file: Pick<File, 'text'>) => Promise<void>
34
+ importFile: (file: Pick<File, 'size' | 'text'>) => Promise<void>
27
35
  /** Drops the run in flight, if any, and clears its pending status. */
28
36
  cancel: () => void
29
37
  }>
@@ -33,6 +41,9 @@ export const THEME_IMPORT_UNREADABLE = 'That file could not be read.'
33
41
  export const THEME_IMPORT_UNAVAILABLE =
34
42
  'The theme importer could not be loaded. Reload the app and try again.'
35
43
  export const THEME_IMPORT_FAILED = 'That theme could not be imported.'
44
+ /** A theme is a small JSON document; bound reads before allocating its text. */
45
+ export const MAX_THEME_FILE_BYTES = 1024 * 1024
46
+ export const THEME_IMPORT_TOO_LARGE = 'That theme file is too large. Choose one 1 MiB or smaller.'
36
47
 
37
48
  export function createThemeFileImporter(host: ThemeFileImporterHost): ThemeFileImporter {
38
49
  let latest = 0
@@ -46,17 +57,31 @@ export function createThemeFileImporter(host: ThemeFileImporterHost): ThemeFileI
46
57
  return {
47
58
  cancel() {
48
59
  latest += 1
60
+ const run = latest
49
61
  if (!pending) return
50
62
  settle()
51
- host.onStatus('')
63
+ if (run === latest) host.onStatus('')
52
64
  },
53
65
  async importFile(file) {
54
66
  latest += 1
55
67
  const run = latest
56
68
  const current = () => run === latest
69
+ const size = file.size
70
+ if (!Number.isSafeInteger(size) || size < 0) {
71
+ settle()
72
+ if (current()) host.onStatus(THEME_IMPORT_UNREADABLE)
73
+ return
74
+ }
75
+ if (size > MAX_THEME_FILE_BYTES) {
76
+ settle()
77
+ if (current()) host.onStatus(THEME_IMPORT_TOO_LARGE)
78
+ return
79
+ }
57
80
  pending = true
58
81
  host.onPending(true)
82
+ if (!current()) return
59
83
  host.onStatus(THEME_IMPORT_PENDING)
84
+ if (!current()) return
60
85
 
61
86
  let text: string
62
87
  try {
@@ -64,31 +89,37 @@ export function createThemeFileImporter(host: ThemeFileImporterHost): ThemeFileI
64
89
  } catch {
65
90
  if (!current()) return
66
91
  settle()
67
- host.onStatus(THEME_IMPORT_UNREADABLE)
92
+ if (current()) host.onStatus(THEME_IMPORT_UNREADABLE)
68
93
  return
69
94
  }
70
95
  if (!current()) return
71
96
 
72
- let importText: (text: string) => CustomThemeImportResult
97
+ let importText: (
98
+ text: string,
99
+ canCommit: () => boolean
100
+ ) => CustomThemeImportResult | Promise<CustomThemeImportResult>
73
101
  try {
74
102
  importText = await host.load()
75
103
  } catch {
76
104
  if (!current()) return
77
105
  settle()
78
- host.onStatus(THEME_IMPORT_UNAVAILABLE)
106
+ if (current()) host.onStatus(THEME_IMPORT_UNAVAILABLE)
79
107
  return
80
108
  }
81
109
  if (!current()) return
82
110
 
83
111
  let result: CustomThemeImportResult
84
112
  try {
85
- result = importText(text)
113
+ result = await importText(text, current)
86
114
  } catch {
115
+ if (!current()) return
87
116
  settle()
88
- host.onStatus(THEME_IMPORT_FAILED)
117
+ if (current()) host.onStatus(THEME_IMPORT_FAILED)
89
118
  return
90
119
  }
120
+ if (!current()) return
91
121
  settle()
122
+ if (!current()) return
92
123
  if (!result.ok) {
93
124
  host.onStatus(result.error)
94
125
  return
@@ -97,7 +128,7 @@ export function createThemeFileImporter(host: ThemeFileImporterHost): ThemeFileI
97
128
  `Imported “${result.theme.name}”.` +
98
129
  (result.theme.notes.length > 0 ? ` ${result.theme.notes.join(' ')}` : '')
99
130
  )
100
- host.onImported(result.theme)
131
+ if (current()) host.onImported(result.theme)
101
132
  },
102
133
  }
103
134
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Owns status completions for asynchronous theme-library actions. Starting a newer
3
+ * import/removal invalidates older completions; disposal suppresses all later UI
4
+ * writes while allowing an already-started storage commit to finish.
5
+ */
6
+ export function createThemeLibraryActionFence(writeStatus: (status: string) => void) {
7
+ let revision = 0
8
+ let disposed = false
9
+
10
+ return {
11
+ begin(): number {
12
+ revision += 1
13
+ return revision
14
+ },
15
+ isCurrent(token: number): boolean {
16
+ return !disposed && token === revision
17
+ },
18
+ report(token: number, status: string): boolean {
19
+ if (disposed || token !== revision) return false
20
+ writeStatus(status)
21
+ return true
22
+ },
23
+ dispose(): void {
24
+ disposed = true
25
+ revision += 1
26
+ },
27
+ }
28
+ }
@@ -0,0 +1,118 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import type { Stats } from 'node:fs'
3
+ import { open, type FileHandle } from 'node:fs/promises'
4
+
5
+ const FILE_CHUNK_BYTES = 64 * 1024
6
+
7
+ function sameFile(expected: Stats, actual: Stats): boolean {
8
+ return (
9
+ actual.isFile() &&
10
+ expected.dev === actual.dev &&
11
+ expected.ino === actual.ino &&
12
+ expected.size === actual.size &&
13
+ expected.mtimeMs === actual.mtimeMs &&
14
+ expected.ctimeMs === actual.ctimeMs
15
+ )
16
+ }
17
+
18
+ type AssetFile = Pick<FileHandle, 'close' | 'stat' | 'read'>
19
+ type OpenAsset = (path: string, flags: 'r') => Promise<AssetFile>
20
+
21
+ /**
22
+ * Stream an immutable bundled asset. This is not a snapshot: detected file changes
23
+ * fail the stream, and a read error can surface after response headers have been sent.
24
+ */
25
+ export function createClientAssetStream(
26
+ path: string,
27
+ expected: Stats,
28
+ openAsset: OpenAsset = open
29
+ ): ReadableStream<Uint8Array> {
30
+ let file: AssetFile | undefined
31
+ let opening: Promise<void> | undefined
32
+ let closing: Promise<void> | undefined
33
+ let cancelled = false
34
+ let offset = 0
35
+ const close = (): Promise<void> => {
36
+ if (closing) return closing
37
+ const current = file
38
+ file = undefined
39
+ if (!current) return Promise.resolve()
40
+ const pending = current.close()
41
+ closing = pending
42
+ const clear = () => {
43
+ if (closing === pending) closing = undefined
44
+ }
45
+ void pending.then(clear, clear)
46
+ return pending
47
+ }
48
+ const ensureOpen = (): Promise<void> => {
49
+ if (cancelled || file) return Promise.resolve()
50
+ if (opening) return opening
51
+ const task = (async () => {
52
+ const opened = await openAsset(path, 'r')
53
+ if (cancelled) {
54
+ await opened.close()
55
+ return
56
+ }
57
+ file = opened
58
+ const actual = await opened.stat()
59
+ if (cancelled) {
60
+ await close()
61
+ return
62
+ }
63
+ if (!sameFile(expected, actual)) throw new Error('Client asset changed during request')
64
+ })()
65
+ const pending = task.finally(() => {
66
+ if (opening === pending) opening = undefined
67
+ })
68
+ opening = pending
69
+ return pending
70
+ }
71
+ return new ReadableStream<Uint8Array>(
72
+ {
73
+ async pull(controller) {
74
+ if (cancelled) return
75
+ try {
76
+ await ensureOpen()
77
+ if (cancelled) return
78
+ const current = file
79
+ if (!current) return
80
+ if (offset === expected.size) {
81
+ const actual = await current.stat()
82
+ if (cancelled) return
83
+ if (!sameFile(expected, actual)) throw new Error('Client asset changed during request')
84
+ await close()
85
+ if (cancelled) return
86
+ controller.close()
87
+ return
88
+ }
89
+ const buffer = Buffer.allocUnsafe(Math.min(FILE_CHUNK_BYTES, expected.size - offset))
90
+ const { bytesRead } = await current.read(buffer, 0, buffer.length, offset)
91
+ if (cancelled) return
92
+ if (!bytesRead) throw new Error('Client asset changed during request')
93
+ offset += bytesRead
94
+ if (offset === expected.size) {
95
+ const actual = await current.stat()
96
+ if (cancelled) return
97
+ if (!sameFile(expected, actual)) throw new Error('Client asset changed during request')
98
+ await close()
99
+ if (cancelled) return
100
+ controller.enqueue(buffer.subarray(0, bytesRead))
101
+ controller.close()
102
+ } else controller.enqueue(buffer.subarray(0, bytesRead))
103
+ } catch (error) {
104
+ await close().catch(() => {})
105
+ if (!cancelled) controller.error(error)
106
+ }
107
+ },
108
+ async cancel() {
109
+ cancelled = true
110
+ const pending = opening
111
+ if (pending) await pending.catch(() => {})
112
+ await close()
113
+ },
114
+ },
115
+ // No prefetch: an unconsumed response neither reads the asset nor holds an fd.
116
+ { highWaterMark: 0 }
117
+ )
118
+ }
@@ -1,9 +1,11 @@
1
- import { realpath, stat } from 'node:fs/promises'
1
+ import { open, realpath, stat } from 'node:fs/promises'
2
2
  import { extname, join, posix, relative, resolve, sep } from 'node:path'
3
+ import { createClientAssetStream } from './client-asset-stream'
3
4
 
4
5
  const MIME: Record<string, string> = {
5
6
  '.html': 'text/html',
6
7
  '.js': 'text/javascript',
8
+ '.mjs': 'text/javascript',
7
9
  '.css': 'text/css',
8
10
  '.svg': 'image/svg+xml',
9
11
  '.json': 'application/json',
@@ -17,13 +19,22 @@ export type ClientOptions = {
17
19
  root: string
18
20
  deniedPaths?: readonly string[]
19
21
  transformHtml?: (html: string, request: Request) => string
22
+ /** Stream GET bodies instead of buffered snapshots. Use only for immutable asset roots. */
23
+ streamAssets?: boolean
20
24
  }
21
25
 
22
26
  const unavailable = (status = 404) =>
23
27
  new Response(null, { status, headers: { 'cache-control': 'no-store' } })
24
28
 
25
- /** Serve a bundled SPA without resolving links outside its client root. */
29
+ /** Serve a bundled SPA without resolving links outside its root. */
26
30
  export async function serveClient(request: Request, options: ClientOptions): Promise<Response> {
31
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
32
+ return new Response(null, {
33
+ status: 405,
34
+ headers: { Allow: 'GET, HEAD', 'cache-control': 'no-store' },
35
+ })
36
+ }
37
+
27
38
  let logical: string
28
39
  try {
29
40
  logical = posix.normalize(
@@ -57,19 +68,58 @@ export async function serveClient(request: Request, options: ClientOptions): Pro
57
68
  const folded = logical.toLowerCase()
58
69
  if (folded === '/assets' || folded.startsWith('/assets/')) return unavailable()
59
70
  filePath = join(root, 'index.html')
71
+ metadata = await stat(filePath).catch(() => null)
72
+ if (!metadata?.isFile()) return unavailable()
60
73
  }
61
74
  const physical = await realpath(filePath).catch(() => null)
62
75
  if (!physical) return unavailable()
63
76
  if (!inside(physical)) return unavailable(403)
64
77
  if (denied('/' + relative(root, physical).replaceAll('\\', '/'))) return unavailable()
78
+ const extension = extname(physical).toLowerCase()
79
+ const contentType = MIME[extension] ?? 'application/octet-stream'
80
+ if (request.method === 'HEAD' && !(extension === '.html' && options.transformHtml)) {
81
+ // Open the file to check readability and derive the representation length.
82
+ const file = await open(physical, 'r')
83
+ let size: number
84
+ try {
85
+ const fileMetadata = await file.stat()
86
+ if (!fileMetadata.isFile()) return unavailable()
87
+ size = fileMetadata.size
88
+ } finally {
89
+ await file.close()
90
+ }
91
+ return new Response(null, {
92
+ headers: {
93
+ 'content-type': contentType,
94
+ 'content-length': String(size),
95
+ 'cache-control': 'no-store',
96
+ },
97
+ })
98
+ }
99
+ if (
100
+ options.streamAssets === true &&
101
+ request.method === 'GET' &&
102
+ !(extension === '.html' && options.transformHtml)
103
+ ) {
104
+ // The stream rechecks this snapshot against its opened file before reading.
105
+ return new Response(createClientAssetStream(physical, metadata), {
106
+ headers: {
107
+ 'content-type': contentType,
108
+ 'cache-control': 'no-store',
109
+ 'content-length': String(metadata.size),
110
+ },
111
+ })
112
+ }
113
+
65
114
  let body = new Uint8Array(await Bun.file(physical).arrayBuffer())
66
- if (extname(physical).toLowerCase() === '.html' && options.transformHtml) {
115
+ if (extension === '.html' && options.transformHtml) {
67
116
  body = new TextEncoder().encode(options.transformHtml(new TextDecoder().decode(body), request))
68
117
  }
69
- return new Response(body, {
118
+ return new Response(request.method === 'HEAD' ? null : body, {
70
119
  headers: {
71
- 'content-type': MIME[extname(physical).toLowerCase()] ?? 'application/octet-stream',
120
+ 'content-type': contentType,
72
121
  'cache-control': 'no-store',
122
+ ...(request.method === 'HEAD' ? { 'content-length': String(body.byteLength) } : {}),
73
123
  },
74
124
  })
75
125
  }
@@ -100,12 +100,71 @@ function createNarrow(query: () => string | undefined) {
100
100
  return narrow
101
101
  }
102
102
 
103
+ const nonTextInputTypes = new Set([
104
+ 'button',
105
+ 'checkbox',
106
+ 'color',
107
+ 'file',
108
+ 'hidden',
109
+ 'image',
110
+ 'radio',
111
+ 'range',
112
+ 'reset',
113
+ 'submit',
114
+ ])
115
+
116
+ /** Whether an element or an ancestor in its composed path accepts text editing. */
117
+ function isEditableElementPath(path: readonly EventTarget[]) {
118
+ let inheritedEditable = false
119
+ for (const target of path) {
120
+ if (!(target instanceof Element)) continue
121
+
122
+ if (target instanceof HTMLInputElement) {
123
+ if (!target.disabled && !target.readOnly && !nonTextInputTypes.has(target.type)) return true
124
+ } else if (target instanceof HTMLTextAreaElement) {
125
+ if (!target.disabled && !target.readOnly) return true
126
+ }
127
+
128
+ const contentEditable = target.getAttribute('contenteditable')?.toLowerCase()
129
+ if (contentEditable === 'false') return false
130
+ if (
131
+ contentEditable === '' ||
132
+ contentEditable === 'true' ||
133
+ contentEditable === 'plaintext-only'
134
+ )
135
+ return true
136
+
137
+ if (target instanceof HTMLElement && target.isContentEditable) inheritedEditable = true
138
+ if (target.ownerDocument.designMode?.toLowerCase() === 'on') inheritedEditable = true
139
+ }
140
+
141
+ return inheritedEditable
142
+ }
143
+
144
+ function hasEditableTarget(event: KeyboardEvent) {
145
+ const path = event.composedPath()
146
+ if (path.some((target) => target instanceof Element)) return isEditableElementPath(path)
147
+
148
+ // Synthetic events dispatched at window have no element in their path; use the
149
+ // focused element, following open shadow roots where the browser exposes them.
150
+ const activePath: EventTarget[] = []
151
+ let activeElement: Element | null = document.activeElement
152
+ while (activeElement) {
153
+ activePath.push(activeElement)
154
+ activeElement = activeElement.shadowRoot?.activeElement ?? null
155
+ }
156
+ return isEditableElementPath(activePath)
157
+ }
158
+
103
159
  /** Shared chrome and navigation composition; applications own routes and services. */
104
160
  export function ApplicationShell(props: ApplicationShellProps) {
105
161
  let sidebarToggle: HTMLButtonElement | undefined
106
162
  const narrow = createNarrow(() =>
107
163
  props.drawer ? (props.narrowQuery ?? '(max-width: 799px)') : undefined
108
164
  )
165
+ const sidebarMobile = createNarrow(() =>
166
+ !props.drawer && props.sidebar ? '(max-width: 48rem)' : undefined
167
+ )
109
168
  const [drawerOpen, setDrawerOpen] = createSignal(false)
110
169
  // The drawer mounts (and its chunk loads) the first time the window is narrow, and
111
170
  // stays mounted after that so its close animation and focus return keep working.
@@ -134,7 +193,8 @@ export function ApplicationShell(props: ApplicationShellProps) {
134
193
  !(event.metaKey || event.ctrlKey) ||
135
194
  event.altKey ||
136
195
  event.shiftKey ||
137
- event.key.toLowerCase() !== 'b'
196
+ event.key.toLowerCase() !== 'b' ||
197
+ hasEditableTarget(event)
138
198
  )
139
199
  return
140
200
  event.preventDefault()
@@ -154,10 +214,10 @@ export function ApplicationShell(props: ApplicationShellProps) {
154
214
  props.onSearch()
155
215
  }
156
216
  onMount(() => {
157
- window.addEventListener('keydown', handleSearch, { capture: true })
217
+ window.addEventListener('keydown', handleSearch)
158
218
  window.addEventListener('keydown', handleToggle)
159
219
  onCleanup(() => {
160
- window.removeEventListener('keydown', handleSearch, { capture: true })
220
+ window.removeEventListener('keydown', handleSearch)
161
221
  window.removeEventListener('keydown', handleToggle)
162
222
  })
163
223
  })
@@ -245,13 +305,16 @@ export function ApplicationShell(props: ApplicationShellProps) {
245
305
  <Show when={props.sidebar}>
246
306
  {(sidebar) => (
247
307
  <PixelPane
248
- class="hidden overflow-visible md:block"
308
+ class="overflow-visible"
309
+ hidden={narrow() || sidebarMobile()}
249
310
  width={sidebar().open ? sidebar().width : 0}
250
311
  >
251
- <ContextualSidebar
252
- {...sidebar()}
253
- restoreFocusRef={sidebar().restoreFocusRef ?? (() => sidebarToggle)}
254
- />
312
+ <Show when={!props.drawer || !narrow()}>
313
+ <ContextualSidebar
314
+ {...sidebar()}
315
+ restoreFocusRef={sidebar().restoreFocusRef ?? (() => sidebarToggle)}
316
+ />
317
+ </Show>
255
318
  </PixelPane>
256
319
  )}
257
320
  </Show>
@@ -312,10 +312,10 @@ export function ApplicationUtilities(props: ApplicationUtilitiesProps) {
312
312
  }
313
313
  onMount(() => {
314
314
  onHash()
315
- window.addEventListener('keydown', onKeyDown, { capture: true })
315
+ window.addEventListener('keydown', onKeyDown)
316
316
  window.addEventListener('hashchange', onHash)
317
317
  onCleanup(() => {
318
- window.removeEventListener('keydown', onKeyDown, { capture: true })
318
+ window.removeEventListener('keydown', onKeyDown)
319
319
  window.removeEventListener('hashchange', onHash)
320
320
  })
321
321
  })
@@ -50,6 +50,11 @@ export function mirrorUpdateState(
50
50
  check: () => note(adapter.check()),
51
51
  getStatus: () => note(adapter.getStatus()),
52
52
  install: (expectedVersion) => note(adapter.install(expectedVersion)),
53
+ isDesktopRuntime: () => adapter.isDesktopRuntime(),
54
+ get pollIntervalMs() {
55
+ return adapter.pollIntervalMs
56
+ },
57
+ ...(adapter.openExternal ? { openExternal: (url: string) => adapter.openExternal!(url) } : {}),
53
58
  ...(cancel ? { cancel: () => note(cancel.call(adapter)) } : {}),
54
59
  }
55
60
  }
@@ -16,13 +16,14 @@ import {
16
16
  getAccent as accentPresetById,
17
17
  } from '@adea-ai/ui/lib/accent-presets'
18
18
  import { isThemeAccentId } from '@adea-ai/ui/lib/themes'
19
+ import { defaultPreferenceStorage } from '@adea-ai/ui/lib/preference-store'
19
20
  import {
20
21
  preferencesFromSelection,
21
22
  type AppearancePreferencesV2,
22
23
  } from '../appearance/appearance-preferences'
23
24
  import {
24
25
  readCustomThemeLibrary,
25
- removeCustomTheme,
26
+ removeCustomThemeAtomically,
26
27
  subscribeCustomThemes,
27
28
  } from '../appearance/custom-theme-library'
28
29
  import { useTheme } from '../appearance/appearance-host'
@@ -40,6 +41,7 @@ import { themeAccentsForRecords } from '@adea-ai/ui/lib/theme-projection'
40
41
  import { draftVariants } from '../appearance/composition'
41
42
  import { createAppearanceEditor } from '../appearance/editor'
42
43
  import { createThemeFileImporter } from '../appearance/theme-file-importer'
44
+ import { createThemeLibraryActionFence } from '../appearance/theme-library-action-fence'
43
45
  import {
44
46
  allThemeRecords,
45
47
  appearanceThemeForPreview,
@@ -94,12 +96,12 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
94
96
  const miniatures = createMemo(() => draftVariants(editor.draft()))
95
97
  // Imported themes: refreshed through the registry subscription so the
96
98
  // picker and this dialog track imports and removals without prop drilling.
97
- const [library, setLibrary] = createSignal(
98
- readCustomThemeLibrary(typeof window === 'undefined' ? undefined : window.localStorage)
99
- )
99
+ const [library, setLibrary] = createSignal(readCustomThemeLibrary(defaultPreferenceStorage()))
100
100
  onMount(() => {
101
- setLibrary(readCustomThemeLibrary(window.localStorage))
102
- onCleanup(subscribeCustomThemes(() => setLibrary(readCustomThemeLibrary(window.localStorage))))
101
+ setLibrary(readCustomThemeLibrary(defaultPreferenceStorage()))
102
+ onCleanup(
103
+ subscribeCustomThemes(() => setLibrary(readCustomThemeLibrary(defaultPreferenceStorage())))
104
+ )
103
105
  })
104
106
  // Reading the library signal here ties the editor's theme list to imports
105
107
  // and removals: the record projection itself has no reactive dependency.
@@ -109,29 +111,53 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
109
111
  }
110
112
  const [importStatus, setImportStatus] = createSignal('')
111
113
  const [importPending, setImportPending] = createSignal(false)
114
+ const themeActionFence = createThemeLibraryActionFence(setImportStatus)
115
+ let importActionToken = 0
112
116
  // The parsing and projection code loads when a file is chosen, not when the
113
117
  // editor opens. A newer file, a closed dialog or an unmounted panel drops an
114
- // import still in flight before it stores or selects anything.
118
+ // import still in flight. The locked mutation rechecks the run before commit;
119
+ // if cancellation happens during the synchronous storage commit, that write is
120
+ // retained but the superseded run does not report or select the theme.
115
121
  const themeImporter = createThemeFileImporter({
116
122
  load: async () => {
117
- const { importCustomTheme } = await import('../appearance/custom-theme-import')
118
- return (text) =>
119
- importCustomTheme(text, window.localStorage, readCustomThemeLibrary(window.localStorage))
123
+ const { importCustomThemeAtomically } = await import('../appearance/custom-theme-import')
124
+ return (text, canCommit) => {
125
+ const storage = defaultPreferenceStorage()
126
+ if (!storage)
127
+ return {
128
+ ok: false,
129
+ error: 'The theme could not be saved. Check your storage and try again.',
130
+ }
131
+ return importCustomThemeAtomically(text, storage, { canCommit })
132
+ }
133
+ },
134
+ onPending: (pending) => {
135
+ if (themeActionFence.isCurrent(importActionToken)) setImportPending(pending)
120
136
  },
121
- onPending: setImportPending,
122
- onStatus: setImportStatus,
137
+ onStatus: (status) => themeActionFence.report(importActionToken, status),
123
138
  // Select the imported theme for its appearance so the user sees it land.
124
- onImported: (theme) =>
125
- setDraft(
126
- theme.appearance === 'dark' ? { darkThemeId: theme.id } : { lightThemeId: theme.id }
127
- ),
139
+ onImported: (theme) => {
140
+ if (!themeActionFence.isCurrent(importActionToken)) return
141
+ setDraft(theme.appearance === 'dark' ? { darkThemeId: theme.id } : { lightThemeId: theme.id })
142
+ },
143
+ })
144
+ onCleanup(() => {
145
+ themeActionFence.dispose()
146
+ themeImporter.cancel()
128
147
  })
129
- onCleanup(themeImporter.cancel)
130
148
  const closeLibrary = () => {
149
+ const action = themeActionFence.begin()
131
150
  themeImporter.cancel()
151
+ setImportPending(false)
152
+ themeActionFence.report(action, '')
132
153
  setLibraryOpen(false)
133
154
  }
134
155
 
156
+ const importThemeFile = (file: File) => {
157
+ importActionToken = themeActionFence.begin()
158
+ void themeImporter.importFile(file)
159
+ }
160
+
135
161
  const themeAccentOptions = createMemo(() => {
136
162
  const draft = editor.draft()
137
163
  const records = themes()
@@ -229,8 +255,9 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
229
255
  props.popover?.onClose()
230
256
  return
231
257
  }
232
- const committed = editor.save()
258
+ const committed = editor.merge(preferencesFromSelection(appearance.selection()))
233
259
  appearance.update(committed)
260
+ editor.open(committed)
234
261
  appearance.preview(undefined)
235
262
  props.popover?.onClose()
236
263
  }
@@ -372,7 +399,7 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
372
399
  onChange={(event) => {
373
400
  const file = event.currentTarget.files?.[0]
374
401
  event.currentTarget.value = ''
375
- if (file) void themeImporter.importFile(file)
402
+ if (file) importThemeFile(file)
376
403
  }}
377
404
  />
378
405
  Import a theme file (.json)
@@ -396,16 +423,21 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
396
423
  type="button"
397
424
  size="sm"
398
425
  variant="ghost"
399
- onClick={() => {
400
- const removed = removeCustomTheme(
401
- theme.id,
402
- typeof window === 'undefined' ? undefined : window.localStorage
403
- )
404
- setImportStatus(
405
- removed
406
- ? ''
407
- : 'The theme could not be removed. Check your storage and try again.'
408
- )
426
+ onClick={async () => {
427
+ const action = themeActionFence.begin()
428
+ themeImporter.cancel()
429
+ setImportPending(false)
430
+ themeActionFence.report(action, '')
431
+ const storage = defaultPreferenceStorage()
432
+ if (!storage) {
433
+ themeActionFence.report(
434
+ action,
435
+ 'The theme could not be removed. Check your storage and try again.'
436
+ )
437
+ return
438
+ }
439
+ const result = await removeCustomThemeAtomically(theme.id, storage)
440
+ themeActionFence.report(action, result.ok ? '' : result.error)
409
441
  }}
410
442
  >
411
443
  Remove