@amd-gaia/agent-ui 0.27.0-rc.11 → 0.27.0-rc.13

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/dist/assets/AdvancedSettings-D2hiKcb8.js +1 -0
  2. package/dist/assets/{AutomationsSettings-CBgmdTDU.js → AutomationsSettings-kmr5NhGJ.js} +1 -1
  3. package/dist/assets/ConnectorsPane-BKJzwjs_.js +1 -0
  4. package/dist/assets/DocumentLibrary-Cen-e75Q.js +5 -0
  5. package/dist/assets/FileBrowser-C1BvzIK3.js +4 -0
  6. package/dist/assets/MemoryDashboard-CTv0qxep.js +1 -0
  7. package/dist/assets/{MessagingSettings-CKylzEfe.js → MessagingSettings-Z9ZX0Hcu.js} +1 -1
  8. package/dist/assets/MobileAccessModal-De86l1zd.js +2 -0
  9. package/dist/assets/{ScheduleManager-xu8gK_Yr.js → ScheduleManager-BLUwCMl0.js} +1 -1
  10. package/dist/assets/folderIndexResult-kIPjvkMW.js +1 -0
  11. package/dist/assets/{index-DTQb951g.js → index-BFIVkgAZ.js} +55 -55
  12. package/dist/assets/{index-ByAKIpox.css → index-DB1-bDNU.css} +1 -1
  13. package/dist/assets/useFocusTrap-CzBMA4Ux.js +6 -0
  14. package/dist/index.html +3 -3
  15. package/dist/sw.js +1 -1
  16. package/main-safety-net.cjs +19 -0
  17. package/main.cjs +150 -44
  18. package/package.json +1 -1
  19. package/services/backend-crash-dialog.cjs +19 -5
  20. package/services/backend-health-monitor.cjs +86 -0
  21. package/services/backend-supervisor.cjs +11 -3
  22. package/services/browser-pane/dev-servers.cjs +44 -1
  23. package/services/browser-pane/listen-addresses.cjs +140 -0
  24. package/services/link-policy.cjs +48 -13
  25. package/services/port-manager.cjs +2 -3
  26. package/services/process-tree.cjs +84 -14
  27. package/dist/assets/AdvancedSettings-Bwkk7Urp.js +0 -1
  28. package/dist/assets/ConnectorsPane-C84jzSpJ.js +0 -1
  29. package/dist/assets/DocumentLibrary-BQsh6FlL.js +0 -5
  30. package/dist/assets/FileBrowser-Cd6e0KtR.js +0 -4
  31. package/dist/assets/MemoryDashboard-CA-SQUh6.js +0 -1
  32. package/dist/assets/MobileAccessModal-Dxs7Nnto.js +0 -2
  33. package/dist/assets/useFocusTrap-bD-rtqqm.js +0 -6
package/dist/index.html CHANGED
@@ -26,10 +26,10 @@
26
26
  // main.tsx applies the theme again and reports why it could not read the saved one.
27
27
  }
28
28
  </script>
29
- <script type="module" crossorigin src="./assets/index-DTQb951g.js"></script>
29
+ <script type="module" crossorigin src="./assets/index-BFIVkgAZ.js"></script>
30
30
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
31
- <link rel="modulepreload" crossorigin href="./assets/useFocusTrap-bD-rtqqm.js">
32
- <link rel="stylesheet" crossorigin href="./assets/index-ByAKIpox.css">
31
+ <link rel="modulepreload" crossorigin href="./assets/useFocusTrap-CzBMA4Ux.js">
32
+ <link rel="stylesheet" crossorigin href="./assets/index-DB1-bDNU.css">
33
33
  </head>
34
34
  <body>
35
35
  <div id="root"></div>
package/dist/sw.js CHANGED
@@ -9,7 +9,7 @@
9
9
  // never sees a stale UI or stale data.
10
10
 
11
11
  const CACHE_PREFIX = 'gaia-assets-';
12
- const CACHE_NAME = CACHE_PREFIX + '0.27.0rc11-c3c1e8b8a25034a3';
12
+ const CACHE_NAME = CACHE_PREFIX + '0.27.0rc13-906cbe39bcfa5271';
13
13
  const ASSETS_PATH = new URL('assets/', self.registration.scope).pathname;
14
14
 
15
15
  self.addEventListener('install', () => {
@@ -110,6 +110,9 @@ const FATAL_EXIT_GRACE_MS = 25000;
110
110
  * when a window's page dies while GAIA runs on, e.g. to offer a reload.
111
111
  * Without it, or if it throws synchronously, the crash is fatal; an async
112
112
  * handler must handle its own failures.
113
+ * @param {Function} [opts.isPanePage] - Called with a webContents whose page
114
+ * died; true means it is a browser-pane tab, which shows its own notice, so
115
+ * the crash is logged only: no dialog, no quit, no crash count.
113
116
  */
114
117
  function installSafetyNet({
115
118
  logPath,
@@ -120,6 +123,7 @@ function installSafetyNet({
120
123
  exitGraceMs = FATAL_EXIT_GRACE_MS,
121
124
  holdCrashCount = () => false,
122
125
  onRendererGone,
126
+ isPanePage,
123
127
  }) {
124
128
  const homedir = homedirFn || (() => os.homedir());
125
129
 
@@ -218,6 +222,21 @@ function installSafetyNet({
218
222
  appendLog(logPath, `[${new Date().toISOString()}] RENDER_PROCESS_EXITED reason=${reason}`);
219
223
  return;
220
224
  }
225
+ if (typeof isPanePage === "function") {
226
+ let panePage = false;
227
+ try {
228
+ panePage = isPanePage(webContents) === true;
229
+ } catch (err) {
230
+ appendLog(logPath, `[${new Date().toISOString()}] RENDER_PROCESS_GONE pane check failed: ${err.stack || err}`);
231
+ }
232
+ if (panePage) {
233
+ appendLog(
234
+ logPath,
235
+ `[${new Date().toISOString()}] PANE_PAGE_GONE reason=${reason} exitCode=${details && details.exitCode}`
236
+ );
237
+ return;
238
+ }
239
+ }
221
240
  if (typeof onRendererGone === "function") {
222
241
  // Only the page died: the backend and agents still run, so the window can come back.
223
242
  appendLog(
package/main.cjs CHANGED
@@ -72,6 +72,8 @@ try {
72
72
  onRendererGone: (contents, details) => {
73
73
  void handleRendererGone(contents, details);
74
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),
75
77
  }));
76
78
  } catch (err) {
77
79
  try { process.stderr.write(`[main] safety-net load failed: ${err.message}\n`); } catch { }
@@ -114,6 +116,7 @@ const {
114
116
  const { showBackendCrashDialog } = require("./services/backend-crash-dialog.cjs");
115
117
  const { showRendererGoneDialog } = require("./services/renderer-gone-dialog.cjs");
116
118
  const { createBackendSupervisor } = require("./services/backend-supervisor.cjs");
119
+ const { createBackendHealthMonitor } = require("./services/backend-health-monitor.cjs");
117
120
  const { buildIndexQuery, INSTALL_SCREEN_QUERY } = require("./services/index-query.cjs");
118
121
  const backendInstaller = require("./services/backend-installer.cjs");
119
122
  const { createEngineInstall } = require("./services/engine-install.cjs");
@@ -126,6 +129,7 @@ const {
126
129
  describeBlockedUrl,
127
130
  describeOpenFailure,
128
131
  openExternalSafely,
132
+ linkNoticeText,
129
133
  } = require("./services/link-policy.cjs");
130
134
  const { installWindowKeys } = require("./services/window-keys.cjs");
131
135
  const { installContextMenu } = require("./services/context-menu.cjs");
@@ -232,6 +236,7 @@ const APP_NAME = "GAIA";
232
236
  // from prior aborted sessions (issue #782 / T5).
233
237
  const DEFAULT_BACKEND_PORT = 4200;
234
238
  const STARTUP_TIMEOUT = 30000;
239
+ const BACKEND_HEALTH_CHECK_TIMEOUT = 2000;
235
240
  // A restart must answer within this, or it counts as a failed try.
236
241
  const RESTART_TIMEOUT = 90000;
237
242
 
@@ -263,6 +268,9 @@ const windowConfig = appConfig.window || {
263
268
  // ── State ──────────────────────────────────────────────────────────────────
264
269
 
265
270
  let backendProcess = null;
271
+ let backendCleanupPending = null;
272
+ let backendHealthMonitoringEnabled = false;
273
+ let backendHealthMonitor = null;
266
274
  // The in-flight startBackend(), so a quit during startup can wait for the
267
275
  // spawn and stop it instead of leaving it behind.
268
276
  let backendStarting = null;
@@ -502,6 +510,32 @@ async function startBackend() {
502
510
  return child;
503
511
  }
504
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
+
505
539
  /**
506
540
  * Start a new backend for the supervisor and resolve once it answers.
507
541
  * Rejects when it exits first or never answers, so the supervisor retries.
@@ -509,18 +543,14 @@ async function startBackend() {
509
543
  * stop it first, or the new backend would run beside it on a new port.
510
544
  */
511
545
  async function restartBackend() {
512
- if (backendProcess) {
513
- const hung = backendProcess;
514
- backendProcess = null;
515
- isIntentionalKill = true;
516
- await portManager.killBackend(hung);
517
- }
546
+ const previousBackend = backendCleanupPending || backendProcess;
547
+ if (previousBackend) await stopBackendTree(previousBackend);
548
+
518
549
  backendStarting = startBackend();
519
550
  const child = await backendStarting;
520
551
  if (!child) throw Object.assign(new Error(missingBackendMessage()), { terminal: true });
521
552
  if (quitStarted()) {
522
- isIntentionalKill = true;
523
- await portManager.killBackend(child);
553
+ await stopBackendTree(child);
524
554
  throw new Error("GAIA is quitting, so the restarted backend was stopped.");
525
555
  }
526
556
  backendProcess = child;
@@ -530,10 +560,10 @@ async function restartBackend() {
530
560
  if (!alive()) {
531
561
  throw new Error(`The backend exited (code ${child.exitCode}, signal ${child.signalCode}) before it answered.`);
532
562
  }
533
- isIntentionalKill = true;
534
- await portManager.killBackend(child);
563
+ await stopBackendTree(child);
535
564
  throw new Error(`The backend did not answer within ${RESTART_TIMEOUT / 1000} s.`);
536
565
  }
566
+ enableBackendHealthMonitoring();
537
567
  console.log(`[main] Backend restarted on port ${backendPort} (pid=${child.pid})`);
538
568
  if (trayManager) {
539
569
  trayManager.setBackendPort(backendPort);
@@ -550,10 +580,13 @@ function backendStateForRenderer(state) {
550
580
  const backendSupervisor = createBackendSupervisor({
551
581
  start: restartBackend,
552
582
  onStopped: (state) => {
553
- const { code = null, signal = null } = state.lastExit || {};
554
- void handleBackendCrash(code, signal);
583
+ void handleBackendCrash(state);
555
584
  },
556
585
  onState: (state) => {
586
+ if (backendHealthMonitor) {
587
+ if (backendHealthMonitoringEnabled && state.status === "running") backendHealthMonitor.start();
588
+ else backendHealthMonitor.stop();
589
+ }
557
590
  console.log(
558
591
  `[main] Backend ${state.status}` +
559
592
  (state.status === "restarting" ? ` (try ${state.attempt} of ${state.maxRestarts})` : "") +
@@ -567,6 +600,22 @@ const backendSupervisor = createBackendSupervisor({
567
600
  },
568
601
  });
569
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
+
570
619
  ipcMain.handle("backend:get-state", () => backendStateForRenderer(backendSupervisor.getState()));
571
620
  ipcMain.handle("backend:restart", () => {
572
621
  backendSupervisor.restartNow();
@@ -577,7 +626,8 @@ ipcMain.handle("backend:restart", () => {
577
626
  * Tell the user the backend stopped and offer Restart / Save diagnostics /
578
627
  * Quit. Invoked by the supervisor's onStopped once automatic restarts run out.
579
628
  */
580
- async function handleBackendCrash(code, signal) {
629
+ async function handleBackendCrash(state) {
630
+ const { code = null, signal = null } = state.lastExit || {};
581
631
  autoUpdater.reportStartFailure();
582
632
  try {
583
633
  const choice = await showBackendCrashDialog({
@@ -585,6 +635,7 @@ async function handleBackendCrash(code, signal) {
585
635
  app,
586
636
  code,
587
637
  signal,
638
+ reason: state.lastError,
588
639
  tailLines: backendStderrTail.slice(-8),
589
640
  writeDiagnostics: () => portManager.writeDiagnosticsBundle(),
590
641
  // The backend is gone, so there is no running work to ask about.
@@ -627,24 +678,10 @@ async function handleRendererGone(contents, { reason }) {
627
678
 
628
679
  async function waitForBackend(timeoutMs, isAlive = () => true) {
629
680
  const start = Date.now();
630
- const http = require("http");
631
681
 
632
682
  while (Date.now() - start < timeoutMs && isAlive()) {
633
683
  try {
634
- await new Promise((resolve, reject) => {
635
- const req = http.get(healthCheckUrl, (res) => {
636
- if (res.statusCode === 200) {
637
- resolve();
638
- } else {
639
- reject(new Error(`Status ${res.statusCode}`));
640
- }
641
- });
642
- req.on("error", reject);
643
- req.setTimeout(2000, () => {
644
- req.destroy();
645
- reject(new Error("timeout"));
646
- });
647
- });
684
+ await checkBackendHealth();
648
685
  return true;
649
686
  } catch {
650
687
  await new Promise((r) => setTimeout(r, 500));
@@ -653,6 +690,51 @@ async function waitForBackend(timeoutMs, isAlive = () => true) {
653
690
  return false;
654
691
  }
655
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
+
656
738
  // ── Window ─────────────────────────────────────────────────────────────────
657
739
 
658
740
  function findDistPath() {
@@ -673,15 +755,28 @@ function findDistPath() {
673
755
 
674
756
  /** Refuse a link loudly — the user clicked it, so they get told why nothing happened. */
675
757
  function reportBlockedLink(url) {
676
- warnAboutLink("Link blocked", describeBlockedUrl(url));
758
+ const locale = app.getLocale();
759
+ warnAboutLink(
760
+ linkNoticeText(locale).blockedTitle,
761
+ describeBlockedUrl(url, locale),
762
+ describeBlockedUrl(url),
763
+ locale,
764
+ );
677
765
  }
678
766
 
679
767
  function reportLinkNotOpened(url, err) {
680
- warnAboutLink("Link not opened", describeOpenFailure(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
+ );
681
775
  }
682
776
 
683
- function warnAboutLink(title, message) {
684
- console.error(`[main] ${message}`);
777
+ // The log line stays English so bug reports stay readable.
778
+ function warnAboutLink(title, message, logMessage, locale) {
779
+ console.error(`[main] ${logMessage}`);
685
780
  // Non-blocking and parented: showErrorBox would freeze the main process.
686
781
  dialog
687
782
  .showMessageBox(mainWindow && !mainWindow.isDestroyed() ? mainWindow : null, {
@@ -689,7 +784,7 @@ function warnAboutLink(title, message) {
689
784
  title,
690
785
  message: title,
691
786
  detail: message,
692
- buttons: ["OK"],
787
+ buttons: [linkNoticeText(locale).ok],
693
788
  noLink: true,
694
789
  })
695
790
  .catch((err) =>
@@ -1248,9 +1343,10 @@ app.whenReady().then(async () => {
1248
1343
  let backendReady = false;
1249
1344
  if (backendProcess) {
1250
1345
  console.log("Waiting for backend to start...");
1251
- backendReady = await waitForBackend(STARTUP_TIMEOUT);
1346
+ backendReady = await waitForBackend(STARTUP_TIMEOUT, () => !quitStarted());
1252
1347
  if (backendReady) {
1253
1348
  console.log("Backend API is ready on port", backendPort);
1349
+ enableBackendHealthMonitoring();
1254
1350
  } else {
1255
1351
  console.warn("Backend did not respond within timeout.");
1256
1352
  }
@@ -1258,8 +1354,16 @@ app.whenReady().then(async () => {
1258
1354
  if (!backendReady) {
1259
1355
  autoUpdater.reportStartFailure();
1260
1356
  if (backendProcess) {
1261
- waitForBackend(STARTUP_TIMEOUT * 10).then((ready) => {
1262
- 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
+ }
1263
1367
  });
1264
1368
  }
1265
1369
  }
@@ -1345,6 +1449,7 @@ const quitGuard = installQuitGuard({
1345
1449
  // Mark any subsequent backend exit as intentional so we don't pop the
1346
1450
  // crash dialog during normal shutdown.
1347
1451
  isIntentionalKill = true;
1452
+ backendHealthMonitor.stop();
1348
1453
  backendSupervisor.stop();
1349
1454
  },
1350
1455
  onError: (err) => {
@@ -1360,6 +1465,7 @@ const quitGuard = installQuitGuard({
1360
1465
  // The installer is already running: a restart now would hold its files open.
1361
1466
  electronAutoUpdater.on("before-quit-for-update", () => {
1362
1467
  updateQuitStarted = true;
1468
+ backendHealthMonitor.stop();
1363
1469
  backendSupervisor.stop();
1364
1470
  });
1365
1471
 
@@ -1369,6 +1475,7 @@ installQuitCleanup({ app, cleanup });
1369
1475
 
1370
1476
  async function cleanup() {
1371
1477
  shutdownStarted = true;
1478
+ backendHealthMonitor.stop();
1372
1479
  backendSupervisor.stop();
1373
1480
  const installStopped = engineInstall ? engineInstall.stop() : null;
1374
1481
  const updating = app.isPackaged && autoUpdater.installsOnQuit();
@@ -1451,7 +1558,7 @@ async function stopBackendForQuit() {
1451
1558
  if (backendStarting) {
1452
1559
  try {
1453
1560
  const started = await backendStarting;
1454
- if (started && !backendProcess && started.exitCode === null && started.signalCode === null) {
1561
+ if (started && !backendProcess && !backendCleanupPending && started.exitCode === null && started.signalCode === null) {
1455
1562
  backendProcess = started;
1456
1563
  }
1457
1564
  } catch (err) {
@@ -1463,17 +1570,16 @@ async function stopBackendForQuit() {
1463
1570
  // (SIGTERM → wait 3 s → SIGKILL).
1464
1571
  // F5: previously we did this inline; extracted so main.cjs stays lean and
1465
1572
  // to prevent orphan leaks across runs (issue #782).
1466
- if (backendProcess) {
1573
+ const processToStop = backendCleanupPending || backendProcess;
1574
+ if (processToStop) {
1467
1575
  console.log("Stopping backend process...");
1468
- const proc = backendProcess;
1576
+ const proc = processToStop;
1469
1577
  backendProcess = null;
1470
- isIntentionalKill = true;
1471
1578
 
1472
1579
  try {
1473
- // Pass the ChildProcess handle (not a bare pid) so port-manager
1474
- // can short-circuit via `proc.exitCode` and close the PID-reuse
1475
- // TOCTOU window.
1476
- 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);
1477
1583
  } catch (err) {
1478
1584
  console.error("Error stopping backend:", err.message);
1479
1585
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amd-gaia/agent-ui",
3
- "version": "0.27.0-rc.11",
3
+ "version": "0.27.0-rc.13",
4
4
  "type": "module",
5
5
  "productName": "GAIA Agent UI",
6
6
  "desktopName": "gaia-desktop.desktop",
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  /**
5
- * The dialog shown when GAIA's backend exits on its own. Every choice ends
5
+ * The dialog shown when GAIA's backend cannot recover after an exit or outage. Every choice ends
6
6
  * somewhere: Restart relaunches the app, Quit quits it, and Save diagnostics
7
7
  * writes the bundle and comes back to the same choice.
8
8
  */
@@ -19,8 +19,11 @@ function stripAnsi(text) {
19
19
  }
20
20
 
21
21
  /** The dialog's detail text: what happened, what to do, then the log tail. */
22
- function crashDetail(code, signal, tailLines) {
23
- const how = signal ? `signal ${signal}` : `exit code ${code}`;
22
+ function crashDetail(code, signal, tailLines, reason) {
23
+ let how;
24
+ if (signal) how = `signal ${signal}`;
25
+ else if (code !== null && code !== undefined) how = `exit code ${code}`;
26
+ else how = `last error: ${reason || "unknown cause"}`;
24
27
  const tail = (tailLines || []).map(stripAnsi).join("\n") || "(nothing was logged)";
25
28
  return (
26
29
  `GAIA's background service stopped unexpectedly (${how}). Your chats are saved.\n` +
@@ -50,8 +53,19 @@ function relaunchOptions(env = process.env, argv = process.argv) {
50
53
  * @param {object} [deps.parent] window the dialog is modal to, e.g. mainWindow
51
54
  * @returns {Promise<"restart"|"quit">}
52
55
  */
53
- async function showBackendCrashDialog({ dialog, app, code, signal, tailLines, writeDiagnostics, beforeQuit, env = process.env, parent }) {
54
- const detail = crashDetail(code, signal, tailLines);
56
+ async function showBackendCrashDialog({
57
+ dialog,
58
+ app,
59
+ code,
60
+ signal,
61
+ reason,
62
+ tailLines,
63
+ writeDiagnostics,
64
+ beforeQuit,
65
+ env = process.env,
66
+ parent,
67
+ }) {
68
+ const detail = crashDetail(code, signal, tailLines, reason);
55
69
  // Modal to GAIA's window and in front: unparented, it can open behind other apps.
56
70
  const owner = parent && !parent.isDestroyed() ? parent : null;
57
71
  if (owner) {
@@ -0,0 +1,86 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ "use strict";
5
+
6
+ const DEFAULTS = Object.freeze({
7
+ intervalMs: 5000,
8
+ failureThreshold: 3,
9
+ });
10
+
11
+ function createBackendHealthMonitor({
12
+ check,
13
+ onUnhealthy,
14
+ intervalMs = DEFAULTS.intervalMs,
15
+ failureThreshold = DEFAULTS.failureThreshold,
16
+ setIntervalFn = setInterval,
17
+ clearIntervalFn = clearInterval,
18
+ }) {
19
+ if (typeof check !== "function") {
20
+ throw new Error("backend health monitor: check must be a function");
21
+ }
22
+ if (typeof onUnhealthy !== "function") {
23
+ throw new Error("backend health monitor: onUnhealthy must be a function");
24
+ }
25
+ if (!Number.isInteger(intervalMs) || intervalMs < 1) {
26
+ throw new Error(`backend health monitor: intervalMs must be a positive integer, got ${intervalMs}`);
27
+ }
28
+ if (!Number.isInteger(failureThreshold) || failureThreshold < 1) {
29
+ throw new Error(`backend health monitor: failureThreshold must be a positive integer, got ${failureThreshold}`);
30
+ }
31
+
32
+ let timer = null;
33
+ let generation = 0;
34
+ let failures = 0;
35
+ let checking = false;
36
+ let activeController = null;
37
+
38
+ async function poll(run) {
39
+ if (checking || timer === null || run !== generation) return;
40
+ checking = true;
41
+ const controller = new AbortController();
42
+ activeController = controller;
43
+ try {
44
+ await check(controller.signal);
45
+ if (run === generation) failures = 0;
46
+ } catch (error) {
47
+ if (run !== generation) return;
48
+ failures += 1;
49
+ if (failures >= failureThreshold) {
50
+ const consecutiveFailures = failures;
51
+ stop();
52
+ onUnhealthy(error, consecutiveFailures);
53
+ }
54
+ } finally {
55
+ if (activeController === controller) activeController = null;
56
+ checking = false;
57
+ }
58
+ }
59
+
60
+ function start() {
61
+ if (timer !== null) return;
62
+ const run = ++generation;
63
+ failures = 0;
64
+ timer = setIntervalFn(() => {
65
+ void poll(run);
66
+ }, intervalMs);
67
+ if (timer && typeof timer.unref === "function") timer.unref();
68
+ }
69
+
70
+ function stop() {
71
+ generation += 1;
72
+ if (activeController) {
73
+ activeController.abort();
74
+ activeController = null;
75
+ }
76
+ if (timer !== null) {
77
+ clearIntervalFn(timer);
78
+ timer = null;
79
+ }
80
+ failures = 0;
81
+ }
82
+
83
+ return { start, stop };
84
+ }
85
+
86
+ module.exports = { createBackendHealthMonitor, DEFAULTS };
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  /**
5
- * Restarts GAIA's backend when it exits on its own: after a growing wait,
5
+ * Restarts GAIA's backend when it exits or stops answering: after a growing wait,
6
6
  * at most `maxRestarts` times in `windowMs`, then it stops and waits for the
7
7
  * user's Restart GAIA (restartNow), which also restarts a backend still
8
8
  * reported running but hung. No Electron imports, so it unit-tests.
@@ -76,7 +76,7 @@ function createBackendSupervisor({
76
76
  ({ port }) => {
77
77
  starting = false;
78
78
  if (stopped) return;
79
- emit({ status: "running", port, since: null, attempt: 0, lastError: null });
79
+ emit({ status: "running", port, since: null, attempt: 0, lastExit: null, lastError: null });
80
80
  },
81
81
  (err) => {
82
82
  starting = false;
@@ -113,7 +113,7 @@ function createBackendSupervisor({
113
113
  return {
114
114
  /** The backend is up on `port` (the first start, outside the supervisor). */
115
115
  running(port) {
116
- emit({ status: "running", port, since: null, attempt: 0, nextAttemptAt: null, lastError: null });
116
+ emit({ status: "running", port, since: null, attempt: 0, nextAttemptAt: null, lastExit: null, lastError: null });
117
117
  },
118
118
 
119
119
  /** No backend could be started at all (its program is missing): wait for Restart GAIA. */
@@ -135,6 +135,14 @@ function createBackendSupervisor({
135
135
  return schedule({ lastExit: { code, signal } });
136
136
  },
137
137
 
138
+ /** A running backend stopped answering, though its child process may remain alive. */
139
+ healthFailed(error) {
140
+ if (stopped) return "stopped";
141
+ if (starting || timer || state.status !== "running") return state.status;
142
+ const lastError = error && error.message ? error.message : String(error);
143
+ return schedule({ lastError });
144
+ },
145
+
138
146
  /** The user's Restart GAIA: start now, with a fresh budget. Also restarts
139
147
  * a backend still reported "running": that is a hung backend the startup
140
148
  * screen offers Restart for, and start() stops the old process first. */