diff --git a/.changeset/830-ios-keyboard.md b/.changeset/830-ios-keyboard.md new file mode 100644 index 00000000..4ef4cd9b --- /dev/null +++ b/.changeset/830-ios-keyboard.md @@ -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. diff --git a/CLAUDE.md b/CLAUDE.md index b19c9f6e..ed9727bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 ` 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 ` 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. diff --git a/config/test-suites.ts b/config/test-suites.ts index 6e523cc3..75a33d61 100644 --- a/config/test-suites.ts +++ b/config/test-suites.ts @@ -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 diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 1e0592f6..68a7c8d1 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -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 unattended agent loop. Shift/Ctrl+Enter POSTs to `/api/sessions/:id/send-key` (`{key:'S-Enter'|'C-Enter'}`, typed by tmux `send-keys -H`: Ctrl+Enter is always a real 0x0a, Shift+Enter is the CLI's declared `capabilities.newline` chord, also 0x0a unless the CLI declares another; sent on keydown only, with the keypress and keyup swallowed too, see the keypress rule under Command palette and shortcut registry) targeting THIS pane's own `sessionId` rather than the primary pane's `activeSessionId` — without it xterm's plain `\r` would submit an incomplete prompt instead of adding a line to it. Smart-copy Ctrl+C/Ctrl+Shift+C is re-implemented against `this.terminal` (Pane B's own) rather than reusing `app.copyTerminalSelection()`, which reads Pane A's terminal and would copy the wrong pane's selection; Ctrl+Shift+C never falls through even with nothing to copy, mirroring terminal-ui.js's own `ev.shiftKey` branch. ⚠️ **This is a UX-parity fix, not an interrupt-safety one** — verified live in a real browser: xterm's `evaluateKeyboardEvent` routes a shifted ctrl-letter into a branch that assigns `c.key` only for two special cases (`_`→US, `@`→NUL), so it emits no data for Ctrl+Shift+C at all regardless of any application gate; a synthetic keydown with the gate removed produces zero WS frames, proving no accidental interrupt reaches the PTY either way. What gating the whole copy block on `hasSelection()` (an earlier draft) actually cost: with no selection, a selection-less Ctrl+Shift+C fell straight to `return true`, silently ceding the keystroke to the BROWSER's own handling (e.g. Chrome's Inspect-Element binding) with no feedback and no copy attempt — Pane A always intercepts it. Ctrl+V goes through the primary pane's paste trap aimed at Pane B (`_handleImagePaste({ terminal, sessionId })`), so a pasted image uploads to Pane B's session. ⚠️ `buildSplitPickerSessions()` also excludes any session with `pid === null` (an exited CLI, a crash-looped session whose breaker tripped, a restore that never re-attached): Pane B has no equivalent of `selectSession()`'s auto re-attach POST, so a pane opened onto one has nothing reading its tmux pane — no `terminal` events ever arrive, and `Session.write()` silently drops every keystroke with no ack either way, so the loss is invisible behind a socket that reports healthy. Pane B's keystrokes go through the exactly-once queue (`_sendInputAsync`) over its own socket, registered in the app's input-socket map (`_registerInputSocket` / `_inputSocketFor`), so they are seq-tagged, ACKed (`{t:'ia'}` is routed by the RECEIVING socket's session, since the frame names none), redelivered after a drop, and the ACK clears the idle alert. ⚠️ What xterm generates never enters that persisted queue: query replies are dropped (`shouldSuppressTerminalQueryResponse`, as the primary pane drops them) and focus/mouse reports go through `_sendInputEphemeral`, or a reload would replay them as typed text. That includes the click report a tile hand-encodes for a mouse-strip CLI: `TerminalTile._installClickListener` passes `ephemeral: true` in its target, which `_sendSyntheticSgrTap` honours, while the primary pane's own report (no flag) stays on `_sendInputAsync` as before. ⚠️ A SHELL Pane B pulls scrollback itself when the wheel goes up at the top of its buffer (`_maybeLoadMoreHistory`/`_pullHistory`): tmux repaints a burst of output instead of scrolling it, so Pane B's own xterm holds about one screen of scrollback while tmux holds every line, and it loaded history exactly once at connect and never again. It is the same bounded pull as Pane A's (`?full=1&tail=TERMINAL_TAIL_SIZE`, no rewrite when the window holds no more rows than the pane already has or the pane is at its `scrollback + rows` cap, and a 60 s back-off instead of 4 s when that skipped window was truncated or the pane is full, since each ask costs the server a whole-history `capture-pane`), against Pane B's OWN terminal rather than `app.terminal`, so it cannot share `_maybeRefetchFullHistory`. The wheel listener is capture-phase because xterm `stopPropagation()`s the events it consumes; the alternate-screen skip (nano, vim, less) only matters for a direct-PTY shell, since under tmux the browser xterm never enters the alternate buffer; skipped too for a detached session (mirrors `_sendResize()`'s own check and app.js's `_maybeRefetchFullHistory`), since its own window already owns its PTY size and scrollback. Live frames arriving from the response onward are held with their arrival time (`_liveQueue`, opened right after `await fetch(...)` beside `capturedAt`; a frame from before it is replaced by the capture or written unchanged, so the pane keeps painting during the round trip) and replayed in order only if they arrived after the capture (the response's arrival stands in for the capture instant, as in `_finishBufferLoad`, so a frame inside that one round trip can be lost or doubled); the request uses the primary pane's budget (`CodemanFetchDeadline.terminalFetchDeadlineMs({ full: true })`, 45 s, 10 s only if that helper is absent) and the body read gets 10 s once the headers land, because from then on the pull holds the pane's live output. The request phase holds no live output, but it does hold the single-flight flag, so a coalesced `{t:'r'}` refresh and a marker owed by a close (below) wait for the response, at worst for that whole budget (accepted: a Codeman restart resets an in-flight request along with the socket, so that pull fails at once and stamps the marker). ⚠️ The "disconnected" marker must be the LAST thing on screen. A replay's own `\x1bc` would otherwise wipe a marker written before the pull and paint a fresh, current-looking history while `onData` keeps silently dropping every keystroke on the dead socket (a Codeman restart drops the socket while the tmux session, and so the HTTP pull, still succeeds), so `_pullHistory()` re-stamps it after the live-frame flush. A close DURING any load (a pull, a refresh; `connect()` awaits the initial load before it creates the socket, so no close lands in that one) writes nothing: `_onSocketClosed()` sets `_markerOwed` while a load's work runs (`_loadRunning`; a load that only waits in the tile grid's queue writes the marker at once, and its refresh resets the screen only once its own capture is in hand), since written there it would sit above the held frames the pull flushes after a skip, a downgrade, a failed fetch or the deadline, above a refresh's replay, or land mid-way through a chunked replay. Each load settles the marker in its OWN `finally` (`_stampMarkerIfOwed()`), after the queue flush, EXCEPT when a trailing refresh is pending: that refresh settles it itself (its replay's queued `\x1bc` would wipe a marker written now, so it re-owes the marker on a closed socket and writes the one copy below its replay, and a refresh that writes nothing stamps the one still owed). The marker stays owed instead of being written twice; the default fake terminal in `test/terminal-tile-unit.test.ts` writes synchronously, so an async-parse fake there pins what ends up on screen. Anything that wipes the terminal on a closed socket (a pull's or a refresh's `\x1bc`) sets `_markerOwed` too, so the marker is rewritten whether or not the close landed during the load. Tracked via `_wsClosed`/`_markerOwed` rather than routed through `_onLiveOutput()`, since a close landing before the response is stamped before the cutoff and would be dropped with the rest of the pre-capture queue. There is no "Load full history" banner in Pane B, so a shell history past that 1 MiB window stays out of reach there. Non-shell Pane B is unchanged: it already loads `full=1`, and its history is out of scope for this pull (codex and Claude's inline renderer do grow tmux history; this just isn't how they recover it). ⚠️ A server `{t:'c'}` frame is a REFRESH, never a bare `clear()` (`_onLiveClear()` calls `_refreshBuffer()`): its one emitter is a fresh Claude pane's first prompt (`Session.startInteractive`, "refresh after startup"), the primary pane answers it with a refetch and replay (`_onSessionClearTerminal`, which stands aside while the grid is open), and xterm's `clear()` keeps only the cursor's row, so a Claude session Run into the grid or Attached in a tile came up as a near-empty tile that an idle Claude never repainted. As a refresh it coalesces behind a load already running (a pull's held frames included) and waits its turn in the grid's load queue. ⚠️ A refresh (`{t:'r'}`, `{t:'c'}`, a reconnect) runs in the primary pane's order (`_onSessionNeedsRefresh`): fetch FIRST, so the pane keeps its last frame through the round trip and through a grid tile's wait; hold live frames from the response on (`_liveQueue`; the body read of a bounded window, a grid tile's or a shell's, gets the 10 s budget, while Pane B's unbounded `full=1` keeps the request's); then the queued in-stream `\x1bc` immediately before the replay, then the held frames that arrived after the response. Never xterm's `clear()`: it is synchronous while queued bytes are parsed after it (they fused into the snapshot) and it keeps the cursor's row and column, where the capture (raw rows, no home) then started. A failed, aborted or empty fetch writes nothing and resets nothing. ⚠️ Live output is flow-controlled per pane (`_writeLive`), because the server applies no backpressure and a flood a tile cannot parse as fast (a shell tile running `cat` on a huge log) used to pile up in xterm's own queue until its WriteBuffer threw past 50M code units and onmessage's catch lost the frames silently: unparsed output is counted through each write's callback, and held output by the queue, against `TerminalTile.LIVE_BACKLOG_BUDGET` (4 MiB; deliberately NOT the primary pane's 128 KB, which caps its own rAF-paced queues, while xterm itself paces a tile and a tight cap would blank-and-reload it on ordinary bursts). Past it a frame is dropped, the tile stops writing onto the hole, and one refresh, debounced and bounded by the primary pane's own rule (`CodemanDroppedOutput`: 2 s, at most `DROP_RECOVERY_MAX_ATTEMPTS`, never retried after a deadline abort), recaptures the screen; the flag clears only once a capture taken after the last dropped frame has replayed. A write xterm throws on is the same drop. Past the bound the flag is released (the tile is never left frozen), a reconnect starts the accounting over (an epoch makes callbacks from before it count nothing) and drops a pending recovery, since its own refresh replaces the screen, and `destroy()` cancels it. ⚠️ App-level terminal actions find their pane through `_focusedPane()`, the terminal focused LAST (not `document.activeElement`, which the mic or a header button takes): Ctrl+L, Ctrl+Shift+R, voice and image paste act on Pane B while it holds the keyboard. Ctrl+W is not an app shortcut at all (Close Session has no default key), so it reaches whichever pane is focused as delete-word. ⚠️ Geometry: `TerminalTile.fit()` sends the size the xterm actually holds, unfloored (the divider's 20% clamp leaves about 28 columns), skips an unchanged size, re-sends on every fresh socket, and adopts the PTY's column count from `{t:'zc'}`; a forced fit (Redraw: Ctrl+Shift+R, the header button, through `restoreTerminalSize`) carries the primary pane's `f` flag, without which `Session.resize` skips a size equal to the one it last applied, and `fit()` returns whether a frame went out, so Redraw reports success only for a resize it sent (a detached session or a socket that is down gets a warning instead); the font, family and weight setters call `tile.fit()`, never a local refit alone (#464). Every capture a pane fetches carries a deadline covering the body (`CodemanFetchDeadline`), so a capture that never answers cannot hold its single-flight flag forever. Design: `docs/split-pane-sessions-plan.md`; the tile class: `docs/tile-grid-plan.md`. +**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 terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattended agent loop. Shift/Ctrl+Enter POSTs to `/api/sessions/:id/send-key` (`{key:'S-Enter'|'C-Enter'}`, typed by tmux `send-keys -H`: Ctrl+Enter is always a real 0x0a, Shift+Enter is the CLI's declared `capabilities.newline` chord, also 0x0a unless the CLI declares another; sent on keydown only, with the keypress and keyup swallowed too, see the keypress rule under Command palette and shortcut registry) targeting THIS pane's own `sessionId` rather than the primary pane's `activeSessionId` — without it xterm's plain `\r` would submit an incomplete prompt instead of adding a line to it. Smart-copy Ctrl+C/Ctrl+Shift+C is re-implemented against `this.terminal` (Pane B's own) rather than reusing `app.copyTerminalSelection()`, which reads Pane A's terminal and would copy the wrong pane's selection; Ctrl+Shift+C never falls through even with nothing to copy, mirroring terminal-ui.js's own `ev.shiftKey` branch. ⚠️ **This is a UX-parity fix, not an interrupt-safety one** — verified live in a real browser: xterm's `evaluateKeyboardEvent` routes a shifted ctrl-letter into a branch that assigns `c.key` only for two special cases (`_`→US, `@`→NUL), so it emits no data for Ctrl+Shift+C at all regardless of any application gate; a synthetic keydown with the gate removed produces zero WS frames, proving no accidental interrupt reaches the PTY either way. What gating the whole copy block on `hasSelection()` (an earlier draft) actually cost: with no selection, a selection-less Ctrl+Shift+C fell straight to `return true`, silently ceding the keystroke to the BROWSER's own handling (e.g. Chrome's Inspect-Element binding) with no feedback and no copy attempt — Pane A always intercepts it. Ctrl+V goes through the primary pane's paste trap aimed at Pane B (`_handleImagePaste({ terminal, sessionId })`), so a pasted image uploads to Pane B's session. ⚠️ `buildSplitPickerSessions()` also excludes any session with `pid === null` (an exited CLI, a crash-looped session whose breaker tripped, a restore that never re-attached): Pane B has no equivalent of `selectSession()`'s auto re-attach POST, so a pane opened onto one has nothing reading its tmux pane — no `terminal` events ever arrive, and `Session.write()` silently drops every keystroke with no ack either way, so the loss is invisible behind a socket that reports healthy. Pane B's keystrokes go through the exactly-once queue (`_sendInputAsync`) over its own socket, registered in the app's input-socket map (`_registerInputSocket` / `_inputSocketFor`), so they are seq-tagged, ACKed (`{t:'ia'}` is routed by the RECEIVING socket's session, since the frame names none), redelivered after a drop, and the ACK clears the idle alert. ⚠️ What xterm generates never enters that persisted queue: query replies are dropped (`shouldSuppressTerminalQueryResponse`, as the primary pane drops them) and focus/mouse reports go through `_sendInputEphemeral`, or a reload would replay them as typed text. That includes the click report a tile hand-encodes for a mouse-strip CLI: `TerminalTile._installClickListener` passes `ephemeral: true` in its target, which `_sendSyntheticSgrTap` honours, while the primary pane's own report (no flag) stays on `_sendInputAsync` as before. ⚠️ A SHELL Pane B pulls scrollback itself when the wheel goes up at the top of its buffer (`_maybeLoadMoreHistory`/`_pullHistory`): tmux repaints a burst of output instead of scrolling it, so Pane B's own xterm holds about one screen of scrollback while tmux holds every line, and it loaded history exactly once at connect and never again. It is the same bounded pull as Pane A's (`?full=1&tail=TERMINAL_TAIL_SIZE`, no rewrite when the window holds no more rows than the pane already has or the pane is at its `scrollback + rows` cap, and a 60 s back-off instead of 4 s when that skipped window was truncated or the pane is full, since each ask costs the server a whole-history `capture-pane`), against Pane B's OWN terminal rather than `app.terminal`, so it cannot share `_maybeRefetchFullHistory`. The wheel listener is capture-phase because xterm `stopPropagation()`s the events it consumes; the alternate-screen skip (nano, vim, less) only matters for a direct-PTY shell, since under tmux the browser xterm never enters the alternate buffer; skipped too for a detached session (mirrors `_sendResize()`'s own check and app.js's `_maybeRefetchFullHistory`), since its own window already owns its PTY size and scrollback. Live frames arriving from the response onward are held with their arrival time (`_liveQueue`, opened right after `await fetch(...)` beside `capturedAt`; a frame from before it is replaced by the capture or written unchanged, so the pane keeps painting during the round trip) and replayed in order only if they arrived after the capture (the response's arrival stands in for the capture instant, as in `_finishBufferLoad`, so a frame inside that one round trip can be lost or doubled); the request uses the primary pane's budget (`CodemanFetchDeadline.terminalFetchDeadlineMs({ full: true })`, 45 s, 10 s only if that helper is absent) and the body read gets 10 s once the headers land, because from then on the pull holds the pane's live output. The request phase holds no live output, but it does hold the single-flight flag, so a coalesced `{t:'r'}` refresh and a marker owed by a close (below) wait for the response, at worst for that whole budget (accepted: a Codeman restart resets an in-flight request along with the socket, so that pull fails at once and stamps the marker). ⚠️ The "disconnected" marker must be the LAST thing on screen. A replay's own `\x1bc` would otherwise wipe a marker written before the pull and paint a fresh, current-looking history while `onData` keeps silently dropping every keystroke on the dead socket (a Codeman restart drops the socket while the tmux session, and so the HTTP pull, still succeeds), so `_pullHistory()` re-stamps it after the live-frame flush. A close DURING any load (a pull, a refresh; `connect()` awaits the initial load before it creates the socket, so no close lands in that one) writes nothing: `_onSocketClosed()` sets `_markerOwed` while a load's work runs (`_loadRunning`; a load that only waits in the tile grid's queue writes the marker at once, and its refresh resets the screen only once its own capture is in hand), since written there it would sit above the held frames the pull flushes after a skip, a downgrade, a failed fetch or the deadline, above a refresh's replay, or land mid-way through a chunked replay. Each load settles the marker in its OWN `finally` (`_stampMarkerIfOwed()`), after the queue flush, EXCEPT when a trailing refresh is pending: that refresh settles it itself (its replay's queued `\x1bc` would wipe a marker written now, so it re-owes the marker on a closed socket and writes the one copy below its replay, and a refresh that writes nothing stamps the one still owed). The marker stays owed instead of being written twice; the default fake terminal in `test/terminal-tile-unit.test.ts` writes synchronously, so an async-parse fake there pins what ends up on screen. Anything that wipes the terminal on a closed socket (a pull's or a refresh's `\x1bc`) sets `_markerOwed` too, so the marker is rewritten whether or not the close landed during the load. Tracked via `_wsClosed`/`_markerOwed` rather than routed through `_onLiveOutput()`, since a close landing before the response is stamped before the cutoff and would be dropped with the rest of the pre-capture queue. There is no "Load full history" banner in Pane B, so a shell history past that 1 MiB window stays out of reach there. Non-shell Pane B is unchanged: it already loads `full=1`, and its history is out of scope for this pull (codex and Claude's inline renderer do grow tmux history; this just isn't how they recover it). ⚠️ A server `{t:'c'}` frame is a REFRESH, never a bare `clear()` (`_onLiveClear()` calls `_refreshBuffer()`): its one emitter is a fresh Claude pane's first prompt (`Session.startInteractive`, "refresh after startup"), the primary pane answers it with a refetch and replay (`_onSessionClearTerminal`, which stands aside while the grid is open), and xterm's `clear()` keeps only the cursor's row, so a Claude session Run into the grid or Attached in a tile came up as a near-empty tile that an idle Claude never repainted. As a refresh it coalesces behind a load already running (a pull's held frames included) and waits its turn in the grid's load queue. ⚠️ A refresh (`{t:'r'}`, `{t:'c'}`, a reconnect) runs in the primary pane's order (`_onSessionNeedsRefresh`): fetch FIRST, so the pane keeps its last frame through the round trip and through a grid tile's wait; hold live frames from the response on (`_liveQueue`; the body read of a bounded window, a grid tile's or a shell's, gets the 10 s budget, while Pane B's unbounded `full=1` keeps the request's); then the queued in-stream `\x1bc` immediately before the replay, then the held frames that arrived after the response. Never xterm's `clear()`: it is synchronous while queued bytes are parsed after it (they fused into the snapshot) and it keeps the cursor's row and column, where the capture (raw rows, no home) then started. A failed, aborted or empty fetch writes nothing and resets nothing. ⚠️ Live output is flow-controlled per pane (`_writeLive`), because the server applies no backpressure and a flood a tile cannot parse as fast (a shell tile running `cat` on a huge log) used to pile up in xterm's own queue until its WriteBuffer threw past 50M code units and onmessage's catch lost the frames silently: unparsed output is counted through each write's callback, and held output by the queue, against `TerminalTile.LIVE_BACKLOG_BUDGET` (4 MiB; deliberately NOT the primary pane's 128 KB, which caps its own rAF-paced queues, while xterm itself paces a tile and a tight cap would blank-and-reload it on ordinary bursts). Past it a frame is dropped, the tile stops writing onto the hole, and one refresh, debounced and bounded by the primary pane's own rule (`CodemanDroppedOutput`: 2 s, at most `DROP_RECOVERY_MAX_ATTEMPTS`, never retried after a deadline abort), recaptures the screen; the flag clears only once a capture taken after the last dropped frame has replayed. A write xterm throws on is the same drop. Past the bound the flag is released (the tile is never left frozen), a reconnect starts the accounting over (an epoch makes callbacks from before it count nothing) and drops a pending recovery, since its own refresh replaces the screen, and `destroy()` cancels it. ⚠️ App-level terminal actions find their pane through `_focusedPane()`, the terminal focused LAST (not `document.activeElement`, which the mic or a header button takes): Ctrl+L, Ctrl+Shift+R, voice and image paste act on Pane B while it holds the keyboard. Ctrl+W is not an app shortcut at all (Close Session has no default key), so it reaches whichever pane is focused as delete-word. ⚠️ Geometry: `TerminalTile.fit()` sends the size the xterm actually holds, unfloored (the divider's 20% clamp leaves about 28 columns), skips an unchanged size, re-sends on every fresh socket, and adopts the PTY's column count from `{t:'zc'}`; a forced fit (Redraw: Ctrl+Shift+R, the header button, through `restoreTerminalSize`) carries the primary pane's `f` flag, without which `Session.resize` skips a size equal to the one it last applied, and `fit()` returns whether a frame went out, so Redraw reports success only for a resize it sent (a detached session or a socket that is down gets a warning instead); the font, family and weight setters call `tile.fit()`, never a local refit alone (#464). Every capture a pane fetches carries a deadline covering the body (`CodemanFetchDeadline`), so a capture that never answers cannot hold its single-flight flag forever. Design: `docs/split-pane-sessions-plan.md`; the tile class: `docs/tile-grid-plan.md`. ### 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. diff --git a/docs/ios-native-input.md b/docs/ios-native-input.md new file mode 100644 index 00000000..10640626 --- /dev/null +++ b/docs/ios-native-input.md @@ -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). diff --git a/docs/pi-integration-plan.md b/docs/pi-integration-plan.md index c5ae19b1..03f3a385 100644 --- a/docs/pi-integration-plan.md +++ b/docs/pi-integration-plan.md @@ -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. diff --git a/docs/reliable-input-delivery.md b/docs/reliable-input-delivery.md index 37e154dd..474e5c1d 100644 --- a/docs/reliable-input-delivery.md +++ b/docs/reliable-input-delivery.md @@ -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 diff --git a/package.json b/package.json index d9807786..848d9a5c 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/xterm-zerolag-input/README.md b/packages/xterm-zerolag-input/README.md index 135bfa09..0a00d7d8 100644 --- a/packages/xterm-zerolag-input/README.md +++ b/packages/xterm-zerolag-input/README.md @@ -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` | diff --git a/packages/xterm-zerolag-input/src/index.ts b/packages/xterm-zerolag-input/src/index.ts index f10d5265..bd919b4e 100644 --- a/packages/xterm-zerolag-input/src/index.ts +++ b/packages/xterm-zerolag-input/src/index.ts @@ -8,6 +8,7 @@ export type { ZerolagInputState, PromptFinder, PromptPosition, + InputEndAnchor, CellDimensions, } from './types.js'; export type { PredictiveEchoOptions, PredictionState } from './predictive-echo-addon.js'; diff --git a/packages/xterm-zerolag-input/src/overlay-renderer.ts b/packages/xterm-zerolag-input/src/overlay-renderer.ts index baa1bab2..e55529f3 100644 --- a/packages/xterm-zerolag-input/src/overlay-renderer.ts +++ b/packages/xterm-zerolag-input/src/overlay-renderer.ts @@ -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, + }; } /** diff --git a/packages/xterm-zerolag-input/src/types.ts b/packages/xterm-zerolag-input/src/types.ts index e81d610d..0b427719 100644 --- a/packages/xterm-zerolag-input/src/types.ts +++ b/packages/xterm-zerolag-input/src/types.ts @@ -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. * diff --git a/packages/xterm-zerolag-input/src/zerolag-input-addon.ts b/packages/xterm-zerolag-input/src/zerolag-input-addon.ts index e1320a98..fca8c07a 100644 --- a/packages/xterm-zerolag-input/src/zerolag-input-addon.ts +++ b/packages/xterm-zerolag-input/src/zerolag-input-addon.ts @@ -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(); } } } diff --git a/packages/xterm-zerolag-input/test/overlay-renderer.test.ts b/packages/xterm-zerolag-input/test/overlay-renderer.test.ts index a83d0901..533ba7c2 100644 --- a/packages/xterm-zerolag-input/test/overlay-renderer.test.ts +++ b/packages/xterm-zerolag-input/test/overlay-renderer.test.ts @@ -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', () => { diff --git a/packages/xterm-zerolag-input/test/zerolag-input-addon.test.ts b/packages/xterm-zerolag-input/test/zerolag-input-addon.test.ts index 4718cb25..fb4fb7df 100644 --- a/packages/xterm-zerolag-input/test/zerolag-input-addon.test.ts +++ b/packages/xterm-zerolag-input/test/zerolag-input-addon.test.ts @@ -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'); + }); +}); diff --git a/scripts/build.mjs b/scripts/build.mjs index f095fbc0..66601af7 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -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', diff --git a/scripts/prepare-test-vendor.mjs b/scripts/prepare-test-vendor.mjs index 5fc34453..8d207c6d 100644 --- a/scripts/prepare-test-vendor.mjs +++ b/scripts/prepare-test-vendor.mjs @@ -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 diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 5260666a..54aa671a 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -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:"` (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. Such a tile connects before its pane exists, the server drops that resize and spawns at 120x40, and Run's own resize measures the parked terminal (nothing), so the chrome refresh calls `tile.paneStarted()` when the session's pid appears or changes. ⚠️ An agent that exited in a live pane (`paneExit`) cannot be re-attached in place (both attach routes refuse while the pane's tmux client runs, and say so in a 200 envelope): its tile shows the exit and points at Close session. ⚠️ Each header (a tile's, both split panes': Pane A gets one only while the split is open, fitted through `sendResize`/`syncTerminalGeometry`) names the harness with PR #532's `run-mode-dot ` logo (the id is data, never a branch) and `SessionState.displayModel` (src/session-display-model.ts: custom endpoint, else the newest report from the CLI itself, i.e. claude's statusline or a footer read with `capabilities.modelDetect`, else what its config pins via the named `modelDetect.configResolver` (dsh-TUI's route, `src/deepseek-route-config.ts`: read-only, bounded, nothing on doubt), else the launch model, else nothing), painted by ONE diffing `_paintSessionHarness`; the model is untrusted text (`textContent`, `data-i18n-skip`). ⚠️ zh-CN: every string the grid shows has its own `ZH_CN` entry or `translateDynamic` pattern in i18n.js (`test/tile-grid-i18n.test.ts` harvests them from the real code; add the entry with any new string), and a refresh compares with the last ENGLISH value it set, never the DOM, which holds the translation. ⚠️ **Detach Tiles** (`tileDetachEnabled`, per-device, default OFF): a header let go outside the window pops the tile out (`detachSession` with a placement), dropped on ANOTHER Codeman window's tiles it moves there, and a pop-out's title drags back onto any grid. A foreign tile docks ONLY through `_dockForeignTile` (the target's own drop, then `tile-adopted` on the window channel), and only the window it was dragged FROM lets go of its copy (never a last-tile fallback onto that session: two windows sizing one PTY garble it). The gesture overlay moves tiles only through tile-grid.js's helpers (`tileDropTargetAt`/`dropOnTileTarget`/`detachTileAtPoint`). → [architecture-invariants#tile-grid](../../docs/architecture-invariants.md#tile-grid) @@ -32,6 +32,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order is the ` + diff --git a/src/web/public/input-cjk.js b/src/web/public/input-cjk.js index 263ce654..3cd9584f 100644 --- a/src/web/public/input-cjk.js +++ b/src/web/public/input-cjk.js @@ -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; }, diff --git a/src/web/public/keyboard-accessory.js b/src/web/public/keyboard-accessory.js index 3e4b2f7b..b3b93bc0 100644 --- a/src/web/public/keyboard-accessory.js +++ b/src/web/public/keyboard-accessory.js @@ -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'); diff --git a/src/web/public/mobile-ime-preview.js b/src/web/public/mobile-ime-preview.js index 42826c8a..0b9e77a9 100644 --- a/src/web/public/mobile-ime-preview.js +++ b/src/web/public/mobile-ime-preview.js @@ -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, diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index 7a292683..33545f59 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -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() { diff --git a/src/web/public/terminal-ios-native-input.js b/src/web/public/terminal-ios-native-input.js new file mode 100644 index 00000000..4ca2210a --- /dev/null +++ b/src/web/public/terminal-ios-native-input.js @@ -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); diff --git a/src/web/public/terminal-keycode229-recovery.js b/src/web/public/terminal-keycode229-recovery.js index d3fd3dfc..223d8cd4 100644 --- a/src/web/public/terminal-keycode229-recovery.js +++ b/src/web/public/terminal-keycode229-recovery.js @@ -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; diff --git a/src/web/public/terminal-tile.js b/src/web/public/terminal-tile.js index 3d1e2e7c..d9e4a1a8 100644 --- a/src/web/public/terminal-tile.js +++ b/src/web/public/terminal-tile.js @@ -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- diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index e3edbdac..a48484cc 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -644,6 +644,7 @@ Object.assign(CodemanApp.prototype, { }; const controller = MobileImePreview.create({ textarea, + ownsNativeInput: () => !!this._iosNativeInput, // An ancestor of the textarea: its capture-phase keydown listener runs // before xterm's capture listener on the textarea, which finalizes the // composition and emits the commit synchronously. @@ -744,7 +745,418 @@ Object.assign(CodemanApp.prototype, { } }, + _initTerminalInputOwner() { + this._destroyIosNativeInput(); + this._destroyKeyCode229Recovery(); + if (window.CodemanIosNativeInput?.isSupported?.() === true) { + this._iosNativeInput = window.CodemanIosNativeInput.create?.({ + terminal: this.terminal, + sendTransaction: (ops) => this._sendNativeInputTransaction(ops), + onCaret: () => this._syncMobileHelperTextareaToCursor(), + onTransaction: (transaction) => { + this._mobileImePreview?.nativeTransaction?.(transaction); + if (transaction.inserted) { + this._mobileImeCommitOutputSeq = this._terminalOutputSeq || 0; + if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(this.activeSessionId)) { + this._transferMobileImeCommitToLocalEcho(); + } + } + }, + isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true, + }); + if (this._iosNativeInput) { + this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, { + anchor: (caret) => this._nativeInputCaretAnchor(caret), + subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback), + }); + return; + } + // create() refused (screen reader, missing xterm internals): keep master's + // soft-keyboard recovery rather than leaving iOS with neither. + this._iosNativeInput = null; + } + try { + this._keyCode229Recovery = window.CodemanKeyCode229Recovery?.create?.({ + textarea: this.terminal.textarea, + emitRecovered: (data) => this._handleTerminalData(data, this.activeSessionId), + getCompositionHelper: () => this.terminal?._core?._compositionHelper, + isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true, + }); + } catch { + this._keyCode229Recovery = null; + } + }, + + _nativeInputCaretAnchor(caret) { + const overlay = this._localEchoOverlay; + if ( + this._localEchoEnabled && + !this._echoPassthroughSessions?.has(this.activeSessionId) && + (overlay?.pendingText || overlay?.getFlushed?.().count) + ) { + const committed = overlay.committedText; + if (typeof committed !== 'string' || !committed.endsWith(caret.text)) return 'hide'; + return overlay.getInputAnchor?.(committed.length - caret.text.length + caret.offset) || 'hide'; + } + return null; + }, + + _destroyIosNativeInput() { + if (typeof this._iosCaretMarker === 'function') this._iosCaretMarker(); + else this._iosCaretMarker?.destroy?.(); + this._iosCaretMarker = null; + this._iosNativeInput?.destroy?.(); + this._iosNativeInput = null; + }, + + // Printable input is batched per session, never against the terminal's later + // activeSessionId. Control actions and lifecycle boundaries seal it first. + _appendPendingInput(sessionId, data) { + if (!this._pendingInput) this._pendingInput = new Map(); + this._pendingInput.set(sessionId, (this._pendingInput.get(sessionId) || '') + data); + }, + + _takeLocalEchoInput(sessionId) { + const text = this._localEchoOverlay?.pendingText || ''; + this._localEchoOverlay?.clear(); + // Suppress detection so PTY-echoed text isn't re-detected as user input. + this._localEchoOverlay?.suppressBufferDetection(); + // Enter commits all text; control chars (Ctrl+C, Escape) change cursor + // position or abort readline, making flushed text tracking invalid. + // The same ownership handoff is used before paste and composer navigation. + this._flushedOffsets?.delete(sessionId); + this._flushedTexts?.delete(sessionId); + return text; + }, + + _submitMainInput(sessionId) { + this._sealPendingInput(sessionId); + if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(sessionId)) { + const text = this._takeLocalEchoInput(sessionId); + // Enter reserves the full buffered text, a short delay so text arrives + // first, and CR together. Later same-session writes cannot overtake CR, + // even when a tab switch flushes the next line during the 80 ms window. + this._enqueueInput(sessionId, [{ write: text }, { gap: 80 }, { write: '\r' }]); + } else { + this._echoPassthroughSessions?.delete(sessionId); + // The CR bypasses onData here, so tell the codex predictor about it as + // typed Enter does (it clears the prediction run). + this._predictHookOnData('\r'); + this._enqueueInput(sessionId, [{ write: '\r' }]); + } + }, + + _submitModifiedEnter(sessionId, key) { + this._prepareExternalInput({ terminal: this.terminal, sessionId, isPrimary: true }, 'modified-enter'); + const text = this._localEchoEnabled ? this._takeLocalEchoInput(sessionId) : ''; + this._enqueueInput(sessionId, [...(text ? [{ write: text }, { gap: 80 }] : []), { key }]); + }, + + _prepareExternalInput(pane, reason, opts = {}) { + if (!pane?.terminal || !pane.sessionId || pane.tile?._destroyed) return; + const host = pane.isPrimary ? this : pane.tile; + host?._iosNativeInput?.settle?.(); + this._sealPendingInput(pane.sessionId); + if (opts.flushEcho && pane.isPrimary && this._localEchoEnabled && + !this._echoPassthroughSessions?.has(pane.sessionId)) { + const text = this._takeLocalEchoInput(pane.sessionId); + if (text) this._enqueueInput(pane.sessionId, [{ write: text }]); + } + host?._iosNativeInput?.reset?.(reason); + host?._mobileImePreview?.reset?.(); + if (host) host._mobileImeCommitOutputSeq = null; + }, + + submitFromToolbar() { + const pane = this._focusedPane(); + if (!pane?.terminal || !pane.sessionId || pane.tile?._destroyed || !this.sessions.has(pane.sessionId)) return; + // Typed Enter spends an armed one-shot Ctrl in onData; this CR skips onData. + if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.clearCtrl?.(); + // The CR goes on the FIFO, not through xterm's triggerDataEvent(data, true), + // so its scrollOnUserInput never runs; scroll to the prompt as it would. + const terminal = pane.terminal; + if (terminal.options?.scrollOnUserInput !== false && typeof terminal.scrollToBottom === 'function') { + terminal.scrollToBottom(); + } + this._prepareExternalInput(pane, 'submit'); + if (pane.isPrimary) this._submitMainInput(pane.sessionId); + else this._sendInputAsync(pane.sessionId, '\r'); + }, + + _sendNativeInputTransaction(ops) { + const sessionId = this.activeSessionId; + if (!sessionId) return; + this._sealPendingInput(sessionId); + // A replacement can contain several DELs followed by an insertion. Decide + // the one-shot modifier once for the insertion, never once per DEL; each + // deletion still needs its own pending/flushed local-echo classification. + const writes = []; + let ctrlIndex = -1; + if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) { + ctrlIndex = ops.findIndex((data) => data !== '\x7f' && !window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(data)); + if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.(); + } + for (let i = 0; i < ops.length; i++) { + const data = i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(ops[i]) : ops[i]; + this._handleTerminalData(data, sessionId, writes); + } + this._enqueueInput(sessionId, writes); + if (ctrlIndex !== -1) this._iosNativeInput?.reset?.('ctrl'); + }, + + // Local echo mode: buffer keystrokes locally (shown in overlay) and only + // send to PTY on Enter. Avoids out-of-order delivery on high-latency + // mobile connections. The overlay + localStorage persistence ensure input + // survives tab switches and reconnects; accepted FIFO items stay session-owned. + _handleTerminalData(data, sessionId, transactionWrites = null) { + // Before anything can rewrite `data`: is this chunk the IME's commit? + const isImeCommit = this._consumeMobileImeTerminalData(data); + const input = window.CodemanTerminalInput; + // Mouse SGR reports (tap-to-position) are NOT IME input — they must reach + // the PTY even while the CJK input field owns focus. Without this exception + // tapping to move the cursor silently does nothing whenever Chinese input + // is on, because cjkActive stays true the whole time the field is visible. + const isMouseReport = /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data); + // CJK input has focus — block xterm from sending keystrokes to PTY. + if (!isMouseReport && (window.cjkActive || document.activeElement?.id === 'cjkInput')) { + // Self-heal: if the CJK field is visible but focus drifted to xterm's + // hidden textarea (e.g. something called terminal.focus()), everything + // typed lands HERE and is swallowed — keyboard shows the IME composing + // while both the CJK field and the terminal stay empty. Route focus + // back so the very next keystroke lands in the CJK field again. + // Only GENUINE typed input qualifies: onData also fires for xterm's + // self-generated query replies (DA/DSR/CPR/OSC during Ink redraws), + // which arrive no matter what has focus — so require focus to be on + // xterm's own textarea and bail on query replies, or this would steal + // focus from the rename/search/settings inputs while output streams. + const cjkEl = document.getElementById('cjkInput'); + if ( + cjkEl?.classList.contains('cjk-input-visible') && + document.activeElement === this.terminal.textarea && + !input?.shouldSuppressTerminalQueryResponse(data) + ) { + _crashDiag.log('CJK regain-focus (onData swallowed input)'); + cjkEl.focus(); + } + return; + } + // Filter terminal query replies generated by xterm.js itself. + // Forwarding them through the WebSocket injects DA/DSR/CPR replies + // into the foreground process as typed input (for example "0;276;0c"). + if (!sessionId || input?.shouldSuppressTerminalQueryResponse(data)) return; + // ── One-shot Ctrl (mobile shell bar, issue #262) ── + // A virtual keyboard reports no usable key events, so a keydown hook + // would never see the character the modifier applies to: it arrives + // here as onData text. Sits AFTER the query-response filter so xterm's + // own DA/CPR replies can never spend the modifier, and BEFORE every + // send path so the control byte follows the normal control-char route + // (immediate flush, local-echo state cleared). + // + // Mouse and focus reports are skipped rather than suppressed: they are + // real bytes the PTY still needs, they just were not typed by anyone. + // A shell session passes mouse DECSETs through, so with vim or htop + // running, one tap on the terminal used to spend the modifier silently + // (measured against a real shell). See isTerminalFocusOrMouseReport. + // Native transactions already applied Ctrl once before entering this path. + if (!transactionWrites && typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() && + !input?.isTerminalFocusOrMouseReport(data)) { + data = KeyboardAccessoryBar.consumeCtrl(data); + this._iosNativeInput?.reset?.('ctrl'); + } + this._lastTerminalData = { data, time: performance.now() }; + const send = (text) => { + if (!text) return; + if (transactionWrites) transactionWrites.push({ write: text }); + else { + this._appendPendingInput(sessionId, text); + this._sealPendingInput(sessionId); + } + }; + // Control/Enter/paste/transaction input seals this session's older printable + // batch before reserving its own FIFO position. No timer resolves a target. + if (transactionWrites || data.charCodeAt(0) < 32 || data.length > 1 || data === '\x7f') this._sealPendingInput(sessionId); + // ── Local Echo Pass-through ── + // After a composer nav key (arrow/Home/End/Delete) the real cursor may + // sit mid-text, where the overlay's append-only buffering would corrupt + // both the preview and the submitted text. Such sessions are handed + // back to plain PTY echo until Enter or Ctrl+C submits/cancels the + // composer line (see the nav-key branch below). + const echoPassthrough = this._localEchoEnabled && this._echoPassthroughSessions?.has(sessionId); + if (echoPassthrough && (data === '\r' || data === '\x03')) this._echoPassthroughSessions.delete(sessionId); + // ── Local Echo Mode ── + // When enabled, keystrokes are buffered locally in the overlay for + // instant visual feedback. Nothing is sent to the PTY until Enter + // (or a control char) is pressed — avoids out-of-order char delivery. + // An IME commit takes the same printable/paste branch as typed text, + // and the overlay then shows it in place of the preview. + if (this._localEchoEnabled && !echoPassthrough) { + if (data === '\x7f') { + const source = this._localEchoOverlay?.removeChar(); + if (source === 'flushed') { + // Sync app-level flushed Maps (per-session state for tab switching). + const { count, text } = this._localEchoOverlay.getFlushed(); + if (this._flushedOffsets?.has(sessionId)) { + if (count === 0) { + this._flushedOffsets.delete(sessionId); + this._flushedTexts?.delete(sessionId); + } else { + this._flushedOffsets.set(sessionId, count); + this._flushedTexts?.set(sessionId, text); + } + } + } + // Nothing pending, nothing flushed, nothing detected: the composer may + // still hold text the overlay cannot see (buffer detection is suppressed + // after a control-char flush), so forward the backspace instead of + // swallowing it (issue #218); an empty composer ignores it. + if (source === 'flushed' || source === false) send(data); + // 'pending' = removed unsent text (no PTY backspace needed). + return; + } + if (/^[\r\n]+$/.test(data)) { + // The shared submit helper reserves buffered text + gap + CR atomically. + this._submitMainInput(sessionId); + return; + } + if (data.charCodeAt(0) >= 32) { + // Paste: append to overlay only (sent on Enter). + // Printable char: add to overlay only (sent on Enter). + if (data.length > 1) this._localEchoOverlay?.appendText(data); + else this._localEchoOverlay?.addChar(data); + if (isImeCommit && this._localEchoOverlay) this._transferMobileImeCommitToLocalEcho(); + return; + } + // Preserve xterm-generated terminal responses that survived query filtering. + // These arrive via triggerDataEvent when the terminal processes buffer + // data (DA responses, OSC color queries, mode reports, etc.). They are NOT + // user input and must not clear flushed text state. Covers CSI (\x1b[), + // OSC (\x1b]), DCS (\x1bP), APC (\x1b_), PM (\x1b^), SOS (\x1bX), and + // other multi-byte ESC sequences. Single-byte ESC (user pressing Escape) + // still falls through to the control char handler below. + if (data.length > 1 && data.charCodeAt(0) === 27) { + // Bracketed paste (terminal.paste() while DECSET 2004 is on): + // flush typed-but-unsent overlay text FIRST so the pasted block + // lands after it in the composer, not before it (issue #219). + // The paste sequence gets its own delayed write: Codex's + // paste-burst handling drops keystrokes that arrive in the SAME + // PTY read as a bracketed paste (verified against codex 0.147), + // mirroring the delayed CR in the Enter helper above. Reserve both + // writes and the gap together so later input cannot overtake the paste. + if (data.startsWith(input.BRACKETED_PASTE_START)) { + const text = this._takeLocalEchoInput(sessionId); + this._enqueueInput(sessionId, [...(text ? [{ write: text }, { gap: 80 }] : []), { write: data }]); + return; + } + // Composer nav keys (arrows, Home/End, Delete, PgUp/PgDn): + // flush unsent text so the key edits the real composer state, + // then hand the session to plain PTY echo until Enter/Ctrl+C. + // The cursor may now sit mid-text, where append-only buffering + // cannot track edits (issue #218). + if (input.isComposerNavKey(data)) { + const text = this._takeLocalEchoInput(sessionId); + if (!this._echoPassthroughSessions) this._echoPassthroughSessions = new Set(); + this._echoPassthroughSessions.add(sessionId); + send(text + data); + return; + } + // Multi-byte escape sequence — forward to PTY without clearing + // overlay/flushed state (terminal response, not user input). + send(data); + return; + } + // During buffer load (tab switch), stray control chars from + // terminal response processing must not wipe the flushed state + // that selectSession() is actively restoring. + if (this._restoringFlushedState) { + send(data); + return; + } + // Control chars (Ctrl+C, single ESC): send buffered text + control char + // immediately through the session FIFO. Tab uses the same text flush. + const text = this._takeLocalEchoInput(sessionId); + // Tab key: send pending text + Tab to PTY for tab completion. + // Set a flag so flushPendingWrites() re-detects buffer text when + // the PTY response arrives (event-driven, with the fallback below). + if (data === '\t') { + // Snapshot prompt line text BEFORE flushing — used to distinguish + // real Tab completions from pre-existing Claude UI text. + let baseText = ''; + try { + const p = this._localEchoOverlay?.findPrompt?.(); + const buf = this.terminal.buffer.active; + const line = p && buf.getLine(buf.viewportY + p.row); + if (line) baseText = line.translateToString(true).slice(p.col + 2).trimEnd(); + } catch {} + this._tabCompletionBaseText = baseText; + this._tabCompletionSessionId = sessionId; + this._tabCompletionRetries = 0; + // Fallback: if flushPendingWrites() detection misses the completion + // (e.g., flicker filter delays data, or xterm hasn't processed writes + // by the time the callback fires), retry detection after a delay. + // This ensures the overlay renders even without further terminal data. + // Both callbacks retain the captured session's completion ownership. + clearTimeout(this._tabCompletionFallback); + this._tabCompletionFallback = setTimeout(() => { + this._tabCompletionFallback = null; + if (this._tabCompletionSessionId !== sessionId) return; + const ov = this._localEchoOverlay; + if (!ov || ov.pendingText) return; + this.terminal.write('', () => { + if (this._tabCompletionSessionId !== sessionId) return; + ov.resetBufferDetection(); + const detected = ov.detectBufferText(); + if (detected && detected !== this._tabCompletionBaseText) { + this._tabCompletionSessionId = null; + this._tabCompletionRetries = 0; + this._tabCompletionBaseText = null; + ov.rerender(); + } + }); + }, 300); + } + send(text + data); + return; + } + // ── Predictive Echo (codex): visual only. A plain statement, never a + // `return`: control ALWAYS falls through into the send path below, + // which is the byte-identity guarantee for #218/#219/#220/#222 — + // with the predictor active, absent or throwing, the wire sees the + // same bytes. Body in _predictHookOnData (vm-testable). + this._predictHookOnData(data); + // Native transactions collect remote writes in order and bypass printable + // batching; the caller appends the entire transaction to its captured FIFO. + if (transactionWrites) { + send(data); + return; + } + // ── Normal Mode (echo disabled) ── + // PTY/Ink handles character echoing; only printable bursts are batched. + this._appendPendingInput(sessionId, data); + // Control chars (Enter, Ctrl+C, escape sequences), paste and DEL — flush + // immediately into the FIFO, behind any accepted delayed reservation. + if (data.charCodeAt(0) < 32 || data.length > 1 || data === '\x7f') { + this._sealPendingInput(sessionId); + return; + } + // Regular chars — flush immediately if typed after a gap (>50ms), + // otherwise coalesce rapid keystrokes with a zero-delay task. Timestamp, + // pending text and timer belong to this session, not the currently active one. + if (!this._lastKeystrokeTime) this._lastKeystrokeTime = new Map(); + if (!this._inputFlushTimeout) this._inputFlushTimeout = new Map(); + const now = performance.now(); + const last = this._lastKeystrokeTime.get(sessionId) || 0; + this._lastKeystrokeTime.set(sessionId, now); + // Single char after a gap — send immediately, no setTimeout latency. + if (now - last > 50) this._sealPendingInput(sessionId); + else if (!this._inputFlushTimeout.has(sessionId)) { + // Rapid sequence (paste or fast typing) — coalesce via a zero-delay task. + this._inputFlushTimeout.set(sessionId, setTimeout(() => this._sealPendingInput(sessionId), 0)); + } + }, + initTerminal() { + if (this.terminal) this._settleMainInput('terminal'); + this._destroyIosNativeInput(); // Load scrollback setting from localStorage, treating DEFAULT_SCROLLBACK as a floor // so users who picked up the previous (smaller) default get the new minimum on upgrade. const stored = parseInt(localStorage.getItem('codeman-scrollback')); @@ -817,17 +1229,19 @@ Object.assign(CodemanApp.prototype, { // punctuation; returning false here would stop xterm before it can diff // the helper textarea and emit the committed Unicode text. this.terminal.attachCustomKeyEventHandler((ev) => { + let nativeKeyResult; try { // Deliberately runs for EVERY keydown, not just keyCode 229: the // controller snapshots a counter and reads nothing off the event, and // the devices this exists for report `key: 'Unidentified'` with no // reliable identity to gate on. Gating it would make recovery inert // exactly where it is needed. Cost is one assignment. - this._keyCode229Recovery?.handleKeyEvent?.(ev); + if (this._iosNativeInput) nativeKeyResult = this._iosNativeInput.keyFilter?.(ev); + else this._keyCode229Recovery?.handleKeyEvent?.(ev); } catch { // The fallback must never interfere with xterm's canonical handler. } - if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return true; + if (ev.isComposing || ev.key === 'Process' || ev.keyCode === 229) return nativeKeyResult ?? true; // Let the app's Alt/Option session-nav and Command Palette shortcuts reach the document keydown handler // (app.js switches tabs by PHYSICAL e.code) instead of xterm injecting ESC into @@ -961,37 +1375,14 @@ Object.assign(CodemanApp.prototype, { // This handler also runs for keypress/keyup: xterm drops a keypress carrying Ctrl/Alt // but NOT one carrying only Shift, so unless every event type is swallowed here, // Shift+Enter's keypress sends a bare \r (submit) after the newline. Only keydown sends. - if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)) { + if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey) && (!this._iosNativeInput || ev.keyCode === 13)) { if (ev.type === 'keydown' && this.activeSessionId) { - if (this._localEchoEnabled) { - const text = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay?.clear(); - this._localEchoOverlay?.suppressBufferDetection(); - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (text) { - this._pendingInput += text; - flushInput(); - } - setTimeout(() => { - fetch(`/api/sessions/${this.activeSessionId}/send-key`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ key: ev.ctrlKey ? 'C-Enter' : 'S-Enter' }), - }); - }, text ? 80 : 0); - } else { - fetch(`/api/sessions/${this.activeSessionId}/send-key`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ key: ev.ctrlKey ? 'C-Enter' : 'S-Enter' }), - }); - } + this._submitModifiedEnter(this.activeSessionId, ev.ctrlKey ? 'C-Enter' : 'S-Enter'); } return false; } - return true; + return nativeKeyResult ?? true; }); // WebGL renderer for GPU-accelerated terminal rendering. @@ -1080,13 +1471,12 @@ Object.assign(CodemanApp.prototype, { this._cjkInput = null; if (typeof CjkInput !== 'undefined') { this._cjkInput = CjkInput.init({ - send: (text) => { - this._handleCjkInput(text); - }, + captureTarget: () => this._focusedPane()?.sessionId, + send: (text, sessionId) => this._handleCjkInput(text, sessionId), // Send on Enter: a long or multi-line held answer goes out like the // mobile prompt composer's Send (one bracketed paste, then Enter as a // separate delayed write), bound to the session it was typed for. - sendPrompt: (text) => this._sendCjkPrompt(text), + sendPrompt: (text, sessionId) => this._sendCjkPrompt(text, sessionId), }); } @@ -1745,356 +2135,8 @@ Object.assign(CodemanApp.prototype, { this.terminalResizeObserver = new ResizeObserver(throttledResize); this.terminalResizeObserver.observe(container); - // Handle keyboard input — send to PTY immediately, no local echo. - // PTY/Ink handles all character echoing to avoid desync ("typing visible below" bug). - this._pendingInput = ''; - this._inputFlushTimeout = null; - this._lastKeystrokeTime = 0; - - const flushInput = () => { - this._inputFlushTimeout = null; - if (this._pendingInput && this.activeSessionId) { - const input = this._pendingInput; - const sessionId = this.activeSessionId; - this._pendingInput = ''; - this._sendInputAsync(sessionId, input); - } - }; - - // Local echo mode: buffer keystrokes locally (shown in overlay) and only - // send to PTY on Enter. Avoids out-of-order delivery on high-latency - // mobile connections. The overlay + localStorage persistence ensure input - // survives tab switches and reconnects. - - const handleTerminalData = (data) => { - // Before anything can rewrite `data`: is this chunk the IME's commit? - const isImeCommit = this._consumeMobileImeTerminalData(data); - // Mouse SGR reports (tap-to-position) are NOT IME input — they must reach - // the PTY even while the CJK input field owns focus. Without this exception - // tapping to move the cursor silently does nothing whenever Chinese input - // is on, because cjkActive stays true the whole time the field is visible. - const isMouseReport = /^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data); - // CJK input has focus — block xterm from sending keystrokes to PTY - if (!isMouseReport && (window.cjkActive || document.activeElement?.id === 'cjkInput')) { - // Self-heal: if the CJK field is visible but focus drifted to xterm's - // hidden textarea (e.g. something called terminal.focus()), everything - // typed lands HERE and is swallowed — keyboard shows the IME composing - // while both the CJK field and the terminal stay empty. Route focus - // back so the very next keystroke lands in the CJK field again. - // Only GENUINE typed input qualifies: onData also fires for xterm's - // self-generated query replies (DA/DSR/CPR/OSC during Ink redraws), - // which arrive no matter what has focus — so require focus to be on - // xterm's own textarea and bail on query replies, or this would steal - // focus from the rename/search/settings inputs while output streams. - const cjkEl = document.getElementById('cjkInput'); - if ( - cjkEl?.classList.contains('cjk-input-visible') && - document.activeElement === this.terminal.textarea && - !window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(data) - ) { - _crashDiag.log('CJK regain-focus (onData swallowed input)'); - cjkEl.focus(); - } - return; - } - if (this.activeSessionId) { - // Filter terminal query replies generated by xterm.js itself. - // Forwarding them through the WebSocket injects DA/DSR/CPR replies - // into the foreground process as typed input (for example "0;276;0c"). - if ( - window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(data) - ) { - return; - } - - // ── One-shot Ctrl (mobile shell bar, issue #262) ── - // A virtual keyboard reports no usable key events, so a keydown hook - // would never see the character the modifier applies to: it arrives - // here as onData text. Sits AFTER the query-response filter so xterm's - // own DA/CPR replies can never spend the modifier, and BEFORE every - // send path so the control byte follows the normal control-char route - // (immediate flush, local-echo state cleared). - // - // Mouse and focus reports are skipped rather than suppressed: they are - // real bytes the PTY still needs, they just were not typed by anyone. - // A shell session passes mouse DECSETs through, so with vim or htop - // running, one tap on the terminal used to spend the modifier silently - // (measured against a real shell). See isTerminalFocusOrMouseReport. - if ( - typeof KeyboardAccessoryBar !== 'undefined' && - KeyboardAccessoryBar.isCtrlArmed?.() && - !window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(data) - ) { - data = KeyboardAccessoryBar.consumeCtrl(data); - } - - this._lastTerminalData = { data, time: performance.now() }; - - // ── Local Echo Pass-through ── - // After a composer nav key (arrow/Home/End/Delete) the real cursor may - // sit mid-text, where the overlay's append-only buffering would corrupt - // both the preview and the submitted text. Such sessions are handed - // back to plain PTY echo until Enter or Ctrl+C submits/cancels the - // composer line (see the nav-key branch below). - const echoPassthrough = - this._localEchoEnabled && this._echoPassthroughSessions?.has(this.activeSessionId); - if (echoPassthrough && (data === '\r' || data === '\x03')) { - this._echoPassthroughSessions.delete(this.activeSessionId); - } - - // ── Local Echo Mode ── - // When enabled, keystrokes are buffered locally in the overlay for - // instant visual feedback. Nothing is sent to the PTY until Enter - // (or a control char) is pressed — avoids out-of-order char delivery. - // An IME commit takes the same printable/paste branch as typed text, - // and the overlay then shows it in place of the preview. - if (this._localEchoEnabled && !echoPassthrough) { - if (data === '\x7f') { - const source = this._localEchoOverlay?.removeChar(); - if (source === 'flushed') { - // Sync app-level flushed Maps (per-session state for tab switching) - const { count, text } = this._localEchoOverlay.getFlushed(); - if (this._flushedOffsets?.has(this.activeSessionId)) { - if (count === 0) { - this._flushedOffsets.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - } else { - this._flushedOffsets.set(this.activeSessionId, count); - this._flushedTexts?.set(this.activeSessionId, text); - } - } - this._pendingInput += data; - flushInput(); - } else if (source === false) { - // Nothing pending, nothing flushed, nothing detected. The - // composer may still hold text the overlay cannot see (buffer - // detection is suppressed after a control-char flush), so - // forward the backspace instead of swallowing it (issue #218); - // an empty composer ignores it. - this._pendingInput += data; - flushInput(); - } - // 'pending' = removed unsent text (no PTY backspace needed) - return; - } - if (/^[\r\n]+$/.test(data)) { - // Enter: send full buffered text + \r to PTY in one shot - const text = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay?.clear(); - // Suppress detection so PTY-echoed text isn't re-detected as user input - this._localEchoOverlay?.suppressBufferDetection(); - // Clear flushed offset and text — Enter commits all text - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - if (text) { - this._pendingInput += text; - flushInput(); - } - // Send \r after a short delay so text arrives first - setTimeout(() => { - this._pendingInput += '\r'; - flushInput(); - }, 80); - return; - } - if (data.length > 1 && data.charCodeAt(0) >= 32) { - // Paste: append to overlay only (sent on Enter) - this._localEchoOverlay?.appendText(data); - if (isImeCommit && this._localEchoOverlay) this._transferMobileImeCommitToLocalEcho(); - return; - } - if (data.charCodeAt(0) < 32) { - // Skip xterm-generated terminal responses. - // These arrive via triggerDataEvent when the terminal processes - // buffer data (DA responses, OSC color queries, mode reports, etc.). - // They are NOT user input and must not clear flushed text state. - // Covers: CSI (\x1b[), OSC (\x1b]), DCS (\x1bP), APC (\x1b_), - // PM (\x1b^), SOS (\x1bX), and any other multi-byte ESC sequence. - // Single-byte ESC (user pressing Escape) still falls through to - // the control char handler below. - if (data.length > 1 && data.charCodeAt(0) === 27) { - // Bracketed paste (terminal.paste() while DECSET 2004 is on): - // flush typed-but-unsent overlay text FIRST so the pasted block - // lands after it in the composer, not before it (issue #219). - // The paste sequence gets its own delayed write: Codex's - // paste-burst handling drops keystrokes that arrive in the SAME - // PTY read as a bracketed paste (verified against codex 0.147), - // mirroring the delayed \r in the Enter branch above. - if (data.startsWith(window.CodemanTerminalInput.BRACKETED_PASTE_START)) { - const hadPending = !!this._localEchoOverlay?.pendingText; - this._flushLocalEchoPending(); - if (hadPending) { - flushInput(); - setTimeout(() => { - this._pendingInput += data; - flushInput(); - }, 80); - } else { - this._pendingInput += data; - flushInput(); - } - return; - } - // Composer nav keys (arrows, Home/End, Delete, PgUp/PgDn): - // flush unsent text so the key edits the real composer state, - // then hand the session to plain PTY echo until Enter/Ctrl+C. - // The cursor may now sit mid-text, where append-only buffering - // cannot track edits (issue #218). - if (window.CodemanTerminalInput.isComposerNavKey(data)) { - this._flushLocalEchoPending(); - if (!this._echoPassthroughSessions) this._echoPassthroughSessions = new Set(); - this._echoPassthroughSessions.add(this.activeSessionId); - this._pendingInput += data; - flushInput(); - return; - } - // Multi-byte escape sequence — forward to PTY without clearing - // overlay/flushed state (terminal response, not user input) - this._pendingInput += data; - flushInput(); - return; - } - // During buffer load (tab switch), stray control chars from - // terminal response processing must not wipe the flushed state - // that selectSession() is actively restoring. - if (this._restoringFlushedState) { - this._pendingInput += data; - flushInput(); - return; - } - // Tab key: send pending text + Tab to PTY for tab completion. - // Set a flag so flushPendingWrites() re-detects buffer text when - // the PTY response arrives (event-driven, no fixed timer). - if (data === '\t') { - const text = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay?.clear(); - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (text) { - this._pendingInput += text; - } - this._pendingInput += data; - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - // Snapshot prompt line text BEFORE flushing — used to distinguish - // real Tab completions from pre-existing Claude UI text. - let baseText = ''; - try { - const p = this._localEchoOverlay?.findPrompt?.(); - if (p) { - const buf = this.terminal.buffer.active; - const line = buf.getLine(buf.viewportY + p.row); - if (line) - baseText = line - .translateToString(true) - .slice(p.col + 2) - .trimEnd(); - } - } catch {} - this._tabCompletionBaseText = baseText; - flushInput(); - this._tabCompletionSessionId = this.activeSessionId; - this._tabCompletionRetries = 0; - // Fallback: if flushPendingWrites() detection misses the completion - // (e.g., flicker filter delays data, or xterm hasn't processed writes - // by the time the callback fires), retry detection after a delay. - // This ensures the overlay renders even without further terminal data. - if (this._tabCompletionFallback) clearTimeout(this._tabCompletionFallback); - const selfTab = this; - this._tabCompletionFallback = setTimeout(() => { - selfTab._tabCompletionFallback = null; - if (!selfTab._tabCompletionSessionId || selfTab._tabCompletionSessionId !== selfTab.activeSessionId) - return; - const ov = selfTab._localEchoOverlay; - if (!ov || ov.pendingText) return; - selfTab.terminal.write('', () => { - if (!selfTab._tabCompletionSessionId) return; - ov.resetBufferDetection(); - const detected = ov.detectBufferText(); - if (detected && detected !== selfTab._tabCompletionBaseText) { - selfTab._tabCompletionSessionId = null; - selfTab._tabCompletionRetries = 0; - selfTab._tabCompletionBaseText = null; - ov.rerender(); - } - }); - }, 300); - return; - } - // Control chars (Ctrl+C, single ESC): send buffered text + control char immediately - const text = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay?.clear(); - // Suppress detection so PTY-echoed text isn't re-detected as user input - this._localEchoOverlay?.suppressBufferDetection(); - // Clear flushed offset and text — control chars (Ctrl+C, Escape) change - // cursor position or abort readline, making flushed text tracking invalid. - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (text) { - this._pendingInput += text; - } - this._pendingInput += data; - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - flushInput(); - return; - } - if (data.length === 1 && data.charCodeAt(0) >= 32) { - // Printable char: add to overlay only (sent on Enter) - this._localEchoOverlay?.addChar(data); - if (isImeCommit && this._localEchoOverlay) this._transferMobileImeCommitToLocalEcho(); - return; - } - } - - // ── Predictive Echo (codex): visual only. A plain statement, never a - // `return`: control ALWAYS falls through into the send path below, - // which is the byte-identity guarantee for #218/#219/#220/#222 — - // with the predictor active, absent or throwing, the wire sees the - // same bytes. Body in _predictHookOnData (vm-testable). - this._predictHookOnData(data); - - // ── Normal Mode (echo disabled) ── - this._pendingInput += data; - - // Control chars (Enter, Ctrl+C, escape sequences) — flush immediately - if (data.charCodeAt(0) < 32 || data.length > 1) { - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - flushInput(); - return; - } - - // Regular chars — flush immediately if typed after a gap (>50ms), - // otherwise batch via microtask to coalesce rapid keystrokes (paste). - const now = performance.now(); - if (now - this._lastKeystrokeTime > 50) { - // Single char after a gap — send immediately, no setTimeout latency - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - this._lastKeystrokeTime = now; - flushInput(); - } else { - // Rapid sequence (paste or fast typing) — coalesce via microtask - this._lastKeystrokeTime = now; - if (!this._inputFlushTimeout) { - this._inputFlushTimeout = setTimeout(flushInput, 0); - } - } - } - }; + // Capture the session when xterm produces data, not when its printable batch flushes. + const handleTerminalData = (data) => this._handleTerminalData(data, this.activeSessionId); // Chrome on Android delivers a `composed: true` input event preceded by a // keydown, which is exactly the shape xterm's _inputEvent refuses to @@ -2110,16 +2152,7 @@ Object.assign(CodemanApp.prototype, { // connect() key handler and onData) wires its own controller the same way // for every grid tile and the split's Pane B; keep the two in step. // create() returns null unless the primary pointer is coarse (#716). - try { - this._keyCode229Recovery = window.CodemanKeyCode229Recovery?.create?.({ - textarea: this.terminal.textarea, - emitRecovered: (data) => handleTerminalData(data), - getCompositionHelper: () => this.terminal?._core?._compositionHelper, - isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true, - }); - } catch { - this._keyCode229Recovery = null; - } + this._initTerminalInputOwner(); this.terminal.onData((data) => { // Canonical xterm data. Telling the controller is what lets it know a // keystroke was already delivered and needs no recovery. @@ -4396,23 +4429,6 @@ Object.assign(CodemanApp.prototype, { this._scheduleTerminalWriteFlush(); }, - /** - * Flush the local-echo overlay's unsent text into `_pendingInput` (no - * trailing Enter) and reset overlay + flushed-state tracking. Used before - * forwarding sequences that must arrive AFTER the typed text (bracketed - * paste, composer nav keys). The caller forwards its own sequence: nav keys - * ride the same write, pastes get a delayed second write because codex - * drops keys that share a PTY read with a bracketed paste. - */ - _flushLocalEchoPending() { - const text = this._localEchoOverlay?.pendingText || ''; - this._localEchoOverlay?.clear(); - this._localEchoOverlay?.suppressBufferDetection(); - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); - if (text) this._pendingInput += text; - }, - /** * Update local echo overlay state based on settings. * Enabled whenever the setting is on — works during idle AND busy. @@ -4431,9 +4447,22 @@ Object.assign(CodemanApp.prototype, { const settings = this.loadAppSettingsFromStorage(); const session = this.activeSessionId ? this.sessions.get(this.activeSessionId) : null; const echoEnabled = settings.localEchoEnabled ?? MobileDetection.isTouchDevice(); - const shouldEnable = !!(echoEnabled && session); - if (this._localEchoEnabled && !shouldEnable) { - this._localEchoOverlay?.clear(); + // Per-session echo policy: 'buffer' (overlay), 'predict' (codex + // write-through, see the onData predict hook), 'off'. Only 'buffer' + // turns the overlay on; this is the one place the mode decides it. + let policy = 'off'; + if (session && echoEnabled) { + if (session.mode === 'codex') policy = 'predict'; + else if (session.mode !== 'shell') policy = 'buffer'; + } + const shouldEnable = policy === 'buffer'; + if (!!this._localEchoEnabled !== shouldEnable) { + this._settleMainInput('echo-policy'); + if (!shouldEnable) { + // Plain PTY echo now owns the line; never restore the overlay snapshot. + this._flushedOffsets?.delete(this.activeSessionId); + this._flushedTexts?.delete(this.activeSessionId); + } } this._localEchoEnabled = shouldEnable; @@ -4471,8 +4500,7 @@ Object.assign(CodemanApp.prototype, { // keystrokes until Enter starves all of that, so codex sessions use // plain PTY echo like shell — visually augmented by the predictive // write-through echo (see _localEchoPolicy below and the onData hook). - // Disable the buffer overlay by clearing any pending text. - this._localEchoOverlay.clear(); + // The policy boundary above already settled and flushed the overlay. this._localEchoEnabled = false; } else { // Codex/Claude-style TUIs usually expose a ❯ prompt. During active @@ -4507,15 +4535,6 @@ Object.assign(CodemanApp.prototype, { } } - // Per-session echo policy: 'buffer' (overlay), 'predict' (codex - // write-through, see the onData predict hook), 'off'. _localEchoEnabled - // keeps its exact historical values above (false for codex/shell), so - // every existing consumer is unchanged; this field is purely additive. - let policy = 'off'; - if (session && echoEnabled) { - if (session.mode === 'codex') policy = 'predict'; - else if (session.mode !== 'shell') policy = 'buffer'; - } this._localEchoPolicy = policy; if (policy !== 'predict') this._predictiveEcho?.clearPredictions(); }, @@ -4543,11 +4562,13 @@ Object.assign(CodemanApp.prototype, { // CJK textarea already provides visual feedback — bypass local echo // buffering so each composed word reaches the PTY immediately. - _handleCjkInput(text) { - if (!this.activeSessionId) { - _crashDiag.log(`CJK send DROP no-session len=${text.length}`); - return; - } + _handleCjkInput(text, sessionId) { + const pane = sessionId ? this._paneForSession(sessionId) : this._focusedPane(); + if (sessionId && !this.sessions.has(sessionId)) return; + if (!pane && !sessionId) return; + sessionId = sessionId || pane.sessionId; + if (!sessionId) return; + if (pane) this._prepareExternalInput(pane, 'cjk'); // ── One-shot Ctrl (mobile shell bar, issue #262) ── // While the CJK field is visible it OWNS the keyboard: onData returns early // for everything it swallows, and the focus router even redirects @@ -4566,8 +4587,8 @@ Object.assign(CodemanApp.prototype, { } // Bypasses onData (like insertTerminalText): predictions cannot see this if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions(); - _crashDiag.log(`CJK send→${this.activeSessionId.slice(0, 8)} len=${text.length}`); - this._sendInputAsync(this.activeSessionId, text); + _crashDiag.log(`CJK send→${sessionId.slice(0, 8)} len=${text.length}`); + this._sendInputAsync(sessionId, text); }, /** @@ -4578,7 +4599,9 @@ Object.assign(CodemanApp.prototype, { * does the same for a long burst. Same split as TmuxManager.sendInput: a * single character is typed (a selection dialog ignores a pasted `3`, then * Enter confirms the highlighted option), anything else goes through the - * composer's path as one bracketed paste. The session is captured now, so the + * composer's path as one bracketed paste. The session is the one CjkInput + * captured when the text was started (`_targetForSend()`), and the text, the + * 120 ms gap and the Enter are reserved on that session's FIFO, so the * delayed Enter cannot follow a tab switch. A lone digit while the session * shows a permission or question dialog goes out without the Enter: the * dialog acts on the digit itself, and a later Enter would confirm whatever @@ -4587,9 +4610,9 @@ Object.assign(CodemanApp.prototype, { * false when nothing was sent (no session, too long), so the field keeps the * text. */ - _sendCjkPrompt(text) { - const sessionId = this.activeSessionId; - if (!sessionId || typeof KeyboardAccessoryBar === 'undefined') { + _sendCjkPrompt(text, targetSessionId) { + const sessionId = targetSessionId || this._focusedPane()?.sessionId; + if (!sessionId || !this.sessions.has(sessionId) || typeof KeyboardAccessoryBar === 'undefined') { _crashDiag.log(`CJK prompt DROP no-session len=${text.length}`); return false; } @@ -4599,15 +4622,17 @@ Object.assign(CodemanApp.prototype, { KeyboardAccessoryBar.clearCtrl?.(); _crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`); if ([...text].length === 1) { + const pane = this._paneForSession(sessionId); + if (pane) this._prepareExternalInput(pane, 'cjk-prompt'); if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions(); - this._sendInputAsync(sessionId, text); const hooks = this.pendingHooks?.get(sessionId); const awaitingChoice = !!hooks && (hooks.has('permission_prompt') || hooks.has('elicitation_dialog')); if (/^\d$/.test(text) && awaitingChoice) { - _crashDiag.log(`CJK prompt digit answers a dialog, no Enter`); + _crashDiag.log(`CJK prompt digit answers dialog, no Enter`); + this._enqueueInput(sessionId, [{ write: text }]); return true; } - setTimeout(() => this._sendInputAsync(sessionId, '\r', { useMux: true }), 120); + this._enqueueInput(sessionId, [{ write: text }, { gap: 120 }, { write: '\r', useMux: true }]); return true; } return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text); @@ -5074,8 +5099,24 @@ Object.assign(CodemanApp.prototype, { return { terminal: this.terminal, sessionId: this.activeSessionId, isPrimary: true, tile: null }; }, + /** Resolve the live native-input owner independently of keyboard focus. */ + _paneForSession(sessionId) { + if (!sessionId) return null; + if (this.activeSessionId === sessionId && !this._tilesOwnTerminal?.() && this.terminal) { + return { terminal: this.terminal, sessionId, isPrimary: true, tile: null }; + } + const tile = this._splitPane?.sessionId === sessionId && !this._splitPane._destroyed + ? this._splitPane + : this._tileFor?.(sessionId); + if (!tile?.terminal || tile._destroyed) return null; + return { terminal: tile.terminal, sessionId, isPrimary: false, tile }; + }, + /** Record which second pane holds the keyboard (null: the primary terminal). */ _noteFocusedTile(tile) { + if ((tile || null) !== (this._focusedTile || null) && typeof CjkInput !== 'undefined') { + CjkInput.flushNow?.(); + } this._focusedTile = tile || null; }, @@ -5104,27 +5145,28 @@ Object.assign(CodemanApp.prototype, { /** Insert editable text at the active prompt without pressing Enter. */ insertTerminalText(text) { - if (!this.activeSessionId || !text) return; + const pane = this._focusedPane(); + if (!text || !pane?.sessionId || !pane.terminal || pane.tile?._destroyed) return; + this._prepareExternalInput(pane, 'insert'); // A tile or the split's Pane B holds the keyboard: the text belongs to that // pane's session. Those panes have no local-echo overlay, and the main // overlay is parked behind the grid, so send it straight to the pane. - const pane = this._focusedPane?.(); if (pane && !pane.isPrimary) { this._sendInputAsync(pane.sessionId, text); pane.terminal?.focus(); return; } - // Under predict the text goes out via sendInput (bypasses onData), so the + // Under predict the text goes out via _sendInputAsync (bypasses onData), so the // hook never sees it: clear outstanding predictions here instead. if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions(); if ( this._localEchoEnabled && this._localEchoOverlay && - !this._echoPassthroughSessions?.has(this.activeSessionId) + !this._echoPassthroughSessions?.has(pane.sessionId) ) { this._localEchoOverlay.appendText(text); } else { - this.sendInput(text).catch(() => {}); + this._sendInputAsync(pane.sessionId, text, { useMux: true }); } this.terminal?.focus(); }, @@ -5134,26 +5176,23 @@ Object.assign(CodemanApp.prototype, { * from Ctrl+L (clear display) and the agent's destructive `/clear` command. */ clearTerminalInput() { - if (!this.activeSessionId) return; - + const pane = this._focusedPane(); + if (!pane?.sessionId || !pane.terminal || pane.tile?._destroyed) return; + this._prepareExternalInput(pane, 'clear'); // discard: the line is thrown away, so a Send on Enter draft must not be - // stashed and come back on the next visit to this session. + // stashed to come back on the next visit to this session. if (typeof CjkInput !== 'undefined') CjkInput.clear({ discard: true }); // A tile or Pane B holds the keyboard: its TUI owns the editable buffer // (no local-echo overlay there), so kill the line in that pane's session, // never in the parked main pane's. - const pane = this._focusedPane?.(); if (pane && !pane.isPrimary) { this._sendInputAsync(pane.sessionId, '\x15'); this.showToast?.('Input cleared', 'success'); pane.terminal?.focus(); return; } - if (this._inputFlushTimeout) { - clearTimeout(this._inputFlushTimeout); - this._inputFlushTimeout = null; - } - this._pendingInput = ''; + // Accepted printable batches were sealed by the external-input boundary; + // only unsent overlay text is discarded below. // Composer content is about to change out from under any predictions if (this._localEchoPolicy === 'predict') this._predictiveEcho?.clearPredictions(); @@ -5161,16 +5200,16 @@ Object.assign(CodemanApp.prototype, { const flushed = this._localEchoOverlay.getFlushed?.() || { count: 0, text: '' }; this._localEchoOverlay.clear(); this._localEchoOverlay.suppressBufferDetection(); - this._flushedOffsets?.delete(this.activeSessionId); - this._flushedTexts?.delete(this.activeSessionId); + this._flushedOffsets?.delete(pane.sessionId); + this._flushedTexts?.delete(pane.sessionId); const flushedLength = Array.from(flushed.text || '').length; if (flushedLength > 0) { - this.sendInput('\x7f'.repeat(flushedLength)).catch(() => {}); + this._sendInputAsync(pane.sessionId, '\x7f'.repeat(flushedLength), { useMux: true }); } } else { // In non-local-echo mode the TUI already owns the editable buffer. Ctrl+U // is the conventional kill-line key supported by shells and agent TUIs. - this.sendInput('\x15').catch(() => {}); + this._sendInputAsync(pane.sessionId, '\x15', { useMux: true }); } this.showToast?.('Input cleared', 'success'); @@ -7180,19 +7219,6 @@ Object.assign(CodemanApp.prototype, { this.showToast('Another device is setting the width — scroll sideways', 'info'); }, - /** - * Send input to the active session. - * @param {string} input - Text to send (include \r for Enter) - * @returns {Promise} - */ - async sendInput(input) { - if (!this.activeSessionId || !input) return; - // Route through the durable, exactly-once delivery layer (useMux for the - // POST fallback) so voice / keyboard-accessory / paste input also survives a - // dropped link instead of being lost in a single best-effort fetch. - this._sendInputAsync(this.activeSessionId, input, { useMux: true }); - }, - // ═══════════════════════════════════════════════════════════════ // Directory Input // ═══════════════════════════════════════════════════════════════ diff --git a/src/web/public/voice-input.js b/src/web/public/voice-input.js index 97e5dbe8..40363ca3 100644 --- a/src/web/public/voice-input.js +++ b/src/web/public/voice-input.js @@ -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 = `
@@ -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 = () => { diff --git a/test/cjk-hold-per-device-setting.test.ts b/test/cjk-hold-per-device-setting.test.ts index 1891e1a8..200c3eda 100644 --- a/test/cjk-hold-per-device-setting.test.ts +++ b/test/cjk-hold-per-device-setting.test.ts @@ -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', () => { diff --git a/test/codex-predictive-echo.test.ts b/test/codex-predictive-echo.test.ts index ec8010af..fac3c38b 100644 --- a/test/codex-predictive-echo.test.ts +++ b/test/codex-predictive-echo.test.ts @@ -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(); diff --git a/test/fixtures/ios-native-replay.js b/test/fixtures/ios-native-replay.js new file mode 100644 index 00000000..5bf1370e --- /dev/null +++ b/test/fixtures/ios-native-replay.js @@ -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(//g, '\n') + .replace(//g, '\r') + .replace(//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); diff --git a/test/image-paste-trap.test.ts b/test/image-paste-trap.test.ts index 0b1961c1..fde21766 100644 --- a/test/image-paste-trap.test.ts +++ b/test/image-paste-trap.test.ts @@ -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) { - 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 () => { diff --git a/test/input-cjk-hold.test.ts b/test/input-cjk-hold.test.ts index 9837cc91..047cf1ff 100644 --- a/test/input-cjk-hold.test.ts +++ b/test/input-cjk-hold.test.ts @@ -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'); diff --git a/test/input-cjk.test.ts b/test/input-cjk.test.ts index 6da9dd71..d15b1fe8 100644 --- a/test/input-cjk.test.ts +++ b/test/input-cjk.test.ts @@ -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 = []; const windowObj: Record = {}; 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(); diff --git a/test/ios-native-input.browser.test.ts b/test/ios-native-input.browser.test.ts new file mode 100644 index 00000000..207ad607 --- /dev/null +++ b/test/ios-native-input.browser.test.ts @@ -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; + _localEchoEnabled: boolean; + _isLoadingBuffer: boolean; + _echoPassthroughSessions?: Set; + _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; + 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((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('.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(); + 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(); + 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(); + 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(); + 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(''); +} diff --git a/test/local-echo-codex-gating.test.ts b/test/local-echo-codex-gating.test.ts index 16eab040..ccb91786 100644 --- a/test/local-echo-codex-gating.test.ts +++ b/test/local-echo-codex-gating.test.ts @@ -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; }; @@ -38,14 +40,15 @@ type AppInstance = { terminal?: { focus: () => void }; _localEchoEnabled?: boolean; _localEchoOverlay?: OverlayStub; - _pendingInput: string; + _pendingInput: Map; + _inputFlushTimeout: Map; + _lastKeystrokeTime: Map; _flushedOffsets?: Map; _flushedTexts?: Map; _echoPassthroughSessions?: Set; loadAppSettingsFromStorage: () => Record; - sendInput: ReturnType; + _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(); }); diff --git a/test/mobile-ime-preview-structure.test.ts b/test/mobile-ime-preview-structure.test.ts index 73f87211..9fb4f934 100644 --- a/test/mobile-ime-preview-structure.test.ts +++ b/test/mobile-ime-preview-structure.test.ts @@ -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(); + const queues = new Map>(); + const draining = new Set(); 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); + }); +}); diff --git a/test/mobile-ime-preview.test.ts b/test/mobile-ime-preview.test.ts index cfdec9a3..243c9b6c 100644 --- a/test/mobile-ime-preview.test.ts +++ b/test/mobile-ime-preview.test.ts @@ -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'); diff --git a/test/mobile-prompt-composer.test.ts b/test/mobile-prompt-composer.test.ts index fe5bd548..85e9a1b0 100644 --- a/test/mobile-prompt-composer.test.ts +++ b/test/mobile-prompt-composer.test.ts @@ -50,6 +50,10 @@ function loadComposer(sessionId = 'session-1') { _echoPassthroughSessions: new Set(), _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((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(); }); }); diff --git a/test/mobile-shell-keyboard.test.ts b/test/mobile-shell-keyboard.test.ts index 833f2ac0..ef1bc893 100644 --- a/test/mobile-shell-keyboard.test.ts +++ b/test/mobile-shell-keyboard.test.ts @@ -160,6 +160,7 @@ function loadBar(sessionMode = 'claude') { activeSessionId: 'session-1', sessions: new Map([['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; + _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; + pendingHooks?: Map>; + _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> }).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> }).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; 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)]).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)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']); }); }); diff --git a/test/mobile/keyboard.test.ts b/test/mobile/keyboard.test.ts index 23576bc2..de29e973 100644 --- a/test/mobile/keyboard.test.ts +++ b/test/mobile/keyboard.test.ts @@ -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 { 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; } diff --git a/test/path-picker-ui.test.ts b/test/path-picker-ui.test.ts index 6fa30b3a..69147f3d 100644 --- a/test/path-picker-ui.test.ts +++ b/test/path-picker-ui.test.ts @@ -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 })._flushedOffsets.has('session-1')).toBe(false); expect((app as { _flushedTexts: Map })._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).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 }); }); }); diff --git a/test/shift-enter-keypress-swallowed.test.ts b/test/shift-enter-keypress-swallowed.test.ts index 5ffe3d14..b481413e 100644 --- a/test/shift-enter-keypress-swallowed.test.ts +++ b/test/shift-enter-keypress-swallowed.test.ts @@ -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'); }); }); diff --git a/test/shift-enter-keypress.browser.test.ts b/test/shift-enter-keypress.browser.test.ts index bf87a603..17a501a6 100644 --- a/test/shift-enter-keypress.browser.test.ts +++ b/test/shift-enter-keypress.browser.test.ts @@ -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; + sessions: Map; + 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 { 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 { diff --git a/test/terminal-input-fifo.test.ts b/test/terminal-input-fifo.test.ts new file mode 100644 index 00000000..a2294068 --- /dev/null +++ b/test/terminal-input-fifo.test.ts @@ -0,0 +1,1074 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +interface CleanupApp { + _disconnectWs?: () => void; + _predictiveEcho?: { clearPredictions: () => void }; + _clearTimer?: (name: string) => void; +} + +function harness() { + const fetchMock = vi.fn().mockResolvedValue({}); + const context = vm.createContext({ + console, + _crashDiag: { log: vi.fn() }, + performance: { now: () => Date.now() }, + setTimeout, + clearTimeout, + setInterval: vi.fn(), + clearInterval: vi.fn(), + requestAnimationFrame: vi.fn(), + HTMLCanvasElement: class {}, + WebSocket: { OPEN: 1 }, + fetch: fetchMock, + document: { addEventListener: vi.fn(), getElementById: () => null, activeElement: null }, + localStorage: { getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn(), length: 0, key: vi.fn() }, + window: { addEventListener: vi.fn(), removeEventListener: vi.fn() }, + MobileDetection: { isTouchDevice: () => true }, + }); + const dir = resolve(import.meta.dirname, '../src/web/public'); + vm.runInContext( + `${readFileSync(resolve(dir, 'constants.js'), 'utf8')}\n${readFileSync(resolve(dir, 'app.js'), 'utf8')}\nglobalThis.App = CodemanApp;`, + context + ); + vm.runInContext(readFileSync(resolve(dir, 'terminal-ui.js'), 'utf8'), context); + const app = Object.create(context.App.prototype); + app.activeSessionId = 'old'; + app.sessions = new Map([ + ['old', { mode: 'claude' }], + ['new', { mode: 'claude' }], + ]); + app._localEchoEnabled = true; + app._flushedOffsets = new Map(); + app._flushedTexts = new Map(); + app._predictHookOnData = vi.fn(); + app._localEchoOverlay = { + pendingText: '', + flushed: '', + get committedText() { + return this.flushed + this.pendingText; + }, + addChar(text: string) { + this.pendingText += text; + }, + appendText(text: string) { + this.pendingText += text; + }, + clear() { + this.pendingText = ''; + this.flushed = ''; + }, + suppressBufferDetection: vi.fn(), + getFlushed() { + return { count: this.flushed.length, text: this.flushed }; + }, + setPrompt: vi.fn(), + removeChar() { + const key = this.pendingText ? 'pendingText' : this.flushed ? 'flushed' : null; + if (!key) return false; + this[key] = Array.from(this[key]).slice(0, -1).join(''); + return key === 'pendingText' ? 'pending' : 'flushed'; + }, + getInputAnchor: vi.fn(() => ({ col: 8, row: 2 })), + }; + const wire: Array<[string, string]> = []; + app._enqueueReliableInput = vi.fn((id: string, text: string) => wire.push([id, text])); + app.terminal = { focus: vi.fn() }; + return { app, wire, context, fetchMock }; +} + +function loadProducerModules(app: object, context: vm.Context) { + context.__app = app; + vm.runInContext('app = globalThis.__app;', context); + const dir = resolve(import.meta.dirname, '../src/web/public'); + for (const file of ['keyboard-accessory.js', 'voice-input.js', 'image-input.js']) { + vm.runInContext(readFileSync(resolve(dir, file), 'utf8'), context); + } +} + +function attachCjk( + app: { + _focusedPane: () => { sessionId: string } | null; + _handleCjkInput: (text: string, sessionId: string) => void; + _sendCjkPrompt: (text: string, sessionId: string) => boolean; + }, + context: vm.Context +) { + const listeners = new Map void>(); + const field = { + value: '', + selectionStart: 1, + selectionEnd: 1, + style: {}, + setAttribute: vi.fn(), + setSelectionRange: vi.fn(), + addEventListener: (name: string, fn: (event: object) => void) => listeners.set(name, fn), + removeEventListener: vi.fn(), + }; + context.navigator = { userAgent: 'iPhone' }; + context.document.getElementById = () => field; + vm.runInContext(readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8'), context); + const cjk = vm.runInContext('CjkInput', context); + cjk.init({ + captureTarget: () => app._focusedPane()?.sessionId, + send: (text: string, sessionId: string) => app._handleCjkInput(text, sessionId), + sendPrompt: (text: string, sessionId: string) => app._sendCjkPrompt(text, sessionId), + }); + return { cjk, field, fire: (name: string, event = {}) => listeners.get(name)!(event) }; +} + +function attachCleanupStubs(app: CleanupApp) { + app._disconnectWs = vi.fn(); + app._predictiveEcho = { clearPredictions: vi.fn() }; + app._clearTimer = vi.fn(); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(0); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe('session-owned main input FIFO', () => { + it('keeps Enter on the old session through a switch and before later old-session writes', () => { + const { app, wire } = harness(); + attachCleanupStubs(app); + app._handleTerminalData('before', 'old'); + app._handleTerminalData('\r', 'old'); + vi.advanceTimersByTime(30); + app._cleanupPreviousSession('new'); + app.activeSessionId = 'new'; + app._sendInputAsync('old', 'after'); + app._sendInputAsync('new', 'independent'); + expect(wire).toEqual([ + ['old', 'before'], + ['new', 'independent'], + ]); + vi.advanceTimersByTime(50); + expect(wire).toEqual([ + ['old', 'before'], + ['new', 'independent'], + ['old', '\r'], + ['old', 'after'], + ]); + }); + + it('queues typing after Enter behind the reserved CR', () => { + const { app, wire } = harness(); + app._handleTerminalData('first', 'old'); + app._handleTerminalData('\r', 'old'); + app._localEchoEnabled = false; + app._handleTerminalData('x', 'old'); + vi.advanceTimersByTime(0); + expect(wire).toEqual([['old', 'first']]); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'first'], + ['old', '\r'], + ['old', 'x'], + ]); + }); + + it('queues a later local echo flush behind the reservation', () => { + const { app, wire } = harness(); + app._handleTerminalData('first', 'old'); + app._handleTerminalData('\r', 'old'); + app._handleTerminalData('later', 'old'); + app._flushLocalEchoTo('old'); + expect(wire).toEqual([['old', 'first']]); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'first'], + ['old', '\r'], + ['old', 'later'], + ]); + }); + + it('seals a printable batch before switching and never reads the new destination in its timer', () => { + const { app, wire } = harness(); + attachCleanupStubs(app); + app._localEchoEnabled = false; + app._handleTerminalData('a', 'old'); + app._handleTerminalData('b', 'old'); + expect(wire).toEqual([]); + app._cleanupPreviousSession('new'); + app.activeSessionId = 'new'; + vi.runAllTimers(); + expect(wire).toEqual([['old', 'ab']]); + }); + + it('seals a printable batch before control input as distinct ordered writes', () => { + const { app, wire } = harness(); + app._localEchoEnabled = false; + app._handleTerminalData('a', 'old'); + app._handleTerminalData('\r', 'old'); + expect(wire).toEqual([ + ['old', 'a'], + ['old', '\r'], + ]); + }); + + it('reserves a delayed bracketed paste ahead of later input', () => { + const { app, wire } = harness(); + const paste = '\x1b[200~pasted\x1b[201~'; + app._flushedOffsets.set('old', 3); + app._flushedTexts.set('old', 'pre'); + app._handleTerminalData('prefix', 'old'); + app._handleTerminalData(paste, 'old'); + expect(app._localEchoOverlay.pendingText).toBe(''); + expect(app._localEchoOverlay.suppressBufferDetection).toHaveBeenCalledOnce(); + expect(app._flushedOffsets.has('old')).toBe(false); + expect(app._flushedTexts.has('old')).toBe(false); + app._sendInputAsync('old', 'suffix'); + expect(wire).toEqual([['old', 'prefix']]); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'prefix'], + ['old', paste], + ['old', 'suffix'], + ]); + }); + + it.each(['S-Enter', 'C-Enter'])('orders text, gap, %s, then later writes', (key) => { + const { app, wire, fetchMock } = harness(); + app._handleTerminalData('line', 'old'); + app._submitModifiedEnter('old', key); + app.activeSessionId = 'new'; + app._sendInputAsync('old', 'next'); + expect(wire).toEqual([['old', 'line']]); + expect(fetchMock).not.toHaveBeenCalled(); + vi.advanceTimersByTime(80); + expect(fetchMock).toHaveBeenCalledWith( + '/api/sessions/old/send-key', + expect.objectContaining({ body: JSON.stringify({ key }) }) + ); + expect(wire).toEqual([ + ['old', 'line'], + ['old', 'next'], + ]); + expect(fetchMock.mock.invocationCallOrder[0]).toBeLessThan(app._enqueueReliableInput.mock.invocationCallOrder[1]); + }); + + it('runs two session FIFOs independently', () => { + const { app, wire } = harness(); + app._enqueueInput('old', [{ write: 'a' }, { gap: 120 }, { write: 'b' }]); + app._enqueueInput('new', [{ write: 'c' }, { gap: 80 }, { write: 'd' }]); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'a'], + ['new', 'c'], + ['new', 'd'], + ]); + vi.advanceTimersByTime(40); + expect(wire.at(-1)).toEqual(['old', 'b']); + }); + + it('drops deleted-session reservations and batches without redirecting', () => { + const { app, wire } = harness(); + app._enqueueInput('old', [{ write: 'a' }, { gap: 80 }, { write: '\r' }]); + for (const name of [ + 'terminalBuffers', + 'terminalBufferCache', + 'ralphStates', + 'ralphClosedSessions', + 'projectInsights', + 'pendingHooks', + 'tabAlerts', + 'attachmentHistoryCounts', + 'terminalLoadStates', + 'idleTimers', + ]) + app[name] = new Map(); + for (const name of [ + '_markTerminalBufferReconciled', + '_clearHistoryTruncation', + '_persistReliableState', + 'clearCountdownTimers', + 'closeSessionLogViewerWindows', + 'closeSessionImagePopups', + 'closeSessionAttachmentCards', + 'closeSessionSubagentWindows', + ]) + app[name] = vi.fn(); + for (const name of ['respawnStatus', 'respawnTimers', 'respawnCountdownTimers', 'respawnActionLogs']) + app[name] = {}; + app.sessionOrder = ['old', 'new']; + app._localEchoEnabled = false; + app._handleTerminalData('pending', 'old'); + app._cleanupSessionData('old'); + app.activeSessionId = 'new'; + app._sendInputAsync('old', 'never'); + vi.runAllTimers(); + expect(wire).toEqual([['old', 'a']]); + expect(app._inputFifos.has('old')).toBe(false); + expect(app._pendingInput.has('old')).toBe(false); + }); +}); + +describe('native main transactions and boundaries', () => { + it('handles each DEL separately with local echo: unsent deletes stay local, flushed deletes reach wire', () => { + const { app, wire } = harness(); + app._localEchoOverlay.pendingText = 'ab'; + app._localEchoOverlay.flushed = 'XY'; + app._flushedOffsets.set('old', 2); + app._flushedTexts.set('old', 'XY'); + app._sendNativeInputTransaction(['\x7f', '\x7f', '\x7f', 'Z']); + expect(wire).toEqual([['old', '\x7f']]); + expect(app._localEchoOverlay.pendingText).toBe('Z'); + expect(app._flushedOffsets.get('old')).toBe(1); + expect(app._flushedTexts.get('old')).toBe('X'); + }); + + it('bypasses printable batching and preserves op boundaries with local echo off', () => { + const { app, wire } = harness(); + app._localEchoEnabled = false; + app._handleTerminalData('a', 'old'); + app._sendNativeInputTransaction(['\x7f', '\x7f', 'replacement']); + expect(wire).toEqual([ + ['old', 'a'], + ['old', '\x7f'], + ['old', '\x7f'], + ['old', 'replacement'], + ]); + }); + + it('captures the session once even if preprocessing changes the active pane', () => { + const { app, wire } = harness(); + app._localEchoEnabled = false; + app._predictHookOnData = () => { + app.activeSessionId = 'new'; + }; + app._sendNativeInputTransaction(['\x7f', 'replacement']); + expect(wire).toEqual([ + ['old', '\x7f'], + ['old', 'replacement'], + ]); + }); + + it.each([true, false])('consumes one-shot Ctrl once per transaction (echo %s)', (echo) => { + const { app, wire, context } = harness(); + app._localEchoEnabled = echo; + app._iosNativeInput = { reset: vi.fn() }; + const ctrl = { isCtrlArmed: () => true, consumeCtrl: vi.fn(() => '\x03') }; + context.KeyboardAccessoryBar = ctrl; + if (echo) app._localEchoOverlay.pendingText = 'ab'; + app._sendNativeInputTransaction(['\x7f', '\x7f', 'c']); + expect(ctrl.consumeCtrl).toHaveBeenCalledExactlyOnceWith('c'); + expect(app._iosNativeInput.reset).toHaveBeenCalledExactlyOnceWith('ctrl'); + expect(wire).toEqual( + echo + ? [['old', '\x03']] + : [ + ['old', '\x7f'], + ['old', '\x7f'], + ['old', '\x03'], + ] + ); + }); + + it('spends Ctrl on a deletion-only transaction without resetting the owner', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = false; + app._iosNativeInput = { reset: vi.fn() }; + const bar = vm.runInContext('KeyboardAccessoryBar', context); + bar.toggleCtrl(); + + app._sendNativeInputTransaction(['\x7f']); + + expect(wire).toEqual([['old', '\x7f']]); + expect(bar.isCtrlArmed()).toBe(false); + expect(app._iosNativeInput.reset).not.toHaveBeenCalled(); + app._sendNativeInputTransaction(['c']); + expect(wire).toEqual([ + ['old', '\x7f'], + ['old', 'c'], + ]); + expect(app._iosNativeInput.reset).not.toHaveBeenCalled(); + }); + + it('settles, seals, flushes, resets owner and preview before session cleanup', () => { + const { app, wire } = harness(); + attachCleanupStubs(app); + const order: string[] = []; + app._iosNativeInput = { + settle: () => { + order.push('settle'); + app._handleTerminalData('native', 'old'); + }, + reset: (reason: string) => order.push(`reset:${reason}`), + }; + app._mobileImePreview = { reset: () => order.push('preview') }; + app._disconnectWs = () => order.push('cleanup'); + app._cleanupPreviousSession('new'); + expect(wire).toEqual([['old', 'native']]); + expect(order).toEqual(['settle', 'reset:session', 'preview', 'cleanup']); + }); + + it('settles and flushes before disabling the echo policy', () => { + const { app, wire } = harness(); + app.loadAppSettingsFromStorage = () => ({ localEchoEnabled: false }); + app._localEchoOverlay.pendingText = 'retained'; + app._iosNativeInput = { settle: vi.fn(), reset: vi.fn() }; + app._updateLocalEchoState(); + expect(wire).toEqual([['old', 'retained']]); + expect(app._localEchoOverlay.pendingText).toBe(''); + expect(app._iosNativeInput.reset).toHaveBeenCalledWith('echo-policy'); + }); + + it('retires flushed snapshots when local echo hands the line to PTY echo', () => { + const { app, wire } = harness(); + app.loadAppSettingsFromStorage = () => ({ localEchoEnabled: false }); + app._handleTerminalData('abc', 'old'); + app._updateLocalEchoState(); + expect(wire).toEqual([['old', 'abc']]); + expect(app._flushedOffsets.has('old')).toBe(false); + expect(app._flushedTexts.has('old')).toBe(false); + app._updateLocalEchoState(); + expect(wire).toEqual([['old', 'abc']]); + }); + + it('resolves primary, split and grid owners independently of focus', () => { + const { app } = harness(); + const split = { sessionId: 'new', terminal: {}, _destroyed: false }; + app._splitPane = split; + app._focusedTile = split; + expect(app._paneForSession('old')).toEqual({ + terminal: app.terminal, + sessionId: 'old', + isPrimary: true, + tile: null, + }); + expect(app._paneForSession('new')?.tile).toBe(split); + app._tilesOwnTerminal = () => true; + const grid = { sessionId: 'old', terminal: {}, _destroyed: false }; + app._tileFor = (id: string) => (id === 'old' ? grid : null); + expect(app._paneForSession('old')?.tile).toBe(grid); + split._destroyed = true; + expect(app._paneForSession('new')).toBeNull(); + grid._destroyed = true; + expect(app._paneForSession('old')).toBeNull(); + expect(app._paneForSession('absent')).toBeNull(); + }); + + it.each(['insertText', 'insertReplacementText', 'compositionend'])( + 'flushes real CJK %s timers to the outgoing pane before focus changes', + (event) => { + const { app, wire, context } = harness(); + const listeners = new Map void>(); + const field = { + value: '', + selectionStart: 1, + selectionEnd: 1, + setSelectionRange: vi.fn(), + addEventListener: (name: string, fn: (event: object) => void) => listeners.set(name, fn), + removeEventListener: vi.fn(), + }; + context.navigator = { userAgent: 'iPhone' }; + context.document.getElementById = () => field; + vm.runInContext(readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8'), context); + const cjk = vm.runInContext('CjkInput', context); + cjk.init({ + captureTarget: () => app._focusedPane()?.sessionId, + send: (text: string, sessionId: string) => app._handleCjkInput(text, sessionId), + }); + field.value = '你好'; + if (event === 'compositionend') { + listeners.get('compositionstart')!({}); + listeners.get('compositionend')!({}); + } else listeners.get('input')!({ inputType: event, isComposing: false }); + expect(wire).toEqual([]); + const tile = { sessionId: 'new', terminal: {} }; + app._noteFocusedTile(tile); + expect(wire).toEqual([['old', '你好']]); + field.value = '再见'; + listeners.get('input')!({ inputType: 'insertText', isComposing: false }); + app._noteFocusedTile(null); + expect(wire).toEqual([ + ['old', '你好'], + ['new', '再见'], + ]); + vi.runAllTimers(); + expect(wire).toHaveLength(2); + cjk.destroy(); + } + ); + + it('flushes CJK text to Pane B before its real teardown destroys the owner', () => { + const { app, wire, context } = harness(); + const { cjk, field, fire } = attachCjk(app, context); + context.window.app = app; + vm.runInContext(readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-tile.js'), 'utf8'), context); + const tile = { + sessionId: 'new', + terminal: { dispose: vi.fn() }, + _destroyIosNativeInput: vi.fn(() => expect(wire).toEqual([['new', '你好']])), + _resetLiveFlow: vi.fn(), + _detachSocket: vi.fn(), + _destroyKeyCode229Recovery: vi.fn(), + }; + app._splitPane = tile; + app._noteFocusedTile(tile); + field.value = '你好'; + fire('input', { inputType: 'insertText', isComposing: false }); + context.window.TerminalTile.prototype.destroy.call(tile); + vi.runAllTimers(); + expect(wire).toEqual([['new', '你好']]); + expect(app._focusedPane().sessionId).toBe('old'); + cjk.destroy(); + }); + + it('Send on Enter keeps a held answer, its gap and Enter on the session it was typed for', () => { + const { app, wire, context } = harness(); + context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false }; + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + // Focus moves to Pane B before Enter; the held answer still belongs to A. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + expect(wire).toEqual([['old', 'y']]); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', 'y'], + ['old', '\r'], + ]); + cjk.destroy(); + }); + + it('Send on Enter sends a restored draft to its own session after focus moves, without an edit', () => { + const { app, wire, context } = harness(); + context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false }; + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + // A draft typed for `old` is stashed on a switch and restored on the way back. + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + cjk.stashDraft('old'); + cjk.clear(); + cjk.restoreDraft('old'); + expect(field.value).toBe('\u200By'); + // Focus moves to Pane B; Enter is pressed without touching the draft. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', 'y'], + ['old', '\r'], + ]); + cjk.destroy(); + }); + + it('Send on Enter sends a held-mode Ctrl key to the session it was typed for across a focus move', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + const bar = vm.runInContext('KeyboardAccessoryBar', context); + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + field.value = '\u200Bab'; + fire('input', { inputType: 'insertText', isComposing: false }); + bar.toggleCtrl(); + fire('compositionstart'); + // Focus moves to Pane B before the composition commits `c`. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + field.value = '\u200Babc'; + fire('compositionend'); + vi.advanceTimersByTime(0); + expect(wire).toEqual([['old', '\x03']]); + expect(field.value).toBe('\u200Bab'); + cjk.destroy(); + }); + + it('Send on Enter lets the next answer capture its own session after Ctrl empties the field', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + const bar = vm.runInContext('KeyboardAccessoryBar', context); + const { cjk, field, fire } = attachCjk(app, context); + cjk.setHoldUntilEnter(true); + bar.toggleCtrl(); + fire('keydown', { key: 'c' }); + field.value = '\u200Bc'; + fire('input', { inputType: 'insertText', isComposing: false }); + expect(wire).toEqual([['old', '\x03']]); + // Focus moves to Pane B; a fresh answer typed there belongs to B. + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('keydown', { key: 'y' }); + field.value = '\u200By'; + fire('input', { inputType: 'insertText', isComposing: false }); + fire('keydown', { key: 'Enter', preventDefault: vi.fn() }); + vi.advanceTimersByTime(120); + expect(wire).toEqual([ + ['old', '\x03'], + ['new', 'y'], + ['new', '\r'], + ]); + cjk.destroy(); + }); + + it('keeps an unfinished CJK composition on B after focus moves to A', () => { + const { app, wire, context } = harness(); + const { cjk, field, fire } = attachCjk(app, context); + const tile = { sessionId: 'new', terminal: {} }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('compositionstart'); + field.value = '你好'; + fire('input', { inputType: 'insertCompositionText', isComposing: true }); + app._noteFocusedTile(null); + expect(wire).toEqual([]); + fire('compositionend'); + vi.runAllTimers(); + expect(wire).toEqual([['new', '你好']]); + cjk.destroy(); + }); + + it('flushes a normal CJK buffer to the current pane', () => { + const { app, wire, context } = harness(); + const { cjk, field, fire } = attachCjk(app, context); + field.value = '你好'; + fire('input', { inputType: 'insertText', isComposing: false }); + vi.runAllTimers(); + expect(wire).toEqual([['old', '你好']]); + cjk.destroy(); + }); + + it.each([false, true])( + 'delivers a captured CJK commit without a pane only while its session exists (removed=%s)', + (removed) => { + const { app, wire, context } = harness(); + const { cjk, field, fire } = attachCjk(app, context); + const tile = { sessionId: 'new', terminal: {}, _destroyed: false }; + app._splitPane = tile; + app._noteFocusedTile(tile); + fire('compositionstart'); + field.value = '你好'; + app._noteFocusedTile(null); + tile._destroyed = true; + if (removed) app.sessions.delete('new'); + const prepare = vi.spyOn(app, '_prepareExternalInput'); + fire('compositionend'); + vi.runAllTimers(); + expect(wire).toEqual(removed ? [] : [['new', '你好']]); + expect(prepare).not.toHaveBeenCalled(); + cjk.destroy(); + } + ); + + it.each(['split', 'grid'])('resets the captured unfocused %s path-picker owner before direct delivery', (layout) => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + const owner = { settle: vi.fn(), reset: vi.fn() }; + const tile = { sessionId: 'new', terminal: {}, _iosNativeInput: owner }; + if (layout === 'split') app._splitPane = tile; + else { + app._tilesOwnTerminal = () => true; + app._tileFor = (id: string) => (id === 'new' ? tile : null); + } + app._noteFocusedTile(tile); + const open = vi.fn(); + context.__openPicker = open; + vm.runInContext('PathPicker.open = globalThis.__openPicker; KeyboardAccessoryBar.pickPath();', context); + app._noteFocusedTile(null); + const prepare = vi.spyOn(app, '_prepareExternalInput'); + open.mock.calls[0][0].onSelect('/project/file.ts'); + expect(owner.settle).toHaveBeenCalledOnce(); + expect(owner.reset).toHaveBeenCalledWith('accessory-path'); + expect(prepare).toHaveBeenCalledWith(expect.objectContaining({ tile }), 'accessory-path', { flushEcho: true }); + expect(wire).toEqual([['new', '/project/file.ts']]); + }); + + it.each([false, true])('keeps the primary path-picker prefix in its overlay when focus moves (%s)', (moved) => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoOverlay.pendingText = 'prefix '; + app._iosNativeInput = { settle: vi.fn(), reset: vi.fn() }; + const open = vi.fn(); + context.__openPicker = open; + vm.runInContext('PathPicker.open = globalThis.__openPicker; KeyboardAccessoryBar.pickPath();', context); + if (moved) app._noteFocusedTile({ sessionId: 'new', terminal: {} }); + const prepare = vi.spyOn(app, '_prepareExternalInput'); + open.mock.calls[0][0].onSelect('/project/file.ts'); + expect(app._iosNativeInput.reset).toHaveBeenCalledWith('accessory-path'); + expect(prepare).toHaveBeenCalledWith( + expect.objectContaining({ isPrimary: true, sessionId: 'old' }), + 'accessory-path' + ); + expect(app._localEchoOverlay.pendingText).toBe('prefix /project/file.ts'); + expect(wire).toEqual([]); + }); + + it.each(['voice', 'accessory', 'upload', 'toolbar-attachment'])( + '%s prepares an unfocused live destination owner, but still sends without a pane', + async (producer) => { + for (const live of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = false; + const owner = { settle: vi.fn(), reset: vi.fn() }; + app._iosNativeInput = { settle: vi.fn(), reset: vi.fn() }; + const tile = { sessionId: 'new', terminal: {}, _iosNativeInput: owner }; + if (live) app._splitPane = tile; + app.showToast = vi.fn(); + app._normalizeImageForUpload = vi.fn(async (file: object) => file); + app._uploadPasteImage = vi.fn(async () => '/image.png'); + if (producer === 'voice') { + await vm.runInContext("VoiceInput._sendToTarget('new', 'inserted')", context); + } else if (producer === 'accessory') { + const target = vm.runInContext( + "KeyboardAccessoryBar._prepareInput('new', 'accessory-compose-send')", + context + ); + app._enqueueInput(target, [{ write: 'inserted' }]); + } else if (producer === 'upload') { + await app._uploadAndInsertImages([{}], { sessionId: 'new' }); + } else { + app._admitPromptAttachments = (files: object[]) => files; + await app._attachFromToolbar([{}], 'new'); + } + expect(wire.length).toBeGreaterThan(0); + expect(wire.every(([id]) => id === 'new')).toBe(true); + expect(owner.reset).toHaveBeenCalledTimes(live ? 1 : 0); + expect(owner.settle).toHaveBeenCalledTimes(live ? 1 : 0); + expect(app._iosNativeInput.reset).not.toHaveBeenCalled(); + } + } + ); + + it.each(['upload', 'Esc', 'paste'])( + '%s preserves the typed prefix before direct writes with echo on or off', + async (producer) => { + for (const echo of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = echo; + app._handleTerminalData('hel', 'old'); + app.showToast = vi.fn(); + app._normalizeImageForUpload = vi.fn(async (file: object) => file); + app._uploadPasteImage = vi.fn(async () => '/p'); + if (producer === 'upload') { + await app._uploadAndInsertImages([{}], { sessionId: 'old' }); + expect(wire).toEqual([ + ['old', 'hel'], + ['old', '/p'], + ]); + app.submitFromToolbar(); + expect(wire).toEqual( + echo + ? [ + ['old', 'hel'], + ['old', '/p'], + ] + : [ + ['old', 'hel'], + ['old', '/p'], + ['old', '\r'], + ] + ); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'hel'], + ['old', '/p'], + ['old', '\r'], + ]); + } else if (producer === 'Esc') { + vm.runInContext("KeyboardAccessoryBar.sendKey('\\x1b')", context); + expect(wire).toEqual([ + ['old', 'hel'], + ['old', '\x1b'], + ]); + } else { + vm.runInContext("KeyboardAccessoryBar._sendBracketedPaste('old', 'world', 'Paste')", context); + expect(wire).toEqual([ + ['old', 'hel'], + ['old', '\x1b[200~world\x1b[201~'], + ]); + } + expect(app._localEchoOverlay.pendingText).toBe(''); + } + } + ); + + it('sends a slash command without submitting the unsent local-echo draft', () => { + for (const echo of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = echo; + app._handleTerminalData('hel', 'old'); + vm.runInContext("KeyboardAccessoryBar.sendCommand('/help')", context); + vi.advanceTimersByTime(120); + // Echo on: `hel` stays in the overlay. Echo off: it was already typed into the PTY. + expect(wire).toEqual([...(echo ? [] : [['old', 'hel']]), ['old', '/help'], ['old', '\r']]); + expect(app._localEchoOverlay.pendingText).toBe(echo ? 'hel' : ''); + } + }); + + it('sends voice dictation without submitting the unsent local-echo draft', async () => { + for (const echo of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = echo; + app._handleTerminalData('hel', 'old'); + await vm.runInContext("VoiceInput._sendToTarget('old', 'world\\r')", context); + // Echo on: `hel` stays in the overlay. Echo off: it was already typed into the PTY. + expect(wire).toEqual([...(echo ? [] : [['old', 'hel']]), ['old', 'world\r']]); + expect(app._localEchoOverlay.pendingText).toBe(echo ? 'hel' : ''); + } + }); + + it('keeps the typed prefix in the overlay when a toolbar attachment appends', async () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._handleTerminalData('hel', 'old'); + app._admitPromptAttachments = (files: object[]) => files; + app._normalizeImageForUpload = vi.fn(async (file: object) => file); + app._uploadPasteImage = vi.fn(async () => '/p'); + app.showToast = vi.fn(); + await app._attachFromToolbar([{}], 'old'); + expect(wire).toEqual([]); + expect(app._localEchoOverlay.pendingText).toBe('hel /p '); + }); + + it('maps the native suffix after a non-BMP committed prefix and hides mismatches or missing cells', () => { + const { app } = harness(); + const caret = { visible: true, text: 'hello', offset: 2 }; + expect(app._nativeInputCaretAnchor(caret)).toBeNull(); + app._localEchoOverlay.flushed = '👍'; + app._localEchoOverlay.pendingText = 'hello'; + expect(app._nativeInputCaretAnchor(caret)).toEqual({ col: 8, row: 2 }); + expect(app._localEchoOverlay.getInputAnchor).toHaveBeenLastCalledWith(4); + expect(app._nativeInputCaretAnchor({ ...caret, text: 'hullo' })).toBe('hide'); + app._localEchoOverlay.getInputAnchor = () => null; + expect(app._nativeInputCaretAnchor(caret)).toBe('hide'); + delete app._localEchoOverlay.getInputAnchor; + expect(app._nativeInputCaretAnchor(caret)).toBe('hide'); + app._echoPassthroughSessions = new Set(['old']); + expect(app._nativeInputCaretAnchor(caret)).toBeNull(); + }); + + it('prepares only the captured tile owner, not the primary owner', () => { + const { app } = harness(); + app._iosNativeInput = { settle: vi.fn(), reset: vi.fn() }; + const tile = { _iosNativeInput: { settle: vi.fn(), reset: vi.fn() } }; + app._prepareExternalInput({ terminal: {}, sessionId: 'new', isPrimary: false, tile }, 'external'); + expect(tile._iosNativeInput.settle).toHaveBeenCalledOnce(); + expect(tile._iosNativeInput.reset).toHaveBeenCalledWith('external'); + expect(app._iosNativeInput.settle).not.toHaveBeenCalled(); + }); + + it('submits the toolbar through the main echo reservation and never falls back from a dead pane', () => { + const { app, wire } = harness(); + const focusedPane = vi.fn(() => ({ terminal: app.terminal, sessionId: 'old', isPrimary: true })); + app._focusedPane = focusedPane; + app._localEchoOverlay.pendingText = 'toolbar'; + app.submitFromToolbar(); + expect(focusedPane).toHaveBeenCalledOnce(); + expect(wire).toEqual([['old', 'toolbar']]); + vi.advanceTimersByTime(80); + expect(wire.at(-1)).toEqual(['old', '\r']); + focusedPane.mockReturnValue({ terminal: {}, sessionId: 'gone', isPrimary: false }); + app.submitFromToolbar(); + expect(wire).toHaveLength(2); + }); + + it('toolbar Enter spends an armed one-shot Ctrl, so the next typed c stays a c', () => { + for (const echo of [true, false]) { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._localEchoEnabled = echo; + const bar = vm.runInContext('KeyboardAccessoryBar', context); + bar.toggleCtrl(); + expect(bar.isCtrlArmed()).toBe(true); + app.submitFromToolbar(); + vi.advanceTimersByTime(80); + expect(bar.isCtrlArmed()).toBe(false); + wire.length = 0; + app._handleTerminalData('c', 'old'); + app.submitFromToolbar(); + vi.advanceTimersByTime(80); + expect(wire).toEqual([ + ['old', 'c'], + ['old', '\r'], + ]); + } + }); + + it('accessory Shift+Tab leaves the unsent draft in the overlay, as a typed Shift+Tab does', () => { + const { app, wire, context } = harness(); + loadProducerModules(app, context); + app._handleTerminalData('hel', 'old'); + vm.runInContext("KeyboardAccessoryBar.handleAction('shift-tab')", context); + expect(wire).toEqual([['old', '\x1b[Z']]); + expect(app._localEchoOverlay.pendingText).toBe('hel'); + // The typed key takes the same path: the draft stays put. + app._handleTerminalData('\x1b[Z', 'old'); + expect(wire).toEqual([ + ['old', '\x1b[Z'], + ['old', '\x1b[Z'], + ]); + expect(app._localEchoOverlay.pendingText).toBe('hel'); + }); + it('resets native ownership before dispatching synthetic compositionend', () => { + const { app, context } = harness(); + attachCleanupStubs(app); + const order: string[] = []; + app._iosNativeInput = { settle: vi.fn(), reset: () => order.push('reset') }; + context.CompositionEvent = class { + constructor(public type: string) {} + }; + app.terminal = { + _core: { _compositionHelper: { _isComposing: true } }, + element: { querySelector: () => ({ dispatchEvent: () => order.push('compositionend') }) }, + }; + app._cleanupPreviousSession('new'); + expect(order).toEqual(['reset', 'compositionend']); + }); + + it('creates an iOS owner instead of recovery, connects transaction/preview/anchor callbacks and disposes prior owners', () => { + const { app, wire, context } = harness(); + const owner = { destroy: vi.fn() }; + const disposeMarker = vi.fn(); + const native = { + isSupported: () => true, + create: vi.fn( + (_options: { + terminal: object; + sendTransaction: (ops: string[]) => void; + onTransaction: (transaction: { inserted: string; deleted: number; composition: boolean }) => void; + isScreenReaderMode: () => boolean; + }) => owner + ), + attachCaretMarker: vi.fn( + ( + _terminal: object, + _owner: object, + _options: { + anchor: () => unknown; + subscribe: (callback: () => void) => unknown; + } + ) => disposeMarker + ), + }; + const recovery = { create: vi.fn() }; + context.window.CodemanIosNativeInput = native; + context.window.CodemanKeyCode229Recovery = recovery; + app._mobileImePreview = { nativeTransaction: vi.fn() }; + const unsubscribe = vi.fn(); + app._localEchoOverlay.onLayout = vi.fn(() => unsubscribe); + app._initTerminalInputOwner(); + expect(native.create).toHaveBeenCalledOnce(); + expect(recovery.create).not.toHaveBeenCalled(); + const options = native.create.mock.calls[0][0]; + expect(options.terminal).toBe(app.terminal); + app._localEchoEnabled = false; + options.sendTransaction(['\x7f', 'native']); + expect(wire).toEqual([ + ['old', '\x7f'], + ['old', 'native'], + ]); + const transaction = { inserted: '', deleted: 1, composition: true }; + options.onTransaction(transaction); + expect(app._mobileImePreview.nativeTransaction).toHaveBeenCalledWith(transaction); + const markerOptions = native.attachCaretMarker.mock.calls[0][2]; + expect(markerOptions.anchor({ visible: true, text: 'native', offset: 2 })).toBeNull(); + expect(markerOptions.subscribe(vi.fn())).toBe(unsubscribe); + app._initTerminalInputOwner(); + expect(owner.destroy).toHaveBeenCalledOnce(); + expect(disposeMarker).toHaveBeenCalledOnce(); + expect(native.create).toHaveBeenCalledTimes(2); + }); + + it('retains the recovery path when the iOS module is absent', () => { + const { app, wire, context } = harness(); + const recovery = { destroy: vi.fn() }; + const create = vi.fn((_options: { emitRecovered: (data: string) => void }) => recovery); + context.window.CodemanKeyCode229Recovery = { create }; + app._localEchoEnabled = false; + app._initTerminalInputOwner(); + create.mock.calls[0][0].emitRecovered('recovered'); + expect(wire).toEqual([['old', 'recovered']]); + app._initTerminalInputOwner(); + expect(recovery.destroy).toHaveBeenCalledOnce(); + }); + + it('falls back to the recovery when the iOS module is supported but create() refuses', () => { + const { app, wire, context } = harness(); + const native = { isSupported: () => true, create: vi.fn(() => null), attachCaretMarker: vi.fn() }; + const create = vi.fn((_options: { emitRecovered: (data: string) => void }) => ({ destroy: vi.fn() })); + context.window.CodemanIosNativeInput = native; + context.window.CodemanKeyCode229Recovery = { create }; + app._localEchoEnabled = false; + app._initTerminalInputOwner(); + expect(native.create).toHaveBeenCalledOnce(); + expect(native.attachCaretMarker).not.toHaveBeenCalled(); + expect(app._iosNativeInput).toBeNull(); + expect(create).toHaveBeenCalledOnce(); + create.mock.calls[0][0].emitRecovered('recovered'); + expect(wire).toEqual([['old', 'recovered']]); + }); + + it('toolbar Enter with echo off clears codex predictions like typed Enter', () => { + const { app, wire } = harness(); + // The harness stubs the hook; run the real one from terminal-ui.js. + delete app._predictHookOnData; + app._localEchoEnabled = false; + app._localEchoPolicy = 'predict'; + app._predictiveEcho = { clearPredictions: vi.fn(), predictChar: vi.fn(), predictBackspace: vi.fn() }; + app._submitMainInput('old'); + expect(app._predictiveEcho.clearPredictions).toHaveBeenCalledOnce(); + expect(wire).toEqual([['old', '\r']]); + }); + + it('settles and resets native ownership before inserting external text into the overlay', () => { + const { app } = harness(); + app._iosNativeInput = { + settle: () => { + app._localEchoOverlay.pendingText = 'native'; + }, + reset: vi.fn(), + }; + app.insertTerminalText('external'); + expect(app._localEchoOverlay.pendingText).toBe('nativeexternal'); + expect(app._iosNativeInput.reset).toHaveBeenCalledWith('insert'); + }); + + it('seals accepted printable input before clear, discarding only unsent overlay text', () => { + const { app, wire } = harness(); + app._appendPendingInput('old', 'accepted'); + app._localEchoOverlay.pendingText = 'discard'; + app._localEchoOverlay.flushed = 'XY'; + app._iosNativeInput = { settle: vi.fn(), reset: vi.fn() }; + app.clearTerminalInput(); + expect(wire).toEqual([ + ['old', 'accepted'], + ['old', '\x7f\x7f'], + ]); + expect(app._pendingInput.get('old')).toBeUndefined(); + expect(app._localEchoOverlay.pendingText).toBe(''); + expect(app._iosNativeInput.reset).toHaveBeenCalledWith('clear'); + }); + + it('captures the CJK target before preparing its native owner', () => { + const { app, wire } = harness(); + app._iosNativeInput = { + settle: vi.fn(), + reset: () => { + app.activeSessionId = 'new'; + }, + }; + app._handleCjkInput('composed'); + expect(wire).toEqual([['old', 'composed']]); + }); +}); diff --git a/test/terminal-ios-native-input.test.ts b/test/terminal-ios-native-input.test.ts new file mode 100644 index 00000000..ec617fb2 --- /dev/null +++ b/test/terminal-ios-native-input.test.ts @@ -0,0 +1,1711 @@ +/** + * VM port of all 34 phone-prototype replay cases. Browser defaults are applied + * explicitly, not attributed to xterm. Real xterm command/paste producers, + * contextmenu selection, computed CSS/layout and trusted keyboard defaults are + * browser integration gates; these tests cover the owner's side of each case. + */ +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import { describe, expect, it, vi } from 'vitest'; + +type Event = Record; +interface Caret { + visible: boolean; + text: string; + offset: number; +} +interface Transaction { + inserted: string; + deleted: number; + composition: boolean; +} +interface NativeOwner { + keyFilter(event: Event): boolean; + reset(reason: string): void; + settle(): void; + destroy(): void; + caret(): Caret; + onCaret(callback: (caret: Caret) => void): () => void; + state(): { synced: string; cursor: number; composing: boolean; invalidated: boolean; generation: number }; +} +interface NativeOptions { + terminal: FakeTerminal; + sendTransaction(ops: string[]): void; + onTransaction(transaction: Transaction): void; + onCaret(caret: Caret): void; + log(entry: Event): void; + isScreenReaderMode(): boolean; + blurPolicy: string; +} +interface NativeApi { + create(options: Partial): NativeOwner | null; + editBetween(previous: string, next: string): { inserted: string; deleted: number }; + classifyKey(event: Event, textarea: FakeTextarea): string; + isSupported(): boolean; + attachCaretMarker( + terminal: FakeTerminal, + owner: NativeOwner, + options?: { + anchor?: (caret: Caret) => { col: number; row: number } | 'hide' | null | undefined; + subscribe?: (callback: () => void) => () => void; + } + ): () => void; +} +interface NativeWindow { + navigator: { userAgent: string; platform?: string; maxTouchPoints: number }; + setTimeout(callback: () => void): number; + clearTimeout(id: number): boolean; + CodemanIosNativeInput?: NativeApi; + MobileImePreview?: { isIosWebKitTouch(nav: NativeWindow['navigator']): boolean }; +} +interface FakeHelper { + _handleAnyTextareaChanges(): void; + _finalizeComposition(): void; + _compositionView?: { classList: Set & { remove(value: string): boolean } }; + _isComposing: boolean; + _isSendingComposition: boolean; +} +interface FakeCore { + _inputEvent(ev?: Event): unknown; + _unprocessedDeadKey?: boolean; + _handleTextAreaBlur(): void; + _compositionHelper: FakeHelper; + coreService: { triggerDataEvent(): void; decPrivateModes?: { applicationCursorKeys: boolean } }; + unicodeService: { getStringCellWidth?: (text: string) => number }; + _renderService: { dimensions: { css: { cell: { width: number; height: number } } } | null }; +} +interface BufferCell { + getChars(): string; + getWidth(): number; +} +interface BufferLine { + isWrapped: boolean; + getCell(col: number): BufferCell | undefined; +} +interface FakeTerminal { + textarea: FakeTextarea; + element: FakeNode; + _core: FakeCore; + cols: number; + rows: number; + buffer: { + active: { + cursorX: number; + cursorY: number; + baseY: number; + viewportY: number; + getLine(row: number): BufferLine | undefined; + }; + }; + options: { theme: { cursor: string }; screenReaderMode: boolean }; + onRender(callback: () => void): { dispose(): void }; + onCursorMove(callback: () => void): { dispose(): void }; + onWriteParsed(callback: () => void): { dispose(): void }; +} +interface Harness { + api: NativeApi; + exposed: NativeWindow; + terminal: FakeTerminal; + textarea: FakeTextarea; + document: FakeDocument; + core: FakeCore; + helper: FakeHelper; + rawProducer: { (): void; mock: unknown }; + originals: Array<{ + target: FakeCore | FakeHelper; + name: string; + method: unknown; + descriptor: PropertyDescriptor | undefined; + }>; + timers: Map void>; + transactions: string[][]; + notifications: Event[]; + records: Event[]; + caretChanges: Event[]; + sent: string[]; + commits: string[]; + screen: FakeNode; + renders: Set<() => void>; + moves: Set<() => void>; + parsed: Set<() => void>; + owner: NativeOwner; + tick(): void; + selection(start: number, end?: number, direction?: string): void; + snapshot(): Array; + silent(type: string, fields?: Event): { defaultPrevented: boolean }; + edit(data: string | null, range?: number[], inputType?: string, composing?: boolean, audit?: boolean): void; + key(key: string, keyCode: number, extra?: Event): boolean; + type(text: string, audit?: boolean): void; + backspace(): void; + enter(): void; + begin(): void; + end(): void; + blur(): void; + focus(): void; + consume(data: string): void; + replaceOwner(extra?: Partial): void; + setAfterTransaction(callback: (ops: string[]) => void): void; + setTransactionHandler(callback: (ops: string[]) => void): void; + onBlur(callback: () => void): void; + value(): string; + pending(): string; + flush(): void; + clearSent(): void; + bytes(expected: string[]): void; + invariant(): void; +} +class FakeStyle { + cssText = ''; + left = ''; + top = ''; + height = ''; + display = ''; + backgroundColor = ''; + properties = new Map(); + getPropertyValue(key: string) { + return this.properties.get(key)?.value ?? ''; + } + getPropertyPriority(key: string) { + return this.properties.get(key)?.priority ?? ''; + } + setProperty(key: string, value: string, priority = '') { + this.properties.set(key, { value, priority }); + } + removeProperty(key: string) { + this.properties.delete(key); + } +} +type Listener = (event: Event) => void; +const DEL = '\x7f'; +const dels = (count: number) => Array(count).fill(DEL); +const project = (value: string) => value.replace(/\r\n|[\r\n]/g, ' '); +// The destination (Claude Code, Codex, the local-echo overlay) deletes one grapheme cluster per DEL. +const trimGrapheme = (value: string) => + [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)] + .slice(0, -1) + .map((part) => part.segment) + .join(''); + +class FakeNode { + listeners = new Map>(); + style = new FakeStyle(); + className = ''; + attributes: Record = {}; + children: FakeNode[] = []; + parent: FakeNode | null = null; + ownerDocument!: FakeDocument; + querySelector: (selector: string) => FakeNode | null = () => null; + addEventListener(type: string, listener: Listener) { + const bucket = this.listeners.get(type) ?? new Set(); + bucket.add(listener); + this.listeners.set(type, bucket); + } + removeEventListener(type: string, listener: Listener) { + this.listeners.get(type)?.delete(listener); + } + fire(type: string, fields: Event = {}) { + const event = { + type, + target: this, + defaultPrevented: false, + preventDefault() { + this.defaultPrevented = true; + }, + ...fields, + }; + for (const listener of [...(this.listeners.get(type) ?? [])]) listener(event); + return event; + } + setAttribute(key: string, value: string) { + this.attributes[key] = value; + } + appendChild(child: FakeNode) { + child.parent = this; + this.children.push(child); + } + remove() { + if (this.parent) this.parent.children.splice(this.parent.children.indexOf(this), 1); + } + count() { + return [...this.listeners.values()].reduce((total, bucket) => total + bucket.size, 0); + } +} + +class FakeDocument extends FakeNode { + activeElement: FakeNode | null = null; + createElement() { + const node = new FakeNode(); + node.ownerDocument = this; + return node; + } +} + +class FakeTextarea extends FakeNode { + private text = ''; + writes: string[] = []; + selectionStart = 0; + selectionEnd = 0; + selectionDirection = 'none'; + get properties() { + return this.style.properties; + } + constructor(document: FakeDocument) { + super(); + this.ownerDocument = document; + } + get value() { + return this.text; + } + set value(value: string) { + this.writes.push('value'); + if (this.text !== value) { + this.selectionStart = this.selectionEnd = value.length; + this.selectionDirection = 'none'; + } + this.text = value; + } + setSelectionRange(start: number, end: number, direction = 'none') { + this.writes.push('selection'); + this.selectionStart = start; + this.selectionEnd = end; + this.selectionDirection = direction; + } +} + +function bufferLine(cells: Array, isWrapped = false): BufferLine { + return { + isWrapped, + getCell(col) { + const value = cells[col]; + if (value === undefined) return undefined; + const [chars, width] = typeof value === 'string' ? [value, 1] : value; + return { getChars: () => chars, getWidth: () => width }; + }, + }; +} + +function harness( + mode = 'direct', + options: { + initialValue?: string; + whitespace?: string; + priority?: string; + screenReaderMode?: boolean; + owner?: Partial; + } = {} +): Harness { + const document = new FakeDocument(); + const textarea = new FakeTextarea(document); + textarea.value = options.initialValue ?? ''; + if (options.whitespace) textarea.style.setProperty('white-space', options.whitespace, options.priority ?? ''); + document.activeElement = textarea; + const timers = new Map void>(); + let timerId = 0; + const exposed: NativeWindow = { + navigator: { userAgent: 'iPhone AppleWebKit/605.1.15', maxTouchPoints: 5 }, + setTimeout: (callback: () => void) => { + const id = ++timerId; + timers.set(id, callback); + return id; + }, + clearTimeout: (id: number) => timers.delete(id), + }; + const context = vm.createContext({ window: exposed, globalThis: exposed }); + for (const file of ['mobile-ime-preview.js', 'terminal-ios-native-input.js']) { + vm.runInContext(readFileSync(new URL(`../src/web/public/${file}`, import.meta.url), 'utf8'), context, { + filename: file, + }); + } + const rawProducer = vi.fn(); + const activeClasses = new Set(['active']); + const compositionView = { + classList: Object.assign(activeClasses, { + remove: (value: string) => activeClasses.delete(value), + }), + }; + const helper: FakeHelper = Object.assign( + Object.create({ + _handleAnyTextareaChanges: rawProducer, + _finalizeComposition: rawProducer, + }), + { _compositionView: compositionView, _isComposing: false, _isSendingComposition: false } + ); + let blurCallback = () => {}; + const core: FakeCore = Object.assign( + Object.create({ + _inputEvent: rawProducer, + _handleTextAreaBlur() { + textarea.value = ''; + textarea.setSelectionRange(0, 0); + blurCallback(); + }, + }), + { + _compositionHelper: helper, + coreService: { triggerDataEvent: rawProducer }, + unicodeService: { + getStringCellWidth: (text: string) => + Array.from(text).reduce((width, point) => width + (/[你好吗]/.test(point) ? 2 : 1), 0), + }, + _renderService: { dimensions: { css: { cell: { width: 8, height: 16 } } } }, + } + ); + const screen = new FakeNode(); + screen.ownerDocument = document; + const element = new FakeNode(); + element.querySelector = (selector: string) => (selector === '.xterm-screen' ? screen : null); + const renders = new Set<() => void>(); + const moves = new Set<() => void>(); + const parsed = new Set<() => void>(); + const subscribe = (set: Set<() => void>, callback: () => void) => { + set.add(callback); + return { dispose: () => set.delete(callback) }; + }; + const terminal: FakeTerminal = { + textarea, + element, + _core: core, + cols: 10, + rows: 5, + buffer: { + active: { + cursorX: 5, + cursorY: 2, + baseY: 0, + viewportY: 0, + getLine: (row) => + row === terminal.buffer.active.baseY + terminal.buffer.active.cursorY + ? bufferLine(Array.from(line + pending)) + : undefined, + }, + }, + options: { theme: { cursor: '#fff' }, screenReaderMode: !!options.screenReaderMode }, + onRender: (callback: () => void) => subscribe(renders, callback), + onCursorMove: (callback: () => void) => subscribe(moves, callback), + onWriteParsed: (callback: () => void) => subscribe(parsed, callback), + }; + const originals = [ + { target: core, name: '_inputEvent' }, + { target: core, name: '_handleTextAreaBlur' }, + { target: helper, name: '_handleAnyTextareaChanges' }, + { target: helper, name: '_finalizeComposition' }, + ].map(({ target, name }) => ({ + target, + name, + method: Reflect.get(target, name), + descriptor: Object.getOwnPropertyDescriptor(target, name), + })); + const sent: string[] = []; + const transactions: string[][] = []; + const notifications: Event[] = []; + const records: Event[] = []; + const caretChanges: Event[] = []; + let line = ''; + let pending = ''; + const commits: string[] = []; + const consume = (data: string) => { + sent.push(data); + if (data === DEL) { + if (pending) pending = trimGrapheme(pending); + else line = trimGrapheme(line); + } else if (data === '\r') { + commits.push(line + pending); + line = ''; + pending = ''; + } else if (data === '\x03') { + line = ''; + pending = ''; + } else if (data.startsWith('\x1b')) { + /* xterm command effect belongs to browser tests */ + } else if (mode === 'local-echo') pending += data; + else line += data; + }; + let afterTransaction = (_ops: string[]) => {}; + let transactionHandler = (ops: string[]) => { + for (const op of ops) consume(op); + }; + // The IIFE just installed this API into the VM's window. + const api = exposed.CodemanIosNativeInput!; + const create = (extra: Partial = {}) => + api.create({ + terminal, + sendTransaction(ops: string[]) { + transactions.push([...ops]); + transactionHandler(ops); + afterTransaction(ops); + }, + onTransaction: (transaction: Transaction) => notifications.push({ ...transaction }), + onCaret: (caret: Caret) => caretChanges.push({ ...caret }), + log: (entry: Event) => records.push(entry), + ...extra, + }); + // Normal replay fixtures have complete internals; null is asserted explicitly + // by the screen-reader/unsupported creation tests. + let owner = create(options.owner)!; + const tick = () => { + for (const [id, callback] of [...timers]) { + timers.delete(id); + callback(); + } + }; + const selection = (start: number, end = start, direction = 'none') => { + textarea.setSelectionRange(start, end, direction); + document.fire('selectionchange'); + }; + const snapshot = () => [textarea.value, textarea.selectionStart, textarea.selectionEnd, textarea.selectionDirection]; + const silent = (type: string, fields: Event = {}) => { + const before = snapshot(); + const writes = textarea.writes.length; + const event = textarea.fire(type, fields); + expect(snapshot()).toEqual(before); + expect(textarea.writes).toHaveLength(writes); + return event; + }; + const edit = (data: string | null, range?: number[], inputType = 'insertText', composing = false, audit = true) => { + if (range) textarea.setSelectionRange(range[0], range[1]); + const fields = { data, inputType, isComposing: composing }; + const before = silent('beforeinput', fields); + if (before.defaultPrevented) return; + let start = textarea.selectionStart; + const end = textarea.selectionEnd; + if (inputType === 'deleteContentBackward') { + if (start === end) { + if (start === 0) return; + // WebKit removes one whole grapheme cluster per Backspace. + const clusters = [ + ...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(textarea.value.slice(0, start)), + ]; + start -= clusters.at(-1)!.segment.length; + } + textarea.value = textarea.value.slice(0, start) + textarea.value.slice(end); + textarea.setSelectionRange(start, start); + } else { + const text = inputType === 'insertLineBreak' ? '\n' : (data ?? ''); + textarea.value = textarea.value.slice(0, start) + text + textarea.value.slice(end); + textarea.setSelectionRange(start + text.length, start + text.length); + } + if (audit) silent('input', fields); + else textarea.fire('input', fields); + }; + const key = (key: string, keyCode: number, extra: Event = {}) => { + const event = { type: 'keydown', key, keyCode, ...extra }; + textarea.fire('keydown', event); + return owner.keyFilter(event); + }; + const type = (text: string, audit = true) => { + key(text, text === ' ' ? 32 : text.toUpperCase().codePointAt(0)!); + expect(owner.keyFilter({ type: 'keypress', key: text })).toBe(false); + edit(text, undefined, 'insertText', false, audit); + }; + const backspace = () => { + if (key('Backspace', 8)) consume(DEL); + else edit(null, undefined, 'deleteContentBackward'); + }; + const enter = () => { + if (key('Enter', 13)) consume('\r'); + }; + const begin = () => { + helper._isComposing = true; + helper._isSendingComposition = true; + compositionView.classList.add('active'); + textarea.fire('compositionstart'); + }; + const end = () => { + helper._finalizeComposition(); + textarea.fire('compositionend'); + }; + const blur = () => { + document.activeElement = null; + core._handleTextAreaBlur(); + textarea.fire('blur'); + }; + const focus = () => { + document.activeElement = textarea; + textarea.fire('focus'); + }; + return { + api, + exposed, + terminal, + textarea, + document, + core, + helper, + rawProducer, + originals, + timers, + tick, + transactions, + notifications, + records, + caretChanges, + sent, + commits, + selection, + snapshot, + silent, + edit, + key, + type, + backspace, + enter, + begin, + end, + blur, + focus, + screen, + renders, + moves, + parsed, + consume, + get owner() { + return owner; + }, + replaceOwner(extra: Partial = {}) { + owner.destroy(); + owner = create(extra)!; + }, + setAfterTransaction(callback: (ops: string[]) => void) { + afterTransaction = callback; + }, + setTransactionHandler(callback: (ops: string[]) => void) { + transactionHandler = callback; + }, + onBlur(callback: () => void) { + blurCallback = callback; + }, + value: () => line + pending, + pending: () => pending, + flush() { + line += pending; + pending = ''; + }, + clearSent() { + sent.length = 0; + transactions.length = 0; + }, + bytes(expected: string[]) { + expect(sent).toEqual(expected); + }, + invariant() { + expect(owner.state().synced).toBe(project(textarea.value)); + expect(owner.state().cursor).toBe(Array.from(project(textarea.value)).length); + expect(records.filter((record) => record.type === 'error')).toEqual([]); + }, + }; +} + +const replayCases: Array<[string, (h: Harness) => void]> = [ + [ + '1 suggestion insertText', + (h) => { + expect(Object.isFrozen(h.api)).toBe(true); + expect(h.api.create({})).toBeNull(); + expect(h.api.create({ terminal: h.terminal, sendTransaction() {}, isScreenReaderMode: () => true })).toBeNull(); + expect(h.api.editBetween('a👍b', 'aX')).toEqual({ deleted: 2, inserted: 'X' }); + // One DEL per grapheme cluster: WebKit removes the whole cluster on one + // Backspace, and Claude Code and Codex delete one grapheme per DEL. + for (const emoji of [ + '\u2764\uFE0F', + '\u{1F44D}\u{1F3FD}', + '\u{1F1EB}\u{1F1F7}', + '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}', + ]) { + expect(h.api.editBetween(`ok${emoji}`, 'ok')).toEqual({ deleted: 1, inserted: '' }); + expect(h.api.editBetween(`a${emoji}b`, 'aX')).toEqual({ deleted: 2, inserted: 'X' }); + } + // A combining mark or tone typed onto the last letter is a plain append, as on master. + expect(h.api.editBetween('\u0E01', '\u0E01\u0E34')).toEqual({ deleted: 0, inserted: '\u0E34' }); + expect(h.api.editBetween('\u0915\u094D', '\u0915\u094D\u0937')).toEqual({ deleted: 0, inserted: '\u0937' }); + for (const ch of 'hel') h.type(ch); + h.type('lo'); + h.tick(); + h.bytes(['h', 'e', 'l', 'lo']); + expect(h.value()).toBe('hello'); + h.invariant(); + }, + ], + [ + '2 suggestion replacement', + (h) => { + for (const ch of 'hel') h.type(ch); + h.edit('hello', [0, 3], 'insertReplacementText'); + h.bytes(['h', 'e', 'l', 'lo']); + h.invariant(); + }, + ], + [ + '3 space and suggestion', + (h) => { + for (const ch of 'hello') h.type(ch); + h.type(' '); + h.type('the'); + h.bytes([...Array.from('hello'), ' ', 'the']); + h.invariant(); + }, + ], + [ + '4 whole-line replacement after delete', + (h) => { + for (const ch of 'helloworld') h.type(ch); + h.flush(); + h.backspace(); + h.edit('Hello World', [0, 9], 'insertReplacementText'); + h.bytes([...Array.from('helloworld'), ...dels(10), 'Hello World']); + expect(h.value()).toBe('Hello World'); + }, + ], + [ + '5 held Backspace bursts', + (h) => { + for (const ch of 'hello world again') { + h.type(ch); + h.invariant(); + } + h.backspace(); + for (let burst = 0; burst < 2; burst++) { + for (let index = 0; index < 7; index++) { + h.backspace(); + h.invariant(); + } + // The captured iOS burst has one final deletion without another keydown. + h.edit(null, undefined, 'deleteContentBackward'); + h.invariant(); + } + h.bytes([...Array.from('hello world again'), ...dels(17)]); + expect(h.value()).toBe(''); + }, + ], + [ + '6 empty-field terminal Backspace', + (h) => { + h.backspace(); + h.backspace(); + h.bytes([DEL, DEL]); + expect(h.transactions).toEqual([]); + }, + ], + [ + '7 command-named suggestions and classification', + (h) => { + for (const text of ['Enter', 'Tab', 'Home']) h.type(text); + h.bytes(['Enter', 'Tab', 'Home']); + const commands: Record = { + 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, + }; + for (let index = 1; index <= 12; index++) commands['F' + index] = 111 + index; + for (const [key, keyCode] of Object.entries(commands)) { + expect(h.api.classifyKey({ key, keyCode }, h.textarea)).toBe('command'); + expect(h.api.classifyKey({ key, keyCode: 0 }, h.textarea)).toBe('native'); + } + for (const key of ['UpArrow', 'DownArrow', 'LeftArrow', 'RightArrow', 'Escape']) { + expect(h.api.classifyKey({ key: 'UIKeyInput' + key }, h.textarea)).toBe('command'); + } + for (const modifier of ['ctrlKey', 'altKey', 'metaKey']) { + expect(h.api.classifyKey({ key: 'x', keyCode: 88, [modifier]: true }, h.textarea)).toBe('command'); + } + expect(h.api.classifyKey({ key: 'F13', keyCode: 112 }, h.textarea)).toBe('native'); + expect(h.api.classifyKey({ key: 'Process' }, h.textarea)).toBe('compose'); + expect(h.api.classifyKey({ key: 'x', keyCode: 229, ctrlKey: true }, h.textarea)).toBe('compose'); + expect(h.api.classifyKey({ key: 'x', isComposing: true }, h.textarea)).toBe('compose'); + }, + ], + [ + '8 Enter command boundary', + (h) => { + h.type('ls'); + h.enter(); + expect(h.textarea.value).toBe(''); + h.type('pwd'); + h.bytes(['ls', '\r', 'pwd']); + expect(h.commits).toEqual(['ls']); + h.invariant(); + }, + ], + [ + '9 keyless dictation', + (h) => { + h.edit('hello world'); + h.bytes(['hello world']); + h.invariant(); + }, + ], + [ + '10 captured dictation event order', + (h) => { + // Ten input events from round1/log-2026-11-18T09-09-26-578Z.json. + // Preserve noncollapsed hypothesis ranges; ignore stale collapsed snapshots. + for (const text of ['he', 'hello', 'hello World', 'hello World,\n']) h.edit(text, [0, h.textarea.value.length]); + h.silent('input', { inputType: 'insertParagraph', data: null }); + h.edit('hello'); + h.edit(' '); + h.edit('World'); + h.edit(null, undefined, 'insertLineBreak'); + h.edit('Test'); + h.bytes(['he', 'llo', ' World', ', ', 'hello', ' ', 'World', ' ', 'Test']); + expect(h.records.filter((record) => record.type === 'drift')).toEqual([]); + expect(h.sent.some((data) => /[\r\n]/.test(data))).toBe(false); + h.invariant(); + }, + ], + [ + '11 229 recovery and drift', + (h) => { + h.key('Process', 229); + h.textarea.value = 'hello'; + h.textarea.setSelectionRange(5, 5); + h.tick(); + h.bytes(['hello']); + h.owner.reset('boundary'); + h.clearSent(); + h.textarea.value = 'external'; + h.selection(8); + h.silent('beforeinput', { inputType: 'insertText', data: 'x' }); + expect(h.owner.state().invalidated).toBe(true); + h.owner.settle(); + h.tick(); + h.bytes([]); + expect(h.textarea.value).toBe('external'); + h.edit('x', undefined, 'insertText', false, false); + h.bytes([]); + expect(h.textarea.value).toBe(''); + h.type('z'); + h.bytes(['z']); + for (const [value, inputType, data, range] of [ + ['abc', 'deleteContentBackward', null, [3, 3]], + ['abc', 'insertReplacementText', 'Q', [0, 3]], + ['', 'insertText', 'Q', [0, 0]], + ] as const) { + h.owner.reset('boundary'); + h.type('remote'); + const remote = h.value(); + h.clearSent(); + h.textarea.value = value; + h.edit(data, [...range], inputType, false, false); + h.tick(); + h.bytes([]); + expect(h.value()).toBe(remote); + expect(h.textarea.value).toBe(''); + h.type('x'); + h.bytes(['x']); + expect(h.value()).toBe(remote + 'x'); + } + h.owner.reset('boundary'); + h.clearSent(); + h.textarea.value = 'abc'; + h.selection(0); + h.backspace(); + h.owner.settle(); + h.tick(); + h.bytes([]); + expect(h.textarea.value).toBe('abc'); + expect(h.owner.state().invalidated).toBe(true); + h.owner.reset('boundary'); + h.textarea.value = 'unowned'; + h.replaceOwner(); + expect(h.owner.state().synced).toBe(''); + h.edit('x', undefined, 'insertText', false, false); + expect(h.textarea.value).toBe(''); + h.bytes([]); + h.type('y'); + h.bytes(['y']); + h.owner.reset('boundary'); + h.clearSent(); + h.key('Process', 229); + h.textarea.value = 'stale'; + const generation = h.owner.state().generation; + h.owner.reset('cancel'); + h.tick(); + h.bytes([]); + expect(h.owner.state().generation).toBe(generation + 1); + }, + ], + [ + '12 composition and immediate Enter', + (h) => { + h.begin(); + h.edit('にほ', undefined, 'insertCompositionText', true); + h.key('x', 88); + h.tick(); + h.bytes([]); + h.end(); + h.enter(); + h.tick(); + h.bytes(['にほ', '\r']); + expect(h.commits).toEqual(['にほ']); + expect(h.helper._isComposing).toBe(false); + expect(h.helper._isSendingComposition).toBe(false); + expect(h.helper._compositionView!.classList.has('active')).toBe(false); + }, + ], + [ + '13 xterm-owned paste', + (h) => { + h.type('hello'); + const paste = h.textarea.fire('paste'); + expect(paste.defaultPrevented).toBe(true); + expect(h.textarea.value).toBe(''); + h.consume(' world'); + h.type('x'); + h.bytes(['hello', ' world', 'x']); + expect(h.transactions).toEqual([['hello'], ['x']]); + }, + ], + [ + '14 blur preservation', + (h) => { + h.type('hel'); + h.selection(1, 2, 'backward'); + const generation = h.owner.state().generation; + h.blur(); + expect(h.snapshot()).toEqual(['hel', 1, 2, 'backward']); + expect(h.owner.state().generation).toBe(generation); + h.focus(); + h.selection(3); + h.type('lo'); + h.bytes(['hel', 'lo']); + h.onBlur(() => h.owner.reset('blur callback')); + h.blur(); + expect(h.textarea.value).toBe(''); + h.onBlur(() => {}); + h.replaceOwner({ blurPolicy: 'stock' }); + h.focus(); + h.type('stock'); + h.blur(); + expect(h.textarea.value).toBe(''); + expect(h.owner.state().synced).toBe(''); + }, + ], + [ + '15 selection replacement', + (h) => { + h.type('hello'); + h.edit('X', [1, 3]); + h.bytes(['hello', ...dels(4), 'Xlo']); + expect(h.value()).toBe('hXlo'); + h.invariant(); + }, + ], + [ + '16 one-shot Ctrl reset', + (h) => { + h.type('hello'); + h.setTransactionHandler((ops) => { + if (ops.includes('c')) { + h.owner.reset('one-shot Ctrl'); + h.consume('\x03'); + } else for (const op of ops) h.consume(op); + }); + h.type('c', false); + expect(h.textarea.value).toBe(''); + expect(h.owner.state().synced).toBe(''); + h.type('x'); + h.bytes(['hello', '\x03', 'x']); + expect(h.value()).toBe('x'); + // The sink models integration's one-shot transformation before delivery. + }, + ], + [ + '17 ArrowLeft command boundary', + (h) => { + h.type('hello'); + expect(h.key('ArrowLeft', 37)).toBe(true); + expect(h.textarea.value).toBe(''); + h.consume('\x1b[D'); + h.type('X'); + h.bytes(['hello', '\x1b[D', 'X']); + expect(h.transactions).toEqual([['hello'], ['X']]); + }, + ], + [ + '18 reentrant reset and reconciliation', + (h) => { + h.type('helloworld'); + h.backspace(); + let resets = 0; + h.setAfterTransaction((ops) => { + if (ops[0] === DEL && resets++ === 0) h.owner.reset('reentrant'); + }); + h.edit('Hello World', [0, 9], 'insertReplacementText', false, false); + expect(h.owner.state().synced).toBe(''); + h.type('x'); + h.bytes(['helloworld', ...dels(10), 'Hello World', 'x']); + h.owner.reset('boundary'); + h.clearSent(); + h.setAfterTransaction((ops) => { + if (ops[0] === 'a') { + h.textarea.value = 'ab'; + h.textarea.setSelectionRange(2, 2); + h.textarea.fire('input'); + h.owner.settle(); + } + }); + h.edit('a', undefined, 'insertText', false, false); + h.bytes(['a', 'b']); + h.invariant(); + }, + ], + [ + '19 keyup focus ownership', + (h) => { + h.type('hel'); + h.document.activeElement = new FakeNode(); + expect(h.owner.keyFilter({ type: 'keyup' })).toBe(false); + expect(h.document.activeElement).not.toBe(h.textarea); + h.focus(); + expect(h.owner.keyFilter({ type: 'keyup' })).toBe(true); + h.bytes(['hel']); + }, + ], + [ + '20 code-point deletion', + (h) => { + h.type('👍'); + h.backspace(); + h.bytes(['👍', DEL]); + h.type('hello'); + h.clearSent(); + h.selection(0); + h.backspace(); + h.bytes([]); + expect(h.textarea.value).toBe('hello'); + }, + ], + [ + '20b grapheme-cluster deletion sends one DEL', + (h) => { + for (const emoji of [ + '\u2764\uFE0F', + '\u{1F44D}\u{1F3FD}', + '\u{1F1EB}\u{1F1F7}', + '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}', + ]) { + h.type('ok'); + h.edit(emoji); + h.clearSent(); + h.backspace(); + expect(h.textarea.value).toBe('ok'); + h.bytes([DEL]); + // The destination keeps the draft: one DEL took the whole emoji, nothing before it. + expect(h.value()).toBe('ok'); + h.invariant(); + h.backspace(); + h.backspace(); + expect(h.value()).toBe(''); + h.clearSent(); + } + }, + ], + [ + '20c combining marks typed one key at a time are plain appends', + (h) => { + // Thai กิ่ and Hindi क्ष: each keystroke extends the last grapheme cluster. + // Re-typing that cluster would make a code-point line editor (zsh) double the base letter. + for (const word of ['\u0E01\u0E34\u0E48', '\u0915\u094D\u0937']) { + for (const ch of word) h.edit(ch); + h.tick(); + h.bytes(Array.from(word)); + expect(h.value()).toBe(word); + h.invariant(); + while (h.textarea.value) h.backspace(); + expect(h.value()).toBe(''); + h.tick(); + h.clearSent(); + } + }, + ], + [ + '21 destroy restoration and stock behavior', + (h) => { + h.key('Process', 229); + h.textarea.value = 'unsent'; + h.owner.destroy(); + h.owner.destroy(); + h.tick(); + h.bytes([]); + for (const { target, name, method, descriptor } of h.originals) { + expect(Reflect.get(target, name)).toBe(method); + expect(Object.getOwnPropertyDescriptor(target, name)).toEqual(descriptor); + } + expect(h.textarea.style.getPropertyValue('white-space')).toBe(''); + expect(h.textarea.count()).toBe(0); + expect(h.document.count()).toBe(0); + expect(h.terminal.element.count()).toBe(0); + h.core._inputEvent(); + expect(h.rawProducer).toHaveBeenCalledOnce(); + h.core._handleTextAreaBlur(); + expect(h.textarea.value).toBe(''); + }, + ], + [ + '22 intact dictation hypothesis replacement', + (h) => { + for (const text of ['he', 'hello', 'hello World', 'hello World,\n']) h.edit(text, [0, h.textarea.value.length]); + h.silent('input', { inputType: 'insertParagraph', data: null }); + expect(h.textarea.value).toBe('hello World,\n'); + h.edit('hello', [0, h.textarea.value.length]); + h.edit(' '); + h.edit('World'); + h.edit(null, undefined, 'insertLineBreak'); + h.edit('Test'); + h.bytes(['he', 'llo', ' World', ', ', ...dels(8), ' ', 'World', ' ', 'Test']); + expect(h.textarea.value).toBe('hello World\nTest'); + expect(h.value()).toBe('hello World Test'); + h.invariant(); + for (const text of ['a\nb', 'a\r\nb', 'a\rb', '\na\n\nb\r', 'a\u00a0']) { + h.owner.reset('boundary'); + h.clearSent(); + h.edit(text); + h.bytes([project(text)]); + h.invariant(); + } + }, + ], + [ + '23 dictated line break then Enter', + (h) => { + h.edit('hello'); + h.edit(null, undefined, 'insertLineBreak'); + h.edit('World'); + expect(h.textarea.value).toBe('hello\nWorld'); + h.enter(); + h.tick(); + h.bytes(['hello', ' ', 'World', '\r']); + expect(h.commits).toEqual(['hello World']); + expect(h.textarea.value).toBe(''); + }, + ], + [ + '24 trackpad visual caret and insertion', + (h) => { + h.type('hello'); + h.clearSent(); + h.selection(2); + h.bytes([]); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 }); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + const marker = h.screen.children[0]; + expect(marker.attributes['aria-hidden']).toBe('true'); + expect(marker.style.cssText).toContain('pointer-events:none'); + expect([marker.style.left, marker.style.top, marker.style.height, marker.style.display]).toEqual([ + '16px', + '32px', + '16px', + 'block', + ]); + h.edit('X'); + h.bytes([...dels(3), 'Xllo']); + expect(h.value()).toBe('heXllo'); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 3 }); + h.clearSent(); + h.selection(6); + expect(marker.style.display).toBe('none'); + h.bytes([]); + h.selection(3); + expect(marker.style.display).toBe('none'); // No parsed echo of the edit yet. + h.terminal.buffer.active.cursorX = 6; + for (const callback of h.parsed) callback(); + expect([marker.style.left, marker.style.top, marker.style.display]).toEqual(['24px', '32px', 'block']); + dispose(); + dispose(); + expect(h.screen.children).toHaveLength(0); + expect(h.renders.size + h.moves.size + h.parsed.size).toBe(0); + }, + ], + [ + '25 mid-word native delete', + (h) => { + h.type('hello'); + h.clearSent(); + h.selection(2); + h.backspace(); + h.bytes([...dels(4), 'llo']); + expect(h.value()).toBe('hllo'); + h.invariant(); + }, + ], + [ + '26 origin Backspace native no-op', + (h) => { + h.consume('z'); + h.type('hello'); + h.clearSent(); + h.selection(0); + expect(h.api.classifyKey({ key: 'Backspace', keyCode: 8 }, h.textarea)).toBe('native'); + h.backspace(); + h.bytes([]); + expect(h.value()).toBe('zhello'); + expect(h.textarea.value).toBe('hello'); + h.invariant(); + }, + ], + [ + '27 middle-word native replacement', + (h) => { + h.type('one cat two'); + h.clearSent(); + h.edit('dog', [4, 7], 'insertReplacementText'); + h.bytes([...dels(7), 'dog two']); + expect(h.value()).toBe('one dog two'); + h.invariant(); + }, + ], + [ + '28 range selection hides caret', + (h) => { + h.type('hello'); + h.clearSent(); + h.selection(1, 3, 'backward'); + h.bytes([]); + expect(h.owner.caret().visible).toBe(false); + expect(h.owner.state().cursor).toBe(5); + h.edit('X'); + h.bytes([...dels(4), 'Xlo']); + h.invariant(); + }, + ], + [ + '29 width table and cursor modes', + (h) => { + h.type('你好'); + h.clearSent(); + for (const applicationCursorKeys of [true, false]) { + h.core.coreService.decPrivateModes = { applicationCursorKeys }; + h.selection(1); + h.bytes([]); + expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 }); + } + h.core.unicodeService.getStringCellWidth = undefined; + expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 }); + h.selection(2); + expect(h.owner.caret().visible).toBe(false); + }, + ], + [ + '30 caret notifications and silent lifecycle', + (h) => { + h.type('hello'); + h.clearSent(); + const changes: Caret[] = []; + const unsubscribe = h.owner.onCaret((caret: Caret) => changes.push(caret)); + h.selection(2); + h.selection(2); + expect(changes).toMatchObject([{ visible: true, text: 'hello', offset: 2 }]); + expect(changes).toHaveLength(1); + h.blur(); + const before = h.caretChanges.length; + h.document.fire('selectionchange'); + expect(h.caretChanges).toHaveLength(before); + h.focus(); + h.begin(); + expect(h.owner.caret().visible).toBe(false); + h.end(); + expect(h.owner.caret().visible).toBe(true); + h.owner.reset('silent'); + h.tick(); + h.bytes([]); + expect(changes.map((value) => value.visible)).toEqual([true, false, true, false, true, false]); + unsubscribe(); + h.selection(0); + expect(changes).toHaveLength(6); + }, + ], + [ + '31 projected UTF-16 caret', + (h) => { + h.edit('a👍\nb'); + h.clearSent(); + h.selection(4); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 4 }); + h.selection(3); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 3 }); + h.selection(1); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 1 }); + h.selection(3); + h.edit('X'); + h.bytes([DEL, DEL, 'X b']); + expect(h.value()).toBe('a👍X b'); + h.invariant(); + }, + ], + [ + '32 local-echo end-anchored edit and Enter', + (h) => { + h.type('hello'); + h.selection(2); + h.type('X'); + expect(h.value()).toBe('heXllo'); + h.enter(); + h.type('next'); + h.bytes(['hello', ...dels(3), 'Xllo', '\r', 'next']); + expect(h.commits).toEqual(['heXllo']); + expect(h.value()).toBe('next'); + h.invariant(); + }, + ], + [ + '33 end-anchored transaction reset and reentrancy', + (h) => { + h.type('hello'); + let resets = 0; + h.setAfterTransaction((ops) => { + if (ops[0] === DEL && resets++ === 0) h.owner.reset('DEL callback'); + }); + h.edit('X', [2, 2], 'insertText', false, false); + h.bytes(['hello', ...dels(3), 'Xllo']); + expect(h.transactions).toEqual([['hello'], [...dels(3), 'Xllo']]); + expect([h.textarea.value, h.owner.state().synced, h.owner.state().cursor]).toEqual(['', '', 0]); + h.clearSent(); + h.setAfterTransaction(() => {}); + h.type('hello'); + h.setAfterTransaction((ops) => { + if (ops[0] === DEL) h.selection(4); + }); + h.edit('X', [2, 2], 'insertText', false, false); + h.bytes(['hello', ...dels(3), 'Xllo']); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 4 }); + h.invariant(); + }, + ], + [ + '34 known contextmenu clipboard writer', + (h) => { + for (const boundary of ['keydown', 'copy', 'keyless', 'blur']) { + h.owner.reset('boundary'); + h.type('hello'); + h.selection(2); + h.clearSent(); + h.terminal.element.fire('contextmenu'); + h.terminal.element.fire('contextmenu'); + // Simulate xterm's known bubble-phase writer after the owner's capture. + h.textarea.value = 'clipboard'; + h.selection(0, 9); + h.owner.settle(); + h.bytes([]); + expect(h.owner.state().synced).toBe('hello'); + if (boundary === 'copy') { + h.document.fire('copy'); + h.tick(); + expect(h.snapshot()).toEqual(['hello', 2, 2, 'none']); + } + if (boundary === 'blur') { + h.blur(); + expect(h.snapshot()).toEqual(['hello', 2, 2, 'none']); + h.focus(); + } + if (boundary === 'keyless') { + const remote = h.value(); + h.edit('X', undefined, 'insertText', false, false); + h.tick(); + h.bytes([]); + expect(h.textarea.value).toBe(''); + h.type('x'); + h.bytes(['x']); + expect(h.value()).toBe(remote + 'x'); + } else { + h.type('X'); + h.tick(); + h.bytes([...dels(3), 'Xllo']); + expect(h.textarea.value).toBe('heXllo'); + } + expect(h.sent.some((data) => data.includes('clipboard'))).toBe(false); + } + }, + ], + [ + 'contextmenu clipboard snapshot restores before empty-line Backspace classification', + (h) => { + expect(h.textarea.value).toBe(''); + h.terminal.element.fire('contextmenu'); + // xterm's bubble handler writes a selection before its next capture keydown. + h.textarea.value = 'clipboard'; + h.selection(0, 9); + expect(h.owner.keyFilter({ type: 'keydown', key: 'Backspace', keyCode: 8 })).toBe(true); + expect(h.textarea.value).toBe(''); + h.bytes([]); + }, + ], +]; + +for (const mode of ['direct', 'local-echo']) { + describe(`CodemanIosNativeInput prototype replays (${mode})`, () => { + it.each(replayCases)('%s', (_name, run) => run(harness(mode))); + }); +} + +describe('CodemanIosNativeInput integration contract', () => { + it('projects CRLF and LF prefixes into UTF-16 caret offsets', () => { + const h = harness(); + h.edit('a👍\r\nb\nc'); + for (const [selection, offset] of [ + [1, 1], + [3, 3], + [5, 4], + [7, 6], + ]) { + h.selection(selection); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b c', offset }); + } + }); + + it('hides pending, invalidated and foreign native snapshots', () => { + const h = harness(); + h.type('hello'); + h.selection(2); + expect(h.owner.caret().visible).toBe(true); + h.textarea.value = 'hellox'; + h.selection(2); + expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hellox', offset: 2 }); + h.textarea.fire('beforeinput'); + expect(h.owner.caret().visible).toBe(false); + h.owner.reset('test'); + h.type('hello'); + h.selection(2); + h.terminal.element.fire('contextmenu'); + expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 }); + }); + + it('maps a你b through validated wide-wrap padding to explicit cells', () => { + const h = harness(); + h.type('a你b'); + h.terminal.cols = 80; + const lines = new Map([ + [0, bufferLine([...Array(78).fill(' '), 'a', ''])], + [1, bufferLine([['你', 2], ['', 0], 'b'], true)], + ]); + Object.assign(h.terminal.buffer.active, { cursorX: 3, cursorY: 1, getLine: (row: number) => lines.get(row) }); + h.selection(0); + const snapshot = h.snapshot(); + const sent = [...h.sent]; + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + const marker = h.screen.children[0]; + for (const [offset, col, row] of [ + [0, 78, 0], + [1, 0, 1], + [2, 2, 1], + ]) { + h.selection(offset); + expect([marker.style.display, marker.style.left, marker.style.top]).toEqual([ + 'block', + `${col * 8}px`, + `${row * 16}px`, + ]); + } + h.selection(0); + expect(h.snapshot()).toEqual(snapshot); + expect(h.sent).toEqual(sent); + expect(h.document.activeElement).toBe(h.textarea); + h.terminal.buffer.active.viewportY = 1; + for (const callback of h.renders) callback(); + expect(marker.style.display).toBe('none'); + dispose(); + }); + + it.each(['e\u0301', '👩‍💻'])('hides offsets inside one buffer cluster %s but maps its start', (cluster) => { + const h = harness(); + h.type(cluster + 'b'); + Object.assign(h.terminal.buffer.active, { + cursorX: 3, + cursorY: 0, + getLine: () => bufferLine([[cluster, 2], ['', 0], 'b']), + }); + h.selection(1); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + const marker = h.screen.children[0]; + expect(marker.style.display).toBe('none'); + h.selection(0); + expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '0px', '0px']); + dispose(); + }); + + it('hides an old identical hello until the next parsed write', () => { + const h = harness(); + h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello')); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + h.type('hello'); + h.selection(2); + const marker = h.screen.children[0]; + expect(marker.style.display).toBe('none'); + for (const callback of h.renders) callback(); + for (const callback of h.moves) callback(); + expect(marker.style.display).toBe('none'); + for (const callback of h.parsed) callback(); + expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '16px', '32px']); + dispose(); + }); + + it('keeps the marker after a copy borrows and restores the native field, with no new output', () => { + const h = harness(); + h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello')); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + h.type('hello'); + h.selection(2); + for (const callback of h.parsed) callback(); + const marker = h.screen.children[0]; + expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']); + // xterm's right-click handler lends the field to native Copy: a different + // terminal selection, then the copy timer restores the draft. No input is + // sent and no xterm write follows. + h.terminal.element.fire('contextmenu'); + h.textarea.value = 'other selection'; + h.selection(0, 15); + expect(marker.style.display).toBe('none'); + h.document.fire('copy'); + h.tick(); + h.selection(2); + expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 }); + expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']); + dispose(); + }); + + it('does not treat an unwritten cell as a native space', () => { + const h = harness(); + h.type('a b'); + h.selection(1); + Object.assign(h.terminal.buffer.active, { cursorX: 3, getLine: () => bufferLine(['a', '', 'b']) }); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + expect(h.screen.children[0].style.display).toBe('none'); + dispose(); + }); + + it('never crosses a hard line break while matching the native field', () => { + const h = harness(); + h.type('ab'); + h.selection(0); + const lines = new Map([ + [0, bufferLine(['a'])], + [1, bufferLine(['b'])], + ]); + Object.assign(h.terminal.buffer.active, { cursorX: 1, cursorY: 1, getLine: (row: number) => lines.get(row) }); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + expect(h.screen.children[0].style.display).toBe('none'); + dispose(); + }); + + it.each(['hellohello', 'hullo', 'xhello'])('checks the full buffer suffix and repetition for %s', (text) => { + const h = harness(); + h.type('hello'); + Object.assign(h.terminal.buffer.active, { cursorX: text.length, getLine: () => bufferLine(Array.from(text)) }); + h.selection(2); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + const marker = h.screen.children[0]; + expect(marker.style.display).toBe(text === 'xhello' ? 'block' : 'none'); + if (text === 'xhello') expect([marker.style.left, marker.style.top]).toEqual(['24px', '32px']); + dispose(); + }); + + it('requires a transaction sink and leaves unsupported xterm internals untouched', () => { + const h = harness(); + h.owner.destroy(); + expect(h.api.create({ terminal: h.terminal })).toBeNull(); + expect(h.textarea.count()).toBe(0); + delete h.helper._compositionView; + expect(h.api.create({ terminal: h.terminal, sendTransaction() {} })).toBeNull(); + const screenReader = harness('direct', { screenReaderMode: true }); + expect(screenReader.owner).toBeNull(); + }); + + it('stands down xterm text producers without canceling native input', () => { + const h = harness(); + expect(h.core._inputEvent()).toBe(false); + h.helper._handleAnyTextareaChanges(); + h.helper._finalizeComposition(); + expect(h.rawProducer).not.toHaveBeenCalled(); + h.tick(); + h.bytes([]); + expect(h.silent('input').defaultPrevented).toBe(false); + }); + + it('clears the pending dead key on committed native text without emitting xterm data', () => { + const h = harness(); + h.core._unprocessedDeadKey = true; + expect(h.core._inputEvent({ data: 'é', inputType: 'insertText' })).toBe(false); + expect(h.core._unprocessedDeadKey).toBe(false); + expect(h.rawProducer).not.toHaveBeenCalled(); + h.tick(); + h.bytes([]); + }); + + it('notifies every settled edit, deletion-only/unchanged composition, and reset', () => { + const h = harness(); + h.type('ab'); + expect(h.notifications.at(-1)).toEqual({ inserted: 'ab', deleted: 0, composition: false }); + h.begin(); + h.edit(null, undefined, 'deleteContentBackward', true); + h.end(); + h.tick(); + expect(h.transactions.at(-1)).toEqual([DEL]); + expect(h.notifications.at(-1)).toEqual({ inserted: '', deleted: 1, composition: true }); + h.begin(); + h.end(); + h.tick(); + expect(h.notifications.at(-1)).toEqual({ inserted: '', deleted: 0, composition: true }); + h.owner.reset('session'); + expect(h.notifications.at(-1)).toEqual({ inserted: '', deleted: 0, composition: false }); + expect(h.owner.state().composing).toBe(false); + }); + + it('settles a completed composition synchronously before Enter and cancels stale work on reset', () => { + const h = harness(); + h.begin(); + h.edit('字', undefined, 'insertCompositionText', true); + h.end(); + h.enter(); + h.bytes(['字', '\r']); + expect(h.notifications).toContainEqual({ inserted: '字', deleted: 0, composition: true }); + h.begin(); + h.owner.reset('session'); + h.textarea.fire('compositionend'); + h.tick(); + h.bytes(['字', '\r']); + expect(h.owner.state().synced).toBe(''); + }); + + it('preserves the single transaction and baseline when hooks throw', () => { + const h = harness('direct', { + owner: { + sendTransaction() { + throw new Error('sink'); + }, + onTransaction() { + throw new Error('preview'); + }, + onCaret() { + throw new Error('marker'); + }, + }, + }); + expect(() => h.edit('hello')).not.toThrow(); + expect(h.owner.state().synced).toBe('hello'); + h.selection(2); + expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 }); + expect(h.owner.state().invalidated).toBe(true); + expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('sendTransaction'); + expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('onTransaction'); + }); + + it.each(['pre-wrap', 'nowrap'])('restores prior whitespace value and important priority (%s)', (value) => { + const h = harness('direct', { whitespace: value, priority: 'important' }); + expect(h.textarea.style.getPropertyValue('white-space')).toBe('pre'); + h.owner.destroy(); + expect(h.textarea.properties.get('white-space')).toEqual({ value, priority: 'important' }); + }); + + it('quarantines foreign input even if the copied text equals the owned baseline and has no beforeinput', () => { + const h = harness(); + h.type('hello'); + h.clearSent(); + h.terminal.element.fire('contextmenu'); + h.textarea.fire('input', { data: 'hello' }); + h.bytes([]); + expect(h.textarea.value).toBe(''); + h.type('x'); + h.bytes(['x']); + expect(h.value()).toBe('hellox'); + }); + + it('retires pending Copy restoration on reset and destroy', () => { + const h = harness(); + h.type('hello'); + h.terminal.element.fire('contextmenu'); + h.textarea.value = 'clipboard'; + h.document.fire('copy'); + h.owner.reset('boundary'); + h.tick(); + expect(h.textarea.value).toBe(''); + h.type('x'); + h.terminal.element.fire('contextmenu'); + h.textarea.value = 'clipboard'; + h.document.fire('copy'); + h.owner.destroy(); + h.tick(); + expect(h.textarea.value).toBe('clipboard'); + }); + + it('positions from an overlay anchor, hides explicitly or on anchor failure, and defaults only on null/undefined', () => { + const h = harness(); + h.type('hello'); + h.selection(2); + let anchor: { col: number; row: number } | 'hide' | null | undefined = { col: 8, row: 3 }; + let fail = false; + let layout = () => {}; + const unsubscribe = vi.fn(); + const dispose = h.api.attachCaretMarker(h.terminal, h.owner, { + anchor(caret) { + expect(caret).toMatchObject({ visible: true, text: 'hello', offset: 2 }); + if (fail) throw new Error('layout'); + return anchor; + }, + subscribe(callback: () => void) { + layout = callback; + return unsubscribe; + }, + }); + const marker = h.screen.children[0]; + expect([marker.style.left, marker.style.top]).toEqual(['64px', '48px']); + anchor = 'hide'; + layout(); + expect(marker.style.display).toBe('none'); + for (const fallback of [null, undefined]) { + anchor = fallback; + layout(); + expect(marker.style.display).toBe('block'); + expect(marker.style.left).toBe('16px'); + } + fail = true; + layout(); + expect(marker.style.display).toBe('none'); + dispose(); + dispose(); + expect(unsubscribe).toHaveBeenCalledOnce(); + expect(h.document.activeElement).toBe(h.textarea); + }); + + it('accounts for scrolling and hides when dimensions are absent or the owner is destroyed', () => { + const h = harness(); + h.type('hello'); + h.selection(2); + h.terminal.buffer.active.baseY = 3; + h.terminal.buffer.active.viewportY = 2; + const dispose = h.api.attachCaretMarker(h.terminal, h.owner); + const marker = h.screen.children[0]; + expect(marker.style.top).toBe('48px'); + const dimensions = h.core._renderService.dimensions; + h.core._renderService.dimensions = null; + for (const callback of h.renders) callback(); + expect(marker.style.display).toBe('none'); + h.core._renderService.dimensions = dimensions; + h.owner.destroy(); + expect(marker.style.display).toBe('none'); + dispose(); + }); + + it('uses precisely the preview platform predicate and fails closed before that dependency loads', () => { + const h = harness(); + expect(h.api.isSupported()).toBe(true); + for (const navigator of [ + { userAgent: 'Android AppleWebKit', maxTouchPoints: 5 }, + { userAgent: 'iPhone AppleWebKit', maxTouchPoints: 0 }, + { userAgent: 'iPhone Gecko', maxTouchPoints: 5 }, + ]) { + h.exposed.navigator = navigator; + expect(h.api.isSupported()).toBe(false); + } + h.exposed.navigator = { userAgent: 'Macintosh AppleWebKit', platform: 'MacIntel', maxTouchPoints: 5 }; + expect(h.api.isSupported()).toBe(true); + delete h.exposed.MobileImePreview; + expect(h.api.isSupported()).toBe(false); + }); +}); diff --git a/test/terminal-keycode229-recovery.browser.test.ts b/test/terminal-keycode229-recovery.browser.test.ts index e0883b65..1daab852 100644 --- a/test/terminal-keycode229-recovery.browser.test.ts +++ b/test/terminal-keycode229-recovery.browser.test.ts @@ -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 = ''; diff --git a/test/terminal-keycode229-recovery.test.ts b/test/terminal-keycode229-recovery.test.ts index bf029e36..7f66db40 100644 --- a/test/terminal-keycode229-recovery.test.ts +++ b/test/terminal-keycode229-recovery.test.ts @@ -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) => 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' }); }); }); diff --git a/test/terminal-tile-input.test.ts b/test/terminal-tile-input.test.ts index ec262d72..0b3ebf49 100644 --- a/test/terminal-tile-input.test.ts +++ b/test/terminal-tile-input.test.ts @@ -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 & { _pendingDeliveries: Map>; @@ -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'); + }); + } +}); diff --git a/test/tile-grid-shortcuts.test.ts b/test/tile-grid-shortcuts.test.ts index 7abbaed6..15654d08 100644 --- a/test/tile-grid-shortcuts.test.ts +++ b/test/tile-grid-shortcuts.test.ts @@ -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); }); diff --git a/test/toolbar-attach.test.ts b/test/toolbar-attach.test.ts index 91c9a652..76caa877 100644 --- a/test/toolbar-attach.test.ts +++ b/test/toolbar-attach.test.ts @@ -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(); diff --git a/test/voice-input-target.test.ts b/test/voice-input-target.test.ts index f33fb21e..5555da67 100644 --- a/test/voice-input-target.test.ts +++ b/test/voice-input-target.test.ts @@ -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).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 }).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 }).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 }).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 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