Merge #839: fix(web): synchronize iOS keyboard edits (#830) (@HadrienKerlero)

This commit is contained in:
Codeman maintainer committed 2026-11-25 16:11:57 +01:00
commit eb40f4aaa5
55 files changed
+6950 -1039

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
---
'aicodeman': patch
'xterm-zerolag-input': patch
---
Fix iOS keyboard suggestions, phrase replacement, dictation and hold-delete by retaining native input ownership in each terminal pane. Preserve local-echo Enter ordering across session switches, reset native editing at toolbar and programmatic input boundaries, and show the native trackpad caret on the exact cell of the visible input, including across wide-character wraps, with emoji-safe deletion. The local-echo overlay deletes one grapheme cluster per backspace and adds `getInputEndAnchor()`, `getInputAnchor(offset)`, `committedText` and `onLayout()` for hosts that position a caret against the drawn input.
+2 -2
View File
@@ -355,7 +355,7 @@ npm test -- -t "pattern" # By name
Three suites are deliberately left out, because they cannot pass on an arbitrary machine. Each has its own runner, and a failure there means "not runnable here", not a regression:
```bash
npm run test:browser # Playwright + chromium, live server; codex-predictive-echo also needs a real codex binary
npm run test:browser # Playwright + chromium, live server (own pretest vendor step); codex-predictive-echo also needs a real codex binary
npm run test:mobile # the above plus environment-specific PNG baselines (own config, own pretest vendor step)
npm run test:perf # wall-clock benchmarks — need an otherwise idle machine
npm run test:all # literally everything; fails ~87 tests on a clean master here, which is why it is not the default
@@ -373,7 +373,7 @@ A raw `npx vitest` used to find no config, so `setup.ts` never ran and the suite
**Ports**: every in-process test server binds port 0 (the one exception, `test/codex-predictive-echo.test.ts`, starts a separate lab server process on 3222). A test that constructs `WebServer` reads `server.boundPort` (mobile tests: `createTestServer()`, then `server.boundPort`); a raw `http`/`net`/Fastify/`ws` server listens on `0` and reads `address().port`. `test/test-ports-guard.test.ts` fails a `WebServer` built on any other port and a raw `listen` on a number or `…PORT` constant. A test that needs a port nothing listens on binds 0, reads it and closes (`closedPort()` in `test/daemon-control.test.ts`), never "the server's port + 1". Never 3000 (the live instance).
⚠️ **Browser tests can pass vacuously on mobile input paths.** Two traps, both hit on 2026-07-27 while fixing the phone Enter button: **(1)** driving input with `app.sendInput('…')` writes PAST the `LocalEchoOverlay`, so `pendingText` stays empty and any overlay bug is invisible — type with `page.keyboard.type()` instead; **(2)** headless Chromium reports `MobileDetection.isTouchDevice()` **false even with `hasTouch: true`**, so `_localEchoEnabled` is off and the local-echo branch never executes. Force it (`app._localEchoEnabled = true`) or the test proves nothing. Assert on real state (`app._localEchoOverlay.pendingText`, plus `tmux -L codeman capture-pane -p -t <pane>` for what actually reached the PTY), not on HTTP 200.
⚠️ **Browser tests can pass vacuously on mobile input paths.** Two traps, both hit on 2026-07-27 while fixing the phone Enter button: **(1)** driving input with `app._sendInputAsync(id, '…')` writes PAST the `LocalEchoOverlay`, so `pendingText` stays empty and any overlay bug is invisible — type with `page.keyboard.type()` instead; **(2)** headless Chromium reports `MobileDetection.isTouchDevice()` **false even with `hasTouch: true`**, so `_localEchoEnabled` is off and the local-echo branch never executes. Force it (`app._localEchoEnabled = true`) or the test proves nothing. Assert on real state (`app._localEchoOverlay.pendingText`, plus `tmux -L codeman capture-pane -p -t <pane>` for what actually reached the PTY), not on HTTP 200.
**Testing against the live instance**: prod is HTTPS-only on :3000 (`curl -sk https://localhost:3000/...`). ⚠️ `w1`/`w2`/`w3` are the user's REAL sessions — never send input to them. Create your own throwaway session (`POST /api/sessions` then `POST /api/sessions/:id/shell`; creation alone leaves `pid: null` and no pane), test against that, and `DELETE` it by exact id when done.
+1
View File
@@ -38,6 +38,7 @@ export const BROWSER_TEST_GLOBS = [
'test/webgl-fallback.test.ts',
'test/terminal-copy-shortcut.test.ts',
'test/terminal-keycode229-recovery.browser.test.ts',
'test/ios-native-input.browser.test.ts',
'test/capture-load-window.browser.test.ts',
'test/capture-geometry-retry.browser.test.ts',
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
+3 -3
View File
@@ -145,7 +145,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.
### Input delivery and WS resilience
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. **Session FIFO** (`_enqueueInput`, app.js, #830): every browser producer (typed main-pane input, toolbar submit, accessory keys and commands, paste, Compose, voice, image upload) captures its session id when the user acts and enqueues ops (`write`, `key`, `gap`) on that session's FIFO, which drains them in order: a `write` goes to `_enqueueReliableInput`, a `key` (a modified Enter such as Shift/Ctrl+Enter) is a direct `POST /api/sessions/:id/send-key` outside the exactly-once layer, and a `gap` delays the next op. ⚠️ A `gap` orders ENQUEUEING only: the next op is handed to the reliable layer after the delay, with no wait for the previous frame's ACK, so a delayed Enter keeps its session and its place but gains no delivery guarantee beyond the exactly-once layer. ⚠️ Ops for an id missing from `app.sessions` are dropped (a probe or deleted session never reaches the wire; tests must register their session). ⚠️ `_cleanupSessionData()` clears the session's FIFO and its pending gap timer, so a deleted session cannot type into a reused id. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR
@@ -1109,7 +1109,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
### Split-pane sessions
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattenLine truncated
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own soft-keyboard input owner: the iOS native-input owner (`_iosNativeInput`, terminal-ios-native-input.js, #830) on iOS WebKit touch, otherwise the keyCode-229 controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring Line truncated
### Tile grid
@@ -1311,7 +1311,7 @@ Mapping is `ctrlByteFor()` (`code & 0x1f` over @A-Z[\]^_ and a-z, plus Ctrl+Spac
⚠️ **Drafts are per-session and in memory only** (`_composerDrafts`, never persisted: prompts routinely carry secrets, and persisting them would need the 0600 treatment the intent store gets). Every non-Send exit (Cancel, backdrop, Escape, "Use terminal keyboard") leaves the taken text ONLY in the draft, with the dot on the key (`has-draft`, kept in step by `_syncComposerDraftIndicator`) as the signal that the terminal prompt is empty on purpose, and `_cleanupSessionData` discards the draft with the session.
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) through `_sendInputAsync` WITHOUT `{ useMux: true }`, plus a SEPARATE Enter 120 ms later WITH it (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
⚠️ **Delivery is a hand-built bracketed-paste frame** (`\x1b[200~` + the text with newlines mapped to `\r` + `\x1b[201~`, byte-identical to what `terminal.paste()` would emit) enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `{ useMux: true }`, then a 120 ms `gap` and a SEPARATE Enter WITH it, all reserved for the composer's session at Send (codex drops keys that share a PTY read with a bracketed paste). Not `terminal.paste()`, for two reasons: xterm's `bracketedPasteMode` mirror is false for every session after a tab switch or reload (`terminal.reset()` in the replay re-clones the DEC modes, the tmux capture carries no `?2004h`, and tmux never forwards the pane's DECSET to a client after attach), so a paste through xterm would go out unbracketed and the CLI would submit at the first `\r`; and xterm's onData is where the local-echo paste branch flushes pending overlay text AHEAD of the block, text the composer has already taken and erased from the PTY, so the frame goes straight to the wire with the composer as the prompt's only owner. The unconditional frame is safe for a CLI that never enabled DECSET 2004 because tmux does the gating (measured against a live pane: markers stripped for a `cat -v` pane, forwarded intact to a process that had emitted `?2004h`).
⚠️ The frame must never take the mux fallback: `TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one, pasted inside a second pair of markers, and get submitted.
+27
View File
@@ -0,0 +1,27 @@
# iOS keyboard ownership (#830)
On iOS WebKit touch devices, `terminal-ios-native-input.js` owns the terminal's native textarea. Its support check shares `MobileImePreview.isIosWebKitTouch`; it loads after the preview and before the primary terminal and tile hosts. These hosts do not also install keyCode-229 recovery on iOS. Other coarse-pointer devices retain that recovery.
The native field retains the editable line, including dictation hypotheses and native newlines. Reconciliation emits shell-safe transactions rather than forwarding each browser event. A dictated line break must never send CR or LF. Trackpad movement changes only the visual caret; it sends no terminal arrows, never focuses the field and never changes its selection.
The owner exposes `caret(): { visible, text, offset, generation }`, with projected text and a UTF-16 offset into that projection (CRLF and LF each become one space). `generation` advances only when an edit is reconciled (sent) or the line is reset; a clipboard snapshot borrowing the field and its restoration leave it unchanged. The marker has two authoritative positioning modes:
- **Local echo:** the field must be an exact suffix of the overlay's last displayed `committedText`. The marker queries `getInputAnchor(base + offset)` for the painted cell, including wide-character wraps. A mismatch or unavailable/clipped layout hides it.
- **Parsed buffer:** with echo off, passthrough, tiles or Pane B, the marker matches the full native text backwards from xterm's cursor, crossing only soft wraps. It skips wide-glyph continuation cells and validated empty wrap padding, then maps the offset to an actual buffer cell. A mismatch, an identical preceding repetition, an offset inside a combined cell (such as a combining mark or ZWJ cluster), or an offscreen row hides it. When `generation` changes it also hides until xterm parses its next write. That wait is a heuristic, not a delivery acknowledgement: any parsed write clears it, so if unrelated output arrives before the echo and identical text already sits before the cursor, the cells can still match the older text.
Both modes hide for an unfocused field, composition, a range selection, the end of the field, a pending/unreconciled edit, an invalidated baseline, a failed transaction sink or a borrowed clipboard snapshot. No mode estimates the caret by subtracting a text width from an end anchor.
Programmatic input calls `_prepareExternalInput` on the captured pane before sending. Toolbar Enter calls `submitFromToolbar()`. The per-session FIFO reserves pending local-echo text, an 80ms gap, and CR together, so switching sessions cannot redirect CR or let later edits overtake it. This is enqueue ordering, not an acknowledgement-completion fence. Logical ACK fences, tagged HTTP success semantics, HTTP/WebSocket handover gating and `/send-key` ACK fencing are outside this fix.
## Browser regression suite
```sh
node scripts/prepare-test-vendor.mjs
npm run test:browser -- test/ios-native-input.browser.test.ts
```
The browser runner also prepares the source-served vendor overlay through `pretest:browser`. `src/web/public/vendor/` is gitignored; source vendor is generated, not tracked. Production builds independently regenerate the overlay from `packages/xterm-zerolag-input` and content-hash it. The overlay must include `getInputAnchor` and `committedText` before running these tests.
The suite serves the real application with Chromium, an iPhone user agent, touch points and a coarse pointer. It observes `_enqueueReliableInput` without replacing `_sendInputAsync`, and reuses the phone-validated WebKit replay defaults. Assertions cover suggestion op boundaries, phrase replacement, held delete, dictation newline suppression, toolbar submission and subsequent suggestions, old-session CR ownership during the gap, trusted CDP paste, caret geometry in both echo modes, emoji deletion, tile session ownership and non-iOS recovery.
These are browser wiring tests, not a substitute for device replay. The logged iPhone event sequences they replay are in [#830](https://github.com/Ark0N/Codeman/issues/830).
+1 -1
View File
@@ -579,7 +579,7 @@ step 1 is a real step). Before shipping:
browser, confirm the reply renders and scrollback survives a tab switch. Do not touch
`w1`/`w2`/`w3`.
4. **Local-echo policy gate (§2.10):** on a phone profile, type into the pi editor through the
buffer overlay (drive with `page.keyboard.type()`, never `app.sendInput()`, and force
buffer overlay (drive with `page.keyboard.type()`, never `app._sendInputAsync()`, and force
`app._localEchoEnabled = true`; headless Chromium reports touch as false) and confirm pi's
composer renders the flushed text correctly on Enter. If it mis-renders, flip pi to the `'off'`
branch in `_updateLocalEchoState` and pin that instead.
+1 -1
View File
@@ -75,7 +75,7 @@ Both transports refuse a frame longer than `MAX_INPUT_LENGTH` (64 KiB,
at the head of the queue, was re-sent every 2 s forever, blocked every later
input for the session, and came back from localStorage on each reload.
- `_sendInputAsync()` splits a paste over the frame limit into in-limit frames
- `_enqueueReliableInput()` (the session FIFO's transport edge) splits a paste over the frame limit into in-limit frames
(`CodemanInputLimit.split`, constants.js, never cutting a surrogate pair). They
go out in seq order, so the PTY sees one contiguous stream. A paste over
`PASTE_MAX_CHARS` (1 MiB), or an oversized `useMux` write (one paste plus its own Enter, never
+1
View File
@@ -23,6 +23,7 @@
"test:watch": "vitest --config config/vitest.ci.config.ts",
"test:coverage": "vitest run --config config/vitest.ci.config.ts --coverage",
"test:ci": "vitest run --config config/vitest.ci.config.ts",
"pretest:browser": "node scripts/prepare-test-vendor.mjs",
"test:browser": "vitest run --config config/vitest.browser.config.ts",
"test:perf": "vitest run --config config/vitest.perf.config.ts",
"test:all": "vitest run --config config/vitest.config.ts",
+7 -1
View File
@@ -203,7 +203,7 @@ Implements the xterm.js `ITerminalAddon` interface. It deliberately does **not**
|--------|---------|-------------|
| `addChar(char)` | `void` | Add a single printable character. Auto-detects existing buffer text on the first keystroke. |
| `appendText(text)` | `void` | Append multiple characters (paste). |
| `removeChar()` | `'pending'` \| `'flushed'` \| `false` | Remove the last character and drop any IME composition. See [backspace handling](#backspace-handling). |
| `removeChar()` | `'pending'` \| `'flushed'` \| `false` | Remove the last grapheme cluster (one user-perceived character: a red heart, a skin-tone emoji, a flag or a ZWJ family is one) and drop any IME composition. See [backspace handling](#backspace-handling). |
| `clear()` | `void` | Clear all state, the composition included, and hide the overlay. Call on Enter, Ctrl+C, Escape. |
| `setComposition(text)` | `void` | Show text an IME is still composing as an underlined tail after the typed text. Pass `''` to remove it. See [IME composition](#ime-composition). |
| `setRowLimit(limit)` | `void` | Narrow the row bound the overlay keeps itself on screen with (normally `terminal.rows`) to the first `limit` screen rows, so it grows upward from the last of them; `null` restores all rows, and a limit above `terminal.rows` changes nothing. For hosts that keep the terminal taller than the box showing it, e.g. while an on-screen keyboard covers the bottom. |
@@ -220,6 +220,8 @@ Implements the xterm.js `ITerminalAddon` interface. It deliberately does **not**
The cascade order is pending text, then flushed text, then auto-detected buffer text (which is what makes backspace work after tab completion). Backspace "just works" across any combination of typed, in-flight and completed text.
One call removes one grapheme cluster: the unit a soft-keyboard Backspace removes, and what Claude Code and Codex delete per `\x7f`. So when it returns `'flushed'`, one `\x7f` removes the same character in those CLIs; a line editor that deletes by code point (bash readline, for a skin tone or a flag) removes less. For `'pending'` or `false`, send nothing. Grapheme boundaries come from `Intl.Segmenter`; where it is missing, one code point is removed instead.
### IME composition
While an input method (Japanese kana, Chinese pinyin, Korean) is still composing, the text is not committed yet, so it is not in `pendingText` either. `setComposition(text)` draws it as an underlined, `aria-hidden` tail right after the pending and flushed text, using the same wrapping and on-screen layout as the rest of the overlay.
@@ -260,6 +262,9 @@ Finds text that exists after the prompt but was never typed through the overlay.
|--------|-------------|
| `rerender()` | Force a re-render. Call after buffer reloads, screen redraws, resizes and reconnects. A no-op when there is nothing to draw, so it needs no guard. |
| `refreshFont()` | Re-cache font and color properties from the terminal. Call after a font size or theme change. |
| `getInputEndAnchor()` | Where the overlay's visible text ends, from its last layout: `{ col, row }` in viewport cells (`col` equals the column count at a full line's right edge), or `null` while the overlay is hidden. For placing a caret marker against the drawn input. |
| `getInputAnchor(offset)` | Resolve an offset in UTF-16 units into the last displayed flushed + pending + composition text to `{ col, row }` in viewport cells. Wrap boundaries prefer the next line; the final offset returns the end anchor. Returns `null` when hidden, out of range, inside a surrogate pair, or on a tail-sliced row. Performs no width measurement or DOM work. |
| `onLayout(callback)` | Call `callback` after each layout, a hide included. Returns an unsubscribe function. |
### Prompt
@@ -274,6 +279,7 @@ Finds text that exists after the prompt but was never typed through the overlay.
| Property | Type | Description |
|----------|------|-------------|
| `pendingText` | `string` | Unacknowledged text (read-only) |
| `committedText` | `string` | Flushed + pending text exactly as last displayed, excluding composition; `''` when hidden (read-only). Visual correspondence data, not a delivery acknowledgement. Offsets use UTF-16 units. |
| `hasPending` | `boolean` | `true` if there is pending or flushed text. Excludes the IME composition, so it can be `false` while the overlay still shows one |
| `composition` | `string` | The text set by `setComposition()`, `''` when none (read-only) |
| `state` | `ZerolagInputState` | Full snapshot: `pendingText`, `flushedLength`, `flushedText`, `visible`, `promptPosition` |
@@ -8,6 +8,7 @@ export type {
ZerolagInputState,
PromptFinder,
PromptPosition,
InputEndAnchor,
CellDimensions,
} from './types.js';
export type { PredictiveEchoOptions, PredictionState } from './predictive-echo-addon.js';
@@ -1,4 +1,4 @@
import type { RenderParams, FontStyle, XtermTerminal } from './types.js';
import type { RenderParams, FontStyle, XtermTerminal, InputEndAnchor } from './types.js';
// ─── CJK / fullwidth character width detection ───────────────────────
@@ -88,6 +88,13 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
return !state.cursor || children[state.lines.length] === state.cursor;
}
interface OverlayPlacement {
end: InputEndAnchor | null;
firstVisible: number;
topRow: number;
keepsPromptLine: boolean;
}
/**
* Render the overlay content into the container element.
*
@@ -102,7 +109,7 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
* DOM work, layout and paint, which a long prompt on a phone paid for in
* dropped frames.
*/
export function renderOverlay(container: HTMLDivElement, params: RenderParams): void {
export function renderOverlay(container: HTMLDivElement, params: RenderParams): OverlayPlacement {
const {
lines,
compositionStart,
@@ -233,11 +240,11 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
state.lines.length = visibleLines.length;
state.lineKeys.length = visibleLines.length;
// Block cursor at end of last line (use visual width for CJK support)
if (showCursor) {
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine);
// Publish the text end from this layout even when the block cursor is hidden.
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine ?? '');
if (showCursor && lastLine !== undefined) {
if (cursorCol < totalCols) {
const cursor = document.createElement('span');
cursor.style.cssText = 'position:absolute;display:inline-block';
@@ -252,6 +259,12 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
}
container.style.display = '';
return {
end: lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 },
firstVisible,
topRow,
keepsPromptLine,
};
}
/**
@@ -66,6 +66,14 @@ export interface PromptPosition {
col: number;
}
/** Viewport position at the end of the visible overlay input. */
export interface InputEndAnchor {
/** Column (0-based); equals the column count at a full line's right edge. */
col: number;
/** Viewport-relative row (0 = top of viewport). */
row: number;
}
/**
* Prompt detection strategy.
*
@@ -6,6 +6,7 @@ import type {
PromptPosition,
PromptFinder,
FontStyle,
InputEndAnchor,
} from './types.js';
import { getCellDimensions } from './cell-dimensions.js';
import { findPrompt, readTextAfterPrompt, promptRowInViewport } from './prompt-finder.js';
@@ -18,6 +19,57 @@ const DEFAULT_BG = '#0d0d0d';
const DEFAULT_FG = '#eeeeee';
const DEFAULT_CURSOR = '#e0e0e0';
interface InputLayoutLine {
start: number;
end: number;
startCol: number;
cols: number[];
codeUnits: number[];
}
interface InputLayout {
text: string;
committedLength: number;
lines: InputLayoutLine[];
firstVisible: number;
topRow: number;
keepsPromptLine: boolean;
startCol: number;
totalCols: number;
}
type GraphemeSegmenter = {
segment(input: string): { containing(index: number): { segment: string } | undefined };
};
const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
try {
const Segmenter = (
Intl as typeof Intl & {
Segmenter?: new (locale?: string, options?: { granularity: 'grapheme' }) => GraphemeSegmenter;
}
).Segmenter;
return Segmenter ? new Segmenter(undefined, { granularity: 'grapheme' }) : null;
} catch {
return null;
}
})();
/**
* UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string).
* `containing()` finds the cluster at the end without walking the whole string (measured
* 0.09 ms at 60,000 characters, against 41 ms for a full scan), and segments with the
* whole text as context, so a cluster of any length and an odd run of flags come out right.
*/
function lastGraphemeWidth(text: string): number {
if (!text) return 1;
if (GRAPHEME_SEGMENTER) return GRAPHEME_SEGMENTER.segment(text).containing(text.length - 1)?.segment.length ?? 1;
const last = text.charCodeAt(text.length - 1);
const previous = text.charCodeAt(text.length - 2);
return last >= 0xdc00 && last <= 0xdfff && previous >= 0xd800 && previous <= 0xdbff ? 2 : 1;
}
/**
* xterm.js addon that provides instant keystroke feedback via a DOM overlay.
*
@@ -76,6 +128,9 @@ export class ZerolagInputAddon implements XtermAddon {
// Render cache
private _lastRenderKey = '';
private _lastPromptPos: PromptPosition | null = null;
private _inputEndAnchor: InputEndAnchor | null = null;
private _layout: InputLayout | null = null;
private _layoutListeners = new Set<() => void>();
// Font cache
private _font: FontStyle = {
@@ -130,6 +185,9 @@ export class ZerolagInputAddon implements XtermAddon {
try {
if (!promptRowInViewport(this._terminal!)) {
this._overlay!.style.display = 'none';
this._inputEndAnchor = null;
this._layout = null;
this._notifyLayout();
if (this._scrollTimer) {
clearTimeout(this._scrollTimer);
this._scrollTimer = null;
@@ -171,6 +229,7 @@ export class ZerolagInputAddon implements XtermAddon {
this._scrollViewport = null;
this._scrollHandler = null;
this._terminal = null;
this._layoutListeners.clear();
}
// ─── Input methods ────────────────────────────────────────────────
@@ -196,10 +255,12 @@ export class ZerolagInputAddon implements XtermAddon {
}
/**
* Remove the last character from the overlay.
* Remove the last grapheme cluster (one user-perceived character).
*
* Cascade order:
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
* 1. Remove the last visible cluster from pending text; if it crosses into
* trustworthy flushed text, remove that tail too → returns `'flushed'`,
* otherwise returns `'pending'`
* 2. Decrement `flushedOffset` if pending is empty but flushed exists → returns `'flushed'`
* 3. Try `detectBufferText()` if both are empty, then decrement → returns `'flushed'`
*
@@ -207,8 +268,8 @@ export class ZerolagInputAddon implements XtermAddon {
*
* - `'pending'`: A character was removed from unsent text. The consumer
* should NOT send backspace to the PTY (the text was never transmitted).
* - `'flushed'`: A character was removed from text already sent to the PTY.
* The consumer SHOULD send backspace to the PTY.
* - `'flushed'`: A character was removed wholly or partly from text already
* sent to the PTY. The consumer SHOULD send one backspace to the PTY.
* - `false`: Nothing to remove. The consumer should NOT send backspace.
*
* Any IME composition is dropped in every case, and the overlay is repainted
@@ -219,32 +280,30 @@ export class ZerolagInputAddon implements XtermAddon {
const droppedComposition = this._composition.length > 0;
this._composition = '';
if (this._pendingText.length > 0) {
this._pendingText = this._pendingText.slice(0, -1);
const pendingLength = this._pendingText.length;
const hasFlushedText = this._flushedOffset > 0 && this._flushedText.length === this._flushedOffset;
const width = lastGraphemeWidth(hasFlushedText ? this._flushedText + this._pendingText : this._pendingText);
const flushedWidth = Math.max(0, width - pendingLength);
this._pendingText = this._pendingText.slice(0, -width);
if (flushedWidth > 0) {
this._flushedOffset -= flushedWidth;
this._flushedText = this._flushedText.slice(0, -flushedWidth);
}
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
this._render();
} else {
this._hide();
}
return 'pending';
}
if (this._flushedOffset > 0) {
this._flushedOffset--;
this._flushedText = this._flushedText.slice(0, -1);
if (this._flushedOffset > 0) {
this._render();
} else {
this._hide();
}
return 'flushed';
return flushedWidth > 0 ? 'flushed' : 'pending';
}
// Both empty — try detecting text already on the prompt line
// (handles tab completion, arrow-key edits, etc.)
this._detectBufferText();
// (handles tab completion, arrow-key edits, etc.).
if (this._flushedOffset === 0) this._detectBufferText();
if (this._flushedOffset > 0) {
this._flushedOffset--;
this._flushedText = this._flushedText.slice(0, -1);
const width = lastGraphemeWidth(this._flushedText);
this._flushedOffset -= width;
this._flushedText = this._flushedText.slice(0, -width);
if (this._flushedOffset > 0) {
this._render();
} else {
@@ -320,6 +379,42 @@ export class ZerolagInputAddon implements XtermAddon {
// ─── Rendering control ────────────────────────────────────────────
/** Viewport text end from the renderer's last visible layout, or null when hidden. */
getInputEndAnchor(): InputEndAnchor | null {
return this._inputEndAnchor ? { ...this._inputEndAnchor } : null;
}
/** Resolve a UTF-16 offset in the last displayed text, with forward wrap affinity. */
getInputAnchor(offset: number): InputEndAnchor | null {
const layout = this._layout;
if (!layout || !Number.isInteger(offset) || offset < 0 || offset > layout.text.length) return null;
if (offset === layout.text.length) return this.getInputEndAnchor();
for (let i = layout.lines.length - 1; i >= layout.firstVisible; i--) {
const line = layout.lines[i];
if (offset < line.start || offset >= line.end) continue;
const index = line.codeUnits.indexOf(offset - line.start);
if (index < 0) return null;
return {
col: (i === 0 && layout.keepsPromptLine ? layout.startCol : 0) + line.cols[index],
row: layout.topRow + i - layout.firstVisible,
};
}
return null;
}
/** Last displayed flushed + pending text, not a delivery acknowledgement. */
get committedText(): string {
return this._layout ? this._layout.text.slice(0, this._layout.committedLength) : '';
}
/** Subscribe after each layout, including hide. Returns an unsubscribe function. */
onLayout(cb: () => void): () => void {
this._layoutListeners.add(cb);
return () => {
this._layoutListeners.delete(cb);
};
}
/**
* Force a re-render of the overlay at the current prompt position.
* Call after terminal resets, buffer reloads, or full-screen redraws
@@ -578,22 +673,35 @@ export class ZerolagInputAddon implements XtermAddon {
}
}
private _notifyLayout(): void {
for (const cb of this._layoutListeners) {
try {
cb();
} catch {
// A visual observer must not interrupt input or the other listeners.
}
}
}
private _hide(): void {
if (!this._overlay) return;
this._lastRenderKey = '';
this._lastPromptPos = null;
this._overlay.innerHTML = '';
this._overlay.style.display = 'none';
this._inputEndAnchor = null;
this._layout = null;
this._notifyLayout();
}
private _render(): void {
if (!this._terminal || !this._overlay) return;
if (!this._hasContent()) {
this._overlay.style.display = 'none';
return;
}
let layoutChanged = true;
try {
if (!this._hasContent()) {
this._overlay.style.display = 'none';
return;
}
const buf = this._terminal.buffer.active;
// Hide the overlay while the cursor row is scrolled out of view
@@ -647,6 +755,7 @@ export class ZerolagInputAddon implements XtermAddon {
}
// The composition is a styled tail after everything the user has typed.
const committedLength = displayText.length;
const compositionStart = [...displayText].length;
displayText += this._composition;
@@ -658,44 +767,61 @@ export class ZerolagInputAddon implements XtermAddon {
// redundant render.
const totalRows = this._layoutRows();
const renderKey = `${displayText}:${compositionStart}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${totalRows}:${this._flushedOffset}`;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') return;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') {
layoutChanged = false;
return;
}
this._lastRenderKey = renderKey;
// Split into visual lines by column width (CJK wide chars = 2 cols)
const firstLineCols = Math.max(1, totalCols - startCol);
const chars = [...displayText]; // proper Unicode iteration
const lines: string[] = [];
const layoutLines: InputLayoutLine[] = [];
let codeUnit = 0;
let ci = 0;
// First line: remaining columns after prompt
{
let lineStr = '';
let lineCols = 0;
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol, cols: [], codeUnits: [] };
while (ci < chars.length) {
const cw = charCellWidth(this._terminal, chars[ci]);
if (lineCols + cw > firstLineCols) break;
line.cols.push(lineCols);
line.codeUnits.push(codeUnit - line.start);
codeUnit += chars[ci].length;
lineStr += chars[ci];
lineCols += cw;
ci++;
}
lines.push(lineStr);
line.end = codeUnit;
layoutLines.push(line);
}
// Subsequent lines: full terminal width
while (ci < chars.length) {
let lineStr = '';
let lineCols = 0;
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol: 0, cols: [], codeUnits: [] };
while (ci < chars.length) {
const cw = charCellWidth(this._terminal, chars[ci]);
if (lineCols + cw > totalCols) break;
line.cols.push(lineCols);
line.codeUnits.push(codeUnit - line.start);
codeUnit += chars[ci].length;
lineStr += chars[ci];
lineCols += cw;
ci++;
}
lines.push(lineStr);
line.end = codeUnit;
layoutLines.push(line);
}
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
renderOverlay(this._overlay, {
const placement = renderOverlay(this._overlay, {
lines,
compositionStart: this._composition ? compositionStart : undefined,
startCol,
@@ -711,6 +837,17 @@ export class ZerolagInputAddon implements XtermAddon {
cursorColor,
terminal: this._terminal,
});
this._inputEndAnchor = placement.end;
this._layout = {
text: displayText,
committedLength,
lines: layoutLines,
firstVisible: placement.firstVisible,
topRow: placement.topRow,
keepsPromptLine: placement.keepsPromptLine,
startCol,
totalCols,
};
} catch {
// Hide on render error but preserve pendingText —
// next rerender() will retry when terminal is ready.
@@ -718,6 +855,12 @@ export class ZerolagInputAddon implements XtermAddon {
this._overlay.innerHTML = '';
this._overlay.style.display = 'none';
}
} finally {
if (this._overlay.style.display === 'none') {
this._inputEndAnchor = null;
this._layout = null;
}
if (layoutChanged) this._notifyLayout();
}
}
}
@@ -531,6 +531,29 @@ describe('renderOverlay — staying on screen (totalRows)', () => {
expect(container.style.top).toBe(6 * 17 + 'px');
});
it('returns the same placement used for upward growth and tail clipping', () => {
const container = document.createElement('div');
const params = makeParams({ lines: ['ab', '你好', 'x'], startCol: 3, promptRow: 5, totalRows: 6 });
expect(renderOverlay(container, params)).toEqual({
end: { col: 1, row: 5 },
firstVisible: 0,
topRow: 3,
keepsPromptLine: true,
});
expect(renderOverlay(container, { ...params, totalRows: 2 })).toEqual({
end: { col: 1, row: 1 },
firstVisible: 1,
topRow: 0,
keepsPromptLine: false,
});
expect(renderOverlay(container, { ...params, lines: [] })).toEqual({
end: null,
firstVisible: 0,
topRow: 5,
keepsPromptLine: true,
});
});
});
describe('renderOverlay: rebuilding only the lines that changed', () => {
@@ -1,6 +1,7 @@
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';
import { createMockTerminal } from './helpers.js';
import { ZerolagInputAddon } from '../src/zerolag-input-addon.js';
import type { InputEndAnchor } from '../src/types.js';
function setup(lines: string[] = ['$ '], promptChar = '$') {
const mock = createMockTerminal({ buffer: { lines } });
@@ -91,6 +92,113 @@ describe('ZerolagInputAddon', () => {
expect(addon.pendingText).toBe('a');
});
it('removes a whole pending emoji without changing flushed UTF-16 offsets', () => {
const { addon } = tracked();
addon.setFlushed(2, 'ab');
addon.appendText('c😀');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('c');
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ab' });
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('');
});
it.each([
['combining accent', 'a', '\u0301'],
['skin-tone modifier', '\u{1F44D}', '\u{1F3FD}'],
])('removes a %s cluster across the pending/flushed boundary', (_name, base, suffix) => {
const { addon } = tracked();
addon.setFlushed(base.length, base);
addon.appendText(suffix);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
expect(addon.pendingText).toBe('');
expect(addon.state.visible).toBe(false);
});
it('keeps flushed text when removing a separate pending character', () => {
const { addon } = tracked();
addon.setFlushed(1, 'a');
addon.appendText('b');
expect(addon.removeChar()).toBe('pending');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
expect(addon.pendingText).toBe('');
});
it('removes a whole flushed emoji and subtracts its UTF-16 width', () => {
const { addon } = tracked();
addon.setFlushed(3, 'a😀');
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
expect(addon.state.visible).toBe(false);
});
it('removes a whole emoji from newly detected buffer text', () => {
const { addon } = tracked(['$ a😀']);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
});
it('hides after deleting the only pending emoji', () => {
const { addon } = tracked();
addon.appendText('😀');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('');
expect(addon.state.visible).toBe(false);
});
const graphemeCases = [
['red heart', '\u2764\uFE0F'],
['skin-tone thumbs up', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
];
it.each(graphemeCases)('removes a whole pending %s grapheme', (_name, emoji) => {
const { addon } = tracked();
addon.appendText('ok' + emoji);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok');
});
it('removes a cluster longer than 64 UTF-16 units in one call', () => {
const { addon } = tracked();
// `a` plus 80 combining acute accents is one grapheme cluster of 81 units.
const cluster = 'a' + '\u0301'.repeat(80);
addon.appendText('ok' + cluster);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok');
});
it('pairs regional indicators from the start of the run', () => {
const { addon } = tracked();
// Five flags then a lone indicator: the last cluster is the lone one, not a pair.
const flags = '\u{1F1EB}\u{1F1F7}'.repeat(5);
addon.appendText('ok' + flags + '\u{1F1EB}');
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok' + flags);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('ok' + '\u{1F1EB}\u{1F1F7}'.repeat(4));
});
it('removes the last grapheme of a long draft', () => {
const { addon } = tracked();
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}';
addon.appendText('a'.repeat(60000) + family);
expect(addon.removeChar()).toBe('pending');
expect(addon.pendingText).toBe('a'.repeat(60000));
});
it.each(graphemeCases)('removes a whole flushed %s grapheme and subtracts its UTF-16 width', (_name, emoji) => {
const { addon } = tracked();
const text = 'ok' + emoji;
addon.setFlushed(text.length, text);
expect(addon.removeChar()).toBe('flushed');
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ok' });
});
it('returns false when nothing to remove', () => {
const { addon } = tracked();
expect(addon.removeChar()).toBe(false);
@@ -831,3 +939,304 @@ describe('setRowLimit', () => {
expect(overlay().style.top).toBe(`${9 * 17}px`);
});
});
describe('input end anchor and layout subscriptions', () => {
function layoutSetup({ cols = 20, rows = 6, promptRow = 1, showCursor = true } = {}) {
const lines = Array.from({ length: rows }, (_, i) => (i === promptRow ? '$ ' : ''));
const mock = createMockTerminal({ buffer: { lines }, cols, rows });
const addon = new ZerolagInputAddon({
prompt: { type: 'character', char: '$', offset: 2 },
showCursor,
});
mock.terminal.loadAddon(addon);
cleanups.push(() => {
addon.dispose();
mock.cleanup();
});
return { addon, mock };
}
it('returns the text end on a short line, including flushed and wide characters', () => {
const { addon } = layoutSetup();
addon.setFlushed(1, 'a');
addon.appendText('你😀');
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
const anchor = addon.getInputEndAnchor()!;
anchor.col = 0;
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
});
it('returns the short text end rather than the row edge with showCursor false', () => {
const { addon, mock } = layoutSetup({ showCursor: false });
addon.appendText('abc');
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
const overlay = mock.terminal.element.querySelector('.xterm-screen')!.lastElementChild!;
expect(overlay.children.length).toBe(1); // line only, no cursor span
});
it('returns the unindented end of a wrapped line', () => {
const { addon } = layoutSetup();
addon.appendText('x'.repeat(23)); // 18 cells on the first line, then 5
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 2 });
});
it('uses the renderer bottom clamp rather than the original prompt row', () => {
const { addon } = layoutSetup({ promptRow: 5 });
addon.appendText('x'.repeat(23));
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 5 });
});
it('follows a narrowed row limit and a clipped tail without prompt indentation', () => {
const { addon } = layoutSetup({ promptRow: 5 });
addon.appendText('x'.repeat(43)); // lines of 18, 20 and 5 cells
addon.setRowLimit(2);
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
addon.setRowLimit(1);
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 0 });
});
it('reports the right edge of an exactly full line without requiring a cursor span', () => {
const { addon } = layoutSetup();
addon.appendText('x'.repeat(18));
expect(addon.getInputEndAnchor()).toEqual({ col: 20, row: 1 });
});
it('returns null before showing, after clear, and after dispose', () => {
const { addon } = layoutSetup();
expect(addon.getInputEndAnchor()).toBeNull();
addon.appendText('abc');
addon.clear();
expect(addon.getInputEndAnchor()).toBeNull();
addon.appendText('x');
addon.dispose();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('returns null after deleting or clearing the last visible text', () => {
const { addon } = layoutSetup();
addon.addChar('x');
addon.removeChar();
expect(addon.getInputEndAnchor()).toBeNull();
addon.setFlushed(1, 'x');
addon.clearFlushed();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('keeps painting at the last prompt when a redraw briefly hides the prompt marker', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
const before = addon.getInputEndAnchor();
expect(before).not.toBeNull();
mock.setLines(['output without a prompt']);
addon.rerender();
expect(addon.state.visible).toBe(true);
expect(addon.getInputEndAnchor()).toEqual(before);
});
it('publishes null on a scroll hide before repainting', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
const anchors: (InputEndAnchor | null)[] = [];
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
mock.setScroll(0, 30);
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
expect(anchors).toEqual([null]);
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null when render finds the cursor outside the viewport', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
mock.setScroll(0, 30);
addon.rerender();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null when cell dimensions disappear', () => {
const { addon, mock } = layoutSetup();
addon.appendText('abc');
Reflect.deleteProperty(mock.terminal._core._renderService, 'dimensions');
addon.rerender();
expect(addon.getInputEndAnchor()).toBeNull();
});
it('publishes null on render failure while preserving the pending input', () => {
const { addon } = layoutSetup();
addon.appendText('abc');
addon.setPrompt({
type: 'custom',
find: () => {
throw new Error('buffer unavailable');
},
});
expect(addon.getInputEndAnchor()).toBeNull();
expect(addon.pendingText).toBe('abc');
});
it('notifies after each layout and hide, and stops after disposal of the listener', () => {
const { addon } = layoutSetup();
const anchors: (InputEndAnchor | null)[] = [];
const dispose = addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
addon.addChar('a');
addon.addChar('b');
addon.rerender();
addon.clear();
expect(anchors).toEqual([{ col: 3, row: 1 }, { col: 4, row: 1 }, { col: 4, row: 1 }, null]);
dispose();
dispose();
addon.addChar('c');
addon.clear();
expect(anchors).toHaveLength(4);
});
it('isolates listener failures from rendering and other listeners', () => {
const { addon } = layoutSetup();
addon.onLayout(() => {
throw new Error('observer failed');
});
const anchors: (InputEndAnchor | null)[] = [];
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
expect(() => addon.appendText('abc')).not.toThrow();
expect(addon.state.visible).toBe(true);
expect(() => addon.clear()).not.toThrow();
expect(anchors).toEqual([{ col: 5, row: 1 }, null]);
});
it('maps a wide wrap with forward affinity from column 78', () => {
const { addon } = layoutSetup({ cols: 80 });
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 78, row: 1 }) });
addon.appendText('a你b');
expect([0, 1, 2, 3].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 78, row: 1 },
{ col: 0, row: 2 },
{ col: 2, row: 2 },
{ col: 3, row: 2 },
]);
expect(addon.getInputEndAnchor()).toEqual({ col: 3, row: 2 });
});
it('maps multiple wide wraps including an empty prompt line', () => {
const { addon } = layoutSetup({ cols: 5 });
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 4, row: 1 }) });
addon.appendText('你好世界a你b');
expect([0, 1, 2, 3, 4, 5, 6, 7].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 0, row: 2 },
{ col: 2, row: 2 },
{ col: 0, row: 3 },
{ col: 2, row: 3 },
{ col: 4, row: 3 },
{ col: 0, row: 4 },
{ col: 2, row: 4 },
{ col: 3, row: 4 },
]);
});
it('maps ZWJ code points and combining marks without accepting surrogate interiors', () => {
const { addon, mock } = layoutSetup();
Object.assign(mock.terminal, {
unicode: {
getStringCellWidth: (ch: string) => (ch === '\u200d' || ch === '\u0301' ? 0 : ch.length === 2 ? 2 : 1),
},
});
addon.appendText('👩\u200d💻e\u0301x');
expect([0, 1, 2, 3, 4, 5, 6, 7, 8].map((offset) => addon.getInputAnchor(offset))).toEqual([
{ col: 2, row: 1 },
null,
{ col: 4, row: 1 },
{ col: 4, row: 1 },
null,
{ col: 6, row: 1 },
{ col: 7, row: 1 },
{ col: 7, row: 1 },
{ col: 8, row: 1 },
]);
});
it('queries the composition tail but exposes only the last displayed committed text', () => {
const { addon } = layoutSetup({ cols: 8 });
addon.setFlushed(2, '😀');
addon.appendText('ab');
addon.setComposition('你好');
expect(addon.committedText).toBe('😀ab');
expect(addon.getInputAnchor(4)).toEqual({ col: 6, row: 1 });
expect(addon.getInputAnchor(5)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(6)).toEqual({ col: 2, row: 2 });
expect(addon.getInputEndAnchor()).toEqual({ col: 2, row: 2 });
addon.setFlushed(2, 'zz', false);
expect(addon.committedText).toBe('😀ab');
expect(addon.state).not.toHaveProperty('committedText');
expect(addon.state).not.toHaveProperty('composition');
});
it('uses upward growth and hides tail-sliced caret rows', () => {
const { addon } = layoutSetup({ cols: 6, rows: 4, promptRow: 3 });
addon.appendText('abcdefghijkl'); // abcd / efghij / kl
expect(addon.getInputAnchor(0)).toEqual({ col: 2, row: 1 });
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 3 });
addon.setRowLimit(2);
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.getInputAnchor(3)).toBeNull();
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 0 });
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 1 });
expect(addon.getInputAnchor(12)).toEqual({ col: 2, row: 1 });
});
it('keeps the final offset at the right edge of a full final row', () => {
const { addon } = layoutSetup({ cols: 6 });
addon.appendText('abcdefghij');
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
expect(addon.getInputAnchor(10)).toEqual({ col: 6, row: 2 });
expect(addon.getInputEndAnchor()).toEqual({ col: 6, row: 2 });
});
it('does no width measurement for a redundant render or an anchor query', () => {
const { addon, mock } = layoutSetup();
const width = vi.fn((ch: string) => (ch === '你' ? 2 : 1));
Object.assign(mock.terminal, { unicode: { getStringCellWidth: width } });
addon.setFlushed(3, 'a你b');
expect(width).toHaveBeenCalled();
width.mockClear();
addon.setFlushed(3, 'a你b'); // same key, unlike forced rerender()
expect(addon.getInputAnchor(1)).toEqual({ col: 3, row: 1 });
expect(addon.getInputAnchor(3)).toEqual({ col: 6, row: 1 });
expect(addon.committedText).toBe('a你b');
expect(width).not.toHaveBeenCalled();
});
it('rejects invalid offsets and clears visual correspondence on hide and disposal', () => {
const { addon, mock } = layoutSetup();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
addon.appendText('abc');
for (const offset of [-1, 4, 0.5, NaN, Infinity]) expect(addon.getInputAnchor(offset)).toBeNull();
mock.setScroll(0, 30);
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
mock.setScroll(0, 0);
addon.rerender();
expect(addon.committedText).toBe('abc');
addon.clear();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
addon.appendText('x');
addon.dispose();
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
});
it('clears offset anchors and committed text on render failure', () => {
const { addon } = layoutSetup();
addon.appendText('abc');
addon.setPrompt({
type: 'custom',
find: () => {
throw new Error('buffer unavailable');
},
});
expect(addon.getInputAnchor(0)).toBeNull();
expect(addon.committedText).toBe('');
expect(addon.pendingText).toBe('abc');
});
});
+2
View File
@@ -114,6 +114,7 @@ appendFileSync(
// 4. Minify frontend assets
run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --outfile=dist/web/public/input-cjk.js --allow-overwrite');
run('minify mobile-ime-preview.js', 'npx esbuild dist/web/public/mobile-ime-preview.js --minify --outfile=dist/web/public/mobile-ime-preview.js --allow-overwrite');
run('minify terminal-ios-native-input.js', 'npx esbuild dist/web/public/terminal-ios-native-input.js --minify --outfile=dist/web/public/terminal-ios-native-input.js --allow-overwrite');
run('minify terminal-keycode229-recovery.js', 'npx esbuild dist/web/public/terminal-keycode229-recovery.js --minify --outfile=dist/web/public/terminal-keycode229-recovery.js --allow-overwrite');
run('minify i18n.js', 'npx esbuild dist/web/public/i18n.js --minify --outfile=dist/web/public/i18n.js --allow-overwrite');
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
@@ -145,6 +146,7 @@ console.log('\n[build] content-hash cache busting');
'keyboard-accessory.js',
'input-cjk.js',
'mobile-ime-preview.js',
'terminal-ios-native-input.js',
'terminal-keycode229-recovery.js',
'sanitize-html.js',
'tab-layout-browser.js',
+1 -1
View File
@@ -17,7 +17,7 @@
* this script adds is FRESHNESS and independence from install time: a checkout
* installed with `--ignore-scripts`, or one borrowing another tree's
* `node_modules`, never ran postinstall, and an edit to the zerolag package after
* install leaves the bundle stale. It runs as `pretest:mobile`.
* install leaves the bundle stale. It runs as `pretest:mobile` and `pretest:browser`.
*
* Mirrors the vendor steps in scripts/build.mjs, targeting the source tree. Same
* inputs and output names, so the page markup needs no test-only branch. That
+5 -3
View File
@@ -10,7 +10,7 @@
**Session lineage lines** (tab → tab it spawned, `sessionLineageLines`, per-device, desktop default ON): a create request may name its spawner via a `parentSessionId` body field or the `X-Codeman-Parent-Session` header; `resolveParentSessionId()` (route-helpers.ts) resolves it (exact id or unique ≥8-char prefix, live, visible, same owner) and ⚠️ anything unresolvable is DROPPED, never a 400. Rides `toState()`, no new SSE event. ⚠️ Rendering is a LAYER on the existing SVG pass (`_appendLineageConnectionLines` at the tail of `_updateConnectionLinesImmediate()`) and draws EVERY family, emphasizing the selected tab's (what it spawned, and the family it was spawned into: `lineage-family--focus`, thicker, opaque, drawn last; lanes stay in strip order), so a selection change must redraw (`_updateActiveTabImmediate`, gated on `_lineageTotalEdges`), and again on the strip's size `transitionend` (the active tab widens for ~150ms after the redraw). Geometry is pure in `computeLineageTree()`: one rounded orthogonal tree per spawning tab, every route starting at the PARENT (siblings share the trunk exactly), routed ONLY through the gaps between tab rows plus a spine left of every row, so it never crosses a tab or the terminal. ⚠️ That room is reserved in CSS by `.session-tabs.lineage-tree` (`_syncLineageGutter()`, called before the wrap is measured), keyed on whether ANY family exists, never on the selection, or every tab switch would resize the header and the PTY. Colors are keyed on the SPAWNING tab, claimed in strip order for every family, and memoized (never by draw index or selection order). ⚠️ Desktop only (z-index vs the fixed mobile header). ⚠️ Paths must keep `data-agent-id="lineage:<childId>"` (the entrance animation queries it); skip endpoints scrolled out of the strip. → [architecture-invariants#session-lineage-lines-tab--tab-it-spawned](../../docs/architecture-invariants.md#session-lineage-lines-tab--tab-it-spawned)
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same keyCode-229 soft-keyboard controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
**Split-pane sessions** (`showSplitButton`, header button, default OFF, desktop-only at 1180px (width alone, so a wide Android tablet clears it), per-device): a second live session ("Pane B") beside the active one, in a `TerminalTile` (terminal-tile.js; the picker, divider and auto-collapse stay in terminal-split.js) with its own xterm + WebSocket, resizable via a draggable divider. Pane B reconnects after a drop, sends input through the exactly-once queue over its own socket (`_registerInputSocket`), has clickable paths and image paste, and owns its geometry (no 40x10 floor, `zc` columns adopted, font changes call `tile.fit()`). ⚠️ Only typed input enters that persisted queue: xterm's query replies are dropped and focus/mouse reports go out ephemeral. ⚠️ App-level terminal actions find their pane through `_focusedPane()` (the terminal focused last), never `this.terminal`. Still plainer than the primary pane (no local-echo overlay, CJK IME textarea or touch handlers), though it wires the same soft-keyboard input as the main pane: the iOS native-input owner (`_iosNativeInput`, #830) on iOS WebKit touch, otherwise the keyCode-229 controller (Android autocorrect, #441/#541), and NOT persisted across reloads. The tile grid (below) reuses `TerminalTile`, and the two are never open together. → [architecture-invariants#split-pane-sessions](../../docs/architecture-invariants.md#split-pane-sessions)
**Tile grid** (`showTileGridButton`, header Tiles button + `Ctrl+Shift+G`, default ON on desktop and OFF on handhelds and touch-primary tablets (primary pointer coarse, `getDefaultSettings()`; a touchscreen laptop keeps ON), desktop-only at 1180px, per-device; tile-grid.js, design `docs/tile-grid-plan.md`): 1 to 6 live sessions side by side (the cap is ONE constant, `TILE_GRID_MAX` in constants.js, owner decision; the layout table still covers 7 to 9, unreachable), each a `TerminalTile` with a header (state dot, harness logo, name, model, menu, zoom, ×; no +, owner decision), laid out by count (`CodemanTileGrid`, constants.js) with draggable column/row dividers, zoom (tmux-style), an Attach overlay, and per-browser persistence (`codeman:tile-grid`, localStorage only: cells with `null` holes, `count`, focus, user zoom, divider fractions, never content; written on every change, kept by EVERY close, restored INSIDE `handleInit` in place of the single-view select, so the main terminal never loads on that page load). While the grid is open the main terminal is PARKED: `activeSessionId` is the focused tile's session, and every main-terminal path that would write, fetch, resize or reconnect stands aside through `_tilesOwnTerminal()` (the WebGL long-task observer included). ⚠️ Every capture a tile fetches (initial, reconnect refresh, `{t:'r'}`, history pull) goes through ONE `TileLoadQueue` (concurrency 1, a deadline covering the body), because each is a synchronous tmux call on the server. ⚠️ Only a USER-initiated pick of a non-tiled session (or `leaveTiles`, a followed link) leaves the grid; an `auto` selection never collapses it, and every app-driven fallback (close, delete, restore) picks a tile. A caller of `closeTileGrid({ reselect: false })` must null `activeSessionId` before any `_cleanupPreviousSession`, or the parked terminal's stale content is saved as a snapshot. ⚠️ The grid and the split are never open together. ⚠️ Tile chords go through `tileShortcutFor` and are swallowed in every xterm key handler BEFORE the Shift+Enter gate; the toggle follows `showTileGridButton` (owner decision: OFF makes the chord inert, it passes through like any unbound key). ⚠️ The Tiles button's click and Ctrl+Shift+G are ONE function, `toggleTileGrid` (owner decision): they open the grid AT ONCE on `tileGridOpenSet` (constants.js): the stored grid EXACTLY as the user left it (owner decision 11: `restoreTileGridCells`, never filled to the count nor trimmed to the window; a cell whose session is gone since is filled from the ranking, a hole the user made stays), else an open split's two, else the open sessions as `rankTileSessions` orders them (working first, keyed off `lastSubmitAt` ONLY, then needing input, then most recent; `_mobileOverviewState`'s states), the active one focused, filled to the remembered count (`codeman:tile-count`, default 6, at most `_tileGridLimit()`) by `tileGridSetForCount`, never a menu. ⚠️ `removeTile(..., { gone: true })` (a session deleted, popped out or refused) keeps the stored `count` so the next open refills that cell; a removal by hand lowers it. Right-click is the 2 / 4 / 6 count menu (`openTileCountMenu`, owner decision 10), which owns its Escape. The button has no native title: its hover card (`_installTileGridHint`, `#tileGridHint`) says it, is its `aria-describedby` (always present, hidden, kept current) and hides in the capture phase on any press, click or right-click, so the menu never opens beside it. ⚠️ The open, the count menu and the toggle's close animate opacity and transform only (the close leaves an inert cloned still copy until the single view's selection settles, at most 700 ms); nothing moves under `prefers-reduced-motion`. ⚠️ Opening builds one tile terminal per frame (`_connectTilesPaced`), so `openTileGrid` returns before the terminals exist: focus is handed over in `_connectTile` (`focusOnConnect`). ⚠️ A divider drag reflows locally per frame and sends ONE resize per affected tile at pointer-up. ⚠️ The grid is CELLS (owner: an empty cell can be any cell): `grid.cells` (id or `null`) is the one source of truth, `grid.ids` a derived getter, never written; the shape still comes from the tile count, a shape change goes through `fitTileCells`, and the stored `ids` carry the cells with `null` holes. ⚠️ A tile moves (its header dragged or its tab dropped onto another tile or an empty cell, `Ctrl+Shift+Arrows`) ONLY through `_reorderTiles`: never a remount, reconnect or reload, and since sizes belong to the cells only a tile whose cell size changed fits; off while a tile is zoomed. The header drag carries its own type, never text, and is not `draggedTabId`; the header focuses on click, never on press, so a cancelled drag changes nothing. The arrow chords skip text fields. ⚠️ Sessions Run from this tab join the open grid (`_joinTileGridFromRun`, called from `_ensureCreatedSessionVisible`); sessions created elsewhere never do. SuchLine truncated
@@ -32,6 +32,8 @@
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order is the `<script>` order in `index.html` (each module's `@loadorder` tag mirrors it). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The edit-based diff described below is settled first at that keydown, so the drain decides with the evidence the timer had and Enter's textarea clear cannot turn the pending line into DELs. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. The same module replaces xterm's `_handleAnyTextareaChanges` (an append-only `newValue.replace(oldValue, '')` diff) with an edit-based one, so an Android autocorrect on space (delete + insert) reaches the PTY once instead of duplicating the line; ⚠️ that diff is settled at the NEXT keydown, before xterm handles that key, because xterm clears the textarea for Enter and a pending diff would then send one DEL per character ahead of the submitted line (except a composition xterm finalizes synchronously at that key, which stays xterm's). ⚠️ Every xterm that takes keyboard input wires its OWN controller from this module (`create()` returns null unless `matchMedia('(pointer: coarse)')` matches or the user agent is Android, so a desktop dead key is not forwarded twice, #716, while an Android device whose mouse, trackpad cover or stylus Chromium reports as the fine primary pointer keeps the soft-keyboard recovery): the primary pane (terminal-ui.js `initTerminal()`) and each `TerminalTile` (terminal-tile.js `_createKeyCode229Recovery()`, so every grid tile and the split's Pane B, which a wide Android tablet reaches), each on its own textarea, composition helper and session; in both, `handleKeyEvent` must run ABOVE the custom key handler's keyCode-229 early return, and `notifyCanonicalData` sits in the onData lambda, never in the send path the recovered bytes also take. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea.
**iOS native input ownership (#830)**: `terminal-ios-native-input.js` loads after `mobile-ime-preview.js` and before the terminal hosts. `MobileImePreview.isIosWebKitTouch` is the shared gate: supported main panes and tiles install `_iosNativeInput`, never `_keyCode229Recovery`. The owner retains the native textarea line, reconciles replacements/deletions as one transaction, and projects trackpad selection through `.ios-native-caret` without sending arrows. The main marker uses the local-echo layout anchor while the overlay owns the line; missing overlay geometry hides it. External producers call `_prepareExternalInput(pane, reason)` before sending. Toolbar Enter uses `submitFromToolbar()`, capturing the focused pane once; text, the 80ms gap and CR reserve that session's FIFO even across a switch. Browser regressions: `test/ios-native-input.browser.test.ts`; run `node scripts/prepare-test-vendor.mjs` first. → [ios-native-input](../../docs/ios-native-input.md)
**Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows, connection lines and tile-grid tiles, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` / `data-tile-anim` on `<html>`; the default `legacy` theme short-circuits every hook (tiles keep the grid's own `settle`). ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Every animation setting lives in App Settings → **Animations** (`#settings-animations`); put new ones there. ⚠️ Tiles are OFF by default (Animations → Tile Animations, default `settle` = the grid's own fade, no screen beat); a theme only presets it. A tile's FRAME animates transform/opacity only (six at once, no filter) with `tile-enter*`/`tile-leave*` keyframe names (what the mount and the still copy listen for); its SCREEN replays the pane style on `.tile-body.term-enter`; a reload's restore always settles. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](../../docs/architecture-invariants.md#entrance-animations)
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. With the opt-in tab "+" on (`showTabNewButton`, `html.tabs-show-new`) a third icon joins them and the reserve grows to 68px, still under the 80px `max-width`. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
@@ -76,7 +78,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Shell keyboard accessory bar + one-shot Ctrl** (`keyboard-accessory.js`): a shell-mode session swaps the mobile accessory bar for terminal controls; `setMode()` records `extendedKeyboardBar` as the base layout and `refreshForActiveSession()` resolves base-vs-shell. ⚠️ Ctrl is a one-shot modifier applied in `terminal.onData` (after `shouldSuppressTerminalQueryResponse`, before every send path), and must skip `isTerminalFocusOrMouseReport()` chunks. ⚠️ It must disarm on use, second tap, any other accessory key, session switch, keyboard dismissal and layout swap. ⚠️ `_handleCjkInput()` must apply it too (the CJK textarea bypasses onData). Mapping: `ctrlByteFor()`. ⚠️ mobile.css's light-skin repaint must keep excluding `.accessory-btn:not(.armed)` or the armed state is invisible. → [architecture-invariants#shell-keyboard-accessory-bar-and-one-shot-ctrl](../../docs/architecture-invariants.md#shell-keyboard-accessory-bar-and-one-shot-ctrl)
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame via `_sendInputAsync` WITHOUT `useMux`, then a separate delayed Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
**Mobile prompt composer** (`keyboard-accessory.js`): the agent bars' Paste key is **Compose**, a native multiline dialog where only **Send** submits (the shell bar keeps plain Paste). Opening it adopts the whole terminal prompt (`_takePendingLocalEcho`), erasing the flushed prefix with backspaces counted in code points. ⚠️ Drafts are per-session and in memory only (`_composerDrafts`), never persisted (prompts carry secrets). ⚠️ Delivery is a hand-built bracketed-paste frame enqueued on the session FIFO (`_enqueueInput`, `_sendBracketedPaste()`) WITHOUT `useMux`, then a `gap` and a separate Enter WITH it; never `terminal.paste()`, and the frame must never take the mux fallback (`TmuxManager.sendInput()` strips every `\r`, the frame's line separator, so the lines weld into one inside a second pair of markers and get submitted). ⚠️ `_composerMaxLength` must stay derived from `MAX_INPUT_LENGTH` minus the markers, or an oversized frame wedges the durable queue. ⚠️ The composer overlay needs its own gutter restatement after the fold rules. The textarea carries `dir="auto"`, so a prompt written in Persian, Arabic or Hebrew lays out right to left from its first letter (#715). Test: `test/mobile-prompt-composer.test.ts`. → [architecture-invariants#mobile-prompt-composer](../../docs/architecture-invariants.md#mobile-prompt-composer)
**Terminal resilience**: a replay clear is the queued in-stream `\x1bc` in `_resetTerminalForReplay()`, never `reset()`/`clear()` (queued bytes fuse into the snapshot); the renderer watchdog `_kickRenderer()` reads xterm privates, pinned by `test/xterm-private-api.test.ts` against the resolved lockfile version; every terminal capture fetch has a deadline that covers the BODY (`_fetchTerminalCapture`). → [architecture-invariants#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines](../../docs/architecture-invariants.md#terminal-resilience-replay-clears-renderer-liveness-fetch-deadlines)
@@ -86,7 +88,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**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. 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.
**`sendEnterKey()` must call `submitFromToolbar()`**, never a raw input POST. The semantic submit captures the focused pane once and calls `_prepareExternalInput` to settle/reset native ownership. For the main pane, it reuses local-echo Enter handling: pending text, the 80ms gap and the CR are reserved atomically in the captured session's FIFO. For a tile, the CR goes to the tile's session. A session switch cannot redirect the delayed CR, and a missing pane must not fall back to another session. 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) then Enter, on the session `CjkInput` captured for that text (`_sendCjkPrompt` reserves the text, 120 ms gap and Enter on that session's FIFO).
⚠️ **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.
+99 -22
View File
@@ -4134,15 +4134,85 @@ class CodemanApp {
}
}
// Session-owned reservations survive pane switches and terminal replacement.
_inputFifo(sessionId) {
if (!this._inputFifos) this._inputFifos = new Map();
if (!this._inputFifos.has(sessionId)) this._inputFifos.set(sessionId, { ops: [], timer: null, draining: false });
return this._inputFifos.get(sessionId);
}
_enqueueInput(sessionId, ops) {
if (!sessionId || (this.sessions && !this.sessions.has(sessionId))) return;
const fifo = this._inputFifo(sessionId);
fifo.ops.push(...ops);
this._drainInputFifo(sessionId, fifo);
}
_drainInputFifo(sessionId, fifo) {
if (fifo.timer !== null || fifo.draining) return;
fifo.draining = true;
try {
while (fifo.ops.length && this._inputFifos.get(sessionId) === fifo) {
const op = fifo.ops.shift();
if (op.gap !== undefined) {
fifo.timer = setTimeout(() => {
fifo.timer = null;
if (this._inputFifos.get(sessionId) === fifo) this._drainInputFifo(sessionId, fifo);
}, op.gap);
break;
}
if (op.key) {
fetch(`/api/sessions/${sessionId}/send-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: op.key }),
}).catch(() => {});
} else if (op.write) {
this._enqueueReliableInput(sessionId, op.write, { useMux: op.useMux });
}
}
} finally {
fifo.draining = false;
}
}
_sealPendingInput(sessionId) {
const timer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(timer);
this._inputFlushTimeout?.delete(sessionId);
const text = this._pendingInput?.get(sessionId);
this._pendingInput?.delete(sessionId);
if (text) this._enqueueInput(sessionId, [{ write: text }]);
}
_settleMainInput(reason) {
const sessionId = this.activeSessionId;
this._iosNativeInput?.settle?.();
this._sealPendingInput(sessionId);
if (sessionId) this._flushLocalEchoTo(sessionId);
this._iosNativeInput?.reset?.(reason);
this._mobileImePreview?.reset?.();
this._mobileImeCommitOutputSeq = null;
this._localEchoOverlay?.clear();
}
/**
* Public input entry point — name/signature kept for all call sites.
* Records the input durably, then delivers it reliably (exactly-once). Never
* blocks the keystroke flush; never silently drops on a half-open socket.
* Seals the session's batched keystrokes, then enqueues the input on that
* session's FIFO, which hands it to the durable exactly-once layer
* (_enqueueReliableInput). It can wait behind an earlier `gap` (a delayed
* Enter); it never silently drops on a half-open socket.
* @param {string} sessionId
* @param {string} input
* @param {{useMux?: boolean}} [opts] - useMux only affects the POST fallback.
*/
_sendInputAsync(sessionId, input, opts) {
this._sealPendingInput(sessionId);
this._enqueueInput(sessionId, [{ write: input, ...opts }]);
}
// Durable delivery starts here; FIFO gaps order enqueueing, not ACK completion.
_enqueueReliableInput(sessionId, input, opts) {
if (!sessionId || !input) return;
const useMux = opts?.useMux === true;
// Both transports refuse a frame over the server's limit (issue #484), and a
@@ -9385,6 +9455,24 @@ class CodemanApp {
// `skipSnapshot`: the tile grid opening on the session it parks
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
this._settleMainInput('session');
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
// exact view on switch-back rather than replaying codex's byte stream, which
@@ -9434,24 +9522,6 @@ class CodemanApp {
// Close WebSocket for previous session (new one opens after buffer load)
this._disconnectWs();
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
// Clean up flicker filter state when switching sessions
this._clearTimer('flickerFilterTimeout');
this.flickerFilterBuffer = '';
@@ -9497,7 +9567,6 @@ class CodemanApp {
if (ta) ta.dispatchEvent(new CompositionEvent('compositionend', { data: '' }));
}
} catch {}
this._flushLocalEchoTo(this.activeSessionId);
this._localEchoOverlay?.clear();
// Predictions are ephemeral + already sent: nothing to save/restore
// across a tab switch (unlike the buffer overlay's setFlushed machinery)
@@ -10017,7 +10086,7 @@ class CodemanApp {
// hides this one from it. Flush first or the characters are cleared
// unread. The geometry replay re-enters here with no gesture behind it,
// so on a touch device this fires while the user is still typing.
this._flushLocalEchoTo(sessionId);
this._settleMainInput('session');
this.activeSessionId = null;
}
// Focus terminal SYNCHRONOUSLY before any await — iOS Safari only honors
@@ -10830,6 +10899,14 @@ class CodemanApp {
this._activeRename.cancel();
}
this.sessions.delete(sessionId);
const fifo = this._inputFifos?.get(sessionId);
clearTimeout(fifo?.timer);
this._inputFifos?.delete(sessionId);
const inputTimer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(inputTimer);
this._inputFlushTimeout?.delete(sessionId);
this._pendingInput?.delete(sessionId);
this._lastKeystrokeTime?.delete(sessionId);
// Remove from tab order
const orderIndex = this.sessionOrder.indexOf(sessionId);
if (orderIndex !== -1) {
+9 -5
View File
@@ -7,7 +7,7 @@
*
* For drag-and-drop: listens on the terminal container for file drops.
*
* @dependency app.js (uses global `app` for sendInput, activeSessionId, showToast)
* @dependency app.js (uses global `app` for _sendInputAsync, _prepareExternalInput, activeSessionId, showToast)
* @dependency panels-ui.js (provides showToast)
*/
@@ -142,6 +142,8 @@ Object.assign(CodemanApp.prototype, {
return;
}
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'toolbar-attachment');
const stillActive = this.activeSessionId === sessionId;
// The overlay holds the prompt only while local echo actually owns it. A
// session handed back to plain PTY echo by a composer nav key (echo
@@ -152,6 +154,7 @@ Object.assign(CodemanApp.prototype, {
// goes to the PTY like any other background write.
const overlayOwnsPrompt =
stillActive &&
(!pane || (pane.isPrimary && pane.sessionId === sessionId)) &&
!this._tilesOwnTerminal?.() &&
this._localEchoEnabled &&
this._localEchoOverlay &&
@@ -394,10 +397,11 @@ Object.assign(CodemanApp.prototype, {
const paths = results.filter(Boolean);
if (paths.length > 0 && options.insert !== false) {
// Insert all paths in one shot, space-separated, in selection order, into
// the session the batch was uploaded TO. Not sendInput(): it re-reads
// activeSessionId, and after the awaits above that is whatever tab the
// user switched to mid-upload, so the paths landed in the wrong session.
// Same delivery sendInput() uses (durable queue, useMux for the POST path).
// the session the batch was uploaded to, captured before the awaits above,
// not the active tab the user may have switched to mid-upload.
// Delivery uses the durable session-bound path, with useMux for the POST fallback.
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'upload-insert', { flushEcho: true });
this._sendInputAsync(sessionId, paths.join(' '), { useMux: true });
}
+1
View File
@@ -4547,6 +4547,7 @@
<script defer src="mobile-ime-preview.js"></script>
<!-- Forwards committed input events that xterm drops on Android/GBoard soft keyboards. Must precede terminal-ui.js. -->
<script defer src="terminal-keycode229-recovery.js"></script>
<script defer src="terminal-ios-native-input.js"></script>
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
<script defer src="sanitize-html.js"></script>
<!-- Owner tab layout projection (grouped vertical rail); pure, read by app.js. -->
+76 -29
View File
@@ -17,10 +17,10 @@
* 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.
* belongs to one session: a captured target takes precedence over _owner when
* clear() stashes it, and restoreDraft() brings it back when that session is
* shown again, except a clear({ discard: true }) (the keyboard bar's clear-line
* key), which throws it away.
*
* ## Android IME challenge
*
@@ -65,6 +65,9 @@
const CjkInput = (() => {
let _textarea = null;
let _send = null;
let _captureTarget = null;
let _target;
let _hasTarget = false;
let _initialized = false;
let _composing = false;
let _flushTimer = null;
@@ -88,10 +91,10 @@ const CjkInput = (() => {
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.
// Send-on-Enter: the session last shown, set by restoreDraft. A captured
// target takes precedence; otherwise clear() stashes a held draft under this
// owner, so paths that drop the active session before the next cleanup
// (goHome, _replaceTileGrid and _onTileAdoptedElsewhere) keep the answer.
let _owner = null;
const _listeners = {};
@@ -195,8 +198,21 @@ const CjkInput = (() => {
return str.replace(/​/g, '');
}
function _holdTarget() {
if (!_hasTarget) {
_target = _captureTarget?.();
_hasTarget = true;
}
}
function _targetForSend() {
return _hasTarget ? _target : _captureTarget?.();
}
function _resetToPhantom() {
_heldBase = '';
_target = undefined;
_hasTarget = false;
// Skip redundant writes: every programmatic value/selection mutation can
// desync an Android IME's input session (InputConnection) — after which
// the keyboard composes in its own UI but NO events ever reach the page.
@@ -236,7 +252,7 @@ const CjkInput = (() => {
const val = _strip(_textarea.value);
_t(`flush ${val ? 'send len=' + val.length : 'empty'}`);
if (val) {
_send(val);
_send(val, _targetForSend());
}
_resetToPhantom();
}
@@ -273,14 +289,15 @@ const CjkInput = (() => {
* (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) {
* even `1\r` in one write sits unsent. Returns false when the text is refused
* (too long, no session), so the field keeps it. `sessionId` is the target
* captured when the text started (see _targetForSend). */
function _sendHeld(val, sessionId) {
if (!_sendPrompt) {
_t('hold send DROP no-prompt-path');
return false;
}
return _sendPrompt(val) !== false;
return _sendPrompt(val, sessionId) !== false;
}
/** Enter: send what the field holds (or a bare Enter when it is empty) and
@@ -296,11 +313,11 @@ const CjkInput = (() => {
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;
if (!_sendHeld(val, _targetForSend())) return false;
} else if (val) {
_send(val + '\r');
_send(val + '\r', _targetForSend());
} else {
_send('\r');
_send('\r', _targetForSend());
}
_resetToPhantom();
if (_hold) _autoGrow();
@@ -336,10 +353,17 @@ const CjkInput = (() => {
return;
}
_t('hold ctrl key');
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
_send(now[at]);
// The control key goes to the session this field's text was captured for;
// with no draft left, the next answer captures its own destination.
const target = _targetForSend();
if (!before) {
_resetToPhantom();
} else {
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
}
_send(now[at], target);
}
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
@@ -353,7 +377,7 @@ const CjkInput = (() => {
const wasEmpty = !_heldBase;
_heldBase = _strip(_textarea.value);
if (!_heldBase) {
if (wasEmpty) _send('\x7f');
if (wasEmpty) _send('\x7f', _targetForSend());
_resetToPhantom();
} else if (!_textarea.value.startsWith(PHANTOM)) {
// Backspace at the very start of the text deleted the phantom: put it
@@ -397,11 +421,12 @@ const CjkInput = (() => {
}
return {
init({ send, sendPrompt = null }) {
init({ send, sendPrompt = null, captureTarget }) {
if (_initialized) this.destroy();
_send = send;
_sendPrompt = sendPrompt;
_captureTarget = captureTarget;
_composing = false;
_printableKeydownAt = null;
_flushTimer = null;
@@ -461,6 +486,7 @@ const CjkInput = (() => {
// ── Composition tracking (keyboard IME — works for CJK typing) ──
_listeners.compositionstart = () => {
_t(`compstart ${_vdesc(_textarea.value)}`);
_holdTarget();
_composing = true;
_printableKeydownAt = null;
_cancelDebouncedFlush();
@@ -515,7 +541,7 @@ const CjkInput = (() => {
// and the arrows already follow.
if (e.ctrlKey && CTRL_KEYS[e.key] && (!_hold || _isEffectivelyEmpty())) {
e.preventDefault();
_send(CTRL_KEYS[e.key]);
_send(CTRL_KEYS[e.key], _targetForSend());
return;
}
@@ -527,7 +553,7 @@ const CjkInput = (() => {
// Backspace: forward to PTY when no real text in textarea
if (e.key === 'Backspace' && _isEffectivelyEmpty()) {
e.preventDefault();
_send('\x7f');
_send('\x7f', _targetForSend());
_resetToPhantom();
return;
}
@@ -539,14 +565,14 @@ const CjkInput = (() => {
const modNav = _modifiedNavSequence(e);
if (modNav) {
e.preventDefault();
_send(modNav);
_send(modNav, _targetForSend());
return;
}
// Arrow/function keys: forward to PTY when no real text
if (PASSTHROUGH_KEYS[e.key] && _isEffectivelyEmpty()) {
e.preventDefault();
_send(PASSTHROUGH_KEYS[e.key]);
_send(PASSTHROUGH_KEYS[e.key], _targetForSend());
return;
}
@@ -554,6 +580,7 @@ const CjkInput = (() => {
// the committed text. Let the browser/IME produce the input event so
// full-width punctuation and other layout transforms are preserved.
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey && _isEffectivelyEmpty()) {
_holdTarget();
_printableKeydownAt = performance.now();
return;
}
@@ -565,6 +592,7 @@ const CjkInput = (() => {
_t(`input ${e.inputType || '?'} ic=${e.isComposing} c=${_composing} ${_vdesc(_textarea.value)}`);
const printableKeydownAt = _printableKeydownAt;
_printableKeydownAt = null;
if (!_isEffectivelyEmpty()) _holdTarget();
// ── Stuck-composition recovery ──
// Some IMEs (WeChat/Sogou keyboards) fire compositionstart without a
// matching compositionend. A stale _composing=true blocks every flush
@@ -591,7 +619,7 @@ const CjkInput = (() => {
if (_composing) return;
if (_isEffectivelyEmpty()) {
_cancelDebouncedFlush();
_send('\x7f');
_send('\x7f', _targetForSend());
_resetToPhantom();
return;
}
@@ -640,6 +668,15 @@ const CjkInput = (() => {
return this;
},
/** Commit settled text before pane ownership changes; never send composition. */
flushNow() {
if (!_initialized || !_textarea) return;
_cancelDebouncedFlush();
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
_flush();
},
/**
* Discard pending text and timers (e.g. on session switch, so stale text
* can't flush into the wrong session). Restores the phantom so backspace
@@ -653,13 +690,15 @@ const CjkInput = (() => {
// 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);
if (_hasTarget && _target) _drafts.delete(_target);
} 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 sessionId = _hasTarget && _target ? _target : _owner;
if (_hold && sessionId) {
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(_owner, draft);
if (draft.trim()) _drafts.set(sessionId, draft);
}
_owner = null;
}
@@ -748,6 +787,7 @@ const CjkInput = (() => {
* clear(); restoreDraft() puts it back when that session is shown again.
*/
stashDraft(sessionId) {
if (_hasTarget && _target) sessionId = _target;
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
@@ -771,6 +811,10 @@ const CjkInput = (() => {
_textarea.value = PHANTOM + draft;
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
_heldBase = draft;
// The restored text belongs to this session: Enter after a focus move to
// another pane must still send it here (see _targetForSend).
_target = sessionId;
_hasTarget = true;
_autoGrow();
},
@@ -802,6 +846,9 @@ const CjkInput = (() => {
window.cjkActive = false;
_composing = false;
_printableKeydownAt = null;
_target = undefined;
_hasTarget = false;
_captureTarget = null;
for (const key of Object.keys(_listeners)) delete _listeners[key];
_initialized = false;
},
+91 -60
View File
@@ -33,7 +33,7 @@
* @globals {class} FocusTrap
*
* @dependency mobile-handlers.js (MobileDetection.isTouchDevice)
* @dependency app.js (uses global `app` for sendInput, activeSessionId, terminal)
* @dependency app.js (uses global `app` for _enqueueInput, _sendInputAsync, _prepareExternalInput, activeSessionId, terminal)
* @loadorder 5 of 15 — loaded after notification-manager.js, before app.js
*/
@@ -1189,7 +1189,7 @@ const KeyboardAccessoryBar = {
/** Handle accessory button actions */
handleAction(action, btn) {
if (typeof app === 'undefined' || !app.activeSessionId) return;
if (typeof app === 'undefined') return;
// Any key other than Ctrl itself spends the modifier. It is a one-shot for
// the next TYPED character, so an accessory key tapped in between (Esc, an
@@ -1228,10 +1228,12 @@ const KeyboardAccessoryBar = {
// Tab means "complete what I just typed", but with local echo the typed
// text is still buffered in the overlay and has never reached the PTY —
// a bare \t would ask the CLI to complete an empty composer.
this.flushPendingThen(() => this.sendKey('\t'));
this.flushPendingThen('\t');
break;
case 'shift-tab':
this.sendKey('\x1b[Z');
// Cycles a mode, never edits the composer: leave the unsent draft in the
// overlay, as a typed Shift+Tab does.
this.sendKey('\x1b[Z', { keepDraft: true });
break;
case 'ctrl-o':
this.sendKey('\x0f');
@@ -1268,6 +1270,7 @@ const KeyboardAccessoryBar = {
this.pickPath();
break;
case 'clear-input':
this._prepareInput(undefined, 'accessory-clear');
app.clearTerminalInput?.();
break;
case 'dismiss':
@@ -1331,38 +1334,53 @@ const KeyboardAccessoryBar = {
this.element.classList.toggle('codex-enabled', this._isCodexSession());
},
/** Capture the destination before settling native input; background drafts
* must never reset a different pane's owner. */
_prepareInput(sessionId, reason, opts) {
const target = sessionId || (typeof app._focusedPane === 'function' ? app._focusedPane()?.sessionId : app.activeSessionId);
const pane = app._paneForSession?.(target);
if (pane) {
if (opts) app._prepareExternalInput?.(pane, reason, opts);
else app._prepareExternalInput?.(pane, reason);
}
return target;
},
/** Send a slash command to the active session.
* Sends text and Enter separately so Ink processes them as distinct events. */
* Sends text and Enter separately so Ink processes them as distinct events.
* The unsent local-echo draft stays in the overlay: flushing it would submit `draft/command`. */
sendCommand(command) {
if (!app.activeSessionId) return;
// Send command text first (without Enter)
app.sendInput(command);
// Send Enter separately after a brief delay so Ink has time to process the text.
setTimeout(() => app.sendInput('\r'), 120);
const sessionId = this._prepareInput(undefined, 'accessory-command');
if (!sessionId) return;
app._enqueueInput(sessionId, [{ write: command, useMux: true }, { gap: 120 }, { write: '\r', useMux: true }]);
},
/**
* Flush whatever the local-echo overlay is still holding, THEN run `after()`.
*
* On a phone the characters you type sit in the overlay and have never
* reached the PTY, so any key that acts on "what I just typed" has to push
* that text out first or the CLI acts on an empty composer. Mirrors the
* flush the typed path performs in terminal-ui.js's onData; the 120ms is the
* same settle delay sendCommand uses, so the text lands before the key.
* Flush local echo and reserve the following key atomically in the session
* FIFO, so switching panes during the settle gap cannot redirect the key.
*/
flushPendingThen(after) {
const overlay = app._localEchoOverlay;
flushPendingThen(sequence, reason = 'accessory-key', passthrough = false) {
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
if (pane) app._prepareExternalInput?.(pane, reason);
const overlay = !pane || pane.isPrimary ? app._localEchoOverlay : null;
const pending = (app._localEchoEnabled && overlay?.pendingText) || '';
if (!pending) {
after();
return;
if (passthrough) {
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
app._echoPassthroughSessions.add(sessionId);
}
overlay.clear();
overlay.suppressBufferDetection?.();
app._flushedOffsets?.delete(app.activeSessionId);
app._flushedTexts?.delete(app.activeSessionId);
app.sendInput(pending);
setTimeout(after, 120);
const ops = [];
if (pending) {
overlay.clear();
overlay.suppressBufferDetection?.();
app._flushedOffsets?.delete(sessionId);
app._flushedTexts?.delete(sessionId);
ops.push({ write: pending, useMux: true }, { gap: 120 });
}
app._predictiveEcho?.clearPredictions();
ops.push({ write: sequence });
app._enqueueInput(sessionId, ops);
},
/**
@@ -1380,38 +1398,41 @@ const KeyboardAccessoryBar = {
* broken because what came back was never what the row showed.
*/
sendNavKey(sequence) {
if (!app.activeSessionId) return;
if (!app._echoPassthroughSessions) app._echoPassthroughSessions = new Set();
app._echoPassthroughSessions.add(app.activeSessionId);
this.flushPendingThen(() => this.sendKey(sequence));
this.flushPendingThen(sequence, 'accessory-navigation', true);
},
/** Send a special key (arrow, escape, etc.) directly to the PTY.
* Bypasses tmux send-keys -l (literal mode) since escape sequences
* must be written raw to be interpreted as key presses by Ink. */
sendKey(escapeSequence) {
if (!app.activeSessionId) return;
// Arrows/Esc move the server-side cursor and bypass onData: clear
// predictions now instead of waiting out the ~150ms off-row grace.
* must be written raw to be interpreted as key presses by Ink.
* `keepDraft` leaves the unsent local-echo draft in the overlay. */
sendKey(escapeSequence, { keepDraft = false } = {}) {
const sessionId = this._prepareInput(undefined, 'accessory-key', keepDraft ? undefined : { flushEcho: true });
if (!sessionId) return;
app._predictiveEcho?.clearPredictions();
fetch(`/api/sessions/${app.activeSessionId}/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: escapeSequence })
}).catch(() => {});
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
},
/** Browse the active session's workspace and insert a selected path without Enter. */
pickPath() {
if (!app.activeSessionId) return;
const session = app.sessions?.get(app.activeSessionId);
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
const session = app.sessions?.get(sessionId);
PathPicker.open({
title: 'Insert File or Folder Path',
sessionId: app.activeSessionId,
sessionId,
initialPath: session?.workingDir || '',
directoriesOnly: false,
onSelect: (path) => {
app.insertTerminalText?.(path);
const targetPane = app._paneForSession?.(sessionId);
if (targetPane?.isPrimary && app._localEchoPolicy === 'predict') app._predictiveEcho?.clearPredictions();
if (targetPane?.isPrimary && app._localEchoEnabled && app._localEchoOverlay && !app._echoPassthroughSessions?.has(sessionId)) {
app._prepareExternalInput?.(targetPane, 'accessory-path');
app._localEchoOverlay.appendText(path);
} else {
if (targetPane) app._prepareExternalInput?.(targetPane, 'accessory-path', { flushEcho: true });
app._sendInputAsync(sessionId, path, { useMux: true });
}
setTimeout(() => app.terminal?.focus(), 100);
},
});
@@ -1421,6 +1442,9 @@ const KeyboardAccessoryBar = {
* exists only in the overlay; flushed text already reached the PTY, so erase
* that prefix before making the textarea authoritative. */
_takePendingLocalEcho(sessionId) {
this._prepareInput(sessionId, 'accessory-compose-adopt');
const pane = app._focusedPane?.();
if (pane && (!pane.isPrimary || pane.sessionId !== sessionId)) return '';
if (!app._localEchoEnabled || !app._localEchoOverlay) return '';
const pending = app._localEchoOverlay.pendingText || '';
const overlayFlushed = app._localEchoOverlay.getFlushed?.() || {};
@@ -1458,17 +1482,15 @@ const KeyboardAccessoryBar = {
* Enter stays a separate delayed write because Codex drops keys sharing a
* PTY read with a bracketed paste. */
_sendComposedPrompt(sessionId, text) {
if (!this._sendBracketedPaste(sessionId, text, 'Prompt')) return false;
setTimeout(() => app._sendInputAsync(sessionId, '\r', { useMux: true }), 120);
return true;
return this._sendBracketedPaste(sessionId, text, 'Prompt', true);
},
/** One bracketed-paste write on the durable session-bound path, the same
* bytes a terminal paste produces, so the receiving shell or CLI takes a
* multi-line block as one edit. Never presses Enter: callers decide.
* `label` names the payload in the too-long toast. */
_sendBracketedPaste(sessionId, text, label) {
if (!sessionId || !text || typeof app._sendInputAsync !== 'function') return false;
_sendBracketedPaste(sessionId, text, label, submit = false) {
if (!sessionId || !text || typeof app._enqueueInput !== 'function') return false;
app._predictiveEcho?.clearPredictions();
// Match xterm's prepareTextForTerminal(): CR keeps embedded newlines inside
// the single-line input transport and is what terminal.paste() emitted.
@@ -1483,7 +1505,10 @@ const KeyboardAccessoryBar = {
app.showToast?.(`${label} is too long to send (maximum ${this._composerMaxLength.toLocaleString()} characters)`, 'error');
return false;
}
app._sendInputAsync(sessionId, `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}`);
this._prepareInput(sessionId, submit ? 'accessory-compose-send' : 'accessory-paste', { flushEcho: true });
const ops = [{ write: `${COMPOSER_PASTE_START}${pasteText}${COMPOSER_PASTE_END}` }];
if (submit) ops.push({ gap: 120 }, { write: '\r', useMux: true });
app._enqueueInput(sessionId, ops);
return true;
},
@@ -1500,13 +1525,15 @@ const KeyboardAccessoryBar = {
/** Open the manual agent prompt composer. Enter remains a newline; only the
* Send button submits. Cancel/backdrop/Escape preserve the per-session draft. */
composePrompt() {
if (typeof app === 'undefined' || !app.activeSessionId) return;
if (this._isShellSession()) {
if (typeof app === 'undefined') return;
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
if (app.sessions?.get(sessionId)?.mode === 'shell') {
this.pasteFromClipboard();
return;
}
const sessionId = app.activeSessionId;
const pending = this._takePendingLocalEcho(sessionId);
const saved = this._composerDrafts.get(sessionId) || '';
// A parked draft and text typed (or attached) on the prompt since are two
@@ -1614,7 +1641,7 @@ const KeyboardAccessoryBar = {
};
syncUploadUi();
try {
const paths = await app._uploadAndInsertImages(images, { insert: false });
const paths = await app._uploadAndInsertImages(images, { insert: false, sessionId });
if (paths?.length) {
const currentOverlay =
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
@@ -1687,10 +1714,13 @@ const KeyboardAccessoryBar = {
// draft would be prepended to it the next time the composer opens.
this._composerDrafts.delete(sessionId);
close({ focusTerminal: true, preserveDraft: false });
const targetPane = app._focusedPane?.();
if (targetPane?.sessionId === sessionId) app._prepareExternalInput?.(targetPane, 'accessory-compose-insert');
if (
app._localEchoEnabled &&
app._localEchoOverlay &&
app.activeSessionId === sessionId &&
(!targetPane || (targetPane.isPrimary && targetPane.sessionId === sessionId)) &&
!app._tilesOwnTerminal?.() &&
!app._echoPassthroughSessions?.has(sessionId)
) {
@@ -1737,10 +1767,11 @@ const KeyboardAccessoryBar = {
* All upload paths reuse app._uploadAndInsertImages() (image-input.js), which
* uploads to /api/sessions/:id/paste-image and inserts the saved path. */
pasteFromClipboard() {
if (typeof app === 'undefined' || !app.activeSessionId) return;
// The shell this overlay was opened for: a tab switch while it is open must
// not deliver the paste to whatever session is active at Send time.
const sessionId = app.activeSessionId;
if (typeof app === 'undefined') return;
// Capture once: switching focus while the dialog is open cannot redirect it.
const pane = app._focusedPane?.();
const sessionId = typeof app._focusedPane === 'function' ? pane?.sessionId : app.activeSessionId;
if (!sessionId) return;
// Create overlay
const overlay = document.createElement('div');
+28 -3
View File
@@ -42,7 +42,9 @@
const KEEP_COMPOSING_KEYCODES = new Set([20, 229, 16, 17, 18]);
const CONTROL_OR_LINE_BREAK = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
function isIosWebKitTouch(nav = navigator) {
// Shared with CodemanIosNativeInput.isSupported(); keep platform gating here
// because the preview predates and loads before the native input owner.
function isIosWebKitTouch(nav = global.navigator) {
const userAgent = String(nav && nav.userAgent ? nav.userAgent : '');
const platform = String(nav && nav.platform ? nav.platform : '');
const touchPoints = Number(nav && nav.maxTouchPoints ? nav.maxTouchPoints : 0);
@@ -59,6 +61,12 @@
const render = typeof options.render === 'function' ? options.render : function () {};
const clear = typeof options.clear === 'function' ? options.clear : function () {};
const onCommit = typeof options.onCommit === 'function' ? options.onCommit : function () {};
const ownsNativeInput =
typeof options.ownsNativeInput === 'function'
? options.ownsNativeInput
: function () {
return false;
};
const scheduleFrame = options.scheduleFrame || global.requestAnimationFrame.bind(global);
const cancelFrame = options.cancelFrame || global.cancelAnimationFrame.bind(global);
const setTimer = options.setTimer || global.setTimeout.bind(global);
@@ -73,6 +81,7 @@
let frameToken = null;
let timerToken = null;
let finalizedByKeydown = false;
let compositionStart = 0;
let destroyed = false;
let invokingClear = false;
@@ -140,17 +149,19 @@
cleanup();
if (destroyed) return;
composing = true;
compositionStart = textarea.selectionStart == null ? textarea.value.length : textarea.selectionStart;
}
function updateComposition(event) {
if (!composing) return;
latestValue = event.data == null ? '' : String(event.data);
const segment = safely(ownsNativeInput) ? textarea.value.slice(compositionStart, textarea.selectionEnd) : '';
latestValue = event.data == null ? segment : String(event.data);
scheduleLatestPreview('provisional');
}
function onComposingInput(event) {
if (!event.isComposing) return;
updateComposition({ data: event.data == null ? textarea.value : event.data });
updateComposition({ data: event.data == null && !safely(ownsNativeInput) ? textarea.value : event.data });
}
function armFallbackTimer(isCurrent) {
@@ -203,6 +214,9 @@
// finalizes it. `isComposing` and `key` are deliberately not consulted,
// because xterm does not consult them.
function onKeydown(event) {
// Native ownership, not xterm's terminal-key heuristic, decides when the
// retained field has finished composing.
if (safely(ownsNativeInput)) return;
if (keydownTarget !== textarea && event.target !== textarea) return;
if (!composing || KEEP_COMPOSING_KEYCODES.has(event.keyCode)) return;
finalizeComposition(latestValue, true);
@@ -246,6 +260,16 @@
return true;
}
function nativeTransaction({ inserted, deleted, composition }) {
if (destroyed || !awaitingCommit) return false;
if (inserted && consumeTerminalData(inserted)) return true;
// No inserted text (or unsafe terminal controls): nothing can display a
// commit later. In particular deletion-only/unchanged compositions settle
// now instead of leaving unrelated input to consume the 2 s fallback.
cleanup();
return false;
}
function completeCommit(result) {
if (destroyed || !result || result.predicted !== true || !committed) return;
cleanup();
@@ -275,6 +299,7 @@
return {
consumeTerminalData,
nativeTransaction,
completeCommit,
noteAuthoritativeOutput,
reset,
+2 -19
View File
@@ -2070,18 +2070,8 @@ Object.assign(CodemanApp.prototype, {
}
},
/** Send Enter to the active session (phone toolbar button).
*
* MUST go through xterm's onData path, NOT straight to sendInput()/the API.
* With local echo on (the mobile default) the characters you typed are still
* buffered in the LocalEchoOverlay and have NEVER reached the PTY. The onData
* Enter branch (terminal-ui.js) is what flushes that pending text and only
* then sends \r. Send a bare \r instead and you submit an empty line while the
* typed text stays stranded on screen — which reads as "the button does
* nothing". triggerDataEvent replays it exactly as if the key were pressed,
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
/** Submit the focused pane through the shared native-input/echo boundary. */
sendEnterKey() {
if (!this.activeSessionId) return;
// While the CJK field is visible, onData drops everything (cjkActive), this
// Enter included. Press Enter in the field instead: it sends what the field
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
@@ -2092,14 +2082,7 @@ Object.assign(CodemanApp.prototype, {
CjkInput.submit?.();
return;
}
const coreService = this.terminal?._core?.coreService;
if (coreService && typeof coreService.triggerDataEvent === 'function') {
coreService.triggerDataEvent('\r', true);
return;
}
// Fallback only if xterm's private core API moves: correct when local echo
// is off, and still better than doing nothing.
this.sendInput('\r');
this.submitFromToolbar();
},
_initRunMode() {
+731
View File
@@ -0,0 +1,731 @@
/**
* @fileoverview iOS WebKit native editing owner for xterm's helper textarea.
*
* Keep the native line intact and reconcile its projected text into one ordered
* transaction. xterm retains commands, paste and composition rendering, but no
* competing text producer. Native selection is visual only: never send arrows.
*
* The shared platform predicate lives in MobileImePreview, which already owns
* it and loads first. Delegating keeps native ownership and preview gating in
* lockstep without adding another platform detector or script dependency.
*
* @dependency mobile-ime-preview.js (shared isIosWebKitTouch predicate)
* @loadorder 5.56 (after mobile-ime-preview.js, before terminal-ui.js/terminal-tile.js)
*/
(function (global) {
'use strict';
// WebKit removes one grapheme cluster per Backspace, and Claude Code and Codex
// delete one grapheme per DEL, so an edit is counted in graphemes: a red heart,
// a skin-tone emoji, a flag or a ZWJ family is one DEL, as it was through xterm.
// Code points stand in where Intl.Segmenter is missing.
const graphemeSegmenter = (function () {
try {
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
: null;
} catch (_) {
return null;
}
})();
function graphemes(text) {
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
}
function editBetween(previous, next) {
// A pure append (including a combining mark or tone typed onto the last letter)
// is sent as-is, as xterm sends it: re-typing the extended cluster would make
// a code-point line editor (zsh) double the base letter.
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
const a = graphemes(previous);
const b = graphemes(next);
let prefix = 0;
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1;
return { deleted: a.length - prefix, inserted: b.slice(prefix).join('') };
}
// Native line breaks are provisional dictation text, never submit commands.
function project(value) {
return value.replace(/\r\n|[\r\n]/g, ' ');
}
const TERMINAL_KEYS = Object.freeze({
Enter: 13,
Tab: 9,
Escape: 27,
ArrowLeft: 37,
ArrowUp: 38,
ArrowRight: 39,
ArrowDown: 40,
Home: 36,
End: 35,
PageUp: 33,
PageDown: 34,
Insert: 45,
Delete: 46,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
});
const IOS_COMMANDS = new Set([
'UIKeyInputUpArrow',
'UIKeyInputDownArrow',
'UIKeyInputLeftArrow',
'UIKeyInputRightArrow',
'UIKeyInputEscape',
]);
function classifyKey(ev, textarea) {
if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return 'compose';
if (
ev.ctrlKey ||
ev.metaKey ||
ev.altKey ||
IOS_COMMANDS.has(ev.key) ||
(Object.prototype.hasOwnProperty.call(TERMINAL_KEYS, ev.key) && TERMINAL_KEYS[ev.key] === ev.keyCode)
)
return 'command';
if (ev.key === 'Backspace' && ev.keyCode === 8 && textarea && textarea.value === '') {
return 'backspace-terminal';
}
return 'native';
}
function isSupported() {
return !!(global.MobileImePreview && global.MobileImePreview.isIosWebKitTouch(global.navigator));
}
function create(options) {
const opts = options || {};
function record(entry) {
try {
if (typeof opts.log === 'function') opts.log(entry);
} catch (_) {
/* Diagnostics are optional. */
}
}
function guard(hook, fn, fallback) {
return function (...args) {
try {
return fn.apply(this, args);
} catch (error) {
record({ type: 'error', hook, error });
return fallback;
}
};
}
const patches = [];
const listeners = [];
let textarea;
let whitespace;
let destroyed = false;
let timer = null;
let synced = '';
let cursor = 0;
let invalidated = false;
let foreignSnapshot = null;
let foreignTimer = null;
const caretListeners = new Set(typeof opts.onCaret === 'function' ? [opts.onCaret] : []);
let notifyCaret = function () {};
let composing = false;
let compositionPending = false;
let reconciling = false;
let again = false;
let generation = 0;
function cancelPending() {
if (timer !== null) {
global.clearTimeout(timer);
timer = null;
}
if (foreignTimer !== null) {
global.clearTimeout(foreignTimer);
foreignTimer = null;
}
}
const destroy = guard('destroy', function () {
if (destroyed) return;
destroyed = true;
cancelPending();
notifyCaret();
caretListeners.clear();
for (const [target, type, listener] of listeners) target.removeEventListener(type, listener, true);
if (whitespace) {
if (whitespace.value) textarea.style.setProperty('white-space', whitespace.value, whitespace.priority);
else textarea.style.removeProperty('white-space');
}
// Restore property ownership as well as function identity: most methods
// originally live on xterm's prototype, not on the instance.
for (let i = patches.length - 1; i >= 0; i -= 1) {
const { target, name, descriptor } = patches[i];
if (descriptor) Object.defineProperty(target, name, descriptor);
else delete target[name];
}
});
try {
const terminal = opts.terminal;
const core = terminal && terminal._core;
const helper = core && core._compositionHelper;
textarea = terminal && terminal.textarea;
if (
!textarea ||
!core ||
!helper ||
!core.coreService ||
typeof core.coreService.triggerDataEvent !== 'function' ||
typeof core._inputEvent !== 'function' ||
typeof core._handleTextAreaBlur !== 'function' ||
typeof helper._handleAnyTextareaChanges !== 'function' ||
typeof helper._finalizeComposition !== 'function' ||
!helper._compositionView ||
!helper._compositionView.classList ||
typeof textarea.setSelectionRange !== 'function' ||
(terminal.options && terminal.options.screenReaderMode) ||
(opts.isScreenReaderMode && opts.isScreenReaderMode())
)
return null;
const sendTransaction = opts.sendTransaction;
if (typeof sendTransaction !== 'function') return null;
whitespace = {
value: textarea.style.getPropertyValue('white-space'),
priority: textarea.style.getPropertyPriority('white-space'),
};
// nowrap collapses whitespace, making WebKit replace trailing spaces with
// NBSP. pre preserves native spaces without wrapping or changing real NBSP.
textarea.style.setProperty('white-space', 'pre');
// A pre-existing field has no provenance: it is not evidence of PTY input.
invalidated = textarea.value !== '';
const caret = guard(
'caret',
function () {
const text = project(textarea.value);
const offset = project(textarea.value.slice(0, textarea.selectionEnd)).length;
return {
visible:
!destroyed &&
textarea.ownerDocument.activeElement === textarea &&
!composing &&
textarea.selectionStart === textarea.selectionEnd &&
offset < text.length &&
text === synced &&
!invalidated &&
!foreignSnapshot,
text,
offset,
// Advances only when an edit is reconciled (sent) or the line is reset;
// a borrowed clipboard value and its restoration leave it unchanged.
generation,
};
},
{ visible: false, text: '', offset: 0, generation: 0 }
);
let previousCaret;
notifyCaret = function () {
const current = caret();
if (
previousCaret &&
previousCaret.visible === current.visible &&
previousCaret.text === current.text &&
previousCaret.offset === current.offset &&
previousCaret.generation === current.generation
)
return;
previousCaret = current;
for (const callback of caretListeners) {
try {
callback({ ...current });
} catch (error) {
record({ type: 'error', hook: 'onCaret', error });
}
}
};
const onCaret = guard('onCaret', function (callback) {
if (destroyed || typeof callback !== 'function') return function () {};
caretListeners.add(callback);
return function () {
caretListeners.delete(callback);
};
});
function restoreForeign() {
if (!foreignSnapshot || destroyed) return;
const snapshot = foreignSnapshot;
foreignSnapshot = null;
if (foreignTimer !== null) {
global.clearTimeout(foreignTimer);
foreignTimer = null;
}
textarea.value = snapshot.value;
textarea.setSelectionRange(snapshot.start, snapshot.end, snapshot.direction);
synced = snapshot.synced;
notifyCaret();
}
function invalidate() {
if (invalidated) return;
record({ type: 'drift', value: textarea.value, synced });
// Never replace a supposedly sent baseline with an unproven field.
cancelPending();
foreignSnapshot = null;
synced = '';
cursor = 0;
invalidated = true;
generation += 1;
record({ type: 'reset', reason: 'drift', generation });
notifyCaret();
}
function schedule() {
if (destroyed || timer !== null) return;
timer = global.setTimeout(
guard('timer', function () {
timer = null;
if (!destroyed) reconcile();
}),
0
);
}
function notifyTransaction(transaction) {
try {
if (typeof opts.onTransaction === 'function') opts.onTransaction(transaction);
} catch (error) {
record({ type: 'error', hook: 'onTransaction', error });
}
}
function reconcile() {
if (destroyed || composing || invalidated || foreignSnapshot) return;
if (reconciling) {
again = true;
return;
}
do {
again = false;
const current = project(textarea.value);
const transaction = { ...editBetween(synced, current), composition: compositionPending };
compositionPending = false;
const ops = [];
if (current !== synced) {
const { deleted, inserted } = transaction;
record({ type: 'reconcile', deleted, inserted });
for (let i = 0; i < deleted; i += 1) ops.push('\x7f');
if (inserted) ops.push(inserted);
synced = current;
cursor = Array.from(current).length;
generation += 1;
}
// Publish the end-anchored baseline BEFORE calling out. A reset inside
// the transaction survives; the destination receives all ops atomically.
reconciling = true;
try {
if (ops.length) {
// These ops bypass xterm's triggerDataEvent(data, true), so its
// scrollOnUserInput never runs; scroll to the prompt as xterm would.
try {
if (
terminal.options &&
terminal.options.scrollOnUserInput !== false &&
typeof terminal.scrollToBottom === 'function'
)
terminal.scrollToBottom();
} catch (error) {
record({ type: 'error', hook: 'scrollOnUserInput', error });
}
try {
sendTransaction(ops);
} catch (error) {
record({ type: 'error', hook: 'sendTransaction', error });
invalidated = true;
}
}
// Empty/deletion-only compositions still settle the visual preview.
notifyTransaction(transaction);
} finally {
reconciling = false;
}
} while (again && !destroyed && !composing && !invalidated && !foreignSnapshot);
notifyCaret();
}
const settle = guard('settle', function () {
cancelPending();
reconcile();
});
const reset = guard('reset', function (reason) {
if (destroyed) return;
cancelPending();
foreignSnapshot = null;
textarea.value = '';
invalidated = false;
synced = '';
cursor = 0;
generation += 1;
composing = false;
compositionPending = false;
record({ type: 'reset', reason, generation });
notifyTransaction({ inserted: '', deleted: 0, composition: false });
notifyCaret();
});
const keyFilter = guard(
'keyFilter',
function (ev) {
if (destroyed) return true;
if (ev.type === 'keypress') return false;
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
if (ev.type !== 'keydown') return true;
restoreForeign();
const kind = composing ? 'compose' : classifyKey(ev, textarea);
if (kind === 'compose') {
schedule();
return false;
}
if (kind === 'command') {
settle();
reset('command');
return true;
}
if (kind === 'backspace-terminal') {
settle();
return true;
}
return false;
},
false
);
function patch(target, name, replacement) {
patches.push({ target, name, descriptor: Object.getOwnPropertyDescriptor(target, name) });
target[name] = guard(name, replacement, false);
}
function listen(type, fn, target = textarea) {
const listener = guard(type, fn);
listeners.push([target, type, listener]);
target.addEventListener(type, listener, true);
}
patch(core, '_inputEvent', function (ev) {
if (ev && ev.data && ev.inputType === 'insertText') core._unprocessedDeadKey = false;
return false;
});
patch(helper, '_handleAnyTextareaChanges', schedule);
patch(helper, '_finalizeComposition', function () {
helper._compositionView.classList.remove('active');
helper._isComposing = false;
helper._isSendingComposition = false;
schedule();
});
const originalBlur = core._handleTextAreaBlur;
patch(core, '_handleTextAreaBlur', function (...args) {
restoreForeign();
const value = textarea.value;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const direction = textarea.selectionDirection;
const before = generation;
try {
return originalBlur.apply(this, args);
} finally {
if (opts.blurPolicy === 'stock') {
synced = '';
cursor = 0;
invalidated = false;
} else if (!destroyed && generation === before) {
textarea.value = value;
textarea.setSelectionRange(start, end, direction);
}
notifyCaret();
}
});
listen('beforeinput', function (ev) {
if (destroyed || composing || ev.isComposing) return;
if (foreignSnapshot || project(textarea.value) !== synced) invalidate();
});
listen('input', function (ev) {
if (!destroyed && !ev.isComposing && !composing) {
if (foreignSnapshot) invalidate();
if (invalidated) reset('drift');
else reconcile();
}
if (!destroyed) notifyCaret();
});
listen('compositionstart', function () {
if (!destroyed) {
composing = true;
notifyCaret();
}
});
listen('compositionend', function () {
if (destroyed) return;
composing = false;
compositionPending = true;
notifyCaret();
schedule();
});
listen(
'selectionchange',
function () {
if (!destroyed && textarea.ownerDocument.activeElement === textarea) notifyCaret();
},
textarea.ownerDocument
);
listen('focus', notifyCaret);
listen('blur', notifyCaret);
// xterm temporarily lends the helper to native Copy. Restore only before
// a new key edit, after Copy has read it, or before blur preservation.
if (terminal.element)
listen(
'contextmenu',
function () {
if (destroyed || foreignSnapshot) return;
foreignSnapshot = {
value: textarea.value,
start: textarea.selectionStart,
end: textarea.selectionEnd,
direction: textarea.selectionDirection,
synced,
};
notifyCaret();
},
terminal.element
);
listen('keydown', restoreForeign);
listen(
'copy',
function () {
if (destroyed || !foreignSnapshot || foreignTimer !== null) return;
foreignTimer = global.setTimeout(
guard('copy timer', function () {
foreignTimer = null;
restoreForeign();
}),
0
);
},
textarea.ownerDocument
);
listen('blur', restoreForeign);
// xterm's paste handler emits the clipboard (bracketed when the app asks)
// but never cancels the event, so the browser would also insert it into
// the field and reconcile would send it a second time. Cancel only the
// native insertion; xterm's bubble listener still runs.
listen('paste', function (ev) {
if (destroyed) return;
settle();
reset('paste');
ev.preventDefault();
});
notifyCaret();
return {
keyFilter,
reset,
settle,
destroy,
caret,
onCaret,
state: guard('state', function () {
return {
value: textarea.value,
synced,
cursor,
composing,
invalidated,
selectionStart: textarea.selectionStart,
selectionEnd: textarea.selectionEnd,
generation,
};
}),
};
} catch (error) {
record({ type: 'error', hook: 'create', error });
destroy();
return null;
}
}
// Visual only: an anchor(caret) supplies the exact viewport cell, 'hide', or
// null to resolve against parsed xterm cells. Neither mode moves native input.
// subscribe(callback) follows overlay repaints without an xterm render.
function bufferCaretAnchor(terminal, caret) {
const buffer = terminal.buffer.active;
const text = caret.text;
if (!text || caret.offset < 0 || caret.offset > text.length) return null;
let row = buffer.baseY + buffer.cursorY;
let col = buffer.cursorX;
let line = buffer.getLine(row);
// Read only as far as the native field and one preceding repetition.
function previousCell() {
while (line) {
if (col === 0) {
if (!line.isWrapped || row === 0) return null;
const following = line;
line = buffer.getLine(--row);
if (!line) return null;
col = terminal.cols;
// A wide glyph that did not fit leaves unused cells before a soft
// wrap. Validate that padding against the following glyph's width;
// ordinary blank cells (including printed spaces) remain text.
let padding = 0;
while (col - padding > 0) {
const cell = line.getCell(col - padding - 1);
if (!cell || cell.getWidth() !== 1 || cell.getChars()) break;
padding += 1;
}
const first = following.getCell(0);
if (padding && first && first.getWidth() > padding) col -= padding;
}
const cell = line.getCell(--col);
if (!cell) return null;
if (cell.getWidth() === 0) continue;
const chars = cell.getChars();
if (!chars) return null;
return { chars, col, row: row - buffer.viewportY };
}
return null;
}
const cells = [];
let remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
return null;
cells.push(cell);
remaining -= cell.chars.length;
}
// A previous identical native-length suffix makes provenance ambiguous.
remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
break;
remaining -= cell.chars.length;
}
if (remaining === 0) return null;
let offset = 0;
for (let i = cells.length - 1; i >= 0; i -= 1) {
const cell = cells[i];
if (caret.offset === offset) return { col: cell.col, row: cell.row };
offset += cell.chars.length;
if (caret.offset < offset) return null; // No cell inside a cluster.
}
return { col: buffer.cursorX, row: buffer.baseY + buffer.cursorY - buffer.viewportY };
}
function attachCaretMarker(terminal, owner, options) {
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
const disposables = [];
let marker;
let disposed = false;
let caretGeneration = 0;
let awaitingEcho = false;
function dispose() {
if (disposed) return;
disposed = true;
for (const cleanup of disposables) {
try {
cleanup();
} catch (_) {
/* Terminal teardown may already have run. */
}
}
if (marker) marker.remove();
}
try {
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
caretGeneration = owner.caret().generation;
marker = screen.ownerDocument.createElement('div');
marker.className = 'ios-native-caret';
marker.setAttribute('aria-hidden', 'true');
marker.style.cssText = 'position:absolute;width:2px;pointer-events:none;display:none;z-index:10';
screen.appendChild(marker);
function position() {
try {
const caret = owner.caret();
const core = terminal._core;
const dimensions = core && core._renderService && core._renderService.dimensions;
const cell = dimensions && dimensions.css && dimensions.css.cell;
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
marker.style.display = 'none';
return;
}
let target = null;
if (anchor) {
try {
target = anchor(caret);
} catch (_) {
target = 'hide';
}
}
if (target == null && !awaitingEcho) target = bufferCaretAnchor(terminal, caret);
if (!target || target === 'hide' || target.row < 0 || target.row >= terminal.rows) {
marker.style.display = 'none';
return;
}
marker.style.display = 'block';
marker.style.left = target.col * cell.width + 'px';
marker.style.top = target.row * cell.height + 'px';
marker.style.height = cell.height + 'px';
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
} catch (_) {
marker.style.display = 'none';
}
}
disposables.push(
owner.onCaret((caret) => {
// Await parsed output only for a reconciled edit or reset (generation),
// never for a borrowed clipboard value or its restoration.
if (caret.generation !== caretGeneration) {
caretGeneration = caret.generation;
awaitingEcho = true;
}
position();
})
);
if (typeof terminal.onWriteParsed === 'function') {
const subscription = terminal.onWriteParsed(() => {
awaitingEcho = false;
position();
});
disposables.push(() => subscription.dispose());
}
for (const name of ['onRender', 'onCursorMove']) {
if (typeof terminal[name] === 'function') {
const subscription = terminal[name](position);
disposables.push(() => subscription.dispose());
}
}
if (options && typeof options.subscribe === 'function') {
try {
const unsubscribe = options.subscribe(position);
if (typeof unsubscribe === 'function') disposables.push(unsubscribe);
} catch (_) {
/* Optional anchor feed. */
}
}
position();
return dispose;
} catch (_) {
dispose();
return dispose;
}
}
global.CodemanIosNativeInput = Object.freeze({ create, editBetween, classifyKey, attachCaretMarker, isSupported });
})(typeof window !== 'undefined' ? window : globalThis);
+25 -4
View File
@@ -60,15 +60,36 @@
(function (global) {
'use strict';
// Grapheme clusters, the unit a soft-keyboard Backspace removes, Claude Code and
// Codex delete per DEL, and the local-echo overlay drops per DEL. Code points
// stand in where Intl.Segmenter is missing (same rule as terminal-ios-native-input.js).
const graphemeSegmenter = (() => {
try {
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
: null;
} catch {
return null;
}
})();
function graphemes(text) {
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
}
/**
* What turns `previous` into `next`, as a terminal sees it: how many characters to delete from
* the END of the line, then what to type. Everything after the common prefix is treated as
* replaced, because a terminal can only edit at its cursor. Counts are code points, so an
* emoji is one DEL, as it is one backspace.
* replaced, because a terminal can only edit at its cursor. Counts are grapheme clusters, so a
* red heart, a skin-tone emoji, a flag or a ZWJ family is one DEL, as it is one backspace.
*/
function editBetween(previous, next) {
const a = Array.from(previous);
const b = Array.from(next);
// A pure append (including a combining mark or tone typed onto the last letter)
// is sent as-is: re-typing the extended cluster would make a code-point line
// editor (zsh) double the base letter.
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
const a = graphemes(previous);
const b = graphemes(next);
let prefix = 0;
const max = Math.min(a.length, b.length);
while (prefix < max && a[prefix] === b[prefix]) prefix += 1;
+69 -1
View File
@@ -54,6 +54,7 @@
* @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, SHELL_LOAD_BASE_QUERY, SHELL_LOAD_QUERY, TERMINAL_CHUNK_SIZE)
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/wheelTicksForGesture/coalesceScrollBytes/sgrWheelReports/pageKeysForGesture, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_clientPointToCell/_handleDesktopTerminalClick, app.tabAlerts)
* @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
* @dependency terminal-ios-native-input.js (window.CodemanIosNativeInput, optional iOS native editing owner)
* @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
*/
@@ -227,6 +228,8 @@
// The soft-keyboard controller (terminal-keycode229-recovery.js): created
// in connect() once the xterm is open, torn down in destroy().
this._keyCode229Recovery = null;
this._iosNativeInput = null;
this._iosCaretMarker = null;
}
async connect() {
@@ -275,7 +278,7 @@
this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
this._createKeyCode229Recovery();
this._createInputOwner();
// The twin of terminal-ui.js's onData gate (initTerminal; keep the two in
// step). Canonical xterm data tells the controller this keystroke was
// delivered, but not a query reply or a focus/mouse report, which xterm
@@ -309,6 +312,7 @@
// here too. Ctrl+V goes through the primary pane's paste trap
// (image-input.js), aimed at this pane (below).
this.terminal.attachCustomKeyEventHandler((ev) => {
if (this._iosNativeInput?.keyFilter(ev) === false) return false;
// FIRST, above the IME early return below, as in terminal-ui.js: every
// keydown settles this pane's pending textarea edit and drains a
// pending recovery BEFORE xterm handles the key, so a character an
@@ -639,6 +643,68 @@
app?._sendInputAsync?.(this.sessionId, data);
}
// iOS owns native textarea edits; other platforms retain the 229 recovery.
// Replacing either controller first settles the old tile's pending edit.
_createInputOwner() {
this._destroyIosNativeInput();
this._destroyKeyCode229Recovery();
if (!this.terminal) return;
const nativeInput = global.CodemanIosNativeInput;
if (!nativeInput?.isSupported?.()) {
this._createKeyCode229Recovery();
return;
}
this._iosNativeInput = nativeInput.create({
terminal: this.terminal,
sendTransaction: (ops) => this._sendNativeInputTransaction(ops),
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
});
if (this._iosNativeInput) {
// Tiles have no local-echo overlay: resolve only from verified parsed cells.
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
return;
}
// create() refused (screen reader, missing xterm internals): keep the
// soft-keyboard recovery rather than leaving the tile with neither.
this._createKeyCode229Recovery();
}
_sendNativeInputTransaction(ops) {
const sessionId = this.sessionId;
const app = global.app;
let ctrlIndex = -1;
// Same rule as the primary pane (terminal-ui.js _sendNativeInputTransaction):
// the edit's first insertion spends the armed Ctrl whatever its length.
// consumeCtrl maps a single character and passes a suggestion or emoji
// through unchanged, but it still disarms, so the next `c` stays a `c`.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
}
// Keep replacement deletions: Ctrl changes only the insertion, once for
// this edit, never once per DEL. Tiles have no local echo to reconcile.
const writes = ops.map((data, i) => ({
write: i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(data) : data,
}));
if (app?._enqueueInput) app._enqueueInput(sessionId, writes);
else for (const { write } of writes) app?._sendInputAsync?.(sessionId, write);
if (ctrlIndex !== -1) this._iosNativeInput?.reset('ctrl');
}
_destroyIosNativeInput() {
try {
this._iosNativeInput?.settle();
} finally {
try {
this._iosNativeInput?.destroy();
} finally {
this._iosNativeInput = null;
this._iosCaretMarker?.();
this._iosCaretMarker = null;
}
}
}
// The soft-keyboard controller, the twin of the primary pane's wiring in
// terminal-ui.js initTerminal() (keep the two in step); the behaviour lives
// once, in terminal-keycode229-recovery.js. Everything it is handed is THIS
@@ -1554,6 +1620,8 @@
}
destroy() {
if (global.app?._focusedTile === this && typeof CjkInput !== 'undefined') CjkInput.flushNow?.();
this._destroyIosNativeInput();
this._destroyed = true;
// Anything still queued for this session stays in the app's queue and is
// delivered over HTTP by the redelivery sweep, so closing the pane mid-
File diff suppressed because it is too large. Load diff
+28 -12
View File
@@ -25,7 +25,7 @@
* @globals {object} VoiceInput
*
* @dependency mobile-handlers.js (MobileDetection for device checks)
* @dependency app.js (uses global `app` for sendInput, showToast, terminal focus)
* @dependency app.js (uses global `app` for _sendInputAsync, _enqueueInput, _prepareExternalInput, showToast, terminal focus)
* @loadorder 3 of 15 — loaded after mobile-handlers.js, before notification-manager.js
*/
@@ -1071,19 +1071,18 @@ const VoiceInput = {
return this._targetSessionId || app.activeSessionId;
},
/**
* Send text to the dictation's own session. The active session keeps going
* through app.sendInput() exactly as before; any other session goes straight
* to the durable queue with the same useMux flag sendInput() passes.
*/
/** Send only to the captured dictation session, never the current tab. */
_sendToTarget(target, text) {
if (target === app.activeSessionId) return app.sendInput(text);
// Closed while dictating: say so instead of queueing text for a session
// that will only answer 404 (and never typing it into some other tab).
if (app.sessions && !app.sessions.has(target)) {
app.showToast?.('That session has closed; dictation not sent', 'warning');
return Promise.resolve();
}
// Settle the destination's iOS owner, but leave an unsent local-echo draft
// in the overlay: flushing it would prepend it to the reviewed dictation.
const pane = app._paneForSession?.(target);
if (pane) app._prepareExternalInput?.(pane, 'voice-send');
app._sendInputAsync(target, text, { useMux: true });
return Promise.resolve();
},
@@ -1098,6 +1097,7 @@ const VoiceInput = {
// If a compose overlay is already open, populate its textarea instead of recreating
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
if (existingTextarea) {
existingTextarea.closest('.voice-compose-overlay').dataset.targetSessionId = target;
existingTextarea.value = trimmed;
existingTextarea.focus();
existingTextarea.selectionStart = existingTextarea.selectionEnd = trimmed.length;
@@ -1113,7 +1113,13 @@ const VoiceInput = {
// sees, so it goes straight to the session instead.
const isActive = target === app.activeSessionId;
const tilesOpen = !!app._tilesOwnTerminal?.();
const pane = app._focusedPane?.();
if (isActive && !tilesOpen && app._localEchoEnabled && app._localEchoOverlay) {
// Focus may have moved to Pane B, but this overlay still belongs to A.
const targetPane = pane?.isPrimary && pane.sessionId === target
? pane
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
app._prepareExternalInput?.(targetPane, 'voice-insert');
app._localEchoOverlay.appendText(trimmed);
} else {
this._sendToTarget(target, trimmed).catch(() => {});
@@ -1158,24 +1164,33 @@ const VoiceInput = {
this._voiceSendHandler = () => {
const target = this._targetSession();
if (!target) return;
const pane = app._focusedPane?.();
const tilesOpen = !!app._tilesOwnTerminal?.();
if (target === app.activeSessionId && !tilesOpen) {
const targetPane = pane?.isPrimary && pane.sessionId === target
? pane
: { isPrimary: true, tile: null, terminal: app.terminal, sessionId: target };
app._prepareExternalInput?.(targetPane, 'voice-submit');
}
// Simulate Enter key: if local echo is active, flush its buffer + send \r;
// otherwise just send \r directly to the PTY. Both the overlay and the
// predictions belong to the ACTIVE session's MAIN terminal, so a
// dictation for another session, or for a tile while the grid has the
// main terminal parked, just sends its Enter there.
if (target !== app.activeSessionId || app._tilesOwnTerminal?.()) {
if (target !== app.activeSessionId || tilesOpen) {
this._sendToTarget(target, '\r').catch(() => {});
} else if (app._localEchoEnabled && app._localEchoOverlay) {
const text = app._localEchoOverlay.pendingText || '';
app._localEchoOverlay.clear();
app._localEchoOverlay.suppressBufferDetection();
if (text) app.sendInput(text).catch(() => {});
setTimeout(() => app.sendInput('\r').catch(() => {}), 80);
const ops = text ? [{ write: text, useMux: true }, { gap: 80 }] : [];
ops.push({ write: '\r', useMux: true });
app._enqueueInput(target, ops);
} else {
// Predict-mode sessions (codex) take this branch: the send bypasses
// onData, so clear outstanding predictions here (composer will reset)
app._predictiveEcho?.clearPredictions();
app.sendInput('\r').catch(() => {});
app._sendInputAsync(target, '\r', { useMux: true });
}
// Blink then restore
gear.classList.add('voice-send-blink');
@@ -1205,6 +1220,7 @@ const VoiceInput = {
document.querySelector('.voice-compose-overlay')?.remove();
const overlay = document.createElement('div');
overlay.className = 'voice-compose-overlay paste-overlay';
overlay.dataset.targetSessionId = this._targetSession();
overlay.innerHTML = `
<div class="paste-dialog">
<textarea class="paste-textarea">${text.replace(/</g, '&lt;')}</textarea>
@@ -1219,7 +1235,7 @@ const VoiceInput = {
const send = () => {
const val = textarea.value.trim();
overlay.remove();
if (val) this._sendToTarget(this._targetSession(), val + '\r').catch(() => {});
if (val) this._sendToTarget(overlay.dataset.targetSessionId, val + '\r').catch(() => {});
};
const cancel = () => overlay.remove();
const newInput = () => {
+22 -6
View File
@@ -158,6 +158,11 @@ describe('a held draft survives a reload of the same session', () => {
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
// Nothing in the same-session reload block may clear the field ahead of
// that flag: a CjkInput.clear() there wipes the held draft keepCjkDraft keeps.
const start = appJs.indexOf('if (this.activeSessionId === sessionId && forceReload) {');
const block = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(block).not.toContain('CjkInput.clear');
});
});
@@ -178,13 +183,24 @@ describe('Send on Enter field layout and strings', () => {
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
it('the phone toolbar Enter presses Enter in the visible CJK field, not a bare terminal Enter', () => {
// 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?.();');
// The real sendEnterKey from session-ui.js, run with and without the field.
for (const visible of [true, false]) {
const submit = vi.fn();
const field = { classList: { contains: (name: string) => visible && name === 'cjk-input-visible' } };
const context = vm.createContext({
CodemanApp: function CodemanApp() {},
CjkInput: { submit },
document: { getElementById: (id: string) => (id === 'cjkInput' ? field : null) },
});
vm.runInContext(`${read('session-ui.js')}\nglobalThis.__mixin = CodemanApp.prototype;`, context);
const mixin = (context as unknown as { __mixin: { sendEnterKey(this: object): void } }).__mixin;
const submitFromToolbar = vi.fn();
mixin.sendEnterKey.call({ submitFromToolbar });
expect(submit).toHaveBeenCalledTimes(visible ? 1 : 0);
expect(submitFromToolbar).toHaveBeenCalledTimes(visible ? 0 : 1);
}
});
it('has zh-CN strings for both field placeholders', () => {
+25 -13
View File
@@ -40,6 +40,16 @@ let untrustedWorkdir: string;
let sessionId: string;
const createdSessions: string[] = [];
/** The transport edge the recorders wrap: every typed producer reaches it through the session FIFO. */
type ReliableSend = (sid: string, data: string, opts?: unknown) => void;
interface RecorderWindow {
app: { _enqueueReliableInput: ReliableSend };
__dbg: Array<[string, string]>;
__trace: string[];
__origSend?: ReliableSend;
__origSend2?: ReliableSend;
}
function hasCodex(): boolean {
try {
execSync(`PATH="${CODEX_BIN_DIR}:$PATH" codex --version`, { stdio: 'pipe' });
@@ -324,12 +334,13 @@ d('codex predictive echo E2E (real codex TUI)', () => {
await resetComposer();
const pidBefore = execSync(`${TMUX} list-panes -a -F '#{pane_id} #{pane_pid}'`, { encoding: 'utf8' }).trim();
await page.evaluate(() => {
const app = (window as any).app;
(window as any).__dbg = [];
if (!(window as any).__origSend2) (window as any).__origSend2 = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return (window as any).__origSend2(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__dbg = [];
const original = (w.__origSend2 ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return original(sid, data, opts);
};
});
await page.keyboard.type('abc', { delay: 30 });
@@ -471,15 +482,16 @@ d('codex predictive echo E2E (real codex TUI)', () => {
const record = () =>
page.evaluate(() => {
const app = (window as any).app;
(window as any).__trace = [];
if (!(window as any).__origSend) (window as any).__origSend = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__trace.push(data);
return (window as any).__origSend(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__trace = [];
const original = (w.__origSend ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__trace.push(data);
return original(sid, data, opts);
};
});
const trace = () => page.evaluate(() => ((window as any).__trace as string[]).join(''));
const trace = () => page.evaluate(() => (window as unknown as RecorderWindow).__trace.join(''));
await record();
await script();
+188
View File
@@ -0,0 +1,188 @@
/** @fileoverview Replay phone-validated iOS native input events and browser defaults. */
// Synthetic events have no browser default. Replay WebKit's order and apply
// native edits by hand, but never apply a default after preventDefault().
(function (global) {
'use strict';
function kev(type, key, keyCode, extra = {}) {
const ev = new KeyboardEvent(type, {
key,
code: extra.code || (key === 'Backspace' ? 'Backspace' : 'Unidentified'),
bubbles: true,
cancelable: true,
composed: true,
ctrlKey: !!extra.ctrlKey,
shiftKey: !!extra.shiftKey,
altKey: !!extra.altKey,
metaKey: !!extra.metaKey,
isComposing: !!extra.isComposing,
});
Object.defineProperties(ev, {
keyCode: { get: () => keyCode },
which: { get: () => keyCode },
charCode: { get: () => (type === 'keypress' ? keyCode : 0) },
});
return ev;
}
function iev(type, inputType, data, options = {}) {
return new InputEvent(type, {
inputType,
data: data ?? null,
bubbles: true,
cancelable: type === 'beforeinput',
composed: true,
isComposing: !!options.isComposing,
});
}
function applyEdit(ta, inputType, data, range) {
const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
const select = HTMLTextAreaElement.prototype.setSelectionRange;
const value = ta.value;
let start = range ? range[0] : ta.selectionStart;
const end = range ? range[1] : ta.selectionEnd;
if (inputType === 'deleteContentBackward') {
if (start === end) {
if (start === 0) return false;
const segments = new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value.slice(0, start));
start -= Array.from(segments).pop().segment.length;
}
setValue.call(ta, value.slice(0, start) + value.slice(end));
select.call(ta, start, start);
} else if (
inputType === 'insertText' ||
inputType === 'insertReplacementText' ||
inputType === 'insertCompositionText' ||
inputType === 'insertLineBreak'
) {
const text = inputType === 'insertLineBreak' ? '\n' : data;
setValue.call(ta, value.slice(0, start) + text + value.slice(end));
// Textarea values normalize CRLF. Use the normalized inserted length.
const caret = start + text.replace(/\r\n?/g, '\n').length;
select.call(ta, caret, caret);
} else {
throw new Error('Unsupported replay edit: ' + inputType);
}
return true;
}
function edit(ta, inputType, data, range, options = {}) {
if (range) HTMLTextAreaElement.prototype.setSelectionRange.call(ta, ...range);
const before = iev('beforeinput', inputType, data, options);
ta.dispatchEvent(before);
if (before.defaultPrevented || !applyEdit(ta, inputType, data, range)) return false;
if (!options.omitInput) ta.dispatchEvent(iev('input', inputType, data, options));
return true;
}
// Replay event order/data, not old value snapshots: those include writes by
// the broken owner. Preserve explicit hypothesis ranges, otherwise let the
// caret advance in the intact field as real browser defaults would.
function capturedEdits(ta, records, afterInput, afterEvent) {
const select = HTMLTextAreaElement.prototype.setSelectionRange;
const decode = (value) =>
value
.replace(/<LF>/g, '\n')
.replace(/<CR>/g, '\r')
.replace(/<NBSP>/g, '\u00a0');
let pending;
for (const record of records) {
if (record.kind !== 'ev' || !['beforeinput', 'input'].includes(record.type)) continue;
const data = record.data === 'null' || record.data == null ? null : decode(record.data);
if (record.type === 'beforeinput') {
if (record.sel[0] !== record.sel[1]) select.call(ta, ...record.sel);
const event = iev(record.type, record.inputType, data, record);
ta.dispatchEvent(event);
if (afterEvent) afterEvent(record);
pending = event.defaultPrevented ? null : { inputType: record.inputType, data };
} else {
if (pending) applyEdit(ta, pending.inputType, pending.data);
pending = null;
ta.dispatchEvent(iev(record.type, record.inputType, data, record));
if (afterInput) afterInput(record);
if (afterEvent) afterEvent(record);
}
}
}
function typeKey(ta, text) {
const first = text.codePointAt(0);
const keyCode = text === ' ' ? 32 : String.fromCodePoint(first).toUpperCase().codePointAt(0);
const down = kev('keydown', text, keyCode);
ta.dispatchEvent(down);
if (!down.defaultPrevented) {
const press = kev('keypress', text, first);
ta.dispatchEvent(press);
if (!press.defaultPrevented) edit(ta, 'insertText', text);
}
ta.dispatchEvent(kev('keyup', text, keyCode));
}
function backspace(ta) {
const down = kev('keydown', 'Backspace', 8);
ta.dispatchEvent(down);
if (!down.defaultPrevented) edit(ta, 'deleteContentBackward');
ta.dispatchEvent(kev('keyup', 'Backspace', 8));
}
function holdDeleteRepeat(ta, burst) {
const down = kev('keydown', 'Backspace', 8);
ta.dispatchEvent(down);
if (!down.defaultPrevented) edit(ta, 'deleteContentBackward');
for (let i = 0; i < burst; i += 1) edit(ta, 'deleteContentBackward');
ta.dispatchEvent(kev('keyup', 'Backspace', 8));
}
function replaceSuggestion(ta, start, end, text) {
return edit(ta, 'insertReplacementText', text, [start, end]);
}
function enter(ta) {
const down = kev('keydown', 'Enter', 13);
ta.dispatchEvent(down);
if (!down.defaultPrevented) {
const press = kev('keypress', 'Enter', 13);
ta.dispatchEvent(press);
if (!press.defaultPrevented) edit(ta, 'insertLineBreak');
}
ta.dispatchEvent(kev('keyup', 'Enter', 13));
}
function caret(ta, index) {
ta.setSelectionRange(index, index);
ta.ownerDocument.dispatchEvent(new Event('selectionchange'));
}
function composition(ta, type, data = '') {
ta.dispatchEvent(new CompositionEvent(type, { data, bubbles: true, composed: true }));
}
function paste(ta, text) {
const clipboardData = new DataTransfer();
clipboardData.setData('text/plain', text);
ta.dispatchEvent(
new ClipboardEvent('paste', {
clipboardData,
bubbles: true,
cancelable: true,
composed: true,
})
);
}
global.IosReplay = Object.freeze({
kev,
iev,
edit,
capturedEdits,
typeKey,
backspace,
holdDeleteRepeat,
replaceSuggestion,
enter,
caret,
composition,
paste,
});
})(window);
+4 -16
View File
@@ -191,7 +191,6 @@ function loadPasteHarness(options: PasteHarnessOptions = {}): Harness {
if (options.localEchoPending !== undefined) {
pendingEcho = options.localEchoPending;
app._localEchoEnabled = true;
app._pendingInput = '';
app._localEchoOverlay = {
get pendingText() {
return pendingEcho;
@@ -206,14 +205,6 @@ function loadPasteHarness(options: PasteHarnessOptions = {}): Harness {
};
app._flushedOffsets = new Map();
app._flushedTexts = new Map();
app._flushLocalEchoPending = function (this: Record<string, any>) {
const pending = this._localEchoOverlay?.pendingText || '';
this._localEchoOverlay.clear();
this._localEchoOverlay.suppressBufferDetection();
this._flushedOffsets?.delete(this.activeSessionId);
this._flushedTexts?.delete(this.activeSessionId);
if (pending) this._pendingInput += pending;
};
}
const toasts: string[] = [];
app.showToast = (message: string) => toasts.push(message);
@@ -260,7 +251,6 @@ function loadImageInputApp() {
const app = new CodemanApp();
app.activeSessionId = 'session-1';
app.showToast = vi.fn();
app.sendInput = vi.fn(async () => {});
app._sendInputAsync = vi.fn();
app._normalizeImageForUpload = vi.fn(async (file) => file);
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => file.path);
@@ -481,7 +471,6 @@ describe('image upload insertion policy', () => {
const paths = await app._uploadAndInsertImages(files, { insert: false });
expect(Array.from(paths)).toEqual(['/tmp/first.png', '/tmp/second.png']);
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._sendInputAsync).not.toHaveBeenCalled();
});
@@ -491,15 +480,15 @@ describe('image upload insertion policy', () => {
const paths = await app._uploadAndInsertImages([{ path: '/tmp/legacy.png' }]);
expect(Array.from(paths)).toEqual(['/tmp/legacy.png']);
// The same delivery sendInput() uses (durable queue, useMux for the POST
// fallback), but addressed to the session the batch was uploaded to.
// Durable delivery with useMux for the POST fallback, addressed to the
// captured session the batch was uploaded to.
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/legacy.png', { useMux: true });
});
it('inserts into the session the upload started in, even after a tab switch mid-upload', async () => {
const app = loadImageInputApp();
// The user switches tabs while the upload is in flight. sendInput() re-read
// activeSessionId after the awaits, so the paths used to land in session-2.
// The user switches tabs while the upload is in flight. The captured session
// must remain the destination after the awaits, rather than the active tab.
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => {
app.activeSessionId = 'session-2';
return file.path;
@@ -509,7 +498,6 @@ describe('image upload insertion policy', () => {
expect(app._uploadPasteImage).toHaveBeenCalledWith('session-1', { path: '/tmp/shot.png' });
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/shot.png', { useMux: true });
expect(app.sendInput).not.toHaveBeenCalled();
});
it('uploads to and inserts into an explicitly named session', async () => {
+31 -1
View File
@@ -54,7 +54,14 @@ function load({
promptResult = true,
touch = true,
translate,
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
captureTarget,
}: {
hold?: boolean;
promptResult?: boolean;
touch?: boolean;
translate?: (s: string) => string;
captureTarget?: () => string;
} = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
@@ -88,6 +95,7 @@ function load({
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({
captureTarget,
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
@@ -438,6 +446,28 @@ describe('CJK input: Send on Enter', () => {
expect(prompts).toEqual([]);
});
it.each([true, false])('a captured target owns the draft across clear (explicit stash: %s)', (stash) => {
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
CjkInput.restoreDraft('session-a');
type(textarea, 'answer for b');
if (stash) CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM + 'answer for b');
});
it('clear({ discard }) also drops a stash under the captured target', () => {
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
CjkInput.restoreDraft('session-a');
type(textarea, 'answer for b');
CjkInput.stashDraft('session-b');
CjkInput.clear({ discard: true });
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('a restored draft is held text: Backspace edits it without a DEL', () => {
const { CjkInput, textarea, sent } = load();
type(textarea, 'ok');
+91 -3
View File
@@ -63,9 +63,10 @@ function makeTextarea(): FakeTextarea {
const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0';
const IOS_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)';
function loadCjkHarness({ ua = ANDROID_UA }: { ua?: string } = {}) {
function loadCjkHarness({ ua = ANDROID_UA, captureTarget }: { ua?: string; captureTarget?: () => string } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const targets: Array<string | undefined> = [];
const windowObj: Record<string, unknown> = {};
const documentObj = {
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
@@ -88,10 +89,16 @@ function loadCjkHarness({ ua = ANDROID_UA }: { ua?: string } = {}) {
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({ send: (text: string) => sent.push(text) });
CjkInput.init({
captureTarget,
send: (text: string, target?: string) => {
sent.push(text);
targets.push(target);
},
});
textarea.fire('focus');
return { CjkInput, textarea, sent, windowObj, documentObj };
return { CjkInput, textarea, sent, targets, windowObj, documentObj };
}
describe('CJK input module', () => {
@@ -103,6 +110,87 @@ describe('CJK input module', () => {
vi.useRealTimers();
});
it.each(['input', 'keydown', 'compositionstart'])(
'captures the destination at the first %s and releases it after flush',
(start) => {
let target = 'B';
const captureTarget = vi.fn(() => target);
const { CjkInput, textarea, sent, targets } = loadCjkHarness({ captureTarget });
if (start === 'keydown') textarea.fire('keydown', { key: 'x' });
if (start === 'compositionstart') textarea.fire('compositionstart');
textarea.value = PHANTOM + '你好';
if (start === 'input') textarea.fire('input', { inputType: 'insertText', isComposing: false });
target = 'A';
if (start === 'keydown') textarea.fire('input', { inputType: 'insertText', isComposing: false });
if (start === 'compositionstart') textarea.fire('compositionend');
vi.runAllTimers();
CjkInput.flushNow();
expect(sent).toEqual(['你好']);
expect(targets).toEqual(['B']);
expect(captureTarget).toHaveBeenCalledTimes(1);
textarea.value = PHANTOM + '再见';
textarea.fire('input', { inputType: 'insertText', isComposing: false });
vi.runAllTimers();
expect(targets).toEqual(['B', 'A']);
}
);
it.each(['clear', 'escape'])('drops the held destination on %s', (action) => {
let target = 'B';
const { CjkInput, textarea, targets } = loadCjkHarness({ captureTarget: () => target });
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'discard';
if (action === 'clear') CjkInput.clear();
else textarea.fire('keydown', { key: 'Escape' });
target = 'A';
textarea.value = PHANTOM + 'send';
textarea.fire('input', { inputType: 'insertText', isComposing: false });
vi.runAllTimers();
expect(targets).toEqual(['A']);
});
it.each([
{ key: 'Enter' },
{ key: 'c', ctrlKey: true },
{ key: 'ArrowUp' },
{ key: 'End', ctrlKey: true },
{ key: 'Backspace' },
])('routes direct $key control keys through the held or fresh destination', (key) => {
let target = 'B';
const { CjkInput, textarea, targets } = loadCjkHarness({ captureTarget: () => target });
textarea.fire('compositionstart');
textarea.fire('compositionend');
target = 'A';
textarea.fire('keydown', key);
expect(targets).toEqual(['B']);
CjkInput.clear();
textarea.fire('keydown', key);
expect(targets).toEqual(['B', 'A']);
});
it('routes phantom deletion to a freshly captured destination', () => {
const { textarea, sent, targets } = loadCjkHarness({ captureTarget: () => 'B' });
textarea.value = '';
textarea.fire('input', { inputType: 'deleteContentBackward', isComposing: false });
expect(sent).toEqual(['\x7f']);
expect(targets).toEqual(['B']);
});
it('flushNow leaves provisional composition untouched until it commits', () => {
const { CjkInput, textarea, sent } = loadCjkHarness();
textarea.fire('compositionstart');
textarea.value = PHANTOM + '你好';
CjkInput.flushNow();
vi.runAllTimers();
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + '你好');
textarea.fire('compositionend');
CjkInput.flushNow();
expect(sent).toEqual(['你好']);
vi.runAllTimers();
expect(sent).toEqual(['你好']);
});
it('sends committed text after a normal composition cycle', () => {
const { textarea, sent } = loadCjkHarness();
+500
View File
@@ -0,0 +1,500 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
import { WebServer } from '../src/web/server.js';
import { resolve } from 'node:path';
// Browser globals are installed by classic scripts, outside TypeScript's module graph.
type SentInput = { id: string; input: string; time: number };
type CellAnchor = { col: number; row: number };
interface TestTerminal {
textarea: HTMLTextAreaElement;
element: HTMLElement;
write(text: string, callback: () => void): void;
cols: number;
scrollToTop(): void;
buffer: { active: { cursorX: number; cursorY: number; viewportY: number; baseY: number } };
_core: {
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } };
_customKeyEventHandler(event: KeyboardEvent): boolean;
};
}
interface NativeOwner {
reset(reason: string): void;
}
interface TestApp {
terminal: TestTerminal;
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
syncTerminalGeometry(): { cols: number; rows: number } | null;
_resizeTimeout: number | null;
activeSessionId: string;
sessions: Map<string, { id: string; mode: string; status?: string }>;
_localEchoEnabled: boolean;
_isLoadingBuffer: boolean;
_echoPassthroughSessions?: Set<string>;
_localEchoOverlay: { clear(): void; pendingText: string; getInputEndAnchor(): CellAnchor | null };
_iosNativeInput: NativeOwner;
_keyCode229Recovery: unknown;
_enqueueReliableInput(id: string, input: string): unknown;
}
interface TestWindow extends Window {
app: TestApp;
__sent: SentInput[];
CodemanIosNativeInput: { isSupported(): boolean };
IosReplay: {
typeKey(ta: HTMLTextAreaElement, text: string): void;
kev(type: string, key: string, keyCode: number, extra?: { shiftKey?: boolean; ctrlKey?: boolean }): KeyboardEvent;
edit(ta: HTMLTextAreaElement, inputType: string, data: string): boolean;
};
TerminalTile: new (
id: string,
mount: HTMLElement,
options: { mode: string }
) => {
connect(): Promise<void>;
destroy(): void;
terminal: TestTerminal;
_iosNativeInput: NativeOwner;
_keyCode229Recovery: unknown;
};
}
// Real platform timers intentionally cover native reconciliation and the FIFO's 80ms gap.
const IOS_UA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5.2 Mobile/15E148 Safari/604.1';
const SESSION = 'ios830-browser';
describe('iOS native input served-app wiring (#830)', () => {
let server: WebServer;
let browser: Browser;
let context: BrowserContext;
let page: Page;
let baseUrl: string;
beforeAll(async () => {
server = new WebServer(0, false, true);
await server.start();
baseUrl = `http://localhost:${server.boundPort}`;
browser = await chromium.launch({ headless: true });
context = await browser.newContext({
userAgent: IOS_UA,
hasTouch: true,
permissions: ['clipboard-read', 'clipboard-write'],
});
await context.addInitScript(() => {
Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 5 });
const native = window.matchMedia.bind(window);
window.matchMedia = (query) => {
const result = native(query);
if (query === '(pointer: coarse)') Object.defineProperty(result, 'matches', { value: true });
return result;
};
});
}, 90000);
afterAll(async () => {
await browser?.close();
await server?.stop();
}, 60000);
async function setup(echo: boolean) {
if (page) await page.close();
page = await context.newPage();
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => (window as unknown as TestWindow).app?._iosNativeInput, null, { timeout: 30000 });
await page.evaluate(
async ({ echo, session }) => {
const w = window as unknown as TestWindow;
const app = w.app;
app.activeSessionId = session;
app.sessions.set(session, { id: session, mode: 'shell', status: 'idle' });
app._localEchoEnabled = echo;
app._isLoadingBuffer = false;
app._echoPassthroughSessions?.delete(session);
app._localEchoOverlay.clear();
app._iosNativeInput.reset('test');
w.__sent = [];
// Observe the real FIFO/handleTerminalData boundary, not _sendInputAsync.
app._enqueueReliableInput = (id: string, input: string) =>
w.__sent.push({ id, input, time: performance.now() });
await new Promise<void>((resolve) => app.terminal.write('\x1bc❯ ', resolve));
app.terminal.textarea.focus();
},
{ echo, session: SESSION }
);
expect(
await page.evaluate(() => ({
supported: (window as unknown as TestWindow).CodemanIosNativeInput.isSupported(),
recovery: (window as unknown as TestWindow).app._keyCode229Recovery,
}))
).toEqual({ supported: true, recovery: null });
await page.addScriptTag({ path: resolve(import.meta.dirname, 'fixtures/ios-native-replay.js') });
}
async function run(action: string) {
return page.evaluate(async (action) => {
const w = window as unknown as TestWindow;
const app = w.app;
const ta = app.terminal.textarea;
const r = w.IosReplay;
const type = async (text: string) => {
for (const ch of text) {
r.typeKey(ta, ch);
await new Promise((resolve) => setTimeout(resolve, 20));
}
};
await new Function('app', 'ta', 'r', 'type', `return (async () => { ${action} })()`)(app, ta, r, type);
await new Promise((resolve) => setTimeout(resolve, 30));
return { sent: w.__sent, pending: app._localEchoOverlay.pendingText, value: ta.value };
}, action);
}
async function markerCell() {
return page.evaluate(() => {
const terminal = (window as unknown as TestWindow).app.terminal;
const marker = terminal.element.querySelector<HTMLElement>('.ios-native-caret')!;
const cell = terminal._core._renderService.dimensions.css.cell;
return {
display: marker.style.display,
col: Math.round(parseFloat(marker.style.left) / cell.width),
row: Math.round(parseFloat(marker.style.top) / cell.height),
};
});
}
for (const echo of [false, true]) {
it(`suggestion commits hello once, and Enter preserves the 80ms gap (echo ${echo})`, async () => {
await setup(echo);
const before = await run("await type('hel'); r.typeKey(ta, 'lo');");
expect(before.sent.map((x) => x.input)).toEqual(echo ? [] : ['h', 'e', 'l', 'lo']);
const result = await run('r.enter(ta); await new Promise(resolve => setTimeout(resolve, 110));');
expect(result.sent.map((x) => x.input)).toEqual(echo ? ['hello', '\r'] : ['h', 'e', 'l', 'lo', '\r']);
if (echo) expect(result.sent[1].time - result.sent[0].time).toBeGreaterThanOrEqual(75);
});
it(`phrase replacement has no stale prefix (echo ${echo})`, async () => {
await setup(echo);
let result = await run("await type('helloworl'); r.replaceSuggestion(ta, 0, 9, 'Hello World');");
if (echo) result = await run('r.enter(ta); await new Promise(resolve => setTimeout(resolve, 110));');
expect(terminalLine(result.sent.map((x) => x.input).join('')).replace(/\r$/, '')).toBe('Hello World');
});
it(`keyless hold-delete bursts empty the line (echo ${echo})`, async () => {
await setup(echo);
const result = await run("await type('hello'); r.holdDeleteRepeat(ta, 8);");
expect(result.value).toBe('');
expect(terminalLine(result.sent.map((x) => x.input).join(''))).toBe('');
if (echo) {
expect(result.sent).toEqual([]);
expect(result.pending).toBe('');
}
});
it(`dictation replacement and line break never submit (echo ${echo})`, async () => {
await setup(echo);
const result = await run(
"r.edit(ta, 'insertText', 'hello'); r.edit(ta, 'insertText', 'Hello World', [0, 5]); r.edit(ta, 'insertLineBreak', null);"
);
// The native field retains dictated newlines; only the shell projection excludes them.
expect(result.value).toBe('Hello World\n');
expect(result.sent.some((x) => /[\r\n]/.test(x.input))).toBe(false);
});
it(`toolbar Enter resets the next suggestion baseline (echo ${echo})`, async () => {
await setup(echo);
await run("await type('hel'); r.typeKey(ta, 'lo');");
await page
.locator('button[onclick="app.sendEnterKey()"]')
.evaluate((button: HTMLButtonElement) => button.click());
const result = await run("r.typeKey(ta, 'lo'); await new Promise(resolve => setTimeout(resolve, 110));");
expect(result.value).toBe('lo');
expect(result.sent.some((x) => x.input.includes('\x7f'))).toBe(false);
expect(result.sent.map((x) => x.input).join('')).toBe(echo ? 'hello\r' : 'hello\rlo');
if (echo) expect(result.pending).toBe('lo');
});
it(`trackpad caret marker sits at cell (4, 0) after he in hello (echo ${echo})`, async () => {
await setup(echo);
await run(
"await type('hello'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('hello', resolve)); r.caret(ta, 2);"
);
expect(await markerCell()).toEqual({ display: 'block', col: 4, row: 0 });
});
it(`a你b wide wrap maps offsets to (78, 0), (0, 1), (2, 1) (echo ${echo})`, async () => {
await setup(echo);
await page.evaluate(async () => {
const app = (window as unknown as TestWindow).app;
const container = app.terminal.element.parentElement!;
const proposed = app.fitAddon.proposeDimensions()!;
const cell = app.terminal._core._renderService.dimensions.css.cell;
// A raw terminal.resize(80, ...) is undone by the app's ResizeObserver.
// Size its real box instead, so every subsequent auto-fit also yields 80.
const width = parseFloat(getComputedStyle(container).width) + (80 - proposed.cols) * cell.width;
container.style.width = container.style.minWidth = container.style.maxWidth = `${width}px`;
app.syncTerminalGeometry();
const layout = Promise.withResolvers<void>();
requestAnimationFrame(() => requestAnimationFrame(() => layout.resolve()));
await layout.promise;
});
// The real 300ms resize handler can clear the viewport; let it finish
// before installing the prompt and typing the native field.
await page.waitForFunction(() => {
const app = (window as unknown as TestWindow).app;
return app.terminal.cols === 80 && app._resizeTimeout === null;
});
await page.evaluate(async () => {
const app = (window as unknown as TestWindow).app;
const written = Promise.withResolvers<void>();
app.terminal.write('\x1bc' + '.'.repeat(76) + '❯ ', written.resolve);
await written.promise;
});
await run(
"await type('a你b'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('a你b', resolve));"
);
for (const [offset, col, row] of [
[0, 78, 0],
[1, 0, 1],
[2, 2, 1],
]) {
await run(`r.caret(ta, ${offset});`);
expect(await page.evaluate(() => (window as unknown as TestWindow).app.terminal.cols)).toBe(80);
expect(await markerCell()).toEqual({ display: 'block', col, row });
}
});
it(`typing while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
await setup(echo);
const scrolled = await page.evaluate(async () => {
const terminal = (window as unknown as TestWindow).app.terminal;
const written = Promise.withResolvers<void>();
terminal.write('line\r\n'.repeat(200) + '❯ ', written.resolve);
await written.promise;
terminal.scrollToTop();
return { viewportY: terminal.buffer.active.viewportY, baseY: terminal.buffer.active.baseY };
});
expect(scrolled.viewportY).toBe(0);
expect(scrolled.baseY).toBeGreaterThan(0);
const result = await run("await type('h');");
expect(result.sent.map((x) => x.input)).toEqual(echo ? [] : ['h']);
const viewport = await page.evaluate(() => {
const buffer = (window as unknown as TestWindow).app.terminal.buffer.active;
return { viewportY: buffer.viewportY, baseY: buffer.baseY };
});
expect(viewport.viewportY).toBe(viewport.baseY);
});
it(`toolbar Enter while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
await setup(echo);
const scrolled = await page.evaluate(async () => {
const terminal = (window as unknown as TestWindow).app.terminal;
const written = Promise.withResolvers<void>();
terminal.write('line\r\n'.repeat(200) + '❯ ', written.resolve);
await written.promise;
terminal.scrollToTop();
return { viewportY: terminal.buffer.active.viewportY, baseY: terminal.buffer.active.baseY };
});
expect(scrolled.viewportY).toBe(0);
expect(scrolled.baseY).toBeGreaterThan(0);
await page
.locator('button[onclick="app.sendEnterKey()"]')
.evaluate((button: HTMLButtonElement) => button.click());
// Echo on delivers the CR after the local-echo gap: wait for it on the wire.
await page.waitForFunction(() => (window as unknown as TestWindow).__sent.some((x) => x.input === '\r'));
const sent = await page.evaluate(() => (window as unknown as TestWindow).__sent.map((x) => x.input));
expect(sent).toEqual(['\r']);
const viewport = await page.evaluate(() => {
const buffer = (window as unknown as TestWindow).app.terminal.buffer.active;
return { viewportY: buffer.viewportY, baseY: buffer.baseY };
});
expect(viewport.viewportY).toBe(viewport.baseY);
});
}
for (const target of ['main', 'tile'] as const) {
for (const modifier of ['shiftKey', 'ctrlKey'] as const) {
it(`${target} ${modifier} Enter submits only on keydown and swallows keypress/keyup`, async () => {
await setup(false);
const result = await page.evaluate(
async ({ target, modifier, session }) => {
const w = window as unknown as TestWindow;
const mount = document.createElement('div');
document.body.appendChild(mount);
const tile = target === 'tile' ? new w.TerminalTile(session, mount, { mode: 'shell' }) : null;
const originalFetch = window.fetch;
const submitted: unknown[] = [];
window.fetch = async (input, init) => {
if (String(input).endsWith(`/api/sessions/${session}/send-key`)) {
submitted.push(JSON.parse(String(init?.body)));
return new Response('{}', { status: 200 });
}
return originalFetch(input, init);
};
try {
if (tile) await tile.connect();
const terminal = tile ? tile.terminal : w.app.terminal;
// Invoke the installed xterm handler for every phase. xterm can deliver
// keypress even after keydown returns false (the original Shift+Enter bug).
const phases = [];
for (const type of ['keydown', 'keypress', 'keyup']) {
const accepted = terminal._core._customKeyEventHandler(
w.IosReplay.kev(type, 'Enter', 13, { [modifier]: true })
);
await new Promise((resolve) => setTimeout(resolve, 30));
phases.push({ accepted, submitted: [...submitted], sent: [...w.__sent] });
}
return phases;
} finally {
window.fetch = originalFetch;
tile?.destroy();
mount.remove();
}
},
{ target, modifier, session: SESSION }
);
const submission = { key: modifier === 'ctrlKey' ? 'C-Enter' : 'S-Enter' };
expect(result).toEqual([
{ accepted: false, submitted: [submission], sent: [] },
{ accepted: false, submitted: [submission], sent: [] },
{ accepted: false, submitted: [submission], sent: [] },
]);
});
}
}
for (const modifier of ['shiftKey', 'ctrlKey'] as const) {
it(`main iOS suggestion word Enter with ${modifier} and non-13 keyCode stays text`, async () => {
await setup(false);
const result = await page.evaluate(async (modifier) => {
const w = window as unknown as TestWindow;
const app = w.app;
const submitted: string[] = [];
const originalFetch = window.fetch;
window.fetch = async (input, init) => {
if (String(input).endsWith('/send-key')) {
submitted.push(String(init?.body));
return new Response('{}', { status: 200 });
}
return originalFetch(input, init);
};
try {
const ta = app.terminal.textarea;
app.terminal._core._customKeyEventHandler(w.IosReplay.kev('keydown', 'Enter', 69, { [modifier]: true }));
app.terminal._core._customKeyEventHandler(w.IosReplay.kev('keypress', 'Enter', 69, { [modifier]: true }));
w.IosReplay.edit(ta, 'insertText', 'Enter');
app.terminal._core._customKeyEventHandler(w.IosReplay.kev('keyup', 'Enter', 69, { [modifier]: true }));
await new Promise((resolve) => setTimeout(resolve, 110));
return { submitted, sent: w.__sent.map((x) => x.input), value: ta.value };
} finally {
window.fetch = originalFetch;
}
}, modifier);
expect(result).toEqual({ submitted: [], sent: ['Enter'], value: 'Enter' });
});
}
it('retains the old session for Enter during its 80ms window', async () => {
await setup(true);
const result = await run(
"await type('hello'); r.enter(ta); app.sessions.set('ios830-second', { id: 'ios830-second', mode: 'shell' }); app._cleanupPreviousSession(app.activeSessionId); app.activeSessionId = 'ios830-second'; await new Promise(resolve => setTimeout(resolve, 110));"
);
expect(result.sent.map((x) => [x.id, x.input])).toEqual([
[SESSION, 'hello'],
[SESSION, '\r'],
]);
});
it('trusted Chromium paste arrives once', async () => {
await setup(false);
await page.evaluate(() => navigator.clipboard.writeText('trusted paste'));
const cdp = await context.newCDPSession(page);
await cdp.send('Input.dispatchKeyEvent', {
type: 'rawKeyDown',
key: 'Unidentified',
code: '',
windowsVirtualKeyCode: 0,
commands: ['paste'],
});
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'Unidentified',
code: '',
windowsVirtualKeyCode: 0,
});
const result = await run('');
expect(result.sent.map((x) => x.input)).toEqual(['trusted paste']);
await cdp.detach();
});
it('emoji deletion leaves no lone surrogate in pending echo', async () => {
await setup(true);
const result = await run("await type('a😀'); r.backspace(ta);");
expect(result.pending).toBe('a');
expect(result.sent).toEqual([]);
});
for (const echo of [false, true]) {
it.each([
['red heart', '\u2764\uFE0F'],
['skin-tone thumbs up', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
])(`deletes a whole %s grapheme with one backspace (echo ${echo})`, async (_name, emoji) => {
await setup(echo);
const result = await run(`await type(${JSON.stringify('ok' + emoji)}); r.backspace(ta);`);
expect(result.value).toBe('ok');
expect(result.pending).toBe(echo ? 'ok' : '');
expect(result.sent.map((x) => x.input)).toEqual(echo ? [] : [...('ok' + emoji), '\x7f']);
});
}
it('a Pane B/grid TerminalTile owns suggestions for its session without 229 recovery', async () => {
await setup(false);
const result = await page.evaluate(async () => {
const w = window as unknown as TestWindow;
const mount = document.createElement('div');
mount.style.cssText = 'position:fixed;left:0;top:0;width:480px;height:320px;z-index:9999';
document.body.appendChild(mount);
w.app.sessions.set('ios830-tile', { id: 'ios830-tile', mode: 'shell', status: 'idle' });
const tile = new w.TerminalTile('ios830-tile', mount, { mode: 'shell' });
try {
await tile.connect();
const ta = tile.terminal.textarea;
ta.focus();
for (const ch of 'hel') w.IosReplay.typeKey(ta, ch);
w.IosReplay.typeKey(ta, 'lo');
await new Promise((resolve) => setTimeout(resolve, 40));
return { owner: !!tile._iosNativeInput, recovery: tile._keyCode229Recovery, sent: w.__sent };
} finally {
tile.destroy();
mount.remove();
}
});
expect(result.owner).toBe(true);
expect(result.recovery).toBeNull();
expect(result.sent.map((x) => [x.id, x.input])).toEqual(
['h', 'e', 'l', 'lo'].map((input) => ['ios830-tile', input])
);
});
it('non-iOS coarse-pointer pages retain 229 recovery', async () => {
const other = await browser.newContext({ hasTouch: true });
const desktop = await other.newPage();
try {
await desktop.goto(baseUrl, { waitUntil: 'domcontentloaded' });
await desktop.waitForFunction(() => (window as unknown as TestWindow).app?._keyCode229Recovery, null, {
timeout: 30000,
});
expect(await desktop.evaluate(() => (window as unknown as TestWindow).app._iosNativeInput ?? null)).toBeNull();
} finally {
await other.close();
}
});
});
function terminalLine(raw: string) {
const line: string[] = [];
for (const ch of raw) {
if (ch === '\x7f') line.pop();
else line.push(ch);
}
return line.join('');
}
+23 -34
View File
@@ -20,6 +20,7 @@ import { performance } from 'node:perf_hooks';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
type OverlayStub = {
pendingText: string;
@@ -28,6 +29,7 @@ type OverlayStub = {
prompts: unknown[];
clear(): void;
suppressBufferDetection(): void;
getFlushed(): { count: number; text: string };
setPrompt(p: unknown): void;
appendText: ReturnType<typeof vi.fn>;
};
@@ -38,14 +40,15 @@ type AppInstance = {
terminal?: { focus: () => void };
_localEchoEnabled?: boolean;
_localEchoOverlay?: OverlayStub;
_pendingInput: string;
_pendingInput: Map<string, string>;
_inputFlushTimeout: Map<string, NodeJS.Timeout>;
_lastKeystrokeTime: Map<string, number>;
_flushedOffsets?: Map<string, number>;
_flushedTexts?: Map<string, string>;
_echoPassthroughSessions?: Set<string>;
loadAppSettingsFromStorage: () => Record<string, unknown>;
sendInput: ReturnType<typeof vi.fn>;
_enqueueReliableInput: Mock;
_updateLocalEchoState(): void;
_flushLocalEchoPending(): void;
insertTerminalText(text: string): void;
};
@@ -111,6 +114,7 @@ function makeOverlay(pending = ''): OverlayStub {
setPrompt(p: unknown) {
this.prompts.push(p);
},
getFlushed: () => ({ count: 0, text: '' }),
appendText: vi.fn(),
};
}
@@ -120,11 +124,14 @@ function makeApp(mode: string, overlay = makeOverlay()): AppInstance {
app.activeSessionId = 's1';
app.sessions = new Map([['s1', { mode }]]);
app._localEchoOverlay = overlay;
app._pendingInput = '';
app._pendingInput = new Map();
app._inputFlushTimeout = new Map();
app._lastKeystrokeTime = new Map();
app.terminal = { focus: vi.fn() };
app._flushedOffsets = new Map([['s1', 3]]);
app._flushedTexts = new Map([['s1', 'abc']]);
app.loadAppSettingsFromStorage = () => ({ localEchoEnabled: true });
app.sendInput = vi.fn().mockResolvedValue(undefined);
app._enqueueReliableInput = vi.fn();
return app;
}
@@ -179,6 +186,7 @@ describe('_updateLocalEchoState mode gating', () => {
it('disables the overlay for codex sessions even with the setting ON (issues #218/#219/#220/#222)', () => {
const overlay = makeOverlay('pending');
const app = makeApp('codex', overlay);
app._localEchoEnabled = true; // Pending overlay text belongs to an enabled buffer policy.
app._updateLocalEchoState();
expect(app._localEchoEnabled).toBe(false);
expect(overlay.cleared).toBeGreaterThan(0);
@@ -199,25 +207,6 @@ describe('_updateLocalEchoState mode gating', () => {
});
});
describe('_flushLocalEchoPending', () => {
it('moves pending text into _pendingInput and resets overlay + flushed tracking', () => {
const overlay = makeOverlay('hello');
const app = makeApp('claude', overlay);
app._flushLocalEchoPending();
expect(app._pendingInput).toBe('hello');
expect(overlay.cleared).toBe(1);
expect(overlay.suppressed).toBe(1);
expect(app._flushedOffsets!.has('s1')).toBe(false);
expect(app._flushedTexts!.has('s1')).toBe(false);
});
it('appends nothing when the overlay is empty', () => {
const app = makeApp('claude', makeOverlay(''));
app._flushLocalEchoPending();
expect(app._pendingInput).toBe('');
});
});
describe('insertTerminalText pass-through routing', () => {
it('appends to the overlay while local echo is buffering', () => {
const overlay = makeOverlay();
@@ -225,7 +214,7 @@ describe('insertTerminalText pass-through routing', () => {
app._localEchoEnabled = true;
app.insertTerminalText('path.txt');
expect(overlay.appendText).toHaveBeenCalledWith('path.txt');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
it('sends directly while the session is in nav-key pass-through', () => {
@@ -234,7 +223,7 @@ describe('insertTerminalText pass-through routing', () => {
app._localEchoEnabled = true;
app._echoPassthroughSessions = new Set(['s1']);
app.insertTerminalText('path.txt');
expect(app.sendInput).toHaveBeenCalledWith('path.txt');
expect(app._enqueueReliableInput).toHaveBeenCalledWith('s1', 'path.txt', { useMux: true });
expect(overlay.appendText).not.toHaveBeenCalled();
});
});
@@ -425,12 +414,12 @@ describe('_predictHookOnData (wire neutrality)', () => {
it('never touches _pendingInput and never sends (visual-only pin)', () => {
const app = makePredictApp();
app._pendingInput = 'queued';
app._pendingInput.set('s1', 'queued');
for (const data of ['h', 'i', '\x7f', '\r', '\x1b[A', 'multi char', '\x1b[200~x\x1b[201~']) {
app._predictHookOnData(data);
}
expect(app._pendingInput).toBe('queued');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._pendingInput.get('s1')).toBe('queued');
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
it('is inert under buffer/off policies and without a predictor', () => {
@@ -451,21 +440,21 @@ describe('_predictHookOnData (wire neutrality)', () => {
app._predictiveEcho!.predictChar.mockImplementation(() => {
throw new Error('boom');
});
app._pendingInput = 'queued';
app._pendingInput.set('s1', 'queued');
expect(() => app._predictHookOnData('h')).not.toThrow();
expect(app._pendingInput).toBe('queued');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._pendingInput.get('s1')).toBe('queued');
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
});
describe('insertTerminalText under predict policy', () => {
it('routes to sendInput (not the overlay) and clears predictions', () => {
it('routes to reliable input (not the overlay) and clears predictions', () => {
const overlay = makeOverlay();
const app = makeApp('codex', overlay) as PredictiveApp;
app._predictiveEcho = makePredictor();
app._updateLocalEchoState(); // predict; _localEchoEnabled false
app.insertTerminalText('path.txt');
expect(app.sendInput).toHaveBeenCalledWith('path.txt');
expect(app._enqueueReliableInput).toHaveBeenCalledWith('s1', 'path.txt', { useMux: true });
expect(overlay.appendText).not.toHaveBeenCalled();
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled();
});
+54 -45
View File
@@ -428,52 +428,42 @@ describe('mobile IME preview lifecycle', () => {
);
});
/**
* Rebuilds the real `handleTerminalData` closure from initTerminal's source,
* so these cases exercise the shipped routing rather than a copy of it.
*/
/** Runs the real session-bound preprocessing method with deterministic FIFO gaps. */
function loadHandleTerminalData(app: App, sent: string[]) {
const marker = 'const handleTerminalData = (data) => {';
const start = terminalSource.indexOf(marker);
if (start < 0) throw new Error('handleTerminalData definition not found');
const bodyStart = start + marker.length;
const end = terminalSource.indexOf('\n };', bodyStart);
if (end < 0) throw new Error('handleTerminalData boundary not found');
const timers: Array<() => void> = [];
const pending = new Map<string, string>();
const queues = new Map<string, Array<{ write?: string; gap?: number }>>();
const draining = new Set<string>();
app._sendInputAsync = (_sessionId: string, data: string) => sent.push(data);
const context = vm.createContext({
console,
performance,
setTimeout: (callback: () => void) => {
timers.push(callback);
return timers.length;
},
clearTimeout: vi.fn(),
document: { activeElement: null, getElementById: vi.fn(() => null) },
window: {
cjkActive: false,
CodemanTerminalInput: {
BRACKETED_PASTE_START: '\x1b[200~',
shouldSuppressTerminalQueryResponse: () => false,
isTerminalFocusOrMouseReport: () => false,
isComposerNavKey: () => false,
},
},
_crashDiag: { log: vi.fn() },
flushInput: () => {
app._inputFlushTimeout = null;
if (app._pendingInput && app.activeSessionId) {
const input = app._pendingInput;
app._pendingInput = '';
app._sendInputAsync(app.activeSessionId, input);
app._sealPendingInput = (sessionId: string) => {
const data = pending.get(sessionId);
pending.delete(sessionId);
if (data) app._enqueueInput(sessionId, [{ write: data }]);
};
app._appendPendingInput = (sessionId: string, data: string) => {
pending.set(sessionId, (pending.get(sessionId) || '') + data);
timers.push(() => app._sealPendingInput(sessionId));
};
app._enqueueInput = (sessionId: string, ops: Array<{ write?: string; gap?: number }>) => {
const queue = queues.get(sessionId) || [];
queue.push(...ops);
queues.set(sessionId, queue);
if (draining.has(sessionId)) return;
draining.add(sessionId);
function drain() {
while (queue.length) {
const op = queue.shift()!;
if (op.gap !== undefined) {
timers.push(drain);
return;
}
if (op.write !== undefined) app._sendInputAsync(sessionId, op.write);
}
},
});
const handler = vm.runInContext(`(function (data) {${terminalSource.slice(bodyStart, end)}\n})`, context) as (
this: App,
data: string
) => void;
return { handle: (data: string) => handler.call(app, data), timers };
draining.delete(sessionId);
}
drain();
};
return { handle: (data: string) => app._handleTerminalData(data, app.activeSessionId), timers };
}
describe('mobile IME commit onData routing', () => {
@@ -521,9 +511,9 @@ describe('mobile IME commit onData routing', () => {
_echoPassthroughSessions: new Set(),
_flushedOffsets: new Map(),
_flushedTexts: new Map(),
_pendingInput: '',
_inputFlushTimeout: null,
_lastKeystrokeTime: 0,
_pendingInput: new Map(),
_inputFlushTimeout: new Map(),
_lastKeystrokeTime: new Map(),
_terminalOutputSeq: 5,
_mobileImePreview: controller,
});
@@ -720,3 +710,22 @@ describe('mobile IME commit and authoritative terminal output', () => {
expect(controller.noteAuthoritativeOutput).toHaveBeenCalledOnce();
});
});
describe('native owner and preview shared platform gate', () => {
it('loads the preview first and delegates native support to its single predicate', () => {
const exposed: {
navigator: { userAgent: string; maxTouchPoints: number };
MobileImePreview?: { isIosWebKitTouch(nav: unknown): boolean };
CodemanIosNativeInput?: { isSupported(): boolean };
} = {
navigator: { userAgent: 'iPhone AppleWebKit/605.1.15', maxTouchPoints: 5 },
};
const context = vm.createContext({ window: exposed, globalThis: exposed });
vm.runInContext(read('src/web/public/mobile-ime-preview.js'), context);
vm.runInContext(read('src/web/public/terminal-ios-native-input.js'), context);
expect(exposed.CodemanIosNativeInput!.isSupported()).toBe(true);
const shared = vi.spyOn(exposed.MobileImePreview!, 'isIosWebKitTouch').mockReturnValue(false);
expect(exposed.CodemanIosNativeInput!.isSupported()).toBe(false);
expect(shared).toHaveBeenCalledWith(exposed.navigator);
});
});
+95
View File
@@ -55,6 +55,8 @@ class FakeNode {
class FakeTextarea extends FakeNode {
value = 'unchanged';
selectionStart = 0;
selectionEnd = 0;
}
type Scheduled = { id: number; callback: () => void; delay?: number };
@@ -133,8 +135,101 @@ function harness(
}
describe('MobileImePreview', () => {
test('native composition ignores xterm terminal-key finalization heuristics', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionupdate', { data: 'に' });
h.textarea.dispatch('keydown', { key: 'x', keyCode: 88 });
expect(h.controller.state.composing).toBe(true);
expect(h.controller.state.awaitingCommit).toBe(false);
h.textarea.dispatch('compositionupdate', { data: '日本' });
h.textarea.dispatch('compositionend', { data: '日本' });
expect(h.controller.nativeTransaction({ inserted: '日本', deleted: 0, composition: true })).toBe(true);
expect(h.onCommit).toHaveBeenCalledWith('日本');
});
beforeEach(() => vi.restoreAllMocks());
test.each([
{ inserted: '', deleted: 2, composition: true },
{ inserted: '', deleted: 0, composition: true },
{ inserted: '', deleted: 0, composition: false },
])('settles an awaiting native transaction immediately: %j', (transaction) => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionupdate', { data: 'draft' });
h.textarea.dispatch('compositionend', { data: '' });
expect(h.controller.state.awaitingCommit).toBe(true);
h.clear.mockClear();
expect(h.controller.nativeTransaction(transaction)).toBe(false);
expect(h.controller.state.awaitingCommit).toBe(false);
expect(h.controller.state.committed).toBe(false);
expect(h.frames).toHaveLength(0);
expect(h.timers).toHaveLength(0);
expect(h.clear).toHaveBeenCalledOnce();
expect(h.controller.consumeTerminalData('unrelated')).toBe(false);
expect(h.onCommit).not.toHaveBeenCalled();
});
test('hands native inserted text through the existing commit lifecycle exactly once', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionend', { data: 'teh' });
expect(h.controller.nativeTransaction({ inserted: 'the', deleted: 3, composition: true })).toBe(true);
expect(h.onCommit).toHaveBeenCalledExactlyOnceWith('the');
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'the', phase: 'committed' });
expect(h.controller.nativeTransaction({ inserted: 'the', deleted: 0, composition: true })).toBe(false);
expect(h.onCommit).toHaveBeenCalledOnce();
h.controller.completeCommit({ predicted: true });
expect(h.timers).toHaveLength(0);
});
test('null-data native provisional input extracts only the composition segment', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.value = 'retained suffix';
h.textarea.selectionStart = h.textarea.selectionEnd = 9;
h.textarea.dispatch('compositionstart');
h.textarea.value = 'retained 日本suffix';
h.textarea.selectionStart = h.textarea.selectionEnd = 11;
h.textarea.dispatch('input', { data: null, isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: '日本', phase: 'provisional' });
h.textarea.dispatch('compositionupdate', { data: null });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: '日本', phase: 'provisional' });
h.textarea.dispatch('input', { data: 'event wins', isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'event wins', phase: 'provisional' });
expect(h.textarea.value).toBe('retained 日本suffix');
});
test.each([undefined, () => false])(
'keeps whole-value provisional fallback without native ownership (%s)',
(ownsNativeInput) => {
const h = harness({ ownsNativeInput });
h.textarea.value = 'retained ';
h.textarea.selectionStart = h.textarea.selectionEnd = 9;
h.textarea.dispatch('compositionstart');
h.textarea.value = 'retained 日本';
h.textarea.selectionStart = h.textarea.selectionEnd = 11;
h.textarea.dispatch('input', { data: null, isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'retained 日本', phase: 'provisional' });
}
);
test('ignores native notifications outside an awaiting commit and after destruction', () => {
const h = harness();
expect(h.controller.nativeTransaction({ inserted: 'ordinary', deleted: 0, composition: false })).toBe(false);
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionend');
h.controller.destroy();
expect(h.controller.nativeTransaction({ inserted: 'late', deleted: 0, composition: true })).toBe(false);
expect(h.onCommit).not.toHaveBeenCalled();
});
test('collapses 500 composition updates into one latest-state frame', () => {
const h = harness();
h.textarea.dispatch('compositionstart');
+40 -22
View File
@@ -50,6 +50,10 @@ function loadComposer(sessionId = 'session-1') {
_echoPassthroughSessions: new Set<string>(),
_predictiveEcho: { clearPredictions: vi.fn() },
_sendInputAsync: vi.fn(),
_enqueueInput: vi.fn(),
_focusedPane: () => ({ sessionId: app.activeSessionId, isPrimary: true }),
_paneForSession: (id: string) => (id === app.activeSessionId ? app._focusedPane() : null),
_prepareExternalInput: vi.fn(),
_uploadAndInsertImages: vi.fn(async () => ['/tmp/image-one.png']),
_promptAttachKind: (file: { type: string; name?: string }) =>
file.type.startsWith('image/')
@@ -265,12 +269,21 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledOnce();
expect(app._sendInputAsync).toHaveBeenNthCalledWith(1, 'session-1', '\x1b[200~first line\rsecond line\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: '\x1b[200~first line\rsecond line\x1b[201~' },
{ gap: 120 },
{ write: '\r', useMux: true },
]);
expect(app._prepareExternalInput).toHaveBeenLastCalledWith(
{ sessionId: 'session-1', isPrimary: true },
'accessory-compose-send',
{ flushEcho: true }
);
expect(composeButton.classList.contains('has-draft')).toBe(false);
expect(timers).toContainEqual(expect.objectContaining({ delay: 120 }));
expect(timers.some((timer) => timer.delay === 120)).toBe(false);
runTimers();
expect(app._sendInputAsync).toHaveBeenNthCalledWith(2, 'session-1', '\r', { useMux: true });
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(document.querySelector('.prompt-composer-overlay')).toBeNull();
bar.composePrompt();
@@ -287,11 +300,15 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~still\rmultiline\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: '\x1b[200~still\rmultiline\x1b[201~' },
{ gap: 120 },
{ write: '\r', useMux: true },
]);
expect(document.querySelector('.prompt-composer-overlay')).toBeNull();
expect(app.showToast).not.toHaveBeenCalled();
runTimers();
expect(app._sendInputAsync).toHaveBeenLastCalledWith('session-1', '\r', { useMux: true });
expect(app._enqueueInput).toHaveBeenCalledOnce();
});
it('releases echo passthrough after a composed prompt is queued', () => {
@@ -343,8 +360,8 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app._sendInputAsync).toHaveBeenCalledOnce();
expect((app._sendInputAsync.mock.calls[0][1] as string).length).toBe(64 * 1024);
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(app._enqueueInput.mock.calls[0][1][0].write.length).toBe(64 * 1024);
expect(app.showToast).not.toHaveBeenCalled();
});
@@ -369,6 +386,7 @@ describe('mobile prompt composer', () => {
it('uploads images without writing into the PTY and inserts their paths into the draft', async () => {
const { app, bar, document } = loadComposer();
app._focusedPane = () => ({ sessionId: 'session-2', isPrimary: false });
let finishUpload!: (paths: string[]) => void;
app._uploadAndInsertImages.mockImplementation(
() => new Promise<string[]>((resolveUpload) => (finishUpload = resolveUpload))
@@ -388,7 +406,7 @@ describe('mobile prompt composer', () => {
finishUpload(['/tmp/image-one.png']);
await vi.waitFor(() => expect(input.value).toBe('review /tmp/image-one.png'));
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false, sessionId: 'session-2' });
expect((document.querySelector('.paste-send') as HTMLButtonElement).disabled).toBe(false);
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).not.toHaveBeenCalled();
@@ -603,7 +621,7 @@ describe('mobile prompt composer', () => {
Object.defineProperty(fileInput, 'files', { configurable: true, value: [video, pdf, script] });
fileInput.dispatchEvent(new document.defaultView!.Event('change', { bubbles: true }));
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false, sessionId: 'session-1' });
expect(app.showToast).toHaveBeenCalledWith('1 file skipped: unsupported type', 'info');
await vi.waitFor(() => expect(textarea(document).value).toContain('/tmp/image-one.png'));
});
@@ -668,7 +686,7 @@ describe('mobile prompt composer', () => {
});
input.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false, sessionId: 'session-1' });
});
});
@@ -697,11 +715,10 @@ describe('mobile shell Paste', () => {
send.click();
runTimers();
expect(app._sendInputAsync).toHaveBeenCalledOnce();
expect(app._sendInputAsync).toHaveBeenCalledWith(
'session-1',
'\x1b[200~cd ~/dotfiles\rgit pull\r./sync.sh\x1b[201~'
);
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: '\x1b[200~cd ~/dotfiles\rgit pull\r./sync.sh\x1b[201~' },
]);
expect(document.querySelector('.paste-overlay')).toBeNull();
});
@@ -711,7 +728,7 @@ describe('mobile shell Paste', () => {
send.click();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~echo one\recho two\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [{ write: '\x1b[200~echo one\recho two\x1b[201~' }]);
});
it('drops paste markers inside the text, so a pasted ESC[201~ cannot end the bracket early', () => {
@@ -722,7 +739,7 @@ describe('mobile shell Paste', () => {
send.click();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~echo safe\rrm -rf ~/x\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [{ write: '\x1b[200~echo safe\rrm -rf ~/x\x1b[201~' }]);
});
it('drops a paste marker hidden inside another one', () => {
@@ -732,7 +749,7 @@ describe('mobile shell Paste', () => {
send.click();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~ok\rrm -rf ~/x\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [{ write: '\x1b[200~ok\rrm -rf ~/x\x1b[201~' }]);
});
it('refuses a paste longer than one input frame and keeps the text for trimming', () => {
@@ -741,7 +758,7 @@ describe('mobile shell Paste', () => {
send.click();
expect(app._sendInputAsync).not.toHaveBeenCalled();
expect(app._enqueueInput).not.toHaveBeenCalled();
expect(app.showToast).toHaveBeenCalledWith(expect.stringContaining('too long'), 'error');
expect(document.querySelector('.paste-overlay')).not.toBeNull();
expect(input.value.length).toBe(bar._composerMaxLength + 1);
@@ -754,7 +771,8 @@ describe('mobile shell Paste', () => {
send.click();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~ls\rpwd\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [{ write: '\x1b[200~ls\rpwd\x1b[201~' }]);
expect(app._prepareExternalInput).not.toHaveBeenCalled();
});
it('uploads a picked image to the shell it was opened for after a tab switch', () => {
@@ -816,7 +834,7 @@ describe('mobile shell Paste', () => {
send.click();
runTimers();
expect(app._sendInputAsync).not.toHaveBeenCalled();
expect(app._enqueueInput).not.toHaveBeenCalled();
expect(document.querySelector('.paste-overlay')).toBeNull();
});
});
+74 -67
View File
@@ -160,6 +160,7 @@ function loadBar(sessionMode = 'claude') {
activeSessionId: 'session-1',
sessions: new Map<string, { mode: string }>([['session-1', { mode: sessionMode }]]),
terminal: { focus: vi.fn() },
_enqueueInput: vi.fn(),
};
const fetchMock = vi.fn(() => Promise.resolve({ ok: true, catch: () => {} }));
const barElement = fakeBarElement();
@@ -499,10 +500,14 @@ describe('one-shot Ctrl through the CJK input field', () => {
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string;
_sendInputAsync: ReturnType<typeof vi.fn>;
_focusedPane: () => { terminal: object; sessionId: string; isPrimary: boolean };
_prepareExternalInput: (...args: unknown[]) => void;
_handleCjkInput(text: string): void;
};
app.activeSessionId = 'cjk-session';
app._sendInputAsync = vi.fn();
app._focusedPane = () => ({ terminal: {}, sessionId: app.activeSessionId, isPrimary: true });
app._prepareExternalInput = vi.fn();
return { app, bar };
}
@@ -549,27 +554,43 @@ 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.
// _sendCjkPrompt is CjkInput's sendPrompt callback, called with the session
// CjkInput captured for the text (_targetForSend). Anything longer than one
// character goes to the composer's _sendComposedPrompt for that session; one
// character, the 120 ms gap and Enter are reserved on that session's FIFO, so
// the delayed Enter cannot follow a tab switch.
type PromptApp = {
activeSessionId: string | null;
sessions: Map<string, { mode: string }>;
pendingHooks?: Map<string, Set<string>>;
_focusedPane(): { sessionId: string | null; terminal: object; isPrimary: boolean } | null;
_paneForSession(id: string): null;
_enqueueReliableInput(id: string, input: string, opts?: { useMux?: boolean }): void;
_sendCjkPrompt(text: string, sessionId?: string): boolean;
};
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
const app = Object.create(CodemanApp.prototype) as PromptApp;
app.activeSessionId = 'session-a';
app.sessions = new Map([
['session-a', { mode: 'claude' }],
['session-b', { mode: 'claude' }],
]);
app._focusedPane = () => ({ sessionId: app.activeSessionId, terminal: {}, isPrimary: true });
app._paneForSession = () => null;
const writes: Array<[string, string, boolean]> = [];
app._enqueueReliableInput = (id, input, opts) => void writes.push([id, input, opts?.useMux === true]);
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
return { app, bar, composed, writes };
}
it('sends through the composer path, bound to the session active at Enter', () => {
it('sends through the composer path for the captured session, not the active one', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(app._sendCjkPrompt('line one\nline two', 'session-a')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
@@ -577,28 +598,28 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
app._sendCjkPrompt('x'.repeat(100), 'session-a');
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('types a single character, then Enter ~120 ms later to the same session', () => {
it('types a single character, then Enter 120 ms later on the same session FIFO across a switch', () => {
// 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).
// split as the tmux manager's submitsAsKeys path.
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]]);
const { app, composed, writes } = promptApp();
expect(app._sendCjkPrompt('1', 'session-a')).toBe(true);
expect(writes).toEqual([['session-a', '1', false]]);
app.activeSessionId = 'session-b';
vi.advanceTimersByTime(119);
expect(writes).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
expect(writes).toEqual([
['session-a', '1', false],
['session-a', '\r', true],
]);
expect(composed).not.toHaveBeenCalled();
composed.mockRestore();
} finally {
@@ -613,19 +634,11 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
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);
const { app, composed, writes } = promptApp();
app.pendingHooks = new Map([['session-a', new Set([hook])]]);
expect(app._sendCjkPrompt('2', 'session-a')).toBe(true);
vi.advanceTimersByTime(500);
expect(writes).toEqual([['session-a', '2', undefined]]);
expect(writes).toEqual([['session-a', '2', false]]);
composed.mockRestore();
}
} finally {
@@ -641,21 +654,13 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
['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);
const { app, composed, writes } = promptApp();
app.pendingHooks = new Map([['session-a', new Set([hook])]]);
expect(app._sendCjkPrompt(text, 'session-a')).toBe(true);
vi.advanceTimersByTime(120);
expect(writes).toEqual([
['session-a', text, undefined],
['session-a', '\r', { useMux: true }],
['session-a', text, false],
['session-a', '\r', true],
]);
composed.mockRestore();
}
@@ -666,19 +671,22 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
it('pastes even a short word: only one character is typed', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('yes')).toBe(true);
expect(app._sendCjkPrompt('yes', 'session-a')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
const { app, composed, writes } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('x'.repeat(100), 'session-a')).toBe(false);
// A captured session that closed meanwhile, or no session at all, sends nothing.
expect(app._sendCjkPrompt('1', 'session-gone')).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('1')).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
expect(writes).toEqual([]);
composed.mockRestore();
});
});
@@ -724,14 +732,15 @@ describe('composer nav keys from the bar', () => {
const app = loaded.app as unknown as Record<string, unknown>;
app._localEchoEnabled = true;
app._localEchoOverlay = overlay;
app.sendInput = vi.fn();
app._flushedOffsets = new Map([['session-1', 3]]);
app._flushedTexts = new Map([['session-1', 'dra']]);
return { ...loaded, app, overlay };
}
const sentKeys = (fetchMock: { mock: { calls: unknown[][] } }) =>
fetchMock.mock.calls.map((call) => JSON.parse((call[1] as { body: string }).body).input);
const sentKeys = (enqueue: { mock: { calls: unknown[][] } }) =>
enqueue.mock.calls.flatMap((call) =>
(call[1] as { write?: string }[]).filter((op) => op.write?.startsWith('\x1b')).map((op) => op.write)
);
it.each(['simple', 'extended'])('exposes Shift arrows in the %s agent layout', (mode) => {
const { bar, barElement } = loadBar('codex');
@@ -744,19 +753,15 @@ describe('composer nav keys from the bar', () => {
['shift-left', '\x1b[1;2D'],
['shift-right', '\x1b[1;2C'],
])('%s flushes the draft before navigation and hands editing to the PTY', (action, sequence) => {
const { bar, app, overlay, fetchMock } = barWithDraft('unfinished follow-up');
const events: string[] = [];
app.sendInput = vi.fn(() => events.push('draft'));
fetchMock.mockImplementation(() => {
events.push('key');
return Promise.resolve({ ok: true, catch: () => {} });
});
const { bar, app, overlay } = barWithDraft('unfinished follow-up');
bar.handleAction(action);
expect(app.sendInput).toHaveBeenCalledWith('unfinished follow-up');
expect(events).toEqual(['draft', 'key']);
expect(sentKeys(fetchMock)).toEqual([sequence]);
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: 'unfinished follow-up', useMux: true },
{ gap: 120 },
{ write: sequence },
]);
expect(overlay.pendingText).toBe('');
expect([...(app._echoPassthroughSessions as Set<string>)]).toEqual(['session-1']);
});
@@ -768,12 +773,15 @@ describe('composer nav keys from the bar', () => {
// goes on painting the draft over the same row and still believes it is
// pending. Flushing first is also what makes the draft recoverable: the
// CLI stashes the live composer and hands it back on Down.
const { bar, app, overlay, fetchMock } = barWithDraft('draft I typed');
const { bar, app, overlay } = barWithDraft('draft I typed');
bar.handleAction('scroll-up');
expect(app.sendInput).toHaveBeenCalledWith('draft I typed');
expect(sentKeys(fetchMock)).toEqual(['\x1b[A']);
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: 'draft I typed', useMux: true },
{ gap: 120 },
{ write: '\x1b[A' },
]);
expect(overlay.pendingText).toBe('');
expect(overlay.suppressBufferDetection).toHaveBeenCalled();
// The overlay's bookkeeping for this session has to go with it.
@@ -793,15 +801,14 @@ describe('composer nav keys from the bar', () => {
});
it('sends all four arrows and skips the flush when there is no draft', () => {
const { bar, app, fetchMock } = barWithDraft('');
const { bar, app } = barWithDraft('');
bar.handleAction('scroll-up');
bar.handleAction('scroll-down');
bar.handleAction('arrow-left');
bar.handleAction('arrow-right');
expect(sentKeys(fetchMock)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']);
expect(app.sendInput).not.toHaveBeenCalled();
expect(sentKeys(app._enqueueInput as ReturnType<typeof vi.fn>)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']);
});
});
+13 -13
View File
@@ -865,7 +865,7 @@ describe('Virtual Keyboard', () => {
},
suppressBufferDetection() {},
};
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1018,7 +1018,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1074,7 +1074,7 @@ describe('Virtual Keyboard', () => {
mode: 'codex',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1120,7 +1120,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'working',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1179,7 +1179,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'working',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1273,7 +1273,7 @@ describe('Virtual Keyboard', () => {
mode: 'codex',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1317,7 +1317,7 @@ describe('Virtual Keyboard', () => {
mode: 'claude',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1461,7 +1461,7 @@ describe('Virtual Keyboard', () => {
status: 'running',
});
app.hideWelcome();
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1542,7 +1542,7 @@ describe('Virtual Keyboard', () => {
status: 'running',
});
app.hideWelcome();
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1591,7 +1591,7 @@ describe('Virtual Keyboard', () => {
// applied to the next character typed on the SYSTEM keyboard, which on a
// phone reaches the app as xterm onData text, not a key event. These drive
// the real xterm instance with page.keyboard.type() and assert on what would
// go out on the wire (_sendInputAsync), not on DOM state alone.
// go out on the wire (_enqueueReliableInput, behind the session FIFO), not on DOM state alone.
describe('Shell keyboard bar', () => {
let context: BrowserContext;
@@ -1620,14 +1620,14 @@ describe('Virtual Keyboard', () => {
async function typeAndCapture(text: string): Promise<string[]> {
await page.evaluate(`(function () {
window.__sent = [];
if (!app.__origSend) app.__origSend = app._sendInputAsync;
app._sendInputAsync = function (sessionId, input) { window.__sent.push(input); };
if (!app.__origSend) app.__origSend = app._enqueueReliableInput;
app._enqueueReliableInput = function (sessionId, input) { window.__sent.push(input); };
app.terminal.focus();
})()`);
await page.keyboard.type(text);
await page.waitForTimeout(200);
const sent = (await page.evaluate(`window.__sent`)) as string[];
await page.evaluate(`(function () { app._sendInputAsync = app.__origSend; })()`);
await page.evaluate(`(function () { app._enqueueReliableInput = app.__origSend; })()`);
return sent;
}
+120 -37
View File
@@ -43,7 +43,15 @@ function loadKeyboardModule() {
terminal: { focus: vi.fn() },
clearTerminalInput: vi.fn(),
insertTerminalText: vi.fn(),
sendInput: vi.fn(),
_enqueueInput: vi.fn(),
_sendInputAsync: vi.fn(),
_focusedPane: () => ({ sessionId: 'session-1', isPrimary: true }),
_paneForSession: (sessionId: string) => ({ sessionId, isPrimary: true }),
_localEchoEnabled: false,
_localEchoPolicy: 'off',
_predictiveEcho: { clearPredictions: vi.fn() },
_localEchoOverlay: { appendText: vi.fn() },
_prepareExternalInput: vi.fn(),
};
const fetchMock = vi.fn(() => Promise.resolve({ ok: true }));
const context = vm.createContext({
@@ -85,11 +93,32 @@ describe('accessory Tab key', () => {
const { app, bar, fetchMock } = loadKeyboardModule();
bar.handleAction('tab');
expect(app.sendInput).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledOnce();
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/sessions/session-1/input');
expect(JSON.parse(init.body)).toEqual({ input: '\t' });
expect(fetchMock).not.toHaveBeenCalled();
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [{ write: '\t' }]);
});
it('prepares the native owner before sending to the captured session', () => {
const { app, bar } = loadKeyboardModule();
Object.assign(app, {
_localEchoEnabled: true,
_localEchoOverlay: { pendingText: 'queued text', clear: vi.fn() },
});
app._prepareExternalInput.mockImplementation(() => {
app.activeSessionId = 'session-2';
});
bar.handleAction('tab');
expect(app._prepareExternalInput).toHaveBeenCalledWith(
{ sessionId: 'session-1', isPrimary: true },
'accessory-key'
);
expect(app._enqueueInput).toHaveBeenCalledExactlyOnceWith('session-1', [
{ write: 'queued text', useMux: true },
{ gap: 120 },
{ write: '\t' },
]);
expect(app._prepareExternalInput.mock.invocationCallOrder[0]).toBeLessThan(
app._enqueueInput.mock.invocationCallOrder[0]
);
});
it('flushes locally-buffered prompt text to the PTY before sending Tab', () => {
@@ -114,13 +143,21 @@ describe('accessory Tab key', () => {
expect(overlay.suppressBufferDetection).toHaveBeenCalledOnce();
expect((app as { _flushedOffsets: Map<string, number> })._flushedOffsets.has('session-1')).toBe(false);
expect((app as { _flushedTexts: Map<string, string> })._flushedTexts.has('session-1')).toBe(false);
expect(app.sendInput).toHaveBeenCalledWith('git sta');
expect(fetchMock).toHaveBeenCalledOnce();
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ input: '\t' });
// Text must reach the PTY before the completion request.
const sendInputOrder = (app.sendInput as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0];
const fetchOrder = fetchMock.mock.invocationCallOrder[0];
expect(sendInputOrder).toBeLessThan(fetchOrder);
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: 'git sta', useMux: true },
{ gap: 120 },
{ write: '\t' },
]);
});
});
describe('toolbar Enter', () => {
it('uses semantic submit instead of replaying native textarea data', () => {
const context = vm.createContext({ CodemanApp: function () {} });
vm.runInContext(`${sessionSource}\nglobalThis.__mixin = CodemanApp.prototype;`, context);
const submitFromToolbar = vi.fn();
context.__mixin.sendEnterKey.call({ submitFromToolbar });
expect(submitFromToolbar).toHaveBeenCalledOnce();
});
});
@@ -130,7 +167,6 @@ describe('mobile filesystem picker actions', () => {
bar.handleAction('clear-input');
expect(app.clearTerminalInput).toHaveBeenCalledOnce();
expect(app.sendInput).not.toHaveBeenCalled();
expect(keyboardSource).toContain('data-action="clear-input"');
expect(keyboardSource).toContain('data-action="clear" title="/clear"');
});
@@ -149,8 +185,60 @@ describe('mobile filesystem picker actions', () => {
directoriesOnly: false,
});
options.onSelect('/mnt/d/AI/project/file.ts');
expect(app.insertTerminalText).toHaveBeenCalledWith('/mnt/d/AI/project/file.ts');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/mnt/d/AI/project/file.ts', { useMux: true });
});
it.each([false, true])('clears primary predictions before inserting a path (buffered=%s)', (buffered) => {
const { app, bar, picker } = loadKeyboardModule();
app._localEchoPolicy = 'predict';
app._localEchoEnabled = buffered;
picker.open = vi.fn();
bar.handleAction('pick-path');
picker.open.mock.calls[0][0].onSelect('/project/file.ts');
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalledOnce();
const insert = buffered ? app._localEchoOverlay.appendText : app._sendInputAsync;
expect(app._predictiveEcho.clearPredictions.mock.invocationCallOrder[0]).toBeLessThan(
insert.mock.invocationCallOrder[0]
);
});
it.each([false, true])(
'appends a picked path to the destination primary overlay without flushing (focus moved=%s)',
(moved) => {
const { app, bar, picker } = loadKeyboardModule();
app._localEchoEnabled = true;
picker.open = vi.fn();
bar.handleAction('pick-path');
if (moved) app._focusedPane = () => ({ sessionId: 'tile-2', isPrimary: false });
picker.open.mock.calls[0][0].onSelect('/project/file.ts');
expect(app._prepareExternalInput).toHaveBeenCalledWith(
{ sessionId: 'session-1', isPrimary: true },
'accessory-path'
);
expect(app._localEchoOverlay.appendText).toHaveBeenCalledWith('/project/file.ts');
expect(app._sendInputAsync).not.toHaveBeenCalled();
expect(app.terminal.focus).toHaveBeenCalledOnce();
}
);
it('prepares an unfocused tile destination with flushEcho before directly writing its path', () => {
const { app, bar, picker } = loadKeyboardModule();
app._localEchoEnabled = true;
app._focusedPane = () => ({ sessionId: 'tile-2', isPrimary: false });
app._paneForSession = (sessionId: string) => ({ sessionId, isPrimary: false });
picker.open = vi.fn();
bar.handleAction('pick-path');
app._focusedPane = () => ({ sessionId: 'session-1', isPrimary: true });
picker.open.mock.calls[0][0].onSelect('/project/file.ts');
expect(app._prepareExternalInput).toHaveBeenCalledWith(
{ sessionId: 'tile-2', isPrimary: false },
'accessory-path',
{ flushEcho: true }
);
expect(app._sendInputAsync).toHaveBeenCalledWith('tile-2', '/project/file.ts', { useMux: true });
expect(app._localEchoOverlay.appendText).not.toHaveBeenCalled();
});
it('wires Link Existing to the shared folder-only picker', () => {
@@ -171,33 +259,30 @@ describe('mobile filesystem picker actions', () => {
it('inserts a selected path into the editable local-echo prompt without sending it', () => {
const appendText = vi.fn();
const sendInput = vi.fn();
const focus = vi.fn();
const app = {
activeSessionId: 'session-1',
_localEchoEnabled: true,
_localEchoOverlay: { appendText },
terminal: { focus },
sendInput,
_focusedPane: () => ({ terminal: app.terminal, sessionId: app.activeSessionId, isPrimary: true }),
_prepareExternalInput: vi.fn(),
};
terminalHarness.mixin.insertTerminalText.call(app, '/mnt/d/AI/project');
expect(appendText).toHaveBeenCalledWith('/mnt/d/AI/project');
expect(sendInput).not.toHaveBeenCalled();
expect(focus).toHaveBeenCalledOnce();
});
it('clears pending and already-flushed prompt text without invoking /clear', () => {
const clear = vi.fn();
const suppressBufferDetection = vi.fn();
const sendInput = vi.fn(() => Promise.resolve());
const showToast = vi.fn();
const focus = vi.fn();
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: 'pending text',
_localEchoEnabled: true,
_localEchoOverlay: {
getFlushed: () => ({ count: 4, text: 'a😀b' }),
@@ -206,18 +291,22 @@ describe('mobile filesystem picker actions', () => {
},
_flushedOffsets: new Map([['session-1', 4]]),
_flushedTexts: new Map([['session-1', 'a😀b']]),
sendInput,
_sendInputAsync: vi.fn(),
_focusedPane: () => ({ terminal: app.terminal, sessionId: app.activeSessionId, isPrimary: true }),
_prepareExternalInput: vi.fn(),
showToast,
terminal: { focus },
};
terminalHarness.mixin.clearTerminalInput.call(app);
expect(app._pendingInput).toBe('');
expect(app._prepareExternalInput).toHaveBeenCalledWith(
expect.objectContaining({ sessionId: 'session-1' }),
'clear'
);
expect(clear).toHaveBeenCalledOnce();
expect(suppressBufferDetection).toHaveBeenCalledOnce();
expect(sendInput).toHaveBeenCalledWith('\x7f'.repeat(3));
expect(sendInput).not.toHaveBeenCalledWith('/clear');
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x7f'.repeat(3), { useMux: true });
expect(app._flushedOffsets.size).toBe(0);
expect(app._flushedTexts.size).toBe(0);
expect(showToast).toHaveBeenCalledWith('Input cleared', 'success');
@@ -227,7 +316,6 @@ describe('mobile filesystem picker actions', () => {
it('sends a picked path to the tile or Pane B that holds the keyboard, never the parked main overlay', () => {
const appendText = vi.fn();
const sendInput = vi.fn();
const _sendInputAsync = vi.fn();
const mainFocus = vi.fn();
const tileFocus = vi.fn();
@@ -236,8 +324,8 @@ describe('mobile filesystem picker actions', () => {
_localEchoEnabled: true,
_localEchoOverlay: { appendText },
terminal: { focus: mainFocus },
sendInput,
_sendInputAsync,
_prepareExternalInput: vi.fn(),
_focusedPane: () => ({ terminal: { focus: tileFocus }, sessionId: 'tile-2', isPrimary: false, tile: {} }),
};
@@ -245,25 +333,22 @@ describe('mobile filesystem picker actions', () => {
expect(_sendInputAsync).toHaveBeenCalledWith('tile-2', '/mnt/d/AI/project');
expect(appendText).not.toHaveBeenCalled();
expect(sendInput).not.toHaveBeenCalled();
expect(tileFocus).toHaveBeenCalledOnce();
expect(mainFocus).not.toHaveBeenCalled();
});
it('clears the prompt of the tile or Pane B that holds the keyboard with Ctrl+U, leaving the main overlay alone', () => {
const clear = vi.fn();
const sendInput = vi.fn(() => Promise.resolve());
const _sendInputAsync = vi.fn();
const showToast = vi.fn();
const tileFocus = vi.fn();
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: 'main pane text',
_localEchoEnabled: true,
_localEchoOverlay: { getFlushed: () => ({ count: 0, text: '' }), clear, suppressBufferDetection: vi.fn() },
sendInput,
_sendInputAsync,
_prepareExternalInput: vi.fn(),
showToast,
terminal: { focus: vi.fn() },
_focusedPane: () => ({ terminal: { focus: tileFocus }, sessionId: 'tile-2', isPrimary: false, tile: {} }),
@@ -272,28 +357,26 @@ describe('mobile filesystem picker actions', () => {
terminalHarness.mixin.clearTerminalInput.call(app);
expect(_sendInputAsync).toHaveBeenCalledWith('tile-2', '\x15');
expect(sendInput).not.toHaveBeenCalled();
expect(clear).not.toHaveBeenCalled();
expect(app._pendingInput).toBe('main pane text');
expect(showToast).toHaveBeenCalledWith('Input cleared', 'success');
expect(tileFocus).toHaveBeenCalledOnce();
});
it('uses Ctrl+U to clear the TUI-owned prompt when local echo is disabled', () => {
const sendInput = vi.fn(() => Promise.resolve());
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: '',
_localEchoEnabled: false,
_localEchoOverlay: null,
sendInput,
_sendInputAsync: vi.fn(),
_focusedPane: () => ({ terminal: app.terminal, sessionId: app.activeSessionId, isPrimary: true }),
_prepareExternalInput: vi.fn(),
showToast: vi.fn(),
terminal: { focus: vi.fn() },
};
terminalHarness.mixin.clearTerminalInput.call(app);
expect(sendInput).toHaveBeenCalledWith('\x15');
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x15', { useMux: true });
});
});
+6 -3
View File
@@ -3,19 +3,22 @@
// It discards a keypress carrying Ctrl/Alt but not one carrying only Shift, so
// a handler that returns false for keydown alone lets Shift+Enter's keypress
// through as a bare \r (submit). The Enter gate must therefore not be keyed on
// ev.type === 'keydown'; only the send-key fetch is.
// ev.type === 'keydown'; only the send-key fetch is. The main pane may add an
// iOS clause after the modifier test (#830), which must not test ev.type either.
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
const PUBLIC = join(new URL('.', import.meta.url).pathname, '../src/web/public');
const GATE = /if \(ev\.key === 'Enter' && \(ev\.shiftKey \|\| ev\.ctrlKey\)(.*)\) \{/;
describe.each(['terminal-ui.js', 'terminal-tile.js'])('%s Shift/Ctrl+Enter handler', (file) => {
const src = readFileSync(join(PUBLIC, file), 'utf8');
it('swallows every event type for Shift/Ctrl+Enter', () => {
expect(src).toMatch(/ev\.key === 'Enter' && \(ev\.shiftKey \|\| ev\.ctrlKey\)\) \{/);
expect(src).not.toMatch(/ev\.key === 'Enter' && \(ev\.shiftKey \|\| ev\.ctrlKey\) && ev\.type === 'keydown'/);
const gate = src.match(GATE);
expect(gate, 'Shift/Ctrl+Enter gate not found').not.toBeNull();
expect(gate![0]).not.toContain('ev.type');
});
});
+51 -19
View File
@@ -38,6 +38,25 @@ interface Pressed {
focused: boolean;
}
/** The slice of the page's `app` and probe globals that pressMain() swaps and restores. */
interface MainProbeWindow {
app: {
activeSessionId: string | null;
_localEchoEnabled: boolean;
_enqueueReliableInput: (sessionId: string, chunk: string) => void;
_pendingInput?: Map<string, string>;
sessions: Map<string, { id: string; mode: string }>;
terminal: { focus(): void; textarea?: HTMLTextAreaElement };
};
__mainSaved?: {
id: string | null;
echo: boolean;
send: (sessionId: string, chunk: string) => void;
};
__mainData: string[];
__sendKeys: string[];
}
describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be swallowed too)', () => {
let server: WebServer;
let browser: Browser;
@@ -105,36 +124,49 @@ describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be sw
/**
* Press `key` in the main pane. `sessionId` null is the welcome screen; otherwise the app thinks
* that session is active, local echo is off (the desktop default) and its real send path,
* `_sendInputAsync`, is recorded instead of posting.
* that session is active, local echo is off (the desktop default), the probe id is registered in
* `app.sessions` (the session FIFO drops input for unknown ids), and the transport edge,
* `_enqueueReliableInput`, is recorded instead of posting.
*/
async function pressMain(key: string, sessionId: string | null): Promise<Pressed> {
await page.evaluate((id) => {
const w = window as any;
const w = window as unknown as MainProbeWindow;
const app = w.app;
w.__mainSaved ??= { id: app.activeSessionId, echo: app._localEchoEnabled, send: app._sendInputAsync };
w.__mainData = [] as string[];
w.__mainSaved ??= { id: app.activeSessionId, echo: app._localEchoEnabled, send: app._enqueueReliableInput };
w.__mainData = [];
w.__sendKeys.length = 0;
app.activeSessionId = id;
app._localEchoEnabled = false;
app._pendingInput = '';
app._sendInputAsync = (_sid: string, chunk: string) => void w.__mainData.push(chunk);
if (id) {
app._pendingInput?.delete(id);
app.sessions.set(id, { id, mode: 'claude' });
}
app._enqueueReliableInput = (_sid: string, chunk: string) => void w.__mainData.push(chunk);
app.terminal.focus();
}, sessionId);
const focused = await page.evaluate(() => document.activeElement === (window as any).app.terminal.textarea);
const focused = await page.evaluate(
() => document.activeElement === (window as unknown as MainProbeWindow).app.terminal.textarea
);
await page.keyboard.press(key);
// The main pane batches onData through a short flush timer before _sendInputAsync.
// The main pane batches onData through a short flush timer before the session FIFO.
await page.waitForTimeout(150);
return page.evaluate((f) => {
const w = window as any;
const app = w.app;
const out = { data: [...w.__mainData], sendKeys: [...w.__sendKeys], focused: f };
app.activeSessionId = w.__mainSaved.id;
app._localEchoEnabled = w.__mainSaved.echo;
app._sendInputAsync = w.__mainSaved.send;
app._pendingInput = '';
return out;
}, focused);
return page.evaluate(
({ f, id }) => {
const w = window as unknown as MainProbeWindow;
const app = w.app;
const saved = w.__mainSaved!;
const out = { data: [...w.__mainData], sendKeys: [...w.__sendKeys], focused: f };
app.activeSessionId = saved.id;
app._localEchoEnabled = saved.echo;
app._enqueueReliableInput = saved.send;
if (id) {
app._pendingInput?.delete(id);
app.sessions.delete(id);
}
return out;
},
{ f: focused, id: sessionId }
);
}
async function pressIn(which: 'paneB' | 'old', key: string): Promise<Pressed> {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -66,6 +66,8 @@ describe('orphaned terminal input recovery wiring', () => {
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => (window as any).app?.terminal, null, { timeout: 30000 });
await page.waitForFunction(() => (window as any).app?._keyCode229Recovery, null, { timeout: 30000 });
expect(await page.evaluate(() => (window as any).app._iosNativeInput)).toBeNull();
expect(await page.evaluate(() => Boolean((window as any).app._keyCode229Recovery))).toBe(true);
}, 90000);
afterAll(async () => {
@@ -96,19 +98,16 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
let xtermEmitted = 0;
const rec = app._keyCode229Recovery;
try {
app.activeSessionId = 'cod388-browser-regression';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-regression', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
// The controller object is Object.freeze()d, so count xterm's own
// canonical emissions by swapping the (writable) property on app.
app._keyCode229Recovery = {
@@ -138,13 +137,14 @@ describe('orphaned terminal input recovery wiring', () => {
}
await new Promise((resolve) => setTimeout(resolve, 60));
return { sent, xtermEmitted };
return { sent: sent.map(([, chunk]) => chunk), xtermEmitted };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-regression');
app._pendingInput.delete('cod388-browser-regression');
app._lastKeystrokeTime.delete('cod388-browser-regression');
app._keyCode229Recovery = rec;
textarea.value = '';
}
@@ -207,17 +207,14 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
try {
app.activeSessionId = 'cod388-browser-batched';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-batched', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.focus();
// One task, no awaits between the three dispatches.
@@ -245,14 +242,16 @@ describe('orphaned terminal input recovery wiring', () => {
Object.defineProperties(enterDown, { keyCode: { value: 13 }, which: { value: 13 } });
textarea.dispatchEvent(enterDown);
await new Promise((resolve) => setTimeout(resolve, 80));
return { wire: sent.join('') };
// Keep real browser timers: this exercises xterm's platform-clock recovery and FIFO gaps.
await new Promise((resolve) => setTimeout(resolve, 150));
return { wire: sent.map(([, chunk]) => chunk).join('') };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-batched');
app._pendingInput.delete('cod388-browser-batched');
app._lastKeystrokeTime.delete('cod388-browser-batched');
textarea.value = '';
}
}, data);
@@ -283,10 +282,8 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
const key229 = () => {
const down = new KeyboardEvent('keydown', { key: 'Unidentified', bubbles: true, cancelable: true });
Object.defineProperties(down, { keyCode: { value: 229 }, which: { value: 229 } });
@@ -296,9 +293,8 @@ describe('orphaned terminal input recovery wiring', () => {
try {
app.activeSessionId = 'cod388-browser-autocorrect';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-autocorrect', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.value = '';
textarea.focus();
@@ -316,17 +312,18 @@ describe('orphaned terminal input recovery wiring', () => {
await new Promise((resolve) => setTimeout(resolve, 80));
const line: string[] = [];
for (const ch of sent.join('')) {
for (const ch of sent.map(([, chunk]) => chunk).join('')) {
if (ch === '\x7f') line.pop();
else line.push(ch);
}
return { raw: sent.join(''), line: line.join(''), textarea: textarea.value };
return { raw: sent.map(([, chunk]) => chunk).join(''), line: line.join(''), textarea: textarea.value };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-autocorrect');
app._pendingInput.delete('cod388-browser-autocorrect');
app._lastKeystrokeTime.delete('cod388-browser-autocorrect');
textarea.value = '';
}
});
@@ -353,10 +350,8 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
const keydown = (init: KeyboardEventInit, keyCode: number) => {
const down = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });
Object.defineProperties(down, { keyCode: { value: keyCode }, which: { value: keyCode } });
@@ -367,9 +362,8 @@ describe('orphaned terminal input recovery wiring', () => {
try {
app.activeSessionId = 'cod388-browser-edit-enter';
app._localEchoEnabled = localEcho;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-edit-enter', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.value = '';
textarea.focus();
@@ -394,17 +388,18 @@ describe('orphaned terminal input recovery wiring', () => {
await new Promise((resolve) => setTimeout(resolve, 250)); // local echo delays the \r by 80 ms
const line: string[] = [];
for (const ch of sent.join('')) {
for (const ch of sent.map(([, chunk]) => chunk).join('')) {
if (ch === '\x7f') line.pop();
else line.push(ch);
}
return { raw: sent.join(''), line: line.join('') };
return { raw: sent.map(([, chunk]) => chunk).join(''), line: line.join('') };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-edit-enter');
app._pendingInput.delete('cod388-browser-edit-enter');
app._lastKeystrokeTime.delete('cod388-browser-edit-enter');
textarea.value = '';
}
}, options);
@@ -480,7 +475,7 @@ describe('orphaned terminal input recovery wiring', () => {
const app = w.app;
const tile = w.__tile229;
const textarea = document.querySelector('#tile229Mount .xterm-helper-textarea') as HTMLTextAreaElement;
const originalSendInput = app._sendInputAsync;
const originalSendInput = app._enqueueReliableInput;
const originalSessionId = app.activeSessionId;
const rec = tile._keyCode229Recovery;
const sent: Array<[string, string]> = [];
@@ -509,7 +504,8 @@ describe('orphaned terminal input recovery wiring', () => {
};
try {
app.activeSessionId = 'cod541-not-the-tile';
app._sendInputAsync = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
app.sessions.set(tileId, { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
if (scenario === 'selfRescued') {
// Counts xterm's own canonical emissions: the tile's onData reads the property at
// call time, and the controller object itself is frozen.
@@ -569,7 +565,8 @@ describe('orphaned terminal input recovery wiring', () => {
tileId,
};
} finally {
app._sendInputAsync = originalSendInput;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete(tileId);
app.activeSessionId = originalSessionId;
tile._keyCode229Recovery = rec;
textarea.value = '';
+64 -1
View File
@@ -13,6 +13,14 @@
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
import { ZerolagInputAddon } from '../packages/xterm-zerolag-input/src/zerolag-input-addon.js';
const MULTI_CODE_POINT_EMOJI = [
['red heart', '\u2764\uFE0F'],
['skin tone', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
] as const;
type Listener = (event: Record<string, unknown>) => void;
@@ -741,6 +749,58 @@ describe('edit-based sync of the helper textarea (autocorrect replacements)', ()
expect(e.sent.slice(2)).toEqual(['\x7f']);
});
it.each(MULTI_CODE_POINT_EMOJI)('deletes a whole %s with one DEL', (_name, emoji) => {
const e = editSyncHarness();
e.create(true);
typeKeys(e, 'ok');
e.keydown();
e.edit(`ok${emoji}`);
e.flush();
const before = e.sent.length;
e.keydown();
e.edit('ok');
e.flush();
expect(e.sent.slice(before)).toEqual(['\x7f']);
});
it.each([
['Thai', '\u0E01\u0E34\u0E48'],
['Hindi', '\u0915\u094D\u0937'],
])('types %s combining marks one field state at a time as plain appends', (_name, word) => {
// Each keystroke extends the last grapheme cluster; re-typing that cluster would
// make a code-point line editor (zsh) double the base letter.
const e = editSyncHarness();
e.create(true);
typeKeys(e, word);
expect(e.sent).toEqual(Array.from(word));
expect(e.line()).toBe(word);
});
it.each(MULTI_CODE_POINT_EMOJI)(
'keeps the local-echo draft at ok when the %s is deleted (real overlay)',
(_name, emoji) => {
const e = editSyncHarness();
e.create(true);
typeKeys(e, 'ok');
e.keydown();
e.edit(`ok${emoji}`);
e.flush();
// Local echo buffers what the recovery emits; each DEL drops one overlay grapheme.
const overlay = new ZerolagInputAddon();
overlay.appendText(e.sent.join(''));
expect(overlay.pendingText).toBe(`ok${emoji}`);
const before = e.sent.length;
e.keydown();
e.edit('ok');
e.flush();
for (const data of e.sent.slice(before)) {
if (data === '\x7f') expect(overlay.removeChar()).toBe('pending');
else overlay.appendText(data);
}
expect(overlay.pendingText).toBe('ok');
}
);
it('stays out of the way while composing, and leaves xterm alone without its internals', () => {
const h = editSyncHarness();
h.create(true);
@@ -770,12 +830,15 @@ describe('edit-based sync of the helper textarea (autocorrect replacements)', ()
expect(terminalSource).toMatch(/getCompositionHelper:\s*\(\)\s*=>\s*this\.terminal\?\._core\?\._compositionHelper/);
});
it('editBetween counts code points and replaces everything after the common prefix', () => {
it('editBetween counts grapheme clusters and replaces everything after the common prefix', () => {
const { editBetween } = editSyncHarness().exposed.CodemanKeyCode229Recovery;
expect(editBetween('abc', 'abcd')).toEqual({ deleted: 0, inserted: 'd' });
expect(editBetween('abc', 'ab')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('testing the peompt', 'testing the prompt ')).toEqual({ deleted: 5, inserted: 'rompt ' });
expect(editBetween('x😀', 'x')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('x\u{1F44D}\u{1F3FD}', 'x')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('', '')).toEqual({ deleted: 0, inserted: '' });
// A mark typed onto the last letter is a plain append, not a DEL and a re-typed cluster.
expect(editBetween('\u0E01', '\u0E01\u0E34')).toEqual({ deleted: 0, inserted: '\u0E34' });
});
});
+215 -1
View File
@@ -94,10 +94,11 @@ function loadContext() {
return {
CodemanApp: (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp,
windowStub,
context,
};
}
const { CodemanApp, windowStub } = loadContext();
const { CodemanApp, windowStub, context } = loadContext();
type App = Record<string, unknown> & {
_pendingDeliveries: Map<string, Array<{ seq: number; data: string }>>;
@@ -163,6 +164,8 @@ afterEach(() => {
beforeEach(() => {
windowStub.__coarsePointer = true;
delete windowStub.CodemanIosNativeInput;
delete context.KeyboardAccessoryBar;
FakeTerminal.coreFactory = null;
FakeFit.proposed = { cols: 80, rows: 24 };
FakeSocket.instances = [];
@@ -1519,3 +1522,214 @@ describe('terminal-tile.js keeps the controller call where it works (source pin)
expect(source).toMatch(/getCompositionHelper:\s*\(\)\s*=>\s*this\.terminal\?\._core\?\._compositionHelper/);
});
});
describe('TerminalTile iOS native input ownership', () => {
type NativeOptions = { terminal: unknown; sendTransaction(ops: string[]): void };
const install = (supported = true) => {
const owner = {
keyFilter: vi.fn(() => true),
settle: vi.fn(),
reset: vi.fn(),
destroy: vi.fn(),
};
let options: NativeOptions;
const dispose = vi.fn();
const create = vi.fn((opts: NativeOptions) => {
options = opts;
return owner;
});
const attachCaretMarker = vi.fn(() => dispose);
windowStub.CodemanIosNativeInput = { isSupported: () => supported, create, attachCaretMarker };
return { owner, create, attachCaretMarker, dispose, send: (ops: string[]) => options.sendTransaction(ops) };
};
it('creates an owner and parsed-buffer marker without an anchor, but no 229 recovery, on iOS', async () => {
const native = install();
const { tile, term } = await connectTile(makeApp());
expect(native.create).toHaveBeenCalledOnce();
expect(native.create.mock.calls[0][0].terminal).toBe(term);
expect(native.attachCaretMarker).toHaveBeenCalledWith(term, native.owner);
expect((tile as ControllerTile)._keyCode229Recovery).toBeNull();
});
it('leaves the non-iOS 229 recovery and key handling unchanged', async () => {
const native = install(false);
const { tile, term } = await connectTile(makeApp());
expect(native.create).not.toHaveBeenCalled();
expect((tile as ControllerTile)._keyCode229Recovery).not.toBeNull();
expect(term.keyHandler!({ type: 'keydown', key: 'a', code: 'KeyA' })).toBe(true);
});
it('falls back to the 229 recovery when the iOS module refuses to create an owner', async () => {
const native = install();
native.create.mockReturnValueOnce(null);
const { tile } = await connectTile(makeApp());
expect(native.create).toHaveBeenCalledOnce();
expect(native.attachCaretMarker).not.toHaveBeenCalled();
expect((tile as ControllerTile)._keyCode229Recovery).not.toBeNull();
});
it('reserves separate DEL writes and insertion for the tile session in one call', async () => {
const native = install();
const app = makeApp();
app.activeSessionId = 'not-the-tile';
app._enqueueInput = vi.fn();
await connectTile(app);
native.send(['\x7f', '\x7f', 'fixed ']);
expect(app._enqueueInput).toHaveBeenCalledExactlyOnceWith('s-tile', [
{ write: '\x7f' },
{ write: '\x7f' },
{ write: 'fixed ' },
]);
});
it('falls back per write while retaining the destination captured before sending', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = undefined;
const { tile } = await connectTile(app);
const send = vi.fn(() => {
(tile as Tile & { sessionId: string }).sessionId = 'changed';
});
app._sendInputAsync = send;
native.send(['\x7f', '\x7f', 'x']);
expect(send.mock.calls).toEqual([
['s-tile', '\x7f'],
['s-tile', '\x7f'],
['s-tile', 'x'],
]);
});
it('runs keyFilter before recovery, composition and tile chord handling', async () => {
const native = install();
native.owner.keyFilter.mockReturnValue(false);
const app = makeApp();
app.tileShortcutFor = vi.fn();
const { tile, term } = await connectTile(app);
const recovery = { handleKeyEvent: vi.fn() };
(tile as ControllerTile)._keyCode229Recovery = recovery;
const ev = { type: 'keydown', key: 'Process', keyCode: 229, isComposing: true };
expect(term.keyHandler!(ev)).toBe(false);
expect(native.owner.keyFilter).toHaveBeenCalledWith(ev);
expect(recovery.handleKeyEvent).not.toHaveBeenCalled();
expect(app.tileShortcutFor).not.toHaveBeenCalled();
});
it('retains paste, tile chords and Shift+Enter when keyFilter allows them', async () => {
const native = install();
const app = makeApp();
app.tileShortcutFor = vi.fn((ev: { key: string }) => ev.key === 'g');
app._handleImagePaste = vi.fn();
const { term } = await connectTile(app);
expect(term.keyHandler!({ type: 'keydown', key: 'g' })).toBe(false);
expect(term.keyHandler!({ type: 'keydown', key: 'v', ctrlKey: true })).toBe(false);
expect(app._handleImagePaste).toHaveBeenCalledOnce();
expect(term.keyHandler!({ type: 'keydown', key: 'Enter', shiftKey: true })).toBe(false);
expect(fetchMock).toHaveBeenCalledWith('/api/sessions/s-tile/send-key', expect.any(Object));
expect(native.owner.keyFilter).toHaveBeenCalledTimes(3);
});
it('settles, destroys and disposes on teardown, including a pending edit', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
const { tile, term } = await connectTile(app);
native.owner.settle.mockImplementation(() => native.send(['last']));
const disposeTerminal = vi.spyOn(term, 'dispose');
tile.destroy();
tile.destroy();
expect(app._enqueueInput).toHaveBeenCalledExactlyOnceWith('s-tile', [{ write: 'last' }]);
expect(native.owner.settle).toHaveBeenCalledOnce();
expect(native.owner.destroy).toHaveBeenCalledOnce();
expect(native.dispose).toHaveBeenCalledOnce();
expect(native.owner.settle.mock.invocationCallOrder[0]).toBeLessThan(
native.owner.destroy.mock.invocationCallOrder[0]
);
expect(native.dispose.mock.invocationCallOrder[0]).toBeLessThan(disposeTerminal.mock.invocationCallOrder[0]);
});
it('disposes the prior owner and marker before reinitialization', async () => {
const previous = install();
const { tile } = await connectTile(makeApp());
const next = install();
(tile as Tile & { _createInputOwner(): void })._createInputOwner();
expect(previous.owner.settle).toHaveBeenCalledOnce();
expect(previous.owner.destroy).toHaveBeenCalledOnce();
expect(previous.dispose).toHaveBeenCalledOnce();
expect(previous.dispose.mock.invocationCallOrder[0]).toBeLessThan(next.create.mock.invocationCallOrder[0]);
});
it('consumes Ctrl once on a single-character insertion, retaining replacement DELs', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
const consumeCtrl = vi.fn(() => '\x03');
context.KeyboardAccessoryBar = { isCtrlArmed: () => true, consumeCtrl };
await connectTile(app);
native.send(['\x7f', '\x7f', 'c']);
expect(consumeCtrl).toHaveBeenCalledExactlyOnceWith('c');
expect(app._enqueueInput).toHaveBeenCalledExactlyOnceWith('s-tile', [
{ write: '\x7f' },
{ write: '\x7f' },
{ write: '\x03' },
]);
expect(native.owner.reset).toHaveBeenCalledExactlyOnceWith('ctrl');
});
it('spends Ctrl on a deletion-only transaction without resetting the owner', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
let armed = true;
const consumeCtrl = vi.fn(() => {
armed = false;
return '\x03';
});
context.KeyboardAccessoryBar = {
isCtrlArmed: () => armed,
consumeCtrl,
clearCtrl: () => {
armed = false;
},
};
await connectTile(app);
native.send(['\x7f']);
expect(armed).toBe(false);
native.send(['c']);
expect(app._enqueueInput.mock.calls).toEqual([
['s-tile', [{ write: '\x7f' }]],
['s-tile', [{ write: 'c' }]],
]);
expect(consumeCtrl).not.toHaveBeenCalled();
expect(native.owner.reset).not.toHaveBeenCalled();
});
// A multi-character suggestion or an emoji has no single key to modify, but it
// must still spend the modifier (applyOneShotCtrl in keyboard-accessory.js),
// or the next plain `c` would become an interrupt.
for (const [label, insertion] of [
['suggestion', 'word'],
['emoji', '👍'],
] as const) {
it(`spends Ctrl on a ${label} insertion, so a following c stays c`, async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
let armed = true;
const consumeCtrl = vi.fn((data: string) => {
armed = false;
return data.length === 1 ? '\x03' : data;
});
context.KeyboardAccessoryBar = { isCtrlArmed: () => armed, consumeCtrl };
await connectTile(app);
native.send([insertion]);
native.send(['c']);
expect(consumeCtrl).toHaveBeenCalledExactlyOnceWith(insertion);
expect(app._enqueueInput.mock.calls).toEqual([
['s-tile', [{ write: insertion }]],
['s-tile', [{ write: 'c' }]],
]);
expect(native.owner.reset).toHaveBeenCalledExactlyOnceWith('ctrl');
});
}
});
+3 -1
View File
@@ -297,7 +297,9 @@ describe('xterm key handlers swallow a chord that applies', () => {
const src = read('terminal-ui.js');
const handler = src.slice(src.indexOf('this.terminal.attachCustomKeyEventHandler((ev) => {'));
const gate = handler.indexOf('if (this.tileShortcutFor?.(ev)) return false;');
const enter = handler.indexOf("if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)) {");
// Prefix only: the gate also carries an iOS keyCode guard (#830), so an iOS
// suggestion word "Enter" with Shift held is text, not a Shift+Enter chord.
const enter = handler.indexOf("if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)");
expect(gate).toBeGreaterThan(0);
expect(gate).toBeLessThan(enter);
});
-1
View File
@@ -49,7 +49,6 @@ function loadToolbar(sessionId: string | null = 'session-1', localEcho = true, k
const app = new CodemanApp();
app.activeSessionId = sessionId;
app.showToast = vi.fn();
app.sendInput = vi.fn(async () => {});
app.terminal = { focus: vi.fn() };
app._isMobileTerminalInputFocused = vi.fn(() => keyboardUp);
app._blurMobileTerminalInput = vi.fn();
+139 -32
View File
@@ -36,7 +36,6 @@ type Voice = {
type Pane = { sessionId: string; isPrimary?: boolean; terminal?: { focus: () => void } };
function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string; tiles?: boolean; pane?: Pane } = {}) {
const sendInput = vi.fn(async () => {});
const sendInputAsync = vi.fn();
const appendText = vi.fn();
const overlayClear = vi.fn();
@@ -57,8 +56,9 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
['session-a', {}],
['session-b', {}],
]),
sendInput,
_sendInputAsync: sendInputAsync,
_enqueueInput: vi.fn(),
_prepareExternalInput: vi.fn(),
showToast,
terminal: { focus: vi.fn() },
_localEchoEnabled: !!opts.localEcho,
@@ -74,7 +74,13 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
const pane = opts.pane;
app._focusedPane = () => pane;
}
app._paneForSession = (id: string) => (opts.pane?.sessionId === id ? opts.pane : null);
if (opts.tiles) app._tilesOwnTerminal = () => true;
const doc = {
querySelector: (sel: string): unknown => (sel === '.btn-settings' ? gear : null),
createElement: (): unknown => ({}),
body: { appendChild: () => {} },
};
const context = vm.createContext({
console,
setTimeout: (fn: () => void) => fn(),
@@ -87,11 +93,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
key === 'codeman-voice-settings' ? JSON.stringify({ insertMode: opts.insertMode || 'direct' }) : null,
setItem: () => {},
},
document: {
querySelector: (sel: string) => (sel === '.btn-settings' ? gear : null),
createElement: () => ({}),
body: { appendChild: () => {} },
},
document: doc,
window: {},
navigator: {},
});
@@ -100,7 +102,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
// Recording itself is out of scope: start() only has to pick the target.
voice._resolveProvider = () => 'webspeech';
voice._startWebSpeech = vi.fn();
return { voice, app, sendInput, sendInputAsync, appendText, overlayClear, showToast, gear };
return { voice, app, sendInputAsync, appendText, overlayClear, showToast, gear, doc };
}
function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] } } }) {
@@ -110,24 +112,23 @@ function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] }
describe('dictation target', () => {
it('sends to the session recording started in, even after a tab switch', () => {
const { voice, app, sendInput, sendInputAsync } = load();
const { voice, app, sendInputAsync } = load();
voice.start();
app.activeSessionId = 'session-b'; // user switched tabs while speaking
voice._insertText('fix the login bug');
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'fix the login bug', { useMux: true });
expect(sendInput).not.toHaveBeenCalled();
});
it('keeps the existing path when the target is still the active session', () => {
const { voice, sendInput, sendInputAsync } = load();
it('uses the session-bound path even while the target is still active', () => {
const { voice, app, sendInputAsync } = load({ pane: { sessionId: 'session-a', isPrimary: true } });
voice.start();
voice._insertText('hello');
expect(sendInput).toHaveBeenCalledWith('hello');
expect(sendInputAsync).not.toHaveBeenCalled();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'hello', { useMux: true });
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send');
});
it('never types another session dictation into the active local-echo overlay', () => {
@@ -142,13 +143,16 @@ describe('dictation target', () => {
});
it('still uses the local-echo overlay for the active session', () => {
const { voice, appendText, sendInput } = load({ localEcho: true });
const { voice, app, appendText } = load({
localEcho: true,
pane: { sessionId: 'session-a', isPrimary: true },
});
voice.start();
voice._insertText('typed locally');
expect(appendText).toHaveBeenCalledWith('typed locally');
expect(sendInput).not.toHaveBeenCalled();
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-insert');
});
it('takes its target from the focused pane when one is reported', () => {
@@ -161,7 +165,7 @@ describe('dictation target', () => {
});
it('the green send button sends Enter to the dictation target', () => {
const { voice, app, gear, sendInput, sendInputAsync } = load();
const { voice, app, gear, sendInputAsync } = load();
voice.start();
voice._insertText('ship it');
app.activeSessionId = 'session-b';
@@ -170,26 +174,23 @@ describe('dictation target', () => {
handler();
expect(sendInputAsync).toHaveBeenLastCalledWith('session-a', '\r', { useMux: true });
// Only the original insert went through sendInput (target was active then).
expect(sendInput).toHaveBeenCalledTimes(1);
});
it('drops dictation for a session that closed meanwhile, with a toast', () => {
const { voice, app, sendInput, sendInputAsync, showToast } = load();
const { voice, app, sendInputAsync, showToast } = load();
voice.start();
app.activeSessionId = 'session-b';
(app.sessions as Map<string, unknown>).delete('session-a');
voice._insertText('too late');
expect(sendInput).not.toHaveBeenCalled();
expect(sendInputAsync).not.toHaveBeenCalled();
expect(showToast).toHaveBeenCalledWith('That session has closed; dictation not sent', 'warning');
});
it('with the tile grid open, dictation goes to the focused tile, not the parked overlay', () => {
const tileTerminal = { focus: vi.fn() };
const { voice, app, appendText, sendInput, sendInputAsync } = load({
const { voice, app, appendText, sendInputAsync } = load({
localEcho: true,
tiles: true,
pane: { sessionId: 'session-a', isPrimary: false, terminal: tileTerminal },
@@ -199,8 +200,7 @@ describe('dictation target', () => {
voice._insertText('into the tile');
expect(appendText).not.toHaveBeenCalled();
expect(sendInput).toHaveBeenCalledWith('into the tile');
expect(sendInputAsync).not.toHaveBeenCalled();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'into the tile', { useMux: true });
// The keyboard goes back to the tile; the main terminal is display: none.
expect(tileTerminal.focus).toHaveBeenCalled();
expect((app.terminal as { focus: ReturnType<typeof vi.fn> }).focus).not.toHaveBeenCalled();
@@ -208,7 +208,7 @@ describe('dictation target', () => {
it('with the tile grid open, the green send button sends only Enter to the tile session', () => {
const tileTerminal = { focus: vi.fn() };
const { voice, app, gear, sendInput, overlayClear } = load({
const { voice, app, gear, sendInputAsync, overlayClear } = load({
localEcho: true,
tiles: true,
pane: { sessionId: 'session-a', isPrimary: false, terminal: tileTerminal },
@@ -221,29 +221,136 @@ describe('dictation target', () => {
clickGreenSend(gear);
expect(overlayClear).not.toHaveBeenCalled();
expect(sendInput).not.toHaveBeenCalledWith('stale main-terminal text');
expect(sendInput).toHaveBeenLastCalledWith('\r');
expect(sendInputAsync).toHaveBeenLastCalledWith('session-a', '\r', { useMux: true });
// The parked main terminal's predictions are not this pane's.
expect(
(app._predictiveEcho as { clearPredictions: ReturnType<typeof vi.fn> }).clearPredictions
).not.toHaveBeenCalled();
});
it('split view is unchanged: a Pane A dictation keeps the overlay and refocuses the main terminal', () => {
it('preserves Pane A pending text and dictation ordering when focus moves to B', () => {
const paneB = { focus: vi.fn() };
const { voice, app, appendText, sendInput } = load({ localEcho: true, focused: 'session-a' });
const { voice, app, appendText, overlayClear, gear, sendInputAsync } = load({
localEcho: true,
focused: 'session-a',
});
const overlay = app._localEchoOverlay as { pendingText: string };
overlay.pendingText = 'earlier text ';
appendText.mockImplementation((text: string) => {
overlay.pendingText += text;
});
overlayClear.mockImplementation(() => {
overlay.pendingText = '';
});
voice.start();
// The user clicked into Pane B while speaking.
// Keep B focused even when the production code requests main-terminal focus.
app._focusedPane = () => ({ sessionId: 'session-b', isPrimary: false, terminal: paneB });
voice._insertText('for pane a');
expect(appendText).toHaveBeenCalledWith('for pane a');
expect(sendInput).not.toHaveBeenCalled();
expect((app.terminal as { focus: ReturnType<typeof vi.fn> }).focus).toHaveBeenCalled();
expect(overlay.pendingText).toBe('earlier text for pane a');
expect(sendInputAsync).not.toHaveBeenCalled();
expect(app._enqueueInput).not.toHaveBeenCalled();
clickGreenSend(gear);
expect(app._enqueueInput).toHaveBeenCalledWith('session-a', [
{ write: 'earlier text for pane a', useMux: true },
{ gap: 80 },
{ write: '\r', useMux: true },
]);
expect(overlay.pendingText).toBe('');
expect(sendInputAsync).not.toHaveBeenCalled();
expect(app._prepareExternalInput).toHaveBeenNthCalledWith(
1,
{ sessionId: 'session-a', isPrimary: true, tile: null, terminal: app.terminal },
'voice-insert'
);
expect(app._prepareExternalInput).toHaveBeenNthCalledWith(
2,
{ sessionId: 'session-a', isPrimary: true, tile: null, terminal: app.terminal },
'voice-submit'
);
// load() creates this terminal mock; its Record boundary erases the shape.
const mainTerminal = app.terminal as { focus: (...args: unknown[]) => void };
expect(mainTerminal.focus).toHaveBeenCalled();
expect(paneB.focus).not.toHaveBeenCalled();
});
it('compose Send delivers only the reviewed dictation and leaves the typed draft in the overlay', () => {
const { voice, app, appendText, overlayClear, sendInputAsync, doc } = load({
insertMode: 'compose',
localEcho: true,
pane: { sessionId: 'session-a', isPrimary: true },
});
const overlay = app._localEchoOverlay as { pendingText: string };
overlay.pendingText = 'hel';
const handlers = new Map<string, () => void>();
const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 };
doc.createElement = () => ({
className: '',
dataset: {},
innerHTML: '',
remove: vi.fn(),
addEventListener: vi.fn(),
querySelector: (sel: string) =>
sel === 'textarea'
? textarea
: { addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler) },
});
voice.start();
voice._insertText('Please fix the bug');
// The dialog's <textarea> gets the text through innerHTML; this stub has no
// HTML parser, so the user's reviewed text is set directly before Send.
textarea.value = 'Please fix the bug';
handlers.get('.paste-send')!();
expect(sendInputAsync).toHaveBeenCalledOnce();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'Please fix the bug\r', { useMux: true });
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send');
expect(overlay.pendingText).toBe('hel');
expect(appendText).not.toHaveBeenCalled();
expect(overlayClear).not.toHaveBeenCalled();
});
it('retargets an existing compose overlay for the next dictation', () => {
const { voice, sendInputAsync, doc } = load({ insertMode: 'compose' });
const handlers = new Map<string, () => void>();
const textarea = {
value: '',
focus: vi.fn(),
blur: vi.fn(),
selectionStart: 0,
selectionEnd: 0,
closest: (): { dataset: Record<string, string> } => overlay,
};
const overlay = {
dataset: {},
className: '',
innerHTML: '',
remove: vi.fn(),
addEventListener: vi.fn(),
querySelector: (sel: string) =>
sel === 'textarea'
? textarea
: {
addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler),
},
};
doc.createElement = () => overlay;
voice._targetSessionId = 'session-a';
voice._insertText('first dictation');
doc.querySelector = (sel: string) => (sel === '.voice-compose-overlay .paste-textarea' ? textarea : null);
voice._targetSessionId = 'session-b';
voice._insertText('second dictation');
handlers.get('.paste-send')!();
expect(sendInputAsync).toHaveBeenCalledExactlyOnceWith('session-b', 'second dictation\r', { useMux: true });
});
it('refuses to start with no session at all', () => {
const { voice, app, showToast } = load();
app.activeSessionId = null;
+17 -3
View File
@@ -51,7 +51,9 @@ describe('xterm private-API dependency guard', () => {
'CompositionHelper fields installEditSync() uses (terminal-keycode229-recovery.js: ' +
'_handleAnyTextareaChanges, _coreService, _isComposing, _isSendingComposition, _dataAlreadySent) ' +
'and the mouse-encoding read _shouldForwardTouchToApp makes (terminal-ui.js: ' +
'_core.coreMouseService.activeEncoding), then update VERIFIED_XTERM_VERSION here. ' +
'_core.coreMouseService.activeEncoding) and the iOS native-input owner (terminal-ios-native-input.js: ' +
'_core._inputEvent, _core._handleTextAreaBlur, _compositionHelper._finalizeComposition, ' +
'_compositionHelper._compositionView), then update VERIFIED_XTERM_VERSION here. ' +
'The accessor is optional-chained, so a renamed field ' +
'degrades to a silent no-op and the freeze it heals comes back unnoticed.'
).toBe(VERIFIED_XTERM_VERSION);
@@ -67,6 +69,12 @@ describe('xterm private-API dependency guard', () => {
// only to an app that asked for SGR mouse reports; if either name changes the read is undefined
// and touch quietly stops forwarding to native SGR tracking apps. Property names survive
// minification, so a string check on the shipped bundle catches a rename on upgrade.
// terminal-ios-native-input.js wraps `_inputEvent`, `_handleTextAreaBlur` and `_finalizeComposition`
// and reads `_compositionView`; if any is missing its create() returns null, and iOS falls back
// to the keyCode-229 recovery, so #830 (suggestions, phrase replacement, held delete) returns
// without a signal.
// The iOS owner also clears `_unprocessedDeadKey` when native input commits text,
// so the next terminal command is not swallowed as part of the dead-key sequence.
it('still ships the composition-helper and mouse-service fields terminal input depends on', () => {
const bundle = readFileSync(resolve(root, 'node_modules/@xterm/xterm/lib/xterm.js'), 'utf8');
for (const name of [
@@ -78,12 +86,18 @@ describe('xterm private-API dependency guard', () => {
'_dataAlreadySent',
'coreMouseService',
'activeEncoding',
'_inputEvent',
'_unprocessedDeadKey',
'_handleTextAreaBlur',
'_finalizeComposition',
'_compositionView',
]) {
expect(
bundle,
`xterm no longer mentions ${name}: re-verify terminal-keycode229-recovery.js installEditSync() ` +
'against the new CompositionHelper, and terminal-ui.js _shouldForwardTouchToApp against the ' +
'new CoreMouseService (both in src/web/public), before bumping VERIFIED_XTERM_VERSION'
'against the new CompositionHelper, terminal-ios-native-input.js create() against the new ' +
'CoreBrowserTerminal and CompositionHelper, and terminal-ui.js _shouldForwardTouchToApp against the ' +
'new CoreMouseService (all in src/web/public), before bumping VERIFIED_XTERM_VERSION'
).toContain(name);
}
});