Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix truncated command descriptions (#417)

kt94be145dc047
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 46040701be..e0e62a2db8 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -13,6 +13,7 @@
- Fixed empty prompt placeholders hiding the input caret.
- Fixed automatic model selection preferring other configured providers over Prime Inference's GLM 5.2 default.
- Fixed missing ripgrep blocking subagents and added actionable installation guidance for the optional search helper ([ENG-4572](https://linear.app/primeintellect/issue/ENG-4572/ripgrep-not-installed)).
+- Fixed narrow slash-command descriptions ending abruptly or clearing the prompt background, and added a content-sized popup above the input with the same distinct surface as `/btw` ([ENG-4542](https://linear.app/primeintellect/issue/ENG-4542/command-descriptions-are-cut-off-on-narrow-screens)).
- Fixed snapshot transfers terminating resident workers, stranding partial readers, or rejecting identical retries ([ENG-4602](https://linear.app/primeintellect/issue/ENG-4602/make-snapshot-transfers-idempotent-and-non-fatal)).
- Fixed the resume picker opening on an older session instead of the newest session ([ENG-4630](https://linear.app/primeintellect/issue/ENG-4630/show-latest-sessions-first-in-resume-list)).
- Fixed tool-only responses rendering directly against the preceding user prompt.
diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
index 4e67583a54..528cadd1f7 100644
--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
@@ -185,9 +185,7 @@ function childAgentRecap(node: ChildAgentInspectorNode): string {
}
function padTableCell(value: string, width: number, ellipsis = ""): string {
- // truncateToWidth emits full ANSI resets around its marker even for plain text.
- // Strip those generated resets before applying foreground/background styling.
- const truncated = truncateToWidth(value, width, ellipsis).replaceAll("\x1b[0m", "");
+ const truncated = truncateToWidth(value, width, ellipsis);
return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
}
@@ -467,11 +465,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
const text = this.elideAroundDiff(label, sharedPrefix, sharedSuffix);
const safeWidth = Math.max(0, width);
const truncated =
- visibleWidth(text) > safeWidth
- ? `${truncateToWidth(text, Math.max(0, safeWidth - 1), "")
- .replaceAll("\x1b[0m", "")
- .trimEnd()}…`
- : text;
+ visibleWidth(text) > safeWidth ? `${truncateToWidth(text, Math.max(0, safeWidth - 1), "").trimEnd()}…` : text;
return theme.fg("dim", padTableCell(truncated, safeWidth));
}
diff --git a/packages/coding-agent/src/modes/interactive/components/custom-editor.ts b/packages/coding-agent/src/modes/interactive/components/custom-editor.ts
index 6b44dd27c9..ddcc9d5dcb 100644
--- a/packages/coding-agent/src/modes/interactive/components/custom-editor.ts
+++ b/packages/coding-agent/src/modes/interactive/components/custom-editor.ts
@@ -296,6 +296,6 @@ export class CustomEditor extends Editor {
const padding = " ".repeat(Math.max(0, placeholderWidth - visibleWidth(placeholderText)));
const line = `${promptLeadingPadding}${promptPrefix}${promptTrailingPadding}${displayText}${padding}${rightPadding}`;
const padded = line + " ".repeat(Math.max(0, width - visibleWidth(line)));
- return this.backgroundColor ? this.backgroundColor(padded) : padded;
+ return this.getAutocompleteAnchorMarker() + (this.backgroundColor ? this.backgroundColor(padded) : padded);
}
}
diff --git a/packages/coding-agent/src/modes/interactive/components/side-question.ts b/packages/coding-agent/src/modes/interactive/components/side-question.ts
index e835794e00..f4487c00f3 100644
--- a/packages/coding-agent/src/modes/interactive/components/side-question.ts
+++ b/packages/coding-agent/src/modes/interactive/components/side-question.ts
@@ -61,7 +61,7 @@ export class SideQuestionComponent implements Component {
private applySurface(line: string, width: number): string {
const padded = line + " ".repeat(Math.max(0, width - visibleWidth(line)));
- const background = theme.getUserMessageBackgroundColor();
+ const background = theme.getPopupBackgroundColor();
return padded
.split("\x1b[0m")
.map((segment) => background(segment))
diff --git a/packages/coding-agent/src/modes/interactive/theme/theme.ts b/packages/coding-agent/src/modes/interactive/theme/theme.ts
index d433b65b5d..7cd2b9bd0a 100644
--- a/packages/coding-agent/src/modes/interactive/theme/theme.ts
+++ b/packages/coding-agent/src/modes/interactive/theme/theme.ts
@@ -416,6 +416,10 @@ export class Theme {
return this.surfaceBackgroundColor("userMessageBg");
}
+ getPopupBackgroundColor(): (str: string) => string {
+ return this.surfaceBackgroundColor("toolPanelBg");
+ }
+
private surfaceBackgroundColor(color: ThemeBg): (str: string) => string {
const terminalBg = getDefaultTerminalColors()?.background;
const surfaceRgb = colorValueToRgb(this.bgColorValues.get(color));
@@ -1264,6 +1268,7 @@ export function getEditorTheme(): EditorTheme {
return {
borderColor: (text: string) => theme.fg("borderMuted", text),
backgroundColor: theme.getEditorBackgroundColor(),
+ autocompleteBackgroundColor: (text: string) => theme.getPopupBackgroundColor()(text),
selectList: getSelectListTheme(),
commandColor: (text: string) => theme.fg("accent", text),
};
diff --git a/packages/coding-agent/test/custom-editor.test.ts b/packages/coding-agent/test/custom-editor.test.ts
index 9a13ff50c6..bef6fc798a 100644
--- a/packages/coding-agent/test/custom-editor.test.ts
+++ b/packages/coding-agent/test/custom-editor.test.ts
@@ -1,4 +1,4 @@
-import type { AutocompleteProvider, EditorTheme, TUI } from "@earendil-works/pi-tui";
+import type { AutocompleteProvider, EditorTheme, OverlayHandle, TUI } from "@earendil-works/pi-tui";
import { CURSOR_MARKER, setKeybindings, visibleWidth } from "@earendil-works/pi-tui";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
@@ -17,8 +17,18 @@ const editorTheme: EditorTheme = {
},
};
+const fakeOverlayHandle: OverlayHandle = {
+ hide: vi.fn(),
+ setHidden: vi.fn(),
+ isHidden: () => false,
+ focus: vi.fn(),
+ unfocus: vi.fn(),
+ isFocused: () => false,
+};
+
const fakeTui = {
requestRender: vi.fn(),
+ showOverlay: vi.fn(() => fakeOverlayHandle),
terminal: { rows: 24, columns: 80 },
} as unknown as TUI;
@@ -172,6 +182,7 @@ describe("CustomEditor", () => {
const line = editor.render(40)[1]!;
expect(line).not.toContain(CURSOR_MARKER);
+ expect(line).toContain("\x1b_pi:autocomplete:");
expect(line).toContain("\x1b[7m \x1b[0mtype to start");
});
@@ -233,7 +244,7 @@ describe("CustomEditor", () => {
it("keeps the surface background across truncation resets in the header line", () => {
const backgroundColor = (text: string) => `<bg>${text}</bg>`;
const editor = new CustomEditor(fakeTui, { ...editorTheme, backgroundColor }, new KeybindingsManager());
- editor.getHeaderLine = () => "x".repeat(100);
+ editor.getHeaderLine = () => `\x1b[31m${"x".repeat(100)}`;
const lines = editor.render(40);
const segments = lines[1]!.split("\x1b[0m");
diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
index aa0d8f0f90..4053d9f280 100644
--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -6,7 +6,7 @@ import { type SideQuestionEvent, startSideQuestion } from "../../../src/core/sid
import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";
import { SideQuestionComponent } from "../../../src/modes/interactive/components/side-question.js";
import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
-import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { getEditorTheme, initTheme, theme } from "../../../src/modes/interactive/theme/theme.js";
import { createHarness, getMessageText } from "../harness.js";
function deferred(): { promise: Promise<void>; resolve: () => void } {
@@ -226,9 +226,12 @@ describe("ENG-4509 side questions", () => {
);
const lines = component.render(40);
const rendered = stripAnsi(lines.join("\n"));
+ const blankPopupLine = theme.getPopupBackgroundColor()(" ".repeat(40));
expect(lines).toHaveLength(8);
expect(lines.every((line) => line.includes("\x1b[48"))).toBe(true);
+ expect(lines[0]).toBe(blankPopupLine);
+ expect(getEditorTheme().autocompleteBackgroundColor?.(" ".repeat(40))).toBe(blankPopupLine);
expect(rendered).toContain(" /btw What changed?");
expect(rendered).not.toContain(" answer");
expect(rendered).toContain("First line");
diff --git a/packages/tui/CHANGELOG.md b/packages/tui/CHANGELOG.md
index 3e8606a623..33467f832f 100644
--- a/packages/tui/CHANGELOG.md
+++ b/packages/tui/CHANGELOG.md
@@ -5,6 +5,7 @@
- Fixed fullscreen drag selection so holding at a transcript edge scrolls through offscreen text ([ENG-4644](https://linear.app/primeintellect/issue/ENG-4644/copy-issues)).
- Fixed slash-command and skill autocomplete not appearing for references typed in the middle of prompts ([ENG-4628](https://linear.app/primeintellect/issue/ENG-4628/support-skill-and-command-autocomplete-mid-prompt)).
- Fixed focused full-pane overlays becoming slow to navigate on wider terminals.
+- Fixed plain-text truncation emitting ANSI resets, marked shortened descriptions with an ellipsis, and rendered autocomplete in content-sized popup surfaces that close when editing leaves the completion context ([ENG-4542](https://linear.app/primeintellect/issue/ENG-4542/command-descriptions-are-cut-off-on-narrow-screens)).
## [0.3.0] - 2026-07-13
diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.ts
index c3060f2c4f..84ccff8f3e 100644
--- a/packages/tui/src/components/editor.ts
+++ b/packages/tui/src/components/editor.ts
@@ -4,7 +4,7 @@ import { getKeybindings } from "../keybindings.js";
import { decodePrintableKey, matchesKey } from "../keys.js";
import { KillRing } from "../kill-ring.js";
import { getSlashCommandContext, type SlashCommandContext } from "../slash-command-context.js";
-import { type Component, CURSOR_MARKER, type Focusable, type TUI } from "../tui.js";
+import { type Component, CURSOR_MARKER, type Focusable, type OverlayHandle, type TUI } from "../tui.js";
import { UndoStack } from "../undo-stack.js";
import { getSegmenter, isPunctuationChar, isWhitespaceChar, truncateToWidth, visibleWidth } from "../utils.js";
import { SelectList, type SelectListLayoutOptions, type SelectListTheme } from "./select-list.js";
@@ -231,6 +231,7 @@ interface LayoutLine {
export interface EditorTheme {
borderColor: (str: string) => string;
backgroundColor?: (str: string) => string;
+ autocompleteBackgroundColor?: (str: string) => string;
selectList: SelectListTheme;
commandColor?: (str: string) => string;
}
@@ -244,9 +245,11 @@ export interface EditorOptions {
const SLASH_COMMAND_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
minPrimaryColumnWidth: 12,
maxPrimaryColumnWidth: 32,
+ showSelectedDescription: true,
};
const ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS = 20;
+let autocompleteAnchorId = 0;
export class Editor implements Component, Focusable {
private state: EditorState = {
@@ -272,6 +275,7 @@ export class Editor implements Component, Focusable {
// Border color (can be changed dynamically)
public borderColor: (str: string) => string;
public backgroundColor: ((str: string) => string) | undefined;
+ public autocompleteBackgroundColor: ((str: string) => string) | undefined;
public commandColor: ((str: string) => string) | undefined;
// Autocomplete support
@@ -286,6 +290,12 @@ export class Editor implements Component, Focusable {
private autocompleteRequestTask: Promise<void> = Promise.resolve();
private autocompleteStartToken: number = 0;
private autocompleteRequestId: number = 0;
+ private autocompleteOverlay?: OverlayHandle;
+ private readonly autocompleteAnchorMarker = `\x1b_pi:autocomplete:${++autocompleteAnchorId}\x07`;
+ private readonly autocompleteOverlayComponent: Component = {
+ render: (width) => this.renderAutocompleteOverlay(width),
+ invalidate: () => this.autocompleteList?.invalidate(),
+ };
// Paste tracking for large pastes
private pastes: Map<number, string> = new Map();
@@ -334,6 +344,7 @@ export class Editor implements Component, Focusable {
this.theme = theme;
this.borderColor = theme.borderColor;
this.backgroundColor = theme.backgroundColor;
+ this.autocompleteBackgroundColor = theme.autocompleteBackgroundColor;
this.commandColor = theme.commandColor;
const paddingX = options.paddingX ?? 0;
this.paddingX = Number.isFinite(paddingX) ? Math.max(0, Math.floor(paddingX)) : 0;
@@ -501,7 +512,13 @@ export class Editor implements Component, Focusable {
// No cached state to invalidate currently
}
- render(width: number): string[] {
+ private getRenderMetrics(width: number): {
+ useBackgroundSurface: boolean;
+ paddingX: number;
+ promptPrefixText: string;
+ promptPrefixWidth: number;
+ inputWidth: number;
+ } {
const maxPadding = Math.max(0, Math.floor((width - 1) / 2));
const useBackgroundSurface = this.backgroundColor !== undefined;
const configuredPaddingX = Math.min(this.paddingX, maxPadding);
@@ -511,7 +528,23 @@ export class Editor implements Component, Focusable {
const contentWidth = Math.max(1, width - paddingX * 2);
const promptPrefixText = this.getPromptPrefix();
const promptPrefixWidth = Math.min(visibleWidth(promptPrefixText), Math.max(0, contentWidth - 1));
- const inputWidth = Math.max(1, contentWidth - promptPrefixWidth);
+
+ return {
+ useBackgroundSurface,
+ paddingX,
+ promptPrefixText,
+ promptPrefixWidth,
+ inputWidth: Math.max(1, contentWidth - promptPrefixWidth),
+ };
+ }
+
+ protected getAutocompleteAnchorMarker(): string {
+ return this.autocompleteOverlay && this.focused ? this.autocompleteAnchorMarker : "";
+ }
+
+ render(width: number): string[] {
+ const { useBackgroundSurface, paddingX, promptPrefixText, promptPrefixWidth, inputWidth } =
+ this.getRenderMetrics(width);
const promptPrefix =
promptPrefixWidth > 0 ? this.formatPromptPrefix(truncateToWidth(promptPrefixText, promptPrefixWidth, "")) : "";
@@ -578,7 +611,6 @@ export class Editor implements Component, Focusable {
const line = this.scrollOffset > 0 ? this.borderColor(` ↑ ${this.scrollOffset} more`) : "";
result.push(renderSurfaceLine(truncateToWidth(line, width)));
}
-
// Render each visible layout line
// Emit hardware cursor marker only when focused and not showing autocomplete
const emitCursorMarker = this.focused && !this.autocompleteState;
@@ -633,7 +665,8 @@ export class Editor implements Component, Focusable {
// Render the line (no side borders, just horizontal lines above and below)
const contentLine = `${promptLeadingPadding}${linePromptPrefix}${promptTrailingPadding}${displayText}${padding}${lineRightPadding}`;
- result.push(useBackgroundSurface ? renderSurfaceLine(contentLine) : contentLine);
+ const anchorMarker = layoutLine.hasCursor ? this.getAutocompleteAnchorMarker() : "";
+ result.push(anchorMarker + (useBackgroundSurface ? renderSurfaceLine(contentLine) : contentLine));
}
// Render bottom border (with scroll indicator if more content below)
@@ -651,21 +684,25 @@ export class Editor implements Component, Focusable {
result.push(renderSurfaceLine(truncateToWidth(line, width)));
}
- // Add autocomplete list if active
- if (this.autocompleteState && this.autocompleteList) {
- const autocompleteResult = this.autocompleteList.render(inputWidth);
- const promptPrefixPadding = " ".repeat(promptPrefixWidth);
- for (const line of autocompleteResult) {
- const lineWidth = visibleWidth(line);
- const linePadding = " ".repeat(Math.max(0, inputWidth - lineWidth));
- const contentLine = `${promptLeadingPadding}${promptPrefixPadding}${promptTrailingPadding}${line}${linePadding}${rightPadding}`;
- result.push(useBackgroundSurface ? renderSurfaceLine(contentLine) : contentLine);
- }
- }
-
return result;
}
+ private renderAutocompleteOverlay(width: number): string[] {
+ if (!(this.autocompleteState && this.autocompleteList)) return [];
+
+ const { useBackgroundSurface, paddingX, promptPrefixWidth, inputWidth } = this.getRenderMetrics(width);
+ const leftPadding = " ".repeat(paddingX + promptPrefixWidth);
+ const rightPadding = " ".repeat(paddingX);
+ const backgroundColor =
+ this.autocompleteBackgroundColor ?? (useBackgroundSurface ? this.backgroundColor : undefined);
+
+ return ["", ...this.autocompleteList.render(inputWidth), ""].map((line) => {
+ const linePadding = " ".repeat(Math.max(0, inputWidth - visibleWidth(line)));
+ const contentLine = `${leftPadding}${line}${linePadding}${rightPadding}`;
+ return backgroundColor ? backgroundColor(contentLine) : contentLine;
+ });
+ }
+
handleInput(data: string): void {
const kb = getKeybindings();
@@ -1246,7 +1283,7 @@ export class Editor implements Component, Focusable {
}
}
} else {
- this.updateAutocomplete();
+ this.refreshAutocompleteAfterEdit();
}
}
@@ -1416,21 +1453,7 @@ export class Editor implements Component, Focusable {
this.onChange(this.getText());
}
- // Update or re-trigger autocomplete after backspace
- if (this.autocompleteState) {
- this.updateAutocomplete();
- } else {
- // If autocomplete was cancelled (no matches), re-trigger if we're in a completable context
- const currentLine = this.state.lines[this.state.cursorLine] || "";
- const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
- if (this.getCurrentSlashCommandContext()) {
- this.tryTriggerAutocomplete();
- }
- // Symbol-based completion context like @ or #
- else if (textBeforeCursor.match(/(?:^|[\s])[@#][^\s]*$/)) {
- this.tryTriggerAutocomplete();
- }
- }
+ this.refreshAutocompleteAfterEdit(true);
}
/**
@@ -1629,6 +1652,7 @@ export class Editor implements Component, Focusable {
if (this.onChange) {
this.onChange(this.getText());
}
+ this.refreshAutocompleteAfterEdit();
}
private deleteToEndOfLine(): void {
@@ -1661,6 +1685,7 @@ export class Editor implements Component, Focusable {
if (this.onChange) {
this.onChange(this.getText());
}
+ this.refreshAutocompleteAfterEdit();
}
private deleteWordBackwards(): void {
@@ -1706,6 +1731,7 @@ export class Editor implements Component, Focusable {
if (this.onChange) {
this.onChange(this.getText());
}
+ this.refreshAutocompleteAfterEdit();
}
private deleteWordForward(): void {
@@ -1748,6 +1774,7 @@ export class Editor implements Component, Focusable {
if (this.onChange) {
this.onChange(this.getText());
}
+ this.refreshAutocompleteAfterEdit();
}
private handleForwardDelete(): void {
@@ -1783,20 +1810,7 @@ export class Editor implements Component, Focusable {
this.onChange(this.getText());
}
- // Update or re-trigger autocomplete after forward delete
- if (this.autocompleteState) {
- this.updateAutocomplete();
- } else {
- const currentLine = this.state.lines[this.state.cursorLine] || "";
- const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
- if (this.getCurrentSlashCommandContext()) {
- this.tryTriggerAutocomplete();
- }
- // Symbol-based completion context like @ or #
- else if (textBeforeCursor.match(/(?:^|[\s])[@#][^\s]*$/)) {
- this.tryTriggerAutocomplete();
- }
- }
+ this.refreshAutocompleteAfterEdit(true);
}
/**
@@ -2009,6 +2023,7 @@ export class Editor implements Component, Focusable {
this.insertYankedText(text);
this.lastAction = "yank";
+ this.refreshAutocompleteAfterEdit();
}
/**
@@ -2032,6 +2047,7 @@ export class Editor implements Component, Focusable {
this.insertYankedText(text);
this.lastAction = "yank";
+ this.refreshAutocompleteAfterEdit();
}
/**
@@ -2144,6 +2160,7 @@ export class Editor implements Component, Focusable {
if (this.onChange) {
this.onChange(this.getText());
}
+ this.refreshAutocompleteAfterEdit();
}
/**
@@ -2442,6 +2459,14 @@ export class Editor implements Component, Focusable {
}
this.autocompleteState = state;
+ if (!this.autocompleteOverlay) {
+ this.autocompleteOverlay = this.tui.showOverlay(this.autocompleteOverlayComponent, {
+ width: "100%",
+ aboveMarker: this.autocompleteAnchorMarker,
+ nonCapturing: true,
+ visible: () => this.focused && this.autocompleteState !== null,
+ });
+ }
}
private cancelAutocompleteRequest(): void {
@@ -2455,6 +2480,8 @@ export class Editor implements Component, Focusable {
}
private clearAutocompleteUi(): void {
+ this.autocompleteOverlay?.hide();
+ this.autocompleteOverlay = undefined;
this.autocompleteState = null;
this.autocompleteList = undefined;
this.autocompletePrefix = "";
@@ -2470,6 +2497,26 @@ export class Editor implements Component, Focusable {
return this.autocompleteState !== null;
}
+ private refreshAutocompleteAfterEdit(retrigger = false): void {
+ const currentLine = this.state.lines[this.state.cursorLine] || "";
+ const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
+ const hasCompletionContext =
+ this.getCurrentSlashCommandContext() !== null || /(?:^|[\s])[@#][^\s]*$/.test(textBeforeCursor);
+
+ if (this.autocompleteState) {
+ if (this.getText().trim().length === 0 || (this.autocompleteState === "regular" && !hasCompletionContext)) {
+ this.cancelAutocomplete();
+ return;
+ }
+ this.updateAutocomplete();
+ return;
+ }
+
+ if (retrigger && hasCompletionContext) {
+ this.tryTriggerAutocomplete();
+ }
+ }
+
private updateAutocomplete(): void {
if (!this.autocompleteState || !this.autocompleteProvider) return;
this.requestAutocomplete({ force: this.autocompleteState === "force", explicitTab: false });
diff --git a/packages/tui/src/components/select-list.ts b/packages/tui/src/components/select-list.ts
index f4cee6ab26..1993bb524e 100644
--- a/packages/tui/src/components/select-list.ts
+++ b/packages/tui/src/components/select-list.ts
@@ -1,6 +1,6 @@
import { getKeybindings } from "../keybindings.js";
import type { Component } from "../tui.js";
-import { truncateToWidth, visibleWidth } from "../utils.js";
+import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "../utils.js";
const DEFAULT_PRIMARY_COLUMN_WIDTH = 32;
const PRIMARY_COLUMN_GAP = 2;
@@ -36,6 +36,7 @@ export interface SelectListLayoutOptions {
minPrimaryColumnWidth?: number;
maxPrimaryColumnWidth?: number;
truncatePrimary?: (context: SelectListTruncatePrimaryContext) => string;
+ showSelectedDescription?: boolean;
}
export class SelectList implements Component {
@@ -107,6 +108,10 @@ export class SelectList implements Component {
lines.push(this.theme.scrollInfo(truncateToWidth(scrollText, width - 2, "")));
}
+ if (this.layout.showSelectedDescription) {
+ this.renderSelectedDescription(lines, width);
+ }
+
return lines;
}
@@ -157,7 +162,7 @@ export class SelectList implements Component {
const remainingWidth = width - descriptionStart - 2; // -2 for safety
if (remainingWidth > MIN_DESCRIPTION_WIDTH) {
- const truncatedDesc = truncateToWidth(descriptionSingleLine, remainingWidth, "");
+ const truncatedDesc = truncateToWidth(descriptionSingleLine, remainingWidth, "…");
if (isSelected) {
return this.theme.selectedText(`${prefix}${truncatedValue}${spacing}${truncatedDesc}`);
}
@@ -216,6 +221,18 @@ export class SelectList implements Component {
return item.label || item.value;
}
+ private renderSelectedDescription(lines: string[], width: number): void {
+ const description = this.filteredItems[this.selectedIndex]?.description?.trim();
+ if (!description) return;
+
+ const indent = width >= 4 ? " " : "";
+ const contentWidth = Math.max(1, width - visibleWidth(indent) - 2);
+ lines.push("");
+ for (const line of wrapTextWithAnsi(description, contentWidth)) {
+ lines.push(this.theme.description(indent + line));
+ }
+ }
+
private notifySelectionChange(): void {
const selectedItem = this.filteredItems[this.selectedIndex];
if (selectedItem && this.onSelectionChange) {
diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.ts
index c14f6fc467..ef2c63bcec 100644
--- a/packages/tui/src/tui.ts
+++ b/packages/tui/src/tui.ts
@@ -195,6 +195,8 @@ export interface OverlayOptions {
row?: SizeValue;
/** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
col?: SizeValue;
+ /** Zero-width marker in base content; positions the overlay immediately above its row. */
+ aboveMarker?: string;
// === Margin from terminal edges ===
/** Margin from terminal edges. Number applies to all sides. */
@@ -1109,6 +1111,7 @@ export class TUI extends Container {
col: number;
w: number;
scrollback: boolean;
+ aboveMarker?: { line: number; col: number };
}[] = [];
let minLinesNeeded = result.length;
@@ -1117,6 +1120,18 @@ export class TUI extends Container {
for (const entry of visibleEntries) {
const { component, options } = entry;
const scrollback = options?.scrollback === true;
+ let aboveMarker: { line: number; col: number } | undefined;
+ if (options?.aboveMarker) {
+ for (let line = result.length - 1; line >= 0; line--) {
+ const markerIndex = result[line].indexOf(options.aboveMarker);
+ if (markerIndex === -1) continue;
+ aboveMarker = { line, col: visibleWidth(result[line].slice(0, markerIndex)) };
+ result[line] =
+ result[line].slice(0, markerIndex) + result[line].slice(markerIndex + options.aboveMarker.length);
+ break;
+ }
+ if (!aboveMarker) continue;
+ }
// Get layout with height=0 first to determine width and maxHeight
// (width and maxHeight don't depend on overlay height)
@@ -1133,8 +1148,10 @@ export class TUI extends Container {
// Get final row/col with actual overlay height
const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
- rendered.push({ component, overlayLines, row, col, w: width, scrollback });
- minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
+ rendered.push({ component, overlayLines, row, col, w: width, scrollback, aboveMarker });
+ if (!aboveMarker) {
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
+ }
}
// Pad to at least terminal height so overlays have screen-relative positions.
@@ -1150,8 +1167,21 @@ export class TUI extends Container {
const viewportStart = Math.max(0, workingHeight - termHeight);
// Composite each overlay
- for (const { component, overlayLines, row, col, w, scrollback } of rendered) {
- const overlayStart = scrollback ? Math.max(0, workingHeight - (row + overlayLines.length)) : viewportStart;
+ for (const renderedOverlay of rendered) {
+ const { component, w, scrollback, aboveMarker } = renderedOverlay;
+ let { overlayLines, row, col } = renderedOverlay;
+ if (aboveMarker) {
+ const markerRow = aboveMarker.line - viewportStart;
+ if (markerRow <= 0 || markerRow >= termHeight) continue;
+ if (overlayLines.length > markerRow) {
+ overlayLines = overlayLines.slice(overlayLines.length - markerRow);
+ }
+ row = markerRow - overlayLines.length;
+ col = Math.max(0, Math.min(aboveMarker.col, termWidth - w));
+ }
+
+ const overlayStart =
+ scrollback && !aboveMarker ? Math.max(0, workingHeight - (row + overlayLines.length)) : viewportStart;
for (let i = 0; i < overlayLines.length; i++) {
const idx = overlayStart + row + i;
if (idx >= 0 && idx < result.length) {
diff --git a/packages/tui/src/utils.ts b/packages/tui/src/utils.ts
index 06ad6dd2bc..3fbdc10e37 100644
--- a/packages/tui/src/utils.ts
+++ b/packages/tui/src/utils.ts
@@ -137,13 +137,12 @@ function finalizeTruncatedResult(
): string {
const reset = "\x1b[0m";
const visibleWidth = prefixWidth + ellipsisWidth;
- let result: string;
-
- if (ellipsis.length > 0) {
- result = `${prefix}${reset}${ellipsis}${reset}`;
- } else {
- result = `${prefix}${reset}`;
- }
+ const prefixHasAnsi = prefix.includes("\x1b");
+ const ellipsisHasAnsi = ellipsis.includes("\x1b");
+ const beforeEllipsis = prefixHasAnsi ? reset : "";
+ const afterEllipsis = prefixHasAnsi || ellipsisHasAnsi ? reset : "";
+ const result =
+ ellipsis.length > 0 ? `${prefix}${beforeEllipsis}${ellipsis}${afterEllipsis}` : `${prefix}${beforeEllipsis}`;
return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;
}
diff --git a/packages/tui/test/editor-autocomplete-overlay.test.ts b/packages/tui/test/editor-autocomplete-overlay.test.ts
new file mode 100644
index 0000000000..81d117e73b
--- /dev/null
+++ b/packages/tui/test/editor-autocomplete-overlay.test.ts
@@ -0,0 +1,79 @@
+import assert from "node:assert";
+import { describe, it } from "node:test";
+import type { AutocompleteProvider } from "../src/autocomplete.js";
+import { Editor } from "../src/components/editor.js";
+import { TUI } from "../src/tui.js";
+import { defaultEditorTheme } from "./test-themes.js";
+import { VirtualTerminal } from "./virtual-terminal.js";
+
+const autocompleteProvider: AutocompleteProvider = {
+ async getSuggestions() {
+ return {
+ prefix: "/",
+ items: [
+ { value: "/help", label: "help" },
+ { value: "/hotkeys", label: "hotkeys" },
+ ],
+ };
+ },
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
+ const nextLines = [...lines];
+ const line = nextLines[cursorLine] ?? "";
+ const before = line.slice(0, cursorCol - prefix.length);
+ nextLines[cursorLine] = before + item.value + line.slice(cursorCol);
+ return { lines: nextLines, cursorLine, cursorCol: before.length + item.value.length };
+ },
+};
+
+async function createOpenAutocomplete(): Promise<Editor> {
+ const tui = new TUI(new VirtualTerminal(40, 12));
+ const editor = new Editor(tui, defaultEditorTheme);
+ tui.setFocus(editor);
+ editor.setAutocompleteProvider(autocompleteProvider);
+ editor.handleInput("/");
+ await Promise.resolve();
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(editor.isShowingAutocomplete(), true);
+ return editor;
+}
+
+describe("editor autocomplete overlay", () => {
+ it("anchors the overlay to the active input row", async () => {
+ const editor = await createOpenAutocomplete();
+ const lines = editor.render(40);
+
+ assert.equal(lines[0]?.includes("\x1b_pi:autocomplete:"), false);
+ assert.equal(lines[1]?.includes("\x1b_pi:autocomplete:"), true);
+ });
+
+ it("closes synchronously when typing leaves the completion context", async () => {
+ const editor = await createOpenAutocomplete();
+
+ editor.handleInput("/");
+
+ assert.equal(editor.getText(), "//");
+ assert.equal(editor.isShowingAutocomplete(), false);
+ });
+
+ it("keeps the overlay visible when fullscreen clips the editor top row", async () => {
+ const terminal = new VirtualTerminal(40, 5);
+ const tui = new TUI(terminal);
+ const editor = new Editor(tui, defaultEditorTheme);
+ tui.setFocus(editor);
+ editor.setAutocompleteProvider(autocompleteProvider);
+ tui.start();
+ tui.enterFullscreen({ scroll: [], dock: editor, mouse: false });
+
+ editor.handleInput("/");
+ await Promise.resolve();
+ await new Promise((resolve) => setImmediate(resolve));
+ tui.requestRender(true);
+ await new Promise<void>((resolve) => process.nextTick(resolve));
+ await terminal.waitForRender();
+
+ const viewport = terminal.getViewport();
+ assert.ok(viewport.some((line) => line.includes("help")));
+ assert.ok(viewport[3]?.includes("/"));
+ tui.stop();
+ });
+});
diff --git a/packages/tui/test/editor.test.ts b/packages/tui/test/editor.test.ts
index 557ba3dae6..1af736c982 100644
--- a/packages/tui/test/editor.test.ts
+++ b/packages/tui/test/editor.test.ts
@@ -2016,6 +2016,45 @@ describe("Editor component", () => {
});
describe("Autocomplete", () => {
+ it("shows suggestions in an overlay without changing editor height", async () => {
+ const tui = createTestTUI(60, 24);
+ const popupBackground = (text: string) => `\x1b[48;2;12;12;16m${text}\x1b[49m`;
+ const editor = new Editor(tui, {
+ ...defaultEditorTheme,
+ autocompleteBackgroundColor: popupBackground,
+ });
+ tui.setFocus(editor);
+ editor.setAutocompleteProvider({
+ getSuggestions: async () => ({
+ items: [
+ { value: "/model", label: "model", description: "Change model" },
+ { value: "/help", label: "help", description: "Show help" },
+ ],
+ prefix: "/",
+ }),
+ applyCompletion,
+ });
+ const editorHeight = editor.render(60).length;
+
+ editor.handleInput("/");
+ await flushAutocomplete();
+
+ assert.equal(editor.render(60).length, editorHeight);
+ assert.equal(tui.hasOverlay(), true);
+ assert.ok(!editor.render(60).some((line) => line.includes("Change model")));
+ const overlayLines = (
+ editor as unknown as { renderAutocompleteOverlay: (width: number) => string[] }
+ ).renderAutocompleteOverlay(60);
+ assert.equal(stripVTControlCharacters(overlayLines[0] ?? "").trim(), "");
+ assert.match(stripVTControlCharacters(overlayLines[1] ?? ""), /model/);
+ assert.equal(stripVTControlCharacters(overlayLines.at(-1) ?? "").trim(), "");
+ assert.ok(overlayLines.every((line) => line.startsWith("\x1b[48;2;12;12;16m")));
+
+ editor.handleInput("\x15");
+ assert.equal(editor.getText(), "");
+ assert.equal(tui.hasOverlay(), false);
+ });
+
it("auto-applies single force-file suggestion without showing menu", async () => {
const editor = new Editor(createTestTUI(), defaultEditorTheme);
diff --git a/packages/tui/test/overlay-options.test.ts b/packages/tui/test/overlay-options.test.ts
index a679ff5d67..97e52f077e 100644
--- a/packages/tui/test/overlay-options.test.ts
+++ b/packages/tui/test/overlay-options.test.ts
@@ -501,6 +501,74 @@ describe("TUI overlay options", () => {
});
});
+ describe("marker anchoring", () => {
+ it("renders above its marker without moving the anchored content", async () => {
+ const terminal = new VirtualTerminal(20, 8);
+ const tui = new TUI(terminal);
+ const marker = "\x1b_pi:test-overlay\x07";
+ const content = new StaticOverlay([
+ "transcript 1",
+ "transcript 2",
+ "transcript 3",
+ "transcript 4",
+ "underlay 1",
+ "underlay 2",
+ `${marker}input`,
+ "footer",
+ ]);
+
+ tui.addChild(content);
+ tui.showOverlay(new StaticOverlay(["suggestion", "description"]), {
+ width: "100%",
+ aboveMarker: marker,
+ nonCapturing: true,
+ });
+ tui.start();
+ await renderAndFlush(tui, terminal);
+
+ const viewport = terminal.getViewport();
+ assert.equal(viewport[4]?.trimEnd(), "suggestion");
+ assert.equal(viewport[5]?.trimEnd(), "description");
+ assert.equal(viewport[6], "input");
+ assert.equal(viewport[7], "footer");
+ assert.ok(viewport.every((line) => !line.includes(marker)));
+ tui.stop();
+ });
+
+ it("anchors above fullscreen dock content", async () => {
+ const terminal = new VirtualTerminal(20, 8);
+ const tui = new TUI(terminal);
+ const marker = "\x1b_pi:fullscreen-overlay\x07";
+ const transcript = new StaticOverlay([
+ "transcript 1",
+ "transcript 2",
+ "transcript 3",
+ "transcript 4",
+ "underlay 1",
+ "underlay 2",
+ ]);
+ const dock = new StaticOverlay([`${marker}input`, "footer"]);
+
+ tui.addChild(transcript);
+ tui.addChild(dock);
+ tui.start();
+ tui.enterFullscreen({ scroll: [transcript], dock, mouse: false });
+ tui.showOverlay(new StaticOverlay(["suggestion", "description"]), {
+ width: "100%",
+ aboveMarker: marker,
+ nonCapturing: true,
+ });
+ await renderAndFlush(tui, terminal);
+
+ const viewport = terminal.getViewport();
+ assert.equal(viewport[4]?.trimEnd(), "suggestion");
+ assert.equal(viewport[5]?.trimEnd(), "description");
+ assert.equal(viewport[6], "input");
+ assert.equal(viewport[7], "footer");
+ tui.stop();
+ });
+ });
+
describe("stacked overlays", () => {
it("should render multiple overlays with later ones on top", async () => {
const terminal = new VirtualTerminal(80, 24);
diff --git a/packages/tui/test/select-list.test.ts b/packages/tui/test/select-list.test.ts
index 053690fe47..3133610c18 100644
--- a/packages/tui/test/select-list.test.ts
+++ b/packages/tui/test/select-list.test.ts
@@ -35,6 +35,59 @@ describe("SelectList", () => {
assert.ok(rendered[0].includes("Line one Line two Line three"));
});
+ it("marks truncated descriptions without resetting outer styles", () => {
+ const items = [
+ {
+ value: "test",
+ label: "test",
+ description: "This description is much too long for the available terminal width",
+ },
+ ];
+ const styledTheme = {
+ ...testTheme,
+ selectedText: (text: string) => `\x1b[35m${text}\x1b[39m`,
+ };
+
+ const list = new SelectList(items, 5, styledTheme);
+ const [line] = list.render(50);
+
+ assert.ok(line?.includes("…"));
+ assert.ok(visibleWidth(line ?? "") <= 50);
+ assert.doesNotMatch(line ?? "", /\x1b\[0m/);
+ });
+
+ it("shows the selected description in a wrapped detail area", () => {
+ const description = "This description is too long to fit on the selected row but remains available in full";
+ const items = [{ value: "test", label: "test", description }];
+ const list = new SelectList(items, 5, testTheme, { showSelectedDescription: true });
+
+ const rendered = list.render(50);
+ const detailLines = rendered.slice(2).map((line) => line.trim());
+
+ assert.ok(rendered[0]?.includes("…"));
+ assert.equal(detailLines.join(" "), description);
+ assert.ok(rendered.every((line) => visibleWidth(line) <= 50));
+ });
+
+ it("sizes the detail area to the selected description", () => {
+ const items = [
+ {
+ value: "long",
+ label: "long",
+ description: "A selected description that wraps across several lines at this terminal width",
+ },
+ { value: "short", label: "short", description: "Short description" },
+ ];
+ const list = new SelectList(items, 5, testTheme, { showSelectedDescription: true });
+
+ const longSelection = list.render(32);
+ list.setSelectedIndex(1);
+ const shortSelection = list.render(32);
+
+ assert.ok(shortSelection.length < longSelection.length);
+ assert.equal(shortSelection.at(-1)?.trim(), "Short description");
+ });
+
it("keeps descriptions aligned when the primary text is truncated", () => {
const items = [
{ value: "short", label: "short", description: "short description" },
diff --git a/packages/tui/test/truncate-to-width.test.ts b/packages/tui/test/truncate-to-width.test.ts
index 42d93ffa6a..f9a110c2a5 100644
--- a/packages/tui/test/truncate-to-width.test.ts
+++ b/packages/tui/test/truncate-to-width.test.ts
@@ -8,7 +8,13 @@ describe("truncateToWidth", () => {
const truncated = truncateToWidth(text, 40, "…");
assert.ok(visibleWidth(truncated) <= 40);
- assert.strictEqual(truncated.endsWith("…\x1b[0m"), true);
+ assert.strictEqual(truncated.endsWith("…"), true);
+ assert.doesNotMatch(truncated, /\x1b\[0m/);
+ });
+
+ it("does not add ANSI resets when truncating plain text", () => {
+ assert.strictEqual(truncateToWidth("abcdef", 4, ""), "abcd");
+ assert.strictEqual(truncateToWidth("abcdef", 4, "…"), "abc…");
});
it("preserves ANSI styling for kept text and resets before and after ellipsis", () => {
@@ -27,9 +33,9 @@ describe("truncateToWidth", () => {
assert.ok(visibleWidth(truncated) <= 20);
});
- it("clips wide ellipsis safely and brackets it with resets", () => {
+ it("clips wide ellipsis safely without adding resets to plain text", () => {
assert.strictEqual(truncateToWidth("abcdef", 1, "🙂"), "");
- assert.strictEqual(truncateToWidth("abcdef", 2, "🙂"), "\x1b[0m🙂\x1b[0m");
+ assert.strictEqual(truncateToWidth("abcdef", 2, "🙂"), "🙂");
assert.ok(visibleWidth(truncateToWidth("abcdef", 2, "🙂")) <= 2);
});
@@ -51,7 +57,7 @@ describe("truncateToWidth", () => {
it("keeps a contiguous prefix instead of skipping a wide grapheme and resuming later", () => {
const truncated = truncateToWidth("🙂\t界 \x1b_abc\x07", 7, "…", true);
- assert.strictEqual(truncated, "🙂\t\x1b[0m…\x1b[0m ");
+ assert.strictEqual(truncated, "🙂\t… ");
});
});