proper-base 0.4.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.
package/index.ts CHANGED
@@ -59,6 +59,10 @@ import {
59
59
  PROMPT_DISPLAY_ENTRY,
60
60
  } from "./src/prompt-display.ts";
61
61
  import { installPromptJump } from "./src/prompt-jump.ts";
62
+ import {
63
+ installRailSetting,
64
+ type RailSettingController,
65
+ } from "./src/rail-setting.ts";
62
66
  import { installRecorder } from "./src/recorder.ts";
63
67
  import { installSelectionDismiss } from "./src/selection-dismiss.ts";
64
68
  import { installFastSessionList } from "./src/session-list.ts";
@@ -290,6 +294,7 @@ export default function (pi: ExtensionAPI) {
290
294
  let removeFooterColors: (() => void) | undefined;
291
295
  let removeJumpToBottom: (() => void) | undefined;
292
296
  let removePromptJump: (() => void) | undefined;
297
+ let railSetting: RailSettingController | undefined;
293
298
  let removePromptClear: (() => void) | undefined;
294
299
  let removeSmartSelection: (() => void) | undefined;
295
300
  let removeSelectionDismiss: (() => void) | undefined;
@@ -568,6 +573,8 @@ export default function (pi: ExtensionAPI) {
568
573
  removeJumpToBottom = undefined;
569
574
  removePromptJump?.();
570
575
  removePromptJump = undefined;
576
+ railSetting?.dispose();
577
+ railSetting = undefined;
571
578
  removePromptClear?.();
572
579
  removePromptClear = undefined;
573
580
  removeSmartSelection?.();
@@ -697,9 +704,16 @@ export default function (pi: ExtensionAPI) {
697
704
  removeJumpToBottom?.();
698
705
  removeJumpToBottom = installJumpToBottom(editor, tui);
699
706
  removePromptJump?.();
707
+ railSetting?.dispose();
708
+ railSetting = installRailSetting(tui, editor, getAgentDir());
709
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
700
710
  removePromptJump = installPromptJump(tui, {
701
711
  color: (value) => ctx.ui.theme.fg("muted", value),
702
712
  subtle: (value) => ctx.ui.theme.fg("dim", value),
713
+ outline: () =>
714
+ railSetting?.enabled() !== false
715
+ ? (transcriptCleanup?.outline() ?? [])
716
+ : [],
703
717
  });
704
718
  imagePreview?.dispose();
705
719
  imagePreview = installImagePreview(editor, tui, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -45,6 +45,7 @@ type InlineSlashEditor = Component & {
45
45
  handleInput?(data: string): void;
46
46
  isShowingAutocomplete?(): boolean;
47
47
  tryTriggerAutocomplete?(): void;
48
+ updateAutocomplete?(): void;
48
49
  [INLINE_SLASH_INSTALLED]?: boolean;
49
50
  };
50
51
 
@@ -104,12 +105,49 @@ export function installInlineSlashAutocomplete(editor: Component): void {
104
105
 
105
106
  const handleInput = target.handleInput.bind(target);
106
107
  target.handleInput = (data: string) => {
108
+ const wasShowing = target.isShowingAutocomplete?.() === true;
109
+ const before = wasShowing ? target.state?.lines.join("\n") : undefined;
107
110
  handleInput(data);
108
- if (target.isShowingAutocomplete?.() || !/^[/a-zA-Z0-9._:-]$/.test(data)) {
109
- return;
110
- }
111
111
  const state = target.state;
112
112
  if (!state) return;
113
+ if (target.isShowingAutocomplete?.()) {
114
+ // Word and line deletes (alt+backspace, ctrl+w/u/k) edit the prompt
115
+ // without the autocomplete refresh pi's insert and backspace paths
116
+ // run, so an open list lingers under stale text. Re-request with
117
+ // the current prompt; an emptied context closes the list through
118
+ // the editor's own no-suggestions path. Single printable keys and
119
+ // backspace already refreshed inside the editor.
120
+ if (
121
+ wasShowing &&
122
+ state.lines.join("\n") !== before &&
123
+ !(data.length === 1 && data >= " ")
124
+ ) {
125
+ target.updateAutocomplete?.();
126
+ }
127
+ return;
128
+ }
129
+ if (wasShowing) {
130
+ // Accepting a command completion closes the list and leaves
131
+ // "/command " behind, but pi re-opens suggestions only from typed
132
+ // characters, so an accepted command's argument menu — /model's
133
+ // list — stayed hidden until another keystroke. A text change
134
+ // during the open-to-closed transition is what separates
135
+ // acceptance from dismissal: Esc leaves the prompt untouched and
136
+ // must not reopen the list just closed. The token shape keeps a
137
+ // completed file path from popping a menu of its own.
138
+ const beforeCursor = (state.lines[state.cursorLine] ?? "").slice(
139
+ 0,
140
+ state.cursorCol,
141
+ );
142
+ if (
143
+ state.lines.join("\n") !== before &&
144
+ /(?:^|\s)\/[a-zA-Z0-9._:-]+ $/.test(beforeCursor)
145
+ ) {
146
+ target.tryTriggerAutocomplete?.();
147
+ }
148
+ return;
149
+ }
150
+ if (!/^[/a-zA-Z0-9._:-]$/.test(data)) return;
113
151
  if (inlineSlashContext(state.lines, state.cursorLine, state.cursorCol)) {
114
152
  target.tryTriggerAutocomplete?.();
115
153
  }
@@ -80,6 +80,35 @@ export type ReverseHistorySearchController = {
80
80
  reset(prompts: readonly string[]): void;
81
81
  };
82
82
 
83
+ /** The large-paste registry pi-tui's `setText()` clears alongside the text. */
84
+ type PasteRegistryEditor = {
85
+ setText?(text: string): void;
86
+ pastes?: Map<number, string>;
87
+ pasteCounter?: number;
88
+ };
89
+
90
+ // pi-tui's `setText()` empties its `[paste #N]` registry even when the new
91
+ // text keeps the markers; submission would then send the literal tag instead
92
+ // of the pasted content. Restore the entries the new text still references,
93
+ // and the id counter with them so the next paste cannot collide with a kept
94
+ // id.
95
+ export function setTextKeepingPastes(editor: unknown, text: string): void {
96
+ const target = editor as PasteRegistryEditor;
97
+ const registry =
98
+ target.pastes instanceof Map ? [...target.pastes] : undefined;
99
+ const counter = target.pasteCounter;
100
+ target.setText?.(text);
101
+ if (!registry?.length || !(target.pastes instanceof Map)) return;
102
+ let kept = false;
103
+ for (const [id, content] of registry) {
104
+ const marker = `[paste #${id}`;
105
+ if (!text.includes(`${marker}]`) && !text.includes(`${marker} `)) continue;
106
+ target.pastes.set(id, content);
107
+ kept = true;
108
+ }
109
+ if (kept && typeof counter === "number") target.pasteCounter = counter;
110
+ }
111
+
83
112
  function segmentImageMarkers(
84
113
  text: string,
85
114
  segments: Iterable<TextSegment>,
@@ -459,7 +488,9 @@ export function installReverseHistorySearch(
459
488
  if (target.isShowingAutocomplete?.()) handleInput("\x1b");
460
489
  const cursor = target.getCursor?.();
461
490
  // Exit Pi's native Up/Down history mode without adding an undo entry.
462
- target.setText?.(draft);
491
+ // Its setText also wipes the large-paste registry while the draft keeps
492
+ // its markers, so the entries the draft references are restored.
493
+ setTextKeepingPastes(target, draft);
463
494
  search = {
464
495
  draft,
465
496
  cursor,
@@ -18,6 +18,7 @@ import {
18
18
  import sharp from "sharp";
19
19
 
20
20
  import { isMounted, rowsBelow } from "./autocomplete-details.ts";
21
+ import { setTextKeepingPastes } from "./editor-navigation.ts";
21
22
 
22
23
  const INSTALLED = Symbol.for("pi-proper-base.image-preview");
23
24
  const ACTIVE_OVERLAY = Symbol.for("pi-proper-base.image-preview-overlay");
@@ -347,7 +348,9 @@ export function installImagePreview(
347
348
  }
348
349
  changingText = true;
349
350
  try {
350
- target.setText?.(text);
351
+ // Not plain setText: that would wipe pi-tui's large-paste registry and
352
+ // orphan any [paste #N] marker sharing the editor with this image.
353
+ setTextKeepingPastes(target, text);
351
354
  } finally {
352
355
  changingText = false;
353
356
  }
@@ -468,17 +471,31 @@ export function installImagePreview(
468
471
  },
469
472
  clear() {
470
473
  stopLoader();
471
- for (const preview of previews.values()) preview.cancelThumbnail?.();
472
- previews.clear();
473
- markersByPath.clear();
474
+ // A paste during an agent run registers a marker the user has not yet
475
+ // submitted. Wiping it here orphans the display-only `[image N]` tag
476
+ // still in the editor, so the next submit would hand that tag to the
477
+ // model instead of the source path. Only previews whose marker has
478
+ // left the editor are dropped.
479
+ const text = target.getText?.() ?? "";
480
+ for (const preview of previews.values()) {
481
+ if (text.includes(preview.marker)) continue;
482
+ preview.cancelThumbnail?.();
483
+ preview.cancelThumbnail = undefined;
484
+ previews.delete(preview.marker);
485
+ markersByPath.delete(preview.path);
486
+ }
474
487
  visibleMarkers = "";
475
488
  activePreviews = [];
476
489
  activeImages = [];
477
490
  releaseOverlay();
491
+ if (previews.size) sync(text);
478
492
  },
479
493
  dispose() {
480
494
  if (target[INSTALLED] !== controller) return;
481
495
  removeFocusRefresh();
496
+ for (const preview of previews.values()) preview.cancelThumbnail?.();
497
+ previews.clear();
498
+ markersByPath.clear();
482
499
  controller.clear();
483
500
  target.render = render;
484
501
  delete target.onChange;
@@ -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
+ }
@@ -41,6 +41,7 @@ type State = {
41
41
  expanded: Map<object, boolean>;
42
42
  hits: Map<number, DetailHit>;
43
43
  pendingHits: DetailHit[];
44
+ outline: OutlineEntry[];
44
45
  globalExpanded: boolean;
45
46
  assistantCache: WeakMap<AssistantComponent, AssistantRenderCache>;
46
47
  };
@@ -50,6 +51,17 @@ type AssistantRenderCache = {
50
51
  lines: Map<string, string[]>;
51
52
  };
52
53
  type DetailKind = "tool" | "error";
54
+ /**
55
+ * One transcript action, in scroll-content coordinates.
56
+ *
57
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
58
+ */
59
+ export type OutlineEntry = {
60
+ row: number;
61
+ kind: "user" | "assistant" | "tool" | "error";
62
+ /** Short action-type name: `prompt`, `reply`, or the tool's name. */
63
+ label: string;
64
+ };
53
65
  type Detail = {
54
66
  owner: object;
55
67
  kind: DetailKind;
@@ -84,6 +96,7 @@ export type TranscriptCleanupController = {
84
96
  completeAssistant(message: object): void;
85
97
  completeTool(toolCallId: string): void;
86
98
  settle(): void;
99
+ outline(): OutlineEntry[];
87
100
  update(ctx: ExtensionContext, tui: TUI): void;
88
101
  uninstall(): void;
89
102
  };
@@ -109,6 +122,7 @@ export function installTranscriptCleanup(
109
122
  expanded: new Map(),
110
123
  hits: new Map(),
111
124
  pendingHits: [],
125
+ outline: [],
112
126
  globalExpanded: ctx.ui.getToolsExpanded(),
113
127
  assistantCache: new WeakMap(),
114
128
  };
@@ -170,6 +184,9 @@ export function installTranscriptCleanup(
170
184
  };
171
185
  state.tui.requestRender();
172
186
  },
187
+ outline() {
188
+ return state.outline;
189
+ },
173
190
  update(nextCtx, nextTui) {
174
191
  state = {
175
192
  ...state,
@@ -197,17 +214,34 @@ export function installTranscriptCleanup(
197
214
  state = { ...state, globalExpanded, expanded: new Map() };
198
215
  }
199
216
  state.pendingHits.length = 0;
217
+ const sink: OutlineEntry[] = [];
200
218
  let lines: string[];
201
219
  if (state.activeStart === undefined && state.ctx.isIdle()) {
202
- lines = renderCollapsed(chat.children, width, state);
220
+ lines = renderCollapsed(chat.children, width, state, sink);
203
221
  } else {
204
222
  const start = state.activeStart ?? chat.children.length;
223
+ const collapsed = renderCollapsed(
224
+ chat.children.slice(0, start),
225
+ width,
226
+ state,
227
+ sink,
228
+ );
205
229
  lines = [
206
- ...renderCollapsed(chat.children.slice(0, start), width, state),
207
- ...renderActive(chat.children.slice(start), width, state),
230
+ ...collapsed,
231
+ ...renderActive(
232
+ chat.children.slice(start),
233
+ width,
234
+ state,
235
+ sink,
236
+ collapsed.length,
237
+ ),
208
238
  ];
209
239
  }
210
- indexDetailHits(lines, documentRowOffset(document, chat, width), state);
240
+ const offset = documentRowOffset(document, chat, width);
241
+ state.outline = sink
242
+ .map((entry) => ({ ...entry, row: offset + entry.row }))
243
+ .sort((a, b) => a.row - b.row);
244
+ indexDetailHits(lines, offset, state);
211
245
  return lines;
212
246
  };
213
247
  chat[INSTALLED] = controller;
@@ -218,6 +252,8 @@ function renderActive(
218
252
  children: Component[],
219
253
  width: number,
220
254
  state: State,
255
+ sink: OutlineEntry[],
256
+ base: number,
221
257
  ): string[] {
222
258
  const output: string[][] = Array.from({ length: children.length });
223
259
  let hasTextBelow = false;
@@ -227,23 +263,54 @@ function renderActive(
227
263
  const native = child.render(width);
228
264
  output[index] =
229
265
  state.completed.has(child) && hasTextBelow
230
- ? renderGroup([child], width, state)
266
+ ? renderGroup([child], width, state, [], 0)
231
267
  : native;
232
268
  if (hasSectionText(native)) hasTextBelow = true;
233
269
  }
270
+ // Outline rows are recorded on a forward pass because the render loop above
271
+ // walks backwards; the discarded renderGroup sink avoids double records.
272
+ let row = base;
273
+ for (let index = 0; index < children.length; index++) {
274
+ const rendered = output[index];
275
+ const child = children[index];
276
+ if (child && rendered?.length) {
277
+ const entry = actionEntry(child);
278
+ if (entry) sink.push({ ...entry, row });
279
+ }
280
+ row += rendered?.length ?? 0;
281
+ }
234
282
  return output.flat();
235
283
  }
236
284
 
285
+ function actionEntry(child: Component): Omit<OutlineEntry, "row"> | undefined {
286
+ if (isUserBoundary(child)) {
287
+ return { kind: "user", label: "prompt" };
288
+ }
289
+ const name = componentName(child);
290
+ if (name === "AssistantMessageComponent") {
291
+ return { kind: "assistant", label: "reply" };
292
+ }
293
+ if (name === "ToolExecutionComponent") {
294
+ const tool = child as ToolComponent;
295
+ return {
296
+ kind: tool.result?.isError === true ? "error" : "tool",
297
+ label: tool.toolName ?? "tool",
298
+ };
299
+ }
300
+ return undefined;
301
+ }
302
+
237
303
  function renderCollapsed(
238
304
  children: Component[],
239
305
  width: number,
240
306
  state: State,
307
+ sink: OutlineEntry[],
241
308
  ): string[] {
242
309
  const lines: string[] = [];
243
310
  let group: Component[] = [];
244
311
  const flush = () => {
245
312
  if (!group.length) return;
246
- lines.push(...renderGroup(group, width, state));
313
+ lines.push(...renderGroup(group, width, state, sink, lines.length));
247
314
  group = [];
248
315
  };
249
316
 
@@ -278,12 +345,19 @@ function renderGroup(
278
345
  group: Component[],
279
346
  width: number,
280
347
  state: State,
348
+ sink: OutlineEntry[],
349
+ base: number,
281
350
  ): string[] {
282
351
  const lines: string[] = [];
283
352
 
284
353
  for (const child of group) {
285
354
  const name = componentName(child);
286
355
  if (isUserBoundary(child)) {
356
+ sink.push({
357
+ kind: "user",
358
+ row: base + lines.length,
359
+ label: "prompt",
360
+ });
287
361
  lines.push(...child.render(width));
288
362
  continue;
289
363
  }
@@ -292,10 +366,18 @@ function renderGroup(
292
366
  continue;
293
367
  }
294
368
  if (name === "AssistantMessageComponent") {
369
+ const startRow = lines.length;
295
370
  const assistant = child as AssistantComponent;
296
371
  const message = assistant.lastMessage;
297
372
  if (!message || !assistant.updateContent) {
298
373
  lines.push(...child.render(width));
374
+ if (lines.length > startRow) {
375
+ sink.push({
376
+ kind: "assistant",
377
+ row: base + startRow,
378
+ label: "reply",
379
+ });
380
+ }
299
381
  continue;
300
382
  }
301
383
  const hasToolCall = message.content.some(
@@ -344,11 +426,25 @@ function renderGroup(
344
426
  );
345
427
  }
346
428
  }
429
+ // A turn whose reply was only tool calls emits nothing of its own; its
430
+ // visible actions are the tool rows, so no assistant entry is recorded.
431
+ if (lines.length > startRow) {
432
+ sink.push({
433
+ kind: "assistant",
434
+ row: base + startRow,
435
+ label: "reply",
436
+ });
437
+ }
347
438
  continue;
348
439
  }
349
440
  if (name === "ToolExecutionComponent") {
350
441
  const tool = child as ToolComponent;
351
442
  const error = tool.result?.isError === true;
443
+ sink.push({
444
+ kind: error ? "error" : "tool",
445
+ row: base + lines.length,
446
+ label: tool.toolName ?? "tool",
447
+ });
352
448
  lines.push(
353
449
  ...renderDetail(
354
450
  {
@@ -488,6 +584,10 @@ function detailColor(
488
584
  }
489
585
 
490
586
  function describeTool(tool: ToolComponent, error: boolean): string {
587
+ return `${error ? "error" : "tool"} · ${toolLabel(tool)}`;
588
+ }
589
+
590
+ function toolLabel(tool: ToolComponent): string {
491
591
  const name = tool.toolName ?? "tool";
492
592
  const args = asRecord(tool.args);
493
593
  const value = [
@@ -502,8 +602,7 @@ function describeTool(tool: ToolComponent, error: boolean): string {
502
602
  ]
503
603
  .map((key) => args?.[key])
504
604
  .find((candidate): candidate is string => typeof candidate === "string");
505
- const target = value ? ` · ${oneLine(value)}` : "";
506
- return `${error ? "error" : "tool"} · ${name}${target}`;
605
+ return value ? `${name} · ${oneLine(value)}` : name;
507
606
  }
508
607
 
509
608
  function oneLine(text: string): string {