Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/coding-agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
- Added environment variables and advanced settings for overriding auto-detected terminal hyperlink, image, and truecolor capabilities ([#8665](https://github.com/earendil-works/pi/issues/8665)).
- Added `fullscreenCopyOnSelect` to disable automatic fullscreen selection copy; when disabled, `Ctrl+X` copies the active text selection before falling back to the last assistant message, while `/tree` still copies the selected message ([#7720](https://github.com/earendil-works/pi/issues/7720)).

### Changed

- Changed fullscreen transcript search arrows to underline on hover and capitalized the search placeholder.

### Fixed

- Fixed toggling thinking visibility clearing partial output from running Bash tools ([#8611](https://github.com/earendil-works/pi/issues/8611)).
Expand Down
2 changes: 2 additions & 0 deletions packages/coding-agent/docs/keybindings.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ These actions apply when interactive mode uses `--tui-mode fullscreen` and targe

Fullscreen transcript bindings take precedence over editor bindings. The default unmodified navigation keys therefore control the transcript in fullscreen mode, while their `ctrl` variants continue to control the editor. Outside fullscreen mode, both variants control the editor.

The transcript search panel shows the configured previous/next shortcuts and clickable arrow controls. Press `tui.altScreen.search` again, or use `tui.altScreen.searchClose`, to close it.

| Key | Default mode | Fullscreen mode |
|-----|--------------|-----------------|
| `home`, `end` | Editor | Transcript |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ export function createInteractiveTui(options: InteractiveTuiOptions): TuiMainScr
return new TuiAltScreen(terminal, options.showHardwareCursor, options.logDirectory, {
searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),
searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
searchNavigationButtonStyle: (text, hovered) => (hovered ? theme.underline(text) : text),
openUrl: openBrowser,
onRightClickPaste: options.onRightClickPaste,
copyOnSelect: options.fullscreenCopyOnSelect,
Expand Down
4 changes: 4 additions & 0 deletions packages/tui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
- Added environment and programmatic overrides for OSC 8 hyperlinks, inline image protocols, and truecolor terminal capabilities ([#8665](https://github.com/earendil-works/pi/issues/8665)).
- Added a `TuiAltScreen` `copyOnSelect` option plus helpers to detect and copy the active fullscreen text selection programmatically ([#7720](https://github.com/earendil-works/pi/issues/7720)).

### Changed

- Changed fullscreen transcript search to use a bordered, placeholder-based input with a muted result count, right-aligned clickable key-and-arrow buttons with configurable hover styling, and open-shortcut toggling.

### Fixed

- Fixed main-screen rendering crashing when image-heavy output exceeded V8's string length limit ([#8028](https://github.com/earendil-works/pi/issues/8028)).
Expand Down
3 changes: 2 additions & 1 deletion packages/tui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ if (isViewportTUI(tui)) {
}
```

Stack entries support `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer and unused delta chains to outer scroll views by default. The primary scroll view receives the alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers, matching common terminal prompt-navigation shortcuts. Press `Ctrl+Shift+F` to search its rendered content, `Enter`/`Ctrl+G` and `Shift+Enter`/`Ctrl+Shift+G` to move between matches, and `Escape` to close search. `TuiAltScreenOptions.searchMatchStyle` and `searchCurrentMatchStyle` customize match highlighting.
Stack entries support `basis`, `grow`, `shrink`, `minSize`, `maxSize`, and responsive `visible` callbacks. Mouse-wheel input targets the scroll view under the pointer and unused delta chains to outer scroll views by default. The primary scroll view receives the alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers, matching common terminal prompt-navigation shortcuts. Press `Ctrl+Shift+F` to open or close its bordered search panel. The panel shows the configured previous/next shortcuts and provides clickable arrow controls; by default, `Enter`/`Ctrl+G` and `Shift+Enter`/`Ctrl+Shift+G` move between matches, and `Escape` also closes search. `TuiAltScreenOptions.searchMatchStyle` and `searchCurrentMatchStyle` customize match highlighting, while `searchNavigationButtonStyle` styles each arrow button and receives its hover state.

Layout geometry is rebuilt for each requested frame. Stateful components are retained, and their existing rendered-line caches remain effective. Calling `render(width)` directly on these layout components produces an unbounded document, which is also used when alt mode restores the main screen.

Expand Down Expand Up @@ -177,6 +177,7 @@ handle.unfocus(); // Release focus to normal fallback
handle.unfocus({ target: baseComponent }); // Release this overlay to a specific component
handle.unfocus({ target: null }); // Release this overlay and leave focus empty
handle.isFocused(); // Check if overlay has focus
handle.getBounds(); // Get last rendered terminal-relative bounds

handle.unfocus();
// Overlay loses focus; TUI falls back to another visible capturing overlay or the previous focus target.
Expand Down
103 changes: 91 additions & 12 deletions packages/tui/src/alt-screen-search.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Input } from "./components/input.ts";
import { getKeybindings } from "./keybindings.ts";
import type { Component, Focusable } from "./tui.ts";
import { getGraphemeSegmenter, stripTerminalSequences, truncateToWidth, visibleWidth } from "./utils.ts";

Expand Down Expand Up @@ -103,14 +104,28 @@ export function getAltScreenSearchMatchKey(match: AltScreenSearchMatch): string
}

export class AltScreenSearchComponent implements Component, Focusable {
private readonly input = new Input();
private readonly input = new Input({
prompt: " ",
placeholder: "Find in transcript",
placeholderStyle: (text) => `\x1b[2m${text}\x1b[22m`,
});
private readonly onQueryChange: (query: string) => void;
private readonly navigationButtonStyle: (text: string, hovered: boolean) => string;
private resultCount = 0;
private resultIndex = -1;
private previousButtonStart = -1;
private previousButtonEnd = -1;
private nextButtonStart = -1;
private nextButtonEnd = -1;
private hoveredNavigationDirection: -1 | 1 | undefined;
private _focused = false;

constructor(onQueryChange: (query: string) => void) {
constructor(
onQueryChange: (query: string) => void,
navigationButtonStyle: (text: string, hovered: boolean) => string = (text) => text,
) {
this.onQueryChange = onQueryChange;
this.navigationButtonStyle = navigationButtonStyle;
}

get focused(): boolean {
Expand All @@ -127,6 +142,19 @@ export class AltScreenSearchComponent implements Component, Focusable {
this.resultCount = count;
}

getNavigationDirectionAt(row: number, column: number): -1 | 1 | undefined {
if (row !== 2) return undefined;
if (column >= this.previousButtonStart && column < this.previousButtonEnd) return -1;
if (column >= this.nextButtonStart && column < this.nextButtonEnd) return 1;
return undefined;
}

setHoveredNavigationDirection(direction: -1 | 1 | undefined): boolean {
if (direction === this.hoveredNavigationDirection) return false;
this.hoveredNavigationDirection = direction;
return true;
}

handleInput(data: string): void {
const previous = this.input.getValue();
this.input.handleInput(data);
Expand All @@ -140,18 +168,69 @@ export class AltScreenSearchComponent implements Component, Focusable {

render(width: number): string[] {
const safeWidth = Math.max(1, width);
const label = " Find transcript";
const innerWidth = Math.max(0, safeWidth - 2);
const formatKey = (key: string | undefined): string =>
key
? key
.split("+")
.map((part) => {
if (process.platform === "darwin" && part.toLowerCase() === "alt") return "Option";
return part.charAt(0).toUpperCase() + part.slice(1);
})
.join("+")
: "Unbound";
const keybindings = getKeybindings();
const previousKey = formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]);
const nextKey = formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]);
const query = this.input.getValue();
const status = !query
const result = !query
? ""
: this.resultCount === 0
? "No matches "
: `${this.resultIndex + 1}/${this.resultCount} `;
const labelWidth = visibleWidth(label);
const statusWidth = visibleWidth(status);
const gap = " ".repeat(Math.max(1, safeWidth - labelWidth - statusWidth));
const title = truncateToWidth(`${label}${gap}${status}`, safeWidth, "");
const padding = " ".repeat(Math.max(0, safeWidth - visibleWidth(title)));
return [`\x1b[7m${title}${padding}\x1b[27m`, ...this.input.render(safeWidth)];
? "No matches"
: `${this.resultIndex + 1}/${this.resultCount}`;
const resultSpace = Math.max(0, innerWidth - 3);
const visibleResult = truncateToWidth(result, resultSpace, "");
const resultText = visibleResult ? `\x1b[2m ${visibleResult} \x1b[22m` : "";
const inputWidth = Math.max(0, innerWidth - visibleWidth(resultText));
const inputLine = truncateToWidth(this.input.render(Math.max(1, inputWidth))[0] ?? "", inputWidth, "");
const inputPadding = " ".repeat(Math.max(0, inputWidth - visibleWidth(inputLine)));
const content = `${inputLine}${inputPadding}${resultText}`;

let previousButton = `↑ ${previousKey}`;
let nextButton = `↓ ${nextKey}`;
let separator = " · ";
const outerGapWidth = 1;
const availableControlsWidth = Math.max(0, innerWidth - outerGapWidth * 2 - 1);
let controlsWidth = visibleWidth(previousButton) + visibleWidth(separator) + visibleWidth(nextButton);
if (controlsWidth > availableControlsWidth) {
previousButton = "↑";
nextButton = "↓";
separator = " ";
controlsWidth = visibleWidth(previousButton) + visibleWidth(separator) + visibleWidth(nextButton);
}
const showButtons = controlsWidth <= availableControlsWidth;
const renderedButtons = showButtons
? this.navigationButtonStyle(previousButton, this.hoveredNavigationDirection === -1) +
separator +
this.navigationButtonStyle(nextButton, this.hoveredNavigationDirection === 1)
: "";
const outerGapsWidth = showButtons ? outerGapWidth * 2 : 0;
const rightRuleWidth = renderedButtons && innerWidth > controlsWidth + outerGapsWidth ? 1 : 0;
const leftRuleWidth = Math.max(
0,
innerWidth - (showButtons ? controlsWidth : 0) - outerGapsWidth - rightRuleWidth,
);
const previousStart = 1 + leftRuleWidth + outerGapWidth;
this.previousButtonStart = showButtons ? previousStart : -1;
this.previousButtonEnd = showButtons ? previousStart + visibleWidth(previousButton) : -1;
this.nextButtonStart = showButtons ? this.previousButtonEnd + visibleWidth(separator) : -1;
this.nextButtonEnd = showButtons ? this.nextButtonStart + visibleWidth(nextButton) : -1;

if (safeWidth === 1) return ["┌", "│", "└"];
return [
`┌${"─".repeat(innerWidth)}┐`,
`│${content}│`,
`└${"─".repeat(leftRuleWidth)}${renderedButtons ? " " : ""}${renderedButtons}${renderedButtons ? " " : ""}${"─".repeat(rightRuleWidth)}┘`,
];
}
}
36 changes: 31 additions & 5 deletions packages/tui/src/components/input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { decodeKittyPrintable } from "../keys.ts";
import { KillRing } from "../kill-ring.ts";
import { type Component, CURSOR_MARKER, type Focusable } from "../tui.ts";
import { UndoStack } from "../undo-stack.ts";
import { getGraphemeSegmenter, isWhitespaceChar, sliceByColumn, visibleWidth } from "../utils.ts";
import { getGraphemeSegmenter, isWhitespaceChar, sliceByColumn, truncateToWidth, visibleWidth } from "../utils.ts";
import { findWordBackward, findWordForward } from "../word-navigation.ts";

const segmenter = getGraphemeSegmenter();
Expand All @@ -13,12 +13,21 @@ interface InputState {
cursor: number;
}

export interface InputOptions {
prompt?: string;
placeholder?: string;
placeholderStyle?: (text: string) => string;
}

/**
* Input component - single-line text input with horizontal scrolling
*/
export class Input implements Component, Focusable {
private value: string = "";
private cursor: number = 0; // Cursor position in the value
private readonly prompt: string;
private readonly placeholder: string;
private readonly placeholderStyle: (text: string) => string;
public onSubmit?: (value: string) => void;
public onEscape?: () => void;

Expand All @@ -36,6 +45,12 @@ export class Input implements Component, Focusable {
// Undo support
private undoStack = new UndoStack<InputState>();

constructor(options: InputOptions = {}) {
this.prompt = options.prompt ?? "> ";
this.placeholder = options.placeholder ?? "";
this.placeholderStyle = options.placeholderStyle ?? ((text) => text);
}

getValue(): string {
return this.value;
}
Expand Down Expand Up @@ -377,11 +392,22 @@ export class Input implements Component, Focusable {

render(width: number): string[] {
// Calculate visible window
const prompt = "> ";
const availableWidth = width - prompt.length;
const availableWidth = width - visibleWidth(this.prompt);

if (availableWidth <= 0) {
return [prompt];
return [truncateToWidth(this.prompt, width, "")];
}

if (this.value.length === 0 && this.placeholder) {
const placeholder = truncateToWidth(this.placeholder, availableWidth, "");
const graphemes = [...segmenter.segment(placeholder)];
const atCursor = graphemes[0]?.segment ?? " ";
const afterCursor = placeholder.slice(atCursor.length);
const marker = this.focused ? CURSOR_MARKER : "";
const cursorChar = `\x1b[7m${this.placeholderStyle(atCursor)}\x1b[27m`;
const textWithCursor = marker + cursorChar + this.placeholderStyle(afterCursor);
const padding = " ".repeat(Math.max(0, availableWidth - visibleWidth(textWithCursor)));
return [this.prompt + textWithCursor + padding];
}

let visibleText = "";
Expand Down Expand Up @@ -440,7 +466,7 @@ export class Input implements Component, Focusable {
// Calculate visual width
const visualLength = visibleWidth(textWithCursor);
const padding = " ".repeat(Math.max(0, availableWidth - visualLength));
const line = prompt + textWithCursor + padding;
const line = this.prompt + textWithCursor + padding;

return [line];
}
Expand Down
1 change: 1 addition & 0 deletions packages/tui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export {
isFocusable,
isViewportTUI,
type OverlayAnchor,
type OverlayBounds,
type OverlayHandle,
type OverlayMargin,
type OverlayOptions,
Expand Down
41 changes: 36 additions & 5 deletions packages/tui/src/tui-alt-screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ export interface TuiAltScreenOptions {
searchMatchStyle?: (text: string) => string;
/** Style the current transcript search match. */
searchCurrentMatchStyle?: (text: string) => string;
/** Style a transcript search navigation button. */
searchNavigationButtonStyle?: (text: string, hovered: boolean) => string;
/** Open an OSC 8 hyperlink activated with a primary-button click. */
openUrl?: (url: string) => void;
/** Handle an unmodified secondary-button press for clipboard paste. Currently enabled on Windows only. */
Expand Down Expand Up @@ -200,6 +202,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
private readonly mouseEnabled: boolean;
private readonly searchMatchStyle: (text: string) => string;
private readonly searchCurrentMatchStyle: (text: string) => string;
private readonly searchNavigationButtonStyle: (text: string, hovered: boolean) => string;
private readonly openUrl?: (url: string) => void;
private readonly onRightClickPaste?: () => void;
private copyOnSelect: boolean;
Expand All @@ -224,6 +227,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
this.mouseEnabled = options.mouse ?? true;
this.searchMatchStyle = options.searchMatchStyle ?? ((text) => `\x1b[4m${text}\x1b[24m`);
this.searchCurrentMatchStyle = options.searchCurrentMatchStyle ?? ((text) => `\x1b[1;7m${text}\x1b[22;27m`);
this.searchNavigationButtonStyle = options.searchNavigationButtonStyle ?? ((text) => text);
this.openUrl = options.openUrl;
this.onRightClickPaste = options.onRightClickPaste;
this.copyOnSelect = options.copyOnSelect ?? true;
Expand Down Expand Up @@ -447,12 +451,15 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
}
}

private openSearch(): void {
private toggleSearch(): void {
if (this.activeSearch) {
this.activeSearch.overlay?.focus();
this.closeSearch();
return;
}
const component = new AltScreenSearchComponent((query) => this.updateSearchQuery(query));
const component = new AltScreenSearchComponent(
(query) => this.updateSearchQuery(query),
this.searchNavigationButtonStyle,
);
const search: ActiveSearch = {
component,
query: "",
Expand All @@ -465,7 +472,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
search.overlay = this.showOverlay(component, {
anchor: "top-right",
width: "40%",
minWidth: 24,
minWidth: 32,
margin: 1,
});
}
Expand Down Expand Up @@ -496,6 +503,28 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
this.requestRender();
}

private getSearchNavigationDirectionAt(x: number, y: number): -1 | 1 | undefined {
const search = this.activeSearch;
const bounds = search?.overlay?.getBounds();
if (!search || !bounds) return undefined;
if (x < bounds.col || x >= bounds.col + bounds.width || y < bounds.row || y >= bounds.row + bounds.height) {
return undefined;
}
return search.component.getNavigationDirectionAt(y - bounds.row, x - bounds.col);
}

private handleSearchMouseEvent(event: SgrMouseEvent): boolean {
const search = this.activeSearch;
if (!search) return false;
const direction = this.getSearchNavigationDirectionAt(event.x, event.y);
if (search.component.setHoveredNavigationDirection(direction)) this.requestRender();
if (direction === undefined || event.release || (event.button & 32) !== 0 || (event.button & 3) !== 0) {
return false;
}
this.navigateSearch(direction);
return true;
}

private refreshSearch(layout: LayoutFrame): boolean {
const search = this.activeSearch;
if (!search) return false;
Expand Down Expand Up @@ -570,6 +599,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
this.selectionPressActive = false;
this.stopSelectionAutoScroll();
this.stopScrollbarHover();
if (this.activeSearch?.component.setHoveredNavigationDirection(undefined)) this.requestRender();
this.stopScrollbarDrag();
this.pressedUrl = undefined;
this.selectionDragged = false;
Expand All @@ -594,6 +624,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
const mouseEvent = this.parseSgrMouseEvent(data);
if (mouseEvent) {
if (this.handleRightClickPaste(mouseEvent)) return { consume: true };
if (this.handleSearchMouseEvent(mouseEvent)) return { consume: true };
const handled = this.handleScrollbarMouseEvent(mouseEvent);
if (!this.scrollbarDrag) this.updateScrollbarHover(mouseEvent.x, mouseEvent.y);
if (!handled) this.handleSelectionMouseEvent(mouseEvent);
Expand All @@ -604,7 +635,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI {
const keybindings = getKeybindings();
const isRelease = isKeyRelease(data);
if (keybindings.matches(data, "tui.altScreen.search")) {
if (!isRelease) this.openSearch();
if (!isRelease) this.toggleSearch();
return { consume: true };
}
if (this.activeSearch?.overlay?.isFocused()) {
Expand Down
Loading