@ftrdotdev/pi-tui 0.2.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/package.json +80 -0
  4. package/src/autocomplete-contract.test.ts +126 -0
  5. package/src/autocomplete-contract.ts +91 -0
  6. package/src/commands/git-execution.test.ts +69 -0
  7. package/src/commands/git-execution.ts +198 -0
  8. package/src/commands/git-status.test.ts +379 -0
  9. package/src/commands/git-status.ts +320 -0
  10. package/src/components/bordered-box.test.ts +136 -0
  11. package/src/components/bordered-box.ts +106 -0
  12. package/src/components/define-component.ts +33 -0
  13. package/src/components/index.ts +35 -0
  14. package/src/config.test.ts +469 -0
  15. package/src/config.ts +307 -0
  16. package/src/frame/box-frame.test.ts +44 -0
  17. package/src/frame/box-frame.ts +160 -0
  18. package/src/icons.ts +203 -0
  19. package/src/index.ts +359 -0
  20. package/src/runtime.ts +256 -0
  21. package/src/session-lifecycle.ts +41 -0
  22. package/src/state.test.ts +7 -0
  23. package/src/state.ts +90 -0
  24. package/src/telemetry.ts +301 -0
  25. package/src/ui/editor-tint.test.ts +70 -0
  26. package/src/ui/editor-tint.ts +78 -0
  27. package/src/ui/editor.ts +403 -0
  28. package/src/ui/footer.test.ts +350 -0
  29. package/src/ui/footer.ts +225 -0
  30. package/src/ui/header.test.ts +260 -0
  31. package/src/ui/header.ts +165 -0
  32. package/src/ui/preview.test.ts +639 -0
  33. package/src/ui/preview.ts +374 -0
  34. package/src/ui/render-helpers.ts +275 -0
  35. package/src/ui/settings-command.test.ts +218 -0
  36. package/src/ui/settings-command.ts +390 -0
  37. package/src/utils.ts +448 -0
  38. package/src/vim/editor-close-autocomplete.ts +26 -0
  39. package/src/vim/editor-host.test.ts +340 -0
  40. package/src/vim/editor-state.test.ts +385 -0
  41. package/src/vim/editor-state.ts +314 -0
  42. package/src/vim/mode-indicator.test.ts +27 -0
  43. package/src/vim/mode-indicator.ts +44 -0
  44. package/src/vim/selection-render.test.ts +77 -0
  45. package/src/vim/selection-render.ts +85 -0
  46. package/src/vim/text-model.test.ts +85 -0
  47. package/src/vim/text-model.ts +75 -0
  48. package/src/vim/vim-router.test.ts +50 -0
  49. package/src/vim/vim-router.ts +55 -0
  50. package/src/vim/word-motion.ts +96 -0
@@ -0,0 +1,70 @@
1
+ import { afterEach, assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ EditorTintService,
6
+ EditorTintServiceDefault,
7
+ type EditorTintServiceHandle,
8
+ resetEditorTintProviders,
9
+ upsertBorderTintProvider,
10
+ } from "./editor-tint.ts";
11
+
12
+ const resolveTint = (): EditorTintServiceHandle =>
13
+ Effect.runSync(
14
+ Effect.service(EditorTintService).pipe(Effect.provide(EditorTintServiceDefault)),
15
+ );
16
+
17
+ afterEach(() => {
18
+ resetEditorTintProviders();
19
+ });
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // EditorTintService (configure / getTint)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ it("returns undefined with no providers registered", () => {
26
+ assert.strictEqual(resolveTint().getTint(), undefined);
27
+ });
28
+
29
+ it("returns the registered provider's tint", () => {
30
+ const tint = resolveTint();
31
+ tint.configure((cur) =>
32
+ upsertBorderTintProvider(cur, { id: "a", getTint: () => "success" }),
33
+ );
34
+ assert.strictEqual(tint.getTint(), "success");
35
+ });
36
+
37
+ it("the last provider with a defined tint wins (later .configure overrides)", () => {
38
+ const tint = resolveTint();
39
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "a", getTint: () => "success" }));
40
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "b", getTint: () => "error" }));
41
+ assert.strictEqual(tint.getTint(), "error");
42
+ });
43
+
44
+ it("providers whose tint is undefined fall through to earlier ones", () => {
45
+ const tint = resolveTint();
46
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "base", getTint: () => "success" }));
47
+ tint.configure((cur) =>
48
+ upsertBorderTintProvider(cur, { id: "pass", getTint: () => undefined }),
49
+ );
50
+ // "pass" is last but undefined → falls through to "base"
51
+ assert.strictEqual(tint.getTint(), "success");
52
+ });
53
+
54
+ it("upserting the same id replaces it in place", () => {
55
+ const tint = resolveTint();
56
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "x", getTint: () => "success" }));
57
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "x", getTint: () => "error" }));
58
+ assert.strictEqual(tint.getTint(), "error");
59
+ });
60
+
61
+ it("a provider's tint is read live on every getTint (dynamic)", () => {
62
+ const tint = resolveTint();
63
+ let current: ThemeColor | undefined = "success";
64
+ tint.configure((cur) => upsertBorderTintProvider(cur, { id: "dyn", getTint: () => current }));
65
+ assert.strictEqual(tint.getTint(), "success");
66
+ current = "warning";
67
+ assert.strictEqual(tint.getTint(), "warning");
68
+ current = undefined;
69
+ assert.strictEqual(tint.getTint(), undefined);
70
+ });
@@ -0,0 +1,78 @@
1
+ import { Context, Layer } from "effect";
2
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
3
+
4
+ /**
5
+ * A border-tint contribution. `id` stamps the contributor so a later
6
+ * `.configure` can replace a specific one (e.g. another extension overriding
7
+ * vim's tint); `getTint` is evaluated live, so a provider whose color changes
8
+ * over time (vim: normal/visual/insert) reflects the current state on every
9
+ * editor render.
10
+ */
11
+ export interface BorderTintProvider {
12
+ readonly id: string;
13
+ readonly getTint: () => ThemeColor | undefined;
14
+ }
15
+
16
+ /**
17
+ * Effect service for editor border coloring — generic, not vim-specific.
18
+ * Any extension can inject or override border tints through
19
+ * `configure`; the editor just asks `getTint` and applies the result (or
20
+ * falls back to pi's own border color when none is defined).
21
+ *
22
+ * Providers are ordered; the last provider with a defined tint wins, so a
23
+ * later `.configure` can override an earlier one. The default layer exposes a
24
+ * shared (module-level) registry, so the editor and any extension that
25
+ * resolves the same service see the same providers.
26
+ *
27
+ * House service pattern (config.ts, vim-router.ts): `Context.Service` class,
28
+ * instance type `EditorTintService["Service"]`, defaulted via a layer.
29
+ */
30
+ export class EditorTintService extends Context.Service<
31
+ EditorTintService,
32
+ {
33
+ readonly configure: (
34
+ update: (current: readonly BorderTintProvider[]) => readonly BorderTintProvider[],
35
+ ) => void;
36
+ readonly getTint: () => ThemeColor | undefined;
37
+ }
38
+ >()("tui/editor/EditorTintService") {}
39
+
40
+ /** Resolved instance shape (what `Effect.service(EditorTintService)` returns). */
41
+ export type EditorTintServiceHandle = EditorTintService["Service"];
42
+
43
+ // Module-level registry shared by every provider of the default layer.
44
+ let providers: readonly BorderTintProvider[] = [];
45
+
46
+ const implementation = EditorTintService.of({
47
+ configure(update) {
48
+ providers = update(providers);
49
+ },
50
+ getTint() {
51
+ for (let i = providers.length - 1; i >= 0; i--) {
52
+ const tint = providers[i]?.getTint();
53
+ if (tint !== undefined) return tint;
54
+ }
55
+ return undefined;
56
+ },
57
+ });
58
+
59
+ /** Default layer exposing the shared registry; extensions may override it. */
60
+ export const EditorTintServiceDefault = Layer.succeed(EditorTintService, implementation);
61
+
62
+ /**
63
+ * Reset the shared registry (test support).
64
+ */
65
+ export function resetEditorTintProviders(): void {
66
+ providers = [];
67
+ }
68
+
69
+ /**
70
+ * Upsert a provider by `id`: drop any existing provider with the same id,
71
+ * then append `provider` so it takes precedence from now on.
72
+ */
73
+ export function upsertBorderTintProvider(
74
+ current: readonly BorderTintProvider[],
75
+ provider: BorderTintProvider,
76
+ ): readonly BorderTintProvider[] {
77
+ return [...current.filter((p) => p.id !== provider.id), provider];
78
+ }
@@ -0,0 +1,403 @@
1
+ import {
2
+ CustomEditor,
3
+ type ExtensionAPI,
4
+ type ExtensionContext,
5
+ type KeybindingsManager,
6
+ type Theme,
7
+ type ThemeColor,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
10
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
+ import {
12
+ inspectAutocompleteInternals,
13
+ type AutocompleteInternals,
14
+ } from "../autocomplete-contract.ts";
15
+ import { makeBorderedBox } from "../components/bordered-box.ts";
16
+ import { buildBoxFrame, composeBorderLine } from "../frame/box-frame.ts";
17
+ import { findBottomBorderIndex, isEditorBorderLine, padRight, stripAnsi } from "../utils.ts";
18
+ import { closeAutocomplete } from "../vim/editor-close-autocomplete.ts";
19
+ import { VimEditorState } from "../vim/editor-state.ts";
20
+ import { vimModeGlyph, vimModeTint } from "../vim/mode-indicator.ts";
21
+ import { type EditorTintServiceHandle, upsertBorderTintProvider } from "./editor-tint.ts";
22
+ import { renderSelection } from "../vim/selection-render.ts";
23
+ import { type Cursor, type Range, type VimTextModelShape } from "../vim/text-model.ts";
24
+ import { wordBackward, wordEnd, wordForward } from "../vim/word-motion.ts";
25
+
26
+ /**
27
+ * Top or bottom border of the editor frame, composed from the shared
28
+ * {@link buildBoxFrame} model and {@link composeBorderLine} so every box in
29
+ * the package uses the same geometry. The top border carries the host
30
+ * editor's scroll hint (`↓ N more`) and, when one is injected, the mode
31
+ * indicator glyph (`N · ↓ 3 more`), with a single trailing space instead of
32
+ * the model's default decorative dash tail — hence the `labelSuffix`
33
+ * override.
34
+ */
35
+ function roundedBorder(
36
+ width: number,
37
+ kind: "top" | "bottom",
38
+ paint: (s: string) => string,
39
+ sourceLine?: string,
40
+ modeGlyph?: string,
41
+ ): string {
42
+ const scrollLabel =
43
+ sourceLine === undefined ? undefined : stripAnsi(sourceLine).match(/([↑↓]\s+\d+\s+more)/)?.[1];
44
+ // The mode glyph and the scroll hint share the border's single label slot;
45
+ // join them with the house separator so a narrow editor drops both together.
46
+ const label =
47
+ modeGlyph === undefined
48
+ ? scrollLabel
49
+ : scrollLabel === undefined
50
+ ? modeGlyph
51
+ : `${modeGlyph} · ${scrollLabel}`;
52
+ const frame = buildBoxFrame(width, {
53
+ label,
54
+ labelWidth: label === undefined ? undefined : visibleWidth(label),
55
+ labelSuffix: label === undefined ? undefined : " ",
56
+ minLabelWidth: 3,
57
+ paddingX: 0,
58
+ });
59
+ // The caller guards `width < 4`, so the frame is never null here; the
60
+ // fallback only narrows the type for the degenerate model.
61
+ if (!frame) return paint(kind === "top" ? "╭╮" : "╰╯");
62
+ return composeBorderLine(frame, kind, paint);
63
+ }
64
+
65
+ export interface TuiEditorOptions {
66
+ /** Called once when the autocomplete internals contract no longer matches. */
67
+ readonly onAutocompleteMismatch?: (detail: string) => void;
68
+ /** Live vim toggle; the editor is a plain always-insert editor when off. */
69
+ readonly getVimEnabled?: () => boolean;
70
+ /** Paint applied to the visual-mode selection span (default: identity). */
71
+ readonly paintSelection?: (s: string) => string;
72
+ /**
73
+ * Current border tint to apply (e.g. from the shared EditorTintService), or
74
+ * undefined to keep pi's own border color. Generic — the editor has no
75
+ * notion of what supplied the color.
76
+ */
77
+ readonly getBorderTint?: () => ThemeColor | undefined;
78
+ /** Paints a given theme color onto text (e.g. `theme.fg(color, s)`). */
79
+ readonly tintPaint?: (color: ThemeColor, s: string) => string;
80
+ /**
81
+ * Live mode indicator for the top border (e.g. vim's N/I/V letter), or
82
+ * undefined for none. A thunk so the glyph follows mode changes on every
83
+ * render; when the scroll hint is also present the two share the label
84
+ * slot (`N · ↓ 3 more`). Generic — the editor has no notion of what
85
+ * supplied the glyph.
86
+ */
87
+ readonly getModeIndicator?: () => string | undefined;
88
+ }
89
+
90
+ export class TuiEditor extends CustomEditor {
91
+ // BorderedBox paints its rails via theme.fg(color, text); route every token
92
+ // through the editor's own border paint so the suggestion box follows bash
93
+ // mode / thinking-level recoloring and any registered border tint like the
94
+ // input frame does.
95
+ private readonly boxTheme: Theme;
96
+ private readonly onAutocompleteMismatch?: (detail: string) => void;
97
+ private readonly paintSelection: (s: string) => string;
98
+ private readonly getBorderTint?: () => ThemeColor | undefined;
99
+ private readonly tintPaint?: (color: ThemeColor, s: string) => string;
100
+ private readonly getModeIndicator?: () => string | undefined;
101
+ /** The modal state machine backing vim; read by the package's tint wiring. */
102
+ readonly vimState: VimEditorState;
103
+ private autocompleteDiagnosed = false;
104
+
105
+ constructor(
106
+ tui: TUI,
107
+ editorTheme: EditorTheme,
108
+ keybindings: KeybindingsManager,
109
+ options: TuiEditorOptions = {},
110
+ ) {
111
+ super(tui, editorTheme, keybindings, { paddingX: 0 });
112
+ this.boxTheme = {
113
+ fg: (_color: ThemeColor, s: string) => this.borderPaint(s),
114
+ } as unknown as Theme;
115
+ this.onAutocompleteMismatch = options.onAutocompleteMismatch;
116
+ this.paintSelection = options.paintSelection ?? ((s: string) => s);
117
+ this.getBorderTint = options.getBorderTint;
118
+ this.tintPaint = options.tintPaint;
119
+ this.getModeIndicator = options.getModeIndicator;
120
+ // The editor exposes its text through a VimTextModelShape adapter (the
121
+ // state machine stays a plain class over that interface; gate off by
122
+ // default). `moveToLineStart`/`moveToLineEnd` live in the adapter because
123
+ // the pi-tui base class already owns those private names.
124
+ this.vimState = new VimEditorState(
125
+ this.buildVimModel(),
126
+ options.getVimEnabled ?? (() => false),
127
+ );
128
+ }
129
+
130
+ override setPaddingX(_padding: number): void {
131
+ // The custom rail owns the horizontal inset and keeps one stable text gap.
132
+ super.setPaddingX(0);
133
+ }
134
+
135
+ /**
136
+ * Validated view of pi's autocomplete internals. When the contract no
137
+ * longer matches (pi internals changed shape), report once and return
138
+ * undefined so rendering falls back to the unframed passthrough.
139
+ */
140
+ private getAutocompleteView(): AutocompleteInternals | undefined {
141
+ const inspection = inspectAutocompleteInternals(this);
142
+ if (inspection.ok) {
143
+ // Both fields are set and cleared together in the built-in editor, so
144
+ // active suggestions without a render-able list mean a rename/shape
145
+ // change rather than a transient in-flight state.
146
+ if (this.isShowingAutocomplete() && inspection.view.autocompleteList === undefined) {
147
+ this.reportAutocompleteMismatch("autocomplete is active but no render-able list was found");
148
+ }
149
+ return inspection.view;
150
+ }
151
+ this.reportAutocompleteMismatch(inspection.issue);
152
+ return undefined;
153
+ }
154
+
155
+ private reportAutocompleteMismatch(detail: string): void {
156
+ if (this.autocompleteDiagnosed) return;
157
+ this.autocompleteDiagnosed = true;
158
+ this.onAutocompleteMismatch?.(detail);
159
+ }
160
+
161
+ // -------------------------------------------------------------------------
162
+ // VimTextModelShape over the real editor
163
+ // -------------------------------------------------------------------------
164
+
165
+ /**
166
+ * The state machine's view of this editor. `moveToLineStart`/
167
+ * `moveToLineEnd` are pure cursor computations provided here because the
168
+ * pi-tui base class owns those private names (they would collide on the
169
+ * class itself).
170
+ */
171
+ private buildVimModel(): VimTextModelShape {
172
+ return {
173
+ getText: () => this.getText(),
174
+ getCursor: () => this.getCursor(),
175
+ moveCursorTo: (c) => this.moveCursorTo(c),
176
+ getLineCount: () => this.getLineCount(),
177
+ lineLength: (line) => this.lineLength(line),
178
+ moveWordForward: (from) => this.moveWordForward(from),
179
+ moveWordBackward: (from) => this.moveWordBackward(from),
180
+ moveWordEnd: (from) => this.moveWordEnd(from),
181
+ moveToLineStart: (c) => ({ line: c.line, col: 0 }),
182
+ moveToLineEnd: (c) => ({ line: c.line, col: this.lineLength(c.line) }),
183
+ deleteRange: (range) => this.deleteRange(range),
184
+ yankRange: (range) => this.yankRange(range),
185
+ replaceRange: (range, text) => this.replaceRange(range, text),
186
+ insertTextAtCursor: (text) => this.insertTextAtCursor(text),
187
+ };
188
+ }
189
+
190
+ getLineCount(): number {
191
+ return this.getLines().length;
192
+ }
193
+
194
+ lineLength(line: number): number {
195
+ return this.getLines()[line]?.length ?? 0;
196
+ }
197
+
198
+ /**
199
+ * Move the cursor, clamped to the text bounds. Writes the private editor
200
+ * state through a guarded surface (pi-tui has no public cursor-setter);
201
+ * `setCursorCol` is preferred because it clears the insert-mode sticky
202
+ * column so vim motions never inherit it.
203
+ */
204
+ moveCursorTo(c: Cursor): void {
205
+ const internal = this as unknown as {
206
+ state?: { cursorLine?: number; cursorCol?: number };
207
+ setCursorCol?: (col: number) => void;
208
+ };
209
+ if (!internal.state) return;
210
+ const line = Math.max(0, Math.min(c.line, this.getLineCount() - 1));
211
+ const col = Math.max(0, Math.min(c.col, this.lineLength(line)));
212
+ internal.state.cursorLine = line;
213
+ if (typeof internal.setCursorCol === "function") internal.setCursorCol(col);
214
+ else internal.state.cursorCol = col;
215
+ }
216
+
217
+ moveWordForward(from: Cursor): Cursor {
218
+ return wordForward(this.getLines(), from);
219
+ }
220
+
221
+ moveWordBackward(from: Cursor): Cursor {
222
+ return wordBackward(this.getLines(), from);
223
+ }
224
+
225
+ moveWordEnd(from: Cursor): Cursor {
226
+ return wordEnd(this.getLines(), from);
227
+ }
228
+
229
+ /** Absolute index of a cursor in the newline-joined text. */
230
+ private absoluteIndex(c: Cursor): number {
231
+ const lines = this.getLines();
232
+ let idx = 0;
233
+ for (let i = 0; i < c.line; i++) idx += (lines[i]?.length ?? 0) + 1;
234
+ return idx + c.col;
235
+ }
236
+
237
+ deleteRange(range: Range): void {
238
+ const flat = this.getText();
239
+ const startIdx = this.absoluteIndex(range.start);
240
+ const endIdx = this.absoluteIndex(range.end);
241
+ this.setText(flat.slice(0, startIdx) + flat.slice(endIdx));
242
+ // setText resets the cursor to the end; restore it to the range start.
243
+ this.moveCursorTo(range.start);
244
+ }
245
+
246
+ yankRange(range: Range): string {
247
+ const flat = this.getText();
248
+ return flat.slice(this.absoluteIndex(range.start), this.absoluteIndex(range.end));
249
+ }
250
+
251
+ replaceRange(range: Range, text: string): void {
252
+ const flat = this.getText();
253
+ const startIdx = this.absoluteIndex(range.start);
254
+ const endIdx = this.absoluteIndex(range.end);
255
+ this.setText(flat.slice(0, startIdx) + text + flat.slice(endIdx));
256
+ this.moveCursorTo(range.start);
257
+ }
258
+
259
+ override handleInput(data: string): void {
260
+ const decision = this.vimState.step(data);
261
+ if (decision.kind === "consumed") {
262
+ // Entering Normal (Escape in Insert) closes the autocomplete popup
263
+ // (binding decision 2); the TUI re-renders after handleInput.
264
+ if (decision.enteredNormal) closeAutocomplete(this);
265
+ return;
266
+ }
267
+ super.handleInput(data);
268
+ }
269
+
270
+ /**
271
+ * The border paint for the current state. A registered border tint (from
272
+ * the shared EditorTintService, which vim or any extension may contribute)
273
+ * overrides pi's own `borderColor`; with no tint, bash/thinking recoloring
274
+ * keeps working untouched.
275
+ */
276
+ private borderPaint(s: string): string {
277
+ const tint = this.getBorderTint?.();
278
+ if (tint !== undefined && this.tintPaint) return this.tintPaint(tint, s);
279
+ return this.borderColor(s);
280
+ }
281
+
282
+ override render(width: number): string[] {
283
+ if (width < 4) return super.render(width);
284
+
285
+ const rail = this.borderPaint("│");
286
+ const borderPaint = (s: string) => this.borderPaint(s);
287
+ const innerWidth = Math.max(0, width - 4);
288
+ const baseLines = super.render(innerWidth);
289
+
290
+ // While suggestions are showing, the built-in editor appends the list
291
+ // right after the input's bottom border. The split point comes from the
292
+ // validated internals contract; when the contract is unavailable (pi
293
+ // internals changed shape) we fall back to the scan below.
294
+ const internals = this.getAutocompleteView();
295
+ const list = internals?.autocompleteList;
296
+ const listLines = list ? list.render(innerWidth) : [];
297
+ const hasFramedList =
298
+ this.isShowingAutocomplete() &&
299
+ listLines.length > 0 &&
300
+ baseLines.length > listLines.length + 1;
301
+ const bottomIdx = hasFramedList
302
+ ? baseLines.length - listLines.length - 1
303
+ : findBottomBorderIndex(baseLines);
304
+
305
+ // Visual-mode selection highlight: paint the state machine's range onto
306
+ // the content lines (between the top border at 0 and the bottom border at
307
+ // bottomIdx). First cut maps the logical range onto the rendered lines.
308
+ const selection = this.vimState.selection;
309
+ const contentLines = selection
310
+ ? renderSelection({
311
+ lines: baseLines.slice(1, bottomIdx),
312
+ selection,
313
+ paint: this.paintSelection,
314
+ })
315
+ : undefined;
316
+
317
+ const result: string[] = [];
318
+ result.push(roundedBorder(width, "top", borderPaint, baseLines[0], this.getModeIndicator?.()));
319
+
320
+ for (let i = 1; i < bottomIdx; i++) {
321
+ const line = contentLines ? (contentLines[i - 1] ?? "") : (baseLines[i] ?? "");
322
+ if (isEditorBorderLine(line)) {
323
+ result.push(`${rail} ${padRight("", innerWidth)} ${rail}`);
324
+ } else {
325
+ result.push(`${rail} ${padRight(line, innerWidth)} ${rail}`);
326
+ }
327
+ }
328
+
329
+ result.push(roundedBorder(width, "bottom", borderPaint, baseLines[bottomIdx]));
330
+
331
+ if (hasFramedList) {
332
+ const prefix = internals?.autocompletePrefix;
333
+ const label = truncateToWidth(
334
+ `suggestions${prefix ? ` · ${prefix}` : ""}`,
335
+ Math.max(4, width - 16),
336
+ "",
337
+ );
338
+ const box = makeBorderedBox(
339
+ { render: () => listLines, invalidate: () => {} },
340
+ this.boxTheme,
341
+ { label, paddingX: 1 },
342
+ );
343
+ result.push(...box.render(width));
344
+ } else {
345
+ for (let i = bottomIdx + 1; i < baseLines.length; i++) {
346
+ result.push(baseLines[i]!);
347
+ }
348
+ }
349
+
350
+ return result.map((line) => truncateToWidth(line, width, ""));
351
+ }
352
+ }
353
+
354
+ export function installEditor(
355
+ _pi: ExtensionAPI,
356
+ ctx: ExtensionContext,
357
+ options: {
358
+ readonly getVimEnabled: () => boolean;
359
+ readonly tint: EditorTintServiceHandle;
360
+ },
361
+ ): () => void {
362
+ ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => {
363
+ const editor = new TuiEditor(tui, editorTheme, keybindings, {
364
+ getVimEnabled: options.getVimEnabled,
365
+ // Paints the resolved border tint through the theme's color fg().
366
+ tintPaint: (color, s) => ctx.ui.theme.fg(color, s),
367
+ // The editor stays generic: it asks the shared service for a tint and
368
+ // knows nothing about vim. vim is just one provider registered here.
369
+ getBorderTint: () => options.tint.getTint(),
370
+ // vim registers its own live mode indicator (the editor stays generic
371
+ // and just asks the injected getter per render, like the tint).
372
+ getModeIndicator: () => vimModeGlyph(editor.vimState),
373
+ paintSelection: (s) => ctx.ui.theme.inverse(s),
374
+ onAutocompleteMismatch: (detail) => {
375
+ const message =
376
+ `[pi-tui] built-in autocomplete internals no longer match the expected contract ` +
377
+ `(${detail}); suggestion framing disabled. ` +
378
+ `This usually means the bundled pi editor changed shape — please update this extension.`;
379
+ console.warn(message);
380
+ // notify may request a render; defer so we never re-enter from inside a render pass.
381
+ queueMicrotask(() =>
382
+ ctx.ui.notify(
383
+ "Autocomplete framing disabled: internals changed shape (see logs).",
384
+ "warning",
385
+ ),
386
+ );
387
+ },
388
+ });
389
+ // Register vim's own border-tint provider into the shared service. The
390
+ // getTint closure reads the editor's live modal state, so the border
391
+ // tracks normal/visual/insert without the editor knowing vim exists.
392
+ options.tint.configure((current) =>
393
+ upsertBorderTintProvider(current, {
394
+ id: "vim",
395
+ getTint: () => vimModeTint(editor.vimState),
396
+ }),
397
+ );
398
+ return editor;
399
+ });
400
+ return () => {
401
+ ctx.ui.setEditorComponent(undefined);
402
+ };
403
+ }