pi-petrroll 0.2.2 → 0.3.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.
package/README.md CHANGED
@@ -6,6 +6,7 @@ Small, focused extensions for [Pi](https://pi.dev). MIT licensed.
6
6
  | --- | --- | --- |
7
7
  | [Change directory](#change-directory) | `/cd <path>` | `change_directory` |
8
8
  | [External costs](#external-costs) | — | `add_cost` |
9
+ | [Scrollbar marks](#scrollbar-marks) | — | — |
9
10
 
10
11
  Independent, focused extensions. No skills, shell wrappers, or replacement built-in tools.
11
12
 
@@ -47,7 +48,7 @@ All extensions load by default. To load only `cd`, including after future update
47
48
  }
48
49
  ```
49
50
 
50
- Disabling `cd` disables both `/cd` and its `change_directory` tool. Disabling `cost` disables `add_cost`. To load only cost recording, use `"extensions": ["extensions/cost/index.ts"]` in the package entry above.
51
+ Disabling `cd` disables both `/cd` and its `change_directory` tool. Disabling `cost` disables `add_cost`. Disabling `scrollbar-marks` restores Pi's plain scrollbar. To load only cost recording, use `"extensions": ["extensions/cost/index.ts"]` in the package entry above.
51
52
 
52
53
  ## Change directory
53
54
 
@@ -123,6 +124,24 @@ After launching a subagent with the ordinary `bash` tool, Pi can call `add_cost`
123
124
 
124
125
  Pi's totals include all entries in the session file, including abandoned branches. Forked or copied sessions inherit costs present in their copied history; a new empty session starts at zero. No session files or Pi internals are patched.
125
126
 
127
+ ## Scrollbar marks
128
+
129
+ Marks where your prompts and the assistant's replies start on the scrollbar at the right of Pi's fullscreen transcript, like an editor's overview ruler:
130
+
131
+ - **Prompts**: `━` in the theme's accent color.
132
+ - **Replies** (assistant text): `─` in the text color.
133
+
134
+ Under the thumb, a mark crosses it as `╋` (accent for prompts, the thumb color for replies), so the thumb keeps its width. While you drag the scrollbar, Pi shows a solid `█` thumb. Prompts then recolor it to accent, and reply marks are hidden.
135
+
136
+ Each mark sits at its proportional position in the transcript, so dragging or scrolling the thumb onto a mark brings that message into view. Prompts win when both fall on the same row. Tool output, thinking-only, and tool-call-only assistant turns are not marked.
137
+
138
+ The marks appear whenever Pi shows the scrollbar. With the default `"fullscreenScrollbar": "auto"`, that is only briefly while scrolling. Set `"fullscreenScrollbar": "always"` in `~/.pi/agent/settings.json` to keep the scrollbar and marks visible.
139
+
140
+ Limitations:
141
+
142
+ - Fullscreen TUI mode only (Pi's default `tuiMode`). In regular mode the terminal owns scrollback and the scrollbar, so the extension does nothing. Print, JSON, and RPC modes are unaffected.
143
+ - Pi has no public scrollbar API yet. The extension wraps the transcript `ScrollView`'s scrollbar style callbacks and content render on that one instance, and wraps `UserMessageComponent.render` once per process to tell prompts from replies. It finds message starts from the OSC 133 zone markers Pi already renders. Disabling or reloading restores the original callbacks. Tested against Pi 1.4.0; future Pi versions may change these internals.
144
+
126
145
  ## Development
127
146
 
128
147
  ```sh
@@ -131,7 +150,7 @@ npm run check
131
150
  npm test
132
151
  ```
133
152
 
134
- Tests cover cost validation, native cost accumulation, persistence/resume, compaction, path handling, copy/branch preservation, cancellation, aborts, concurrency, and a real Pi runtime handoff with a fake model stream. The runtime test verifies that tool results are copied, `read` and `bash` use the new cwd, destination `AGENTS.md` replaces source context, and the agent continues only after the host finishes switching. Unit tests also cover continuation-submission failures without rolling back the successful switch. Tests do not call a model API or use your credentials.
153
+ Tests cover scrollbar mark detection, scaling, painting, and restoration, cost validation, native cost accumulation, persistence/resume, compaction, path handling, copy/branch preservation, cancellation, aborts, concurrency, and a real Pi runtime handoff with a fake model stream. The runtime test verifies that tool results are copied, `read` and `bash` use the new cwd, destination `AGENTS.md` replaces source context, and the agent continues only after the host finishes switching. Unit tests also cover continuation-submission failures without rolling back the successful switch. Tests do not call a model API or use your credentials.
135
154
 
136
155
  ```text
137
156
  extensions/
@@ -139,10 +158,14 @@ extensions/
139
158
  index.ts
140
159
  cost/
141
160
  index.ts
161
+ scrollbar-marks/
162
+ index.ts
163
+ marks.ts
142
164
  tests/
143
165
  cd.test.ts
144
166
  cost.test.ts
145
167
  runtime.test.ts
168
+ scrollbar-marks.test.ts
146
169
  ```
147
170
 
148
171
  Pi discovers entry points through `pi.extensions` in `package.json`. Add future independent extensions under `extensions/<name>/index.ts`; no new skill or package is needed. Keep helpers inside the extension directory so they are not discovered as standalone extensions.
@@ -0,0 +1,116 @@
1
+ import { UserMessageComponent, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { attachScrollbarMarks, type AttachOptions, type MarkKind, type MarkStyles, type ScrollViewLike } from "./marks.ts";
3
+
4
+ const WIDGET_KEY = "pi-petrroll.scrollbar-marks";
5
+ const USER_SINK = Symbol.for("pi-petrroll.scrollbar-marks.user-sink");
6
+ const USER_PATCHED = Symbol.for("pi-petrroll.scrollbar-marks.user-patched");
7
+
8
+ type SinkHolder = typeof globalThis & { [USER_SINK]?: Set<string> };
9
+
10
+ /**
11
+ * Record the first rendered line of every user message while a transcript render is collecting.
12
+ * Installed once per process; it survives `/reload` and only forwards to the current collector.
13
+ */
14
+ function patchUserMessages(): boolean {
15
+ const proto = (UserMessageComponent as unknown as { prototype?: Record<PropertyKey, unknown> } | undefined)?.prototype;
16
+ if (!proto || typeof proto.render !== "function") return false;
17
+ if (proto[USER_PATCHED]) return true;
18
+ const original = proto.render as (this: unknown, width: number) => string[];
19
+ proto.render = function (this: unknown, width: number): string[] {
20
+ const lines = original.call(this, width);
21
+ const sink = (globalThis as SinkHolder)[USER_SINK];
22
+ if (sink && lines.length > 0) sink.add(lines[0]!);
23
+ return lines;
24
+ };
25
+ proto[USER_PATCHED] = true;
26
+ return true;
27
+ }
28
+
29
+ const classifyUserMessages: NonNullable<AttachOptions["classify"]> = (render) => {
30
+ const holder = globalThis as SinkHolder;
31
+ const previous = holder[USER_SINK];
32
+ const prompts = new Set<string>();
33
+ holder[USER_SINK] = prompts;
34
+ try {
35
+ return { result: render(), isPrompt: (line) => prompts.has(line) };
36
+ } finally {
37
+ holder[USER_SINK] = previous;
38
+ }
39
+ };
40
+
41
+ type ThemeLike = { fg(color: "accent" | "text", text: string): string };
42
+
43
+ export function createMarkStyles(theme: ThemeLike): MarkStyles {
44
+ const color = (kind: MarkKind) => (kind === "prompt" ? "accent" : "text");
45
+ return {
46
+ track: (kind) => theme.fg(color(kind), kind === "prompt" ? "━" : "─"),
47
+ // Keep the thumb's width: the idle thumb "┃" becomes a heavy cross "╋" (the same tick as on the
48
+ // track, crossing the thumb); the active block thumb "█" cannot carry a tick, so only prompts
49
+ // recolor it. Replies stay in Pi's thumb color so the thumb never changes width or vanishes.
50
+ thumb: (kind, glyph, piThumb) => {
51
+ const cell = glyph === "┃" ? "╋" : glyph;
52
+ return kind === "prompt" ? theme.fg("accent", cell) : piThumb(cell);
53
+ },
54
+ };
55
+ }
56
+
57
+ function isTranscriptView(value: unknown): value is ScrollViewLike {
58
+ const view = value as Partial<ScrollViewLike> | undefined;
59
+ return (
60
+ !!view &&
61
+ view.primary === true &&
62
+ typeof view.updateLayout === "function" &&
63
+ typeof view.scrollbarTrackStyle === "function" &&
64
+ typeof view.scrollbarThumbStyle === "function" &&
65
+ Array.isArray(view.children) &&
66
+ typeof view.children[0]?.render === "function"
67
+ );
68
+ }
69
+
70
+ function install(ctx: ExtensionContext): void {
71
+ const canClassify = patchUserMessages();
72
+ ctx.ui.setWidget(
73
+ WIDGET_KEY,
74
+ (tui, theme) => {
75
+ let view: ScrollViewLike | undefined;
76
+ let restore: (() => void) | undefined;
77
+ const styles = createMarkStyles(theme);
78
+ return {
79
+ // Renders nothing below the editor. It is only here to see the TUI each frame and attach to
80
+ // the fullscreen transcript once it exists (regular mode has no primary scroll view).
81
+ render(): string[] {
82
+ const candidate = (tui as unknown as { getPrimaryScrollView?: () => unknown }).getPrimaryScrollView?.();
83
+ if (candidate !== view && isTranscriptView(candidate)) {
84
+ restore?.();
85
+ view = candidate;
86
+ restore = attachScrollbarMarks(candidate, {
87
+ styles,
88
+ ...(canClassify ? { classify: classifyUserMessages } : {}),
89
+ });
90
+ tui.requestRender();
91
+ }
92
+ return [];
93
+ },
94
+ invalidate(): void {},
95
+ dispose(): void {
96
+ restore?.();
97
+ restore = undefined;
98
+ view = undefined;
99
+ },
100
+ };
101
+ },
102
+ { placement: "belowEditor" },
103
+ );
104
+ }
105
+
106
+ export default function (pi: ExtensionAPI) {
107
+ pi.on("session_start", async (_event, ctx) => {
108
+ if (ctx.mode !== "tui") return;
109
+ install(ctx);
110
+ });
111
+
112
+ pi.on("session_shutdown", async (_event, ctx) => {
113
+ if (ctx.mode !== "tui") return;
114
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
115
+ });
116
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Scrollbar marks for Pi's fullscreen transcript.
3
+ *
4
+ * Pi paints the transcript scrollbar one row at a time, top to bottom, calling the ScrollView's
5
+ * `scrollbarTrackStyle` or `scrollbarThumbStyle` once per row right after layout. This module wraps
6
+ * those callbacks on one ScrollView instance (plus its content render and `updateLayout`) so each
7
+ * row can show whether a prompt or reply starts in the corresponding part of the transcript.
8
+ * Everything is instance-level and fully reversible; no Pi module is modified.
9
+ */
10
+
11
+ export type MarkKind = "prompt" | "reply";
12
+
13
+ /** Rendered message starts carry an OSC 133 prompt-zone start, possibly after other zone markers. */
14
+ const ZONE_START = /^(?:\x1b\]133;[BC](?:\x07|\x1b\\))*\x1b\]133;A(?:\x07|\x1b\\)/;
15
+
16
+ export interface MarkStyles {
17
+ /** Track cell (outside the thumb) for a row containing a mark. */
18
+ track(kind: MarkKind): string;
19
+ /**
20
+ * Thumb cell for a row containing a mark; receives Pi's thumb glyph and Pi's thumb styler.
21
+ * Return undefined to keep Pi's thumb unchanged.
22
+ */
23
+ thumb(kind: MarkKind, glyph: string, piThumb: (text: string) => string): string | undefined;
24
+ }
25
+
26
+ /** Minimal structural view of `@earendil-works/pi-tui`'s ScrollView that this module relies on. */
27
+ export interface ScrollViewLike {
28
+ readonly primary: boolean;
29
+ readonly children: { render(width: number): string[] }[];
30
+ scrollbarTrackStyle: (text: string) => string;
31
+ scrollbarThumbStyle: (text: string) => string;
32
+ updateLayout(contentHeight: number, viewportHeight: number, requestRender: () => void): void;
33
+ }
34
+
35
+ /** Content rows where prompts and replies start, in transcript order. */
36
+ export interface ContentMarks {
37
+ prompt: number[];
38
+ reply: number[];
39
+ }
40
+
41
+ /**
42
+ * Find message starts in rendered transcript lines.
43
+ * `isPrompt(line)` decides whether a zone-start line belongs to a user prompt; others are replies.
44
+ */
45
+ export function findMarks(lines: readonly string[], isPrompt: (line: string) => boolean): ContentMarks {
46
+ const marks: ContentMarks = { prompt: [], reply: [] };
47
+ for (let row = 0; row < lines.length; row++) {
48
+ const line = lines[row]!;
49
+ if (!ZONE_START.test(line)) continue;
50
+ (isPrompt(line) ? marks.prompt : marks.reply).push(row);
51
+ }
52
+ return marks;
53
+ }
54
+
55
+ /**
56
+ * Map content rows onto scrollbar rows, like an overview ruler: row `r` of `contentHeight` lands on
57
+ * track row `floor(r * trackHeight / contentHeight)`. Prompts win over replies on shared rows.
58
+ */
59
+ export function mapToTrack(marks: ContentMarks, contentHeight: number, trackHeight: number): (MarkKind | undefined)[] {
60
+ const track: (MarkKind | undefined)[] = new Array(Math.max(0, trackHeight)).fill(undefined);
61
+ if (contentHeight <= 0 || trackHeight <= 0) return track;
62
+ const scale = Math.min(1, trackHeight / contentHeight);
63
+ const place = (row: number, kind: MarkKind) => {
64
+ const index = Math.min(trackHeight - 1, Math.floor(row * scale));
65
+ if (index >= 0 && track[index] !== "prompt") track[index] = kind;
66
+ };
67
+ for (const row of marks.reply) place(row, "reply");
68
+ for (const row of marks.prompt) place(row, "prompt");
69
+ return track;
70
+ }
71
+
72
+ export interface AttachOptions {
73
+ styles: MarkStyles;
74
+ /**
75
+ * Run the transcript render and report which zone-start lines are prompts.
76
+ * Defaults to treating every zone start as a reply.
77
+ */
78
+ classify?: <T>(render: () => T) => { result: T; isPrompt: (line: string) => boolean };
79
+ }
80
+
81
+ const ATTACHED = Symbol.for("pi-petrroll.scrollbar-marks.attached");
82
+
83
+ /** Install marks on a ScrollView. Returns an idempotent function that restores the original behavior. */
84
+ export function attachScrollbarMarks(view: ScrollViewLike, options: AttachOptions): () => void {
85
+ const target = view as ScrollViewLike & { [ATTACHED]?: () => void };
86
+ target[ATTACHED]?.();
87
+
88
+ const child = view.children[0];
89
+ if (!child) return () => {};
90
+
91
+ const originalTrack = view.scrollbarTrackStyle;
92
+ const originalThumb = view.scrollbarThumbStyle;
93
+ const hadOwnUpdateLayout = Object.prototype.hasOwnProperty.call(view, "updateLayout");
94
+ const originalUpdateLayout = view.updateLayout;
95
+ const hadOwnRender = Object.prototype.hasOwnProperty.call(child, "render");
96
+ const originalRender = child.render;
97
+ const classify = options.classify ?? ((render) => ({ result: render(), isPrompt: () => false }));
98
+
99
+ let marks: ContentMarks = { prompt: [], reply: [] };
100
+ let track: (MarkKind | undefined)[] = [];
101
+ let row = 0;
102
+
103
+ child.render = function (this: unknown, width: number): string[] {
104
+ const { result, isPrompt } = classify(() => originalRender.call(child, width));
105
+ marks = findMarks(result, isPrompt);
106
+ return result;
107
+ };
108
+
109
+ view.updateLayout = function (this: unknown, contentHeight, viewportHeight, requestRender) {
110
+ originalUpdateLayout.call(view, contentHeight, viewportHeight, requestRender);
111
+ track = mapToTrack(marks, contentHeight, viewportHeight);
112
+ row = 0;
113
+ };
114
+
115
+ view.scrollbarTrackStyle = (text) => {
116
+ const kind = track[row++];
117
+ return kind ? options.styles.track(kind) : originalTrack(text);
118
+ };
119
+ view.scrollbarThumbStyle = (text) => {
120
+ const kind = track[row++];
121
+ return (kind && options.styles.thumb(kind, text, originalThumb)) ?? originalThumb(text);
122
+ };
123
+
124
+ let restored = false;
125
+ const restore = () => {
126
+ if (restored) return;
127
+ restored = true;
128
+ view.scrollbarTrackStyle = originalTrack;
129
+ view.scrollbarThumbStyle = originalThumb;
130
+ if (hadOwnUpdateLayout) view.updateLayout = originalUpdateLayout;
131
+ else delete (view as Partial<ScrollViewLike>).updateLayout;
132
+ if (hadOwnRender) child.render = originalRender;
133
+ else delete (child as Partial<typeof child>).render;
134
+ if (target[ATTACHED] === restore) delete target[ATTACHED];
135
+ };
136
+ target[ATTACHED] = restore;
137
+ return restore;
138
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-petrroll",
3
- "version": "0.2.2",
4
- "description": "Small, focused Pi extensions by petrroll: switch projects and track external costs in your session.",
3
+ "version": "0.3.1",
4
+ "description": "Small, focused Pi extensions by petrroll: switch projects, track external costs, and mark prompts on the scrollbar.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Petr Houška (petrroll)",