@amd-gaia/agent-ui 0.25.4-rc.6 → 0.25.4-rc.7

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.
@@ -0,0 +1 @@
1
+ import{W as e}from"./useT-DmcuCJlO.js";var t={name:`message-square`,size:24,node:[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}]]};t.node;var n=e(t),r={name:`zap`,size:24,node:[[`path`,{d:`M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z`,key:`1v7up4`}]]};r.node;var i=e(r);export{n,i as t};
package/dist/index.html CHANGED
@@ -12,10 +12,10 @@
12
12
  <meta name="apple-mobile-web-app-capable" content="yes" />
13
13
  <meta name="apple-mobile-web-app-title" content="GAIA" />
14
14
  <title>GAIA Agent UI</title>
15
- <script type="module" crossorigin src="./assets/index-8uiHNHOH.js"></script>
15
+ <script type="module" crossorigin src="./assets/index-eGMUmm-L.js"></script>
16
16
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
17
- <link rel="modulepreload" crossorigin href="./assets/apiBase-DSN0u9ls.js">
18
- <link rel="modulepreload" crossorigin href="./assets/api-By968363.js">
17
+ <link rel="modulepreload" crossorigin href="./assets/useT-DmcuCJlO.js">
18
+ <link rel="modulepreload" crossorigin href="./assets/api-BsMIEtSA.js">
19
19
  <link rel="stylesheet" crossorigin href="./assets/index-CNhwlnjv.css">
20
20
  </head>
21
21
  <body>
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.25.4rc6-26817f7b44d5eb59';
12
+ const CACHE_NAME = CACHE_PREFIX + '0.25.4rc7-5bfd5826c9744ded';
13
13
  const ASSETS_PATH = new URL('assets/', self.registration.scope).pathname;
14
14
 
15
15
  self.addEventListener('install', () => {
package/main.cjs CHANGED
@@ -92,6 +92,7 @@ const {
92
92
  fetchWorkInProgress,
93
93
  installQuitGuard,
94
94
  QUIT,
95
+ quitOnTermSignal,
95
96
  RESTART_FOR_UPDATE,
96
97
  } = require("./services/quit-guard.cjs");
97
98
  const AgentProcessManager = require("./services/agent-process-manager.cjs");
@@ -1186,7 +1187,7 @@ app.whenReady().then(async () => {
1186
1187
  if (showingInstallScreen) {
1187
1188
  const installed = await engineInstall.run();
1188
1189
  if (!installed) {
1189
- console.log("[main] Quit while the install waited on Try again");
1190
+ console.log("[main] Quit during the backend install");
1190
1191
  return;
1191
1192
  }
1192
1193
  engineInstall.starting();
@@ -1338,11 +1339,13 @@ const quitGuard = installQuitGuard({
1338
1339
  },
1339
1340
  });
1340
1341
 
1342
+ quitOnTermSignal({ proc: process, app, guard: quitGuard });
1343
+
1341
1344
  installQuitCleanup({ app, cleanup });
1342
1345
 
1343
1346
  async function cleanup() {
1344
1347
  shutdownStarted = true;
1345
- if (engineInstall) engineInstall.stop();
1348
+ const installStopped = engineInstall ? engineInstall.stop() : null;
1346
1349
 
1347
1350
  // Phase F: tear down auto-updater timers and IPC handlers.
1348
1351
  try {
@@ -1365,9 +1368,9 @@ async function cleanup() {
1365
1368
  keepAwake = null;
1366
1369
  }
1367
1370
 
1368
- // The agents and the backend stop side by side: each waits out its own
1369
- // grace period, and in series they could overrun the quit's time limit.
1370
- await Promise.all([stopAgentsForQuit(), stopBackendForQuit()]);
1371
+ // The install, the agents and the backend stop side by side: each waits out
1372
+ // its own grace period, and in series they could overrun the quit's time limit.
1373
+ await Promise.all([installStopped, stopAgentsForQuit(), stopBackendForQuit()]);
1371
1374
 
1372
1375
  // Destroy tray icon
1373
1376
  if (trayManager) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amd-gaia/agent-ui",
3
- "version": "0.25.4-rc.6",
3
+ "version": "0.25.4-rc.7",
4
4
  "type": "module",
5
5
  "productName": "GAIA Agent UI",
6
6
  "description": "Chat with the GAIA agent - local and private by default on AMD Ryzen AI, cloud models when you choose them",
@@ -17,6 +17,7 @@
17
17
  * - installBackend(opts) → Promise<void>
18
18
  * - ensureBackend(opts) → Promise<string> (returns gaia bin path)
19
19
  * - isBackendCurrent() → boolean (nothing to install or refresh)
20
+ * - stopRunningDaemon(opts) → Promise<void> (before the venv is touched)
20
21
  * - getInstalledVersion(gaiaBin) → string | null
21
22
  * - findGaiaBin() → string | null
22
23
  * - getState() / setState() → state machine helpers
@@ -150,8 +151,16 @@ const FAILURE_REASONS = Object.freeze({
150
151
  NETWORK: "network",
151
152
  TLS: "tls",
152
153
  LOCKED: "locked",
154
+ DAEMON: "daemon",
153
155
  });
154
156
 
157
+ // `gaia daemon stop` can take about 90 s: up to 45 s for a graceful exit, then
158
+ // terminating the daemon and its agents, then up to 20 s for GAIA's Lemonade Server.
159
+ const DAEMON_STOP_TIMEOUT_MS = 120 * 1000;
160
+ /** `gaia daemon stop` exit code: the daemon stopped, GAIA's Lemonade Server did not. */
161
+ const DAEMON_STOP_LEMONADE_EXIT = 3;
162
+ const DAEMON_INSTANCE_FILE = path.join(GAIA_HOME, "host", "instance.json");
163
+
155
164
  // Stage an older installer recorded while it ran `gaia init`; the package was
156
165
  // already in place by then.
157
166
  const LEGACY_SETUP_STAGE = "gaia-init";
@@ -459,9 +468,13 @@ function findGaiaBin() {
459
468
  *
460
469
  * `onLine(line)` sees each whole stdout line as it arrives; a line it returns
461
470
  * true for is left out of the log.
471
+ *
472
+ * When `signal` aborts, the child and everything it started are stopped and
473
+ * the Promise rejects with InstallCancelled once they are gone.
462
474
  */
463
- function runCommand(cmd, args, { env, stageLabel, onLine } = {}) {
464
- return new Promise((resolve) => {
475
+ function runCommand(cmd, args, { env, stageLabel, onLine, signal, timeoutMs } = {}) {
476
+ if (signal && signal.aborted) return Promise.reject(new InstallCancelled());
477
+ return new Promise((resolve, reject) => {
465
478
  log(`$ ${cmd} ${args.join(" ")}`);
466
479
  let proc;
467
480
  try {
@@ -478,6 +491,21 @@ function runCommand(cmd, args, { env, stageLabel, onLine } = {}) {
478
491
  return;
479
492
  }
480
493
 
494
+ let stopping = false;
495
+ const onAbort = () => {
496
+ stopping = true;
497
+ stopTimer();
498
+ log(`Stopping ${cmd}: GAIA is quitting`);
499
+ require("./process-tree.cjs")
500
+ .killProcessTree(proc, { label: stageLabel || cmd, log, logError })
501
+ .then(() => reject(new InstallCancelled()), reject);
502
+ };
503
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
504
+ const finish = (result) => {
505
+ if (signal) signal.removeEventListener("abort", onAbort);
506
+ if (!stopping) resolve(result);
507
+ };
508
+
481
509
  let stdout = "";
482
510
  let stderr = "";
483
511
  let partial = "";
@@ -525,18 +553,123 @@ function runCommand(cmd, args, { env, stageLabel, onLine } = {}) {
525
553
  });
526
554
  });
527
555
 
556
+ // From `timers`, not the globals: the installer tests run this file in a bare vm context.
557
+ let timer = null;
558
+ if (timeoutMs) {
559
+ timer = require("timers").setTimeout(() => {
560
+ logError(`${cmd} ${args.join(" ")} did not finish within ${Math.round(timeoutMs / 1000)}s — ending it`);
561
+ killTree(proc);
562
+ finish({ code: null, stdout, stderr, timedOut: true });
563
+ }, timeoutMs);
564
+ }
565
+ const stopTimer = () => {
566
+ if (timer) require("timers").clearTimeout(timer);
567
+ };
568
+
528
569
  proc.on("error", (err) => {
570
+ stopTimer();
529
571
  logError(`${cmd} error: ${err.message}`);
530
- resolve({ code: -1, stdout, stderr, error: err });
572
+ finish({ code: -1, stdout, stderr, error: err });
531
573
  });
532
574
 
533
575
  proc.on("exit", (code) => {
576
+ stopTimer();
534
577
  log(` exit code: ${code}`);
535
- resolve({ code, stdout, stderr });
578
+ finish({ code, stdout, stderr });
536
579
  });
537
580
  });
538
581
  }
539
582
 
583
+ /** End `proc` and what it started: a Windows venv launcher runs Python as a child. */
584
+ function killTree(proc) {
585
+ if (IS_WINDOWS) {
586
+ const r = spawnSync("taskkill", ["/PID", String(proc.pid), "/T", "/F"], {
587
+ windowsHide: true,
588
+ timeout: 30 * 1000,
589
+ });
590
+ if (r.error || r.status !== 0) {
591
+ logError(`taskkill /PID ${proc.pid} /T /F failed: ${r.error ? r.error.message : `exit ${r.status}`}`);
592
+ }
593
+ return;
594
+ }
595
+ try {
596
+ proc.kill("SIGKILL");
597
+ } catch (err) {
598
+ logError(`Could not end pid ${proc.pid}: ${err.message}`);
599
+ }
600
+ }
601
+
602
+ /** The pid of the GAIA daemon ~/.gaia/host/instance.json records, when that process is alive. */
603
+ function liveDaemonPid() {
604
+ let pid;
605
+ try {
606
+ pid = Number(JSON.parse(fs.readFileSync(DAEMON_INSTANCE_FILE, "utf8")).pid);
607
+ } catch (err) {
608
+ if (err.code !== "ENOENT") log(`Could not read ${DAEMON_INSTANCE_FILE}: ${err.message}`);
609
+ return null;
610
+ }
611
+ if (!Number.isInteger(pid) || pid <= 0) return null;
612
+ try {
613
+ process.kill(pid, 0);
614
+ return pid;
615
+ } catch (err) {
616
+ // EPERM: the process exists but belongs to someone else.
617
+ return err.code === "EPERM" ? pid : null;
618
+ }
619
+ }
620
+
621
+ /**
622
+ * Stop the GAIA daemon (and the agents it runs) that the existing venv may be
623
+ * running, so the install doesn't trip over its open files. Throws an
624
+ * InstallError naming the daemon only when one is still alive afterwards: a
625
+ * stop that fails with no daemon running (a broken venv, say) must not block
626
+ * the reinstall that repairs it.
627
+ */
628
+ async function stopRunningDaemon({ timeoutMs = DAEMON_STOP_TIMEOUT_MS, signal } = {}) {
629
+ if (!fs.existsSync(GAIA_BIN) || !fs.existsSync(GAIA_PYTHON_BIN)) return;
630
+ const result = await runCommand(GAIA_BIN, ["daemon", "stop"], {
631
+ stageLabel: "daemon",
632
+ timeoutMs,
633
+ signal,
634
+ // gaia prints emoji, which a Windows pipe's code page can't encode.
635
+ env: { ...process.env, PYTHONIOENCODING: "utf-8" },
636
+ });
637
+ if (result.code === 0) return;
638
+ const output = `${result.stdout || ""}\n${result.stderr || ""}`;
639
+ if (result.code === 2 && /invalid choice: '?daemon'?/.test(output)) {
640
+ log("The installed GAIA predates the daemon — nothing to stop");
641
+ return;
642
+ }
643
+ const pid = liveDaemonPid();
644
+ if (pid === null) {
645
+ if (result.code === DAEMON_STOP_LEMONADE_EXIT) {
646
+ log(
647
+ "The GAIA daemon stopped, but GAIA's Lemonade Server did not (see the lines above). " +
648
+ "It lives outside the backend's files, so the install goes on."
649
+ );
650
+ } else {
651
+ log(
652
+ `gaia daemon stop ${result.timedOut ? "timed out" : `exited ${result.code}`}, ` +
653
+ "but no GAIA daemon is running — continuing"
654
+ );
655
+ }
656
+ return;
657
+ }
658
+ const why = result.timedOut
659
+ ? `did not stop within ${Math.round(timeoutMs / 1000)} seconds`
660
+ : `could not be stopped (gaia daemon stop exit ${result.code})`;
661
+ log(`To stop it by hand: ${GAIA_BIN} daemon stop`);
662
+ throw new InstallError(
663
+ `GAIA's background service (the GAIA daemon, pid ${pid}) ${why}, so its files can't be updated.`,
664
+ {
665
+ stage: STAGES.CREATE_VENV,
666
+ code: result.code,
667
+ reason: FAILURE_REASONS.DAEMON,
668
+ suggestion: `It has no window to close. Restart your PC, then try again. The log at ${LOG_FILE} has the details.`,
669
+ }
670
+ );
671
+ }
672
+
540
673
  /**
541
674
  * Detect the Windows "file in use" signature in command output. An upgrade's
542
675
  * `uv pip install --refresh` can't replace gaia.exe while a previous GAIA
@@ -1053,6 +1186,14 @@ class InstallError extends Error {
1053
1186
  }
1054
1187
  }
1055
1188
 
1189
+ /** The caller's signal stopped the install: the app is quitting, nothing failed. */
1190
+ class InstallCancelled extends Error {
1191
+ constructor() {
1192
+ super("The install stopped because GAIA is quitting; it continues on the next launch.");
1193
+ this.name = "InstallCancelled";
1194
+ }
1195
+ }
1196
+
1056
1197
  /** Which FAILURE_REASONS a uv failure's output shows, or null. */
1057
1198
  function failureReason(output) {
1058
1199
  if (isFileLockedError(output)) return FAILURE_REASONS.LOCKED;
@@ -1277,7 +1418,7 @@ function addManagedBinToPath() {
1277
1418
  *
1278
1419
  * Throws InstallError on failure.
1279
1420
  */
1280
- async function ensureUv({ onProgress, isPackaged } = {}) {
1421
+ async function ensureUv({ onProgress, isPackaged, signal } = {}) {
1281
1422
  const report = makeProgressReporter(onProgress);
1282
1423
  report(STAGES.ENSURE_UV, 0, "Checking uv (Python package manager)");
1283
1424
 
@@ -1376,13 +1517,13 @@ async function ensureUv({ onProgress, isPackaged } = {}) {
1376
1517
  "-Command",
1377
1518
  "irm https://astral.sh/uv/install.ps1 | iex",
1378
1519
  ],
1379
- { stageLabel: "uv-install-dev" }
1520
+ { stageLabel: "uv-install-dev", signal }
1380
1521
  );
1381
1522
  } else {
1382
1523
  result = await runCommand(
1383
1524
  "bash",
1384
1525
  ["-c", "curl -LsSf https://astral.sh/uv/install.sh | sh"],
1385
- { stageLabel: "uv-install-dev" }
1526
+ { stageLabel: "uv-install-dev", signal }
1386
1527
  );
1387
1528
  }
1388
1529
 
@@ -1443,7 +1584,7 @@ async function ensureUv({ onProgress, isPackaged } = {}) {
1443
1584
  "-Command",
1444
1585
  "irm https://astral.sh/uv/install.ps1 | iex",
1445
1586
  ],
1446
- { stageLabel: "uv-install-packaged-rescue" }
1587
+ { stageLabel: "uv-install-packaged-rescue", signal }
1447
1588
  );
1448
1589
  if (rescue.code === 0) {
1449
1590
  // Ensure common install locations are present on PATH for this
@@ -1469,6 +1610,7 @@ async function ensureUv({ onProgress, isPackaged } = {}) {
1469
1610
  log(`Packaged Windows: automated uv installer exited ${rescue.code}`);
1470
1611
  }
1471
1612
  } catch (rescueErr) {
1613
+ if (rescueErr instanceof InstallCancelled) throw rescueErr;
1472
1614
  log(`Packaged Windows: rescue installer threw: ${rescueErr.message}`);
1473
1615
  }
1474
1616
  }
@@ -1570,13 +1712,14 @@ async function installBackend(opts = {}) {
1570
1712
  setState(STATES.INSTALLING, { stage: STAGES.ENSURE_UV, version });
1571
1713
 
1572
1714
  // Stage 1: ensure uv
1573
- await ensureUv({ onProgress: opts.onProgress, isPackaged: opts.isPackaged });
1715
+ await ensureUv({ onProgress: opts.onProgress, isPackaged: opts.isPackaged, signal: opts.signal });
1574
1716
 
1575
1717
  // Stage 2: create venv
1576
1718
  setState(STATES.INSTALLING, { stage: STAGES.CREATE_VENV, version });
1577
1719
  report(STAGES.CREATE_VENV, 0, "Creating Python 3.12 environment");
1578
1720
 
1579
1721
  ensureGaiaHome();
1722
+ await stopRunningDaemon({ signal: opts.signal });
1580
1723
 
1581
1724
  // If the venv exists but the python binary is missing, treat as partial.
1582
1725
  const venvLooksValid =
@@ -1593,7 +1736,7 @@ async function installBackend(opts = {}) {
1593
1736
  }
1594
1737
 
1595
1738
  const venvArgs = ["venv", GAIA_VENV, "--python", "3.12"];
1596
- let venvResult = await runCommand("uv", venvArgs, { stageLabel: "venv" });
1739
+ let venvResult = await runCommand("uv", venvArgs, { stageLabel: "venv", signal: opts.signal });
1597
1740
  // uv downloads Python 3.12 when none is installed; behind a corporate
1598
1741
  // proxy that fails on uv's bundled roots exactly like the pip step below.
1599
1742
  let venvNativeTls = false;
@@ -1616,6 +1759,7 @@ async function installBackend(opts = {}) {
1616
1759
  }
1617
1760
  venvResult = await runCommand("uv", [...venvArgs, "--native-tls"], {
1618
1761
  stageLabel: "venv",
1762
+ signal: opts.signal,
1619
1763
  });
1620
1764
  }
1621
1765
  if (venvResult.code !== 0) {
@@ -1663,7 +1807,7 @@ async function installBackend(opts = {}) {
1663
1807
  const offline = await runCommand(
1664
1808
  "uv",
1665
1809
  ["pip", "install", pipPackage, "--offline", "--compile-bytecode", "--python", GAIA_PYTHON_BIN],
1666
- { stageLabel: "pip" }
1810
+ { stageLabel: "pip", signal: opts.signal }
1667
1811
  );
1668
1812
  fs.rmSync(_prefetchMarker(toPep440(version)), { force: true });
1669
1813
  if (offline.code === 0) {
@@ -1685,7 +1829,7 @@ async function installBackend(opts = {}) {
1685
1829
  ) {
1686
1830
  const attemptArgs = useNativeTls ? [...pipArgs, "--native-tls"] : pipArgs;
1687
1831
  if (useNativeTls) nativeTlsAttempted = true;
1688
- installResult = await runCommand("uv", attemptArgs, { stageLabel: "pip" });
1832
+ installResult = await runCommand("uv", attemptArgs, { stageLabel: "pip", signal: opts.signal });
1689
1833
  if (installResult.code === 0) break;
1690
1834
  const attemptOutput = `${installResult.stdout || ""}\n${installResult.stderr || ""}`;
1691
1835
  // A corporate proxy's custom root CA isn't in uv's bundled webpki roots, so
@@ -1728,10 +1872,14 @@ async function installBackend(opts = {}) {
1728
1872
  const moved = moveLockedAside(lockedFiles(firstOutput));
1729
1873
  if (moved.length > 0) {
1730
1874
  report(STAGES.INSTALL_PACKAGE, 0, "Another program has GAIA's files open — retrying the install");
1731
- installResult = await runCommand("uv", useNativeTls ? [...pipArgs, "--native-tls"] : pipArgs, {
1732
- stageLabel: "pip",
1733
- });
1734
- putBackUnreplaced(moved);
1875
+ try {
1876
+ installResult = await runCommand("uv", useNativeTls ? [...pipArgs, "--native-tls"] : pipArgs, {
1877
+ stageLabel: "pip",
1878
+ signal: opts.signal,
1879
+ });
1880
+ } finally {
1881
+ putBackUnreplaced(moved);
1882
+ }
1735
1883
  }
1736
1884
  }
1737
1885
  if (installResult.code !== 0) {
@@ -1891,6 +2039,7 @@ async function refreshAgent(gaiaBin, opts = {}) {
1891
2039
  const result = await runCommand(gaiaBin, ["init", "--agent-only"], {
1892
2040
  stageLabel: "agent",
1893
2041
  env: { ...process.env, COLUMNS: "1000" },
2042
+ signal: opts.signal,
1894
2043
  });
1895
2044
  const lastLine = `${result.stderr || ""}`.trim().split(/\r?\n/).pop();
1896
2045
  if (result.code === AGENT_KEPT_EXIT) {
@@ -2070,8 +2219,11 @@ function venvPackageVersion() {
2070
2219
  * - version: override the pinned version
2071
2220
  * - allowPartialRestart: bool (default true) — restart from scratch if
2072
2221
  * the state file indicates a `partial` install.
2222
+ * - signal: AbortSignal — stops the running step (the app is quitting)
2073
2223
  *
2074
- * Throws InstallError on failure and updates the state file.
2224
+ * Throws InstallError on failure and updates the state file. Throws
2225
+ * InstallCancelled when `signal` stopped it; the state file then still says
2226
+ * installing, so the next launch runs the install again.
2075
2227
  */
2076
2228
  async function ensureBackend(opts = {}) {
2077
2229
  openLog({ truncate: true });
@@ -2207,6 +2359,10 @@ async function ensureBackend(opts = {}) {
2207
2359
  await refreshAgent(verified, opts);
2208
2360
  return verified;
2209
2361
  } catch (err) {
2362
+ if (err instanceof InstallCancelled) {
2363
+ log(err.message);
2364
+ throw err;
2365
+ }
2210
2366
  if (err instanceof InstallError) {
2211
2367
  setState(STATES.FAILED, {
2212
2368
  stage: err.stage || null,
@@ -2238,6 +2394,7 @@ module.exports = {
2238
2394
  getInstalledVersion,
2239
2395
  findGaiaBin,
2240
2396
  toPep440,
2397
+ stopRunningDaemon,
2241
2398
 
2242
2399
  // Pre-checks
2243
2400
  runPreChecks,
@@ -2271,6 +2428,8 @@ module.exports = {
2271
2428
  STATES,
2272
2429
  STAGES,
2273
2430
  FAILURE_REASONS,
2431
+ DAEMON_STOP_TIMEOUT_MS,
2432
+ DAEMON_STOP_LEMONADE_EXIT,
2274
2433
  GAIA_HOME,
2275
2434
  GAIA_VENV,
2276
2435
  GAIA_BIN,
@@ -2278,4 +2437,5 @@ module.exports = {
2278
2437
 
2279
2438
  // Error
2280
2439
  InstallError,
2440
+ InstallCancelled,
2281
2441
  };
@@ -65,6 +65,8 @@ function createEngineInstall({
65
65
  let wakeForRetry = null;
66
66
  let lockedFiles = null;
67
67
  let closing = false;
68
+ let quitting = null;
69
+ let installing = null;
68
70
 
69
71
  /** Who holds `files` open, summarized for the screen; null when Windows can't say. */
70
72
  async function findHolders(files) {
@@ -141,18 +143,25 @@ function createEngineInstall({
141
143
 
142
144
  /**
143
145
  * Install, and after a failure wait for Try again. Resolves true once the
144
- * backend is installed, false when stop() ended the wait.
146
+ * backend is installed, false when stop() ended the install or the wait.
145
147
  */
146
148
  async function run() {
149
+ quitting = new AbortController();
147
150
  for (;;) {
148
151
  publish({ phase: "running", stage: null, percent: null, message: "", error: null });
149
152
  try {
150
- await installer.ensureBackend({
153
+ installing = installer.ensureBackend({
151
154
  isPackaged,
152
155
  onProgress: (stage, percent, message) => publish({ stage, percent, message }),
156
+ signal: quitting.signal,
153
157
  });
158
+ await installing;
154
159
  return true;
155
160
  } catch (err) {
161
+ if (quitting.signal.aborted) {
162
+ console.log(`[main] Backend install stopped for the quit: ${err.message}`);
163
+ return false;
164
+ }
156
165
  console.error(`[main] Backend install failed: ${err.stack || err}`);
157
166
  lockedFiles = err.reason === "locked" && err.lockedFiles?.length ? err.lockedFiles : null;
158
167
  const lockedBy = lockedFiles && platform === "win32" ? await findHolders(lockedFiles) : null;
@@ -194,9 +203,19 @@ function createEngineInstall({
194
203
  run,
195
204
  /** The install is done and the backend process is coming up. */
196
205
  starting: () => publish({ stage: STARTING_STAGE, percent: null, message: "" }),
197
- /** Quitting: release a run() that is waiting on Try again. */
198
- stop: () => {
206
+ /**
207
+ * Quitting: stop a running install, with every process it started, or
208
+ * release a run() waiting on Try again. Resolves once the install has ended.
209
+ */
210
+ stop: async () => {
199
211
  if (wakeForRetry) wakeForRetry(false);
212
+ if (!quitting) return;
213
+ quitting.abort();
214
+ // run() reports the outcome; this only waits for the processes to be gone.
215
+ await installing?.then(
216
+ () => {},
217
+ () => {}
218
+ );
200
219
  },
201
220
  };
202
221
  }
@@ -235,9 +235,26 @@ function attachWindowGuards(win, { app, guard, getTray, isQuitting, platform, re
235
235
  win.on("session-end", () => guard.allow());
236
236
  }
237
237
 
238
+ /**
239
+ * SIGTERM (logout, shutdown, `kill`) quits without the question: nobody is
240
+ * there to answer it, so the dialog would hold the app until it is SIGKILLed.
241
+ * Electron's own SIGTERM handling quits through the guard, which asks.
242
+ *
243
+ * @param {{proc: NodeJS.Process, app: Electron.App,
244
+ * guard: ReturnType<typeof installQuitGuard>, logger?: {log: Function}}} deps
245
+ */
246
+ function quitOnTermSignal({ proc, app, guard, logger = console }) {
247
+ proc.on("SIGTERM", () => {
248
+ logger.log("[main] SIGTERM: quitting without asking about running work");
249
+ guard.allow();
250
+ app.quit();
251
+ });
252
+ }
253
+
238
254
  module.exports = {
239
255
  QUIT_ANYWAY_MS,
240
256
  attachWindowGuards,
257
+ quitOnTermSignal,
241
258
  backendJson,
242
259
  fetchWorkInProgress,
243
260
  describeWork,
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{K as t,P as n,i as r,n as i,o as a,r as o}from"./apiBase-DSN0u9ls.js";import{At as s,Bt as c,I as l,R as u,V as d,Y as f,jt as p,q as m,ut as h}from"./api-By968363.js";import{Lt as g,Ut as _,X as v,a as y,bt as b,c as x,d as S,l as C,nt as w,o as T,r as E,s as D,tt as O,u as k,zt as A}from"./index-8uiHNHOH.js";var j=e(t(),1);function M(){let e=O(),[t,n]=(0,j.useState)(null),[a,c]=(0,j.useState)(null),[u,d]=(0,j.useState)(``),[f,p]=(0,j.useState)(``),[m,h]=(0,j.useState)(!1),[g,_]=(0,j.useState)(null),[v,y]=(0,j.useState)(!1);(0,j.useEffect)(()=>{l().then(e=>{n(e),d(e.saved_base_url??e.base_url??``)}).catch(e=>c(e instanceof Error?e.message:String(e)))},[]);let x=(0,j.useCallback)(async e=>{h(!0),_(null);try{let t=await s(e);n(t),p(``),y(!1)}catch(e){y(k(e)),_(e instanceof Error?e.message:String(e))}finally{h(!1)}},[]),S=()=>void x({mode:`external`,base_url:u.trim(),api_key:f.trim()||void 0});if(a)return r(`section`,{className:`settings-section`,children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),r(`div`,{className:`model-warning`,role:`alert`,children:[o(A,{size:14}),r(`div`,{className:`model-warning-content`,children:[o(`strong`,{children:e(`settings.server.readFailed`)}),o(`p`,{children:a})]})]})]});if(!t)return null;let C=t.mode===`external`;return r(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),o(`p`,{className:`model-override-desc`,role:`status`,children:t.source===`env`?e(`settings.server.usesEnv`,{url:t.base_url??``}):C?e(`settings.server.usesYours`,{url:t.base_url??``}):e(`settings.server.usesOwn`)}),t.source===`env`?o(`p`,{className:`model-status-hint`,children:e(`settings.server.unsetEnv`)}):r(i.Fragment,{children:[r(`p`,{className:`model-status-hint`,children:[e(`settings.server.useYours`),` `,o(`bdi`,{children:t.what_gaia_does})]}),r(`form`,{className:`model-input-row`,onSubmit:e=>{e.preventDefault(),S()},children:[o(`input`,{type:`text`,className:`model-input`,placeholder:`http://localhost:13305`,value:u,onChange:e=>{d(e.target.value),_(null)},disabled:m,spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":e(`settings.server.address`)}),o(`input`,{type:`password`,className:`model-input`,autoComplete:`off`,placeholder:t.api_key_stored?e.bare(`settings.server.keySaved`):e.bare(`settings.server.keyOptional`),value:f,onChange:e=>p(e.target.value),disabled:m,"aria-label":e(`settings.server.key`)}),o(`div`,{className:`model-btn-group`,children:o(`button`,{type:`submit`,className:`btn-model-save`,disabled:m||!u.trim(),children:m?r(i.Fragment,{children:[o(b,{size:13,className:`btn-spinner`}),` `,e(`settings.server.checking`)]}):e(`settings.server.use`)})})]}),C&&o(`div`,{className:`setting-actions`,children:o(`button`,{type:`button`,className:`btn-secondary`,disabled:m,onClick:()=>void x({mode:`gaia`}),children:e(`settings.server.useOwn`)})}),g&&r(`div`,{className:`model-warning`,role:`alert`,children:[o(A,{size:14}),r(`div`,{className:`model-warning-content`,children:[o(`strong`,{children:e(v?`settings.server.needsKey`:`settings.server.notSwitched`)}),o(`p`,{children:g})]})]})]})]})}var N={vulkan:`Vulkan`,rocm:`ROCm`,metal:`Metal`,cpu:`CPU`,npu:`NPU`,remote:`Remote (cloud)`},P={gaia:`settings.server.ownerGaia`,user:`settings.server.ownerUser`,remote:`settings.server.ownerRemote`};function F(e){return e?N[e]??e:`unknown`}function I(e){if(!e)return`unknown`;let t=F(e.backend);return e.backend_source===`lemonade_default`?`${t} (Lemonade's default)`:t}function L(e){return e?`${Math.round(e/1024)}K tokens`:`unknown`}var R={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 z(e,t){if(!e.model_type)return t(`settings.server.loadedModel`);let n=e.model_type.toLowerCase(),r=R[n];return r?t(r):t(`settings.server.kindOther`,{kind:`${n.charAt(0).toUpperCase()}${n.slice(1)}`})}function B(e,t){let n=[e.name?w(e.name):t.bare(`settings.server.unknownModel`),I(e)];return e.backend!==`remote`&&e.ctx_size&&n.push(L(e.ctx_size)),n.join(` · `)}function V({label:e,value:t,title:n}){return r(`div`,{className:`status-row`,children:[o(`span`,{className:`status-label`,children:e}),o(`span`,{className:`status-value model-server-value`,dir:`auto`,title:n??t,children:t})]})}function ee(){let e=O(),t=a(e=>e.openSettings),[n,s]=(0,j.useState)(null),[c,l]=(0,j.useState)(null),[u,f]=(0,j.useState)(null),[m,g]=(0,j.useState)(null),[_,v]=(0,j.useState)(!1);(0,j.useEffect)(()=>{d().then(s).catch(e=>l(e instanceof Error?e.message:String(e)))},[]);let x=(0,j.useCallback)(async t=>{f(t),g(null);try{let n=await p(t);s(n),g({ok:!0,text:e(`settings.server.savedBackend`)})}catch(e){g({ok:!1,text:e instanceof Error?e.message:String(e)})}finally{f(null)}},[e]),S=n?.chat_model??null,C=(0,j.useCallback)(async()=>{if(S?.name){v(!0);try{if(!await h(S.name,S.ctx_size??void 0))return;g({ok:!0,text:e(`settings.server.reloading`,{name:S.name})})}catch(e){g({ok:!1,text:e instanceof Error?e.message:String(e)})}finally{v(!1)}}},[S,e]),T=o(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>t(`model`),children:e(`settings.server.changeModel`)});if(c)return r(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),o(y,{message:c})]});if(!n)return r(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),o(`p`,{className:`loading-text`,children:e(`settings.server.checkingServer`)})]});if(!n.reachable)return r(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),o(y,{message:n.error??e(`settings.errors.serverDownTitle`)}),T]});let E=n.available_backends??[],D=n.preferred_backend??null,k=E.map(e=>e.name);D&&!k.includes(D)&&k.push(D);let A=D??n.default_backend??null,M=E.filter(e=>e.state===`installable`).map(e=>F(e.name)),N=!!S?.name&&S.recipe===`llamacpp`;return r(`section`,{className:`settings-section`,"aria-label":e(`settings.advanced.modelServer`),children:[o(`h4`,{children:e(`settings.advanced.modelServer`)}),r(`div`,{className:`status-grid`,children:[o(V,{label:e(`settings.server.server`),value:`${P[n.owner]?e(P[n.owner]):n.owner}${n.version?` v${n.version}`:``}`}),o(V,{label:e(`settings.server.addressShort`),value:n.base_url}),o(V,{label:e(`settings.server.chatModel`),value:S?.name?w(S.name):e(`settings.advanced.noneLoaded`),title:S?.name??void 0}),S&&o(V,{label:e(`settings.server.runsOn`),value:I(S)}),S&&S.backend!==`remote`&&o(V,{label:e(`settings.advanced.context`),value:L(S.ctx_size)}),o(V,{label:e(`settings.advanced.embedding`),value:n.embedding_model?.name?`${n.embedding_model.name} · ${I(n.embedding_model)}`:e(`settings.advanced.noneLoaded`)}),(n.loaded_models??[]).map((t,n)=>o(V,{label:z(t,e),value:B(t,e),title:t.name??void 0},`${t.name??`unknown`}-${n}`))]}),n.embedding_note&&o(`p`,{className:`settings-hint`,children:o(`bdi`,{children:n.embedding_note})}),n.system_info_error&&o(`p`,{className:`settings-hint`,children:o(`bdi`,{children:n.system_info_error})}),r(`div`,{className:`settings-field model-server-backend`,children:[o(`span`,{className:`settings-label`,children:e(`settings.server.backend`)}),E.length===0&&!D?o(`span`,{className:`settings-hint`,children:e(`settings.server.noBackends`)}):r(i.Fragment,{children:[o(`div`,{className:`segmented`,role:`radiogroup`,"aria-label":e(`settings.server.backendShort`),children:k.map(e=>r(`button`,{type:`button`,role:`radio`,"aria-checked":A===e,className:A===e?`is-active`:``,disabled:u!==null,onClick:()=>{e!==A&&x(e)},children:[u===e?o(b,{size:12,className:`spin`}):null,F(e)]},e))}),r(`span`,{className:`settings-hint`,children:[e(`settings.server.backendHint`),M.length>0&&` ${e(`settings.server.installable`,{names:M.join(`, `)})}`]})]}),m?.ok&&o(`p`,{className:`settings-ok`,role:`status`,children:m.text}),m&&!m.ok&&o(y,{message:m.text})]}),r(`div`,{className:`settings-row`,children:[T,N&&r(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>void C(),disabled:_,children:[_?o(b,{size:13,className:`spin`}):null,e(`settings.server.reload`)]})]})]})}function H(){let e=O(),[t,a]=(0,j.useState)(null),[s,l]=(0,j.useState)(!0),[d,p]=(0,j.useState)([]),[h,w]=(0,j.useState)(``),[k,N]=(0,j.useState)(``),[P,F]=(0,j.useState)(!1),[I,L]=(0,j.useState)(!1),[R,z]=(0,j.useState)(null),[B,V]=(0,j.useState)(!1),H=(0,j.useRef)(null),[W,G]=(0,j.useState)(!1),[K,q]=(0,j.useState)(!1),[J,ne]=(0,j.useState)(!1),[re,ie]=(0,j.useState)(null);(0,j.useEffect)(()=>{n.system.info(`Checking system status...`);let e=n.system.time();f().then(t=>{a(t),n.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||n.system.warn(`Lemonade Server is NOT running.`)}).catch(e=>{n.system.error(`Failed to get system status`,e),a(null)}).finally(()=>l(!1)),u().then(e=>p(e.servers)).catch(()=>{}),m().then(e=>{let t=e.custom_model??``;w(t),N(t),G(e.dynamic_tools),q(e.dynamic_tools_locked)}).catch(e=>{n.system.error(`Failed to load settings`,e)}).finally(()=>F(!0))},[]),(0,j.useEffect)(()=>()=>{H.current&&clearTimeout(H.current)},[]);let ae=(0,j.useCallback)(async()=>{let e=h.trim(),t=e.length>0?e:``;L(!0),z(null),V(!1);try{n.system.info(`Saving custom_model override`,{custom_model:t});let e=(await c({custom_model:t})).custom_model??``;w(e),N(e),V(!0),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>V(!1),2200)}catch(e){let t=e instanceof Error?e.message:String(e);n.system.error(`Failed to save custom_model`,e),z(t)}finally{L(!1)}},[h]),oe=(0,j.useCallback)(async()=>{if(K||J)return;let e=W,t=!e;G(t),ne(!0),ie(null);try{n.system.info(`Saving dynamic_tools setting`,{dynamic_tools:t});let e=await c({dynamic_tools:t});G(e.dynamic_tools),q(e.dynamic_tools_locked)}catch(t){let r=t instanceof Error?t.message:String(t);n.system.error(`Failed to save dynamic_tools`,t),G(e),ie(r)}finally{ne(!1)}},[W,K,J]),se=h.trim()!==k.trim(),Y=t?t.default_model_name:v,{isLoadingModel:ce,isDownloadingModel:X,downloadError:Z,loadModel:le,downloadModel:ue}=E(Y??void 0),Q=!!t?.default_model_is_cloud,de=!Q&&!!(t?.lemonade_running&&t.model_loaded&&t.expected_model_loaded===!1),fe=!Q&&!!(t?.lemonade_running&&t.model_loaded&&t.context_size_sufficient===!1),$=!Q&&!(!t?.lemonade_running||t.model_loaded||t.model_downloaded!==!1),pe=(de||fe)&&Y!==null,me=d.some(e=>!e.connected);return r(`div`,{className:`settings-pane`,children:[o(`h2`,{className:`settings-pane-title`,children:e(`settings.section.advanced`)}),o(`section`,{className:`settings-card`,"aria-label":e(`settings.advanced.status`),children:s?o(`p`,{className:`loading-text`,children:e(`settings.advanced.checking`)}):t?r(i.Fragment,{children:[r(`div`,{className:`status-grid`,children:[o(U,{label:e(`settings.advanced.modelServer`),value:t.lemonade_running?t.lemonade_version?e(`settings.advanced.runningAt`,{version:t.lemonade_version}):e(`settings.advanced.running`):x(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:x(t)?e(`settings.advanced.notInstalledHint`):t.lemonade_error?e(`settings.advanced.queryFailed`,{reason:t.lemonade_error}):t.start_instruction&&!D(t.start_instruction)?t.start_instruction:e(`settings.advanced.notRunningHint`)}),x(t)&&o(T,{className:`btn-primary`}),o(U,{label:e(`settings.section.model`),value:t.model_loaded||e(`settings.advanced.noneLoaded`),ok:!!t.model_loaded&&(Q||t.expected_model_loaded!==!1),hint:t.model_loaded?!Q&&t.expected_model_loaded===!1?e(`settings.advanced.expected`,{name:Y??``}):void 0:e(`settings.advanced.loadsFirst`)}),o(U,{label:e(`settings.advanced.disk`),value:r(`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})]}),$&&r(`div`,{className:`model-action-row model-action-row--download`,children:[r(`div`,{className:`model-action-info`,children:[o(`span`,{className:`model-action-label`,children:e(`settings.advanced.notDownloaded`)}),o(`span`,{className:`model-action-desc`,children:e(`settings.advanced.notDownloadedHint`,{name:Y??``,need:`6 GB`})})]}),o(`button`,{className:`btn-model-action btn-model-action--download`,onClick:()=>ue(!1),disabled:X,children:X?r(i.Fragment,{children:[o(b,{size:13,className:`btn-spinner`}),` `,e(`settings.advanced.downloading`)]}):e(`settings.model.download`)})]}),$&&Z&&o(y,{message:Z}),pe&&r(`div`,{className:`model-action-row model-action-row--load`,children:[r(`div`,{className:`model-action-info`,children:[o(`span`,{className:`model-action-label`,children:e(de?`settings.advanced.wrongModel`:`settings.advanced.smallContext`)}),o(`span`,{className:`model-action-desc`,children:e(`settings.advanced.loadHint`,{name:Y??``,size:`${32 .toFixed(0)}K`})})]}),o(`button`,{className:`btn-model-action btn-model-action--load`,onClick:()=>le(),disabled:ce,children:ce?r(i.Fragment,{children:[o(b,{size:13,className:`btn-spinner`}),` `,e(`settings.advanced.loading`)]}):e(`settings.advanced.load`)})]}),r(`details`,{className:`settings-more`,children:[r(`summary`,{children:[o(_,{size:13,className:`settings-disclosure-chevron`,"aria-hidden":`true`}),` `,e(`settings.advanced.details`)]}),r(`div`,{className:`status-grid`,children:[t.model_size_gb!=null&&o(U,{label:e(`settings.advanced.modelSize`),value:r(`bdi`,{dir:`ltr`,children:[t.model_size_gb,` GB`]}),ok:!0}),t.model_device&&!Q&&o(U,{label:e(`settings.advanced.device`),value:t.model_device.toUpperCase(),ok:t.model_device!==`cpu`}),t.model_context_size!=null&&o(U,{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&&o(U,{label:e(`settings.advanced.capabilities`),value:t.model_labels.join(`, `),ok:!0}),o(U,{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&&o(U,{label:`GPU`,value:o(`bdi`,{children:`${t.gpu_name}${t.gpu_vram_gb?` (${S(t.gpu_vram_gb)})`:``}`}),ok:!0}),o(U,{label:e(`settings.advanced.memory`),value:t.memory_available_gb==null?e(`settings.advanced.unknown`):r(`bdi`,{dir:`ltr`,children:[t.memory_available_gb,` GB`]}),ok:t.memory_available_gb!=null&&t.memory_available_gb>2}),t.processor_name&&o(U,{label:e(`settings.advanced.processor`),value:o(`bdi`,{children:t.processor_name}),ok:!0})]}),t.lemonade_running&&Y!==null&&!Q&&r(`div`,{className:`force-redownload-row`,children:[o(`span`,{className:`force-redownload-label`,children:e(`settings.advanced.corrupted`)}),o(`button`,{className:`btn-force-redownload`,onClick:()=>ue(!0),disabled:X,children:X?r(i.Fragment,{children:[o(b,{size:12,className:`btn-spinner`}),` `,e(`settings.advanced.downloading`)]}):e(`settings.advanced.redownload`)})]}),!$&&Z&&o(y,{message:Z})]})]}):o(`div`,{className:`status-error`,children:o(`p`,{children:e(`settings.advanced.unreachable`)})})}),r(C,{title:e(`settings.advanced.serverTitle`),hint:e(`settings.advanced.serverHint`),children:[o(ee,{}),o(M,{})]}),r(C,{title:e(`settings.advanced.customTitle`),hint:k||e(`settings.advanced.customHint`),children:[o(`p`,{className:`model-override-desc`,children:e(`settings.advanced.customDesc`)}),r(`div`,{className:`model-input-row`,children:[o(`input`,{type:`text`,className:`model-input${k?` has-override`:``}`,placeholder:e.bare(`settings.advanced.customPlaceholder`),value:h,onChange:e=>{w(e.target.value),z(null),V(!1)},onKeyDown:e=>{e.key===`Enter`&&!I&&se&&P&&(e.preventDefault(),ae())},disabled:!P||I,spellCheck:!1,autoCapitalize:`off`,autoCorrect:`off`,"aria-label":e(`settings.advanced.customAria`)}),o(`div`,{className:`model-btn-group`,children:o(`button`,{className:`btn-model-save${B?` saved`:``}`,onClick:()=>{ae()},disabled:!P||I||!se&&!B,"aria-label":e(`settings.advanced.customSave`),children:I?r(i.Fragment,{children:[o(b,{size:13,className:`btn-spinner`}),` `,e(`settings.models.applying`)]}):B?r(i.Fragment,{children:[o(g,{size:13}),` `,e(`settings.advanced.saved`)]}):e(`settings.advanced.save`)})})]}),o(`p`,{className:`model-status-hint`,children:e(`settings.advanced.customIds`)}),R&&o(te,{message:R})]}),r(C,{title:e(`settings.advanced.dynamicTitle`),children:[o(`p`,{className:`model-override-desc`,children:e(`settings.advanced.dynamicDesc`)}),r(`label`,{className:`setting-row`,children:[o(`span`,{children:e(`settings.advanced.dynamicEnable`)}),r(`span`,{className:`toggle-switch`,children:[o(`input`,{type:`checkbox`,checked:W,onChange:()=>void oe(),disabled:!P||J||K,"aria-label":e(W?`settings.advanced.dynamicOff`:`settings.advanced.dynamicOn`)}),o(`span`,{className:`toggle-track`})]})]}),K&&o(`p`,{className:`model-status-hint`,children:e(`settings.advanced.dynamicLocked`)}),re&&o(te,{message:re})]}),d.length>0&&o(C,{title:e(`settings.advanced.mcp`),count:d.length,defaultOpen:me,children:o(`div`,{className:`status-grid`,children:d.map(t=>r(`div`,{className:`status-row`,children:[o(`bdi`,{className:`status-label`,children:t.name}),o(`div`,{className:`status-value-wrap`,children:t.connected?r(`span`,{className:`status-value ok mcp-status-connected`,children:[o(g,{size:12}),e.plural(`settings.advanced.tools`,t.tool_count)]}):r(`span`,{className:`status-value warn mcp-status-failed`,title:t.error??void 0,children:[o(A,{size:12}),e(`settings.custom.failed`)]})})]},t.name))})}),r(`div`,{className:`about-info`,children:[r(`p`,{children:[r(`bdi`,{dir:`ltr`,children:[`GAIA v`,`0.25.4rc6`]}),` `,o(`span`,{className:`beta-badge`,children:`BETA`})]}),o(`p`,{className:`about-sub`,children:e(`settings.advanced.about`)})]})]})}function te({message:e}){let t=O();return r(`div`,{className:`model-warning`,role:`alert`,children:[o(A,{size:14}),r(`div`,{className:`model-warning-content`,children:[o(`strong`,{children:t(`settings.advanced.saveFailed`)}),o(`p`,{children:e})]})]})}function U({label:e,value:t,ok:n,hint:i}){return r(`div`,{className:`status-row${i?` status-row--has-hint`:``}`,children:[o(`span`,{className:`status-label`,children:e}),r(`div`,{className:`status-value-wrap`,children:[o(`span`,{className:`status-value ${n?`ok`:`warn`}`,children:t}),i&&o(`span`,{className:`status-hint`,children:i})]})]})}export{H as AdvancedSettings};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{K as t,P as n,i as r,n as i,o as a,r as o,t as s}from"./apiBase-DSN0u9ls.js";import{_n as c,bn as l,cn as u,dn as d,fn as f,gn as p,hn as m,ln as h,mn as g,on as _,pn as v,sn as y,un as b,vn as x,yn as S}from"./api-By968363.js";import{At as C,Bt as w,Lt as T,Ut as E,bt as D,it as O,kt as k,l as A,tt as j,zt as M}from"./index-8uiHNHOH.js";var N=e(t(),1),P=n.api;function F(e){switch(e){case`connector.configured`:return`configured`;case`connector.disconnected`:return`disconnected`;case`connection.revoked`:return`disconnected`;case`connector.oauth.completed`:return`oauth_completed`;case`connection.connected`:return`oauth_completed`;case`connector.oauth.error`:return`oauth_error`;case`connector.tested`:return`tested`;case`connector.enabled`:return`enabled`;case`connector.disabled`:return`disabled`;case`connector.grant.changed`:return`grant_changed`;case`connector.activation.changed`:return`activation_changed`;default:return null}}function I(e){let t=(0,N.useRef)(e);(0,N.useEffect)(()=>{t.current=e},[e]),(0,N.useEffect)(()=>{let e=`${s()}/connectors/events`,n=null,r=1e3,i=null,a=!1,o=()=>{a||(n=new EventSource(e),n.onopen=()=>{r=1e3},n.onmessage=e=>{try{let n=JSON.parse(e.data),r=F(n.type);if(r===null){P.debug(`connectors-sse: ignoring event`,n.type);return}let i=n.payload??{},a=i.connector_id??i.provider??null;t.current({connectorId:a,reason:r,payload:i})}catch(e){P.warn(`connectors-sse: malformed event`,e)}},n.onerror=()=>{n?.close(),n=null,!a&&(i=setTimeout(o,r),r=Math.min(r*2,3e4))})};return o(),()=>{a=!0,i&&clearTimeout(i),n?.close()}},[])}function L(e){return e.type===`mcp_server`&&e.configured}function R({connector:e,onChanged:t}){let n=j(),[i,a]=(0,N.useState)(!1),[s,c]=(0,N.useState)(!1),[l,u]=(0,N.useState)(null),[p,m]=(0,N.useState)(null),h=(0,N.useRef)(null),g=(0,N.useRef)(null);(0,N.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;h.current&&!h.current.contains(t)&&g.current&&!g.current.contains(t)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let _=(0,N.useCallback)(()=>a(!1),[]);if(O(i,_),(0,N.useEffect)(()=>{if(!i)return;let e=()=>{if(!h.current)return;let e=h.current.getBoundingClientRect();m({top:e.bottom+4,right:window.innerWidth-e.right})};return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[i]),!L(e))return null;let y=e=>{e.stopPropagation(),e.preventDefault()},b=e=>{if(y(e),!i&&h.current){let e=h.current.getBoundingClientRect();m({top:e.bottom+4,right:window.innerWidth-e.right})}a(e=>!e)},x=async e=>{c(!0),u(null);try{await e(),a(!1),t()}catch(e){u(e instanceof Error?e.message:String(e))}finally{c(!1)}};return r(`div`,{className:`connector-tile-menu`,onClick:y,onKeyDown:y,children:[o(`button`,{ref:h,type:`button`,className:`connector-tile-menu-trigger`,"aria-haspopup":`menu`,"aria-expanded":i,"aria-label":n(`settings.connectors.actions`),onClick:b,disabled:s,children:o(C,{size:14})}),i&&p&&r(`div`,{ref:g,role:`menu`,className:`connector-tile-menu-popup`,style:{position:`fixed`,top:p.top,right:p.right},children:[e.enabled?o(`button`,{role:`menuitem`,type:`button`,className:`connector-tile-menu-item`,onClick:()=>void x(()=>d(e.id)),disabled:s,children:n(`settings.connectors.disable`)}):o(`button`,{role:`menuitem`,type:`button`,className:`connector-tile-menu-item`,onClick:()=>void x(()=>v(e.id)),disabled:s,children:n(`settings.connectors.enable`)}),o(`div`,{className:`connector-tile-menu-divider`}),o(`button`,{role:`menuitem`,type:`button`,className:`connector-tile-menu-item connector-tile-menu-item--danger`,onClick:()=>void x(()=>f(e.id)),disabled:s,children:n(`settings.connectors.disconnect`)}),l&&o(`div`,{className:`connector-tile-menu-error`,children:l})]})]})}var z={"https://www.googleapis.com/auth/gmail.readonly":`settings.connectors.scope.gmailRead`,"https://www.googleapis.com/auth/gmail.modify":`settings.connectors.scope.gmailModify`,"https://www.googleapis.com/auth/gmail.send":`settings.connectors.scope.gmailSend`,"https://www.googleapis.com/auth/gmail.compose":`settings.connectors.scope.gmailCompose`,"https://www.googleapis.com/auth/calendar.readonly":`settings.connectors.scope.calendarRead`,"https://www.googleapis.com/auth/calendar.events":`settings.connectors.scope.calendarEvents`,"https://www.googleapis.com/auth/drive.readonly":`settings.connectors.scope.driveRead`,"https://www.googleapis.com/auth/drive.file":`settings.connectors.scope.driveFile`,"https://www.googleapis.com/auth/spreadsheets.readonly":`settings.connectors.scope.sheetsRead`,"https://www.googleapis.com/auth/spreadsheets":`settings.connectors.scope.sheets`,openid:`settings.connectors.scope.openid`,"https://www.googleapis.com/auth/userinfo.email":`settings.connectors.scope.email`,email:`settings.connectors.scope.email`,profile:`settings.connectors.scope.profile`,"https://graph.microsoft.com/Mail.ReadWrite":`settings.connectors.scope.outlookMail`,"https://graph.microsoft.com/Mail.Send":`settings.connectors.scope.outlookSend`,"https://graph.microsoft.com/Calendars.ReadWrite":`settings.connectors.scope.outlookCalendar`,"https://graph.microsoft.com/Calendars.Read":`settings.connectors.scope.outlookCalendarRead`,"https://graph.microsoft.com/User.Read":`settings.connectors.scope.microsoftProfile`};function B(e,t){let n=z[e];return n?t(n):e.split(/[/.:]/).pop()??e}var V=6,H=[`use`];function U(e,t){return!(`revoke_supported`in e)||e.revoke_supported&&e.revoked_remotely?null:e.revoke_supported&&!e.revoked_remotely?t(`settings.connectors.notRevoked`,{reason:String(e.revoke_error??t.bare(`settings.advanced.unknown`))}):e.revoke_error?t(`settings.connectors.localOnly`,{reason:String(e.revoke_error)}):t(`settings.connectors.noRevokeApi`)}function W(){let e=j(),[t,n]=(0,N.useState)([]),[a,s]=(0,N.useState)([]),[c,l]=(0,N.useState)(!0),[u,d]=(0,N.useState)(null),[f,m]=(0,N.useState)(null),[h,_]=(0,N.useState)(null),[v,y]=(0,N.useState)(``),b=(0,N.useCallback)(async()=>{try{let[{connectors:e},{agent_mcps:t}]=await Promise.all([S(),p()]);n(e),s(t),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}},[]);(0,N.useEffect)(()=>{b()},[b]);let x=e=>_(t=>t===e?null:e),C=(0,N.useCallback)(async e=>{try{let t=await g(e);n(n=>n.map(n=>n.id===e?t:n))}catch{b()}},[b]);I((0,N.useCallback)(t=>{t.reason===`disconnected`&&m(U(t.payload,e)),t.connectorId?C(t.connectorId):b()},[C,b,e]));let w=v.trim().toLowerCase(),T=t.filter(e=>!w||e.display_name.toLowerCase().includes(w)||e.description.toLowerCase().includes(w)),E=T.filter(e=>e.configured),O=T.filter(e=>!e.configured&&e.type===`oauth_pkce`),k=T.filter(e=>!e.configured&&e.type!==`oauth_pkce`),P=!t.some(e=>e.configured),F=e=>o(`div`,{className:`connectors-list`,children:e.map(e=>o(G,{connector:e,expanded:h===e.id,onToggle:()=>x(e.id),onChanged:()=>void C(e.id)},e.id))});return r(`section`,{className:`connectors-section`,"aria-label":e(`settings.section.connectors`),children:[o(`p`,{className:`settings-pane-lede`,children:e(`settings.connectors.lede`)}),u&&r(`div`,{className:`error-banner`,children:[o(M,{size:14}),o(`span`,{children:u})]}),f&&r(`div`,{className:`error-banner`,role:`status`,onClick:()=>m(null),children:[o(M,{size:14}),o(`span`,{children:f})]}),c?o(`div`,{className:`connectors-loading`,children:o(D,{size:16,className:`spin`})}):r(i.Fragment,{children:[t.length>V&&o(`input`,{className:`settings-input`,type:`search`,value:v,onChange:e=>y(e.target.value),placeholder:e(`settings.connectors.search`),"aria-label":e(`settings.connectors.search`)}),t.length===0&&!u&&o(`p`,{className:`settings-hint`,children:e(`settings.connectors.none`)}),w&&T.length===0&&o(`p`,{className:`settings-hint`,children:e(`settings.connectors.noMatch`)}),E.length>0&&o(A,{title:e(`settings.connectors.connected`),count:E.length,defaultOpen:!0,forceOpen:!!w,children:F(E)}),O.length>0&&o(A,{title:e(`settings.connectors.accounts`),hint:e(`settings.connectors.accountsHint`),count:O.length,defaultOpen:P,forceOpen:!!w,children:F(O)}),k.length>0&&o(A,{title:e(`settings.connectors.servers`),hint:e(`settings.connectors.serversHint`),count:k.length,forceOpen:!!w,children:F(k)}),a.length>0&&!w&&o(A,{title:e(`settings.connectors.agentServers`),count:a.length,children:o(X,{servers:a,expanded:h,onToggle:x})})]})]})}function G({connector:e,expanded:t,onToggle:n,onChanged:i}){let a=j();return r(`div`,{className:`connector-tile${t?` connector-tile--open`:``}`,children:[r(`div`,{className:`connector-tile-row`,children:[r(`button`,{type:`button`,className:`connector-tile-header`,onClick:n,"aria-expanded":t,children:[o(`bdi`,{className:`connector-tile-name`,children:e.display_name}),e.configured&&o(`span`,{className:`connector-tile-type`,children:e.type===`oauth_pkce`?`OAuth`:`MCP`}),e.configured?e.type===`mcp_server`&&e.enabled===!1?o(`span`,{className:`connector-status disabled`,children:a(`settings.connectors.disabled`)}):r(`span`,{className:`connector-status ok`,children:[o(T,{size:12}),e.account_id?o(`bdi`,{dir:`ltr`,children:e.account_id}):a(`settings.connectors.configured`)]}):e.configurable===!1?o(`span`,{className:`connector-status idle`,children:a(`settings.connectors.setupRequired`)}):null,o(`span`,{className:`connector-tile-chevron`,children:o(t?w:E,{size:14})})]}),o(R,{connector:e,onChanged:i})]}),t&&r(`div`,{className:`connector-detail`,children:[e.type===`oauth_pkce`?o(K,{connector:e,onChanged:i}):o(J,{connector:e,onChanged:i}),e.configured&&o(Q,{connectorId:e.id,connectorType:e.type})]})]})}function K({connector:e,onChanged:t}){let n=j(),[s,c]=(0,N.useState)(!1),[l,d]=(0,N.useState)(null),[p,m]=(0,N.useState)({}),[g,_]=(0,N.useState)(null),{agents:v}=a(),b=v.filter(t=>t.namespaced_agent_id&&t.required_connections?.some(t=>t.connector_id===e.id)),x=b.map(e=>e.namespaced_agent_id).join(`,`),[S,C]=(0,N.useState)(()=>new Set);(0,N.useEffect)(()=>{C(new Set(b.map(e=>e.namespaced_agent_id)))},[x]);let w=e=>C(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),T=()=>[...S];(0,N.useEffect)(()=>{let e=()=>{t()};return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[t]);let E=e=>{let t=window;t.gaia?.openExternal?t.gaia.openExternal(e):window.open(e,`_blank`,`noopener`)},O=async()=>{c(!0),d(null);try{let t=await y(e.id,e.available_scopes?.length?e.available_scopes:e.default_scopes,T());E(t.authorization_url)}catch(e){d(e instanceof Error?e.message:String(e))}finally{c(!1)}},A=async()=>{c(!0),d(null),_(null);try{let t=await u(e.id,e.available_scopes?.length?e.available_scopes:e.default_scopes,T());_(t)}catch(e){d(e instanceof Error?e.message:String(e))}finally{c(!1)}};(0,N.useEffect)(()=>{e.configured&&_(null)},[e.configured]),I((0,N.useCallback)(t=>{t.connectorId===e.id&&(t.reason===`oauth_error`?(d(String(t.payload.error??n(`settings.connectors.deviceFailed`))),_(null)):t.reason===`oauth_completed`&&_(null))},[e.id,n]));let P=async()=>{c(!0),d(null);try{await f(e.id),t()}catch(e){d(e instanceof Error?e.message:String(e))}finally{c(!1)}},F=async()=>{let r=(e.oauth_setup_fields??[]).filter(e=>e.required!==!1&&!p[e.key]?.trim()).map(e=>e.label);if(r.length)d(n(`settings.connectors.required`,{fields:r.join(`, `)}));else{c(!0),d(null);try{let n=e.available_scopes?.length?e.available_scopes:e.default_scopes,r=await h(e.id,{...p,scopes:n,grant_agents:T()}),i=typeof r.authorization_url==`string`?r.authorization_url:null;i&&E(i),t()}catch(e){d(e instanceof Error?e.message:String(e))}finally{c(!1)}}},L=e.oauth_setup_fields??[],R=e.configurable===!1&&!e.configured&&L.length>0;return r(`div`,{className:`configure-body`,children:[e.description&&o(`p`,{className:`connector-desc`,children:o(`bdi`,{children:e.description})}),R&&r(`div`,{className:`oauth-setup-form`,children:[o(`p`,{className:`connector-desc`,children:n(`settings.connectors.firstSetup`)}),L.map(e=>r(`label`,{className:`oauth-setup-field`,children:[o(`span`,{className:`oauth-setup-label`,children:e.label}),o(`input`,{type:e.kind===`secret`?`password`:`text`,className:`oauth-setup-input`,placeholder:e.placeholder,value:p[e.key]??``,onChange:t=>m(n=>({...n,[e.key]:t.target.value})),autoComplete:`off`,spellCheck:!1}),e.help_md&&o(`span`,{className:`oauth-setup-help`,children:o(`bdi`,{children:e.help_md})})]},e.key))]}),!e.configured&&b.length>0&&r(`div`,{className:`oauth-grant-onconnect`,children:[o(`p`,{className:`oauth-grant-onconnect-label`,children:n(`settings.connectors.grantOnConnect`)}),b.map(e=>r(`label`,{className:`oauth-grant-onconnect-item`,children:[o(`input`,{type:`checkbox`,checked:S.has(e.namespaced_agent_id),onChange:()=>w(e.namespaced_agent_id)}),o(`span`,{children:e.name})]},e.namespaced_agent_id)),o(`p`,{className:`oauth-grant-onconnect-help`,children:n(`settings.connectors.grantLater`)})]}),!R&&o(q,{connector:e,onChanged:t}),l&&r(`div`,{className:`configure-error`,children:[o(M,{size:12}),` `,l]}),r(`div`,{className:`configure-actions`,children:[e.configured?o(`button`,{className:`btn-secondary`,disabled:s,onClick:()=>void P(),children:s?o(D,{size:12,className:`spin`}):n(`settings.connectors.disconnect`)}):R?o(`button`,{className:`btn-primary`,disabled:s,onClick:()=>void F(),children:s?o(D,{size:12,className:`spin`}):r(i.Fragment,{children:[o(k,{size:12}),` `,n(`settings.connectors.saveConnect`)]})}):e.configurable===!1?o(`span`,{className:`connector-setup-required`,title:e.config_error??void 0,children:n(`settings.connectors.setupRequired`)}):r(i.Fragment,{children:[o(`button`,{className:`btn-primary`,disabled:s||g!==null,onClick:()=>void O(),children:s?o(D,{size:12,className:`spin`}):r(i.Fragment,{children:[o(k,{size:12}),` `,n(`settings.key.connect`)]})}),e.supports_device_code&&o(`button`,{className:`btn-secondary`,disabled:s||g!==null,onClick:()=>void A(),title:n(`settings.connectors.codeTitle`),children:n(`settings.connectors.code`)})]}),(e.docs_url||e.product_url)&&r(`a`,{href:e.docs_url||e.product_url||`#`,target:`_blank`,rel:`noopener noreferrer`,className:`connector-product-link`,children:[n(`settings.connectors.learnMore`),` `,o(k,{size:11})]})]}),g&&!e.configured&&r(`div`,{className:`device-code-block`,children:[r(`p`,{className:`device-code-instructions`,children:[n(`settings.connectors.goTo`),` `,o(`a`,{href:g.verification_uri,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>{e.preventDefault(),E(g.verification_uri)},children:g.verification_uri})]}),r(`div`,{className:`device-code-value`,children:[o(`code`,{children:g.user_code}),o(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>void navigator.clipboard?.writeText(g.user_code),title:n(`settings.connectors.copyCode`),children:n(`gpu.copy`)})]}),r(`p`,{className:`device-code-waiting`,children:[o(D,{size:12,className:`spin`}),` `,n(`settings.connectors.waiting`)]}),o(`button`,{type:`button`,className:`btn-secondary`,onClick:()=>_(null),children:n(`settings.key.cancel`)})]})]})}function q({connector:e,onChanged:t}){let n=j(),[a,s]=(0,N.useState)(!1),[c,l]=(0,N.useState)({}),[u,d]=(0,N.useState)(!1),[f,p]=(0,N.useState)(!1),[m,g]=(0,N.useState)(null),_=e.oauth_setup_fields??[];if(_.length===0)return null;let v=e.oauth_client,y=v?.source===`keyring`?n(`settings.connectors.savedClient`,{id:v.client_id??``}):v?.source===`env`?n(`settings.connectors.envClient`,{id:v.client_id??``}):n(`settings.connectors.noClient`),b=async()=>{if(!c.client_id?.trim())g(n(`settings.connectors.clientRequired`));else{d(!0),g(null),p(!1);try{await h(e.id,{...Object.fromEntries(Object.entries(c).map(([e,t])=>[e,t.trim()])),save_only:!0}),p(!0),l({}),t(),setTimeout(()=>p(!1),2200)}catch(e){g(e instanceof Error?e.message:String(e))}finally{d(!1)}}};return r(`div`,{className:`oauth-client-editor`,children:[r(`button`,{type:`button`,className:`oauth-client-editor__toggle`,onClick:()=>s(e=>!e),"aria-expanded":a,children:[o(a?w:E,{size:12}),o(`span`,{children:n(`settings.connectors.client`)}),o(`span`,{className:`oauth-client-editor__status`,children:y})]}),a&&r(`div`,{className:`oauth-setup-form`,children:[o(`p`,{className:`connector-desc`,children:n(`settings.connectors.clientHelp`)}),_.map(e=>r(`label`,{className:`oauth-setup-field`,children:[o(`span`,{className:`oauth-setup-label`,children:e.label}),o(`input`,{type:e.kind===`secret`?`password`:`text`,className:`oauth-setup-input`,placeholder:e.kind===`secret`&&v?.source===`keyring`&&v.has_secret?`••••••••`:e.placeholder,value:c[e.key]??``,onChange:t=>l(n=>({...n,[e.key]:t.target.value})),autoComplete:`off`,spellCheck:!1}),e.help_md&&o(`span`,{className:`oauth-setup-help`,children:o(`bdi`,{children:e.help_md})})]},e.key)),m&&r(`div`,{className:`configure-error`,children:[o(M,{size:12}),` `,m]}),o(`div`,{className:`configure-actions`,children:o(`button`,{className:`btn-model-save${f?` saved`:``}`,disabled:u||!c.client_id?.trim(),onClick:()=>void b(),children:u?o(D,{size:12,className:`spin`}):f?r(i.Fragment,{children:[o(T,{size:12}),` `,n(`settings.advanced.saved`)]}):n(`settings.connectors.saveClient`)})})]})]})}function J({connector:e,onChanged:t}){let n=j(),[a,s]=(0,N.useState)(()=>Object.fromEntries(e.mcp_env_keys.map(e=>[e,``]))),[c,l]=(0,N.useState)(!1),[u,p]=(0,N.useState)(!1),[m,g]=(0,N.useState)(null);(0,N.useEffect)(()=>{s(Object.fromEntries(e.mcp_env_keys.map(e=>[e,``])))},[e.mcp_env_keys.join(`,`)]);let _=e.mcp_env_keys.length===0,y=Object.values(a).every(e=>e.trim()===``),b=async()=>{let n=Object.fromEntries(Object.entries(a).filter(([,e])=>e.trim()!==``));if(_||Object.keys(n).length!==0){l(!0),g(null),p(!1);try{await h(e.id,n),p(!0),t(),setTimeout(()=>p(!1),2200)}catch(e){g(e instanceof Error?e.message:String(e))}finally{l(!1)}}},x=async()=>{l(!0),g(null);try{await f(e.id),s(Object.fromEntries(e.mcp_env_keys.map(e=>[e,``]))),t()}catch(e){g(e instanceof Error?e.message:String(e))}finally{l(!1)}},S=async()=>{l(!0),g(null);try{e.enabled?await d(e.id):await v(e.id),t()}catch(e){g(e instanceof Error?e.message:String(e))}finally{l(!1)}};return r(`div`,{className:`configure-body`,children:[e.description&&o(`p`,{className:`connector-desc`,children:o(`bdi`,{children:e.description})}),m&&r(`div`,{className:`configure-error`,children:[o(M,{size:12}),` `,m]}),e.configured&&r(`div`,{className:`connector-toggle-row`,children:[o(`span`,{className:`connector-toggle-label`,children:n(`settings.connectors.active`)}),r(`span`,{className:`toggle-switch`,children:[o(`input`,{type:`checkbox`,checked:e.enabled!==!1,onChange:()=>void S(),disabled:c,"aria-label":e.enabled?n(`settings.connectors.disableServer`):n(`settings.connectors.enableServer`)}),o(`span`,{className:`toggle-track`})]})]}),e.configured&&e.enabled===!1&&o(`p`,{className:`connector-toggle-help`,children:n(`settings.connectors.disabledHelp`)}),e.mcp_env_keys.map(t=>r(`div`,{className:`mcp-key-row`,children:[o(`label`,{className:`mcp-key-label`,children:t}),o(`input`,{type:`password`,className:`mcp-key-input`,placeholder:e.configured?`••••••••`:n.bare(`settings.connectors.enterValue`),value:a[t]??``,onChange:e=>s(n=>({...n,[t]:e.target.value})),spellCheck:!1,autoComplete:`off`})]},t)),r(`div`,{className:`configure-actions`,children:[!(_&&e.configured)&&o(`button`,{className:`btn-model-save${u?` saved`:``}`,disabled:c||!_&&y,onClick:()=>void b(),children:c?o(D,{size:12,className:`spin`}):u?r(i.Fragment,{children:[o(T,{size:12}),` `,n(`settings.advanced.saved`)]}):n(_?`settings.key.connect`:`settings.advanced.save`)}),e.configured&&o(`button`,{className:`btn-secondary`,disabled:c,onClick:()=>void x(),children:n(`settings.connectors.disconnect`)}),e.product_url&&r(`a`,{href:e.product_url,target:`_blank`,rel:`noopener noreferrer`,className:`connector-product-link`,children:[n(`settings.connectors.docs`),` `,o(k,{size:11})]})]})]})}function Y({agent:e,connectorId:t,grantedScopes:n,onChanged:i}){let a=j(),s=e.required_connections?.find(e=>e.connector_id===t),c=e.namespaced_agent_id;if(!s||!c)return null;let[u,d]=(0,N.useState)(()=>new Set(n)),[f,p]=(0,N.useState)(null),[h,g]=(0,N.useState)(null);(0,N.useEffect)(()=>{d(new Set(n))},[n.join(`,`)]);let _=async e=>{if(f!==null)return;let r=new Set(u);r.has(e)?r.delete(e):r.add(e),d(r),p(e),g(null);try{r.size===0?await l(t,c):await m(t,c,[...r]),i()}catch(e){d(new Set(n)),g(e instanceof Error?e.message:String(e))}finally{p(null)}};return r(`div`,{className:`grant-agent-card`,children:[o(`bdi`,{className:`grant-agent-card-name`,children:e.name}),o(`div`,{className:`grant-scope-list`,children:s.scopes.map(e=>r(`label`,{className:`grant-scope-item`,children:[o(`span`,{className:`grant-scope-label`,children:B(e,a)}),r(`span`,{className:`toggle-switch`,children:[o(`input`,{type:`checkbox`,checked:u.has(e),onChange:()=>void _(e),disabled:f!==null}),o(`span`,{className:`toggle-track`})]})]},e))}),h&&r(`div`,{className:`grant-scope-warning grant-scope-warning--error`,children:[o(M,{size:11}),` `,h]})]})}function X({servers:e,expanded:t,onToggle:n}){return o(`div`,{className:`agent-mcps-section`,children:o(`div`,{className:`connectors-list`,children:e.map(e=>{let r=`${e.agent_id}::${e.server_name}`;return o(Z,{server:e,expanded:t===r,onToggle:()=>n(r)},r)})})})}function Z({server:e,expanded:t,onToggle:n}){let i=j(),a=[e.command,...e.args].join(` `);return r(`div`,{className:`agent-mcp-tile${t?` agent-mcp-tile--open`:``}`,children:[r(`button`,{type:`button`,className:`agent-mcp-tile-header`,onClick:n,"aria-expanded":t,children:[o(`span`,{className:`agent-mcp-server-name`,children:e.server_name}),o(`span`,{className:`agent-mcp-agent-label`,children:i(`settings.connectors.via`,{name:e.agent_name})}),e.disabled?o(`span`,{className:`agent-mcp-status disabled`,children:i(`settings.connectors.disabled`)}):r(`span`,{className:`agent-mcp-status enabled`,children:[o(T,{size:11}),` `,i(`settings.connectors.active`)]}),o(`span`,{className:`agent-mcp-readonly-badge`,children:i(`settings.connectors.readOnly`)}),o(`span`,{className:`agent-mcp-chevron`,children:o(t?w:E,{size:14})})]}),t&&r(`div`,{className:`agent-mcp-detail`,children:[a&&o(`bdi`,{dir:`ltr`,className:`agent-mcp-command-row`,children:a}),o(`bdi`,{dir:`ltr`,className:`agent-mcp-config-path`,children:e.config_path}),o(`div`,{className:`agent-mcp-config-hint`,children:i(`settings.connectors.editConfig`)})]})]})}function Q({connectorId:e,connectorType:t}){let n=j(),{agents:s}=a(),[l,u]=(0,N.useState)({}),[d,f]=(0,N.useState)({}),[p,m]=(0,N.useState)(!0),h=(0,N.useCallback)(async()=>{try{let[{grants:t},{activations:n}]=await Promise.all([x(e),c(e)]);u(t),f(n)}catch{u({}),f({})}finally{m(!1)}},[e]);if((0,N.useEffect)(()=>{h()},[h]),I((0,N.useCallback)(t=>{t.connectorId===e&&(t.reason===`grant_changed`||t.reason===`activation_changed`||t.reason===`disconnected`)&&h()},[e,h])),p)return null;let g=s.filter(t=>t.namespaced_agent_id&&t.required_connections?.some(t=>t.connector_id===e)),_=t===`mcp_server`?s.filter(t=>t.namespaced_agent_id&&(t.consumes_mcp_servers||t.required_connections?.some(t=>t.connector_id===e))):[];return r(`div`,{className:`connection-grants`,children:[o(`div`,{className:`grants-header`,children:n(`settings.connectors.grants`)}),g.length===0?o(`div`,{className:`grants-empty`,children:n(`settings.connectors.noGrants`)}):g.map(t=>o(Y,{agent:t,connectorId:e,grantedScopes:l[t.namespaced_agent_id]??[],onChanged:()=>void h()},t.namespaced_agent_id)),_.length>0&&r(i.Fragment,{children:[o(`div`,{className:`grants-header grants-header--activations`,children:n(`settings.connectors.activeFor`)}),o(`div`,{className:`grants-help`,children:n(`settings.connectors.activationHelp`)}),_.map(t=>o($,{agent:t,connectorId:e,active:!!d[t.namespaced_agent_id],grantedScopes:l[t.namespaced_agent_id]??[],onChanged:()=>void h()},`activation-${t.namespaced_agent_id}`))]})]})}function $({agent:e,connectorId:t,active:n,grantedScopes:i,onChanged:a}){let s=j(),c=e.required_connections?.find(e=>e.connector_id===t),l=e.namespaced_agent_id;if(!l)return null;let[u,d]=(0,N.useState)(n),[f,p]=(0,N.useState)(!1),[m,h]=(0,N.useState)(null);(0,N.useEffect)(()=>{d(n)},[n]);let g=async()=>{if(f)return;let e=!u;d(e),p(!0),h(null);try{if(e){let e=i.length===0?c?[...c.scopes]:[...H]:void 0;await _(t,l,e)}else await b(t,l);a()}catch(e){d(n),h(e instanceof Error?e.message:String(e))}finally{p(!1)}};return r(`div`,{className:`grant-agent-card`,children:[o(`bdi`,{className:`grant-agent-card-name`,children:e.name}),o(`div`,{className:`grant-scope-list`,children:r(`label`,{className:`grant-scope-item`,children:[o(`span`,{className:`grant-scope-label`,children:s(u?`settings.connectors.toolsVisible`:`settings.connectors.toolsHidden`)}),r(`span`,{className:`toggle-switch`,children:[o(`input`,{type:`checkbox`,checked:u,onChange:()=>void g(),disabled:f}),o(`span`,{className:`toggle-track`})]})]})}),m&&r(`div`,{className:`grant-scope-warning grant-scope-warning--error`,children:[o(M,{size:11}),` `,m]})]})}function ee(){let e=j();return r(`div`,{className:`settings-pane`,children:[o(`h2`,{className:`settings-pane-title`,children:e(`settings.section.connectors`)}),o(W,{})]})}export{ee as ConnectorsPane};