pi-tui-prompt-box 0.1.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 18.11.2026
4
+
5
+ ### New
6
+ * `[ui]` Draw user messages in the chat as prompt boxes with the box background.
7
+ * `[ui]` Color the accent bar of each user message with its prompt's thinking level.
8
+ * `[ui]` Hide Pi's `Thinking level` chat status -> the boxes show the level by color.
9
+ * `[config]` Add the `userMessageBoxes` option to keep Pi's own user messages.
10
+
11
+
3
12
  ## [0.1.1] - 12.11.2026
4
13
 
5
14
  ### New
package/README.md CHANGED
@@ -1,7 +1,7 @@
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">
4
+ <img width="456" src="https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/e0ae300ca7aea2ed2d873e6c7d544951dc6b0564/doc/images/pi-tui-prompt-box.png" alt="pi-tui-prompt-box preview">
5
5
  <br>
6
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
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>
@@ -10,17 +10,27 @@
10
10
 
11
11
  <br>
12
12
 
13
- An alternative style for the prompt input in [Pi](https://pi.dev).
13
+ An alternative style for the prompt input in [Pi](https://pi.dev): a filled
14
+ prompt box with the model, thinking level, and busy indicator inside.
14
15
 
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.
16
+ Your messages in the chat are drawn as the same boxes, which is
17
+ [optional](#configuration). Other TUI components are only moved to line up
18
+ with the prompt box. Their content and styling stay unchanged.
17
19
 
18
20
  It is a building block, not a full theme: combine it with your favorite footer,
19
21
  completion menu, or any other styling extension.
20
22
 
21
- ## Demo
23
+ ## Demo: `Mode Colors`
22
24
 
23
- ![Demo: thinking levels and bash mode](https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/530f3c8670c3c91c9f970a791509f21cdcedd79e/doc/images/demo.gif)
25
+ The accent bar and spinner colors show the selected thinking level:
26
+
27
+ ![Demo: Mode Colors](https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/530f3c8670c3c91c9f970a791509f21cdcedd79e/doc/images/demo.gif)
28
+
29
+ ## Demo: `Message Colors`
30
+
31
+ Each message in the chat keeps the color of the thinking level it was sent with:
32
+
33
+ ![Demo: Message Colors](https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/442bc8dc44b4e230bd6f958024ac963476a8cc39/doc/images/user-messages.gif)
24
34
 
25
35
  ## Install
26
36
 
@@ -28,10 +38,10 @@ completion menu, or any other styling extension.
28
38
  pi install npm:pi-tui-prompt-box
29
39
  ```
30
40
 
31
- ## Side Effects
41
+ ## What It Changes
32
42
 
33
43
  - Moves the chat, widgets, dialogs, and footer right so they line up with the
34
- prompt box. Their content and styling stay unchanged.
44
+ prompt box.
35
45
 
36
46
  - Removes the model, provider, and thinking level from the default footer, as the
37
47
  prompt box already shows them. Custom footers stay unchanged.
@@ -39,8 +49,21 @@ pi install npm:pi-tui-prompt-box
39
49
  - Moves Pi's busy indicator (spinner and message) into the prompt box. Custom
40
50
  spinner widgets stay unchanged.
41
51
 
42
- - Replaces Pi's editor, so it does not work together with other extensions that
43
- replace the editor.
52
+ - Draws your messages in the chat as prompt boxes, colored by the thinking level
53
+ they were sent with, and hides Pi's `Thinking level` chat status. This is
54
+ [optional](#configuration).
55
+
56
+ ## Configuration
57
+
58
+ User message boxes are on by default. To keep Pi's own look for your messages
59
+ in the chat, create
60
+ `~/.pi/agent/extensions/pi-tui-prompt-box.json` and run `/reload`:
61
+
62
+ ```json
63
+ {
64
+ "userMessageBoxes": false
65
+ }
66
+ ```
44
67
 
45
68
  ## Context Footprint
46
69
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tui-prompt-box",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A prompt box style for Pi that combines with other styling extensions",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "extensions": [
33
33
  "./src/index.ts"
34
34
  ],
35
- "image": "https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/d40318c625f33ef90f99108bb0536a8872174cab/doc/images/pi-tui-prompt-box.png"
35
+ "image": "https://media.githubusercontent.com/media/dimk90/pi-tui-prompt-box/e0ae300ca7aea2ed2d873e6c7d544951dc6b0564/doc/images/pi-tui-prompt-box.png"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@earendil-works/pi-coding-agent": "*",
package/src/config.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Override-only user configuration.
3
+ *
4
+ * Defaults live in this module; the global `<agent dir>/extensions/pi-tui-prompt-box.json` carries overrides
5
+ * only and is never created by the extension. An absent file or omitted key is silent; an unreadable,
6
+ * unparseable, or invalid file warns and falls back to the defaults.
7
+ */
8
+
9
+ import { readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
13
+
14
+ /** Global override file; project-local configuration is not supported. */
15
+ export const CONFIG_FILE_NAME = "pi-tui-prompt-box.json";
16
+
17
+ /**
18
+ * Options of the extension.
19
+ */
20
+ export interface PromptBoxConfig {
21
+ /** Draw user messages in the chat as prompt boxes and hide Pi's thinking level status; see doc/ui.md. */
22
+ userMessageBoxes: boolean;
23
+ }
24
+
25
+ /**
26
+ * A loaded configuration with the problems found in its file.
27
+ */
28
+ export interface ConfigLoadResult {
29
+ /** Defaults with every valid override applied. */
30
+ config: PromptBoxConfig;
31
+ /** One message per problem, ready to show to the user. */
32
+ warnings: string[];
33
+ }
34
+
35
+ /** Configuration used when no override file exists. */
36
+ export const DEFAULT_CONFIG: Readonly<PromptBoxConfig> = { userMessageBoxes: true };
37
+
38
+ /**
39
+ * Returns the absolute path of the global override file.
40
+ */
41
+ export function getConfigFilePath(): string {
42
+ return join(getAgentDir(), "extensions", CONFIG_FILE_NAME);
43
+ }
44
+
45
+ /**
46
+ * Reads and validates the override file at `filePath`. A missing file yields the defaults without warnings;
47
+ * an invalid or unknown key warns and keeps the other keys.
48
+ */
49
+ export function loadConfigFile(filePath: string): ConfigLoadResult {
50
+ let text: string;
51
+ try {
52
+ text = readFileSync(filePath, "utf8");
53
+ } catch (error) {
54
+ // An absent file is the expected state for users who never configured anything
55
+ if (isMissingFileError(error))
56
+ return { config: { ...DEFAULT_CONFIG }, warnings: [] };
57
+
58
+ return useDefaults(`Cannot read ${filePath}: ${describeError(error)}.`);
59
+ }
60
+
61
+ let overrides: unknown;
62
+ try {
63
+ overrides = JSON.parse(text);
64
+ } catch (error) {
65
+ return useDefaults(`Cannot parse ${filePath}: ${describeError(error)}.`);
66
+ }
67
+
68
+ if (typeof overrides !== "object" || overrides === null || Array.isArray(overrides))
69
+ return useDefaults(`${filePath} must contain a JSON object.`);
70
+
71
+ return applyOverrides(overrides, filePath);
72
+ }
73
+
74
+ /**
75
+ * Applies the valid entries of `overrides` to the defaults, with a warning for every other entry.
76
+ */
77
+ function applyOverrides(overrides: object, filePath: string): ConfigLoadResult {
78
+ const config = { ...DEFAULT_CONFIG };
79
+ const warnings: string[] = [];
80
+ for (const [key, value] of Object.entries(overrides)) {
81
+ if (key !== "userMessageBoxes")
82
+ warnings.push(`Unknown key "${key}" in ${filePath}.`);
83
+ else if (typeof value !== "boolean")
84
+ warnings.push(`"${key}" in ${filePath} must be true or false.`);
85
+ else
86
+ config.userMessageBoxes = value;
87
+ }
88
+
89
+ return { config, warnings };
90
+ }
91
+
92
+ /**
93
+ * Returns the defaults with `warning` as the only problem.
94
+ */
95
+ function useDefaults(warning: string): ConfigLoadResult {
96
+ return { config: { ...DEFAULT_CONFIG }, warnings: [warning] };
97
+ }
98
+
99
+ /**
100
+ * Tells whether `error` is the file system error for a path that does not exist.
101
+ */
102
+ function isMissingFileError(error: unknown): boolean {
103
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
104
+ }
105
+
106
+ /**
107
+ * Returns a short reason for an unknown thrown value.
108
+ */
109
+ function describeError(error: unknown): string {
110
+ return error instanceof Error ? error.message : String(error);
111
+ }
package/src/index.ts CHANGED
@@ -4,23 +4,29 @@
4
4
  * Usage: pi -e .
5
5
  */
6
6
 
7
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
8
8
  import type { RgbColor, TUI } from "@earendil-works/pi-tui";
9
9
 
10
+ import { getConfigFilePath, loadConfigFile } from "./config.ts";
11
+ import { findPromptThinkingLevel } from "./prompt-thinking-level.ts";
10
12
  import { findRoutedModel } from "./routed-model.ts";
11
13
  import { watchTerminalBackground } from "./terminal-background.ts";
14
+ import { type ChatMessageStyle, styleChatMessages } from "./ui/chat-messages.ts";
12
15
  import { computeBoxColors, type ReadBoxColors } from "./ui/colors.ts";
13
- import { padPiContainers } from "./ui/padded-containers.ts";
16
+ import { findPiContainers, padPiContainers } from "./ui/padded-containers.ts";
14
17
  import { findBuiltInFooter, PaddedFooter } from "./ui/padded-footer.ts";
15
18
  import { PromptBoxEditor, type RenderStatus } from "./ui/prompt-box-editor.ts";
16
19
  import { readScrollbarPadding } from "./ui/scrollbar-padding.ts";
17
20
  import { formatStatus, readRoutedLevelColor } from "./ui/status-line.ts";
18
21
 
22
+ type ThinkingLevel = Parameters<Theme["getThinkingBorderColor"]>[0];
23
+
19
24
  /**
20
25
  * Registers the prompt box editor for every session.
21
26
  */
22
27
  export default function promptBox(pi: ExtensionAPI): void {
23
28
  let restoreContainers: (() => void) | undefined;
29
+ let restoreChatMessages: (() => void) | undefined;
24
30
  let stopWatchingBackground: (() => void) | undefined;
25
31
 
26
32
  pi.on("session_start", (_event, ctx) => {
@@ -58,6 +64,11 @@ export default function promptBox(pi: ExtensionAPI): void {
58
64
  if (!editorTui || !editor)
59
65
  return;
60
66
 
67
+ // Read on every session start, so a reload applies a changed file
68
+ const { config, warnings } = loadConfigFile(getConfigFilePath());
69
+ for (const warning of warnings)
70
+ ctx.ui.notify(warning, "warning");
71
+
61
72
  stopWatchingBackground = watchTerminalBackground(editorTui, (background) => {
62
73
  terminalBackground = background;
63
74
  editorTui?.requestRender();
@@ -65,6 +76,18 @@ export default function promptBox(pi: ExtensionAPI): void {
65
76
 
66
77
  restoreContainers = padPiContainers(editorTui, editor);
67
78
 
79
+ // A message sent in this session has no entry id yet and gets the current level
80
+ const resolveBarColor: ChatMessageStyle["resolveBarColor"] = (messageId) => {
81
+ const promptLevel = messageId ? findPromptThinkingLevel(ctx.sessionManager, messageId) : undefined;
82
+ // The session keeps levels as plain strings; Pi's theme draws an unknown level as `off`
83
+ const level = (promptLevel ?? pi.getThinkingLevel()) as ThinkingLevel;
84
+
85
+ return (text) => ctx.ui.theme.getThinkingBorderColor(level)(text);
86
+ };
87
+ const chat = config.userMessageBoxes ? findPiContainers(editorTui, editor)?.chat : undefined;
88
+ if (chat)
89
+ restoreChatMessages = styleChatMessages(chat, { readBoxColors, resolveBarColor });
90
+
68
91
  // Search before setFooter(): it removes the current footer from the tree before calling the factory
69
92
  const builtInFooter = findBuiltInFooter(editorTui);
70
93
  if (!builtInFooter)
@@ -82,11 +105,14 @@ export default function promptBox(pi: ExtensionAPI): void {
82
105
  stopWatchingBackground?.();
83
106
  stopWatchingBackground = undefined;
84
107
 
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")
108
+ // Pi keeps its containers across extension reloads and session changes, so remove the padding and the
109
+ // message styling for the next extension instance; on quit they stay, as Pi may still print the transcript
110
+ if (event.reason !== "quit") {
88
111
  restoreContainers?.();
112
+ restoreChatMessages?.();
113
+ }
89
114
 
90
115
  restoreContainers = undefined;
116
+ restoreChatMessages = undefined;
91
117
  });
92
118
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Thinking level of a past prompt, read from the session.
3
+ */
4
+
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+
7
+ /**
8
+ * Finds the thinking level that was set when the session entry `entryId` was added: the level of the nearest
9
+ * thinking level change above it on its branch.
10
+ *
11
+ * Pi records the level at session start and on every change, so only an unknown entry returns `undefined`.
12
+ */
13
+ export function findPromptThinkingLevel(
14
+ sessionManager: Pick<ExtensionContext["sessionManager"], "getEntry">,
15
+ entryId: string,
16
+ ): string | undefined {
17
+ let entry = sessionManager.getEntry(entryId);
18
+ while (entry) {
19
+ if (entry.type === "thinking_level_change")
20
+ return entry.thinkingLevel;
21
+
22
+ entry = entry.parentId ? sessionManager.getEntry(entry.parentId) : undefined;
23
+ }
24
+
25
+ return undefined;
26
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Pi's chat messages restyled: user messages drawn as prompt boxes, and Pi's thinking level status hidden;
3
+ * see doc/ui.md.
4
+ */
5
+
6
+ import { UserMessageComponent } from "@earendil-works/pi-coding-agent";
7
+ import { type Component, Markdown, Spacer, stripTerminalSequences } from "@earendil-works/pi-tui";
8
+
9
+ import type { ReadBoxColors } from "./colors.ts";
10
+ import type { ParentComponent } from "./padded-containers.ts";
11
+ import { BAR_WIDTH, INNER_PADDING, renderBoxRow } from "./prompt-box-editor.ts";
12
+
13
+ // Pi's chat status after a thinking level change; the user message boxes show the level by their color
14
+ const THINKING_LEVEL_STATUS = /^Thinking level: \S+$/;
15
+ // The chat is already moved by the box margins
16
+ const NO_MARGINS = { left: 0, right: 0 };
17
+ // Fields of Pi's Markdown that draw the padding and the background of a user message
18
+ const MARKDOWN_BLOCK_FIELDS = ["paddingX", "paddingY", "defaultTextStyle"] as const;
19
+
20
+ /**
21
+ * Look of the restyled chat messages.
22
+ */
23
+ export interface ChatMessageStyle {
24
+ /** Called on every render, so the user message boxes follow the terminal background like the prompt box. */
25
+ readBoxColors: ReadBoxColors;
26
+ /**
27
+ * Returns the accent bar color of a user message. Called once per message, when it is styled, with the
28
+ * session entry id Pi gave it; a message sent in this session has none. The returned color is called on
29
+ * every render.
30
+ */
31
+ resolveBarColor: (messageId: string | undefined) => (text: string) => string;
32
+ }
33
+
34
+ /**
35
+ * Restyles the messages of Pi's `chat` container: the ones it holds now and every one Pi adds later.
36
+ *
37
+ * User messages are drawn as prompt boxes, see {@link boxUserMessage}. Pi's thinking level status is hidden,
38
+ * see {@link hideThinkingLevelStatus}. Only the `chat` instance and the message instances are changed, not
39
+ * their classes.
40
+ *
41
+ * @returns A function that restores `chat` and the messages it still holds, or `undefined` when `chat` is
42
+ * already restyled.
43
+ */
44
+ export function styleChatMessages(chat: ParentComponent, style: ChatMessageStyle): (() => void) | undefined {
45
+ if (Object.hasOwn(chat, "addChild"))
46
+ return undefined;
47
+
48
+ const restoreFunctions = new WeakMap<Component, () => void>();
49
+ const styleMessage = (message: Component, previous: Component | undefined) => {
50
+ const restore = message instanceof UserMessageComponent
51
+ ? boxUserMessage(message, style)
52
+ : hideThinkingLevelStatus(message, previous);
53
+ if (restore)
54
+ restoreFunctions.set(message, restore);
55
+ };
56
+ chat.children.forEach((message, index) => styleMessage(message, chat.children[index - 1]));
57
+
58
+ const addChild = chat.addChild.bind(chat);
59
+ chat.addChild = (message: Component): void => {
60
+ styleMessage(message, chat.children.at(-1));
61
+ addChild(message);
62
+ };
63
+
64
+ return () => {
65
+ Reflect.deleteProperty(chat, "addChild");
66
+ for (const message of chat.children)
67
+ restoreFunctions.get(message)?.();
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Makes the user `message` render as a prompt box: accent bar, and the text lines between a top and a bottom
73
+ * padding row on the box background; see doc/ui.md.
74
+ *
75
+ * Pi's Markdown inside the message keeps rendering the text, without its own padding and background. Pi
76
+ * replaces it when the `outputPad` setting changes, so it is looked up on every render. When it is not found,
77
+ * or below the box minimum width, the message renders as Pi draws it.
78
+ *
79
+ * @returns A function that restores Pi's rendering.
80
+ */
81
+ function boxUserMessage(message: UserMessageComponent, style: ChatMessageStyle): () => void {
82
+ const render = message.render.bind(message);
83
+ const barColor = style.resolveBarColor(readMessageId(message));
84
+ let unpadded: { markdown: Markdown; restore: () => void } | undefined;
85
+ const restoreMarkdown = () => {
86
+ unpadded?.restore();
87
+ unpadded = undefined;
88
+ };
89
+
90
+ message.render = (width: number): string[] => {
91
+ const textWidth = width - BAR_WIDTH - 2 * INNER_PADDING;
92
+ const markdown = textWidth < 1 ? undefined : findMarkdown(message);
93
+ if (!markdown) {
94
+ restoreMarkdown();
95
+ return render(width);
96
+ }
97
+
98
+ if (unpadded?.markdown !== markdown)
99
+ unpadded = { markdown, restore: unpadMarkdown(markdown) };
100
+
101
+ const textLines = render(textWidth);
102
+ if (textLines.length === 0)
103
+ return textLines;
104
+
105
+ const boxStyle = { margins: NO_MARGINS, barColor, colors: style.readBoxColors() };
106
+
107
+ return [
108
+ renderBoxRow("", textWidth, boxStyle),
109
+ ...textLines.map((line) => renderBoxRow(line, textWidth, boxStyle)),
110
+ renderBoxRow("", textWidth, boxStyle),
111
+ ];
112
+ };
113
+
114
+ return () => {
115
+ Reflect.deleteProperty(message, "render");
116
+ restoreMarkdown();
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Returns the session entry id of the user `message`, which Pi's types mark private, or `undefined` for a
122
+ * message sent in this session.
123
+ */
124
+ function readMessageId(message: UserMessageComponent): string | undefined {
125
+ const messageId: unknown = Reflect.get(message, "messageId");
126
+
127
+ return typeof messageId === "string" ? messageId : undefined;
128
+ }
129
+
130
+ /**
131
+ * Finds Pi's Markdown that renders the text of the user `message`, or returns `undefined` when the message
132
+ * has another shape.
133
+ */
134
+ function findMarkdown(message: UserMessageComponent): Markdown | undefined {
135
+ const markdown = message.children[0];
136
+ if (!(markdown instanceof Markdown) || typeof Reflect.get(markdown, "paddingX") !== "number")
137
+ return undefined;
138
+
139
+ return markdown;
140
+ }
141
+
142
+ /**
143
+ * Removes the padding and the background of `markdown`, so it renders only the text lines. Pi's types mark
144
+ * these fields private.
145
+ *
146
+ * @returns A function that sets them back.
147
+ */
148
+ function unpadMarkdown(markdown: Markdown): () => void {
149
+ const fields = MARKDOWN_BLOCK_FIELDS.map((name) => [name, Reflect.get(markdown, name) as unknown] as const);
150
+ const textStyle = Reflect.get(markdown, "defaultTextStyle") as unknown;
151
+
152
+ Reflect.set(markdown, "paddingX", 0);
153
+ Reflect.set(markdown, "paddingY", 0);
154
+ Reflect.set(markdown, "defaultTextStyle", { ...(isObject(textStyle) ? textStyle : {}), bgColor: undefined });
155
+ markdown.invalidate();
156
+
157
+ return () => {
158
+ for (const [name, value] of fields)
159
+ Reflect.set(markdown, name, value);
160
+
161
+ markdown.invalidate();
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Hides Pi's `Thinking level: <level>` chat status: the `status` text and the `spacer` Pi adds before it.
167
+ *
168
+ * Pi shows later statuses in the same text component, so the text is checked on every render and only the
169
+ * thinking level status is hidden. Pi does not export its status text class, so it is matched by its `build`
170
+ * method; other components are left unchanged.
171
+ *
172
+ * @returns A function that shows the status again, or `undefined` when `status` is not a status text.
173
+ */
174
+ function hideThinkingLevelStatus(status: Component, spacer: Component | undefined): (() => void) | undefined {
175
+ if (!isStatusText(status))
176
+ return undefined;
177
+
178
+ const isHidden = () => THINKING_LEVEL_STATUS.test(stripTerminalSequences(status.build()).trim());
179
+ const showStatus = hideWhile(status, isHidden);
180
+ const showSpacer = spacer instanceof Spacer ? hideWhile(spacer, isHidden) : undefined;
181
+
182
+ return () => {
183
+ showStatus();
184
+ showSpacer?.();
185
+ };
186
+ }
187
+
188
+ /**
189
+ * Pi's status text, which builds its themed text on demand.
190
+ */
191
+ interface StatusText extends Component {
192
+ build: () => string;
193
+ }
194
+
195
+ /**
196
+ * Checks if `component` has a `build` method, as Pi's status text has.
197
+ */
198
+ function isStatusText(component: Component): component is StatusText {
199
+ return "build" in component && typeof component.build === "function";
200
+ }
201
+
202
+ /**
203
+ * Makes `component` render no lines while `isHidden()` returns `true`.
204
+ *
205
+ * @returns A function that removes the check.
206
+ */
207
+ function hideWhile(component: Component, isHidden: () => boolean): () => void {
208
+ const render = component.render.bind(component);
209
+ component.render = (width: number): string[] => (isHidden() ? [] : render(width));
210
+
211
+ return () => {
212
+ Reflect.deleteProperty(component, "render");
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Checks if `value` is a non-null object.
218
+ */
219
+ function isObject(value: unknown): value is object {
220
+ return typeof value === "object" && value !== null;
221
+ }
@@ -20,8 +20,9 @@ const CHAT_INDEX = 2;
20
20
  /**
21
21
  * Component with child components, matched by shape like Pi's `Container`.
22
22
  */
23
- interface ParentComponent extends Component {
23
+ export interface ParentComponent extends Component {
24
24
  children: Component[];
25
+ addChild(component: Component): void;
25
26
  }
26
27
 
27
28
  /**
@@ -101,7 +102,9 @@ export function padComponent(
101
102
  /**
102
103
  * Pi's containers that get the padding.
103
104
  */
104
- interface PiContainers {
105
+ export interface PiContainers {
106
+ /** Holds the messages of the session. */
107
+ chat: ParentComponent;
105
108
  /** Chat, queued messages, and widgets above and below the editor. */
106
109
  alwaysPadded: Component[];
107
110
  /** Holds the editor, or a selector or extension dialog shown in its place. */
@@ -112,7 +115,7 @@ interface PiContainers {
112
115
  * Finds Pi's chat, queued messages, widget, and editor containers, or returns `undefined` when the tree has
113
116
  * another shape.
114
117
  */
115
- function findPiContainers(root: Component, editor: Component): PiContainers | undefined {
118
+ export function findPiContainers(root: Component, editor: Component): PiContainers | undefined {
116
119
  if (!isParent(root) || root.children.length !== ROOT_CHILD_COUNT) return undefined;
117
120
  if (root.children.some((child) => !isParent(child))) return undefined;
118
121
  const rootChildren = root.children as ParentComponent[];
@@ -125,7 +128,7 @@ function findPiContainers(root: Component, editor: Component): PiContainers | un
125
128
  if (!chat || !isParent(chat)) return undefined;
126
129
 
127
130
  const alwaysPadded = [chat, ...PADDED_ROOT_INDEXES.map((index) => rootChildren[index] as Component)];
128
- return { alwaysPadded, editorContainer };
131
+ return { chat, alwaysPadded, editorContainer };
129
132
  }
130
133
 
131
134
  /**
@@ -136,8 +139,11 @@ function isPadded(component: Component): boolean {
136
139
  }
137
140
 
138
141
  /**
139
- * Checks if `component` has a `children` array, as Pi's `Container` has.
142
+ * Checks if `component` has a `children` array and an `addChild` method, as Pi's `Container` has.
140
143
  */
141
144
  function isParent(component: Component): component is ParentComponent {
142
- return "children" in component && Array.isArray(component.children);
145
+ if (!("children" in component) || !Array.isArray(component.children))
146
+ return false;
147
+
148
+ return "addChild" in component && typeof component.addChild === "function";
143
149
  }
@@ -23,8 +23,8 @@ import type { BashMode } from "./status-line.ts";
23
23
  */
24
24
  export const LEFT_MARGIN = 1;
25
25
  export const RIGHT_MARGIN = 0;
26
- const INNER_PADDING = 2;
27
- const BAR_WIDTH = 1;
26
+ export const INNER_PADDING = 2;
27
+ export const BAR_WIDTH = 1;
28
28
  // Pi's select list starts every item with a 2-column prefix (`→ ` or spaces); the list is moved left by it,
29
29
  // so the item text starts in the same column as the input text
30
30
  const SELECT_PREFIX_WIDTH = 2;
@@ -86,7 +86,7 @@ interface BoxMargins {
86
86
  /**
87
87
  * Shared look of the box rows of one render.
88
88
  */
89
- interface BoxStyle {
89
+ export interface BoxStyle {
90
90
  margins: BoxMargins;
91
91
  barColor: (text: string) => string;
92
92
  colors: BoxColors;
@@ -378,7 +378,7 @@ function renderHalfRow(barChar: string, fillChar: string, boxWidth: number, styl
378
378
  * Renders one full-height box row: accent bar, padding and content on the box background.
379
379
  * Content wider than `textWidth` extends into the right inner padding; only scroll indicators do that.
380
380
  */
381
- function renderBoxRow(content: string, textWidth: number, style: BoxStyle): string {
381
+ export function renderBoxRow(content: string, textWidth: number, style: BoxStyle): string {
382
382
  const { margins, barColor, colors } = style;
383
383
  const leftMargin = " ".repeat(margins.left);
384
384
  const rightMargin = " ".repeat(margins.right);