@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
@@ -1,3 +1,4 @@
1
+ import { discardStream } from "../shared/discard-stream.js";
1
2
  // src/updates/release-location.ts
2
3
  /** `value` as a URL inside `scope`: the same https origin, under its path prefix, with no
3
4
  * credentials, port, fragment or dot segments. */
@@ -28,7 +29,7 @@ async function fetchReleaseLocation(location, scope, fetcher, signal) {
28
29
  308
29
30
  ].includes(response.status)) return response;
30
31
  const next = response.headers.get("location");
31
- await response.body?.cancel();
32
+ discardStream(response.body);
32
33
  if (!next || redirects === 5) throw new Error("Invalid release redirect");
33
34
  url = releaseUrl(new URL(next, url).href, root);
34
35
  }
@@ -36,12 +37,12 @@ async function fetchReleaseLocation(location, scope, fetcher, signal) {
36
37
  /** Read a 200 response body of at most `maximum` bytes. */
37
38
  async function readReleaseBytes(response, maximum) {
38
39
  if (response.status !== 200 || !response.body) {
39
- await response.body?.cancel();
40
+ discardStream(response.body);
40
41
  throw new Error("Release feed request failed");
41
42
  }
42
43
  const length = response.headers.get("content-length");
43
44
  if (length !== null && (!/^\d+$/.test(length) || Number(length) > maximum)) {
44
- await response.body.cancel();
45
+ discardStream(response.body);
45
46
  throw new Error("Release feed response exceeds bound");
46
47
  }
47
48
  const reader = response.body.getReader(), chunks = [];
@@ -52,7 +53,7 @@ async function readReleaseBytes(response, maximum) {
52
53
  if (done) break;
53
54
  total += value.length;
54
55
  if (total > maximum) {
55
- await reader.cancel();
56
+ discardStream(reader);
56
57
  throw new Error("Release feed response exceeds bound");
57
58
  }
58
59
  chunks.push(value);
@@ -23,6 +23,11 @@ function mirrorUpdateState(adapter, onState) {
23
23
  check: () => note(adapter.check()),
24
24
  getStatus: () => note(adapter.getStatus()),
25
25
  install: (expectedVersion) => note(adapter.install(expectedVersion)),
26
+ isDesktopRuntime: () => adapter.isDesktopRuntime(),
27
+ get pollIntervalMs() {
28
+ return adapter.pollIntervalMs;
29
+ },
30
+ ...adapter.openExternal ? { openExternal: (url) => adapter.openExternal(url) } : {},
26
31
  ...cancel ? { cancel: () => note(cancel.call(adapter)) } : {}
27
32
  };
28
33
  }
@@ -18,6 +18,8 @@ export declare function armUpdateHelper(options: {
18
18
  processes?: UpdateHelperRequest['processes'];
19
19
  processTimeoutMs?: number;
20
20
  armTimeoutMs?: number;
21
+ /** Maximum time to confirm helper exit before cancellation preserves recovery state. */
22
+ cancelTimeoutMs?: number;
21
23
  env?: Record<string, string | undefined>;
22
24
  }): Promise<{
23
25
  cancel(): Promise<void>;
@@ -1,12 +1,30 @@
1
1
  import { updateStagingFor } from "./update-swap.js";
2
2
  import { updateLauncherPath } from "./update-launch.js";
3
- import { copyFile, lstat, mkdir, realpath, rm, unlink, writeFile } from "node:fs/promises";
3
+ import { copyFile, lstat, mkdir, readFile, realpath, rm, unlink, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { spawn } from "node:child_process";
6
6
  // src/updates/update-arm.ts
7
7
  function exited(child) {
8
8
  return child.exitCode !== null || child.signalCode !== null;
9
9
  }
10
+ function waitForExit(child, timeoutMs) {
11
+ if (exited(child) || child.pid === void 0) return Promise.resolve(true);
12
+ return new Promise((resolveExit) => {
13
+ let timer;
14
+ let settled = false;
15
+ const finish = (didExit) => {
16
+ if (settled) return;
17
+ settled = true;
18
+ if (timer) clearTimeout(timer);
19
+ child.off("exit", onExit);
20
+ resolveExit(didExit);
21
+ };
22
+ const onExit = () => finish(true);
23
+ child.once("exit", onExit);
24
+ if (exited(child)) finish(true);
25
+ else timer = setTimeout(() => finish(false), timeoutMs);
26
+ });
27
+ }
10
28
  /** The Bun runtime inside an installed app tree, which the helper copy runs on. */
11
29
  function updateRuntimePath(platform, target) {
12
30
  const launcher = updateLauncherPath(platform, target);
@@ -45,24 +63,57 @@ async function armUpdateHelper(options) {
45
63
  };
46
64
  const armed = join(staging, "helper-armed");
47
65
  let child;
48
- async function reset() {
49
- if (child && !exited(child) && child.pid !== void 0) try {
50
- process.kill(child.pid);
51
- } catch {}
52
- for (const name of ["request.json", "helper-armed"]) await unlink(join(staging, name)).catch(() => void 0);
53
- await rm(helper, {
66
+ let helperCreated = false;
67
+ let requestCreated = false;
68
+ let resetCompleted = false;
69
+ let resetInProgress;
70
+ async function performReset() {
71
+ if (child && !exited(child) && child.pid !== void 0) {
72
+ try {
73
+ process.kill(child.pid);
74
+ } catch (error) {
75
+ if (error.code !== "ESRCH") throw new Error("Update helper could not be stopped; recovery state was preserved", { cause: error });
76
+ }
77
+ if (!await waitForExit(child, options.cancelTimeoutMs ?? 1e4)) throw new Error("Update helper did not exit after cancellation; recovery state was preserved");
78
+ }
79
+ let marker;
80
+ if (child?.pid !== void 0) {
81
+ try {
82
+ marker = await readFile(armed, "utf8");
83
+ } catch (error) {
84
+ if (error.code !== "ENOENT") throw new Error("Update helper ownership could not be verified; recovery state was preserved", { cause: error });
85
+ }
86
+ if (marker !== void 0 && marker.trim() !== String(child.pid)) throw new Error("Update helper ownership changed; recovery state was preserved");
87
+ }
88
+ if (requestCreated) await unlink(join(staging, "request.json")).catch(() => void 0);
89
+ if (marker !== void 0) await unlink(armed).catch(() => void 0);
90
+ if (helperCreated) await rm(helper, {
54
91
  recursive: true,
55
92
  force: true
56
93
  });
57
94
  }
95
+ function reset() {
96
+ if (resetCompleted) return Promise.resolve();
97
+ if (resetInProgress) return resetInProgress;
98
+ const attempt = performReset();
99
+ resetInProgress = attempt;
100
+ attempt.then(() => {
101
+ resetCompleted = true;
102
+ }).finally(() => {
103
+ if (resetInProgress === attempt) resetInProgress = void 0;
104
+ }).catch(() => {});
105
+ return attempt;
106
+ }
58
107
  try {
59
108
  await mkdir(helper, { mode: 448 });
109
+ helperCreated = true;
60
110
  await copyFile(updateRuntimePath(options.platform, options.target), runtime);
61
111
  await copyFile(options.helperScript, script);
62
112
  await writeFile(join(staging, "request.json"), JSON.stringify(request) + "\n", {
63
113
  flag: "wx",
64
114
  mode: 384
65
115
  });
116
+ requestCreated = true;
66
117
  const started = spawn(runtime, [
67
118
  script,
68
119
  "--staging",
@@ -27,10 +27,11 @@ async function discoverSignedRelease(options) {
27
27
  if (selected.channel !== trust.channel) throw new Error("Invalid channel pointer");
28
28
  } else {
29
29
  const kinds = trust.channel === "stable" ? ["stable"] : trust.channel === "dev" ? ["dev"] : ["daily", "stable"];
30
- const entry = parseReleaseLedger(await readReleaseJson(await get("index.json"), MAX_LEDGER_BYTES), new URL(trust.feed).pathname.split("/").at(-2)).releases.find((item) => kinds.includes(item.kind) && versionLessThan(item.tag, olderThan));
30
+ const entry = parseReleaseLedger(await readReleaseJson(await get("index.json"), MAX_LEDGER_BYTES), new URL(trust.feed).pathname.split("/").at(-2)).releases.reduce((best, item) => kinds.includes(item.kind) && versionLessThan(item.tag, olderThan) && (!best || versionLessThan(best.tag, item.tag)) ? item : best, void 0);
31
31
  if (entry) {
32
32
  selected = parseFeedRelease(await readReleaseJson(await get(`${entry.tag}/release.json`), MAX_POINTER_BYTES));
33
33
  if (selected.tag !== entry.tag) throw new Error("Invalid feed release");
34
+ if (!selected.assets.some((asset) => asset.name === discoveryName)) throw new Error("Selected previous release does not advertise this descriptor");
34
35
  }
35
36
  }
36
37
  const listed = selected?.assets.find((asset) => asset.name === discoveryName);
@@ -0,0 +1,7 @@
1
+ /** Discard a framework download under the caller's canonical, app-owned root. */
2
+ export declare function discardOwnedUpdateDownload(root: string, directory: string): Promise<void>;
3
+ /** Use an explicit owner for injected downloads; otherwise own the built-in layout. */
4
+ export declare function selectUpdateDownloadDiscard<T extends {
5
+ path: string;
6
+ directory: string;
7
+ }>(root: string, customDownloader: boolean, owner?: (input: T) => Promise<void>): ((input: T) => Promise<void>) | undefined;
@@ -0,0 +1,21 @@
1
+ import { rm } from "node:fs/promises";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ // src/updates/update-download-cleanup.ts
4
+ /** Discard a framework download under the caller's canonical, app-owned root. */
5
+ async function discardOwnedUpdateDownload(root, directory) {
6
+ if (dirname(directory) !== root || !basename(directory).startsWith("framework-update-")) throw new Error("Invalid update download directory");
7
+ await rm(directory, {
8
+ recursive: true,
9
+ force: true
10
+ });
11
+ }
12
+ /** Use an explicit owner for injected downloads; otherwise own the built-in layout. */
13
+ function selectUpdateDownloadDiscard(root, customDownloader, owner) {
14
+ if (owner || customDownloader) return owner;
15
+ const downloadsRoot = resolve(root);
16
+ return async ({ directory, path }) => {
17
+ if (resolve(path) !== join(directory, "archive")) throw new Error("Invalid update download archive");
18
+ await discardOwnedUpdateDownload(downloadsRoot, directory);
19
+ };
20
+ }
21
+ export { discardOwnedUpdateDownload, selectUpdateDownloadDiscard };
@@ -13,43 +13,61 @@ async function downloadVerifiedRelease(options) {
13
13
  const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
14
14
  const fetcher = options.fetch ?? globalThis.fetch;
15
15
  let temporary;
16
+ let response;
16
17
  try {
17
18
  if (signal.aborted) throw new Error("Release download cancelled");
18
19
  const { url, name } = descriptor.asset;
19
20
  const feed = url.slice(0, url.length - `${descriptor.tag}/${name}`.length);
20
- const response = await fetchReleaseLocation(url, feed, fetcher, signal);
21
- if (response.status !== 200 || !response.body) {
22
- await response.body?.cancel();
23
- throw new Error("Release download failed");
24
- }
21
+ response = await fetchReleaseLocation(url, feed, fetcher, signal);
22
+ if (response.status !== 200 || !response.body) throw new Error("Release download failed");
23
+ const body = response.body;
25
24
  const length = response.headers.get("content-length");
26
- if (length !== null && (!/^\d+$/.test(length) || Number(length) !== descriptor.asset.size)) {
27
- await response.body.cancel();
28
- throw new Error("Release download size mismatch");
29
- }
25
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) !== descriptor.asset.size)) throw new Error("Release download size mismatch");
30
26
  temporary = await mkdtemp(join(resolve(options.directory), "framework-update-"));
31
27
  const path = join(temporary, "archive");
32
28
  const file = await open(path, "wx", 384);
33
29
  try {
34
30
  async function* writeChunks() {
35
31
  let size = 0;
36
- for await (const chunk of response.body) {
37
- if (!(chunk instanceof Uint8Array) || signal.aborted) throw new Error("Invalid download chunk");
38
- size += chunk.length;
39
- if (!Number.isSafeInteger(size) || size > descriptor.asset.size) throw new Error("Release download exceeds signed size");
40
- let offset = 0;
41
- while (offset < chunk.length) {
42
- const { bytesWritten } = await file.write(chunk, offset, chunk.length - offset);
43
- if (!bytesWritten) throw new Error("Unable to write update");
44
- offset += bytesWritten;
32
+ const reader = body.getReader();
33
+ let complete = false;
34
+ const cancelRead = () => {
35
+ reader.cancel().catch(() => {});
36
+ };
37
+ signal.addEventListener("abort", cancelRead, { once: true });
38
+ try {
39
+ if (signal.aborted) cancelRead();
40
+ for (;;) {
41
+ const { value: chunk, done } = await reader.read();
42
+ if (signal.aborted) throw new Error("Release download cancelled");
43
+ if (done) {
44
+ complete = true;
45
+ break;
46
+ }
47
+ if (!(chunk instanceof Uint8Array) || signal.aborted) throw new Error("Invalid download chunk");
48
+ size += chunk.length;
49
+ if (!Number.isSafeInteger(size) || size > descriptor.asset.size) throw new Error("Release download exceeds signed size");
50
+ let offset = 0;
51
+ while (offset < chunk.length) {
52
+ const { bytesWritten } = await file.write(chunk, offset, chunk.length - offset);
53
+ if (!bytesWritten) throw new Error("Unable to write update");
54
+ offset += bytesWritten;
55
+ }
56
+ yield chunk;
45
57
  }
46
- yield chunk;
58
+ } finally {
59
+ signal.removeEventListener("abort", cancelRead);
60
+ if (!complete) cancelRead();
61
+ reader.releaseLock();
47
62
  }
48
63
  }
49
- if (!await verifyReleaseStream(writeChunks(), descriptor)) throw new Error("Release download verification failed");
64
+ const verified = await verifyReleaseStream(writeChunks(), descriptor);
65
+ if (signal.aborted) throw new Error("Release download cancelled");
66
+ if (!verified) throw new Error("Release download verification failed");
50
67
  } finally {
51
68
  await file.close();
52
69
  }
70
+ if (signal.aborted) throw new Error("Release download cancelled");
53
71
  return {
54
72
  path,
55
73
  directory: temporary
@@ -62,6 +80,9 @@ async function downloadVerifiedRelease(options) {
62
80
  throw error;
63
81
  } finally {
64
82
  clearTimeout(timer);
83
+ if (response?.body && !response.bodyUsed && !response.body.locked) try {
84
+ response.body.cancel().catch(() => {});
85
+ } catch {}
65
86
  }
66
87
  }
67
88
  export { downloadVerifiedRelease };
@@ -1,2 +1,3 @@
1
- /** Rename without replacing an existing destination. The caller must validate and own both parent directories. */
2
- export declare function renameUpdateExclusive(source: string, destination: string): void;
1
+ import { renameExclusive } from '../native/exclusive-rename';
2
+ /** Rename an updater payload without replacing an existing destination. */
3
+ export declare const renameUpdateExclusive: typeof renameExclusive;
@@ -1,52 +1,5 @@
1
- import { isAbsolute, resolve } from "node:path";
2
- import { FFIType, dlopen, ptr } from "bun:ffi";
1
+ import { renameExclusive } from "../native/exclusive-rename.js";
3
2
  // src/updates/update-exclusive-rename.ts
4
- /** Rename without replacing an existing destination. The caller must validate and own both parent directories. */
5
- function renameUpdateExclusive(source, destination) {
6
- if (typeof source !== "string" || typeof destination !== "string" || !isAbsolute(source) || !isAbsolute(destination) || resolve(source) !== source || resolve(destination) !== destination || source === destination || source.includes("\0") || destination.includes("\0")) throw new Error("Invalid exclusive rename paths");
7
- if (process.platform === "darwin") {
8
- const library = dlopen("libSystem.B.dylib", { renamex_np: {
9
- args: [
10
- FFIType.ptr,
11
- FFIType.ptr,
12
- FFIType.u32
13
- ],
14
- returns: FFIType.i32
15
- } });
16
- try {
17
- const from = Buffer.from(source + "\0"), to = Buffer.from(destination + "\0");
18
- if (library.symbols.renamex_np(ptr(from), ptr(to), 4) !== 0) throw new Error("Exclusive rename failed");
19
- } finally {
20
- library.close();
21
- }
22
- } else if (process.platform === "linux") {
23
- const library = dlopen("libc.so.6", { renameat2: {
24
- args: [
25
- FFIType.i32,
26
- FFIType.ptr,
27
- FFIType.i32,
28
- FFIType.ptr,
29
- FFIType.u32
30
- ],
31
- returns: FFIType.i32
32
- } });
33
- try {
34
- const from = Buffer.from(source + "\0"), to = Buffer.from(destination + "\0");
35
- if (library.symbols.renameat2(-100, ptr(from), -100, ptr(to), 1) !== 0) throw new Error("Exclusive rename failed");
36
- } finally {
37
- library.close();
38
- }
39
- } else if (process.platform === "win32") {
40
- const library = dlopen("kernel32.dll", { MoveFileW: {
41
- args: [FFIType.ptr, FFIType.ptr],
42
- returns: FFIType.i32
43
- } });
44
- try {
45
- const from = Buffer.from(source + "\0", "utf16le"), to = Buffer.from(destination + "\0", "utf16le");
46
- if (library.symbols.MoveFileW(ptr(from), ptr(to)) === 0) throw new Error("Exclusive rename failed");
47
- } finally {
48
- library.close();
49
- }
50
- } else throw new Error("Unsupported exclusive rename platform");
51
- }
3
+ /** Rename an updater payload without replacing an existing destination. */
4
+ var renameUpdateExclusive = renameExclusive;
52
5
  export { renameUpdateExclusive };
@@ -22,7 +22,7 @@ async function extractVerifiedUpdate(options) {
22
22
  };
23
23
  if (!isVerifiedRelease(descriptor) || !expected[platform] || descriptor.platform !== expected[platform][0] || descriptor.arch !== expected[platform][1] || !isAbsolute(archive) || !isAbsolute(options.directory) || !Number.isSafeInteger(maxCompressedBytes) || maxCompressedBytes < 1 || descriptor.asset.size > maxCompressedBytes || !Number.isSafeInteger(maxExpandedBytes) || maxExpandedBytes < 1) throw new Error("Invalid update extraction context");
24
24
  assertPortableAppName(appName);
25
- const sidecars = assertSidecarNames(options.sidecars ?? []);
25
+ const sidecars = assertSidecarNames(options.sidecars ?? [], platform);
26
26
  const archiveRoot = platform === "macos-arm64" ? `${appName}.app` : appName.replaceAll(" ", "");
27
27
  const info = await lstat(archive);
28
28
  if (!info.isFile() || info.isSymbolicLink() || info.size !== descriptor.asset.size) throw new Error("Invalid update archive");
@@ -9,7 +9,11 @@ type State = Readonly<{
9
9
  availableVersion: string | null;
10
10
  error: string | null;
11
11
  }>;
12
- /** Coordinates trusted discovery and download; the platform adapter owns safe application and recovery. */
12
+ /**
13
+ * Coordinates discovery and download with point-in-time trust checks. The
14
+ * stage callback owns safe application, including trust at its own commit
15
+ * boundary; these checks do not lock a mutable policy during staging.
16
+ */
13
17
  export declare function createUpdateManager(options: {
14
18
  currentVersion: string;
15
19
  trust: ReleaseTrust;
@@ -21,6 +25,18 @@ export declare function createUpdateManager(options: {
21
25
  path: string;
22
26
  directory: string;
23
27
  }) => Promise<void>;
28
+ /**
29
+ * Dispose of a downloaded result rejected before stage takes ownership.
30
+ * Without a callback, built-in downloads are discarded automatically and
31
+ * injected downloads are preserved for their owner to clean up.
32
+ * This callback is awaited and must settle; its failure does not mask the
33
+ * update failure.
34
+ */
35
+ discardDownload?: (input: {
36
+ descriptor: VerifiedRelease;
37
+ path: string;
38
+ directory: string;
39
+ }) => Promise<void>;
24
40
  discover?: typeof discoverSignedRelease;
25
41
  download?: typeof downloadVerifiedRelease;
26
42
  fetch?: FetchFunction;
@@ -2,9 +2,17 @@ import { isVerifiedReleaseForTrust } from "./signed-release.js";
2
2
  import { versionLessThan } from "./release-version.js";
3
3
  import { discoverSignedRelease } from "./update-discovery.js";
4
4
  import { downloadVerifiedRelease } from "./update-download.js";
5
+ import { selectUpdateDownloadDiscard } from "./update-download-cleanup.js";
5
6
  // src/updates/update-manager.ts
6
- /** Coordinates trusted discovery and download; the platform adapter owns safe application and recovery. */
7
+ /**
8
+ * Coordinates discovery and download with point-in-time trust checks. The
9
+ * stage callback owns safe application, including trust at its own commit
10
+ * boundary; these checks do not lock a mutable policy during staging.
11
+ */
7
12
  function createUpdateManager(options) {
13
+ const directory = options.directory;
14
+ const download = options.download;
15
+ const discardDownload = selectUpdateDownloadDiscard(directory, download !== void 0, options.discardDownload);
8
16
  if (!/^\d+\.\d+\.\d+(?:-dev\.\d+)?$/.test(options.currentVersion) || options.currentVersion.length > 64 || !Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1 || typeof options.stage !== "function") throw new Error("Invalid update manager configuration");
9
17
  let state = Object.freeze({
10
18
  phase: "idle",
@@ -55,19 +63,30 @@ function createUpdateManager(options) {
55
63
  try {
56
64
  if (input.approved !== true || !pending || state.phase !== "available" || input.expectedVersion !== pending.version) throw new Error("Update approval does not match the available version");
57
65
  const descriptor = pending;
58
- set("downloading");
59
66
  try {
60
- const download = await (options.download ?? downloadVerifiedRelease)({
67
+ if (!isVerifiedReleaseForTrust(descriptor, options.trust)) throw new Error("Untrusted update");
68
+ set("downloading");
69
+ const downloaded = await (download ?? downloadVerifiedRelease)({
61
70
  descriptor,
62
- directory: options.directory,
71
+ directory,
63
72
  maxBytes: options.maxBytes,
64
73
  fetch: options.fetch
65
74
  });
66
- set("staging");
67
- await options.stage({
75
+ const stageInput = {
68
76
  descriptor,
69
- ...download
70
- });
77
+ path: downloaded.path,
78
+ directory: downloaded.directory
79
+ };
80
+ try {
81
+ if (!isVerifiedReleaseForTrust(descriptor, options.trust)) throw new Error("Untrusted update");
82
+ } catch (error) {
83
+ try {
84
+ await discardDownload?.(stageInput);
85
+ } catch {}
86
+ throw error;
87
+ }
88
+ set("staging");
89
+ await options.stage(stageInput);
71
90
  pending = void 0;
72
91
  return set("staged", descriptor.version);
73
92
  } catch {
@@ -1,8 +1,9 @@
1
- import { realpath } from "node:fs/promises";
1
+ import { linuxProcessIsExited } from "./linux-process-state.js";
2
+ import { readFile, realpath } from "node:fs/promises";
2
3
  import { isAbsolute } from "node:path";
4
+ import { FFIType, dlopen, ptr } from "bun:ffi";
3
5
  import { execFile } from "node:child_process";
4
6
  import { promisify } from "node:util";
5
- import { FFIType, dlopen, ptr } from "bun:ffi";
6
7
  // src/updates/update-process-fence.ts
7
8
  var execute = promisify(execFile);
8
9
  function isProcessRunning(pid) {
@@ -14,6 +15,20 @@ function isProcessRunning(pid) {
14
15
  throw new Error("Cannot inspect update process", { cause: error });
15
16
  }
16
17
  }
18
+ /** Only used after the process executable has been verified and acknowledged. */
19
+ async function hasVerifiedProcessExited(pid) {
20
+ if (!isProcessRunning(pid)) return true;
21
+ if (process.platform !== "linux") return false;
22
+ let stat;
23
+ try {
24
+ stat = await readFile(`/proc/${pid}/stat`, "utf8");
25
+ } catch (error) {
26
+ const code = error.code;
27
+ if ((code === "ENOENT" || code === "ESRCH") && !isProcessRunning(pid)) return true;
28
+ throw new Error("Cannot inspect update process", { cause: error });
29
+ }
30
+ return linuxProcessIsExited(stat, pid);
31
+ }
17
32
  /** Wait without signalling only processes whose executables were verified. This is not complete app-process discovery. */
18
33
  async function waitForUpdateProcesses(options) {
19
34
  if (!Array.isArray(options.processes) || options.processes.length < 1 || options.processes.length > 16 || !Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 12e4) throw new Error("Invalid update process fence");
@@ -105,7 +120,7 @@ async function waitForUpdateProcesses(options) {
105
120
  const notified = options.onVerified?.();
106
121
  if (typeof notified === "object" && notified !== null && "then" in notified) throw new Error("Update process acknowledgement must be synchronous");
107
122
  while (waiting.size) {
108
- for (const pid of waiting) if (!isProcessRunning(pid)) waiting.delete(pid);
123
+ for (const pid of waiting) if (await hasVerifiedProcessExited(pid)) waiting.delete(pid);
109
124
  if (!waiting.size) return;
110
125
  if (Date.now() >= deadline) throw new Error("Update processes did not exit");
111
126
  await Bun.sleep(Math.min(100, Math.max(1, deadline - Date.now())));
@@ -1,14 +1,16 @@
1
1
  import { preferencesFromSelection } from "../appearance/appearance-preferences.js";
2
- import { readCustomThemeLibrary, removeCustomTheme, subscribeCustomThemes } from "../appearance/custom-theme-library.js";
2
+ import { readCustomThemeLibrary, removeCustomThemeAtomically, subscribeCustomThemes } from "../appearance/custom-theme-library.js";
3
3
  import { useTheme } from "../appearance/appearance-host.js";
4
4
  import { draftVariants } from "../appearance/composition.js";
5
5
  import { createAppearanceEditor } from "../appearance/editor.js";
6
6
  import { createThemeFileImporter } from "../appearance/theme-file-importer.js";
7
+ import { createThemeLibraryActionFence } from "../appearance/theme-library-action-fence.js";
7
8
  import { DEFAULT_CUSTOM_ACCENT, allThemeRecords, appearanceThemeForPreview, normalizeCustomAccent } from "../appearance/theme-record-adapter.js";
8
9
  import { mirrorWindowSurface } from "../appearance/window-surface.js";
9
10
  import { createComponent, effect, insert, mergeProps, setAttribute, template } from "solid-js/web";
10
11
  import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from "solid-js";
11
12
  import { MonitorCog } from "lucide-solid";
13
+ import { defaultPreferenceStorage } from "@adea-ai/ui/lib/preference-store";
12
14
  import { isThemeAccentId } from "@adea-ai/ui/lib/themes";
13
15
  import { accents, getAccent } from "@adea-ai/ui/lib/accent-presets";
14
16
  import { themeAccentsForRecords } from "@adea-ai/ui/lib/theme-projection";
@@ -48,10 +50,10 @@ function AppearanceHost(props) {
48
50
  const [accentStatus, setAccentStatus] = createSignal("");
49
51
  const [libraryOpen, setLibraryOpen] = createSignal(false);
50
52
  const miniatures = createMemo(() => draftVariants(editor.draft()));
51
- const [library, setLibrary] = createSignal(readCustomThemeLibrary(typeof window === "undefined" ? void 0 : window.localStorage));
53
+ const [library, setLibrary] = createSignal(readCustomThemeLibrary(defaultPreferenceStorage()));
52
54
  onMount(() => {
53
- setLibrary(readCustomThemeLibrary(window.localStorage));
54
- onCleanup(subscribeCustomThemes(() => setLibrary(readCustomThemeLibrary(window.localStorage))));
55
+ setLibrary(readCustomThemeLibrary(defaultPreferenceStorage()));
56
+ onCleanup(subscribeCustomThemes(() => setLibrary(readCustomThemeLibrary(defaultPreferenceStorage()))));
55
57
  });
56
58
  const themes = () => {
57
59
  library();
@@ -59,20 +61,44 @@ function AppearanceHost(props) {
59
61
  };
60
62
  const [importStatus, setImportStatus] = createSignal("");
61
63
  const [importPending, setImportPending] = createSignal(false);
64
+ const themeActionFence = createThemeLibraryActionFence(setImportStatus);
65
+ let importActionToken = 0;
62
66
  const themeImporter = createThemeFileImporter({
63
67
  load: async () => {
64
- const { importCustomTheme } = await import("../appearance/custom-theme-import.js");
65
- return (text) => importCustomTheme(text, window.localStorage, readCustomThemeLibrary(window.localStorage));
68
+ const { importCustomThemeAtomically } = await import("../appearance/custom-theme-import.js");
69
+ return (text, canCommit) => {
70
+ const storage = defaultPreferenceStorage();
71
+ if (!storage) return {
72
+ ok: false,
73
+ error: "The theme could not be saved. Check your storage and try again."
74
+ };
75
+ return importCustomThemeAtomically(text, storage, { canCommit });
76
+ };
66
77
  },
67
- onPending: setImportPending,
68
- onStatus: setImportStatus,
69
- onImported: (theme) => setDraft(theme.appearance === "dark" ? { darkThemeId: theme.id } : { lightThemeId: theme.id })
78
+ onPending: (pending) => {
79
+ if (themeActionFence.isCurrent(importActionToken)) setImportPending(pending);
80
+ },
81
+ onStatus: (status) => themeActionFence.report(importActionToken, status),
82
+ onImported: (theme) => {
83
+ if (!themeActionFence.isCurrent(importActionToken)) return;
84
+ setDraft(theme.appearance === "dark" ? { darkThemeId: theme.id } : { lightThemeId: theme.id });
85
+ }
86
+ });
87
+ onCleanup(() => {
88
+ themeActionFence.dispose();
89
+ themeImporter.cancel();
70
90
  });
71
- onCleanup(themeImporter.cancel);
72
91
  const closeLibrary = () => {
92
+ const action = themeActionFence.begin();
73
93
  themeImporter.cancel();
94
+ setImportPending(false);
95
+ themeActionFence.report(action, "");
74
96
  setLibraryOpen(false);
75
97
  };
98
+ const importThemeFile = (file) => {
99
+ importActionToken = themeActionFence.begin();
100
+ themeImporter.importFile(file);
101
+ };
76
102
  const themeAccentOptions = createMemo(() => {
77
103
  const draft = editor.draft();
78
104
  const records = themes();
@@ -145,8 +171,9 @@ function AppearanceHost(props) {
145
171
  props.popover?.onClose();
146
172
  return;
147
173
  }
148
- const committed = editor.save();
174
+ const committed = editor.merge(preferencesFromSelection(appearance.selection()));
149
175
  appearance.update(committed);
176
+ editor.open(committed);
150
177
  appearance.preview(void 0);
151
178
  props.popover?.onClose();
152
179
  };
@@ -270,7 +297,7 @@ function AppearanceHost(props) {
270
297
  onChange: (event) => {
271
298
  const file = event.currentTarget.files?.[0];
272
299
  event.currentTarget.value = "";
273
- if (file) themeImporter.importFile(file);
300
+ if (file) importThemeFile(file);
274
301
  }
275
302
  }), "Import a theme file (.json)"];
276
303
  }
@@ -305,9 +332,18 @@ function AppearanceHost(props) {
305
332
  type: "button",
306
333
  size: "sm",
307
334
  variant: "ghost",
308
- onClick: () => {
309
- const removed = removeCustomTheme(theme.id, typeof window === "undefined" ? void 0 : window.localStorage);
310
- setImportStatus(removed ? "" : "The theme could not be removed. Check your storage and try again.");
335
+ onClick: async () => {
336
+ const action = themeActionFence.begin();
337
+ themeImporter.cancel();
338
+ setImportPending(false);
339
+ themeActionFence.report(action, "");
340
+ const storage = defaultPreferenceStorage();
341
+ if (!storage) {
342
+ themeActionFence.report(action, "The theme could not be removed. Check your storage and try again.");
343
+ return;
344
+ }
345
+ const result = await removeCustomThemeAtomically(theme.id, storage);
346
+ themeActionFence.report(action, result.ok ? "" : result.error);
311
347
  },
312
348
  children: "Remove"
313
349
  }), null);