@adea-ai/app-framework 0.34.0 → 0.35.1

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 (40) hide show
  1. package/README.md +10 -10
  2. package/dist/desktop/desktop-client.d.ts +5 -0
  3. package/dist/desktop/desktop-client.js +12 -3
  4. package/dist/framework-source.json +1 -1
  5. package/dist/installer/installer-upgrade-command.js +1 -1
  6. package/dist/native/app-bundle.d.ts +14 -2
  7. package/dist/native/app-bundle.js +18 -5
  8. package/dist/native/desktop-build.d.ts +63 -0
  9. package/dist/native/desktop-build.js +119 -0
  10. package/dist/native/native-utilities.d.ts +18 -0
  11. package/dist/native/native-utilities.js +22 -1
  12. package/dist/native/sidecar-services.d.ts +5 -0
  13. package/dist/native/sidecar-services.js +10 -4
  14. package/dist/release/local-release.js +1 -1
  15. package/dist/shell/app-utilities.d.ts +1 -0
  16. package/dist/shell/app-utilities.js +2 -1
  17. package/dist/shell/media-query.d.ts +8 -0
  18. package/dist/shell/media-query.js +51 -0
  19. package/dist/updates/desktop-updater.js +1 -1
  20. package/dist/updates/release-version.d.ts +11 -0
  21. package/dist/updates/release-version.js +23 -1
  22. package/dist/updates/update-adapter.d.ts +38 -1
  23. package/dist/updates/update-adapter.js +121 -1
  24. package/dist/updates/update-channel-store.js +1 -1
  25. package/dist/updates/update-discovery.js +1 -1
  26. package/dist/updates/update-handoff-plan.js +1 -1
  27. package/dist/updates/update-manager.js +1 -1
  28. package/dist/views/update-surface.js +2 -2
  29. package/package.json +27 -2
  30. package/src/native/electrobun-types.d.ts +87 -0
  31. package/src/shell/app-utilities.tsx +1 -0
  32. package/src/shell/media-query.ts +59 -0
  33. package/src/updates/release-version.ts +33 -0
  34. package/src/updates/update-adapter.ts +168 -1
  35. package/templates/application/electrobun.config.ts +6 -2
  36. package/templates/application/scripts/app-version.ts +2 -8
  37. package/templates/application/scripts/build-desktop.ts +9 -36
  38. package/templates/application/src/bun/index.ts +5 -16
  39. package/templates/application/tsconfig.json +1 -1
  40. package/templates/application/src/electrobun.d.ts +0 -27
@@ -1,5 +1,5 @@
1
1
  import type { UpdateAdapter, UpdateChannel, UpdateState } from '@adea-ai/ui/components/composites/update-dialog';
2
- import { type NativeUpdateSnapshotOf } from './update-state';
2
+ import { type NativeUpdateSnapshotOf, type NativeUpdateState } from './update-state';
3
3
  export type { UpdateAdapter, UpdateChannel, UpdateState };
4
4
  /** Channel persistence as a `read`/`persist` pair. */
5
5
  export type UpdateChannelStore = Readonly<{
@@ -46,3 +46,40 @@ export declare function nativeUpdateAdapter(native: NativeUpdateAdapter | (() =>
46
46
  }): UpdateAdapter;
47
47
  /** The adapter for a build with no installer: the dialog explains updates are desktop-only. */
48
48
  export declare function browserUpdateAdapter(currentVersion?: string): UpdateAdapter;
49
+ /** Every phase the shared update dialog understands, in state-machine order. */
50
+ export declare const UPDATE_PHASES: readonly ["idle", "checking", "current", "unavailable", "available", "downloading", "installing", "cancelling", "cancelled", "installed", "failed"];
51
+ export declare function isUpdatePhase(value: unknown): value is UpdateState['phase'];
52
+ /** Phases in which an update occupies the app: offered, in flight, or awaiting the restart. */
53
+ export declare const UPDATE_PENDING_PHASES: readonly ["available", "downloading", "installing", "installed"];
54
+ /** Whether a phase should raise a pending-update badge. */
55
+ export declare function isUpdatePending(phase: string | null | undefined): boolean;
56
+ /** The snapshot the `desktop_update_*` services answer with. */
57
+ export type DesktopUpdateStatus = NativeUpdateState<UpdateState['phase']>;
58
+ /**
59
+ * Check a `desktop_update_*` answer at the boundary, so a malformed reply fails here instead of
60
+ * inside the dialog. `release_notes` may be absent (older hosts), and reads as null.
61
+ */
62
+ export declare function parseDesktopUpdateStatus(value: unknown): DesktopUpdateStatus;
63
+ /** Call a desktop service by name, as the app's desktop client does. */
64
+ export type DesktopServiceInvoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
65
+ /**
66
+ * The shared dialog's adapter for the framework desktop updater (`registerUpdateServices`).
67
+ * Every answer is checked with `parseDesktopUpdateStatus` and reported to `onStatus`, so a
68
+ * pending-update badge can follow the same updater. `confirmInstall` may decline an install.
69
+ * Because the dialog keeps polling while that question is open, an install runs only if the
70
+ * updater still offers the version; otherwise the current state is returned so the user can
71
+ * decide again. A rejected install re-reads the status before rethrowing, since the updater
72
+ * may have dropped its offer.
73
+ */
74
+ export declare function desktopUpdateAdapter(invoke: DesktopServiceInvoke, options?: {
75
+ confirmInstall?(version: string): boolean | Promise<boolean>;
76
+ openExternal?(url: string): Promise<void>;
77
+ onStatus?(status: DesktopUpdateStatus): void;
78
+ isDesktopRuntime?(): boolean;
79
+ /** Polling interval during native work; default 500 ms. */
80
+ pollIntervalMs?: number;
81
+ /** Show the available release's notes; default true. */
82
+ releaseNotes?: boolean;
83
+ }): UpdateAdapter;
84
+ /** The `desktop_update_channel*` services as the update surface's channel service. */
85
+ export declare function desktopUpdateChannelService(invoke: DesktopServiceInvoke): UpdateChannelService;
@@ -1,3 +1,4 @@
1
+ import { isUpdateChannel } from "./release-version.js";
1
2
  import { toUpdateState } from "./update-state.js";
2
3
  // src/updates/update-adapter.ts
3
4
  /** Normalize either channel shape to `read`/`persist`. */
@@ -88,4 +89,123 @@ function browserUpdateAdapter(currentVersion = "") {
88
89
  isDesktopRuntime: () => false
89
90
  };
90
91
  }
91
- export { browserUpdateAdapter, mirrorUpdateState, nativeUpdateAdapter, updateChannelStore, updateStateFromNative };
92
+ /** Every phase the shared update dialog understands, in state-machine order. */
93
+ var UPDATE_PHASES = [
94
+ "idle",
95
+ "checking",
96
+ "current",
97
+ "unavailable",
98
+ "available",
99
+ "downloading",
100
+ "installing",
101
+ "cancelling",
102
+ "cancelled",
103
+ "installed",
104
+ "failed"
105
+ ];
106
+ function isUpdatePhase(value) {
107
+ return UPDATE_PHASES.includes(value);
108
+ }
109
+ /** Phases in which an update occupies the app: offered, in flight, or awaiting the restart. */
110
+ var UPDATE_PENDING_PHASES = [
111
+ "available",
112
+ "downloading",
113
+ "installing",
114
+ "installed"
115
+ ];
116
+ /** Whether a phase should raise a pending-update badge. */
117
+ function isUpdatePending(phase) {
118
+ return UPDATE_PENDING_PHASES.includes(phase);
119
+ }
120
+ var isText = (value) => typeof value === "string";
121
+ var isNullableText = (value) => value === null || isText(value);
122
+ var isByteCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
123
+ /**
124
+ * Check a `desktop_update_*` answer at the boundary, so a malformed reply fails here instead of
125
+ * inside the dialog. `release_notes` may be absent (older hosts), and reads as null.
126
+ */
127
+ function parseDesktopUpdateStatus(value) {
128
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid desktop update status");
129
+ const record = value;
130
+ const releaseNotes = record.release_notes ?? null;
131
+ if (!isText(record.current_version) || !isNullableText(record.available_version) || !isUpdatePhase(record.phase) || !isText(record.changelog) || !isNullableText(releaseNotes) || !isNullableText(record.release_date) || !isByteCount(record.downloaded_bytes) || record.total_bytes !== null && !isByteCount(record.total_bytes) || !isNullableText(record.error) || !isText(record.github_url) || typeof record.restart_required !== "boolean") throw new Error("Invalid desktop update status");
132
+ return {
133
+ phase: record.phase,
134
+ current_version: record.current_version,
135
+ available_version: record.available_version,
136
+ changelog: record.changelog,
137
+ release_notes: releaseNotes,
138
+ release_date: record.release_date,
139
+ downloaded_bytes: record.downloaded_bytes,
140
+ total_bytes: record.total_bytes,
141
+ error: record.error,
142
+ github_url: record.github_url,
143
+ restart_required: record.restart_required
144
+ };
145
+ }
146
+ /** Phases from which an offered version may be installed. */
147
+ var INSTALLABLE_PHASES = [
148
+ "available",
149
+ "failed",
150
+ "cancelled"
151
+ ];
152
+ /**
153
+ * The shared dialog's adapter for the framework desktop updater (`registerUpdateServices`).
154
+ * Every answer is checked with `parseDesktopUpdateStatus` and reported to `onStatus`, so a
155
+ * pending-update badge can follow the same updater. `confirmInstall` may decline an install.
156
+ * Because the dialog keeps polling while that question is open, an install runs only if the
157
+ * updater still offers the version; otherwise the current state is returned so the user can
158
+ * decide again. A rejected install re-reads the status before rethrowing, since the updater
159
+ * may have dropped its offer.
160
+ */
161
+ function desktopUpdateAdapter(invoke, options = {}) {
162
+ let latest;
163
+ const view = (status) => toUpdateState(status, { includeReleaseNotes: options.releaseNotes !== false });
164
+ const call = async (command, args) => {
165
+ const status = parseDesktopUpdateStatus(await invoke(command, args));
166
+ latest = status;
167
+ try {
168
+ options.onStatus?.(status);
169
+ } catch {}
170
+ return status;
171
+ };
172
+ const read = () => call("desktop_update_status");
173
+ return {
174
+ getStatus: async () => view(await read()),
175
+ check: async () => view(await call("desktop_update_check")),
176
+ install: async (expectedVersion) => {
177
+ if (options.confirmInstall && !await options.confirmInstall(expectedVersion)) return view(latest ?? await read());
178
+ const offered = latest ?? await read();
179
+ if (offered.available_version !== expectedVersion || !INSTALLABLE_PHASES.includes(offered.phase)) return view(await read());
180
+ try {
181
+ return view(await call("desktop_update_install", {
182
+ expectedVersion,
183
+ approved: true,
184
+ restart: true
185
+ }));
186
+ } catch (error) {
187
+ await read().catch(() => {});
188
+ throw error;
189
+ }
190
+ },
191
+ cancel: async () => view(await call("desktop_update_cancel")),
192
+ isDesktopRuntime: () => options.isDesktopRuntime?.() ?? true,
193
+ pollIntervalMs: options.pollIntervalMs ?? 500,
194
+ ...options.openExternal ? { openExternal: options.openExternal } : {}
195
+ };
196
+ }
197
+ /** The `desktop_update_channel*` services as the update surface's channel service. */
198
+ function desktopUpdateChannelService(invoke) {
199
+ return {
200
+ async channel() {
201
+ const channel = await invoke("desktop_update_channel");
202
+ return isUpdateChannel(channel) ? channel : "stable";
203
+ },
204
+ async setChannel(channel) {
205
+ const saved = await invoke("desktop_update_channel_save", { channel });
206
+ if (!isUpdateChannel(saved)) throw new Error("Invalid update channel");
207
+ return saved;
208
+ }
209
+ };
210
+ }
211
+ export { UPDATE_PENDING_PHASES, UPDATE_PHASES, browserUpdateAdapter, desktopUpdateAdapter, desktopUpdateChannelService, isUpdatePending, isUpdatePhase, mirrorUpdateState, nativeUpdateAdapter, parseDesktopUpdateStatus, updateChannelStore, updateStateFromNative };
@@ -1,7 +1,7 @@
1
+ import { isUpdateChannel } from "./release-version.js";
1
2
  import { errorCode } from "../app/value-guards.js";
2
3
  import { isCanonicalPath } from "../native/canonical-path.js";
3
4
  import { createSerialQueue } from "../app/serial-queue.js";
4
- import { isUpdateChannel } from "./release-version.js";
5
5
  import { openUnchangedFile, sameFile } from "./stable-file.js";
6
6
  import { lstat, open, realpath, rename, unlink } from "node:fs/promises";
7
7
  import { join } from "node:path";
@@ -1,6 +1,6 @@
1
+ import { versionLessThan } from "./release-version.js";
1
2
  import { isRepositorySlug, verifyReleaseDescriptor } from "./signed-release.js";
2
3
  import { parseFeedRelease, parseReleaseLedger } from "./release-feed.js";
3
- import { versionLessThan } from "./release-version.js";
4
4
  import { fetchReleaseLocation, readReleaseBytes, readReleaseJson } from "./release-location.js";
5
5
  import { createHash } from "node:crypto";
6
6
  // src/updates/update-discovery.ts
@@ -1,7 +1,7 @@
1
+ import { versionLessThan } from "./release-version.js";
1
2
  import { isCanonicalPath } from "../native/canonical-path.js";
2
3
  import { assertPortableAppName } from "../installer/installer-layout.js";
3
4
  import { isVerifiedReleaseForTrust } from "./signed-release.js";
4
- import { versionLessThan } from "./release-version.js";
5
5
  import { basename } from "node:path";
6
6
  // src/updates/update-handoff-plan.ts
7
7
  /** Validate an explicitly approved update and its intended installation. This plan does not move files or launch a helper. */
@@ -1,5 +1,5 @@
1
- import { isVerifiedReleaseForTrust } from "./signed-release.js";
2
1
  import { versionLessThan } from "./release-version.js";
2
+ import { isVerifiedReleaseForTrust } from "./signed-release.js";
3
3
  import { discoverSignedRelease } from "./update-discovery.js";
4
4
  import { downloadVerifiedRelease } from "./update-download.js";
5
5
  import { selectUpdateDownloadDiscard } from "./update-download-cleanup.js";
@@ -1,4 +1,4 @@
1
- import { browserUpdateAdapter, mirrorUpdateState, nativeUpdateAdapter, updateChannelStore, updateStateFromNative } from "../updates/update-adapter.js";
1
+ import { UPDATE_PENDING_PHASES, UPDATE_PHASES, browserUpdateAdapter, desktopUpdateAdapter, desktopUpdateChannelService, isUpdatePending, isUpdatePhase, mirrorUpdateState, nativeUpdateAdapter, parseDesktopUpdateStatus, updateChannelStore, updateStateFromNative } from "../updates/update-adapter.js";
2
2
  import { createComponent } from "solid-js/web";
3
3
  import { createMemo } from "solid-js";
4
4
  import { UpdateChannelControl, UpdateDialog } from "@adea-ai/ui/components/composites/update-dialog";
@@ -61,4 +61,4 @@ function ApplicationUpdateSurface(props) {
61
61
  }
62
62
  });
63
63
  }
64
- export { ApplicationUpdateSurface, browserUpdateAdapter, mirrorUpdateState, nativeUpdateAdapter, updateChannelStore, updateStateFromNative };
64
+ export { ApplicationUpdateSurface, UPDATE_PENDING_PHASES, UPDATE_PHASES, browserUpdateAdapter, desktopUpdateAdapter, desktopUpdateChannelService, isUpdatePending, isUpdatePhase, mirrorUpdateState, nativeUpdateAdapter, parseDesktopUpdateStatus, updateChannelStore, updateStateFromNative };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/app-framework",
3
- "version": "0.34.0",
3
+ "version": "0.35.1",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -34,6 +34,7 @@
34
34
  "src/desktop/client-response-lifecycle.ts",
35
35
  "src/desktop/client-asset-manifest.ts",
36
36
  "src/native/*.patch",
37
+ "src/native/electrobun-types.d.ts",
37
38
  "src/native/renderer-profile.ts",
38
39
  "src/native/window-options.ts",
39
40
  "src/shell",
@@ -56,7 +57,12 @@
56
57
  },
57
58
  "./update-state": "./src/updates/update-state.ts",
58
59
  "./window-options": "./src/native/window-options.ts",
59
- "./release-version": "./src/updates/release-version.ts",
60
+ "./release-version": {
61
+ "types": "./dist/updates/release-version.d.ts",
62
+ "bun": "./src/updates/release-version.ts",
63
+ "solid": "./src/updates/release-version.ts",
64
+ "import": "./dist/updates/release-version.js"
65
+ },
60
66
  "./app-shell": {
61
67
  "types": "./dist/shell/app-shell.d.ts",
62
68
  "solid": "./src/shell/app-shell.tsx",
@@ -258,6 +264,18 @@
258
264
  "types": "./dist/release/release-steps.d.ts",
259
265
  "import": "./dist/release/release-steps.js"
260
266
  },
267
+ "./release-feed": {
268
+ "types": "./dist/updates/release-feed.d.ts",
269
+ "import": "./dist/updates/release-feed.js"
270
+ },
271
+ "./release-location": {
272
+ "types": "./dist/updates/release-location.d.ts",
273
+ "import": "./dist/updates/release-location.js"
274
+ },
275
+ "./update-process-liveness": {
276
+ "types": "./dist/updates/update-process-liveness.d.ts",
277
+ "import": "./dist/updates/update-process-liveness.js"
278
+ },
261
279
  "./update-manager": {
262
280
  "types": "./dist/updates/update-manager.d.ts",
263
281
  "import": "./dist/updates/update-manager.js"
@@ -318,6 +336,13 @@
318
336
  "types": "./dist/native/native-utilities.d.ts",
319
337
  "import": "./dist/native/native-utilities.js"
320
338
  },
339
+ "./desktop-build": {
340
+ "types": "./dist/native/desktop-build.d.ts",
341
+ "import": "./dist/native/desktop-build.js"
342
+ },
343
+ "./electrobun-types": {
344
+ "types": "./src/native/electrobun-types.d.ts"
345
+ },
321
346
  "./app-bundle": {
322
347
  "types": "./dist/native/app-bundle.d.ts",
323
348
  "import": "./dist/native/app-bundle.js"
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Ambient declarations for the Electrobun 2.0.5 main-process APIs framework applications use.
3
+ * Electrobun ships its runtime without type definitions, so a host declares the surface it
4
+ * calls. Reference this file instead of keeping a copy: add
5
+ * `"@adea-ai/app-framework/electrobun-types"` to `compilerOptions.types`, or
6
+ * `/// <reference types="@adea-ai/app-framework/electrobun-types" />` to a declaration file.
7
+ * Every member was checked against the pinned 2.0.5 API.
8
+ */
9
+ declare module 'electrobun/bun' {
10
+ import type { NativeWindow, SecureWindowOptions } from '@adea-ai/app-framework/secure-window'
11
+ import type { ApplicationMenuItem } from '@adea-ai/app-framework/application-menu'
12
+
13
+ /** Window options for a host that loads its URL itself rather than through `createSecureWindow`. */
14
+ export type BrowserWindowOptions = {
15
+ title?: string
16
+ titleBarStyle?: 'default' | 'hiddenInset'
17
+ /** Nudges the native traffic lights from their hiddenInset position. */
18
+ trafficLightOffset?: { x: number; y: number }
19
+ /** A see-through window background, set at creation only (there is no runtime setter). */
20
+ transparent?: boolean
21
+ renderer?: 'native' | 'cef'
22
+ url?: string
23
+ frame?: { width?: number; height?: number; x?: number; y?: number }
24
+ }
25
+
26
+ /**
27
+ * The view a window creates. The constructor stores `options.partition` and then calls
28
+ * `init()`, which passes `this.partition` to native creation; `constructPartitionedWindow`
29
+ * relies on that order.
30
+ */
31
+ export class BrowserView {
32
+ id: number
33
+ renderer: 'native' | 'cef'
34
+ partition: string | null
35
+ init(this: { partition: string | null }): unknown
36
+ }
37
+
38
+ export class BrowserWindow implements NativeWindow {
39
+ constructor(options: SecureWindowOptions | BrowserWindowOptions)
40
+ webview: NativeWindow['webview'] & BrowserView
41
+ on(event: 'close' | 'focus' | 'blur', handler: () => void): unknown
42
+ close(): unknown
43
+ /** Brings the window forward. */
44
+ activate(): void
45
+ }
46
+
47
+ /**
48
+ * The main-process app handle. `open-url` passes the event data (`{ url }`) and returns a
49
+ * disposer; the URL schemes themselves are declared in `electrobun.config.ts`.
50
+ */
51
+ export const app: {
52
+ on(name: 'open-url', handler: (payload: { url?: unknown }) => void): () => void
53
+ }
54
+
55
+ /** The native application menu (macOS and Windows). */
56
+ export const ApplicationMenu: {
57
+ setApplicationMenu(menu: ApplicationMenuItem[]): void
58
+ /** A non-role item was chosen; `event.data.action` is the item's `action`. */
59
+ on(name: 'application-menu-clicked', handler: (event: unknown) => void): void
60
+ }
61
+
62
+ export const Utils: {
63
+ paths: { userData: string }
64
+ openExternal(url: string): boolean
65
+ /** Quits the app; the update handoff calls it once the helper is armed. */
66
+ quit(): void
67
+ /** Native open panel; resolves the picked absolute paths, `[]` when the user cancels. */
68
+ openFileDialog(options?: {
69
+ startingFolder?: string
70
+ allowedFileTypes?: string
71
+ canChooseFiles?: boolean
72
+ canChooseDirectory?: boolean
73
+ allowsMultipleSelection?: boolean
74
+ }): Promise<string[]>
75
+ showNotification(request: { title: string; body: string; silent?: boolean }): void
76
+ /** Native modal message box; resolves the chosen button index, or `cancelId` on dismissal. */
77
+ showMessageBox(options: {
78
+ type?: 'info' | 'warning' | 'error' | 'question'
79
+ title?: string
80
+ message?: string
81
+ detail?: string
82
+ buttons?: string[]
83
+ defaultId?: number
84
+ cancelId?: number
85
+ }): Promise<{ response: number }>
86
+ }
87
+ }
@@ -30,6 +30,7 @@ import { hasEditableKeyboardTarget } from './keyboard-target'
30
30
  import { browserUpdateAdapter, type UpdateChannelSource } from '../updates/update-adapter'
31
31
 
32
32
  export * from './shortcut-platform'
33
+ export { createMediaQuery, DEFAULT_NARROW_QUERY } from './media-query'
33
34
 
34
35
  const AppearancePanel = lazy(() =>
35
36
  import('@adea-ai/ui/components/theme').then((module) => ({ default: module.AppearancePanel }))
@@ -0,0 +1,59 @@
1
+ import { createEffect, createSignal, onCleanup } from 'solid-js'
2
+
3
+ /** When the application shell counts a window as narrow. */
4
+ export const DEFAULT_NARROW_QUERY = '(max-width: 799px)'
5
+
6
+ type SharedQuery = {
7
+ list: MediaQueryList
8
+ subscribers: Set<(matches: boolean) => void>
9
+ stop(): void
10
+ }
11
+
12
+ // One MediaQueryList listener per query text, shared by every subscriber and removed with
13
+ // the last of them.
14
+ const shared = new Map<string, SharedQuery>()
15
+
16
+ const supported = () => typeof window !== 'undefined' && typeof window.matchMedia === 'function'
17
+
18
+ function subscribe(query: string, subscriber: (matches: boolean) => void): () => void {
19
+ let entry = shared.get(query)
20
+ if (!entry) {
21
+ const list = window.matchMedia(query)
22
+ const subscribers = new Set<(matches: boolean) => void>()
23
+ // Read the list rather than the event, which some environments omit.
24
+ const notify = () => {
25
+ for (const notifySubscriber of subscribers) notifySubscriber(list.matches)
26
+ }
27
+ list.addEventListener('change', notify)
28
+ entry = { list, subscribers, stop: () => list.removeEventListener('change', notify) }
29
+ shared.set(query, entry)
30
+ }
31
+ const current = entry
32
+ current.subscribers.add(subscriber)
33
+ subscriber(current.list.matches)
34
+ return () => {
35
+ current.subscribers.delete(subscriber)
36
+ if (current.subscribers.size > 0 || shared.get(query) !== current) return
37
+ current.stop()
38
+ shared.delete(query)
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Reactive `matchMedia`. Components watching the same query share one listener. The query
44
+ * may be reactive and the subscription follows it; an empty or absent query, or a runtime
45
+ * without `matchMedia`, reads as not matching.
46
+ */
47
+ export function createMediaQuery(query: string | (() => string | undefined)): () => boolean {
48
+ const text = typeof query === 'function' ? query : () => query
49
+ const [matches, setMatches] = createSignal(false)
50
+ createEffect(() => {
51
+ const value = text()
52
+ if (!value || !supported()) {
53
+ setMatches(false)
54
+ return
55
+ }
56
+ onCleanup(subscribe(value, setMatches))
57
+ })
58
+ return matches
59
+ }
@@ -55,3 +55,36 @@ export function versionLessThan(a: string, b: string): boolean {
55
55
  }
56
56
  return false
57
57
  }
58
+
59
+ /** The longest release version a build, tag or feed may carry. */
60
+ const MAX_RELEASE_VERSION_LENGTH = 64
61
+ const RELEASE_VERSION = /^\d+\.\d+\.\d+(?:-dev\.\d+)?$/
62
+
63
+ /** A release version in the update grammar: `x.y.z` or the dev build `x.y.z-dev.N`. */
64
+ export function isReleaseVersion(value: unknown): value is string {
65
+ return (
66
+ typeof value === 'string' &&
67
+ value.length <= MAX_RELEASE_VERSION_LENGTH &&
68
+ RELEASE_VERSION.test(value)
69
+ )
70
+ }
71
+
72
+ /** A release tag: `v` followed by a release version. */
73
+ export function isReleaseTag(value: unknown): value is string {
74
+ return typeof value === 'string' && value.startsWith('v') && isReleaseVersion(value.slice(1))
75
+ }
76
+
77
+ /**
78
+ * The version a build stamps on the shell and its client: the release workflow's
79
+ * `ADEA_APP_RELEASE_VERSION`, otherwise `fallback` (usually the package version).
80
+ * Anything outside the release grammar throws, so a build never ships a version the
81
+ * updater cannot order.
82
+ */
83
+ export function applicationVersion(
84
+ env: Readonly<Record<string, string | undefined>>,
85
+ fallback: unknown
86
+ ): string {
87
+ const version = env.ADEA_APP_RELEASE_VERSION ?? fallback
88
+ if (!isReleaseVersion(version)) throw new Error('Invalid application release version')
89
+ return version
90
+ }
@@ -3,7 +3,8 @@ import type {
3
3
  UpdateChannel,
4
4
  UpdateState,
5
5
  } from '@adea-ai/ui/components/composites/update-dialog'
6
- import { toUpdateState, type NativeUpdateSnapshotOf } from './update-state'
6
+ import { isUpdateChannel } from './release-version'
7
+ import { toUpdateState, type NativeUpdateSnapshotOf, type NativeUpdateState } from './update-state'
7
8
 
8
9
  export type { UpdateAdapter, UpdateChannel, UpdateState }
9
10
 
@@ -141,3 +142,169 @@ export function browserUpdateAdapter(currentVersion = ''): UpdateAdapter {
141
142
  isDesktopRuntime: () => false,
142
143
  }
143
144
  }
145
+
146
+ /** Every phase the shared update dialog understands, in state-machine order. */
147
+ export const UPDATE_PHASES = [
148
+ 'idle',
149
+ 'checking',
150
+ 'current',
151
+ 'unavailable',
152
+ 'available',
153
+ 'downloading',
154
+ 'installing',
155
+ 'cancelling',
156
+ 'cancelled',
157
+ 'installed',
158
+ 'failed',
159
+ ] as const satisfies readonly UpdateState['phase'][]
160
+
161
+ export function isUpdatePhase(value: unknown): value is UpdateState['phase'] {
162
+ return (UPDATE_PHASES as readonly unknown[]).includes(value)
163
+ }
164
+
165
+ /** Phases in which an update occupies the app: offered, in flight, or awaiting the restart. */
166
+ export const UPDATE_PENDING_PHASES = [
167
+ 'available',
168
+ 'downloading',
169
+ 'installing',
170
+ 'installed',
171
+ ] as const satisfies readonly UpdateState['phase'][]
172
+
173
+ /** Whether a phase should raise a pending-update badge. */
174
+ export function isUpdatePending(phase: string | null | undefined): boolean {
175
+ return (UPDATE_PENDING_PHASES as readonly (string | null | undefined)[]).includes(phase)
176
+ }
177
+
178
+ /** The snapshot the `desktop_update_*` services answer with. */
179
+ export type DesktopUpdateStatus = NativeUpdateState<UpdateState['phase']>
180
+
181
+ const isText = (value: unknown): value is string => typeof value === 'string'
182
+ const isNullableText = (value: unknown): value is string | null => value === null || isText(value)
183
+ const isByteCount = (value: unknown): value is number =>
184
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
185
+
186
+ /**
187
+ * Check a `desktop_update_*` answer at the boundary, so a malformed reply fails here instead of
188
+ * inside the dialog. `release_notes` may be absent (older hosts), and reads as null.
189
+ */
190
+ export function parseDesktopUpdateStatus(value: unknown): DesktopUpdateStatus {
191
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
192
+ throw new Error('Invalid desktop update status')
193
+ const record = value as Record<string, unknown>
194
+ const releaseNotes = record.release_notes ?? null
195
+ if (
196
+ !isText(record.current_version) ||
197
+ !isNullableText(record.available_version) ||
198
+ !isUpdatePhase(record.phase) ||
199
+ !isText(record.changelog) ||
200
+ !isNullableText(releaseNotes) ||
201
+ !isNullableText(record.release_date) ||
202
+ !isByteCount(record.downloaded_bytes) ||
203
+ (record.total_bytes !== null && !isByteCount(record.total_bytes)) ||
204
+ !isNullableText(record.error) ||
205
+ !isText(record.github_url) ||
206
+ typeof record.restart_required !== 'boolean'
207
+ )
208
+ throw new Error('Invalid desktop update status')
209
+ return {
210
+ phase: record.phase,
211
+ current_version: record.current_version,
212
+ available_version: record.available_version,
213
+ changelog: record.changelog,
214
+ release_notes: releaseNotes,
215
+ release_date: record.release_date,
216
+ downloaded_bytes: record.downloaded_bytes,
217
+ total_bytes: record.total_bytes as number | null,
218
+ error: record.error,
219
+ github_url: record.github_url,
220
+ restart_required: record.restart_required,
221
+ }
222
+ }
223
+
224
+ /** Call a desktop service by name, as the app's desktop client does. */
225
+ export type DesktopServiceInvoke = (
226
+ command: string,
227
+ args?: Record<string, unknown>
228
+ ) => Promise<unknown>
229
+
230
+ /** Phases from which an offered version may be installed. */
231
+ const INSTALLABLE_PHASES: readonly string[] = ['available', 'failed', 'cancelled']
232
+
233
+ /**
234
+ * The shared dialog's adapter for the framework desktop updater (`registerUpdateServices`).
235
+ * Every answer is checked with `parseDesktopUpdateStatus` and reported to `onStatus`, so a
236
+ * pending-update badge can follow the same updater. `confirmInstall` may decline an install.
237
+ * Because the dialog keeps polling while that question is open, an install runs only if the
238
+ * updater still offers the version; otherwise the current state is returned so the user can
239
+ * decide again. A rejected install re-reads the status before rethrowing, since the updater
240
+ * may have dropped its offer.
241
+ */
242
+ export function desktopUpdateAdapter(
243
+ invoke: DesktopServiceInvoke,
244
+ options: {
245
+ confirmInstall?(version: string): boolean | Promise<boolean>
246
+ openExternal?(url: string): Promise<void>
247
+ onStatus?(status: DesktopUpdateStatus): void
248
+ isDesktopRuntime?(): boolean
249
+ /** Polling interval during native work; default 500 ms. */
250
+ pollIntervalMs?: number
251
+ /** Show the available release's notes; default true. */
252
+ releaseNotes?: boolean
253
+ } = {}
254
+ ): UpdateAdapter {
255
+ let latest: DesktopUpdateStatus | undefined
256
+ const view = (status: DesktopUpdateStatus) =>
257
+ toUpdateState(status, { includeReleaseNotes: options.releaseNotes !== false })
258
+ const call = async (command: string, args?: Record<string, unknown>) => {
259
+ const status = parseDesktopUpdateStatus(await invoke(command, args))
260
+ latest = status
261
+ try {
262
+ options.onStatus?.(status)
263
+ } catch {
264
+ // A badge observer must not change what the updater answered.
265
+ }
266
+ return status
267
+ }
268
+ const read = () => call('desktop_update_status')
269
+ return {
270
+ getStatus: async () => view(await read()),
271
+ check: async () => view(await call('desktop_update_check')),
272
+ install: async (expectedVersion) => {
273
+ if (options.confirmInstall && !(await options.confirmInstall(expectedVersion)))
274
+ return view(latest ?? (await read()))
275
+ const offered = latest ?? (await read())
276
+ if (
277
+ offered.available_version !== expectedVersion ||
278
+ !INSTALLABLE_PHASES.includes(offered.phase)
279
+ )
280
+ return view(await read())
281
+ try {
282
+ return view(
283
+ await call('desktop_update_install', { expectedVersion, approved: true, restart: true })
284
+ )
285
+ } catch (error) {
286
+ await read().catch(() => {})
287
+ throw error
288
+ }
289
+ },
290
+ cancel: async () => view(await call('desktop_update_cancel')),
291
+ isDesktopRuntime: () => options.isDesktopRuntime?.() ?? true,
292
+ pollIntervalMs: options.pollIntervalMs ?? 500,
293
+ ...(options.openExternal ? { openExternal: options.openExternal } : {}),
294
+ }
295
+ }
296
+
297
+ /** The `desktop_update_channel*` services as the update surface's channel service. */
298
+ export function desktopUpdateChannelService(invoke: DesktopServiceInvoke): UpdateChannelService {
299
+ return {
300
+ async channel() {
301
+ const channel = await invoke('desktop_update_channel')
302
+ return isUpdateChannel(channel) ? channel : 'stable'
303
+ },
304
+ async setChannel(channel) {
305
+ const saved = await invoke('desktop_update_channel_save', { channel })
306
+ if (!isUpdateChannel(saved)) throw new Error('Invalid update channel')
307
+ return saved
308
+ },
309
+ }
310
+ }