From 64ee504247075b81e3fad656324ac5af23f921b1 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Mon, 16 Nov 2026 17:39:22 +0100 Subject: [PATCH] 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(); });