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

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 (32) hide show
  1. package/dist/assets/AdvancedSettings-DFPlX5A7.js +1 -0
  2. package/dist/assets/AutomationsSettings-BKuzxL5F.js +1 -0
  3. package/dist/assets/ConnectorsPane-DLSjsjK9.js +1 -0
  4. package/dist/assets/DocumentLibrary-7V_F8HCS.js +5 -0
  5. package/dist/assets/FileBrowser-qHRJyIqQ.js +4 -0
  6. package/dist/assets/MemoryDashboard-BtwW3P2t.js +1 -0
  7. package/dist/assets/MessagingSettings-DdXCBqWQ.js +1 -0
  8. package/dist/assets/MobileAccessModal-CDJUUka1.js +2 -0
  9. package/dist/assets/ScheduleManager-C-yl3LIj.js +1 -0
  10. package/dist/assets/index-DG7wkQw4.css +1 -0
  11. package/dist/assets/index-LRcMky7O.js +222 -0
  12. package/dist/assets/useFocusTrap-CdA6vhPR.js +6 -0
  13. package/dist/index.html +3 -3
  14. package/dist/sw.js +1 -1
  15. package/main.cjs +31 -65
  16. package/package.json +1 -1
  17. package/preload.cjs +6 -0
  18. package/services/auto-updater.cjs +99 -0
  19. package/services/backend-orphan.cjs +162 -1
  20. package/dist/assets/AdvancedSettings-DHERtrno.js +0 -1
  21. package/dist/assets/AutomationsSettings-4FWcRau9.js +0 -1
  22. package/dist/assets/ConnectorsPane-Dkat1zLC.js +0 -1
  23. package/dist/assets/DocumentLibrary-Dll55N7l.js +0 -5
  24. package/dist/assets/FileBrowser-wFHqH6K_.js +0 -4
  25. package/dist/assets/MemoryDashboard-BuUBoNq8.js +0 -1
  26. package/dist/assets/MessagingSettings-DomiT2rX.js +0 -1
  27. package/dist/assets/MobileAccessModal-B2gaE8nk.js +0 -2
  28. package/dist/assets/ScheduleManager-8UE81KlQ.js +0 -1
  29. package/dist/assets/index-BiETDNik.css +0 -1
  30. package/dist/assets/index-HCZ86cyP.js +0 -220
  31. package/dist/assets/useFocusTrap-BFi0chLf.js +0 -6
  32. package/dist/assets/zap-DjkIffnX.js +0 -1
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-HCZ86cyP.js"></script>
29
+ <script type="module" crossorigin src="./assets/index-LRcMky7O.js"></script>
30
30
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
31
- <link rel="modulepreload" crossorigin href="./assets/useFocusTrap-BFi0chLf.js">
32
- <link rel="stylesheet" crossorigin href="./assets/index-BiETDNik.css">
31
+ <link rel="modulepreload" crossorigin href="./assets/useFocusTrap-CdA6vhPR.js">
32
+ <link rel="stylesheet" crossorigin href="./assets/index-DG7wkQw4.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.0rc2-0aaf94c22e3f4d41';
12
+ const CACHE_NAME = CACHE_PREFIX + '0.27.0rc5-8a2651b6eeb28520';
13
13
  const ASSETS_PATH = new URL('assets/', self.registration.scope).pathname;
14
14
 
15
15
  self.addEventListener('install', () => {
package/main.cjs CHANGED
@@ -105,7 +105,11 @@ const AgentProcessManager = require("./services/agent-process-manager.cjs");
105
105
  const NotificationService = require("./services/notification-service.cjs");
106
106
  const KeepAwake = require("./services/keep-awake.cjs");
107
107
  const PortManager = require("./services/port-manager.cjs");
108
- const { isGaiaBackendProcess } = require("./services/backend-orphan.cjs");
108
+ const {
109
+ cleanupOrphanedBackends,
110
+ forgetBackend,
111
+ recordBackend,
112
+ } = require("./services/backend-orphan.cjs");
109
113
  const { showBackendCrashDialog } = require("./services/backend-crash-dialog.cjs");
110
114
  const { showRendererGoneDialog } = require("./services/renderer-gone-dialog.cjs");
111
115
  const { createBackendSupervisor } = require("./services/backend-supervisor.cjs");
@@ -320,54 +324,25 @@ function quitStarted() {
320
324
  // ── Backend Process ────────────────────────────────────────────────────────
321
325
 
322
326
  /**
323
- * Terminate a backend left running from a previous launch.
327
+ * Terminate backends left running by a previous launch.
324
328
  *
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.
329
+ * The desktop app may crash, leaving an orphaned `gaia chat --ui` process. On
330
+ * Windows that process keeps an open handle on `gaia.exe`, so the next
331
+ * upgrade's `uv pip install --refresh` fails with `os error 32` (file in use)
332
+ * — issue #1388. We MUST run this BEFORE the installer (`engineInstall.run()`),
333
+ * not just before spawning the new backend, so the executable can be replaced.
331
334
  *
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.
335
+ * Each app records its backend under ~/.gaia/backend-pids/<app pid>.pid. Only
336
+ * backends whose app is gone are stopped, and only once verified to be a GAIA
337
+ * backend (issue #782): another copy of the app sharing ~/.gaia keeps its own
338
+ * (issue #7062).
336
339
  */
337
340
  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
- }
352
-
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
- }
341
+ await cleanupOrphanedBackends({
342
+ gaiaDir: _GAIA_DIR,
343
+ killBackend: (pid) => portManager.killBackend(pid),
344
+ logger: console,
345
+ });
371
346
  }
372
347
 
373
348
  /**
@@ -402,8 +377,7 @@ async function startBackend() {
402
377
  }
403
378
  healthCheckUrl = `http://localhost:${backendPort}/api/health`;
404
379
  // 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.
380
+ // on this path. A no-op once earlier startup removed the orphans' records.
407
381
  // Dev QA mode leaves it alone: it belongs to the installed app's backend.
408
382
  if (!devQa) await cleanupOrphanedBackend();
409
383
 
@@ -465,15 +439,12 @@ async function startBackend() {
465
439
  console.error("Failed to start backend:", err.message);
466
440
  });
467
441
 
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.
442
+ // Record this backend so a later launch can stop it if this app dies
443
+ // without stopping it. The record is removed when the child exits.
471
444
  if (!devQa) {
472
445
  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})`);
446
+ const file = recordBackend({ gaiaDir: _GAIA_DIR, ownerPid: process.pid, backendPid: child.pid });
447
+ console.log(`[main] Wrote backend pidfile ${file} (pid=${child.pid})`);
477
448
  } catch (err) {
478
449
  console.warn(`[main] Could not write backend pidfile: ${err.message}`);
479
450
  }
@@ -491,18 +462,13 @@ async function startBackend() {
491
462
  // Once restarts run out, the supervisor's onStopped shows the crash dialog.
492
463
  if (crashed) backendSupervisor.crashed({ code, signal });
493
464
 
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
- }
465
+ // Remove this app's record, unless a newer backend already replaced it.
466
+ if (!devQa) {
467
+ try {
468
+ forgetBackend({ gaiaDir: _GAIA_DIR, ownerPid: process.pid, backendPid: child.pid });
469
+ } catch (err) {
470
+ console.warn(`[main] Failed to remove backend pidfile: ${err.message}`);
502
471
  }
503
- } catch (err) {
504
- // Non-fatal — just log and continue.
505
- console.warn(`[main] Failed to remove backend pidfile: ${err.message}`);
506
472
  }
507
473
  });
508
474
 
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.5",
4
4
  "type": "module",
5
5
  "productName": "GAIA Agent UI",
6
6
  "desktopName": "gaia-desktop.desktop",
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.
@@ -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,
@@ -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
+ };
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{Bt as t,En as n,Gt as r,L as i,Lt as a,Nn as o,Nt as s,Tn as c,Ut as l,c as u,et as d,ii as f,l as p,on as m,s as h,u as g,ui as _,y as v}from"./useFocusTrap-BFi0chLf.js";import{Et as y,Kt as b,Ot as x,Rt as S,Tt as C,c as w,d as T,dn as E,et as D,f as O,g as k,gn as A,h as j,i as M,l as N,p as P,u as ee,un as F,v as te,wt as I,xt as ne}from"./index-HCZ86cyP.js";var L=e(_(),1);function re(){let e=h(),t=v(e=>e.runSetupAgain),n=v(e=>e.closeSettings),[r,i]=(0,L.useState)(null),[a,o]=(0,L.useState)(null),[l,d]=(0,L.useState)(``),[f,m]=(0,L.useState)(``),[_,y]=(0,L.useState)(!1),[x,S]=(0,L.useState)(null),[C,w]=(0,L.useState)(!1);(0,L.useEffect)(()=>{s().then(e=>{i(e),d(e.saved_base_url??e.base_url??``)}).catch(e=>o(e instanceof Error?e.message:String(e)))},[]);let T=(0,L.useCallback)(async e=>{y(!0),S(null);try{let r=await c(e);i(r),m(``),w(!1),r.mode===`gaia`&&!r.gaia_installed&&(n(),t(!0))}catch(e){w(j(e)),S(e instanceof Error?e.message:String(e))}finally{y(!1)}},[n,t]),E=()=>void T({mode:`external`,base_url:l.trim(),api_key:f.trim()||void 0});if(a)return g(`section`,{className:`settings-section`,children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),g(`div`,{className:`model-warning`,role:`alert`,children:[p(F,{size:14}),g(`div`,{className:`model-warning-content`,children:[p(`strong`,{children:e(`settings.server.readFailed`)}),p(`p`,{children:a})]})]})]});if(!r)return null;let D=r.mode===`external`,O=r.source===`env`;return g(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),p(`p`,{className:`model-override-desc`,role:`status`,children:O?e(`settings.server.usesEnv`,{url:r.base_url??``}):D?e(`settings.server.usesYours`,{url:r.base_url??``}):e(`settings.server.usesOwn`)}),!O&&r.env_url_ignored&&p(`p`,{className:`model-status-hint`,children:e(`settings.server.envIgnored`,{url:r.env_url_ignored})}),O?p(`p`,{className:`model-status-hint`,children:e(`settings.server.envUseOwn`)}):g(u.Fragment,{children:[g(`p`,{className:`model-status-hint`,children:[e(`settings.server.useYours`),` `,p(`bdi`,{children:r.what_gaia_does})]}),g(`form`,{className:`model-input-row`,onSubmit:e=>{e.preventDefault(),E()},children:[p(`input`,{type:`text`,className:`model-input`,placeholder:`http://localhost:13305`,value:l,onChange:e=>{d(e.target.value),S(null)},disabled:_,spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":e(`settings.server.address`)}),p(`input`,{type:`password`,className:`model-input`,autoComplete:`off`,placeholder:r.api_key_stored?e.bare(`settings.server.keySaved`):e.bare(`settings.server.keyOptional`),value:f,onChange:e=>m(e.target.value),disabled:_,"aria-label":e(`settings.server.key`)}),p(`div`,{className:`model-btn-group`,children:p(`button`,{type:`submit`,className:`btn-primary`,disabled:_||!l.trim(),children:_?g(u.Fragment,{children:[p(b,{size:13,className:`btn-spinner`}),` `,e(`settings.server.checking`)]}):e(`settings.server.use`)})})]})]}),D&&p(`div`,{className:`setting-actions`,children:p(`button`,{type:`button`,className:`btn-secondary`,disabled:_,onClick:()=>void T({mode:`gaia`}),children:e(`settings.server.useOwn`)})}),x&&g(`div`,{className:`model-warning`,role:`alert`,children:[p(F,{size:14}),g(`div`,{className:`model-warning-content`,children:[p(`strong`,{children:e(C?`settings.server.needsKey`:`settings.server.notSwitched`)}),p(`p`,{children:x})]})]})]})}var R={vulkan:`Vulkan`,rocm:`ROCm`,metal:`Metal`,cpu:`CPU`,npu:`NPU`,remote:`Remote (cloud)`},z={gaia:`settings.server.ownerGaia`,user:`settings.server.ownerUser`,remote:`settings.server.ownerRemote`};function B(e){return e?R[e]??e:`unknown`}function V(e){if(!e)return`unknown`;let t=B(e.backend);return e.backend_source===`lemonade_default`?`${t} (Lemonade's default)`:t}function H(e){return e?`${Math.round(e/1024)}K tokens`:`unknown`}var U={asr:`settings.server.kind.speechRecognition`,embedding:`settings.server.kind.embedding`,image:`settings.server.kind.image`,llm:`settings.server.kind.language`,rerank:`settings.server.kind.reranker`,reranking:`settings.server.kind.reranker`,stt:`settings.server.kind.speechRecognition`,transcription:`settings.server.kind.speechRecognition`,tts:`settings.server.kind.speech`,vision:`settings.server.kind.vision`,"3d":`settings.server.kind.threeD`};function W(e,t){if(!e.model_type)return t(`settings.server.loadedModel`);let n=e.model_type.toLowerCase(),r=U[n];return r?t(r):t(`settings.server.kindOther`,{kind:`${n.charAt(0).toUpperCase()}${n.slice(1)}`})}function G(e,t){let n=[e.name?I(e.name):t.bare(`settings.server.unknownModel`),V(e)];return e.backend!==`remote`&&e.ctx_size&&n.push(H(e.ctx_size)),n.join(` · `)}function K({label:e,value:t,title:n}){return g(`div`,{className:`status-row`,children:[p(`span`,{className:`status-label`,children:e}),p(`span`,{className:`status-value model-server-value`,dir:`auto`,title:n??t,children:t})]})}function ie(){let e=h(),r=v(e=>e.openSettings),i=x(e=>e.show),[a,o]=(0,L.useState)(null),[s,c]=(0,L.useState)(null),[l,d]=(0,L.useState)(null),[f,_]=(0,L.useState)(null),[y,C]=(0,L.useState)(!1);(0,L.useEffect)(()=>{t().then(o).catch(e=>c(e instanceof Error?e.message:String(e)))},[]);let T=(0,L.useCallback)(async t=>{d(t),_(null);try{let r=await n(t);o(r),_({ok:!0,text:e(`settings.server.savedBackend`)})}catch(e){_({ok:!1,text:e instanceof Error?e.message:String(e)})}finally{d(null)}},[e]),E=a?.chat_model??null,O=(0,L.useCallback)(async()=>{if(E?.name){C(!0);try{if(!await m(E.name,E.ctx_size??void 0))return;_({ok:!0,text:e(`settings.server.reloading`,{name:E.name})})}catch(e){_({ok:!1,text:e instanceof Error?e.message:String(e)})}finally{C(!1)}}},[E,e]),k=p(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>r(`model`),children:e(`settings.server.changeModel`)}),A=g(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>i(`model_server`),children:[p(S,{size:13,"aria-hidden":`true`}),` `,e(`logs.serverLog`)]});if(s)return g(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),p(w,{message:s})]});if(!a)return g(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),p(`p`,{className:`loading-text`,children:e(`settings.server.checkingServer`)})]});if(!a.reachable)return g(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),p(w,{message:a.error??e(`settings.errors.serverDownTitle`)}),g(`div`,{className:`settings-row`,children:[k,A]})]});let j=a.available_backends??[],M=a.preferred_backend??null,N=j.map(e=>e.name);M&&!N.includes(M)&&N.push(M);let P=M??a.default_backend??null,ee=j.filter(e=>e.state===`installable`).map(e=>B(e.name)),F=!!E?.name&&E.recipe===`llamacpp`;return g(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[p(`h4`,{children:e(`settings.advanced.modelServer`)}),g(`div`,{className:`status-grid`,children:[p(K,{label:e(`settings.server.server`),value:`${z[a.owner]?e(z[a.owner]):a.owner}${a.version?` v${a.version}`:``}`}),p(K,{label:e(`settings.server.addressShort`),value:a.base_url}),p(K,{label:e(`settings.server.chatModel`),value:E?.name?I(E.name):e(`settings.advanced.noneLoaded`),title:E?.name??void 0}),E&&p(K,{label:e(`settings.server.runsOn`),value:V(E)}),E&&E.backend!==`remote`&&p(K,{label:e(`settings.advanced.context`),value:H(E.ctx_size)}),p(K,{label:e(`settings.advanced.embedding`),value:a.embedding_model?.name?`${a.embedding_model.name} · ${V(a.embedding_model)}`:e(`settings.advanced.noneLoaded`)}),(a.loaded_models??[]).map((t,n)=>p(K,{label:W(t,e),value:G(t,e),title:t.name??void 0},`${t.name??`unknown`}-${n}`))]}),a.embedding_note&&p(`p`,{className:`settings-hint`,children:p(`bdi`,{children:a.embedding_note})}),a.system_info_error&&p(`p`,{className:`settings-hint`,children:p(`bdi`,{children:a.system_info_error})}),g(`div`,{className:`settings-field model-server-backend`,children:[p(`span`,{className:`settings-label`,children:e(`settings.server.backend`)}),j.length===0&&!M?p(`span`,{className:`settings-hint`,children:e(`settings.server.noBackends`)}):g(u.Fragment,{children:[p(D,{className:`segmented`,"aria-label":e(`settings.server.backendShort`),children:N.map(e=>g(`button`,{type:`button`,role:`radio`,"aria-checked":P===e,className:P===e?`is-active`:``,disabled:l!==null,onClick:()=>{e!==P&&T(e)},children:[l===e?p(b,{size:12,className:`spin`}):null,B(e)]},e))}),g(`span`,{className:`settings-hint`,children:[e(`settings.server.backendHint`),ee.length>0&&` ${e(`settings.server.installable`,{names:ee.join(`, `)})}`]})]}),f?.ok&&p(`p`,{className:`settings-ok`,role:`status`,children:f.text}),f&&!f.ok&&p(w,{message:f.text})]}),g(`div`,{className:`settings-row`,children:[k,A,F&&g(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>void O(),disabled:y,children:[y?p(b,{size:13,className:`spin`}):null,e(`settings.server.reload`)]})]})]})}function ae(e,t){return!e||!t||t.found?null:{kind:t.checked?`unlisted`:`unchecked`,id:e}}function q(){let e=h(),[t,n]=(0,L.useState)(null),[s,c]=(0,L.useState)(!0),[m,_]=(0,L.useState)([]),[v,x]=(0,L.useState)(``),[S,D]=(0,L.useState)(``),[k,j]=(0,L.useState)(!1),[I,R]=(0,L.useState)(!1),[z,B]=(0,L.useState)(null),[V,H]=(0,L.useState)(null),[U,W]=(0,L.useState)(!1),G=(0,L.useRef)(null),[K,q]=(0,L.useState)(!1),[J,le]=(0,L.useState)(!1),[ue,de]=(0,L.useState)(!1),[fe,pe]=(0,L.useState)(null);(0,L.useEffect)(()=>{f.system.info(`Checking system status...`);let e=f.system.time();r().then(t=>{n(t),f.system.timed(`System status received`,e,{lemonade:t.lemonade_running?`running`:`stopped`,model:t.model_loaded||`none`,embedding:t.embedding_model_loaded?`yes`:`no`,disk:`${t.disk_space_gb}GB free`,memory:t.memory_available_gb==null?`unknown`:`${t.memory_available_gb}GB available`}),t.lemonade_running||f.system.warn(`Lemonade Server is NOT running.`)}).catch(e=>{f.system.error(`Failed to get system status`,e),n(null)}).finally(()=>c(!1)),a().then(e=>_(e.servers)).catch(()=>{}),l().then(e=>{let t=e.custom_model??``;x(t),D(t),H(ae(t,e.model_status)),q(e.dynamic_tools),le(e.dynamic_tools_locked)}).catch(e=>{f.system.error(`Failed to load settings`,e)}).finally(()=>j(!0))},[]),(0,L.useEffect)(()=>()=>{G.current&&clearTimeout(G.current)},[]);let me=(0,L.useCallback)(async()=>{let t=v.trim(),i=t.length>0?t:``,a=y.getState().active?.model;R(!0),B(null),H(null),W(!1);try{f.system.info(`Saving custom_model override`,{custom_model:i});let e=await o({custom_model:i}),t=e.custom_model??``;x(t),D(t),C(a),r().then(n).catch(e=>f.system.error(`Failed to get system status`,e)),H(ae(t,e.model_status)),W(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>W(!1),2200)}catch(t){f.system.error(`Failed to save custom_model`,t);let n=t instanceof d&&t.httpStatus===422&&t.fields.includes(`custom_model`);B(n?e(`settings.advanced.customModelInvalid`):t instanceof Error?t.message:String(t))}finally{R(!1)}},[v,e]),he=(0,L.useCallback)(async()=>{if(J||ue)return;let e=K,t=!e;q(t),de(!0),pe(null);try{f.system.info(`Saving dynamic_tools setting`,{dynamic_tools:t});let e=await o({dynamic_tools:t});q(e.dynamic_tools),le(e.dynamic_tools_locked)}catch(t){let n=t instanceof Error?t.message:String(t);f.system.error(`Failed to save dynamic_tools`,t),q(e),pe(n)}finally{de(!1)}},[K,J,ue]),ge=v.trim()!==S.trim(),X=t?t.default_model_name:ne,{isLoadingModel:_e,isDownloadingModel:Z,downloadError:Q,loadModel:ve,downloadModel:ye}=M(X??void 0),$=!!t?.default_model_is_cloud,be=!$&&!!(t?.lemonade_running&&t.model_loaded&&t.expected_model_loaded===!1&&t.model_downloaded!==!1),xe=!$&&!!(t?.lemonade_running&&t.model_loaded&&t.context_size_sufficient===!1),Se=!$&&!(!t?.lemonade_running||t.model_loaded||t.model_downloaded!==!1),Ce=(be||xe)&&X!==null,we=m.some(e=>!e.connected);return g(`div`,{className:`settings-pane`,children:[p(`h2`,{className:`settings-pane-title`,children:e(`settings.section.advanced`)}),p(`section`,{className:`settings-card`,"aria-label":e(`settings.advanced.status`),children:s?p(`p`,{className:`loading-text`,children:e(`settings.advanced.checking`)}):t?g(u.Fragment,{children:[g(`div`,{className:`status-grid`,children:[p(Y,{label:e(`settings.advanced.modelServer`),value:t.lemonade_running?t.lemonade_version?e(`settings.advanced.runningAt`,{version:t.lemonade_version}):e(`settings.advanced.running`):T(t)?e(`settings.advanced.notInstalled`):t.lemonade_error?e(`settings.advanced.unavailable`):e(`settings.advanced.notRunning`),ok:t.lemonade_running,hint:t.lemonade_running?void 0:T(t)?e(`settings.advanced.notInstalledHint`):t.lemonade_error?e(`settings.advanced.queryFailed`,{reason:t.lemonade_error}):t.start_instruction&&!ee(t.start_instruction)?O(e,t.start_instruction)??void 0:e(`settings.advanced.notRunningHint`)}),T(t)&&p(N,{className:`btn-primary`}),p(Y,{label:e(`settings.section.model`),value:t.model_loaded||e(`settings.advanced.noneLoaded`),ok:!!t.model_loaded&&($||t.expected_model_loaded!==!1),hint:t.model_loaded?!$&&t.expected_model_loaded===!1?e(`settings.advanced.expected`,{name:X??``}):void 0:e(t.lemonade_running?`settings.advanced.loadsFirst`:`settings.advanced.loadsWhenBack`)}),p(Y,{label:e(`settings.advanced.disk`),value:g(`bdi`,{dir:`ltr`,children:[t.disk_space_gb,` GB`]}),ok:t.disk_space_gb>5,hint:!t.model_loaded&&t.disk_space_gb<30?e(`settings.advanced.diskLow`,{need:`6 GB`,size:`${t.disk_space_gb} GB`}):void 0})]}),Se&&g(`div`,{className:`model-action-row model-action-row--download`,children:[g(`div`,{className:`model-action-info`,children:[p(`span`,{className:`model-action-label`,children:e(`settings.advanced.notDownloaded`)}),p(`span`,{className:`model-action-desc`,children:e(`settings.advanced.notDownloadedHint`,{name:X??``,need:`6 GB`})})]}),p(`button`,{className:`btn-primary`,onClick:()=>ye(!1,void 0,!t.model_loaded),disabled:Z,children:Z?g(u.Fragment,{children:[p(b,{size:13,className:`btn-spinner`}),` `,e(`settings.advanced.downloading`)]}):e(`settings.model.download`)})]}),Se&&Q&&p(w,{message:Q}),Ce&&g(`div`,{className:`model-action-row model-action-row--load`,children:[g(`div`,{className:`model-action-info`,children:[p(`span`,{className:`model-action-label`,children:e(be?`settings.advanced.wrongModel`:`settings.advanced.smallContext`)}),p(`span`,{className:`model-action-desc`,children:e(`settings.advanced.loadHint`,{name:X??``})})]}),p(`button`,{className:`btn-primary`,onClick:()=>ve(),disabled:_e,children:_e?g(u.Fragment,{children:[p(b,{size:13,className:`btn-spinner`}),` `,e(`settings.advanced.loading`)]}):e(`settings.advanced.load`)})]}),g(`details`,{className:`settings-more`,children:[g(`summary`,{children:[p(A,{size:13,className:`settings-disclosure-chevron`,"aria-hidden":`true`}),` `,e(`settings.advanced.details`)]}),g(`div`,{className:`status-grid`,children:[t.model_size_gb!=null&&p(Y,{label:e(`settings.advanced.modelSize`),value:g(`bdi`,{dir:`ltr`,children:[t.model_size_gb,` GB`]}),ok:!0}),t.model_device&&!$&&p(Y,{label:e(`settings.advanced.device`),value:t.model_device.toUpperCase(),ok:t.model_device!==`cpu`}),t.model_context_size!=null&&p(Y,{label:e(`settings.advanced.context`),value:e(`settings.ctx.tokens`,{size:`${(t.model_context_size/1024).toFixed(0)}K`}),ok:t.context_size_sufficient}),t.model_labels&&t.model_labels.length>0&&p(Y,{label:e(`settings.advanced.capabilities`),value:ce(e,t.model_labels),ok:!0}),p(Y,{label:e(`settings.advanced.embedding`),value:t.embedding_model_loaded?e(`settings.advanced.available`):e(`settings.advanced.notLoaded`),ok:t.embedding_model_loaded}),t.gpu_name&&p(Y,{label:`GPU`,value:p(`bdi`,{children:`${t.gpu_name}${t.gpu_vram_gb?` (${te(t.gpu_vram_gb)})`:``}`}),ok:!0}),p(Y,{label:e(`settings.advanced.memory`),value:t.memory_available_gb==null?e(`settings.advanced.unknown`):g(`bdi`,{dir:`ltr`,children:[t.memory_available_gb,` GB`]}),ok:t.memory_available_gb!=null&&t.memory_available_gb>2}),t.processor_name&&p(Y,{label:e(`settings.advanced.processor`),value:p(`bdi`,{children:t.processor_name}),ok:!0})]}),t.lemonade_running&&X!==null&&!$&&g(`div`,{className:`force-redownload-row`,children:[p(`span`,{className:`force-redownload-label`,children:e(`settings.advanced.corrupted`)}),p(`button`,{className:`btn-secondary`,onClick:()=>ye(!0,void 0,!t.model_loaded),disabled:Z,children:Z?g(u.Fragment,{children:[p(b,{size:12,className:`btn-spinner`}),` `,e(`settings.advanced.downloading`)]}):e(`settings.advanced.redownload`)})]}),!Se&&Q&&p(w,{message:Q})]})]}):p(`div`,{className:`status-error`,children:p(`p`,{children:e(`settings.advanced.unreachable`)})})}),p(oe,{}),g(P,{title:e(`settings.advanced.serverTitle`),hint:e(`settings.advanced.serverHint`),targetId:`model-server`,children:[p(ie,{}),p(re,{})]}),g(P,{title:e(`settings.advanced.customTitle`),hint:S?i(S,`ltr`):e(`settings.advanced.customHint`),targetId:`custom-model`,children:[p(`p`,{className:`model-override-desc`,children:e(`settings.advanced.customDesc`)}),g(`div`,{className:`model-input-row`,children:[p(`input`,{type:`text`,className:`model-input${S?` has-override`:``}`,placeholder:e.bare(`settings.advanced.customPlaceholder`),value:v,dir:v?`ltr`:void 0,onChange:e=>{x(e.target.value),B(null),H(null),W(!1)},onKeyDown:e=>{e.key===`Enter`&&!I&&ge&&k&&(e.preventDefault(),me())},disabled:!k||I,spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":e(`settings.advanced.customAria`)}),p(`div`,{className:`model-btn-group`,children:p(`button`,{className:`btn-primary`,onClick:()=>{me()},disabled:!k||I||!ge&&!U,"aria-label":e(`settings.advanced.customSave`),children:I?g(u.Fragment,{children:[p(b,{size:13,className:`btn-spinner`}),` `,e(`settings.models.applying`)]}):U?g(u.Fragment,{children:[p(E,{size:13}),` `,e(`settings.advanced.saved`)]}):e(`settings.advanced.save`)})})]}),p(`p`,{className:`model-status-hint`,children:e(`settings.advanced.customIds`)}),z&&p(se,{message:z}),V&&g(`div`,{className:`model-warning`,role:`status`,children:[p(F,{size:14}),p(`div`,{className:`model-warning-content`,children:p(`p`,{children:V.kind===`unlisted`?e(`settings.advanced.customNotListed`,{id:V.id}):e(`settings.advanced.customNotChecked`)})})]})]}),g(P,{title:e(`settings.advanced.dynamicTitle`),children:[p(`p`,{className:`model-override-desc`,children:e(`settings.advanced.dynamicDesc`)}),g(`label`,{className:`setting-row`,children:[p(`span`,{children:e(`settings.advanced.dynamicEnable`)}),g(`span`,{className:`toggle-switch`,children:[p(`input`,{type:`checkbox`,checked:K,onChange:()=>void he(),disabled:!k||ue||J,"aria-label":e(K?`settings.advanced.dynamicOff`:`settings.advanced.dynamicOn`)}),p(`span`,{className:`toggle-track`})]})]}),J&&p(`p`,{className:`model-status-hint`,children:e(`settings.advanced.dynamicLocked`)}),fe&&p(se,{message:fe})]}),m.length>0&&p(P,{title:e(`settings.advanced.mcp`),count:m.length,defaultOpen:we,children:p(`div`,{className:`status-grid`,children:m.map(t=>g(`div`,{className:`status-row`,children:[p(`bdi`,{className:`status-label`,children:t.name}),p(`div`,{className:`status-value-wrap`,children:t.connected?g(`span`,{className:`status-value ok mcp-status-connected`,children:[p(E,{size:12}),e.plural(`settings.advanced.tools`,t.tool_count)]}):g(`span`,{className:`status-value warn mcp-status-failed`,title:t.error??void 0,children:[p(F,{size:12}),e(`settings.custom.failed`)]})})]},t.name))})})]})}function oe(){let e=h(),t=x(e=>e.show);return g(`section`,{className:`settings-card`,"aria-labelledby":`settings-logs-title`,children:[p(`h3`,{className:`settings-label`,id:`settings-logs-title`,children:e(`logs.title`)}),p(`p`,{className:`settings-hint`,children:e(`logs.settingsHint`)}),p(`div`,{className:`settings-row`,children:g(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>t(`gaia`),children:[p(S,{size:13,"aria-hidden":`true`}),` `,e(`logs.view`)]})}),p(k,{})]})}function se({message:e}){let t=h();return g(`div`,{className:`model-warning`,role:`alert`,children:[p(F,{size:14}),g(`div`,{className:`model-warning-content`,children:[p(`strong`,{children:t(`settings.advanced.saveFailed`)}),p(`p`,{children:e})]})]})}var J={cloud:`settings.advanced.capability.cloud`,chat:`settings.advanced.capability.chat`,vision:`settings.advanced.capability.vision`,"tool-calling":`settings.advanced.capability.toolCalling`,reasoning:`settings.advanced.capability.reasoning`,embeddings:`settings.advanced.capability.embeddings`,reranking:`settings.advanced.capability.reranking`,coding:`settings.advanced.capability.coding`,audio:`settings.advanced.capability.audio`,image:`settings.advanced.capability.image`,tts:`settings.advanced.capability.tts`,stt:`settings.advanced.capability.stt`,transcription:`settings.advanced.capability.transcription`};function ce(e,t){return e.compose(e=>t.map(t=>J[t]?e(J[t]):t).join(e(`mem.listSeparator`)))}function Y({label:e,value:t,ok:n,hint:r}){return g(`div`,{className:`status-row${r?` status-row--has-hint`:``}`,children:[p(`span`,{className:`status-label`,children:e}),g(`div`,{className:`status-value-wrap`,children:[p(`span`,{className:`status-value ${n?`ok`:`warn`}`,children:t}),r&&p(`span`,{className:`status-hint`,children:r})]})]})}export{q as AdvancedSettings};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{I as t,c as n,et as r,l as i,r as a,rt as o,s,st as c,u as l,ui as u,y as d}from"./useFocusTrap-BFi0chLf.js";import{Kt as f,m as p}from"./index-HCZ86cyP.js";var m=e(u(),1);function h(){return c(`GET`,`/automations`)}function g(e,t){return c(`POST`,`/automations/${encodeURIComponent(e)}/${t?`pause`:`resume`}`,void 0,o)}function _(e){return c(`DELETE`,`/automations/${encodeURIComponent(e)}`,void 0,o)}function v(e){return e instanceof r?e.detail||e.message:e instanceof Error?e.message:String(e)}var y=[[`week`,604800],[`day`,86400],[`hour`,3600],[`minute`,60]];function b(e,n){let r=y.find(([,t])=>e%t===0)??y[y.length-1],i=Math.max(1,Math.round(e/r[1])),a=`schedules.span.${r[0]}.${new Intl.PluralRules(n.locale).select(i)}`;return t(a)?n.compose(e=>e(`schedules.desc.every`,{span:e(a,{n:i})})):null}function x(e,t){return new Intl.DateTimeFormat(a(t),{weekday:`short`,day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`}).format(new Date(e*1e3))}var S=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`];function C(e,t){let n=e.split(`,`).map(e=>S.indexOf(e.trim()));return n.some(e=>e<0)?e:t.compose(e=>n.length===7?e(`schedules.days.every`):n.length===5&&n.every(e=>e<5)?e(`schedules.days.weekdays`):n.length===2&&n.includes(5)&&n.includes(6)?e(`schedules.days.weekends`):n.map(t=>e(`schedules.day.${t}`)).join(e(`schedules.days.join`)))}function w(e,t){return e.heartbeat?t(`settings.automations.kind.heartbeat`):t(`settings.automations.kind.${e.kind}`)}function T({item:e,busy:t,onToggle:r,onRemove:a}){let o=s(),c=i(`bdi`,{children:x(e.next_at,o)}),u=e.every_seconds>0?b(e.every_seconds,o):null,d=e.say||e.prompt;return l(`li`,{className:`settings-card automation-card${e.paused?` is-paused`:``}`,"data-automation":e.id,children:[l(`div`,{className:`automation-head`,children:[i(`h3`,{className:`settings-label automation-name`,children:i(`bdi`,{children:e.name})}),i(`span`,{className:`automation-kind`,children:w(e,o)}),e.paused&&i(`span`,{className:`automation-paused`,children:o(`settings.automations.paused`)})]}),l(`p`,{className:`settings-hint automation-when`,children:[e.every_seconds>0?l(n.Fragment,{children:[u&&i(`span`,{children:u}),!e.paused&&l(`span`,{children:[o(`settings.automations.next`),` `,c]})]}):l(`span`,{children:[o(`settings.automations.once`),` `,c]}),e.quiet&&l(`span`,{children:[o(`settings.automations.quiet`),` `,i(`bdi`,{dir:`ltr`,children:e.quiet})]}),e.days&&l(`span`,{children:[o(`settings.automations.days`),` `,C(e.days,o)]})]}),d&&i(`p`,{className:`automation-detail`,dir:`auto`,children:i(`bdi`,{children:d})}),e.check&&l(`p`,{className:`settings-hint automation-check`,children:[o(`settings.automations.check`),` `,i(`code`,{dir:`ltr`,children:e.check})]}),e.failures>0&&i(`p`,{className:`settings-error`,role:`status`,children:o.plural(`settings.automations.failing`,e.failures)}),l(`div`,{className:`settings-row`,children:[l(`button`,{type:`button`,className:`btn-secondary`,onClick:r,disabled:t,children:[t&&i(f,{size:13,className:`spin`,"aria-hidden":`true`}),e.paused?o(`settings.automations.resume`):o(`settings.automations.pause`)]}),i(`button`,{type:`button`,className:`btn-danger`,onClick:a,disabled:t,children:o(`settings.automations.remove`)})]})]})}function E(){let e=s(),t=d(e=>e.openSettings),[r,a]=(0,m.useState)(null),[o,c]=(0,m.useState)(null),[u,y]=(0,m.useState)(null),[b,x]=(0,m.useState)(new Set),[S,C]=(0,m.useState)(null),w=(0,m.useRef)(0),E=(0,m.useCallback)(()=>{let e=++w.current;h().then(t=>{e===w.current&&(c(null),a(t))}).catch(t=>{e===w.current&&c(v(t))})},[]);(0,m.useEffect)(E,[E]);let D=async(e,t)=>{x(t=>new Set(t).add(e)),y(null);try{await t()}catch(e){y(v(e))}finally{x(t=>{let n=new Set(t);return n.delete(e),n}),E()}},O=e=>{C(null),D(e.id,()=>_(e.id))};return l(`div`,{className:`settings-pane`,children:[i(`h2`,{className:`settings-pane-title`,children:e(`settings.section.automations`)}),i(`p`,{className:`settings-pane-lede`,children:e(`settings.automations.lede`)}),o&&l(n.Fragment,{children:[i(`p`,{className:`settings-error`,role:`alert`,children:e(`settings.automations.loadFailed`,{error:o})}),i(`button`,{type:`button`,className:`btn-secondary`,onClick:E,children:e(`settings.automations.retry`)})]}),!r&&!o&&l(`p`,{className:`settings-hint`,children:[i(f,{size:13,className:`spin`}),` `,e(`settings.loading`)]}),r&&r.delivers===null&&r.automations.length>0&&i(`p`,{className:`settings-hint automation-unchecked`,children:e(`settings.automations.deliveryUnknown`)}),r&&r.delivers===!1&&r.automations.length>0&&l(`div`,{className:`settings-warning`,children:[i(`p`,{children:e(`settings.automations.noDelivery`)}),i(`button`,{type:`button`,className:`btn-secondary automation-messaging`,onClick:()=>t(`messaging`),children:e(`settings.automations.openMessaging`)})]}),u&&i(`p`,{className:`settings-error`,role:`alert`,children:u}),r&&r.automations.length===0&&i(`p`,{className:`settings-hint automation-empty`,children:e(`settings.automations.empty`)}),r&&r.automations.length>0&&i(`ul`,{className:`automation-list`,children:r.automations.map(e=>i(T,{item:e,busy:b.has(e.id),onToggle:()=>void D(e.id,()=>g(e.id,!e.paused)),onRemove:()=>C(e)},e.id))}),S&&i(p,{title:e(`settings.automations.removeTitle`,{name:S.name}),confirmLabel:e(`settings.automations.remove`),cancelLabel:e(`settings.automations.cancel`),danger:!0,onConfirm:()=>O(S),onCancel:()=>C(null),children:i(`p`,{children:e(`settings.automations.removeBody`)})})]})}export{E as AutomationsSettings};