herdr-gentle-shell 1.6.2 → 1.8.0

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.
@@ -275,7 +275,6 @@
275
275
  import net from "node:net";
276
276
  import { createHash, randomUUID } from "node:crypto";
277
277
  import { spawn, spawnSync } from "node:child_process";
278
- import { generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
279
278
  import * as fs from "node:fs";
280
279
  import { homedir } from "node:os";
281
280
  import { delimiter as pathDelimiter, dirname, join, resolve as resolvePath, relative as pathRelative, basename as pathBasename, isAbsolute as pathIsAbsolute } from "node:path";
@@ -294,7 +293,15 @@ const nodeRequire = createRequire(import.meta.url);
294
293
  // are the only surface the harness extracts.
295
294
 
296
295
  export const PRESENCE_HEADER_LIMIT = 16 * 1024;
297
- export const PRESENCE_ACTIVITY_LIMIT = 16 * 1024 * 1024;
296
+ // The activity read is synchronous and runs on the agent's own event loop on
297
+ // every beat, so this ceiling is a cost the session pays rather than a hostile
298
+ // file's business alone. The envelope the writer emits is bounded by the same
299
+ // caps the reader honours (128 tracked tasks, ≤120-char labels): 16× the header
300
+ // limit covers that worst case with margin, and keeps the per-beat parse in
301
+ // single-digit milliseconds instead of the hundreds of milliseconds a 16 MiB
302
+ // ceiling allowed. An oversized file still resolves to no snapshot, never a
303
+ // partial one.
304
+ export const PRESENCE_ACTIVITY_LIMIT = 256 * 1024;
298
305
  export const PRESENCE_FRESH_MS = 15_000;
299
306
  export const PRESENCE_MAX_DIR_ENTRIES = 128;
300
307
  export const PRESENCE_MAX_WITNESSED = 256;
@@ -1303,138 +1310,6 @@ export function computeNativeState({
1303
1310
  return undefined;
1304
1311
  }
1305
1312
 
1306
- // ---------------------------------------------------------------------------
1307
- // Live session-changes metric (S62: authoritative publisher, never transcript)
1308
- //
1309
- // Gentle-shell shows the CURRENT working tree against HEAD for the session's
1310
- // subscribed roots. The transcript aggregate below (aggregateChanges over
1311
- // SESSION_CHANGE_ENTRY before/after patches) is retained as legacy evidence
1312
- // for other needs but is NOT the publisher authority: beats publish the
1313
- // live Git scan instead, so external/untracked edits and scope registration
1314
- // reflect immediately with numerical equality to the reference.
1315
- // ---------------------------------------------------------------------------
1316
-
1317
- function sameSnapshot(before, after) {
1318
- return (
1319
- before?.kind === after?.kind &&
1320
- (before?.kind === "absent" ||
1321
- (before?.kind === "text" &&
1322
- after?.kind === "text" &&
1323
- before?.text === after?.text))
1324
- );
1325
- }
1326
-
1327
- function snapshotPatchText(snapshot) {
1328
- return snapshot && snapshot.kind === "text" && typeof snapshot.text === "string" ? snapshot.text : "";
1329
- }
1330
-
1331
- function unavailableReason(snapshot) {
1332
- if (snapshot?.kind === "unavailable" && typeof snapshot?.reason === "string" && snapshot.reason.length > 0) {
1333
- return snapshot.reason;
1334
- }
1335
- return "Snapshot unavailable.";
1336
- }
1337
-
1338
- // Unified-patch accounting identical to Gentle Shell
1339
- // SessionChanges.changed(): generateUnifiedPatch(path, before, after),
1340
- // enter after the first @@ hunk, count lines beginning + and -. Fail-closed
1341
- // to 0/0 so token bounds hold when the patch cannot be built.
1342
- function safePatchPath(path) {
1343
- if (typeof path !== "string") return "change";
1344
- const clean = path.replace(/[\0\r\n]/g, "").slice(0, 256);
1345
- return clean.length > 0 ? clean : "change";
1346
- }
1347
-
1348
- function patchLineCounts(pathLabel, before, after) {
1349
- try {
1350
- const patch = generateUnifiedPatch(pathLabel, before, after);
1351
- const patchLines = patch.split("\n");
1352
- const firstHunk = patchLines.findIndex((line) => line.startsWith("@@"));
1353
- const lines = firstHunk < 0 ? [] : patchLines.slice(firstHunk + 1);
1354
- return {
1355
- added: lines.filter((line) => line.startsWith("+")).length,
1356
- deleted: lines.filter((line) => line.startsWith("-")).length,
1357
- };
1358
- } catch {
1359
- return { added: 0, deleted: 0 };
1360
- }
1361
- }
1362
-
1363
- function isPlausibleEvidence(evidence) {
1364
- return (
1365
- isRecord(evidence) &&
1366
- typeof evidence.id === "string" &&
1367
- evidence.id.length > 0 &&
1368
- typeof evidence.root === "string" &&
1369
- evidence.root.length > 0 &&
1370
- typeof evidence.path === "string" &&
1371
- evidence.path.length > 0 &&
1372
- isRecord(evidence.before) &&
1373
- isRecord(evidence.after)
1374
- );
1375
- }
1376
-
1377
- function aggregateChanges(entries, sessionId) {
1378
- const seen = new Set();
1379
- const perRoot = new Map();
1380
- let paths = 0;
1381
- for (const entry of entries ?? []) {
1382
- if (!isRecord(entry) || entry.type !== "custom" || entry.customType !== CHANGE_ENTRY) continue;
1383
- const data = entry.data;
1384
- if (!isRecord(data) || data.sessionId !== sessionId || !isPlausibleEvidence(data.evidence)) continue;
1385
- const evidence = data.evidence;
1386
- if (seen.has(evidence.id)) continue;
1387
- seen.add(evidence.id);
1388
- if (sameSnapshot(evidence.before, evidence.after)) continue;
1389
- let perPath = perRoot.get(evidence.root);
1390
- if (!perPath) {
1391
- perPath = new Map();
1392
- perRoot.set(evidence.root, perPath);
1393
- }
1394
- let slot = perPath.get(evidence.path);
1395
- if (!slot) {
1396
- if (paths >= MAX_CHANGE_PATHS) continue;
1397
- paths += 1;
1398
- slot = { before: evidence.before, after: evidence.after };
1399
- if (evidence.before?.kind === "unavailable") slot.unavailable = unavailableReason(evidence.before);
1400
- if (evidence.after?.kind === "unavailable" && !slot.unavailable) {
1401
- slot.unavailable = unavailableReason(evidence.after);
1402
- }
1403
- perPath.set(evidence.path, slot);
1404
- } else {
1405
- if (!slot.unavailable && !sameSnapshot(slot.after, evidence.before)) {
1406
- slot.unavailable =
1407
- "Snapshot continuity lost (external or unobserved edit); session diff unavailable.";
1408
- }
1409
- if (evidence.before?.kind === "unavailable" && !slot.unavailable) {
1410
- slot.unavailable = unavailableReason(evidence.before);
1411
- }
1412
- if (evidence.after?.kind === "unavailable" && !slot.unavailable) {
1413
- slot.unavailable = unavailableReason(evidence.after);
1414
- }
1415
- slot.after = evidence.after;
1416
- }
1417
- }
1418
- let files = 0;
1419
- let added = 0;
1420
- let deleted = 0;
1421
- for (const perPath of perRoot.values()) {
1422
- for (const [changePath, { before, after, unavailable }] of perPath) {
1423
- if (!unavailable && sameSnapshot(before, after)) continue;
1424
- files += 1;
1425
- if (unavailable) continue;
1426
- const { added: fileAdded, deleted: fileDeleted } = patchLineCounts(
1427
- safePatchPath(changePath),
1428
- snapshotPatchText(before),
1429
- snapshotPatchText(after),
1430
- );
1431
- added += fileAdded;
1432
- deleted += fileDeleted;
1433
- }
1434
- }
1435
- return { files, added, deleted };
1436
- }
1437
-
1438
1313
  // ---------------------------------------------------------------------------
1439
1314
  // Live Git scope + scan (S62, mirrored from gentle-shell shell-changes.ts +
1440
1315
  // session-changes.ts + bounded-writer-admission.ts). Self-contained like the
@@ -1922,6 +1797,10 @@ function sidebarPublishingEnabled() {
1922
1797
  // jiti; the tests load a copy as .mjs), so it carries no type annotations.
1923
1798
  const MOSHI_AGENT = "pi";
1924
1799
  const MOSHI_MAX_CHILD_HEADER = 16 * 1024;
1800
+ // Upper bound on one envelope's socket lifetime. Long enough for a local
1801
+ // daemon to answer a session.update, short enough that a hung peer cannot tie
1802
+ // up a descriptor for the rest of the session.
1803
+ const MOSHI_SEND_TIMEOUT_MS = 2000;
1925
1804
 
1926
1805
  function moshiSocketPath() {
1927
1806
  const override = process.env.MOSHI_SOCKET_PATH;
@@ -1945,6 +1824,20 @@ function moshiSendEnvelope(envelope) {
1945
1824
  const done = new Promise((resolve) => sock.once("close", () => resolve()));
1946
1825
  moshiInFlight.add(done);
1947
1826
  void done.then(() => moshiInFlight.delete(done));
1827
+ // A peer that accepts the envelope and never finishes the connection holds
1828
+ // this socket — and its fd — in FIN_WAIT_2 for the life of the session: the
1829
+ // half-close below is not an answer from it, only a request. One bounded,
1830
+ // unref'd destroy settles the envelope either way, so `moshiInFlight`
1831
+ // always drains and a broken daemon can never accumulate open handles.
1832
+ const giveUp = setTimeout(() => {
1833
+ try {
1834
+ sock.destroy();
1835
+ } catch {
1836
+ // Already gone; the close event below still settles the promise.
1837
+ }
1838
+ }, MOSHI_SEND_TIMEOUT_MS);
1839
+ giveUp.unref?.();
1840
+ sock.once("close", () => clearTimeout(giveUp));
1948
1841
  sock.setNoDelay(true);
1949
1842
  sock.on("error", () => {
1950
1843
  try {
@@ -2146,13 +2039,13 @@ function lastFinishedLabel(taskMap) {
2146
2039
  }
2147
2040
 
2148
2041
  // ---------------------------------------------------------------------------
2149
- // `/herdr-gentle:customize`: exactly two switches, offered in the floating panel
2042
+ // `/herdr-gentle:customize`: three categories, offered in the floating panel
2150
2043
  // shaped like Gentle Shell's own card (odd/tasks/restore-customize-panel.md T1;
2151
- // odd/tasks/customize-parity-done-idle.md T1/T3).
2044
+ // odd/tasks/customize-parity-done-idle.md T1/T3; odd/tasks/theme-sync.md T3).
2152
2045
  //
2153
2046
  // The command is registered BEFORE the `enabled()` gate in the factory below,
2154
2047
  // so it stays reachable from a plain Pi session outside a Herdr pane; the
2155
- // producer itself still needs a pane. The two switches are:
2048
+ // producer itself still needs a pane. The switches are:
2156
2049
  //
2157
2050
  // - Sidebar agent rows. The marked `[ui.sidebar.agents.rows_by_agent]` block
2158
2051
  // belongs to the Herdr plugin's own `bin/configure.js`, which is installed as
@@ -2168,6 +2061,12 @@ function lastFinishedLabel(taskMap) {
2168
2061
  // nothing at all. Disabling skips the gate and stays unconditional. A Pi
2169
2062
  // reload is requested only when the settings entry actually changed, because
2170
2063
  // that entry is the only part that waits for the next Pi extension load.
2064
+ // - Theme sync. `lib/theme-store.js` holds the one persisted document
2065
+ // (`gentle-theme.json`): whether Herdr follows the theme active in Pi (S1/S2)
2066
+ // and, with the sync off, the one theme the user pinned (S4). The toggle
2067
+ // writes that document and needs NO Pi reload — the palette lives in Herdr,
2068
+ // not in this extension — and the theme row lists `ctx.ui.getAllThemes()`
2069
+ // while refusing to change anything as long as the stored sync is on.
2171
2070
  //
2172
2071
  // No argument opens the recovered panel from lib/customize-panel.js through
2173
2072
  // `ctx.ui.custom` with the overlay options the former implementation pinned;
@@ -2181,9 +2080,32 @@ function lastFinishedLabel(taskMap) {
2181
2080
  const CUSTOMIZE_TITLE = "Customize · Herdr Gentle Shell";
2182
2081
  const CUSTOMIZE_SIDEBAR_LABEL = "Sidebar agent rows";
2183
2082
  const CUSTOMIZE_MOSHI_LABEL = "Moshi notifications";
2083
+ const CUSTOMIZE_THEME_SYNC_LABEL = "Theme sync";
2084
+ const CUSTOMIZE_THEME_LABEL = "Gentle Shell theme";
2184
2085
  const CUSTOMIZE_ON = "On";
2185
2086
  const CUSTOMIZE_OFF = "Off";
2186
2087
 
2088
+ // The theme picker's "no theme assigned" entry. It is deliberately NOT `Off`:
2089
+ // `Off` is the label the panel paints for a stored `null`
2090
+ // (THEME_OFF_LABEL in lib/theme-projection.js), and a Pi theme may legitimately
2091
+ // be named `Off`. Reusing that spelling as the sentinel would make such a theme
2092
+ // unpinnable, because selecting it would read as "clear the pin".
2093
+ const CUSTOMIZE_THEME_UNASSIGN = "Off (no theme assigned)";
2094
+
2095
+ // The row id `lib/customize-panel.js` gives the theme value row. It is not an
2096
+ // On/Off pair: the row opens the host's theme list, so the apply path keys the
2097
+ // list on this id instead of on a value it could toggle.
2098
+ const CUSTOMIZE_THEME_SELECT_ROW_ID = "select";
2099
+ const THEME_SYNC_ON_TEXT = "Theme sync on; Herdr's palette follows the theme active in Pi.";
2100
+ const THEME_SYNC_OFF_TEXT = "Theme sync off; Herdr keeps the palette it was last given.";
2101
+ // The refusal keeps S4's promise: the pinned theme is only available while the
2102
+ // sync is off, so a stored sync turns the row into a no-op with a reason.
2103
+ const THEME_SYNC_REFUSED_TEXT = "Turn Theme sync off to pick a specific theme.";
2104
+ const THEME_LIST_UNAVAILABLE_TEXT =
2105
+ "Could not read Pi's theme list (this host exposes no getAllThemes()); nothing was changed.";
2106
+ const THEME_STORE_UNAVAILABLE_TEXT =
2107
+ "Could not reach the theme store (lib/theme-store.js is unavailable); nothing was changed.";
2108
+
2187
2109
  // The former panel's geometry and overlay options, unchanged. The helpers
2188
2110
  // module (@earendil-works/pi-tui) is resolved lazily through the injectable
2189
2111
  // seam below so registering the extension never depends on it and tests can
@@ -2203,29 +2125,57 @@ export function setCustomizeTuiLoader(loader) {
2203
2125
  customizeTuiLoader = loader;
2204
2126
  }
2205
2127
 
2206
- // The panel module lives in lib/, resolved relative to this file in the
2207
- // installed package. Tests load a copy from a temp directory and point the
2128
+ // The panel and the theme store live in lib/, resolved relative to this file in
2129
+ // the installed package. Tests load a copy from a temp directory and point the
2208
2130
  // documented override at the real lib dir. A single-file deployment (the
2209
- // installed copy or symlink without sibling helpers) has no panel module, so
2210
- // the callback returns null and the command keeps the plain menu below.
2131
+ // installed copy or symlink without sibling helpers) has neither module, so the
2132
+ // panel loader returns null (keeping the plain menu below) and the theme store
2133
+ // reports `ok: false`, which the panel paints as `Unknown` instead of guessing.
2134
+ function customizeLibDir() {
2135
+ const override = process.env.GENTLE_CUSTOMIZE_LIB_DIR;
2136
+ return typeof override === "string" && override.length > 0
2137
+ ? override
2138
+ : join(dirname(fileURLToPath(import.meta.url)), "..", "lib");
2139
+ }
2140
+
2211
2141
  function customizePanelModule() {
2212
2142
  try {
2213
- const override = process.env.GENTLE_CUSTOMIZE_LIB_DIR;
2214
- const dir = typeof override === "string" && override.length > 0
2215
- ? override
2216
- : join(dirname(fileURLToPath(import.meta.url)), "..", "lib");
2217
- return nodeRequire(join(dir, "customize-panel.js"));
2143
+ return nodeRequire(join(customizeLibDir(), "customize-panel.js"));
2218
2144
  } catch {
2219
2145
  return null;
2220
2146
  }
2221
2147
  }
2222
2148
 
2149
+ function themeStoreModule() {
2150
+ try {
2151
+ return nodeRequire(join(customizeLibDir(), "theme-store.js"));
2152
+ } catch {
2153
+ return null;
2154
+ }
2155
+ }
2156
+
2157
+ // Never throws: an unreadable decision is `ok: false` with the inert defaults,
2158
+ // so the panel shows `Unknown` and the apply path refuses instead of writing a
2159
+ // value nobody chose (S7).
2160
+ function readCustomizeThemeState() {
2161
+ const inert = { ok: false, sync: false, theme: null, updatedAt: null };
2162
+ const store = themeStoreModule();
2163
+ if (!store || typeof store.readThemeState !== "function") return inert;
2164
+ try {
2165
+ const state = store.readThemeState(process.env);
2166
+ return isRecord(state) ? state : inert;
2167
+ } catch (error) {
2168
+ return { ...inert, error: `could not read the theme state: ${error?.message ?? error}` };
2169
+ }
2170
+ }
2171
+
2223
2172
  function customizePanelModel() {
2224
2173
  const panel = customizePanelModule();
2225
2174
  if (!panel) return null;
2226
2175
  return panel.customizePanelModel({
2227
2176
  sidebar: sidebarRowsState().state,
2228
2177
  moshi: moshiFlagEnabled(moshiFlagPath()) ? "on" : "off",
2178
+ theme: readCustomizeThemeState(),
2229
2179
  });
2230
2180
  }
2231
2181
 
@@ -2616,11 +2566,16 @@ function applyMoshiNotifications(want) {
2616
2566
  }
2617
2567
 
2618
2568
  // One apply path for both switches: notify once with the verdict and reload Pi
2619
- // only when the Moshi settings entry actually changed.
2569
+ // only when the Moshi settings entry actually changed. The theme switch never
2570
+ // reloads: the palette it writes belongs to Herdr, so a Pi reload would only
2571
+ // restart the extension for nothing.
2620
2572
  async function applyCustomizeSwitch(id, value, ctx) {
2573
+ const want = value === "on";
2621
2574
  const result = id === "sidebar"
2622
- ? await applySidebarRows(value === "on")
2623
- : applyMoshiNotifications(value === "on");
2575
+ ? await applySidebarRows(want)
2576
+ : id === "theme-sync"
2577
+ ? applyThemeSync(want)
2578
+ : applyMoshiNotifications(want);
2624
2579
  const notify = ctx?.ui?.notify;
2625
2580
  if (typeof notify === "function") {
2626
2581
  notify(`${result.text}${result.needsReload ? " Reloading now to apply the change." : ""}`, result.level);
@@ -2628,42 +2583,205 @@ async function applyCustomizeSwitch(id, value, ctx) {
2628
2583
  if (result.needsReload && typeof ctx?.reload === "function") await ctx.reload();
2629
2584
  }
2630
2585
 
2586
+ // The one-line spelling of the theme state, shared by `status` and the menu
2587
+ // fallback so "unknown" can never drift from what the panel shows: an unreadable
2588
+ // store names no value at all, and an unassigned theme reads as `none`.
2589
+ function themeStateLabels(state) {
2590
+ if (!state || state.ok === false) return { sync: "unknown", theme: "unknown" };
2591
+ const theme = typeof state.theme === "string" && state.theme.length > 0 ? state.theme : "none";
2592
+ return { sync: state.sync === true ? "on" : "off", theme };
2593
+ }
2594
+
2595
+ function themeStoreWriteError(error) {
2596
+ return `Could not write the theme store: ${error?.message ?? error}; nothing was changed.`;
2597
+ }
2598
+
2599
+ // S1/S2: the sync flag is the whole toggle, and the theme the user pinned is
2600
+ // carried across it untouched, so turning the sync off restores that choice
2601
+ // instead of silently unassigning it. Nothing is reloaded.
2602
+ function applyThemeSync(want) {
2603
+ const store = themeStoreModule();
2604
+ if (!store || typeof store.writeThemeState !== "function") {
2605
+ return { changed: false, needsReload: false, level: "error", text: THEME_STORE_UNAVAILABLE_TEXT };
2606
+ }
2607
+ const state = readCustomizeThemeState();
2608
+ // An unreadable document is written over rather than blocked on (the same
2609
+ // repair the sidebar switch offers), but an already-correct flag still reports
2610
+ // "already" instead of rewriting the file.
2611
+ const current = state.sync === true;
2612
+ if (current === want) {
2613
+ return {
2614
+ changed: false,
2615
+ needsReload: false,
2616
+ level: "info",
2617
+ text: `Theme sync already ${want ? "on" : "off"}; nothing was changed.`,
2618
+ };
2619
+ }
2620
+ try {
2621
+ store.writeThemeState(process.env, { sync: want, theme: state.theme ?? null });
2622
+ } catch (error) {
2623
+ return { changed: false, needsReload: false, level: "error", text: themeStoreWriteError(error) };
2624
+ }
2625
+ return {
2626
+ changed: true,
2627
+ needsReload: false,
2628
+ level: "info",
2629
+ text: want ? THEME_SYNC_ON_TEXT : THEME_SYNC_OFF_TEXT,
2630
+ };
2631
+ }
2632
+
2633
+ // `ctx.ui.getAllThemes()` documents `{ name, path }` records; a plain string list
2634
+ // is accepted too. A malformed entry is skipped instead of failing the whole
2635
+ // list, and the result is deduplicated and sorted so the prompt is stable.
2636
+ function themeNames(themes) {
2637
+ if (!Array.isArray(themes)) return null;
2638
+ const names = [];
2639
+ for (const entry of themes) {
2640
+ const name = typeof entry === "string" ? entry : isRecord(entry) ? entry.name : null;
2641
+ if (typeof name !== "string") continue;
2642
+ const clean = name.trim();
2643
+ if (clean.length > 0) names.push(clean);
2644
+ }
2645
+ return [...new Set(names)].sort();
2646
+ }
2647
+
2648
+ // The picker's entries plus the ONE entry that means "unassign". A theme really
2649
+ // named like the sentinel moves the sentinel instead of being shadowed, so every
2650
+ // theme name stays selectable and only the returned label writes `theme: null`.
2651
+ function themeSelectionOptions(names) {
2652
+ let unassign = CUSTOMIZE_THEME_UNASSIGN;
2653
+ let attempt = 2;
2654
+ while (names.includes(unassign)) {
2655
+ unassign = `${CUSTOMIZE_THEME_UNASSIGN} ${attempt}`;
2656
+ attempt += 1;
2657
+ }
2658
+ return { options: [...names, unassign], unassign };
2659
+ }
2660
+
2661
+ // S4: pin one of Pi's themes while the sync is off. The refusal, the missing
2662
+ // theme list and an empty answer all write NOTHING, so the stored document only
2663
+ // ever changes to a value the user actually picked.
2664
+ async function applyThemeSelection(ctx) {
2665
+ const notify = ctx?.ui?.notify;
2666
+ const store = themeStoreModule();
2667
+ if (!store || typeof store.writeThemeState !== "function") {
2668
+ if (typeof notify === "function") notify(THEME_STORE_UNAVAILABLE_TEXT, "warning");
2669
+ return;
2670
+ }
2671
+ if (readCustomizeThemeState().sync === true) {
2672
+ if (typeof notify === "function") notify(THEME_SYNC_REFUSED_TEXT, "warning");
2673
+ return;
2674
+ }
2675
+ const listThemes = ctx?.ui?.getAllThemes;
2676
+ if (typeof listThemes !== "function") {
2677
+ if (typeof notify === "function") notify(THEME_LIST_UNAVAILABLE_TEXT, "warning");
2678
+ return;
2679
+ }
2680
+ let themes;
2681
+ try {
2682
+ themes = listThemes.call(ctx.ui);
2683
+ } catch {
2684
+ themes = null;
2685
+ }
2686
+ const names = themeNames(themes);
2687
+ if (names === null) {
2688
+ if (typeof notify === "function") notify(THEME_LIST_UNAVAILABLE_TEXT, "warning");
2689
+ return;
2690
+ }
2691
+ const select = ctx?.ui?.select;
2692
+ if (typeof select !== "function") return;
2693
+ const picker = themeSelectionOptions(names);
2694
+ let picked;
2695
+ try {
2696
+ // The unassign entry is its own label, never the stored-value label `Off`, so
2697
+ // a theme named `Off` is pinned like any other and a way back to "no theme"
2698
+ // is always offered.
2699
+ picked = await select(CUSTOMIZE_THEME_LABEL, picker.options);
2700
+ } catch {
2701
+ picked = undefined;
2702
+ }
2703
+ // Esc/cancel and an empty answer write nothing at all.
2704
+ if (typeof picked !== "string" || picked.length === 0) return;
2705
+ const next = picked === picker.unassign ? null : picked;
2706
+ try {
2707
+ store.writeThemeState(process.env, { sync: false, theme: next });
2708
+ } catch (error) {
2709
+ if (typeof notify === "function") notify(themeStoreWriteError(error), "error");
2710
+ return;
2711
+ }
2712
+ if (typeof notify === "function") {
2713
+ notify(
2714
+ next === null
2715
+ ? "Gentle Shell theme set to Off; Herdr keeps the palette it was last given."
2716
+ : `Gentle Shell theme set to ${next}.`,
2717
+ "info",
2718
+ );
2719
+ }
2720
+ }
2721
+
2631
2722
  // The single apply path shared by the overlay and the menu fallback. The choice
2632
2723
  // the panel resolves names the switch it drives (`switchId`) and the value to
2633
2724
  // apply; that switch id is the only thing read here, so a row can never apply a
2634
2725
  // switch its category does not own. An inconclusive sidebar verdict is never a
2635
2726
  // refusal: choosing On still attempts the repair and reports the apply step's
2636
- // own error, exactly like the baseline menu did.
2637
- const CUSTOMIZE_SWITCH_IDS = ["sidebar", "moshi"];
2727
+ // own error, exactly like the baseline menu did. The theme value is the one row
2728
+ // that is not a toggle: it carries the `select` row id, and the refusal for a
2729
+ // stored sync lives in `applyThemeSelection` so both entry points share it.
2730
+ const CUSTOMIZE_SWITCH_IDS = ["sidebar", "moshi", "theme-sync", "theme"];
2638
2731
 
2639
2732
  async function applyCustomizeChoice(choice, ctx) {
2640
2733
  if (!isRecord(choice)) return;
2641
2734
  const switchId = choice.switchId;
2642
2735
  const valueId = choice.valueId;
2643
2736
  if (!CUSTOMIZE_SWITCH_IDS.includes(switchId)) return;
2737
+ if (switchId === "theme") {
2738
+ if (valueId !== CUSTOMIZE_THEME_SELECT_ROW_ID) return;
2739
+ await applyThemeSelection(ctx);
2740
+ return;
2741
+ }
2644
2742
  if (valueId !== "on" && valueId !== "off") return;
2645
2743
  await applyCustomizeSwitch(switchId, valueId, ctx);
2646
2744
  }
2647
2745
 
2648
2746
  // The former plain menu, kept as the fallback when the TUI helpers or
2649
2747
  // `ctx.ui.custom` are unavailable. It reads the same model and applies
2650
- // through the same path as the overlay.
2748
+ // through the same path as the overlay, and it offers the theme rows too, so
2749
+ // theme sync is reachable in a plain terminal.
2651
2750
  async function runCustomizeFallback(ctx) {
2652
2751
  const select = ctx?.ui?.select;
2653
2752
  if (typeof select !== "function") return;
2654
2753
  let picked = null;
2655
2754
  try {
2656
- picked = await select(CUSTOMIZE_TITLE, [CUSTOMIZE_SIDEBAR_LABEL, CUSTOMIZE_MOSHI_LABEL]);
2755
+ picked = await select(CUSTOMIZE_TITLE, [
2756
+ CUSTOMIZE_SIDEBAR_LABEL,
2757
+ CUSTOMIZE_MOSHI_LABEL,
2758
+ CUSTOMIZE_THEME_SYNC_LABEL,
2759
+ CUSTOMIZE_THEME_LABEL,
2760
+ ]);
2657
2761
  } catch {
2658
2762
  picked = undefined;
2659
2763
  }
2660
2764
  // Esc/cancel (null or undefined) writes nothing and reloads nothing.
2661
2765
  if (picked === undefined || picked === null) return;
2662
- const id = picked === CUSTOMIZE_SIDEBAR_LABEL ? "sidebar" : picked === CUSTOMIZE_MOSHI_LABEL ? "moshi" : null;
2766
+ // The theme value is not an On/Off switch: it opens the (already sorted)
2767
+ // theme list itself, so the second prompt below never applies to it.
2768
+ if (picked === CUSTOMIZE_THEME_LABEL) {
2769
+ await applyThemeSelection(ctx);
2770
+ return;
2771
+ }
2772
+ const id = picked === CUSTOMIZE_SIDEBAR_LABEL
2773
+ ? "sidebar"
2774
+ : picked === CUSTOMIZE_MOSHI_LABEL
2775
+ ? "moshi"
2776
+ : picked === CUSTOMIZE_THEME_SYNC_LABEL
2777
+ ? "theme-sync"
2778
+ : null;
2663
2779
  if (!id) return;
2664
2780
  const current = id === "sidebar"
2665
2781
  ? sidebarRowsState().state
2666
- : (moshiFlagEnabled(moshiFlagPath()) ? "on" : "off");
2782
+ : id === "theme-sync"
2783
+ ? themeStateLabels(readCustomizeThemeState()).sync
2784
+ : (moshiFlagEnabled(moshiFlagPath()) ? "on" : "off");
2667
2785
  let choice = null;
2668
2786
  try {
2669
2787
  choice = await select(`${picked} (currently ${current})`, [CUSTOMIZE_ON, CUSTOMIZE_OFF]);
@@ -2682,8 +2800,12 @@ async function executeCustomize(rawArgs, ctx) {
2682
2800
  // One read-only line: nothing is written and nothing is reloaded.
2683
2801
  const sidebar = sidebarRowsState();
2684
2802
  const moshi = moshiFlagEnabled(moshiFlagPath()) ? "on" : "off";
2803
+ const theme = themeStateLabels(readCustomizeThemeState());
2685
2804
  if (typeof notify === "function") {
2686
- notify(`customize status: sidebar=${sidebar.state} moshi=${moshi}`, "info");
2805
+ notify(
2806
+ `customize status: sidebar=${sidebar.state} moshi=${moshi} theme-sync=${theme.sync} theme=${theme.theme}`,
2807
+ "info",
2808
+ );
2687
2809
  }
2688
2810
  return;
2689
2811
  }
@@ -2753,7 +2875,7 @@ export default function (pi) {
2753
2875
  // must stay reachable from a plain Pi session outside a Herdr pane.
2754
2876
  if (typeof pi?.registerCommand === "function") {
2755
2877
  pi.registerCommand("herdr-gentle:customize", {
2756
- description: "Customize Herdr Gentle Shell: sidebar agent rows and Moshi notifications",
2878
+ description: "Customize Herdr Gentle Shell: sidebar agent rows, Moshi notifications and the Herdr theme",
2757
2879
  handler: async (args, ctx) => {
2758
2880
  await executeCustomize(args, ctx);
2759
2881
  },