@adea-ai/app-framework 0.39.1 → 0.39.2

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 (34) hide show
  1. package/ci/desktop-release-feed.sh +8 -0
  2. package/ci/desktop-release.sh +2 -0
  3. package/dist/cli/release-finalize-cli.d.ts +1 -0
  4. package/dist/cli/release-finalize-cli.js +17 -13
  5. package/dist/desktop/client-assets.js +52 -7
  6. package/dist/developer-app/developer-app.js +30 -12
  7. package/dist/framework-source.json +1 -1
  8. package/dist/native/sidecar.d.ts +0 -19
  9. package/dist/native/sidecar.js +35 -9
  10. package/dist/native/window-bootstrap.js +3 -1
  11. package/dist/shell/app-shell.js +49 -60
  12. package/dist/shell/app-utilities.js +17 -10
  13. package/dist/shell/media-query.d.ts +2 -1
  14. package/dist/shell/media-query.js +4 -3
  15. package/dist/update-helper.bundle.js +4 -4
  16. package/dist/updates/desktop-updater.js +2 -2
  17. package/dist/updates/helper/resume-staging.d.ts +4 -1
  18. package/dist/updates/helper/resume-staging.js +7 -9
  19. package/dist/updates/helper/update-resume.js +4 -3
  20. package/dist/updates/install/update-download.d.ts +1 -0
  21. package/dist/updates/install/update-download.js +10 -2
  22. package/dist/updates/install/update-swap.d.ts +2 -0
  23. package/dist/updates/install/update-swap.js +6 -2
  24. package/dist/updates/launch/update-launch-gate.d.ts +3 -2
  25. package/dist/updates/launch/update-launch-gate.js +3 -2
  26. package/dist/updates/locks/update-download-lock.js +2 -2
  27. package/dist/updates/retention/retirement-inventory.d.ts +4 -0
  28. package/dist/updates/retention/retirement-inventory.js +6 -4
  29. package/dist/updates/update-state-store.js +3 -3
  30. package/package.json +1 -1
  31. package/src/desktop/client-assets.ts +73 -13
  32. package/src/shell/app-shell.tsx +38 -47
  33. package/src/shell/app-utilities.tsx +22 -17
  34. package/src/shell/media-query.ts +4 -3
@@ -98,3 +98,11 @@ upload() { # <content|live>
98
98
  feed_object_matches "$key" "$size" "$digest" || { say "upload of $key did not verify"; exit 1; }
99
99
  done < "$work/objects-$phase.tsv"
100
100
  }
101
+
102
+ # Puts the published release.json of <app>/<tag> where link_release reads it, when this process
103
+ # did not stage it: a retry of an already-published daily runs in a fresh work folder.
104
+ feed_fetch_manifest() { # <app> <tag>
105
+ mkdir -p "$out/$1/$2"
106
+ feed_s3 get-object --key "$1/$2/release.json" "$out/$1/$2/release.json" >/dev/null ||
107
+ { say "refusing: could not read the published $1/$2/release.json"; return 1; }
108
+ }
@@ -107,6 +107,8 @@ link_release() { # <tag>
107
107
  if [ -n "${CI_JOB_TOKEN:-}" ]; then header=JOB-TOKEN token=$CI_JOB_TOKEN
108
108
  elif [ -n "${GITLAB_RELEASE_TOKEN:-}" ]; then header=PRIVATE-TOKEN token=$GITLAB_RELEASE_TOKEN; fi
109
109
  [ -z "$dry" ] && [ -n "$header" ] || { say "GitLab release links skipped"; return 0; }
110
+ # An already-published daily retried in a fresh process staged nothing: read what was published.
111
+ [ -f "$out/$repo/$1/release.json" ] || feed_fetch_manifest "$repo" "$1" || exit 1
110
112
  if [ -z "$project" ]; then
111
113
  # The origin remote's path (https://host/<path>.git or git@host:<path>.git), URL-encoded.
112
114
  project=${GITLAB_PROJECT:-$(git -C "$root" remote get-url origin)}
@@ -1 +1,2 @@
1
+ #!/usr/bin/env bun
1
2
  export {};
@@ -1,20 +1,24 @@
1
+ #!/usr/bin/env bun
1
2
  import { gitCli, originRepository } from "../release/local-provenance.js";
2
3
  import { verifyLocalRelease } from "../release/local-release.js";
3
4
  import { finalizeReleasePleaseDraft, parseFinalizationEvent } from "../release/release-finalize.js";
5
+ import { redactedErrorMessage, runCli } from "./cli-runner.js";
4
6
  import { readFile } from "node:fs/promises";
5
7
  // src/cli/release-finalize-cli.ts
6
- if (process.argv[2] === "--local") {
7
- const [configPath, tag, ...extra] = process.argv.slice(3);
8
- if (!configPath || !tag || extra.length) throw new Error("Expected release configuration and tag");
9
- const config = JSON.parse(await readFile(configPath, "utf8"));
10
- const result = await verifyLocalRelease({
11
- config,
12
- tag,
13
- repository: await originRepository(gitCli()),
14
- fetch
15
- });
16
- console.log(JSON.stringify(result));
17
- } else {
8
+ await runCli((error) => `Release finalization failed: ${redactedErrorMessage(error)}`, async () => {
9
+ if (process.argv[2] === "--local") {
10
+ const [configPath, tag, ...extra] = process.argv.slice(3);
11
+ if (!configPath || !tag || extra.length) throw new Error("Expected release configuration and tag");
12
+ const config = JSON.parse(await readFile(configPath, "utf8"));
13
+ const result = await verifyLocalRelease({
14
+ config,
15
+ tag,
16
+ repository: await originRepository(gitCli()),
17
+ fetch
18
+ });
19
+ console.log(JSON.stringify(result));
20
+ return;
21
+ }
18
22
  const configPath = process.argv[2];
19
23
  if (!configPath || process.argv.length !== 3 || !process.env.GITHUB_EVENT_PATH) throw new Error("Expected release configuration and workflow event");
20
24
  const config = JSON.parse(await readFile(configPath, "utf8"));
@@ -27,4 +31,4 @@ if (process.argv[2] === "--local") {
27
31
  ...identity
28
32
  });
29
33
  console.log("Qualified draft published as a prerelease");
30
- }
34
+ });
@@ -27,6 +27,38 @@ var unavailable = (status = 404) => new Response(null, {
27
27
  headers: { "cache-control": "no-store" }
28
28
  });
29
29
  var IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
30
+ var REVALIDATE_CACHE_CONTROL = "no-cache";
31
+ function fileEntityTag(metadata) {
32
+ return `W/"${[
33
+ metadata.dev,
34
+ metadata.ino,
35
+ metadata.size,
36
+ metadata.mtimeMs,
37
+ metadata.ctimeMs
38
+ ].map((value) => Math.trunc(value * 1e3).toString(36)).join("-")}"`;
39
+ }
40
+ function matchesEntityTag(request, tag) {
41
+ const header = request.headers.get("if-none-match");
42
+ if (!header) return false;
43
+ if (header.trim() === "*") return true;
44
+ return header.split(",").some((candidate) => {
45
+ const value = candidate.trim();
46
+ return value === tag || `W/${value}` === tag;
47
+ });
48
+ }
49
+ var deniedPrefixCache = /* @__PURE__ */ new Map();
50
+ /** Normalized, case-folded denied prefixes, computed once per distinct list. */
51
+ function deniedPrefixes(paths) {
52
+ if (!paths?.length) return [];
53
+ const key = paths.join("\0");
54
+ let prefixes = deniedPrefixCache.get(key);
55
+ if (!prefixes) {
56
+ prefixes = paths.map((item) => posix.normalize("/" + item.replaceAll("\\", "/")).toLowerCase().replace(/\/$/, "") || "/");
57
+ if (deniedPrefixCache.size >= 32) deniedPrefixCache.clear();
58
+ deniedPrefixCache.set(key, prefixes);
59
+ }
60
+ return prefixes;
61
+ }
30
62
  function clientPath(request) {
31
63
  try {
32
64
  const path = posix.normalize("/" + decodeURIComponent(new URL(request.url).pathname).replaceAll("\\", "/"));
@@ -131,11 +163,12 @@ async function serveClientInternal(request, options, onMissingRoot) {
131
163
  });
132
164
  const logical = clientPath(request);
133
165
  if (logical === void 0) return unavailable();
134
- const denied = (path) => (options.deniedPaths ?? []).some((item) => {
135
- const prefix = posix.normalize("/" + item.replaceAll("\\", "/")).toLowerCase().replace(/\/$/, "") || "/";
166
+ const prefixes = deniedPrefixes(options.deniedPaths);
167
+ const denied = (path) => {
168
+ if (!prefixes.length) return false;
136
169
  const folded = path.toLowerCase();
137
- return prefix === "/" || folded === prefix || folded.startsWith(prefix + "/");
138
- });
170
+ return prefixes.some((prefix) => prefix === "/" || folded === prefix || folded.startsWith(prefix + "/"));
171
+ };
139
172
  if (denied(logical)) return unavailable();
140
173
  let root;
141
174
  try {
@@ -167,6 +200,18 @@ async function serveClientInternal(request, options, onMissingRoot) {
167
200
  const contentType = MIME[extension] ?? "application/octet-stream";
168
201
  const configuredSha256 = options.immutableAssets?.get(logical);
169
202
  const immutableSha256 = extension !== ".html" && extension !== ".map" && typeof configuredSha256 === "string" && /^[a-f0-9]{64}$/.test(configuredSha256) ? configuredSha256 : void 0;
203
+ const entityTag = extension !== ".html" && extension !== ".map" && configuredSha256 === void 0 ? fileEntityTag(metadata) : void 0;
204
+ if (entityTag !== void 0 && matchesEntityTag(request, entityTag)) return new Response(null, {
205
+ status: 304,
206
+ headers: {
207
+ etag: entityTag,
208
+ "cache-control": REVALIDATE_CACHE_CONTROL
209
+ }
210
+ });
211
+ const uncachedHeaders = entityTag === void 0 ? { "cache-control": "no-store" } : {
212
+ "cache-control": REVALIDATE_CACHE_CONTROL,
213
+ etag: entityTag
214
+ };
170
215
  if (request.method === "HEAD" && !(extension === ".html" && options.transformHtml)) {
171
216
  const file = await open(physical, "r");
172
217
  let fileMetadata;
@@ -180,14 +225,14 @@ async function serveClientInternal(request, options, onMissingRoot) {
180
225
  return new Response(null, { headers: {
181
226
  "content-type": contentType,
182
227
  "content-length": String(fileMetadata.size),
183
- "cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store"
228
+ ...cacheVerified ? { "cache-control": IMMUTABLE_CACHE_CONTROL } : uncachedHeaders
184
229
  } });
185
230
  }
186
231
  if (options.streamAssets === true && request.method === "GET" && !(extension === ".html" && options.transformHtml)) {
187
232
  const cacheVerified = immutableSha256 !== void 0 && await matchesManifestDigest(physical, metadata, immutableSha256, options.verificationCache);
188
233
  return new Response(createClientAssetStream(physical, metadata, void 0, options.openFileLimit), { headers: {
189
234
  "content-type": contentType,
190
- "cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store",
235
+ ...cacheVerified ? { "cache-control": IMMUTABLE_CACHE_CONTROL } : uncachedHeaders,
191
236
  "content-length": String(metadata.size)
192
237
  } });
193
238
  }
@@ -196,7 +241,7 @@ async function serveClientInternal(request, options, onMissingRoot) {
196
241
  const cacheVerified = immutableSha256 !== void 0 && createHash("sha256").update(body).digest("hex") === immutableSha256;
197
242
  return new Response(request.method === "HEAD" ? null : body, { headers: {
198
243
  "content-type": contentType,
199
- "cache-control": cacheVerified ? IMMUTABLE_CACHE_CONTROL : "no-store",
244
+ ...cacheVerified ? { "cache-control": IMMUTABLE_CACHE_CONTROL } : uncachedHeaders,
200
245
  ...cacheVerified && request.method === "GET" ? { "content-length": String(body.byteLength) } : {},
201
246
  ...request.method === "HEAD" ? { "content-length": String(body.byteLength) } : {}
202
247
  } });
@@ -1,5 +1,5 @@
1
1
  import { dirname, isAbsolute, join, resolve } from "node:path";
2
- import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, watch, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, watch, writeFileSync } from "node:fs";
3
3
  import { spawn, spawnSync } from "node:child_process";
4
4
  import { homedir } from "node:os";
5
5
  // src/developer-app/developer-app.ts
@@ -138,11 +138,18 @@ var ICON_SIZES = [
138
138
  512
139
139
  ];
140
140
  function writeIconset(png, iconset) {
141
+ const outputs = ICON_SIZES.flatMap((size) => [{
142
+ pixels: String(size),
143
+ out: join(iconset, `icon_${size}x${size}.png`)
144
+ }, {
145
+ pixels: String(Math.min(size * 2, 512)),
146
+ out: join(iconset, `icon_${size}x${size}@2x.png`)
147
+ }]);
148
+ const source = statSync(png, { throwIfNoEntry: false });
149
+ if (source && outputs.every(({ out }) => (statSync(out, { throwIfNoEntry: false })?.mtimeMs ?? -1) >= source.mtimeMs)) return;
141
150
  mkdirSync(iconset, { recursive: true });
142
- for (const size of ICON_SIZES) for (const [scale, suffix] of [[1, ""], [2, "@2x"]]) {
143
- const pixels = String(Math.min(size * scale, 512));
144
- const out = join(iconset, `icon_${size}x${size}${suffix}.png`);
145
- spawnSync("sips", [
151
+ for (const { pixels, out } of outputs) {
152
+ const result = spawnSync("sips", [
146
153
  "-z",
147
154
  pixels,
148
155
  pixels,
@@ -150,6 +157,7 @@ function writeIconset(png, iconset) {
150
157
  "--out",
151
158
  out
152
159
  ], { stdio: "ignore" });
160
+ if (result.status !== 0) console.warn(`developer app: could not size the icon to ${pixels}px (${result.error?.message ?? `sips exited ${result.status}`})`);
153
161
  }
154
162
  }
155
163
  /** The shell environment for a developer app run. */
@@ -163,13 +171,21 @@ function developerAppShellEnv(config, env = process.env) {
163
171
  };
164
172
  }
165
173
  /** Stop a child and the process group it leads. */
166
- function stopGroup(child) {
174
+ function stopGroup(child, signal = "SIGTERM") {
167
175
  try {
168
- process.kill(-child.pid, "SIGTERM");
176
+ process.kill(-child.pid, signal);
169
177
  } catch {
170
- child.kill("SIGTERM");
178
+ child.kill(signal);
171
179
  }
172
180
  }
181
+ /** Stop a child's group, and kill it if it is still running after `graceMs`. */
182
+ function stopGroupWithin(child, graceMs = 3e3) {
183
+ if (child.exitCode !== null || child.signalCode !== null) return;
184
+ const timer = setTimeout(() => stopGroup(child, "SIGKILL"), graceMs);
185
+ timer.unref?.();
186
+ child.once("exit", () => clearTimeout(timer));
187
+ stopGroup(child);
188
+ }
173
189
  /**
174
190
  * Run the developer app from the checkout until its window closes or the process is
175
191
  * stopped: the UI dev server first, then the shell once the dev server answers.
@@ -221,11 +237,13 @@ async function runDeveloperApp(config, options = {}) {
221
237
  log("developer app: starting the UI dev server…");
222
238
  for (;;) {
223
239
  try {
224
- if ((await fetch(origin + "/")).status < 500) break;
240
+ const response = await fetch(origin + "/", { signal: AbortSignal.timeout(2e3) });
241
+ await response.body?.cancel();
242
+ if (response.status < 500) break;
225
243
  } catch {}
226
- await new Promise((done) => setTimeout(done, 500));
244
+ await new Promise((done) => setTimeout(done, 100));
227
245
  }
228
- for (const path of config.ui.warm ?? []) await fetch(origin + path, { signal: AbortSignal.timeout(12e4) }).catch(() => void 0);
246
+ await Promise.all((config.ui.warm ?? []).map((path) => fetch(origin + path, { signal: AbortSignal.timeout(12e4) }).then((response) => response.arrayBuffer()).catch(() => void 0)));
229
247
  log(`developer app: UI on ${origin} (hot reload); starting ${identity.name}`);
230
248
  let shell;
231
249
  let restarting = false;
@@ -256,7 +274,7 @@ async function runDeveloperApp(config, options = {}) {
256
274
  startShell();
257
275
  started();
258
276
  });
259
- stopGroup(running);
277
+ stopGroupWithin(running);
260
278
  })
261
279
  });
262
280
  for (const folder of config.watch ?? ["src"]) watch(join(config.shellDirectory, folder), { recursive: true }, (_event, file) => onChange(file ? String(file) : null));
@@ -1 +1 @@
1
- {"version":"0.39.1","commit":"4b9894a73bdbe3960175c897fa65c64447551953"}
1
+ {"version":"0.39.2","commit":"fea5e125f2bc439593e77b52f4b3660d57308b85"}
@@ -1,22 +1,3 @@
1
- /**
2
- * Language-agnostic sidecar host: runs a bundled executable, written in any
3
- * language, and calls it over stdio with line-delimited JSON.
4
- *
5
- * Wire protocol, one JSON object per line in each direction:
6
- *
7
- * host → sidecar {"id": 1, "command": "name", "args": {...}}
8
- * sidecar → host {"id": 1, "ok": true, "value": ...}
9
- * {"id": 1, "ok": false, "error": "readable message"}
10
- *
11
- * Ids are positive JavaScript-safe integers; replies may arrive in any order.
12
- * A sidecar must exit when its stdin closes so it never outlives the host, and
13
- * should answer a request it cannot parse with `"id": null` (logged here).
14
- *
15
- * The host starts the process on the first call, respawns it on the next call
16
- * after it exits (within the restart budget), and kills it on `stop()` or when
17
- * the host process exits. `call()` never throws: every failure resolves as
18
- * `{ok: false, reason, error}` with a readable message.
19
- */
20
1
  export type SidecarFailure =
21
2
  /** The sidecar answered with `ok: false`. */
22
3
  'command_failed' | 'timeout' | 'aborted' | 'request_too_large' | 'reply_too_large'
@@ -1,4 +1,24 @@
1
+ import { Buffer } from "node:buffer";
1
2
  // src/native/sidecar.ts
3
+ /**
4
+ * Language-agnostic sidecar host: runs a bundled executable, written in any
5
+ * language, and calls it over stdio with line-delimited JSON.
6
+ *
7
+ * Wire protocol, one JSON object per line in each direction:
8
+ *
9
+ * host → sidecar {"id": 1, "command": "name", "args": {...}}
10
+ * sidecar → host {"id": 1, "ok": true, "value": ...}
11
+ * {"id": 1, "ok": false, "error": "readable message"}
12
+ *
13
+ * Ids are positive JavaScript-safe integers; replies may arrive in any order.
14
+ * A sidecar must exit when its stdin closes so it never outlives the host, and
15
+ * should answer a request it cannot parse with `"id": null` (logged here).
16
+ *
17
+ * The host starts the process on the first call, respawns it on the next call
18
+ * after it exits (within the restart budget), and kills it on `stop()` or when
19
+ * the host process exits. `call()` never throws: every failure resolves as
20
+ * `{ok: false, reason, error}` with a readable message.
21
+ */
2
22
  var STOP_GRACE_PERIOD_MS = 1e3;
3
23
  var MAX_REQUEST_ID = Number.MAX_SAFE_INTEGER;
4
24
  var NEWLINE = 10;
@@ -160,19 +180,25 @@ function createSidecar(options) {
160
180
  });
161
181
  else pending.resolve(fail("command_failed", typeof record.error === "string" && record.error ? record.error : `The ${name} command failed`));
162
182
  }
183
+ function boundedStderrTail(text) {
184
+ if (text.length * 3 <= maxStderrBytes) return text;
185
+ const tail = encoder.encode(text);
186
+ if (tail.byteLength <= maxStderrBytes) return text;
187
+ let offset = tail.byteLength - maxStderrBytes;
188
+ while (offset < tail.byteLength && (tail[offset] & 192) === 128) offset++;
189
+ return new TextDecoder().decode(tail.subarray(offset));
190
+ }
163
191
  async function readStderr(stream) {
164
192
  const decoder = new TextDecoder();
165
193
  let buffer = "";
166
194
  const append = (text) => {
167
195
  if (!text) return;
168
- const tail = encoder.encode(stderrTail + text);
169
- let offset = Math.max(0, tail.byteLength - maxStderrBytes);
170
- while (offset < tail.byteLength && (tail[offset] & 192) === 128) offset++;
171
- stderrTail = new TextDecoder().decode(tail.subarray(offset));
196
+ stderrTail += text;
197
+ if (stderrTail.length > 2 * maxStderrBytes) stderrTail = boundedStderrTail(stderrTail);
172
198
  buffer += text;
173
199
  const lines = buffer.split("\n");
174
200
  buffer = lines.pop() ?? "";
175
- if (encoder.encode(buffer).byteLength > maxStderrBytes) buffer = "";
201
+ if (buffer.length > maxStderrBytes || buffer.length * 3 > maxStderrBytes && encoder.encode(buffer).byteLength > maxStderrBytes) buffer = "";
176
202
  for (const line of lines) if (line.trim()) note(`${name}: ${line.slice(0, 4096)}`);
177
203
  };
178
204
  try {
@@ -232,11 +258,11 @@ function createSidecar(options) {
232
258
  id,
233
259
  command,
234
260
  args: args ?? {}
235
- });
261
+ }) + "\n";
236
262
  } catch {
237
263
  return Promise.resolve(fail("invalid_request", `The ${name} request is not JSON`));
238
264
  }
239
- if (encoder.encode(line).byteLength > maxRequestBytes) return Promise.resolve(fail("request_too_large", `The ${name} request is too large`));
265
+ if (Buffer.byteLength(line, "utf8") - 1 > maxRequestBytes) return Promise.resolve(fail("request_too_large", `The ${name} request is too large`));
240
266
  const state = ensure();
241
267
  if (!("process" in state)) return Promise.resolve(state);
242
268
  return new Promise((resolve) => {
@@ -262,7 +288,7 @@ function createSidecar(options) {
262
288
  retire(state, "exited", `The ${name} is not accepting requests`);
263
289
  };
264
290
  try {
265
- Promise.resolve(state.process.stdin.write(line + "\n")).catch(writeFailed);
291
+ Promise.resolve(state.process.stdin.write(line)).catch(writeFailed);
266
292
  Promise.resolve(state.process.stdin.flush()).catch(writeFailed);
267
293
  } catch {
268
294
  writeFailed();
@@ -287,7 +313,7 @@ function createSidecar(options) {
287
313
  get pid() {
288
314
  return running?.process.pid;
289
315
  },
290
- stderr: () => stderrTail
316
+ stderr: () => stderrTail = boundedStderrTail(stderrTail)
291
317
  };
292
318
  }
293
319
  export { createSidecar };
@@ -2,6 +2,8 @@ import { createChannelProofVerifier } from "../desktop/channel-proof.js";
2
2
  import { createLoopbackPolicy } from "../desktop/loopback-policy.js";
3
3
  import { createHash, randomBytes, randomUUID } from "node:crypto";
4
4
  // src/native/window-bootstrap.ts
5
+ /** Every bootstrap request carries the same `{}` body. */
6
+ var EMPTY_OBJECT_SHA256 = createHash("sha256").update("{}").digest("hex");
5
7
  /**
6
8
  * Window-specific proof key and preload. This requires a native renderer that
7
9
  * protects the preload secret from untrusted frames and enforces a navigation
@@ -28,7 +30,7 @@ function createNativeWindowGrant(options) {
28
30
  principal: options.principal
29
31
  } : void 0
30
32
  });
31
- const bodySha256 = createHash("sha256").update("{}").digest("hex");
33
+ const bodySha256 = EMPTY_OBJECT_SHA256;
32
34
  return {
33
35
  origin,
34
36
  preload: `(() => {
@@ -1,6 +1,7 @@
1
1
  import { hasEditableKeyboardTarget } from "./keyboard-target.js";
2
+ import { createMediaQuery } from "./media-query.js";
2
3
  import { className, createComponent, effect, insert, memo, mergeProps, template } from "solid-js/web";
3
- import { For, Show, Suspense, createComputed, createEffect, createSignal, lazy, onCleanup, onMount, untrack } from "solid-js";
4
+ import { For, Show, Suspense, children, createComputed, createEffect, createSignal, lazy, onCleanup, onMount, untrack } from "solid-js";
4
5
  import { AppShell, AppShellBody, AppShellContent, AppShellMain, SkipLink } from "@adea-ai/ui/components/layout/app-shell";
5
6
  import { ContextualSidebar } from "@adea-ai/ui/components/layout/contextual-sidebar";
6
7
  import { PixelPane } from "@adea-ai/ui/components/layout/pixel-pane";
@@ -14,30 +15,14 @@ import { PanelLeftClose, PanelLeftIcon, PanelLeftOpen } from "lucide-solid";
14
15
  var _tmpl$ = /*#__PURE__*/ template(`<div>`);
15
16
  var _tmpl$2 = /*#__PURE__*/ template(`<div data-slot=app-shell-main class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">`);
16
17
  var NavigationDrawer = lazy(() => import("./navigation-drawer.js").then((module) => ({ default: module.NavigationDrawer })));
17
- function createNarrow(query) {
18
- const [narrow, setNarrow] = createSignal(false);
19
- createEffect(() => {
20
- const value = query();
21
- if (!value || typeof window === "undefined" || !window.matchMedia) return setNarrow(false);
22
- const media = window.matchMedia(value);
23
- const update = () => setNarrow(media.matches);
24
- update();
25
- media.addEventListener("change", update);
26
- onCleanup(() => media.removeEventListener("change", update));
27
- });
28
- return narrow;
29
- }
30
18
  function getSidebarResponsiveMode(sidebar) {
31
- if (sidebar && "responsiveMode" in sidebar) {
32
- const mode = sidebar.responsiveMode;
33
- if (mode === "auto" || mode === "desktop" || mode === "mobile") return mode;
34
- }
19
+ return sidebar?.responsiveMode;
35
20
  }
36
21
  /** Shared chrome and navigation composition; applications own routes and services. */
37
22
  function ApplicationShell(props) {
38
23
  let sidebarToggle;
39
- const narrow = createNarrow(() => props.drawer ? props.narrowQuery ?? "(max-width: 799px)" : void 0);
40
- const sidebarMobile = createNarrow(() => !props.drawer && props.sidebar ? "(max-width: 48rem)" : void 0);
24
+ const narrow = createMediaQuery(() => props.drawer ? props.narrowQuery ?? "(max-width: 799px)" : void 0);
25
+ const sidebarMobile = createMediaQuery(() => !props.drawer && props.sidebar ? "(max-width: 48rem)" : void 0);
41
26
  const [sidebarElementMobile, setSidebarElementMobile] = createSignal();
42
27
  const sidebarElements = /* @__PURE__ */ new Map();
43
28
  const sidebarElementCallbacks = /* @__PURE__ */ new Map();
@@ -130,6 +115,49 @@ function ApplicationShell(props) {
130
115
  window.removeEventListener("keydown", handleToggle);
131
116
  });
132
117
  });
118
+ const RailContent = () => {
119
+ const rail = children(() => props.rail);
120
+ return createComponent(Show, {
121
+ get when() {
122
+ return rail();
123
+ },
124
+ get fallback() {
125
+ return createComponent(SideRailSection, {
126
+ label: "Views",
127
+ get children() {
128
+ return createComponent(For, {
129
+ get each() {
130
+ return props.destinations;
131
+ },
132
+ children: (item) => createComponent(SideRailItem, {
133
+ as: "button",
134
+ type: "button",
135
+ get label() {
136
+ return item.label;
137
+ },
138
+ get ["aria-label"]() {
139
+ return item.label;
140
+ },
141
+ get active() {
142
+ return props.activeDestination === item.id;
143
+ },
144
+ get ["aria-pressed"]() {
145
+ return props.activeDestination === item.id;
146
+ },
147
+ onClick: () => props.onNavigate(item.id),
148
+ get children() {
149
+ return item.icon;
150
+ }
151
+ })
152
+ });
153
+ }
154
+ });
155
+ },
156
+ get children() {
157
+ return rail();
158
+ }
159
+ });
160
+ };
133
161
  return createComponent(TooltipProvider, {
134
162
  openDelay: 150,
135
163
  get children() {
@@ -259,46 +287,7 @@ function ApplicationShell(props) {
259
287
  return props.footer;
260
288
  },
261
289
  get children() {
262
- return createComponent(Show, {
263
- get when() {
264
- return props.rail;
265
- },
266
- get fallback() {
267
- return createComponent(SideRailSection, {
268
- label: "Views",
269
- get children() {
270
- return createComponent(For, {
271
- get each() {
272
- return props.destinations;
273
- },
274
- children: (item) => createComponent(SideRailItem, {
275
- as: "button",
276
- type: "button",
277
- get label() {
278
- return item.label;
279
- },
280
- get ["aria-label"]() {
281
- return item.label;
282
- },
283
- get active() {
284
- return props.activeDestination === item.id;
285
- },
286
- get ["aria-pressed"]() {
287
- return props.activeDestination === item.id;
288
- },
289
- onClick: () => props.onNavigate(item.id),
290
- get children() {
291
- return item.icon;
292
- }
293
- })
294
- });
295
- }
296
- });
297
- },
298
- get children() {
299
- return props.rail;
300
- }
301
- });
290
+ return createComponent(RailContent, {});
302
291
  }
303
292
  });
304
293
  }
@@ -70,7 +70,7 @@ function ApplicationUtilities(props) {
70
70
  if (changed) props.settings?.onSectionChange?.(id);
71
71
  };
72
72
  const settingsOpen = () => props.settings?.open !== void 0 ? props.settings.open : dialog() === "settings";
73
- const updatesAlways = () => props.accountMenu?.updates === "always";
73
+ const updatesAlways = createMemo(() => props.accountMenu?.updates === "always");
74
74
  const updateAdapter = createMemo(() => props.updater ?? browserUpdateAdapter(props.identity.version));
75
75
  const markMounted = (value) => {
76
76
  if (!mounted().has(value)) setMounted((current) => new Set(current).add(value));
@@ -147,20 +147,27 @@ function ApplicationUtilities(props) {
147
147
  });
148
148
  });
149
149
  const close = () => show(void 0);
150
- const items = () => {
151
- const menu = props.accountMenu;
150
+ const menuSettingsShortcut = createMemo(() => props.accountMenu?.settingsShortcut);
151
+ const menuSettingsKeyshortcuts = createMemo(() => props.accountMenu?.settingsKeyshortcuts ?? "Meta+, Control+,");
152
+ const menuAppearance = createMemo(() => props.accountMenu?.appearance !== false);
153
+ const hasSettings = createMemo(() => Boolean(props.settings));
154
+ const hasHelp = createMemo(() => Boolean(props.help));
155
+ const hasUpdates = createMemo(() => Boolean(props.updater || props.onUpdates || updatesAlways()));
156
+ const items = createMemo(() => {
157
+ const onSettings = props.onSettings;
158
+ const onHelp = props.onHelp;
152
159
  const shared = createAppMenuItems({
153
160
  primaryItem: props.primaryItem,
154
- settingsShortcut: menu?.settingsShortcut,
161
+ settingsShortcut: menuSettingsShortcut(),
155
162
  onAbout: (target) => open("about", target),
156
- onUpdates: props.updater || props.onUpdates || updatesAlways() ? (target) => openUpdates(target) : void 0,
157
- onSettings: props.onSettings ?? (props.settings ? (target) => openSettings(void 0, target) : void 0),
158
- onHelp: props.onHelp ?? (props.help ? (target) => open("help", target) : void 0),
163
+ onUpdates: hasUpdates() ? (target) => openUpdates(target) : void 0,
164
+ onSettings: onSettings ?? (hasSettings() ? (target) => openSettings(void 0, target) : void 0),
165
+ onHelp: onHelp ?? (hasHelp() ? (target) => open("help", target) : void 0),
159
166
  onFeedback: props.onFeedback
160
167
  }).map((item) => {
161
168
  if (item.id === "settings" && item.shortcut) return {
162
169
  ...item,
163
- keyshortcuts: menu?.settingsKeyshortcuts ?? "Meta+, Control+,"
170
+ keyshortcuts: menuSettingsKeyshortcuts()
164
171
  };
165
172
  if (item.id === "updates" && updatesAlways()) return {
166
173
  ...item,
@@ -168,14 +175,14 @@ function ApplicationUtilities(props) {
168
175
  };
169
176
  return item;
170
177
  });
171
- if (menu?.appearance === false) return shared;
178
+ if (!menuAppearance()) return shared;
172
179
  return [{
173
180
  id: "appearance",
174
181
  label: "Appearance",
175
182
  icon: createComponent(Palette, { "aria-hidden": "true" }),
176
183
  onSelectAfterClose: (target) => open("appearance", target)
177
184
  }, ...shared];
178
- };
185
+ });
179
186
  return [createComponent(AccountMenu, {
180
187
  get items() {
181
188
  return items();
@@ -3,6 +3,7 @@ export declare const DEFAULT_NARROW_QUERY = "(max-width: 799px)";
3
3
  /**
4
4
  * Reactive `matchMedia`. Components watching the same query share one listener. The query
5
5
  * may be reactive and the subscription follows it; an empty or absent query, or a runtime
6
- * without `matchMedia`, reads as not matching.
6
+ * without `matchMedia`, reads as not matching. The first read already reflects the window, so
7
+ * a narrow window never renders its wide layout for a frame and then swaps it out.
7
8
  */
8
9
  export declare function createMediaQuery(query: string | (() => string | undefined)): () => boolean;
@@ -1,4 +1,4 @@
1
- import { createEffect, createSignal, onCleanup } from "solid-js";
1
+ import { createComputed, createSignal, onCleanup } from "solid-js";
2
2
  // src/shell/media-query.ts
3
3
  /** When the application shell counts a window as narrow. */
4
4
  var DEFAULT_NARROW_QUERY = "(max-width: 799px)";
@@ -33,12 +33,13 @@ function subscribe(query, subscriber) {
33
33
  /**
34
34
  * Reactive `matchMedia`. Components watching the same query share one listener. The query
35
35
  * may be reactive and the subscription follows it; an empty or absent query, or a runtime
36
- * without `matchMedia`, reads as not matching.
36
+ * without `matchMedia`, reads as not matching. The first read already reflects the window, so
37
+ * a narrow window never renders its wide layout for a frame and then swaps it out.
37
38
  */
38
39
  function createMediaQuery(query) {
39
40
  const text = typeof query === "function" ? query : () => query;
40
41
  const [matches, setMatches] = createSignal(false);
41
- createEffect(() => {
42
+ createComputed(() => {
42
43
  const value = text();
43
44
  if (!value || !supported()) {
44
45
  setMatches(false);
@@ -632,14 +632,14 @@ class UpdateLockBusyError extends Error {
632
632
  }
633
633
  }
634
634
  async function acquireUpdateLock(target, timeoutMs = 5000) {
635
- const deadline = Date.now() + timeoutMs;
635
+ const deadline = performance.now() + timeoutMs;
636
636
  while (true) {
637
637
  const lock = await tryAcquireUpdateLock(target);
638
638
  if (lock)
639
639
  return lock;
640
- if (Date.now() >= deadline)
640
+ if (performance.now() >= deadline)
641
641
  throw new UpdateLockBusyError;
642
- await Bun.sleep(Math.min(25, Math.max(1, deadline - Date.now())));
642
+ await Bun.sleep(Math.min(25, Math.max(1, deadline - performance.now())));
643
643
  }
644
644
  }
645
645
  function parseState(value) {
@@ -793,7 +793,7 @@ async function readUpdateTreeDigest(tree, options = {}) {
793
793
  }
794
794
  if (before.isDirectory()) {
795
795
  writeRecord("directory", relative, before.mode, 0n);
796
- const names = (await readdir(path)).toSorted((left, right) => Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")));
796
+ const names = (await readdir(path)).map((name) => ({ name, bytes: Buffer.from(name, "utf8") })).toSorted((left, right) => Buffer.compare(left.bytes, right.bytes)).map(({ name }) => name);
797
797
  for (const name of names) {
798
798
  const child = relative ? `${relative}/${name}` : name;
799
799
  await visit(join6(path, name), child);