herdr-gentle-shell 1.7.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.
@@ -0,0 +1,413 @@
1
+ // @ts-nocheck
2
+ // herdr-theme-sync.ts — Herdr's palette follows the active Gentle Shell / Pi
3
+ // theme (odd/tasks/theme-sync-fix.md T3 over S3/S4/S7).
4
+ //
5
+ // This is a Pi extension of its own rather than a section of
6
+ // extensions/gentle-herdr-state.ts for one concrete reason: turning a Pi theme
7
+ // colour into a Herdr hex value needs `colorToHex` from
8
+ // @earendil-works/pi-tui, and the state sidecar is loaded by every suite as a
9
+ // renamed copy with its single package import stubbed — a second host import
10
+ // there would mean a second stub in six test files. The sidecar also owns the
11
+ // pane-scoped session state machine; following a theme is independent of it.
12
+ //
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 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.
24
+ //
25
+ // The rules the code keeps, each of them a spec:
26
+ // S3 sync ON -> Herdr's palette is the palette of the theme Pi is showing
27
+ // right now, and a theme recoloured in place (same name, new
28
+ // colours) is noticed without restarting the session;
29
+ // S4 sync OFF -> the one theme the user assigned, resolved by name; a name
30
+ // this install does not have applies 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.
33
+ //
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.
39
+ //
40
+ // Plain JavaScript with a .ts extension (// @ts-nocheck, no type annotations),
41
+ // exactly like the other extensions, so the rename-and-stub test loading works
42
+ // under plain node.
43
+
44
+ import { colorToHex } from "@earendil-works/pi-tui";
45
+ import { createRequire } from "node:module";
46
+ import { fileURLToPath } from "node:url";
47
+ import { dirname, join } from "node:path";
48
+
49
+ const require = createRequire(import.meta.url);
50
+
51
+ const TICK_MS = 500;
52
+
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
+ });
61
+
62
+ // Package-side helpers live in lib/. Tests copy this file out of the repository,
63
+ // so the override points at the real lib/ exactly like GENTLE_CUSTOMIZE_LIB_DIR
64
+ // does for the state sidecar; production resolves relative to this file.
65
+ function libRequire(name) {
66
+ const override = process.env.GENTLE_THEME_SYNC_LIB_DIR;
67
+ const dir = typeof override === "string" && override.length > 0
68
+ ? override
69
+ : join(dirname(fileURLToPath(import.meta.url)), "..", "lib");
70
+ return require(join(dir, name));
71
+ }
72
+
73
+ function themeStore() {
74
+ return libRequire("theme-store.js");
75
+ }
76
+
77
+ function themeProjection() {
78
+ return libRequire("theme-projection.js");
79
+ }
80
+
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");
86
+ }
87
+
88
+ /* ------------------------------------------------------------ projection */
89
+
90
+ // Pi's `Theme.colors` resolves every token to a `Color` (the terminal default is
91
+ // already substituted), so `colorToHex` is the whole conversion. Anything that is
92
+ // not a concrete hex afterwards is dropped rather than defaulted: projectPalette
93
+ // omits it, and Herdr keeps the base-theme colour for that surface instead of
94
+ // painting a guess.
95
+ function convertColors(colors, projection) {
96
+ const converted = {};
97
+ // `muted` paints two Herdr tokens (subtext0 and overlay0), so the source roles
98
+ // are visited once each: one conversion, one emitted pair, never half-applied.
99
+ for (const piToken of new Set(Object.values(projection.HERDR_ROLE_SOURCES))) {
100
+ let raw;
101
+ try {
102
+ raw = colors[piToken];
103
+ } catch {
104
+ continue;
105
+ }
106
+ // "" is Pi's "terminal default" in a theme document: it has no hex spelling.
107
+ if (raw === "" || raw === undefined || raw === null) continue;
108
+ let hex;
109
+ try {
110
+ hex = colorToHex(raw);
111
+ } catch {
112
+ // One unconvertible token must not cost the rest of the palette.
113
+ continue;
114
+ }
115
+ if (projection.isConcreteHex(hex)) converted[piToken] = hex;
116
+ }
117
+ return converted;
118
+ }
119
+
120
+ // A theme whose palette cannot be read at all is NOT evidence that the user has
121
+ // no palette, so the tick is skipped instead of writing an empty projection.
122
+ function themeColors(theme) {
123
+ if (!theme || typeof theme !== "object") return null;
124
+ let colors;
125
+ try {
126
+ colors = theme.colors;
127
+ } catch {
128
+ return null;
129
+ }
130
+ if (!colors || typeof colors !== "object") return null;
131
+ return colors;
132
+ }
133
+
134
+ /* ---------------------------------------------------------------- factory */
135
+
136
+ export default function (pi) {
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;
143
+
144
+ // Everything the follower remembers for ONE session. The notices are
145
+ // per-session: a tick must never nag, and a new session is a new conversation.
146
+ const seen = {
147
+ stateKey: null, // the last requested {sync, theme} that was acted on
148
+ fingerprint: null, // the last palette that was acted on
149
+ failure: null, // the last failure text already reported
150
+ missingTheme: false, // the unavailable-theme notice was shown
151
+ unavailable: false, // the environment notice was shown
152
+ noColours: false, // the "nothing to project" notice was shown
153
+ busy: false, // an apply is in flight
154
+ };
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;
166
+
167
+ function notify(ctx, message, level = "warning") {
168
+ try {
169
+ if (ctx && ctx.ui && typeof ctx.ui.notify === "function") ctx.ui.notify(message, level);
170
+ } catch {
171
+ // A UI that cannot notify must not break the follower.
172
+ }
173
+ }
174
+
175
+ // The writer repeats its refusal on every attempt; the user is told once per
176
+ // distinct failure. `seen.failure` is cleared by a success, so the same refusal
177
+ // after a good apply is news again.
178
+ function reportFailure(ctx, text) {
179
+ if (seen.failure === text) return;
180
+ seen.failure = text;
181
+ notify(ctx, text);
182
+ }
183
+
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");
212
+ return;
213
+ }
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;
218
+ return;
219
+ }
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");
228
+ return;
229
+ }
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}`);
240
+ }
241
+ }
242
+
243
+ // One evaluation: read the switch, decide what palette it asks for, and apply it
244
+ // only when that answer is new.
245
+ async function step(ctx) {
246
+ const store = themeStore();
247
+ let snapshot;
248
+ try {
249
+ snapshot = store.readThemeState(process.env);
250
+ } catch {
251
+ return;
252
+ }
253
+ // A switch this package cannot read is a refusal (an unparsable or
254
+ // unreadable document): do nothing, and never write.
255
+ if (!snapshot || snapshot.ok !== true) return;
256
+
257
+ const projection = themeProjection();
258
+ const sync = snapshot.sync === true;
259
+ const chosen = sync ? null : projection.normalizeThemeName(snapshot.theme);
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
+ }
271
+
272
+ let theme;
273
+ let label;
274
+ if (sync) {
275
+ theme = ctx && ctx.ui ? ctx.ui.theme : undefined;
276
+ label = theme && typeof theme.name === "string" ? theme.name : null;
277
+ } else {
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;
281
+ theme = undefined;
282
+ try {
283
+ theme = ctx && ctx.ui && typeof ctx.ui.getTheme === "function" ? ctx.ui.getTheme(chosen) : undefined;
284
+ } catch {
285
+ theme = undefined;
286
+ }
287
+ if (!theme) {
288
+ // S4: a selection for a theme this install does not have applies nothing.
289
+ // Recording nothing keeps the tick cheap and lets a later install of that
290
+ // exact theme be picked up without a restart, while the notice is once.
291
+ if (!seen.missingTheme) {
292
+ seen.missingTheme = true;
293
+ notify(
294
+ ctx,
295
+ `The Pi theme "${chosen}" is not installed, so Herdr's palette was left unchanged; pick an installed theme in /herdr-gentle:customize.`,
296
+ );
297
+ }
298
+ return;
299
+ }
300
+ }
301
+
302
+ const rawColors = themeColors(theme);
303
+ if (rawColors === null) return;
304
+
305
+ const colors = convertColors(rawColors, projection);
306
+ const observed = JSON.stringify([sync, chosen]);
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;
313
+ // Recorded BEFORE the apply on purpose: a failed or refused apply must not be
314
+ // retried on the next tick, and it must not block the next observed change
315
+ // either, which is exactly what "the last observed request" means.
316
+ seen.stateKey = observed;
317
+ seen.fingerprint = fingerprint;
318
+ if (!changed) return;
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);
356
+ }
357
+
358
+ async function evaluate(ctx) {
359
+ if (seen.busy) return; // never stack applies
360
+ seen.busy = true;
361
+ try {
362
+ await step(ctx);
363
+ } catch {
364
+ // A tick runs from a timer: an escaping error would take Pi down with it.
365
+ } finally {
366
+ seen.busy = false;
367
+ }
368
+ }
369
+
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;
375
+ if (timer !== null) {
376
+ clearInterval(timer);
377
+ timer = null;
378
+ }
379
+ }
380
+
381
+ pi.on("session_start", async (event, ctx) => {
382
+ stop();
383
+ seen.stateKey = null;
384
+ seen.fingerprint = null;
385
+ seen.failure = null;
386
+ seen.missingTheme = false;
387
+ seen.unavailable = false;
388
+ seen.noColours = false;
389
+ seen.busy = false;
390
+ reloadOwed = false;
391
+ // This session is live again from here on.
392
+ stopped = false;
393
+ // One immediate evaluation, so the palette is right before the first tick
394
+ // instead of up to half a second later — or never, in a short-lived session.
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);
406
+ // An idle follower must never keep Pi (or a scripted session) alive.
407
+ if (timer && typeof timer.unref === "function") timer.unref();
408
+ });
409
+
410
+ pi.on("session_shutdown", () => {
411
+ stop();
412
+ });
413
+ }