mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 13:09:33 +01:00
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:
commit
6222444e82
20 files changed
+1725
-42
No files matched your search
@@ -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.
|
||||||
@@ -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.
|
**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.
|
**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.
|
⚠️ 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.
|
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`.
|
**(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.
|
⚠️ **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`.
|
⚠️ **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`.
|
||||||
|
|||||||
@@ -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
|
Ctrl- and Alt-modified navigation keys typed through it reach the CLI as the modified
|
||||||
sequences, so word jumps and history keys keep working.
|
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
|
## Voice dictation
|
||||||
|
|
||||||
`Ctrl+Shift+V`, or the microphone button. There are three providers and the default is
|
`Ctrl+Shift+V`, or the microphone button. There are three providers and the default is
|
||||||
|
|||||||
@@ -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). |
|
| 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). |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
|
||||||
|
|||||||
+3
-3
@@ -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)
|
**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)
|
**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)
|
**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.
|
**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.
|
⚠️ **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
@@ -4929,6 +4929,11 @@ class CodemanApp {
|
|||||||
document.body.classList.toggle('cjk-input-visible', !!showCjk);
|
document.body.classList.toggle('cjk-input-visible', !!showCjk);
|
||||||
cjkEl.style.display = showCjk ? 'block' : 'none';
|
cjkEl.style.display = showCjk ? 'block' : 'none';
|
||||||
cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true');
|
cjkEl.setAttribute('aria-hidden', showCjk ? 'false' : 'true');
|
||||||
|
if (typeof CjkInput !== 'undefined') {
|
||||||
|
CjkInput.setHoldUntilEnter?.(
|
||||||
|
!!(settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false)
|
||||||
|
);
|
||||||
|
}
|
||||||
if (!showCjk) window.cjkActive = false;
|
if (!showCjk) window.cjkActive = false;
|
||||||
if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard();
|
if (typeof KeyboardHandler !== 'undefined') KeyboardHandler.updateLayoutForKeyboard();
|
||||||
}
|
}
|
||||||
@@ -9379,7 +9384,7 @@ class CodemanApp {
|
|||||||
|
|
||||||
// `skipSnapshot`: the tile grid opening on the session it parks
|
// `skipSnapshot`: the tile grid opening on the session it parks
|
||||||
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
|
// (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 +
|
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
|
||||||
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
|
// 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
|
// 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.
|
// 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
|
// 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.
|
// 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') {
|
if (typeof CjkInput !== 'undefined') {
|
||||||
CjkInput.clear();
|
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
|
||||||
|
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
|
||||||
|
CjkInput.clear();
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const cjkEl = document.getElementById('cjkInput');
|
const cjkEl = document.getElementById('cjkInput');
|
||||||
if (cjkEl) cjkEl.value = '';
|
if (cjkEl) cjkEl.value = '';
|
||||||
@@ -9973,11 +9986,19 @@ class CodemanApp {
|
|||||||
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
|
if (this._tileGrid.has(sessionId)) return this._selectTiledSession(sessionId, options);
|
||||||
if (options?.auto === true && !options?.leaveTiles) return;
|
if (options?.auto === true && !options?.leaveTiles) return;
|
||||||
this.closeTileGrid({ keepStored: true, reselect: false });
|
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;
|
// The parked terminal still holds what it showed before the grid opened;
|
||||||
// with no active id, the switch below snapshots none of it.
|
// with no active id, the switch below snapshots none of it.
|
||||||
this.activeSessionId = null;
|
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) {
|
if (this.activeSessionId === sessionId && forceReload) {
|
||||||
|
reloadingSameSession = true;
|
||||||
this.terminalBufferCache?.delete(sessionId);
|
this.terminalBufferCache?.delete(sessionId);
|
||||||
this._xtermSnapshots?.delete(sessionId);
|
this._xtermSnapshots?.delete(sessionId);
|
||||||
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
|
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.
|
// A session tab takes the stage back from any active web tab.
|
||||||
this._hideWebviewLayer?.();
|
this._hideWebviewLayer?.();
|
||||||
|
|
||||||
this._cleanupPreviousSession(sessionId);
|
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
|
||||||
this.activeSessionId = sessionId;
|
this.activeSessionId = sessionId;
|
||||||
this._activateFileBrowserSession?.(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
|
// 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).
|
// if this one resizes instead (the geometry work below then fits it).
|
||||||
this._reconcileKeyboardHold?.({ resize: false });
|
this._reconcileKeyboardHold?.({ resize: false });
|
||||||
@@ -10823,6 +10845,7 @@ class CodemanApp {
|
|||||||
this._flushedOffsets?.delete(sessionId);
|
this._flushedOffsets?.delete(sessionId);
|
||||||
this._flushedTexts?.delete(sessionId);
|
this._flushedTexts?.delete(sessionId);
|
||||||
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.discardComposerDraft?.(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/
|
// 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
|
// exited). Not a lost prompt — the target no longer exists. Only reached on
|
||||||
// real session removal, never on a tab switch.
|
// real session removal, never on a tab switch.
|
||||||
@@ -11104,6 +11127,9 @@ class CodemanApp {
|
|||||||
this._retireUrlSession();
|
this._retireUrlSession();
|
||||||
// Home is a choice to leave the grid too; it is remembered for Tiles.
|
// Home is a choice to leave the grid too; it is remembered for Tiles.
|
||||||
this.closeTileGrid?.({ keepStored: true, reselect: false });
|
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
|
// Deselect active session and show welcome screen
|
||||||
this.activeSessionId = null;
|
this.activeSessionId = null;
|
||||||
try { localStorage.removeItem('codeman-active-session'); } catch {}
|
try { localStorage.removeItem('codeman-active-session'); } catch {}
|
||||||
|
|||||||
@@ -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.":
|
"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 的全屏模式)仍像以前一样调整尺寸。',
|
'对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。',
|
||||||
'CJK Input': '中日韩输入',
|
'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': '扩展键盘栏',
|
'Extended Keyboard Bar': '扩展键盘栏',
|
||||||
'Gesture Control (beta)': '手势控制(测试版)',
|
'Gesture Control (beta)': '手势控制(测试版)',
|
||||||
'Wheel Scrolls Local History': '滚轮滚动本地历史',
|
'Wheel Scrolls Local History': '滚轮滚动本地历史',
|
||||||
|
|||||||
@@ -2065,6 +2065,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
|
<label class="switch switch-sm"><input type="checkbox" id="appSettingsCjkInput"><span class="slider"></span></label>
|
||||||
</div>
|
</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" data-search="extended keyboard bar tab esc arrows phone">
|
||||||
<div class="set-row-text">
|
<div class="set-row-text">
|
||||||
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
|
<span class="set-row-label">Extended Keyboard Bar <span class="set-tag">phone</span></span>
|
||||||
|
|||||||
+321
-13
@@ -7,6 +7,21 @@
|
|||||||
* While this textarea has focus, window.cjkActive = true blocks xterm's onData.
|
* While this textarea has focus, window.cjkActive = true blocks xterm's onData.
|
||||||
* Arrow keys and function keys are forwarded to PTY directly.
|
* 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 IME challenge
|
||||||
*
|
*
|
||||||
* Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use
|
* Android virtual keyboards (WeChat, Sogou, Gboard in Chinese mode) use
|
||||||
@@ -57,6 +72,27 @@ const CjkInput = (() => {
|
|||||||
let _dictationActive = false;
|
let _dictationActive = false;
|
||||||
let _dictationDecayTimer = null;
|
let _dictationDecayTimer = null;
|
||||||
let _printableKeydownAt = 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 _listeners = {};
|
||||||
|
|
||||||
const PHANTOM = '';
|
const PHANTOM = '';
|
||||||
@@ -160,6 +196,7 @@ const CjkInput = (() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function _resetToPhantom() {
|
function _resetToPhantom() {
|
||||||
|
_heldBase = '';
|
||||||
// Skip redundant writes: every programmatic value/selection mutation can
|
// Skip redundant writes: every programmatic value/selection mutation can
|
||||||
// desync an Android IME's input session (InputConnection) — after which
|
// desync an Android IME's input session (InputConnection) — after which
|
||||||
// the keyboard composes in its own UI but NO events ever reach the page.
|
// the keyboard composes in its own UI but NO events ever reach the page.
|
||||||
@@ -189,6 +226,13 @@ const CjkInput = (() => {
|
|||||||
_t('flush SKIP composing');
|
_t('flush SKIP composing');
|
||||||
return;
|
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);
|
const val = _strip(_textarea.value);
|
||||||
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
|
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
|
||||||
if (val) {
|
if (val) {
|
||||||
@@ -197,6 +241,133 @@ const CjkInput = (() => {
|
|||||||
_resetToPhantom();
|
_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 */
|
/** Cancel any pending debounced flush */
|
||||||
function _cancelDebouncedFlush() {
|
function _cancelDebouncedFlush() {
|
||||||
if (_flushTimer) {
|
if (_flushTimer) {
|
||||||
@@ -226,14 +397,16 @@ const CjkInput = (() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
init({ send }) {
|
init({ send, sendPrompt = null }) {
|
||||||
if (_initialized) this.destroy();
|
if (_initialized) this.destroy();
|
||||||
|
|
||||||
_send = send;
|
_send = send;
|
||||||
|
_sendPrompt = sendPrompt;
|
||||||
_composing = false;
|
_composing = false;
|
||||||
_printableKeydownAt = null;
|
_printableKeydownAt = null;
|
||||||
_flushTimer = null;
|
_flushTimer = null;
|
||||||
_textarea = document.getElementById('cjkInput');
|
_textarea = document.getElementById('cjkInput');
|
||||||
|
_holdApplied = false; // a new field has not had the mode applied
|
||||||
if (!_textarea) return this;
|
if (!_textarea) return this;
|
||||||
|
|
||||||
_resetToPhantom();
|
_resetToPhantom();
|
||||||
@@ -316,16 +489,14 @@ const CjkInput = (() => {
|
|||||||
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
|
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
|
||||||
_printableKeydownAt = null;
|
_printableKeydownAt = null;
|
||||||
if (e.key === 'Enter') {
|
if (e.key === 'Enter') {
|
||||||
e.preventDefault();
|
// Send-on-Enter: Shift+Enter (or an IME still composing) is a newline
|
||||||
_composing = false;
|
// in the field, never a send.
|
||||||
_cancelDebouncedFlush();
|
if (_hold && (e.shiftKey || e.isComposing || e.keyCode === 229)) {
|
||||||
const val = _strip(_textarea.value);
|
setTimeout(_autoGrow, 0);
|
||||||
if (val) {
|
return;
|
||||||
_send(val + '\r');
|
|
||||||
} else {
|
|
||||||
_send('\r');
|
|
||||||
}
|
}
|
||||||
_resetToPhantom();
|
e.preventDefault();
|
||||||
|
_submit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,10 +505,15 @@ const CjkInput = (() => {
|
|||||||
_composing = false;
|
_composing = false;
|
||||||
_cancelDebouncedFlush();
|
_cancelDebouncedFlush();
|
||||||
_resetToPhantom();
|
_resetToPhantom();
|
||||||
|
if (_hold) _autoGrow();
|
||||||
return;
|
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();
|
e.preventDefault();
|
||||||
_send(CTRL_KEYS[e.key]);
|
_send(CTRL_KEYS[e.key]);
|
||||||
return;
|
return;
|
||||||
@@ -405,6 +581,11 @@ const CjkInput = (() => {
|
|||||||
_composing = false;
|
_composing = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (_hold) {
|
||||||
|
_holdInput(e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// ── Backspace / delete detection ──
|
// ── Backspace / delete detection ──
|
||||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||||
if (_composing) return;
|
if (_composing) return;
|
||||||
@@ -464,9 +645,24 @@ const CjkInput = (() => {
|
|||||||
* can't flush into the wrong session). Restores the phantom so backspace
|
* can't flush into the wrong session). Restores the phantom so backspace
|
||||||
* forwarding keeps working — unlike a raw `textarea.value = ''`.
|
* forwarding keeps working — unlike a raw `textarea.value = ''`.
|
||||||
*/
|
*/
|
||||||
clear() {
|
clear({ discard = false } = {}) {
|
||||||
if (!_initialized || !_textarea) return;
|
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();
|
_cancelDebouncedFlush();
|
||||||
clearTimeout(_compositionFlushTimer);
|
clearTimeout(_compositionFlushTimer);
|
||||||
_compositionFlushTimer = null;
|
_compositionFlushTimer = null;
|
||||||
@@ -475,6 +671,118 @@ const CjkInput = (() => {
|
|||||||
_resetToPhantom();
|
_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). */
|
/** Diagnostic: recent IME event trace (ring buffer). */
|
||||||
getTrace() {
|
getTrace() {
|
||||||
return _trace.slice();
|
return _trace.slice();
|
||||||
|
|||||||
@@ -435,27 +435,55 @@ const KeyboardHandler = {
|
|||||||
// BEHIND the keyboard with its own search box out of sight.
|
// BEHIND the keyboard with its own search box out of sight.
|
||||||
const caseSheet = document.querySelector('.mobile-case-picker.active .mobile-case-picker-sheet');
|
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) {
|
if (isSmallMedium) {
|
||||||
// Phones/small tablets: toolbar and accessory bar are position:fixed
|
// Phones/small tablets: toolbar and accessory bar are position:fixed
|
||||||
// via CSS. Use translateY to lift them above the keyboard.
|
// via CSS. Use translateY to lift them above the keyboard.
|
||||||
const toolbar = document.querySelector('.toolbar');
|
const toolbar = document.querySelector('.toolbar');
|
||||||
const main = document.querySelector('.main');
|
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) {
|
if (toolbar) {
|
||||||
toolbar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
toolbar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
|
||||||
}
|
}
|
||||||
if (accessoryBar) {
|
if (accessoryBar) {
|
||||||
accessoryBar.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
accessoryBar.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
|
||||||
}
|
}
|
||||||
if (caseSheet) {
|
if (caseSheet) {
|
||||||
caseSheet.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
caseSheet.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
|
||||||
}
|
}
|
||||||
if (main && keyboardHeight > 0) {
|
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`;
|
main.style.paddingBottom = `${84 + cjkInputHeight}px`;
|
||||||
}
|
}
|
||||||
} else if (keyboardHeight > 0) {
|
} else if (keyboardHeight > 0) {
|
||||||
@@ -472,11 +500,8 @@ const KeyboardHandler = {
|
|||||||
// CJK textarea positioning (always position:fixed on touch devices).
|
// CJK textarea positioning (always position:fixed on touch devices).
|
||||||
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
|
if (cjkInput?.classList.contains('cjk-input-visible') && keyboardHeight > 0) {
|
||||||
if (isSmallMedium) {
|
if (isSmallMedium) {
|
||||||
// Phones: use translateY like toolbar/accessory bar.
|
// Phones: use translateY like toolbar/accessory bar (it sits inside .app too).
|
||||||
const layoutHeight = window.innerHeight;
|
cjkInput.style.transform = insideLift > 0 ? `translateY(${-insideLift}px)` : '';
|
||||||
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
|
|
||||||
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
|
|
||||||
cjkInput.style.transform = keyboardOffset > 0 ? `translateY(${-keyboardOffset}px)` : '';
|
|
||||||
cjkInput.style.bottom = '';
|
cjkInput.style.bottom = '';
|
||||||
} else {
|
} else {
|
||||||
// iPad: direct bottom = keyboard + accessory bar height.
|
// 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
|
// keyboard was still up must still have its inline offset cleared, or the
|
||||||
// next open slides in already displaced.
|
// next open slides in already displaced.
|
||||||
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
|
const caseSheet = document.querySelector('.mobile-case-picker-sheet');
|
||||||
|
const appEl = document.querySelector('.app');
|
||||||
|
|
||||||
|
if (appEl) {
|
||||||
|
appEl.style.transform = '';
|
||||||
|
}
|
||||||
if (toolbar) {
|
if (toolbar) {
|
||||||
toolbar.style.transform = '';
|
toolbar.style.transform = '';
|
||||||
}
|
}
|
||||||
@@ -729,6 +758,11 @@ const KeyboardHandler = {
|
|||||||
if (el.closest('.xterm') || el.closest('.terminal-container')) {
|
if (el.closest('.xterm') || el.closest('.terminal-container')) {
|
||||||
return false;
|
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();
|
const tagName = el.tagName?.toLowerCase();
|
||||||
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
|
// Exclude type=range, type=checkbox, type=radio (don't trigger keyboard)
|
||||||
|
|||||||
@@ -2082,6 +2082,16 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
|
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
|
||||||
sendEnterKey() {
|
sendEnterKey() {
|
||||||
if (!this.activeSessionId) return;
|
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;
|
const coreService = this.terminal?._core?.coreService;
|
||||||
if (coreService && typeof coreService.triggerDataEvent === 'function') {
|
if (coreService && typeof coreService.triggerDataEvent === 'function') {
|
||||||
coreService.triggerDataEvent('\r', true);
|
coreService.triggerDataEvent('\r', true);
|
||||||
|
|||||||
@@ -649,6 +649,8 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
document.getElementById('appSettingsTerminalWheelLocal').checked =
|
document.getElementById('appSettingsTerminalWheelLocal').checked =
|
||||||
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
|
settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false;
|
||||||
document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? 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('appSettingsExtendedKeyboardBar').checked = settings.extendedKeyboardBar ?? false;
|
||||||
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
|
document.getElementById('appSettingsTabTwoRows').checked = settings.tabTwoRows ?? defaults.tabTwoRows ?? false;
|
||||||
document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings);
|
document.getElementById('appSettingsShowTabCliLogos').checked = this.tabCliLogosEnabled(settings);
|
||||||
@@ -3195,6 +3197,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
),
|
),
|
||||||
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
|
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
|
||||||
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
|
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
|
||||||
|
cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,
|
||||||
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
|
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
|
||||||
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
|
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
|
||||||
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
|
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
|
||||||
@@ -3440,6 +3443,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
|
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
|
||||||
keyboardHoldsRows: _khr,
|
keyboardHoldsRows: _khr,
|
||||||
cjkInputEnabled: _cjk,
|
cjkInputEnabled: _cjk,
|
||||||
|
cjkInputHoldUntilEnter: _cjkHold,
|
||||||
extendedKeyboardBar: _ekb,
|
extendedKeyboardBar: _ekb,
|
||||||
skin: _skin,
|
skin: _skin,
|
||||||
language: _language,
|
language: _language,
|
||||||
@@ -4478,6 +4482,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
sessionListLayout: 'header',
|
sessionListLayout: 'header',
|
||||||
sessionSidebarFontSize: 12,
|
sessionSidebarFontSize: 12,
|
||||||
cjkInputEnabled: false,
|
cjkInputEnabled: false,
|
||||||
|
cjkInputHoldUntilEnter: false,
|
||||||
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
|
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
|
||||||
webglRendererEnabled: false, // mobile always uses the DOM renderer
|
webglRendererEnabled: false, // mobile always uses the DOM renderer
|
||||||
skin: 'daylight-blue',
|
skin: 'daylight-blue',
|
||||||
@@ -5206,7 +5211,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
|
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
|
||||||
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
|
||||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
'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',
|
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
|
||||||
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
|
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
|
||||||
'language',
|
'language',
|
||||||
|
|||||||
@@ -14199,6 +14199,12 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
|||||||
resize: none;
|
resize: none;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
box-sizing: border-box;
|
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 {
|
#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);
|
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 {
|
body.touch-device.cjk-input-visible .main {
|
||||||
padding-bottom: calc(84px + var(--safe-area-bottom));
|
padding-bottom: calc(84px + var(--safe-area-bottom));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1083,6 +1083,10 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
send: (text) => {
|
send: (text) => {
|
||||||
this._handleCjkInput(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
|
// selectSession() ends with scrollToLastNonEmptyLine(), that made
|
||||||
// the keyboard unreachable after every tab switch.
|
// the keyboard unreachable after every tab switch.
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
this._blurMobileTerminalInput();
|
if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();
|
||||||
}
|
}
|
||||||
// Hold still and this press becomes a text selection. Cancelled by any
|
// 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.
|
// 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
|
// 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
|
// armed modifier could neither fire NOR be spent: it survived until a
|
||||||
// session switch and then turned an innocent keystroke into a control byte.
|
// 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
|
// This is the module's single choke point to the PTY in live mode, so applying
|
||||||
// covers typed characters, IME flushes, Enter, backspace and arrows at once.
|
// 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,
|
// Same policy as the onData hook: the next single character is modified,
|
||||||
// anything longer merely spends the modifier.
|
// anything longer merely spends the modifier.
|
||||||
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
||||||
@@ -4564,6 +4570,49 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
this._sendInputAsync(this.activeSessionId, text);
|
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).
|
* Re-assert a history anchor captured before a terminal write (#358).
|
||||||
*
|
*
|
||||||
@@ -5087,7 +5136,9 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
clearTerminalInput() {
|
clearTerminalInput() {
|
||||||
if (!this.activeSessionId) return;
|
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
|
// 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,
|
// (no local-echo overlay there), so kill the line in that pane's session,
|
||||||
// never in the parked main pane's.
|
// never in the parked main pane's.
|
||||||
@@ -5650,6 +5701,19 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
return 'content';
|
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() {
|
_blurMobileTerminalInput() {
|
||||||
const active = document.activeElement;
|
const active = document.activeElement;
|
||||||
if (
|
if (
|
||||||
@@ -5848,6 +5912,9 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
) {
|
) {
|
||||||
// No focus change: a 'content' tap was already blurred by touchstart, and
|
// 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.
|
// 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';
|
return 'link';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2651,6 +2651,20 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
// Aborts any in-flight normal select at its next _isStaleSelect check.
|
// Aborts any in-flight normal select at its next _isStaleSelect check.
|
||||||
const selectGen = ++this._selectGeneration;
|
const selectGen = ++this._selectGeneration;
|
||||||
this._hideWebviewLayer?.();
|
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;
|
this.activeSessionId = sessionId;
|
||||||
grid.focusedId = sessionId;
|
grid.focusedId = sessionId;
|
||||||
// Moving focus off a zoomed tile restores the grid, as selecting another
|
// Moving focus off a zoomed tile restores the grid, as selecting another
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
// test/cjk-hold-per-device-setting.test.ts
|
||||||
|
// Port: none (static analysis + vm, runs in CI, no browser/server).
|
||||||
|
//
|
||||||
|
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
|
||||||
|
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
|
||||||
|
// merge policy, stripped out of the object saveAppSettings() PUTs
|
||||||
|
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
|
||||||
|
// never declared in the schema. Plus the pieces around the mode: a held draft
|
||||||
|
// surviving a reload of the same session, the field staying one line tall with
|
||||||
|
// the keyboard down, and zh-CN strings for its placeholders.
|
||||||
|
import { describe, it, expect, vi } from 'vitest';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
|
||||||
|
const HERE = fileURLToPath(new URL('.', import.meta.url));
|
||||||
|
const PUBLIC = join(HERE, '../src/web/public');
|
||||||
|
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
|
||||||
|
|
||||||
|
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
|
||||||
|
const settingsUi = read('settings-ui.js');
|
||||||
|
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
|
||||||
|
|
||||||
|
it('is in the client-side displayKeys merge policy', () => {
|
||||||
|
const start = settingsUi.indexOf('const displayKeys = new Set([');
|
||||||
|
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
|
||||||
|
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
|
||||||
|
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is never declared in the .strict() SettingsUpdateSchema', () => {
|
||||||
|
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
|
||||||
|
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is loaded into and saved from its App Settings switch', () => {
|
||||||
|
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
|
||||||
|
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
|
||||||
|
expect(settingsUi).toContain(
|
||||||
|
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a held draft survives a reload of the same session', () => {
|
||||||
|
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
|
||||||
|
// activeSessionId before calling it on a same-session forceReload (tapping the
|
||||||
|
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
|
||||||
|
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
|
||||||
|
const clear = vi.fn();
|
||||||
|
const stashDraft = vi.fn();
|
||||||
|
const context = vm.createContext({
|
||||||
|
console,
|
||||||
|
setTimeout,
|
||||||
|
clearTimeout,
|
||||||
|
setInterval: vi.fn(),
|
||||||
|
clearInterval: vi.fn(),
|
||||||
|
requestAnimationFrame: vi.fn(),
|
||||||
|
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||||
|
WebSocket: { OPEN: 1 },
|
||||||
|
fetch: vi.fn(),
|
||||||
|
URLSearchParams,
|
||||||
|
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
|
||||||
|
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||||
|
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||||
|
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
|
||||||
|
CjkInput: { holdUntilEnter: hold, clear, 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<string, unknown> & {
|
||||||
|
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
|
||||||
|
};
|
||||||
|
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 Object.assign(clear, { stashDraft });
|
||||||
|
}
|
||||||
|
|
||||||
|
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
|
||||||
|
expect(cleanup(true, true)).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still clears on a real switch', () => {
|
||||||
|
expect(cleanup(true, false)).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
|
||||||
|
expect(cleanup(false, true)).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('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', () => {
|
||||||
|
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
|
||||||
|
// that call as the line right after the activeSessionId assignment.
|
||||||
|
expect(read('app.js')).toContain(
|
||||||
|
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(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 does not stash again for a tile closed from this tab', () => {
|
||||||
|
// removeSession discards the closed session's draft first; a stash after
|
||||||
|
// that would keep it in the map until the page reloads.
|
||||||
|
expect(read('tile-grid.js')).toContain(
|
||||||
|
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
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('going Home stashes the draft of the session it leaves', () => {
|
||||||
|
const appJs = read('app.js');
|
||||||
|
const start = appJs.indexOf(' goHome() {');
|
||||||
|
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
|
||||||
|
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
|
||||||
|
});
|
||||||
|
|
||||||
|
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(
|
||||||
|
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
|
||||||
|
);
|
||||||
|
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Send on Enter field layout and strings', () => {
|
||||||
|
it('keeps the field one line tall while the keyboard is down', () => {
|
||||||
|
// .main reserves a fixed 84px there; a grown field would cover the terminal.
|
||||||
|
expect(read('styles.css')).toMatch(
|
||||||
|
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('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');
|
||||||
|
for (const placeholder of [
|
||||||
|
'CJK input (Enter = send, Esc = clear)',
|
||||||
|
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
|
||||||
|
]) {
|
||||||
|
expect(cjk).toContain(`'${placeholder}'`);
|
||||||
|
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js,
|
||||||
|
* setting cjkInputHoldUntilEnter): typed text stays in the field until Enter,
|
||||||
|
* so a phone user can scroll the terminal and edit an answer before sending.
|
||||||
|
*
|
||||||
|
* Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also
|
||||||
|
* carries the attributes and style the mode touches.
|
||||||
|
*/
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
const PHANTOM = '';
|
||||||
|
|
||||||
|
function makeTextarea() {
|
||||||
|
const listeners = new Map<string, Array<(e?: unknown) => void>>();
|
||||||
|
const attrs: Record<string, string> = {};
|
||||||
|
return {
|
||||||
|
value: '',
|
||||||
|
placeholder: '',
|
||||||
|
style: { height: '' } as Record<string, string>,
|
||||||
|
scrollHeight: 34,
|
||||||
|
// border-box with a 1px border: offsetHeight - clientHeight is the borders.
|
||||||
|
offsetHeight: 36,
|
||||||
|
clientHeight: 34,
|
||||||
|
attrs,
|
||||||
|
blur: vi.fn(),
|
||||||
|
focus: vi.fn(),
|
||||||
|
getClientRects: (): unknown[] => [{}],
|
||||||
|
classList: { contains: (c: string) => c === 'cjk-input-visible' },
|
||||||
|
setSelectionRange: () => {},
|
||||||
|
setAttribute: vi.fn((k: string, v: string) => {
|
||||||
|
attrs[k] = v;
|
||||||
|
}),
|
||||||
|
addEventListener: (ev: string, fn: (e?: unknown) => void) => {
|
||||||
|
listeners.set(ev, [...(listeners.get(ev) ?? []), fn]);
|
||||||
|
},
|
||||||
|
removeEventListener: (ev: string, fn: (e?: unknown) => void) => {
|
||||||
|
listeners.set(
|
||||||
|
ev,
|
||||||
|
(listeners.get(ev) ?? []).filter((f) => f !== fn)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
fire(ev: string, arg: Record<string, unknown> = {}) {
|
||||||
|
const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg };
|
||||||
|
for (const fn of listeners.get(ev) ?? []) fn(base);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function load({
|
||||||
|
hold = true,
|
||||||
|
promptResult = true,
|
||||||
|
touch = true,
|
||||||
|
translate,
|
||||||
|
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
|
||||||
|
const textarea = makeTextarea();
|
||||||
|
const sent: string[] = [];
|
||||||
|
const prompts: string[] = [];
|
||||||
|
const layout = vi.fn();
|
||||||
|
// The shell bar's one-shot Ctrl, reduced to its armed flag.
|
||||||
|
const bar = {
|
||||||
|
armed: false,
|
||||||
|
isCtrlArmed() {
|
||||||
|
return this.armed;
|
||||||
|
},
|
||||||
|
clearCtrl() {
|
||||||
|
this.armed = false;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const context = vm.createContext({
|
||||||
|
window: translate ? { CodemanI18n: { t: translate } } : {},
|
||||||
|
document: {
|
||||||
|
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
|
||||||
|
activeElement: null,
|
||||||
|
body: { classList: { contains: (c: string) => touch && c === 'touch-device' } },
|
||||||
|
},
|
||||||
|
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
|
||||||
|
KeyboardHandler: { updateLayoutForKeyboard: layout },
|
||||||
|
KeyboardAccessoryBar: bar,
|
||||||
|
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
|
||||||
|
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
|
||||||
|
performance: { now: () => performance.now() },
|
||||||
|
console,
|
||||||
|
});
|
||||||
|
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
|
||||||
|
vm.runInContext(src, context, { filename: 'input-cjk.js' });
|
||||||
|
const CjkInput = vm.runInContext('CjkInput', context);
|
||||||
|
CjkInput.init({
|
||||||
|
send: (t: string) => sent.push(t),
|
||||||
|
sendPrompt: (t: string) => {
|
||||||
|
prompts.push(t);
|
||||||
|
return promptResult;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
CjkInput.setHoldUntilEnter(hold);
|
||||||
|
textarea.fire('focus');
|
||||||
|
return { CjkInput, textarea, sent, prompts, layout, bar };
|
||||||
|
}
|
||||||
|
|
||||||
|
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
|
||||||
|
textarea.value = PHANTOM + text;
|
||||||
|
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
|
||||||
|
textarea.value = valueAfter;
|
||||||
|
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
|
||||||
|
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
|
||||||
|
|
||||||
|
describe('CJK input: Send on Enter', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps typed text in the field instead of streaming it', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'use Postgres');
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'use Postgres');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps text after a physical keystroke (no zero-latency flush)', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false });
|
||||||
|
type(textarea, 'a');
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps text across a composition cycle and autocorrect rewrites', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
textarea.fire('compositionstart');
|
||||||
|
textarea.value = PHANTOM + 'teh';
|
||||||
|
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
|
||||||
|
textarea.fire('compositionend');
|
||||||
|
textarea.value = PHANTOM + 'the';
|
||||||
|
textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' });
|
||||||
|
vi.advanceTimersByTime(5000);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'the');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends one line 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(prompts).toEqual(['yes, use Postgres']);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
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);
|
||||||
|
expect(prompts).toEqual(['yes']);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'yes');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
|
||||||
|
const { textarea, sent, prompts } = load();
|
||||||
|
type(textarea, 'line one\nline two');
|
||||||
|
enter(textarea);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(prompts).toEqual(['line one\nline two']);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
|
||||||
|
const { textarea, prompts } = load({ promptResult: false });
|
||||||
|
type(textarea, 'line one\nline two');
|
||||||
|
enter(textarea);
|
||||||
|
expect(prompts).toHaveLength(1);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats Shift+Enter as a newline, never a send', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'first');
|
||||||
|
const preventDefault = vi.fn();
|
||||||
|
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault });
|
||||||
|
vi.advanceTimersByTime(10);
|
||||||
|
expect(preventDefault).not.toHaveBeenCalled();
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends a bare Enter when the field is empty (accepting a default answer)', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
|
||||||
|
expect(sent).toEqual(['\r']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still forwards Backspace on an empty field to the PTY', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
textarea.fire('keydown', { key: 'Backspace', keyCode: 8 });
|
||||||
|
expect(sent).toEqual(['\x7f']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not send Backspace when deleting the last held character', () => {
|
||||||
|
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
|
||||||
|
// a stray DEL would eat its last character.
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'a');
|
||||||
|
type(textarea, 'ab');
|
||||||
|
backspace(textarea, PHANTOM + 'a');
|
||||||
|
backspace(textarea, PHANTOM);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'a');
|
||||||
|
backspace(textarea, PHANTOM);
|
||||||
|
backspace(textarea, '');
|
||||||
|
expect(sent).toEqual(['\x7f']);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not send Backspace for select-all + delete of held text', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'abc');
|
||||||
|
backspace(textarea, '');
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'a');
|
||||||
|
backspace(textarea, PHANTOM);
|
||||||
|
vi.advanceTimersByTime(2000);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'abc');
|
||||||
|
backspace(textarea, 'abc');
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
|
||||||
|
// _handleCjkInput turns the single character into the control byte.
|
||||||
|
const { textarea, sent, bar } = load();
|
||||||
|
bar.armed = true;
|
||||||
|
type(textarea, 'c');
|
||||||
|
expect(sent).toEqual(['c']);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
|
||||||
|
const { textarea, sent, bar } = load();
|
||||||
|
type(textarea, 'ab');
|
||||||
|
bar.armed = true;
|
||||||
|
type(textarea, 'abc');
|
||||||
|
expect(sent).toEqual(['c']);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'ab');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
|
||||||
|
const { textarea, sent, bar } = load();
|
||||||
|
bar.armed = true;
|
||||||
|
textarea.fire('compositionstart');
|
||||||
|
textarea.value = PHANTOM + 'c';
|
||||||
|
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
|
||||||
|
textarea.fire('compositionend');
|
||||||
|
vi.advanceTimersByTime(10);
|
||||||
|
expect(sent).toEqual(['c']);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
|
||||||
|
const { textarea, sent, bar } = load();
|
||||||
|
bar.armed = true;
|
||||||
|
type(textarea, 'hello');
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'hello');
|
||||||
|
expect(bar.armed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Escape clears the held text without sending', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'never mind');
|
||||||
|
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turning the mode off drops the held draft and the stashes, so live mode sends only new keys', () => {
|
||||||
|
const { CjkInput, textarea, sent } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'rm -rf build\nsecond line');
|
||||||
|
CjkInput.stashDraft('session-b');
|
||||||
|
CjkInput.setHoldUntilEnter(false);
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
type(textarea, 'x');
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(sent).toEqual(['x']);
|
||||||
|
CjkInput.setHoldUntilEnter(true);
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stays one line on a desktop, where growing would resize the PTY', () => {
|
||||||
|
const { textarea, layout } = load({ touch: false });
|
||||||
|
layout.mockClear();
|
||||||
|
textarea.scrollHeight = 60;
|
||||||
|
type(textarea, 'a\nb\nc');
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(textarea.style.height).toBe('');
|
||||||
|
expect(layout).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('translates its placeholder itself, since i18n.js skips textareas', () => {
|
||||||
|
const { CjkInput, textarea } = load({ translate: (s) => `zh:${s}` });
|
||||||
|
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||||
|
CjkInput.setHoldUntilEnter(false);
|
||||||
|
expect(textarea.placeholder).toBe('zh:CJK input (Enter = send, Esc = clear)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turns autocorrect on in the mode and back off without it', () => {
|
||||||
|
const { CjkInput, textarea } = load();
|
||||||
|
expect(textarea.attrs.autocorrect).toBe('on');
|
||||||
|
expect(textarea.attrs.spellcheck).toBe('true');
|
||||||
|
CjkInput.setHoldUntilEnter(false);
|
||||||
|
expect(textarea.attrs.autocorrect).toBe('off');
|
||||||
|
expect(textarea.attrs.spellcheck).toBe('false');
|
||||||
|
expect(CjkInput.holdUntilEnter).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grows the field with its text and re-runs the keyboard layout', () => {
|
||||||
|
const { textarea, layout } = load();
|
||||||
|
layout.mockClear();
|
||||||
|
textarea.scrollHeight = 60;
|
||||||
|
type(textarea, 'a\nb\nc');
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
// 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();
|
||||||
|
const placeholder = textarea.placeholder;
|
||||||
|
let writes = 0;
|
||||||
|
Object.defineProperty(textarea, 'placeholder', {
|
||||||
|
get: () => placeholder,
|
||||||
|
set: () => {
|
||||||
|
writes++;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
CjkInput.setHoldUntilEnter(true);
|
||||||
|
expect(textarea.setAttribute).not.toHaveBeenCalled();
|
||||||
|
expect(writes).toBe(0);
|
||||||
|
CjkInput.setHoldUntilEnter(false);
|
||||||
|
expect(textarea.setAttribute).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('follows a live language switch with the mode unchanged', () => {
|
||||||
|
// App Settings runs applyLocalization(), then _updateCjkInputState(), which
|
||||||
|
// calls setHoldUntilEnter() with the same mode.
|
||||||
|
let lang = 'en';
|
||||||
|
const { CjkInput, textarea } = load({ translate: (s) => (lang === 'zh' ? `zh:${s}` : s) });
|
||||||
|
expect(textarea.placeholder).toBe('Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||||
|
textarea.setAttribute.mockClear();
|
||||||
|
lang = 'zh';
|
||||||
|
CjkInput.setHoldUntilEnter(true);
|
||||||
|
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||||
|
expect(textarea.setAttribute).not.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: the stash is consumed, so once the user empties the
|
||||||
|
// field (Esc here) a second visit does not bring it back. A draft still in
|
||||||
|
// the field when the session is left is stashed again by clear().
|
||||||
|
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
|
||||||
|
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('clear() stashes a held draft for the session it was typed for, with no stash call', () => {
|
||||||
|
// goHome(), _replaceTileGrid and _onTileAdoptedElsewhere drop the active
|
||||||
|
// session before the next cleanup, which then has no session to stash for.
|
||||||
|
const { CjkInput, textarea, sent } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'typed for a');
|
||||||
|
CjkInput.clear();
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'typed for a');
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear({ discard }) throws the draft away: a same-tab restore and a switch back stay empty', () => {
|
||||||
|
// The keyboard bar's clear-line key (terminal-ui.js clearTerminalInput).
|
||||||
|
const { CjkInput, textarea } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'thrown away');
|
||||||
|
CjkInput.clear({ discard: true });
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
expect(CjkInput.draftOwner).toBe('session-a');
|
||||||
|
// Tapping the session's own tab: the field is kept, then restoreDraft runs.
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
// Switching away and back.
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear({ discard }) also drops an older stash of the same session', () => {
|
||||||
|
const { CjkInput, textarea } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'old');
|
||||||
|
CjkInput.stashDraft('session-a');
|
||||||
|
CjkInput.clear({ discard: true });
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a removed session loses its field text: discardDraft drops the owner', () => {
|
||||||
|
const { CjkInput, textarea } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'for a closed tile');
|
||||||
|
CjkInput.discardDraft('session-a');
|
||||||
|
expect(CjkInput.draftOwner).toBe(null);
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a field still holding text keeps its owner when another session is shown', () => {
|
||||||
|
const { CjkInput, textarea } = load();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'still for a');
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
expect(CjkInput.draftOwner).toBe('session-a');
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'still for a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Ctrl shortcuts stay in the field while it holds a draft', () => {
|
||||||
|
// Ctrl+Z is undo, Ctrl+A select all, Ctrl+C copy: never a control byte to
|
||||||
|
// the CLI while there is a draft to act on.
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
type(textarea, 'draft');
|
||||||
|
for (const key of ['z', 'a', 'c']) {
|
||||||
|
const preventDefault = vi.fn();
|
||||||
|
textarea.fire('keydown', { key, keyCode: key.toUpperCase().charCodeAt(0), ctrlKey: true, preventDefault });
|
||||||
|
expect(preventDefault).not.toHaveBeenCalled();
|
||||||
|
}
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Ctrl shortcuts reach the CLI from an empty field', () => {
|
||||||
|
const { textarea, sent } = load();
|
||||||
|
const preventDefault = vi.fn();
|
||||||
|
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true, preventDefault });
|
||||||
|
expect(preventDefault).toHaveBeenCalled();
|
||||||
|
expect(sent).toEqual(['\x03']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('live mode keeps sending Ctrl shortcuts with text in the field', () => {
|
||||||
|
const { textarea, sent } = load({ hold: false });
|
||||||
|
textarea.value = PHANTOM + 'x';
|
||||||
|
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true });
|
||||||
|
expect(sent).toEqual(['\x03']);
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(sent).toEqual(['hi']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
// Port: none (pure logic in a vm context — no browser, no server).
|
||||||
|
//
|
||||||
|
// KeyboardHandler scrolls a newly focused text field into view (scrollInputIntoView,
|
||||||
|
// `scrollIntoView({ block: 'center' })`) once the keyboard is up. The pinned CJK /
|
||||||
|
// Send on Enter field (#cjkInput) is position:fixed and already lifted above the
|
||||||
|
// keyboard by updateLayoutForKeyboard(), so scrolling it into view only centred it in
|
||||||
|
// its scrollable ancestors and pushed the terminal off screen. It must be skipped,
|
||||||
|
// like xterm's own inputs, while ordinary inputs keep the behaviour.
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/mobile-handlers.js'), 'utf8');
|
||||||
|
|
||||||
|
function loadHandler() {
|
||||||
|
const context = vm.createContext({
|
||||||
|
console,
|
||||||
|
navigator: { userAgent: 'test', maxTouchPoints: 1 },
|
||||||
|
window: { addEventListener: () => {}, matchMedia: () => ({ matches: false }), scrollTo: () => {} },
|
||||||
|
document: {
|
||||||
|
body: { classList: { add: () => {}, remove: () => {} } },
|
||||||
|
addEventListener: () => {},
|
||||||
|
getElementById: () => null,
|
||||||
|
querySelector: () => null,
|
||||||
|
},
|
||||||
|
setTimeout: () => 1,
|
||||||
|
clearTimeout: () => {},
|
||||||
|
});
|
||||||
|
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
|
||||||
|
return (context as { __KH: any }).__KH;
|
||||||
|
}
|
||||||
|
|
||||||
|
function element(tagName: string, { id = '', inside = '' }: { id?: string; inside?: string } = {}) {
|
||||||
|
return { tagName, id, type: '', isContentEditable: false, closest: (sel: string) => (sel === inside ? {} : null) };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('KeyboardHandler.isInputElement', () => {
|
||||||
|
it('skips the pinned CJK field, which the keyboard layout positions itself', () => {
|
||||||
|
expect(loadHandler().isInputElement(element('TEXTAREA', { id: 'cjkInput' }))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still skips xterm inputs and still scrolls ordinary fields into view', () => {
|
||||||
|
const kh = loadHandler();
|
||||||
|
expect(kh.isInputElement(element('TEXTAREA', { inside: '.xterm' }))).toBe(false);
|
||||||
|
expect(kh.isInputElement(element('TEXTAREA', { id: 'someOtherField' }))).toBe(true);
|
||||||
|
expect(kh.isInputElement(element('INPUT'))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function loadLayout({
|
||||||
|
focused = 'cjkInput',
|
||||||
|
offsetTop,
|
||||||
|
height = 458,
|
||||||
|
width = 390,
|
||||||
|
innerHeight = 744,
|
||||||
|
clientHeight = 744,
|
||||||
|
}: {
|
||||||
|
focused?: string;
|
||||||
|
offsetTop: number;
|
||||||
|
height?: number;
|
||||||
|
width?: number;
|
||||||
|
innerHeight?: number;
|
||||||
|
clientHeight?: number;
|
||||||
|
}) {
|
||||||
|
const el = (offsetHeight = 36) => ({
|
||||||
|
style: {} as Record<string, string>,
|
||||||
|
offsetHeight,
|
||||||
|
classList: { contains: () => true },
|
||||||
|
});
|
||||||
|
// .app is sized to the visual viewport (--app-height), which is what its fixed
|
||||||
|
// children are placed against once it carries a transform.
|
||||||
|
const nodes: Record<string, any> = {
|
||||||
|
'.app': el(height),
|
||||||
|
'.toolbar': el(),
|
||||||
|
'.main': el(),
|
||||||
|
'.keyboard-accessory-bar': el(),
|
||||||
|
'.mobile-case-picker.active .mobile-case-picker-sheet': el(300),
|
||||||
|
};
|
||||||
|
const cjk = { ...el(), id: 'cjkInput' };
|
||||||
|
const context = vm.createContext({
|
||||||
|
console,
|
||||||
|
navigator: { userAgent: 'test', maxTouchPoints: 1 },
|
||||||
|
window: {
|
||||||
|
addEventListener: () => {},
|
||||||
|
matchMedia: () => ({ matches: false }),
|
||||||
|
scrollTo: () => {},
|
||||||
|
innerHeight,
|
||||||
|
innerWidth: width, // MobileDetection (defined in the module) reads this
|
||||||
|
visualViewport: { offsetTop, height },
|
||||||
|
},
|
||||||
|
document: {
|
||||||
|
body: { classList: { add: () => {}, remove: () => {} } },
|
||||||
|
documentElement: { clientHeight },
|
||||||
|
addEventListener: () => {},
|
||||||
|
activeElement: focused === 'cjkInput' ? cjk : { id: focused },
|
||||||
|
getElementById: (id: string) => (id === 'cjkInput' ? cjk : null),
|
||||||
|
querySelector: (sel: string) => nodes[sel] || null,
|
||||||
|
},
|
||||||
|
setTimeout: () => 1,
|
||||||
|
clearTimeout: () => {},
|
||||||
|
});
|
||||||
|
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
|
||||||
|
const kh = (context as { __KH: any }).__KH;
|
||||||
|
kh.keyboardVisible = true;
|
||||||
|
kh.initialViewportHeight = 744;
|
||||||
|
return { kh, nodes, cjk };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('KeyboardHandler follows the visual-viewport pan on phones', () => {
|
||||||
|
it('moves the app down by the pan and lifts nothing more (measured Android case)', () => {
|
||||||
|
const { kh, nodes, cjk } = loadLayout({ offsetTop: 285 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
|
||||||
|
// .app bottom = 285 + 458 = 743, visual bottom = 743: the bars already sit on it.
|
||||||
|
expect(nodes['.toolbar'].style.transform).toBe('');
|
||||||
|
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
|
||||||
|
expect(cjk.style.transform).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not lift the bars twice on a partial pan', () => {
|
||||||
|
// Mid-animation: offsetTop 100 in a 744 layout. Lifting by the layout gap (186px)
|
||||||
|
// inside the shifted .app would float the bars 186px above the keyboard.
|
||||||
|
const { kh, nodes, cjk } = loadLayout({ offsetTop: 100 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('translateY(100px)');
|
||||||
|
expect(nodes['.toolbar'].style.transform).toBe('');
|
||||||
|
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
|
||||||
|
expect(cjk.style.transform).toBe('');
|
||||||
|
// The open case sheet is inside .app too (index.html #mobileCasePickerModal):
|
||||||
|
// the layout gap on top of the shift floated it 186px above the keyboard.
|
||||||
|
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the old lift when there is no pan', () => {
|
||||||
|
const { kh, nodes } = loadLayout({ offsetTop: 0 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('');
|
||||||
|
expect(nodes['.toolbar'].style.transform).toBe('translateY(-286px)');
|
||||||
|
// Without a pan insideLift is the layout gap, so the case sheet keeps its lift
|
||||||
|
// (test/mobile-case-sheet-keyboard-lift.test.ts).
|
||||||
|
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('translateY(-286px)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('follows a pan whatever has focus, so a focus change cannot drop the shift', () => {
|
||||||
|
const { kh, nodes } = loadLayout({ focused: 'someOtherField', offsetTop: 285 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never shifts the app outside the phone layout (tablet landscape)', () => {
|
||||||
|
const { kh, nodes } = loadLayout({ offsetTop: 285, width: 1024 });
|
||||||
|
nodes['.app'].style.transform = 'translateY(285px)'; // left over from portrait
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lifts the bars when iOS reports innerHeight as the shrunk visual height', () => {
|
||||||
|
// Measured on an iPhone, first keyboard open: innerHeight 323 = visual height,
|
||||||
|
// documentElement.clientHeight 640. Lifting by innerHeight - visual bottom gave 0.
|
||||||
|
const { kh, nodes, cjk } = loadLayout({ offsetTop: 0, height: 323, innerHeight: 323, clientHeight: 640 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
expect(nodes['.toolbar'].style.transform).toBe('translateY(-317px)');
|
||||||
|
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('translateY(-317px)');
|
||||||
|
expect(cjk.style.transform).toBe('translateY(-317px)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the shift when the layout resets', () => {
|
||||||
|
const { kh, nodes } = loadLayout({ offsetTop: 285 });
|
||||||
|
kh.updateLayoutForKeyboard();
|
||||||
|
kh.resetLayout();
|
||||||
|
expect(nodes['.app'].style.transform).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -41,8 +41,9 @@ function loadTerminalModule(): TerminalModule {
|
|||||||
console,
|
console,
|
||||||
setInterval: vi.fn(),
|
setInterval: vi.fn(),
|
||||||
clearInterval: vi.fn(),
|
clearInterval: vi.fn(),
|
||||||
setTimeout,
|
// Looked up per call, so a test's vi.useFakeTimers() reaches the cached module.
|
||||||
clearTimeout,
|
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
|
||||||
|
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
|
||||||
requestAnimationFrame: vi.fn(),
|
requestAnimationFrame: vi.fn(),
|
||||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||||
WebSocket: { OPEN: 1 },
|
WebSocket: { OPEN: 1 },
|
||||||
@@ -547,6 +548,141 @@ describe('one-shot Ctrl through the CJK input field', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
const app = Object.create(CodemanApp.prototype) as {
|
||||||
|
activeSessionId: string | null;
|
||||||
|
_sendCjkPrompt(text: string): boolean;
|
||||||
|
};
|
||||||
|
app.activeSessionId = 'session-a';
|
||||||
|
const composed = vi
|
||||||
|
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
|
||||||
|
.mockReturnValue(true);
|
||||||
|
return { app, bar, composed };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('sends through the composer path, bound to the session active at Enter', () => {
|
||||||
|
const { app, composed } = promptApp();
|
||||||
|
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
|
||||||
|
app.activeSessionId = 'session-b';
|
||||||
|
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
|
||||||
|
composed.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
|
||||||
|
const { app, bar, composed } = promptApp();
|
||||||
|
bar.toggleCtrl();
|
||||||
|
app._sendCjkPrompt('x'.repeat(100));
|
||||||
|
expect(bar.isCtrlArmed()).toBe(false);
|
||||||
|
composed.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('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('sends a lone digit without Enter while a permission or question dialog waits', () => {
|
||||||
|
// The dialog acts on the digit keypress itself; an Enter 120 ms later would
|
||||||
|
// confirm whatever the CLI shows next (a second permission prompt, unseen).
|
||||||
|
// Same rule as the Approvals Inbox and the Discord bridge (awaitingChoice).
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
|
||||||
|
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]);
|
||||||
|
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
|
||||||
|
['session-a', new Set([hook])],
|
||||||
|
]);
|
||||||
|
expect(app._sendCjkPrompt('2')).toBe(true);
|
||||||
|
vi.advanceTimersByTime(500);
|
||||||
|
expect(writes).toEqual([['session-a', '2', undefined]]);
|
||||||
|
composed.mockRestore();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the delayed Enter for a digit when only an idle prompt is pending, or for a letter in a dialog', () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const cases: Array<[string, string]> = [
|
||||||
|
['idle_prompt', '1'],
|
||||||
|
['permission_prompt', 'y'],
|
||||||
|
];
|
||||||
|
for (const [hook, text] of cases) {
|
||||||
|
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]);
|
||||||
|
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
|
||||||
|
['session-a', new Set([hook])],
|
||||||
|
]);
|
||||||
|
expect(app._sendCjkPrompt(text)).toBe(true);
|
||||||
|
vi.advanceTimersByTime(120);
|
||||||
|
expect(writes).toEqual([
|
||||||
|
['session-a', text, undefined],
|
||||||
|
['session-a', '\r', { useMux: true }],
|
||||||
|
]);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('armed styling survives the light-skin overrides', () => {
|
describe('armed styling survives the light-skin overrides', () => {
|
||||||
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
|
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
|
||||||
|
|
||||||
|
|||||||
@@ -145,6 +145,28 @@ describe('terminal touch tap mouse guard', () => {
|
|||||||
expect(app._isMobileTerminalInputFocused()).toBe(true);
|
expect(app._isMobileTerminalInputFocused()).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('a content touchstart blurs xterm input but leaves the pinned CJK field focused', () => {
|
||||||
|
const { app, setActiveElement } = loadTerminalUiHarness();
|
||||||
|
setActiveElement({ id: '', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } });
|
||||||
|
expect(app._contentTouchStartBlurs()).toBe(true);
|
||||||
|
// A swipe that starts on the live screen must not close the keyboard the field owns.
|
||||||
|
setActiveElement({ id: 'cjkInput', classList: { contains: () => false } });
|
||||||
|
expect(app._contentTouchStartBlurs()).toBe(false);
|
||||||
|
setActiveElement(null);
|
||||||
|
expect(app._contentTouchStartBlurs()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the content touchstart only blurs through _contentTouchStartBlurs()', () => {
|
||||||
|
// The touchstart listener lives in initTerminal, which this harness does not run,
|
||||||
|
// so pin its one line: an unconditional blur there closes the pinned field's
|
||||||
|
// keyboard on every swipe that starts on the live screen.
|
||||||
|
const code = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
|
||||||
|
const branch = code.slice(code.indexOf("if (touchStartIntent === 'content') {"));
|
||||||
|
const body = branch.slice(0, branch.indexOf('// Hold still and this press becomes a text selection.'));
|
||||||
|
expect(body).toContain('if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();');
|
||||||
|
expect(body.match(/_blurMobileTerminalInput\(\)/g)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
|
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
|
||||||
const { app } = loadTerminalUiHarness();
|
const { app } = loadTerminalUiHarness();
|
||||||
app.activeSessionId = 'sess-1';
|
app.activeSessionId = 'sess-1';
|
||||||
@@ -973,9 +995,27 @@ describe('terminal link tap', () => {
|
|||||||
app._isOutsideWorktreePath = () => false;
|
app._isOutsideWorktreePath = () => false;
|
||||||
windowRef.open = vi.fn();
|
windowRef.open = vi.fn();
|
||||||
app.registerFilePathLinkProvider();
|
app.registerFilePathLinkProvider();
|
||||||
return { app, windowRef, sent };
|
return { app, windowRef, sent, setActiveElement: harness.setActiveElement };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it('a link tap closes the keyboard of the pinned CJK field, which touchstart left focused', () => {
|
||||||
|
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||||
|
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
|
||||||
|
const cjk = { id: 'cjkInput', classList: { contains: () => false }, blur: vi.fn() };
|
||||||
|
setActiveElement(cjk);
|
||||||
|
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
|
||||||
|
expect(cjk.blur).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a link tap leaves focus alone otherwise (touchstart already blurred xterm input)', () => {
|
||||||
|
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||||
|
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
|
||||||
|
const other = { id: '', classList: { contains: () => false }, blur: vi.fn() };
|
||||||
|
setActiveElement(other);
|
||||||
|
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
|
||||||
|
expect(other.blur).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('opens a URL under the finger in a new tab', () => {
|
it('opens a URL under the finger in a new tab', () => {
|
||||||
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||||
const { app, windowRef } = linkHarness([line, '', '❯ ']);
|
const { app, windowRef } = linkHarness([line, '', '❯ ']);
|
||||||
|
|||||||
Reference in new issue
Block a user