herdr-gentle-shell 1.8.0 → 1.8.1

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.
@@ -1,6 +1,6 @@
1
1
  // @ts-nocheck
2
2
  // herdr-theme-sync.ts — Herdr's palette follows the active Gentle Shell / Pi
3
- // theme (odd/tasks/theme-sync.md T3b over S3/S4/S5/S7).
3
+ // theme (odd/tasks/theme-sync-fix.md T3 over S3/S4/S7).
4
4
  //
5
5
  // This is a Pi extension of its own rather than a section of
6
6
  // extensions/gentle-herdr-state.ts for one concrete reason: turning a Pi theme
@@ -11,8 +11,16 @@
11
11
  // pane-scoped session state machine; following a theme is independent of it.
12
12
  //
13
13
  // In one sentence: every tick the follower reads the persisted switch, and when
14
- // the palette it asks for differs from the one it last applied, it pipes the
15
- // projection to the plugin's own bin/configure-theme.js.
14
+ // the palette it asks for differs from the one it last asked for, it applies the
15
+ // projection IN PROCESS through lib/herdr-theme-apply.js.
16
+ //
17
+ // Why in process, and why that is the whole fix (evidence E1/E2): the shipped
18
+ // follower spawned the theme writer CLI of the INSTALLED Herdr plugin, found
19
+ // through `herdr plugin list`. A Pi-only update therefore kept running the old
20
+ // plugin's writer (which the user's install did not even have), and that writer
21
+ // refused the user's real config. The reference implementation
22
+ // (/home/jona/dev/upstream/gentle-herdr) applies from Pi itself, so this file now
23
+ // does the same and owns no knowledge of plugin roots, child processes or CLIs.
16
24
  //
17
25
  // The rules the code keeps, each of them a spec:
18
26
  // S3 sync ON -> Herdr's palette is the palette of the theme Pi is showing
@@ -20,39 +28,36 @@
20
28
  // colours) is noticed without restarting the session;
21
29
  // S4 sync OFF -> the one theme the user assigned, resolved by name; a name
22
30
  // this install does not have applies nothing;
23
- // S5 turning the sync off keeps the palette Herdr already has: nothing here
24
- // ever removes a managed block;
25
- // S7 the default install (sync off, no theme) spawns nothing and writes
26
- // nothing.
31
+ // S7 the default install (sync off, no theme) writes nothing at all, and
32
+ // turning the sync off keeps the palette Herdr already has.
27
33
  //
28
- // There is deliberately NO Herdr pane gate. Herdr's config is the user's own and
29
- // outlives any pane, so a Pi session started outside Herdr still keeps Herdr's
30
- // palette in sync; gating on HERDR_ENV would make the feature work only in the
31
- // one pane the user already has open.
34
+ // There is deliberately NO Herdr pane gate here: availability (Herdr pane,
35
+ // remote session, unsupported binary, subagent child) is decided once, by
36
+ // `applyHerdrTheme`, so the follower can never disagree with the writer about who
37
+ // may write. The child guard below is the one exception, and it is about
38
+ // registration, not about availability: a subagent's Pi must not even start this.
32
39
  //
33
40
  // Plain JavaScript with a .ts extension (// @ts-nocheck, no type annotations),
34
41
  // exactly like the other extensions, so the rename-and-stub test loading works
35
42
  // under plain node.
36
43
 
37
44
  import { colorToHex } from "@earendil-works/pi-tui";
38
- import { spawnSync } from "node:child_process";
39
- import { existsSync } from "node:fs";
40
45
  import { createRequire } from "node:module";
41
46
  import { fileURLToPath } from "node:url";
42
- import { dirname, join, isAbsolute as pathIsAbsolute, resolve as resolvePath } from "node:path";
47
+ import { dirname, join } from "node:path";
43
48
 
44
49
  const require = createRequire(import.meta.url);
45
50
 
46
51
  const TICK_MS = 500;
47
- const APPLY_TIMEOUT_MS = 60000;
48
- const PLUGIN_LIST_TIMEOUT_MS = 15000;
49
- // A refusal is explained in one line; anything longer is noise in a transcript.
50
- const FAILURE_TAIL_MAX = 300;
51
52
 
52
- const HERDR_PLUGIN_ACTIVE_ID = "herdr-gentle-shell";
53
- const HERDR_PLUGIN_LEGACY_ID = "herdr-gentle-agents";
54
- const CONFIGURE_BASENAME = "configure.js";
55
- const THEME_CONFIGURE_BASENAME = "configure-theme.js";
53
+ // What the user is told when the writer refuses to touch this environment, keyed
54
+ // by the reason `applyHerdrTheme` returns. `child` is absent on purpose: a child
55
+ // never registers this extension at all.
56
+ const UNAVAILABLE_NOTICES = Object.freeze({
57
+ "not-herdr": "Herdr theme sync is inactive: this Pi session is not inside a Herdr pane.",
58
+ remote: "Herdr theme sync is inactive: this is a remote session and Herdr reads its config on another machine.",
59
+ unsupported: "Herdr theme sync is not supported in this environment.",
60
+ });
56
61
 
57
62
  // Package-side helpers live in lib/. Tests copy this file out of the repository,
58
63
  // so the override points at the real lib/ exactly like GENTLE_CUSTOMIZE_LIB_DIR
@@ -73,81 +78,11 @@ function themeProjection() {
73
78
  return libRequire("theme-projection.js");
74
79
  }
75
80
 
76
- /* --------------------------------------------------------- script lookup */
77
-
78
- // bin/configure-theme.js lives in the Herdr plugin (installed as its own
79
- // package), so the Pi side resolves that root exactly like
80
- // lib/gentle-sidebar.js and the state sidecar do: a read-only
81
- // `herdr plugin list --json`, with GENTLE_HERDR_PLUGIN_ROOT as the documented
82
- // override for isolated runs. The active (renamed) id is queried first; a zero
83
- // match falls through to one explicit lookup by the retired id. Ambiguous roots
84
- // fail closed on either id.
85
- function herdrPluginRoots(id) {
86
- let result;
87
- try {
88
- result = spawnSync(
89
- process.env.HERDR_BIN_PATH || "herdr",
90
- ["plugin", "list", "--plugin", id, "--json"],
91
- { encoding: "utf8", timeout: PLUGIN_LIST_TIMEOUT_MS, windowsHide: true },
92
- );
93
- } catch (error) {
94
- return { ok: false, note: `could not resolve the installed plugin root: ${error?.message ?? error}.` };
95
- }
96
- if (result.error) {
97
- return { ok: false, note: `could not resolve the installed plugin root: ${result.error.message}.` };
98
- }
99
- if (result.status !== 0) {
100
- return { ok: false, note: `could not resolve the installed plugin root (plugin list exited ${result.status}).` };
101
- }
102
- try {
103
- const doc = JSON.parse(result.stdout || "");
104
- const arr = (doc && doc.result && doc.result.plugins) || doc.plugins || [];
105
- if (!Array.isArray(arr)) throw new Error("no plugins array");
106
- const hits = arr.filter((p) => p && (p.plugin_id === id || p.id === id));
107
- const roots = [...new Set(hits.map((hit) => hit.plugin_root).filter((root) => typeof root === "string" && root.length > 0))];
108
- return { ok: true, roots };
109
- } catch (error) {
110
- return { ok: false, note: `could not resolve the installed plugin root: malformed plugin list (${error?.message ?? error}).` };
111
- }
112
- }
113
-
114
- function checkConfigureScript(roots) {
115
- if (roots.length !== 1 || !pathIsAbsolute(roots[0])) {
116
- const why = roots.length === 0 ? "no match" : "ambiguous or non-absolute";
117
- return { ok: false, note: `could not resolve the installed plugin root (${why}).` };
118
- }
119
- const script = join(roots[0], "bin", CONFIGURE_BASENAME);
120
- if (!existsSync(script)) {
121
- return { ok: false, note: `could not resolve the installed plugin root (${roots[0]} has no bin/${CONFIGURE_BASENAME}).` };
122
- }
123
- return { ok: true, script };
124
- }
125
-
126
- function resolveConfigureScript() {
127
- const override = process.env.GENTLE_HERDR_PLUGIN_ROOT;
128
- if (typeof override === "string" && override.length > 0) {
129
- return { ok: true, script: join(resolvePath(override), "bin", CONFIGURE_BASENAME) };
130
- }
131
- const active = herdrPluginRoots(HERDR_PLUGIN_ACTIVE_ID);
132
- if (!active.ok) return active;
133
- if (active.roots.length > 0) return checkConfigureScript(active.roots);
134
- const legacy = herdrPluginRoots(HERDR_PLUGIN_LEGACY_ID);
135
- if (!legacy.ok) return legacy;
136
- if (legacy.roots.length > 0) return checkConfigureScript(legacy.roots);
137
- return {
138
- ok: false,
139
- note: `could not resolve the installed plugin root (no match for ${HERDR_PLUGIN_ACTIVE_ID} or ${HERDR_PLUGIN_LEGACY_ID}).`,
140
- };
141
- }
142
-
143
- // The theme writer is the sidebar writer's SIBLING, not the same file: each owns
144
- // a different managed block, so the resolved path only tells us where the plugin
145
- // lives. Swapping the last segment keeps the override and both id lookups on one
146
- // code path instead of re-deriving the root three times.
147
- function resolveThemeScript() {
148
- const resolved = resolveConfigureScript();
149
- if (!resolved.ok) return resolved;
150
- return { ok: true, script: join(dirname(resolved.script), THEME_CONFIGURE_BASENAME) };
81
+ // The in-process writer: it owns the availability guard, the bounded read, the
82
+ // safe write and the reload. Loading it lazily keeps this file's import surface
83
+ // to the single host package the stub pattern needs.
84
+ function themeApply() {
85
+ return libRequire("herdr-theme-apply.js");
151
86
  }
152
87
 
153
88
  /* ------------------------------------------------------------ projection */
@@ -183,7 +118,7 @@ function convertColors(colors, projection) {
183
118
  }
184
119
 
185
120
  // A theme whose palette cannot be read at all is NOT evidence that the user has
186
- // no palette, so the tick is skipped instead of stripping Herdr's custom block.
121
+ // no palette, so the tick is skipped instead of writing an empty projection.
187
122
  function themeColors(theme) {
188
123
  if (!theme || typeof theme !== "object") return null;
189
124
  let colors;
@@ -196,21 +131,15 @@ function themeColors(theme) {
196
131
  return colors;
197
132
  }
198
133
 
199
- // The last non-empty stderr line, capped: the CLI names its refusal there, and a
200
- // tick-by-tick wall of text is exactly what must not happen.
201
- function stderrTail(text) {
202
- const lines = String(text ?? "")
203
- .split(/\r?\n/)
204
- .map((line) => line.trim())
205
- .filter((line) => line.length > 0);
206
- if (lines.length === 0) return "";
207
- return lines[lines.length - 1].slice(0, FAILURE_TAIL_MAX);
208
- }
209
-
210
134
  /* ---------------------------------------------------------------- factory */
211
135
 
212
136
  export default function (pi) {
213
137
  if (!pi || typeof pi.on !== "function") return;
138
+ // CHILD GUARD, before anything is registered: a subagent's "active theme" is
139
+ // not the palette the user is looking at, so its Pi must never write the user's
140
+ // Herdr config. Skipping registration entirely (rather than refusing later) also
141
+ // means no timer runs in a child for the whole session.
142
+ if (process.env.GENTLE_PI_AGENTS_CHILD === "1") return;
214
143
 
215
144
  // Everything the follower remembers for ONE session. The notices are
216
145
  // per-session: a tick must never nag, and a new session is a new conversation.
@@ -219,10 +148,21 @@ export default function (pi) {
219
148
  fingerprint: null, // the last palette that was acted on
220
149
  failure: null, // the last failure text already reported
221
150
  missingTheme: false, // the unavailable-theme notice was shown
222
- unresolvable: false, // the plugin-root refusal was shown
151
+ unavailable: false, // the environment notice was shown
152
+ noColours: false, // the "nothing to project" notice was shown
223
153
  busy: false, // an apply is in flight
224
154
  };
225
155
  let timer = null;
156
+ // F4: a shutdown can land while the initial evaluation is awaiting the writer.
157
+ // The flag makes "this session is over" observable after that await, so the
158
+ // start path can no longer arm a tick that keeps writing the user's config for a
159
+ // session nobody is looking at.
160
+ let stopped = false;
161
+ // F2: `partial/reload` means the config was written but Herdr was not told. The
162
+ // flag survives until a reload actually succeeds and is honoured on the next
163
+ // apply attempt of THIS session. It is session memory on purpose (a restart
164
+ // forgets it), which is why the notice names the manual command.
165
+ let reloadOwed = false;
226
166
 
227
167
  function notify(ctx, message, level = "warning") {
228
168
  try {
@@ -232,7 +172,7 @@ export default function (pi) {
232
172
  }
233
173
  }
234
174
 
235
- // The CLI repeats its refusal on every attempt; the user is told once per
175
+ // The writer repeats its refusal on every attempt; the user is told once per
236
176
  // distinct failure. `seen.failure` is cleared by a success, so the same refusal
237
177
  // after a good apply is news again.
238
178
  function reportFailure(ctx, text) {
@@ -241,50 +181,68 @@ export default function (pi) {
241
181
  notify(ctx, text);
242
182
  }
243
183
 
244
- function applyPalette(ctx, projection, paletteInput) {
245
- let payload;
246
- try {
247
- payload = projection.projectPalette(paletteInput);
248
- } catch {
249
- // projectPalette only throws on a malformed input this file built; there is
250
- // nothing honest to apply, and guessing would paint a palette nobody chose.
251
- return;
252
- }
253
- const resolved = resolveThemeScript();
254
- if (!resolved.ok) {
255
- if (!seen.unresolvable) {
256
- seen.unresolvable = true;
257
- notify(ctx, `Could not apply the palette to Herdr: ${resolved.note} The palette Herdr has was left untouched.`);
258
- }
184
+ // One sentence, always terminated. A child-process message ends in a newline (or
185
+ // in its own period), and the reload notice must read as prose plus the command
186
+ // that repairs it by hand.
187
+ function sentence(text) {
188
+ const trimmed = String(text ?? "").trim().replace(/\.+$/, "");
189
+ return trimmed === "" ? "" : `${trimmed}.`;
190
+ }
191
+
192
+ function reloadNotice(error) {
193
+ const reason = sentence(error);
194
+ const repair = "Run 'herdr server reload-config' to apply it.";
195
+ return reason === ""
196
+ ? `Herdr theme written; Herdr reload failed. ${repair}`
197
+ : `Herdr theme written; Herdr reload failed: ${reason} ${repair}`;
198
+ }
199
+
200
+ // Every outcome of a change the USER made must be visible: before this, an
201
+ // apply that never happened looked exactly like one that worked.
202
+ function reportResult(ctx, result, label, userInitiated) {
203
+ const status = result && result.status;
204
+ if (status === "requested") {
205
+ seen.failure = null;
206
+ // A reload actually happened (with or without a write), so an owed one is
207
+ // paid off.
208
+ reloadOwed = false;
209
+ // A palette-only change (the Pi theme recoloured while the sync is on) is
210
+ // not a user action, so it stays silent; a switch the user flipped is news.
211
+ if (userInitiated) notify(ctx, `Herdr theme applied: ${label}; reload requested`, "info");
259
212
  return;
260
213
  }
261
- let result;
262
- try {
263
- result = spawnSync(process.execPath, [resolved.script, "--apply", "--json", "--reload"], {
264
- input: JSON.stringify(payload),
265
- encoding: "utf8",
266
- timeout: APPLY_TIMEOUT_MS,
267
- windowsHide: true,
268
- });
269
- } catch (error) {
270
- reportFailure(ctx, `Could not apply the palette to Herdr: ${resolved.script} could not start (${error?.message ?? error}).`);
214
+ if (status === "unchanged") {
215
+ // Herdr already holds this palette: nothing was written and nothing needs
216
+ // saying, but an earlier failure is over.
217
+ seen.failure = null;
271
218
  return;
272
219
  }
273
- if (result.error) {
274
- reportFailure(ctx, `Could not apply the palette to Herdr: ${resolved.script} could not start (${result.error.message}).`);
220
+ if (status === "unavailable") {
221
+ // Reached only when the user opted in (sync on or a theme pinned, which is
222
+ // the only way this follower asks for an apply). It is a state of the
223
+ // environment, not an error, hence `info` and once per session.
224
+ const text = UNAVAILABLE_NOTICES[result.reason];
225
+ if (text === undefined || seen.unavailable) return;
226
+ seen.unavailable = true;
227
+ notify(ctx, text, "info");
275
228
  return;
276
229
  }
277
- if (result.status !== 0) {
278
- const tail = stderrTail(result.stderr);
279
- reportFailure(ctx, `Could not apply the palette to Herdr: configure-theme exited ${result.status}${tail ? `: ${tail}` : "."}`);
280
- return;
230
+ if (status === "partial") {
231
+ if (result.stage === "reload") {
232
+ // The write is committed and Herdr was not told: remember the debt so the
233
+ // next apply attempt still asks for the reload, and tell the user the
234
+ // command that repairs it even if they restart Pi.
235
+ reloadOwed = true;
236
+ reportFailure(ctx, reloadNotice(result.error));
237
+ return;
238
+ }
239
+ reportFailure(ctx, `Herdr theme not applied: ${result.error}`);
281
240
  }
282
- seen.failure = null;
283
241
  }
284
242
 
285
243
  // One evaluation: read the switch, decide what palette it asks for, and apply it
286
244
  // only when that answer is new.
287
- function step(ctx) {
245
+ async function step(ctx) {
288
246
  const store = themeStore();
289
247
  let snapshot;
290
248
  try {
@@ -299,17 +257,27 @@ export default function (pi) {
299
257
  const projection = themeProjection();
300
258
  const sync = snapshot.sync === true;
301
259
  const chosen = sync ? null : projection.normalizeThemeName(snapshot.theme);
302
- // S7 + S5: sync off with nothing assigned is the default install. No spawn, no
303
- // write, no removal — Herdr keeps the palette it already has.
304
- if (!sync && chosen === null) return;
260
+ // S7: sync off with nothing assigned is the default install. No write, no
261
+ // apply call, no removal — Herdr keeps the palette it already has. F1: it must
262
+ // also FORGET what was applied, because turning the sync off (or clearing the
263
+ // pin) is the user saying "stop touching Herdr". Without that reset the next
264
+ // "on" looks unchanged — same sync+theme, same palette — and a config the user
265
+ // repaired in between would never be written.
266
+ if (!sync && chosen === null) {
267
+ seen.stateKey = null;
268
+ seen.fingerprint = null;
269
+ return;
270
+ }
305
271
 
306
272
  let theme;
307
- let name;
273
+ let label;
308
274
  if (sync) {
309
275
  theme = ctx && ctx.ui ? ctx.ui.theme : undefined;
310
- name = theme && typeof theme.name === "string" ? theme.name : null;
276
+ label = theme && typeof theme.name === "string" ? theme.name : null;
311
277
  } else {
312
- name = chosen;
278
+ // The selected name IS the label: the assigned theme is what the user asked
279
+ // for, whether or not this install has it.
280
+ label = chosen;
313
281
  theme = undefined;
314
282
  try {
315
283
  theme = ctx && ctx.ui && typeof ctx.ui.getTheme === "function" ? ctx.ui.getTheme(chosen) : undefined;
@@ -336,22 +304,62 @@ export default function (pi) {
336
304
 
337
305
  const colors = convertColors(rawColors, projection);
338
306
  const observed = JSON.stringify([sync, chosen]);
339
- const fingerprint = projection.paletteFingerprint({ name, colors });
340
- const changed = observed !== seen.stateKey || fingerprint !== seen.fingerprint;
307
+ const fingerprint = projection.paletteFingerprint({ name: label, colors });
308
+ // "User-initiated" is exactly a change of the stored {sync, theme}: a first
309
+ // evaluation in a session is one too, because the user set the switch before
310
+ // Pi started or through the customize panel.
311
+ const userInitiated = observed !== seen.stateKey;
312
+ const changed = userInitiated || fingerprint !== seen.fingerprint;
341
313
  // Recorded BEFORE the apply on purpose: a failed or refused apply must not be
342
314
  // retried on the next tick, and it must not block the next observed change
343
315
  // either, which is exactly what "the last observed request" means.
344
316
  seen.stateKey = observed;
345
317
  seen.fingerprint = fingerprint;
346
318
  if (!changed) return;
347
- applyPalette(ctx, projection, { name, colors });
319
+
320
+ let projected;
321
+ try {
322
+ projected = projection.projectPalette({ name: label, colors });
323
+ } catch {
324
+ // projectPalette only throws on a malformed input this file built; there is
325
+ // nothing honest to apply, and guessing would paint a palette nobody chose.
326
+ return;
327
+ }
328
+
329
+ // F3: a projection without a single concrete token would still rewrite the
330
+ // theme name to one-dark and announce success — a change the user never chose
331
+ // and no palette at all. Apply nothing and say why, once per session.
332
+ if (projected.theme.custom === undefined) {
333
+ if (!seen.noColours) {
334
+ seen.noColours = true;
335
+ notify(ctx, `Herdr theme not applied: ${label ?? "the active theme"} has no concrete colours to project.`);
336
+ }
337
+ return;
338
+ }
339
+
340
+ // F2: an owed reload rides along with this attempt. It is only ever sent on a
341
+ // real apply attempt (never on an unchanged tick), so Herdr is not reloaded
342
+ // every 500 ms while one is pending.
343
+ const options = { projection: projected.theme };
344
+ if (reloadOwed) options.forceReload = true;
345
+
346
+ let result;
347
+ try {
348
+ result = await themeApply().applyHerdrTheme(options);
349
+ } catch (error) {
350
+ // `applyHerdrTheme` reports its own refusals and failures as a status; a
351
+ // throw is unexpected, and it must not escape into the tick's caller.
352
+ reportFailure(ctx, `Herdr theme not applied: ${error?.message ?? error}`);
353
+ return;
354
+ }
355
+ reportResult(ctx, result, label ?? "the active theme", userInitiated);
348
356
  }
349
357
 
350
- function evaluate(ctx) {
358
+ async function evaluate(ctx) {
351
359
  if (seen.busy) return; // never stack applies
352
360
  seen.busy = true;
353
361
  try {
354
- step(ctx);
362
+ await step(ctx);
355
363
  } catch {
356
364
  // A tick runs from a timer: an escaping error would take Pi down with it.
357
365
  } finally {
@@ -360,24 +368,41 @@ export default function (pi) {
360
368
  }
361
369
 
362
370
  function stop() {
371
+ // F4: marking the session stopped is what the start path checks after its one
372
+ // await; clearing the timer is what makes the next session (or the end of this
373
+ // one) quiet.
374
+ stopped = true;
363
375
  if (timer !== null) {
364
376
  clearInterval(timer);
365
377
  timer = null;
366
378
  }
367
379
  }
368
380
 
369
- pi.on("session_start", (event, ctx) => {
381
+ pi.on("session_start", async (event, ctx) => {
370
382
  stop();
371
383
  seen.stateKey = null;
372
384
  seen.fingerprint = null;
373
385
  seen.failure = null;
374
386
  seen.missingTheme = false;
375
- seen.unresolvable = false;
387
+ seen.unavailable = false;
388
+ seen.noColours = false;
376
389
  seen.busy = false;
390
+ reloadOwed = false;
391
+ // This session is live again from here on.
392
+ stopped = false;
377
393
  // One immediate evaluation, so the palette is right before the first tick
378
394
  // instead of up to half a second later — or never, in a short-lived session.
379
- evaluate(ctx);
380
- timer = setInterval(() => evaluate(ctx), TICK_MS);
395
+ await evaluate(ctx);
396
+ // The evaluation above awaited a child process; a shutdown may have landed in
397
+ // that window. Arming a tick now would keep writing the user's config for a
398
+ // session that is already over.
399
+ if (stopped) return;
400
+ timer = setInterval(() => {
401
+ // A tick is asynchronous (the reload is a child process). The promise is
402
+ // RETURNED rather than discarded so a driver can await one tick; `evaluate`
403
+ // swallows every error, so it can never reject into the timer.
404
+ return evaluate(ctx);
405
+ }, TICK_MS);
381
406
  // An idle follower must never keep Pi (or a scripted session) alive.
382
407
  if (timer && typeof timer.unref === "function") timer.unref();
383
408
  });