diff --git a/.changeset/fullscreen-search-cli.md b/.changeset/fullscreen-search-cli.md new file mode 100644 index 00000000000..8cc259a6242 --- /dev/null +++ b/.changeset/fullscreen-search-cli.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/kimi-code": minor +--- + +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 new file mode 100644 index 00000000000..7cde5df8fce --- /dev/null +++ b/.changeset/fullscreen-search-pi-tui.md @@ -0,0 +1,5 @@ +--- +"@moonshot-ai/pi-tui": minor +--- + +Default alternate-screen transcript search to `Ctrl+F` with `↑`/`↓` navigation, and add programmatic search opening. 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..113507a0d72 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: KimiSlashCommand, + 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..b37d537599b 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); + 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: Pick; + }; + 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/components/editor/custom-editor.ts b/apps/kimi-code/src/tui/components/editor/custom-editor.ts index bce1fa0ca0f..e3cf92c5d76 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); @@ -86,8 +86,8 @@ function mapVisibleIdxToRaw(line: string, visibleIdx: number): number { return i; } -function stripSgr(s: string): string { - return s.replace(ANSI_SGR, ''); +function stripNonVisibleSequences(s: string): string { + return s.replace(ANSI_NON_VISIBLE, ''); } function alternateSubmitKey(data: string): Exclude | undefined { @@ -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,45 +693,34 @@ function injectArgumentHint( realTextLength: number, width: number, ): string { - const cursorIdx = line.indexOf(CURSOR_BLOCK); - const cursorPresent = cursorIdx !== -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 = 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)); -} - -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( @@ -734,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/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/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/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/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/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..f908b486e81 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, @@ -18,6 +22,7 @@ function resolve( pluginCommandMap: new Map(), isStreaming: false, isCompacting: false, + tuiMode: 'regular', ...overrides, }); } @@ -26,6 +31,7 @@ describe('resolveUserInput', () => { const options = { isStreaming: false, isCompacting: false, + tuiMode: 'regular' as const, skillCommandMap: new Map([ ['skill:review', 'review'], ['quick', 'review'], @@ -457,6 +463,97 @@ 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, + }, + ui: { mode }, + }, + skillCommandMap: new Map(), + pluginCommandMap: new Map(), + }); + + 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('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/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/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/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(), 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..244d6e772cd 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,187 @@ describe('createTUIState', () => { expect(typeof internals.openUrl).toBe('function'); expect(typeof internals.onRightClickPaste).toBe('function'); }); + + 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 }, + }); + 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+f', 'ctrl+shift+f']); + expect(getKeybindings().getKeys('tui.altScreen.searchPrevious')).toEqual([ + 'up', + 'shift+enter', + 'ctrl+shift+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(); + } + }); + + 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(); + } + }); + + 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(); + } + }); }); 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) | 是 | diff --git a/packages/pi-tui/UPSTREAM.md b/packages/pi-tui/UPSTREAM.md index fcdfc3a9be8..487e385c758 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-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 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`. + +### kitty-caps-lock-modified-letter-normalization — keep + +**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:** `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 17fd1103396..c3a882204d4 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 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: " ", @@ -229,6 +248,11 @@ export class AltScreenSearchComponent implements Component, Focusable { this.input.focused = value; } + setQuery(query: string): void { + this.input.setValue(query); + this.input.setCursor(query.length); + } + setResult(index: number, count: number): void { this.resultIndex = index; this.resultCount = count; @@ -274,21 +298,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 query = this.input.getValue(); - const result = !query + const result = !query.trim() ? "" : this.resultCount === 0 ? "No matches" @@ -302,8 +314,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..4914ecf754b 100644 --- a/packages/pi-tui/src/components/input.ts +++ b/packages/pi-tui/src/components/input.ts @@ -68,6 +68,30 @@ export class Input implements Component, Focusable { this.cursor = Math.min(this.cursor, value.length); } + 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; + } + handleInput(data: string): void { // Handle bracketed paste mode // Start of paste: \x1b[200~ 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 37ef33cc6b1..d0d5fc69e7c 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, @@ -378,9 +379,12 @@ 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; - if ((effectiveModifier & MODIFIERS.shift) !== 0 && codepoint >= 65 && codepoint <= 90) { + const normalizeUppercaseLetter = + (effectiveModifier & MODIFIERS.shift) !== 0 || + ((modifier & CAPS_LOCK_BIT) !== 0 && effectiveModifier !== 0); + if (normalizeUppercaseLetter && codepoint >= 65 && codepoint <= 90) { return codepoint + 32; } return codepoint; @@ -721,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, ); @@ -844,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, @@ -1302,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 c4650cbc4b1..595b15f3bac 100644 --- a/packages/pi-tui/src/tui-alt-screen.ts +++ b/packages/pi-tui/src/tui-alt-screen.ts @@ -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 @@ -394,6 +398,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 +587,37 @@ 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) { + 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; } + if (!this.hasSearchableScrollView()) return; + const component = new AltScreenSearchComponent( - (query) => this.updateSearchQuery(query), + (nextQuery) => this.updateSearchQuery(nextQuery), this.searchNavigationButtonStyle, ); + 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 +630,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 { @@ -809,7 +844,7 @@ export class TuiAltScreen extends TuiBase implements ViewportTUI { // 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 }; } @@ -936,8 +971,14 @@ 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); + 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) { + this.closeSearch(); + } + this.setFocus(focusTarget); + } if (result.capture) this.mouseCapture = result.target; return ( result.render ?? diff --git a/packages/pi-tui/test/input.test.ts b/packages/pi-tui/test/input.test.ts index e1f3f81726f..548a01f810d 100644 --- a/packages/pi-tui/test/input.test.ts +++ b/packages/pi-tui/test/input.test.ts @@ -34,6 +34,50 @@ describe("Input component", () => { assert.strictEqual(input.getValue(), "\\x"); }); + 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.setCursor(2); + assert.strictEqual(ascii.getCursor(), 2); + ascii.handleInput("\x7f"); + 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("你好🙂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(), "你好🙂"); + unicode.handleInput("\x7f"); + 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", () => { it("supports a custom prompt and styled placeholder", () => { const input = new Input({ 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 4494508e10f..57dd2d4f984 100644 --- a/packages/pi-tui/test/keys.test.ts +++ b/packages/pi-tui/test/keys.test.ts @@ -671,5 +671,20 @@ describe("parseKey", () => { it("should parse double bracket pageUp", () => { assert.strictEqual(parseKey("\x1b[[5~"), "pageUp"); }); + + 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); + 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..be57604d8c3 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,6 +958,249 @@ describe("TuiAltScreen", () => { assert.ok(!populated.some((line) => line.includes("Find in transcript"))); }); + it("formats custom search controls, handles narrow fallback, and suppresses whitespace no-matches", () => { + const originalKeybindings = getKeybindings(); + const changes: string[] = []; + 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); + 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"))); + } 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, { @@ -972,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`); @@ -983,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(); }); @@ -1137,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( @@ -1162,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(); @@ -2743,4 +2986,112 @@ describe("TuiAltScreen", () => { assert.ok(tui.viewportTop < topWithoutMenu); 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); + 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"))); + + 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, basis: 0, grow: 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 tui = new TuiAltScreen(terminal); + 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(); + }); + + 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 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, basis: 0, grow: 1 }, wheelFocusRegion, 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"))); + + 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); + 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 = wheelStripRow + 3; + 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"))); + + terminal.sendInput(`\x1b[<64;3;${wheelStripRow + 1}M`); + await terminal.waitForRender(); + assert.strictEqual(tui.getFocusedComponent(), wheelFocusRegion); + tui.stop(); + }); });