UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

1,015 lines (769 loc) • 41.7 kB
> senpi can create TUI components. Ask it to build one for your use case. # TUI Components Extensions and custom tools can render custom TUI components for interactive user interfaces. This page covers the component system and available building blocks. **Source:** [`@earendil-works/pi-tui`](https://github.com/earendil-works/pi/tree/main/packages/tui) ## Component Interface All components implement: ```typescript interface Component { render(width: number): string[]; handleInput?(data: string): void; handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined; wantsKeyRelease?: boolean; invalidate(): void; } ``` | Method | Description | |--------|-------------| | `render(width)` | Return array of strings (one per line). Each line **must not exceed `width`**. | | `handleInput?(data)` | Receive keyboard input when component has focus. | | `handleMouse?(event)` | Receive normalized pointer input in fullscreen mode, or scoped clicks in regular mode. | | `wantsKeyRelease?` | If true, component receives key release events (Kitty protocol). Default: false. | | `invalidate()` | Clear cached render state. Called on theme changes. | The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line. Styles do not carry across lines. If you emit multi-line text with styling, reapply styles per line or use `wrapTextWithAnsi()` so styles are preserved for each wrapped line. ## Focusable Interface (IME Support) Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface: ```typescript import { CURSOR_MARKER, type Component, type Focusable } from "@earendil-works/pi-tui"; class MyInput implements Component, Focusable { focused: boolean = false; // Set by TUI when focus changes render(width: number): string[] { const marker = this.focused ? CURSOR_MARKER : ""; // Emit marker right before the fake cursor return [`> ${beforeCursor}${marker}\x1b[7m${atCursor}\x1b[27m${afterCursor}`]; } } ``` When a `Focusable` component has focus, TUI: 1. Sets `focused = true` on the component 2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence) 3. Positions the hardware terminal cursor at that location 4. Shows the hardware cursor only when `showHardwareCursor` is enabled The cursor remains hidden by default. This keeps the fake cursor rendering, while still positioning the hardware cursor for terminals that track IME candidate windows with hidden cursors. Some terminals require a visible hardware cursor for IME positioning; enable it with the renderer's `showHardwareCursor` constructor argument or `setShowHardwareCursor(true)`. Pi also maps `PI_HARDWARE_CURSOR=1` to this setting before it creates its renderer. The `Editor` and `Input` built-in components already implement this interface. ### Container Components with Embedded Inputs When a container component (dialog, selector, etc.) contains an `Input` or `Editor` child, the container must implement `Focusable` and propagate the focus state to the child. Otherwise, the hardware cursor won't be positioned correctly for IME input. ```typescript import { Container, type Focusable, Input } from "@earendil-works/pi-tui"; class SearchDialog extends Container implements Focusable { private searchInput: Input; // Focusable implementation - propagate to child input for IME cursor positioning private _focused = false; get focused(): boolean { return this._focused; } set focused(value: boolean) { this._focused = value; this.searchInput.focused = value; } constructor() { super(); this.searchInput = new Input(); this.addChild(this.searchInput); } } ``` Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position on screen. ## Using Components **In extensions** via `ctx.ui.custom()`: ```typescript pi.on("session_start", async (_event, ctx) => { const result = await ctx.ui.custom<string | null>((tui, theme, keybindings, done) => new MyComponent({ theme, keybindings, onChange: () => tui.requestRender(), onSelect: (value) => done(value), onCancel: () => done(null), }) ); }); ``` **In custom tools** via `ctx.ui.custom()`: ```typescript async execute(toolCallId, params, signal, onUpdate, ctx) { const result = await ctx.ui.custom<string | null>((tui, theme, keybindings, done) => new MyComponent({ theme, keybindings, onChange: () => tui.requestRender(), onSelect: (value) => done(value), onCancel: () => done(null), }) ); // Use result... } ``` ## Overlays Overlays render components on top of existing content without clearing the screen. Pass `{ overlay: true }` to `ctx.ui.custom()`: ```typescript const result = await ctx.ui.custom<string | null>( (tui, theme, keybindings, done) => new MyDialog({ onClose: done }), { overlay: true } ); ``` For positioning and sizing, use `overlayOptions`: ```typescript const result = await ctx.ui.custom<string | null>( (tui, theme, keybindings, done) => new SidePanel({ onClose: done }), { overlay: true, overlayOptions: { // Size: number or percentage string width: "50%", // 50% of terminal width minWidth: 40, // minimum 40 columns maxHeight: "80%", // max 80% of terminal height // Position: anchor-based (default: "center") anchor: "right-center", // 9 positions: center, top-left, top-center, etc. offsetX: -2, // offset from anchor offsetY: 0, // Or percentage/absolute positioning row: "25%", // 25% from top col: 10, // column 10 // Margins margin: 2, // all sides, or { top, right, bottom, left } // Responsive: hide on narrow terminals visible: (termWidth, termHeight) => termWidth >= 80, }, // Get handle for programmatic focus and visibility control onHandle: (handle) => { // handle.focus() - focus this overlay and bring it to the visual front // handle.unfocus() - release input to normal fallback // handle.unfocus({ target }) - release input to a specific component or null // handle.setHidden(true/false) - toggle visibility // handle.hide() - permanently remove }, } ); ``` ### Overlay Focus A focused visible overlay keeps input ownership across temporary non-overlay UI. If an overlay opens another `ctx.ui.custom()` component without `{ overlay: true }`, that replacement UI receives input while it is active; when it closes, the focused overlay can reclaim input. Use `handle.unfocus()` when a visible overlay should stop owning input and let TUI fall back to another visible capturing overlay or the previous focus target. Use `handle.unfocus({ target })` when a specific component should receive input while the overlay stays visible. Passing `{ target: null }` intentionally leaves no focused component until focus is set again. ### Question Overlay and Async Widget When the agent asks a blocking question (`waitForAnswer: true`), a full-screen overlay appears with a tab for each question and a final Submit tab. Use digits or arrows to choose options, Space to toggle multi-select choices, and Enter to confirm and advance. The Submit tab contains the optional comment editor and accepts partial answers after confirmation; unanswered questions are reported back as unanswered. Esc backs out of an editor or asks for confirmation before discarding a draft. Pending option buttons are clickable in regular and fullscreen modes. A single-question single-select click writes the selected highlight before answering; multi-select clicks toggle choices. Click the header to expand, own answer to type a custom reply, or `+N more` to cycle requests. Expanded tabs and Submit are clickable too. Pressing without releasing, dragging away, double-clicking, or clicking a gap does not answer. Async questions (`waitForAnswer: false`) queue above the editor without taking focus or replacing earlier requests. The widget shows the pending count, the shown question and options, its countdown, and `+N more`. `alt+down` cycles requests from an empty composer; Tab still completes and Shift+Tab still cycles thinking. Each request keeps its own draft and idle deadline. Open the shown request with empty Enter or `app.question.answer` (defaults `alt+up` and `alt+a`, shown as Option on macOS). A pending question wins the shared `alt+up` chord; without one it restores queued messages. Windows/WSL dequeue uses `alt+q` instead. The hint prefers `alt+a` in tmux, Apple Terminal, Warp and VS Code; the macOS `å` fallback still works. Rebind either action in `keybindings.json`. A valid digit on an empty composer selects the corresponding option of the first unanswered sub-question. A single-question single-select digit or Enter submits immediately; multiple sub-questions advance through the component. `/answer` lists multiple pending requests, `/answer <n>` opens the n-th, and `/answer skip` dismisses the shown request. Esc collapses the component with its draft kept. An answered question collapses in the transcript to a compact `↳ <header>: <answer>` chip; comments render quoted and dismissed or timed-out questions render `(no answer)`. Click the chip to expand the original message and click again to collapse it. `/answer skip` also tells the agent that you dismissed the question. If you had already answered some of its questions, a cancel you choose (`/answer skip`, Esc or Ctrl+C in the question, the cancel button or Remove on another client) gives the agent those answers once and the chip is marked `(cancelled)`; so does a question whose UI fails. Every other cancel stays silent even with answers: aborting the turn (its result is replaced like any other tool's), closing the session, disabling ask-user, or an RPC client disconnecting. A question that times out also keeps its partial answers. While a question is pending, the terminal title shows `? <header>`, and `askUser.bell` controls the one-time arrival bell. Text first typed or pasted into an empty composer binds to the shown request and labels the border `↳ reply to <header>`. Enter sends that comment only to its bound request; the follow-up chord (`alt+enter`, or `ctrl+q` on Windows/WSL) sends an ordinary message instead. Text present before arrival and recalled history stay chat. If a bound request settles, the text is preserved, the label clears with a notice, and the next Enter sends chat rather than answering another request. ### Overlay Lifecycle Overlay components are disposed when closed. Don't reuse references - create fresh instances: ```typescript // Wrong - stale reference let menu: MenuComponent; await ctx.ui.custom((_, __, ___, done) => { menu = new MenuComponent(done); return menu; }, { overlay: true }); setActiveComponent(menu); // Disposed // Correct - re-call to re-show const showMenu = () => ctx.ui.custom((_, __, ___, done) => new MenuComponent(done), { overlay: true }); await showMenu(); // First show await showMenu(); // "Back" = just call again ``` See [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for comprehensive examples covering anchors, margins, stacking, responsive visibility, and animation. ## Built-in Components Import from `@earendil-works/pi-tui`: ```typescript import { Text, Box, Container, Spacer, Markdown } from "@earendil-works/pi-tui"; ``` ### Text Multi-line text with word wrapping. ```typescript const text = new Text( "Hello World", // content 1, // paddingX (default: 1) 1, // paddingY (default: 1) (s) => bgGray(s) // optional background function ); text.setText("Updated"); ``` ### Box Container with padding and background color. ```typescript const box = new Box( 1, // paddingX 1, // paddingY (s) => bgGray(s) // background function ); box.addChild(new Text("Content", 0, 0)); box.setBgFn((s) => bgBlue(s)); ``` ### Container Groups child components vertically. ```typescript const container = new Container(); container.addChild(component1); container.addChild(component2); container.removeChild(component1); ``` ### Spacer Empty vertical space. ```typescript const spacer = new Spacer(2); // 2 empty lines ``` ### Markdown Renders markdown with syntax highlighting. ```typescript const md = new Markdown( "# Title\n\nSome **bold** text", 1, // paddingX 1, // paddingY theme // MarkdownTheme (see below) ); md.setText("Updated markdown"); ``` ### Image Renders images in supported terminals (Kitty, iTerm2, Ghostty, WezTerm, Warp). ```typescript const image = new Image( base64Data, // base64-encoded image "image/png", // MIME type theme, // ImageTheme { maxWidthCells: 80, maxHeightCells: 24 } ); ``` ## Keyboard Input Use `matchesKey()` for key detection: ```typescript import { matchesKey, Key } from "@earendil-works/pi-tui"; handleInput(data: string) { if (matchesKey(data, Key.up)) { this.selectedIndex--; } else if (matchesKey(data, Key.enter)) { this.onSelect?.(this.selectedIndex); } else if (matchesKey(data, Key.escape)) { this.onCancel?.(); } else if (matchesKey(data, Key.ctrl("c"))) { // Ctrl+C } } ``` **Key identifiers** (use `Key.*` for autocomplete, or string literals): - Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end` - Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right` - With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")` - String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"` ## Mouse Input Fullscreen mode routes normalized press, release, click, move, drag, and wheel events to components and overlays. Return `{ handled: true }` to suppress default behavior, `capture: true` to retain drag/release ownership, `focus: true` to request keyboard focus, and `render: true` when a hover or release visibly changes the component. Press, click, drag, and wheel render by default; no-op move/release events do not. ```typescript import { MouseRegion } from "@earendil-works/pi-tui"; const clickable = new MouseRegion(content, (event) => { if (event.button !== "left") return undefined; if (event.type === "press") return { handled: true }; if (event.type !== "click") return undefined; expanded = !expanded; return { handled: true }; }); ``` In fullscreen mode, unhandled wheel input scrolls the nearest `ScrollView`; unhandled primary-button drags retain transcript selection. OSC 8 links take precedence over parent click regions. `Input`, `Editor`, `SelectList`, and `SettingsList` include fullscreen mouse behavior. Fullscreen Markdown selection keeps the normal rendered appearance and copies the corresponding original Markdown. Selecting a complete formatted construct retains its syntax; selecting inside it copies only that source fragment. Original line breaks are preserved and visual wrapping adds no clipboard line breaks. `fullscreenCopyOnSelect` controls automatic copying; with it disabled, `Ctrl+X` copies the active selection. Selecting any part of a formula converted to Unicode copies the whole original formula, including its delimiters. If the formula body renders unchanged, selecting inside it copies only that source fragment. Selecting any part of a horizontal rule copies the authored rule as a whole, without trailing block separators. When a reference link displays its URL in parentheses, selecting any part of that suffix copies the link's own source syntax (`[ref]`, `[ref][1]` or `[ref][]`), without the remote definition or unselected surrounding prose. Selecting inside the link label still copies only that source fragment. If a display transform changes a Markdown component, selecting its text copies rendered text for the entire drag, including line breaks from visual wrapping. This also applies to unchanged prose beside a transformed block such as a Mermaid diagram. A selection with invalid source mapping, such as a wrapped-table selection that skips source content, still reports that the original source is unavailable and leaves the clipboard intact. The terminal's selection-bypass gesture copies its screen text. Custom components that copy rendered arrays or add ASCII left padding can preserve selection metadata with `copyLineSources`. Preserve the visible text when carrying its metadata. Returned arrays are source snapshots: if provenance changes, publish a new array even when its text looks identical. Do not replace metadata on an array that a retained frame may still use: ```typescript import { copyLineSources } from "@earendil-works/pi-tui"; const original = markdown.render(width - 2); return copyLineSources(original, original.map((line) => ` ${line}`), 0, 2); ``` Regular mode supports scoped capture through `const release = tui.acquireMouseCapture("pending-question")`; the host releases it when the interactive surface closes and reapplies its intent to a replacement renderer after a mode switch. Only an acknowledged, unmodified left press followed by release in the same cell within 500 ms produces a click. Wheel, motion, other buttons, and modified reports are consumed without action. Native selection and scrollback remain unchanged outside the lease; while captured, use the terminal's selection bypass (usually Shift-drag, or Option-drag in iTerm2/Terminal.app). Unknown, stale, resized, or image-bearing frame placement disables click dispatch rather than guessing. Short frames use private cursor-position calibration; after external output the next render appends a fresh frame before recalibration, preserving diagnostics and scrollback. Keyboard paths remain available. This library foundation does not itself enable capture for every regular-mode component. The `terminal.mouse` setting defaults to `"whilePending"`: the host captures regular-mode input only while an async or blocking question is pending. `"off"` disables mouse capture in both modes; `"always"` keeps regular-mode capture active even without a question. Change it in `/settings` or settings JSON. The default `tuiMode` remains `"regular"`. While captured, wheel reports are consumed, not native scrollback; use the terminal's bypass modifier (Shift-drag on Ghostty/kitty/WezTerm/Alacritty/Windows Terminal, Option-drag on iTerm2/Terminal.app) or disable capture for native selection. ### Multiplexers **tmux:** Short startup frames work even when tmux swallows private `ESC[?6n`. When `TMUX_PANE` is set, the terminal reads `tmux display-message -p -t "$TMUX_PANE" "#{cursor_y} #{cursor_x}"` twice at least 10 ms apart. Only matching numeric pane-relative readings within the total 750 ms query budget establish an anchor. Command errors, movement and timeout leave clicks disabled; no bare CPR is sent. Outside tmux the private cursor-query path is unchanged. Enable tmux mouse forwarding to deliver clicks. **herdr:** The builtin reporter shows a pending question as blocked and returns to working or idle after settlement. Mouse forwarding and `alt+up`, `alt+down`, digits and `/answer skip` were verified in herdr 0.9.0. Regular-mode clicks work on a viewport-filled frame. Fresh short frames have a known fail-closed limitation: the pane writes `ESC[?6n` but receives no private reply. In a 120x40 test, outer-client `ESC[<0;27;25M` then `ESC[<0;27;25m` did not answer that short frame; after filling the pane, `ESC[<0;27;34M` then `ESC[<0;27;34m` answered successfully. Use keyboard answers when the initial anchor is unavailable. Tracked in [#1688](https://github.com/code-yeongyu/senpi/issues/1688); unknown placement is never guessed. ## Line Width **Critical:** Each line from `render()` must not exceed the `width` parameter. ```typescript import { visibleWidth, truncateToWidth } from "@earendil-works/pi-tui"; render(width: number): string[] { // Truncate long lines return [truncateToWidth(this.text, width)]; } ``` Utilities: - `visibleWidth(str)` - Get display width (ignores ANSI codes) - `truncateToWidth(str, width, ellipsis?)` - Truncate with optional ellipsis - `wrapTextWithAnsi(str, width)` - Word wrap preserving ANSI codes ## Creating Custom Components Example: Interactive selector ```typescript import { matchesKey, Key, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; class MySelector { private items: string[]; private selected = 0; private cachedWidth?: number; private cachedLines?: string[]; public onSelect?: (item: string) => void; public onCancel?: () => void; constructor(items: string[]) { this.items = items; } handleInput(data: string): void { if (matchesKey(data, Key.up) && this.selected > 0) { this.selected--; this.invalidate(); } else if (matchesKey(data, Key.down) && this.selected < this.items.length - 1) { this.selected++; this.invalidate(); } else if (matchesKey(data, Key.enter)) { this.onSelect?.(this.items[this.selected]); } else if (matchesKey(data, Key.escape)) { this.onCancel?.(); } } render(width: number): string[] { if (this.cachedLines && this.cachedWidth === width) { return this.cachedLines; } this.cachedLines = this.items.map((item, i) => { const prefix = i === this.selected ? "> " : " "; return truncateToWidth(prefix + item, width); }); this.cachedWidth = width; return this.cachedLines; } invalidate(): void { this.cachedWidth = undefined; this.cachedLines = undefined; } } ``` Usage in an extension: ```typescript pi.registerCommand("pick", { description: "Pick an item", handler: async (_args, ctx) => { const items = ["Option A", "Option B", "Option C"]; const selected = await ctx.ui.custom<string | null>((tui, _theme, _keybindings, done) => { const selector = new MySelector(items); selector.onSelect = done; selector.onCancel = () => done(null); return { render: (width) => selector.render(width), handleInput: (data) => { selector.handleInput(data); tui.requestRender(); }, invalidate: () => selector.invalidate(), }; }); if (selected !== null) { ctx.ui.notify(`Selected: ${selected}`, "info"); } } }); ``` ## Theming Components accept theme objects for styling. **In `renderCall`/`renderResult`**, use the `theme` parameter: ```typescript renderResult(result, options, theme, context) { // Use theme.fg() for foreground colors return new Text(theme.fg("success", "Done!"), 0, 0); // Use theme.bg() for background colors const styled = theme.bg("toolPendingBg", theme.fg("accent", "text")); } ``` **Foreground colors** (`theme.fg(color, text)`): | Category | Colors | |----------|--------| | General | `text`, `accent`, `muted`, `dim`, `searchMatchText` | | Status | `success`, `error`, `warning` | | Borders | `border`, `borderAccent`, `borderMuted` | | Messages | `userMessageText`, `customMessageText`, `customMessageLabel` | | Tools | `toolTitle`, `toolOutput` | | Diffs | `toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext` | | Markdown | `mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet` | | Syntax | `syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation` | | Thinking | `thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh`, `thinkingMax` | | Modes | `bashMode` | **Background colors** (`theme.bg(color, text)`): `selectedBg`, `searchMatchBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg` **Combined styles** (`theme.style(text, options)`) apply foreground and background colors with text attributes in one call: ```typescript return new Text(theme.style("Done!", { fg: "success", bg: "toolSuccessBg", bold: true }), 0, 0); ``` A style color can be a semantic theme token or a concrete `Color`. Foreground tokens are accepted as `fg` and background tokens as `bg`; to use a token's color in the other position, pass its concrete color, for example `{ fg: theme.colors.userMessageBg }`. Read concrete colors from `theme.colors` and use the TUI library's color utilities, such as `mixColors()`, for color math. Tokens a theme sets to the terminal default report the color the terminal announced, or a guess when it did not. Use `theme.appearance` (`"dark"` or `"light"`) to decide, for example, whether to lighten or darken a color. **For Markdown**, use `getMarkdownTheme()`: ```typescript import { getMarkdownTheme } from "@code-yeongyu/senpi"; import { Markdown } from "@earendil-works/pi-tui"; renderResult(result, options, theme, context) { const mdTheme = getMarkdownTheme(); return new Markdown(result.details.markdown, 0, 0, mdTheme); } ``` **For custom components**, define your own theme interface: ```typescript interface MyTheme { selected: (s: string) => string; normal: (s: string) => string; } ``` ## Debug logging Set `PI_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout. ```bash PI_TUI_WRITE_LOG=/tmp/tui-ansi.log bunx tsx packages/tui/test/chat-simple.ts ``` ## Performance Cache rendered output when possible: ```typescript class CachedComponent { private cachedWidth?: number; private cachedLines?: string[]; render(width: number): string[] { if (this.cachedLines && this.cachedWidth === width) { return this.cachedLines; } // ... compute lines ... this.cachedWidth = width; this.cachedLines = lines; return lines; } invalidate(): void { this.cachedWidth = undefined; this.cachedLines = undefined; } } ``` Call `invalidate()` when state changes, then use the injected `tui.requestRender()` to trigger re-render. ## Invalidation and Theme Changes When the theme changes, the TUI calls `invalidate()` on all components to clear their caches. Components must properly implement `invalidate()` to ensure theme changes take effect. ### The Problem If a component pre-bakes theme colors into strings (via `theme.fg()`, `theme.bg()`, etc.) and caches them, the cached strings contain ANSI escape codes from the old theme. Simply clearing the render cache isn't enough if the component stores the themed content separately. **Wrong approach** (theme colors won't update): ```typescript class BadComponent extends Container { private content: Text; constructor(message: string, theme: Theme) { super(); // Pre-baked theme colors stored in Text component this.content = new Text(theme.fg("accent", message), 1, 0); this.addChild(this.content); } // No invalidate override - parent's invalidate only clears // child render caches, not the pre-baked content } ``` ### The Solution Components that build content with theme colors must rebuild that content when `invalidate()` is called: ```typescript class GoodComponent extends Container { private message: string; private content: Text; constructor(message: string) { super(); this.message = message; this.content = new Text("", 1, 0); this.addChild(this.content); this.updateDisplay(); } private updateDisplay(): void { // Rebuild content with current theme this.content.setText(theme.fg("accent", this.message)); } override invalidate(): void { super.invalidate(); // Clear child caches this.updateDisplay(); // Rebuild with new theme } } ``` ### Pattern: Rebuild on Invalidate For components with complex content: ```typescript class ComplexComponent extends Container { private data: SomeData; constructor(data: SomeData) { super(); this.data = data; this.rebuild(); } private rebuild(): void { this.clear(); // Remove all children // Build UI with current theme this.addChild(new Text(theme.fg("accent", theme.bold("Title")), 1, 0)); this.addChild(new Spacer(1)); for (const item of this.data.items) { const color = item.active ? "success" : "muted"; this.addChild(new Text(theme.fg(color, item.label), 1, 0)); } } override invalidate(): void { super.invalidate(); this.rebuild(); } } ``` ### When This Matters This pattern is needed when: 1. **Pre-baking theme colors** - Using `theme.fg()` or `theme.bg()` to create styled strings stored in child components 2. **Syntax highlighting** - Using `highlightCode()` which applies theme-based syntax colors 3. **Complex layouts** - Building child component trees that embed theme colors This pattern is NOT needed when: 1. **Using theme callbacks** - Passing functions like `(text) => theme.fg("accent", text)` that are called during render 2. **Simple containers** - Just grouping other components without adding themed content 3. **Stateless render** - Computing themed output fresh in every `render()` call (no caching) ## Common Patterns These patterns cover the most common UI needs in extensions. **Copy these patterns instead of building from scratch.** ### Pattern 1: Selection Dialog (SelectList) For letting users pick from a list of options. Use `SelectList` from `@earendil-works/pi-tui` with `DynamicBorder` for framing. ```typescript import type { ExtensionAPI } from "@code-yeongyu/senpi"; import { DynamicBorder } from "@code-yeongyu/senpi"; import { Container, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui"; pi.registerCommand("pick", { handler: async (_args, ctx) => { const items: SelectItem[] = [ { value: "opt1", label: "Option 1", description: "First option" }, { value: "opt2", label: "Option 2", description: "Second option" }, { value: "opt3", label: "Option 3" }, // description is optional ]; const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => { const container = new Container(); // Top border container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s))); // Title container.addChild(new Text(theme.fg("accent", theme.bold("Pick an Option")), 1, 0)); // SelectList with theme const selectList = new SelectList(items, Math.min(items.length, 10), { selectedPrefix: (t) => theme.fg("accent", t), selectedText: (t) => theme.fg("accent", t), description: (t) => theme.fg("muted", t), scrollInfo: (t) => theme.fg("dim", t), noMatch: (t) => theme.fg("warning", t), }); selectList.onSelect = (item) => done(item.value); selectList.onCancel = () => done(null); container.addChild(selectList); // Help text container.addChild(new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel"), 1, 0)); // Bottom border container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s))); return { render: (w) => container.render(w), invalidate: () => container.invalidate(), handleInput: (data) => { selectList.handleInput(data); tui.requestRender(); }, }; }); if (result) { ctx.ui.notify(`Selected: ${result}`, "info"); } }, }); ``` **Examples:** [preset.ts](../examples/extensions/preset.ts), [tools.ts](../examples/extensions/tools.ts) ### Pattern 2: Async Operation with Cancel (BorderedLoader) For operations that take time and should be cancellable. `BorderedLoader` shows a spinner and handles escape to cancel. ```typescript import { BorderedLoader } from "@code-yeongyu/senpi"; pi.registerCommand("fetch", { handler: async (_args, ctx) => { const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => { const loader = new BorderedLoader(tui, theme, "Fetching data..."); loader.onAbort = () => done(null); // Do async work fetchData(loader.signal) .then((data) => done(data)) .catch(() => done(null)); return loader; }); if (result === null) { ctx.ui.notify("Cancelled", "info"); } else { ctx.ui.setEditorText(result); } }, }); ``` **Examples:** [qna.ts](../examples/extensions/qna.ts), [handoff.ts](../examples/extensions/handoff.ts) ### Pattern 3: Settings/Toggles (SettingsList) For toggling multiple settings. Use `SettingsList` from `@earendil-works/pi-tui` with `getSettingsListTheme()`. ```typescript import { getSettingsListTheme } from "@code-yeongyu/senpi"; import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui"; pi.registerCommand("settings", { handler: async (_args, ctx) => { const items: SettingItem[] = [ { id: "verbose", label: "Verbose mode", currentValue: "off", values: ["on", "off"] }, { id: "color", label: "Color output", currentValue: "on", values: ["on", "off"] }, ]; await ctx.ui.custom((_tui, theme, _kb, done) => { const container = new Container(); container.addChild(new Text(theme.fg("accent", theme.bold("Settings")), 1, 1)); const settingsList = new SettingsList( items, Math.min(items.length + 2, 15), getSettingsListTheme(), (id, newValue) => { // Handle value change ctx.ui.notify(`${id} = ${newValue}`, "info"); }, () => done(undefined), // On close { enableSearch: true }, // Optional: enable fuzzy search by label ); container.addChild(settingsList); return { render: (w) => container.render(w), invalidate: () => container.invalidate(), handleInput: (data) => settingsList.handleInput?.(data), }; }); }, }); ``` **Examples:** [tools.ts](../examples/extensions/tools.ts) ### Pattern 4: Persistent Status Indicator Show status in the footer that persists across renders. Good for mode indicators. ```typescript // Set status (shown in footer) ctx.ui.setStatus("my-ext", ctx.ui.theme.fg("accent", "● active")); // Clear status ctx.ui.setStatus("my-ext", undefined); ``` **Examples:** [status-line.ts](../examples/extensions/status-line.ts), [plan-mode/index.ts](../examples/extensions/plan-mode/index.ts), [preset.ts](../examples/extensions/preset.ts) ### Pattern 4b: Working Indicator Customization Customize the inline working indicator shown while senpi is streaming a response. ```typescript // Static indicator ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Custom animated indicator ctx.ui.setWorkingIndicator({ frames: [ ctx.ui.theme.fg("dim", "·"), ctx.ui.theme.fg("muted", "•"), ctx.ui.theme.fg("accent", "●"), ctx.ui.theme.fg("muted", "•"), ], intervalMs: 120, }); // Hide the indicator entirely ctx.ui.setWorkingIndicator({ frames: [] }); // Restore senpi's default spinner ctx.ui.setWorkingIndicator(); ``` This only affects the normal streaming working indicator. Compaction and retry loaders keep their built-in styling. Custom frames are rendered verbatim, so extensions must add their own colors when needed. **Examples:** [working-indicator.ts](../examples/extensions/working-indicator.ts) ### Pattern 5: Widgets Above/Below Editor Show persistent content above or below the input editor. Good for todo lists, progress. ```typescript // Simple string array (above editor by default) ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]); // Render below the editor ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" }); // Or with theme ctx.ui.setWidget("my-widget", (_tui, theme) => { const lines = items.map((item, i) => item.done ? theme.fg("success", "✓ ") + theme.fg("muted", item.text) : theme.fg("dim", "○ ") + item.text ); return { render: () => lines, invalidate: () => {}, }; }); // Clear ctx.ui.setWidget("my-widget", undefined); ``` **Examples:** [plan-mode/index.ts](../examples/extensions/plan-mode/index.ts) ### Pattern 6: Custom Footer Replace the footer. `footerData` exposes data not otherwise accessible to extensions. ```typescript ctx.ui.setFooter((tui, theme, footerData) => ({ invalidate() {}, render(width: number): string[] { // footerData.getGitBranch(): string | null // footerData.getExtensionStatuses(): ReadonlyMap<string, string> return [`${ctx.model?.id} (${footerData.getGitBranch() || "no git"})`]; }, dispose: footerData.onBranchChange(() => tui.requestRender()), // reactive })); ctx.ui.setFooter(undefined); // restore default ``` Token stats available via `ctx.sessionManager.getBranch()` and `ctx.model`. **Examples:** [custom-footer.ts](../examples/extensions/custom-footer.ts) ### Pattern 7: Custom Editor (vim mode, etc.) Replace the main input editor with a custom implementation. Useful for modal editing (vim), different keybindings (emacs), or specialized input handling. ```typescript import { CustomEditor, type ExtensionAPI } from "@code-yeongyu/senpi"; import { matchesKey, truncateToWidth } from "@earendil-works/pi-tui"; type Mode = "normal" | "insert"; class VimEditor extends CustomEditor { private mode: Mode = "insert"; handleInput(data: string): void { // Escape: switch to normal mode, or pass through for app handling if (matchesKey(data, "escape")) { if (this.mode === "insert") { this.mode = "normal"; return; } // In normal mode, escape aborts agent (handled by CustomEditor) super.handleInput(data); return; } // Insert mode: pass everything to CustomEditor if (this.mode === "insert") { super.handleInput(data); return; } // Normal mode: vim-style navigation switch (data) { case "i": this.mode = "insert"; return; case "h": super.handleInput("\x1b[D"); return; // Left case "j": super.handleInput("\x1b[B"); return; // Down case "k": super.handleInput("\x1b[A"); return; // Up case "l": super.handleInput("\x1b[C"); return; // Right } // Pass unhandled keys to super (ctrl+c, etc.), but filter printable chars if (data.length === 1 && data.charCodeAt(0) >= 32) return; super.handleInput(data); } render(width: number): string[] { const lines = super.render(width); // Add mode indicator to bottom border (use truncateToWidth for ANSI-safe truncation) if (lines.length > 0) { const label = this.mode === "normal" ? " NORMAL " : " INSERT "; const lastLine = lines[lines.length - 1]!; // Pass "" as ellipsis to avoid adding "..." when truncating lines[lines.length - 1] = truncateToWidth(lastLine, width - label.length, "") + label; } return lines; } } export default function (pi: ExtensionAPI) { pi.on("session_start", (_event, ctx) => { // Factory receives the TUI, theme, and keybindings from the app ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings) ); }); } ``` **Key points:** - **Extend `CustomEditor`** (not base `Editor`) to get app keybindings (escape to abort, ctrl+d to exit, model switching, etc.) - **Call `super.handleInput(data)`** for keys you don't handle - **Status spinners**: custom editors keep standalone status rows by default. Pass `{ embedWorkingStatus: true }` as the fourth `CustomEditor` constructor argument to embed working, compaction, branch summarization, and retry spinners in the editor border instead. - **Factory pattern**: `setEditorComponent` receives a factory function that gets `tui`, `theme`, and `keybindings` - **Pass `undefined`** to restore the default editor: `ctx.ui.setEditorComponent(undefined)` **Examples:** [modal-editor.ts](../examples/extensions/modal-editor.ts) ## Key Rules 1. **Always use theme from callback** - Don't import theme directly. Use `theme` from the `ctx.ui.custom((tui, theme, keybindings, done) => ...)` callback. 2. **Always type DynamicBorder color param** - Write `(s: string) => theme.fg("accent", s)`, not `(s) => theme.fg("accent", s)`. 3. **Call tui.requestRender() after state changes** - In `handleInput`, call `tui.requestRender()` after updating state. 4. **Return the three-method object** - Custom components need `{ render, invalidate, handleInput }`. 5. **Use existing components** - `SelectList`, `SettingsList`, `BorderedLoader` cover 90% of cases. Don't rebuild them. ## Examples - **Selection UI**: [examples/extensions/preset.ts](../examples/extensions/preset.ts) - SelectList with DynamicBorder framing - **Async with cancel**: [examples/extensions/qna.ts](../examples/extensions/qna.ts) - BorderedLoader for LLM calls - **Settings toggles**: [examples/extensions/tools.ts](../examples/extensions/tools.ts) - SettingsList for tool enable/disable - **Status indicators**: [examples/extensions/plan-mode/index.ts](../examples/extensions/plan-mode/index.ts) - setStatus and setWidget - **Working indicator**: [examples/extensions/working-indicator.ts](../examples/extensions/working-indicator.ts) - setWorkingIndicator - **Custom footer**: [examples/extensions/custom-footer.ts](../examples/extensions/custom-footer.ts) - setFooter with stats - **Custom editor**: [examples/extensions/modal-editor.ts](../examples/extensions/modal-editor.ts) - Vim-like modal editing - **Snake game**: [examples/extensions/snake.ts](../examples/extensions/snake.ts) - Full game with keyboard input, game loop - **Custom tool rendering**: [examples/extensions/todo.ts](../examples/extensions/todo.ts) - renderCall and renderResult