pi-tui-prompt-box 0.0.1 → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ ## [0.1.1] - 12.11.2026
4
+
5
+ ### New
6
+ * `[ui]` Show the routed model of a virtual model in the status line, not in the footer.
7
+ * `[ui]` Color the routed thinking level and the busy indicator with that level's color.
8
+
9
+ ## [0.1.0] - 11.11.2026
10
+
11
+ ### New
12
+ * `[ui]` Replace the prompt editor with a filled box and an inner status line.
13
+ * `[ui]` Take the accent bar and status line colors from the current Pi theme.
14
+ * `[ui]` Show `Bash` in the status line for `!` input, `Bash (no context)` for `!!`.
15
+ * `[ui]` Indent Pi's footer by the box margin so it starts in the same column as the box.
16
+ * `[ui]` Remove the model and provider from Pi's built-in footer -> the box shows them.
17
+ * `[ui]` Show Pi's busy indicators in the status line, including retry and compaction.
18
+ * `[ui]` Show only the spinner for Pi's default `Working` message.
19
+ * `[ui]` Indent the chat, queued messages, and widgets by the box margin.
20
+ * `[ui]` Keep the chat clear of Pi's fullscreen `auto` scrollbar; box and footer align.
21
+ * `[ui]` Align the autocomplete item text with the input text.
22
+ * `[ui]` Map mouse clicks on the box to the input text and the autocomplete list.
23
+ * `[ui]` Indent selectors and extension dialogs shown in place of the box like the chat.
24
+ * `[ui]` Show Pi's scroll indicators as `N ↑` / `N ↓` in the box padding rows.
25
+ * `[ui]` Apply Pi's editor `paddingX` setting to the box margins, not the text padding.
26
+ * `[ui]` Show `thinking off` in the status line; hide the level for non-reasoning models.
27
+ * `[ui]` Derive the box background from the terminal background instead of a fixed gray.
28
+
29
+
30
+ ## [0.0.1] - 01.11.2026
31
+
32
+ 🌱 Proof-of-Concept implementation.
package/README.md CHANGED
@@ -1,18 +1,26 @@
1
1
  # pi-tui-prompt-box
2
2
 
3
3
  <p align="center">
4
+ <img width="456" src="https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/d40318c625f33ef90f99108bb0536a8872174cab/doc/images/pi-tui-prompt-box.png" alt="pi-tui-prompt-box preview">
5
+ <br>
4
6
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square" alt="License: MIT"></a>
7
+ <a href="https://pi.dev/packages/pi-tui-prompt-box"><img src="https://img.shields.io/badge/Pi-Package-6366F1?style=flat-square" alt="Pi Package"></a>
5
8
  <a href="https://www.npmjs.com/package/pi-tui-prompt-box"><img src="https://img.shields.io/npm/v/pi-tui-prompt-box?style=flat-square&amp;logoColor=white" alt="npm version"></a>
6
9
  </p>
7
10
 
8
11
  <br>
9
12
 
10
- [Pi](https://pi.dev) extension that replaces the prompt editor with a filled
11
- box. The box has a left accent bar and a status line inside it with the model,
12
- the provider, the thinking level, and a busy indicator.
13
+ An alternative style for the prompt input in [Pi](https://pi.dev).
13
14
 
14
- > [!Warning]
15
- > **Early access**: the look and behavior may still change.
15
+ It styles the prompt box and nothing else. Other TUI components are only moved
16
+ to line up with the box. Their content and styling stay unchanged.
17
+
18
+ It is a building block, not a full theme: combine it with your favorite footer,
19
+ completion menu, or any other styling extension.
20
+
21
+ ## Demo
22
+
23
+ ![Demo: thinking levels and bash mode](https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/530f3c8670c3c91c9f970a791509f21cdcedd79e/doc/images/demo.gif)
16
24
 
17
25
  ## Install
18
26
 
@@ -20,6 +28,20 @@ the provider, the thinking level, and a busy indicator.
20
28
  pi install npm:pi-tui-prompt-box
21
29
  ```
22
30
 
31
+ ## Side Effects
32
+
33
+ - Moves the chat, widgets, dialogs, and footer right so they line up with the
34
+ prompt box. Their content and styling stay unchanged.
35
+
36
+ - Removes the model, provider, and thinking level from the default footer, as the
37
+ prompt box already shows them. Custom footers stay unchanged.
38
+
39
+ - Moves Pi's busy indicator (spinner and message) into the prompt box. Custom
40
+ spinner widgets stay unchanged.
41
+
42
+ - Replaces Pi's editor, so it does not work together with other extensions that
43
+ replace the editor.
44
+
23
45
  ## Context Footprint
24
46
 
25
47
  None. The extension only changes the terminal UI: it adds no tools, prompt
@@ -27,10 +49,9 @@ sections, or messages to the model context.
27
49
 
28
50
  ## My Other Stuff
29
51
 
30
- 📌 [S-VHS](https://github.com/dimk90/s-vhs) - terminal recorder used to create the demo GIFs.
52
+ 📌 [S-VHS](https://github.com/dimk90/s-vhs) - A terminal recorder used to create the demo GIFs.
31
53
 
32
- 📌 [pi-context-view](https://github.com/dimk90/pi-context-view) - Pi extension to visualize context usage and inspect
33
- the hidden parts: base prompt, tool definitions, and extension injections.
54
+ 📌 [pi-context-view](https://github.com/dimk90/pi-context-view) - Pi extension to visualize context usage and inspect its hidden parts.
34
55
 
35
56
  ## License
36
57
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-tui-prompt-box",
3
- "version": "0.0.1",
4
- "description": "Replaces Pi's prompt editor with a filled box that shows the model, thinking level, and busy state",
3
+ "version": "0.1.1",
4
+ "description": "A prompt box style for Pi that combines with other styling extensions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Dmitry Makarov",
@@ -15,28 +15,33 @@
15
15
  },
16
16
  "keywords": [
17
17
  "pi",
18
+ "pi-package",
18
19
  "pi-extension",
19
- "coding-agent"
20
+ "coding-agent",
21
+ "theme"
20
22
  ],
21
23
  "engines": {
22
24
  "node": ">=22.19.0"
23
25
  },
24
26
  "files": [
25
27
  "src",
26
- "README.md"
28
+ "README.md",
29
+ "CHANGELOG.md"
27
30
  ],
28
31
  "pi": {
29
32
  "extensions": [
30
33
  "./src/index.ts"
31
- ]
34
+ ],
35
+ "image": "https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/d40318c625f33ef90f99108bb0536a8872174cab/doc/images/pi-tui-prompt-box.png"
32
36
  },
33
37
  "peerDependencies": {
34
38
  "@earendil-works/pi-coding-agent": "*",
35
39
  "@earendil-works/pi-tui": "*"
36
40
  },
37
41
  "devDependencies": {
38
- "@earendil-works/pi-coding-agent": "1.4.0",
39
- "@earendil-works/pi-tui": "1.4.0",
42
+ "@earendil-works/pi-ai": "1.5.2",
43
+ "@earendil-works/pi-coding-agent": "1.5.2",
44
+ "@earendil-works/pi-tui": "1.5.2",
40
45
  "@types/node": "^22.20.1",
41
46
  "typescript": "^7.0.2"
42
47
  },
package/src/index.ts CHANGED
@@ -5,60 +5,88 @@
5
5
  */
6
6
 
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
- import type { TUI } from "@earendil-works/pi-tui";
8
+ import type { RgbColor, TUI } from "@earendil-works/pi-tui";
9
9
 
10
- import { PromptBoxEditor } from "./ui/prompt-box-editor.ts";
11
- import { formatStatus } from "./ui/status-line.ts";
12
-
13
- const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
14
- const SPINNER_INTERVAL_MS = 80;
10
+ import { findRoutedModel } from "./routed-model.ts";
11
+ import { watchTerminalBackground } from "./terminal-background.ts";
12
+ import { computeBoxColors, type ReadBoxColors } from "./ui/colors.ts";
13
+ import { padPiContainers } from "./ui/padded-containers.ts";
14
+ import { findBuiltInFooter, PaddedFooter } from "./ui/padded-footer.ts";
15
+ import { PromptBoxEditor, type RenderStatus } from "./ui/prompt-box-editor.ts";
16
+ import { readScrollbarPadding } from "./ui/scrollbar-padding.ts";
17
+ import { formatStatus, readRoutedLevelColor } from "./ui/status-line.ts";
15
18
 
16
19
  /**
17
20
  * Registers the prompt box editor for every session.
18
21
  */
19
22
  export default function promptBox(pi: ExtensionAPI): void {
20
- let isWorking = false;
21
- let spinnerIndex = 0;
22
- let spinnerTimer: ReturnType<typeof setInterval> | undefined;
23
- let activeTui: TUI | undefined;
23
+ let restoreContainers: (() => void) | undefined;
24
+ let stopWatchingBackground: (() => void) | undefined;
24
25
 
25
- function stopSpinner(): void {
26
- clearInterval(spinnerTimer);
27
- spinnerTimer = undefined;
28
- }
26
+ pi.on("session_start", (_event, ctx) => {
27
+ const renderStatus: RenderStatus = (barColor, bashMode) =>
28
+ formatStatus({
29
+ theme: ctx.ui.theme,
30
+ levelColor: barColor,
31
+ bashMode,
32
+ model: ctx.model,
33
+ getProviderName: (provider) => ctx.modelRegistry.getProviderDisplayName(provider),
34
+ thinkingLevel: pi.getThinkingLevel(),
35
+ routedModel: findRoutedModel(ctx),
36
+ });
29
37
 
30
- pi.on("agent_start", () => {
31
- isWorking = true;
32
- stopSpinner();
33
- spinnerTimer = setInterval(() => {
34
- spinnerIndex = (spinnerIndex + 1) % SPINNER_FRAMES.length;
35
- activeTui?.requestRender();
36
- }, SPINNER_INTERVAL_MS);
37
- activeTui?.requestRender();
38
- });
38
+ let terminalBackground: RgbColor | undefined;
39
+ const readBoxColors: ReadBoxColors = () =>
40
+ computeBoxColors(terminalBackground, ctx.ui.theme.appearance, ctx.ui.theme.getColorMode());
39
41
 
40
- pi.on("agent_settled", () => {
41
- isWorking = false;
42
- stopSpinner();
43
- activeTui?.requestRender();
44
- });
42
+ let editorTui: TUI | undefined;
43
+ let editor: PromptBoxEditor | undefined;
44
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => {
45
+ editorTui = tui;
46
+ const readRightPadding = () => readScrollbarPadding(tui);
47
+ const readBusyColor = () => readRoutedLevelColor(ctx.ui.theme, findRoutedModel(ctx));
48
+ editor = new PromptBoxEditor(tui, theme, keybindings,
49
+ renderStatus,
50
+ readBoxColors,
51
+ readRightPadding,
52
+ readBusyColor,
53
+ );
54
+ return editor;
55
+ });
45
56
 
46
- pi.on("session_shutdown", () => {
47
- stopSpinner();
48
- activeTui = undefined;
49
- });
57
+ // Pi calls the editor factory synchronously, so both are set here in TUI mode only
58
+ if (!editorTui || !editor)
59
+ return;
50
60
 
51
- pi.on("session_start", (_event, ctx) => {
52
- // The box shows its own busy indicator in the status line
53
- ctx.ui.setWorkingVisible(false);
61
+ stopWatchingBackground = watchTerminalBackground(editorTui, (background) => {
62
+ terminalBackground = background;
63
+ editorTui?.requestRender();
64
+ });
54
65
 
55
- const renderStatus = () => {
56
- const spinnerFrame = isWorking ? SPINNER_FRAMES[spinnerIndex] : undefined;
57
- return formatStatus(ctx.model, pi.getThinkingLevel(), spinnerFrame);
58
- };
59
- ctx.ui.setEditorComponent((tui, theme, keybindings) => {
60
- activeTui = tui;
61
- return new PromptBoxEditor(tui, theme, keybindings, renderStatus);
66
+ restoreContainers = padPiContainers(editorTui, editor);
67
+
68
+ // Search before setFooter(): it removes the current footer from the tree before calling the factory
69
+ const builtInFooter = findBuiltInFooter(editorTui);
70
+ if (!builtInFooter)
71
+ return;
72
+
73
+ const readModelState = () => ({
74
+ model: ctx.model,
75
+ thinkingLevel: pi.getThinkingLevel(),
76
+ routedModel: findRoutedModel(ctx),
62
77
  });
78
+ ctx.ui.setFooter((tui) => new PaddedFooter(builtInFooter, readModelState, () => readScrollbarPadding(tui)));
79
+ });
80
+
81
+ pi.on("session_shutdown", (event) => {
82
+ stopWatchingBackground?.();
83
+ stopWatchingBackground = undefined;
84
+
85
+ // Pi keeps its containers across extension reloads and session changes, so remove the padding for the
86
+ // next extension instance; on quit it stays, as Pi may still print the transcript
87
+ if (event.reason !== "quit")
88
+ restoreContainers?.();
89
+
90
+ restoreContainers = undefined;
63
91
  });
64
92
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Routed model: the physical model a virtual model picked for the latest successful response.
3
+ */
4
+
5
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
6
+
7
+ // API id of Pi's virtual models; Pi does not export its own constant
8
+ const VIRTUAL_MODEL_API = "pi-virtual";
9
+
10
+ /**
11
+ * Physical model that answered, with the thinking level the router picked for it.
12
+ */
13
+ export interface RoutedModel {
14
+ model: NonNullable<ExtensionContext["model"]>;
15
+ thinkingLevel?: Parameters<Theme["getThinkingBorderColor"]>[0];
16
+ }
17
+
18
+ /**
19
+ * Parts of the extension context the routed model is read from.
20
+ */
21
+ export interface RoutedModelSource {
22
+ model: ExtensionContext["model"];
23
+ sessionManager: Pick<ExtensionContext["sessionManager"], "getLeafEntry" | "getEntry">;
24
+ modelRegistry: Pick<ExtensionContext["modelRegistry"], "find">;
25
+ }
26
+
27
+ /**
28
+ * Finds the routed model of the latest successful response on the current session branch.
29
+ *
30
+ * Pi gives extensions no access to the `routedModel` of its session, so this follows the same rules:
31
+ * only under a virtual selection, and failed or aborted responses are skipped. Returns `undefined`
32
+ * without such a response, or when its model is no longer in the registry.
33
+ */
34
+ export function findRoutedModel(source: RoutedModelSource): RoutedModel | undefined {
35
+ const { model, sessionManager, modelRegistry } = source;
36
+ if (model?.api !== VIRTUAL_MODEL_API)
37
+ return undefined;
38
+
39
+ // The answer is usually near the leaf, so walk up from it instead of building the whole branch
40
+ let entry = sessionManager.getLeafEntry();
41
+ while (entry) {
42
+ if (entry.type === "message" && entry.message.role === "assistant") {
43
+ const { stopReason, provider, model: modelId, thinkingLevel } = entry.message;
44
+ if (stopReason !== "error" && stopReason !== "aborted") {
45
+ const routedModel = modelRegistry.find(provider, modelId);
46
+ if (!routedModel || routedModel.api === VIRTUAL_MODEL_API)
47
+ return undefined;
48
+
49
+ return { model: routedModel, thinkingLevel };
50
+ }
51
+ }
52
+
53
+ entry = entry.parentId ? sessionManager.getEntry(entry.parentId) : undefined;
54
+ }
55
+
56
+ return undefined;
57
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Terminal background color, as the terminal reports it, for the box background.
3
+ */
4
+
5
+ import type { RgbColor, TerminalColors, TUI } from "@earendil-works/pi-tui";
6
+
7
+ // Pi waits as long for the terminal colors at startup
8
+ const QUERY_TIMEOUT_MS = 100;
9
+
10
+ /**
11
+ * Queries the terminal colors now and on every light/dark change the terminal reports, and passes each
12
+ * reported background to `onChange`, also replies that arrive after the timeout. Pi keeps the colors it
13
+ * read private, so the extension asks the terminal itself. Returns a function that stops watching;
14
+ * replies that arrive after it are ignored.
15
+ */
16
+ export function watchTerminalBackground(tui: TUI, onChange: (background: RgbColor) => void): () => void {
17
+ let stopped = false;
18
+ const report = (colors: TerminalColors) => {
19
+ if (!stopped && colors.background)
20
+ onChange(colors.background);
21
+ };
22
+ const query = () => {
23
+ void tui.queryTerminalColors({ timeoutMs: QUERY_TIMEOUT_MS, onLateReply: report }).then(report);
24
+ };
25
+
26
+ query();
27
+ const unsubscribe = tui.onTerminalColorSchemeChange(query);
28
+
29
+ return () => {
30
+ stopped = true;
31
+ unsubscribe();
32
+ };
33
+ }
package/src/ui/colors.ts CHANGED
@@ -1,10 +1,62 @@
1
1
  /**
2
- * ANSI color codes shared by the prompt box components; see doc/ui.md.
2
+ * ANSI color codes of the box background, shared by the prompt box components; see doc/ui.md.
3
3
  */
4
4
 
5
+ import type { ThemeAppearance } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ backgroundAnsi,
8
+ type Color,
9
+ colorToOkhsl,
10
+ foregroundAnsi,
11
+ okhslColor,
12
+ type RgbColor,
13
+ rgbColor,
14
+ type TerminalColorMode,
15
+ } from "@earendil-works/pi-tui";
16
+
5
17
  export const RESET = "\x1b[0m";
6
- export const BOX_BG = "\x1b[48;2;30;30;30m"; // #1e1e1e
7
- export const BOX_FG = "\x1b[38;2;30;30;30m"; // #1e1e1e, for half blocks drawn on the terminal background
8
- export const ACCENT_FG = "\x1b[38;2;92;156;245m"; // #5c9cf5
9
- export const BRIGHT_FG = "\x1b[38;2;238;238;238m"; // #eeeeee
10
- export const DIM_FG = "\x1b[38;2;128;128;128m";
18
+
19
+ // OKHSL lightness between the terminal background and the box background; a #0a0a0a terminal gets a #1f1f1f box
20
+ const BOX_LIGHTNESS_SHIFT = 0.08;
21
+ // Backgrounds above this OKHSL lightness count as light, so the box gets darker instead of lighter
22
+ const LIGHT_BACKGROUND_LIGHTNESS = 0.5;
23
+ // Pi's guesses for the terminal background when the terminal does not report it
24
+ const GUESSED_BACKGROUNDS = {
25
+ dark: rgbColor(0, 0, 0),
26
+ light: rgbColor(255, 255, 255),
27
+ } satisfies Record<ThemeAppearance, Color>;
28
+
29
+ /**
30
+ * ANSI codes that draw the box background.
31
+ */
32
+ export interface BoxColors {
33
+ /** Background code for the full box rows. */
34
+ background: string;
35
+ /** Foreground code for the half blocks of the bottom edge, drawn on the terminal background. */
36
+ halfBlock: string;
37
+ }
38
+
39
+ /**
40
+ * Function that returns the current box colors; called on every render.
41
+ */
42
+ export type ReadBoxColors = () => BoxColors;
43
+
44
+ /**
45
+ * Computes the box colors from the terminal background: the same hue and saturation, with the OKHSL
46
+ * lightness moved by `BOX_LIGHTNESS_SHIFT` toward the middle, so the box is lighter on dark terminals and
47
+ * darker on light ones. Without a reported background, Pi's guess for the theme `appearance` is used.
48
+ */
49
+ export function computeBoxColors(
50
+ terminalBackground: RgbColor | undefined,
51
+ appearance: ThemeAppearance,
52
+ mode: TerminalColorMode,
53
+ ): BoxColors {
54
+ const background = terminalBackground
55
+ ? rgbColor(terminalBackground.r, terminalBackground.g, terminalBackground.b)
56
+ : GUESSED_BACKGROUNDS[appearance];
57
+ const { h, s, l } = colorToOkhsl(background);
58
+ const shift = l > LIGHT_BACKGROUND_LIGHTNESS ? -BOX_LIGHTNESS_SHIFT : BOX_LIGHTNESS_SHIFT;
59
+ const boxColor = okhslColor(h, s, l + shift);
60
+
61
+ return { background: backgroundAnsi(boxColor, mode), halfBlock: foregroundAnsi(boxColor, mode) };
62
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Pi's chat, queued messages, extension widgets, and the dialogs shown in place of the editor moved right by the
3
+ * box margins, so they start in the same column as the prompt box, and kept clear of Pi's fullscreen scrollbar.
4
+ */
5
+
6
+ import type { Component, TuiMouseEvent, TuiMouseEventResult } from "@earendil-works/pi-tui";
7
+
8
+ import { LEFT_MARGIN, RIGHT_MARGIN } from "./prompt-box-editor.ts";
9
+ import { type ReadRightPadding, readScrollbarPadding } from "./scrollbar-padding.ts";
10
+
11
+ // Pi's TUI children, in this order: document, queued messages, status, widgets above, editor,
12
+ // widgets below, footer
13
+ const ROOT_CHILD_COUNT = 7;
14
+ const EDITOR_INDEX = 4;
15
+ const PADDED_ROOT_INDEXES = [1, 3, 5];
16
+ // Pi's document container holds the header, the loaded resources, and the chat, in this order
17
+ const DOCUMENT_CHILD_COUNT = 3;
18
+ const CHAT_INDEX = 2;
19
+
20
+ /**
21
+ * Component with child components, matched by shape like Pi's `Container`.
22
+ */
23
+ interface ParentComponent extends Component {
24
+ children: Component[];
25
+ }
26
+
27
+ /**
28
+ * Moves Pi's chat, queued messages, widgets above and below the editor, and the dialogs shown in place of the
29
+ * editor right by the box margins.
30
+ *
31
+ * Pi gives extensions no references to these containers, so they are found by the shape of the TUI tree
32
+ * under `root`, starting from the root child that holds `editor`. Nothing is changed when the shape differs.
33
+ * The editor container is padded only while it does not hold `editor`, which draws its own margins: Pi shows
34
+ * its selectors and extension dialogs in the same container, in place of the editor.
35
+ * In fullscreen mode with the `auto` scrollbar, they are also narrowed by the scrollbar width; see
36
+ * {@link readScrollbarPadding}.
37
+ *
38
+ * @returns A function that removes the padding, or `undefined` when nothing was changed, for example
39
+ * because the containers are already padded.
40
+ */
41
+ export function padPiContainers(root: Component, editor: Component): (() => void) | undefined {
42
+ const containers = findPiContainers(root, editor);
43
+ if (!containers || [...containers.alwaysPadded, containers.editorContainer].some(isPadded))
44
+ return undefined;
45
+
46
+ const readRightPadding = () => readScrollbarPadding(root);
47
+ const restoreFunctions = containers.alwaysPadded.map((container) => padComponent(container, readRightPadding));
48
+ const { editorContainer } = containers;
49
+ const isDialogShown = () => !editorContainer.children.includes(editor);
50
+ restoreFunctions.push(padComponent(editorContainer, readRightPadding, isDialogShown));
51
+ return () => {
52
+ for (const restore of restoreFunctions) restore();
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Makes `component` render narrower by the box margins and `readRightPadding()`, with every line indented by
58
+ * the left margin.
59
+ *
60
+ * Only this instance is changed, not its class, so Pi keeps its own reference and keeps updating it, in
61
+ * both regular and fullscreen mode. Mouse events are passed in the component coordinates; events on the
62
+ * margins are not handled. `readRightPadding` is called on every render and mouse event, so the padding
63
+ * follows Pi's mode and settings. `shouldPad` is called the same way; while it returns `false`, the component
64
+ * renders and gets mouse events unchanged.
65
+ *
66
+ * @returns A function that removes the padding.
67
+ */
68
+ export function padComponent(
69
+ component: Component,
70
+ readRightPadding: ReadRightPadding = () => 0,
71
+ shouldPad: () => boolean = () => true,
72
+ ): () => void {
73
+ const render = component.render.bind(component);
74
+ const handleMouse = component.handleMouse?.bind(component);
75
+ const readInnerWidth = (width: number) => width - LEFT_MARGIN - RIGHT_MARGIN - readRightPadding();
76
+
77
+ component.render = (width: number): string[] => {
78
+ if (!shouldPad()) return render(width);
79
+ const innerWidth = readInnerWidth(width);
80
+ if (innerWidth < 1) return render(width);
81
+ const leftMargin = " ".repeat(LEFT_MARGIN);
82
+ return render(innerWidth).map((line) => leftMargin + line);
83
+ };
84
+ if (handleMouse) {
85
+ component.handleMouse = (event: TuiMouseEvent): TuiMouseEventResult | undefined => {
86
+ if (!shouldPad()) return handleMouse(event);
87
+ const innerWidth = readInnerWidth(event.width);
88
+ if (innerWidth < 1) return handleMouse(event);
89
+ const x = event.x - LEFT_MARGIN;
90
+ if (x < 0 || x >= innerWidth) return undefined;
91
+ return handleMouse({ ...event, x, width: innerWidth });
92
+ };
93
+ }
94
+
95
+ return () => {
96
+ Reflect.deleteProperty(component, "render");
97
+ Reflect.deleteProperty(component, "handleMouse");
98
+ };
99
+ }
100
+
101
+ /**
102
+ * Pi's containers that get the padding.
103
+ */
104
+ interface PiContainers {
105
+ /** Chat, queued messages, and widgets above and below the editor. */
106
+ alwaysPadded: Component[];
107
+ /** Holds the editor, or a selector or extension dialog shown in its place. */
108
+ editorContainer: ParentComponent;
109
+ }
110
+
111
+ /**
112
+ * Finds Pi's chat, queued messages, widget, and editor containers, or returns `undefined` when the tree has
113
+ * another shape.
114
+ */
115
+ function findPiContainers(root: Component, editor: Component): PiContainers | undefined {
116
+ if (!isParent(root) || root.children.length !== ROOT_CHILD_COUNT) return undefined;
117
+ if (root.children.some((child) => !isParent(child))) return undefined;
118
+ const rootChildren = root.children as ParentComponent[];
119
+ const editorContainer = rootChildren[EDITOR_INDEX];
120
+ if (!editorContainer?.children.includes(editor)) return undefined;
121
+
122
+ const document = rootChildren[0];
123
+ if (!document || document.children.length !== DOCUMENT_CHILD_COUNT) return undefined;
124
+ const chat = document.children[CHAT_INDEX];
125
+ if (!chat || !isParent(chat)) return undefined;
126
+
127
+ const alwaysPadded = [chat, ...PADDED_ROOT_INDEXES.map((index) => rootChildren[index] as Component)];
128
+ return { alwaysPadded, editorContainer };
129
+ }
130
+
131
+ /**
132
+ * Checks if `component` was already padded: Pi's containers take `render` from their class.
133
+ */
134
+ function isPadded(component: Component): boolean {
135
+ return Object.hasOwn(component, "render");
136
+ }
137
+
138
+ /**
139
+ * Checks if `component` has a `children` array, as Pi's `Container` has.
140
+ */
141
+ function isParent(component: Component): component is ParentComponent {
142
+ return "children" in component && Array.isArray(component.children);
143
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Pi's built-in footer moved right by the box margins, so it starts in the same column as the prompt box.
3
+ */
4
+
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { type Component, stripTerminalSequences, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
+
8
+ import type { RoutedModel } from "../routed-model.ts";
9
+ import { LEFT_MARGIN, RIGHT_MARGIN } from "./prompt-box-editor.ts";
10
+ import type { ReadRightPadding } from "./scrollbar-padding.ts";
11
+
12
+ // Index of the footer line with the token stats on the left and the model on the right
13
+ const STATS_LINE_INDEX = 1;
14
+
15
+ // Pi puts at least this many spaces between the stats and the model
16
+ const MIN_MODEL_GAP = 2;
17
+
18
+ /**
19
+ * Model state the built-in footer shows; read on every render, as Pi's footer does.
20
+ */
21
+ export interface FooterModelState {
22
+ model: ExtensionContext["model"];
23
+ thinkingLevel: string;
24
+ /** Model a virtual `model` routed the latest response to; Pi's footer adds it after `→`. */
25
+ routedModel?: RoutedModel;
26
+ }
27
+
28
+ /**
29
+ * Finds Pi's built-in footer in the component tree under `root`.
30
+ *
31
+ * Pi gives extensions no reference to its footer, so the tree is searched. The footer is matched by its
32
+ * methods, not with `instanceof`: Pi itself uses duck typing, as `instanceof` can fail across module copies.
33
+ */
34
+ export function findBuiltInFooter(root: Component): Component | undefined {
35
+ if (isBuiltInFooter(root))
36
+ return root;
37
+
38
+ if (!("children" in root) || !Array.isArray(root.children))
39
+ return undefined;
40
+
41
+ for (const child of root.children as Component[]) {
42
+ const footer = findBuiltInFooter(child);
43
+ if (footer)
44
+ return footer;
45
+ }
46
+
47
+ return undefined;
48
+ }
49
+
50
+ /**
51
+ * Removes the model part that Pi's built-in footer right-aligns on its stats line: `(provider) model • level`,
52
+ * with ` → model • level` after it for a routed model.
53
+ *
54
+ * The prompt box status line already shows it. The line is changed only when it ends with exactly the text
55
+ * Pi builds from `state`; otherwise, for example when Pi truncated it, it is returned unchanged.
56
+ */
57
+ export function removeModelPart(line: string, state: FooterModelState): string {
58
+ const { model, thinkingLevel, routedModel } = state;
59
+ if (!model)
60
+ return line;
61
+
62
+ let modelPart = model.id;
63
+ if (model.reasoning)
64
+ modelPart += thinkingLevel === "off" ? " • thinking off" : ` • ${thinkingLevel}`;
65
+
66
+ // Pi may show no routed model where the status line still does, for example after compaction
67
+ const modelParts = [modelPart];
68
+ if (routedModel) {
69
+ const routedLevel = routedModel.thinkingLevel ? ` • ${routedModel.thinkingLevel}` : "";
70
+ modelParts.unshift(`${modelPart} → ${routedModel.model.id}${routedLevel}`);
71
+ }
72
+
73
+ const plainLine = stripTerminalSequences(line);
74
+ const gap = " ".repeat(MIN_MODEL_GAP);
75
+ const candidates = modelParts.flatMap((part) => [`(${model.provider}) ${part}`, part]);
76
+ for (const candidate of candidates) {
77
+ if (!plainLine.endsWith(gap + candidate))
78
+ continue;
79
+
80
+ const statsWidth = visibleWidth(plainLine.slice(0, -candidate.length).trimEnd());
81
+ return truncateToWidth(line, statsWidth, "");
82
+ }
83
+
84
+ return line;
85
+ }
86
+
87
+ /**
88
+ * Renders `footer` narrower by the box margins and `readRightPadding()`, indents every line by the left
89
+ * margin, and removes the model part from the stats line.
90
+ *
91
+ * Pi owns the wrapped footer and keeps updating it, so this component never disposes it.
92
+ */
93
+ export class PaddedFooter implements Component {
94
+ private readonly footer: Component;
95
+ private readonly readModelState: () => FooterModelState;
96
+ private readonly readRightPadding: ReadRightPadding;
97
+
98
+ constructor(
99
+ footer: Component,
100
+ readModelState: () => FooterModelState,
101
+ readRightPadding: ReadRightPadding = () => 0,
102
+ ) {
103
+ this.footer = footer;
104
+ this.readModelState = readModelState;
105
+ this.readRightPadding = readRightPadding;
106
+ }
107
+
108
+ render(width: number): string[] {
109
+ const innerWidth = width - LEFT_MARGIN - RIGHT_MARGIN - this.readRightPadding();
110
+ if (innerWidth < 1)
111
+ return this.footer.render(width);
112
+
113
+ const leftMargin = " ".repeat(LEFT_MARGIN);
114
+ const lines = this.footer.render(innerWidth);
115
+ const modelState = this.readModelState();
116
+
117
+ return lines.map((line, index) => {
118
+ const content = index === STATS_LINE_INDEX ? removeModelPart(line, modelState) : line;
119
+ return leftMargin + content;
120
+ });
121
+ }
122
+
123
+ invalidate(): void {
124
+ this.footer.invalidate();
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Tells Pi's `FooterComponent` apart from other components by the methods only it has.
130
+ */
131
+ function isBuiltInFooter(component: Component): boolean {
132
+ return "setSession" in component && "setAutoCompactEnabled" in component;
133
+ }
@@ -3,74 +3,390 @@
3
3
  */
4
4
 
5
5
  import { CustomEditor, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
6
- import { type EditorTheme, type TUI, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
6
+ import {
7
+ type EditorTheme,
8
+ stripTerminalSequences,
9
+ truncateToWidth,
10
+ type TUI,
11
+ type TuiMouseEvent,
12
+ type TuiMouseEventResult,
13
+ visibleWidth,
14
+ } from "@earendil-works/pi-tui";
7
15
 
8
- import { ACCENT_FG, BOX_BG, BOX_FG, RESET } from "./colors.ts";
16
+ import { type BoxColors, type ReadBoxColors, RESET } from "./colors.ts";
17
+ import type { ReadRightPadding } from "./scrollbar-padding.ts";
18
+ import type { BashMode } from "./status-line.ts";
9
19
 
10
- const OUTER_MARGIN = 1;
20
+ /**
21
+ * Terminal columns left empty on each side of the box; the chat and the footer use them too.
22
+ * Pi's editor `paddingX` setting adds to them only for the box.
23
+ */
24
+ export const LEFT_MARGIN = 1;
25
+ export const RIGHT_MARGIN = 0;
11
26
  const INNER_PADDING = 2;
12
27
  const BAR_WIDTH = 1;
28
+ // Pi's select list starts every item with a 2-column prefix (`→ ` or spaces); the list is moved left by it,
29
+ // so the item text starts in the same column as the input text
30
+ const SELECT_PREFIX_WIDTH = 2;
31
+ // Columns between the left margin and the input text
32
+ const TEXT_OFFSET = BAR_WIDTH + INNER_PADDING;
33
+ // Box rows between the text lines and the autocomplete lines (blank, status, half row), where the base
34
+ // editor has only its bottom border
35
+ const ROWS_AFTER_TEXT = 3;
36
+ const BASE_ROWS_AFTER_TEXT = 1;
37
+ // Base editor row of its top border; mouse events on box rows without text are passed on this row
38
+ const BASE_BORDER_ROW = 0;
39
+ // Spaces between the status line text and Pi's busy indicator
40
+ const BUSY_GAP = 2;
41
+ // Pi's default working message, also with the interrupt hint Pi adds after an extension reload
42
+ const DEFAULT_WORKING_MESSAGE = /^Working( \(.+ to interrupt\))?$/;
43
+ // Wide enough for the default working message; Pi pads the rendered indicator to this width
44
+ const MESSAGE_CHECK_WIDTH = 200;
45
+
46
+ // Scroll indicator arrows, as Pi shows them in its borders
47
+ const SCROLL_UP = "↑";
48
+ const SCROLL_DOWN = "↓";
49
+ // Columns between a scroll indicator and the right edge of the box; it extends into the inner padding
50
+ const SCROLL_INDICATOR_GAP = 1;
13
51
 
14
52
  // Returned by renderBottomBorder() so render() can find where the text lines end
15
53
  const BOTTOM_BORDER_MARKER = "\x00prompt-box-bottom-border\x00";
16
54
 
55
+ /**
56
+ * Builds the status line on every render from the editor state Pi does not expose elsewhere.
57
+ */
58
+ export type RenderStatus = (barColor: (text: string) => string, bashMode: BashMode) => string;
59
+
60
+ /**
61
+ * Returns the color of Pi's busy indicator when it differs from the accent bar: the routed thinking level
62
+ * color. Returns `undefined` to use the accent bar color.
63
+ */
64
+ export type ReadBusyColor = () => ((text: string) => string) | undefined;
65
+
66
+ // Pi does not export the StatusIndicator type
67
+ type StatusIndicator = NonNullable<Parameters<CustomEditor["setWorkingStatusIndicator"]>[0]>;
68
+
69
+ /**
70
+ * Box geometry of the last render, used to map mouse events to the base editor layout.
71
+ */
72
+ interface BoxLayout {
73
+ leftMargin: number;
74
+ textWidth: number;
75
+ textLineCount: number;
76
+ }
77
+
78
+ /**
79
+ * Terminal columns left empty on each side of the box.
80
+ */
81
+ interface BoxMargins {
82
+ left: number;
83
+ right: number;
84
+ }
85
+
86
+ /**
87
+ * Shared look of the box rows of one render.
88
+ */
89
+ interface BoxStyle {
90
+ margins: BoxMargins;
91
+ barColor: (text: string) => string;
92
+ colors: BoxColors;
93
+ }
94
+
17
95
  /**
18
96
  * Main editor drawn as a filled box with a left accent bar and a status line inside.
19
97
  *
20
98
  * The base editor renders the text lines; this class replaces its borders and
21
99
  * wraps every line in the box background. `renderStatus` is called on every
22
- * render, so the status line always shows the current state.
100
+ * render, so the status line always shows the current state. The accent bar
101
+ * uses the `borderColor` Pi sets from the thinking level and bash mode.
102
+ * Pi colors its working and compaction indicators with the `borderColor` it reads back, so reading it
103
+ * returns `readBusyColor()` when set, except in bash mode; the bar keeps the color Pi set.
104
+ * With `embedWorkingStatus`, Pi passes its busy indicators (working, retry,
105
+ * compaction, branch summary) to the editor, which shows them in the status line.
106
+ * `readBoxColors` is called on every render, so the box follows the terminal background.
107
+ * `readRightPadding` is called on every render and adds columns to the right margin.
108
+ * Pi's editor `paddingX` setting adds columns to both margins of the box and moves the autocomplete list
109
+ * with it; the text padding inside the box stays the same.
110
+ * Pi's scroll indicators (`N ↑`, `N ↓`) go right-aligned into the padding rows
111
+ * around the text, in the theme `borderColor` (Pi's `borderMuted`).
23
112
  */
24
113
  export class PromptBoxEditor extends CustomEditor {
25
- private readonly renderStatus: () => string;
114
+ private readonly renderStatus: RenderStatus;
115
+ // The base class keeps the theme private; its borderColor stays Pi's `borderMuted` while Pi changes the
116
+ // editor borderColor for the thinking level and bash mode
117
+ private readonly editorTheme: EditorTheme;
118
+ private readonly readBoxColors: ReadBoxColors;
119
+ private readonly readRightPadding: ReadRightPadding;
120
+ private readonly readBusyColor: ReadBusyColor;
121
+ // The borderColor Pi set; the `borderColor` property itself returns the busy indicator color
122
+ private barColor: (text: string) => string;
123
+ private statusIndicator: StatusIndicator | undefined;
124
+ // Pi's editor paddingX setting; the base editor keeps 0, so its text indent inside the box stays the same
125
+ private boxPaddingX = 0;
126
+ // Text lines hidden above and below the visible ones, set by the base render through the border methods
127
+ private hiddenAbove = 0;
128
+ private hiddenBelow = 0;
129
+ // Undefined when the last render fell back to the base editor layout
130
+ private boxLayout: BoxLayout | undefined;
131
+ // Set while the base editor renders its own layout below the box minimum width, so it keeps Pi's borders
132
+ private renderingFallback = false;
26
133
 
27
- constructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager, renderStatus: () => string) {
28
- super(tui, theme, keybindings, { paddingX: 0 });
134
+ constructor(
135
+ tui: TUI,
136
+ theme: EditorTheme,
137
+ keybindings: KeybindingsManager,
138
+ renderStatus: RenderStatus,
139
+ readBoxColors: ReadBoxColors,
140
+ readRightPadding: ReadRightPadding = () => 0,
141
+ readBusyColor: ReadBusyColor = () => undefined,
142
+ ) {
143
+ super(tui, theme, keybindings, { paddingX: 0, embedWorkingStatus: true });
29
144
  this.renderStatus = renderStatus;
145
+ this.editorTheme = theme;
146
+ this.readBoxColors = readBoxColors;
147
+ this.readRightPadding = readRightPadding;
148
+ this.readBusyColor = readBusyColor;
149
+
150
+ // The base class declares borderColor as a field, so the accessor is defined on the instance
151
+ this.barColor = this.borderColor;
152
+ Object.defineProperty(this, "borderColor", {
153
+ configurable: true,
154
+ enumerable: true,
155
+ get: () => this.readIndicatorColor(),
156
+ set: (color: (text: string) => string) => {
157
+ this.barColor = color;
158
+ },
159
+ });
160
+ }
161
+
162
+ // The base class keeps the indicator private, so keep a copy for the status line
163
+ override setWorkingStatusIndicator(indicator: StatusIndicator | undefined): void {
164
+ super.setWorkingStatusIndicator(indicator);
165
+ this.statusIndicator = indicator;
166
+ }
167
+
168
+ // Pi copies its editor paddingX setting here; it widens the box margins instead of the base text indent
169
+ override getPaddingX(): number {
170
+ return this.boxPaddingX;
30
171
  }
31
172
 
32
- protected override renderBottomBorder(): string {
173
+ override setPaddingX(padding: number): void {
174
+ const boxPaddingX = Number.isFinite(padding) ? Math.max(0, Math.floor(padding)) : 0;
175
+ if (this.boxPaddingX === boxPaddingX)
176
+ return;
177
+
178
+ this.boxPaddingX = boxPaddingX;
179
+ this.tui.requestRender();
180
+ }
181
+
182
+ // In the box layout the base top border is dropped; only its hidden line count is kept
183
+ protected override renderTopBorder(width: number, hiddenLineCount: number): string {
184
+ if (this.renderingFallback)
185
+ return super.renderTopBorder(width, hiddenLineCount);
186
+
187
+ this.hiddenAbove = hiddenLineCount;
188
+ return "";
189
+ }
190
+
191
+ protected override renderBottomBorder(width: number, hiddenLineCount: number): string {
192
+ if (this.renderingFallback)
193
+ return super.renderBottomBorder(width, hiddenLineCount);
194
+
195
+ this.hiddenBelow = hiddenLineCount;
33
196
  return BOTTOM_BORDER_MARKER;
34
197
  }
35
198
 
36
199
  override render(width: number): string[] {
37
- const textWidth = width - 2 * OUTER_MARGIN - BAR_WIDTH - 2 * INNER_PADDING;
38
- if (textWidth < 1) return super.render(width);
200
+ const margins = {
201
+ left: LEFT_MARGIN + this.boxPaddingX,
202
+ right: RIGHT_MARGIN + this.boxPaddingX + this.readRightPadding(),
203
+ };
204
+ const textWidth = width - margins.left - margins.right - BAR_WIDTH - 2 * INNER_PADDING;
205
+ if (textWidth < 1) {
206
+ this.boxLayout = undefined;
207
+ return this.renderFallback(width);
208
+ }
39
209
 
40
210
  // Base layout: top border, text lines, bottom border, autocomplete lines
41
211
  const baseLines = super.render(textWidth);
42
212
  const bottomBorderIndex = baseLines.indexOf(BOTTOM_BORDER_MARKER);
43
213
  const textLines = baseLines.slice(1, bottomBorderIndex);
44
214
  const autocompleteLines = baseLines.slice(bottomBorderIndex + 1);
215
+ this.boxLayout = { leftMargin: margins.left, textWidth, textLineCount: textLines.length };
216
+
217
+ const boxWidth = width - margins.left - margins.right - BAR_WIDTH;
218
+ const barColor = this.barColor;
219
+ const colors = this.readBoxColors();
220
+ const status = this.renderStatusLine(textWidth, barColor);
221
+
222
+ const scrollUp = this.renderScrollIndicator(SCROLL_UP, this.hiddenAbove, textWidth);
223
+ const scrollDown = this.renderScrollIndicator(SCROLL_DOWN, this.hiddenBelow, textWidth);
224
+
225
+ const autocompleteIndent = " ".repeat(margins.left + TEXT_OFFSET - SELECT_PREFIX_WIDTH);
226
+
227
+ const style = { margins, barColor, colors };
45
228
 
46
- const boxWidth = width - 2 * OUTER_MARGIN - BAR_WIDTH;
47
229
  return [
48
- renderHalfRow("╻", "▄", boxWidth),
49
- ...textLines.map((line) => renderBoxRow(line, textWidth)),
50
- renderBoxRow("", textWidth),
51
- renderBoxRow(truncateToWidth(this.renderStatus(), textWidth, ""), textWidth),
52
- renderHalfRow("╹", "▀", boxWidth),
53
- ...autocompleteLines.map((line) => " ".repeat(OUTER_MARGIN + BAR_WIDTH + INNER_PADDING) + line),
230
+ renderBoxRow(scrollUp, textWidth, style),
231
+ ...textLines.map((line) => renderBoxRow(line, textWidth, style)),
232
+ renderBoxRow(scrollDown, textWidth, style),
233
+ renderBoxRow(status, textWidth, style),
234
+ renderHalfRow("╹", "▀", boxWidth, style),
235
+ ...autocompleteLines.map((line) => padToWidth(autocompleteIndent + line, width)),
54
236
  ];
55
237
  }
238
+
239
+ /**
240
+ * Passes the mouse event to the base editor in its own layout, so clicks place the cursor under the pointer
241
+ * and select autocomplete items. Box rows without text (top padding, blank, status, half row) are passed on
242
+ * the base top border row, so the box takes focus there as on Pi's borders.
243
+ */
244
+ override handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
245
+ const layout = this.boxLayout;
246
+ if (!layout)
247
+ return super.handleMouse(event);
248
+
249
+ const autocompleteRow = 1 + layout.textLineCount + ROWS_AFTER_TEXT;
250
+ const rowShift = ROWS_AFTER_TEXT - BASE_ROWS_AFTER_TEXT;
251
+ const baseEvent = { ...event, width: layout.textWidth, height: event.height - rowShift };
252
+ const textIndent = layout.leftMargin + TEXT_OFFSET;
253
+ if (event.y >= autocompleteRow) {
254
+ const x = event.x - textIndent + SELECT_PREFIX_WIDTH;
255
+ return super.handleMouse({ ...baseEvent, x, y: event.y - rowShift });
256
+ }
257
+
258
+ const y = event.y <= layout.textLineCount ? event.y : BASE_BORDER_ROW;
259
+
260
+ return super.handleMouse({ ...baseEvent, x: event.x - textIndent, y });
261
+ }
262
+
263
+ /**
264
+ * Returns the color Pi's busy indicator gets when it reads `borderColor`. In bash mode, and for the base
265
+ * editor borders of the fallback layout, it is the accent bar color.
266
+ */
267
+ private readIndicatorColor(): (text: string) => string {
268
+ if (this.renderingFallback || detectBashMode(this.getText()) !== "off")
269
+ return this.barColor;
270
+
271
+ return this.readBusyColor() ?? this.barColor;
272
+ }
273
+
274
+ /**
275
+ * Renders the base editor layout with Pi's borders, for widths below the box minimum.
276
+ */
277
+ private renderFallback(width: number): string[] {
278
+ this.renderingFallback = true;
279
+ try {
280
+ return super.render(width);
281
+ } finally {
282
+ this.renderingFallback = false;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Renders Pi's scroll indicator (`N ↑`) right-aligned `SCROLL_INDICATOR_GAP` columns before the box edge, so
288
+ * it extends into the inner padding, or an empty row content when no lines are hidden. The label is cut from
289
+ * the right when the box is too narrow.
290
+ */
291
+ private renderScrollIndicator(direction: string, hiddenLineCount: number, textWidth: number): string {
292
+ if (hiddenLineCount < 1)
293
+ return "";
294
+
295
+ const indicatorWidth = textWidth + INNER_PADDING - SCROLL_INDICATOR_GAP;
296
+ const label = truncateToWidth(`${hiddenLineCount} ${direction}`, indicatorWidth, "");
297
+
298
+ return " ".repeat(indicatorWidth - visibleWidth(label)) + this.editorTheme.borderColor(label);
299
+ }
300
+
301
+ /**
302
+ * Renders the status line text followed by Pi's busy indicator, if any, within `textWidth`.
303
+ * The text is cut first so the spinner always fits; the indicator message is cut as Pi does in its border.
304
+ * Pi's default working message is dropped, so a normal turn shows only the spinner.
305
+ */
306
+ private renderStatusLine(textWidth: number, barColor: (text: string) => string): string {
307
+ const text = this.renderStatus(barColor, detectBashMode(this.getText()));
308
+ const indicator = this.statusIndicator;
309
+ if (!indicator)
310
+ return truncateToWidth(text, textWidth, "");
311
+
312
+ const spinnerWidth = visibleWidth(indicator.renderSpinnerInBorder(textWidth));
313
+ const fittedText = truncateToWidth(text, Math.max(0, textWidth - BUSY_GAP - spinnerWidth), "");
314
+ const busyWidth = textWidth - visibleWidth(fittedText) - BUSY_GAP;
315
+ if (busyWidth < 1)
316
+ return fittedText;
317
+
318
+ const busy = hasDefaultWorkingMessage(indicator)
319
+ ? indicator.renderSpinnerInBorder(busyWidth)
320
+ : indicator.renderInBorder(busyWidth);
321
+
322
+ return truncateToWidth(`${fittedText}${" ".repeat(BUSY_GAP)}${busy}`, textWidth, "");
323
+ }
56
324
  }
57
325
 
58
326
  /**
59
- * Renders the thin top or bottom edge of the box with half blocks.
327
+ * Checks if the indicator shows Pi's default working message, which the box hides to show only the spinner.
328
+ * Pi keeps the message private, so it is read from the rendered indicator.
329
+ * An indicator without a spinner keeps its message, so it never disappears.
60
330
  */
61
- function renderHalfRow(barChar: string, fillChar: string, boxWidth: number): string {
62
- const margin = " ".repeat(OUTER_MARGIN);
63
- return `${margin}${ACCENT_FG}${barChar}${BOX_FG}${fillChar.repeat(boxWidth)}${RESET}${margin}`;
331
+ function hasDefaultWorkingMessage(indicator: StatusIndicator): boolean {
332
+ if (indicator.kind !== "working")
333
+ return false;
334
+
335
+ const spinner = stripTerminalSequences(indicator.renderSpinnerInBorder(MESSAGE_CHECK_WIDTH));
336
+ if (!spinner)
337
+ return false;
338
+
339
+ const rendered = stripTerminalSequences(indicator.renderInBorder(MESSAGE_CHECK_WIDTH));
340
+ const message = rendered.startsWith(`${spinner} `) ? rendered.slice(spinner.length + 1) : rendered;
341
+
342
+ return DEFAULT_WORKING_MESSAGE.test(message);
343
+ }
344
+
345
+ /**
346
+ * Detects bash mode with Pi's rules: `!` runs a command, `!!` also keeps its output out of the context.
347
+ */
348
+ function detectBashMode(text: string): BashMode {
349
+ const input = text.trimStart();
350
+ if (input.startsWith("!!"))
351
+ return "no-context";
352
+
353
+ if (input.startsWith("!"))
354
+ return "context";
355
+
356
+ return "off";
357
+ }
358
+
359
+ /**
360
+ * Pads `line` with trailing spaces to `width` columns, so rows outside the box have the full width too.
361
+ */
362
+ function padToWidth(line: string, width: number): string {
363
+ return line + " ".repeat(Math.max(0, width - visibleWidth(line)));
364
+ }
365
+
366
+ /**
367
+ * Renders the thin bottom edge of the box with half blocks.
368
+ */
369
+ function renderHalfRow(barChar: string, fillChar: string, boxWidth: number, style: BoxStyle): string {
370
+ const { margins, barColor, colors } = style;
371
+ const leftMargin = " ".repeat(margins.left);
372
+ const rightMargin = " ".repeat(margins.right);
373
+
374
+ return `${leftMargin}${barColor(barChar)}${colors.halfBlock}${fillChar.repeat(boxWidth)}${RESET}${rightMargin}`;
64
375
  }
65
376
 
66
377
  /**
67
378
  * Renders one full-height box row: accent bar, padding and content on the box background.
379
+ * Content wider than `textWidth` extends into the right inner padding; only scroll indicators do that.
68
380
  */
69
- function renderBoxRow(content: string, textWidth: number): string {
70
- const margin = " ".repeat(OUTER_MARGIN);
381
+ function renderBoxRow(content: string, textWidth: number, style: BoxStyle): string {
382
+ const { margins, barColor, colors } = style;
383
+ const leftMargin = " ".repeat(margins.left);
384
+ const rightMargin = " ".repeat(margins.right);
71
385
  const padding = " ".repeat(INNER_PADDING);
72
- const fill = " ".repeat(Math.max(0, textWidth - visibleWidth(content)));
386
+ const fill = " ".repeat(Math.max(0, textWidth + INNER_PADDING - visibleWidth(content)));
73
387
  // Styled content may reset all attributes, which would also drop the box background
74
- const boxedContent = content.replaceAll(RESET, RESET + BOX_BG);
75
- return `${margin}${ACCENT_FG}┃${RESET}${BOX_BG}${padding}${boxedContent}${fill}${padding}${RESET}${margin}`;
388
+ const boxedContent = content.replaceAll(RESET, RESET + colors.background);
389
+ const box = `${colors.background}${padding}${boxedContent}${fill}${RESET}`;
390
+
391
+ return `${leftMargin}${barColor("┃")}${RESET}${box}${rightMargin}`;
76
392
  }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Right padding that keeps the chat, the prompt box, and the footer clear of Pi's fullscreen scrollbar.
3
+ */
4
+
5
+ import type { Component } from "@earendil-works/pi-tui";
6
+
7
+ // Pi's fullscreen scrollbar in `auto` mode is drawn over the last column of the chat, so that column is left empty
8
+ const SCROLLBAR_WIDTH = 1;
9
+
10
+ /**
11
+ * Function that returns the columns to leave empty on the right of a component, besides the box margin.
12
+ */
13
+ export type ReadRightPadding = () => number;
14
+
15
+ /**
16
+ * Returns the columns to leave for Pi's fullscreen scrollbar: its width in the `auto` mode, else 0.
17
+ *
18
+ * In `auto` mode Pi draws the scrollbar over the last column of the chat when it scrolls. In `always` mode
19
+ * Pi already narrows the chat for it; `hidden` mode and regular TUI mode have no scrollbar. Pi gives
20
+ * extensions no reference to its scroll view, so it is found by shape among the children of the fullscreen
21
+ * layout root of `tui`: the child that holds the document, the first TUI child, and has a `scrollbar` mode.
22
+ * Pi replaces the TUI on a mode switch, and `tui` follows it, so call this on every render.
23
+ */
24
+ export function readScrollbarPadding(tui: Component): number {
25
+ const document = readChildren(tui)?.[0];
26
+ if (!document)
27
+ return 0;
28
+
29
+ // Pi keeps the fullscreen layout root in a field that its types mark private
30
+ const layoutRoot: unknown = Reflect.get(tui, "layoutRoot");
31
+ const scrollView = readChildren(layoutRoot)?.find((child) => readChildren(child)?.[0] === document);
32
+ if (!isObject(scrollView) || !("scrollbar" in scrollView) || scrollView.scrollbar !== "auto")
33
+ return 0;
34
+
35
+ return SCROLLBAR_WIDTH;
36
+ }
37
+
38
+ /**
39
+ * Returns the `children` array of `value`, as Pi's `Container` has, or `undefined` when it has none.
40
+ */
41
+ function readChildren(value: unknown): unknown[] | undefined {
42
+ if (!isObject(value) || !("children" in value) || !Array.isArray(value.children))
43
+ return undefined;
44
+
45
+ return value.children;
46
+ }
47
+
48
+ /**
49
+ * Checks if `value` is a non-null object.
50
+ */
51
+ function isObject(value: unknown): value is object {
52
+ return typeof value === "object" && value !== null;
53
+ }
@@ -2,28 +2,92 @@
2
2
  * Status line shown inside the prompt box.
3
3
  */
4
4
 
5
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
6
6
 
7
- import { ACCENT_FG, BRIGHT_FG, DIM_FG } from "./colors.ts";
7
+ import type { RoutedModel } from "../routed-model.ts";
8
8
 
9
9
  /**
10
- * Builds the status line: model, provider, thinking level and an optional busy indicator.
10
+ * Bash mode of the input:
11
+ * off a normal prompt
12
+ * context `!` runs a shell command; its output goes to the model context
13
+ * no-context `!!` runs a shell command; its output stays out of the context
11
14
  */
12
- export function formatStatus(
13
- model: ExtensionContext["model"],
14
- thinkingLevel: string,
15
- spinnerFrame: string | undefined,
16
- ): string {
17
- const modelText = model ? `${BRIGHT_FG}${model.name} ${DIM_FG}${model.provider}` : `${DIM_FG}no model`;
18
- const separator = `${DIM_FG} · `;
19
- const mode = `${ACCENT_FG}${capitalize(thinkingLevel)}`;
20
- const busy = spinnerFrame ? `${DIM_FG} ${spinnerFrame} Working` : "";
21
- return `${modelText}${separator}${mode}${busy}`;
15
+ export type BashMode = "off" | "context" | "no-context";
16
+
17
+ /**
18
+ * Current state shown in the status line, with the colors to draw it.
19
+ */
20
+ export interface StatusLineOptions {
21
+ theme: Theme;
22
+ /** Colors the thinking level or `Bash`; the editor `borderColor`, so it matches the accent bar. */
23
+ levelColor: (text: string) => string;
24
+ bashMode: BashMode;
25
+ model: ExtensionContext["model"];
26
+ /** Returns the display name of a provider id, like Pi's model registry: `opencode` → `OpenCode Zen`. */
27
+ getProviderName: (provider: string) => string;
28
+ thinkingLevel: string;
29
+ /** Model a virtual `model` routed the latest response to; shown after `→`. */
30
+ routedModel?: RoutedModel;
22
31
  }
23
32
 
24
33
  /**
25
- * Upper-cases the first letter, e.g. "medium" -> "Medium".
34
+ * Returns the theme color of the routed thinking level, or `undefined` when the status line shows no routed
35
+ * level: without a routed model, without its level, or for a routed model without reasoning support.
26
36
  */
27
- function capitalize(text: string): string {
28
- return text.charAt(0).toUpperCase() + text.slice(1);
37
+ export function readRoutedLevelColor(
38
+ theme: Theme,
39
+ routedModel: RoutedModel | undefined,
40
+ ): ((text: string) => string) | undefined {
41
+ if (!routedModel?.model.reasoning || !routedModel.thinkingLevel)
42
+ return undefined;
43
+
44
+ return theme.getThinkingBorderColor(routedModel.thinkingLevel);
45
+ }
46
+
47
+ /**
48
+ * Builds the status line text: model, provider and thinking level, then the routed model in the same format.
49
+ * Like Pi's footer, the level shows only for models with reasoning support, and level `off` shows as `thinking off`.
50
+ * In bash mode, `Bash` replaces them. Pi's busy indicator is added by the editor.
51
+ */
52
+ export function formatStatus(options: StatusLineOptions): string {
53
+ const { theme, levelColor, bashMode, model, thinkingLevel, routedModel } = options;
54
+ if (bashMode === "context")
55
+ return levelColor("Bash");
56
+
57
+ if (bashMode === "no-context")
58
+ return `${levelColor("Bash")}${theme.fg("dim", " (no context)")}`;
59
+
60
+ if (!model)
61
+ return theme.fg("dim", "no model");
62
+
63
+ const selectedText = formatModel(options, model, thinkingLevel, levelColor);
64
+ if (!routedModel)
65
+ return selectedText;
66
+
67
+ // The routed level has the color of its own level, which can differ from the accent bar
68
+ const routedLevelColor = readRoutedLevelColor(theme, routedModel) ?? levelColor;
69
+ const routedText = formatModel(options, routedModel.model, routedModel.thinkingLevel, routedLevelColor);
70
+
71
+ return `${selectedText}${theme.fg("dim", " → ")}${routedText}`;
72
+ }
73
+
74
+ /**
75
+ * Formats one model as `name provider · level`; the level is left out for models without reasoning support
76
+ * and when it is unknown.
77
+ */
78
+ function formatModel(
79
+ options: StatusLineOptions,
80
+ model: NonNullable<ExtensionContext["model"]>,
81
+ thinkingLevel: string | undefined,
82
+ levelColor: (text: string) => string,
83
+ ): string {
84
+ const { theme, getProviderName } = options;
85
+ const modelText = `${theme.fg("text", model.name)} ${theme.fg("dim", getProviderName(model.provider))}`;
86
+ if (!model.reasoning || !thinkingLevel)
87
+ return modelText;
88
+
89
+ const separator = theme.fg("dim", " · ");
90
+ const level = levelColor(thinkingLevel === "off" ? "thinking off" : thinkingLevel);
91
+
92
+ return `${modelText}${separator}${level}`;
29
93
  }