@amd-gaia/agent-ui 0.27.0-rc.2 → 0.27.0-rc.21

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 (57) hide show
  1. package/bin/gaia-ui.cjs +57 -3
  2. package/dist/assets/AdvancedSettings-DD-RVnWp.js +1 -0
  3. package/dist/assets/AutomationsSettings-rLo6mWU6.js +1 -0
  4. package/dist/assets/ConnectorsPane-BxG6qzLb.css +1 -0
  5. package/dist/assets/ConnectorsPane-DdYiHRhD.js +1 -0
  6. package/dist/assets/DocumentLibrary-BY3B6vwk.js +5 -0
  7. package/dist/assets/{DocumentLibrary-fEMoY7lH.css → DocumentLibrary-Ctwq2m2t.css} +1 -1
  8. package/dist/assets/FileBrowser-DZVXejEq.js +4 -0
  9. package/dist/assets/FileBrowser-DxS29ShT.css +1 -0
  10. package/dist/assets/MemoryDashboard-Bfy9g6TS.css +1 -0
  11. package/dist/assets/MemoryDashboard-BlNGTH6-.js +1 -0
  12. package/dist/assets/MessagingSettings-BHd7ftWx.js +1 -0
  13. package/dist/assets/{MobileAccessModal-BrZMaERi.css → MobileAccessModal-DSFjH6di.css} +1 -1
  14. package/dist/assets/MobileAccessModal-DbSJ06l7.js +2 -0
  15. package/dist/assets/ScheduleManager-CEBoBLPV.css +1 -0
  16. package/dist/assets/ScheduleManager-ClE3JXAN.js +1 -0
  17. package/dist/assets/folderIndexResult-BIoxqF5I.js +1 -0
  18. package/dist/assets/index-DDO2kO5x.js +226 -0
  19. package/dist/assets/index-DXyVxzzC.css +1 -0
  20. package/dist/assets/useFocusTrap-Cy_PGcml.js +6 -0
  21. package/dist/index.html +3 -3
  22. package/dist/sw.js +1 -1
  23. package/main-safety-net.cjs +26 -2
  24. package/main.cjs +226 -122
  25. package/package.json +2 -2
  26. package/preload.cjs +6 -0
  27. package/services/auto-updater.cjs +99 -0
  28. package/services/backend-crash-dialog.cjs +19 -5
  29. package/services/backend-health-monitor.cjs +86 -0
  30. package/services/backend-installer.cjs +1 -0
  31. package/services/backend-orphan.cjs +162 -1
  32. package/services/backend-supervisor.cjs +35 -9
  33. package/services/browser-pane/dev-servers.cjs +44 -1
  34. package/services/browser-pane/listen-addresses.cjs +140 -0
  35. package/services/context-menu.cjs +79 -0
  36. package/services/link-policy.cjs +78 -7
  37. package/services/port-manager.cjs +2 -3
  38. package/services/process-tree.cjs +84 -14
  39. package/services/quit-guard.cjs +8 -4
  40. package/services/ui-token.cjs +156 -0
  41. package/dist/assets/AdvancedSettings-DHERtrno.js +0 -1
  42. package/dist/assets/AutomationsSettings-4FWcRau9.js +0 -1
  43. package/dist/assets/ConnectorsPane-BGI8nBUb.css +0 -1
  44. package/dist/assets/ConnectorsPane-Dkat1zLC.js +0 -1
  45. package/dist/assets/DocumentLibrary-Dll55N7l.js +0 -5
  46. package/dist/assets/FileBrowser-1goNp4CP.css +0 -1
  47. package/dist/assets/FileBrowser-wFHqH6K_.js +0 -4
  48. package/dist/assets/MemoryDashboard-BuUBoNq8.js +0 -1
  49. package/dist/assets/MemoryDashboard-RpfLag-v.css +0 -1
  50. package/dist/assets/MessagingSettings-DomiT2rX.js +0 -1
  51. package/dist/assets/MobileAccessModal-B2gaE8nk.js +0 -2
  52. package/dist/assets/ScheduleManager-8UE81KlQ.js +0 -1
  53. package/dist/assets/ScheduleManager-BZzEH2-W.css +0 -1
  54. package/dist/assets/index-BiETDNik.css +0 -1
  55. package/dist/assets/index-HCZ86cyP.js +0 -220
  56. package/dist/assets/useFocusTrap-BFi0chLf.js +0 -6
  57. package/dist/assets/zap-DjkIffnX.js +0 -1
package/main.cjs CHANGED
@@ -17,6 +17,7 @@ const {
17
17
  app,
18
18
  autoUpdater: electronAutoUpdater,
19
19
  BrowserWindow,
20
+ clipboard,
20
21
  Menu,
21
22
  dialog,
22
23
  ipcMain,
@@ -71,6 +72,8 @@ try {
71
72
  onRendererGone: (contents, details) => {
72
73
  void handleRendererGone(contents, details);
73
74
  },
75
+ // A pane tab's crash is the pane's to report ("Reload to try again"), not GAIA's.
76
+ isPanePage: (contents) => contents.session === session.fromPartition(PANE_PARTITION),
74
77
  }));
75
78
  } catch (err) {
76
79
  try { process.stderr.write(`[main] safety-net load failed: ${err.message}\n`); } catch { }
@@ -105,10 +108,15 @@ const AgentProcessManager = require("./services/agent-process-manager.cjs");
105
108
  const NotificationService = require("./services/notification-service.cjs");
106
109
  const KeepAwake = require("./services/keep-awake.cjs");
107
110
  const PortManager = require("./services/port-manager.cjs");
108
- const { isGaiaBackendProcess } = require("./services/backend-orphan.cjs");
111
+ const {
112
+ cleanupOrphanedBackends,
113
+ forgetBackend,
114
+ recordBackend,
115
+ } = require("./services/backend-orphan.cjs");
109
116
  const { showBackendCrashDialog } = require("./services/backend-crash-dialog.cjs");
110
117
  const { showRendererGoneDialog } = require("./services/renderer-gone-dialog.cjs");
111
118
  const { createBackendSupervisor } = require("./services/backend-supervisor.cjs");
119
+ const { createBackendHealthMonitor } = require("./services/backend-health-monitor.cjs");
112
120
  const { buildIndexQuery, INSTALL_SCREEN_QUERY } = require("./services/index-query.cjs");
113
121
  const backendInstaller = require("./services/backend-installer.cjs");
114
122
  const { createEngineInstall } = require("./services/engine-install.cjs");
@@ -119,11 +127,16 @@ const {
119
127
  isAllowedExternalUrl,
120
128
  isInAppNavigation,
121
129
  describeBlockedUrl,
130
+ describeOpenFailure,
131
+ openExternalSafely,
132
+ linkNoticeText,
122
133
  } = require("./services/link-policy.cjs");
123
134
  const { installWindowKeys } = require("./services/window-keys.cjs");
135
+ const { installContextMenu } = require("./services/context-menu.cjs");
124
136
  const { installQuitCleanup } = require("./services/quit-cleanup.cjs");
125
137
  const { chromiumSwitches } = require("./services/chromium-switches.cjs");
126
138
  const { titleBarKind, titleBarOptions } = require("./services/window-frame.cjs");
139
+ const { installBackendAuth } = require("./services/ui-token.cjs");
127
140
  const { resolveDevQaMode } = require("./services/dev-qa-mode.cjs");
128
141
  const { createBrowserPaneService, PANE_PARTITION } = require("./services/browser-pane/ipc.cjs");
129
142
  const { DevServerSupervisor } = require("./services/browser-pane/dev-servers.cjs");
@@ -223,6 +236,7 @@ const APP_NAME = "GAIA";
223
236
  // from prior aborted sessions (issue #782 / T5).
224
237
  const DEFAULT_BACKEND_PORT = 4200;
225
238
  const STARTUP_TIMEOUT = 30000;
239
+ const BACKEND_HEALTH_CHECK_TIMEOUT = 2000;
226
240
  // A restart must answer within this, or it counts as a failed try.
227
241
  const RESTART_TIMEOUT = 90000;
228
242
 
@@ -254,6 +268,9 @@ const windowConfig = appConfig.window || {
254
268
  // ── State ──────────────────────────────────────────────────────────────────
255
269
 
256
270
  let backendProcess = null;
271
+ let backendCleanupPending = null;
272
+ let backendHealthMonitoringEnabled = false;
273
+ let backendHealthMonitor = null;
257
274
  // The in-flight startBackend(), so a quit during startup can wait for the
258
275
  // spawn and stop it instead of leaving it behind.
259
276
  let backendStarting = null;
@@ -262,6 +279,8 @@ let shutdownStarted = false;
262
279
  // Set once an update install starts quitting the app.
263
280
  let updateQuitStarted = false;
264
281
  let backendPort = DEFAULT_BACKEND_PORT;
282
+ // The port of the backend this app spawned; only it is sent the API token.
283
+ let spawnedBackendPort = null;
265
284
  let healthCheckUrl = `http://localhost:${backendPort}/api/health`;
266
285
  let backendStderrTail = [];
267
286
  let isIntentionalKill = false;
@@ -320,54 +339,34 @@ function quitStarted() {
320
339
  // ── Backend Process ────────────────────────────────────────────────────────
321
340
 
322
341
  /**
323
- * Terminate a backend left running from a previous launch.
342
+ * Terminate backends left running by a previous launch.
324
343
  *
325
- * The desktop app may be double-clicked multiple times or crash, leaving an
326
- * orphaned `gaia chat --ui` process. On Windows that process keeps an open
327
- * handle on `gaia.exe`, so the next upgrade's `uv pip install --refresh` fails
328
- * with `os error 32` (file in use) — issue #1388. We MUST run this BEFORE the
329
- * installer (`engineInstall.run()`), not just before spawning the new backend,
330
- * so the executable can be replaced.
344
+ * The desktop app may crash, leaving an orphaned `gaia chat --ui` process. On
345
+ * Windows that process keeps an open handle on `gaia.exe`, so the next
346
+ * upgrade's `uv pip install --refresh` fails with `os error 32` (file in use)
347
+ * — issue #1388. We MUST run this BEFORE the installer (`engineInstall.run()`),
348
+ * not just before spawning the new backend, so the executable can be replaced.
331
349
  *
332
- * The PID is read from ~/.gaia/backend.pid and verified to be a GAIA backend
333
- * (conservative match) before signalling, so we never kill unrelated user
334
- * processes (issue #782 TOCTOU mitigation). Idempotent: the pidfile is removed
335
- * after the first call, so later calls are no-ops.
350
+ * Each app records its backend under ~/.gaia/backend-pids/<app pid>.pid. Only
351
+ * backends whose app is gone are stopped, and only once verified to be a GAIA
352
+ * backend (issue #782): another copy of the app sharing ~/.gaia keeps its own
353
+ * (issue #7062).
336
354
  */
337
355
  async function cleanupOrphanedBackend() {
338
- try {
339
- const pidFile = path.join(_GAIA_DIR, "backend.pid");
340
- if (!fs.existsSync(pidFile)) return;
341
- try {
342
- const existingPid = parseInt(fs.readFileSync(pidFile, "utf8").trim(), 10);
343
- if (!Number.isNaN(existingPid)) {
344
- console.log(`[main] Found existing backend pidfile (${existingPid}) — verifying process identity`);
345
-
346
- let isBackend = false;
347
- try {
348
- isBackend = isGaiaBackendProcess(existingPid);
349
- } catch (err) {
350
- console.warn(`[main] Could not verify pid ${existingPid}: ${err.message}`);
351
- }
356
+ await cleanupOrphanedBackends({
357
+ gaiaDir: _GAIA_DIR,
358
+ killBackend: (pid) => portManager.killBackend(pid),
359
+ logger: console,
360
+ });
361
+ }
352
362
 
353
- if (!isBackend) {
354
- console.log(`[main] PID ${existingPid} does not appear to be a GAIA backend; skipping kill`);
355
- } else {
356
- try {
357
- await portManager.killBackend(existingPid);
358
- console.log(`[main] Cleaned up previous backend pid ${existingPid}`);
359
- } catch (err) {
360
- console.warn(`[main] Could not clean previous backend pid ${existingPid}: ${err.message}`);
361
- }
362
- }
363
- }
364
- } catch (err) {
365
- console.warn(`[main] Failed reading backend pidfile: ${err.message}`);
366
- }
367
- try { fs.unlinkSync(pidFile); } catch { /* ignore */ }
368
- } catch (err) {
369
- console.warn(`[main] PID cleanup check failed: ${err.message}`);
370
- }
363
+ /** What the user reads when GAIA's backend program can't be found: what to do, and where it looked. */
364
+ function missingBackendMessage() {
365
+ const looked = [backendInstaller.BUNDLED_GAIA_BIN, backendInstaller.GAIA_BIN].filter(Boolean).join(", ");
366
+ return (
367
+ "GAIA's backend program is missing, so GAIA can't start: the app's files are incomplete. " +
368
+ `Reinstall GAIA from https://amd-gaia.ai/#install. Looked for ${looked} and for gaia on PATH.`
369
+ );
371
370
  }
372
371
 
373
372
  /**
@@ -402,12 +401,13 @@ async function startBackend() {
402
401
  }
403
402
  healthCheckUrl = `http://localhost:${backendPort}/api/health`;
404
403
  // Defensively clean up any orphaned backend in case bootstrap was skipped
405
- // on this path. cleanupOrphanedBackend() is idempotent and a no-op once the
406
- // pidfile has already been consumed earlier in app startup.
404
+ // on this path. A no-op once earlier startup removed the orphans' records.
407
405
  // Dev QA mode leaves it alone: it belongs to the installed app's backend.
408
406
  if (!devQa) await cleanupOrphanedBackend();
409
407
 
410
408
  console.log(`Starting backend: ${gaiaCmd} chat --ui --ui-port ${backendPort}`);
409
+ spawnedBackendPort = backendPort;
410
+ const childPort = backendPort;
411
411
 
412
412
  // Reset per-spawn state so a fresh crash dialog doesn't mix tails.
413
413
  backendStderrTail = [];
@@ -465,15 +465,12 @@ async function startBackend() {
465
465
  console.error("Failed to start backend:", err.message);
466
466
  });
467
467
 
468
- // Write a PID file so subsequent AppImage launches can detect and
469
- // cleanup this backend if it becomes orphaned. The pidfile is removed
470
- // when the child exits.
468
+ // Record this backend so a later launch can stop it if this app dies
469
+ // without stopping it. The record is removed when the child exits.
471
470
  if (!devQa) {
472
471
  try {
473
- try { fs.mkdirSync(_GAIA_DIR, { recursive: true }); } catch { /* ignore */ }
474
- const pidFile = path.join(_GAIA_DIR, "backend.pid");
475
- fs.writeFileSync(pidFile, String(child.pid), { mode: 0o600 });
476
- console.log(`[main] Wrote backend pidfile ${pidFile} (pid=${child.pid})`);
472
+ const file = recordBackend({ gaiaDir: _GAIA_DIR, ownerPid: process.pid, backendPid: child.pid });
473
+ console.log(`[main] Wrote backend pidfile ${file} (pid=${child.pid})`);
477
474
  } catch (err) {
478
475
  console.warn(`[main] Could not write backend pidfile: ${err.message}`);
479
476
  }
@@ -486,23 +483,20 @@ async function startBackend() {
486
483
  console.error(`Backend exited with code ${code} (signal=${signal}, pid=${child.pid})`);
487
484
  }
488
485
  if (backendProcess === child) backendProcess = null;
486
+ // Whatever binds the port next is not ours, so it gets no token.
487
+ if (spawnedBackendPort === childPort) spawnedBackendPort = null;
489
488
  if (trayManager && !isQuitting) trayManager.setBackendAlive(false);
490
489
 
491
490
  // Once restarts run out, the supervisor's onStopped shows the crash dialog.
492
491
  if (crashed) backendSupervisor.crashed({ code, signal });
493
492
 
494
- // Remove pidfile on exit to avoid leaving stale PID behind.
495
- try {
496
- const pidFile = path.join(_GAIA_DIR, "backend.pid");
497
- if (fs.existsSync(pidFile)) {
498
- const p = fs.readFileSync(pidFile, "utf8").trim();
499
- if (p && parseInt(p, 10) === child.pid) {
500
- try { fs.unlinkSync(pidFile); } catch { /* ignore */ }
501
- }
493
+ // Remove this app's record, unless a newer backend already replaced it.
494
+ if (!devQa) {
495
+ try {
496
+ forgetBackend({ gaiaDir: _GAIA_DIR, ownerPid: process.pid, backendPid: child.pid });
497
+ } catch (err) {
498
+ console.warn(`[main] Failed to remove backend pidfile: ${err.message}`);
502
499
  }
503
- } catch (err) {
504
- // Non-fatal — just log and continue.
505
- console.warn(`[main] Failed to remove backend pidfile: ${err.message}`);
506
500
  }
507
501
  });
508
502
 
@@ -516,19 +510,47 @@ async function startBackend() {
516
510
  return child;
517
511
  }
518
512
 
513
+ /** Stop a backend tree and keep its handle pending until termination is verified. */
514
+ async function stopBackendTree(proc) {
515
+ backendCleanupPending = proc;
516
+ isIntentionalKill = true;
517
+ try {
518
+ const result = await portManager.killBackend(proc);
519
+ if (!result || !Array.isArray(result.survivors)) {
520
+ throw new Error("The backend stop did not confirm that its process tree exited.");
521
+ }
522
+ if (result.survivors.length) {
523
+ throw new Error(`The backend process tree is still running (pid ${result.survivors.join(", ")}).`);
524
+ }
525
+ if (result.verified !== true) {
526
+ throw new Error(
527
+ "The backend process tree could not be verified as stopped. " +
528
+ "Quit GAIA, end any leftover GAIA or Python processes in Task Manager, then reopen GAIA."
529
+ );
530
+ }
531
+ } catch (err) {
532
+ isIntentionalKill = false;
533
+ throw err;
534
+ }
535
+ if (backendCleanupPending === proc) backendCleanupPending = null;
536
+ if (backendProcess === proc) backendProcess = null;
537
+ }
538
+
519
539
  /**
520
540
  * Start a new backend for the supervisor and resolve once it answers.
521
541
  * Rejects when it exits first or never answers, so the supervisor retries.
542
+ * A backend still alive here is a hung one Restart GAIA was pressed for:
543
+ * stop it first, or the new backend would run beside it on a new port.
522
544
  */
523
545
  async function restartBackend() {
546
+ const previousBackend = backendCleanupPending || backendProcess;
547
+ if (previousBackend) await stopBackendTree(previousBackend);
548
+
524
549
  backendStarting = startBackend();
525
550
  const child = await backendStarting;
526
- if (!child) {
527
- throw new Error("GAIA's backend program is missing, so it can't restart. Reinstall GAIA.");
528
- }
551
+ if (!child) throw Object.assign(new Error(missingBackendMessage()), { terminal: true });
529
552
  if (quitStarted()) {
530
- isIntentionalKill = true;
531
- await portManager.killBackend(child);
553
+ await stopBackendTree(child);
532
554
  throw new Error("GAIA is quitting, so the restarted backend was stopped.");
533
555
  }
534
556
  backendProcess = child;
@@ -538,10 +560,10 @@ async function restartBackend() {
538
560
  if (!alive()) {
539
561
  throw new Error(`The backend exited (code ${child.exitCode}, signal ${child.signalCode}) before it answered.`);
540
562
  }
541
- isIntentionalKill = true;
542
- await portManager.killBackend(child);
563
+ await stopBackendTree(child);
543
564
  throw new Error(`The backend did not answer within ${RESTART_TIMEOUT / 1000} s.`);
544
565
  }
566
+ enableBackendHealthMonitoring();
545
567
  console.log(`[main] Backend restarted on port ${backendPort} (pid=${child.pid})`);
546
568
  if (trayManager) {
547
569
  trayManager.setBackendPort(backendPort);
@@ -558,21 +580,42 @@ function backendStateForRenderer(state) {
558
580
  const backendSupervisor = createBackendSupervisor({
559
581
  start: restartBackend,
560
582
  onStopped: (state) => {
561
- const { code = null, signal = null } = state.lastExit || {};
562
- void handleBackendCrash(code, signal);
583
+ void handleBackendCrash(state);
563
584
  },
564
585
  onState: (state) => {
586
+ if (backendHealthMonitor) {
587
+ if (backendHealthMonitoringEnabled && state.status === "running") backendHealthMonitor.start();
588
+ else backendHealthMonitor.stop();
589
+ }
565
590
  console.log(
566
591
  `[main] Backend ${state.status}` +
567
592
  (state.status === "restarting" ? ` (try ${state.attempt} of ${state.maxRestarts})` : "") +
568
593
  (state.lastError ? `: ${state.lastError}` : "")
569
594
  );
595
+ // A backend up again after a failed start leaves nothing to roll back from.
596
+ if (state.status === "running") autoUpdater.clearStartFailure();
570
597
  if (mainWindow && !mainWindow.isDestroyed()) {
571
598
  mainWindow.webContents.send("backend:state", backendStateForRenderer(state));
572
599
  }
573
600
  },
574
601
  });
575
602
 
603
+ backendHealthMonitor = createBackendHealthMonitor({
604
+ check: checkBackendHealth,
605
+ onUnhealthy: (error, failures) => {
606
+ const message = error && error.message ? error.message : String(error);
607
+ const reason = new Error(`Health check failed ${failures} consecutive times: ${message}`);
608
+ console.warn(`[main] ${reason.message}`);
609
+ backendSupervisor.healthFailed(reason);
610
+ },
611
+ });
612
+
613
+ function enableBackendHealthMonitoring() {
614
+ if (quitStarted()) return;
615
+ backendHealthMonitoringEnabled = true;
616
+ if (backendSupervisor.getState().status === "running") backendHealthMonitor.start();
617
+ }
618
+
576
619
  ipcMain.handle("backend:get-state", () => backendStateForRenderer(backendSupervisor.getState()));
577
620
  ipcMain.handle("backend:restart", () => {
578
621
  backendSupervisor.restartNow();
@@ -583,7 +626,8 @@ ipcMain.handle("backend:restart", () => {
583
626
  * Tell the user the backend stopped and offer Restart / Save diagnostics /
584
627
  * Quit. Invoked by the supervisor's onStopped once automatic restarts run out.
585
628
  */
586
- async function handleBackendCrash(code, signal) {
629
+ async function handleBackendCrash(state) {
630
+ const { code = null, signal = null } = state.lastExit || {};
587
631
  autoUpdater.reportStartFailure();
588
632
  try {
589
633
  const choice = await showBackendCrashDialog({
@@ -591,6 +635,7 @@ async function handleBackendCrash(code, signal) {
591
635
  app,
592
636
  code,
593
637
  signal,
638
+ reason: state.lastError,
594
639
  tailLines: backendStderrTail.slice(-8),
595
640
  writeDiagnostics: () => portManager.writeDiagnosticsBundle(),
596
641
  // The backend is gone, so there is no running work to ask about.
@@ -633,24 +678,10 @@ async function handleRendererGone(contents, { reason }) {
633
678
 
634
679
  async function waitForBackend(timeoutMs, isAlive = () => true) {
635
680
  const start = Date.now();
636
- const http = require("http");
637
681
 
638
682
  while (Date.now() - start < timeoutMs && isAlive()) {
639
683
  try {
640
- await new Promise((resolve, reject) => {
641
- const req = http.get(healthCheckUrl, (res) => {
642
- if (res.statusCode === 200) {
643
- resolve();
644
- } else {
645
- reject(new Error(`Status ${res.statusCode}`));
646
- }
647
- });
648
- req.on("error", reject);
649
- req.setTimeout(2000, () => {
650
- req.destroy();
651
- reject(new Error("timeout"));
652
- });
653
- });
684
+ await checkBackendHealth();
654
685
  return true;
655
686
  } catch {
656
687
  await new Promise((r) => setTimeout(r, 500));
@@ -659,6 +690,51 @@ async function waitForBackend(timeoutMs, isAlive = () => true) {
659
690
  return false;
660
691
  }
661
692
 
693
+ function checkBackendHealth(signal) {
694
+ const http = require("http");
695
+ return new Promise((resolve, reject) => {
696
+ let settled = false;
697
+ let deadline = null;
698
+ let req = null;
699
+ const onAbort = () => {
700
+ const error = new Error("Health check was cancelled.");
701
+ finish(reject, error);
702
+ req.destroy(error);
703
+ };
704
+ const finish = (handler, value) => {
705
+ if (settled) return;
706
+ settled = true;
707
+ if (deadline) clearTimeout(deadline);
708
+ if (signal) signal.removeEventListener("abort", onAbort);
709
+ handler(value);
710
+ };
711
+ req = http.get(healthCheckUrl, (res) => {
712
+ if (res.statusCode !== 200) {
713
+ finish(reject, new Error(`Health endpoint returned status ${res.statusCode}.`));
714
+ res.destroy();
715
+ return;
716
+ }
717
+ res.once("end", () => finish(resolve));
718
+ res.once("aborted", () => finish(reject, new Error("Health endpoint response was aborted.")));
719
+ res.once("close", () => {
720
+ if (!res.complete) finish(reject, new Error("Health endpoint response closed before completion."));
721
+ });
722
+ res.once("error", (error) => finish(reject, error));
723
+ res.resume();
724
+ });
725
+ deadline = setTimeout(() => {
726
+ const error = new Error("Health endpoint did not answer within 2 s.");
727
+ finish(reject, error);
728
+ req.destroy(error);
729
+ }, BACKEND_HEALTH_CHECK_TIMEOUT);
730
+ req.once("error", (error) => finish(reject, error));
731
+ if (signal) {
732
+ if (signal.aborted) onAbort();
733
+ else signal.addEventListener("abort", onAbort, { once: true });
734
+ }
735
+ });
736
+ }
737
+
662
738
  // ── Window ─────────────────────────────────────────────────────────────────
663
739
 
664
740
  function findDistPath() {
@@ -679,21 +755,41 @@ function findDistPath() {
679
755
 
680
756
  /** Refuse a link loudly — the user clicked it, so they get told why nothing happened. */
681
757
  function reportBlockedLink(url) {
682
- const message = describeBlockedUrl(url);
683
- console.error(`[main] ${message}`);
758
+ const locale = app.getLocale();
759
+ warnAboutLink(
760
+ linkNoticeText(locale).blockedTitle,
761
+ describeBlockedUrl(url, locale),
762
+ describeBlockedUrl(url),
763
+ locale,
764
+ );
765
+ }
766
+
767
+ function reportLinkNotOpened(url, err) {
768
+ const locale = app.getLocale();
769
+ warnAboutLink(
770
+ linkNoticeText(locale).notOpenedTitle,
771
+ describeOpenFailure(url, err, locale),
772
+ describeOpenFailure(url, err),
773
+ locale,
774
+ );
775
+ }
776
+
777
+ // The log line stays English so bug reports stay readable.
778
+ function warnAboutLink(title, message, logMessage, locale) {
779
+ console.error(`[main] ${logMessage}`);
684
780
  // Non-blocking and parented: showErrorBox would freeze the main process.
685
781
  dialog
686
782
  .showMessageBox(mainWindow && !mainWindow.isDestroyed() ? mainWindow : null, {
687
783
  type: "warning",
688
- title: "Link blocked",
689
- message: "Link blocked",
784
+ title,
785
+ message: title,
690
786
  detail: message,
691
- buttons: ["OK"],
787
+ buttons: [linkNoticeText(locale).ok],
692
788
  noLink: true,
693
789
  })
694
790
  .catch((err) =>
695
791
  console.error(
696
- `[main] Could not show the link-blocked dialog: ${err && err.message ? err.message : err}`
792
+ `[main] Could not show the "${title}" dialog: ${err && err.message ? err.message : err}`
697
793
  )
698
794
  );
699
795
  }
@@ -760,13 +856,14 @@ function createWindow() {
760
856
  installWindowKeys(mainWindow.webContents, { devTools: !app.isPackaged });
761
857
  }
762
858
  mainWindow.setMenuBarVisibility(false);
859
+ installContextMenu(mainWindow, { Menu, clipboard, locale: app.getLocale() });
763
860
 
764
861
  // Open external links in the default browser. The URL here is already
765
862
  // RESOLVED against the file:// document, so a scheme-less markdown link
766
863
  // arrives as file:///C:/… — check the scheme before handing it to the OS.
767
864
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
768
865
  if (isAllowedExternalUrl(url)) {
769
- shell.openExternal(url);
866
+ openExternalSafely(shell, url, (err) => reportLinkNotOpened(url, err));
770
867
  } else {
771
868
  reportBlockedLink(url);
772
869
  }
@@ -780,7 +877,7 @@ function createWindow() {
780
877
  if (isInAppNavigation(url, currentUrl)) return;
781
878
  event.preventDefault();
782
879
  if (isAllowedExternalUrl(url)) {
783
- shell.openExternal(url);
880
+ openExternalSafely(shell, url, (err) => reportLinkNotOpened(url, err));
784
881
  return;
785
882
  }
786
883
  reportBlockedLink(url);
@@ -888,9 +985,11 @@ async function loadApp() {
888
985
  </div>
889
986
  </body>
890
987
  </html>`;
891
- mainWindow.loadURL(
892
- "data:text/html;charset=utf-8," + encodeURIComponent(waitingHtml)
893
- );
988
+ mainWindow
989
+ .loadURL("data:text/html;charset=utf-8," + encodeURIComponent(waitingHtml))
990
+ .catch((err) =>
991
+ console.error(`[main] Could not show the waiting page: ${err && err.message ? err.message : err}`)
992
+ );
894
993
  }
895
994
  }
896
995
 
@@ -1007,22 +1106,13 @@ function setupJumpList() {
1007
1106
  items: [
1008
1107
  {
1009
1108
  type: "task",
1010
- title: "New Task",
1011
- description: "Start a new agent task",
1109
+ title: "Open GAIA",
1110
+ description: "Show the GAIA window",
1012
1111
  program: process.execPath,
1013
1112
  args: "",
1014
1113
  iconPath: process.execPath,
1015
1114
  iconIndex: 0,
1016
1115
  },
1017
- {
1018
- type: "task",
1019
- title: "Agent Manager",
1020
- description: "View and manage OS agents",
1021
- program: process.execPath,
1022
- args: "--show-agents",
1023
- iconPath: process.execPath,
1024
- iconIndex: 0,
1025
- },
1026
1116
  ],
1027
1117
  },
1028
1118
  ]);
@@ -1132,6 +1222,7 @@ app.whenReady().then(async () => {
1132
1222
  // The window, and the tray that keeps a closed one reachable, come before
1133
1223
  // anything that can take time, so an install runs in plain sight.
1134
1224
  titleDownloadSaveDialogs();
1225
+ installBackendAuth(session.defaultSession, { getPort: () => spawnedBackendPort });
1135
1226
  // Before the window: the desktop ties a window to its launcher when it appears.
1136
1227
  if (app.isPackaged) {
1137
1228
  try {
@@ -1214,7 +1305,9 @@ app.whenReady().then(async () => {
1214
1305
  if (shutdownStarted) return;
1215
1306
  backendStarting = startBackend();
1216
1307
  backendProcess = await backendStarting;
1308
+ // The window reads this state and shows the failure instead of waiting for a backend.
1217
1309
  if (backendProcess) backendSupervisor.running(backendPort);
1310
+ else backendSupervisor.failedToStart(missingBackendMessage());
1218
1311
  if (shutdownStarted) {
1219
1312
  console.log("[main] Quit during startup — not opening the window");
1220
1313
  return;
@@ -1250,9 +1343,10 @@ app.whenReady().then(async () => {
1250
1343
  let backendReady = false;
1251
1344
  if (backendProcess) {
1252
1345
  console.log("Waiting for backend to start...");
1253
- backendReady = await waitForBackend(STARTUP_TIMEOUT);
1346
+ backendReady = await waitForBackend(STARTUP_TIMEOUT, () => !quitStarted());
1254
1347
  if (backendReady) {
1255
1348
  console.log("Backend API is ready on port", backendPort);
1349
+ enableBackendHealthMonitoring();
1256
1350
  } else {
1257
1351
  console.warn("Backend did not respond within timeout.");
1258
1352
  }
@@ -1260,8 +1354,16 @@ app.whenReady().then(async () => {
1260
1354
  if (!backendReady) {
1261
1355
  autoUpdater.reportStartFailure();
1262
1356
  if (backendProcess) {
1263
- waitForBackend(STARTUP_TIMEOUT * 10).then((ready) => {
1264
- if (ready) autoUpdater.clearStartFailure();
1357
+ waitForBackend(STARTUP_TIMEOUT * 10, () => !quitStarted()).then((ready) => {
1358
+ if (ready) {
1359
+ autoUpdater.clearStartFailure();
1360
+ enableBackendHealthMonitoring();
1361
+ } else if (backendProcess && !quitStarted() && backendSupervisor.getState().status === "running") {
1362
+ backendHealthMonitoringEnabled = true;
1363
+ backendSupervisor.healthFailed(
1364
+ new Error("The backend health endpoint did not respond during the startup grace period.")
1365
+ );
1366
+ }
1265
1367
  });
1266
1368
  }
1267
1369
  }
@@ -1347,6 +1449,7 @@ const quitGuard = installQuitGuard({
1347
1449
  // Mark any subsequent backend exit as intentional so we don't pop the
1348
1450
  // crash dialog during normal shutdown.
1349
1451
  isIntentionalKill = true;
1452
+ backendHealthMonitor.stop();
1350
1453
  backendSupervisor.stop();
1351
1454
  },
1352
1455
  onError: (err) => {
@@ -1362,6 +1465,7 @@ const quitGuard = installQuitGuard({
1362
1465
  // The installer is already running: a restart now would hold its files open.
1363
1466
  electronAutoUpdater.on("before-quit-for-update", () => {
1364
1467
  updateQuitStarted = true;
1468
+ backendHealthMonitor.stop();
1365
1469
  backendSupervisor.stop();
1366
1470
  });
1367
1471
 
@@ -1371,6 +1475,7 @@ installQuitCleanup({ app, cleanup });
1371
1475
 
1372
1476
  async function cleanup() {
1373
1477
  shutdownStarted = true;
1478
+ backendHealthMonitor.stop();
1374
1479
  backendSupervisor.stop();
1375
1480
  const installStopped = engineInstall ? engineInstall.stop() : null;
1376
1481
  const updating = app.isPackaged && autoUpdater.installsOnQuit();
@@ -1453,7 +1558,7 @@ async function stopBackendForQuit() {
1453
1558
  if (backendStarting) {
1454
1559
  try {
1455
1560
  const started = await backendStarting;
1456
- if (started && !backendProcess && started.exitCode === null && started.signalCode === null) {
1561
+ if (started && !backendProcess && !backendCleanupPending && started.exitCode === null && started.signalCode === null) {
1457
1562
  backendProcess = started;
1458
1563
  }
1459
1564
  } catch (err) {
@@ -1465,17 +1570,16 @@ async function stopBackendForQuit() {
1465
1570
  // (SIGTERM → wait 3 s → SIGKILL).
1466
1571
  // F5: previously we did this inline; extracted so main.cjs stays lean and
1467
1572
  // to prevent orphan leaks across runs (issue #782).
1468
- if (backendProcess) {
1573
+ const processToStop = backendCleanupPending || backendProcess;
1574
+ if (processToStop) {
1469
1575
  console.log("Stopping backend process...");
1470
- const proc = backendProcess;
1576
+ const proc = processToStop;
1471
1577
  backendProcess = null;
1472
- isIntentionalKill = true;
1473
1578
 
1474
1579
  try {
1475
- // Pass the ChildProcess handle (not a bare pid) so port-manager
1476
- // can short-circuit via `proc.exitCode` and close the PID-reuse
1477
- // TOCTOU window.
1478
- await portManager.killBackend(proc);
1580
+ // Pass the ChildProcess handle so the process-tree tracker can safely
1581
+ // retry descendants if the launcher exits during termination.
1582
+ await stopBackendTree(proc);
1479
1583
  } catch (err) {
1480
1584
  console.error("Error stopping backend:", err.message);
1481
1585
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amd-gaia/agent-ui",
3
- "version": "0.27.0-rc.2",
3
+ "version": "0.27.0-rc.21",
4
4
  "type": "module",
5
5
  "productName": "GAIA Agent UI",
6
6
  "desktopName": "gaia-desktop.desktop",
@@ -71,7 +71,7 @@
71
71
  },
72
72
  "devDependencies": {
73
73
  "@playwright/test": "1.65.1",
74
- "@testing-library/jest-dom": "^7.0.0",
74
+ "@testing-library/jest-dom": "^8.0.0",
75
75
  "@testing-library/react": "^16.1.0",
76
76
  "@testing-library/user-event": "^14.5.2",
77
77
  "@types/react": "^19.2.17",
package/preload.cjs CHANGED
@@ -175,6 +175,12 @@ contextBridge.exposeInMainWorld("gaiaUpdater", {
175
175
  /** Go back to the version before the last update, and pin it. */
176
176
  revertUpdate: () => ipcRenderer.invoke("gaia:update:revert"),
177
177
 
178
+ /** Setup finished on this version: remember it as the one to come back to. */
179
+ markSetupWorked: () => ipcRenderer.invoke("gaia:update:setup-worked"),
180
+
181
+ /** Go back to the last version setup finished on, and pin it. */
182
+ revertToLastWorking: () => ipcRenderer.invoke("gaia:update:revert-to-working"),
183
+
178
184
  /**
179
185
  * Resume normal auto-updates — clears the version pin set by installVersion.
180
186
  * Resolves with the updated state.