proper-base 0.2.5 → 0.2.7

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
@@ -106,15 +106,25 @@ dragging.
106
106
  ### Clipboard and model image context
107
107
 
108
108
  Ctrl+V and Ctrl+Shift+V both use Pi's image-or-text clipboard action. Readable
109
- clipboard image paths appear as short `[image N]` markers, while a text-only
110
- panel shows their source paths. Deleting inside a marker removes the whole
111
- marker. On submit, each marker expands back to the path the agent can read.
112
-
113
- proper-base never enables Kitty rendering or changes terminal image
114
- capabilities. Images remain in model context for every tool loop in the turn
115
- that introduced them. A later user message replaces older image blocks only in
116
- the outbound context copy, so saved sessions, exports, resumes, and branches
117
- retain the originals.
109
+ clipboard image paths appear as short `[image N]` markers. Image-capable
110
+ terminals render compact previews; text-only terminals show marker source paths.
111
+ Oversized sources are converted to pixel-bounded PNG thumbnails with the
112
+ package's asynchronous `sharp` dependency instead of transmitting the full image
113
+ for a tiny preview. `sharp` ships prebuilt macOS arm64/x64 and Linux binaries, so
114
+ no external image command is required. Pi's accent braille loader animates while conversion runs; the
115
+ marker and path appear only if conversion is unavailable or fails. When terminal
116
+ focus returns, active Kitty previews are retransmitted so a lost terminal-side
117
+ scene cannot remain blank behind Pi's upload cache. Left and Right treat each
118
+ intact `[image N]` marker as one cursor token. When the cursor lands on it, Pi
119
+ inverse-highlights the complete marker; Backspace removes the whole highlighted
120
+ token. On submit, each marker expands back to the original path the agent can
121
+ read.
122
+
123
+ Under `TERM_PROGRAM=Scribe`, proper-base enables Kitty capability before Pi's
124
+ renderer starts. Other terminals keep Pi's detected capabilities. Images remain
125
+ in model context for every tool loop in the turn that introduced them. A later
126
+ user message replaces older image blocks only in the outbound context copy, so
127
+ saved sessions, exports, resumes, and branches retain the originals.
118
128
 
119
129
  ### Footer
120
130
 
package/index.ts CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  import { type HistoryGuard, installHistoryGuard } from "./src/history-guard.ts";
41
41
  import { omitPriorTurnImages } from "./src/image-context.ts";
42
42
  import {
43
+ enableScribeImageCapability,
43
44
  type ImagePreviewController,
44
45
  installImagePreview,
45
46
  } from "./src/image-preview.ts";
@@ -210,6 +211,8 @@ function decodeModelReference(value: string): ModelReference | undefined {
210
211
  }
211
212
 
212
213
  export default function (pi: ExtensionAPI) {
214
+ enableScribeImageCapability();
215
+
213
216
  let removeFooterColors: (() => void) | undefined;
214
217
  let removeJumpToBottom: (() => void) | undefined;
215
218
  let removePromptClear: (() => void) | undefined;
@@ -572,14 +575,17 @@ export default function (pi: ExtensionAPI) {
572
575
  activeTui = tui;
573
576
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
574
577
  transcriptCleanup?.uninstall();
575
- transcriptCleanup = installTranscriptCleanup(tui, ctx, keybindings);
578
+ transcriptCleanup = installTranscriptCleanup(tui, ctx);
576
579
  removeSmartSelection?.();
577
580
  removeSmartSelection = installSmartSelection(tui);
578
581
  historyGuard = installHistoryGuard(editor);
579
582
  removeJumpToBottom?.();
580
583
  removeJumpToBottom = installJumpToBottom(editor, tui);
581
584
  imagePreview?.dispose();
582
- imagePreview = installImagePreview(editor, tui);
585
+ imagePreview = installImagePreview(editor, tui, {
586
+ fallbackColor: (value) => ctx.ui.theme.fg("dim", value),
587
+ loadingColor: (value) => ctx.ui.theme.fg("accent", value),
588
+ });
583
589
  installEditorNavigation(editor, keybindings);
584
590
  installInlineSlashAutocomplete(editor);
585
591
  installRecorder(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -62,5 +62,8 @@
62
62
  "extensions": [
63
63
  "./index.ts"
64
64
  ]
65
+ },
66
+ "dependencies": {
67
+ "sharp": "0.35.3"
65
68
  }
66
69
  }
@@ -13,6 +13,7 @@ const REVERSE_SEARCH_INSTALLED = Symbol.for(
13
13
  );
14
14
  const PROMPT_CLEAR_INSTALLED = Symbol.for("pi-proper-base.prompt-clear");
15
15
  const CLEAR_EXIT_WINDOW_MS = 500;
16
+ const IMAGE_MARKER = /\[image [1-9]\d*\]/g;
16
17
 
17
18
  type Keybindings = {
18
19
  matches(data: string, action: string): boolean;
@@ -34,6 +35,12 @@ type PromptClearController = {
34
35
  ): void;
35
36
  };
36
37
 
38
+ type TextSegment = {
39
+ segment: string;
40
+ index: number;
41
+ input: string;
42
+ };
43
+
37
44
  type NavigableEditor = Component & {
38
45
  borderColor?(text: string): string;
39
46
  handleInput?(data: string): void;
@@ -49,6 +56,7 @@ type NavigableEditor = Component & {
49
56
  cursorCol: number;
50
57
  };
51
58
  setCursorCol?(column: number): void;
59
+ segment?(text: string, mode: "grapheme" | "word"): Iterable<TextSegment>;
52
60
  lastWidth?: number;
53
61
  buildVisualLineMap?(width: number): Array<{
54
62
  logicalLine: number;
@@ -72,6 +80,55 @@ export type ReverseHistorySearchController = {
72
80
  reset(prompts: readonly string[]): void;
73
81
  };
74
82
 
83
+ function segmentImageMarkers(
84
+ text: string,
85
+ segments: Iterable<TextSegment>,
86
+ ): TextSegment[] {
87
+ const markers = [...text.matchAll(IMAGE_MARKER)].map((match) => ({
88
+ start: match.index,
89
+ end: match.index + match[0].length,
90
+ }));
91
+ if (markers.length === 0) return [...segments];
92
+
93
+ const result: TextSegment[] = [];
94
+ let markerIndex = 0;
95
+ for (const segment of segments) {
96
+ while (
97
+ markerIndex < markers.length &&
98
+ (markers[markerIndex]?.end ?? 0) <= segment.index
99
+ ) {
100
+ markerIndex += 1;
101
+ }
102
+ const marker = markers[markerIndex];
103
+ if (marker && segment.index >= marker.start && segment.index < marker.end) {
104
+ if (segment.index === marker.start) {
105
+ result.push({
106
+ segment: text.slice(marker.start, marker.end),
107
+ index: marker.start,
108
+ input: text,
109
+ });
110
+ }
111
+ continue;
112
+ }
113
+ result.push(segment);
114
+ }
115
+ return result;
116
+ }
117
+
118
+ function imageMarkerCursorTarget(
119
+ line: string,
120
+ column: number,
121
+ direction: "left" | "right",
122
+ ): number | undefined {
123
+ for (const match of line.matchAll(IMAGE_MARKER)) {
124
+ const start = match.index;
125
+ const end = start + match[0].length;
126
+ if (direction === "left" && column > start && column <= end) return start;
127
+ if (direction === "right" && column >= start && column < end) return end;
128
+ }
129
+ return undefined;
130
+ }
131
+
75
132
  export function installEditorNavigation(
76
133
  editor: Component,
77
134
  keybindings: Keybindings,
@@ -86,10 +143,21 @@ export function installEditorNavigation(
86
143
  return;
87
144
  }
88
145
 
146
+ const segment = target.segment?.bind(target);
147
+ if (segment) {
148
+ target.segment = (text, mode) =>
149
+ segmentImageMarkers(text, segment(text, mode));
150
+ }
89
151
  const handleInput = target.handleInput.bind(target);
90
152
  target.handleInput = (data: string) => {
91
153
  const home = keybindings.matches(data, "tui.editor.cursorLineStart");
92
154
  const end = keybindings.matches(data, "tui.editor.cursorLineEnd");
155
+ const left = keybindings.matches(data, "tui.editor.cursorLeft");
156
+ const right = keybindings.matches(data, "tui.editor.cursorRight");
157
+ const backspace = keybindings.matches(
158
+ data,
159
+ "tui.editor.deleteCharBackward",
160
+ );
93
161
  const previous =
94
162
  keybindings.matches(data, "tui.editor.cursorUp") ||
95
163
  keybindings.matches(data, "tui.editor.historyPrevious");
@@ -97,6 +165,37 @@ export function installEditorNavigation(
97
165
  handleInput(data);
98
166
  return;
99
167
  }
168
+ if (backspace) {
169
+ const cursor = target.getCursor?.();
170
+ const state = target.state;
171
+ const line = cursor ? target.getLines?.()[cursor.line] : undefined;
172
+ const marker = line
173
+ ? [...line.matchAll(IMAGE_MARKER)].find(
174
+ (match) => match.index === cursor?.col,
175
+ )
176
+ : undefined;
177
+ if (cursor && state && marker) {
178
+ const end = marker.index + marker[0].length;
179
+ if (target.setCursorCol) target.setCursorCol(end);
180
+ else state.cursorCol = end;
181
+ handleInput(data);
182
+ return;
183
+ }
184
+ }
185
+ if (left || right) {
186
+ const cursor = target.getCursor?.();
187
+ const state = target.state;
188
+ const line = cursor ? target.getLines?.()[cursor.line] : undefined;
189
+ const column =
190
+ cursor && line !== undefined
191
+ ? imageMarkerCursorTarget(line, cursor.col, left ? "left" : "right")
192
+ : undefined;
193
+ if (column !== undefined && state) {
194
+ if (target.setCursorCol) target.setCursorCol(column);
195
+ else state.cursorCol = column;
196
+ return;
197
+ }
198
+ }
100
199
  if (previous) {
101
200
  const before = target.getLines?.().join("\n");
102
201
  handleInput(data);
@@ -1,22 +1,42 @@
1
- import { accessSync, constants } from "node:fs";
2
- import { basename, isAbsolute } from "node:path";
3
-
1
+ import { readFileSync } from "node:fs";
2
+ import { basename, extname, isAbsolute } from "node:path";
4
3
  import {
5
4
  type Component,
5
+ getCapabilities,
6
+ getCellDimensions,
7
+ getImageDimensions,
8
+ Image,
9
+ type ImageTheme,
10
+ Loader,
6
11
  type OverlayHandle,
7
12
  type OverlayMargin,
8
13
  type OverlayOptions,
14
+ setCapabilities,
9
15
  type TUI,
10
16
  wrapTextWithAnsi,
11
17
  } from "@earendil-works/pi-tui";
18
+ import sharp from "sharp";
12
19
 
13
20
  import { isMounted, rowsBelow } from "./autocomplete-details.ts";
14
21
 
15
22
  const INSTALLED = Symbol.for("pi-proper-base.image-preview");
16
23
  const ACTIVE_OVERLAY = Symbol.for("pi-proper-base.image-preview-overlay");
24
+ const FOCUS_REFRESH = Symbol.for("pi-proper-base.image-preview-focus-refresh");
25
+ const FOCUS_IN = "\x1b[I";
17
26
  const CLIPBOARD_IMAGE = /^pi-clipboard-[0-9a-f-]+\.(?:gif|jpe?g|png|webp)$/i;
18
27
  const CLIPBOARD_IMAGE_PATH =
19
28
  /(?:[A-Za-z]:[\\/]|\/)[^\s]*?pi-clipboard-[0-9a-f-]+\.(?:gif|jpe?g|png|webp)/gi;
29
+ const PREVIEW_WIDTH = 24;
30
+ const PREVIEW_HEIGHT = 6;
31
+ const THUMBNAIL_TIMEOUT_SECONDS = 5;
32
+
33
+ const MIME_TYPES: Record<string, string> = {
34
+ ".gif": "image/gif",
35
+ ".jpeg": "image/jpeg",
36
+ ".jpg": "image/jpeg",
37
+ ".png": "image/png",
38
+ ".webp": "image/webp",
39
+ };
20
40
 
21
41
  type PreviewEditor = Component & {
22
42
  getText?(): string;
@@ -31,9 +51,32 @@ type PreviewEditor = Component & {
31
51
  };
32
52
  };
33
53
 
54
+ type PreviewImage = {
55
+ base64: string;
56
+ mimeType: string;
57
+ };
58
+
59
+ type PreviewTheme = ImageTheme & {
60
+ loadingColor?: (value: string) => string;
61
+ };
62
+
63
+ type Thumbnailer = (
64
+ path: string,
65
+ widthPx: number,
66
+ heightPx: number,
67
+ done: (image: PreviewImage | undefined) => void,
68
+ ) => () => void;
69
+
34
70
  type Preview = {
35
71
  marker: string;
36
72
  path: string;
73
+ image: PreviewImage | undefined;
74
+ cancelThumbnail: (() => void) | undefined;
75
+ };
76
+
77
+ type PreviewImagePlan = {
78
+ image: PreviewImage | undefined;
79
+ thumbnail: { widthPx: number; heightPx: number } | undefined;
37
80
  };
38
81
 
39
82
  export type ImagePreviewController = {
@@ -46,6 +89,95 @@ type InstalledEditor = PreviewEditor & {
46
89
  [INSTALLED]?: ImagePreviewController;
47
90
  };
48
91
  type OverlayTui = TUI & { [ACTIVE_OVERLAY]?: OverlayHandle };
92
+ type FocusRefreshController = {
93
+ restore(): void;
94
+ };
95
+ type FocusRefreshTui = OverlayTui & {
96
+ handleViewportInput?(data: string): unknown;
97
+ uploadedKittyImages?: Map<unknown, unknown>;
98
+ [FOCUS_REFRESH]?: FocusRefreshController;
99
+ };
100
+
101
+ function installFocusRefresh(tui: TUI, refresh: () => void): () => void {
102
+ const host = tui as FocusRefreshTui;
103
+ host[FOCUS_REFRESH]?.restore();
104
+ const original = host.handleViewportInput;
105
+ if (!original) return () => {};
106
+ const controller: FocusRefreshController = {
107
+ restore() {
108
+ if (host[FOCUS_REFRESH] !== controller) return;
109
+ host.handleViewportInput = original;
110
+ delete host[FOCUS_REFRESH];
111
+ },
112
+ };
113
+ host.handleViewportInput = function (data: string) {
114
+ const result = original.call(this, data);
115
+ if (data === FOCUS_IN) refresh();
116
+ return result;
117
+ };
118
+ host[FOCUS_REFRESH] = controller;
119
+ return () => controller.restore();
120
+ }
121
+
122
+ export function enableScribeImageCapability(): void {
123
+ if (process.env.TERM_PROGRAM?.toLowerCase() !== "scribe") return;
124
+ const capabilities = getCapabilities();
125
+ if (capabilities.images !== "kitty") {
126
+ setCapabilities({ ...capabilities, images: "kitty" });
127
+ }
128
+ }
129
+
130
+ function sharpThumbnail(
131
+ path: string,
132
+ widthPx: number,
133
+ heightPx: number,
134
+ done: (image: PreviewImage | undefined) => void,
135
+ ): () => void {
136
+ let cancelled = false;
137
+ const pipeline = sharp(path, { pages: 1 })
138
+ .rotate()
139
+ .resize({
140
+ width: widthPx,
141
+ height: heightPx,
142
+ fit: "inside",
143
+ withoutEnlargement: true,
144
+ })
145
+ .png()
146
+ .timeout({ seconds: THUMBNAIL_TIMEOUT_SECONDS });
147
+ void pipeline
148
+ .toBuffer()
149
+ .then((output) => {
150
+ if (!cancelled) {
151
+ done({ base64: output.toString("base64"), mimeType: "image/png" });
152
+ }
153
+ })
154
+ .catch(() => {
155
+ if (!cancelled) done(undefined);
156
+ });
157
+ return () => {
158
+ cancelled = true;
159
+ pipeline.destroy();
160
+ };
161
+ }
162
+
163
+ export function planPreviewImage(
164
+ mimeType: string,
165
+ source: Buffer,
166
+ ): PreviewImagePlan {
167
+ const base64 = source.toString("base64");
168
+ const dimensions = getImageDimensions(base64, mimeType);
169
+ const cells = getCellDimensions();
170
+ const widthPx = Math.max(1, PREVIEW_WIDTH * cells.widthPx);
171
+ const heightPx = Math.max(1, PREVIEW_HEIGHT * cells.heightPx);
172
+ if (
173
+ dimensions &&
174
+ dimensions.widthPx <= widthPx &&
175
+ dimensions.heightPx <= heightPx
176
+ ) {
177
+ return { image: { base64, mimeType }, thumbnail: undefined };
178
+ }
179
+ return { image: undefined, thumbnail: { widthPx, heightPx } };
180
+ }
49
181
 
50
182
  function singleDeletionIndex(
51
183
  before: string,
@@ -62,6 +194,8 @@ function singleDeletionIndex(
62
194
  export function installImagePreview(
63
195
  editor: Component,
64
196
  tui: TUI,
197
+ theme: PreviewTheme = { fallbackColor: (value) => value },
198
+ thumbnailer: Thumbnailer = sharpThumbnail,
65
199
  ): ImagePreviewController | undefined {
66
200
  const target = editor as InstalledEditor;
67
201
  const existing = target[INSTALLED];
@@ -71,7 +205,9 @@ export function installImagePreview(
71
205
  let counter = 0;
72
206
  let changingText = false;
73
207
  let previousText = target.getText();
208
+ let visibleMarkers = "";
74
209
  let activePreviews: Preview[] = [];
210
+ let activeImages: Array<Image | undefined> = [];
75
211
  let handler = target.onChange;
76
212
  const previews = new Map<string, Preview>();
77
213
  const markersByPath = new Map<string, string>();
@@ -79,11 +215,27 @@ export function installImagePreview(
79
215
  const host = tui as OverlayTui;
80
216
  const margin: OverlayMargin = { bottom: 0 };
81
217
  let overlay: OverlayHandle | undefined;
218
+ let loader: Loader | undefined;
219
+ let removeFocusRefresh = () => {};
82
220
 
221
+ const stopLoader = () => {
222
+ loader?.stop();
223
+ loader = undefined;
224
+ };
225
+ const renderLoader = (width: number) => {
226
+ loader ??= new Loader(
227
+ tui,
228
+ theme.loadingColor ?? theme.fallbackColor,
229
+ (value) => value,
230
+ "",
231
+ );
232
+ return loader.render(Math.min(width, PREVIEW_WIDTH + 2));
233
+ };
83
234
  const releaseOverlay = () => {
84
235
  const active = overlay;
85
236
  if (!active) return;
86
237
  active.hide();
238
+ stopLoader();
87
239
  overlay = undefined;
88
240
  if (host[ACTIVE_OVERLAY] === active) delete host[ACTIVE_OVERLAY];
89
241
  };
@@ -101,11 +253,18 @@ export function installImagePreview(
101
253
  };
102
254
  const component: Component = {
103
255
  render(width: number) {
104
- return activePreviews.flatMap((preview) =>
105
- wrapTextWithAnsi(`${preview.marker} ${preview.path}`, width),
106
- );
256
+ return activePreviews.flatMap((preview, index) => {
257
+ const image = getCapabilities().images
258
+ ? activeImages[index]
259
+ : undefined;
260
+ if (image) return image.render(Math.min(width, PREVIEW_WIDTH + 2));
261
+ if (preview.cancelThumbnail) return renderLoader(width);
262
+ return wrapTextWithAnsi(`${preview.marker} ${preview.path}`, width);
263
+ });
264
+ },
265
+ invalidate() {
266
+ for (const image of activeImages) image?.invalidate();
107
267
  },
108
- invalidate() {},
109
268
  };
110
269
  const options: OverlayOptions = {
111
270
  anchor: "bottom-left",
@@ -127,9 +286,24 @@ export function installImagePreview(
127
286
  };
128
287
 
129
288
  const sync = (text: string) => {
130
- activePreviews = [...previews.values()].filter((preview) =>
289
+ const active = [...previews.values()].filter((preview) =>
131
290
  text.includes(preview.marker),
132
291
  );
292
+ const signature = active.map((preview) => preview.marker).join("\0");
293
+ if (signature !== visibleMarkers) {
294
+ visibleMarkers = signature;
295
+ activePreviews = active;
296
+ activeImages = active.map((preview) =>
297
+ preview.image
298
+ ? new Image(preview.image.base64, preview.image.mimeType, theme, {
299
+ filename: preview.path,
300
+ maxWidthCells: PREVIEW_WIDTH,
301
+ maxHeightCells: PREVIEW_HEIGHT,
302
+ })
303
+ : undefined,
304
+ );
305
+ }
306
+ if (!active.some((preview) => preview.cancelThumbnail)) stopLoader();
133
307
  if (isVisible() && isMounted(tui, target)) ensureOverlay();
134
308
  else releaseOverlay();
135
309
  };
@@ -176,15 +350,38 @@ export function installImagePreview(
176
350
  const known = markersByPath.get(path);
177
351
  if (known) return known;
178
352
  if (!isAbsolute(path) || !CLIPBOARD_IMAGE.test(basename(path))) return;
353
+ const mimeType = MIME_TYPES[extname(path).toLowerCase()];
354
+ if (!mimeType) return;
179
355
  try {
180
- accessSync(path, constants.R_OK);
356
+ const marker = `[image ${++counter}]`;
357
+ const plan = planPreviewImage(mimeType, readFileSync(path));
358
+ const preview: Preview = {
359
+ marker,
360
+ path,
361
+ image: plan.image,
362
+ cancelThumbnail: undefined,
363
+ };
364
+ previews.set(marker, preview);
365
+ markersByPath.set(path, marker);
366
+ if (plan.thumbnail) {
367
+ preview.cancelThumbnail = thumbnailer(
368
+ path,
369
+ plan.thumbnail.widthPx,
370
+ plan.thumbnail.heightPx,
371
+ (image) => {
372
+ preview.cancelThumbnail = undefined;
373
+ if (!image || previews.get(marker) !== preview) return;
374
+ preview.image = image;
375
+ visibleMarkers = "";
376
+ sync(target.getText?.() ?? "");
377
+ tui.requestRender();
378
+ },
379
+ );
380
+ }
381
+ return marker;
181
382
  } catch {
182
383
  return;
183
384
  }
184
- const marker = `[image ${++counter}]`;
185
- previews.set(marker, { marker, path });
186
- markersByPath.set(path, marker);
187
- return marker;
188
385
  };
189
386
  const ingest = (text: string, cursor: number | undefined) => {
190
387
  let mappedCursor = cursor;
@@ -226,6 +423,7 @@ export function installImagePreview(
226
423
  ) {
227
424
  continue;
228
425
  }
426
+ preview.cancelThumbnail?.();
229
427
  previews.delete(preview.marker);
230
428
  markersByPath.delete(preview.path);
231
429
  const cleaned =
@@ -248,22 +446,32 @@ export function installImagePreview(
248
446
 
249
447
  const controller: ImagePreviewController = {
250
448
  prepare(text) {
449
+ stopLoader();
251
450
  let prepared = text;
252
451
  for (const preview of previews.values()) {
253
452
  prepared = prepared.replaceAll(preview.marker, preview.path);
453
+ preview.cancelThumbnail?.();
454
+ preview.cancelThumbnail = undefined;
254
455
  }
456
+ visibleMarkers = "";
255
457
  activePreviews = [];
458
+ activeImages = [];
256
459
  releaseOverlay();
257
460
  return prepared;
258
461
  },
259
462
  clear() {
463
+ stopLoader();
464
+ for (const preview of previews.values()) preview.cancelThumbnail?.();
260
465
  previews.clear();
261
466
  markersByPath.clear();
467
+ visibleMarkers = "";
262
468
  activePreviews = [];
469
+ activeImages = [];
263
470
  releaseOverlay();
264
471
  },
265
472
  dispose() {
266
473
  if (target[INSTALLED] !== controller) return;
474
+ removeFocusRefresh();
267
475
  controller.clear();
268
476
  target.render = render;
269
477
  delete target.onChange;
@@ -284,6 +492,13 @@ export function installImagePreview(
284
492
  } catch {
285
493
  return undefined;
286
494
  }
495
+ removeFocusRefresh = installFocusRefresh(tui, () => {
496
+ if (!isVisible() || !activeImages.some(Boolean)) return;
497
+ const uploaded = (host as FocusRefreshTui).uploadedKittyImages;
498
+ if (!uploaded) return;
499
+ uploaded.clear();
500
+ tui.requestRender(true);
501
+ });
287
502
  target.render = (width: number) => {
288
503
  const lines = render.call(target, width);
289
504
  sync(target.getText?.() ?? "");
@@ -10,13 +10,9 @@ import {
10
10
  } from "@earendil-works/pi-tui";
11
11
 
12
12
  const INSTALLED = Symbol.for("pi-proper-base.transcript-cleanup");
13
- const PROCESS_LINK_PREFIX = "pi-proper-base://process/";
14
13
  const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
15
14
  const LEFT_BUTTON = "0";
16
15
 
17
- type Keybindings = {
18
- getKeys(action: "app.tools.expand"): readonly string[];
19
- };
20
16
  type ComponentContainer = Component & { children: Component[] };
21
17
  type AssistantMessage = {
22
18
  content: Array<{ type: string; text?: string; thinking?: string }>;
@@ -31,17 +27,20 @@ type AssistantComponent = Component & {
31
27
  type InstalledContainer = ComponentContainer & {
32
28
  [INSTALLED]?: TranscriptCleanupController;
33
29
  };
30
+ type DetailHit = {
31
+ owner: object;
32
+ line: string;
33
+ end: number;
34
+ };
34
35
  type State = {
35
36
  ctx: ExtensionContext;
36
37
  tui: TUI;
37
- keybindings: Keybindings;
38
38
  activeStart: number | undefined;
39
39
  completed: Set<Component>;
40
40
  owned: Set<Component>;
41
41
  expanded: Map<object, boolean>;
42
- groups: Map<string, object>;
43
- ids: WeakMap<object, string>;
44
- nextId: number;
42
+ hits: Map<number, DetailHit>;
43
+ pendingHits: DetailHit[];
45
44
  globalExpanded: boolean;
46
45
  assistantCache: WeakMap<AssistantComponent, AssistantRenderCache>;
47
46
  };
@@ -68,6 +67,16 @@ type MouseTui = TUI & {
68
67
  inputListeners?: Set<TuiInputListener>;
69
68
  previousLines?: string[];
70
69
  previousScreen?: string[];
70
+ getPrimaryScrollView?(): unknown;
71
+ getScrollSelectionPoint?(
72
+ scrollView: unknown,
73
+ x: number,
74
+ y: number,
75
+ ): { row: number; col: number } | undefined;
76
+ };
77
+ type TranscriptContainers = {
78
+ document: ComponentContainer;
79
+ chat: InstalledContainer;
71
80
  };
72
81
 
73
82
  export type TranscriptCleanupController = {
@@ -75,33 +84,31 @@ export type TranscriptCleanupController = {
75
84
  completeAssistant(message: object): void;
76
85
  completeTool(toolCallId: string): void;
77
86
  settle(): void;
78
- update(ctx: ExtensionContext, tui: TUI, keybindings: Keybindings): void;
87
+ update(ctx: ExtensionContext, tui: TUI): void;
79
88
  uninstall(): void;
80
89
  };
81
90
 
82
91
  export function installTranscriptCleanup(
83
92
  tui: TUI,
84
93
  ctx: ExtensionContext,
85
- keybindings: Keybindings,
86
94
  ): TranscriptCleanupController | undefined {
87
- const chat = findChatContainer(tui) as InstalledContainer | undefined;
88
- if (!chat) return undefined;
95
+ const containers = findTranscriptContainers(tui);
96
+ if (!containers) return undefined;
97
+ const { document, chat } = containers;
89
98
  if (chat[INSTALLED]) {
90
- chat[INSTALLED].update(ctx, tui, keybindings);
99
+ chat[INSTALLED].update(ctx, tui);
91
100
  return chat[INSTALLED];
92
101
  }
93
102
 
94
103
  let state: State = {
95
104
  ctx,
96
105
  tui,
97
- keybindings,
98
106
  activeStart: ctx.isIdle() ? undefined : chat.children.length,
99
107
  completed: new Set(),
100
108
  owned: new Set(chat.children),
101
109
  expanded: new Map(),
102
- groups: new Map(),
103
- ids: new WeakMap(),
104
- nextId: 0,
110
+ hits: new Map(),
111
+ pendingHits: [],
105
112
  globalExpanded: ctx.ui.getToolsExpanded(),
106
113
  assistantCache: new WeakMap(),
107
114
  };
@@ -163,12 +170,11 @@ export function installTranscriptCleanup(
163
170
  };
164
171
  state.tui.requestRender();
165
172
  },
166
- update(nextCtx, nextTui, nextKeybindings) {
173
+ update(nextCtx, nextTui) {
167
174
  state = {
168
175
  ...state,
169
176
  ctx: nextCtx,
170
177
  tui: nextTui,
171
- keybindings: nextKeybindings,
172
178
  };
173
179
  },
174
180
  uninstall() {
@@ -190,15 +196,19 @@ export function installTranscriptCleanup(
190
196
  if (globalExpanded !== state.globalExpanded) {
191
197
  state = { ...state, globalExpanded, expanded: new Map() };
192
198
  }
193
- state.groups.clear();
199
+ state.pendingHits.length = 0;
200
+ let lines: string[];
194
201
  if (state.activeStart === undefined && state.ctx.isIdle()) {
195
- return renderCollapsed(chat.children, width, state);
202
+ lines = renderCollapsed(chat.children, width, state);
203
+ } else {
204
+ const start = state.activeStart ?? chat.children.length;
205
+ lines = [
206
+ ...renderCollapsed(chat.children.slice(0, start), width, state),
207
+ ...renderActive(chat.children.slice(start), width, state),
208
+ ];
196
209
  }
197
- const start = state.activeStart ?? chat.children.length;
198
- return [
199
- ...renderCollapsed(chat.children.slice(0, start), width, state),
200
- ...renderActive(chat.children.slice(start), width, state),
201
- ];
210
+ indexDetailHits(lines, documentRowOffset(document, chat, width), state);
211
+ return lines;
202
212
  };
203
213
  chat[INSTALLED] = controller;
204
214
  return controller;
@@ -407,28 +417,20 @@ function hasSectionText(lines: string[]): boolean {
407
417
  }
408
418
 
409
419
  function renderDetail(detail: Detail, width: number, state: State): string[] {
410
- let id = state.ids.get(detail.owner);
411
- if (!id) {
412
- id = String(++state.nextId);
413
- state.ids.set(detail.owner, id);
414
- }
415
- state.groups.set(id, detail.owner);
416
420
  const expanded = state.expanded.get(detail.owner) ?? state.globalExpanded;
417
- const keys = state.keybindings.getKeys("app.tools.expand").join("/");
418
- const action = expanded ? "collapse" : "expand";
419
- const hint = keys
420
- ? ` (click or ${keys} to ${action})`
421
- : ` (click to ${action})`;
422
- const label = `${expanded ? "▾" : "▸"} ${detail.label}${hint}`;
423
- const styled = state.ctx.ui.theme.fg(detailColor(detail.kind), label);
424
- const header = truncateToWidth(
425
- `\x1b]8;;${PROCESS_LINK_PREFIX}${id}\x07${styled}\x1b]8;;\x07`,
426
- width,
427
- "",
421
+ const marker = state.ctx.ui.theme.fg(
422
+ "borderAccent",
423
+ state.ctx.ui.theme.bold(expanded ? "⌄" : "›"),
428
424
  );
429
- const lines = [
430
- `${header}${" ".repeat(Math.max(0, width - visibleWidth(header)))}`,
431
- ];
425
+ const label = state.ctx.ui.theme.fg(detailColor(detail.kind), detail.label);
426
+ const header = truncateToWidth(`${marker} ${label}`, width, "");
427
+ const headerLine = `${header}${" ".repeat(Math.max(0, width - visibleWidth(header)))}`;
428
+ state.pendingHits.push({
429
+ owner: detail.owner,
430
+ line: headerLine,
431
+ end: visibleWidth(header),
432
+ });
433
+ const lines = [headerLine];
432
434
  const expandable = detail.component as ToolComponent;
433
435
  // setExpanded rebuilds the tool's result renderer even when the state is
434
436
  // unchanged, which re-sanitizes full outputs on every frame. Skip no-ops.
@@ -436,11 +438,14 @@ function renderDetail(detail: Detail, width: number, state: State): string[] {
436
438
  if (expanded) {
437
439
  lines.push(...detail.component.render(width));
438
440
  const button = `\x1b[7m ${state.ctx.ui.theme.fg(detailColor(detail.kind), "collapse")} \x1b[27m`;
439
- const linked = `\x1b]8;;${PROCESS_LINK_PREFIX}${id}\x07${button}\x1b]8;;\x07`;
440
- const rendered = truncateToWidth(linked, width, "");
441
- lines.push(
442
- `${rendered}${" ".repeat(Math.max(0, width - visibleWidth(rendered)))}`,
443
- );
441
+ const rendered = truncateToWidth(button, width, "");
442
+ const buttonLine = `${rendered}${" ".repeat(Math.max(0, width - visibleWidth(rendered)))}`;
443
+ state.pendingHits.push({
444
+ owner: detail.owner,
445
+ line: buttonLine,
446
+ end: visibleWidth(rendered),
447
+ });
448
+ lines.push(buttonLine);
444
449
  }
445
450
  return lines;
446
451
  }
@@ -459,7 +464,16 @@ function detailColor(
459
464
  function describeTool(tool: ToolComponent, error: boolean): string {
460
465
  const name = tool.toolName ?? "tool";
461
466
  const args = asRecord(tool.args);
462
- const value = ["path", "command", "pattern", "query", "task", "url", "action"]
467
+ const value = [
468
+ "tool",
469
+ "path",
470
+ "command",
471
+ "pattern",
472
+ "query",
473
+ "task",
474
+ "url",
475
+ "action",
476
+ ]
463
477
  .map((key) => args?.[key])
464
478
  .find((candidate): candidate is string => typeof candidate === "string");
465
479
  const target = value ? ` · ${oneLine(value)}` : "";
@@ -476,6 +490,29 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
476
490
  : undefined;
477
491
  }
478
492
 
493
+ function documentRowOffset(
494
+ document: ComponentContainer,
495
+ chat: ComponentContainer,
496
+ width: number,
497
+ ): number {
498
+ const chatIndex = document.children.indexOf(chat);
499
+ if (chatIndex <= 0) return 0;
500
+ return document.children
501
+ .slice(0, chatIndex)
502
+ .reduce((rows, child) => rows + child.render(width).length, 0);
503
+ }
504
+
505
+ function indexDetailHits(lines: string[], offset: number, state: State): void {
506
+ state.hits.clear();
507
+ let nextRow = 0;
508
+ for (const hit of state.pendingHits) {
509
+ const relativeRow = lines.indexOf(hit.line, nextRow);
510
+ if (relativeRow < 0) continue;
511
+ state.hits.set(offset + relativeRow, hit);
512
+ nextRow = relativeRow + 1;
513
+ }
514
+ }
515
+
479
516
  function handleClick(
480
517
  data: string,
481
518
  state: State,
@@ -485,51 +522,44 @@ function handleClick(
485
522
  if (!match || match[1] !== LEFT_BUTTON) return undefined;
486
523
  const column = Number.parseInt(match[2] ?? "", 10) - 1;
487
524
  const row = Number.parseInt(match[3] ?? "", 10) - 1;
488
- const line = screenLines(state.tui)[row];
489
- if (!line) return undefined;
490
- const link = linkAtColumn(line, column);
491
- if (!link?.startsWith(PROCESS_LINK_PREFIX)) return undefined;
492
- const owner = state.groups.get(link.slice(PROCESS_LINK_PREFIX.length));
493
- if (!owner) return undefined;
525
+ const point = contentPoint(state.tui, column, row);
526
+ if (!point) return undefined;
527
+ const hit = state.hits.get(point.row);
528
+ if (!hit || point.col < 0 || point.col >= hit.end) return undefined;
529
+ const screenLine = screenLines(state.tui)[row];
530
+ if (!screenLine || !sameHitText(screenLine, hit)) return undefined;
494
531
  if (match[4] === "M") {
495
532
  state.expanded.set(
496
- owner,
497
- !(state.expanded.get(owner) ?? state.globalExpanded),
533
+ hit.owner,
534
+ !(state.expanded.get(hit.owner) ?? state.globalExpanded),
498
535
  );
499
536
  state.tui.requestRender();
500
537
  }
501
538
  return { consume: true };
502
539
  }
503
540
 
504
- function screenLines(tui: TUI): string[] {
541
+ function contentPoint(
542
+ tui: TUI,
543
+ column: number,
544
+ row: number,
545
+ ): { row: number; col: number } | undefined {
505
546
  const host = tui as MouseTui;
506
- return host.previousScreen ?? host.previousLines ?? [];
547
+ const scrollView = host.getPrimaryScrollView?.();
548
+ return scrollView !== undefined && host.getScrollSelectionPoint
549
+ ? host.getScrollSelectionPoint(scrollView, column, row)
550
+ : { row, col: column };
507
551
  }
508
552
 
509
- function linkAtColumn(line: string, column: number): string | undefined {
510
- let active: string | undefined;
511
- let visible = 0;
512
- for (let index = 0; index < line.length; ) {
513
- if (line.startsWith("\x1b]8;;", index)) {
514
- const end = line.indexOf("\x07", index + 5);
515
- if (end < 0) break;
516
- active = line.slice(index + 5, end) || undefined;
517
- index = end + 1;
518
- continue;
519
- }
520
- if (line[index] === "\x1b") {
521
- const end = line.indexOf("m", index + 1);
522
- if (end < 0) break;
523
- index = end + 1;
524
- continue;
525
- }
526
- const character = line[index] ?? "";
527
- const width = visibleWidth(character);
528
- if (column >= visible && column < visible + width) return active;
529
- visible += width;
530
- index += character.length;
531
- }
532
- return undefined;
553
+ function sameHitText(line: string, hit: DetailHit): boolean {
554
+ return (
555
+ truncateToWidth(stripTerminalSequences(line), hit.end, "") ===
556
+ truncateToWidth(stripTerminalSequences(hit.line), hit.end, "")
557
+ );
558
+ }
559
+
560
+ function screenLines(tui: TUI): string[] {
561
+ const host = tui as MouseTui;
562
+ return host.previousScreen ?? host.previousLines ?? [];
533
563
  }
534
564
 
535
565
  function prioritize(tui: TUI, listener: TuiInputListener): void {
@@ -541,7 +571,7 @@ function prioritize(tui: TUI, listener: TuiInputListener): void {
541
571
  for (const entry of rest) listeners.add(entry);
542
572
  }
543
573
 
544
- function findChatContainer(tui: TUI): ComponentContainer | undefined {
574
+ function findTranscriptContainers(tui: TUI): TranscriptContainers | undefined {
545
575
  for (const root of roots(tui)) {
546
576
  const document = find(root, (component) => {
547
577
  const children = childrenOf(component);
@@ -553,7 +583,12 @@ function findChatContainer(tui: TUI): ComponentContainer | undefined {
553
583
  );
554
584
  });
555
585
  const chat = document ? childrenOf(document)[2] : undefined;
556
- if (chat) return chat as ComponentContainer;
586
+ if (document && chat) {
587
+ return {
588
+ document: document as ComponentContainer,
589
+ chat: chat as InstalledContainer,
590
+ };
591
+ }
557
592
  }
558
593
  return undefined;
559
594
  }