@adea-ai/app-framework 0.39.0 → 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 +108 -0
  2. package/ci/desktop-release.sh +15 -33
  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 +2 -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
@@ -0,0 +1,108 @@
1
+ # shellcheck shell=bash
2
+ # Release-feed steps (an S3-compatible bucket such as Cloudflare R2) of adea-desktop-release,
3
+ # sourced by ci/desktop-release.sh and by its tests. The caller defines `say` and `sha256` and sets
4
+ # bucket, work, out and dry, plus R2_ENDPOINT or CLOUDFLARE_ACCOUNT_ID, R2_ACCESS_KEY_ID and
5
+ # R2_SECRET_ACCESS_KEY.
6
+
7
+ feed_s3() {
8
+ AWS_ACCESS_KEY_ID="$R2_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY="$R2_SECRET_ACCESS_KEY" \
9
+ AWS_DEFAULT_REGION=auto AWS_REQUEST_CHECKSUM_CALCULATION=when_required \
10
+ aws s3api "$@" --bucket "$bucket" \
11
+ --endpoint-url "${R2_ENDPOINT:-https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com}" --output text
12
+ }
13
+
14
+ # Prints "<size> <sha256>" for the stored <key> (the digest from its sha256 metadata, or "None"
15
+ # for an object uploaded without it), or nothing when the feed has no such object. Any other HEAD
16
+ # failure (credentials, network, throttling) is not evidence of absence, so it fails.
17
+ feed_object_head() { # <key>
18
+ local head err
19
+ if head=$(feed_s3 head-object --key "$1" --query '[ContentLength, Metadata.sha256]' 2>"$work/head.err"); then
20
+ printf '%s\n' "$head" | tr '\t' ' '
21
+ return 0
22
+ fi
23
+ err=$(cat "$work/head.err")
24
+ case "$err" in
25
+ *'(404)'* | *'Not Found'* | *NoSuchKey*) return 0 ;;
26
+ esac
27
+ say "refusing: could not tell whether $1 exists: $err" >&2
28
+ return 1
29
+ }
30
+
31
+ # True only when the stored <key> holds exactly <size> bytes whose SHA-256 is <digest>. An object
32
+ # of the same size from an interrupted or different upload is not the staged file: the digest is
33
+ # compared from the object's sha256 metadata, or from its downloaded bytes when it has none.
34
+ feed_object_matches() { # <key> <size> <digest>
35
+ local head stored_size stored_digest copy="$work/existing-object" actual
36
+ head=$(feed_object_head "$1") || return 1
37
+ [ -n "$head" ] || return 1
38
+ read -r stored_size stored_digest <<<"$head"
39
+ [ "$stored_size" = "$2" ] || return 1
40
+ if [ -n "$stored_digest" ] && [ "$stored_digest" != None ]; then
41
+ [ "$stored_digest" = "$3" ]
42
+ return
43
+ fi
44
+ rm -f "$copy"
45
+ feed_s3 get-object --key "$1" "$copy" >/dev/null || { say "refusing: could not read the existing $1"; return 1; }
46
+ actual=$(sha256 "$copy")
47
+ rm -f "$copy"
48
+ [ "$actual" = "$3" ]
49
+ }
50
+
51
+ # What clients follow to find a release: the channel pointers and any installers. They go up
52
+ # only after the release they name has verified from the feed.
53
+ feed_live_key() { # <key>
54
+ case "$1" in */channels/* | */install/*) return 0 ;; *) return 1 ;; esac
55
+ }
56
+
57
+ # Uploads one phase of the staged plan, in plan order. `content` is the release itself (immutable
58
+ # files, release.json and the ledger); `live` is the channel pointers and installers, uploaded
59
+ # after the content verified. An immutable file is written only if absent (If-None-Match), and an
60
+ # existing one must already hold the same bytes. Every write stores its SHA-256 as metadata and is
61
+ # read back by size and digest.
62
+ upload() { # <content|live>
63
+ local phase=${1:?content|live} plan="$out/upload-plan.json" key size digest type cache file put_err
64
+ bun -e '
65
+ const plan = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))
66
+ for (const o of plan.objects) console.log([o.key, o.size, o.sha256, o.contentType, o.cacheControl].join("\t"))' "$plan" |
67
+ while IFS=$'\t' read -r key rest; do
68
+ if feed_live_key "$key"; then [ "$phase" = live ] || continue; else [ "$phase" = content ] || continue; fi
69
+ printf '%s\t%s\n' "$key" "$rest"
70
+ done > "$work/objects-$phase.tsv"
71
+ say "upload $phase ($(wc -l < "$work/objects-$phase.tsv" | tr -d ' ') objects, in order) to s3://$bucket via R2 S3 API:"
72
+ cut -f1,2 "$work/objects-$phase.tsv" | sed 's/^/ /'
73
+ [ -z "$dry" ] || { say "dry run: nothing uploaded"; return 0; }
74
+ while IFS=$'\t' read -r key size digest type cache; do
75
+ file="$out/$key"
76
+ [ "$(wc -c < "$file" | tr -d ' ')" = "$size" ] && [ "$(sha256 "$file")" = "$digest" ] ||
77
+ { say "refusing: $key changed after staging"; exit 1; }
78
+ if [ "$cache" != no-cache ]; then
79
+ if feed_s3 put-object --key "$key" --body "$file" --content-type "$type" --cache-control "$cache" \
80
+ --metadata "sha256=$digest" --if-none-match '*' >/dev/null 2>"$work/put.err"; then
81
+ say " uploaded $key"
82
+ else
83
+ put_err=$(cat "$work/put.err")
84
+ case "$put_err" in
85
+ *'(412)'* | *PreconditionFailed*) ;;
86
+ *) say "refusing: upload of $key failed: $put_err"; exit 1 ;;
87
+ esac
88
+ feed_object_matches "$key" "$size" "$digest" ||
89
+ { say "refusing: immutable $key exists with other bytes"; exit 1; }
90
+ say " exists $key"
91
+ continue
92
+ fi
93
+ else
94
+ feed_s3 put-object --key "$key" --body "$file" --content-type "$type" --cache-control "$cache" \
95
+ --metadata "sha256=$digest" >/dev/null
96
+ say " uploaded $key"
97
+ fi
98
+ feed_object_matches "$key" "$size" "$digest" || { say "upload of $key did not verify"; exit 1; }
99
+ done < "$work/objects-$phase.tsv"
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
+ }
@@ -2,8 +2,8 @@
2
2
  # adea-desktop-release: publish a desktop release from a release tag pipeline (GitLab CI, CircleCI or
3
3
  # GitHub Actions) with the framework's local release mode. It builds this machine's platform (macOS arm64 or Linux x64),
4
4
  # signs the channel descriptors, uploads the staged tree to the app's release feed (an
5
- # S3-compatible bucket such as Cloudflare R2) in plan order with the channel pointers last,
6
- # verifies the feed and links every published file on the GitLab release.
5
+ # S3-compatible bucket such as Cloudflare R2), verifies the release from the feed, then uploads the
6
+ # channel pointers clients follow, and links every published file on the GitLab release.
7
7
  #
8
8
  # adea-desktop-release daily build and publish the tag's daily (CI_COMMIT_TAG = v<version>)
9
9
  # adea-desktop-release stable promote the newest qualified daily after the soak
@@ -40,10 +40,16 @@ if [ -z "${CI_COMMIT_TAG:-}" ]; then
40
40
  [ -n "$CI_COMMIT_TAG" ] || [ "${GITHUB_REF_TYPE:-}" != tag ] || CI_COMMIT_TAG=${GITHUB_REF_NAME:-}
41
41
  fi
42
42
  CI_COMMIT_SHA=${CI_COMMIT_SHA:-${CIRCLE_SHA1:-${GITHUB_SHA:-}}}
43
- CI_PIPELINE_ID=${CI_PIPELINE_ID:-${CIRCLE_WORKFLOW_ID:-${GITHUB_RUN_ID:-}}}
43
+ # The run id signs into the descriptors and must be a positive integer: CircleCI's build number,
44
+ # not its workflow id (a UUID).
45
+ CI_PIPELINE_ID=${CI_PIPELINE_ID:-${CIRCLE_BUILD_NUM:-${GITHUB_RUN_ID:-}}}
44
46
  sha256() { if command -v shasum >/dev/null; then shasum -a 256 "$1"; else sha256sum "$1"; fi | cut -d' ' -f1; }
45
47
  b64d() { printf '%s' "$1" | base64 -d 2>/dev/null || printf '%s' "$1" | base64 -D; }
46
48
 
49
+ # upload and the feed's other bucket steps, beside this script in the installed package.
50
+ # shellcheck source=ci/desktop-release-feed.sh
51
+ source "$(dirname "$(readlink -f "$0")")/desktop-release-feed.sh"
52
+
47
53
  root=$(git rev-parse --show-toplevel)
48
54
  cd "$root"
49
55
  sha=${CI_COMMIT_SHA:-}
@@ -94,34 +100,6 @@ extend_plan() { # <channel> <tag> <released sha>
94
100
  else rc=$?; [ "$rc" = 3 ] || exit "$rc"; fi
95
101
  }
96
102
 
97
- # Uploads the staged plan in order: immutable files first (an existing one must already hold the
98
- # same bytes), channel pointers last, each verified by size after the upload.
99
- upload() {
100
- local plan="$out/upload-plan.json"
101
- bun -e '
102
- const plan = JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))
103
- for (const o of plan.objects) console.log([o.key, o.size, o.sha256, o.contentType, o.cacheControl].join("\t"))' "$plan" > "$work/objects.tsv"
104
- say "upload plan ($(wc -l < "$work/objects.tsv" | tr -d ' ') objects, in order) to s3://$bucket via R2 S3 API:"
105
- cut -f1,2 "$work/objects.tsv" | sed 's/^/ /'
106
- [ -z "$dry" ] || { say "dry run: nothing uploaded"; return 0; }
107
- local endpoint=${R2_ENDPOINT:-https://$CLOUDFLARE_ACCOUNT_ID.r2.cloudflarestorage.com}
108
- s3() { AWS_ACCESS_KEY_ID="$R2_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY="$R2_SECRET_ACCESS_KEY" \
109
- AWS_DEFAULT_REGION=auto AWS_REQUEST_CHECKSUM_CALCULATION=when_required \
110
- aws s3api "$@" --bucket "$bucket" --endpoint-url "$endpoint" --output text; }
111
- while IFS=$'\t' read -r key size digest type cache; do
112
- file="$out/$key"
113
- [ "$(wc -c < "$file" | tr -d ' ')" = "$size" ] && [ "$(sha256 "$file")" = "$digest" ] ||
114
- { say "refusing: $key changed after staging"; exit 1; }
115
- if [ "$cache" != no-cache ] && existing=$(s3 head-object --key "$key" --query ContentLength 2>/dev/null); then
116
- [ "$existing" = "$size" ] || { say "refusing: immutable $key exists with other bytes"; exit 1; }
117
- say " exists $key"; continue
118
- fi
119
- s3 put-object --key "$key" --body "$file" --content-type "$type" --cache-control "$cache" >/dev/null
120
- [ "$(s3 head-object --key "$key" --query ContentLength)" = "$size" ] || { say "upload of $key did not verify"; exit 1; }
121
- say " uploaded $key"
122
- done < "$work/objects.tsv"
123
- }
124
-
125
103
  # Links every published file of <tag> on its GitLab release (creating the release when release
126
104
  # tooling has not), pointing at the feed. Links that already exist are kept.
127
105
  link_release() { # <tag>
@@ -129,6 +107,8 @@ link_release() { # <tag>
129
107
  if [ -n "${CI_JOB_TOKEN:-}" ]; then header=JOB-TOKEN token=$CI_JOB_TOKEN
130
108
  elif [ -n "${GITLAB_RELEASE_TOKEN:-}" ]; then header=PRIVATE-TOKEN token=$GITLAB_RELEASE_TOKEN; fi
131
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
132
112
  if [ -z "$project" ]; then
133
113
  # The origin remote's path (https://host/<path>.git or git@host:<path>.git), URL-encoded.
134
114
  project=${GITLAB_PROJECT:-$(git -C "$root" remote get-url origin)}
@@ -173,8 +153,9 @@ if [ "$channel" = stable ]; then
173
153
  [ -n "$tag" ] || { say "nothing to promote"; exit 0; }
174
154
  released=$(bun -e 'const l=require(process.argv[1]);console.log(l.releases.find(r=>r.tag===process.argv[2]).sourceSha)' "$out/$repo/index.json" "$tag")
175
155
  extend_plan stable "$tag" "$released"
176
- upload
156
+ upload content
177
157
  [ -n "$dry" ] || bun "$cli/release-finalize-cli.js" --local release-config.json "$tag"
158
+ upload live
178
159
  exit 0
179
160
  fi
180
161
 
@@ -222,7 +203,8 @@ bun -e '
222
203
  if (missing.length) { console.error("command artifacts missing from the plan: " + missing.join(", ")); process.exit(1) }' \
223
204
  "$out/upload-plan.json" "$PWD/release-config.json" "$repo" "$tag" "$platform"
224
205
  extend_plan daily "$tag" "$sha"
225
- upload
206
+ upload content
226
207
  verified=$(bun "$cli/release-finalize-cli.js" --local release-config.json "$tag")
227
208
  say "verified from the feed: $verified"
209
+ upload live
228
210
  link_release "$tag"
@@ -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.0","commit":"a96af4fbc2012cc05a0fa1cfed906934dfdc7ac5"}
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: `(() => {