diff --git a/.changeset/cjk-send-on-enter.md b/.changeset/cjk-send-on-enter.md new file mode 100644 index 00000000..67be1cb6 --- /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. The phone toolbar's Enter button now also sends the CJK field's text while the field is visible, in live mode too. On phones the keyboard layout also gets sturdier for everyone: a swipe that starts on the live screen no longer closes the pinned field's keyboard, the app follows the browser when it pans the screen to a focused field instead of leaving only the terminal's last line visible, and on iOS the toolbar, accessory bar and field sit on the keyboard on its first open instead of behind it. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 57de889a..2b140de1 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -1139,7 +1139,9 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t **A fold is not a keyboard.** `KeyboardHandler.handleViewportResize()` (mobile-handlers.js) used to read any visual-viewport height drop over 150px as the keyboard appearing. A virtual keyboard only ever takes HEIGHT, so a resize that changes the WIDTH is the device changing shape (a rotation, or a foldable opening or closing) and is skipped by both detection branches. Closing an iPhone Duo (626→466pt wide, 890→678pt tall) otherwise latched `keyboardVisible` with no keyboard on screen: the accessory bar appeared, `main` grew 84px of dead padding, and `updateAppHeight()`, which bails while the keyboard is up, stopped refreshing `--app-height`. The latch was sticky because clearing it needed the height back within 100px of a baseline belonging to a display the user was no longer looking at. The shape branch re-baselines instead, which is also what lets a keyboard opened after the fold be detected, and `init()` seeds `lastViewportWidth` so the first resize of the page is not itself read as a shape change. -**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both. +**With the keyboard up, the new baseline is `window.innerHeight`, never the shrunk visual height.** The page sets no `interactive-widget`, so the default resizes-visual mode holds on both engines: the keyboard shrinks only the visual viewport and the layout viewport stays the display's full height (`updateLayoutForKeyboard()` relies on the same fact, but measures that height as the larger of `innerHeight` and `documentElement.clientHeight`: on a first keyboard open iOS Safari briefly reported `innerHeight` as the shrunk visual height, 323 against a 640 layout viewport, which zeroed the bars' lift). The first version baselined to the shrunk height, which made `heightDiff` 0, so the settle event the OS animation fires at the new width (or any later address-bar drift) satisfied the hide branch and ran `onKeyboardHide()` with the keyboard still on screen: accessory bar hidden, the toolbar lift dropped, `main`'s padding cleared. It could not recover, because no further 150px drop can re-arm the show branch against a baseline already sitting at the shrunk height. Reproduced against the real handler in the vm harness with both the fold flavour (626x590 → 466x378 → 466x378) and the rotation flavour (393x359 → 852x150 → 852x160); `test/viewport-shape-change.test.ts` models the two heights separately and pins both. + +**A pan of the visual viewport moves `.app` with it.** In resizes-visual mode a focused field that starts behind the keyboard makes Android pan the visual viewport down to reveal it: the pinned `#cjkInput` sits at the bottom of the layout viewport, and Chrome panned 285px with a 458px visual viewport in a 744px layout one. `.app` is sized to the visual viewport (`--app-height`) but laid out at the top of the layout viewport, so that pan left only the terminal's last line on screen. On phones `updateLayoutForKeyboard()` therefore sets `.app`'s `translateY` to `visualViewport.offsetTop` while the keyboard is up, whatever has focus (no pan, the usual case, moves nothing), and clears it on every other branch and in `resetLayout()`. ⚠️ The transform makes `.app` the box its `position: fixed` children are placed against (header, `.toolbar`, the accessory bar, which is inserted before the toolbar, `#cjkInput`, and the phone case sheet, `#mobileCasePickerModal`), so their lift is measured from `.app`'s bottom (`insideLift`), not the layout viewport's: lifting them by the layout gap as well floated them above the keyboard on a partial pan. Separately, `KeyboardHandler.isInputElement()` skips `#cjkInput` like xterm's inputs, because the focusin `scrollIntoView({ block: 'center' })` centred the fixed field in its ancestors and pushed the terminal off screen. Pinned by `test/keyboard-handler-pinned-field.test.ts`. **The hinge is a reserved region, and the CSS is inert by construction.** The CSS Viewport Segments media features report two segments only while a foldable is actually bent; `--fold-inline-end` / `--fold-block-end` (end of styles.css) measure the strip to keep clear from the LEADING segment (`env(viewport-segment-right 0 0)` and `env(viewport-segment-bottom 0 0)`, physical sides in every text direction) and are `0px` on everything else. The seven centred overlays are all `position: fixed; inset: 0` flex boxes; each shrinks its CONTENT box with padding rather than the box itself, so the backdrop still covers the far side of the fold and still swallows taps there. The cascade traps, each measured in headless Chromium against styles.css + mobile.css in index.html link order: (1) a later `padding-right` longhand beats the earlier `padding` shorthand it composes with, so each fold rule re-states the overlay's own gutter; (2) a base gutter that a LATER `@media` block overrides needs its own fold restatement in that block on a ZERO base, since the unconditional rules at the end of the file otherwise put the gutter back (the phone path picker and path preview drop to `padding: 0` under 600px and came back at 16px and 18px on every phone); (3) a compound rule written to outrank a mobile.css shorthand must be scoped to the band where that shorthand applies, because outside it there is no gutter to compose with (the palette's `.modal.command-palette-modal` added 0.75rem at 393, 900 and 1400px and pushed the shell 6px off centre, and inside the band it lost its bottom gutter to the shorthand until it restated that side too); (4) mobile.css loads AFTER styles.css, so a same-specificity rule there wins under its own breakpoint (the response viewer's `max-height: 92dvh` under 600px beat the tabletop cap, which now has a twin at the end of mobile.css). `test/foldable-layout.test.ts` DERIVES the overlay list from the stylesheet, simulates the cascade across both files at every breakpoint with and without the fold rules, and requires the two results to differ by exactly the fold strip, so each of the four fails there instead of on hardware nobody has. @@ -1269,7 +1271,7 @@ The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTime ⚠️ It must disarm on ALL of: use, second tap, any other accessory key, session switch, keyboard dismissal, and a layout swap; a modifier left armed turns the next innocent keystroke into a control byte. -⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY, so one call covers typed characters, IME flushes, Enter, backspace and arrows. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke. +⚠️ **onData is not the only input path** — with `cjkInputEnabled` on, the CJK textarea owns the keyboard (onData returns early for everything it swallows, and the focus router sends `terminal.focus()` there, which is where the bar refocuses after every key), so `_handleCjkInput()` applies the modifier too. It is that module's single choke point to the PTY in live mode, so one call covers typed characters, IME flushes, Enter, backspace and arrows; in Send on Enter a held answer leaves through `_sendCjkPrompt()` instead, which spends the modifier, while an armed next character still goes through `_handleCjkInput()`. Without it an armed modifier could neither fire NOR be spent, and survived to a later keystroke. Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Space=NUL / Ctrl+?=DEL); characters with no control equivalent pass through unchanged, like a hardware keyboard. @@ -1299,6 +1301,8 @@ Tests: `test/mobile-prompt-composer.test.ts` (in the CI gate, deliberately not u **(2)** In `_handleMobileTerminalTap`, a second tap on **inert `content`** (`startedWithTerminalFocus`) blurs instead of re-focusing. ⚠️ Scoped to `content` on purpose: the prompt row (`input`) keeps focus-then-position so a second tap still places the caret, and actionable rows blur earlier via `_isActionableMobileTerminalTap`. +⚠️ **The pinned CJK field keeps its focus through a swipe.** `initTerminal`'s touchstart blurs the focused input on `content` before the gesture is known to be a tap or a scroll. For xterm's helper textarea that blur, with the `preventDefault` beside it, is what keeps the compatibility click from opening the keyboard. The visible `#cjkInput` owns the keyboard instead, so `_contentTouchStartBlurs()` leaves it focused; blurring it closed the keyboard on every swipe that started on the live screen. A real tap still closes it: inert content through (2), a link in `_handleMobileTerminalTap`'s link branch (which blurs because touchstart did not), a long press in `_beginTouchSelection`. A sideways session swipe keeps it open, since the field's draft is per session. Pinned by `test/terminal-touch-tap.test.ts`. + ⚠️ **A scroll ends in `touchend` too** — dismissing there closes the keyboard and drops the composer mid-read, so travel is tracked from `touchstart` and multi-touch is never a tap. Both classifiers MUST share one threshold: `initTerminal`'s `TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`, since a gesture the terminal calls a scroll and the dismiss handler calls a tap is exactly that bug. ⚠️ **An accessory key that keeps the keyboard up must not take focus on the press.** The keys that act on the terminal and leave the keyboard open (`ACCESSORY_REFOCUS_ACTIONS` in keyboard-accessory.js: scroll, arrows, Tab, Shift+Tab, Ctrl, Esc, clear input and the rest) cancel the `mousedown` default, the same pattern as the Attach input, so the hidden textarea keeps focus through the press; the `terminal.focus()` in the click handler stays as the fallback. Letting the tap blur the terminal and refocusing it afterwards made every such key start a keyboard dismissal, a blur/focus pair per tap that shifted the toolbar each time. A first tap on clear/compact only arms the confirm and is treated the same; the confirming tap, and keys that open a dialog or dismiss the keyboard on purpose, keep the default. Pinned against the real module by `test/accessory-keeps-terminal-focus.test.ts`. diff --git a/docs/wiki/Input-And-Voice.md b/docs/wiki/Input-And-Voice.md index d15e7864..54b29cfa 100644 --- a/docs/wiki/Input-And-Voice.md +++ b/docs/wiki/Input-And-Voice.md @@ -67,6 +67,22 @@ 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. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen +keyboard has no Shift+Enter, and the extended bar's newline key goes to the CLI, not the field), +Esc clears the field, and autocorrect is on. 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 one exception is a lone digit while a permission or question dialog is waiting: the +digit answers the dialog by itself, so no Enter follows it, which would otherwise confirm whatever +the CLI shows next. 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 a hardware keyboard, Ctrl shortcuts (undo, select all, copy) act on +the field while it holds a draft and reach the CLI only when it is empty. With the keyboard down +the field stays one line tall. A draft stays with its session: switching tabs and coming back +brings it back. + ## Voice dictation `Ctrl+Shift+V`, or the microphone button. There are three providers and the default is diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 821d6ab0..5bfd53a2 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. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). 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/CLAUDE.md b/src/web/CLAUDE.md index 6932427d..5260666a 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 ` +
+
+ 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..263ce654 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -7,6 +7,21 @@ * While this textarea has focus, window.cjkActive = true blocks xterm's onData. * Arrow keys and function keys are forwarded to PTY directly. * + * ## Send on Enter (setting cjkInputHoldUntilEnter) + * + * The live mode above streams typed text to the PTY after a short debounce. + * With Send on Enter on, the field is a chat box instead: _flush() holds the + * text, and only Enter sends it, through the sendPrompt callback + * (terminal-ui.js _sendCjkPrompt: a single character is typed, anything longer + * goes as the composer's bracketed paste, Enter is always its own later write, + * and a lone digit at a pending dialog goes without it). Shift+Enter is a + * newline, Esc clears, Backspace and the arrows reach the PTY only from an + * empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft + * belongs to one session (_owner): clear() stashes it under that session and + * restoreDraft() brings it back when the session is shown again, except a + * clear({ discard: true }) (the keyboard bar's clear-line key), which throws + * it away. + * * ## Android IME challenge * * Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use @@ -57,6 +72,27 @@ 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; + // 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 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(); + // Send-on-Enter: the session the field's text belongs to (the one last shown, + // set by restoreDraft). clear() stashes a held draft under it, so every path + // that drops the active session before the next cleanup (goHome, the tile + // grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer. + let _owner = null; const _listeners = {}; const PHANTOM = '​'; @@ -160,6 +196,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. @@ -189,6 +226,13 @@ const CjkInput = (() => { _t('flush SKIP composing'); return; } + // Send-on-Enter: nothing leaves the field until Enter (keydown handler). + if (_hold) { + _t('flush SKIP hold'); + _holdSettle(); + _autoGrow(); + return; + } const val = _strip(_textarea.value); _t(`flush ${val ? 'send len=' + val.length : 'empty'}`); if (val) { @@ -197,6 +241,133 @@ 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; + // 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; + } + // Only a touch device grows the field: there it is position: fixed above the + // keyboard. On a desktop it sits in the flex column under the terminal, so + // every line it gained would shrink the terminal box, refit and resize the + // session's PTY (a CLI repaint each time). It stays one line there and + // scrolls inside instead. + if (!document.body?.classList?.contains('touch-device')) { + _textarea.style.height = ''; + return; + } + const before = _textarea.style.height; + _textarea.style.height = 'auto'; + // 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, 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 (!_sendPrompt) { + _t('hold send DROP no-prompt-path'); + return false; + } + 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; + } + + /** 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; + } + _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 */ function _cancelDebouncedFlush() { if (_flushTimer) { @@ -226,14 +397,16 @@ const CjkInput = (() => { } return { - init({ send }) { + init({ send, sendPrompt = null }) { if (_initialized) this.destroy(); _send = send; + _sendPrompt = sendPrompt; _composing = false; _printableKeydownAt = null; _flushTimer = null; _textarea = document.getElementById('cjkInput'); + _holdApplied = false; // a new field has not had the mode applied if (!_textarea) return this; _resetToPhantom(); @@ -316,16 +489,14 @@ const CjkInput = (() => { _t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`); _printableKeydownAt = null; if (e.key === 'Enter') { - e.preventDefault(); - _composing = false; - _cancelDebouncedFlush(); - const val = _strip(_textarea.value); - if (val) { - _send(val + '\r'); - } else { - _send('\r'); + // 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; } - _resetToPhantom(); + e.preventDefault(); + _submit(); return; } @@ -334,10 +505,15 @@ const CjkInput = (() => { _composing = false; _cancelDebouncedFlush(); _resetToPhantom(); + if (_hold) _autoGrow(); return; } - if (e.ctrlKey && CTRL_KEYS[e.key]) { + // Send-on-Enter with a draft in the field: Ctrl shortcuts are the + // field's (Ctrl+Z undo, Ctrl+A select all, Ctrl+C copy a selection), so + // they reach the CLI only while the field is empty, the rule Backspace + // and the arrows already follow. + if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) { e.preventDefault(); _send(CTRL_KEYS[e.key]); return; @@ -405,6 +581,11 @@ const CjkInput = (() => { _composing = false; } + if (_hold) { + _holdInput(e); + return; + } + // ── Backspace / delete detection ── if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') { if (_composing) return; @@ -464,9 +645,24 @@ const CjkInput = (() => { * can't flush into the wrong session). Restores the phantom so backspace * forwarding keeps working — unlike a raw `textarea.value = ''`. */ - clear() { + clear({ discard = false } = {}) { if (!_initialized || !_textarea) return; - _t('clear (external)'); + _t(`clear (external)${discard ? ' discard' : ''}`); + if (discard) { + // The user threw the text away (the keyboard bar's clear-line key): + // nothing is stashed, any older stash of this session goes too, and the + // field keeps its owner, since the session shown has not changed. + if (_owner) _drafts.delete(_owner); + } else { + // Send-on-Enter: a held draft is stashed for the session it was typed + // for, whichever path got here. discardDraft() drops the owner of a + // removed session, so its text is not stashed again. + if (_hold && _owner) { + const draft = _strip(_textarea.value); + if (draft.trim()) _drafts.set(_owner, draft); + } + _owner = null; + } _cancelDebouncedFlush(); clearTimeout(_compositionFlushTimer); _compositionFlushTimer = null; @@ -475,6 +671,118 @@ 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) { + // The placeholder first, before the early return: App Settings applies a + // language switch live and then calls this with the mode unchanged. It is + // written only when the text differs, so a field mid-composition is not + // touched. i18n.js skips