d3ro-voice/packages/core/__tests__/terminal-prompt.test.ts

365 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from 'vitest'
import {
TerminalKeystrokeTracker,
composeHangul2Set,
decideSuggestion,
extractTerminalActiveContext,
extractTerminalPromptPrefix,
isTerminalApp,
isTerminalOrDeveloperSurface
} from '../src/input-intelligence'
describe('terminal prompt extraction', () => {
it('takes the Claude Code input line and ignores the status line below it', () => {
const screen = [
'● Wrote 3 files',
'',
'╭──────────────────────────────────────╮',
'│ > 오늘 회의 내용을 정리해서 │',
'╰──────────────────────────────────────╯',
' ◑ OPUS 5 · 5 medium │ CTX ▕░░▏',
].join('\n')
expect(extractTerminalPromptPrefix(screen)).toBe('오늘 회의 내용을 정리해서')
})
it('joins wrapped continuation lines of a long prompt', () => {
const screen = ['──────────', '> 긴 문장을 쓰다 보면', ' 줄이 바뀌어서 이어진다', '──────────', ' ? for shortcuts'].join('\n')
expect(extractTerminalPromptPrefix(screen)).toBe('긴 문장을 쓰다 보면 줄이 바뀌어서 이어진다')
})
it('reads shell prompts', () => {
expect(extractTerminalPromptPrefix('PS C:\\Users\\me> git commit -m "고친')).toBe('git commit -m "고친')
expect(extractTerminalPromptPrefix('C:\\work> dir')).toBe('dir')
expect(extractTerminalPromptPrefix('me@host:~/app$ npm run')).toBe('npm run')
expect(extractTerminalPromptPrefix('❯ cargo build')).toBe('cargo build')
})
it('returns null when only output is on screen, and does not mistake percentages for prompts', () => {
expect(extractTerminalPromptPrefix('Compiling...\n100% 완료\nDone in 3s')).toBeNull()
expect(extractTerminalPromptPrefix('')).toBeNull()
})
it('an empty prompt yields an empty prefix', () => {
expect(extractTerminalPromptPrefix('output\n> ')).toBe('')
})
it('recognises terminal apps and developer surfaces', () => {
expect(isTerminalApp('WindowsTerminal.exe')).toBe(true)
expect(isTerminalApp('Kitedesk.exe')).toBe(true)
expect(isTerminalApp('wezterm-gui.exe')).toBe(true)
expect(isTerminalApp('neovide.exe')).toBe(true)
expect(isTerminalApp('KakaoTalk.exe')).toBe(false)
expect(isTerminalApp(null)).toBe(false)
expect(isTerminalOrDeveloperSurface('WindowsTerminal.exe')).toBe(true)
expect(isTerminalOrDeveloperSurface('Kitedesk.exe')).toBe(true)
expect(isTerminalOrDeveloperSurface('Code.exe')).toBe(true)
expect(isTerminalOrDeveloperSurface('Agent Switchboard.exe')).toBe(true)
expect(isTerminalOrDeveloperSurface('KakaoTalk.exe')).toBe(false)
})
it('extracts active Vim insert line, command line, and normal mode from terminal screen snapshots', () => {
const prevVim = ['hello world', '~', '~', '-- INSERT -- 1,12 All'].join(
'\n'
)
const currVim = [
'hello world dkssudgktpdy',
'~',
'~',
'-- INSERT -- 1,25 All'
].join('\n')
const insertCtx = extractTerminalActiveContext(prevVim, currVim)
expect(insertCtx).toEqual({
prefix: 'hello world dkssudgktpdy',
caretReliable: true,
vimMode: 'insert',
isVimScreen: true
})
const normalScreen = ['hello world', '~', '~', ' 1,11 All'].join(
'\n'
)
const normalCtx = extractTerminalActiveContext(currVim, normalScreen)
expect(normalCtx.vimMode).toBe('normal')
expect(normalCtx.caretReliable).toBe(false)
const cmdScreen = ['hello world', '~', '~', ':ㅈㅂ'].join('\n')
const cmdCtx = extractTerminalActiveContext(normalScreen, cmdScreen)
expect(cmdCtx).toEqual({
prefix: ':ㅈㅂ',
caretReliable: true,
vimMode: 'command',
isVimScreen: true
})
})
it('composes 2-set Hangul and tracks Vim modes + trailing spaces in TerminalKeystrokeTracker', () => {
expect(composeHangul2Set('dkssudgktpdy')).toBe('안녕하세요')
expect(composeHangul2Set('wq')).toBe('ㅈㅂ')
expect(composeHangul2Set('gtihubdp')).toBe('ㅎ샤ㅗㅕㅠ에')
const tracker = new TerminalKeystrokeTracker()
const pressChar = (ch: string, koreanIme = false): void => {
const upper = ch.toUpperCase()
const vk = ch === ':' ? 0xba : ch === ' ' ? 0x20 : upper.charCodeAt(0)
const shift = ch === ':' || (ch >= 'A' && ch <= 'Z')
tracker.onKeyDown({
hwnd: 101,
vk,
shift,
ctrl: false,
alt: false,
meta: false,
koreanIme
})
}
// Esc → Vim Normal mode (h/j/k/l ignored) → 'i' → Insert mode → 'dkssudgktpdy '
tracker.onKeyDown({ hwnd: 101, vk: 0x1b, shift: false, ctrl: false, alt: false, meta: false })
for (const ch of 'jjlli') pressChar(ch, false)
expect(tracker.vimMode).toBe('insert')
for (const ch of 'dkssudgktpdy ') pressChar(ch, false)
expect(tracker.getSnapshot(101)).toEqual({
prefix: 'dkssudgktpdy ',
caretReliable: true,
isComposing: false,
vimMode: 'insert'
})
// Windows Terminal strips trailing space from screen rows; reconcileWithScreen restores it
const screenWithoutSpace = ['dkssudgktpdy', '~', '-- INSERT --'].join('\n')
expect(tracker.reconcileWithScreen(screenWithoutSpace)).toEqual({
prefix: 'dkssudgktpdy ',
caretReliable: true,
isComposing: false,
vimMode: 'insert'
})
// Programmatic replacement updates the tracked buffer
tracker.applyReplacement('dkssudgktpdy '.length, '안녕하세요 ')
expect(tracker.currentPrefix()).toBe('안녕하세요 ')
// Esc → ':' → 'wq' in Korean IME → ':ㅈㅂ'
tracker.onKeyDown({ hwnd: 101, vk: 0x1b, shift: false, ctrl: false, alt: false, meta: false })
expect(tracker.vimMode).toBe('normal')
pressChar(':', true)
expect(tracker.vimMode).toBe('command')
pressChar('w', true)
pressChar('q', true)
expect(tracker.getSnapshot(101)).toEqual({
prefix: ':ㅈㅂ',
caretReliable: true,
isComposing: true,
vimMode: 'command'
})
})
it('reconciles IME VK_PROCESSKEY (vk=null) Hangul after : in Vim command line and shell prompts under nvim title', () => {
const tracker = new TerminalKeystrokeTracker()
const title = 'nvim - D3RO Terminal & Vim E2E'
// 1. Initial Vim normal screen
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n', title)).toEqual({
prefix: '',
caretReliable: false,
isComposing: false,
vimMode: 'normal'
})
// 2. ':' sent as hardware VK (0xba + Shift), followed by IME vk=null for 'ㅈ' and 'ㅂ'
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0xba, shift: true, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:ㅈㅂ', title)).toEqual({
prefix: ':ㅈㅂ',
caretReliable: true,
isComposing: false,
vimMode: 'command'
})
tracker.applyReplacement(2, 'wq')
// 2b. Even if a stale ':wq' snapshot was reconciled right before a new ':ㅂ!' command line,
// the rendered ':ㅂ!' command line must win over stale ':wq:!'.
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:wq', title)).toEqual({
prefix: ':wq',
caretReliable: true,
isComposing: false,
vimMode: 'command'
})
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0xba, shift: true, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0x31, shift: true, ctrl: false, alt: false, meta: false })
expect(tracker.reconcileWithScreen('안녕하세요 \n~\n~\n:ㅂ!', title)).toEqual({
prefix: ':ㅂ!',
caretReliable: true,
isComposing: false,
vimMode: 'command'
})
// 3. Shell prompt screen inside a window whose title still contains 'nvim'
tracker.onPointerOrFocusChange(202)
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: null, shift: false, ctrl: false, alt: false, meta: false })
tracker.onKeyDown({ hwnd: 202, windowTitle: title, vk: 0x20, shift: false, ctrl: false, alt: false, meta: false })
expect(tracker.reconcileWithScreen('Windows PowerShell\nPS D:\\workspace> 퍄ㅡ ', title)).toEqual({
prefix: 'PS D:\\workspace> 퍄ㅡ '.replace('PS D:\\workspace> ', ''),
caretReliable: true,
isComposing: false,
vimMode: null
})
})
it('reconciles xterm-helper-textarea without repeating replacements when textarea.value stays stale', () => {
const tracker = new TerminalKeystrokeTracker()
const hwnd = 303
const title = 'Agent Switchboard'
// User types 'h','e','l','l','o',' ' while koreanIme initially reported false on keydown
for (const vk of [0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20]) {
tracker.onKeyDown({
hwnd,
windowTitle: title,
vk,
shift: false,
ctrl: false,
alt: false,
meta: false,
koreanIme: false
})
}
// xterm-helper-textarea receives Hangul from IME ('ㅗ디ㅣㅐ '), proving Korean IME is active
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ ', hwnd, title)).toEqual({
prefix: 'ㅗ디ㅣㅐ ',
caretReliable: true,
isComposing: false,
vimMode: null
})
// TypoCorrectionService replaces 'ㅗ디ㅣㅐ ' (6 chars) with 'hello '
tracker.applyReplacement(6, 'hello ')
// Next snapshot 400ms later: xterm.textarea.value is STILL 'ㅗ디ㅣㅐ ' (xterm ignores Backspace/SendInput),
// but reconcileWithXtermValue must return 'hello ' so it never loops into 'hhhhhhhhhhhello'!
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ ', hwnd, title)).toEqual({
prefix: 'hello ',
caretReliable: true,
isComposing: false,
vimMode: null
})
// User continues typing 'w','o','r','l','d',' ' while Chromium HWND still reports koreanIme: false;
// because _imm32Supported is false, koreanIme: false does NOT override _koreanIme = true!
for (const vk of [0x57, 0x4f, 0x52, 0x4c, 0x44, 0x20]) {
tracker.onKeyDown({
hwnd,
windowTitle: title,
vk,
shift: false,
ctrl: false,
alt: false,
meta: false,
koreanIme: false
})
}
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ재깅 ', hwnd, title)).toEqual({
prefix: 'hello 재깅 ',
caretReliable: true,
isComposing: false,
vimMode: null
})
tracker.applyReplacement(3, 'world ')
expect(tracker.reconcileWithXtermValue('ㅗ디ㅣㅐ재깅 ', hwnd, title)).toEqual({
prefix: 'hello world ',
caretReliable: true,
isComposing: false,
vimMode: null
})
// Even if the host app clears textarea.value to '' mid-line (e.g., on Space or compositionend),
// the active line is preserved until Enter/Ctrl+C/Esc.
expect(tracker.reconcileWithXtermValue('', hwnd, title)).toEqual({
prefix: 'hello world ',
caretReliable: true,
isComposing: false,
vimMode: null
})
// Pressing Enter (0x0D) resets the tracked line
tracker.onKeyDown({
hwnd,
windowTitle: title,
vk: 0x0d,
shift: false,
ctrl: false,
alt: false,
meta: false
})
expect(tracker.reconcileWithXtermValue('', hwnd, title)).toEqual({
prefix: '',
caretReliable: false,
isComposing: false,
vimMode: null
})
// Pressing Ctrl+C or Esc followed by 'git' or Korean 'dd' ('ㅇㅇ') must NOT falsely enter Vim mode
tracker.onKeyDown({
hwnd,
windowTitle: title,
vk: 0x1b,
shift: false,
ctrl: false,
alt: false,
meta: false
})
for (const vk of [0x47, 0x49, 0x54]) {
tracker.onKeyDown({
hwnd,
windowTitle: title,
vk,
shift: false,
ctrl: false,
alt: false,
meta: false,
koreanIme: true
})
}
expect(tracker.vimMode).toBeNull()
expect(tracker.currentPrefix()).toBe('햣')
})
})
describe('a visible suggestion survives a typing pause', () => {
const base = {
enabled: true,
modelAvailable: true,
composing: false,
hasSelection: false,
isPassword: false,
isEditable: true,
appName: 'KakaoTalk.exe',
excludedApps: [],
editedSinceFocus: false,
typedRecently: false,
prefix: '내일 몇 시에 볼까',
idleMs: 5000,
triggerDelayMs: 100,
minPrefixChars: 4,
sinceLastRequestMs: 60_000,
minIntervalMs: 5000,
requestsThisMinute: 0,
maxRequestsPerMinute: 6,
requestsToday: 0,
dailyBudget: 500,
}
it('keeps the overlay while the user reads and picks a candidate', () => {
expect(decideSuggestion({ ...base, overlayVisible: true })).toEqual({ action: 'skip', reason: 'already-visible' })
})
it('still refuses to start a new suggestion without typing', () => {
expect(decideSuggestion({ ...base, overlayVisible: false })).toEqual({ action: 'clear', reason: 'not-typing' })
})
})