proper-base 0.3.0 → 0.5.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.
@@ -2,10 +2,13 @@ import type { TUI, TuiInputListener } from "@earendil-works/pi-tui";
2
2
  import {
3
3
  compositeTuiLine,
4
4
  sliceByColumn,
5
+ stripTerminalSequences,
6
+ truncateToWidth,
5
7
  visibleWidth,
6
8
  } from "@earendil-works/pi-tui";
7
9
 
8
10
  import { prioritize } from "./jump-to-bottom.ts";
11
+ import type { OutlineEntry } from "./transcript-cleanup.ts";
9
12
 
10
13
  const INSTALLED = Symbol.for("pi-proper-base.prompt-jump");
11
14
  // Plain arrows rather than arrowheads or chevrons: U+2303/U+2304 and the
@@ -15,6 +18,43 @@ const UP = " ↑ ";
15
18
  const DOWN = " ↓ ";
16
19
  /** Columns kept clear to the right of the chips, sparing the scrollbar. */
17
20
  const RIGHT_GAP = 1;
21
+ /** Topmost rail row the stack may grow up to, below the chips. */
22
+ const RAIL_TOP = 2;
23
+ // One relevant symbol per action type, from code points common monospace
24
+ // fonts carry: the transcript's own › marks prompts, ‹ mirrors it for
25
+ // replies, × marks failures, and tool families map by name with a plain
26
+ // dot as the fallback.
27
+ const USER_SYMBOL = "›";
28
+ const ASSISTANT_SYMBOL = "‹";
29
+ const ERROR_SYMBOL = "×";
30
+ const FALLBACK_TOOL_SYMBOL = "·";
31
+ const TOOL_SYMBOLS: ReadonlyArray<readonly [RegExp, string]> = [
32
+ [/grep|search|find|glob|locate/, "/"],
33
+ [/read/, "≡"],
34
+ [/edit/, "±"],
35
+ [/write/, "+"],
36
+ [/bash|exec|command|shell/, "$"],
37
+ [/fetch|web|url|http/, "@"],
38
+ [/agent|task/, "&"],
39
+ ];
40
+ /** Widest hover-expanded row: symbol, space, and the action name. */
41
+ const MAX_EXPANDED_WIDTH = 16;
42
+ // Fixed truecolors, following the footer's precedent: prompts, replies, and
43
+ // failures keep stable identities, and each tool name hashes into the
44
+ // palette so one tool always wears one color.
45
+ const USER_COLOR = "38;2;120;170;255";
46
+ const ASSISTANT_COLOR = "38;2;140;200;140";
47
+ const ERROR_COLOR = "38;2;235;110;110";
48
+ const TOOL_COLORS = [
49
+ "38;2;80;190;180",
50
+ "38;2;175;150;235",
51
+ "38;2;210;170;90",
52
+ "38;2;215;125;95",
53
+ "38;2;120;155;205",
54
+ "38;2;225;140;175",
55
+ "38;2;160;180;95",
56
+ "38;2;95;190;225",
57
+ ];
18
58
  // ESC prefix is matched separately: biome bans control characters in
19
59
  // regexes, and string literals carry it fine.
20
60
  const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
@@ -42,16 +82,21 @@ type Scroller = TUI & {
42
82
  type LayoutBox = {
43
83
  scrollView?: unknown;
44
84
  scrollContentLines?: readonly string[];
85
+ rect?: { y: number; height: number };
45
86
  children?: LayoutBox[];
46
87
  };
47
88
  type LayoutFrame = { root: LayoutBox; primaryScrollView?: unknown };
48
89
  type Installed = Scroller & { [INSTALLED]?: () => void };
49
90
  /** Screen columns of the rendered chips, in 0-based terminal cells. */
50
91
  type Hit = { start: number; middle: number; end: number };
92
+ /** Screen cells of the rendered rail, with each tile's content row. */
93
+ type RailHit = { start: number; end: number; top: number; rows: number[] };
51
94
  export type PromptJumpOptions = {
52
95
  color(value: string): string;
53
96
  /** Weaker than `color`, so the reading recedes behind the chips. */
54
97
  subtle(value: string): string;
98
+ /** Session actions painted as the rail; omitted or empty disables it. */
99
+ outline?(): readonly OutlineEntry[];
55
100
  };
56
101
 
57
102
  function scroller(tui: TUI): Scroller | undefined {
@@ -65,12 +110,12 @@ function scroller(tui: TUI): Scroller | undefined {
65
110
  : undefined;
66
111
  }
67
112
 
68
- function contentLines(view: Scroller): readonly string[] | undefined {
113
+ function primaryBox(view: Scroller): LayoutBox | undefined {
69
114
  const layout = view.currentLayout;
70
115
  const scrollView = layout?.primaryScrollView;
71
116
  if (!layout || !scrollView) return undefined;
72
- const visit = (box: LayoutBox): readonly string[] | undefined => {
73
- if (box.scrollView === scrollView) return box.scrollContentLines;
117
+ const visit = (box: LayoutBox): LayoutBox | undefined => {
118
+ if (box.scrollView === scrollView) return box;
74
119
  for (const child of box.children ?? []) {
75
120
  const found = visit(child);
76
121
  if (found) return found;
@@ -80,6 +125,38 @@ function contentLines(view: Scroller): readonly string[] | undefined {
80
125
  return visit(layout.root);
81
126
  }
82
127
 
128
+ function contentLines(view: Scroller): readonly string[] | undefined {
129
+ return primaryBox(view)?.scrollContentLines;
130
+ }
131
+
132
+ /** FNV-1a, the same tiny stable hash the OSC 8 id tagging uses. */
133
+ function fnv1a(value: string): number {
134
+ let hash = 0x811c9dc5;
135
+ for (let index = 0; index < value.length; index++) {
136
+ hash ^= value.charCodeAt(index);
137
+ hash = Math.imul(hash, 0x01000193) >>> 0;
138
+ }
139
+ return hash;
140
+ }
141
+
142
+ function tileColor(entry: OutlineEntry): string {
143
+ if (entry.kind === "user") return USER_COLOR;
144
+ if (entry.kind === "assistant") return ASSISTANT_COLOR;
145
+ if (entry.kind === "error") return ERROR_COLOR;
146
+ return TOOL_COLORS[fnv1a(entry.label) % TOOL_COLORS.length] ?? USER_COLOR;
147
+ }
148
+
149
+ function railSymbol(entry: OutlineEntry): string {
150
+ if (entry.kind === "user") return USER_SYMBOL;
151
+ if (entry.kind === "assistant") return ASSISTANT_SYMBOL;
152
+ if (entry.kind === "error") return ERROR_SYMBOL;
153
+ const name = entry.label.toLowerCase();
154
+ for (const [pattern, symbol] of TOOL_SYMBOLS) {
155
+ if (pattern.test(name)) return symbol;
156
+ }
157
+ return FALLBACK_TOOL_SYMBOL;
158
+ }
159
+
83
160
  /**
84
161
  * Leading SGR sequences of a slice, which carry the colors already active at
85
162
  * that column. Replaying them under the glyphs keeps the transcript's own
@@ -171,7 +248,7 @@ function jump(view: Scroller, direction: 1 | -1): void {
171
248
 
172
249
  /**
173
250
  * Render clickable previous/next prompt chips in the top-right corner of the
174
- * transcript viewport.
251
+ * transcript viewport, and the clickable session action rail beneath them.
175
252
  *
176
253
  * The chips composite into the finished screen rather than an overlay: any
177
254
  * visible overlay disables Pi's scrollbar hit testing, which is a gesture
@@ -195,6 +272,22 @@ export function installPromptJump(
195
272
  target[INSTALLED]?.();
196
273
 
197
274
  let hit: Hit | undefined;
275
+ let railHit: RailHit | undefined;
276
+ /** Viewport rect the last painted frame placed the rail with. */
277
+ let railRect: { y: number; height: number } | undefined;
278
+ // The rail rests faint — the closest a character grid comes to
279
+ // transparency — and takes full intensity while the pointer hovers its
280
+ // column. Pure no-button motion is the evidence hover tracking works at
281
+ // all: multiplexers run button-motion tracking only, and there the rail
282
+ // keeps full intensity instead of resting permanently dim.
283
+ let railHovered = false;
284
+ let motionSeen = false;
285
+ // Whether a button press is currently unreleased, tracked from the raw
286
+ // stream. xterm encodes no-button motion with base 3, but Scribe uses
287
+ // base 0 — the left button's — so that shape only reads as hover while
288
+ // nothing is actually held; with a press open it is drag motion.
289
+ let buttonHeld = false;
290
+ const railDimmed = () => motionSeen && !railHovered;
198
291
  // The prompt scan walks every transcript line and runs once per frame
199
292
  // while the viewport is scrolled up, so it is cached on the pair that
200
293
  // changes when the reading can change.
@@ -207,57 +300,163 @@ export function installPromptJump(
207
300
  const hadOwnMethod = Object.hasOwn(view, "compositeFlashes");
208
301
  const flashes = view.compositeFlashes;
209
302
 
210
- const decorate = (screen: string[], width: number): string[] => {
211
- const start = width - RIGHT_GAP - chipWidth;
212
- if (start < 0) {
213
- hit = undefined;
214
- return screen;
215
- }
216
- hit = { start, middle: start + visibleWidth(UP), end: start + chipWidth };
217
- const painted = [...screen];
218
- // Colored per frame rather than once at install, so a theme that rejects
219
- // the request fails inside the guard instead of out of the editor factory.
220
- paintRow(
221
- painted,
222
- 0,
223
- options.color(`${UP}${DOWN}`),
224
- chipWidth,
225
- start,
226
- width,
227
- );
228
- // The reading only answers "where am I", so it stays out of the way while
229
- // the viewport is already following the newest output.
230
- let count: string | undefined;
303
+ /**
304
+ * Paint the session action rail: one uniquely colored, type-relevant
305
+ * symbol per action in a single column against the scrollbar gap, stacked
306
+ * in session order and anchored to the bottom of the transcript viewport.
307
+ * The stack grows upward from there, does not move with transcript
308
+ * scrolling, and when it overflows it shows the newest tail, sliding only
309
+ * to keep the action the viewport currently sits in on screen.
310
+ *
311
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
312
+ */
313
+ const paintRail = (
314
+ painted: string[],
315
+ width: number,
316
+ rect: { y: number; height: number } | undefined,
317
+ ): RailHit | undefined => {
318
+ const entries = options.outline?.() ?? [];
319
+ if (!entries.length) return undefined;
320
+ // One cell against the scrollbar gap.
321
+ const start = width - RIGHT_GAP - 1;
322
+ if (start < 0) return undefined;
323
+ const bottom = rect ? rect.y + rect.height : 0;
324
+ const height = bottom - RAIL_TOP;
325
+ if (height <= 0) return undefined;
326
+ // The action the viewport currently sits in; -1 above the first one.
327
+ let current = entries.length - 1;
231
328
  if (!view.isFollowingOutput) {
232
- const lines = contentLines(view) ?? [];
233
- const top = view.viewportTop;
329
+ current = -1;
330
+ for (let index = 0; index < entries.length; index++) {
331
+ const entry = entries[index];
332
+ if (!entry || entry.row > view.viewportTop) break;
333
+ current = index;
334
+ }
335
+ }
336
+ const offset =
337
+ entries.length <= height
338
+ ? 0
339
+ : Math.min(entries.length - height, Math.max(0, current));
340
+ const count = Math.min(entries.length - offset, height);
341
+ // Anchored to the bottom of the transcript viewport: the stack grows
342
+ // upward from there and only slides once it reaches the top.
343
+ const top = bottom - count;
344
+ const rows: number[] = [];
345
+ // While the pointer hovers, each row expands to "symbol name", still
346
+ // flush against the gap; the hit band widens with the longest row so
347
+ // the pointer can travel along the names without collapsing them.
348
+ // The no-motion fallback stays a compact fully lit column.
349
+ let bandWidth = 1;
350
+ for (let index = offset; index < offset + count; index++) {
351
+ const entry = entries[index];
352
+ if (!entry) break;
353
+ const row = top + rows.length;
354
+ const text = railHovered
355
+ ? truncateToWidth(
356
+ `${railSymbol(entry)} ${entry.label}`,
357
+ MAX_EXPANDED_WIDTH,
358
+ "…",
359
+ )
360
+ : railSymbol(entry);
361
+ const textWidth = visibleWidth(text);
362
+ const columnStart = width - RIGHT_GAP - textWidth;
363
+ if (columnStart < 0) {
364
+ rows.push(entry.row);
365
+ continue;
366
+ }
367
+ bandWidth = Math.max(bandWidth, textWidth);
368
+ // Resting, the rail sits underneath the session text: a symbol paints
369
+ // only when its cell is blank, and a transcript row running through
370
+ // the column keeps its text. Hover lifts the stack to the top.
234
371
  if (
235
- !countCache ||
236
- countCache.length !== lines.length ||
237
- countCache.top !== top
372
+ railDimmed() &&
373
+ stripTerminalSequences(
374
+ sliceByColumn(painted[row] ?? "", columnStart, textWidth, true),
375
+ ).trim()
238
376
  ) {
239
- countCache = {
240
- length: lines.length,
241
- top,
242
- value: promptCount(lines, top),
243
- };
377
+ rows.push(entry.row);
378
+ continue;
244
379
  }
245
- count = countCache.value;
380
+ let tile = `\x1b[${tileColor(entry)}m${text}\x1b[39m`;
381
+ if (index === current) tile = `\x1b[7m${tile}\x1b[27m`;
382
+ // Faint keeps the per-type colors readable while receding behind the
383
+ // transcript; hover restores full intensity.
384
+ if (railDimmed()) tile = `\x1b[2m${tile}\x1b[22m`;
385
+ paintRow(painted, row, tile, textWidth, columnStart, width);
386
+ rows.push(entry.row);
246
387
  }
247
- if (count) {
248
- const countWidth = visibleWidth(count);
249
- // Centred on the chips rather than the screen edge: the chips carry a
250
- // padding column each, so sharing the right margin would sit the
251
- // reading off to one side of the arrows.
252
- const centred = Math.min(
253
- start + Math.round((chipWidth - countWidth) / 2),
254
- width - RIGHT_GAP - countWidth,
388
+ return { start: width - RIGHT_GAP - bandWidth, end: start + 1, top, rows };
389
+ };
390
+
391
+ const decorate = (screen: string[], width: number): string[] => {
392
+ const painted = [...screen];
393
+ const start = width - RIGHT_GAP - chipWidth;
394
+ if (start < 0) {
395
+ hit = undefined;
396
+ } else {
397
+ hit = { start, middle: start + visibleWidth(UP), end: start + chipWidth };
398
+ // Colored per frame rather than once at install, so a theme that rejects
399
+ // the request fails inside the guard instead of out of the editor factory.
400
+ paintRow(
401
+ painted,
402
+ 0,
403
+ options.color(`${UP}${DOWN}`),
404
+ chipWidth,
405
+ start,
406
+ width,
255
407
  );
256
- paintRow(painted, 1, options.subtle(count), countWidth, centred, width);
408
+ // The reading only answers "where am I", so it stays out of the way
409
+ // while the viewport is already following the newest output.
410
+ let count: string | undefined;
411
+ if (!view.isFollowingOutput) {
412
+ const lines = contentLines(view) ?? [];
413
+ const top = view.viewportTop;
414
+ if (
415
+ !countCache ||
416
+ countCache.length !== lines.length ||
417
+ countCache.top !== top
418
+ ) {
419
+ countCache = {
420
+ length: lines.length,
421
+ top,
422
+ value: promptCount(lines, top),
423
+ };
424
+ }
425
+ count = countCache.value;
426
+ }
427
+ if (count) {
428
+ const countWidth = visibleWidth(count);
429
+ // Centred on the chips rather than the screen edge: the chips carry a
430
+ // padding column each, so sharing the right margin would sit the
431
+ // reading off to one side of the arrows.
432
+ const centred = Math.min(
433
+ start + Math.round((chipWidth - countWidth) / 2),
434
+ width - RIGHT_GAP - countWidth,
435
+ );
436
+ paintRow(painted, 1, options.subtle(count), countWidth, centred, width);
437
+ }
257
438
  }
439
+ railRect = primaryBox(view)?.rect;
440
+ railHit = paintRail(painted, width, railRect);
258
441
  return painted;
259
442
  };
260
443
 
444
+ /**
445
+ * The renderer assigns the frame's layout only after compositing, so the
446
+ * rail is always placed with the previous frame's viewport. The frames of
447
+ * a settled session make that invisible — except right after a reload,
448
+ * where the one frame drawn against the outgoing layout can be the last
449
+ * for a while, leaving the stack floating above the bottom. Once this
450
+ * frame's own layout lands, ask for one corrective repaint if it moved;
451
+ * repainting re-runs this check, which stops as soon as the rects agree.
452
+ */
453
+ const verify = () => {
454
+ if (!(options.outline?.() ?? []).length) return;
455
+ const now = primaryBox(view)?.rect;
456
+ if (now?.y === railRect?.y && now?.height === railRect?.height) return;
457
+ view.requestRender();
458
+ };
459
+
261
460
  const wrapped = (screen: string[], width: number, height: number) => {
262
461
  // This runs inside the renderer's own frame, where anything thrown leaves
263
462
  // the process with no handler and takes the session down. A decoration is
@@ -265,8 +464,11 @@ export function installPromptJump(
265
464
  let painted = screen;
266
465
  try {
267
466
  painted = decorate(screen, width);
467
+ // After the current frame completes and its layout is assigned.
468
+ queueMicrotask(verify);
268
469
  } catch {
269
470
  hit = undefined;
471
+ railHit = undefined;
270
472
  }
271
473
  // Flashes composite last, so a transient message still wins the row.
272
474
  return flashes.call(view, painted, width, height);
@@ -274,20 +476,71 @@ export function installPromptJump(
274
476
  view.compositeFlashes = wrapped;
275
477
 
276
478
  const listener: TuiInputListener = (data) => {
277
- const button = hit;
278
- if (!button) return undefined;
279
- if (!data.startsWith("\x1b")) return undefined;
479
+ if (!data.startsWith(ESC)) return undefined;
480
+ // A moving pointer batches several SGR events into one stdin chunk, so
481
+ // motion is scanned per sequence — a whole-chunk match would miss every
482
+ // coalesced stream and never prove hover tracking. The last position
483
+ // wins. Pure no-button motion drives the hover reveal and is never
484
+ // consumed: the renderer needs it for its own hover surfaces.
485
+ let moved = false;
486
+ let pointerColumn = 0;
487
+ let pointerRow = 0;
488
+ for (const segment of data.split(ESC)) {
489
+ if (!segment) continue;
490
+ const event = SGR_MOUSE_TAIL.exec(segment);
491
+ if (!event) continue;
492
+ const code = Number.parseInt(event[1] ?? "", 10);
493
+ if ((code & 32) !== 32) {
494
+ // Plain button traffic: remember whether a press is unreleased,
495
+ // which is what separates drag motion from hover below. Wheel
496
+ // reports carry bit 64 and say nothing about held buttons.
497
+ if ((code & 64) === 0) buttonHeld = event[4] === "M";
498
+ continue;
499
+ }
500
+ if ((code & 3) !== 3 && buttonHeld) continue;
501
+ moved = true;
502
+ pointerColumn = Number.parseInt(event[2] ?? "", 10) - 1;
503
+ pointerRow = Number.parseInt(event[3] ?? "", 10) - 1;
504
+ }
505
+ if (moved) {
506
+ const rail = railHit;
507
+ const wasDimmed = railDimmed();
508
+ motionSeen = true;
509
+ railHovered =
510
+ !!rail &&
511
+ pointerColumn >= rail.start &&
512
+ pointerColumn < rail.end &&
513
+ pointerRow >= RAIL_TOP &&
514
+ pointerRow < rail.top + rail.rows.length;
515
+ if (railDimmed() !== wasDimmed) view.requestRender();
516
+ return undefined;
517
+ }
280
518
  const match = SGR_MOUSE_TAIL.exec(data.slice(1));
281
519
  if (!match || match[1] !== LEFT_BUTTON) return undefined;
282
520
  const column = Number.parseInt(match[2] ?? "", 10) - 1;
283
521
  const row = Number.parseInt(match[3] ?? "", 10) - 1;
284
- if (row !== 0 || column < button.start || column >= button.end) {
285
- return undefined;
522
+ const button = hit;
523
+ if (button && row === 0 && column >= button.start && column < button.end) {
524
+ // Consume the release too, so the renderer never sees a half press and
525
+ // starts a text selection at the chips.
526
+ if (match[4] === "M") jump(view, column < button.middle ? -1 : 1);
527
+ return { consume: true };
286
528
  }
287
- // Consume the release too, so the renderer never sees a half press and
288
- // starts a text selection at the chips.
289
- if (match[4] === "M") jump(view, column < button.middle ? -1 : 1);
290
- return { consume: true };
529
+ const rail = railHit;
530
+ if (
531
+ rail &&
532
+ column >= rail.start &&
533
+ column < rail.end &&
534
+ row >= rail.top &&
535
+ row < rail.top + rail.rows.length
536
+ ) {
537
+ if (match[4] === "M") {
538
+ const target = rail.rows[row - rail.top];
539
+ if (target !== undefined) view.scrollBy(target - view.viewportTop);
540
+ }
541
+ return { consume: true };
542
+ }
543
+ return undefined;
291
544
  };
292
545
  const unsubscribe = tui.addInputListener(listener);
293
546
  prioritize(tui, listener);
@@ -300,6 +553,7 @@ export function installPromptJump(
300
553
  if (hadOwnMethod) view.compositeFlashes = flashes;
301
554
  else delete (view as Partial<Scroller>).compositeFlashes;
302
555
  hit = undefined;
556
+ railHit = undefined;
303
557
  delete target[INSTALLED];
304
558
  };
305
559
  target[INSTALLED] = dispose;
@@ -0,0 +1,200 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { Component, TUI } from "@earendil-works/pi-tui";
5
+
6
+ const INSTALLED = Symbol.for("pi-proper-base.rail-setting");
7
+ const ITEM_ID = "proper-base-session-rail";
8
+
9
+ type SettingItem = {
10
+ id: string;
11
+ label: string;
12
+ description?: string;
13
+ currentValue: string;
14
+ values?: string[];
15
+ };
16
+ /** Pi's settings selector, by shape: a component holding a SettingsList. */
17
+ type SettingsHost = Component & {
18
+ settingsList?: {
19
+ items?: SettingItem[];
20
+ onChange?: (id: string, value: string) => void;
21
+ };
22
+ };
23
+ type ComponentContainer = Component & {
24
+ children: Component[];
25
+ addChild(component: Component): void;
26
+ };
27
+ type InstalledContainer = ComponentContainer & { [INSTALLED]?: () => void };
28
+
29
+ export type RailSettingController = {
30
+ /** Whether the session action rail is enabled. Cached per session. */
31
+ enabled(): boolean;
32
+ dispose(): void;
33
+ };
34
+
35
+ function configPath(agentDir: string): string {
36
+ return join(agentDir, "proper-base.json");
37
+ }
38
+
39
+ export function readRailEnabled(agentDir: string): boolean {
40
+ try {
41
+ const parsed = JSON.parse(
42
+ readFileSync(configPath(agentDir), "utf8"),
43
+ ) as unknown;
44
+ return (parsed as { sessionRail?: unknown } | null)?.sessionRail !== false;
45
+ } catch {
46
+ return true;
47
+ }
48
+ }
49
+
50
+ /** Fail-open like the history store: a read-only agent dir only costs
51
+ * persistence, never the session. Other keys in the file are preserved. */
52
+ function writeRailEnabled(agentDir: string, enabled: boolean): void {
53
+ try {
54
+ let parsed: Record<string, unknown> = {};
55
+ try {
56
+ const existing = JSON.parse(
57
+ readFileSync(configPath(agentDir), "utf8"),
58
+ ) as unknown;
59
+ if (existing && typeof existing === "object") {
60
+ parsed = existing as Record<string, unknown>;
61
+ }
62
+ } catch {
63
+ // Damaged or absent config starts fresh.
64
+ }
65
+ parsed.sessionRail = enabled;
66
+ writeFileSync(
67
+ configPath(agentDir),
68
+ `${JSON.stringify(parsed, null, "\t")}\n`,
69
+ );
70
+ } catch {
71
+ // Persistence is best-effort.
72
+ }
73
+ }
74
+
75
+ function componentName(component: Component): string | undefined {
76
+ return (component as { constructor?: { name?: string } }).constructor?.name;
77
+ }
78
+
79
+ function childrenOf(component: Component): Component[] {
80
+ return (component as Partial<ComponentContainer>).children ?? [];
81
+ }
82
+
83
+ function findEditorContainer(
84
+ tui: TUI,
85
+ editor: Component,
86
+ ): ComponentContainer | undefined {
87
+ const roots = (tui as TUI & { layoutRoot?: Component }).layoutRoot
88
+ ? [(tui as TUI & { layoutRoot?: Component }).layoutRoot as Component]
89
+ : tui.children;
90
+ const visit = (component: Component): ComponentContainer | undefined => {
91
+ const children = childrenOf(component);
92
+ if (
93
+ children.includes(editor) &&
94
+ typeof (component as Partial<ComponentContainer>).addChild === "function"
95
+ ) {
96
+ return component as ComponentContainer;
97
+ }
98
+ for (const child of children) {
99
+ const found = visit(child);
100
+ if (found) return found;
101
+ }
102
+ return undefined;
103
+ };
104
+ for (const root of roots) {
105
+ const found = visit(root);
106
+ if (found) return found;
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * Add a "Session action rail" toggle to Pi's native `/settings` menu.
113
+ *
114
+ * Pi has no extension hook into that menu, so this is a guarded
115
+ * compatibility layer in the house style: the container Pi mounts selectors
116
+ * into is the editor's own parent, its `addChild` is wrapped once, and every
117
+ * settings selector that mounts receives one extra item spliced into its
118
+ * `SettingsList`, whose instance-held `onChange` is wrapped to keep the
119
+ * toggle out of Pi's own switch. A renamed component or list shape installs
120
+ * or injects nothing and the rail simply stays enabled.
121
+ *
122
+ * The choice persists as `sessionRail` in the agent directory's
123
+ * `proper-base.json`; other sessions pick a change up at their next start.
124
+ *
125
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
126
+ */
127
+ export function installRailSetting(
128
+ tui: TUI,
129
+ editor: Component,
130
+ agentDir: string,
131
+ ): RailSettingController {
132
+ let enabled = readRailEnabled(agentDir);
133
+ let disposed = false;
134
+ let uninstall: (() => void) | undefined;
135
+
136
+ const inject = (selector: SettingsHost): void => {
137
+ const list = selector.settingsList;
138
+ const items = list?.items;
139
+ if (!list || !Array.isArray(items) || typeof list.onChange !== "function")
140
+ return;
141
+ if (items.some((item) => item?.id === ITEM_ID)) return;
142
+ items.push({
143
+ id: ITEM_ID,
144
+ label: "Session action rail",
145
+ description:
146
+ "proper-base: colored per-action jump symbols along the transcript's right edge",
147
+ currentValue: enabled ? "true" : "false",
148
+ values: ["true", "false"],
149
+ });
150
+ const native = list.onChange;
151
+ list.onChange = (id, value) => {
152
+ if (id === ITEM_ID) {
153
+ enabled = value === "true";
154
+ writeRailEnabled(agentDir, enabled);
155
+ return;
156
+ }
157
+ native(id, value);
158
+ };
159
+ };
160
+
161
+ const wrap = () => {
162
+ if (disposed) return;
163
+ const container = findEditorContainer(tui, editor) as
164
+ | InstalledContainer
165
+ | undefined;
166
+ if (!container) return;
167
+ // A reload runs the new factory before the outgoing instance shuts
168
+ // down; take over any wrapper it left.
169
+ container[INSTALLED]?.();
170
+ const native = container.addChild.bind(container);
171
+ const wrapped = (component: Component) => {
172
+ native(component);
173
+ if (componentName(component) === "SettingsSelectorComponent") {
174
+ inject(component as SettingsHost);
175
+ }
176
+ };
177
+ container.addChild = wrapped;
178
+ const restore = () => {
179
+ if (container.addChild === wrapped) {
180
+ container.addChild = native;
181
+ }
182
+ delete container[INSTALLED];
183
+ };
184
+ container[INSTALLED] = restore;
185
+ uninstall = restore;
186
+ };
187
+
188
+ // The editor mounts into its container right after the factory returns,
189
+ // so the parent walk has to wait a tick.
190
+ queueMicrotask(wrap);
191
+
192
+ return {
193
+ enabled: () => enabled,
194
+ dispose() {
195
+ disposed = true;
196
+ uninstall?.();
197
+ uninstall = undefined;
198
+ },
199
+ };
200
+ }