From e0e2f689cf02d81ff459646223e2d835a8ea75b2 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sun, 15 Nov 2026 18:38:25 +0100 Subject: [PATCH 01/12] feat(mobile): Send on Enter for the pinned CJK input field A per-device setting next to CJK Input keeps typed text in the pinned field until Enter instead of streaming it to the PTY, so a phone user can scroll the terminal and edit an answer before sending (Termux-style). One line goes as text + CR, several lines as one bracketed paste with a delayed Enter, like the prompt composer. Shift+Enter is a newline, Escape clears, Backspace on an empty field still reaches the PTY, and autocorrect is on in this mode. The field grows with its text and the keyboard layout reserves its real height. Co-Authored-By: Claude Opus 5.5 --- .changeset/cjk-send-on-enter.md | 5 + docs/wiki/Settings-Reference.md | 1 + src/web/public/app.js | 5 + src/web/public/index.html | 7 ++ src/web/public/input-cjk.js | 77 +++++++++++- src/web/public/mobile-handlers.js | 6 +- src/web/public/settings-ui.js | 7 +- test/input-cjk-hold.test.ts | 202 ++++++++++++++++++++++++++++++ 8 files changed, 307 insertions(+), 3 deletions(-) create mode 100644 .changeset/cjk-send-on-enter.md create mode 100644 test/input-cjk-hold.test.ts diff --git a/.changeset/cjk-send-on-enter.md b/.changeset/cjk-send-on-enter.md new file mode 100644 index 00000000..9241ef1f --- /dev/null +++ b/.changeset/cjk-send-on-enter.md @@ -0,0 +1,5 @@ +--- +"aicodeman": patch +--- + +Add a per-device "Send on Enter" mode for the pinned CJK input field, so phone users can scroll the terminal while a typed answer waits in the field until Enter. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 821d6ab0..99d00430 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -48,6 +48,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service). | Local Echo | On for touch devices | Paints keystrokes locally and flushes on Enter. See [Input And Voice](Input-And-Voice). | | Keep Size Under Keyboard | On | For local Claude sessions, the on-screen keyboard no longer resizes the session: the terminal keeps its rows and the view scrolls so the prompt sits just above the keyboard. Resizing made Claude reprint its screen and drop transcript lines from history. Codex, Claude's fullscreen mode, remote and Docker sessions resize as before. See [Mobile Guide](Mobile-Guide). | | CJK Input | Off | IME composition through a dedicated text field. | +| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. Shift+Enter adds a line, Esc clears, autocorrect is on. | | Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. | | Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. | | Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. | diff --git a/src/web/public/app.js b/src/web/public/app.js index e2b4c68c..1f178c2a 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -4929,6 +4929,11 @@ class CodemanApp { document.body.classList.toggle('cjk-input-visible', !!showCjk); cjkEl.style.display = showCjk ? 'block' : 'none'; cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true'); + if (typeof CjkInput !== 'undefined') { + CjkInput.setHoldUntilEnter?.( + !!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false) + ); + } if (!showCjk) window.cjkActive = false; if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard(); } diff --git a/src/web/public/index.html b/src/web/public/index.html index 7d1d1430..4ce3de8b 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -2064,6 +2064,13 @@ +
+
+ Input Field: Send on Enter + With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode. +
+ +
Extended Keyboard Bar phone diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 4f5420b7..89d7cccd 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -57,6 +57,10 @@ const CjkInput = (() => { let _dictationActive = false; let _dictationDecayTimer = null; let _printableKeydownAt = null; + // Send-on-Enter mode (setting cjkInputHoldUntilEnter): typed text stays in the + // field until Enter, like a chat box, instead of streaming to the PTY as it is + // typed. Lets a phone user scroll the terminal and edit an answer before sending. + let _hold = false; const _listeners = {}; const PHANTOM = '​'; @@ -189,6 +193,12 @@ const CjkInput = (() => { _t('flush SKIP composing'); return; } + // Send-on-Enter: nothing leaves the field until Enter (keydown handler). + if (_hold) { + _t('flush SKIP hold'); + _autoGrow(); + return; + } const val = _strip(_textarea.value); _t(`flush ${val ? 'send len=' + val.length : 'empty'}`); if (val) { @@ -197,6 +207,35 @@ const CjkInput = (() => { _resetToPhantom(); } + /** Send-on-Enter: grow the field with its content (up to the CSS max-height) + * and let the keyboard layout re-read its height. */ + function _autoGrow() { + if (!_textarea) return; + const before = _textarea.style.height; + _textarea.style.height = 'auto'; + _textarea.style.height = `${_textarea.scrollHeight}px`; + if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') { + KeyboardHandler.updateLayoutForKeyboard?.(); + } + } + + /** Send-on-Enter: deliver the held text as one prompt, then Enter. One line + * goes as typed text + CR in one write (what live mode's Enter sends, so CLI + * menus that answer to a digit keep working). Several lines go as one + * bracketed paste with Enter as a separate, delayed write, the same bytes as + * the mobile prompt composer (keyboard-accessory.js _sendComposedPrompt), so + * embedded newlines don't submit early. */ + function _sendHeld(val) { + if (!/\n/.test(val)) { + _send(val + '\r'); + return; + } + let text = val; + while (/\x1b\[20[01]~/.test(text)) text = text.replace(/\x1b\[20[01]~/g, ''); + _send(`\x1b[200~${text.replace(/\r?\n/g, '\r')}\x1b[201~`); + setTimeout(() => _send('\r'), 120); + } + /** Cancel any pending debounced flush */ function _cancelDebouncedFlush() { if (_flushTimer) { @@ -316,16 +355,25 @@ const CjkInput = (() => { _t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`); _printableKeydownAt = null; if (e.key === 'Enter') { + // Send-on-Enter: Shift+Enter (or an IME still composing) is a newline + // in the field, never a send. + if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) { + setTimeout(_autoGrow, 0); + return; + } e.preventDefault(); _composing = false; _cancelDebouncedFlush(); const val = _strip(_textarea.value); - if (val) { + if (_hold && val) { + _sendHeld(val); + } else if (val) { _send(val + '\r'); } else { _send('\r'); } _resetToPhantom(); + if (_hold) _autoGrow(); return; } @@ -334,6 +382,7 @@ const CjkInput = (() => { _composing = false; _cancelDebouncedFlush(); _resetToPhantom(); + if (_hold) _autoGrow(); return; } @@ -475,6 +524,32 @@ const CjkInput = (() => { _resetToPhantom(); }, + /** + * Send-on-Enter mode on or off (setting cjkInputHoldUntilEnter). On: text + * stays in the field until Enter and the browser's autocorrect is allowed, + * since nothing typed has reached the PTY yet. Off: the original live mode. + */ + setHoldUntilEnter(on) { + _hold = !!on; + if (!_textarea) return; + const v = _hold ? 'on' : 'off'; + _textarea.setAttribute('autocorrect', v); + _textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off'); + _textarea.setAttribute('spellcheck', _hold ? 'true' : 'false'); + _textarea.placeholder = _hold + ? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)' + : 'CJK input (Enter = send, Esc = clear)'; + if (_hold) { + _cancelDebouncedFlush(); + _autoGrow(); + } else { + _textarea.style.height = ''; + } + _t(`hold ${v}`); + }, + + get holdUntilEnter() { return _hold; }, + /** Diagnostic: recent IME event trace (ring buffer). */ getTrace() { return _trace.slice(); diff --git a/src/web/public/mobile-handlers.js b/src/web/public/mobile-handlers.js index e172683e..8e008dcd 100644 --- a/src/web/public/mobile-handlers.js +++ b/src/web/public/mobile-handlers.js @@ -455,7 +455,11 @@ const KeyboardHandler = { caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : ''; } if (main && keyboardHeight > 0) { - const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') ? 44 : 0; + // The field grows with its text in Send-on-Enter mode, so reserve its + // real height (44 = the one-line field plus its border, the old constant). + const cjkInputHeight = cjkInput?.classList.contains('cjk-input-visible') + ? Math.max(44, cjkInput.offsetHeight + 10) + : 0; main.style.paddingBottom = `${84 + cjkInputHeight}px`; } } else if (keyboardHeight > 0) { diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 8cd7a874..8a9f9c76 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -649,6 +649,8 @@ Object.assign(CodemanApp.prototype, { document.getElementById('appSettingsTerminalWheelLocal').checked = settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false; document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false; + document.getElementById('appSettingsCjkHoldUntilEnter').checked = + settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false; document.getElementById('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false; document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false; document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings); @@ -3195,6 +3197,7 @@ Object.assign(CodemanApp.prototype, { ), terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked, cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked, + cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked, webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked, extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked, tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked, @@ -3440,6 +3443,7 @@ Object.assign(CodemanApp.prototype, { // SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT. keyboardHoldsRows: _khr, cjkInputEnabled: _cjk, + cjkInputHoldUntilEnter: _cjkHold, extendedKeyboardBar: _ekb, skin: _skin, language: _language, @@ -4478,6 +4482,7 @@ Object.assign(CodemanApp.prototype, { sessionListLayout: 'header', sessionSidebarFontSize: 12, cjkInputEnabled: false, + cjkInputHoldUntilEnter: false, terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel webglRendererEnabled: false, // mobile always uses the DOM renderer skin: 'daylight-blue', @@ -5206,7 +5211,7 @@ Object.assign(CodemanApp.prototype, { 'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost', 'showLifecycleLog', 'showResponseViewer', 'showRedrawButton', 'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents', - 'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar', + 'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'cjkInputHoldUntilEnter', 'extendedKeyboardBar', 'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled', 'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold', 'language', diff --git a/test/input-cjk-hold.test.ts b/test/input-cjk-hold.test.ts new file mode 100644 index 00000000..5d59349c --- /dev/null +++ b/test/input-cjk-hold.test.ts @@ -0,0 +1,202 @@ +/** + * @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js, + * setting cjkInputHoldUntilEnter): typed text stays in the field until Enter, + * so a phone user can scroll the terminal and edit an answer before sending. + * + * Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also + * carries the attributes and style the mode touches. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const PHANTOM = '​'; + +function makeTextarea() { + const listeners = new Map void>>(); + const attrs: Record = {}; + return { + value: '', + placeholder: '', + style: { height: '' } as Record, + scrollHeight: 34, + attrs, + blur: () => {}, + focus: () => {}, + classList: { contains: (c: string) => c === 'cjk-input-visible' }, + setSelectionRange: () => {}, + setAttribute: (k: string, v: string) => { + attrs[k] = v; + }, + addEventListener: (ev: string, fn: (e?: unknown) => void) => { + listeners.set(ev, [...(listeners.get(ev) ?? []), fn]); + }, + removeEventListener: (ev: string, fn: (e?: unknown) => void) => { + listeners.set( + ev, + (listeners.get(ev) ?? []).filter((f) => f !== fn) + ); + }, + fire(ev: string, arg: Record = {}) { + const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg }; + for (const fn of listeners.get(ev) ?? []) fn(base); + }, + }; +} + +function load({ hold = true } = {}) { + const textarea = makeTextarea(); + const sent: string[] = []; + const layout = vi.fn(); + const context = vm.createContext({ + window: {}, + document: { getElementById: (id: string) => (id === 'cjkInput' ? textarea : null), activeElement: null }, + navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' }, + KeyboardHandler: { updateLayoutForKeyboard: layout }, + setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms), + clearTimeout: (t: ReturnType) => clearTimeout(t), + performance: { now: () => performance.now() }, + console, + }); + const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8'); + vm.runInContext(src, context, { filename: 'input-cjk.js' }); + const CjkInput = vm.runInContext('CjkInput', context); + CjkInput.init({ send: (t: string) => sent.push(t) }); + CjkInput.setHoldUntilEnter(hold); + textarea.fire('focus'); + return { CjkInput, textarea, sent, layout }; +} + +function type(textarea: ReturnType, text: string) { + textarea.value = PHANTOM + text; + textarea.fire('input', { isComposing: false, inputType: 'insertText' }); +} + +describe('CJK input: Send on Enter', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('keeps typed text in the field instead of streaming it', () => { + const { textarea, sent } = load(); + type(textarea, 'use Postgres'); + vi.advanceTimersByTime(5000); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'use Postgres'); + }); + + it('keeps text after a physical keystroke (no zero-latency flush)', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false }); + type(textarea, 'a'); + vi.advanceTimersByTime(1000); + expect(sent).toEqual([]); + }); + + it('keeps text across a composition cycle and autocorrect rewrites', () => { + const { textarea, sent } = load(); + textarea.fire('compositionstart'); + textarea.value = PHANTOM + 'teh'; + textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' }); + textarea.fire('compositionend'); + textarea.value = PHANTOM + 'the'; + textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' }); + vi.advanceTimersByTime(5000); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'the'); + }); + + it('sends one line as text + CR on Enter, then clears the field', () => { + const { textarea, sent } = load(); + type(textarea, 'yes, use Postgres'); + const preventDefault = vi.fn(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault }); + expect(preventDefault).toHaveBeenCalled(); + expect(sent).toEqual(['yes, use Postgres\r']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('sends a digit as typed so CLI menus still answer to it', () => { + const { textarea, sent } = load(); + type(textarea, '2'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['2\r']); + }); + + it('sends several lines as one bracketed paste, Enter as a later write', () => { + const { textarea, sent } = load(); + type(textarea, 'line one\nline two'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~']); + vi.advanceTimersByTime(150); + expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~', '\r']); + }); + + it('drops paste markers inside the held text', () => { + const { textarea, sent } = load(); + type(textarea, 'a\x1b[201~b\nc'); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent[0]).toBe('\x1b[200~ab\rc\x1b[201~'); + }); + + it('treats Shift+Enter as a newline, never a send', () => { + const { textarea, sent } = load(); + type(textarea, 'first'); + const preventDefault = vi.fn(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault }); + vi.advanceTimersByTime(10); + expect(preventDefault).not.toHaveBeenCalled(); + expect(sent).toEqual([]); + }); + + it('sends a bare Enter when the field is empty (accepting a default answer)', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + expect(sent).toEqual(['\r']); + }); + + it('still forwards Backspace on an empty field to the PTY', () => { + const { textarea, sent } = load(); + textarea.fire('keydown', { key: 'Backspace', keyCode: 8 }); + expect(sent).toEqual(['\x7f']); + }); + + it('Escape clears the held text without sending', () => { + const { textarea, sent } = load(); + type(textarea, 'never mind'); + textarea.fire('keydown', { key: 'Escape', keyCode: 27 }); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM); + }); + + it('turns autocorrect on in the mode and back off without it', () => { + const { CjkInput, textarea } = load(); + expect(textarea.attrs.autocorrect).toBe('on'); + expect(textarea.attrs.spellcheck).toBe('true'); + CjkInput.setHoldUntilEnter(false); + expect(textarea.attrs.autocorrect).toBe('off'); + expect(textarea.attrs.spellcheck).toBe('false'); + expect(CjkInput.holdUntilEnter).toBe(false); + }); + + it('grows the field with its text and re-runs the keyboard layout', () => { + const { textarea, layout } = load(); + layout.mockClear(); + textarea.scrollHeight = 60; + type(textarea, 'a\nb\nc'); + vi.advanceTimersByTime(1000); + expect(textarea.style.height).toBe('60px'); + expect(layout).toHaveBeenCalled(); + }); + + it('live mode is unchanged: text streams after the debounce', () => { + const { textarea, sent } = load({ hold: false }); + type(textarea, 'hi'); + vi.advanceTimersByTime(1000); + expect(sent).toEqual(['hi']); + }); +}); From b8a44666439c45c99ae4f741159a013e8b939870 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Sun, 15 Nov 2026 18:42:59 +0100 Subject: [PATCH 02/12] docs(mobile): zh-CN strings and Input And Voice section for Send on Enter Co-Authored-By: Claude Opus 5.5 --- docs/wiki/Input-And-Voice.md | 6 ++++++ src/web/public/i18n.js | 3 +++ 2 files changed, 9 insertions(+) diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index d15e7864..2bbfb83a 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -67,6 +67,12 @@ below the terminal that owns composition, then delivers the composed text to the Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified sequences, so word jumps and history keys keep working. +On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box: +typed text stays in it until Enter, so you can scroll the terminal back to a question and edit +your answer before sending. Shift+Enter adds a line, Esc clears the field, and autocorrect is on. +A one-line answer is sent as typed, so CLI menus that take a digit still work; several lines go +as one paste followed by Enter. + ## Voice dictation `Ctrl+Shift+V`, or the microphone button. There are three providers and the default is diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 923742fe..a85f1dfe 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -743,6 +743,9 @@ "For local Claude sessions, opening the on-screen keyboard keeps the session's size and scrolls the view instead, so Claude does not reprint its screen and lose transcript lines. Full-screen interfaces (Codex, Claude's fullscreen mode) are resized as before.": '对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。', 'CJK Input': '中日韩输入', + 'Input Field: Send on Enter': '输入框:按 Enter 发送', + 'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.': + '开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。', 'Extended Keyboard Bar': '扩展键盘栏', 'Gesture Control (beta)': '手势控制(测试版)', 'Wheel Scrolls Local History': '滚轮滚动本地历史', From 95fb147e9c52b7730659e716a295cd398e62d779 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Mon, 16 Nov 2026 14:18:18 +0100 Subject: [PATCH 03/12] fix(mobile): Send on Enter review fixes - A long single line (over 64 characters) or several lines now go through the composer's _sendComposedPrompt: one bracketed paste, then Enter as a separate delayed write to the session captured at Enter. Claude Code took a long `\r` burst as a paste and left it unsent, and the old delayed Enter followed a tab switch. A refused prompt keeps the text in the field. - Deleting held text no longer sends Backspace to the PTY. It goes out only when the field was already empty (the phantom itself deleted), so select-all + delete is covered too. - With the one-shot Ctrl armed, the next single typed character skips the hold and reaches _handleCjkInput, which turns it into the control byte; any other change spends the modifier, as in live mode. - A reload of the session already shown (tapping its tab, the geometry retry) keeps a held draft. - With the keyboard down the field stays one line tall, so it no longer covers the terminal's last rows. - zh-CN strings for both field placeholders, and a test pinning cjkInputHoldUntilEnter as per-device. Co-Authored-By: Claude Opus 5.5 --- docs/wiki/Input-And-Voice.md | 7 +- src/web/public/app.js | 14 +- src/web/public/i18n.js | 2 + src/web/public/input-cjk.js | 115 ++++++++++++++-- src/web/public/styles.css | 7 + src/web/public/terminal-ui.js | 25 ++++ test/cjk-hold-per-device-setting.test.ts | 129 ++++++++++++++++++ test/input-cjk-hold.test.ts | 163 ++++++++++++++++++++--- test/mobile-shell-keyboard.test.ts | 45 +++++++ 9 files changed, 474 insertions(+), 33 deletions(-) create mode 100644 test/cjk-hold-per-device-setting.test.ts diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index 2bbfb83a..d073f93d 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -70,8 +70,11 @@ sequences, so word jumps and history keys keep working. On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box: typed text stays in it until Enter, so you can scroll the terminal back to a question and edit your answer before sending. Shift+Enter adds a line, Esc clears the field, and autocorrect is on. -A one-line answer is sent as typed, so CLI menus that take a digit still work; several lines go -as one paste followed by Enter. +A short one-line answer is sent as typed, so CLI menus that take a digit still work; a longer +answer, or several lines, goes like the prompt composer's Send: one paste, then Enter to the same +session. With the keyboard bar's one-shot Ctrl armed, the next key you type goes out as a control +key (Ctrl, then `c` is Ctrl+C) instead of being held. With the keyboard down the field stays one +line tall, and tapping the tab you are on keeps the draft. ## Voice dictation diff --git a/src/web/public/app.js b/src/web/public/app.js index 1f178c2a..2a430d3c 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9384,7 +9384,7 @@ class CodemanApp { // `skipSnapshot`: the tile grid opening on the session it parks // (tile-grid.js openTileGrid), whose snapshot closing the grid discards. - _cleanupPreviousSession(newSessionId, { skipSnapshot = false } = {}) { + _cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) { // Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback + // colors/attrs) before the terminal gets cleared/reset. Lets us restore the // exact view on switch-back rather than replaying codex's byte stream, which @@ -9437,8 +9437,11 @@ class CodemanApp { // Clear CJK input to prevent sending stale text to the wrong session. // Must go through CjkInput.clear() — a raw value wipe leaves the module's // pending flush timers armed and drops the phantom char it relies on. + // A held Send on Enter draft survives a reload of the same session: nothing + // switched, and the answer would be gone. Live mode still clears, since a + // pending debounced flush could fire mid-reconnect. if (typeof CjkInput !== 'undefined') { - CjkInput.clear(); + if (!(keepCjkDraft && CjkInput.holdUntilEnter)) CjkInput.clear(); } else { const cjkEl = document.getElementById('cjkInput'); if (cjkEl) cjkEl.value = ''; @@ -9982,7 +9985,12 @@ class CodemanApp { // with no active id, the switch below snapshots none of it. this.activeSessionId = null; } + // A reload of the session already shown (tapping its own tab, the geometry + // retry) is not a switch: _cleanupPreviousSession keeps a Send on Enter + // draft for it, which it cannot tell on its own once activeSessionId is null. + let reloadingSameSession = false; if (this.activeSessionId === sessionId && forceReload) { + reloadingSameSession = true; this.terminalBufferCache?.delete(sessionId); this._xtermSnapshots?.delete(sessionId); try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {} @@ -10029,7 +10037,7 @@ class CodemanApp { // A session tab takes the stage back from any active web tab. this._hideWebviewLayer?.(); - this._cleanupPreviousSession(sessionId); + this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession }); this.activeSessionId = sessionId; this._activateFileBrowserSession?.(sessionId); // A keyboard row hold belongs to the session it was taken for: release it here diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index a85f1dfe..5b768a14 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -744,6 +744,8 @@ '对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。', 'CJK Input': '中日韩输入', 'Input Field: Send on Enter': '输入框:按 Enter 发送', + 'CJK input (Enter = send, Esc = clear)': '中日韩输入(Enter 发送,Esc 清除)', + 'Type, Enter to send (Shift+Enter: new line, Esc: clear)': '输入文字,按 Enter 发送(Shift+Enter 换行,Esc 清除)', 'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.': '开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。', 'Extended Keyboard Bar': '扩展键盘栏', diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 89d7cccd..6274474b 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -61,6 +61,13 @@ const CjkInput = (() => { // field until Enter, like a chat box, instead of streaming to the PTY as it is // typed. Lets a phone user scroll the terminal and edit an answer before sending. let _hold = false; + // Send-on-Enter: the held text as of the last settled input event (phantom + // stripped). Tells a deletion that emptied the field from a Backspace on a field + // that was already empty, and finds the one character an armed Ctrl applies to. + let _heldBase = ''; + // Send-on-Enter: delivers a held prompt that is long or multi-line to the + // session it was typed for (terminal-ui.js passes the composer's send path). + let _sendPrompt = null; const _listeners = {}; const PHANTOM = '​'; @@ -110,6 +117,13 @@ const CjkInput = (() => { const DEBOUNCE_DICTATION_MS = 1500; const DICTATION_DECAY_MS = 3000; + // Send-on-Enter: the longest single line still written as `\r` in one + // go. Claude Code takes a burst of about a hundred characters or more as a + // paste (src/web/route-helpers.ts) and turns its \r into a newline, so the + // answer would sit unsent. Short answers (a menu digit, a word) keep the + // one-write form; anything longer goes out as a prompt with a separate Enter. + const HELD_DIRECT_MAX = 64; + const PASSTHROUGH_KEYS = { ArrowUp: '\x1b[A', ArrowDown: '\x1b[B', @@ -164,6 +178,7 @@ const CjkInput = (() => { } function _resetToPhantom() { + _heldBase = ''; // Skip redundant writes: every programmatic value/selection mutation can // desync an Android IME's input session (InputConnection) — after which // the keyboard composes in its own UI but NO events ever reach the page. @@ -196,6 +211,7 @@ const CjkInput = (() => { // Send-on-Enter: nothing leaves the field until Enter (keydown handler). if (_hold) { _t('flush SKIP hold'); + _holdSettle(); _autoGrow(); return; } @@ -219,21 +235,86 @@ const CjkInput = (() => { } } - /** Send-on-Enter: deliver the held text as one prompt, then Enter. One line - * goes as typed text + CR in one write (what live mode's Enter sends, so CLI - * menus that answer to a digit keep working). Several lines go as one - * bracketed paste with Enter as a separate, delayed write, the same bytes as - * the mobile prompt composer (keyboard-accessory.js _sendComposedPrompt), so - * embedded newlines don't submit early. */ + /** Send-on-Enter: deliver the held text, then Enter. Returns false when the + * text was refused (too long, no session), so the field keeps it. + * A short single line goes as typed text + CR in one write: what live mode's + * Enter sends, so CLI menus that answer to a digit keep working. Anything + * longer, or with several lines, goes through `_sendPrompt`: the mobile prompt + * composer's path (KeyboardAccessoryBar._sendComposedPrompt), one bracketed + * paste and then Enter as a separate, delayed write bound to the session the + * text was typed for, so neither a long line nor an embedded newline submits + * early and a tab switch cannot take the Enter elsewhere. */ function _sendHeld(val) { - if (!/\n/.test(val)) { + if (!/\n/.test(val) && val.length <= HELD_DIRECT_MAX) { _send(val + '\r'); + return true; + } + if (!_sendPrompt) { + _t('hold send DROP no-prompt-path'); + return false; + } + return _sendPrompt(val) !== false; + } + + function _ctrlArmed() { + return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true; + } + + /** Index of the one character `after` adds to `before`, or -1 when the change + * is anything else (several characters, a deletion, a rewrite). */ + function _singleInsertionAt(before, after) { + if (after.length !== before.length + 1) return -1; + let i = 0; + while (i < before.length && before[i] === after[i]) i++; + return after.slice(i + 1) === before.slice(i) ? i : -1; + } + + /** Send-on-Enter: settle the field after an input event. With the shell bar's + * one-shot Ctrl armed, a single typed character is not held: it leaves the + * field and goes to the PTY, where _handleCjkInput turns it into the control + * byte (`c` → Ctrl+C). Any other change spends the modifier, the same rule + * live mode follows for a multi-character chunk. */ + function _holdSettle() { + const before = _heldBase; + const now = _strip(_textarea.value); + _heldBase = now; + if (now === before || !_ctrlArmed()) return; + const at = _singleInsertionAt(before, now); + if (at < 0 || now[at] === '\n') { + KeyboardAccessoryBar.clearCtrl?.(); return; } - let text = val; - while (/\x1b\[20[01]~/.test(text)) text = text.replace(/\x1b\[20[01]~/g, ''); - _send(`\x1b[200~${text.replace(/\r?\n/g, '\r')}\x1b[201~`); - setTimeout(() => _send('\r'), 120); + _t('hold ctrl key'); + _textarea.value = PHANTOM + before; + _textarea.setSelectionRange(1 + at, 1 + at); + _heldBase = before; + _send(now[at]); + } + + /** Send-on-Enter input handling: nothing is flushed, the field only settles. + * A deletion forwards Backspace to the PTY only when the field was ALREADY + * empty, i.e. the phantom itself was deleted. Deleting the last held + * character (or select-all + delete) must not also delete a character from + * the CLI's own composer, which Attach, image paste, Path and the mic fill. */ + function _holdInput(e) { + if (_composing) return; // composed text settles at compositionend (_flush) + if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') { + const wasEmpty = !_heldBase; + _heldBase = _strip(_textarea.value); + if (!_heldBase) { + if (wasEmpty) _send('\x7f'); + _resetToPhantom(); + } else if (!_textarea.value.startsWith(PHANTOM)) { + // Backspace at the very start of the text deleted the phantom: put it + // back with the caret where it was, at the start of the text. + _textarea.value = PHANTOM + _textarea.value; + _textarea.setSelectionRange(1, 1); + } + _autoGrow(); + return; + } + _holdSettle(); + _autoGrow(); } /** Cancel any pending debounced flush */ @@ -265,10 +346,11 @@ const CjkInput = (() => { } return { - init({ send }) { + init({ send, sendPrompt = null }) { if (_initialized) this.destroy(); _send = send; + _sendPrompt = sendPrompt; _composing = false; _printableKeydownAt = null; _flushTimer = null; @@ -366,7 +448,8 @@ const CjkInput = (() => { _cancelDebouncedFlush(); const val = _strip(_textarea.value); if (_hold && val) { - _sendHeld(val); + // Refused (too long, no session): keep the text so nothing is lost. + if (!_sendHeld(val)) return; } else if (val) { _send(val + '\r'); } else { @@ -454,6 +537,11 @@ const CjkInput = (() => { _composing = false; } + if (_hold) { + _holdInput(e); + return; + } + // ── Backspace / delete detection ── if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') { if (_composing) return; @@ -532,6 +620,7 @@ const CjkInput = (() => { setHoldUntilEnter(on) { _hold = !!on; if (!_textarea) return; + _heldBase = _strip(_textarea.value); const v = _hold ? 'on' : 'off'; _textarea.setAttribute('autocorrect', v); _textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off'); diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 2ceb4d6f..5dd912d7 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -14235,6 +14235,13 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat bottom: calc(var(--safe-area-bottom) + 84px); } +/* Send on Enter grows the field with its text, but with the keyboard down .main + reserves a fixed 84px (below), so a grown field would cover the terminal's + last rows. Keep it one line tall there; the text scrolls inside. */ +.touch-device:not(.keyboard-visible) #cjkInput.cjk-input-visible { + max-height: 34px; +} + body.touch-device.cjk-input-visible .main { padding-bottom: calc(84px + var(--safe-area-bottom)); } diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index eab9a73e..46cdbf44 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -1083,6 +1083,10 @@ Object.assign(CodemanApp.prototype, { send: (text) => { this._handleCjkInput(text); }, + // Send on Enter: a long or multi-line held answer goes out like the + // mobile prompt composer's Send (one bracketed paste, then Enter as a + // separate delayed write), bound to the session it was typed for. + sendPrompt: (text) => this._sendCjkPrompt(text), }); } @@ -4564,6 +4568,27 @@ Object.assign(CodemanApp.prototype, { this._sendInputAsync(this.activeSessionId, text); }, + /** + * Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held + * answer that is too long for one `\r` write, or has several lines. + * Claude Code takes a long burst as a paste and its \r as a newline, so it goes + * through the composer's path instead: the session is captured now, so the + * delayed Enter cannot follow a tab switch, and the length check applies. + * Returns false when nothing was sent, so the field keeps the text. + */ + _sendCjkPrompt(text) { + const sessionId = this.activeSessionId; + if (!sessionId || typeof KeyboardAccessoryBar === 'undefined') { + _crashDiag.log(`CJK prompt DROP no-session len=${text.length}`); + return false; + } + // A multi-character chunk spends an armed one-shot Ctrl (same rule as + // _handleCjkInput); leaving it armed would modify the next keystroke. + KeyboardAccessoryBar.clearCtrl?.(); + _crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`); + return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text); + }, + /** * Re-assert a history anchor captured before a terminal write (#358). * diff --git a/test/cjk-hold-per-device-setting.test.ts b/test/cjk-hold-per-device-setting.test.ts new file mode 100644 index 00000000..1e76428e --- /dev/null +++ b/test/cjk-hold-per-device-setting.test.ts @@ -0,0 +1,129 @@ +// test/cjk-hold-per-device-setting.test.ts +// Port: none (static analysis + vm, runs in CI, no browser/server). +// +// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a +// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys +// merge policy, stripped out of the object saveAppSettings() PUTs +// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and +// never declared in the schema. Plus the pieces around the mode: a held draft +// surviving a reload of the same session, the field staying one line tall with +// the keyboard down, and zh-CN strings for its placeholders. +import { describe, it, expect, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; +import vm from 'node:vm'; + +const HERE = fileURLToPath(new URL('.', import.meta.url)); +const PUBLIC = join(HERE, '../src/web/public'); +const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8'); + +describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => { + const settingsUi = read('settings-ui.js'); + const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8'); + + it('is in the client-side displayKeys merge policy', () => { + const start = settingsUi.indexOf('const displayKeys = new Set(['); + const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start)); + expect(displayKeys).toContain("'cjkInputHoldUntilEnter'"); + }); + + it('is stripped out of the object saveAppSettings() PUTs to the server', () => { + expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,'); + }); + + it('is never declared in the .strict() SettingsUpdateSchema', () => { + expect(schemas).not.toContain('cjkInputHoldUntilEnter'); + }); + + it('defaults OFF on handhelds, next to cjkInputEnabled', () => { + expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/); + }); + + it('is loaded into and saved from its App Settings switch', () => { + expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"'); + expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked ="); + expect(settingsUi).toContain( + "cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked," + ); + }); +}); + +describe('a held draft survives a reload of the same session', () => { + // The REAL _cleanupPreviousSession from app.js. selectSession() nulls + // activeSessionId before calling it on a same-session forceReload (tapping the + // tab already shown, the geometry retry), so it is told through keepCjkDraft. + function cleanup(hold: boolean, keepCjkDraft: boolean) { + const clear = vi.fn(); + const context = vm.createContext({ + console, + setTimeout, + clearTimeout, + setInterval: vi.fn(), + clearInterval: vi.fn(), + requestAnimationFrame: vi.fn(), + HTMLCanvasElement: class HTMLCanvasElement {}, + WebSocket: { OPEN: 1 }, + fetch: vi.fn(), + URLSearchParams, + document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null }, + localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() }, + window: { addEventListener: vi.fn(), removeEventListener: vi.fn() }, + MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' }, + CjkInput: { holdUntilEnter: hold, clear }, + }); + vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context); + const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp; + const app = Object.create(CodemanApp.prototype) as Record & { + _cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void; + }; + app.activeSessionId = null; + app._clearTimer = vi.fn(); + app._disconnectWs = vi.fn(); + app._xtermSnapshots = new Map(); + app.pendingWrites = []; + app._cleanupPreviousSession('s1', { keepCjkDraft }); + return clear; + } + + it('keeps the draft on a same-session reload in Send on Enter mode', () => { + expect(cleanup(true, true)).not.toHaveBeenCalled(); + }); + + it('still clears on a real switch', () => { + expect(cleanup(true, false)).toHaveBeenCalled(); + }); + + it('still clears in live mode, where a pending flush could fire mid-reconnect', () => { + expect(cleanup(false, true)).toHaveBeenCalled(); + }); + + it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => { + const appJs = read('app.js'); + expect(appJs).toMatch( + /if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/ + ); + expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });'); + }); +}); + +describe('Send on Enter field layout and strings', () => { + it('keeps the field one line tall while the keyboard is down', () => { + // .main reserves a fixed 84px there; a grown field would cover the terminal. + expect(read('styles.css')).toMatch( + /\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/ + ); + }); + + it('has zh-CN strings for both field placeholders', () => { + const i18n = read('i18n.js'); + const cjk = read('input-cjk.js'); + for (const placeholder of [ + 'CJK input (Enter = send, Esc = clear)', + 'Type, Enter to send (Shift+Enter: new line, Esc: clear)', + ]) { + expect(cjk).toContain(`'${placeholder}'`); + expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1); + } + }); +}); diff --git a/test/input-cjk-hold.test.ts b/test/input-cjk-hold.test.ts index 5d59349c..f17a0772 100644 --- a/test/input-cjk-hold.test.ts +++ b/test/input-cjk-hold.test.ts @@ -45,15 +45,27 @@ function makeTextarea() { }; } -function load({ hold = true } = {}) { +function load({ hold = true, promptResult = true } = {}) { const textarea = makeTextarea(); const sent: string[] = []; + const prompts: string[] = []; const layout = vi.fn(); + // The shell bar's one-shot Ctrl, reduced to its armed flag. + const bar = { + armed: false, + isCtrlArmed() { + return this.armed; + }, + clearCtrl() { + this.armed = false; + }, + }; const context = vm.createContext({ window: {}, document: { getElementById: (id: string) => (id === 'cjkInput' ? textarea : null), activeElement: null }, navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' }, KeyboardHandler: { updateLayoutForKeyboard: layout }, + KeyboardAccessoryBar: bar, setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms), clearTimeout: (t: ReturnType) => clearTimeout(t), performance: { now: () => performance.now() }, @@ -62,10 +74,16 @@ function load({ hold = true } = {}) { const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8'); vm.runInContext(src, context, { filename: 'input-cjk.js' }); const CjkInput = vm.runInContext('CjkInput', context); - CjkInput.init({ send: (t: string) => sent.push(t) }); + CjkInput.init({ + send: (t: string) => sent.push(t), + sendPrompt: (t: string) => { + prompts.push(t); + return promptResult; + }, + }); CjkInput.setHoldUntilEnter(hold); textarea.fire('focus'); - return { CjkInput, textarea, sent, layout }; + return { CjkInput, textarea, sent, prompts, layout, bar }; } function type(textarea: ReturnType, text: string) { @@ -73,6 +91,14 @@ function type(textarea: ReturnType, text: string) { textarea.fire('input', { isComposing: false, inputType: 'insertText' }); } +function backspace(textarea: ReturnType, valueAfter: string) { + textarea.value = valueAfter; + textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' }); +} + +const enter = (textarea: ReturnType) => + textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); + describe('CJK input: Send on Enter', () => { beforeEach(() => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }); @@ -127,20 +153,43 @@ describe('CJK input: Send on Enter', () => { expect(sent).toEqual(['2\r']); }); - it('sends several lines as one bracketed paste, Enter as a later write', () => { - const { textarea, sent } = load(); - type(textarea, 'line one\nline two'); - textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); - expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~']); - vi.advanceTimersByTime(150); - expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~', '\r']); + it('sends a long single line as a prompt, never as one \\r burst', () => { + // Claude Code takes a burst of ~100+ characters as a paste and its \r as a + // newline, so the answer would sit unsent (src/web/route-helpers.ts). + const { textarea, sent, prompts } = load(); + const long = 'x'.repeat(150); + type(textarea, long); + enter(textarea); + expect(sent).toEqual([]); + expect(prompts).toEqual([long]); + expect(textarea.value).toBe(PHANTOM); }); - it('drops paste markers inside the held text', () => { - const { textarea, sent } = load(); - type(textarea, 'a\x1b[201~b\nc'); - textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); - expect(sent[0]).toBe('\x1b[200~ab\rc\x1b[201~'); + it('keeps a line at the direct-write limit as one write, one over it as a prompt', () => { + const { textarea, sent, prompts } = load(); + type(textarea, 'a'.repeat(64)); + enter(textarea); + type(textarea, 'b'.repeat(65)); + enter(textarea); + expect(sent).toEqual(['a'.repeat(64) + '\r']); + expect(prompts).toEqual(['b'.repeat(65)]); + }); + + it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => { + const { textarea, sent, prompts } = load(); + type(textarea, 'line one\nline two'); + enter(textarea); + vi.advanceTimersByTime(500); + expect(prompts).toEqual(['line one\nline two']); + expect(sent).toEqual([]); + }); + + it('keeps the text in the field when the prompt is refused (too long, no session)', () => { + const { textarea, prompts } = load({ promptResult: false }); + type(textarea, 'line one\nline two'); + enter(textarea); + expect(prompts).toHaveLength(1); + expect(textarea.value).toBe(PHANTOM + 'line one\nline two'); }); it('treats Shift+Enter as a newline, never a send', () => { @@ -165,6 +214,90 @@ describe('CJK input: Send on Enter', () => { expect(sent).toEqual(['\x7f']); }); + it('does not send Backspace when deleting the last held character', () => { + // The CLI's own composer may hold text (Attach, image paste, Path, mic): + // a stray DEL would eat its last character. + const { textarea, sent } = load(); + type(textarea, 'a'); + type(textarea, 'ab'); + backspace(textarea, PHANTOM + 'a'); + backspace(textarea, PHANTOM); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM); + }); + + it('sends Backspace once the field is empty and the phantom itself is deleted', () => { + const { textarea, sent } = load(); + type(textarea, 'a'); + backspace(textarea, PHANTOM); + backspace(textarea, ''); + expect(sent).toEqual(['\x7f']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('does not send Backspace for select-all + delete of held text', () => { + const { textarea, sent } = load(); + type(textarea, 'abc'); + backspace(textarea, ''); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM); + }); + + it('deletes held text right after typing it, before any debounce, without a DEL', () => { + const { textarea, sent } = load(); + type(textarea, 'a'); + backspace(textarea, PHANTOM); + vi.advanceTimersByTime(2000); + expect(sent).toEqual([]); + }); + + it('puts the phantom back when Backspace at the start of the text deleted it', () => { + const { textarea, sent } = load(); + type(textarea, 'abc'); + backspace(textarea, 'abc'); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'abc'); + }); + + it('one-shot Ctrl: the next typed character goes out instead of being held', () => { + // _handleCjkInput turns the single character into the control byte. + const { textarea, sent, bar } = load(); + bar.armed = true; + type(textarea, 'c'); + expect(sent).toEqual(['c']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('one-shot Ctrl: held text stays and only the new character leaves the field', () => { + const { textarea, sent, bar } = load(); + type(textarea, 'ab'); + bar.armed = true; + type(textarea, 'abc'); + expect(sent).toEqual(['c']); + expect(textarea.value).toBe(PHANTOM + 'ab'); + }); + + it('one-shot Ctrl: a character committed by an IME composition also goes out', () => { + const { textarea, sent, bar } = load(); + bar.armed = true; + textarea.fire('compositionstart'); + textarea.value = PHANTOM + 'c'; + textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' }); + textarea.fire('compositionend'); + vi.advanceTimersByTime(10); + expect(sent).toEqual(['c']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => { + const { textarea, sent, bar } = load(); + bar.armed = true; + type(textarea, 'hello'); + expect(sent).toEqual([]); + expect(textarea.value).toBe(PHANTOM + 'hello'); + expect(bar.armed).toBe(false); + }); + it('Escape clears the held text without sending', () => { const { textarea, sent } = load(); type(textarea, 'never mind'); diff --git a/test/mobile-shell-keyboard.test.ts b/test/mobile-shell-keyboard.test.ts index 00b2ee78..5286be02 100644 --- a/test/mobile-shell-keyboard.test.ts +++ b/test/mobile-shell-keyboard.test.ts @@ -547,6 +547,51 @@ describe('one-shot Ctrl through the CJK input field', () => { }); }); +describe('Send on Enter: a long or multi-line held answer goes out as a composed prompt', () => { + // _sendCjkPrompt is CjkInput's sendPrompt callback. It hands the text to the + // composer's _sendComposedPrompt with the session captured at Enter, so the + // delayed Enter cannot follow a tab switch. + function promptApp() { + const { CodemanApp, bar } = loadTerminalModule(); + bar.clearCtrl(); + const app = Object.create(CodemanApp.prototype) as { + activeSessionId: string | null; + _sendCjkPrompt(text: string): boolean; + }; + app.activeSessionId = 'session-a'; + const composed = vi + .spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt') + .mockReturnValue(true); + return { app, bar, composed }; + } + + it('sends through the composer path, bound to the session active at Enter', () => { + const { app, composed } = promptApp(); + expect(app._sendCjkPrompt('line one\nline two')).toBe(true); + app.activeSessionId = 'session-b'; + expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two'); + composed.mockRestore(); + }); + + it('spends an armed one-shot Ctrl, like any multi-character chunk', () => { + const { app, bar, composed } = promptApp(); + bar.toggleCtrl(); + app._sendCjkPrompt('x'.repeat(100)); + expect(bar.isCtrlArmed()).toBe(false); + composed.mockRestore(); + }); + + it('reports a refusal so the field keeps the text', () => { + const { app, composed } = promptApp(); + composed.mockReturnValue(false); + expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); + app.activeSessionId = null; + expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); + expect(composed).toHaveBeenCalledTimes(1); + composed.mockRestore(); + }); +}); + describe('armed styling survives the light-skin overrides', () => { const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8'); From 64ee504247075b81e3fad656324ac5af23f921b1 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Mon, 16 Nov 2026 17:39:22 +0100 Subject: [PATCH 04/12] fix(mobile): Send on Enter second review fixes - Never send a held answer as text + CR in one write: Codex folds an Enter in the same burst into a paste. A single character is typed, then CR ~120 ms later to the session captured at Enter; anything longer goes through _sendComposedPrompt. Drops HELD_DIRECT_MAX. No session keeps the text in the field. - Cap #cjkInput at 68px on every device, not only touch. - _autoGrow adds the border height and skips a hidden field. - setHoldUntilEnter returns early when the mode is unchanged. - Per-session held drafts: stashed on switch and tile focus, restored on return, dropped when the session is removed. - Toolbar Enter presses Enter in the visible CJK field (commits an active composition first). - Blank-only field sends a bare Enter. Co-Authored-By: Claude Opus 5.5 --- docs/wiki/Input-And-Voice.md | 9 +- src/web/public/app.js | 16 +- src/web/public/input-cjk.js | 141 ++++++++++++----- src/web/public/session-ui.js | 10 ++ src/web/public/styles.css | 5 + src/web/public/terminal-ui.js | 25 ++- src/web/public/tile-grid.js | 11 ++ test/cjk-hold-per-device-setting.test.ts | 63 +++++++- test/input-cjk-hold.test.ts | 185 +++++++++++++++++++---- test/mobile-shell-keyboard.test.ts | 45 +++++- 10 files changed, 418 insertions(+), 92 deletions(-) diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index d073f93d..c386a1ee 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -70,11 +70,12 @@ sequences, so word jumps and history keys keep working. On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box: typed text stays in it until Enter, so you can scroll the terminal back to a question and edit your answer before sending. Shift+Enter adds a line, Esc clears the field, and autocorrect is on. -A short one-line answer is sent as typed, so CLI menus that take a digit still work; a longer -answer, or several lines, goes like the prompt composer's Send: one paste, then Enter to the same -session. With the keyboard bar's one-shot Ctrl armed, the next key you type goes out as a control +Enter always goes out as its own write, a moment after the text, to the session the answer was +typed for: a single character is typed, so CLI menus that take a digit still work, and anything +longer goes like the prompt composer's Send, as one paste. The toolbar's Enter button sends the +field too. With the keyboard bar's one-shot Ctrl armed, the next key you type goes out as a control key (Ctrl, then `c` is Ctrl+C) instead of being held. With the keyboard down the field stays one -line tall, and tapping the tab you are on keeps the draft. +line tall. A draft stays with its session: switching tabs and coming back brings it back. ## Voice dictation diff --git a/src/web/public/app.js b/src/web/public/app.js index 2a430d3c..c3f36ca6 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9438,10 +9438,15 @@ class CodemanApp { // Must go through CjkInput.clear() — a raw value wipe leaves the module's // pending flush timers armed and drops the phantom char it relies on. // A held Send on Enter draft survives a reload of the same session: nothing - // switched, and the answer would be gone. Live mode still clears, since a - // pending debounced flush could fire mid-reconnect. + // switched, and the answer would be gone. On a real switch it is stashed for + // the session being left (selectSession restores it on the way back), so a + // stray swipe does not lose it. Live mode still clears, since a pending + // debounced flush could fire mid-reconnect. if (typeof CjkInput !== 'undefined') { - if (!(keepCjkDraft && CjkInput.holdUntilEnter)) CjkInput.clear(); + if (!(keepCjkDraft && CjkInput.holdUntilEnter)) { + if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId); + CjkInput.clear(); + } } else { const cjkEl = document.getElementById('cjkInput'); if (cjkEl) cjkEl.value = ''; @@ -9981,6 +9986,9 @@ class CodemanApp { if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options); if (options?.auto === true && !options?.leaveTiles) return; this.closeTileGrid({ keepStored: true, reselect: false }); + // The focused tile's Send on Enter draft: the null below hides that + // session from _cleanupPreviousSession, which would clear it unstashed. + if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId); // The parked terminal still holds what it showed before the grid opened; // with no active id, the switch below snapshots none of it. this.activeSessionId = null; @@ -10039,6 +10047,7 @@ class CodemanApp { this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession }); this.activeSessionId = sessionId; + if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId); this._activateFileBrowserSession?.(sessionId); // A keyboard row hold belongs to the session it was taken for: release it here // if this one resizes instead (the geometry work below then fits it). @@ -10836,6 +10845,7 @@ class CodemanApp { this._flushedOffsets?.delete(sessionId); this._flushedTexts?.delete(sessionId); if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.discardComposerDraft?.(sessionId); + if (typeof CjkInput !== 'undefined') CjkInput.discardDraft?.(sessionId); // Drop any durably-queued input for a session that's actually gone (deleted/ // exited). Not a lost prompt — the target no longer exists. Only reached on // real session removal, never on a tab switch. diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 6274474b..50beebc9 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -65,9 +65,14 @@ const CjkInput = (() => { // stripped). Tells a deletion that emptied the field from a Backspace on a field // that was already empty, and finds the one character an armed Ctrl applies to. let _heldBase = ''; - // Send-on-Enter: delivers a held prompt that is long or multi-line to the - // session it was typed for (terminal-ui.js passes the composer's send path). + // Send-on-Enter: delivers a held answer, text first and Enter as a separate + // delayed write, to the session it was typed for (terminal-ui.js). let _sendPrompt = null; + // Send-on-Enter: whether setHoldUntilEnter() has applied the current mode to + // the field yet, so a repeat call with the same mode leaves the field alone. + let _holdApplied = false; + // Send-on-Enter: held drafts of the sessions switched away from, by session id. + const _drafts = new Map(); const _listeners = {}; const PHANTOM = '​'; @@ -117,13 +122,6 @@ const CjkInput = (() => { const DEBOUNCE_DICTATION_MS = 1500; const DICTATION_DECAY_MS = 3000; - // Send-on-Enter: the longest single line still written as `\r` in one - // go. Claude Code takes a burst of about a hundred characters or more as a - // paste (src/web/route-helpers.ts) and turns its \r into a newline, so the - // answer would sit unsent. Short answers (a menu digit, a word) keep the - // one-write form; anything longer goes out as a prompt with a separate Enter. - const HELD_DIRECT_MAX = 64; - const PASSTHROUGH_KEYS = { ArrowUp: '\x1b[A', ArrowDown: '\x1b[B', @@ -227,28 +225,28 @@ const CjkInput = (() => { * and let the keyboard layout re-read its height. */ function _autoGrow() { if (!_textarea) return; + // A hidden field (no session shown yet) measures 0: leave the CSS height, + // or it stays a sliver until the next keystroke. + if (_textarea.getClientRects && !_textarea.getClientRects().length) { + _textarea.style.height = ''; + return; + } const before = _textarea.style.height; _textarea.style.height = 'auto'; - _textarea.style.height = `${_textarea.scrollHeight}px`; + // border-box: scrollHeight leaves the borders out, offsetHeight - clientHeight adds them back. + _textarea.style.height = `${_textarea.scrollHeight + _textarea.offsetHeight - _textarea.clientHeight}px`; if (_textarea.style.height !== before && typeof KeyboardHandler !== 'undefined') { KeyboardHandler.updateLayoutForKeyboard?.(); } } - /** Send-on-Enter: deliver the held text, then Enter. Returns false when the - * text was refused (too long, no session), so the field keeps it. - * A short single line goes as typed text + CR in one write: what live mode's - * Enter sends, so CLI menus that answer to a digit keep working. Anything - * longer, or with several lines, goes through `_sendPrompt`: the mobile prompt - * composer's path (KeyboardAccessoryBar._sendComposedPrompt), one bracketed - * paste and then Enter as a separate, delayed write bound to the session the - * text was typed for, so neither a long line nor an embedded newline submits - * early and a tab switch cannot take the Enter elsewhere. */ + /** Send-on-Enter: deliver the held text, then Enter, through `_sendPrompt` + * (terminal-ui.js _sendCjkPrompt). Enter is never part of the text's write: + * Codex takes characters arriving in one burst as a paste and folds an Enter + * inside it into the paste, and Claude Code does the same for a long burst, so + * even `1\r` in one write sits unsent. Returns false when the text was refused + * (too long, no session), so the field keeps it. */ function _sendHeld(val) { - if (!/\n/.test(val) && val.length <= HELD_DIRECT_MAX) { - _send(val + '\r'); - return true; - } if (!_sendPrompt) { _t('hold send DROP no-prompt-path'); return false; @@ -256,6 +254,30 @@ const CjkInput = (() => { return _sendPrompt(val) !== false; } + /** Enter: send what the field holds (or a bare Enter when it is empty) and + * reset it. Returns false when a held answer was refused, which keeps it. */ + function _submit() { + _composing = false; + _cancelDebouncedFlush(); + clearTimeout(_compositionFlushTimer); + _compositionFlushTimer = null; + let val = _strip(_textarea.value); + // Only blank lines held (Shift+Enter, then Enter): a bare Enter, not a + // newline typed into the CLI. + if (_hold && !val.trim()) val = ''; + if (_hold && val) { + // Refused (too long, no session): keep the text so nothing is lost. + if (!_sendHeld(val)) return false; + } else if (val) { + _send(val + '\r'); + } else { + _send('\r'); + } + _resetToPhantom(); + if (_hold) _autoGrow(); + return true; + } + function _ctrlArmed() { return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true; } @@ -355,6 +377,7 @@ const CjkInput = (() => { _printableKeydownAt = null; _flushTimer = null; _textarea = document.getElementById('cjkInput'); + _holdApplied = false; // a new field has not had the mode applied if (!_textarea) return this; _resetToPhantom(); @@ -444,19 +467,7 @@ const CjkInput = (() => { return; } e.preventDefault(); - _composing = false; - _cancelDebouncedFlush(); - const val = _strip(_textarea.value); - if (_hold && val) { - // Refused (too long, no session): keep the text so nothing is lost. - if (!_sendHeld(val)) return; - } else if (val) { - _send(val + '\r'); - } else { - _send('\r'); - } - _resetToPhantom(); - if (_hold) _autoGrow(); + _submit(); return; } @@ -618,8 +629,13 @@ const CjkInput = (() => { * since nothing typed has reached the PTY yet. Off: the original live mode. */ setHoldUntilEnter(on) { + // Called on every session select and SSE reconnect: with the mode + // unchanged, leave the field alone, since rewriting its attributes while + // it has focus can disturb a composition in progress. + if (_holdApplied && _textarea && _hold === !!on) return; _hold = !!on; if (!_textarea) return; + _holdApplied = true; _heldBase = _strip(_textarea.value); const v = _hold ? 'on' : 'off'; _textarea.setAttribute('autocorrect', v); @@ -639,6 +655,59 @@ const CjkInput = (() => { get holdUntilEnter() { return _hold; }, + /** + * Enter from outside the field (the phone toolbar's Enter button, which + * xterm's onData would swallow while the field is visible). Same as Enter + * in the field. Returns false when nothing was done (not initialized) or a + * held answer was refused. + */ + submit() { + if (!_initialized || !_textarea) return false; + _t(`submit (external) c=${_composing}`); + if (_composing) { + // An IME still composing (Gboard holds the current word, iOS the + // unconverted pinyin): reading and resetting the field under it can + // desync the keyboard. Blur commits the composition, focus keeps the + // keyboard up (still inside the tap's gesture), then send what landed. + _textarea.blur(); + _textarea.focus(); + } + return _submit(); + }, + + /** + * Send-on-Enter: keep the held draft of the session being left, so a + * switch (a stray sideways swipe) does not lose an answer. Call before + * clear(); restoreDraft() puts it back when that session is shown again. + */ + stashDraft(sessionId) { + if (!_initialized || !_textarea || !_hold || !sessionId) return; + // An empty field leaves any stash alone: a draft only sits in the map + // while its session is not shown (restoreDraft takes it out), and the + // tile grid may stash an id whose draft is already put away. + const draft = _strip(_textarea.value); + if (draft.trim()) _drafts.set(sessionId, draft); + }, + + /** Send-on-Enter: show the draft stashed for this session, if any, unless + * the field already holds text. */ + restoreDraft(sessionId) { + if (!_initialized || !_textarea || !_hold || !_drafts.has(sessionId)) return; + if (_strip(_textarea.value)) return; + const draft = _drafts.get(sessionId); + _drafts.delete(sessionId); + _t(`restore draft len=${draft.length}`); + _textarea.value = PHANTOM + draft; + _textarea.setSelectionRange(_textarea.value.length, _textarea.value.length); + _heldBase = draft; + _autoGrow(); + }, + + /** Forget a stashed draft when its session no longer exists. */ + discardDraft(sessionId) { + _drafts.delete(sessionId); + }, + /** Diagnostic: recent IME event trace (ring buffer). */ getTrace() { return _trace.slice(); diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index 09a350bc..7a292683 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -2082,6 +2082,16 @@ Object.assign(CodemanApp.prototype, { * so overlay flush, flushed-offset cleanup and ordering are all reused. */ sendEnterKey() { if (!this.activeSessionId) return; + // While the CJK field is visible, onData drops everything (cjkActive), this + // Enter included. Press Enter in the field instead: it sends what the field + // holds (a Send on Enter answer, or live text not yet flushed), then Enter. + if ( + typeof CjkInput !== 'undefined' && + document.getElementById('cjkInput')?.classList.contains('cjk-input-visible') + ) { + CjkInput.submit?.(); + return; + } const coreService = this.terminal?._core?.coreService; if (coreService && typeof coreService.triggerDataEvent === 'function') { coreService.triggerDataEvent('\r', true); diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 5dd912d7..c31dba41 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -14199,6 +14199,11 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat resize: none; line-height: 1.4; box-sizing: border-box; + /* Send on Enter grows the field with its text (input-cjk.js _autoGrow), and the + setting is not limited to phones: cap it everywhere, not only in the + .touch-device rule, or on desktop it pushes the terminal (and its PTY) down. */ + max-height: 68px; + overflow-y: auto; } #cjkInput:focus { diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 46cdbf44..13376a12 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4570,11 +4570,15 @@ Object.assign(CodemanApp.prototype, { /** * Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held - * answer that is too long for one `\r` write, or has several lines. - * Claude Code takes a long burst as a paste and its \r as a newline, so it goes - * through the composer's path instead: the session is captured now, so the - * delayed Enter cannot follow a tab switch, and the length check applies. - * Returns false when nothing was sent, so the field keeps the text. + * answer, then Enter as its own write ~120 ms later. Never `\r` in one + * write: Codex reads characters arriving in one burst as a paste and folds an + * Enter inside it into the paste (even `1\r` stays unsent), and Claude Code + * does the same for a long burst. Same split as TmuxManager.sendInput: a + * single character is typed (a selection dialog ignores a pasted `3`, then + * Enter confirms the highlighted option), anything else goes through the + * composer's path as one bracketed paste. The session is captured now, so the + * delayed Enter cannot follow a tab switch. Returns false when nothing was + * sent (no session, too long), so the field keeps the text. */ _sendCjkPrompt(text) { const sessionId = this.activeSessionId; @@ -4582,10 +4586,17 @@ Object.assign(CodemanApp.prototype, { _crashDiag.log(`CJK prompt DROP no-session len=${text.length}`); return false; } - // A multi-character chunk spends an armed one-shot Ctrl (same rule as - // _handleCjkInput); leaving it armed would modify the next keystroke. + // A held answer is never what an armed one-shot Ctrl applies to (CjkInput + // sends the next typed character straight away as the control key), so + // Enter spends it, the same rule _handleCjkInput has for a longer chunk. KeyboardAccessoryBar.clearCtrl?.(); _crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`); + if ([...text].length === 1) { + if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions(); + this._sendInputAsync(sessionId, text); + setTimeout(() => this._sendInputAsync(sessionId, '\r', { useMux: true }), 120); + return true; + } return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text); }, diff --git a/src/web/public/tile-grid.js b/src/web/public/tile-grid.js index 018dd2f3..7fd3a0c7 100644 --- a/src/web/public/tile-grid.js +++ b/src/web/public/tile-grid.js @@ -2651,6 +2651,17 @@ Object.assign(CodemanApp.prototype, { // Aborts any in-flight normal select at its next _isStaleSelect check. const selectGen = ++this._selectGeneration; this._hideWebviewLayer?.(); + // The one CJK field follows tile focus, and Enter sends to the session + // active at that moment: a Send on Enter draft typed for one tile must not + // go to the next. Stash it for the tile left, show the one focused (also + // the draft openTileGrid's cleanup stashed for the session it parked). + if (typeof CjkInput !== 'undefined') { + if (this.activeSessionId && this.activeSessionId !== sessionId) { + CjkInput.stashDraft?.(this.activeSessionId); + CjkInput.clear(); + } + CjkInput.restoreDraft?.(sessionId); + } this.activeSessionId = sessionId; grid.focusedId = sessionId; // Moving focus off a zoomed tile restores the grid, as selecting another diff --git a/test/cjk-hold-per-device-setting.test.ts b/test/cjk-hold-per-device-setting.test.ts index 1e76428e..0a46d986 100644 --- a/test/cjk-hold-per-device-setting.test.ts +++ b/test/cjk-hold-per-device-setting.test.ts @@ -53,8 +53,9 @@ describe('a held draft survives a reload of the same session', () => { // The REAL _cleanupPreviousSession from app.js. selectSession() nulls // activeSessionId before calling it on a same-session forceReload (tapping the // tab already shown, the geometry retry), so it is told through keepCjkDraft. - function cleanup(hold: boolean, keepCjkDraft: boolean) { + function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) { const clear = vi.fn(); + const stashDraft = vi.fn(); const context = vm.createContext({ console, setTimeout, @@ -70,20 +71,21 @@ describe('a held draft survives a reload of the same session', () => { localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() }, window: { addEventListener: vi.fn(), removeEventListener: vi.fn() }, MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' }, - CjkInput: { holdUntilEnter: hold, clear }, + CjkInput: { holdUntilEnter: hold, clear, stashDraft }, }); vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context); const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp; const app = Object.create(CodemanApp.prototype) as Record & { _cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void; }; - app.activeSessionId = null; + app.activeSessionId = outgoing; + app.sessions = new Map(); app._clearTimer = vi.fn(); app._disconnectWs = vi.fn(); app._xtermSnapshots = new Map(); app.pendingWrites = []; app._cleanupPreviousSession('s1', { keepCjkDraft }); - return clear; + return Object.assign(clear, { stashDraft }); } it('keeps the draft on a same-session reload in Send on Enter mode', () => { @@ -98,6 +100,41 @@ describe('a held draft survives a reload of the same session', () => { expect(cleanup(false, true)).toHaveBeenCalled(); }); + it('stashes the held draft of the session being left before clearing', () => { + const clear = cleanup(true, false, 's0'); + expect(clear.stashDraft).toHaveBeenCalledWith('s0'); + expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]); + }); + + it('selectSession restores the draft of the session it lands on', () => { + expect(read('app.js')).toContain( + "this.activeSessionId = sessionId;\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);" + ); + }); + + it('leaving the tile grid for another session stashes the focused tile draft', () => { + // selectSession nulls activeSessionId there, which hides the tile from + // _cleanupPreviousSession. + expect(read('app.js')).toMatch( + /CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/ + ); + }); + + it('tile focus stashes the draft of the tile left and restores the focused one', () => { + const tiles = read('tile-grid.js'); + const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {'); + const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start)); + expect(body).toMatch( + /CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/ + ); + }); + + it('a removed session drops its stashed draft', () => { + expect(read('app.js')).toMatch( + /discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/ + ); + }); + it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => { const appJs = read('app.js'); expect(appJs).toMatch( @@ -115,6 +152,24 @@ describe('Send on Enter field layout and strings', () => { ); }); + it('caps the field on every device, not only in the .touch-device rule', () => { + // The setting is not limited to phones; on desktop an uncapped field grew to + // 502px at 25 lines and resized the PTY on every step. + const css = read('styles.css'); + const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {'))); + expect(base).toContain('max-height: 68px;'); + expect(base).toContain('overflow-y: auto;'); + }); + + it('the phone toolbar Enter presses Enter in the visible CJK field', () => { + // onData drops everything while cjkActive, so the xterm path does nothing. + const sessionUi = read('session-ui.js'); + const start = sessionUi.indexOf(' sendEnterKey() {'); + const body = sessionUi.slice(start, sessionUi.indexOf('triggerDataEvent', start)); + expect(body).toContain("classList.contains('cjk-input-visible')"); + expect(body).toContain('CjkInput.submit?.();'); + }); + it('has zh-CN strings for both field placeholders', () => { const i18n = read('i18n.js'); const cjk = read('input-cjk.js'); diff --git a/test/input-cjk-hold.test.ts b/test/input-cjk-hold.test.ts index f17a0772..d2b6140e 100644 --- a/test/input-cjk-hold.test.ts +++ b/test/input-cjk-hold.test.ts @@ -21,14 +21,18 @@ function makeTextarea() { placeholder: '', style: { height: '' } as Record, scrollHeight: 34, + // border-box with a 1px border: offsetHeight - clientHeight is the borders. + offsetHeight: 36, + clientHeight: 34, attrs, - blur: () => {}, - focus: () => {}, + blur: vi.fn(), + focus: vi.fn(), + getClientRects: (): unknown[] => [{}], classList: { contains: (c: string) => c === 'cjk-input-visible' }, setSelectionRange: () => {}, - setAttribute: (k: string, v: string) => { + setAttribute: vi.fn((k: string, v: string) => { attrs[k] = v; - }, + }), addEventListener: (ev: string, fn: (e?: unknown) => void) => { listeners.set(ev, [...(listeners.get(ev) ?? []), fn]); }, @@ -136,43 +140,38 @@ describe('CJK input: Send on Enter', () => { expect(textarea.value).toBe(PHANTOM + 'the'); }); - it('sends one line as text + CR on Enter, then clears the field', () => { - const { textarea, sent } = load(); + it('sends one line on Enter through the prompt path, then clears the field', () => { + const { textarea, sent, prompts } = load(); type(textarea, 'yes, use Postgres'); const preventDefault = vi.fn(); textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault }); expect(preventDefault).toHaveBeenCalled(); - expect(sent).toEqual(['yes, use Postgres\r']); - expect(textarea.value).toBe(PHANTOM); - }); - - it('sends a digit as typed so CLI menus still answer to it', () => { - const { textarea, sent } = load(); - type(textarea, '2'); - textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false }); - expect(sent).toEqual(['2\r']); - }); - - it('sends a long single line as a prompt, never as one \\r burst', () => { - // Claude Code takes a burst of ~100+ characters as a paste and its \r as a - // newline, so the answer would sit unsent (src/web/route-helpers.ts). - const { textarea, sent, prompts } = load(); - const long = 'x'.repeat(150); - type(textarea, long); - enter(textarea); + expect(prompts).toEqual(['yes, use Postgres']); expect(sent).toEqual([]); - expect(prompts).toEqual([long]); expect(textarea.value).toBe(PHANTOM); }); - it('keeps a line at the direct-write limit as one write, one over it as a prompt', () => { + it('never writes text and Enter together, whatever the length', () => { + // Codex takes characters arriving in one burst as a paste and folds an Enter + // inside it into the paste, so even `1\r` in one write stays unsent; Claude + // Code does the same for a long burst. terminal-ui.js _sendCjkPrompt types a + // single character and pastes anything longer, Enter always on its own. const { textarea, sent, prompts } = load(); - type(textarea, 'a'.repeat(64)); + for (const answer of ['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]) { + type(textarea, answer); + enter(textarea); + } + expect(sent).toEqual([]); + expect(prompts).toEqual(['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]); + expect(textarea.value).toBe(PHANTOM); + }); + + it('keeps a short answer in the field when it is refused (no session)', () => { + const { textarea, prompts } = load({ promptResult: false }); + type(textarea, 'yes'); enter(textarea); - type(textarea, 'b'.repeat(65)); - enter(textarea); - expect(sent).toEqual(['a'.repeat(64) + '\r']); - expect(prompts).toEqual(['b'.repeat(65)]); + expect(prompts).toEqual(['yes']); + expect(textarea.value).toBe(PHANTOM + 'yes'); }); it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => { @@ -322,10 +321,132 @@ describe('CJK input: Send on Enter', () => { textarea.scrollHeight = 60; type(textarea, 'a\nb\nc'); vi.advanceTimersByTime(1000); - expect(textarea.style.height).toBe('60px'); + // scrollHeight + the 2px of border, so a two-line draft does not scroll inside. + expect(textarea.style.height).toBe('62px'); expect(layout).toHaveBeenCalled(); }); + it('leaves the field alone when the mode is set again unchanged', () => { + // Runs on every session select and SSE reconnect, possibly mid-composition. + const { CjkInput, textarea } = load(); + textarea.setAttribute.mockClear(); + textarea.placeholder = 'untouched'; + CjkInput.setHoldUntilEnter(true); + expect(textarea.setAttribute).not.toHaveBeenCalled(); + expect(textarea.placeholder).toBe('untouched'); + CjkInput.setHoldUntilEnter(false); + expect(textarea.setAttribute).toHaveBeenCalled(); + }); + + it('submit() from outside the field (toolbar Enter) sends like Enter', () => { + const { CjkInput, textarea, prompts, sent } = load(); + type(textarea, 'go ahead'); + expect(CjkInput.submit()).toBe(true); + expect(prompts).toEqual(['go ahead']); + expect(textarea.value).toBe(PHANTOM); + expect(CjkInput.submit()).toBe(true); + expect(sent).toEqual(['\r']); + }); + + it('submit() keeps a refused answer and reports it', () => { + const { CjkInput, textarea } = load({ promptResult: false }); + type(textarea, 'go ahead'); + expect(CjkInput.submit()).toBe(false); + expect(textarea.value).toBe(PHANTOM + 'go ahead'); + }); + + it('a draft stashed on a switch comes back for its own session only', () => { + const { CjkInput, textarea, sent, prompts } = load(); + type(textarea, 'half an answer'); + CjkInput.stashDraft('session-a'); + CjkInput.clear(); + expect(textarea.value).toBe(PHANTOM); + CjkInput.restoreDraft('session-b'); + expect(textarea.value).toBe(PHANTOM); + CjkInput.restoreDraft('session-a'); + expect(textarea.value).toBe(PHANTOM + 'half an answer'); + // Restored once: a second visit does not bring it back again. + CjkInput.clear(); + CjkInput.restoreDraft('session-a'); + expect(textarea.value).toBe(PHANTOM); + expect(sent).toEqual([]); + expect(prompts).toEqual([]); + }); + + it('a restored draft is held text: Backspace edits it without a DEL', () => { + const { CjkInput, textarea, sent } = load(); + type(textarea, 'ok'); + CjkInput.stashDraft('session-a'); + CjkInput.clear(); + CjkInput.restoreDraft('session-a'); + backspace(textarea, PHANTOM + 'o'); + backspace(textarea, PHANTOM); + expect(sent).toEqual([]); + }); + + it('an empty field stashes nothing, and a discarded draft is gone', () => { + const { CjkInput, textarea } = load(); + type(textarea, 'draft'); + CjkInput.stashDraft('session-a'); + CjkInput.discardDraft('session-a'); + CjkInput.clear(); + CjkInput.restoreDraft('session-a'); + expect(textarea.value).toBe(PHANTOM); + CjkInput.stashDraft('session-b'); + CjkInput.restoreDraft('session-b'); + expect(textarea.value).toBe(PHANTOM); + }); + + it('a switch with an empty field keeps the draft already stashed for that session', () => { + // The tile grid stashes the session it parks, then may stash it again from + // tile focus with the field already cleared. + const { CjkInput, textarea } = load(); + type(textarea, 'keep me'); + CjkInput.stashDraft('session-a'); + CjkInput.clear(); + CjkInput.stashDraft('session-a'); + CjkInput.restoreDraft('session-a'); + expect(textarea.value).toBe(PHANTOM + 'keep me'); + }); + + it('sends a bare Enter when the field holds only blank lines', () => { + const { textarea, sent, prompts } = load(); + type(textarea, '\n'); + enter(textarea); + expect(prompts).toEqual([]); + expect(sent).toEqual(['\r']); + }); + + it('submit() mid-composition commits it first (blur, focus) and sends what landed', () => { + const { CjkInput, textarea, prompts } = load(); + textarea.fire('compositionstart'); + textarea.value = PHANTOM + 'yes'; + textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' }); + expect(CjkInput.submit()).toBe(true); + expect(textarea.blur).toHaveBeenCalled(); + expect(textarea.focus).toHaveBeenCalled(); + expect(prompts).toEqual(['yes']); + expect(textarea.value).toBe(PHANTOM); + }); + + it('a hidden field does not get a 0px height (no session shown yet)', () => { + const { CjkInput, textarea } = load({ hold: false }); + textarea.getClientRects = () => []; + textarea.scrollHeight = 0; + textarea.style.height = '40px'; + CjkInput.setHoldUntilEnter(true); + expect(textarea.style.height).toBe(''); + }); + + it('live mode stashes no drafts', () => { + const { CjkInput, textarea } = load({ hold: false }); + textarea.value = PHANTOM + 'abc'; + CjkInput.stashDraft('session-a'); + CjkInput.clear(); + CjkInput.restoreDraft('session-a'); + expect(textarea.value).toBe(PHANTOM); + }); + it('live mode is unchanged: text streams after the debounce', () => { const { textarea, sent } = load({ hold: false }); type(textarea, 'hi'); diff --git a/test/mobile-shell-keyboard.test.ts b/test/mobile-shell-keyboard.test.ts index 5286be02..aff9bdd8 100644 --- a/test/mobile-shell-keyboard.test.ts +++ b/test/mobile-shell-keyboard.test.ts @@ -41,8 +41,9 @@ function loadTerminalModule(): TerminalModule { console, setInterval: vi.fn(), clearInterval: vi.fn(), - setTimeout, - clearTimeout, + // Looked up per call, so a test's vi.useFakeTimers() reaches the cached module. + setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms), + clearTimeout: (t: ReturnType) => clearTimeout(t), requestAnimationFrame: vi.fn(), HTMLCanvasElement: class HTMLCanvasElement {}, WebSocket: { OPEN: 1 }, @@ -547,10 +548,10 @@ describe('one-shot Ctrl through the CJK input field', () => { }); }); -describe('Send on Enter: a long or multi-line held answer goes out as a composed prompt', () => { - // _sendCjkPrompt is CjkInput's sendPrompt callback. It hands the text to the - // composer's _sendComposedPrompt with the session captured at Enter, so the - // delayed Enter cannot follow a tab switch. +describe('Send on Enter: a held answer goes out with Enter as its own write', () => { + // _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one + // character goes to the composer's _sendComposedPrompt with the session + // captured at Enter, so the delayed Enter cannot follow a tab switch. function promptApp() { const { CodemanApp, bar } = loadTerminalModule(); bar.clearCtrl(); @@ -581,12 +582,44 @@ describe('Send on Enter: a long or multi-line held answer goes out as a composed composed.mockRestore(); }); + it('types a single character, then Enter ~120 ms later to the same session', () => { + // Codex folds an Enter that arrives in the same burst as the text into a + // paste, even for `1\r`; a selection dialog ignores a pasted digit. Same + // split as TmuxManager.sendInput (submitsAsKeys). + vi.useFakeTimers(); + try { + const { app, composed } = promptApp(); + const writes: Array<[string, string, unknown]> = []; + (app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) => + writes.push([id, input, opts]); + expect(app._sendCjkPrompt('1')).toBe(true); + expect(writes).toEqual([['session-a', '1', undefined]]); + app.activeSessionId = 'session-b'; + vi.advanceTimersByTime(119); + expect(writes).toHaveLength(1); + vi.advanceTimersByTime(1); + expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]); + expect(composed).not.toHaveBeenCalled(); + composed.mockRestore(); + } finally { + vi.useRealTimers(); + } + }); + + it('pastes even a short word: only one character is typed', () => { + const { app, composed } = promptApp(); + expect(app._sendCjkPrompt('yes')).toBe(true); + expect(composed).toHaveBeenCalledWith('session-a', 'yes'); + composed.mockRestore(); + }); + it('reports a refusal so the field keeps the text', () => { const { app, composed } = promptApp(); composed.mockReturnValue(false); expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); app.activeSessionId = null; expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false); + expect(app._sendCjkPrompt('1')).toBe(false); expect(composed).toHaveBeenCalledTimes(1); composed.mockRestore(); }); From 80d719df5fe60162bd0148ead8d850b0a6beed6b Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Mon, 16 Nov 2026 20:38:20 +0100 Subject: [PATCH 05/12] fix(mobile): keep the Send on Enter draft when going Home goHome() nulled activeSessionId without stashing the field, so picking the session again cleared the draft. Stash it first. Docs: src/web/CLAUDE.md lists cjkInputHoldUntilEnter among the per-device keys the strict schema does not declare, and notes the sendEnterKey() exception for the visible CJK field. Co-Authored-By: Claude Opus 5.5 --- src/web/CLAUDE.md | 4 ++-- src/web/public/app.js | 3 +++ test/cjk-hold-per-device-setting.test.ts | 7 +++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 6932427d..37c97087 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -56,7 +56,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry) -**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. +**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. **Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `
` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `