Merge #820: Send on Enter for the pinned CJK input field

A per-device mode for the pinned CJK field on phones: a typed answer stays in the field while the terminal scrolls and goes out only on Enter.
This commit is contained in:
Codeman maintainer committed 2026-11-20 04:00:05 +01:00
commit 6222444e82
20 files changed
+1725 -42

No files matched your search

+3 -3
View File
@@ -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 `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
@@ -82,11 +82,11 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**WebSocket output-gap reconcile** (`_wsOutputGapSession`, app.js): output frames carry no sequence number, so an unintentional WS close while SSE stays up marks the session and the next open reconciles. ⚠️ The marker is cleared only once a repaint actually happened (`_markTerminalBufferReconciled()`, never in a `finally`). → [architecture-invariants#websocket-output-gap-reconcile](../../docs/architecture-invariants.md#websocket-output-gap-reconcile)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Dismissing the on-screen keyboard** (`terminal-ui.js`): two gestures blur the terminal's hidden textarea. (1) `_installMobileKeyboardDismiss()`, a document `touchend` that must never fire inside `#terminalContainer` or on a control (`MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR`, via `closest()`; roving-tabindex items sit at `tabindex=-1`, so the grouped rail's are listed as `[role="treeitem"]`). (2) In `_handleMobileTerminalTap`, a second tap on inert `content` blurs; the prompt row keeps focus-then-position. ⚠️ A scroll also ends in `touchend`: both classifiers must share one threshold (`TAP_THRESHOLD` reads `MOBILE_KEYBOARD_DISMISS_TAP_SLOP`), and multi-touch is never a tap. ⚠️ An accessory key that keeps the keyboard up (`ACCESSORY_REFOCUS_ACTIONS`, keyboard-accessory.js) cancels its `mousedown` default, so the press does not blur the terminal; the click-time `terminal.focus()` stays as the fallback. Letting the tap blur and refocusing afterwards made every such key start a dismissal, a blur/focus pair per tap. A first tap on clear/compact only arms the confirm and is treated the same (`test/accessory-keeps-terminal-focus.test.ts`). ⚠️ The content touchstart blur skips the visible `#cjkInput` (`_contentTouchStartBlurs()`), or every swipe on the live screen closed its keyboard; a tap still closes it (inert content, a link, a long press). On phones `updateLayoutForKeyboard()` also moves `.app` by `visualViewport.offsetTop` while the keyboard is up, and lifts the fixed bars inside it from `.app`'s bottom (architecture-invariants, Folding devices section). ⚠️ CI cannot see the only test for (1): run `npm run test:mobile -- test/mobile/keyboard.test.ts` by hand and diff the FAIL list against master. → [architecture-invariants#dismissing-the-on-screen-keyboard](../../docs/architecture-invariants.md#dismissing-the-on-screen-keyboard)
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
+29 -3
View File
@@ -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();
}
@@ -9379,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
@@ -9432,8 +9437,16 @@ 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. 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') {
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 = '';
@@ -9973,11 +9986,19 @@ 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;
}
// 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 {}
@@ -10024,9 +10045,10 @@ 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);
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(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).
this._reconcileKeyboardHold?.({ resize: false });
@@ -10823,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.
@@ -11104,6 +11127,9 @@ class CodemanApp {
this._retireUrlSession();
// Home is a choice to leave the grid too; it is remembered for Tiles.
this.closeTileGrid?.({ keepStored: true, reselect: false });
// A Send on Enter draft goes with its session: the null below hides that
// session from the next _cleanupPreviousSession, which would clear it unstashed.
if (typeof CjkInput !== 'undefined' && this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
// Deselect active session and show welcome screen
this.activeSessionId = null;
try { localStorage.removeItem('codeman-active-session'); } catch {}
+5
View File
@@ -743,6 +743,11 @@
"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 发送',
'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': '扩展键盘栏',
'Gesture Control (beta)': '手势控制(测试版)',
'Wheel Scrolls Local History': '滚轮滚动本地历史',
+7
View File
@@ -2065,6 +2065,13 @@
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="cjk input send on enter hold draft pinned prompt field phone">
<div class="set-row-text">
<span class="set-row-label">Input Field: Send on Enter</span>
<span class="set-row-desc">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.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkHoldUntilEnter"><span class="slider"></span></label>
</div>
<div class="set-row" data-search="extended keyboard bar tab esc arrows phone">
<div class="set-row-text">
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
+321 -13
View File
@@ -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 <textarea> subtrees (what is typed there is user
// content), so it is translated here, like the prompt composer's.
if (_textarea) {
const source = !!on
? 'Type, Enter to send (Shift+Enter: new line, Esc: clear)'
: 'CJK input (Enter = send, Esc = clear)';
const i18n = typeof window !== 'undefined' ? window.CodemanI18n : undefined;
const placeholder = typeof i18n?.t === 'function' ? i18n.t(source) : source;
if (_textarea.placeholder !== placeholder) _textarea.placeholder = placeholder;
}
// Called on every session select and SSE reconnect: with the mode
// unchanged, leave the rest of the field alone, since rewriting its
// attributes while it has focus can disturb a composition in progress.
if (_holdApplied && _textarea && _hold === !!on) return;
const wasHolding = _hold;
_hold = !!on;
if (!_textarea) return;
_holdApplied = true;
// Turning the mode off: live mode's next flush would send everything in
// the field, a held multi-line draft included (its newline runs the first
// line in a shell), and stashed drafts would come back if the mode is
// switched on again. Drop them all.
if (wasHolding && !_hold) {
_drafts.clear();
_resetToPhantom();
}
_heldBase = _strip(_textarea.value);
const v = _hold ? 'on' : 'off';
_textarea.setAttribute('autocorrect', v);
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
_textarea.setAttribute('spellcheck', _hold ? 'true' : 'false');
if (_hold) {
_cancelDebouncedFlush();
_autoGrow();
} else {
_textarea.style.height = '';
}
_t(`hold ${v}`);
},
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) return;
// The field now belongs to this session, draft or not (see _owner),
// unless it still holds another session's text (no clear() in between).
if (!_owner || !_strip(_textarea.value)) _owner = sessionId || null;
if (!_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);
if (_owner === sessionId) _owner = null;
},
/** Diagnostic/test: the session the field's text belongs to. */
get draftOwner() { return _owner; },
/** Diagnostic: recent IME event trace (ring buffer). */
getTrace() {
return _trace.slice();
+47 -13
View File
@@ -435,27 +435,55 @@ const KeyboardHandler = {
// BEHIND the keyboard with its own search box out of sight.
const caseSheet = document.querySelector('.mobile-case-picker.active .mobile-case-picker-sheet');
// A focused field that starts behind the keyboard (the pinned CJK / Send on
// Enter field) makes Android pan the visual viewport down to reveal it (measured
// on Chrome: offsetTop 285px with a 458px visual viewport in a 744px layout one).
// The app is sized to the visual viewport but laid out at the top of the layout
// viewport, so that pan left only the terminal's last line on screen. On phones,
// follow the pan while the keyboard is up, whatever has focus: without a pan
// (offsetTop 0, the usual case) nothing moves, and a focus change that keeps the
// pan cannot drop the shift. Every other branch clears it.
// ⚠️ The transform makes .app the box its position:fixed children (header,
// toolbar, accessory bar, the field) are placed against, so their keyboard lift
// below is measured from .app's bottom, not the layout viewport's, or they would
// be lifted twice on a partial pan. The case sheet (#mobileCasePickerModal) is
// inside .app too and takes the same lift.
const appEl = document.querySelector('.app');
const pan = isSmallMedium ? Math.round(window.visualViewport.offsetTop || 0) : 0;
if (appEl) appEl.style.transform = pan > 0 ? `translateY(${pan}px)` : '';
// The layout viewport's height, which position:fixed bottoms are measured from.
// ⚠️ Not window.innerHeight alone: on the first keyboard open after focusing the
// pinned field, iOS Safari reported innerHeight as the shrunk visual height (323)
// while the layout viewport stayed 640 (documentElement.clientHeight), so the lift
// came out 0 and the bars stayed behind the keyboard. Earlier a delayed
// scrollIntoView re-ran this pass once innerHeight had caught up; without it the
// stale value stuck. The larger of the two cannot be stale in that direction.
const layoutHeight = Math.max(window.innerHeight, document.documentElement?.clientHeight || 0);
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
const insideLift = pan > 0 && appEl ? Math.max(0, pan + appEl.offsetHeight - visualBottom) : keyboardOffset;
if (isSmallMedium) {
// Phones/small tablets: toolbar and accessory bar are position:fixed
// via CSS. Use translateY to lift them above the keyboard.
const toolbar = document.querySelector('.toolbar');
const main = document.querySelector('.main');
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
if (toolbar) {
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
toolbar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (accessoryBar) {
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
accessoryBar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
}
if (caseSheet) {
caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
caseSheet.style.transform = insideLift > 0 ? `translateY(${-insideLift}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) {
@@ -472,11 +500,8 @@ const KeyboardHandler = {
// CJK textarea positioning (always position:fixed on touch devices).
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
if (isSmallMedium) {
// Phones: use translateY like toolbar/accessory bar.
const layoutHeight = window.innerHeight;
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
// Phones: use translateY like toolbar/accessory bar (it sits inside .app too).
cjkInput.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
cjkInput.style.bottom = '';
} else {
// iPad: direct bottom = keyboard + accessory bar height.
@@ -499,7 +524,11 @@ const KeyboardHandler = {
// keyboard was still up must still have its inline offset cleared, or the
// next open slides in already displaced.
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
const appEl = document.querySelector('.app');
if (appEl) {
appEl.style.transform = '';
}
if (toolbar) {
toolbar.style.transform = '';
}
@@ -729,6 +758,11 @@ const KeyboardHandler = {
if (el.closest('.xterm') || el.closest('.terminal-container')) {
return false;
}
// The pinned CJK / Send on Enter field is position:fixed and lifted above the
// keyboard by updateLayoutForKeyboard(). Scrolling it into view centred it in its
// scrollable ancestors instead, which pushed the terminal off screen whenever the
// field took focus.
if (el.id === 'cjkInput') return false;
const tagName = el.tagName?.toLowerCase();
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
+10
View File
@@ -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);
+6 -1
View File
@@ -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',
+13
View File
@@ -14199,6 +14199,12 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
resize: none;
line-height: 1.4;
box-sizing: border-box;
/* A backstop: Send on Enter grows the field with its text only on touch devices
(input-cjk.js _autoGrow), where the .touch-device rule caps it too. On desktop
it keeps its one-line height, so this cap only guards against anything else
setting a taller one, which would push the terminal (and its PTY) down. */
max-height: 68px;
overflow-y: auto;
}
#cjkInput:focus {
@@ -14235,6 +14241,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));
}
+71 -4
View File
@@ -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),
});
}
@@ -1374,7 +1378,7 @@ Object.assign(CodemanApp.prototype, {
// selectSession() ends with scrollToLastNonEmptyLine(), that made
// the keyboard unreachable after every tab switch.
ev.preventDefault();
this._blurMobileTerminalInput();
if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
}
// Hold still and this press becomes a text selection. Cancelled by any
// travel past the shared tap slop below, so a scroll can never become one.
@@ -4551,8 +4555,10 @@ Object.assign(CodemanApp.prototype, {
// after every key. So the onData hook never sees these keystrokes, and an
// armed modifier could neither fire NOR be spent: it survived until a
// session switch and then turned an innocent keystroke into a control byte.
// This is the module's single choke point to the PTY, so applying it here
// covers typed characters, IME flushes, Enter, backspace and arrows at once.
// This is the module's single choke point to the PTY in live mode, so applying
// it here covers typed characters, IME flushes, Enter, backspace and arrows at
// once. In Send on Enter a held answer leaves through _sendCjkPrompt instead,
// which spends the modifier; an armed next character still comes here.
// Same policy as the onData hook: the next single character is modified,
// anything longer merely spends the modifier.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
@@ -4564,6 +4570,49 @@ Object.assign(CodemanApp.prototype, {
this._sendInputAsync(this.activeSessionId, text);
},
/**
* Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held
* answer, then Enter as its own write ~120 ms later. Never `<text>\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. A lone digit while the session
* shows a permission or question dialog goes out without the Enter: the
* dialog acts on the digit itself, and a later Enter would confirm whatever
* the CLI shows next (a second permission prompt, unseen). Same rule as the
* Approvals Inbox and the Discord bridge (server.ts awaitingChoice). Returns
* false when nothing was sent (no session, too long), 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 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);
const hooks = this.pendingHooks?.get(sessionId);
const awaitingChoice = !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog'));
if (/^\d$/.test(text) && awaitingChoice) {
_crashDiag.log(`CJK prompt digit answers a dialog, no Enter`);
return true;
}
setTimeout(() => this._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
return true;
}
return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text);
},
/**
* Re-assert a history anchor captured before a terminal write (#358).
*
@@ -5087,7 +5136,9 @@ Object.assign(CodemanApp.prototype, {
clearTerminalInput() {
if (!this.activeSessionId) return;
if (typeof CjkInput !== 'undefined') CjkInput.clear();
// discard: the line is thrown away, so a Send on Enter draft must not be
// stashed and come back on the next visit to this session.
if (typeof CjkInput !== 'undefined') CjkInput.clear({ discard: true });
// A tile or Pane B holds the keyboard: its TUI owns the editable buffer
// (no local-echo overlay there), so kill the line in that pane's session,
// never in the parked main pane's.
@@ -5650,6 +5701,19 @@ Object.assign(CodemanApp.prototype, {
return 'content';
},
/**
* Whether a touchstart on transcript content should blur the focused terminal input.
* It does for xterm's helper textarea: that blur, with the preventDefault beside it,
* keeps the compatibility click from opening the keyboard. It must NOT for the pinned
* CJK field: at touchstart the gesture may still be a scroll, and that field owns the
* keyboard while it is visible, so blurring it closed the keyboard on every swipe that
* started on the live screen. A real tap on inert transcript still closes the keyboard
* at touchend (the startedWithTerminalFocus branch), so a tap keeps its meaning.
*/
_contentTouchStartBlurs() {
return document.activeElement?.id !== 'cjkInput';
},
_blurMobileTerminalInput() {
const active = document.activeElement;
if (
@@ -5848,6 +5912,9 @@ Object.assign(CodemanApp.prototype, {
) {
// No focus change: a 'content' tap was already blurred by touchstart, and
// popping the keyboard behind a tab that is about to take over is noise.
// The pinned CJK field is the exception touchstart leaves focused (a swipe must
// not close its keyboard), so a tap that opens a link closes it here instead.
if (!this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
return 'link';
}
+14
View File
@@ -2651,6 +2651,20 @@ 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) {
// A tile closed from this tab is already gone from this.sessions and
// its draft discarded: stashing it again would leave it in the map
// until the page reloads.
if (this.sessions?.has(this.activeSessionId)) 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