From 3b5779ba8e07e8b30d93672b72a73ee84376bd6c Mon Sep 17 00:00:00 2001 From: grapedge Date: Wed, 25 Nov 2026 12:33:31 -0800 Subject: [PATCH 01/10] feat(pi-tui): support instance keybindings, openSearch, and arrow navigation labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Allow TuiAltScreen instances to override viewport and search keybindings without mutating the global singleton, add idempotent TuiAltScreen.openSearch(query?) with Input.moveCursorToEnd(), show semantic arrow navigation labels (↑ Previous / ↓ Next), defer search shortcuts to focused non-search overlays and non-scroll layout roots, and normalize Kitty Caps Lock + Ctrl letter sequences. --- packages/pi-tui/UPSTREAM.md | 12 + packages/pi-tui/src/alt-screen-search.ts | 49 ++- packages/pi-tui/src/components/input.ts | 5 + packages/pi-tui/src/keys.ts | 8 +- packages/pi-tui/src/tui-alt-screen.ts | 63 +++- packages/pi-tui/test/input.test.ts | 21 ++ packages/pi-tui/test/keys.test.ts | 11 + packages/pi-tui/test/tui-alt-screen.test.ts | 327 ++++++++++++++++++++ 8 files changed, 468 insertions(+), 28 deletions(-) diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index fcdfc3a9be8..9c6a45160a8 100644 --- a/packages/pi-tui/UPSTREAM.md +++ b/packages/pi-tui/UPSTREAM.md @@ -246,3 +246,15 @@ Each card: **decision** and **why not in the app**. Status is `keep` or `absorbe **Decision:** `requestAnimationFrame` and `cancelAnimationFrame` on the TUI work like the browser's. A request runs once; every callback of a frame gets the same timestamp on the `performance.now()` clock; frames are never replayed after a late wake. By default they land on a fixed `ANIMATION_FRAME_INTERVAL_MS` grid. `setAnimationFrameRate` on `TuiBase` takes a whole number of frames per second from 1 to `MAX_ANIMATION_FRAME_RATE` and throws `RangeError` on anything else; after it, the next frame comes one new interval after the last frame. One unref'd timer serves all requests and exists only while a request is pending. A throwing callback does not stop the other callbacks or later frames, and the first error is rethrown in a microtask. `stop()` pauses frames and keeps the requests; `start()` resumes on the next frame. An optional constructor clock lets tests drive frames by hand. Without one, each scheduler keeps the global timers and `performance.now` it found when it was created, so a running frame chain never moves onto fake timers that a later test installs. With no requests, behavior matches upstream. **Why not in the app:** Pausing and resuming must follow the renderer's own `stop()` and `start()`, which hosts such as the external editor call directly. One clock in the renderer also lets every animated component share one timer and one frame time. The host sets the frame rate there for the same reason: the timer and the grid belong to the renderer, and no component sees the others' requests. + +### alt-screen-instance-keybindings-and-open-search — keep + +**Decision:** `TuiAltScreenOptions` accepts an optional per-instance `keybindings` manager (falling back dynamically to global `getKeybindings()`), which `TuiAltScreen` and `AltScreenSearchComponent` use for viewport and search key matching and navigation labels. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search and optionally prefills a single-line sanitized query with the cursor placed at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and only opens search when the active layout has a searchable scroll view, so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Defaults match upstream when no instance keybindings are passed. + +**Why not in the app:** Search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`; mutating the process-wide global keybindings singleton leaks across TUI modes and tests. + +### kitty-caps-lock-ctrl-letter-normalization — keep + +**Decision:** When Kitty CSI-u input reports an uppercase Latin letter (`A`–`Z`) with Caps Lock and Ctrl active (without Shift), key matching and `parseKey` normalize the letter identity to lowercase so `ctrl+` bindings match while plain Caps Lock uppercase text input stays unaffected. + +**Why not in the app:** `TuiAltScreen` and `KeybindingsManager` dispatch viewport and search bindings directly through `keys.ts` before any app component input handler runs. diff --git a/packages/pi-tui/src/alt-screen-search.ts b/packages/pi-tui/src/alt-screen-search.ts index 17fd1103396..4cf62781740 100644 --- a/packages/pi-tui/src/alt-screen-search.ts +++ b/packages/pi-tui/src/alt-screen-search.ts @@ -1,5 +1,6 @@ import { Input } from "./components/input.ts"; -import { getKeybindings } from "./keybindings.ts"; +import { getKeybindings, type KeybindingsManager } from "./keybindings.ts"; +import type { KeyId } from "./keys.ts"; import type { Component, Focusable, TuiMouseEvent, TuiMouseEventResult } from "./tui.ts"; import { getGraphemeSegmenter, stripTerminalSequences, truncateToWidth, visibleWidth } from "./utils.ts"; @@ -194,6 +195,24 @@ export function getAltScreenSearchMatchKey(match: AltScreenSearchMatch): string return first && last ? `${first.row}:${first.startCol}:${last.row}:${last.endCol}` : ""; } +function formatKey(key: KeyId | undefined): string { + return key + ? key + .split("+") + .map((part) => { + if (process.platform === "darwin" && part.toLowerCase() === "alt") return "Option"; + return part.charAt(0).toUpperCase() + part.slice(1); + }) + .join("+") + : "Unbound"; +} + +function formatSearchNavigationLabel(direction: -1 | 1, key: KeyId | undefined): string { + if (direction === -1 && key?.toLowerCase() === "up") return "↑ Previous"; + if (direction === 1 && key?.toLowerCase() === "down") return "↓ Next"; + return `${direction < 0 ? "↑" : "↓"} ${formatKey(key)}`; +} + export class AltScreenSearchComponent implements Component, Focusable { private readonly input = new Input({ prompt: " ", @@ -202,6 +221,7 @@ export class AltScreenSearchComponent implements Component, Focusable { }); private readonly onQueryChange: (query: string) => void; private readonly navigationButtonStyle: (text: string, hovered: boolean) => string; + private readonly keybindings?: KeybindingsManager; private resultCount = 0; private resultIndex = -1; private previousButtonStart = -1; @@ -215,9 +235,11 @@ export class AltScreenSearchComponent implements Component, Focusable { constructor( onQueryChange: (query: string) => void, navigationButtonStyle: (text: string, hovered: boolean) => string = (text) => text, + keybindings?: KeybindingsManager, ) { this.onQueryChange = onQueryChange; this.navigationButtonStyle = navigationButtonStyle; + this.keybindings = keybindings; } get focused(): boolean { @@ -229,6 +251,11 @@ export class AltScreenSearchComponent implements Component, Focusable { this.input.focused = value; } + setQuery(query: string): void { + this.input.setValue(query); + this.input.moveCursorToEnd(); + } + setResult(index: number, count: number): void { this.resultIndex = index; this.resultCount = count; @@ -274,21 +301,9 @@ export class AltScreenSearchComponent implements Component, Focusable { render(width: number): string[] { const safeWidth = Math.max(1, width); 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 keybindings = this.keybindings ?? getKeybindings(); const query = this.input.getValue(); - const result = !query + const result = !query.trim() ? "" : this.resultCount === 0 ? "No matches" @@ -302,8 +317,8 @@ export class AltScreenSearchComponent implements Component, Focusable { const inputPadding = " ".repeat(Math.max(0, inputWidth - visibleWidth(inputLine))); const content = `${inputLine}${inputPadding}${resultText}`; - let previousButton = `↑ ${previousKey}`; - let nextButton = `↓ ${nextKey}`; + let previousButton = formatSearchNavigationLabel(-1, keybindings.getKeys("tui.altScreen.searchPrevious")[0]); + let nextButton = formatSearchNavigationLabel(1, keybindings.getKeys("tui.altScreen.searchNext")[0]); let separator = " · "; const outerGapWidth = 1; const availableControlsWidth = Math.max(0, innerWidth - outerGapWidth * 2 - 1); diff --git a/packages/pi-tui/src/components/input.ts b/packages/pi-tui/src/components/input.ts index d4872975b51..0cd2ad12e7b 100644 --- a/packages/pi-tui/src/components/input.ts +++ b/packages/pi-tui/src/components/input.ts @@ -68,6 +68,11 @@ export class Input implements Component, Focusable { this.cursor = Math.min(this.cursor, value.length); } + moveCursorToEnd(): void { + this.lastAction = null; + this.cursor = this.value.length; + } + handleInput(data: string): void { // Handle bracketed paste mode // Start of paste: \x1b[200~ diff --git a/packages/pi-tui/src/keys.ts b/packages/pi-tui/src/keys.ts index 37ef33cc6b1..34fd296edcf 100644 --- a/packages/pi-tui/src/keys.ts +++ b/packages/pi-tui/src/keys.ts @@ -300,7 +300,8 @@ const MODIFIERS = { super: 8, } as const; -const LOCK_MASK = 64 + 128; // Caps Lock + Num Lock +const CAPS_LOCK_BIT = 64; +const LOCK_MASK = CAPS_LOCK_BIT + 128; // Caps Lock + Num Lock const CODEPOINTS = { escape: 27, @@ -380,7 +381,10 @@ function normalizeKittyFunctionalCodepoint(codepoint: number): number { function normalizeShiftedLetterIdentityCodepoint(codepoint: number, modifier: number): number { const effectiveModifier = modifier & ~LOCK_MASK; - if ((effectiveModifier & MODIFIERS.shift) !== 0 && codepoint >= 65 && codepoint <= 90) { + const normalizeUppercaseLetter = + (effectiveModifier & MODIFIERS.shift) !== 0 || + ((modifier & CAPS_LOCK_BIT) !== 0 && (effectiveModifier & MODIFIERS.ctrl) !== 0); + if (normalizeUppercaseLetter && codepoint >= 65 && codepoint <= 90) { return codepoint + 32; } return codepoint; diff --git a/packages/pi-tui/src/tui-alt-screen.ts b/packages/pi-tui/src/tui-alt-screen.ts index c4650cbc4b1..cdcfcf4d2d3 100644 --- a/packages/pi-tui/src/tui-alt-screen.ts +++ b/packages/pi-tui/src/tui-alt-screen.ts @@ -6,7 +6,7 @@ import { } from "./alt-screen-search.ts"; import { AltScreenFlashContainer } from "./components/alt-screen-flash.ts"; import { ScrollView } from "./components/scroll-view.ts"; -import { getKeybindings } from "./keybindings.ts"; +import { getKeybindings, type KeybindingsManager } from "./keybindings.ts"; import { isKeyRelease } from "./keys.ts"; import { getLayoutBoxesAt, @@ -168,6 +168,10 @@ interface SearchHighlightRange { current: boolean; } +function sanitizeSearchQuery(query: string): string { + return query.replace(/\r\n|[\r\n\t]/g, " "); +} + export interface TuiAltScreenOptions { /** * Logical lines moved for each mouse-wheel event (default: 1). `"auto"` accelerates fast wheel @@ -184,6 +188,8 @@ export interface TuiAltScreenOptions { searchCurrentMatchStyle?: (text: string) => string; /** Style a transcript search navigation button. */ searchNavigationButtonStyle?: (text: string, hovered: boolean) => string; + /** Keybindings for alternate-screen viewport navigation and search. Defaults to global keybindings. */ + keybindings?: KeybindingsManager; /** * Render a clickable jump-to-end label. It is centered on the last row of a follow-end * primary scroll view while that view is scrolled away from its end. @@ -267,6 +273,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { private readonly searchMatchStyle: (text: string) => string; private readonly searchCurrentMatchStyle: (text: string) => string; private readonly searchNavigationButtonStyle: (text: string, hovered: boolean) => string; + private readonly keybindings?: KeybindingsManager; private readonly scrollToEndIndicator?: () => string; private readonly openUrl?: (url: string) => void; private readonly onRightClickPaste?: () => void; @@ -295,6 +302,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { 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.keybindings = options.keybindings; this.scrollToEndIndicator = options.scrollToEndIndicator; this.openUrl = options.openUrl; this.onRightClickPaste = options.onRightClickPaste; @@ -394,6 +402,10 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { return this.currentLayout?.primaryScrollView ?? this.implicitScrollView; } + private hasSearchableScrollView(): boolean { + return this.layoutRoot === undefined || this.currentLayout?.primaryScrollView !== undefined; + } + protected override beforeTerminalStart(): void { this.stopSelectionAutoScroll(); this.selectionPressActive = false; @@ -579,19 +591,38 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { } } - private toggleSearch(): void { - if (this.activeSearch) { - this.closeSearch(); + /** Open and focus transcript search, optionally pre-filling a single-line query. */ + openSearch(query?: string): void { + const sanitized = query === undefined ? undefined : sanitizeSearchQuery(query); + const existing = this.activeSearch; + if (existing) { + if (existing.overlay?.isHidden()) existing.overlay.setHidden(false); + existing.overlay?.focus(); + if (sanitized !== undefined) { + existing.component.setQuery(sanitized); + if (sanitized !== existing.query) { + existing.query = sanitized; + existing.component.setResult(-1, 0); + } + existing.anchorRow = this.getPrimaryScrollView().scrollTop; + existing.selectionMode = "query"; + } + this.requestRender(); return; } + const component = new AltScreenSearchComponent( - (query) => this.updateSearchQuery(query), + (nextQuery) => this.updateSearchQuery(nextQuery), this.searchNavigationButtonStyle, + this.keybindings, ); + if (sanitized !== undefined) { + component.setQuery(sanitized); + } const search: ActiveSearch = { component, index: new AltScreenSearchIndex(), - query: "", + query: sanitized ?? "", matches: [], selectedIndex: -1, anchorRow: this.getPrimaryScrollView().scrollTop, @@ -604,6 +635,15 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { minWidth: 32, margin: 1, }); + this.requestRender(); + } + + private toggleSearch(): void { + if (this.activeSearch) { + this.closeSearch(); + return; + } + this.openSearch(); } private closeSearch(): void { @@ -733,10 +773,14 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { this.flashes.flash(message, durationMs); } + private isNonSearchOverlayFocused(): boolean { + return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true; + } + /** Focused overlays and components that capture viewport input receive viewport keys instead of the transcript. */ private shouldDeferViewportInput(): boolean { if (this.getFocusedComponent()?.capturesViewportInput) return true; - return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true; + return this.isNonSearchOverlayFocused(); } private clearComponentMouseGesture(): void { @@ -803,13 +847,14 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { } if (this.isMouseSequence(data)) return { consume: true }; - const keybindings = getKeybindings(); + const keybindings = this.keybindings ?? getKeybindings(); const isRelease = isKeyRelease(data); + if (this.isNonSearchOverlayFocused()) return undefined; // When the primary scroll view has nothing to scroll (short content, or a // full-screen component mounted as the layout root), let navigation keys // fall through to the focused component instead of consuming them. const primaryScrollable = this.getPrimaryScrollView().canScroll; - if (keybindings.matches(data, "tui.altScreen.search")) { + if (keybindings.matches(data, "tui.altScreen.search") && (this.activeSearch || this.hasSearchableScrollView())) { if (!isRelease) this.toggleSearch(); return { consume: true }; } diff --git a/packages/pi-tui/test/input.test.ts b/packages/pi-tui/test/input.test.ts index e1f3f81726f..bcdc13a5eaf 100644 --- a/packages/pi-tui/test/input.test.ts +++ b/packages/pi-tui/test/input.test.ts @@ -34,6 +34,27 @@ describe("Input component", () => { assert.strictEqual(input.getValue(), "\\x"); }); + it("moves cursor to the end for ASCII and multi-byte text without changing setValue clamping", () => { + const preserved = new Input(); + preserved.setValue("hello"); + preserved.handleInput("\x7f"); + assert.strictEqual(preserved.getValue(), "hello"); + + const ascii = new Input(); + ascii.setValue("hello"); + ascii.moveCursorToEnd(); + ascii.handleInput("\x7f"); + assert.strictEqual(ascii.getValue(), "hell"); + + const unicode = new Input(); + unicode.setValue("你好🙂"); + unicode.moveCursorToEnd(); + unicode.handleInput("\x7f"); + assert.strictEqual(unicode.getValue(), "你好"); + unicode.handleInput("\x7f"); + assert.strictEqual(unicode.getValue(), "你"); + }); + describe("render", () => { it("supports a custom prompt and styled placeholder", () => { const input = new Input({ diff --git a/packages/pi-tui/test/keys.test.ts b/packages/pi-tui/test/keys.test.ts index 4494508e10f..f2a428281dd 100644 --- a/packages/pi-tui/test/keys.test.ts +++ b/packages/pi-tui/test/keys.test.ts @@ -671,5 +671,16 @@ describe("parseKey", () => { it("should parse double bracket pageUp", () => { assert.strictEqual(parseKey("\x1b[[5~"), "pageUp"); }); + + it("should match and parse Kitty Ctrl+letter sequences with Caps Lock active", () => { + assert.strictEqual(matchesKey("\x1b[70;69u", "ctrl+f"), true); + assert.strictEqual(parseKey("\x1b[70;69u"), "ctrl+f"); + assert.strictEqual(matchesKey("\x1b[71;69u", "ctrl+g"), true); + assert.strictEqual(parseKey("\x1b[71;69u"), "ctrl+g"); + assert.strictEqual(matchesKey("\x1b[70;69u", "ctrl+shift+f"), false); + assert.strictEqual(matchesKey("\x1b[70;70u", "ctrl+shift+f"), true); + assert.strictEqual(matchesKey("\x1b[70;71u", "ctrl+alt+f"), true); + assert.strictEqual(matchesKey("\x1b[70;65u", "f"), false); + }); }); }); diff --git a/packages/pi-tui/test/tui-alt-screen.test.ts b/packages/pi-tui/test/tui-alt-screen.test.ts index fb9b4adc051..16b79f74546 100644 --- a/packages/pi-tui/test/tui-alt-screen.test.ts +++ b/packages/pi-tui/test/tui-alt-screen.test.ts @@ -958,6 +958,257 @@ describe("TuiAltScreen", () => { assert.ok(!populated.some((line) => line.includes("Find in transcript"))); }); + it("formats custom arrow search controls, handles narrow fallback, and suppresses whitespace no-matches", () => { + const changes: string[] = []; + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], + "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], + }); + const component = new AltScreenSearchComponent((query) => changes.push(query), undefined, keybindings); + const wide = component.render(48).map((line) => stripTerminalSequences(line)); + const wideControls = wide[2] ?? ""; + assert.match(wideControls, /^└─+ ↑ Previous · ↓ Next ─┘$/); + assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("↑")), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("Previous") + 4), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("·")), undefined); + assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("↓")), 1); + assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("Next") + 2), 1); + + const narrow = component.render(20).map((line) => stripTerminalSequences(line)); + const narrowControls = narrow[2] ?? ""; + assert.match(narrowControls, /^└─+ ↑ ↓ ─┘$/); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑")), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑") + 1), undefined); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↓")), 1); + + const reversedKeybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.searchPrevious": "down", + "tui.altScreen.searchNext": "up", + }); + const reversed = new AltScreenSearchComponent(() => {}, undefined, reversedKeybindings); + const reversedLines = reversed.render(48).map((line) => stripTerminalSequences(line)); + assert.match(reversedLines[2] ?? "", /^└─+ ↑ Down · ↓ Up ─┘$/); + + component.setQuery(" "); + component.setResult(-1, 0); + assert.deepStrictEqual(changes, []); + const whitespaceLines = component.render(48).map((line) => stripTerminalSequences(line)); + assert.ok(!whitespaceLines.some((line) => line.includes("No matches"))); + + component.setQuery("missing"); + component.setResult(-1, 0); + const missingLines = component.render(48).map((line) => stripTerminalSequences(line)); + assert.ok(missingLines.some((line) => line.includes("No matches"))); + }); + + it("uses instance keybindings for search toggling and navigation without mutating global keybindings", async () => { + const globalSearchBefore = getKeybindings().getKeys("tui.altScreen.search"); + const globalPrevBefore = getKeybindings().getKeys("tui.altScreen.searchPrevious"); + const globalNextBefore = getKeybindings().getKeys("tui.altScreen.searchNext"); + + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], + "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], + "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], + }); + const terminal = new VirtualTerminal(100, 6); + const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + tui.addChild(new Text("needle one\nmiddle\nneedle two\nend", 0, 0)); + tui.start(); + try { + await terminal.waitForRender(); + + terminal.sendInput("\x06"); + terminal.sendInput("needle"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("1/2"))); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + terminal.sendInput("\x1b[B"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("2/2"))); + + terminal.sendInput("\x1b[A"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("1/2"))); + + terminal.sendInput("\x06"); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + terminal.sendInput("\x1b[102;6u"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + terminal.sendInput("\x1b[102;6u"); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.search"), globalSearchBefore); + assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.searchPrevious"), globalPrevBefore); + assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.searchNext"), globalNextBefore); + } finally { + tui.stop(); + } + }); + + it("opens search empty or prefilled with cursor at end via openSearch", async () => { + const terminal = new VirtualTerminal(80, 6); + const tui = new TuiAltScreen(terminal); + tui.addChild( + new Text( + [ + "line 1", + "line 2 needl short", + "line 3", + "line 4", + "line 5 needle one", + "line 6", + "line 7", + "line 8", + "line 9", + "line 10 needle two", + "line 11", + "line 12", + ].join("\n"), + 0, + 0, + ), + ); + tui.start(); + try { + await terminal.waitForRender(); + + tui.openSearch(); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("Find in transcript"))); + + terminal.sendInput("\x1b"); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + + tui.openSearch("needle"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("needle") && line.includes("2/2"))); + + terminal.sendInput("\x7f"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("needl ") && line.includes("3/3"))); + } finally { + tui.stop(); + } + }); + + it("refocuses, replaces, recenters same queries, and sanitizes multiline queries in openSearch", async () => { + const terminal = new RecordingTerminal(80, 6); + const tui = new TuiAltScreen(terminal); + const transcript = new ScrollView( + new Text( + [ + "line 1", + "line 2 needle one", + "line 3 alpha target", + "line 4", + "line 5", + "line 6", + "quick", + "brown", + "fox end", + "line 10", + "line 11", + "line 12", + "line 13 needle two", + "line 14", + "line 15", + ].join("\n"), + 0, + 0, + ), + { follow: "end", primary: true }, + ); + const editorInputs: string[] = []; + const editor = { + focused: false, + render: () => ["editor"], + invalidate: () => {}, + handleInput: (data: string) => editorInputs.push(data), + }; + tui.setLayoutRoot( + new VStack([ + { component: transcript, basis: 0, grow: 1, minSize: 1 }, + { component: editor, basis: 1, shrink: 0 }, + ]), + ); + tui.setFocus(editor); + tui.start(); + try { + await terminal.waitForRender(); + + tui.openSearch("needle"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("needle") && line.includes("2/2"))); + + tui.setFocus(null); + tui.setFocus(editor); + terminal.sendInput("z"); + assert.deepStrictEqual(editorInputs, ["z"]); + + tui.openSearch(); + await terminal.waitForRender(); + assert.notStrictEqual(tui.getFocusedComponent(), editor); + assert.ok(terminal.getViewport().some((line) => line.includes("needle") && line.includes("2/2"))); + terminal.sendInput("\x07"); + await terminal.waitForRender(); + assert.deepStrictEqual(editorInputs, ["z"]); + assert.ok(terminal.getViewport().some((line) => line.includes("1/2"))); + terminal.sendInput("\x1b[103;6u"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("2/2"))); + + tui.scrollToTop(); + await terminal.waitForRender(); + assert.strictEqual(transcript.scrollTop, 0); + assert.ok(terminal.getViewport().some((line) => line.includes("2/2"))); + + const sameQueryEventCount = terminal.events.length; + tui.openSearch("needle"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("1/2"))); + assert.ok(terminal.getViewport().some((line) => line.includes("line 2 needle one"))); + assert.ok( + terminal.events + .slice(sameQueryEventCount) + .every((event) => event.type !== "write" || !event.data.includes("No matches")), + ); + + tui.openSearch("alpha"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("alpha") && line.includes("1/1"))); + assert.ok(terminal.getViewport().some((line) => line.includes("line 3 alpha target"))); + + tui.scrollToBottom(); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("line 3 alpha target"))); + + const recenterEventCount = terminal.events.length; + tui.openSearch("alpha"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("alpha") && line.includes("1/1"))); + assert.ok(terminal.getViewport().some((line) => line.includes("line 3 alpha target"))); + assert.ok( + terminal.events + .slice(recenterEventCount) + .every((event) => event.type !== "write" || !event.data.includes("No matches")), + ); + + tui.openSearch("quick\r\nbrown\nfox\tend"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("quick brown fox end") && line.includes("1/1"))); + } finally { + tui.stop(); + } + }); + it("navigates transcript search with hoverable arrow buttons and toggles it with its shortcut", async () => { const terminal = new RecordingTerminal(120, 6); const tui = new TuiAltScreen(terminal, undefined, undefined, { @@ -2743,4 +2994,80 @@ describe("TuiAltScreen", () => { assert.ok(tui.viewportTop < topWithoutMenu); tui.stop(); }); + + it("defers search shortcut to a focused non-search overlay", async () => { + const terminal = new VirtualTerminal(60, 8); + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], + }); + const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + tui.addChild(new Text("alpha\nbeta\ngamma", 0, 0)); + const overlay = new InputOverlay(); + tui.start(); + await terminal.waitForRender(); + + const handle = tui.showOverlay(overlay); + await terminal.waitForRender(); + assert.strictEqual(overlay.focused, true); + + terminal.sendInput("\x06"); + await terminal.waitForRender(); + assert.deepStrictEqual(overlay.inputs, ["\x06"]); + assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + + handle.hide(); + await terminal.waitForRender(); + terminal.sendInput("\x06"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("Find in transcript"))); + tui.stop(); + }); + + it("defers search shortcut when layoutRoot has no scroll view but keeps search for short scrollable layouts", async () => { + const terminal = new VirtualTerminal(60, 8); + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], + }); + const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const takeover = new InputOverlay(); + tui.setLayoutRoot(takeover); + tui.setFocus(takeover); + tui.start(); + await terminal.waitForRender(); + + terminal.sendInput("\x06"); + await terminal.waitForRender(); + assert.deepStrictEqual(takeover.inputs, ["\x06"]); + assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + + const shortScrollView = new ScrollView(new Text("short alpha line", 0, 0), { primary: true }); + tui.setLayoutRoot(new VStack([{ component: shortScrollView, flex: 1 }])); + await terminal.waitForRender(); + assert.strictEqual(shortScrollView.canScroll, false); + + terminal.sendInput("\x06"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("Find in transcript"))); + tui.stop(); + }); + + it("opens and closes search with Kitty Ctrl+F when Caps Lock is active", async () => { + const terminal = new VirtualTerminal(60, 8); + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], + }); + const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + tui.addChild(new Text("alpha\nbeta", 0, 0)); + tui.start(); + await terminal.waitForRender(); + + terminal.sendInput("\x1b[70;69u"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("Find in transcript"))); + + terminal.sendInput("\x1b[70;69u"); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + tui.stop(); + }); }); From c9acb3561c5a00afabd34f48c0f65f8b59a6142f Mon Sep 17 00:00:00 2001 From: grapedge Date: Wed, 25 Nov 2026 12:33:31 -0800 Subject: [PATCH 02/10] feat(tui): use Ctrl+F for fullscreen search and add fullscreen /find command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bind fullscreen transcript search to Ctrl+F (retaining Ctrl+Shift+F) and match navigation to ↑/↓ via per-instance keybindings, add fullscreen-only /find [query] command hidden in regular mode, unify host slash-command resolution with runtime tuiMode, and show Ctrl-F in fullscreen /help. --- apps/kimi-code/src/tui/commands/dispatch.ts | 25 +-- apps/kimi-code/src/tui/commands/registry.ts | 36 ++- apps/kimi-code/src/tui/commands/resolve.ts | 48 +++- apps/kimi-code/src/tui/commands/types.ts | 7 +- .../src/tui/components/dialogs/help-panel.ts | 3 + .../kimi-code/src/tui/constant/keybindings.ts | 7 + .../src/tui/controllers/editor-keyboard.ts | 16 +- apps/kimi-code/src/tui/kimi-tui.ts | 21 +- apps/kimi-code/src/tui/tui-state.ts | 4 + apps/kimi-code/test/tui/commands/find.test.ts | 205 ++++++++++++++++++ .../test/tui/commands/registry.test.ts | 36 ++- .../test/tui/commands/resolve.test.ts | 101 ++++++++- .../tui/components/panels/help-panel.test.ts | 33 +++ .../test/tui/create-tui-state.test.ts | 154 ++++++++++++- 14 files changed, 638 insertions(+), 58 deletions(-) create mode 100644 apps/kimi-code/src/tui/constant/keybindings.ts create mode 100644 apps/kimi-code/test/tui/commands/find.test.ts diff --git a/apps/kimi-code/src/tui/commands/dispatch.ts b/apps/kimi-code/src/tui/commands/dispatch.ts index 0dfb545ed67..9fb8096b0c6 100644 --- a/apps/kimi-code/src/tui/commands/dispatch.ts +++ b/apps/kimi-code/src/tui/commands/dispatch.ts @@ -1,4 +1,4 @@ -import type { Component, Focusable } from '@moonshot-ai/pi-tui'; +import { TuiAltScreen, type Component, type Focusable } from '@moonshot-ai/pi-tui'; import type { DeviceAuthorization } from '@moonshot-ai/kimi-code-oauth'; import type { ReverseRpcModalOwner } from '../reverse-rpc/modal-coordinator'; @@ -59,7 +59,7 @@ import { handleReloadCommand, handleReloadTuiCommand } from './reload'; import type { SkillListSession } from './skills'; import { canRestoreSubmittedInput, - resolveUserInput, + resolveHostUserInput, type SlashCommandIntent, slashBusyMessage, slashCommandBusyReason, @@ -207,19 +207,7 @@ export function dispatchInput( text: string, delivery: FollowUpDelivery = 'default', ): void { - const { intent, activations } = resolveUserInput({ - input: text, - skillCommandMap: host.skillCommandMap, - pluginCommandMap: host.pluginCommandMap, - isStreaming: host.state.appState.streamingPhase !== 'idle', - isCompacting: host.state.appState.isCompacting, - skillVariantPathForCommand: host.skillVariantPathForCommand === undefined - ? undefined - : (commandName, tokenStart) => host.skillVariantPathForCommand!(commandName, tokenStart), - defaultSkillPathForCommand: host.defaultSkillPathForCommand === undefined - ? undefined - : (commandName) => host.defaultSkillPathForCommand!(commandName), - }); + const { intent, activations } = resolveHostUserInput(host, text); if (intent.kind === 'skill' || (activations.length > 0 && intent.kind !== 'builtin')) { const leading = activations[0]; if (intent.kind === 'skill' && leading?.args !== undefined && host.state.appState.model.trim().length > 0) { @@ -373,6 +361,13 @@ async function handleBuiltInSlashCommand( case 'help': host.showHelpPanel(); return; + case 'find': { + if (host.state.ui instanceof TuiAltScreen) { + const query = args.trim(); + host.state.ui.openSearch(query.length > 0 ? query : undefined); + } + return; + } case 'version': host.showStatus(`Kimi Code v${host.state.appState.version}`); return; diff --git a/apps/kimi-code/src/tui/commands/registry.ts b/apps/kimi-code/src/tui/commands/registry.ts index 3ff9c965d59..fb1cb9a749f 100644 --- a/apps/kimi-code/src/tui/commands/registry.ts +++ b/apps/kimi-code/src/tui/commands/registry.ts @@ -2,9 +2,10 @@ import { readdirSync, statSync } from 'node:fs'; import { homedir } from 'node:os'; import { basename, dirname, join, relative, resolve } from 'pathe'; -import type { AutocompleteItem } from '@moonshot-ai/pi-tui'; +import type { AutocompleteItem, TuiMode } from '@moonshot-ai/pi-tui'; import { completeLeadingArg, type ArgCompletionSpec } from './complete-args'; +import { isExperimentalFlagEnabled } from './experimental-flags'; import type { KimiSlashCommand, SlashCommandAvailability } from './types'; const GOAL_ARG_COMPLETIONS: readonly ArgCompletionSpec[] = [ @@ -236,6 +237,15 @@ export const BUILTIN_SLASH_COMMANDS = [ priority: 80, availability: 'always', }, + { + name: 'find', + aliases: [], + description: 'Search the conversation', + priority: 80, + argumentHint: '[query]', + availability: 'always', + visible: ({ tuiMode }) => tuiMode === 'fullscreen', + }, { name: 'new', aliases: ['clear'], @@ -465,6 +475,16 @@ export const BUILTIN_SLASH_COMMANDS = [ export type BuiltinSlashCommand = (typeof BUILTIN_SLASH_COMMANDS)[number]; export type BuiltinSlashCommandName = BuiltinSlashCommand['name']; +export function isSlashCommandVisible( + command: Pick, + tuiMode: TuiMode, +): boolean { + return ( + isExperimentalFlagEnabled(command.experimentalFlag) && + (command.visible?.({ tuiMode }) ?? true) + ); +} + export function findBuiltInSlashCommand(commandName: string): BuiltinSlashCommand | undefined { const commands = BUILTIN_SLASH_COMMANDS as readonly KimiSlashCommand[]; return commands.find( @@ -472,6 +492,20 @@ export function findBuiltInSlashCommand(commandName: string): BuiltinSlashComman ) as BuiltinSlashCommand | undefined; } +export function findVisibleBuiltInSlashCommand( + commandName: string, + tuiMode: TuiMode, +): BuiltinSlashCommand | undefined { + const command = findBuiltInSlashCommand(commandName); + return command !== undefined && isSlashCommandVisible(command, tuiMode) ? command : undefined; +} + +export function getVisibleBuiltInSlashCommands(tuiMode: TuiMode): KimiSlashCommand[] { + return sortSlashCommands( + BUILTIN_SLASH_COMMANDS.filter((command) => isSlashCommandVisible(command, tuiMode)), + ); +} + export function resolveSlashCommandAvailability( command: KimiSlashCommand, args: string, diff --git a/apps/kimi-code/src/tui/commands/resolve.ts b/apps/kimi-code/src/tui/commands/resolve.ts index 9d884482a68..68c0bd36858 100644 --- a/apps/kimi-code/src/tui/commands/resolve.ts +++ b/apps/kimi-code/src/tui/commands/resolve.ts @@ -1,16 +1,16 @@ +import type { TuiMode } from '@moonshot-ai/pi-tui'; + import { - findBuiltInSlashCommand, + findVisibleBuiltInSlashCommand, resolveSlashCommandAvailability, type BuiltinSlashCommand, type BuiltinSlashCommandName, } from './registry'; -import { isExperimentalFlagEnabled } from './experimental-flags'; import { parseSlashInput } from './parse'; import type { TUIState } from '../tui-state'; import type { InlineSkillActivation } from '../types'; import { extractInlineSkillActivations, findInlineSkillTokens } from '../utils/inline-skill-tokens'; import type { - KimiSlashCommand, ParsedSlashInput, SlashCommandBusyReason, SlashCommandInvalidReason, @@ -55,6 +55,7 @@ export interface ResolveSlashCommandInput { readonly pluginCommandMap: ReadonlyMap; readonly isStreaming: boolean; readonly isCompacting: boolean; + readonly tuiMode?: TuiMode; readonly skillVariantPathForCommand?: (commandName: string, tokenStart: number) => string | undefined; readonly defaultSkillPathForCommand?: (commandName: string) => string | undefined; } @@ -63,11 +64,8 @@ export function resolveSlashCommandInput(options: ResolveSlashCommandInput): Sla const parsed = parseSlashInput(options.input); if (parsed === null) return { kind: 'not-command' }; - const command = findBuiltInSlashCommand(parsed.name); - if ( - command !== undefined && - isExperimentalFlagEnabled((command as KimiSlashCommand).experimentalFlag) - ) { + const command = findVisibleBuiltInSlashCommand(parsed.name, options.tuiMode ?? 'regular'); + if (command !== undefined) { const busyReason = slashCommandBusyReason(options); if ( busyReason !== undefined && @@ -172,6 +170,40 @@ export function resolveUserInput(options: ResolveSlashCommandInput): { return { intent, activations: selectedActivations }; } +export interface SlashCommandResolutionHost { + readonly state: { + readonly appState: Pick; + readonly ui?: Partial>; + }; + readonly skillCommandMap: ReadonlyMap; + readonly pluginCommandMap: ReadonlyMap; + readonly skillVariantPathForCommand?: (commandName: string, tokenStart: number) => string | undefined; + readonly defaultSkillPathForCommand?: (commandName: string) => string | undefined; +} + +export function resolveHostUserInput( + host: SlashCommandResolutionHost, + input: string, + overrides?: Partial>, +): ReturnType { + return resolveUserInput({ + input, + skillCommandMap: host.skillCommandMap, + pluginCommandMap: host.pluginCommandMap, + isStreaming: overrides?.isStreaming ?? host.state.appState.streamingPhase !== 'idle', + isCompacting: overrides?.isCompacting ?? host.state.appState.isCompacting, + tuiMode: overrides?.tuiMode ?? host.state.ui?.mode, + skillVariantPathForCommand: + host.skillVariantPathForCommand === undefined + ? undefined + : (commandName, tokenStart) => host.skillVariantPathForCommand!(commandName, tokenStart), + defaultSkillPathForCommand: + host.defaultSkillPathForCommand === undefined + ? undefined + : (commandName) => host.defaultSkillPathForCommand!(commandName), + }); +} + export function resolveSkillCommand( skillCommandMap: ReadonlyMap, commandName: string, diff --git a/apps/kimi-code/src/tui/commands/types.ts b/apps/kimi-code/src/tui/commands/types.ts index 1c254bbb6d2..78b8cb0da4f 100644 --- a/apps/kimi-code/src/tui/commands/types.ts +++ b/apps/kimi-code/src/tui/commands/types.ts @@ -1,8 +1,12 @@ -import type { AutocompleteItem, SlashCommand } from '@moonshot-ai/pi-tui'; +import type { AutocompleteItem, SlashCommand, TuiMode } from '@moonshot-ai/pi-tui'; import type { SkillSummary } from '@moonshot-ai/kimi-code-sdk'; export type SlashCommandAvailability = 'always' | 'idle-only'; +export interface SlashCommandContext { + readonly tuiMode: TuiMode; +} + export interface KimiSlashCommand extends SlashCommand { readonly name: Name; readonly aliases: readonly string[]; @@ -14,6 +18,7 @@ export interface KimiSlashCommand extends SlashCom readonly priority?: number; readonly availability?: SlashCommandAvailability | ((args: string) => SlashCommandAvailability); readonly experimentalFlag?: string; + readonly visible?: (context: SlashCommandContext) => boolean; readonly completeArgs?: (argumentPrefix: string) => AutocompleteItem[] | null; } diff --git a/apps/kimi-code/src/tui/components/dialogs/help-panel.ts b/apps/kimi-code/src/tui/components/dialogs/help-panel.ts index 0ba5b61b545..3b0f0618694 100644 --- a/apps/kimi-code/src/tui/components/dialogs/help-panel.ts +++ b/apps/kimi-code/src/tui/components/dialogs/help-panel.ts @@ -4,6 +4,7 @@ import { Key, decodeKittyPrintable, type Focusable, + type TuiMode, truncateToWidth, } from '@moonshot-ai/pi-tui'; import { @@ -34,10 +35,12 @@ const SUBMIT_DESCRIPTIONS: Readonly> = { export function keyboardShortcuts( followUpBehavior: FollowUpBehavior, ctrlEnterRecognized: boolean, + tuiMode: TuiMode = 'regular', ): readonly KeyboardShortcut[] { const submit = FOLLOW_UP_KEYMAP[followUpBehavior]; return [ { keys: 'Shift-Tab', description: 'Toggle plan mode' }, + ...(tuiMode === 'fullscreen' ? [{ keys: 'Ctrl-F', description: 'Search conversation' }] : []), { keys: 'Ctrl-G', description: 'Edit in external editor ($VISUAL / $EDITOR)' }, { keys: 'Ctrl-O', description: 'Toggle tool output / compaction summary expansion' }, { keys: 'Ctrl-S', description: 'Steer — inject a follow-up during streaming' }, diff --git a/apps/kimi-code/src/tui/constant/keybindings.ts b/apps/kimi-code/src/tui/constant/keybindings.ts new file mode 100644 index 00000000000..63036d7697a --- /dev/null +++ b/apps/kimi-code/src/tui/constant/keybindings.ts @@ -0,0 +1,7 @@ +import type { KeybindingsConfig } from '@moonshot-ai/pi-tui'; + +export const KIMI_ALT_SCREEN_KEYBINDINGS: KeybindingsConfig = { + 'tui.altScreen.search': ['ctrl+f', 'ctrl+shift+f'], + 'tui.altScreen.searchPrevious': ['up', 'shift+enter', 'ctrl+shift+g'], + 'tui.altScreen.searchNext': ['down', 'enter', 'ctrl+g'], +}; diff --git a/apps/kimi-code/src/tui/controllers/editor-keyboard.ts b/apps/kimi-code/src/tui/controllers/editor-keyboard.ts index 3dc1b020f28..640d487d850 100644 --- a/apps/kimi-code/src/tui/controllers/editor-keyboard.ts +++ b/apps/kimi-code/src/tui/controllers/editor-keyboard.ts @@ -29,7 +29,7 @@ import type { VideoAttachment, } from '../utils/image-attachment-store'; import { extractMediaAttachments, imageExtensionForMime } from '../utils/image-placeholder'; -import { resolveUserInput } from '../commands/resolve'; +import { resolveHostUserInput } from '../commands/resolve'; import type { PendingExit, QueuedMessage } from '../types'; import type { TUIState } from '../tui-state'; import type { BtwPanelController } from './btw-panel'; @@ -352,19 +352,7 @@ export class EditorKeyboardController { return; } if (extraction !== undefined) { - const { activations } = resolveUserInput({ - input: text, - skillCommandMap: host.skillCommandMap, - pluginCommandMap: host.pluginCommandMap, - isStreaming: true, - isCompacting: host.state.appState.isCompacting, - skillVariantPathForCommand: host.skillVariantPathForCommand === undefined - ? undefined - : (commandName, tokenStart) => host.skillVariantPathForCommand!(commandName, tokenStart), - defaultSkillPathForCommand: host.defaultSkillPathForCommand === undefined - ? undefined - : (commandName) => host.defaultSkillPathForCommand!(commandName), - }); + const { activations } = resolveHostUserInput(host, text, { isStreaming: true }); host.state.queuedMessages.push({ text, agentId: host.harness?.interactiveAgentId, diff --git a/apps/kimi-code/src/tui/kimi-tui.ts b/apps/kimi-code/src/tui/kimi-tui.ts index f2ce768d78a..f749d2bfe95 100644 --- a/apps/kimi-code/src/tui/kimi-tui.ts +++ b/apps/kimi-code/src/tui/kimi-tui.ts @@ -60,18 +60,17 @@ import { BannerProvider } from './banner/banner-provider'; import { resolveBannerAudienceContext, type BannerAudienceContext } from './banner/audience'; import { readBannerDisplayState, writeBannerDisplayState } from './banner/state'; import { - BUILTIN_SLASH_COMMANDS, buildPluginSlashCommands, buildSkillSlashCommands, + getVisibleBuiltInSlashCommands, goalObjectiveLengthWarning, isExperimentalFlagEnabled, setExperimentalFeatures, - sortSlashCommands, type KimiSlashCommand, type SkillListSession, } from './commands'; import * as slashCommands from './commands/dispatch'; -import { resolveUserInput, skillVariantPathsForInput } from './commands/resolve'; +import { resolveHostUserInput, skillVariantPathsForInput } from './commands/resolve'; import { applyTranscriptPresentation, runQueuedModelSwitch } from './commands/config'; import { promptSshPassword } from './commands/prompts'; import { CacheHintController } from './controllers/cache-hint-controller'; @@ -631,9 +630,7 @@ export class KimiTUI { } private getSlashCommands(): readonly KimiSlashCommand[] { - const builtins = sortSlashCommands(BUILTIN_SLASH_COMMANDS).filter((command) => - isExperimentalFlagEnabled(command.experimentalFlag), - ); + const builtins = getVisibleBuiltInSlashCommands(this.state.ui.mode); return [...builtins, ...this.skillCommands, ...this.pluginCommands]; } @@ -2043,16 +2040,7 @@ export class KimiTUI { private async persistInputHistory(text: string): Promise { const trimmed = text.trim(); if (trimmed.length === 0) return; - const activations = text.startsWith('!') ? [] : resolveUserInput({ - input: trimmed, - skillCommandMap: this.skillCommandMap, - pluginCommandMap: this.pluginCommandMap, - isStreaming: this.state.appState.streamingPhase !== 'idle', - isCompacting: this.state.appState.isCompacting, - skillVariantPathForCommand: (commandName, start) => - this.skillVariantPathForCommand(commandName, start), - defaultSkillPathForCommand: (commandName) => this.defaultSkillPathForCommand(commandName), - }).activations; + const activations = text.startsWith('!') ? [] : resolveHostUserInput(this, trimmed).activations; const entry: InputHistoryEntry = { content: trimmed, inlineSkillActivations: activations.length === 0 ? undefined : activations, @@ -5190,6 +5178,7 @@ export class KimiTUI { shortcuts: keyboardShortcuts( resolveFollowUpBehavior(this.state.appState.followUpBehavior), isKittyProtocolActive(), + this.state.ui.mode, ), onClose: () => { this.hideHelpPanel(); diff --git a/apps/kimi-code/src/tui/tui-state.ts b/apps/kimi-code/src/tui/tui-state.ts index 940d9aeb8a4..6ff740512a4 100644 --- a/apps/kimi-code/src/tui/tui-state.ts +++ b/apps/kimi-code/src/tui/tui-state.ts @@ -1,6 +1,8 @@ import { Container, + KeybindingsManager, ProcessTerminal, + TUI_KEYBINDINGS, type Component, TuiAltScreen, TuiMainScreen, @@ -23,6 +25,7 @@ import { QueuePaneComponent } from './components/panes/queue-pane'; import type { SessionRow, SessionsScope } from './components/dialogs/session-picker'; import { CustomEditor } from './components/editor/custom-editor'; import { DEFAULT_MARKDOWN_CONFIG, DEFAULT_TUI_CONFIG, resolveWheelScrollLines } from './config'; +import { KIMI_ALT_SCREEN_KEYBINDINGS } from './constant/keybindings'; import { CHROME_GUTTER, DOCK_QUEUE_ROWS, DOCK_UPDATES_ROWS } from './constant/rendering'; import { CLICK_GUARD_MS } from './constant/terminal'; import type { TasksBrowserState } from './controllers/tasks-browser'; @@ -100,6 +103,7 @@ export function createTUIState(options: KimiTUIOptions): TUIState { const fullscreen = (options.resolvedTuiMode ?? initialAppState.tuiMode) === 'fullscreen'; const ui = fullscreen ? new TuiAltScreen(terminal, undefined, undefined, { + keybindings: new KeybindingsManager(TUI_KEYBINDINGS, KIMI_ALT_SCREEN_KEYBINDINGS), openUrl, refocusMouseGuardMs: CLICK_GUARD_MS, copyOnSelect: diff --git a/apps/kimi-code/test/tui/commands/find.test.ts b/apps/kimi-code/test/tui/commands/find.test.ts new file mode 100644 index 00000000000..c412cc63edb --- /dev/null +++ b/apps/kimi-code/test/tui/commands/find.test.ts @@ -0,0 +1,205 @@ +import { Text, TuiAltScreen, type Terminal } from '@moonshot-ai/pi-tui'; +import { VirtualTerminal } from '@moonshot-ai/pi-tui/testing'; +import { describe, expect, it, vi } from 'vitest'; + +import { dispatchInput, type SlashCommandHost } from '#/tui/commands/dispatch'; +import { createTUIState, type KimiTUIOptions } from '#/tui/kimi-tui'; +import { mountFooter } from '#/tui/tui-state'; +import type { AppState } from '#/tui/types'; + +function fakeInitialAppState(tuiMode: 'regular' | 'fullscreen'): AppState { + return { + model: 'test-model', + workDir: '/tmp/kimi-test', + additionalDirs: [], + sessionId: 'sess-1', + permissionMode: 'manual', + planMode: false, + inputMode: 'prompt', + swarmMode: false, + towerMode: false, + thinkingEffort: 'off', + contextUsage: 0, + contextTokens: 0, + maxContextTokens: 0, + isCompacting: false, + isReplaying: false, + streamingPhase: 'idle', + streamingStartTime: 0, + stepRetry: null, + theme: 'dark', + version: '0.0.0-test', + editorCommand: null, + notifications: { enabled: true, condition: 'unfocused' }, + upgrade: { autoInstall: true }, + transcript: { toolCallDensity: 'compact', thinking: 'grouped' }, + availableModels: {}, + availableProviders: {}, + sessionTitle: null, + mcpServersSummary: null, + tuiMode, + }; +} + +async function mountHost( + tuiMode: 'regular' | 'fullscreen', + options: { + transcript?: string; + streamingPhase?: AppState['streamingPhase']; + isCompacting?: boolean; + skillCommandMap?: Map; + } = {}, +) { + const opts: KimiTUIOptions = { + initialAppState: { + ...fakeInitialAppState(tuiMode), + streamingPhase: options.streamingPhase ?? 'idle', + isCompacting: options.isCompacting ?? false, + }, + startup: { continueLast: false, yolo: false, auto: false, plan: false }, + }; + const state = createTUIState(opts); + const vt = new VirtualTerminal(100, 12); + (state.ui as { terminal: Terminal }).terminal = vt; + if (options.transcript !== undefined) { + state.transcriptContainer.addChild(new Text(options.transcript, 0, 0)); + } + mountFooter(state); + state.editorContainer.addChild(state.editor); + if (!(state.ui instanceof TuiAltScreen)) { + state.ui.addChild(state.transcriptContainer); + state.ui.addChild(state.editorContainer); + } + state.ui.setFocus(state.editor); + state.ui.start(); + await vt.waitForRender(); + + const host = { + state, + session: undefined, + skillCommandMap: options.skillCommandMap ?? new Map(), + pluginCommandMap: new Map(), + ensureSession: vi.fn(async () => undefined), + showError: vi.fn(), + showStatus: vi.fn(), + sendNormalUserInput: vi.fn(), + sendInlineSkillUserInput: vi.fn(async () => {}), + restoreInputText: vi.fn(), + track: vi.fn(), + } as unknown as SlashCommandHost & { + ensureSession: ReturnType; + showError: ReturnType; + sendNormalUserInput: ReturnType; + sendInlineSkillUserInput: ReturnType; + track: ReturnType; + }; + + return { host, state, vt }; +} + +describe('/find slash command dispatch', () => { + it('opens and focuses an empty search box in fullscreen mode without requiring a session', async () => { + const { host, state, vt } = await mountHost('fullscreen', { + transcript: 'needle one\nmiddle\nneedle two', + }); + try { + dispatchInput(host, '/find'); + await vt.waitForRender(); + + const viewport = vt.getViewport(); + expect(viewport.some((line) => line.includes('Find in transcript'))).toBe(true); + expect(viewport.some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(true); + expect(host.ensureSession).not.toHaveBeenCalled(); + expect(host.sendNormalUserInput).not.toHaveBeenCalled(); + expect(host.showError).not.toHaveBeenCalled(); + + vt.sendInput('needle'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('needle') && line.includes('/2'))).toBe(true); + } finally { + state.ui.stop(); + } + }); + + it('prefills the query with cursor at the end and highlights matches immediately', async () => { + const { host, state, vt } = await mountHost('fullscreen', { + transcript: 'needl short\nneedle one\nmiddle\nneedle two', + }); + try { + dispatchInput(host, '/find needle '); + await vt.waitForRender(); + + const initialViewport = vt.getViewport(); + expect(initialViewport.some((line) => line.includes('needle') && line.includes('/2'))).toBe(true); + expect(initialViewport.some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(true); + + vt.sendInput('\u007F'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('needl') && line.includes('/3'))).toBe(true); + } finally { + state.ui.stop(); + } + }); + + it('works while streaming and while compacting in fullscreen mode', async () => { + const streaming = await mountHost('fullscreen', { + transcript: 'alpha\nbeta\nalpha', + streamingPhase: 'composing', + }); + try { + dispatchInput(streaming.host, '/find alpha'); + await streaming.vt.waitForRender(); + expect(streaming.vt.getViewport().some((line) => line.includes('alpha') && line.includes('/2'))).toBe(true); + expect(streaming.host.showError).not.toHaveBeenCalled(); + } finally { + streaming.state.ui.stop(); + } + + const compacting = await mountHost('fullscreen', { + transcript: 'alpha\nbeta\nalpha', + isCompacting: true, + }); + try { + dispatchInput(compacting.host, '/find alpha'); + await compacting.vt.waitForRender(); + expect(compacting.vt.getViewport().some((line) => line.includes('alpha') && line.includes('/2'))).toBe(true); + expect(compacting.host.showError).not.toHaveBeenCalled(); + } finally { + compacting.state.ui.stop(); + } + }); + + it('passes /find through as normal input or a same-named skill in regular mode', async () => { + const regular = await mountHost('regular', { + transcript: 'needle one', + }); + try { + dispatchInput(regular.host, '/find needle'); + await regular.vt.waitForRender(); + + expect(regular.host.sendNormalUserInput).toHaveBeenCalledWith('/find needle', undefined, 'default'); + expect(regular.host.track).not.toHaveBeenCalledWith('input_command', { command: 'find' }); + expect(regular.vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(false); + } finally { + regular.state.ui.stop(); + } + + const withSkill = await mountHost('regular', { + skillCommandMap: new Map([['skill:find', 'find']]), + }); + try { + dispatchInput(withSkill.host, '/find needle'); + await withSkill.vt.waitForRender(); + + expect(withSkill.host.sendInlineSkillUserInput).toHaveBeenCalledWith( + '/find needle', + [{ skillName: 'find', path: undefined, start: 0, args: 'needle' }], + undefined, + 'default', + ); + expect(withSkill.host.sendNormalUserInput).not.toHaveBeenCalled(); + } finally { + withSkill.state.ui.stop(); + } + }); +}); diff --git a/apps/kimi-code/test/tui/commands/registry.test.ts b/apps/kimi-code/test/tui/commands/registry.test.ts index d135e0a7365..1f0962f3645 100644 --- a/apps/kimi-code/test/tui/commands/registry.test.ts +++ b/apps/kimi-code/test/tui/commands/registry.test.ts @@ -1,15 +1,19 @@ import { BUILTIN_SLASH_COMMANDS, findBuiltInSlashCommand, + findVisibleBuiltInSlashCommand, + getVisibleBuiltInSlashCommands, + isSlashCommandVisible, parseSlashInput, resolveSlashCommandAvailability, + setExperimentalFeatures, addDirArgumentCompletions, sortSlashCommands, swarmArgumentCompletions, towerArgumentCompletions, type KimiSlashCommand, } from '#/tui/commands/index'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; describe('parseSlashInput', () => { it('parses command names and trimmed args', () => { @@ -172,6 +176,7 @@ describe('built-in slash command registry', () => { 'editor', 'exit', 'export-debug-zip', + 'find', 'fork', 'help', 'import-sessions', @@ -250,4 +255,33 @@ describe('built-in slash command registry', () => { expect(resolveSlashCommandAvailability(command!, '')).toBe('always'); }); + describe('command visibility', () => { + afterEach(() => { + setExperimentalFeatures([]); + }); + + it('registers find as always available and visible only in fullscreen mode', () => { + const command = findBuiltInSlashCommand('find'); + expect(command).toBeDefined(); + expect((command as KimiSlashCommand).argumentHint).toBe('[query]'); + expect(resolveSlashCommandAvailability(command!, '')).toBe('always'); + expect(isSlashCommandVisible(command!, 'regular')).toBe(false); + expect(isSlashCommandVisible(command!, 'fullscreen')).toBe(true); + }); + + it('filters visible built-in commands by tuiMode and experimental flags', () => { + expect(findVisibleBuiltInSlashCommand('find', 'regular')).toBeUndefined(); + expect(findVisibleBuiltInSlashCommand('find', 'fullscreen')?.name).toBe('find'); + expect(getVisibleBuiltInSlashCommands('regular').map((command) => command.name)).not.toContain('find'); + expect(getVisibleBuiltInSlashCommands('fullscreen').map((command) => command.name)).toContain('find'); + + expect(findVisibleBuiltInSlashCommand('tower', 'fullscreen')).toBeUndefined(); + expect(getVisibleBuiltInSlashCommands('fullscreen').map((command) => command.name)).not.toContain('tower'); + + setExperimentalFeatures([{ id: 'tower', enabled: true }]); + expect(findVisibleBuiltInSlashCommand('tower', 'regular')?.name).toBe('tower'); + expect(getVisibleBuiltInSlashCommands('regular').map((command) => command.name)).toContain('tower'); + }); + }); + }); diff --git a/apps/kimi-code/test/tui/commands/resolve.test.ts b/apps/kimi-code/test/tui/commands/resolve.test.ts index f70c3ef303d..a69e7e3598e 100644 --- a/apps/kimi-code/test/tui/commands/resolve.test.ts +++ b/apps/kimi-code/test/tui/commands/resolve.test.ts @@ -6,7 +6,11 @@ import { } from '#/tui/commands/index'; import { afterEach, describe, expect, it } from 'vitest'; -import { resolveUserInput, skillVariantPathsForInput } from '#/tui/commands/resolve'; +import { + resolveHostUserInput, + resolveUserInput, + skillVariantPathsForInput, +} from '#/tui/commands/resolve'; function resolve( input: string, @@ -457,6 +461,101 @@ describe('resolveSlashCommandInput', () => { expect(resolve('/worktree')).toMatchObject({ kind: 'builtin', name: 'worktree' }); }); + it('hides /find in regular mode and lets it fall through to a message or same-named skill', () => { + expect(resolve('/find')).toEqual({ kind: 'message', input: '/find' }); + expect(resolve('/find needle', { tuiMode: 'regular' })).toEqual({ + kind: 'message', + input: '/find needle', + }); + + const skillCommandMap = new Map([['skill:find', 'find']]); + expect(resolve('/find needle', { tuiMode: 'regular', skillCommandMap })).toEqual({ + kind: 'skill', + commandName: 'find', + skillName: 'find', + args: 'needle', + }); + }); + + it('resolves /find as an always-available builtin in fullscreen mode', () => { + expect(resolve('/find', { tuiMode: 'fullscreen' })).toMatchObject({ + kind: 'builtin', + name: 'find', + args: '', + }); + expect(resolve('/find needle', { tuiMode: 'fullscreen' })).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + expect( + resolve('/find needle', { tuiMode: 'fullscreen', isStreaming: true }), + ).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + expect( + resolve('/find needle', { tuiMode: 'fullscreen', isCompacting: true }), + ).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + + const skillCommandMap = new Map([['skill:find', 'find']]); + expect( + resolve('/find needle', { tuiMode: 'fullscreen', skillCommandMap }), + ).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + }); + +}); + +describe('resolveHostUserInput', () => { + const makeHost = (mode?: 'regular' | 'fullscreen') => ({ + state: { + appState: { + streamingPhase: 'idle' as const, + isCompacting: false, + }, + ...(mode !== undefined ? { ui: { mode } } : {}), + }, + skillCommandMap: new Map(), + pluginCommandMap: new Map(), + }); + + it('injects tuiMode from host.state.ui.mode and defaults omitted ui to regular', () => { + expect(resolveHostUserInput(makeHost('regular'), '/find needle').intent).toEqual({ + kind: 'message', + input: '/find needle', + }); + expect(resolveHostUserInput(makeHost(undefined), '/find needle').intent).toEqual({ + kind: 'message', + input: '/find needle', + }); + expect(resolveHostUserInput(makeHost('fullscreen'), '/find needle').intent).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + }); + + it('applies streaming overrides when resolving host input', () => { + expect(resolveHostUserInput(makeHost('fullscreen'), '/new', { isStreaming: true }).intent).toEqual({ + kind: 'blocked', + commandName: 'new', + reason: 'streaming', + }); + expect(resolveHostUserInput(makeHost('fullscreen'), '/find needle', { isStreaming: true }).intent).toMatchObject({ + kind: 'builtin', + name: 'find', + args: 'needle', + }); + }); }); describe('goal command resolution', () => { diff --git a/apps/kimi-code/test/tui/components/panels/help-panel.test.ts b/apps/kimi-code/test/tui/components/panels/help-panel.test.ts index 0b0a1f0426b..8a75b6dad02 100644 --- a/apps/kimi-code/test/tui/components/panels/help-panel.test.ts +++ b/apps/kimi-code/test/tui/components/panels/help-panel.test.ts @@ -37,6 +37,39 @@ describe('HelpPanelComponent', () => { }, ); + it('includes Ctrl-F only in fullscreen mode', () => { + const regularShortcuts = keyboardShortcuts('queue', false, 'regular'); + const fullscreenShortcuts = keyboardShortcuts('queue', false, 'fullscreen'); + + expect(regularShortcuts.some((shortcut) => shortcut.keys === 'Ctrl-F')).toBe(false); + expect(fullscreenShortcuts).toContainEqual({ + keys: 'Ctrl-F', + description: 'Search conversation', + }); + + const regularOut = strip( + new HelpPanelComponent({ + commands: [], + shortcuts: regularShortcuts, + onClose: () => {}, + }) + .render(80) + .join('\n'), + ); + const fullscreenOut = strip( + new HelpPanelComponent({ + commands: [], + shortcuts: fullscreenShortcuts, + onClose: () => {}, + }) + .render(80) + .join('\n'), + ); + expect(regularOut).not.toMatch(/Ctrl-F/); + expect(fullscreenOut).toMatch(/Ctrl-F/); + expect(fullscreenOut).toMatch(/Search conversation/); + }); + it('renders keyboard shortcuts + slash commands sections', () => { const panel = new HelpPanelComponent({ commands: [cmd('exit', 'Exit', ['quit', 'q'])], diff --git a/apps/kimi-code/test/tui/create-tui-state.test.ts b/apps/kimi-code/test/tui/create-tui-state.test.ts index af3716cf038..957afcc8d59 100644 --- a/apps/kimi-code/test/tui/create-tui-state.test.ts +++ b/apps/kimi-code/test/tui/create-tui-state.test.ts @@ -1,4 +1,12 @@ -import { ScrollView, Text, TuiAltScreen, TuiMainScreen, VStack, type Terminal } from '@moonshot-ai/pi-tui'; +import { + getKeybindings, + ScrollView, + Text, + TuiAltScreen, + TuiMainScreen, + VStack, + type Terminal, +} from '@moonshot-ai/pi-tui'; import { VirtualTerminal } from '@moonshot-ai/pi-tui/testing'; import { describe, it, expect, onTestFinished, vi } from 'vitest'; @@ -7,7 +15,9 @@ import { StickyUserMessageComponent } from '#/tui/components/messages/sticky-use import { TranscriptView } from '#/tui/components/messages/transcript-view'; import type { WheelScrollLines } from '#/tui/config'; import { createTUIState, type KimiTUIOptions } from '#/tui/kimi-tui'; +import { mountFooter } from '#/tui/tui-state'; import type { AppState } from '#/tui/types'; +import { beginScreenTakeover, endScreenTakeover } from '#/tui/utils/screen-takeover'; function fakeInitialAppState(): AppState { return { @@ -240,4 +250,146 @@ describe('createTUIState', () => { expect(typeof internals.openUrl).toBe('function'); expect(typeof internals.onRightClickPaste).toBe('function'); }); + + it('injects fullscreen search keybindings without mutating global keybindings', async () => { + const state = createTUIState({ + initialAppState: { ...fakeInitialAppState(), tuiMode: 'fullscreen' }, + startup: { continueLast: false, yolo: false, auto: false, plan: false }, + }); + const vt = new VirtualTerminal(100, 12); + (state.ui as { terminal: Terminal }).terminal = vt; + state.transcriptContainer.addChild(new Text('needle one\nmiddle\nneedle two\nend', 0, 0)); + mountFooter(state); + state.editorContainer.addChild(state.editor); + state.ui.setFocus(state.editor); + state.ui.start(); + + try { + await vt.waitForRender(); + + vt.sendInput('\u0006'); + vt.sendInput('needle'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(true); + const beforeNav = vt.getViewport().find((line) => line.includes('/2')); + expect(beforeNav).toBeDefined(); + + vt.sendInput('\u001B[B'); + await vt.waitForRender(); + const afterDown = vt.getViewport().find((line) => line.includes('/2')); + expect(afterDown).toBeDefined(); + expect(afterDown).not.toBe(beforeNav); + + vt.sendInput('\u001B[A'); + await vt.waitForRender(); + const afterUp = vt.getViewport().find((line) => line.includes('/2')); + expect(afterUp).toBe(beforeNav); + + vt.sendInput('\u0006'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(false); + + vt.sendInput('\u001B[102;6u'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(true); + + vt.sendInput('\u001B[102;6u'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(false); + + expect(getKeybindings().getKeys('tui.altScreen.search')).toEqual(['ctrl+shift+f']); + expect(getKeybindings().getKeys('tui.altScreen.searchPrevious')).toEqual([ + 'shift+enter', + 'ctrl+shift+g', + ]); + expect(getKeybindings().getKeys('tui.altScreen.searchNext')).toEqual(['enter', 'ctrl+g']); + expect(getKeybindings().getKeys('tui.editor.cursorRight')).toEqual(['right', 'ctrl+f']); + } finally { + state.ui.stop(); + } + }); + + it('keeps regular mode and Ctrl+F cursor movement unaffected', async () => { + const state = createTUIState({ + initialAppState: { ...fakeInitialAppState(), tuiMode: 'regular' }, + startup: { continueLast: false, yolo: false, auto: false, plan: false }, + }); + const vt = new VirtualTerminal(100, 12); + (state.ui as { terminal: Terminal }).terminal = vt; + state.ui.addChild(state.editor); + state.ui.setFocus(state.editor); + state.ui.start(); + + try { + await vt.waitForRender(); + + vt.sendInput('ac'); + vt.sendInput('\u001B[D'); + vt.sendInput('\u0006'); + vt.sendInput('!'); + await vt.waitForRender(); + + expect(state.ui).toBeInstanceOf(TuiMainScreen); + expect(state.editor.getText()).toBe('ac!'); + expect(vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(false); + } finally { + state.ui.stop(); + } + }); + + it('lets fullscreen screen-takeover viewers receive Ctrl+F and opens search on Caps Lock Ctrl+F', async () => { + const state = createTUIState({ + initialAppState: { ...fakeInitialAppState(), tuiMode: 'fullscreen' }, + startup: { continueLast: false, yolo: false, auto: false, plan: false }, + }); + const vt = new VirtualTerminal(100, 12); + (state.ui as { terminal: Terminal }).terminal = vt; + state.transcriptContainer.addChild(new Text('needle line', 0, 0)); + mountFooter(state); + state.editorContainer.addChild(state.editor); + state.ui.setFocus(state.editor); + state.ui.start(); + + try { + await vt.waitForRender(); + + vt.sendInput('ab'); + vt.sendInput('\u001B[D'); + vt.sendInput('\u001B[70;69u'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(true); + expect(state.editor.getCursor().col).toBe(1); + + vt.sendInput('\u001B[70;69u'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(false); + + const viewerInputs: string[] = []; + const takeoverViewer = { + handleInput: (data: string) => { + viewerInputs.push(data); + }, + render: () => ['takeover viewer'], + invalidate: () => {}, + }; + const takeover = beginScreenTakeover(state.ui, takeoverViewer); + state.ui.setFocus(takeoverViewer); + await vt.waitForRender(); + + vt.sendInput('\u0006'); + await vt.waitForRender(); + expect(viewerInputs).toEqual(['\u0006']); + expect(vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(false); + + endScreenTakeover(state.ui, takeover); + state.ui.setFocus(state.editor); + await vt.waitForRender(); + + vt.sendInput('\u0006'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('Find in transcript'))).toBe(true); + } finally { + state.ui.stop(); + } + }); }); From c4053b5001eac44ef0ff9daa44e35ec9517420a1 Mon Sep 17 00:00:00 2001 From: grapedge Date: Wed, 25 Nov 2026 12:33:32 -0800 Subject: [PATCH 03/10] docs: document fullscreen Ctrl+F search, /find command, and add changesets Document Ctrl-F and /find [] in English and Chinese reference pages and add changesets for @moonshot-ai/pi-tui and @moonshot-ai/kimi-code. --- .changeset/fullscreen-search-cli.md | 5 +++++ .changeset/fullscreen-search-pi-tui.md | 5 +++++ docs/en/reference/keyboard.md | 1 + docs/en/reference/slash-commands.md | 1 + docs/zh/reference/keyboard.md | 1 + docs/zh/reference/slash-commands.md | 1 + 6 files changed, 14 insertions(+) create mode 100644 .changeset/fullscreen-search-cli.md create mode 100644 .changeset/fullscreen-search-pi-tui.md diff --git a/.changeset/fullscreen-search-cli.md b/.changeset/fullscreen-search-cli.md new file mode 100644 index 00000000000..09f2789b0c0 --- /dev/null +++ b/.changeset/fullscreen-search-cli.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": minor +--- + +Switch fullscreen conversation search to `Ctrl+F` (keeping `Ctrl+Shift+F`), add `↑` and `↓` navigation between matches, and add the `/find` slash command in fullscreen mode. Run `/find` or `/find ` to search the conversation. In fullscreen mode, `Ctrl+F` now opens search instead of moving the editor cursor right; use `→` to move right or switch to regular mode to keep the previous `Ctrl+F` cursor movement. diff --git a/.changeset/fullscreen-search-pi-tui.md b/.changeset/fullscreen-search-pi-tui.md new file mode 100644 index 00000000000..9e59f7600c4 --- /dev/null +++ b/.changeset/fullscreen-search-pi-tui.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/pi-tui": minor +--- + +Support per-instance keybindings and programmatic transcript search opening with optional query prefill in alternate-screen mode, add end-of-line cursor positioning for single-line inputs, display `↑ Previous` and `↓ Next` labels when search navigation uses arrow keys, defer search shortcuts to focused overlays and non-scroll layout roots, and normalize Kitty Caps Lock + Ctrl letter sequences. diff --git a/docs/en/reference/keyboard.md b/docs/en/reference/keyboard.md index b3173f0a36f..80d4c89d5d9 100644 --- a/docs/en/reference/keyboard.md +++ b/docs/en/reference/keyboard.md @@ -14,6 +14,7 @@ The following keys are always available in the input box: | `Esc` | Close a popup / cancel completion / interrupt streaming output or context compaction | | `Ctrl-C` | Interrupt the current streaming output, or clear the input box | | `Ctrl-D` | Exit Kimi Code CLI when the input box is empty | +| `Ctrl-F` | Open the search box to search the conversation in fullscreen mode | | `Ctrl-N` | Focus the experimental `Updates` panel, including while an approval or question waits | | `Tab` / `→` | Insert the full experimental prompt prediction when a suggestion is shown in an empty input box | diff --git a/docs/en/reference/slash-commands.md b/docs/en/reference/slash-commands.md index 826f64e7400..d721c17b7d3 100644 --- a/docs/en/reference/slash-commands.md +++ b/docs/en/reference/slash-commands.md @@ -43,6 +43,7 @@ Some commands are only available in the idle state. Executing these commands whi | `/export-debug-zip` | — | Export the current session as a debug ZIP archive (same behavior as [`kimi export`](./kimi-command.md#kimi-export)) | No | | `/import-sessions` | — | Import Claude Code and Codex sessions from the last 15 or 30 days as regular sessions (same behavior as [`kimi import-sessions`](./kimi-command.md#kimi-import-sessions)) | No | | `/copy` | — | Copy the last assistant message to the clipboard | No | +| `/find []` | — | Search the current conversation in fullscreen mode | Yes | | `/add-dir []` | — | Add an extra workspace directory to the current session. Run without a path (or with `list`) to list configured directories. When adding, choose whether to remember the directory in the workspace registry | No | | `/web` | — | Open the current session in the web UI: pick a running server to connect to, or start a new foreground server after the TUI exits. See [`kimi web`](./kimi-command.md#kimi-web) | Yes | | `/desktop` | `/install-desktop` | Open the Kimi Code desktop app page in your browser (URL follows the active region: `https://www.kimi.com/code` or `https://www.kimi.ai/code`). See [`kimi install-desktop`](./kimi-command.md#kimi-install-desktop) | Yes | diff --git a/docs/zh/reference/keyboard.md b/docs/zh/reference/keyboard.md index 990028448bd..e0150ff7199 100644 --- a/docs/zh/reference/keyboard.md +++ b/docs/zh/reference/keyboard.md @@ -14,6 +14,7 @@ Kimi Code CLI 的 TUI 交互模式支持一套键盘快捷键。键位按使用 | `Esc` | 关闭弹窗 / 取消补全 / 中断流式输出或上下文压缩 | | `Ctrl-C` | 中断当前流式输出,或清空输入框 | | `Ctrl-D` | 在输入框为空时退出 Kimi Code CLI | +| `Ctrl-F` | 在全屏模式下唤起搜索框,搜索对话内容 | | `Ctrl-N` | 聚焦实验性 `Updates` 面板,审批或提问等待时也可用 | | `Tab` / `→` | 空输入框中显示实验性提示词预测时,填入完整建议 | diff --git a/docs/zh/reference/slash-commands.md b/docs/zh/reference/slash-commands.md index 4062fee1b0b..4246bafce9e 100644 --- a/docs/zh/reference/slash-commands.md +++ b/docs/zh/reference/slash-commands.md @@ -43,6 +43,7 @@ | `/export-debug-zip` | — | 将当前会话导出为调试用 ZIP 压缩包(与 [`kimi export`](./kimi-command.md#kimi-export) 行为一致) | 否 | | `/import-sessions` | — | 将最近 15 天或 30 天的 Claude Code 和 Codex 会话导入为普通会话(与 [`kimi import-sessions`](./kimi-command.md#kimi-import-sessions) 行为一致) | 否 | | `/copy` | — | 将最后一条 AI 回复复制到剪贴板 | 否 | +| `/find []` | — | 在全屏模式下搜索当前对话内容 | 是 | | `/add-dir []` | — | 为当前会话添加额外的工作目录。不带路径(或传入 `list`)运行时列出已配置的目录。添加时可选择是否将目录记入工作区注册表(持久保留) | 否 | | `/web` | — | 在 web UI 中打开当前会话:选择一个运行中的实例进行连接,或在 TUI 退出后新开一个前台服务器。参见 [`kimi web`](./kimi-command.md#kimi-web) | 是 | | `/desktop` | `/install-desktop` | 在浏览器中打开 Kimi Code 桌面端页面(地址随当前区域而定:`https://www.kimi.com/code` 或 `https://www.kimi.ai/code`)。参见 [`kimi install-desktop`](./kimi-command.md#kimi-install-desktop) | 是 | From 98fbfac28c6e6caf96da1de7f3611b3c0e1a87b0 Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 01:13:04 -0800 Subject: [PATCH 04/10] fix(pi-tui): close active search when mouse focus moves to another component Close active transcript search before transferring mouse focus to a component outside the search overlay so keyboard input goes directly to the clicked target instead of being reclaimed by overlay focus restore, while keeping scroll, selection, and search-box clicks open. --- .changeset/fullscreen-search-pi-tui.md | 2 +- packages/pi-tui/UPSTREAM.md | 2 +- packages/pi-tui/src/tui-alt-screen.ts | 7 ++- packages/pi-tui/test/tui-alt-screen.test.ts | 55 +++++++++++++++++++++ 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/.changeset/fullscreen-search-pi-tui.md b/.changeset/fullscreen-search-pi-tui.md index 9e59f7600c4..77ba50e781e 100644 --- a/.changeset/fullscreen-search-pi-tui.md +++ b/.changeset/fullscreen-search-pi-tui.md @@ -2,4 +2,4 @@ "@moonshot-ai/pi-tui": minor --- -Support per-instance keybindings and programmatic transcript search opening with optional query prefill in alternate-screen mode, add end-of-line cursor positioning for single-line inputs, display `↑ Previous` and `↓ Next` labels when search navigation uses arrow keys, defer search shortcuts to focused overlays and non-scroll layout roots, and normalize Kitty Caps Lock + Ctrl letter sequences. +Support per-instance keybindings and programmatic transcript search opening with optional query prefill in alternate-screen mode, add end-of-line cursor positioning for single-line inputs, display `↑ Previous` and `↓ Next` labels when search navigation uses arrow keys, defer search shortcuts to focused overlays and non-scroll layout roots, close active search when mouse focus moves to another component, and normalize Kitty Caps Lock + Ctrl letter sequences. diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index 9c6a45160a8..63360583aac 100644 --- a/packages/pi-tui/UPSTREAM.md +++ b/packages/pi-tui/UPSTREAM.md @@ -249,7 +249,7 @@ Each card: **decision** and **why not in the app**. Status is `keep` or `absorbe ### alt-screen-instance-keybindings-and-open-search — keep -**Decision:** `TuiAltScreenOptions` accepts an optional per-instance `keybindings` manager (falling back dynamically to global `getKeybindings()`), which `TuiAltScreen` and `AltScreenSearchComponent` use for viewport and search key matching and navigation labels. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search and optionally prefills a single-line sanitized query with the cursor placed at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and only opens search when the active layout has a searchable scroll view, so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Defaults match upstream when no instance keybindings are passed. +**Decision:** `TuiAltScreenOptions` accepts an optional per-instance `keybindings` manager (falling back dynamically to global `getKeybindings()`), which `TuiAltScreen` and `AltScreenSearchComponent` use for viewport and search key matching and navigation labels. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search and optionally prefills a single-line sanitized query with the cursor placed at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and only opens search when the active layout has a searchable scroll view, so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Clicking a focusable component outside the search overlay closes active transcript search before transferring focus so keyboard input goes directly to the clicked target instead of being reclaimed by overlay focus restore, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. Defaults match upstream when no instance keybindings are passed. **Why not in the app:** Search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`; mutating the process-wide global keybindings singleton leaks across TUI modes and tests. diff --git a/packages/pi-tui/src/tui-alt-screen.ts b/packages/pi-tui/src/tui-alt-screen.ts index cdcfcf4d2d3..57654051e5e 100644 --- a/packages/pi-tui/src/tui-alt-screen.ts +++ b/packages/pi-tui/src/tui-alt-screen.ts @@ -982,7 +982,12 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { private applyMouseDispatchResult(event: TuiMouseEvent, result: TuiMouseDispatchResult): boolean { const focusTarget = this.resolveMouseFocusTarget(result.focusTarget ?? result.target.component); const focusChanged = result.focus === true && this.getFocusedComponent() !== focusTarget; - if (result.focus) this.setFocus(focusTarget); + if (result.focus) { + if (this.activeSearch && focusTarget !== this.activeSearch.component) { + this.closeSearch(); + } + this.setFocus(focusTarget); + } if (result.capture) this.mouseCapture = result.target; return ( result.render ?? diff --git a/packages/pi-tui/test/tui-alt-screen.test.ts b/packages/pi-tui/test/tui-alt-screen.test.ts index 16b79f74546..585a2b2b33c 100644 --- a/packages/pi-tui/test/tui-alt-screen.test.ts +++ b/packages/pi-tui/test/tui-alt-screen.test.ts @@ -3070,4 +3070,59 @@ describe("TuiAltScreen", () => { assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); tui.stop(); }); + + it("closes active search when clicking a focusable editor while keeping search open on scroll, selection, and search-box clicks", async () => { + const terminal = new VirtualTerminal(80, 12); + const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], + "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], + "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], + }); + const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const scrollView = new ScrollView( + new Text(Array.from({ length: 20 }, (_, index) => `alpha line ${index + 1}`).join("\n"), 0, 0), + { primary: true }, + ); + const editor = new Editor(tui, defaultEditorTheme); + tui.setLayoutRoot(new VStack([{ component: scrollView, flex: 1 }, { component: editor }])); + tui.setFocus(editor); + tui.start(); + await terminal.waitForRender(); + + tui.openSearch("alpha"); + await terminal.waitForRender(); + assert.strictEqual(editor.focused, false); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + terminal.sendInput("\x1b[<64;5;3M"); + terminal.sendInput("\x1b[<0;2;2M"); + terminal.sendInput("\x1b[<32;6;2M"); + terminal.sendInput("\x1b[<0;6;2m"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + const searchRow = terminal.getViewport().findIndex((line) => line.includes("alpha") && line.includes("/20")); + assert.ok(searchRow >= 0); + const searchCol = terminal.getViewport()[searchRow]!.indexOf("alpha") + 1; + terminal.sendInput(`\x1b[<0;${searchCol};${searchRow + 1}M`); + terminal.sendInput(`\x1b[<0;${searchCol};${searchRow + 1}m`); + terminal.sendInput("x"); + await terminal.waitForRender(); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + assert.strictEqual(editor.getText(), ""); + + const editorRow = 11; + terminal.sendInput(`\x1b[<0;5;${editorRow}M`); + terminal.sendInput(`\x1b[<0;5;${editorRow}m`); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + assert.strictEqual(editor.focused, true); + assert.strictEqual(tui.getFocusedComponent(), editor); + + terminal.sendInput("hello"); + await terminal.waitForRender(); + assert.strictEqual(editor.getText(), "hello"); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + tui.stop(); + }); }); From 4adf299c14a7829904d5b26959b55db360714afb Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 01:13:08 -0800 Subject: [PATCH 05/10] fix(tui): preserve cursor marker and line width with slash argument hints Update CustomEditor argument hint injection to anchor after FAKE_CURSOR_END and measure trailing padding with visibleWidth so hardware cursor and IME positioning remain intact and lines do not overflow; skip APC cursor markers during slash token highlighting. --- .changeset/fullscreen-search-cli.md | 2 +- .../tui/components/editor/custom-editor.ts | 24 ++++++----- .../components/editor/custom-editor.test.ts | 19 +++++++++ .../test/tui/create-tui-state.test.ts | 40 +++++++++++++++++++ 4 files changed, 74 insertions(+), 11 deletions(-) diff --git a/.changeset/fullscreen-search-cli.md b/.changeset/fullscreen-search-cli.md index 09f2789b0c0..eb1d6c651dd 100644 --- a/.changeset/fullscreen-search-cli.md +++ b/.changeset/fullscreen-search-cli.md @@ -2,4 +2,4 @@ "@moonshot-ai/kimi-code": minor --- -Switch fullscreen conversation search to `Ctrl+F` (keeping `Ctrl+Shift+F`), add `↑` and `↓` navigation between matches, and add the `/find` slash command in fullscreen mode. Run `/find` or `/find ` to search the conversation. In fullscreen mode, `Ctrl+F` now opens search instead of moving the editor cursor right; use `→` to move right or switch to regular mode to keep the previous `Ctrl+F` cursor movement. +Switch fullscreen conversation search to `Ctrl+F` (keeping `Ctrl+Shift+F`), add `↑` and `↓` navigation between matches, close search when clicking back into the input box, add the `/find` slash command in fullscreen mode, and fix missing cursor and IME positioning when slash command argument hints are shown. Run `/find` or `/find ` to search the conversation. In fullscreen mode, `Ctrl+F` now opens search instead of moving the editor cursor right; use `→` to move right or switch to regular mode to keep the previous `Ctrl+F` cursor movement. diff --git a/apps/kimi-code/src/tui/components/editor/custom-editor.ts b/apps/kimi-code/src/tui/components/editor/custom-editor.ts index bce1fa0ca0f..737f72357cb 100644 --- a/apps/kimi-code/src/tui/components/editor/custom-editor.ts +++ b/apps/kimi-code/src/tui/components/editor/custom-editor.ts @@ -21,7 +21,7 @@ import { extractAtPrefix } from './file-mention-provider'; import { findInlineSkillTokens } from '../../utils/inline-skill-tokens'; import { WrappingSelectList } from './wrapping-select-list'; -const ANSI_SGR = /\u001B\[[0-9;]*m/g; +const ANSI_NON_VISIBLE = /\u001B\[[0-9;]*m|\u001B_[^\u0007\u001B]*(?:\u0007|\u001B\\)/g; const PASTE_MARKER_RE = /\[paste #(\d+)(?: (?:\+\d+ lines|\d+ chars))?\]/g; const BRACKET_PASTE_START = '\u001B[200~'; @@ -72,7 +72,7 @@ export function normalizeCapsLockedCtrl(data: string): string { function mapVisibleIdxToRaw(line: string, visibleIdx: number): number { let visibleCount = 0; let i = 0; - const re = new RegExp(ANSI_SGR.source, 'y'); + const re = new RegExp(ANSI_NON_VISIBLE.source, 'y'); while (i < line.length && visibleCount < visibleIdx) { re.lastIndex = i; const m = re.exec(line); @@ -87,7 +87,7 @@ function mapVisibleIdxToRaw(line: string, visibleIdx: number): number { } function stripSgr(s: string): string { - return s.replace(ANSI_SGR, ''); + return s.replace(ANSI_NON_VISIBLE, ''); } function alternateSubmitKey(data: string): Exclude | undefined { @@ -673,18 +673,22 @@ function injectArgumentHint( realTextLength: number, width: number, ): string { - const cursorIdx = line.indexOf(CURSOR_BLOCK); - const cursorPresent = cursorIdx !== -1; + const fakeCursorEnd = line.indexOf(FAKE_CURSOR_END); + const legacyCursorIdx = line.indexOf(CURSOR_BLOCK); + const cursorPresent = fakeCursorEnd !== -1 || legacyCursorIdx !== -1; const contentWidth = Math.max(1, width - EDITOR_LEFT_PADDING * 2); const available = contentWidth - realTextLength - (cursorPresent ? 1 : 0); const trimmed = truncateHint(hint, available); if (trimmed.length === 0) return line; const colored = currentTheme.fg('textDim', trimmed); - const insertAt = cursorPresent - ? cursorIdx + CURSOR_BLOCK.length - : mapVisibleIdxToRaw(line, EDITOR_LEFT_PADDING + realTextLength); - const trailing = line.length - insertAt; - return line.slice(0, insertAt) + colored + ' '.repeat(Math.max(0, trailing - trimmed.length)); + const insertAt = fakeCursorEnd !== -1 + ? fakeCursorEnd + FAKE_CURSOR_END.length + : legacyCursorIdx !== -1 + ? legacyCursorIdx + CURSOR_BLOCK.length + : mapVisibleIdxToRaw(line, EDITOR_LEFT_PADDING + realTextLength); + const trailing = line.slice(insertAt); + const remaining = Math.max(0, visibleWidth(trailing) - visibleWidth(trimmed)); + return line.slice(0, insertAt) + colored + ' '.repeat(remaining); } function truncateHint(hint: string, maxLen: number): string { diff --git a/apps/kimi-code/test/tui/components/editor/custom-editor.test.ts b/apps/kimi-code/test/tui/components/editor/custom-editor.test.ts index dcca706d508..a139ae74117 100644 --- a/apps/kimi-code/test/tui/components/editor/custom-editor.test.ts +++ b/apps/kimi-code/test/tui/components/editor/custom-editor.test.ts @@ -380,6 +380,25 @@ describe('CustomEditor slash argument hint', () => { expect(plain).toContain('[list] | '); }); + it('preserves hardware cursor marker, fake cursor, and exact line width with an argument hint', () => { + const editor = makeEditor(); + editor.focused = true; + editor.setArgumentHints(new Map([['find', '[query]']])); + + for (const input of ['/find', '/find ']) { + editor.setText(input); + const rendered = editor.render(60); + const contentLine = rendered[1] ?? ''; + + expect(rendered.every((line) => visibleWidth(line) === 60)).toBe(true); + expect(contentLine).toContain(CURSOR_MARKER); + expect(contentLine).toContain(`${FAKE_CURSOR_START} ${FAKE_CURSOR_END}`); + const markerIdx = contentLine.indexOf(CURSOR_MARKER); + expect(visibleWidth(contentLine.slice(0, markerIdx))).toBe(4 + input.length); + expect(contentLine.indexOf(FAKE_CURSOR_END)).toBeLessThan(contentLine.indexOf('[query]')); + } + }); + it('hides the hint once an argument is typed', () => { const editor = makeEditor(); editor.setArgumentHints(new Map([['add-dir', '[list] | ']])); diff --git a/apps/kimi-code/test/tui/create-tui-state.test.ts b/apps/kimi-code/test/tui/create-tui-state.test.ts index 957afcc8d59..aa7964c0fb1 100644 --- a/apps/kimi-code/test/tui/create-tui-state.test.ts +++ b/apps/kimi-code/test/tui/create-tui-state.test.ts @@ -392,4 +392,44 @@ describe('createTUIState', () => { state.ui.stop(); } }); + + it('closes fullscreen search and routes typing to the editor when clicking the editor', async () => { + const state = createTUIState({ + initialAppState: { ...fakeInitialAppState(), tuiMode: 'fullscreen' }, + startup: { continueLast: false, yolo: false, auto: false, plan: false }, + }); + const vt = new VirtualTerminal(100, 12); + (state.ui as { terminal: Terminal }).terminal = vt; + state.transcriptContainer.addChild(new Text('needle line one\nmiddle\nneedle line two', 0, 0)); + mountFooter(state); + state.editorContainer.addChild(state.editor); + state.ui.setFocus(state.editor); + state.ui.start(); + + try { + await vt.waitForRender(); + + vt.sendInput('\u0006'); + vt.sendInput('needle'); + await vt.waitForRender(); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(true); + expect(state.editor.focused).toBe(false); + + const editorRow = vt.getViewport().findIndex((line) => line.includes('>')); + expect(editorRow).toBeGreaterThanOrEqual(0); + vt.sendInput(`\u001B[<0;6;${editorRow + 1}M`); + vt.sendInput(`\u001B[<0;6;${editorRow + 1}m`); + await vt.waitForRender(); + + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(false); + expect(state.editor.focused).toBe(true); + + vt.sendInput('hello'); + await vt.waitForRender(); + expect(state.editor.getText()).toBe('hello'); + expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(false); + } finally { + state.ui.stop(); + } + }); }); From 79cf589e76aa92904d201bd1287e2b196d29f05f Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 04:13:33 -0800 Subject: [PATCH 06/10] refactor(pi-tui): unify fullscreen search defaults in TUI_KEYBINDINGS and tighten search/keys guards --- .changeset/fullscreen-search-pi-tui.md | 2 +- .../kimi-code/src/tui/constant/keybindings.ts | 7 - apps/kimi-code/src/tui/tui-state.ts | 4 - .../test/tui/create-tui-state.test.ts | 7 +- packages/pi-tui/UPSTREAM.md | 12 +- packages/pi-tui/src/alt-screen-search.ts | 7 +- packages/pi-tui/src/keybindings.ts | 6 +- packages/pi-tui/src/keys.ts | 14 +- packages/pi-tui/src/tui-alt-screen.ts | 16 +- packages/pi-tui/test/keybindings.test.ts | 6 +- packages/pi-tui/test/keys.test.ts | 6 +- packages/pi-tui/test/tui-alt-screen.test.ts | 174 +++++++++--------- 12 files changed, 119 insertions(+), 142 deletions(-) delete mode 100644 apps/kimi-code/src/tui/constant/keybindings.ts diff --git a/.changeset/fullscreen-search-pi-tui.md b/.changeset/fullscreen-search-pi-tui.md index 77ba50e781e..58a9d9e74a8 100644 --- a/.changeset/fullscreen-search-pi-tui.md +++ b/.changeset/fullscreen-search-pi-tui.md @@ -2,4 +2,4 @@ "@moonshot-ai/pi-tui": minor --- -Support per-instance keybindings and programmatic transcript search opening with optional query prefill in alternate-screen mode, add end-of-line cursor positioning for single-line inputs, display `↑ Previous` and `↓ Next` labels when search navigation uses arrow keys, defer search shortcuts to focused overlays and non-scroll layout roots, close active search when mouse focus moves to another component, and normalize Kitty Caps Lock + Ctrl letter sequences. +Default alternate-screen transcript search to `Ctrl+F` (keeping `Ctrl+Shift+F`) and match navigation to `↑`/`↓` with `↑ Previous · ↓ Next` labels, add programmatic `openSearch(query?)` and single-line end-of-line cursor positioning, defer search shortcuts to focused overlays and non-scroll layout roots, close active search when non-wheel mouse focus moves to another component, and normalize Kitty Caps Lock modified letter sequences. diff --git a/apps/kimi-code/src/tui/constant/keybindings.ts b/apps/kimi-code/src/tui/constant/keybindings.ts deleted file mode 100644 index 63036d7697a..00000000000 --- a/apps/kimi-code/src/tui/constant/keybindings.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { KeybindingsConfig } from '@moonshot-ai/pi-tui'; - -export const KIMI_ALT_SCREEN_KEYBINDINGS: KeybindingsConfig = { - 'tui.altScreen.search': ['ctrl+f', 'ctrl+shift+f'], - 'tui.altScreen.searchPrevious': ['up', 'shift+enter', 'ctrl+shift+g'], - 'tui.altScreen.searchNext': ['down', 'enter', 'ctrl+g'], -}; diff --git a/apps/kimi-code/src/tui/tui-state.ts b/apps/kimi-code/src/tui/tui-state.ts index 6ff740512a4..940d9aeb8a4 100644 --- a/apps/kimi-code/src/tui/tui-state.ts +++ b/apps/kimi-code/src/tui/tui-state.ts @@ -1,8 +1,6 @@ import { Container, - KeybindingsManager, ProcessTerminal, - TUI_KEYBINDINGS, type Component, TuiAltScreen, TuiMainScreen, @@ -25,7 +23,6 @@ import { QueuePaneComponent } from './components/panes/queue-pane'; import type { SessionRow, SessionsScope } from './components/dialogs/session-picker'; import { CustomEditor } from './components/editor/custom-editor'; import { DEFAULT_MARKDOWN_CONFIG, DEFAULT_TUI_CONFIG, resolveWheelScrollLines } from './config'; -import { KIMI_ALT_SCREEN_KEYBINDINGS } from './constant/keybindings'; import { CHROME_GUTTER, DOCK_QUEUE_ROWS, DOCK_UPDATES_ROWS } from './constant/rendering'; import { CLICK_GUARD_MS } from './constant/terminal'; import type { TasksBrowserState } from './controllers/tasks-browser'; @@ -103,7 +100,6 @@ export function createTUIState(options: KimiTUIOptions): TUIState { const fullscreen = (options.resolvedTuiMode ?? initialAppState.tuiMode) === 'fullscreen'; const ui = fullscreen ? new TuiAltScreen(terminal, undefined, undefined, { - keybindings: new KeybindingsManager(TUI_KEYBINDINGS, KIMI_ALT_SCREEN_KEYBINDINGS), openUrl, refocusMouseGuardMs: CLICK_GUARD_MS, copyOnSelect: diff --git a/apps/kimi-code/test/tui/create-tui-state.test.ts b/apps/kimi-code/test/tui/create-tui-state.test.ts index aa7964c0fb1..244d6e772cd 100644 --- a/apps/kimi-code/test/tui/create-tui-state.test.ts +++ b/apps/kimi-code/test/tui/create-tui-state.test.ts @@ -251,7 +251,7 @@ describe('createTUIState', () => { expect(typeof internals.onRightClickPaste).toBe('function'); }); - it('injects fullscreen search keybindings without mutating global keybindings', async () => { + it('supports Ctrl+F, Ctrl+Shift+F, and Up/Down search navigation in fullscreen mode', async () => { const state = createTUIState({ initialAppState: { ...fakeInitialAppState(), tuiMode: 'fullscreen' }, startup: { continueLast: false, yolo: false, auto: false, plan: false }, @@ -297,12 +297,13 @@ describe('createTUIState', () => { await vt.waitForRender(); expect(vt.getViewport().some((line) => line.includes('↑ Previous · ↓ Next'))).toBe(false); - expect(getKeybindings().getKeys('tui.altScreen.search')).toEqual(['ctrl+shift+f']); + expect(getKeybindings().getKeys('tui.altScreen.search')).toEqual(['ctrl+f', 'ctrl+shift+f']); expect(getKeybindings().getKeys('tui.altScreen.searchPrevious')).toEqual([ + 'up', 'shift+enter', 'ctrl+shift+g', ]); - expect(getKeybindings().getKeys('tui.altScreen.searchNext')).toEqual(['enter', 'ctrl+g']); + expect(getKeybindings().getKeys('tui.altScreen.searchNext')).toEqual(['down', 'enter', 'ctrl+g']); expect(getKeybindings().getKeys('tui.editor.cursorRight')).toEqual(['right', 'ctrl+f']); } finally { state.ui.stop(); diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index 63360583aac..ee3378e847d 100644 --- a/packages/pi-tui/UPSTREAM.md +++ b/packages/pi-tui/UPSTREAM.md @@ -247,14 +247,14 @@ Each card: **decision** and **why not in the app**. Status is `keep` or `absorbe **Why not in the app:** Pausing and resuming must follow the renderer's own `stop()` and `start()`, which hosts such as the external editor call directly. One clock in the renderer also lets every animated component share one timer and one frame time. The host sets the frame rate there for the same reason: the timer and the grid belong to the renderer, and no component sees the others' requests. -### alt-screen-instance-keybindings-and-open-search — keep +### alt-screen-search-bindings-and-open-search — keep -**Decision:** `TuiAltScreenOptions` accepts an optional per-instance `keybindings` manager (falling back dynamically to global `getKeybindings()`), which `TuiAltScreen` and `AltScreenSearchComponent` use for viewport and search key matching and navigation labels. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search and optionally prefills a single-line sanitized query with the cursor placed at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and only opens search when the active layout has a searchable scroll view, so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Clicking a focusable component outside the search overlay closes active transcript search before transferring focus so keyboard input goes directly to the clicked target instead of being reclaimed by overlay focus restore, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. Defaults match upstream when no instance keybindings are passed. +**Decision:** Default alternate-screen search keybindings in `TUI_KEYBINDINGS` use `["ctrl+f", "ctrl+shift+f"]` for `tui.altScreen.search`, `["up", "shift+enter", "ctrl+shift+g"]` for `tui.altScreen.searchPrevious`, and `["down", "enter", "ctrl+g"]` for `tui.altScreen.searchNext`. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search (when the active layout has a searchable scroll view) and optionally prefills a single-line sanitized query with the cursor at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and requires a searchable scroll view so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Non-wheel mouse focus transfers to a component outside the search overlay close active transcript search before moving focus, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. -**Why not in the app:** Search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`; mutating the process-wide global keybindings singleton leaks across TUI modes and tests. +**Why not in the app:** Default keybindings live in `TUI_KEYBINDINGS` shared by all `pi-tui` components; search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, mouse focus dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`. -### kitty-caps-lock-ctrl-letter-normalization — keep +### kitty-caps-lock-modified-letter-normalization — keep -**Decision:** When Kitty CSI-u input reports an uppercase Latin letter (`A`–`Z`) with Caps Lock and Ctrl active (without Shift), key matching and `parseKey` normalize the letter identity to lowercase so `ctrl+` bindings match while plain Caps Lock uppercase text input stays unaffected. +**Decision:** When Kitty CSI-u input reports an uppercase Latin letter (`A`–`Z`) with Caps Lock and any non-lock modifier (`ctrl`, `alt`, `super`, or `shift`) active, key matching and `parseKey` normalize the letter identity to lowercase so modified letter bindings match while plain Caps Lock uppercase text input stays unaffected. -**Why not in the app:** `TuiAltScreen` and `KeybindingsManager` dispatch viewport and search bindings directly through `keys.ts` before any app component input handler runs. +**Why not in the app:** `KeybindingsManager`, `TuiAltScreen`, and all `pi-tui` components dispatch keybindings directly through `keys.ts` before any app component input handler runs. diff --git a/packages/pi-tui/src/alt-screen-search.ts b/packages/pi-tui/src/alt-screen-search.ts index 4cf62781740..333c8edcae0 100644 --- a/packages/pi-tui/src/alt-screen-search.ts +++ b/packages/pi-tui/src/alt-screen-search.ts @@ -1,5 +1,5 @@ import { Input } from "./components/input.ts"; -import { getKeybindings, type KeybindingsManager } from "./keybindings.ts"; +import { getKeybindings } from "./keybindings.ts"; import type { KeyId } from "./keys.ts"; import type { Component, Focusable, TuiMouseEvent, TuiMouseEventResult } from "./tui.ts"; import { getGraphemeSegmenter, stripTerminalSequences, truncateToWidth, visibleWidth } from "./utils.ts"; @@ -221,7 +221,6 @@ export class AltScreenSearchComponent implements Component, Focusable { }); private readonly onQueryChange: (query: string) => void; private readonly navigationButtonStyle: (text: string, hovered: boolean) => string; - private readonly keybindings?: KeybindingsManager; private resultCount = 0; private resultIndex = -1; private previousButtonStart = -1; @@ -235,11 +234,9 @@ export class AltScreenSearchComponent implements Component, Focusable { constructor( onQueryChange: (query: string) => void, navigationButtonStyle: (text: string, hovered: boolean) => string = (text) => text, - keybindings?: KeybindingsManager, ) { this.onQueryChange = onQueryChange; this.navigationButtonStyle = navigationButtonStyle; - this.keybindings = keybindings; } get focused(): boolean { @@ -301,7 +298,7 @@ export class AltScreenSearchComponent implements Component, Focusable { render(width: number): string[] { const safeWidth = Math.max(1, width); const innerWidth = Math.max(0, safeWidth - 2); - const keybindings = this.keybindings ?? getKeybindings(); + const keybindings = getKeybindings(); const query = this.input.getValue(); const result = !query.trim() ? "" diff --git a/packages/pi-tui/src/keybindings.ts b/packages/pi-tui/src/keybindings.ts index 7dd9a3a0204..b33919d58d8 100644 --- a/packages/pi-tui/src/keybindings.ts +++ b/packages/pi-tui/src/keybindings.ts @@ -190,15 +190,15 @@ export const TUI_KEYBINDINGS = { description: "Jump to next semantic prompt", }, "tui.altScreen.search": { - defaultKeys: "ctrl+shift+f", + defaultKeys: ["ctrl+f", "ctrl+shift+f"], description: "Search the primary scroll view", }, "tui.altScreen.searchNext": { - defaultKeys: ["enter", "ctrl+g"], + defaultKeys: ["down", "enter", "ctrl+g"], description: "Select the next search match", }, "tui.altScreen.searchPrevious": { - defaultKeys: ["shift+enter", "ctrl+shift+g"], + defaultKeys: ["up", "shift+enter", "ctrl+shift+g"], description: "Select the previous search match", }, "tui.altScreen.searchClose": { diff --git a/packages/pi-tui/src/keys.ts b/packages/pi-tui/src/keys.ts index 34fd296edcf..d0d5fc69e7c 100644 --- a/packages/pi-tui/src/keys.ts +++ b/packages/pi-tui/src/keys.ts @@ -379,11 +379,11 @@ function normalizeKittyFunctionalCodepoint(codepoint: number): number { return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint) ?? codepoint; } -function normalizeShiftedLetterIdentityCodepoint(codepoint: number, modifier: number): number { +function normalizeLetterIdentityCodepoint(codepoint: number, modifier: number): number { const effectiveModifier = modifier & ~LOCK_MASK; const normalizeUppercaseLetter = (effectiveModifier & MODIFIERS.shift) !== 0 || - ((modifier & CAPS_LOCK_BIT) !== 0 && (effectiveModifier & MODIFIERS.ctrl) !== 0); + ((modifier & CAPS_LOCK_BIT) !== 0 && effectiveModifier !== 0); if (normalizeUppercaseLetter && codepoint >= 65 && codepoint <= 90) { return codepoint + 32; } @@ -725,11 +725,11 @@ function matchesKittySequence(data: string, expectedCodepoint: number, expectedM const actualMod = parsed.modifier & ~LOCK_MASK; const expectedMod = expectedModifier & ~LOCK_MASK; - const normalizedCodepoint = normalizeShiftedLetterIdentityCodepoint( + const normalizedCodepoint = normalizeLetterIdentityCodepoint( normalizeKittyFunctionalCodepoint(parsed.codepoint), parsed.modifier, ); - const normalizedExpectedCodepoint = normalizeShiftedLetterIdentityCodepoint( + const normalizedExpectedCodepoint = normalizeLetterIdentityCodepoint( normalizeKittyFunctionalCodepoint(expectedCodepoint), expectedModifier, ); @@ -848,8 +848,8 @@ function matchesPrintableModifyOtherKeys(data: string, expectedKeycode: number, if (!parsed) return false; const physicalMatch = parsed.modifier === expectedModifier && - normalizeShiftedLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === - normalizeShiftedLetterIdentityCodepoint(expectedKeycode, expectedModifier); + normalizeLetterIdentityCodepoint(parsed.codepoint, parsed.modifier) === + normalizeLetterIdentityCodepoint(expectedKeycode, expectedModifier); if (physicalMatch) return true; const logicalShiftedSymbol = getLogicalShiftedSymbolCandidate( parsed.codepoint, @@ -1306,7 +1306,7 @@ export function matchesKey(data: string, keyId: KeyId): boolean { */ function formatParsedKey(codepoint: number, modifier: number, baseLayoutKey?: number): string | undefined { const normalizedCodepoint = normalizeKittyFunctionalCodepoint(codepoint); - const identityCodepoint = normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint, modifier); + const identityCodepoint = normalizeLetterIdentityCodepoint(normalizedCodepoint, modifier); // Use base layout key only when codepoint is not a recognized Latin // letter (a-z), digit (0-9), or symbol (/, -, [, ;, etc.). For those, diff --git a/packages/pi-tui/src/tui-alt-screen.ts b/packages/pi-tui/src/tui-alt-screen.ts index 57654051e5e..9f757e8fd35 100644 --- a/packages/pi-tui/src/tui-alt-screen.ts +++ b/packages/pi-tui/src/tui-alt-screen.ts @@ -6,7 +6,7 @@ import { } from "./alt-screen-search.ts"; import { AltScreenFlashContainer } from "./components/alt-screen-flash.ts"; import { ScrollView } from "./components/scroll-view.ts"; -import { getKeybindings, type KeybindingsManager } from "./keybindings.ts"; +import { getKeybindings } from "./keybindings.ts"; import { isKeyRelease } from "./keys.ts"; import { getLayoutBoxesAt, @@ -188,8 +188,6 @@ export interface TuiAltScreenOptions { searchCurrentMatchStyle?: (text: string) => string; /** Style a transcript search navigation button. */ searchNavigationButtonStyle?: (text: string, hovered: boolean) => string; - /** Keybindings for alternate-screen viewport navigation and search. Defaults to global keybindings. */ - keybindings?: KeybindingsManager; /** * Render a clickable jump-to-end label. It is centered on the last row of a follow-end * primary scroll view while that view is scrolled away from its end. @@ -273,7 +271,6 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { private readonly searchMatchStyle: (text: string) => string; private readonly searchCurrentMatchStyle: (text: string) => string; private readonly searchNavigationButtonStyle: (text: string, hovered: boolean) => string; - private readonly keybindings?: KeybindingsManager; private readonly scrollToEndIndicator?: () => string; private readonly openUrl?: (url: string) => void; private readonly onRightClickPaste?: () => void; @@ -302,7 +299,6 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { 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.keybindings = options.keybindings; this.scrollToEndIndicator = options.scrollToEndIndicator; this.openUrl = options.openUrl; this.onRightClickPaste = options.onRightClickPaste; @@ -596,7 +592,6 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { const sanitized = query === undefined ? undefined : sanitizeSearchQuery(query); const existing = this.activeSearch; if (existing) { - if (existing.overlay?.isHidden()) existing.overlay.setHidden(false); existing.overlay?.focus(); if (sanitized !== undefined) { existing.component.setQuery(sanitized); @@ -610,11 +605,11 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { this.requestRender(); return; } + if (!this.hasSearchableScrollView()) return; const component = new AltScreenSearchComponent( (nextQuery) => this.updateSearchQuery(nextQuery), this.searchNavigationButtonStyle, - this.keybindings, ); if (sanitized !== undefined) { component.setQuery(sanitized); @@ -847,7 +842,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { } if (this.isMouseSequence(data)) return { consume: true }; - const keybindings = this.keybindings ?? getKeybindings(); + const keybindings = getKeybindings(); const isRelease = isKeyRelease(data); if (this.isNonSearchOverlayFocused()) return undefined; // When the primary scroll view has nothing to scroll (short content, or a @@ -981,8 +976,9 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { private applyMouseDispatchResult(event: TuiMouseEvent, result: TuiMouseDispatchResult): boolean { const focusTarget = this.resolveMouseFocusTarget(result.focusTarget ?? result.target.component); - const focusChanged = result.focus === true && this.getFocusedComponent() !== focusTarget; - if (result.focus) { + const shouldFocus = result.focus === true && event.type !== "wheel"; + const focusChanged = shouldFocus && this.getFocusedComponent() !== focusTarget; + if (shouldFocus) { if (this.activeSearch && focusTarget !== this.activeSearch.component) { this.closeSearch(); } diff --git a/packages/pi-tui/test/keybindings.test.ts b/packages/pi-tui/test/keybindings.test.ts index a68644c545c..1998da3d506 100644 --- a/packages/pi-tui/test/keybindings.test.ts +++ b/packages/pi-tui/test/keybindings.test.ts @@ -38,9 +38,9 @@ describe("KeybindingsManager", () => { assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.lineDown"), []); assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.previousPrompt"), ["ctrl+shift+up", "ctrl+up"]); assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.nextPrompt"), ["ctrl+shift+down", "ctrl+down"]); - assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.search"), ["ctrl+shift+f"]); - assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.searchNext"), ["enter", "ctrl+g"]); - assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.searchPrevious"), ["shift+enter", "ctrl+shift+g"]); + assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.search"), ["ctrl+f", "ctrl+shift+f"]); + assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.searchNext"), ["down", "enter", "ctrl+g"]); + assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.searchPrevious"), ["up", "shift+enter", "ctrl+shift+g"]); assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.searchClose"), ["escape"]); assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.top"), ["ctrl+home"]); assert.deepStrictEqual(keybindings.getKeys("tui.altScreen.bottom"), ["ctrl+end"]); diff --git a/packages/pi-tui/test/keys.test.ts b/packages/pi-tui/test/keys.test.ts index f2a428281dd..57dd2d4f984 100644 --- a/packages/pi-tui/test/keys.test.ts +++ b/packages/pi-tui/test/keys.test.ts @@ -672,11 +672,15 @@ describe("parseKey", () => { assert.strictEqual(parseKey("\x1b[[5~"), "pageUp"); }); - it("should match and parse Kitty Ctrl+letter sequences with Caps Lock active", () => { + it("should match and parse Kitty modified letter sequences with Caps Lock active", () => { assert.strictEqual(matchesKey("\x1b[70;69u", "ctrl+f"), true); assert.strictEqual(parseKey("\x1b[70;69u"), "ctrl+f"); assert.strictEqual(matchesKey("\x1b[71;69u", "ctrl+g"), true); assert.strictEqual(parseKey("\x1b[71;69u"), "ctrl+g"); + assert.strictEqual(matchesKey("\x1b[70;67u", "alt+f"), true); + assert.strictEqual(parseKey("\x1b[70;67u"), "alt+f"); + assert.strictEqual(matchesKey("\x1b[70;73u", "super+f"), true); + assert.strictEqual(parseKey("\x1b[70;73u"), "super+f"); assert.strictEqual(matchesKey("\x1b[70;69u", "ctrl+shift+f"), false); assert.strictEqual(matchesKey("\x1b[70;70u", "ctrl+shift+f"), true); assert.strictEqual(matchesKey("\x1b[70;71u", "ctrl+alt+f"), true); diff --git a/packages/pi-tui/test/tui-alt-screen.test.ts b/packages/pi-tui/test/tui-alt-screen.test.ts index 585a2b2b33c..1efe0dcb53a 100644 --- a/packages/pi-tui/test/tui-alt-screen.test.ts +++ b/packages/pi-tui/test/tui-alt-screen.test.ts @@ -940,13 +940,13 @@ describe("TuiAltScreen", () => { assert.match(lines[0] ?? "", /^┌─+┐$/); assert.match(lines[1] ?? "", /^│ Find in transcript +│$/); assert.ok(rendered[1]?.includes("\x1b[2m")); - assert.match(lines[2] ?? "", /^└─+ ↑ Shift\+Enter · ↓ Enter ─┘$/); + assert.match(lines[2] ?? "", /^└─+ ↑ Previous · ↓ Next ─┘$/); const controls = lines[2] ?? ""; assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("↑")), -1); - assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("Shift+Enter") + 5), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("Previous") + 4), -1); assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("·")), undefined); assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("↓")), 1); - assert.strictEqual(component.getNavigationDirectionAt(2, controls.lastIndexOf("Enter") + 2), 1); + assert.strictEqual(component.getNavigationDirectionAt(2, controls.indexOf("Next") + 2), 1); component.handleInput("n"); component.setResult(0, 2); @@ -958,61 +958,57 @@ describe("TuiAltScreen", () => { assert.ok(!populated.some((line) => line.includes("Find in transcript"))); }); - it("formats custom arrow search controls, handles narrow fallback, and suppresses whitespace no-matches", () => { + it("formats custom search controls, handles narrow fallback, and suppresses whitespace no-matches", () => { + const originalKeybindings = getKeybindings(); const changes: string[] = []; - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], - "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], - }); - const component = new AltScreenSearchComponent((query) => changes.push(query), undefined, keybindings); - const wide = component.render(48).map((line) => stripTerminalSequences(line)); - const wideControls = wide[2] ?? ""; - assert.match(wideControls, /^└─+ ↑ Previous · ↓ Next ─┘$/); - assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("↑")), -1); - assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("Previous") + 4), -1); - assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("·")), undefined); - assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("↓")), 1); - assert.strictEqual(component.getNavigationDirectionAt(2, wideControls.indexOf("Next") + 2), 1); - - const narrow = component.render(20).map((line) => stripTerminalSequences(line)); - const narrowControls = narrow[2] ?? ""; - assert.match(narrowControls, /^└─+ ↑ ↓ ─┘$/); - assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑")), -1); - assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑") + 1), undefined); - assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↓")), 1); - - const reversedKeybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.searchPrevious": "down", - "tui.altScreen.searchNext": "up", - }); - const reversed = new AltScreenSearchComponent(() => {}, undefined, reversedKeybindings); - const reversedLines = reversed.render(48).map((line) => stripTerminalSequences(line)); - assert.match(reversedLines[2] ?? "", /^└─+ ↑ Down · ↓ Up ─┘$/); - - component.setQuery(" "); - component.setResult(-1, 0); - assert.deepStrictEqual(changes, []); - const whitespaceLines = component.render(48).map((line) => stripTerminalSequences(line)); - assert.ok(!whitespaceLines.some((line) => line.includes("No matches"))); - - component.setQuery("missing"); - component.setResult(-1, 0); - const missingLines = component.render(48).map((line) => stripTerminalSequences(line)); - assert.ok(missingLines.some((line) => line.includes("No matches"))); - }); - - it("uses instance keybindings for search toggling and navigation without mutating global keybindings", async () => { - const globalSearchBefore = getKeybindings().getKeys("tui.altScreen.search"); - const globalPrevBefore = getKeybindings().getKeys("tui.altScreen.searchPrevious"); - const globalNextBefore = getKeybindings().getKeys("tui.altScreen.searchNext"); - - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], - "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], - "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], - }); + const component = new AltScreenSearchComponent((query) => changes.push(query)); + try { + const narrow = component.render(20).map((line) => stripTerminalSequences(line)); + const narrowControls = narrow[2] ?? ""; + assert.match(narrowControls, /^└─+ ↑ ↓ ─┘$/); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑")), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↑") + 1), undefined); + assert.strictEqual(component.getNavigationDirectionAt(2, narrowControls.indexOf("↓")), 1); + + setKeybindings( + new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.searchPrevious": ["shift+enter", "ctrl+shift+g"], + "tui.altScreen.searchNext": ["enter", "ctrl+g"], + }), + ); + const keyNameLines = component.render(48).map((line) => stripTerminalSequences(line)); + const keyNameControls = keyNameLines[2] ?? ""; + assert.match(keyNameControls, /^└─+ ↑ Shift\+Enter · ↓ Enter ─┘$/); + assert.strictEqual(component.getNavigationDirectionAt(2, keyNameControls.indexOf("Shift+Enter") + 5), -1); + assert.strictEqual(component.getNavigationDirectionAt(2, keyNameControls.lastIndexOf("Enter") + 2), 1); + + setKeybindings( + new KeybindingsManager(TUI_KEYBINDINGS, { + "tui.altScreen.searchPrevious": "down", + "tui.altScreen.searchNext": "up", + }), + ); + const reversedLines = component.render(48).map((line) => stripTerminalSequences(line)); + assert.match(reversedLines[2] ?? "", /^└─+ ↑ Down · ↓ Up ─┘$/); + + component.setQuery(" "); + component.setResult(-1, 0); + assert.deepStrictEqual(changes, []); + const whitespaceLines = component.render(48).map((line) => stripTerminalSequences(line)); + assert.ok(!whitespaceLines.some((line) => line.includes("No matches"))); + + component.setQuery("missing"); + component.setResult(-1, 0); + const missingLines = component.render(48).map((line) => stripTerminalSequences(line)); + assert.ok(missingLines.some((line) => line.includes("No matches"))); + } finally { + setKeybindings(originalKeybindings); + } + }); + + it("toggles transcript search with Ctrl+F or Ctrl+Shift+F and navigates with Up/Down by default", async () => { const terminal = new VirtualTerminal(100, 6); - const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const tui = new TuiAltScreen(terminal); tui.addChild(new Text("needle one\nmiddle\nneedle two\nend", 0, 0)); tui.start(); try { @@ -1043,10 +1039,6 @@ describe("TuiAltScreen", () => { terminal.sendInput("\x1b[102;6u"); await terminal.waitForRender(); assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); - - assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.search"), globalSearchBefore); - assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.searchPrevious"), globalPrevBefore); - assert.deepStrictEqual(getKeybindings().getKeys("tui.altScreen.searchNext"), globalNextBefore); } finally { tui.stop(); } @@ -1223,10 +1215,10 @@ describe("TuiAltScreen", () => { await terminal.waitForRender(); let viewport = terminal.getViewport(); assert.ok(viewport.some((line) => line.includes("1/2"))); - assert.ok(viewport.some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(viewport.some((line) => line.includes("↑ Previous · ↓ Next"))); let arrowRow = viewport.findIndex((line) => line.includes("↑") && line.includes("↓")); - let arrowColumn = viewport[arrowRow]?.lastIndexOf("Enter") ?? -1; + let arrowColumn = viewport[arrowRow]?.lastIndexOf("Next") ?? -1; assert.ok(arrowRow >= 0 && arrowColumn >= 0); const hoverEventCount = terminal.events.length; terminal.sendInput(`\x1b[<35;${arrowColumn + 1};${arrowRow + 1}M`); @@ -1234,25 +1226,25 @@ describe("TuiAltScreen", () => { assert.ok( terminal.events .slice(hoverEventCount) - .some((event) => event.type === "write" && event.data.includes("\x1b[45m↓ Enter\x1b[49m")), + .some((event) => event.type === "write" && event.data.includes("\x1b[45m↓ Next\x1b[49m")), ); terminal.sendInput(`\x1b[<0;${arrowColumn + 1};${arrowRow + 1}M`); await terminal.waitForRender(); viewport = terminal.getViewport(); assert.ok(viewport.some((line) => line.includes("2/2"))); - assert.ok(viewport.some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(viewport.some((line) => line.includes("↑ Previous · ↓ Next"))); arrowRow = viewport.findIndex((line) => line.includes("↑") && line.includes("↓")); - arrowColumn = (viewport[arrowRow]?.indexOf("Shift+Enter") ?? -3) + 3; + arrowColumn = (viewport[arrowRow]?.indexOf("Previous") ?? -3) + 3; assert.ok(arrowRow >= 0 && arrowColumn >= 0); terminal.sendInput(`\x1b[<0;${arrowColumn + 1};${arrowRow + 1}M`); await terminal.waitForRender(); assert.ok(terminal.getViewport().some((line) => line.includes("1/2"))); - assert.ok(terminal.getViewport().some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); terminal.sendInput("\x1b[102;6u"); await terminal.waitForRender(); - assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); tui.stop(); }); @@ -1388,7 +1380,7 @@ describe("TuiAltScreen", () => { await terminal.waitForRender(); assert.strictEqual(transcript.isFollowingEnd, false); assert.ok(terminal.getViewport().some((line) => line.includes("2/2"))); - assert.ok(terminal.getViewport().some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); assert.ok(terminal.getViewport().some((line) => line.includes("line 10 needle two"))); assert.deepStrictEqual(editorInputs, []); assert.ok( @@ -1413,7 +1405,7 @@ describe("TuiAltScreen", () => { terminal.sendInput("\x1b"); terminal.sendInput("x"); await terminal.waitForRender(); - assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Shift+Enter · ↓ Enter"))); + assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); assert.deepStrictEqual(editorInputs, ["x"]); tui.stop(); @@ -2997,10 +2989,7 @@ describe("TuiAltScreen", () => { it("defers search shortcut to a focused non-search overlay", async () => { const terminal = new VirtualTerminal(60, 8); - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], - }); - const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const tui = new TuiAltScreen(terminal); tui.addChild(new Text("alpha\nbeta\ngamma", 0, 0)); const overlay = new InputOverlay(); tui.start(); @@ -3023,12 +3012,9 @@ describe("TuiAltScreen", () => { tui.stop(); }); - it("defers search shortcut when layoutRoot has no scroll view but keeps search for short scrollable layouts", async () => { + it("defers search shortcut and ignores openSearch when layoutRoot has no scroll view, but keeps search for short scrollable layouts", async () => { const terminal = new VirtualTerminal(60, 8); - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], - }); - const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const tui = new TuiAltScreen(terminal); const takeover = new InputOverlay(); tui.setLayoutRoot(takeover); tui.setFocus(takeover); @@ -3040,8 +3026,13 @@ describe("TuiAltScreen", () => { assert.deepStrictEqual(takeover.inputs, ["\x06"]); assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + tui.openSearch("alpha"); + await terminal.waitForRender(); + assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); + assert.ok(!terminal.getViewport().some((line) => line.includes("No matches"))); + const shortScrollView = new ScrollView(new Text("short alpha line", 0, 0), { primary: true }); - tui.setLayoutRoot(new VStack([{ component: shortScrollView, flex: 1 }])); + tui.setLayoutRoot(new VStack([{ component: shortScrollView, basis: 0, grow: 1 }])); await terminal.waitForRender(); assert.strictEqual(shortScrollView.canScroll, false); @@ -3053,10 +3044,7 @@ describe("TuiAltScreen", () => { it("opens and closes search with Kitty Ctrl+F when Caps Lock is active", async () => { const terminal = new VirtualTerminal(60, 8); - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], - }); - const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const tui = new TuiAltScreen(terminal); tui.addChild(new Text("alpha\nbeta", 0, 0)); tui.start(); await terminal.waitForRender(); @@ -3071,20 +3059,18 @@ describe("TuiAltScreen", () => { tui.stop(); }); - it("closes active search when clicking a focusable editor while keeping search open on scroll, selection, and search-box clicks", async () => { + it("closes active search when clicking a focusable editor while keeping search open on scroll, wheel focus results, selection, and search-box clicks", async () => { const terminal = new VirtualTerminal(80, 12); - const keybindings = new KeybindingsManager(TUI_KEYBINDINGS, { - "tui.altScreen.search": ["ctrl+f", "ctrl+shift+f"], - "tui.altScreen.searchPrevious": ["up", "shift+enter", "ctrl+shift+g"], - "tui.altScreen.searchNext": ["down", "enter", "ctrl+g"], - }); - const tui = new TuiAltScreen(terminal, undefined, undefined, { keybindings }); + const tui = new TuiAltScreen(terminal); const scrollView = new ScrollView( new Text(Array.from({ length: 20 }, (_, index) => `alpha line ${index + 1}`).join("\n"), 0, 0), { primary: true }, ); + const wheelFocusRegion = new MouseRegion(new Text("wheel strip", 0, 0), (event) => + event.type === "wheel" ? { handled: true, focus: true } : undefined, + ); const editor = new Editor(tui, defaultEditorTheme); - tui.setLayoutRoot(new VStack([{ component: scrollView, flex: 1 }, { component: editor }])); + tui.setLayoutRoot(new VStack([{ component: scrollView, basis: 0, grow: 1 }, wheelFocusRegion, editor])); tui.setFocus(editor); tui.start(); await terminal.waitForRender(); @@ -3094,12 +3080,16 @@ describe("TuiAltScreen", () => { assert.strictEqual(editor.focused, false); assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + const wheelStripRow = terminal.getViewport().findIndex((line) => line.includes("wheel strip")); + assert.ok(wheelStripRow >= 0); + terminal.sendInput(`\x1b[<64;3;${wheelStripRow + 1}M`); terminal.sendInput("\x1b[<64;5;3M"); terminal.sendInput("\x1b[<0;2;2M"); terminal.sendInput("\x1b[<32;6;2M"); terminal.sendInput("\x1b[<0;6;2m"); await terminal.waitForRender(); assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + assert.notStrictEqual(tui.getFocusedComponent(), wheelFocusRegion); const searchRow = terminal.getViewport().findIndex((line) => line.includes("alpha") && line.includes("/20")); assert.ok(searchRow >= 0); @@ -3111,7 +3101,7 @@ describe("TuiAltScreen", () => { assert.ok(terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); assert.strictEqual(editor.getText(), ""); - const editorRow = 11; + const editorRow = wheelStripRow + 3; terminal.sendInput(`\x1b[<0;5;${editorRow}M`); terminal.sendInput(`\x1b[<0;5;${editorRow}m`); await terminal.waitForRender(); From 55a016a837e2aad28d3d4c23417ef8171db6b848 Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 04:13:34 -0800 Subject: [PATCH 07/10] refactor(tui): require tuiMode in slash resolution and deduplicate editor cursor injection --- apps/kimi-code/src/tui/commands/registry.ts | 2 +- apps/kimi-code/src/tui/commands/resolve.ts | 8 +- .../tui/components/editor/custom-editor.ts | 83 ++++++++++--------- .../test/tui/commands/add-dir.test.ts | 3 + apps/kimi-code/test/tui/commands/goal.test.ts | 2 +- .../test/tui/commands/resolve.test.ts | 12 ++- .../tui/controllers/editor-keyboard.test.ts | 6 +- 7 files changed, 61 insertions(+), 55 deletions(-) diff --git a/apps/kimi-code/src/tui/commands/registry.ts b/apps/kimi-code/src/tui/commands/registry.ts index fb1cb9a749f..113507a0d72 100644 --- a/apps/kimi-code/src/tui/commands/registry.ts +++ b/apps/kimi-code/src/tui/commands/registry.ts @@ -476,7 +476,7 @@ export type BuiltinSlashCommand = (typeof BUILTIN_SLASH_COMMANDS)[number]; export type BuiltinSlashCommandName = BuiltinSlashCommand['name']; export function isSlashCommandVisible( - command: Pick, + command: KimiSlashCommand, tuiMode: TuiMode, ): boolean { return ( diff --git a/apps/kimi-code/src/tui/commands/resolve.ts b/apps/kimi-code/src/tui/commands/resolve.ts index 68c0bd36858..b37d537599b 100644 --- a/apps/kimi-code/src/tui/commands/resolve.ts +++ b/apps/kimi-code/src/tui/commands/resolve.ts @@ -55,7 +55,7 @@ export interface ResolveSlashCommandInput { readonly pluginCommandMap: ReadonlyMap; readonly isStreaming: boolean; readonly isCompacting: boolean; - readonly tuiMode?: TuiMode; + readonly tuiMode: TuiMode; readonly skillVariantPathForCommand?: (commandName: string, tokenStart: number) => string | undefined; readonly defaultSkillPathForCommand?: (commandName: string) => string | undefined; } @@ -64,7 +64,7 @@ export function resolveSlashCommandInput(options: ResolveSlashCommandInput): Sla const parsed = parseSlashInput(options.input); if (parsed === null) return { kind: 'not-command' }; - const command = findVisibleBuiltInSlashCommand(parsed.name, options.tuiMode ?? 'regular'); + const command = findVisibleBuiltInSlashCommand(parsed.name, options.tuiMode); if (command !== undefined) { const busyReason = slashCommandBusyReason(options); if ( @@ -173,7 +173,7 @@ export function resolveUserInput(options: ResolveSlashCommandInput): { export interface SlashCommandResolutionHost { readonly state: { readonly appState: Pick; - readonly ui?: Partial>; + readonly ui: Pick; }; readonly skillCommandMap: ReadonlyMap; readonly pluginCommandMap: ReadonlyMap; @@ -192,7 +192,7 @@ export function resolveHostUserInput( pluginCommandMap: host.pluginCommandMap, isStreaming: overrides?.isStreaming ?? host.state.appState.streamingPhase !== 'idle', isCompacting: overrides?.isCompacting ?? host.state.appState.isCompacting, - tuiMode: overrides?.tuiMode ?? host.state.ui?.mode, + tuiMode: overrides?.tuiMode ?? host.state.ui.mode, skillVariantPathForCommand: host.skillVariantPathForCommand === undefined ? undefined diff --git a/apps/kimi-code/src/tui/components/editor/custom-editor.ts b/apps/kimi-code/src/tui/components/editor/custom-editor.ts index 737f72357cb..e3cf92c5d76 100644 --- a/apps/kimi-code/src/tui/components/editor/custom-editor.ts +++ b/apps/kimi-code/src/tui/components/editor/custom-editor.ts @@ -86,7 +86,7 @@ function mapVisibleIdxToRaw(line: string, visibleIdx: number): number { return i; } -function stripSgr(s: string): string { +function stripNonVisibleSequences(s: string): string { return s.replace(ANSI_NON_VISIBLE, ''); } @@ -255,7 +255,7 @@ export class CustomEditor extends Editor { let highlighted = original; let leadingRange: { start: number; end: number } | null = null; if (text.startsWith('/')) { - leadingRange = leadingSlashTokenRange(stripSgr(original)); + leadingRange = leadingSlashTokenRange(stripNonVisibleSequences(original)); const leading = highlightFirstSlashToken(original, 'primary'); if (leading !== undefined) { highlighted = leading; @@ -571,7 +571,7 @@ export class CustomEditor extends Editor { } export function highlightFirstSlashToken(line: string, token: 'primary'): string | undefined { - const visible = stripSgr(line); + const visible = stripNonVisibleSequences(line); const range = leadingSlashTokenRange(visible); if (range === null) return undefined; const ranges = [range]; @@ -605,7 +605,7 @@ export function highlightInlineSkillTokens( token: 'primary', ): string | undefined { if (skillCommandNames.size === 0) return undefined; - const visible = stripSgr(line); + const visible = stripNonVisibleSequences(line); const ranges = findInlineSkillTokens(visible, { isKnownSkill: (commandName) => skillCommandNames.has(commandName) || skillCommandNames.has(`skill:${commandName}`), @@ -665,7 +665,27 @@ function highlightVisibleRanges( } const EDITOR_LEFT_PADDING = 4; -const CURSOR_BLOCK = '\u001B[7m \u001B[0m'; + +function findCursorAnchor( + line: string, + fallbackVisibleIdx: number, +): { readonly insertAt: number; readonly cursorCells: number } { + const fakeCursorEnd = line.indexOf(FAKE_CURSOR_END); + if (fakeCursorEnd !== -1) { + return { insertAt: fakeCursorEnd + FAKE_CURSOR_END.length, cursorCells: 1 }; + } + return { insertAt: mapVisibleIdxToRaw(line, fallbackVisibleIdx), cursorCells: 0 }; +} + +function injectTextAfterCursor( + line: string, + insertAt: number, + styledText: string, + textWidth: number, +): string { + const remaining = Math.max(0, visibleWidth(line.slice(insertAt)) - textWidth); + return line.slice(0, insertAt) + styledText + ' '.repeat(remaining); +} function injectArgumentHint( line: string, @@ -673,49 +693,34 @@ function injectArgumentHint( realTextLength: number, width: number, ): string { - const fakeCursorEnd = line.indexOf(FAKE_CURSOR_END); - const legacyCursorIdx = line.indexOf(CURSOR_BLOCK); - const cursorPresent = fakeCursorEnd !== -1 || legacyCursorIdx !== -1; + const { insertAt, cursorCells } = findCursorAnchor(line, EDITOR_LEFT_PADDING + realTextLength); const contentWidth = Math.max(1, width - EDITOR_LEFT_PADDING * 2); - const available = contentWidth - realTextLength - (cursorPresent ? 1 : 0); - const trimmed = truncateHint(hint, available); + const available = contentWidth - realTextLength - cursorCells; + if (available <= 0) return line; + const trimmed = truncateToWidth(hint, available, '…'); if (trimmed.length === 0) return line; - const colored = currentTheme.fg('textDim', trimmed); - const insertAt = fakeCursorEnd !== -1 - ? fakeCursorEnd + FAKE_CURSOR_END.length - : legacyCursorIdx !== -1 - ? legacyCursorIdx + CURSOR_BLOCK.length - : mapVisibleIdxToRaw(line, EDITOR_LEFT_PADDING + realTextLength); - const trailing = line.slice(insertAt); - const remaining = Math.max(0, visibleWidth(trailing) - visibleWidth(trimmed)); - return line.slice(0, insertAt) + colored + ' '.repeat(remaining); -} - -function truncateHint(hint: string, maxLen: number): string { - if (maxLen <= 0) return ''; - if (hint.length <= maxLen) return hint; - if (maxLen === 1) return '…'; - return `${hint.slice(0, maxLen - 1)}…`; + return injectTextAfterCursor( + line, + insertAt, + currentTheme.fg('textDim', trimmed), + visibleWidth(trimmed), + ); } function injectPromptPrediction(line: string, prediction: string, width: number): string { - const fakeCursorEnd = line.indexOf(FAKE_CURSOR_END); - const legacyCursorIdx = line.indexOf(CURSOR_BLOCK); - const cursorPresent = fakeCursorEnd !== -1 || legacyCursorIdx !== -1; + const { insertAt, cursorCells } = findCursorAnchor(line, EDITOR_LEFT_PADDING); const contentWidth = Math.max(1, width - EDITOR_LEFT_PADDING * 2); - const available = contentWidth - (cursorPresent ? 1 : 0); + const available = contentWidth - cursorCells; if (available <= 0) return line; const preview = prediction.replaceAll(/\s+/g, ' ').trim(); const trimmed = truncateToWidth(preview, available, '…'); if (trimmed.length === 0) return line; - const insertAt = fakeCursorEnd !== -1 - ? fakeCursorEnd + FAKE_CURSOR_END.length - : legacyCursorIdx !== -1 - ? legacyCursorIdx + CURSOR_BLOCK.length - : mapVisibleIdxToRaw(line, EDITOR_LEFT_PADDING); - const trailing = line.slice(insertAt); - const remaining = Math.max(0, visibleWidth(trailing) - visibleWidth(trimmed)); - return line.slice(0, insertAt) + currentTheme.fg('textMuted', trimmed) + ' '.repeat(remaining); + return injectTextAfterCursor( + line, + insertAt, + currentTheme.fg('textMuted', trimmed), + visibleWidth(trimmed), + ); } export function injectPromptSymbol( @@ -738,7 +743,7 @@ export function wrapWithSideBorders( ): string[] { let seenTop = false; return lines.map((line) => { - const plain = stripSgr(line); + const plain = stripNonVisibleSequences(line); if (plain.length > 0 && plain[0] === '─') { const isTop = !seenTop; const leftCorner = seenTop ? '╰' : options.connectedAbove === true ? '├' : '╭'; diff --git a/apps/kimi-code/test/tui/commands/add-dir.test.ts b/apps/kimi-code/test/tui/commands/add-dir.test.ts index a0a0db0d73d..6114f98425a 100644 --- a/apps/kimi-code/test/tui/commands/add-dir.test.ts +++ b/apps/kimi-code/test/tui/commands/add-dir.test.ts @@ -21,6 +21,9 @@ function makeHost(additionalDirs: readonly string[] = []) { streamingPhase: 'idle', isCompacting: false, }, + ui: { + mode: 'regular' as const, + }, }; let mountedPanel: MountedPanel | null = null; const session = { diff --git a/apps/kimi-code/test/tui/commands/goal.test.ts b/apps/kimi-code/test/tui/commands/goal.test.ts index 4490728d4cf..ca3e514bc93 100644 --- a/apps/kimi-code/test/tui/commands/goal.test.ts +++ b/apps/kimi-code/test/tui/commands/goal.test.ts @@ -116,7 +116,7 @@ function makeHost( livePane: { pendingApproval: null, pendingQuestion: null }, notifyPanel: { setPrompt: vi.fn() }, transcriptContainer, - ui: { requestRender: vi.fn() }, + ui: { mode: overrides.fullscreen === true ? ('fullscreen' as const) : ('regular' as const), requestRender: vi.fn() }, theme: { palette: getBuiltInPalette('dark') }, }, session: hasSession ? session : undefined, diff --git a/apps/kimi-code/test/tui/commands/resolve.test.ts b/apps/kimi-code/test/tui/commands/resolve.test.ts index a69e7e3598e..f908b486e81 100644 --- a/apps/kimi-code/test/tui/commands/resolve.test.ts +++ b/apps/kimi-code/test/tui/commands/resolve.test.ts @@ -22,6 +22,7 @@ function resolve( pluginCommandMap: new Map(), isStreaming: false, isCompacting: false, + tuiMode: 'regular', ...overrides, }); } @@ -30,6 +31,7 @@ describe('resolveUserInput', () => { const options = { isStreaming: false, isCompacting: false, + tuiMode: 'regular' as const, skillCommandMap: new Map([ ['skill:review', 'review'], ['quick', 'review'], @@ -516,27 +518,23 @@ describe('resolveSlashCommandInput', () => { }); describe('resolveHostUserInput', () => { - const makeHost = (mode?: 'regular' | 'fullscreen') => ({ + const makeHost = (mode: 'regular' | 'fullscreen') => ({ state: { appState: { streamingPhase: 'idle' as const, isCompacting: false, }, - ...(mode !== undefined ? { ui: { mode } } : {}), + ui: { mode }, }, skillCommandMap: new Map(), pluginCommandMap: new Map(), }); - it('injects tuiMode from host.state.ui.mode and defaults omitted ui to regular', () => { + it('resolves built-in visibility from host.state.ui.mode', () => { expect(resolveHostUserInput(makeHost('regular'), '/find needle').intent).toEqual({ kind: 'message', input: '/find needle', }); - expect(resolveHostUserInput(makeHost(undefined), '/find needle').intent).toEqual({ - kind: 'message', - input: '/find needle', - }); expect(resolveHostUserInput(makeHost('fullscreen'), '/find needle').intent).toMatchObject({ kind: 'builtin', name: 'find', diff --git a/apps/kimi-code/test/tui/controllers/editor-keyboard.test.ts b/apps/kimi-code/test/tui/controllers/editor-keyboard.test.ts index eb972a76984..9e3f0e1a84c 100644 --- a/apps/kimi-code/test/tui/controllers/editor-keyboard.test.ts +++ b/apps/kimi-code/test/tui/controllers/editor-keyboard.test.ts @@ -73,7 +73,7 @@ function createHarness( editorCommand: null, }, footer: { setTransientHint: footerHint }, - ui: options.ui ?? { requestRender: vi.fn() }, + ui: options.ui ?? { mode: 'regular' as const, requestRender: vi.fn() }, }, session, btwPanelController: { cancelRunning: btwCancelRunning, closeOrCancel: btwCloseOrCancel }, @@ -506,7 +506,7 @@ describe('EditorKeyboardController Shift-Tab plan toggle', () => { activeDialog: null, appState: { streamingPhase: 'idle', isCompacting: false, planMode: false }, footer: { setTransientHint: vi.fn() }, - ui: { requestRender: vi.fn() }, + ui: { mode: 'regular' as const, requestRender: vi.fn() }, }, session: options.sessionless ? undefined : { cancel: vi.fn(async () => {}) }, worktreeCreation: @@ -600,7 +600,7 @@ describe('EditorKeyboardController Ctrl-S steering', () => { queuedMessages: options.queued, appState: { streamingPhase: 'waiting', isCompacting: false, model: 'k2' }, footer: { setTransientHint: vi.fn() }, - ui: { requestRender: vi.fn() }, + ui: { mode: 'regular' as const, requestRender: vi.fn() }, }, session: { id: 's1' }, skillCommandMap: options.skillCommandMap ?? new Map(), From cc1b0a3f77d0967c8b1badc781fd398021420380 Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 04:39:36 -0800 Subject: [PATCH 08/10] refactor(pi-tui): replace Input.moveCursorToEnd with getCursor and setCursor --- packages/pi-tui/UPSTREAM.md | 2 +- packages/pi-tui/src/alt-screen-search.ts | 2 +- packages/pi-tui/src/components/input.ts | 21 +++++++++++++- packages/pi-tui/test/input.test.ts | 37 +++++++++++++++++++----- 4 files changed, 52 insertions(+), 10 deletions(-) diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index ee3378e847d..fc68fe66a60 100644 --- a/packages/pi-tui/UPSTREAM.md +++ b/packages/pi-tui/UPSTREAM.md @@ -249,7 +249,7 @@ Each card: **decision** and **why not in the app**. Status is `keep` or `absorbe ### alt-screen-search-bindings-and-open-search — keep -**Decision:** Default alternate-screen search keybindings in `TUI_KEYBINDINGS` use `["ctrl+f", "ctrl+shift+f"]` for `tui.altScreen.search`, `["up", "shift+enter", "ctrl+shift+g"]` for `tui.altScreen.searchPrevious`, and `["down", "enter", "ctrl+g"]` for `tui.altScreen.searchNext`. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search (when the active layout has a searchable scroll view) and optionally prefills a single-line sanitized query with the cursor at the end via `Input.moveCursorToEnd()`. When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and requires a searchable scroll view so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Non-wheel mouse focus transfers to a component outside the search overlay close active transcript search before moving focus, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. +**Decision:** Default alternate-screen search keybindings in `TUI_KEYBINDINGS` use `["ctrl+f", "ctrl+shift+f"]` for `tui.altScreen.search`, `["up", "shift+enter", "ctrl+shift+g"]` for `tui.altScreen.searchPrevious`, and `["down", "enter", "ctrl+g"]` for `tui.altScreen.searchNext`. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search (when the active layout has a searchable scroll view) and optionally prefills a single-line sanitized query with the cursor at the end via `Input.setCursor(position)` (paired with `Input.getCursor()`). When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and requires a searchable scroll view so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Non-wheel mouse focus transfers to a component outside the search overlay close active transcript search before moving focus, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. **Why not in the app:** Default keybindings live in `TUI_KEYBINDINGS` shared by all `pi-tui` components; search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, mouse focus dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`. diff --git a/packages/pi-tui/src/alt-screen-search.ts b/packages/pi-tui/src/alt-screen-search.ts index 333c8edcae0..c3a882204d4 100644 --- a/packages/pi-tui/src/alt-screen-search.ts +++ b/packages/pi-tui/src/alt-screen-search.ts @@ -250,7 +250,7 @@ export class AltScreenSearchComponent implements Component, Focusable { setQuery(query: string): void { this.input.setValue(query); - this.input.moveCursorToEnd(); + this.input.setCursor(query.length); } setResult(index: number, count: number): void { diff --git a/packages/pi-tui/src/components/input.ts b/packages/pi-tui/src/components/input.ts index 0cd2ad12e7b..4914ecf754b 100644 --- a/packages/pi-tui/src/components/input.ts +++ b/packages/pi-tui/src/components/input.ts @@ -68,8 +68,27 @@ export class Input implements Component, Focusable { this.cursor = Math.min(this.cursor, value.length); } - moveCursorToEnd(): void { + getCursor(): number { + return this.cursor; + } + + setCursor(position: number): void { this.lastAction = null; + if (Number.isNaN(position) || position <= 0) { + this.cursor = 0; + return; + } + if (position >= this.value.length) { + this.cursor = this.value.length; + return; + } + const target = Math.floor(position); + for (const grapheme of segmenter.segment(this.value)) { + if (target < grapheme.index + grapheme.segment.length) { + this.cursor = grapheme.index; + return; + } + } this.cursor = this.value.length; } diff --git a/packages/pi-tui/test/input.test.ts b/packages/pi-tui/test/input.test.ts index bcdc13a5eaf..548a01f810d 100644 --- a/packages/pi-tui/test/input.test.ts +++ b/packages/pi-tui/test/input.test.ts @@ -34,25 +34,48 @@ describe("Input component", () => { assert.strictEqual(input.getValue(), "\\x"); }); - it("moves cursor to the end for ASCII and multi-byte text without changing setValue clamping", () => { + it("gets and sets cursor position with clamping and grapheme alignment without changing setValue", () => { const preserved = new Input(); preserved.setValue("hello"); + assert.strictEqual(preserved.getCursor(), 0); preserved.handleInput("\x7f"); assert.strictEqual(preserved.getValue(), "hello"); const ascii = new Input(); ascii.setValue("hello"); - ascii.moveCursorToEnd(); + ascii.setCursor(2); + assert.strictEqual(ascii.getCursor(), 2); ascii.handleInput("\x7f"); - assert.strictEqual(ascii.getValue(), "hell"); + assert.strictEqual(ascii.getValue(), "hllo"); + assert.strictEqual(ascii.getCursor(), 1); + ascii.setCursor(99); + assert.strictEqual(ascii.getCursor(), 4); + ascii.setCursor(-5); + assert.strictEqual(ascii.getCursor(), 0); + ascii.setCursor(Number.NaN); + assert.strictEqual(ascii.getCursor(), 0); + ascii.setCursor(Number.POSITIVE_INFINITY); + assert.strictEqual(ascii.getCursor(), 4); + ascii.handleInput("\x7f"); + assert.strictEqual(ascii.getValue(), "hll"); const unicode = new Input(); - unicode.setValue("你好🙂"); - unicode.moveCursorToEnd(); + unicode.setValue("你好🙂a"); + unicode.setCursor(3); + assert.strictEqual(unicode.getCursor(), 2); + unicode.setCursor(unicode.getValue().length); + assert.strictEqual(unicode.getCursor(), 5); unicode.handleInput("\x7f"); - assert.strictEqual(unicode.getValue(), "你好"); + assert.strictEqual(unicode.getValue(), "你好🙂"); unicode.handleInput("\x7f"); - assert.strictEqual(unicode.getValue(), "你"); + assert.strictEqual(unicode.getValue(), "你好"); + + const combining = new Input(); + combining.setValue("e\u0301x"); + combining.setCursor(1); + assert.strictEqual(combining.getCursor(), 0); + combining.setCursor(2); + assert.strictEqual(combining.getCursor(), 2); }); describe("render", () => { From acbf61c9903d7eb72124acc5d1768db412de8bff Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 04:39:36 -0800 Subject: [PATCH 09/10] chore: tighten fullscreen search changeset summaries --- .changeset/fullscreen-search-cli.md | 2 +- .changeset/fullscreen-search-pi-tui.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/fullscreen-search-cli.md b/.changeset/fullscreen-search-cli.md index eb1d6c651dd..8cc259a6242 100644 --- a/.changeset/fullscreen-search-cli.md +++ b/.changeset/fullscreen-search-cli.md @@ -2,4 +2,4 @@ "@moonshot-ai/kimi-code": minor --- -Switch fullscreen conversation search to `Ctrl+F` (keeping `Ctrl+Shift+F`), add `↑` and `↓` navigation between matches, close search when clicking back into the input box, add the `/find` slash command in fullscreen mode, and fix missing cursor and IME positioning when slash command argument hints are shown. Run `/find` or `/find ` to search the conversation. In fullscreen mode, `Ctrl+F` now opens search instead of moving the editor cursor right; use `→` to move right or switch to regular mode to keep the previous `Ctrl+F` cursor movement. +Support searching conversations in fullscreen mode with `Ctrl+F` or `/find`. diff --git a/.changeset/fullscreen-search-pi-tui.md b/.changeset/fullscreen-search-pi-tui.md index 58a9d9e74a8..7cde5df8fce 100644 --- a/.changeset/fullscreen-search-pi-tui.md +++ b/.changeset/fullscreen-search-pi-tui.md @@ -2,4 +2,4 @@ "@moonshot-ai/pi-tui": minor --- -Default alternate-screen transcript search to `Ctrl+F` (keeping `Ctrl+Shift+F`) and match navigation to `↑`/`↓` with `↑ Previous · ↓ Next` labels, add programmatic `openSearch(query?)` and single-line end-of-line cursor positioning, defer search shortcuts to focused overlays and non-scroll layout roots, close active search when non-wheel mouse focus moves to another component, and normalize Kitty Caps Lock modified letter sequences. +Default alternate-screen transcript search to `Ctrl+F` with `↑`/`↓` navigation, and add programmatic search opening. From 91bbc05ddf5e2816ae68902c12108bdf5a4429e8 Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 05:07:35 -0800 Subject: [PATCH 10/10] fix(pi-tui): limit wheel focus suppression to active search and drop speculative overlay guard --- packages/pi-tui/UPSTREAM.md | 2 +- packages/pi-tui/src/tui-alt-screen.ts | 9 ++----- packages/pi-tui/test/tui-alt-screen.test.ts | 29 +++------------------ 3 files changed, 7 insertions(+), 33 deletions(-) diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index fc68fe66a60..487e385c758 100644 --- a/packages/pi-tui/UPSTREAM.md +++ b/packages/pi-tui/UPSTREAM.md @@ -249,7 +249,7 @@ Each card: **decision** and **why not in the app**. Status is `keep` or `absorbe ### alt-screen-search-bindings-and-open-search — keep -**Decision:** Default alternate-screen search keybindings in `TUI_KEYBINDINGS` use `["ctrl+f", "ctrl+shift+f"]` for `tui.altScreen.search`, `["up", "shift+enter", "ctrl+shift+g"]` for `tui.altScreen.searchPrevious`, and `["down", "enter", "ctrl+g"]` for `tui.altScreen.searchNext`. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search (when the active layout has a searchable scroll view) and optionally prefills a single-line sanitized query with the cursor at the end via `Input.setCursor(position)` (paired with `Input.getCursor()`). When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding defers to focused non-search overlays and requires a searchable scroll view so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. Non-wheel mouse focus transfers to a component outside the search overlay close active transcript search before moving focus, while scrolling, clicking search controls, and drag-selecting transcript text keep search open. +**Decision:** Default alternate-screen search keybindings in `TUI_KEYBINDINGS` use `["ctrl+f", "ctrl+shift+f"]` for `tui.altScreen.search`, `["up", "shift+enter", "ctrl+shift+g"]` for `tui.altScreen.searchPrevious`, and `["down", "enter", "ctrl+g"]` for `tui.altScreen.searchNext`. `TuiAltScreen.openSearch(query?)` idempotently opens or refocuses transcript search (when the active layout has a searchable scroll view) and optionally prefills a single-line sanitized query with the cursor at the end via `Input.setCursor(position)` (paired with `Input.getCursor()`). When primary search navigation keys are `up`/`down`, `AltScreenSearchComponent` renders semantic `↑ Previous` and `↓ Next` labels (with narrow fallback `↑ ↓`), and whitespace-only queries do not show `No matches`. The `tui.altScreen.search` binding requires a searchable scroll view so full-screen layout takeovers without a `ScrollView` keep their own `Ctrl+F` handling. While transcript search is active, non-wheel mouse focus transfers to a component outside the search overlay close active search before moving focus, whereas wheel events, clicking search controls, and drag-selecting transcript text keep search open; when search is inactive, wheel focus requests keep upstream semantics. **Why not in the app:** Default keybindings live in `TUI_KEYBINDINGS` shared by all `pi-tui` components; search overlay lifecycle, `ActiveSearch` state, viewport key dispatch, mouse focus dispatch, search label formatting, and `Input` cursor positioning are private to `TuiAltScreen`, `AltScreenSearchComponent`, and `Input`. diff --git a/packages/pi-tui/src/tui-alt-screen.ts b/packages/pi-tui/src/tui-alt-screen.ts index 9f757e8fd35..595b15f3bac 100644 --- a/packages/pi-tui/src/tui-alt-screen.ts +++ b/packages/pi-tui/src/tui-alt-screen.ts @@ -768,14 +768,10 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { this.flashes.flash(message, durationMs); } - private isNonSearchOverlayFocused(): boolean { - return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true; - } - /** Focused overlays and components that capture viewport input receive viewport keys instead of the transcript. */ private shouldDeferViewportInput(): boolean { if (this.getFocusedComponent()?.capturesViewportInput) return true; - return this.isNonSearchOverlayFocused(); + return this.isOverlayFocused() && this.activeSearch?.overlay?.isFocused() !== true; } private clearComponentMouseGesture(): void { @@ -844,7 +840,6 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { const keybindings = getKeybindings(); const isRelease = isKeyRelease(data); - if (this.isNonSearchOverlayFocused()) return undefined; // When the primary scroll view has nothing to scroll (short content, or a // full-screen component mounted as the layout root), let navigation keys // fall through to the focused component instead of consuming them. @@ -976,7 +971,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { private applyMouseDispatchResult(event: TuiMouseEvent, result: TuiMouseDispatchResult): boolean { const focusTarget = this.resolveMouseFocusTarget(result.focusTarget ?? result.target.component); - const shouldFocus = result.focus === true && event.type !== "wheel"; + const shouldFocus = result.focus === true && !(this.activeSearch && event.type === "wheel"); const focusChanged = shouldFocus && this.getFocusedComponent() !== focusTarget; if (shouldFocus) { if (this.activeSearch && focusTarget !== this.activeSearch.component) { diff --git a/packages/pi-tui/test/tui-alt-screen.test.ts b/packages/pi-tui/test/tui-alt-screen.test.ts index 1efe0dcb53a..be57604d8c3 100644 --- a/packages/pi-tui/test/tui-alt-screen.test.ts +++ b/packages/pi-tui/test/tui-alt-screen.test.ts @@ -2987,31 +2987,6 @@ describe("TuiAltScreen", () => { tui.stop(); }); - it("defers search shortcut to a focused non-search overlay", async () => { - const terminal = new VirtualTerminal(60, 8); - const tui = new TuiAltScreen(terminal); - tui.addChild(new Text("alpha\nbeta\ngamma", 0, 0)); - const overlay = new InputOverlay(); - tui.start(); - await terminal.waitForRender(); - - const handle = tui.showOverlay(overlay); - await terminal.waitForRender(); - assert.strictEqual(overlay.focused, true); - - terminal.sendInput("\x06"); - await terminal.waitForRender(); - assert.deepStrictEqual(overlay.inputs, ["\x06"]); - assert.ok(!terminal.getViewport().some((line) => line.includes("Find in transcript"))); - - handle.hide(); - await terminal.waitForRender(); - terminal.sendInput("\x06"); - await terminal.waitForRender(); - assert.ok(terminal.getViewport().some((line) => line.includes("Find in transcript"))); - tui.stop(); - }); - it("defers search shortcut and ignores openSearch when layoutRoot has no scroll view, but keeps search for short scrollable layouts", async () => { const terminal = new VirtualTerminal(60, 8); const tui = new TuiAltScreen(terminal); @@ -3113,6 +3088,10 @@ describe("TuiAltScreen", () => { await terminal.waitForRender(); assert.strictEqual(editor.getText(), "hello"); assert.ok(!terminal.getViewport().some((line) => line.includes("↑ Previous · ↓ Next"))); + + terminal.sendInput(`\x1b[<64;3;${wheelStripRow + 1}M`); + await terminal.waitForRender(); + assert.strictEqual(tui.getFocusedComponent(), wheelFocusRegion); tui.stop(); }); });