Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(autocomplete): improve terminal compatibility and CJK support
Jiang Bohan452ba8b5bb6b
diff --git a/src/agent/cli/autocomplete.ts b/src/agent/cli/autocomplete.tsindex e12ac87a5b..1564983a07 100644--- a/src/agent/cli/autocomplete.ts+++ b/src/agent/cli/autocomplete.ts@@ -3,6 +3,8 @@** Real-time dropdown autocomplete for terminal input* No external dependencies - uses raw terminal control+ *+ * Falls back to simple readline when terminal doesn't support advanced features*/import * as readline from "readline";@@ -30,10 +32,7 @@ const CURSOR_TO_COL = (n: number) => `${ESC}[${n}G`;const RESET = `${ESC}[0m`;const INVERSE = `${ESC}[7m`;const SHOW_CURSOR = `${ESC}[?25h`;-const SAVE_CURSOR = `${ESC}[s`;-const RESTORE_CURSOR = `${ESC}[u`;const CLEAR_TO_END = `${ESC}[J`;-const CURSOR_DOWN = (n: number) => (n > 0 ? `${ESC}[${n}B` : "");// Strip ANSI escape codes to get visual lengthconst ANSI_REGEX = /\x1b\[[0-9;]*m/g;@@ -41,10 +40,99 @@ function stripAnsi(str: string): string {return str.replace(ANSI_REGEX, "");}+/**+ * Get the visual width of a string in terminal columns+ * Full-width characters (CJK, etc.) take 2 columns+ */+function getStringWidth(str: string): number {+ let width = 0;+ for (const char of str) {+ const code = char.codePointAt(0);+ if (code === undefined) continue;++ // Check for full-width characters:+ // - CJK Unified Ideographs (Chinese, Japanese Kanji, Korean Hanja)+ // - CJK Symbols and Punctuation+ // - Hiragana, Katakana+ // - Hangul+ // - Full-width ASCII and symbols+ if (+ (code >= 0x1100 && code <= 0x115f) || // Hangul Jamo+ (code >= 0x2e80 && code <= 0x9fff) || // CJK+ (code >= 0xac00 && code <= 0xd7a3) || // Hangul Syllables+ (code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs+ (code >= 0xfe10 && code <= 0xfe1f) || // Vertical forms+ (code >= 0xfe30 && code <= 0xfe6f) || // CJK Compatibility Forms+ (code >= 0xff00 && code <= 0xff60) || // Full-width ASCII+ (code >= 0xffe0 && code <= 0xffe6) || // Full-width symbols+ (code >= 0x20000 && code <= 0x2ffff) // CJK Extension B and beyond+ ) {+ width += 2;+ } else {+ width += 1;+ }+ }+ return width;+}++/**+ * Check if terminal supports advanced cursor control+ */+function isTerminalSupported(): boolean {+ // Check TERM environment variable+ const term = process.env.TERM;+ if (!term) {+ return false;+ }++ // Check if running in known unsupported environments+ const unsupportedTerms = ["dumb", "emacs"];+ if (unsupportedTerms.includes(term.toLowerCase())) {+ return false;+ }++ // Check if stdout is a TTY+ if (!process.stdout.isTTY) {+ return false;+ }++ return true;+}++/**+ * Simple readline input (fallback for unsupported terminals)+ */+function simpleInput(config: AutocompleteConfig): Promise<string> {+ return new Promise((resolve) => {+ const { prompt = "> " } = config;++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ terminal: true,+ });++ rl.question(prompt, (answer) => {+ rl.close();+ resolve(answer);+ });++ rl.on("close", () => {+ resolve("");+ });+ });+}+/*** Read a line with real-time autocomplete dropdown+ * Falls back to simple readline on unsupported terminals*/export function autocompleteInput(config: AutocompleteConfig): Promise<string> {+ // Fall back to simple input if terminal doesn't support advanced features+ if (!isTerminalSupported()) {+ return simpleInput(config);+ }+return new Promise((resolve) => {const { getSuggestions, prompt = "> ", maxSuggestions = 5 } = config;@@ -55,12 +143,14 @@ export function autocompleteInput(config: AutocompleteConfig): Promise<string> {let cursorPos = 0;let suggestions: AutocompleteOption[] = [];let selectedIndex = -1;- let initialized = false;+ let lastRenderedLines = 0; // Track how many lines we rendered (for cleanup)// Enable raw modeif (stdin.isTTY) {stdin.setRawMode(true);}++ // Set up keypress eventsreadline.emitKeypressEvents(stdin);const cleanup = () => {@@ -71,43 +161,40 @@ export function autocompleteInput(config: AutocompleteConfig): Promise<string> {stdin.removeListener("keypress", onKeypress);};- const render = () => {- if (!initialized) {- // First render - save cursor position as anchor- stdout.write(SAVE_CURSOR);- initialized = true;- } else {- // Restore to anchor and clear everything after it- stdout.write(RESTORE_CURSOR);+ const clearDisplay = () => {+ // Move to beginning of current line+ stdout.write("\r");+ // Clear current line+ stdout.write(CLEAR_LINE);+ // Clear any suggestion lines below+ if (lastRenderedLines > 0) {stdout.write(CLEAR_TO_END);- // Re-save in case terminal scrolled- stdout.write(SAVE_CURSOR);}+ };++ const render = () => {+ clearDisplay();// Write prompt and inputstdout.write(`${prompt}${input}`);- // Calculate cursor position accounting for line wrapping+ // Calculate cursor position accounting for line wrapping and wide charactersconst termWidth = stdout.columns || 80;- const promptVisualLen = stripAnsi(prompt).length;- const cursorOffset = promptVisualLen + cursorPos;+ const promptVisualWidth = getStringWidth(stripAnsi(prompt));+ // Calculate visual width of input up to cursor position+ const inputBeforeCursor = input.slice(0, cursorPos);+ const inputVisualWidth = getStringWidth(inputBeforeCursor);+ const cursorOffset = promptVisualWidth + inputVisualWidth;// Handle edge case: when cursor is exactly at line boundary,// show it at end of current line, not start of next line- let cursorRow: number;let cursorCol: number;if (cursorOffset > 0 && cursorOffset % termWidth === 0) {- cursorRow = cursorOffset / termWidth - 1;cursorCol = termWidth;} else {- cursorRow = Math.floor(cursorOffset / termWidth);cursorCol = (cursorOffset % termWidth) + 1;}- // Calculate total lines for suggestions positioning- const totalLength = promptVisualLen + input.length;- const totalLines = Math.ceil(totalLength / termWidth) || 1;-// Get and display suggestions if input starts with /if (input.startsWith("/") && input.length > 1) {suggestions = getSuggestions(input).slice(0, maxSuggestions);@@ -118,8 +205,7 @@ export function autocompleteInput(config: AutocompleteConfig): Promise<string> {selectedIndex = suggestions.length - 1;}- // Move to end of input text before showing suggestions- // Cursor is currently at end of text, just go to new line+ // Move to new line for suggestionsstdout.write("\n");for (let i = 0; i < suggestions.length; i++) {@@ -137,30 +223,26 @@ export function autocompleteInput(config: AutocompleteConfig): Promise<string> {}}- // Move cursor back up to input line (accounting for wrapped lines)- const linesFromEnd = totalLines - 1 - cursorRow;- stdout.write(CURSOR_UP(suggestions.length + linesFromEnd));+ lastRenderedLines = suggestions.length;++ // Move cursor back up to input line+ stdout.write(CURSOR_UP(suggestions.length));stdout.write(CURSOR_TO_COL(cursorCol));+ } else {+ lastRenderedLines = 0;}} else {suggestions = [];selectedIndex = -1;+ lastRenderedLines = 0;}- // Position cursor for wrapped text- // After writing, cursor is at end of text. Move to correct position.- // Go back to start of input block, then move to target row/col- const endRow = totalLines - 1;- if (endRow > cursorRow) {- stdout.write(CURSOR_UP(endRow - cursorRow));- }+ // Position cursor correctly within inputstdout.write(CURSOR_TO_COL(cursorCol));};const submit = (value: string) => {- // Clear suggestions before submitting- stdout.write(RESTORE_CURSOR);- stdout.write(CLEAR_TO_END);+ clearDisplay();stdout.write(`${prompt}${value}\n`);cleanup();resolve(value);@@ -171,12 +253,14 @@ export function autocompleteInput(config: AutocompleteConfig): Promise<string> {// Handle Ctrl+Cif (key.ctrl && key.name === "c") {+ clearDisplay();cleanup();process.exit(0);}// Handle Ctrl+D (EOF)if (key.ctrl && key.name === "d") {+ clearDisplay();cleanup();stdout.write("\n");resolve("");