aegiscode 7.0.34 → 7.0.36

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.
@@ -5,7 +5,7 @@
5
5
  // Conveying a modified copy, or running one as a network service, owes the
6
6
  // corresponding source under this licence (§5/§13) — see LICENSING.md.
7
7
  /**
8
- * AEGIS Desktop — thin Electron main shell (host 2).
8
+ * aegis one — thin Electron main shell (host 2).
9
9
  *
10
10
  * This process owns the ONLY privileged object in the app: an instance of the
11
11
  * shared thin client (../client/aegis.js), which holds the AEGIS_API_KEY read
@@ -336,6 +336,45 @@ const MENU_SEARCH_MEMORY_CHANNEL = `${IPC_PREFIX}menuSearchMemory`;
336
336
  * the licence, the program notice and the vendored attributions, parsed out
337
337
  * of LICENSING.md and the two NOTICE files rather than retyped in a renderer. */
338
338
  const MENU_CREDITS_CHANNEL = `${IPC_PREFIX}menuCredits`;
339
+ // ⌘P command palette and ⌘B sidebar toggle. Both are pure renderer concerns —
340
+ // which commands exist, whether the rail is showing — but the chord has to be
341
+ // registered in the MENU, not in a renderer keydown, because a sandboxed
342
+ // renderer never sees the keystroke when focus is in the native menu bar, and
343
+ // because an accelerator here is what makes the chord show up in the menu the
344
+ // user can read. The click handlers only ping the renderer; nothing about the
345
+ // palette's contents lives in this process.
346
+ const MENU_PALETTE_CHANNEL = `${IPC_PREFIX}menuPalette`;
347
+ const MENU_TOGGLE_SIDEBAR_CHANNEL = `${IPC_PREFIX}menuToggleSidebar`;
348
+ /** Edit > Find in conversation (Cmd/Ctrl+F).
349
+ *
350
+ * Distinct from MENU_SEARCH_CHANNEL (Cmd/Ctrl+K) on purpose: that chord opens
351
+ * the sheet that searches every stored session and memory, which answers "I
352
+ * wrote this down somewhere". This one is scoped to the transcript already on
353
+ * screen and never leaves the renderer — there is no store to query, so the
354
+ * menu only has to say the key was pressed. Registered here rather than in a
355
+ * renderer keydown because a sandboxed renderer never sees the keystroke and
356
+ * because an accelerator in the menu is what makes the chord discoverable. */
357
+ const MENU_FIND_CHANNEL = `${IPC_PREFIX}menuFind`;
358
+ /** View > Go Back / Go Forward.
359
+ *
360
+ * Both chords are conventional on Linux and Windows (Alt+Left/Right) and on macOS
361
+ * (Cmd+[ / Cmd+]) — the accelerator string below is one of each rather than four,
362
+ * because Electron's `CmdOrCtrl` covers the modifier and the bracket keys cover
363
+ * the rest. They are menu items rather than renderer keydown handlers for the
364
+ * same reason as Find: a sandboxed renderer never sees the keystroke, and the
365
+ * menu is what makes a chord discoverable.
366
+ *
367
+ * There is no state here beyond what the renderer reports (see SET_NAV_STATE):
368
+ * main.js only forwards the press and greys the rows out. */
369
+ const MENU_GO_BACK_CHANNEL = `${IPC_PREFIX}menuGoBack`;
370
+ const MENU_GO_FORWARD_CHANNEL = `${IPC_PREFIX}menuGoForward`;
371
+ /** What the renderer last said about its stack. Module-level because
372
+ * buildAppMenu is a pure template builder called from bootstrap and from
373
+ * rebuildAppMenu, and the enabled state of two menu rows is the only thing that
374
+ * has to survive between those calls. Defaults to false: at boot the stack is
375
+ * empty, and a command that is greyed out until proven usable is the honest
376
+ * default for a feature whose whole content is "where you have been". */
377
+ const navState = { back: false, forward: false };
339
378
  /** File > Save as… / Export session — same "menu has no state of its own,
340
379
  * renderer does the work" pattern as the two channels above: the renderer
341
380
  * knows the open session id, main.js just pings it. */
@@ -386,6 +425,34 @@ const QUICK_LAUNCHER_PUSH_CHANNEL = `${IPC_PREFIX}quickLauncherPush`;
386
425
  */
387
426
  const QUEUE_PROGRESS_CHANNEL = `${QUEUE_PREFIX}progress`;
388
427
 
428
+ /**
429
+ * Main -> renderer push channel for "the queue file changed".
430
+ *
431
+ * QUEUE_PROGRESS_CHANNEL carries the frames of a drain that THIS main process
432
+ * started, sent to one target window. That is enough to follow a drain, but it
433
+ * cannot report a row APPEARING: `aegiscode autonomous add` in a shell, a second
434
+ * window's enqueue, and a task the auto-drain timer picks up all mutate the same
435
+ * queue file with no frame anywhere. Repainting the card was the CALLER's job —
436
+ * every renderer helper re-read after its own call — so those writers left the
437
+ * card stale: a missing row, or "queue is empty" painted over a running task.
438
+ *
439
+ * This channel moves that repaint to the mutation itself. It is deliberately
440
+ * payload-light ({ at }): the renderer reacts by re-reading queue.list(), which
441
+ * is the same call it already trusts, so no second copy of the queue state can
442
+ * drift out of sync with the file the CLI also writes.
443
+ */
444
+ const QUEUE_CHANGED_CHANNEL = `${QUEUE_PREFIX}changed`;
445
+
446
+ /**
447
+ * The queue methods that can change the file, and therefore owe the renderer a
448
+ * QUEUE_CHANGED_CHANNEL push. `list` and `entitlement` are reads and are left
449
+ * out on purpose: `entitlement` can hit the network, and notifying on a read the
450
+ * renderer makes in response to a notification would be a re-render loop.
451
+ */
452
+ const QUEUE_MUTATING_METHODS = new Set([
453
+ 'enqueue', 'clear', 'retry', 'remove', 'drain', 'proceed', 'stop',
454
+ ]);
455
+
389
456
  /**
390
457
  * How much task text the queue surface accepts, and how many rounds a queued
391
458
  * task may take. Both are ceilings on what ONE renderer call can ask the app to
@@ -522,6 +589,30 @@ function abortedTurnPayload(err) {
522
589
  };
523
590
  }
524
591
 
592
+ /** Whether a background lane's classified failure line is printed.
593
+ *
594
+ * The line is written for an operator: `status 0 [timeout]` vs `402` vs `401`
595
+ * is what tells them which failure this was, and it is the only place that
596
+ * survives — the renderer only ever sees a message string. But the lanes that
597
+ * reach it are the ones the user never typed: the welcome panel's greeting,
598
+ * fired on boot while the window is still painting, and the discovery cards.
599
+ * When a provider is slow to warm, the greeting's own 10s budget expires and
600
+ * the very first thing a launch printed was `[model] background aegis turn
601
+ * produced no answer: Provider request timed out` — a real fact about the
602
+ * provider, printed at the user as if the app had failed to start.
603
+ *
604
+ * So it is quiet by default and `AEGIS_DEBUG=1` brings it back. Nothing is
605
+ * lost by hiding it: those lanes already render their own state (the panel
606
+ * keeps its fact line, a discovery card says "Path unavailable"), and a
607
+ * provider that is genuinely down still names itself on the next turn the
608
+ * user actually sends. `AEGIS_DEBUG` is the same switch `bin/aegis.js` uses
609
+ * for its launch errors, so there is one way to ask this app to talk.
610
+ */
611
+ function backgroundLaneLogs() {
612
+ const v = process.env.AEGIS_DEBUG;
613
+ return v === '1' || v === 'true' || v === 'yes';
614
+ }
615
+
525
616
  /**
526
617
  * Precise classification of a cloud-sync refusal — the desktop port of
527
618
  * `describeError()` in cli/src/cloudsync.js, so both hosts name a 402/401 the
@@ -682,7 +773,7 @@ function watchTopupCredit(aegis, opts) {
682
773
  const Ctor = electron && electron.Notification;
683
774
  if (Ctor && Ctor.isSupported()) {
684
775
  new Ctor({
685
- title: 'AEGIS Desktop',
776
+ title: 'aegis one',
686
777
  body: `Bank credited — €${amount.toFixed(2)} available`,
687
778
  }).show();
688
779
  }
@@ -756,6 +847,7 @@ function watchTopupCredit(aegis, opts) {
756
847
  */
757
848
  let memoryIndexHandle = null;
758
849
  let memoryIndexOff = false;
850
+ let memoryIndexTries = 0;
759
851
  function memoryIndex(dir) {
760
852
  if (memoryIndexHandle) return memoryIndexHandle;
761
853
  if (memoryIndexOff || !dir) return null;
@@ -763,13 +855,19 @@ function memoryIndex(dir) {
763
855
  const store = new memoryStore.MemoryStore({ dir });
764
856
  const opened = store.open();
765
857
  if (!opened.ok) {
766
- memoryIndexOff = true;
858
+ // `node:sqlite` missing is permanent, so latch on sight. Anything else
859
+ // (EACCES on the dir, EBUSY, a corrupt file) may be transient and must
860
+ // not kill indexing for the whole process — but search runs on every
861
+ // keystroke, so stop attempting a doomed open after a few rather than
862
+ // retrying it per character.
863
+ if (!memoryStore.isAvailable() || ++memoryIndexTries >= 3) memoryIndexOff = true;
767
864
  return null;
768
865
  }
866
+ memoryIndexTries = 0;
769
867
  memoryIndexHandle = store;
770
868
  return memoryIndexHandle;
771
869
  } catch {
772
- memoryIndexOff = true;
870
+ if (!memoryStore.isAvailable() || ++memoryIndexTries >= 3) memoryIndexOff = true;
773
871
  return null;
774
872
  }
775
873
  }
@@ -1382,13 +1480,22 @@ function createIpcDispatch(aegis, dir, persistApiKey, openExternal, providerConf
1382
1480
  payload && payload.apiKey
1383
1481
  ),
1384
1482
 
1385
- memorySearch: (payload) =>
1386
- normalizeMemoryReadWithFallback(
1387
- aegis.memorySearch(payload && payload.query, payload && payload.limit),
1483
+ memorySearch: (payload) => {
1484
+ // Level buys recall BREADTH, never a new approval: the limit is clamped
1485
+ // by turn.js inside the capabilities object itself, so a hand-edited
1486
+ // ledger buys at most MAX_RECALL_ENTRIES. Absent avatar ⇒ no cap change.
1487
+ const caps = avatar && typeof avatar.capabilities === 'function' ? avatar.capabilities() : null;
1488
+ const asked = payload && payload.limit;
1489
+ const limit = Number.isFinite(asked)
1490
+ ? asked
1491
+ : (caps && Number.isFinite(caps.recallEntries) ? caps.recallEntries : undefined);
1492
+ return normalizeMemoryReadWithFallback(
1493
+ aegis.memorySearch(payload && payload.query, limit),
1388
1494
  memoryIndex(dir),
1389
1495
  payload && payload.query,
1390
- payload && payload.limit
1391
- ),
1496
+ limit
1497
+ );
1498
+ },
1392
1499
  memorySave: (payload) =>
1393
1500
  saveMemoryWithQueue(aegis, dir, payload && payload.entry, avatar, memoryIndex(dir)),
1394
1501
  memoryList: (payload) =>
@@ -1420,6 +1527,47 @@ function createIpcDispatch(aegis, dir, persistApiKey, openExternal, providerConf
1420
1527
  importConversation: (payload) =>
1421
1528
  aegis.importConversation(payload || {}),
1422
1529
 
1530
+ // The companion's customization pane (`renderer/avatar/pane.js`), now a
1531
+ // card in Settings. Two channels, mirroring the pane's own contract: the
1532
+ // pane PREVIEWS freely against an in-memory persona and only this pair
1533
+ // decides whether anything reached disk. `writePersona` validates the
1534
+ // merge before touching the file (write-then-revalidate), so a patch that
1535
+ // cannot be repaired answers `{ ok: false, reason }` and leaves the
1536
+ // stored persona alone — the status line the pane shows is main's answer,
1537
+ // never the pane's guess. `capabilities` gates cosmetics; when the store
1538
+ // has no ledger to consult it returns null and the pane correctly gates
1539
+ // nothing rather than inventing a lock.
1540
+ personaRead: () => {
1541
+ if (!avatar) return { ok: false, reason: 'no avatar store in this build' };
1542
+ try {
1543
+ const read = avatar.readPersona();
1544
+ return {
1545
+ ok: true,
1546
+ persona: read.persona,
1547
+ warnings: read.warnings || [],
1548
+ capabilities: typeof avatar.capabilities === 'function' ? avatar.capabilities() : null,
1549
+ };
1550
+ } catch (err) {
1551
+ return { ok: false, reason: errorText(err) };
1552
+ }
1553
+ },
1554
+ personaPatch: (payload) => {
1555
+ if (!avatar) return { ok: false, reason: 'no avatar store in this build' };
1556
+ const patch = payload && payload.patch;
1557
+ if (!patch || typeof patch !== 'object') return { ok: false, reason: 'no patch' };
1558
+ try {
1559
+ const next = avatar.writePersona(patch);
1560
+ return {
1561
+ ok: true,
1562
+ saved: true,
1563
+ persona: next.persona,
1564
+ warnings: next.warnings || [],
1565
+ };
1566
+ } catch (err) {
1567
+ return { ok: false, reason: errorText(err) };
1568
+ }
1569
+ },
1570
+
1423
1571
  // Links inside rendered markdown must never navigate the app's own
1424
1572
  // BrowserWindow (that would point the chat UI at an arbitrary model-
1425
1573
  // supplied origin) — they open in the OS default browser instead.
@@ -1456,8 +1604,8 @@ function withReplyNotify(promise, event, onReplyFinished) {
1456
1604
  * tests, where the safe no-op default in createIpcDispatch takes over.
1457
1605
  * `onReplyFinished` is likewise bootstrap()-only: it fires the native
1458
1606
  * "reply ready" notification when the window is unfocused/hidden. */
1459
- function registerIpc(ipcMain, aegis, dir, persistApiKey, openExternal, onReplyFinished, providerConfigured, getVaultBackend) {
1460
- const dispatch = createIpcDispatch(aegis, dir, persistApiKey, openExternal, providerConfigured, undefined, getVaultBackend);
1607
+ function registerIpc(ipcMain, aegis, dir, persistApiKey, openExternal, onReplyFinished, providerConfigured, getVaultBackend, avatar) {
1608
+ const dispatch = createIpcDispatch(aegis, dir, persistApiKey, openExternal, providerConfigured, avatar, getVaultBackend);
1461
1609
  for (const [name, handler] of Object.entries(dispatch)) {
1462
1610
  if (name === 'chatCompletion') {
1463
1611
  // Streaming render (D2.1): when the renderer asks for stream, SSE deltas
@@ -1510,6 +1658,54 @@ function registerIpc(ipcMain, aegis, dir, persistApiKey, openExternal, onReplyFi
1510
1658
  * turn that off for good — the engine reads the flag per tool call, so the
1511
1659
  * change applies to the very next call, no restart.
1512
1660
  */
1661
+ /**
1662
+ * Interface text scale: `aegis:getFontScale` / `aegis:setFontScale`.
1663
+ *
1664
+ * The renderer-side half of the reference's `--app-font-scale`: every size in
1665
+ * this stylesheet's type ramp is `calc(…px * var(--app-font-scale, 1))`, and
1666
+ * this dispatch is what sets that variable. Without a persisted value the ramp
1667
+ * would be a constant, which is what it was before this existed.
1668
+ *
1669
+ * Registered through the generic registerConfirmModeIpc like the rest — it only
1670
+ * wires `{name: handler}` pairs as `aegis:<name>`. Clamping lives in the store
1671
+ * (clampFontScale), so this stays a pass-through and main/rendered halves cannot
1672
+ * disagree about the legal range.
1673
+ */
1674
+ /**
1675
+ * Accent skin: `aegis:getAccent` / `aegis:setAccent`.
1676
+ *
1677
+ * Same pass-through shape as createFontScaleDispatch, and for the same reason:
1678
+ * the legal names live in the store (ACCENT_SKINS / clampAccent), so main cannot
1679
+ * accept a skin the stylesheet has no rule for. A malformed payload returns the
1680
+ * STORED value rather than resetting to `default` — absent means "change
1681
+ * nothing", not "pick the first option".
1682
+ */
1683
+ function createAccentDispatch(settings) {
1684
+ if (!settings) throw new Error('createAccentDispatch requires a settings store');
1685
+ return {
1686
+ getAccent: () => ({ name: settings.getAccent() }),
1687
+ setAccent: (payload) => {
1688
+ const name = payload && payload.name;
1689
+ if (typeof name !== 'string') return { name: settings.getAccent() };
1690
+ return { name: settings.setAccent(name) };
1691
+ },
1692
+ };
1693
+ }
1694
+
1695
+ function createFontScaleDispatch(settings) {
1696
+ if (!settings) throw new Error('createFontScaleDispatch requires a settings store');
1697
+ return {
1698
+ getFontScale: () => ({ scale: settings.getFontScale() }),
1699
+ setFontScale: (payload) => {
1700
+ // A malformed payload must not reset the user's text size, exactly as in
1701
+ // createConfirmModeDispatch: absent means "change nothing", not "use 1".
1702
+ const scale = payload && payload.scale;
1703
+ if (typeof scale !== 'number') return { scale: settings.getFontScale() };
1704
+ return { scale: settings.setFontScale(scale) };
1705
+ },
1706
+ };
1707
+ }
1708
+
1513
1709
  function createConfirmModeDispatch(settings) {
1514
1710
  if (!settings) throw new Error('createConfirmModeDispatch requires a settings store');
1515
1711
  return {
@@ -1649,6 +1845,104 @@ function createPermRulesDispatch(store) {
1649
1845
  * Every handler answers the policy as RE-READ from the store, never the value
1650
1846
  * that was posted, so a rejected choice cannot be painted as accepted.
1651
1847
  */
1848
+ /**
1849
+ * The terminal face, opened from the window's topbar (`(cli)`).
1850
+ *
1851
+ * `aegiscode/one` ships BOTH faces in one artifact — this window, and the
1852
+ * `aegiscode` terminal — and until this dispatch the terminal was reachable
1853
+ * only by leaving the app and typing the command. The chip in the topbar
1854
+ * launches it the same way `one/src/selfhost.js` re-enters for an `aegiscode`
1855
+ * launch (Electron-as-Node over `resources/faces/cli/**`), which is what makes
1856
+ * a packaged install work with no Node on PATH.
1857
+ *
1858
+ * The decision of WHAT to run and WHICH emulator is pure and lives in
1859
+ * lib/local/cli-face.js; all that belongs here is the effects: probe PATH,
1860
+ * spawn detached, and report a sentence when there is nothing to spawn. It
1861
+ * resolves `{ ok:true, emulator }` or `{ ok:false, reason, command }` and never
1862
+ * rejects — an absent emulator is a message to show, not an exception to catch.
1863
+ *
1864
+ * Detached + unref, deliberately: the terminal outlives a window the user
1865
+ * closes moments later, and a CLI session must not be killed because the chat
1866
+ * window it was started from went away.
1867
+ */
1868
+ function createCliFaceDispatch(deps) {
1869
+ const d = deps || {};
1870
+ const face = d.face || require('./lib/local/cli-face.js');
1871
+ const platformMod = d.platform || require('./vendor/platform.js');
1872
+ const spawnChild = d.spawn || require('node:child_process').spawn;
1873
+
1874
+ // PATH resolution goes through client/platform.js (the repo's single OS map,
1875
+ // shipped flat as vendor/platform.js) rather than a hand-rolled scan here, so
1876
+ // win32's PATHEXT handling is the same code the rest of the app uses.
1877
+ const exists = (name) => {
1878
+ try {
1879
+ return Boolean(platformMod.resolveExecutable(name, {
1880
+ platform: d.hostPlatform || process.platform,
1881
+ env: d.env || process.env,
1882
+ }));
1883
+ } catch {
1884
+ return false;
1885
+ }
1886
+ };
1887
+
1888
+ // Whether the app BUNDLES the terminal face (an installed npm copy ships it at
1889
+ // `vendor/faces/cli/**`) is a filesystem fact, so the probe lives here and the
1890
+ // module stays pure. Injected as `d.entryExists` in tests.
1891
+ const entryExists =
1892
+ d.entryExists ||
1893
+ ((p) => {
1894
+ try {
1895
+ return require('node:fs').existsSync(p);
1896
+ } catch {
1897
+ return false;
1898
+ }
1899
+ });
1900
+
1901
+ return {
1902
+ openCliFace: (payload) => {
1903
+ const appInfo = d.appInfo || {};
1904
+ let planned;
1905
+ try {
1906
+ planned = face.plan({
1907
+ packaged: appInfo.packaged,
1908
+ resourcesPath: appInfo.resourcesPath,
1909
+ appDir: appInfo.appDir,
1910
+ execPath: appInfo.execPath,
1911
+ nodePath: appInfo.nodePath,
1912
+ platform: d.hostPlatform || process.platform,
1913
+ exists,
1914
+ entryExists,
1915
+ args: payload && Array.isArray(payload.args) ? payload.args : [],
1916
+ });
1917
+ } catch (err) {
1918
+ return { ok: false, reason: `could not plan the terminal face: ${(err && err.message) || err}`, command: face.CLI_BIN };
1919
+ }
1920
+ if (!planned || !planned.ok) {
1921
+ return {
1922
+ ok: false,
1923
+ reason: (planned && planned.reason) || 'could not open a terminal',
1924
+ command: (planned && planned.command) || face.CLI_BIN,
1925
+ };
1926
+ }
1927
+ try {
1928
+ const child = spawnChild(planned.exec, planned.args, {
1929
+ detached: true,
1930
+ stdio: 'ignore',
1931
+ env: Object.assign({}, d.env || process.env, planned.env || {}),
1932
+ });
1933
+ if (child && typeof child.unref === 'function') child.unref();
1934
+ } catch (err) {
1935
+ return {
1936
+ ok: false,
1937
+ reason: `could not start ${planned.exec}: ${(err && err.message) || err}`,
1938
+ command: planned.command,
1939
+ };
1940
+ }
1941
+ return { ok: true, emulator: planned.exec, command: planned.command };
1942
+ },
1943
+ };
1944
+ }
1945
+
1652
1946
  function createSandboxPolicyDispatch(settings, sandbox, opts) {
1653
1947
  if (!settings) throw new Error('createSandboxPolicyDispatch requires a settings store');
1654
1948
  const mod = sandbox || {};
@@ -2035,12 +2329,45 @@ function createEngine(aegis, { app, safeStorage, dir: dirOverride, sessionsDir:
2035
2329
  // readable by this process.
2036
2330
  const settingsDir = dirOverride || resolveUserDataDir(app);
2037
2331
  const settings = createSettingsStore({ dir: settingsDir, safeStorage });
2332
+ // THE LEDGER. `store.js` was written in Phase 20 but never constructed, so
2333
+ // every `avatar.awardSave`/`awardQueued`/`awardImports` below was reached
2334
+ // with `undefined` and silently did nothing: no level ever rose. It is
2335
+ // built here, once, in main — a renderer-held counter is a suggestion, the
2336
+ // same reasoning persist-gate.js follows — and it lives in `settingsDir`
2337
+ // (Electron's userData), never the shared store: XP is this host's own.
2338
+ const avatar = avatarStore.createAvatarStore({ dir: settingsDir, log: () => {} });
2339
+ // Phase 19's carve-outs are swept over the whole level range at boot, so a
2340
+ // bad edit to level.js fails the app at startup instead of shipping a level
2341
+ // that quietly widens an approval. Same shape as verifyInvariants elsewhere.
2342
+ try {
2343
+ avatar.verifyAtBoot();
2344
+ } catch (err) {
2345
+ console.error('aegis: avatar carve-out violation', err && err.message);
2346
+ }
2038
2347
  // Relocate a pre-fix `settings['aegis']` key into the reserved namespace so
2039
2348
  // it stops showing up as a provider. Ciphertext-level, so safe pre-'ready'.
2040
2349
  settings.migrateLegacyAegisKey();
2350
+ const avatarCaps = () => {
2351
+ try {
2352
+ return avatar.capabilities();
2353
+ } catch {
2354
+ return null;
2355
+ }
2356
+ };
2041
2357
  const engine = createLocalEngine({
2042
2358
  aegis,
2043
2359
  settings,
2360
+ // The level's recall breadth and the persona's register fragment reach
2361
+ // turn assembly through exactly one seam (`lib/avatar/turn.js`), which is
2362
+ // pure and already owns both halves. Nothing here can mint an approval:
2363
+ // `recallPolicy()` keeps `approvalFields` at 0, so a level cannot widen
2364
+ // blast radius through the prompt.
2365
+ recallProvider: ({ system }) =>
2366
+ require('./lib/avatar/turn.js').composeSystemPrompt(system, {
2367
+ capabilities: avatarCaps(),
2368
+ persona: avatar.readPersona().persona,
2369
+ deep: false,
2370
+ }).system,
2044
2371
  // The outcome bound (~/plan/agent-safety-plan.md §1b). The engine decides WHEN
2045
2372
  // to ask and what the policy is; this host decides only that it is wanted.
2046
2373
  // The stored policy (Settings › sandbox) is preferred, and `null` there means
@@ -2076,7 +2403,7 @@ function createEngine(aegis, { app, safeStorage, dir: dirOverride, sessionsDir:
2076
2403
  // userData/sessions.json, once, when the shared store is still empty, so an
2077
2404
  // upgrade does not look like every conversation was deleted.
2078
2405
  const sessionsDir = sessionsOverride || sessionStore.resolveStoreDir(settingsDir);
2079
- return { engine, sessionsDir, settingsDir, settings };
2406
+ return { engine, sessionsDir, settingsDir, settings, avatar };
2080
2407
  }
2081
2408
 
2082
2409
  /** Largest pre-edit read the diff bridge will hand the renderer (bytes). */
@@ -2711,26 +3038,78 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2711
3038
  auto: () => autoPush.auto(),
2712
3039
  memoryPersistState: () => autoPush.gate(),
2713
3040
  listSessions: () => ({ sessions: sessions.listSessions(dir) }),
2714
- // The SESSION search the menu's "Search sessions…" (Cmd/Ctrl+K) runs. It
2715
- // lives here, not in the renderer, for the same reason the list does: the
2716
- // store is a main-process file, and `listSessions()` truncates — it returns
2717
- // title/messages/updatedAt, so a renderer-side filter would be a second,
2718
- // weaker copy of the same read. `searchSessions` takes the query and returns
2719
- // the ranked matches plus WHICH field matched, so the row can say why it is
2720
- // in the list. An empty query returns the newest N unchanged, so the sheet
2721
- // opens on something instead of a blank pane.
3041
+ // The ONE search the menu's "Search" (Cmd/Ctrl+K) runs — sessions AND
3042
+ // memory under a single query box.
2722
3043
  //
2723
- // The ranking is `client/session-search.js` — the same module the CLI's
2724
- // /resume picker filters with, so the two faces cannot order the same
2725
- // conversation differently.
3044
+ // It used to be two sheets on two accelerators: Cmd/Ctrl+K searched
3045
+ // sessions, Cmd/Ctrl+Shift+K opened the memory inspector. Same verb, two
3046
+ // surfaces, and neither could answer "I know I wrote this down somewhere".
3047
+ // This channel now returns both stores in one payload so the renderer can
3048
+ // paint one list; the inspector keeps its own door in the Memory pane.
3049
+ //
3050
+ // Why the ranking is HERE and not in the renderer: both stores are
3051
+ // main-process files (sessions.json, memory.db), and `listSessions()`
3052
+ // truncates — it returns title/messages/updatedAt — so a renderer-side
3053
+ // filter would be a second, weaker copy of the same read.
3054
+ //
3055
+ // The session ranking is `client/session-search.js`, the same module the
3056
+ // CLI's /resume picker filters with, so the two faces cannot order the same
3057
+ // conversation differently. Memory ranks through `memory-store.js`'s own
3058
+ // `search()`, which is FTS5 when the build has it — its tiers are not
3059
+ // comparable to the session tiers, which is exactly why the sheet draws the
3060
+ // two groups as SECTIONS with a flat cursor order rather than one
3061
+ // cross-type column.
3062
+ //
3063
+ // An empty query returns the newest N of each, so the sheet opens on
3064
+ // something instead of a blank pane.
2726
3065
  searchSessions: (payload) => {
2727
3066
  const query = payload && typeof payload.query === 'string' ? payload.query : '';
2728
3067
  const limit = Number.isInteger(payload && payload.limit) ? payload.limit : 50;
3068
+ const cap = Math.max(1, limit);
2729
3069
  const all = sessions.listSessions(dir) || [];
2730
- const ranked = sessionSearch.rankSessions(query, all).slice(0, Math.max(1, limit));
3070
+ const ranked = sessionSearch.rankSessions(query, all).slice(0, cap);
3071
+ // Memory is READ-ONLY here: `search()` is a local index read, never a
3072
+ // cloud round trip, so a keystroke cannot cost the user a metered call.
3073
+ // An unavailable index (no SQLite in this build) is an empty section, not
3074
+ // an error — a search that still works for sessions beats one that fails
3075
+ // because the other store is missing.
3076
+ let memory = [];
3077
+ let memoryTotal = 0;
3078
+ // `ok` | `unavailable` (no SQLite in this build) | `error` (index exists
3079
+ // but could not be read). The renderer must tell these apart: reporting
3080
+ // "0 memories" would claim the store is empty when the truth is that it
3081
+ // was never searched.
3082
+ let memoryStatus = 'ok';
3083
+ try {
3084
+ const index = memoryIndex(dir);
3085
+ if (index) {
3086
+ const found = index.search(query, { limit: cap });
3087
+ if (found && found.ok) {
3088
+ memory = (found.results || []).map((r) => ({
3089
+ id: r.id,
3090
+ content: r.body || '',
3091
+ scope: r.scope || '',
3092
+ tags: Array.isArray(r.tags) ? r.tags : [],
3093
+ updated: r.updated || null,
3094
+ }));
3095
+ memoryTotal = index.count();
3096
+ } else {
3097
+ memoryStatus = 'error';
3098
+ }
3099
+ } else {
3100
+ memoryStatus = memoryStore.isAvailable() && dir ? 'error' : 'unavailable';
3101
+ }
3102
+ } catch {
3103
+ memory = [];
3104
+ memoryTotal = 0;
3105
+ memoryStatus = 'error';
3106
+ }
2731
3107
  return {
2732
3108
  query,
2733
3109
  total: all.length,
3110
+ memoryStatus,
3111
+ memoryTotal,
3112
+ memory,
2734
3113
  sessions: ranked.map((s) => ({
2735
3114
  id: s && s.id,
2736
3115
  title: (s && s.title) || (s && s.id) || 'untitled',
@@ -2756,6 +3135,20 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2756
3135
  ),
2757
3136
  delete: (payload) =>
2758
3137
  sessions.deleteSession(dir, payload && payload.sessionId),
3138
+ // Rename a thread by hand (the library pane's Rename button).
3139
+ //
3140
+ // `renameSession`, not `setTitle`: lib/sync/sessions.js explains at length
3141
+ // why the shared store's `setTitle` is deliberately NOT re-exported under
3142
+ // that name (client/naming.js duck-checks it to decide whether to spend a
3143
+ // model round). The write it performs is the same one, marked `named` so
3144
+ // no later naming round can overwrite a name the user typed. An empty
3145
+ // title is refused rather than written — blanking a name is not a rename.
3146
+ rename: (payload) =>
3147
+ sessions.renameSession(
3148
+ dir,
3149
+ payload && payload.sessionId,
3150
+ payload && payload.title
3151
+ ),
2759
3152
  // The naming ladder (client/naming.js), run in the MAIN process.
2760
3153
  //
2761
3154
  // The window used to name a thread `prompt.slice(0, 60)` — in the renderer,
@@ -2794,7 +3187,15 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2794
3187
  prompt: text,
2795
3188
  system: opts.system,
2796
3189
  maxTokens: 64,
2797
- sessionId,
3190
+ // NOT the turn's `sessionId`. The engine keys its cancel registry
3191
+ // by that id (lib/local/engine.js `controllers`), and the desktop
3192
+ // reuses the conversation id for the turn it is streaming — so a
3193
+ // naming round sharing it fought the live turn for the Stop
3194
+ // button. The engine now refuses to lose the turn's controller
3195
+ // either way, but a decoration should not be claiming the turn's
3196
+ // identity in the first place: approvals, round counts and
3197
+ // cancellation all hang off this id, and naming is none of them.
3198
+ sessionId: `${sessionId}:naming`,
2798
3199
  // `tools: false` is the engine's own opt-out (a naming round must
2799
3200
  // not run the agent loop); nothing else here is a wire field.
2800
3201
  tools: false,
@@ -2805,8 +3206,20 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
2805
3206
  return null;
2806
3207
  }
2807
3208
  };
3209
+ // `sessions.namingStore`, not `sessions`: the binding deliberately does
3210
+ // not carry a bare `setTitle`, because naming.js arms itself on that
3211
+ // name and an incidental re-export would turn a model round per
3212
+ // conversation on invisibly (see lib/sync/sessions.js). Passing the
3213
+ // adapter is what arms it, here, on purpose — this ladder was dead for
3214
+ // as long as the binding was handed over directly.
2808
3215
  try {
2809
- return await namingLib.nameSession(sessions, dir, sessionId, prompt, { callModel });
3216
+ return await namingLib.nameSession(
3217
+ sessions.namingStore,
3218
+ dir,
3219
+ sessionId,
3220
+ prompt,
3221
+ { callModel }
3222
+ );
2810
3223
  } catch {
2811
3224
  return null;
2812
3225
  }
@@ -3024,10 +3437,16 @@ function registerModelIpc(ipcMain, engine, sessionsDir, aegis, onReplyFinished,
3024
3437
  // here. The stack does not survive anything useful.
3025
3438
  const status = err && typeof err.status === 'number' ? err.status : 0;
3026
3439
  const code = (err && err.code) || '';
3027
- console.warn(
3028
- `[model] background ${lane} turn produced no answer: ${errorText(err)}` +
3029
- `${status ? ` (status ${status})` : ''}${code ? ` [${code}]` : ''}`
3030
- );
3440
+ // Quiet by default — see backgroundLaneLogs(). A background lane
3441
+ // stalling on boot is a fact about the provider, not about this
3442
+ // app, and saying it in the terminal made a healthy launch read as
3443
+ // a failure. AEGIS_DEBUG=1 restores the line for diagnosis.
3444
+ if (backgroundLaneLogs()) {
3445
+ console.warn(
3446
+ `[model] background ${lane} turn produced no answer: ${errorText(err)}` +
3447
+ `${status ? ` (status ${status})` : ''}${code ? ` [${code}]` : ''}`
3448
+ );
3449
+ }
3031
3450
  // Resolved, so Electron does not print the rejection and the lane
3032
3451
  // that asked can read "nothing came back" without a try/catch.
3033
3452
  // `bestEffortFailed` is the discriminator; the empty content keeps
@@ -3576,7 +3995,29 @@ function createAutoDispatch({ autoDrain, autoMint } = {}) {
3576
3995
  * drain/proceed to set `target` would make an automatic drain's progress
3577
3996
  * invisible in exactly that case, and an invisible drain reads as a hang.
3578
3997
  */
3579
- function registerQueueIpc(ipcMain, { engine, env, queue, autonomous, entitlement, aegis } = {}) {
3998
+ /**
3999
+ * Every live window, for a broadcast. Resolved lazily through `require` rather
4000
+ * than injected from the top of this file because electron may be absent (a
4001
+ * plain `node` test of this module): a missing BrowserWindow means "no windows
4002
+ * to tell", which must degrade to a no-op rather than a throw inside a mutation.
4003
+ */
4004
+ function liveAppWindows() {
4005
+ try {
4006
+ const electron = require('electron');
4007
+ const BrowserWindow = electron && electron.BrowserWindow;
4008
+ if (!BrowserWindow || typeof BrowserWindow.getAllWindows !== 'function') return [];
4009
+ return BrowserWindow.getAllWindows().filter((win) => win
4010
+ && typeof win.send === 'function'
4011
+ && !(typeof win.isDestroyed === 'function' && win.isDestroyed()));
4012
+ } catch {
4013
+ return [];
4014
+ }
4015
+ }
4016
+
4017
+ function registerQueueIpc(
4018
+ ipcMain,
4019
+ { engine, env, queue, autonomous, entitlement, aegis, windows = liveAppWindows } = {},
4020
+ ) {
3580
4021
  // The window a drain's frames go to. One drain runs at a time process-wide
3581
4022
  // (queue.js's lock), so a single target is enough, and a second window's
3582
4023
  // drain is refused by the lock rather than interleaving two progress streams.
@@ -3617,6 +4058,27 @@ function registerQueueIpc(ipcMain, { engine, env, queue, autonomous, entitlement
3617
4058
  }
3618
4059
  : undefined,
3619
4060
  });
4061
+ // Tell every window the queue file moved. Broadcast rather than `target`:
4062
+ // the writer may be a timer or another process, so "the window that asked"
4063
+ // is either absent or no longer the one displaying the card. A window that
4064
+ // died between the snapshot and the send must not fail the mutation that is
4065
+ // already committed to disk, so each send is isolated.
4066
+ const notifyChanged = () => {
4067
+ let list = [];
4068
+ try {
4069
+ list = windows() || [];
4070
+ } catch {
4071
+ list = [];
4072
+ }
4073
+ for (const win of list) {
4074
+ try {
4075
+ win.send(QUEUE_CHANGED_CHANNEL, { at: Date.now() });
4076
+ } catch {
4077
+ // One dead window, not a failed enqueue.
4078
+ }
4079
+ }
4080
+ };
4081
+
3620
4082
  const dispatch = createQueueDispatch({
3621
4083
  engine,
3622
4084
  env,
@@ -3624,6 +4086,11 @@ function registerQueueIpc(ipcMain, { engine, env, queue, autonomous, entitlement
3624
4086
  autonomous,
3625
4087
  entitlement: resolved,
3626
4088
  log: (event) => {
4089
+ // A worker frame that SETTLES a task is a mutation from the renderer's
4090
+ // point of view, and it is the only signal an auto-drain tick emits —
4091
+ // that drain has no click behind it, so without this the card keeps
4092
+ // showing the task as pending for the whole tick and after it.
4093
+ if (event && event.type === 'finish') notifyChanged();
3627
4094
  if (!target || typeof target.send !== 'function') return;
3628
4095
  if (typeof target.isDestroyed === 'function' && target.isDestroyed()) return;
3629
4096
  target.send(QUEUE_PROGRESS_CHANNEL, event);
@@ -3632,7 +4099,21 @@ function registerQueueIpc(ipcMain, { engine, env, queue, autonomous, entitlement
3632
4099
  for (const [name, handler] of Object.entries(dispatch)) {
3633
4100
  ipcMain.handle(`${QUEUE_PREFIX}${name}`, (event, payload) => {
3634
4101
  target = (event && event.sender) || null;
3635
- return handler(payload);
4102
+ const result = handler(payload);
4103
+ if (!QUEUE_MUTATING_METHODS.has(name)) return result;
4104
+ // After the mutation has actually landed, never before: a listener that
4105
+ // re-reads on the push must not see the pre-write file. `enqueue`,
4106
+ // `drain` and `proceed` are async, so this waits for their own settle —
4107
+ // and notifies on rejection too, because a failed drain still moved the
4108
+ // task it claimed.
4109
+ if (result && typeof result.then === 'function') {
4110
+ return result.then(
4111
+ (value) => { notifyChanged(); return value; },
4112
+ (err) => { notifyChanged(); throw err; },
4113
+ );
4114
+ }
4115
+ notifyChanged();
4116
+ return result;
3636
4117
  });
3637
4118
  }
3638
4119
  return dispatch;
@@ -3959,7 +4440,7 @@ function createNpmUpdateManager({
3959
4440
  // the unchanged original. It gets the same version news, addressed to
3960
4441
  // the install that actually owns it.
3961
4442
  command: packaged
3962
- ? `${res.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`
4443
+ ? `${res.latest} is published — reinstall aegis one from the installer to pick it up`
3963
4444
  : (plan && plan.instruction) || `npm i -g ${PKG}@latest`,
3964
4445
  // Whether `command` is something to TYPE or a sentence to READ. The
3965
4446
  // banner otherwise prefixes "run:" to it, which is right for
@@ -4221,8 +4702,7 @@ function sendDeepLinkToWindow(win, parsed) {
4221
4702
 
4222
4703
  /** Application menu: the platform defaults (Edit roles, mac's app/quit
4223
4704
  * items) plus the native-shell accelerators this plan adds — New Chat
4224
- * (Cmd/Ctrl+N), Search sessions… (Cmd/Ctrl+K), Search memory…
4225
- * (Cmd/Ctrl+Shift+K), Reload (Cmd/Ctrl+R) and Toggle DevTools
4705
+ * (Cmd/Ctrl+N), Search (Cmd/Ctrl+K), Reload (Cmd/Ctrl+R) and Toggle DevTools
4226
4706
  * (Cmd/Ctrl+Shift+I) are plain Electron roles that already carry the right
4227
4707
  * accelerator on every platform — plus a manual "Check for Updates…" entry,
4228
4708
  * since the automatic checks in createUpdateManager.start() only run on ready
@@ -4234,8 +4714,9 @@ function sendDeepLinkToWindow(win, parsed) {
4234
4714
  *
4235
4715
  * * Cmd/Ctrl+K opened the MEMORY inspector while the item said "Search…", so
4236
4716
  * the label named neither the sheet nor the thing the user wanted. The
4237
- * chord now goes to a real session search (client/session-search.js); the
4238
- * inspector keeps its own item on its own chord instead of sharing one.
4717
+ * chord now goes to one search over sessions AND memory (sessions ranked by
4718
+ * client/session-search.js, memory by memory-store.js), and the two are
4719
+ * drawn as sections of a single list rather than as two sheets.
4239
4720
  * * There was no licence surface anywhere in the app. `Help` is now on every
4240
4721
  * platform and leads with Credits & Licence, which renders
4241
4722
  * client/credits.js — the licence, the program notice and every vendored
@@ -4270,25 +4751,90 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
4270
4751
  accelerator: 'CmdOrCtrl+N',
4271
4752
  click: () => sendToAppWindow(BrowserWindow, MENU_NEW_CHAT_CHANNEL),
4272
4753
  };
4273
- // View > Search sessions… (Cmd/Ctrl+K).
4754
+ // View > Search (Cmd/Ctrl+K).
4274
4755
  //
4275
- // This item used to be labelled `Search…` and opened the MEMORY inspector — the
4276
- // accelerator, the label and the sheet disagreed about what they were for, and
4277
- // nothing in the app searched conversations at all. A session search is now a
4278
- // thing that exists (renderer/openSessionSearch in app.js, ranked by
4279
- // client/session-search.js), so the plain accelerator goes to the thing the
4280
- // label promises; the inspector keeps a menu item of its own below.
4756
+ // Two corrections live in this item's history. It once said `Search…` and
4757
+ // opened the MEMORY inspector, so the accelerator, the label and the sheet
4758
+ // disagreed. It then said `Search sessions…` and searched only conversations,
4759
+ // while memory kept a parallel sheet on Cmd/Ctrl+Shift+K — one verb, two
4760
+ // surfaces, and no way to answer "I know I wrote this down somewhere".
4761
+ // It is now one sheet over both stores (see `searchSessions` above), so the
4762
+ // label promises exactly what the sheet does and stops naming one store.
4281
4763
  const searchItem = {
4282
- label: 'Search sessions…',
4764
+ label: 'Search',
4283
4765
  accelerator: 'CmdOrCtrl+K',
4284
4766
  click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_CHANNEL),
4285
4767
  };
4286
- // View > Search memory… — the inspector that Cmd/Ctrl+K used to open. Shift
4287
- // because the plain chord is the session search now; the two are separate
4288
- // sheets, so they cannot share a keystroke.
4768
+ // View > Command palette (Cmd/Ctrl+P).
4769
+ //
4770
+ // NOT Cmd/Ctrl+K: that chord already opens the search sheet above, and a
4771
+ // palette that stole it would either break a chord users know or make the
4772
+ // palette secretly mean "search". The palette is a superset of reach over
4773
+ // handlers that already exist (see renderer/commands.js), so it earns its
4774
+ // own chord rather than renaming someone else's.
4775
+ const paletteItem = {
4776
+ label: 'Command palette…',
4777
+ accelerator: 'CmdOrCtrl+P',
4778
+ click: () => sendToAppWindow(BrowserWindow, MENU_PALETTE_CHANNEL),
4779
+ };
4780
+ // View > Toggle sidebar (Cmd/Ctrl+B).
4781
+ //
4782
+ // Registered here for the same reason: the accelerator belongs to the menu so
4783
+ // the chord is discoverable, and the renderer owns what "collapsed" means
4784
+ // (it keeps the rail's state rather than unmounting it — see .side.is-collapsed).
4785
+ const toggleSidebarItem = {
4786
+ label: 'Toggle sidebar',
4787
+ accelerator: 'CmdOrCtrl+B',
4788
+ click: () => sendToAppWindow(BrowserWindow, MENU_TOGGLE_SIDEBAR_CHANNEL),
4789
+ };
4790
+ // Edit > Find in conversation (Cmd/Ctrl+F).
4791
+ //
4792
+ // It lives in EDIT, not View, because that is where every platform puts Find
4793
+ // and where the user's hand already goes. Distinct from View > Search
4794
+ // (Cmd/Ctrl+K): that one opens a sheet over the whole install, this one is
4795
+ // scoped to the transcript on screen and never leaves this window. Both
4796
+ // chords stay free of each other's meaning.
4797
+ const findItem = {
4798
+ label: 'Find in conversation',
4799
+ accelerator: 'CmdOrCtrl+F',
4800
+ click: () => sendToAppWindow(BrowserWindow, MENU_FIND_CHANNEL),
4801
+ };
4802
+ // View > Go Back / Go Forward.
4803
+ //
4804
+ // These were the two commands this app could not offer, because there was no
4805
+ // history to walk: views were one-shot jumps. `renderer/nav-history.js` is the
4806
+ // stack and `app.js` is what knows that an entry means Settings rather than a
4807
+ // session; this process only forwards the press.
4808
+ //
4809
+ // BOTH ITEMS ARE ALWAYS VISIBLE, never removed when there is nowhere to go. A
4810
+ // menu row that comes and goes makes the chord look broken rather than used-up.
4811
+ // They are disabled instead, driven by the renderer's report (SET_NAV_STATE) —
4812
+ // the only state about this feature that crosses the boundary.
4813
+ const goBackItem = {
4814
+ label: 'Go Back',
4815
+ accelerator: isMac ? 'Cmd+[' : 'Alt+Left',
4816
+ enabled: navState.back,
4817
+ click: () => sendToAppWindow(BrowserWindow, MENU_GO_BACK_CHANNEL),
4818
+ };
4819
+ const goForwardItem = {
4820
+ label: 'Go Forward',
4821
+ accelerator: isMac ? 'Cmd+]' : 'Alt+Right',
4822
+ enabled: navState.forward,
4823
+ click: () => sendToAppWindow(BrowserWindow, MENU_GO_FORWARD_CHANNEL),
4824
+ };
4825
+ // Cmd/Ctrl+Shift+K still opens the same sheet, pre-scoped to memory — the
4826
+ // chord people already learned keeps working, and it lands them in the one
4827
+ // search rather than a second one.
4828
+ //
4829
+ // `visible: false` is deliberate. Electron registers the accelerator of a
4830
+ // hidden item, so the key survives; what goes away is the MENU ROW that
4831
+ // advertised a separate memory search. Removing the item entirely would have
4832
+ // silently killed a chord users have muscle memory for; leaving it visible
4833
+ // would keep advertising the split this change exists to remove.
4289
4834
  const searchMemoryItem = {
4290
- label: 'Search memory…',
4835
+ label: 'Search memory',
4291
4836
  accelerator: 'CmdOrCtrl+Shift+K',
4837
+ visible: false,
4292
4838
  click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_MEMORY_CHANNEL),
4293
4839
  };
4294
4840
  // Help > Credits & licence — the AGPL licence, the program notice, and every
@@ -4377,14 +4923,22 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
4377
4923
  { role: 'copy' },
4378
4924
  { role: 'paste' },
4379
4925
  { role: 'selectAll' },
4926
+ { type: 'separator' },
4927
+ findItem,
4380
4928
  ],
4381
4929
  },
4382
4930
  {
4383
4931
  label: 'View',
4384
4932
  submenu: [
4933
+ paletteItem,
4385
4934
  searchItem,
4386
4935
  searchMemoryItem,
4387
4936
  { type: 'separator' },
4937
+ toggleSidebarItem,
4938
+ { type: 'separator' },
4939
+ goBackItem,
4940
+ goForwardItem,
4941
+ { type: 'separator' },
4388
4942
  fingerprintItem,
4389
4943
  googleDriveItem,
4390
4944
  { type: 'separator' },
@@ -4604,7 +5158,138 @@ function bootstrap() {
4604
5158
  return;
4605
5159
  }
4606
5160
 
4607
- app.setName('AEGIS Desktop');
5161
+ app.setName('aegis one');
5162
+
5163
+ // The rename from "AEGIS Desktop" to "aegis one" moves Electron's userData
5164
+ // root (`~/.config/aegis one` on Linux, `%APPDATA%\aegis one` on Windows,
5165
+ // `~/Library/Application Support/aegis one` on macOS) — and with it every
5166
+ // byte of state this host owns: settings.json, the account key in
5167
+ // safeStorage, sessions.json, the queue and the XP ledger. A plain rename
5168
+ // of the app would therefore look to an existing user exactly like a fresh
5169
+ // install that lost all their chats.
5170
+ //
5171
+ // So before anything reads the path, adopt the old root in place: if the
5172
+ // new directory does not exist yet and the legacy one does, move it. This
5173
+ // runs before the first getPath('userData') call anywhere in this file
5174
+ // (the settings store is built later, inside bootstrap()), which is the
5175
+ // only window where the path can still be chosen.
5176
+ //
5177
+ // A failure here is never fatal: falling back to setPath keeps the data
5178
+ // readable under its old name rather than starting the user empty, and an
5179
+ // install with neither directory is simply a first run.
5180
+ try {
5181
+ const userDataDir = app.getPath('userData');
5182
+ // TWO prior names, not one. `aegis one` is the third name this app has
5183
+ // shipped under: "AEGIS Desktop" (the packaged identity in
5184
+ // electron-builder.yml, still frozen) is what the first installs wrote, and
5185
+ // "AEGIS One" is the casing a short-lived build used. A user can arrive
5186
+ // from either, so both are candidates and neither is assumed to exist.
5187
+ const parentDir = path.dirname(userDataDir);
5188
+ const LEGACY_NAMES = ['AEGIS Desktop', 'AEGIS One'];
5189
+ // Electron creates the userData directory eagerly, and a single launch of
5190
+ // this version before the guard was correct leaves a NON-empty root full of
5191
+ // Chromium profile junk (Cache/, GPUCache/, Local Storage/, Preferences,
5192
+ // DIPS, Trust Tokens…) plus a stub settings.json. Testing "is the
5193
+ // directory empty" was therefore not enough — it is non-empty, yet contains
5194
+ // none of the user's chats — and the adoption silently never ran, stranding
5195
+ // sessions.json, the memory DB and the avatar under the old name.
5196
+ //
5197
+ // So decide on *user state*, not directory occupancy: a fresh Chromium
5198
+ // profile can never manufacture sessions.json, queue.jsonl, the avatar dir
5199
+ // or an xp ledger. memory.db is deliberately NOT a marker — the app creates
5200
+ // an empty one on first launch, so its presence proves nothing either way.
5201
+ const STATE_ENTRIES = ['sessions.json', 'avatar', 'xp.json', 'queue.jsonl', 'memory.db', 'settings.json'];
5202
+ const isDir = (p) => {
5203
+ try {
5204
+ return fs.statSync(p).isDirectory();
5205
+ } catch {
5206
+ return false;
5207
+ }
5208
+ };
5209
+ const sizeOf = (p) => {
5210
+ try {
5211
+ return fs.statSync(p).size;
5212
+ } catch {
5213
+ return -1;
5214
+ }
5215
+ };
5216
+ // settings.json only counts as state when it carries the account key; the
5217
+ // stub a pre-migration launch wrote holds nothing but __quickLauncher.
5218
+ const hasAccountKey = (dir) => {
5219
+ try {
5220
+ return fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes('"__aegis"');
5221
+ } catch {
5222
+ return false;
5223
+ }
5224
+ };
5225
+ const hasUserState = (dir) => {
5226
+ if (!isDir(dir)) return false;
5227
+ let names;
5228
+ try {
5229
+ names = fs.readdirSync(dir);
5230
+ } catch {
5231
+ return false;
5232
+ }
5233
+ // A real conversation store, avatar or XP ledger can only come from the
5234
+ // user. memory.db is deliberately NOT a marker: the app creates a small
5235
+ // empty one on first launch, so its presence proves nothing either way.
5236
+ if (['sessions.json', 'avatar', 'xp.json', 'queue.jsonl'].some((n) => names.includes(n))) return true;
5237
+ return hasAccountKey(dir);
5238
+ };
5239
+ const isEmptyDir = (p) => isDir(p) && fs.readdirSync(p).length === 0;
5240
+
5241
+ // Prefer whichever legacy root actually carries state; among two that do,
5242
+ // take the larger sessions.json (the more recently used install).
5243
+ const legacyDir = LEGACY_NAMES.map((n) => path.join(parentDir, n))
5244
+ .filter((d) => hasUserState(d))
5245
+ .sort((a, b) => sizeOf(path.join(b, 'sessions.json')) - sizeOf(path.join(a, 'sessions.json')))[0];
5246
+
5247
+ if (legacyDir && !hasUserState(userDataDir)) {
5248
+ try {
5249
+ if (!fs.existsSync(userDataDir) || isEmptyDir(userDataDir)) {
5250
+ // Nothing in the way: adopt the whole root in place. rename(2) can
5251
+ // replace an existing *empty* target on POSIX but not on Windows, so
5252
+ // drop the placeholder first to keep both platforms on one path.
5253
+ if (fs.existsSync(userDataDir)) fs.rmdirSync(userDataDir);
5254
+ fs.renameSync(legacyDir, userDataDir);
5255
+ } else {
5256
+ // The new root already holds profile junk from a launch that predates
5257
+ // this fix, so it cannot be replaced wholesale. Move the user-state
5258
+ // entries across one by one, and replace the two files a pre-fix
5259
+ // launch seeded with a worthless stub — leaving those in place is what
5260
+ // would strand the account key and the memory DB under the old name
5261
+ // even though the chats themselves came across.
5262
+ const moved = [];
5263
+ for (const name of STATE_ENTRIES) {
5264
+ const from = path.join(legacyDir, name);
5265
+ const to = path.join(userDataDir, name);
5266
+ if (!fs.existsSync(from)) continue;
5267
+ const exists = fs.existsSync(to);
5268
+ if (exists) {
5269
+ const replaceable =
5270
+ (name === 'settings.json' && hasAccountKey(legacyDir) && !hasAccountKey(userDataDir)) ||
5271
+ (name === 'memory.db' && sizeOf(from) > sizeOf(to));
5272
+ if (!replaceable) continue;
5273
+ fs.rmSync(to, { recursive: true, force: true });
5274
+ }
5275
+ fs.renameSync(from, to);
5276
+ moved.push(name);
5277
+ }
5278
+ if (moved.length) console.warn(`aegis: adopted user state from ${legacyDir}: ${moved.join(', ')}`);
5279
+ }
5280
+ } catch (moveErr) {
5281
+ // Different device or a locked file: point the app at the old root
5282
+ // instead. Deprecated name, but the user keeps their data.
5283
+ console.warn(
5284
+ `aegis: could not move ${legacyDir} -> ${userDataDir} ` +
5285
+ `(${moveErr && moveErr.message}); reading the old location instead`
5286
+ );
5287
+ app.setPath('userData', legacyDir);
5288
+ }
5289
+ }
5290
+ } catch (renameErr) {
5291
+ console.warn(`aegis: userData adoption skipped: ${renameErr && renameErr.message}`);
5292
+ }
4608
5293
 
4609
5294
  // Read ~/.aegiscode/.env into process.env once, before anything resolves a
4610
5295
  // key (resolveStartupKey() later in this function, and every BYOK provider
@@ -4654,7 +5339,7 @@ function bootstrap() {
4654
5339
  // One settings store backs both the provider settings surface and the AEGIS
4655
5340
  // API key entry. It lives only in the main process and encrypts keys at rest
4656
5341
  // via Electron safeStorage (best-effort base64 when unavailable).
4657
- const { engine, sessionsDir, settingsDir, settings } = createEngine(aegis, {
5342
+ const { engine, sessionsDir, settingsDir, settings, avatar } = createEngine(aegis, {
4658
5343
  app,
4659
5344
  safeStorage,
4660
5345
  dir: dataDir,
@@ -4813,7 +5498,7 @@ function bootstrap() {
4813
5498
  if (!win || win.isDestroyed()) return;
4814
5499
  if (win.isFocused() && win.isVisible()) return;
4815
5500
  if (!Notification || !Notification.isSupported()) return;
4816
- const note = new Notification({ title: 'AEGIS Desktop', body: 'Reply ready' });
5501
+ const note = new Notification({ title: 'aegis one', body: 'Reply ready' });
4817
5502
  note.on('click', () => {
4818
5503
  if (win.isDestroyed()) return;
4819
5504
  if (win.isMinimized()) win.restore();
@@ -4858,7 +5543,8 @@ function bootstrap() {
4858
5543
  (url) => shell.openExternal(url),
4859
5544
  handleReplyFinished,
4860
5545
  () => providerRouteConfigured(engine),
4861
- () => settings.vaultBackendConfig().backend
5546
+ () => settings.vaultBackendConfig().backend,
5547
+ avatar
4862
5548
  );
4863
5549
  const modelIpc = registerModelIpc(
4864
5550
  ipcMain,
@@ -4886,6 +5572,8 @@ function bootstrap() {
4886
5572
  // the CLI, which shares this store.
4887
5573
  registerConfirmModeIpc(ipcMain, withAutoRoundsSwitch(createConfirmModeDispatch(settings), modelIpc.modelDispatch));
4888
5574
  registerConfirmModeIpc(ipcMain, createPermissionModeDispatch(settings));
5575
+ registerConfirmModeIpc(ipcMain, createFontScaleDispatch(settings));
5576
+ registerConfirmModeIpc(ipcMain, createAccentDispatch(settings));
4889
5577
 
4890
5578
  // Vault backend preference (Settings/the authorship panel → Google Drive /
4891
5579
  // AE / No sync): aegis:getVaultBackend / aegis:setVaultBackend. Registered
@@ -4915,6 +5603,25 @@ function bootstrap() {
4915
5603
  createSandboxPolicyDispatch(settings, require('./lib/local/sandbox.js'), { appDir: __dirname })
4916
5604
  );
4917
5605
 
5606
+ // The topbar's `(cli)` chip: aegis:openCliFace. `aegiscode/one` has two
5607
+ // faces and this is the one the window could not reach — it opens the
5608
+ // terminal face in a real terminal emulator, the same entry point a packaged
5609
+ // `aegiscode` launch runs (resources/faces/cli/bin/aegiscode.js under
5610
+ // Electron-as-Node). Registered here, beside the other settings-surface
5611
+ // dispatches, because it is the same generic { name: handler } wiring.
5612
+ registerConfirmModeIpc(
5613
+ ipcMain,
5614
+ createCliFaceDispatch({
5615
+ appInfo: {
5616
+ packaged: app.isPackaged,
5617
+ resourcesPath: process.resourcesPath,
5618
+ appDir: __dirname,
5619
+ execPath: process.execPath,
5620
+ nodePath: process.execPath,
5621
+ },
5622
+ })
5623
+ );
5624
+
4918
5625
  // Funnel instrumentation (Phase 2 of docs/upgrade-conversion-plan.md):
4919
5626
  // aegis:telemetryEvent / aegis:telemetryReport, backed by
4920
5627
  // lib/local/telemetry.js.
@@ -5263,6 +5970,21 @@ function bootstrap() {
5263
5970
  });
5264
5971
  registerUpdateIpc(ipcMain, updateManager);
5265
5972
  ipcMain.handle(`${IPC_PREFIX}accountStatus`, () => accountKey.status());
5973
+ // The renderer's report of whether Back/Forward would move (see app.js
5974
+ // updateNavMenu). Returns nothing useful on purpose: it is a one-way state
5975
+ // push, and the renderer's only interest is that the menu rebuilt. Cheap
5976
+ // enough to call on every push — buildAppMenu is a template literal and
5977
+ // setApplicationMenu is the native call it replaces, not an addition to it. */
5978
+ ipcMain.handle(`${IPC_PREFIX}setNavState`, (_event, payload) => {
5979
+ const next = payload && typeof payload === 'object' ? payload : {};
5980
+ const back = Boolean(next.back);
5981
+ const forward = Boolean(next.forward);
5982
+ if (back === navState.back && forward === navState.forward) return { ok: true };
5983
+ navState.back = back;
5984
+ navState.forward = forward;
5985
+ rebuildAppMenu();
5986
+ return { ok: true };
5987
+ });
5266
5988
  ipcMain.handle(`${IPC_PREFIX}registerAccount`, () => accountKey.registerAccount());
5267
5989
  // Google sign-in + Drive connect/sync (lib/google-connect.js). Every call
5268
5990
  // resolves `{ ok, … }` / `{ ok: false, error }` rather than throwing, same
@@ -5360,7 +6082,30 @@ function bootstrap() {
5360
6082
  // app had failed to open.
5361
6083
  show: true,
5362
6084
  backgroundColor: '#0d1117',
5363
- title: 'AEGIS Desktop',
6085
+ title: 'aegis one',
6086
+ // DECISION (2026-11-15, explicit user request — see git blame before
6087
+ // changing this block again): keep the real OS window — native title
6088
+ // bar, native taskbar/alt-tab entry, native menu bar — but let THIS app
6089
+ // paint the strip behind the OS's own min/max/close buttons so it reads
6090
+ // as part of the UI instead of a mismatched light-grey bar on top of a
6091
+ // dark app. That is `titleBarStyle: 'hidden'` + `titleBarOverlay`, NOT
6092
+ // `frame: false`. Two earlier passes tried frame:false with a hand-built
6093
+ // #win-controls (custom buttons, their own IPC round trip, a boot-time
6094
+ // race against windowState's maximize()) — real surface for a result
6095
+ // that still wasn't the OS's own button, just a drawing of one, and the
6096
+ // user explicitly asked for the OS one back. `titleBarOverlay` keeps the
6097
+ // native click target/double-click-to-maximize/accessibility and just
6098
+ // recolours the strip; `height: 35` matches `.topbar`'s own measured
6099
+ // height (style.css) so the overlay and the in-page strip read as one
6100
+ // bar. There is no more #win-controls markup, no windowMinimize/
6101
+ // windowMaximize/windowClose IPC, and no WINDOW_STATE_CHANGED_CHANNEL —
6102
+ // the OS owns the buttons now, so none of that plumbing has a job.
6103
+ titleBarStyle: 'hidden',
6104
+ titleBarOverlay: {
6105
+ color: '#111114',
6106
+ symbolColor: '#94a2b6',
6107
+ height: 35,
6108
+ },
5364
6109
  icon: iconForPlatform(iconsDir, process.platform),
5365
6110
  webPreferences: {
5366
6111
  preload: path.join(__dirname, 'preload.js'),
@@ -5631,6 +6376,8 @@ module.exports = {
5631
6376
  MENU_SEARCH_CHANNEL,
5632
6377
  MENU_SEARCH_MEMORY_CHANNEL,
5633
6378
  MENU_CREDITS_CHANNEL,
6379
+ MENU_PALETTE_CHANNEL,
6380
+ MENU_TOGGLE_SIDEBAR_CHANNEL,
5634
6381
  MENU_EXPORT_MARKDOWN_CHANNEL,
5635
6382
  MENU_EXPORT_JSON_CHANNEL,
5636
6383
  MENU_FINGERPRINT_CHANNEL,
@@ -5684,6 +6431,7 @@ module.exports = {
5684
6431
  registerConfirmModeIpc,
5685
6432
  QUEUE_PREFIX,
5686
6433
  QUEUE_PROGRESS_CHANNEL,
6434
+ QUEUE_CHANGED_CHANNEL,
5687
6435
  QUEUE_MAX_TASK_CHARS,
5688
6436
  QUEUE_MAX_ROUNDS,
5689
6437
  createQueueEngine,