proper-base 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -158,7 +158,7 @@ highlight. Custom replacement footers are not changed.
158
158
 
159
159
  ## Install
160
160
 
161
- Node 22.19 or newer is required. The package is tested against Pi 0.84.2.
161
+ Node 22.19 or newer is required. The package is tested against Pi 0.84.4.
162
162
 
163
163
  From npm:
164
164
 
package/index.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  getAgentDir,
18
18
  SessionManager,
19
19
  } from "@earendil-works/pi-coding-agent";
20
+ import { matchesKey } from "@earendil-works/pi-tui";
20
21
 
21
22
  import {
22
23
  installAutocompleteDetails,
@@ -24,6 +25,7 @@ import {
24
25
  installModelAutocompleteSubmit,
25
26
  sortModelAutocompleteDescending,
26
27
  } from "./src/autocomplete-details.ts";
28
+ import { installClipboardLeakGuard } from "./src/clipboard-guard.ts";
27
29
  import { commitGuardReason } from "./src/commit-guard.ts";
28
30
  import {
29
31
  installEditorNavigation,
@@ -46,16 +48,21 @@ import {
46
48
  import { type HistoryGuard, installHistoryGuard } from "./src/history-guard.ts";
47
49
  import { omitPriorTurnImages } from "./src/image-context.ts";
48
50
  import {
49
- enableScribeImageCapability,
51
+ enableScribeCapabilities,
50
52
  type ImagePreviewController,
51
53
  installImagePreview,
52
54
  } from "./src/image-preview.ts";
53
55
  import { installJumpToBottom } from "./src/jump-to-bottom.ts";
56
+ import { installOsc8LinkIds } from "./src/osc8-link-ids.ts";
54
57
  import {
55
58
  createPromptDisplay,
56
59
  PROMPT_DISPLAY_ENTRY,
57
60
  } from "./src/prompt-display.ts";
58
61
  import { installPromptJump } from "./src/prompt-jump.ts";
62
+ import {
63
+ installRailSetting,
64
+ type RailSettingController,
65
+ } from "./src/rail-setting.ts";
59
66
  import { installRecorder } from "./src/recorder.ts";
60
67
  import { installSelectionDismiss } from "./src/selection-dismiss.ts";
61
68
  import { installFastSessionList } from "./src/session-list.ts";
@@ -72,6 +79,7 @@ import {
72
79
  type TranscriptCleanupController,
73
80
  } from "./src/transcript-cleanup.ts";
74
81
  import { normalizeCpaTransientError } from "./src/transient-retry.ts";
82
+ import { installWheelScrollLines } from "./src/wheel-scroll.ts";
75
83
 
76
84
  /** Prompts seeded into the editor. Older prompts past this point are dropped. */
77
85
  const MAX_ENTRIES = 200;
@@ -247,7 +255,9 @@ function decodeModelReference(value: string): ModelReference | undefined {
247
255
  }
248
256
 
249
257
  export default function (pi: ExtensionAPI) {
250
- enableScribeImageCapability();
258
+ // @lat: [[lat.md/proper-base/proper-base#proper-base#Clipboard leak guard]]
259
+ installClipboardLeakGuard();
260
+ enableScribeCapabilities();
251
261
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session listing]]
252
262
  installFastSessionList(SessionManager, getAgentDir());
253
263
 
@@ -284,9 +294,11 @@ export default function (pi: ExtensionAPI) {
284
294
  let removeFooterColors: (() => void) | undefined;
285
295
  let removeJumpToBottom: (() => void) | undefined;
286
296
  let removePromptJump: (() => void) | undefined;
297
+ let railSetting: RailSettingController | undefined;
287
298
  let removePromptClear: (() => void) | undefined;
288
299
  let removeSmartSelection: (() => void) | undefined;
289
300
  let removeSelectionDismiss: (() => void) | undefined;
301
+ let removeOsc8LinkIds: (() => void) | undefined;
290
302
  let imagePreview: ImagePreviewController | undefined;
291
303
  let removeTerminalInput: (() => void) | undefined;
292
304
  let transcriptCleanup: TranscriptCleanupController | undefined;
@@ -418,7 +430,13 @@ export default function (pi: ExtensionAPI) {
418
430
  event.message.role === "assistant" &&
419
431
  event.message.stopReason !== "aborted"
420
432
  ) {
421
- pendingPrompt.processed = true;
433
+ // Streaming opens the assistant message with a "pending" partial as
434
+ // soon as response headers arrive — instantly behind a local proxy,
435
+ // with zero tokens produced. That is not assistant processing yet;
436
+ // content arrival marks it through message_update instead.
437
+ if (event.message.stopReason !== "pending") {
438
+ pendingPrompt.processed = true;
439
+ }
422
440
  imagePreview?.clear();
423
441
  }
424
442
  });
@@ -555,12 +573,16 @@ export default function (pi: ExtensionAPI) {
555
573
  removeJumpToBottom = undefined;
556
574
  removePromptJump?.();
557
575
  removePromptJump = undefined;
576
+ railSetting?.dispose();
577
+ railSetting = undefined;
558
578
  removePromptClear?.();
559
579
  removePromptClear = undefined;
560
580
  removeSmartSelection?.();
561
581
  removeSmartSelection = undefined;
562
582
  removeSelectionDismiss?.();
563
583
  removeSelectionDismiss = undefined;
584
+ removeOsc8LinkIds?.();
585
+ removeOsc8LinkIds = undefined;
564
586
  imagePreview?.dispose();
565
587
  imagePreview = undefined;
566
588
  removeTerminalInput?.();
@@ -660,20 +682,38 @@ export default function (pi: ExtensionAPI) {
660
682
  new CustomEditor(tui, theme, keybindings);
661
683
  activeEditor = editor as PromptEditor;
662
684
  activeTui = tui;
685
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Wheel scroll rate]]
686
+ installWheelScrollLines(tui);
663
687
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
664
688
  transcriptCleanup?.uninstall();
665
689
  transcriptCleanup = installTranscriptCleanup(tui, ctx);
666
690
  removeSmartSelection?.();
667
691
  removeSmartSelection = installSmartSelection(tui);
668
692
  removeSelectionDismiss?.();
669
- removeSelectionDismiss = installSelectionDismiss(tui);
693
+ // The copy action reads the active selection after this listener runs,
694
+ // so its keystroke must not dismiss the selection it is about to copy.
695
+ removeSelectionDismiss = installSelectionDismiss(tui, (data) =>
696
+ keybindings
697
+ .getKeys("app.message.copy")
698
+ .some((key) => matchesKey(data, key)),
699
+ );
700
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Hyperlink identity]]
701
+ removeOsc8LinkIds?.();
702
+ removeOsc8LinkIds = installOsc8LinkIds(tui);
670
703
  historyGuard = installHistoryGuard(editor);
671
704
  removeJumpToBottom?.();
672
705
  removeJumpToBottom = installJumpToBottom(editor, tui);
673
706
  removePromptJump?.();
707
+ railSetting?.dispose();
708
+ railSetting = installRailSetting(tui, editor, getAgentDir());
709
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
674
710
  removePromptJump = installPromptJump(tui, {
675
711
  color: (value) => ctx.ui.theme.fg("muted", value),
676
712
  subtle: (value) => ctx.ui.theme.fg("dim", value),
713
+ outline: () =>
714
+ railSetting?.enabled() !== false
715
+ ? (transcriptCleanup?.outline() ?? [])
716
+ : [],
677
717
  });
678
718
  imagePreview?.dispose();
679
719
  imagePreview = installImagePreview(editor, tui, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.3.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",
@@ -53,8 +53,8 @@
53
53
  "@earendil-works/pi-tui": "*"
54
54
  },
55
55
  "devDependencies": {
56
- "@earendil-works/pi-coding-agent": "0.84.2",
57
- "@earendil-works/pi-tui": "0.84.2",
56
+ "@earendil-works/pi-coding-agent": "0.84.4",
57
+ "@earendil-works/pi-tui": "0.84.4",
58
58
  "@types/node": "25.9.5",
59
59
  "typescript": "6.0.2"
60
60
  },
@@ -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
  }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * pi's bundled `@mariozechner/clipboard` addon constructs a fresh clipboard-rs
3
+ * `ClipboardContext` on every exported call. On X11 each context opens two X
4
+ * connections and a detached service thread, and the crate defines no `Drop`
5
+ * for the context, so every clipboard read leaks both connections for the life
6
+ * of the pi process. Days of pasting across long-lived sessions exhaust Xorg's
7
+ * ~256 client slots, after which every X client on the machine — including the
8
+ * `xclip` calls behind image paste — fails with "Maximum number of clients
9
+ * reached".
10
+ *
11
+ * pi already distrusts the crate for Linux clipboard writes and shells out to
12
+ * platform tools there. This guard extends that policy to the two Linux read
13
+ * paths that still call the addon: `readClipboardText()` (which has no
14
+ * subprocess fallback of its own) and the `hasImage()` probe that runs ahead
15
+ * of pi's complete `xclip`/`wl-paste` image path. macOS and Windows keep the
16
+ * addon: pi has no subprocess clipboard implementation on either.
17
+ */
18
+
19
+ import { spawn } from "node:child_process";
20
+ import { realpathSync } from "node:fs";
21
+ import { createRequire } from "node:module";
22
+
23
+ /** Installed once per process; the flag lives on pi's cached module object. */
24
+ const PATCHED = Symbol.for("proper-base.clipboard-leak-guard");
25
+
26
+ // Mirrors pi's own READ_CLIPBOARD_OPTIONS in dist/utils/clipboard.js.
27
+ const READ_TIMEOUT_MS = 5000;
28
+ const READ_MAX_BUFFER = 50 * 1024 * 1024;
29
+
30
+ interface NativeClipboardModule {
31
+ getText: unknown;
32
+ hasImage: unknown;
33
+ }
34
+
35
+ function isRecord(value: unknown): value is Record<string, unknown> {
36
+ return typeof value === "object" && value !== null;
37
+ }
38
+
39
+ /**
40
+ * Resolve the exact module instance pi loaded. pi's `clipboard-native.js`
41
+ * requires the addon from inside the pi package, and Node's CJS cache is keyed
42
+ * by resolved filename, so a `createRequire` rooted anywhere in that package
43
+ * returns the same exports object. `process.argv[1]` is pi's entry script; its
44
+ * realpath lands inside the package in both the plain and bundled layouts.
45
+ */
46
+ function resolveNativeClipboard(
47
+ entryPoint: string | undefined,
48
+ ): NativeClipboardModule | null {
49
+ if (!entryPoint) return null;
50
+ const bases = [entryPoint];
51
+ try {
52
+ bases.unshift(realpathSync(entryPoint));
53
+ } catch {
54
+ // Keep the raw entry point as the only candidate.
55
+ }
56
+ for (const base of bases) {
57
+ try {
58
+ const loaded: unknown = createRequire(base)("@mariozechner/clipboard");
59
+ if (isRecord(loaded)) return loaded as unknown as NativeClipboardModule;
60
+ } catch {
61
+ // Not resolvable from this base; try the next one.
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** One bounded asynchronous tool run; null means this tool cannot serve. */
68
+ function runTool(
69
+ command: string,
70
+ args: string[],
71
+ env: NodeJS.ProcessEnv,
72
+ ): Promise<string | null> {
73
+ return new Promise((resolve) => {
74
+ let child: ReturnType<typeof spawn>;
75
+ try {
76
+ child = spawn(command, args, {
77
+ env,
78
+ stdio: ["ignore", "pipe", "ignore"],
79
+ });
80
+ } catch {
81
+ resolve(null);
82
+ return;
83
+ }
84
+ let timer: NodeJS.Timeout | undefined;
85
+ let settled = false;
86
+ const finish = (value: string | null): void => {
87
+ if (settled) return;
88
+ settled = true;
89
+ if (timer) clearTimeout(timer);
90
+ resolve(value);
91
+ };
92
+ // The timeout bounds a stuck clipboard owner; the size cap mirrors pi's
93
+ // own read bounds and stops a pathological selection from accumulating.
94
+ timer = setTimeout(() => {
95
+ child.kill("SIGKILL");
96
+ finish(null);
97
+ }, READ_TIMEOUT_MS);
98
+ timer.unref?.();
99
+ const chunks: Buffer[] = [];
100
+ let size = 0;
101
+ child.on("error", () => finish(null));
102
+ child.stdout?.on("data", (chunk: Buffer) => {
103
+ size += chunk.length;
104
+ if (size > READ_MAX_BUFFER) {
105
+ child.kill("SIGKILL");
106
+ finish(null);
107
+ return;
108
+ }
109
+ chunks.push(chunk);
110
+ });
111
+ child.on("close", (code) => {
112
+ finish(code === 0 ? Buffer.concat(chunks).toString("utf8") : null);
113
+ });
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Read clipboard text through the platform tools pi already trusts for
119
+ * writes. Fully asynchronous: runtime extensions never synchronously wait on
120
+ * child processes, and pi awaits `getText()` anyway.
121
+ */
122
+ export async function readClipboardTextViaTools(
123
+ env: NodeJS.ProcessEnv = process.env,
124
+ ): Promise<string> {
125
+ const attempts: Array<[string, string[]]> = env.WAYLAND_DISPLAY
126
+ ? [
127
+ ["wl-paste", ["--no-newline", "--type", "text"]],
128
+ ["xclip", ["-selection", "clipboard", "-o"]],
129
+ ]
130
+ : [
131
+ ["xclip", ["-selection", "clipboard", "-o"]],
132
+ ["xsel", ["--clipboard", "--output"]],
133
+ ];
134
+ for (const [command, args] of attempts) {
135
+ const text = await runTool(command, args, env);
136
+ if (text !== null) return text;
137
+ }
138
+ return "";
139
+ }
140
+
141
+ export interface ClipboardGuardOptions {
142
+ platform?: NodeJS.Platform;
143
+ env?: NodeJS.ProcessEnv;
144
+ entryPoint?: string;
145
+ /** Test seam; defaults to resolving pi's cached addon instance. */
146
+ loadModule?: () => NativeClipboardModule | null;
147
+ /** Test seam; defaults to the subprocess reader above. */
148
+ readText?: () => string | Promise<string>;
149
+ }
150
+
151
+ // @lat: [[lat.md/proper-base/proper-base#proper-base#Clipboard leak guard]]
152
+ export function installClipboardLeakGuard(
153
+ options: ClipboardGuardOptions = {},
154
+ ): boolean {
155
+ const platform = options.platform ?? process.platform;
156
+ if (platform !== "linux") return false;
157
+ const native = options.loadModule
158
+ ? options.loadModule()
159
+ : resolveNativeClipboard(options.entryPoint ?? process.argv[1]);
160
+ if (
161
+ !native ||
162
+ typeof native.getText !== "function" ||
163
+ typeof native.hasImage !== "function"
164
+ ) {
165
+ return false;
166
+ }
167
+ const flags = native as unknown as Record<PropertyKey, unknown>;
168
+ if (flags[PATCHED]) return true;
169
+ const readText =
170
+ options.readText ?? (() => readClipboardTextViaTools(options.env));
171
+ // pi awaits getText(); an async wrapper keeps that contract, and an empty
172
+ // read becomes `null` through pi's own `text || null`.
173
+ native.getText = async () => readText();
174
+ // hasImage() gates pi's only getImageBinary() call, and on Linux pi's own
175
+ // xclip/wl-paste image path runs immediately after a false, so image paste
176
+ // loses nothing. setText and getImageBinary stay native: pi never calls
177
+ // either on Linux (writes already use the platform tools).
178
+ native.hasImage = () => false;
179
+ flags[PATCHED] = true;
180
+ return true;
181
+ }
@@ -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");
@@ -119,11 +120,18 @@ function installFocusRefresh(tui: TUI, refresh: () => void): () => void {
119
120
  return () => controller.restore();
120
121
  }
121
122
 
122
- export function enableScribeImageCapability(): void {
123
+ /**
124
+ * Pi's terminal allowlist does not know Scribe, so detection leaves Kitty
125
+ * images and OSC 8 hyperlinks off. Scribe supports both. Hyperlinks matter
126
+ * because Pi reopens the OSC 8 sequence on every wrapped physical row, so
127
+ * the terminal's ctrl+click opens the full URL instead of one row's
128
+ * fragment of a hard-wrapped link.
129
+ */
130
+ export function enableScribeCapabilities(): void {
123
131
  if (process.env.TERM_PROGRAM?.toLowerCase() !== "scribe") return;
124
132
  const capabilities = getCapabilities();
125
- if (capabilities.images !== "kitty") {
126
- setCapabilities({ ...capabilities, images: "kitty" });
133
+ if (capabilities.images !== "kitty" || !capabilities.hyperlinks) {
134
+ setCapabilities({ ...capabilities, images: "kitty", hyperlinks: true });
127
135
  }
128
136
  }
129
137
 
@@ -340,7 +348,9 @@ export function installImagePreview(
340
348
  }
341
349
  changingText = true;
342
350
  try {
343
- 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);
344
354
  } finally {
345
355
  changingText = false;
346
356
  }
@@ -461,17 +471,31 @@ export function installImagePreview(
461
471
  },
462
472
  clear() {
463
473
  stopLoader();
464
- for (const preview of previews.values()) preview.cancelThumbnail?.();
465
- previews.clear();
466
- 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
+ }
467
487
  visibleMarkers = "";
468
488
  activePreviews = [];
469
489
  activeImages = [];
470
490
  releaseOverlay();
491
+ if (previews.size) sync(text);
471
492
  },
472
493
  dispose() {
473
494
  if (target[INSTALLED] !== controller) return;
474
495
  removeFocusRefresh();
496
+ for (const preview of previews.values()) preview.cancelThumbnail?.();
497
+ previews.clear();
498
+ markersByPath.clear();
475
499
  controller.clear();
476
500
  target.render = render;
477
501
  delete target.onChange;
@@ -0,0 +1,90 @@
1
+ import type { TUI } from "@earendil-works/pi-tui";
2
+
3
+ const INSTALLED = Symbol.for("pi-proper-base.osc8-link-ids");
4
+ const OSC8_OPEN = "\x1b]8;;";
5
+ const ESC = "\x1b";
6
+ const BEL = "\x07";
7
+
8
+ type TerminalWriter = {
9
+ write(data: string): void;
10
+ [INSTALLED]?: () => void;
11
+ };
12
+
13
+ type TerminalTui = TUI & { terminal?: TerminalWriter };
14
+
15
+ /** FNV-1a of the URI in base36. */
16
+ function linkId(uri: string): string {
17
+ let hash = 0x811c9dc5;
18
+ for (let index = 0; index < uri.length; index++) {
19
+ hash ^= uri.charCodeAt(index);
20
+ hash = Math.imul(hash, 0x01000193);
21
+ }
22
+ return (hash >>> 0).toString(36);
23
+ }
24
+
25
+ /** End of the URI starting at `uriStart`: the position of its BEL or ST
26
+ * terminator, or -1 when the sequence is unterminated or malformed. */
27
+ function uriEndAt(data: string, uriStart: number): number {
28
+ const belAt = data.indexOf(BEL, uriStart);
29
+ const escAt = data.indexOf(ESC, uriStart);
30
+ if (belAt !== -1 && (escAt === -1 || belAt < escAt)) return belAt;
31
+ if (escAt !== -1 && data.startsWith("\\", escAt + 1)) return escAt;
32
+ return -1;
33
+ }
34
+
35
+ /**
36
+ * Give anonymous OSC 8 opens a stable URI-derived id. Pi reopens a wrapped
37
+ * hyperlink on every physical row without an id, so terminals assign each
38
+ * row its own link identity and hover-highlight one row at a time. A shared
39
+ * id lets id-aware terminals treat all rows of one link as a unit. Closes
40
+ * (empty URI), opens that already carry params, and malformed or split
41
+ * sequences stay untouched, and data without an anonymous open passes
42
+ * through by reference.
43
+ */
44
+ export function tagAnonymousOsc8Links(data: string): string {
45
+ let openAt = data.indexOf(OSC8_OPEN);
46
+ if (openAt === -1) return data;
47
+ let result = "";
48
+ let copied = 0;
49
+ while (openAt !== -1) {
50
+ const uriStart = openAt + OSC8_OPEN.length;
51
+ const uriEnd = uriEndAt(data, uriStart);
52
+ if (uriEnd > uriStart) {
53
+ const uri = data.slice(uriStart, uriEnd);
54
+ result += `${data.slice(copied, openAt)}${ESC}]8;id=${linkId(uri)};${uri}`;
55
+ copied = uriEnd;
56
+ }
57
+ openAt = data.indexOf(OSC8_OPEN, uriStart);
58
+ }
59
+ if (copied === 0) return data;
60
+ return result + data.slice(copied);
61
+ }
62
+
63
+ /**
64
+ * Rewrite TUI terminal writes so wrapped links share one hyperlink id.
65
+ * Unknown terminal shapes install nothing and keep Pi's native output.
66
+ */
67
+ export function installOsc8LinkIds(tui: TUI): (() => void) | undefined {
68
+ const terminal = (tui as TerminalTui).terminal;
69
+ if (!terminal || typeof terminal.write !== "function") return undefined;
70
+ if (terminal[INSTALLED]) return terminal[INSTALLED];
71
+
72
+ const hadOwnMethod = Object.hasOwn(terminal, "write");
73
+ const original = terminal.write;
74
+ const wrapped = function (this: TerminalWriter, data: string) {
75
+ return original.call(
76
+ this,
77
+ typeof data === "string" ? tagAnonymousOsc8Links(data) : data,
78
+ );
79
+ };
80
+ terminal.write = wrapped;
81
+
82
+ const dispose = () => {
83
+ if (terminal.write !== wrapped) return;
84
+ if (hadOwnMethod) terminal.write = original;
85
+ else delete (terminal as { write?: unknown }).write;
86
+ delete terminal[INSTALLED];
87
+ };
88
+ terminal[INSTALLED] = dispose;
89
+ return dispose;
90
+ }