@amd-gaia/agent-ui 0.25.4 → 0.26.0-rc.10

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 (33) hide show
  1. package/bin/gaia-ui.cjs +19 -16
  2. package/dist/assets/AdvancedSettings-w9D1AXlP.js +1 -0
  3. package/dist/assets/ConnectorsPane-B1lwOGL5.css +1 -0
  4. package/dist/assets/ConnectorsPane-BxnbIY7k.js +1 -0
  5. package/dist/assets/{DocumentLibrary-2IMvlsjP.js → DocumentLibrary-BwCg6OBt.js} +2 -2
  6. package/dist/assets/FileBrowser-ZQ8nEd3a.js +4 -0
  7. package/dist/assets/MemoryDashboard-DDIIbL38.js +1 -0
  8. package/dist/assets/MobileAccessModal-DgmEaSve.js +2 -0
  9. package/dist/assets/{ScheduleManager-D_KcT6nO.js → ScheduleManager-5ISmwd1h.js} +1 -1
  10. package/dist/assets/api-B8v2Xp8S.js +4 -0
  11. package/dist/assets/index--tVNC0Jc.js +83 -0
  12. package/dist/assets/index-r-CFg5BV.css +1 -0
  13. package/dist/assets/useT-ByY7OhOj.js +3 -0
  14. package/dist/assets/{zap-FkXztfRB.js → zap-D6QQWCNv.js} +1 -1
  15. package/dist/index.html +4 -4
  16. package/dist/sw.js +1 -1
  17. package/main.cjs +29 -4
  18. package/package.json +2 -1
  19. package/services/auto-updater.cjs +10 -0
  20. package/services/backend-installer.cjs +230 -512
  21. package/services/quit-guard.cjs +25 -6
  22. package/services/tray-host.cjs +1 -1
  23. package/services/tray-manager.cjs +32 -5
  24. package/dist/assets/AdvancedSettings-Dkjf4LIp.js +0 -1
  25. package/dist/assets/ConnectorsPane-CIV89VVI.js +0 -1
  26. package/dist/assets/ConnectorsPane-CzLYXGMl.css +0 -1
  27. package/dist/assets/FileBrowser-DMnjs5do.js +0 -4
  28. package/dist/assets/MemoryDashboard-BAqXtg9o.js +0 -1
  29. package/dist/assets/MobileAccessModal-CrtIKCP3.js +0 -2
  30. package/dist/assets/api-D5mTAXjB.js +0 -4
  31. package/dist/assets/index-B7tI0eKR.css +0 -1
  32. package/dist/assets/index-CsgZhHsw.js +0 -80
  33. package/dist/assets/useT-CtECS-vp.js +0 -3
@@ -4,8 +4,10 @@
4
4
  /**
5
5
  * backend-installer.cjs — Shared GAIA Python backend bootstrap logic.
6
6
  *
7
- * Single source of truth for installing / upgrading the GAIA Python backend
8
- * (`~/.gaia/venv` with `amd-gaia[ui]==<pinned-version>`). Called from both:
7
+ * Single source of truth for the GAIA backend the app runs. A packaged app
8
+ * runs the frozen `gaia` it ships (<resources>/core) and installs nothing; run
9
+ * from source, it installs `~/.gaia/venv` with `amd-gaia[ui]==<pinned-version>`.
10
+ * Called from both:
9
11
  *
10
12
  * - `bin/gaia-ui.cjs` (the npm CLI entry point)
11
13
  * - `main.cjs` (the Electron app, on first-run bootstrap)
@@ -17,7 +19,7 @@
17
19
  * - installBackend(opts) → Promise<void>
18
20
  * - ensureBackend(opts) → Promise<string> (returns gaia bin path)
19
21
  * - isBackendCurrent() → boolean (nothing to install or refresh)
20
- * - stopRunningDaemon(opts) → Promise<void> (before the venv is touched)
22
+ * - stopRunningDaemon(opts) → Promise<void> (before its files are replaced)
21
23
  * - getInstalledVersion(gaiaBin) → string | null
22
24
  * - findGaiaBin() → string | null
23
25
  * - getState() / setState() → state machine helpers
@@ -33,8 +35,7 @@
33
35
 
34
36
  "use strict";
35
37
 
36
- const { spawn, spawnSync, execSync } = require("child_process");
37
- const crypto = require("crypto");
38
+ const { spawn, spawnSync, execFileSync } = require("child_process");
38
39
  const fs = require("fs");
39
40
  const path = require("path");
40
41
  const os = require("os");
@@ -55,6 +56,16 @@ const GAIA_PYTHON_BIN = IS_WINDOWS
55
56
  ? path.join(GAIA_VENV, "Scripts", "python.exe")
56
57
  : path.join(GAIA_VENV, "bin", "python");
57
58
 
59
+ // The frozen `gaia` a packaged app ships (installer/core/freeze.py). A packaged
60
+ // app runs only this one; the venv below is for running the app from source.
61
+ const BUNDLED_GAIA_BIN = process.resourcesPath
62
+ ? path.join(process.resourcesPath, "core", IS_WINDOWS ? "gaia.exe" : "gaia")
63
+ : null;
64
+ // Not ~/.gaia/core: install.sh unpacks its own gaia there.
65
+ const APPIMAGE_CORE_ROOT = path.join(GAIA_HOME, "app-core");
66
+ // Written last, so a copy a quit cut short is redone.
67
+ const APPIMAGE_CORE_DONE = ".copied";
68
+
58
69
  const STATE_FILE = path.join(GAIA_HOME, "electron-install-state.json");
59
70
  const LOG_FILE = path.join(GAIA_HOME, "electron-install.log");
60
71
  // hub/installer.py writes this once the flagship is installed; first-run setup installs it.
@@ -78,55 +89,6 @@ const NETWORK_CHECK_TIMEOUT_MS = 5000;
78
89
  const INSTALL_MAX_ATTEMPTS = 3;
79
90
  const INSTALL_RETRY_BACKOFF_MS = 3000;
80
91
 
81
- // ── Bundled `uv` binary ──────────────────────────────────────────────────────
82
- //
83
- // Issue #782 / T3: the AppImage now ships a pinned `uv` under
84
- // `extraResources` (see electron-builder.yml). At runtime we copy it into
85
- // `~/.gaia/bin/uv` with atomic-rename + SHA256 verification. The previous
86
- // `curl | sh` path is retained only as an unpackaged-dev fallback so
87
- // contributors running from source keep working.
88
- //
89
- // When bumping uv, update:
90
- // - .github/workflows/build-installers.yml (tarball .tar.gz SHA256 — archive)
91
- // - BUNDLED_UV_SHA256 below (extracted binary SHA256, linux-x64/win-x64 only)
92
- //
93
- // IMPORTANT: per-platform verification strategy differs:
94
- // - linux-x64 / win-x64: BUNDLED_UV_SHA256 pins the raw extracted-binary
95
- // digest (no post-build modification) — deterministic across CI runs.
96
- // - mac-arm64: NOT pinned here. electron-builder code-signs the bundled uv
97
- // during packaging (ad-hoc `identity=-` when no Developer ID cert is
98
- // configured, which is every CI build today), and ad-hoc codesign output
99
- // depends on the codesign/Xcode toolchain baked into the GitHub-hosted
100
- // `macos-latest` runner image — which floats and is NOT reproducible
101
- // across CI runs (observed: macos-15-arm64 vs macos-26-arm64 images
102
- // produced two different digests for byte-identical source). A fixed
103
- // SHA256 pin is therefore not deterministic on macOS and would fail
104
- // ~half of CI runs and brick first-launch on user machines whenever the
105
- // runner image rolls. Instead, ensureUv() and the dmg-structural-smoke
106
- // test both run `codesign --verify --strict` against the bundled binary
107
- // — this validates the on-disk signature is intact/untampered without
108
- // depending on the exact signing bytes, and still fails loud on
109
- // corruption or an actually-invalid signature.
110
- const BUNDLED_UV_VERSION = "0.5.14";
111
- const BUNDLED_UV_SHA256 = {
112
- "linux-x64": "0e05d828b5708e8a927724124db3746396afddad6273c47283d7c562dc795bd6",
113
- // The Windows extracted uv.exe SHA is populated by CI during the
114
- // build step. The placeholder MUST be replaced in CI before packaging
115
- // so runtime verification remains strict.
116
- "win-x64": "055d55eec85a91cfb5e9c8bc7f6463f9883866796c5bcb205fbcdfed9c088c88",
117
- // mac-arm64: intentionally absent. See the comment block above — the
118
- // post-codesign digest is not deterministic across CI runner images, so
119
- // mac-arm64 is verified via codesignVerify() (identity/signature validity)
120
- // instead of a fixed SHA256 pin. bundledUvPlatformKey() still returns
121
- // "mac-arm64"; callers must not treat a missing entry here as "unpinned
122
- // platform" for darwin — see ensureUv()/installBundledUv().
123
- };
124
-
125
- const MANAGED_UV_DIR = path.join(GAIA_HOME, "bin");
126
- const MANAGED_UV_BIN = IS_WINDOWS
127
- ? path.join(MANAGED_UV_DIR, "uv.exe")
128
- : path.join(MANAGED_UV_DIR, "uv");
129
-
130
92
  const STATES = Object.freeze({
131
93
  IDLE: "idle",
132
94
  INSTALLING: "installing",
@@ -437,22 +399,79 @@ function makeProgressReporter(onProgress) {
437
399
  // ── Command helpers ──────────────────────────────────────────────────────────
438
400
 
439
401
  /**
440
- * Check if a command exists on PATH.
402
+ * Check if a command exists on PATH. Throws when the lookup itself can't run.
441
403
  */
442
404
  function commandExists(cmd) {
443
- try {
444
- const check = IS_WINDOWS ? `where ${cmd}` : `command -v ${cmd}`;
445
- execSync(check, { stdio: "ignore" });
446
- return true;
447
- } catch {
448
- return false;
405
+ // `command -v` is a shell built-in, so it works where `which` isn't installed; the name is $1, never script text.
406
+ const [file, args] = IS_WINDOWS
407
+ ? ["where", [cmd]]
408
+ : ["sh", ["-c", 'command -v "$1"', "sh", cmd]];
409
+ const result = spawnSync(file, args, { stdio: "ignore", shell: false, windowsHide: true });
410
+ if (result.error || result.status === null) {
411
+ const reason = result.error ? result.error.message : `killed by ${result.signal}`;
412
+ throw new InstallError(`Could not check whether "${cmd}" is on PATH: running ${file} failed (${reason}).`, {
413
+ code: result.error ? result.error.code : null,
414
+ suggestion: IS_WINDOWS
415
+ ? "Make sure C:\\Windows\\System32 is on PATH, then restart GAIA."
416
+ : "Make sure /bin/sh exists and /bin is on PATH, then restart GAIA.",
417
+ });
449
418
  }
419
+ return result.status === 0;
420
+ }
421
+
422
+ /** The `gaia` this packaged app ships, or null when it ships none. */
423
+ function shippedGaiaBin() {
424
+ return BUNDLED_GAIA_BIN && fs.existsSync(BUNDLED_GAIA_BIN) ? BUNDLED_GAIA_BIN : null;
425
+ }
426
+
427
+ /** Where an AppImage keeps its copy of the shipped core for this version. */
428
+ function appImageCoreDir() {
429
+ return path.join(APPIMAGE_CORE_ROOT, toPep440(appVersion()));
450
430
  }
451
431
 
452
432
  /**
453
- * Find the gaia binary — prefer the managed venv, fall back to PATH.
433
+ * The shipped `gaia` as the app runs it, or null until it can run. An
434
+ * AppImage's files vanish when the app quits, and the daemon outlives the app,
435
+ * so an AppImage runs a copy under ~/.gaia once ensureBundledCore has made it.
436
+ */
437
+ function bundledGaiaBin() {
438
+ const shipped = shippedGaiaBin();
439
+ if (!shipped || !process.env.APPIMAGE) return shipped;
440
+ const dir = appImageCoreDir();
441
+ return fs.existsSync(path.join(dir, APPIMAGE_CORE_DONE)) ? path.join(dir, path.basename(shipped)) : null;
442
+ }
443
+
444
+ /** bundledGaiaBin, after copying an AppImage's core out of its mount. */
445
+ async function ensureBundledCore() {
446
+ const shipped = shippedGaiaBin();
447
+ if (!shipped || !process.env.APPIMAGE) return shipped;
448
+ const ready = bundledGaiaBin();
449
+ if (ready) return ready;
450
+ const dir = appImageCoreDir();
451
+ log(`Copying the backend out of the AppImage to ${dir}`);
452
+ fs.rmSync(dir, { recursive: true, force: true });
453
+ await fs.promises.cp(path.dirname(shipped), dir, { recursive: true, verbatimSymlinks: true });
454
+ fs.writeFileSync(path.join(dir, APPIMAGE_CORE_DONE), appVersion());
455
+ const copy = bundledGaiaBin();
456
+ const older = listDir(APPIMAGE_CORE_ROOT).filter((name) => name !== path.basename(dir));
457
+ if (older.length) {
458
+ // A daemon from an older copy reads its files as it runs, so it stops first.
459
+ await stopRunningDaemon({ gaiaBin: copy });
460
+ for (const name of older) {
461
+ fs.rmSync(path.join(APPIMAGE_CORE_ROOT, name), { recursive: true, force: true });
462
+ }
463
+ }
464
+ return copy;
465
+ }
466
+
467
+ /**
468
+ * Find the gaia binary. A packaged app runs only the one it ships; from
469
+ * source, the managed venv, else PATH.
454
470
  */
455
471
  function findGaiaBin() {
472
+ if (shippedGaiaBin()) {
473
+ return bundledGaiaBin();
474
+ }
456
475
  if (fs.existsSync(GAIA_BIN)) {
457
476
  return GAIA_BIN;
458
477
  }
@@ -625,9 +644,9 @@ function liveDaemonPid() {
625
644
  * stop that fails with no daemon running (a broken venv, say) must not block
626
645
  * the reinstall that repairs it.
627
646
  */
628
- async function stopRunningDaemon({ timeoutMs = DAEMON_STOP_TIMEOUT_MS, signal } = {}) {
629
- if (!fs.existsSync(GAIA_BIN) || !fs.existsSync(GAIA_PYTHON_BIN)) return;
630
- const result = await runCommand(GAIA_BIN, ["daemon", "stop"], {
647
+ async function stopRunningDaemon({ gaiaBin = GAIA_BIN, timeoutMs = DAEMON_STOP_TIMEOUT_MS, signal } = {}) {
648
+ if (!fs.existsSync(gaiaBin) || (gaiaBin === GAIA_BIN && !fs.existsSync(GAIA_PYTHON_BIN))) return;
649
+ const result = await runCommand(gaiaBin, ["daemon", "stop"], {
631
650
  stageLabel: "daemon",
632
651
  timeoutMs,
633
652
  signal,
@@ -658,7 +677,7 @@ async function stopRunningDaemon({ timeoutMs = DAEMON_STOP_TIMEOUT_MS, signal }
658
677
  const why = result.timedOut
659
678
  ? `did not stop within ${Math.round(timeoutMs / 1000)} seconds`
660
679
  : `could not be stopped (gaia daemon stop exit ${result.code})`;
661
- log(`To stop it by hand: ${GAIA_BIN} daemon stop`);
680
+ log(`To stop it by hand: ${gaiaBin} daemon stop`);
662
681
  throw new InstallError(
663
682
  `GAIA's background service (the GAIA daemon, pid ${pid}) ${why}, so its files can't be updated.`,
664
683
  {
@@ -842,14 +861,20 @@ function checkDiskSpace() {
842
861
  logError(`statfsSync failed: ${err.message}`);
843
862
  }
844
863
 
845
- // Fallback: platform-specific shell commands. Non-fatal if unavailable.
864
+ // Fallback: platform-specific tools. Non-fatal if unavailable.
846
865
  try {
847
866
  if (IS_WINDOWS) {
848
- // Use PowerShell to read free space on the drive containing parent.
849
- const drive = path.parse(parent).root.replace(/\\$/, "");
850
- const out = execSync(
851
- `powershell -NoProfile -Command "(Get-PSDrive -Name '${drive.replace(":", "")}').Free"`,
852
- { encoding: "utf8", timeout: 5000 }
867
+ // The drive letter reaches PowerShell through the environment, not the script text.
868
+ const drive = path.parse(parent).root.replace(/[:\\]+$/, "");
869
+ const out = execFileSync(
870
+ "powershell",
871
+ ["-NoProfile", "-Command", "(Get-PSDrive -Name $env:GAIA_DISK_DRIVE).Free"],
872
+ {
873
+ encoding: "utf8",
874
+ timeout: 5000,
875
+ windowsHide: true,
876
+ env: { ...process.env, GAIA_DISK_DRIVE: drive },
877
+ }
853
878
  ).trim();
854
879
  const freeBytes = parseInt(out, 10);
855
880
  if (!Number.isNaN(freeBytes)) {
@@ -861,7 +886,7 @@ function checkDiskSpace() {
861
886
  }
862
887
  } else {
863
888
  // `df -k <parent>` — second line, 4th column is available 1K blocks.
864
- const out = execSync(`df -k "${parent}"`, { encoding: "utf8", timeout: 5000 });
889
+ const out = execFileSync("df", ["-k", parent], { encoding: "utf8", timeout: 5000 });
865
890
  const lines = out.trim().split("\n");
866
891
  if (lines.length >= 2) {
867
892
  const cols = lines[lines.length - 1].trim().split(/\s+/);
@@ -1174,7 +1199,7 @@ async function runPreChecks(opts = {}) {
1174
1199
  // ── uv install ───────────────────────────────────────────────────────────────
1175
1200
 
1176
1201
  class InstallError extends Error {
1177
- constructor(message, { stage, code, suggestion, reason, lockedFiles } = {}) {
1202
+ constructor(message, { stage, code, suggestion, reason, lockedFiles, keepState } = {}) {
1178
1203
  super(message);
1179
1204
  this.name = "InstallError";
1180
1205
  this.stage = stage || null;
@@ -1183,6 +1208,8 @@ class InstallError extends Error {
1183
1208
  this.reason = reason || null;
1184
1209
  // The files another program held open, for main to find who holds them.
1185
1210
  this.lockedFiles = lockedFiles || null;
1211
+ // Nothing was touched, so the recorded state still holds.
1212
+ this.keepState = Boolean(keepState);
1186
1213
  }
1187
1214
  }
1188
1215
 
@@ -1194,446 +1221,119 @@ class InstallCancelled extends Error {
1194
1221
  }
1195
1222
  }
1196
1223
 
1197
- /** Which FAILURE_REASONS a uv failure's output shows, or null. */
1198
- function failureReason(output) {
1199
- if (isFileLockedError(output)) return FAILURE_REASONS.LOCKED;
1200
- if (isTlsCertError(output)) return FAILURE_REASONS.TLS;
1201
- if (isTransientNetworkError(output)) return FAILURE_REASONS.NETWORK;
1202
- return null;
1224
+ /** ENOSPC on POSIX (os error 28) and ERROR_DISK_FULL on Windows (os error 112). */
1225
+ function isDiskFullError(output) {
1226
+ return /No space left on device|not enough space on the disk|os error (28|112)\b/i.test(output || "");
1203
1227
  }
1204
1228
 
1205
1229
  /**
1206
- * Which `extraResources` subdirectory holds the bundled uv for this host.
1207
- * Returns null for platforms we don't yet ship a binary for (falls through
1208
- * to the dev fallback).
1230
+ * The pre-check found too little space to install. `keep`: a working install
1231
+ * is in place and the refusal leaves it, and its recorded state, untouched.
1209
1232
  */
1210
- function bundledUvPlatformKey() {
1211
- if (process.platform === "linux" && process.arch === "x64") return "linux-x64";
1212
- if (process.platform === "win32" && process.arch === "x64") return "win-x64";
1213
- if (process.platform === "darwin" && process.arch === "arm64") return "mac-arm64";
1214
- return null;
1215
- }
1216
-
1217
- /**
1218
- * Stream-SHA256 a file. Returns lowercase hex.
1219
- */
1220
- function sha256File(filePath) {
1221
- return new Promise((resolve, reject) => {
1222
- const hash = crypto.createHash("sha256");
1223
- const stream = fs.createReadStream(filePath);
1224
- stream.on("error", reject);
1225
- stream.on("data", (chunk) => hash.update(chunk));
1226
- stream.on("end", () => resolve(hash.digest("hex")));
1227
- });
1228
- }
1229
-
1230
- /**
1231
- * Verify a macOS binary's code signature is structurally intact via
1232
- * `codesign --verify --strict`. Used in place of a fixed SHA256 pin for
1233
- * mac-arm64 (see the BUNDLED_UV_SHA256 comment) — ad-hoc-signed binaries
1234
- * (identity=-, which is every CI build today) pass this check, but a
1235
- * corrupted, tampered, or actually-unsigned binary fails it. This does NOT
1236
- * depend on the specific bytes any given codesign/Xcode toolchain produces,
1237
- * so it is stable across GitHub-hosted runner image rollovers where a fixed
1238
- * digest pin is not.
1239
- *
1240
- * @param {string} binPath
1241
- * @returns {{ ok: boolean, output: string }}
1242
- */
1243
- function codesignVerify(binPath) {
1244
- const result = spawnSync("codesign", ["--verify", "--strict", binPath], {
1245
- encoding: "utf8",
1246
- });
1247
- const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
1248
- return { ok: result.status === 0, output };
1249
- }
1250
-
1251
- /**
1252
- * Resolve the bundled uv binary path inside the Electron resources dir.
1253
- * Returns null if this isn't an Electron-packaged runtime (no
1254
- * `process.resourcesPath`) or if the host platform isn't bundled.
1255
- */
1256
- function findBundledUvResource() {
1257
- const key = bundledUvPlatformKey();
1258
- if (!key) return null;
1259
- const resourcesPath = process.resourcesPath;
1260
- if (!resourcesPath) return null;
1261
- const candidate = path.join(
1262
- resourcesPath,
1263
- "vendor",
1264
- "uv",
1265
- key,
1266
- IS_WINDOWS ? "uv.exe" : "uv"
1267
- );
1268
- return fs.existsSync(candidate) ? candidate : null;
1269
- }
1270
-
1271
- /**
1272
- * Atomically install the bundled uv into ~/.gaia/bin/uv after verifying it.
1273
- * Returns the installed path.
1274
- *
1275
- * Verification strategy differs by platform (see the BUNDLED_UV_SHA256
1276
- * comment): mac-arm64 uses `codesign --verify --strict` (darwin only —
1277
- * post-codesign SHA256 is not deterministic across CI runner images);
1278
- * linux-x64 / win-x64 use the SHA256 pin in BUNDLED_UV_SHA256, which IS
1279
- * deterministic for those platforms (no post-build re-signing).
1280
- *
1281
- * Writes to `uv.tmp-<pid>-<rand>` with mode 0o700, verifies, `chmod +x`,
1282
- * then `fs.rename()` (atomic on same filesystem).
1283
- */
1284
- async function installBundledUv(sourcePath, platformKey) {
1285
- const isDarwin = platformKey === "mac-arm64";
1286
- const expected = BUNDLED_UV_SHA256[platformKey];
1287
- if (!isDarwin && (!expected || expected.startsWith("<"))) {
1288
- // Enforce strict verification: builds MUST populate the expected SHA
1289
- // for packaged binaries. Failing fast prevents shipping an unverified
1290
- // uv binary which would be a supply-chain regression.
1291
- throw new InstallError(
1292
- `No bundled uv checksum registered for platform ${platformKey}. Build must populate BUNDLED_UV_SHA256.${platformKey}`,
1293
- { stage: STAGES.ENSURE_UV }
1294
- );
1295
- }
1296
-
1297
- ensureGaiaHome();
1298
- try {
1299
- fs.mkdirSync(MANAGED_UV_DIR, { recursive: true });
1300
- } catch (err) {
1301
- throw new InstallError(
1302
- `Could not create ${MANAGED_UV_DIR}: ${err.message}`,
1303
- { stage: STAGES.ENSURE_UV }
1304
- );
1305
- }
1306
-
1307
- const rand = crypto.randomBytes(6).toString("hex");
1308
- const tmpPath = path.join(
1309
- MANAGED_UV_DIR,
1310
- `uv.tmp-${process.pid}-${rand}${IS_WINDOWS ? ".exe" : ""}`
1311
- );
1312
-
1313
- // Copy source → tmp with restrictive mode.
1314
- await new Promise((resolve, reject) => {
1315
- const rs = fs.createReadStream(sourcePath);
1316
- const ws = fs.createWriteStream(tmpPath, { mode: 0o700 });
1317
- rs.on("error", reject);
1318
- ws.on("error", reject);
1319
- ws.on("finish", resolve);
1320
- rs.pipe(ws);
1321
- });
1322
-
1323
- if (isDarwin) {
1324
- // chmod BEFORE codesign --verify: codesign needs the execute bit to
1325
- // resolve the binary's designated requirement on some toolchains.
1326
- try {
1327
- fs.chmodSync(tmpPath, 0o700);
1328
- } catch (err) {
1329
- log(`Warning: chmod on tmp uv failed: ${err.message}`);
1330
- }
1331
- const { ok, output } = codesignVerify(tmpPath);
1332
- if (!ok) {
1333
- try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
1334
- throw new InstallError(
1335
- `Bundled uv failed code signature verification (codesign --verify --strict): ${output || "no output"}`,
1336
- {
1337
- stage: STAGES.ENSURE_UV,
1338
- suggestion:
1339
- "The AppImage/installer may be corrupt. Re-download from https://amd-gaia.ai and try again.",
1340
- }
1341
- );
1342
- }
1343
- log("Bundled uv passed codesign --verify --strict");
1344
- } else {
1345
- let actual;
1346
- try {
1347
- actual = await sha256File(tmpPath);
1348
- } catch (err) {
1349
- try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
1350
- throw new InstallError(
1351
- `Could not hash copied uv binary: ${err.message}`,
1352
- { stage: STAGES.ENSURE_UV }
1353
- );
1354
- }
1355
-
1356
- if (actual !== expected) {
1357
- try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
1358
- throw new InstallError(
1359
- `Bundled uv SHA256 mismatch (expected ${expected}, got ${actual}).`,
1360
- {
1361
- stage: STAGES.ENSURE_UV,
1362
- suggestion:
1363
- "The AppImage/installer may be corrupt. Re-download from https://amd-gaia.ai and try again.",
1364
- }
1365
- );
1366
- }
1367
-
1368
- try {
1369
- if (!IS_WINDOWS) fs.chmodSync(tmpPath, 0o700);
1370
- } catch (err) {
1371
- log(`Warning: chmod on tmp uv failed: ${err.message}`);
1372
- }
1373
- }
1374
-
1375
- try {
1376
- // rename() is atomic on the same filesystem on POSIX; on Windows
1377
- // it requires the target not to exist, so unlink first.
1378
- if (IS_WINDOWS && fs.existsSync(MANAGED_UV_BIN)) {
1379
- try { fs.unlinkSync(MANAGED_UV_BIN); } catch { /* ignore */ }
1233
+ function lowDiskError(disk, { keep, installedVersion }) {
1234
+ const mb = (bytes) => Math.round(bytes / (1024 * 1024));
1235
+ const requiredMb = mb(disk.requiredBytes);
1236
+ const freeMb = disk.freeBytes != null ? mb(disk.freeBytes) : null;
1237
+ const need = freeMb != null ? `${requiredMb - freeMb} MB more` : `${requiredMb} MB`;
1238
+ const kept = keep ? ` Your installed GAIA${installedVersion ? ` ${installedVersion}` : ""} was not changed.` : "";
1239
+ return new InstallError(
1240
+ `Not enough free disk space${keep ? " to update GAIA" : ""}. Required: ${requiredMb} MB${
1241
+ freeMb != null ? `, available: ${freeMb} MB` : ""
1242
+ }.${kept}`,
1243
+ {
1244
+ stage: STAGES.PRE_CHECKS,
1245
+ reason: FAILURE_REASONS.DISK,
1246
+ suggestion: `Free at least ${need} at ${path.dirname(GAIA_HOME)}, then try again.`,
1247
+ keepState: keep,
1380
1248
  }
1381
- fs.renameSync(tmpPath, MANAGED_UV_BIN);
1382
- } catch (err) {
1383
- try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
1384
- throw new InstallError(
1385
- `Could not install uv to ${MANAGED_UV_BIN}: ${err.message}`,
1386
- { stage: STAGES.ENSURE_UV }
1387
- );
1388
- }
1389
-
1390
- log(`Installed bundled uv v${BUNDLED_UV_VERSION} → ${MANAGED_UV_BIN}`);
1391
- return MANAGED_UV_BIN;
1249
+ );
1392
1250
  }
1393
1251
 
1394
- /**
1395
- * Prepend ~/.gaia/bin to this process's PATH so child spawns see our
1396
- * managed uv before any system-wide install.
1397
- */
1398
- function addManagedBinToPath() {
1399
- if (
1400
- process.env.PATH &&
1401
- !process.env.PATH.split(path.delimiter).includes(MANAGED_UV_DIR)
1402
- ) {
1403
- process.env.PATH = `${MANAGED_UV_DIR}${path.delimiter}${process.env.PATH}`;
1404
- log(`Prepended ${MANAGED_UV_DIR} to PATH for this process`);
1405
- }
1252
+ /** Which FAILURE_REASONS a uv failure's output shows, or null. */
1253
+ function failureReason(output) {
1254
+ if (isDiskFullError(output)) return FAILURE_REASONS.DISK;
1255
+ if (isFileLockedError(output)) return FAILURE_REASONS.LOCKED;
1256
+ if (isTlsCertError(output)) return FAILURE_REASONS.TLS;
1257
+ if (isTransientNetworkError(output)) return FAILURE_REASONS.NETWORK;
1258
+ return null;
1406
1259
  }
1407
1260
 
1408
1261
  /**
1409
- * Ensure `uv` is available. Preference order (per issue #782 / T3):
1410
- * 1. Managed copy at ~/.gaia/bin/uv already verified (warm-install fast path):
1411
- * SHA256 pin on linux-x64/win-x64, `codesign --verify --strict` on mac-arm64.
1412
- * 2. Bundled binary in process.resourcesPath/vendor/uv/<platform>/uv:
1413
- * copy atomically to ~/.gaia/bin/uv with the same platform-appropriate
1414
- * verification.
1415
- * 3. DEV-ONLY fallback (app.isPackaged === false OR no resourcesPath):
1416
- * the original `curl | sh` from astral.sh. Not a shipped-user path.
1417
- * 4. System `uv` on PATH (last resort — unverified version).
1262
+ * Ensure `uv` is available. Only running the app from source gets here: a
1263
+ * packaged app ships its backend. Uses the uv on PATH, else installs it from
1264
+ * astral.sh.
1418
1265
  *
1419
1266
  * Throws InstallError on failure.
1420
1267
  */
1421
- async function ensureUv({ onProgress, isPackaged, signal } = {}) {
1268
+ async function ensureUv({ onProgress, signal } = {}) {
1422
1269
  const report = makeProgressReporter(onProgress);
1423
1270
  report(STAGES.ENSURE_UV, 0, "Checking uv (Python package manager)");
1424
1271
 
1425
- const platformKey = bundledUvPlatformKey();
1426
- const isDarwin = platformKey === "mac-arm64";
1427
- const expectedSha = platformKey ? BUNDLED_UV_SHA256[platformKey] : null;
1428
-
1429
- // Fast path: warm install already on disk and still passes verification.
1430
- if (isDarwin && fs.existsSync(MANAGED_UV_BIN)) {
1431
- const { ok, output } = codesignVerify(MANAGED_UV_BIN);
1432
- if (ok) {
1433
- log(`Managed uv at ${MANAGED_UV_BIN} passed codesign --verify --strict — reusing`);
1434
- addManagedBinToPath();
1435
- report(STAGES.ENSURE_UV, 100, "uv ready (cached)");
1436
- return;
1437
- }
1438
- log(`Managed uv failed codesign verification (${output || "no output"}) — replacing`);
1439
- } else if (expectedSha && fs.existsSync(MANAGED_UV_BIN)) {
1440
- try {
1441
- const actual = await sha256File(MANAGED_UV_BIN);
1442
- if (actual === expectedSha) {
1443
- log(`Managed uv at ${MANAGED_UV_BIN} passed SHA256 check — reusing`);
1444
- addManagedBinToPath();
1445
- report(STAGES.ENSURE_UV, 100, "uv ready (cached)");
1446
- return;
1447
- }
1448
- log(
1449
- `Managed uv hash mismatch (expected ${expectedSha}, got ${actual}) — replacing`
1450
- );
1451
- } catch (err) {
1452
- log(`Could not verify managed uv: ${err.message} — replacing`);
1453
- }
1454
- }
1455
-
1456
- // Bundled path (the shipped-user path — AppImage, NSIS, DMG).
1457
- const bundled = findBundledUvResource();
1458
- if (bundled && platformKey) {
1459
- report(STAGES.ENSURE_UV, 30, "Installing bundled uv");
1460
- log(`Using bundled uv from ${bundled}`);
1461
-
1462
- // Verify the source resource before copying — catches installer
1463
- // corruption before we touch the user's home. mac-arm64 uses
1464
- // codesign --verify --strict (see BUNDLED_UV_SHA256 comment for why a
1465
- // fixed digest isn't viable there); other platforms use the SHA256 pin,
1466
- // which CI must have populated — a missing/placeholder value is a
1467
- // build-time error, rejected at runtime here.
1468
- if (isDarwin) {
1469
- const { ok, output } = codesignVerify(bundled);
1470
- if (!ok) {
1471
- throw new InstallError(
1472
- `Bundled uv resource failed code signature verification (codesign --verify --strict): ${output || "no output"}`,
1473
- {
1474
- stage: STAGES.ENSURE_UV,
1475
- suggestion:
1476
- "The installer appears to be corrupt. Re-download GAIA from https://amd-gaia.ai and try again.",
1477
- }
1478
- );
1479
- }
1480
- } else {
1481
- const srcHash = await sha256File(bundled);
1482
- if (srcHash !== expectedSha) {
1483
- throw new InstallError(
1484
- `Bundled uv resource SHA256 mismatch (expected ${expectedSha}, got ${srcHash}).`,
1485
- {
1486
- stage: STAGES.ENSURE_UV,
1487
- suggestion:
1488
- "The installer appears to be corrupt. Re-download GAIA from https://amd-gaia.ai and try again.",
1489
- }
1490
- );
1491
- }
1492
- }
1493
- await installBundledUv(bundled, platformKey);
1494
- addManagedBinToPath();
1495
- report(STAGES.ENSURE_UV, 100, "uv installed (bundled)");
1272
+ if (commandExists("uv")) {
1273
+ log("uv already on PATH (dev) — using system install");
1274
+ report(STAGES.ENSURE_UV, 100, "uv is already installed (system)");
1496
1275
  return;
1497
1276
  }
1498
1277
 
1499
- // DEV-ONLY fallback for contributors running from source (no
1500
- // extraResources, no packaged app). Never fires for end users.
1501
- const isDev = isPackaged === false || !process.resourcesPath;
1502
- if (isDev) {
1503
- if (commandExists("uv")) {
1504
- log("uv already on PATH (dev) — using system install");
1505
- report(STAGES.ENSURE_UV, 100, "uv is already installed (system)");
1506
- return;
1507
- }
1508
-
1509
- log("[dev] No bundled uv and no system uv — falling back to curl|sh installer");
1510
- let result;
1511
- if (IS_WINDOWS) {
1512
- result = await runCommand(
1513
- "powershell",
1514
- [
1515
- "-ExecutionPolicy",
1516
- "Bypass",
1517
- "-Command",
1518
- "irm https://astral.sh/uv/install.ps1 | iex",
1519
- ],
1520
- { stageLabel: "uv-install-dev", signal }
1521
- );
1522
- } else {
1523
- result = await runCommand(
1524
- "bash",
1525
- ["-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"],
1526
- { stageLabel: "uv-install-dev", signal }
1527
- );
1528
- }
1529
-
1530
- if (result.code !== 0) {
1531
- throw new InstallError(
1532
- `Could not install uv automatically (exit code ${result.code}).`,
1533
- {
1534
- stage: STAGES.ENSURE_UV,
1535
- code: result.code,
1536
- suggestion: IS_WINDOWS
1537
- ? 'Install uv manually: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"'
1538
- : "Install uv manually: curl -LsSf https://astral.sh/uv/install.sh | sh",
1539
- }
1540
- );
1541
- }
1278
+ log("No uv on PATH — installing it from astral.sh");
1279
+ let result;
1280
+ if (IS_WINDOWS) {
1281
+ result = await runCommand(
1282
+ "powershell",
1283
+ [
1284
+ "-ExecutionPolicy",
1285
+ "Bypass",
1286
+ "-Command",
1287
+ "irm https://astral.sh/uv/install.ps1 | iex",
1288
+ ],
1289
+ { stageLabel: "uv-install", signal }
1290
+ );
1291
+ } else {
1292
+ result = await runCommand(
1293
+ "bash",
1294
+ ["-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"],
1295
+ { stageLabel: "uv-install", signal }
1296
+ );
1297
+ }
1542
1298
 
1543
- if (!commandExists("uv")) {
1544
- const candidates = [
1545
- path.join(os.homedir(), ".local", "bin"),
1546
- path.join(os.homedir(), ".cargo", "bin"),
1547
- ];
1548
- for (const uvDir of candidates) {
1549
- if (process.env.PATH && !process.env.PATH.includes(uvDir)) {
1550
- process.env.PATH = `${uvDir}${path.delimiter}${process.env.PATH}`;
1551
- log(`Added ${uvDir} to PATH for this process`);
1552
- }
1299
+ if (result.code !== 0) {
1300
+ throw new InstallError(
1301
+ `Could not install uv automatically (exit code ${result.code}).`,
1302
+ {
1303
+ stage: STAGES.ENSURE_UV,
1304
+ code: result.code,
1305
+ suggestion: IS_WINDOWS
1306
+ ? 'Install uv manually: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"'
1307
+ : "Install uv manually: curl -LsSf https://astral.sh/uv/install.sh | sh",
1553
1308
  }
1554
- }
1555
-
1556
- if (!commandExists("uv")) {
1557
- throw new InstallError(
1558
- "uv installed but not found on PATH. A shell restart may be required.",
1559
- {
1560
- stage: STAGES.ENSURE_UV,
1561
- suggestion:
1562
- "Restart your terminal or reboot, then re-launch GAIA. If the problem persists, install uv manually from https://astral.sh/uv",
1563
- }
1564
- );
1565
- }
1566
-
1567
- report(STAGES.ENSURE_UV, 100, "uv installed (dev fallback)");
1568
- return;
1309
+ );
1569
1310
  }
1570
1311
 
1571
- // Packaged Windows rescue: try the Astral PowerShell installer even when
1572
- // running a packaged build. This provides an automated recovery path for
1573
- // end users on clean machines that don't have uv and where the installer
1574
- // build unexpectedly omitted a bundled binary. It is a last-resort and
1575
- // non-fatal attempt; on failure we fall through to the generic error.
1576
- if (IS_WINDOWS && !isDev) {
1577
- log("Packaged Windows: attempting automated uv installer (rescue)");
1578
- try {
1579
- const rescue = await runCommand(
1580
- "powershell",
1581
- [
1582
- "-ExecutionPolicy",
1583
- "Bypass",
1584
- "-Command",
1585
- "irm https://astral.sh/uv/install.ps1 | iex",
1586
- ],
1587
- { stageLabel: "uv-install-packaged-rescue", signal }
1588
- );
1589
- if (rescue.code === 0) {
1590
- // Ensure common install locations are present on PATH for this
1591
- // process in case the installer placed uv in a user-local bin.
1592
- const candidates = [
1593
- path.join(os.homedir(), ".local", "bin"),
1594
- path.join(os.homedir(), ".cargo", "bin"),
1595
- ];
1596
- for (const uvDir of candidates) {
1597
- if (process.env.PATH && !process.env.PATH.includes(uvDir)) {
1598
- process.env.PATH = `${uvDir}${path.delimiter}${process.env.PATH}`;
1599
- log(`Added ${uvDir} to PATH for this process`);
1600
- }
1601
- }
1602
- if (commandExists("uv")) {
1603
- log("Packaged Windows: uv installed and found on PATH (rescue succeeded)");
1604
- addManagedBinToPath();
1605
- report(STAGES.ENSURE_UV, 100, "uv ready (system, unverified)");
1606
- return;
1607
- }
1608
- log("Packaged Windows: uv installer ran but uv not found on PATH");
1609
- } else {
1610
- log(`Packaged Windows: automated uv installer exited ${rescue.code}`);
1312
+ if (!commandExists("uv")) {
1313
+ const candidates = [
1314
+ path.join(os.homedir(), ".local", "bin"),
1315
+ path.join(os.homedir(), ".cargo", "bin"),
1316
+ ];
1317
+ for (const uvDir of candidates) {
1318
+ if (process.env.PATH && !process.env.PATH.includes(uvDir)) {
1319
+ process.env.PATH = `${uvDir}${path.delimiter}${process.env.PATH}`;
1320
+ log(`Added ${uvDir} to PATH for this process`);
1611
1321
  }
1612
- } catch (rescueErr) {
1613
- if (rescueErr instanceof InstallCancelled) throw rescueErr;
1614
- log(`Packaged Windows: rescue installer threw: ${rescueErr.message}`);
1615
1322
  }
1616
1323
  }
1617
1324
 
1618
- // Packaged build, but we somehow don't have a bundled binary for this
1619
- // platform AND no system uv. Last-ditch: accept an unverified system uv
1620
- // if present; otherwise fail with a clear message.
1621
- if (commandExists("uv")) {
1622
- log(
1623
- `No bundled uv for ${process.platform}-${process.arch}, using system uv on PATH (unverified)`
1325
+ if (!commandExists("uv")) {
1326
+ throw new InstallError(
1327
+ "uv installed but not found on PATH. A shell restart may be required.",
1328
+ {
1329
+ stage: STAGES.ENSURE_UV,
1330
+ suggestion:
1331
+ "Restart your terminal or reboot, then re-launch GAIA. If the problem persists, install uv manually from https://astral.sh/uv",
1332
+ }
1624
1333
  );
1625
- report(STAGES.ENSURE_UV, 100, "uv ready (system, unverified)");
1626
- return;
1627
1334
  }
1628
1335
 
1629
- throw new InstallError(
1630
- `GAIA could not find or install its Python helper (uv) required to provision the backend.`,
1631
- {
1632
- stage: STAGES.ENSURE_UV,
1633
- suggestion:
1634
- "GAIA attempted automatic recovery but could not install uv. Please either: (a) click 'Install uv' in the dialog to let GAIA try again, or (b) install uv from https://astral.sh/uv and re-launch GAIA.",
1635
- }
1636
- );
1336
+ report(STAGES.ENSURE_UV, 100, "uv installed");
1637
1337
  }
1638
1338
 
1639
1339
  // ── Backend install ──────────────────────────────────────────────────────────
@@ -2065,8 +1765,12 @@ function _prefetchMarker(pep440) {
2065
1765
  return path.join(PREFETCH_DIR, `${pep440}.ready`);
2066
1766
  }
2067
1767
 
2068
- /** True when an earlier prefetch left everything `version` needs in uv's cache. */
1768
+ /**
1769
+ * True when `version`'s backend needs no download: an app that ships its
1770
+ * backend gets it with the update, otherwise a prefetch left it in uv's cache.
1771
+ */
2069
1772
  function isBackendPrefetched(version) {
1773
+ if (shippedGaiaBin()) return true;
2070
1774
  return Boolean(version) && fs.existsSync(_prefetchMarker(toPep440(version)));
2071
1775
  }
2072
1776
 
@@ -2077,6 +1781,10 @@ function isBackendPrefetched(version) {
2077
1781
  * Throws with uv's own words when the download fails.
2078
1782
  */
2079
1783
  async function prefetchBackend(appVersion, { isPackaged } = {}) {
1784
+ if (isPackaged) {
1785
+ log("This app ships its own backend, so the update carries it and there is nothing to prefetch");
1786
+ return;
1787
+ }
2080
1788
  if (process.env.GAIA_LOCAL_WHEEL) {
2081
1789
  log("GAIA_LOCAL_WHEEL is set: the next launch installs that wheel, so there is nothing to prefetch");
2082
1790
  return;
@@ -2140,7 +1848,14 @@ function _lastLines({ stdout, stderr }) {
2140
1848
  */
2141
1849
  function isBackendCurrent() {
2142
1850
  // A local wheel is reinstalled on every launch, as ensureBackend says.
2143
- if (process.env.GAIA_LOCAL_WHEEL) return false;
1851
+ if (process.env.GAIA_LOCAL_WHEEL && !shippedGaiaBin()) return false;
1852
+ if (shippedGaiaBin()) {
1853
+ // The core is always current; an app version is done once it refreshed the agent.
1854
+ if (!bundledGaiaBin()) return false;
1855
+ const prev = getState();
1856
+ if (!prev) return !fs.existsSync(FLAGSHIP_SENTINEL);
1857
+ return prev.state === STATES.READY && toPep440(prev.version || "") === toPep440(appVersion());
1858
+ }
2144
1859
  const bin = findGaiaBin();
2145
1860
  if (!bin) return false;
2146
1861
  const prev = getState();
@@ -2154,6 +1869,10 @@ function isBackendCurrent() {
2154
1869
  * `gaia --version`, which starts Python and can take 20 s+ on a busy PC.
2155
1870
  */
2156
1871
  function getInstalledVersion(gaiaBin) {
1872
+ // Built with the app, from the same commit.
1873
+ if (shippedGaiaBin() && gaiaBin === bundledGaiaBin()) {
1874
+ return toPep440(appVersion());
1875
+ }
2157
1876
  if (gaiaBin === GAIA_BIN) {
2158
1877
  // existsSync follows the venv's python symlink, so a removed base interpreter reads as missing.
2159
1878
  if (!fs.existsSync(GAIA_PYTHON_BIN)) {
@@ -2229,6 +1948,19 @@ async function ensureBackend(opts = {}) {
2229
1948
  openLog({ truncate: true });
2230
1949
 
2231
1950
  try {
1951
+ const bundled = await ensureBundledCore();
1952
+ if (bundled) {
1953
+ log(`Using the GAIA backend this app ships: ${bundled}`);
1954
+ await refreshAgent(bundled, opts);
1955
+ return bundled;
1956
+ }
1957
+ if (opts.isPackaged) {
1958
+ throw new InstallError("This GAIA install is missing its backend.", {
1959
+ stage: STAGES.VERIFY,
1960
+ suggestion: `Reinstall GAIA from https://amd-gaia.ai/#install. Expected it at ${BUNDLED_GAIA_BIN}.`,
1961
+ });
1962
+ }
1963
+
2232
1964
  const preChecks = await runPreChecks({ onProgress: opts.onProgress });
2233
1965
 
2234
1966
  // Handle a pre-existing partial install first (before disk/network fails
@@ -2251,31 +1983,6 @@ async function ensureBackend(opts = {}) {
2251
1983
  }
2252
1984
  }
2253
1985
 
2254
- // Disk check failure: fatal, surface as InstallError.
2255
- if (!preChecks.disk.ok) {
2256
- const freeMb =
2257
- preChecks.disk.freeBytes != null
2258
- ? Math.round(preChecks.disk.freeBytes / (1024 * 1024))
2259
- : null;
2260
- const requiredMb = Math.round(
2261
- preChecks.disk.requiredBytes / (1024 * 1024)
2262
- );
2263
- const err = new InstallError(
2264
- `Not enough free disk space. Required: ${requiredMb} MB${
2265
- freeMb != null ? `, available: ${freeMb} MB` : ""
2266
- }.`,
2267
- {
2268
- stage: STAGES.PRE_CHECKS,
2269
- reason: FAILURE_REASONS.DISK,
2270
- suggestion: `Free at least ${requiredMb} MB at ${path.dirname(
2271
- GAIA_HOME
2272
- )} and try again.`,
2273
- }
2274
- );
2275
- setState(STATES.FAILED, { stage: STAGES.PRE_CHECKS, message: err.message });
2276
- throw err;
2277
- }
2278
-
2279
1986
  // Network check is ADVISORY, never fatal. A failed HEAD probe is most often
2280
1987
  // a corporate TLS-inspection proxy whose root CA isn't in Node's bundled
2281
1988
  // trust store (#1572) — the machine is online and `uv`/`pip`, which honor
@@ -2311,8 +2018,9 @@ async function ensureBackend(opts = {}) {
2311
2018
  prev.stage === LEGACY_SETUP_STAGE ||
2312
2019
  prev.stage === STAGES.VERIFY ||
2313
2020
  prev.stage === STAGES.AGENT_REFRESH;
2021
+ let installedVersion = null;
2314
2022
  if (existingBin) {
2315
- const installedVersion = getInstalledVersion(existingBin);
2023
+ installedVersion = getInstalledVersion(existingBin);
2316
2024
  const versionMatches =
2317
2025
  expectedVersion !== null && installedVersion === toPep440(expectedVersion);
2318
2026
  if (versionMatches && packageFinished && prev && prev.stage === STAGES.AGENT_REFRESH) {
@@ -2338,6 +2046,12 @@ async function ensureBackend(opts = {}) {
2338
2046
  log("GAIA backend not found — installing from scratch");
2339
2047
  }
2340
2048
 
2049
+ // Checked only once there is something to install, so a full disk never stops a current install.
2050
+ if (!preChecks.disk.ok) {
2051
+ const keep = Boolean(existingBin) && packageFinished && prev?.state !== STATES.FAILED;
2052
+ throw lowDiskError(preChecks.disk, { keep, installedVersion });
2053
+ }
2054
+
2341
2055
  await installBackend(opts);
2342
2056
 
2343
2057
  const verified = findGaiaBin();
@@ -2364,6 +2078,10 @@ async function ensureBackend(opts = {}) {
2364
2078
  throw err;
2365
2079
  }
2366
2080
  if (err instanceof InstallError) {
2081
+ if (err.keepState) {
2082
+ log(`Install refused; the recorded state is unchanged: ${err.message}`);
2083
+ throw err;
2084
+ }
2367
2085
  setState(STATES.FAILED, {
2368
2086
  stage: err.stage || null,
2369
2087
  message: err.message,