@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
@@ -41,6 +41,8 @@
41
41
  * - installVersion(tag) → downgrade/install a specific tagged release
42
42
  * - clearPin() → resume auto-updates (clear the version pin)
43
43
  * - revertUpdate() → go back to the version before the last update
44
+ * - markSetupWorked() → note that setup finished on the running version
45
+ * - revertToLastWorking() → go back to the last version setup finished on
44
46
  * - setAutoUpdate(enabled) → persist the auto-update preference
45
47
  * - downloadUpdate() → download the offered update ("Update now")
46
48
  * - restartToInstall() → restart into a downloaded update
@@ -92,6 +94,8 @@ const PICKER_FEED_PAGES = 3;
92
94
  // Where a restart notes the update it started: a silent install that fails
93
95
  // shows nothing, so the next launch is what finds out.
94
96
  const INSTALL_ATTEMPT_PATH = path.join(os.homedir(), ".gaia", "update-attempt.json");
97
+ // The last app version first-run setup finished on, and when: {version, at}.
98
+ const LAST_WORKING_PATH = path.join(os.homedir(), ".gaia", "last-working-version.json");
95
99
  const PREVIOUS_VERSION_KEY = "previousAppVersion";
96
100
  const LAUNCHES_SINCE_UPDATE_KEY = "launchesSinceUpdate";
97
101
  // Same cap as the TUI's sumsAtOnce, to go easy on proxies.
@@ -343,6 +347,8 @@ const state = {
343
347
  pinnedVersion: null,
344
348
  previousVersion: null,
345
349
  startFailed: false,
350
+ // An older version setup last finished on, {version, at}, or null.
351
+ lastWorking: null,
346
352
  autoUpdate: false,
347
353
  // Offer release candidates too; off by default. A release-candidate build
348
354
  // is offered newer candidates without it.
@@ -1225,6 +1231,80 @@ async function revertUpdate() {
1225
1231
  }
1226
1232
  }
1227
1233
 
1234
+ /** Installing an older release in-app is proven only for the Windows setup and the AppImage. */
1235
+ function _canInstallOlder() {
1236
+ return process.platform === "win32" || (process.platform === "linux" && Boolean(process.env.APPIMAGE));
1237
+ }
1238
+
1239
+ /**
1240
+ * The older version setup last finished on, as {version, at}, or null. Only a
1241
+ * version that really finished setup on this PC counts. Works before init().
1242
+ */
1243
+ function lastWorkingVersion() {
1244
+ if (isDisabled() || !_canInstallOlder()) return null;
1245
+ const { version, at } = _readJsonFile(LAST_WORKING_PATH);
1246
+ if (typeof version !== "string" || typeof at !== "string" || Number.isNaN(Date.parse(at))) return null;
1247
+ return _compareVersions(version, _runningVersion()) < 0 ? { version, at } : null;
1248
+ }
1249
+
1250
+ /** Setup finished on the running version: it is the one to come back to. Throws when it can't be saved. */
1251
+ function markSetupWorked() {
1252
+ const record = { version: _runningVersion(), at: new Date().toISOString() };
1253
+ fs.mkdirSync(path.dirname(LAST_WORKING_PATH), { recursive: true });
1254
+ const tmp = `${LAST_WORKING_PATH}.${process.pid}.tmp`;
1255
+ fs.writeFileSync(tmp, JSON.stringify(record));
1256
+ fs.renameSync(tmp, LAST_WORKING_PATH);
1257
+ setState({ lastWorking: lastWorkingVersion() });
1258
+ }
1259
+
1260
+ /**
1261
+ * Go back to the version setup last finished on, pinned so the broken one
1262
+ * isn't reinstalled. A failed setup is the user's call to make, so a pin they
1263
+ * set doesn't stop it; a failed install puts that pin back.
1264
+ */
1265
+ async function revertToLastWorking() {
1266
+ const last = lastWorkingVersion();
1267
+ if (!last) {
1268
+ throw _userError(
1269
+ "noEarlier",
1270
+ { url: RELEASES_PAGE },
1271
+ `There is no earlier GAIA version to go back to on this PC. Pick one in Settings → General → Updates, or download it from ${RELEASES_PAGE}.`
1272
+ );
1273
+ }
1274
+ if (state.status === STATES.DOWNLOADING) {
1275
+ throw _userError("checkBusy", {}, "An update is already downloading — try again in a moment.");
1276
+ }
1277
+ log("info", `Setup failed on GAIA ${_runningVersion()}: going back to ${last.version}, where it last finished`);
1278
+ const tag = _tagForVersion(last.version);
1279
+ const userPin = state.pinnedVersion;
1280
+ try {
1281
+ await installVersion(tag);
1282
+ } catch (err) {
1283
+ // A refused restart leaves the pin and the download: neither may outlive it.
1284
+ if (state.pinnedVersion === tag) {
1285
+ clearPin();
1286
+ if (userPin) {
1287
+ try {
1288
+ _savePin(userPin);
1289
+ setState({ pinnedVersion: userPin });
1290
+ // clearPin() turned auto-download on and swapped to the forward feed.
1291
+ autoUpdaterRef.setFeedURL(_releaseFeed(userPin));
1292
+ _applyInstallPolicy();
1293
+ } catch (pinErr) {
1294
+ const reason = (pinErr && pinErr.message) || String(pinErr);
1295
+ log("error", `Couldn't put back the pin to ${userPin}:`, reason);
1296
+ throw _userError(
1297
+ "failedWith",
1298
+ { reason: `${err.message} The pin to ${userPin} could not be put back in ${UPDATE_CONFIG_PATH} (${reason}).` },
1299
+ `${err.message} The pin to ${userPin} could not be put back: ${reason}`
1300
+ );
1301
+ }
1302
+ }
1303
+ }
1304
+ throw err;
1305
+ }
1306
+ }
1307
+
1228
1308
  /** True for the first few launches after an update landed, the only time a failed start blames it. */
1229
1309
  function _updateIsRecent() {
1230
1310
  // An attempt from the running version is a failed install, not an update.
@@ -1668,6 +1748,14 @@ function registerIpcHandlers() {
1668
1748
  await revertUpdate();
1669
1749
  return getState();
1670
1750
  });
1751
+ ipcMain.handle("gaia:update:setup-worked", () => {
1752
+ markSetupWorked();
1753
+ return getState();
1754
+ });
1755
+ ipcMain.handle("gaia:update:revert-to-working", async () => {
1756
+ await revertToLastWorking();
1757
+ return getState();
1758
+ });
1671
1759
  ipcMain.handle("gaia:update:resume", async () => {
1672
1760
  clearPin();
1673
1761
  return getState();
@@ -1703,6 +1791,8 @@ function unregisterIpcHandlers() {
1703
1791
  "gaia:update:list-releases",
1704
1792
  "gaia:update:install-version",
1705
1793
  "gaia:update:revert",
1794
+ "gaia:update:setup-worked",
1795
+ "gaia:update:revert-to-working",
1706
1796
  "gaia:update:resume",
1707
1797
  "gaia:update:set-auto-update",
1708
1798
  "gaia:update:set-include-prereleases",
@@ -1813,6 +1903,7 @@ function init(mainWindow, options = {}) {
1813
1903
  }
1814
1904
  _readInstallOutcome();
1815
1905
  state.previousVersion = previousVersion();
1906
+ state.lastWorking = lastWorkingVersion();
1816
1907
  } catch (err) {
1817
1908
  log("error", "Failed to load electron-updater:", err && err.message);
1818
1909
  setState({
@@ -1909,6 +2000,11 @@ function _initDisabled() {
1909
2000
  state.currentVersion = electron.app.getVersion() || null;
1910
2001
  if (!ipcHandlersRegistered) {
1911
2002
  electron.ipcMain.handle("gaia:update:get-status", () => getState());
2003
+ // Still recorded, so turning updates back on knows where setup worked.
2004
+ electron.ipcMain.handle("gaia:update:setup-worked", () => {
2005
+ markSetupWorked();
2006
+ return getState();
2007
+ });
1912
2008
  ipcHandlersRegistered = true;
1913
2009
  }
1914
2010
  }
@@ -1962,6 +2058,9 @@ module.exports = {
1962
2058
  installVersion,
1963
2059
  previousVersion,
1964
2060
  revertUpdate,
2061
+ lastWorkingVersion,
2062
+ markSetupWorked,
2063
+ revertToLastWorking,
1965
2064
  reportStartFailure,
1966
2065
  clearStartFailure,
1967
2066
  clearPin,
@@ -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 };
@@ -2157,6 +2157,7 @@ module.exports = {
2157
2157
  GAIA_HOME,
2158
2158
  GAIA_VENV,
2159
2159
  GAIA_BIN,
2160
+ BUNDLED_GAIA_BIN,
2160
2161
  MIN_DISK_SPACE_BYTES,
2161
2162
 
2162
2163
  // Error
@@ -11,8 +11,16 @@
11
11
  // unrelated user process (issue #782 TOCTOU mitigation).
12
12
 
13
13
  const realFs = require("fs");
14
+ const path = require("path");
14
15
  const { spawnSync: realSpawnSync } = require("child_process");
15
16
 
17
+ // One record per running app, named for the app's pid: two copies of the app
18
+ // sharing ~/.gaia (an installed app and a dev build) must not see each other's
19
+ // live backend as an orphan (issue #7062).
20
+ const PIDFILE_DIR = "backend-pids";
21
+ // Written by versions before per-app records; read only to clean up after them.
22
+ const LEGACY_PIDFILE = "backend.pid";
23
+
16
24
  // Legitimate backend invocation is `gaia chat --ui --ui-port <port>`. Match on
17
25
  // "gaia" plus one of the backend-specific flags so unrelated Python/Node
18
26
  // processes (Jupyter, LSP, etc.) are never matched.
@@ -80,4 +88,157 @@ function isGaiaBackendProcess(pid, deps = {}) {
80
88
  return false;
81
89
  }
82
90
 
83
- module.exports = { isGaiaBackendProcess, commandLooksLikeBackend };
91
+ function pidAlive(pid) {
92
+ try {
93
+ process.kill(pid, 0);
94
+ return true;
95
+ } catch (err) {
96
+ // EPERM: it exists but belongs to someone else.
97
+ return err.code === "EPERM";
98
+ }
99
+ }
100
+
101
+ function backendRecordPath(gaiaDir, ownerPid) {
102
+ return path.join(gaiaDir, PIDFILE_DIR, `${ownerPid}.pid`);
103
+ }
104
+
105
+ /** Record that app `ownerPid` started backend `backendPid`. Returns the file written. */
106
+ function recordBackend({ gaiaDir, ownerPid, backendPid, fs = realFs }) {
107
+ const file = backendRecordPath(gaiaDir, ownerPid);
108
+ fs.mkdirSync(path.dirname(file), { recursive: true });
109
+ fs.writeFileSync(file, String(backendPid), { mode: 0o600 });
110
+ return file;
111
+ }
112
+
113
+ /** Remove app `ownerPid`'s record, but only while it still names `backendPid`. */
114
+ function forgetBackend({ gaiaDir, ownerPid, backendPid, fs = realFs }) {
115
+ const file = backendRecordPath(gaiaDir, ownerPid);
116
+ let recorded;
117
+ try {
118
+ recorded = parseInt(fs.readFileSync(file, "utf8").trim(), 10);
119
+ } catch (err) {
120
+ if (err.code === "ENOENT") return false;
121
+ throw err;
122
+ }
123
+ if (recorded !== backendPid) return false;
124
+ fs.unlinkSync(file);
125
+ return true;
126
+ }
127
+
128
+ /**
129
+ * Stop every recorded backend whose app is gone, and delete its record.
130
+ * A backend whose app is still running is left alone, record and all: it
131
+ * belongs to another copy of the app sharing this ~/.gaia.
132
+ *
133
+ * @returns {Promise<{ killed: number[], kept: number[] }>} backend pids
134
+ */
135
+ async function cleanupOrphanedBackends({
136
+ gaiaDir,
137
+ selfPid = process.pid,
138
+ killBackend,
139
+ isBackend = isGaiaBackendProcess,
140
+ isAlive = pidAlive,
141
+ fs = realFs,
142
+ logger = console,
143
+ }) {
144
+ const killed = [];
145
+ const kept = [];
146
+
147
+ async function stopIfBackend(backendPid, source) {
148
+ let confirmed = false;
149
+ try {
150
+ confirmed = isBackend(backendPid);
151
+ } catch (err) {
152
+ logger.warn(`[main] Could not verify pid ${backendPid} from ${source}: ${err.message}`);
153
+ }
154
+ if (!confirmed) {
155
+ logger.log(`[main] PID ${backendPid} from ${source} is not a GAIA backend; skipping kill`);
156
+ return;
157
+ }
158
+ try {
159
+ await killBackend(backendPid);
160
+ killed.push(backendPid);
161
+ logger.log(`[main] Stopped orphaned backend pid ${backendPid} (from ${source})`);
162
+ } catch (err) {
163
+ logger.warn(`[main] Could not stop orphaned backend pid ${backendPid}: ${err.message}`);
164
+ }
165
+ }
166
+
167
+ function readPid(file) {
168
+ return parseInt(fs.readFileSync(file, "utf8").trim(), 10);
169
+ }
170
+
171
+ function remove(file) {
172
+ try {
173
+ fs.unlinkSync(file);
174
+ } catch (err) {
175
+ if (err.code !== "ENOENT") logger.warn(`[main] Could not remove ${file}: ${err.message}`);
176
+ }
177
+ }
178
+
179
+ const legacy = path.join(gaiaDir, LEGACY_PIDFILE);
180
+ if (fs.existsSync(legacy)) {
181
+ try {
182
+ const backendPid = readPid(legacy);
183
+ if (!Number.isNaN(backendPid)) await stopIfBackend(backendPid, LEGACY_PIDFILE);
184
+ } catch (err) {
185
+ logger.warn(`[main] Failed reading ${legacy}: ${err.message}`);
186
+ }
187
+ remove(legacy);
188
+ }
189
+
190
+ const dir = path.join(gaiaDir, PIDFILE_DIR);
191
+ let names = [];
192
+ try {
193
+ names = fs.readdirSync(dir);
194
+ } catch (err) {
195
+ if (err.code !== "ENOENT") logger.warn(`[main] Could not list ${dir}: ${err.message}`);
196
+ }
197
+ for (const name of names) {
198
+ const m = /^(\d+)\.pid$/.exec(name);
199
+ if (!m) continue;
200
+ const ownerPid = Number(m[1]);
201
+ const file = path.join(dir, name);
202
+ let backendPid;
203
+ try {
204
+ backendPid = readPid(file);
205
+ } catch (err) {
206
+ logger.warn(`[main] Failed reading ${file}: ${err.message}`);
207
+ continue;
208
+ }
209
+ if (ownerPid !== selfPid && isAlive(ownerPid)) {
210
+ // A record whose backend is gone is stale, even if its app's pid is now
211
+ // someone else's; it can never protect a live backend, so drop it.
212
+ let stale = false;
213
+ if (!Number.isNaN(backendPid)) {
214
+ try {
215
+ stale = !isBackend(backendPid);
216
+ } catch (err) {
217
+ logger.warn(`[main] Could not verify pid ${backendPid} from ${PIDFILE_DIR}/${name}: ${err.message}`);
218
+ }
219
+ }
220
+ if (stale) {
221
+ logger.log(`[main] Backend pid ${backendPid} of app pid ${ownerPid} is gone; removing its record`);
222
+ remove(file);
223
+ continue;
224
+ }
225
+ if (!Number.isNaN(backendPid)) kept.push(backendPid);
226
+ logger.log(`[main] Backend pid ${backendPid} belongs to running GAIA app pid ${ownerPid}; leaving it`);
227
+ continue;
228
+ }
229
+ if (!Number.isNaN(backendPid)) await stopIfBackend(backendPid, `${PIDFILE_DIR}/${name}`);
230
+ remove(file);
231
+ }
232
+ return { killed, kept };
233
+ }
234
+
235
+ module.exports = {
236
+ isGaiaBackendProcess,
237
+ commandLooksLikeBackend,
238
+ cleanupOrphanedBackends,
239
+ recordBackend,
240
+ forgetBackend,
241
+ backendRecordPath,
242
+ PIDFILE_DIR,
243
+ LEGACY_PIDFILE,
244
+ };
@@ -2,9 +2,10 @@
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
- * user's Restart GAIA (restartNow). No Electron imports, so it unit-tests.
7
+ * user's Restart GAIA (restartNow), which also restarts a backend still
8
+ * reported running but hung. No Electron imports, so it unit-tests.
8
9
  *
9
10
  * State, as sent to the renderer:
10
11
  * status "running" | "restarting" | "stopped"
@@ -26,7 +27,8 @@ const DEFAULTS = Object.freeze({
26
27
 
27
28
  /**
28
29
  * @param {object} deps
29
- * @param {() => Promise<{port: number}>} deps.start spawns the backend and resolves once it answers
30
+ * @param {() => Promise<{port: number}>} deps.start spawns the backend and resolves once it answers;
31
+ * it rejects with an error carrying `terminal: true` when no retry can succeed
30
32
  * @param {(state: object) => void} deps.onState called with every new state
31
33
  * @param {(state: object) => void} [deps.onStopped] called once each time restarts run out
32
34
  */
@@ -74,12 +76,18 @@ function createBackendSupervisor({
74
76
  ({ port }) => {
75
77
  starting = false;
76
78
  if (stopped) return;
77
- emit({ status: "running", port, since: null, attempt: 0, lastError: null });
79
+ emit({ status: "running", port, since: null, attempt: 0, lastExit: null, lastError: null });
78
80
  },
79
81
  (err) => {
80
82
  starting = false;
81
83
  if (stopped) return;
82
- schedule({ lastError: err && err.message ? err.message : String(err) });
84
+ const lastError = err && err.message ? err.message : String(err);
85
+ // A retry can't fix it (the program is missing): stop now, with no crash dialog.
86
+ if (err && err.terminal) {
87
+ emit({ status: "stopped", nextAttemptAt: null, lastError });
88
+ return;
89
+ }
90
+ schedule({ lastError });
83
91
  }
84
92
  );
85
93
  }
@@ -105,7 +113,13 @@ function createBackendSupervisor({
105
113
  return {
106
114
  /** The backend is up on `port` (the first start, outside the supervisor). */
107
115
  running(port) {
108
- 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
+ },
118
+
119
+ /** No backend could be started at all (its program is missing): wait for Restart GAIA. */
120
+ failedToStart(error) {
121
+ if (stopped) return;
122
+ emit({ status: "stopped", port: null, since: now(), attempt: 0, nextAttemptAt: null, lastError: error });
109
123
  },
110
124
 
111
125
  /** The backend exited on its own. Returns what happens next. */
@@ -121,7 +135,17 @@ function createBackendSupervisor({
121
135
  return schedule({ lastExit: { code, signal } });
122
136
  },
123
137
 
124
- /** The user's Restart GAIA: start now, with a fresh budget. */
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
+
146
+ /** The user's Restart GAIA: start now, with a fresh budget. Also restarts
147
+ * a backend still reported "running": that is a hung backend the startup
148
+ * screen offers Restart for, and start() stops the old process first. */
125
149
  restartNow() {
126
150
  if (stopped || starting) return;
127
151
  if (timer) {
@@ -129,8 +153,10 @@ function createBackendSupervisor({
129
153
  timer = null;
130
154
  }
131
155
  history = [];
132
- if (state.status === "running") return;
133
- emit({ status: "restarting", attempt: 1 });
156
+ // A restart from running starts a new outage: stamp it so the banner's
157
+ // timer counts from here, as the crash path does. From stopped, the
158
+ // outage began when the backend gave up, so keep that time.
159
+ emit({ status: "restarting", attempt: 1, ...(state.status === "running" ? { since: now() } : {}) });
134
160
  attemptStart();
135
161
  },
136
162
 
@@ -14,6 +14,10 @@
14
14
  * A ledger file records each server's pids and command lines, so the next
15
15
  * launch can stop servers a crash left behind. It only ever signals a pid it
16
16
  * recorded whose command line still matches.
17
+ *
18
+ * A server must listen only on loopback. Once its port answers, the
19
+ * addresses it is bound to are read from the OS; one bound to every interface
20
+ * or to a network address is stopped with an error saying how to bind it.
17
21
  */
18
22
 
19
23
  "use strict";
@@ -24,6 +28,7 @@ const net = require("net");
24
28
  const path = require("path");
25
29
  const { BridgeError } = require("./bridge-error.cjs");
26
30
  const { descendantsFromTable, killProcessTree, listProcesses } = require("../process-tree.cjs");
31
+ const { isLoopback, listeningAddresses } = require("./listen-addresses.cjs");
27
32
 
28
33
  /** @typedef {import("./contract").DevServerSpec} DevServerSpec */
29
34
  /** @typedef {import("./contract").DevServerState} DevServerState */
@@ -49,6 +54,10 @@ const LINE_CHARS = 500;
49
54
  const PROBE_EVERY_MS = 100;
50
55
  const PROBE_TIMEOUT_MS = 400;
51
56
  const REAP_GRACE_MS = 3000;
57
+ const LOOPBACK_HINT =
58
+ 'Start it bound to 127.0.0.1: in launch.json\'s runtimeArgs add "--bind 127.0.0.1" for python -m http.server, ' +
59
+ '"--host 127.0.0.1" for Vite or webpack serve, "--hostname 127.0.0.1" for Next.js, "-a 127.0.0.1" for http-server, ' +
60
+ 'or "--listen tcp://127.0.0.1:<port>" for serve; for an npm script, put the flag in package.json\'s script.';
52
61
  const ERROR_LINE = /\berror\b|\bfailed\b|\bexception\b|\bfatal\b|\bpanic\b|ERR!/i;
53
62
 
54
63
  function envNameAllowed(name) {
@@ -56,6 +65,7 @@ function envNameAllowed(name) {
56
65
  }
57
66
 
58
67
  /**
68
+ * HOST=127.0.0.1 is the loopback bind for dev servers that read it; launch.json may set another loopback HOST.
59
69
  * @param {DevServerSpec} spec @param {NodeJS.ProcessEnv} from
60
70
  * @param {string | null} searchPath The backend's login-shell PATH; an app opened from the Dock has only launchd's.
61
71
  */
@@ -63,7 +73,7 @@ function childEnv(spec, from, searchPath = null) {
63
73
  const env = {};
64
74
  for (const name of INHERITED_ENV) if (from[name] !== undefined) env[name] = from[name];
65
75
  if (searchPath) env.PATH = searchPath;
66
- return { ...env, ...spec.env };
76
+ return { ...env, HOST: "127.0.0.1", ...spec.env };
67
77
  }
68
78
 
69
79
  /** True when something accepts a TCP connection on the port, over IPv4 or IPv6 loopback. */
@@ -148,6 +158,7 @@ class DevServerSupervisor {
148
158
  * spawn?: typeof childProcess.spawn,
149
159
  * listProcesses?: typeof listProcesses,
150
160
  * killTree?: typeof killProcessTree,
161
+ * listeningAddresses?: typeof listeningAddresses,
151
162
  * reapGraceMs?: number,
152
163
  * logger?: { log: Function, error: Function },
153
164
  * }} deps
@@ -158,6 +169,7 @@ class DevServerSupervisor {
158
169
  spawn: childProcess.spawn,
159
170
  listProcesses,
160
171
  killTree: killProcessTree,
172
+ listeningAddresses,
161
173
  reapGraceMs: REAP_GRACE_MS,
162
174
  logger: console,
163
175
  ...deps,
@@ -427,10 +439,41 @@ class DevServerSupervisor {
427
439
  }
428
440
  await new Promise((r) => setTimeout(r, PROBE_EVERY_MS));
429
441
  }
442
+ await this.requireLoopbackOnly(entry);
430
443
  entry.status = "ready";
431
444
  this.deps.onChange();
432
445
  }
433
446
 
447
+ /** Stop a server anything off this computer could reach, or whose binding can't be read. */
448
+ async requireLoopbackOnly(entry) {
449
+ let addresses;
450
+ try {
451
+ addresses = await this.deps.listeningAddresses(entry.spec.port);
452
+ } catch (err) {
453
+ await this.halt(entry);
454
+ throw this.notLoopback(entry, `answered, but GAIA could not read which network addresses it listens on (${err.message}), so it stopped it rather than risk exposing it.`, []);
455
+ }
456
+ const open = addresses.filter((a) => !isLoopback(a));
457
+ if (addresses.length > 0 && open.length === 0) return;
458
+ await this.halt(entry);
459
+ if (addresses.length === 0) {
460
+ throw this.notLoopback(entry, "answered, but GAIA could not see which address it listens on, so it stopped it rather than risk exposing it.", []);
461
+ }
462
+ const everywhere = open.some((a) => a === "*" || a === "0.0.0.0" || a === "::");
463
+ const where = everywhere ? "all network interfaces" : `the network address ${open.join(", ")}`;
464
+ throw this.notLoopback(entry, `listened on ${where}, so other computers on the network could reach it; GAIA stopped it.`, open);
465
+ }
466
+
467
+ notLoopback(entry, what, addresses) {
468
+ const { spec } = entry;
469
+ this.deps.logger.error(`[dev-servers] Stopped "${spec.name}" on port ${spec.port}: not bound to loopback only (${addresses.join(", ") || "binding unknown"}).`);
470
+ return new BridgeError("dev_server_failed", `Dev server "${spec.name}" (${spec.argv.join(" ")}) on port ${spec.port} ${what} ${LOOPBACK_HINT}`, {
471
+ exitCode: null,
472
+ lines: [],
473
+ addresses,
474
+ });
475
+ }
476
+
434
477
  failed(entry, what) {
435
478
  const { spec } = entry;
436
479
  const lines = readLines(entry.logFile).slice(-FAIL_LINES);