The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): modified Enter and bare LF insert a newline in the composer across IDE and macOS terminals (#87854)
brooklyn!21c1fe6686c6
diff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.tsindex aa07bf9a097..f8585521cb5 100644--- a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts+++ b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts@@ -105,6 +105,64 @@ describe('parseMultipleKeypresses text control splitting', () => {})})+describe('parseMultipleKeypresses CSI u (Kitty keyboard protocol)', () => {+ it('parses Shift+Enter (CSI 13;2u) as return with shift=true', () => {+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, '\x1b[13;2u')++ expect(keys).toHaveLength(1)+ expect(keys[0]).toMatchObject({+ kind: 'key',+ name: 'return',+ shift: true,+ ctrl: false,+ meta: false,+ super: false+ })+ })++ it('parses Ctrl+Enter (CSI 13;5u) as return with ctrl=true', () => {+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, '\x1b[13;5u')++ expect(keys).toHaveLength(1)+ expect(keys[0]).toMatchObject({+ kind: 'key',+ name: 'return',+ shift: false,+ ctrl: true,+ meta: false,+ super: false+ })+ })++ it('parses Cmd+Enter (CSI 13;9u) as return with super=true', () => {+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, '\x1b[13;9u')++ expect(keys).toHaveLength(1)+ expect(keys[0]).toMatchObject({+ kind: 'key',+ name: 'return',+ shift: false,+ ctrl: false,+ meta: false,+ super: true+ })+ })++ it('parses plain Enter (CSI 13u) as return with no modifiers', () => {+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, '\x1b[13u')++ expect(keys).toHaveLength(1)+ expect(keys[0]).toMatchObject({+ kind: 'key',+ name: 'return',+ shift: false,+ ctrl: false,+ meta: false,+ super: false+ })+ })+})+describe('mouse wheel modifier decoding', () => {// SGR mouse format: ESC [ < button ; col ; row M// Wheel up = 64 (0x40), wheel down = 65 (0x41).diff --git a/ui-tui/src/__tests__/terminalParity.test.ts b/ui-tui/src/__tests__/terminalParity.test.tsindex e103b0b68c8..d1f36f49d97 100644--- a/ui-tui/src/__tests__/terminalParity.test.ts+++ b/ui-tui/src/__tests__/terminalParity.test.ts@@ -26,6 +26,56 @@ describe('terminalParityHints', () => {})it('suppresses IDE setup hint when keybindings are already configured', async () => {+ const readFile = vi.fn().mockResolvedValue(+ JSON.stringify([+ {+ key: 'cmd+c',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus && terminalTextSelected',+ args: { text: '\u001b[99;13u' }+ },+ {+ key: 'shift+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[13;2u' }+ },+ {+ key: 'ctrl+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[13;5u' }+ },+ {+ key: 'cmd+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[13;9u' }+ },+ {+ key: 'cmd+z',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[122;9u' }+ },+ {+ key: 'shift+cmd+z',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[122;10u' }+ }+ ])+ )++ const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {+ fileOps: { readFile },+ homeDir: '/tmp/fake-home'+ })++ expect(hints.some(h => h.key === 'ide-setup')).toBe(false)+ })++ it('shows IDE setup hint when keybindings use legacy sequences', async () => {const readFile = vi.fn().mockResolvedValue(JSON.stringify([{@@ -72,6 +122,7 @@ describe('terminalParityHints', () => {homeDir: '/tmp/fake-home'})- expect(hints.some(h => h.key === 'ide-setup')).toBe(false)+ // Legacy bindings don't match current CSI u targets, so setup is still needed+ expect(hints.some(h => h.key === 'ide-setup')).toBe(true)})})diff --git a/ui-tui/src/__tests__/terminalSetup.test.ts b/ui-tui/src/__tests__/terminalSetup.test.tsindex a9664a6dd45..dee678b90c8 100644--- a/ui-tui/src/__tests__/terminalSetup.test.ts+++ b/ui-tui/src/__tests__/terminalSetup.test.ts@@ -96,7 +96,11 @@ describe('configureTerminalKeybindings', () => {expect(written).toContain('terminalTextSelected')expect(written).toContain('\\u001b[99;13u')expect(written).toContain('shift+enter')+ expect(written).toContain('\\u001b[13;2u')expect(written).toContain('cmd+enter')+ expect(written).toContain('\\u001b[13;9u')+ expect(written).toContain('ctrl+enter')+ expect(written).toContain('\\u001b[13;5u')expect(written).toContain('cmd+z')})@@ -352,19 +356,19 @@ describe('configureTerminalKeybindings', () => {key: 'shift+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: '\\\r\n' }+ args: { text: '\u001b[13;2u' }},{key: 'ctrl+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: '\\\r\n' }+ args: { text: '\u001b[13;5u' }},{key: 'cmd+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: '\\\r\n' }+ args: { text: '\u001b[13;9u' }},{key: 'cmd+z',@@ -396,4 +400,104 @@ describe('configureTerminalKeybindings', () => {})).resolves.toBe(false)})++ it('prompts for setup when legacy \\\r\n bindings are present', async () => {+ // Old keybindings using the legacy \\\r\n sequence should be detected as+ // incomplete — they need migration to the CSI u encoding.+ const readLegacy = vi.fn().mockResolvedValue(+ JSON.stringify([+ {+ key: 'cmd+c',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus && terminalTextSelected',+ args: { text: '\u001b[99;13u' }+ },+ {+ key: 'shift+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ },+ {+ key: 'ctrl+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ },+ {+ key: 'cmd+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ },+ {+ key: 'cmd+z',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[122;9u' }+ },+ {+ key: 'shift+cmd+z',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\u001b[122;10u' }+ }+ ])+ )++ await expect(+ shouldPromptForTerminalSetup({+ env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,+ fileOps: { readFile: readLegacy }+ })+ ).resolves.toBe(true)+ })++ it('migrates legacy \\\r\n bindings to CSI u sequences', async () => {+ const mkdir = vi.fn().mockResolvedValue(undefined)+ const readFile = vi.fn().mockResolvedValue(+ JSON.stringify([+ {+ key: 'shift+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ },+ {+ key: 'ctrl+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ },+ {+ key: 'cmd+enter',+ command: 'workbench.action.terminal.sendSequence',+ when: 'terminalFocus',+ args: { text: '\\\r\n' }+ }+ ])+ )+ const writeFile = vi.fn().mockResolvedValue(undefined)+ const copyFile = vi.fn().mockResolvedValue(undefined)++ const result = await configureTerminalKeybindings('vscode', {+ fileOps: { copyFile, mkdir, readFile, writeFile },+ homeDir: '/Users/me',+ platform: 'darwin'+ })++ expect(result.success).toBe(true)+ expect(result.requiresRestart).toBe(true)+ expect(result.message).toContain('migrated 3 legacy bindings to CSI u encoding')+ const written = writeFile.mock.calls[0]?.[1] as string+ const parsed = JSON.parse(written)+ // All three Enter bindings should now use CSI u sequences+ const enterBindings = parsed.filter((b: { key: string }) =>+ ['shift+enter', 'ctrl+enter', 'cmd+enter'].includes(b.key)+ )+ expect(enterBindings).toHaveLength(3)+ expect(enterBindings.find((b: { key: string }) => b.key === 'shift+enter')?.args?.text).toBe('\u001b[13;2u')+ expect(enterBindings.find((b: { key: string }) => b.key === 'ctrl+enter')?.args?.text).toBe('\u001b[13;5u')+ expect(enterBindings.find((b: { key: string }) => b.key === 'cmd+enter')?.args?.text).toBe('\u001b[13;9u')+ })})diff --git a/ui-tui/src/__tests__/textInputReturnAction.test.ts b/ui-tui/src/__tests__/textInputReturnAction.test.tsnew file mode 100644index 00000000000..5548bb80906--- /dev/null+++ b/ui-tui/src/__tests__/textInputReturnAction.test.ts@@ -0,0 +1,79 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const originalPlatform = process.platform++async function importTextInput(platform: NodeJS.Platform) {+ vi.resetModules()+ Object.defineProperty(process, 'platform', { value: platform })++ return import('../components/textInput.js')+}++afterEach(() => {+ Object.defineProperty(process, 'platform', { value: originalPlatform })+ vi.resetModules()+})++const key = (overrides: Record<string, unknown> = {}) =>+ ({ ctrl: false, meta: false, return: true, shift: false, super: false, ...overrides }) as any++describe('shouldInsertNewlineOnReturn', () => {+ it('keeps plain Enter (CR) as submit on macOS', async () => {+ const { shouldInsertNewlineOnReturn } = await importTextInput('darwin')++ expect(shouldInsertNewlineOnReturn(key(), '\r')).toBe(false)+ })++ it('accepts bare LF as a macOS multiline fallback', async () => {+ const { shouldInsertNewlineOnReturn } = await importTextInput('darwin')++ expect(shouldInsertNewlineOnReturn(key(), '\n')).toBe(true)+ })++ it('inserts a newline for explicit modified Enter chords on macOS', async () => {+ const { shouldInsertNewlineOnReturn } = await importTextInput('darwin')++ expect(shouldInsertNewlineOnReturn(key({ ctrl: true }), '\r')).toBe(true)+ expect(shouldInsertNewlineOnReturn(key({ shift: true }), '\r')).toBe(true)+ expect(shouldInsertNewlineOnReturn(key({ meta: true }), '\r')).toBe(true)+ expect(shouldInsertNewlineOnReturn(key({ super: true }), '\r')).toBe(true)+ })++ it('inserts a newline for Shift/Ctrl Enter on non-macOS', async () => {+ const { shouldInsertNewlineOnReturn } = await importTextInput('linux')++ expect(shouldInsertNewlineOnReturn(key({ shift: true }), '\r')).toBe(true)+ expect(shouldInsertNewlineOnReturn(key({ ctrl: true }), '\r')).toBe(true)+ })++ it('keeps plain Enter as submit on a plain non-macOS terminal', async () => {+ const prev = { ...process.env }+ for (const k of ['SSH_CONNECTION', 'SSH_CLIENT', 'SSH_TTY', 'WT_SESSION', 'GHOSTTY_RESOURCES_DIR', 'GHOSTTY_BIN_DIR', 'WSL_DISTRO_NAME']) {+ delete process.env[k]+ }+ process.env.TERM = 'xterm-256color'+ process.env.TERM_PROGRAM = ''++ try {+ const { shouldInsertNewlineOnReturn } = await importTextInput('linux')++ expect(shouldInsertNewlineOnReturn(key(), '\n')).toBe(false)+ expect(shouldInsertNewlineOnReturn(key(), '\r')).toBe(false)+ } finally {+ process.env = prev+ }+ })++ it('accepts a bare LF as a multiline fallback over SSH on non-macOS', async () => {+ const prev = { ...process.env }+ process.env.SSH_CONNECTION = '10.0.0.1 22 10.0.0.2 22'++ try {+ const { shouldInsertNewlineOnReturn } = await importTextInput('linux')++ expect(shouldInsertNewlineOnReturn(key(), '\n')).toBe(true)+ } finally {+ process.env = prev+ }+ })+})diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsxindex a13fdd77db6..fcea86d78d3 100644--- a/ui-tui/src/components/textInput.tsx+++ b/ui-tui/src/components/textInput.tsx@@ -229,6 +229,32 @@ export function shouldPreserveCtrlJNewline(env: MinimalEnv = process.env): boolereturn (env.WSL_DISTRO_NAME ?? '').toLowerCase().includes('microsoft')}+type ReturnDecisionKey = {+ ctrl: boolean+ meta: boolean+ return?: boolean+ shift?: boolean+ super?: boolean+}++/**+ * Decide whether a Return keypress should insert a newline instead of+ * submitting. An explicit modified Enter (Shift/Ctrl, or the platform action+ * modifier) always inserts a newline. Beyond that, terminals that can't send a+ * distinct Shift+Enter collapse a modified Enter / Ctrl+J down to a bare LF —+ * shouldPreserveCtrlJNewline() detects that via env (SSH, Windows Terminal,+ * Ghostty, WSL), and macOS terminals (Terminal.app, iTerm2 defaults) do it too+ * but aren't env-detectable, so a bare LF is treated as a newline there as well.+ * Plain Enter (CR) stays submit everywhere.+ */+export function shouldInsertNewlineOnReturn(key: ReturnDecisionKey, sequence = ''): boolean {+ if (key.shift || key.ctrl || (isMac ? isActionMod(key) : key.meta)) {+ return true+ }++ return sequence === '\n' && (isMac || shouldPreserveCtrlJNewline())+}+function prevPos(s: string, p: number) {const pos = snapPos(s, p)let prev = 0@@ -1288,9 +1314,9 @@ export function TextInput({const range = selRange()const pending = valueForReturnSubmit(vRef.current, curRef.current, inp, range)const sequence = (event.keypress as { sequence?: string }).sequence- const preserveBareLineFeed = shouldPreserveCtrlJNewline() && sequence === '\n'+ const insertNewline = shouldInsertNewlineOnReturn(k, sequence ?? '')- if (k.shift || k.ctrl || preserveBareLineFeed || (isMac ? isActionMod(k) : k.meta)) {+ if (insertNewline) {commit(ins(pending.value, pending.cursor, '\n'), pending.cursor + 1)} else {cbSubmit.current?.(pending.value)diff --git a/ui-tui/src/lib/terminalSetup.ts b/ui-tui/src/lib/terminalSetup.tsindex 7d387797d04..ed8cba2673f 100644--- a/ui-tui/src/lib/terminalSetup.ts+++ b/ui-tui/src/lib/terminalSetup.ts@@ -26,7 +26,57 @@ export type TerminalSetupResult = {const DEFAULT_FILE_OPS: FileOps = { copyFile, mkdir, readFile, writeFile }const COPY_SEQUENCE = '\u001b[99;13u'-const MULTILINE_SEQUENCE = '\\\r\n'+// Kitty keyboard protocol CSI u sequences for modified Enter keys.+// Codepoint 13 = Enter; modifier encoding: 1 + (shift?1:0) + (alt?2:0) + (ctrl?4:0) + (super?8:0).+// These are recognized by Ink's parse-keypress CSI u handler and produce+// key.return=true with the correct modifier flags, so textInput.tsx's+// existing k.return && (k.shift || k.ctrl || ...) branch inserts a newline.+const SHIFT_ENTER_SEQUENCE = '\u001b[13;2u' // modifier 2 = shift+const CTRL_ENTER_SEQUENCE = '\u001b[13;5u' // modifier 5 = ctrl+const SUPER_ENTER_SEQUENCE = '\u001b[13;9u' // modifier 9 = super (Cmd on macOS)++// Legacy multiline sequence used before CSI u migration. Old keybindings+// that still send this will be auto-replaced on next terminal setup.+const LEGACY_MULTILINE_SEQUENCE = '\\\r\n'++/**+ * Migrate legacy keybindings that used the old \\\r\n escape sequence+ * for modified Enter keys. Those sequences arrived at Ink as separate+ * key events (backslash + return), causing unintended submissions.+ * The replacement CSI u sequences are parsed correctly by Ink's+ * parse-keypress handler and produce the proper modifier flags.+ */+function migrateLegacyBindings(keybindings: unknown[]): number {+ let migrated = 0++ const replacements: Map<string, string> = new Map([+ ['shift+enter', SHIFT_ENTER_SEQUENCE],+ ['ctrl+enter', CTRL_ENTER_SEQUENCE],+ ['cmd+enter', SUPER_ENTER_SEQUENCE]+ ])++ for (let i = 0; i < keybindings.length; i++) {+ const entry = keybindings[i]++ if (!isKeybinding(entry)) {+ continue+ }++ const replacement = replacements.get(entry.key ?? '')++ if (+ replacement &&+ entry.command === 'workbench.action.terminal.sendSequence' &&+ entry.when === 'terminalFocus' &&+ entry.args?.text === LEGACY_MULTILINE_SEQUENCE+ ) {+ keybindings[i] = { ...entry, args: { text: replacement } }+ migrated += 1+ }+ }++ return migrated+}const TERMINAL_META: Record<SupportedTerminal, { appName: string; label: string }> = {vscode: { appName: 'Code', label: 'VS Code' },@@ -46,19 +96,19 @@ const BASE_BINDINGS: Keybinding[] = [key: 'shift+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: MULTILINE_SEQUENCE }+ args: { text: SHIFT_ENTER_SEQUENCE }},{key: 'ctrl+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: MULTILINE_SEQUENCE }+ args: { text: CTRL_ENTER_SEQUENCE }},{key: 'cmd+enter',command: 'workbench.action.terminal.sendSequence',when: 'terminalFocus',- args: { text: MULTILINE_SEQUENCE }+ args: { text: SUPER_ENTER_SEQUENCE }},{key: 'cmd+z',@@ -335,6 +385,7 @@ export async function configureTerminalKeybindings(}}+ const migrated = migrateLegacyBindings(keybindings)const targets = targetBindings(platform)const conflicts = targets.filter(target =>@@ -360,23 +411,33 @@ export async function configureTerminalKeybindings(}}- if (!added) {+ if (!added && !migrated) {return {success: true,message: `${meta.label} terminal keybindings already configured.`}}- if (hasExistingFile) {+ if (hasExistingFile && (added || migrated)) {await backupFile(keybindingsFile, ops)}await ops.writeFile(keybindingsFile, `${JSON.stringify(keybindings, null, 2)}\n`, 'utf8')+ const parts: string[] = []++ if (added) {+ parts.push(`Added ${added} ${meta.label} terminal keybinding${added === 1 ? '' : 's'}`)+ }++ if (migrated) {+ parts.push(`migrated ${migrated} legacy binding${migrated === 1 ? '' : 's'} to CSI u encoding`)+ }+return {success: true,requiresRestart: true,- message: `Added ${added} ${meta.label} terminal keybinding${added === 1 ? '' : 's'} in ${keybindingsFile}`+ message: `${parts.join(', ')} in ${keybindingsFile}`}} catch (error) {return {