Skip to content

Fix #1883: send mobile keyboard replaces to the PTY as DELs plus new text - #1884

Merged
waleedkadous merged 12 commits into
mainfrom
builder/bugfix-1883
Nov 9, 2026
Merged

waleedkadous merged 12 commits into
mainfrom
builder/bugfix-1883

Conversation

@waleedkadous

@waleedkadous waleedkadous commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On a phone, accepting a keyboard suggestion in the dashboard terminal sent the partial word and the preceding clause to the PTY again. On touch devices the Terminal now sends every soft-keyboard edit as a replace: DELs for the text being replaced, then the new text. The desktop path is unchanged.

Fixes #1883

Root Cause

The root cause is partly different from what the issue describes (correction posted on #1883). xterm.js keeps everything typed since the last Enter in its hidden textarea. A mobile keyboard's autocomplete, autocorrect and smart punctuation edit that text in place. xterm's textarea handlers assume the textarea only grows by appends:

  • _handleAnyTextareaChanges (keydown 229, outside a composition) sends newValue.replace(oldValue, ''). Once the keyboard has edited text it already committed, oldValue is no longer a substring, so the whole textarea is resent. This is the repeated clause in samples 1 and 3.
  • _finalizeComposition sends value.substring(start) with start recorded at the end of the value. When the keyboard recomposes a word that starts earlier, the result is a misaligned tail (ciecu plus a fragment of circumstances).

The #253/#517 guard only drops exact repeats, so none of this was caught.

Fix

  • apps/web/src/lib/imeInput.ts:
    • reconcileComposition(sent, committed) is a pure function that returns DELs for the diverging tail, then the new text. It counts code points, so an emoji takes one DEL.
    • TextareaMirror tracks what the PTY holds of the textarea. Two floors bound the DELs. A replace never reaches back past other input (a key, a virtual key, a paste), because its DELs would hit that input. Text that never reached the PTY (the context-menu selection xterm puts in the textarea) is never deleted at all. Only the keyboard's backspace still deletes past other input, at the cursor as stock xterm does. A cut, drag or undo of hidden textarea text that would reach back past it fails loud instead.
    • attachImeInput keeps composition and input events away from xterm's textarea listeners (container capture phase) and sends each edit through term.input.
  • Terminal.tsx:
    • The bridge exists only when (pointer: coarse). It owns keydown 229 through the custom key handler.
    • Its edits bypass the exact-dup guard; otherwise fast double letters would drop.
    • Every other onData payload that is actually sent (keys, paste, sticky modifiers) rebases the mirror. Data dropped by the socket check, the dedup guard or the initial-phase filter does not. Neither do terminal replies (DA, CPR, DECRPM): xterm answers a TUI's queries through onData, and those three are now skipped using the same regexes as the initial-phase filter, shared as stripTerminalReplies. Moving the full server reply table into codev-types is follow-up Share the terminal-reply table between the server gate and the web client (codev-types) #1885.
  • VirtualKeyboard.tsx: Esc and Tab go straight to the WebSocket, so they report back (onKeySent) and rebase the mirror, but only when the socket actually took them.
  • Sticky modifiers: a soft-keyboard character that Cmd swallows (copy, or paste with an empty or denied clipboard), or that Ctrl turns into a control character, is marked as never sent. Nothing typed before it can be deleted or replaced, since the line's state after a control character is unknown.
  • Every textarea edit syncs, including cut, drag, drop, yank and undo/redo (stock xterm never sent those). A cut of sent text deletes it on the PTY; one that reaches back past other input fails loud. A paste is the only exception, since xterm sends it.
  • Desync fails loud. The bridge logs [Terminal IME #1883] … with console.error and resyncs from textarea.value in two cases: the textarea changed outside an input event, or an edit replaced text sent before other terminal input (that text cannot be retracted). An edit the closed socket could not take (a reconnect) logs console.warn instead, so console.error stays meaningful. It never deletes text the PTY didn't get from the textarea, and never resends text already sent. The log carries lengths only, never the command line.
  • xterm clears the textarea on blur (keyboard dismissed). The bridge follows that clear instead of reporting it as a desync.
  • The bridge also handles two things it found along the way:
    • xterm's paste handler doesn't preventDefault, so the browser also inserts the clipboard into the textarea. That insertFromPaste is not resent, and it is taken as already on the PTY, so autocorrecting pasted text replaces it (teh → the, not tehthe). Only the last line of a multi-line paste is editable.
    • With xterm's composition sizing bypassed, a 0×0 textarea made Blink drop the caret to 0, so the bridge gives the textarea a 1px minimum.

Behaviour change for CJK input on touch devices: xterm's composition overlay never activates. Intermediate composing text (kana) streams to the PTY as it is typed, and is retracted with DELs when the IME converts it (kanji). This converges to the right bytes in a line editor, but it has not been tried with a real CJK IME on a device. The same applies to the alternate screen (vim normal mode, less, fzf). There, streamed composing text and the DELs that retract it act as commands, not text. Stock xterm also mangled autocorrect there (whole-textarea resends), but whether to bypass the bridge on the alternate screen, and how to treat CJK composition, is follow-up #1887.

Deviation from the issue's prescription (approved by the architect): sync is live per input event rather than deferred to compositionend, and it covers non-composition edits, because that is where the clause repeat actually comes from.

Test Plan

  • Regression test, real browser: apps/web/playwright/ime-replace.spec.ts (new pnpm test:browser, new CI job web-browser). The real xterm.js and the real Terminal run in Chromium. Keyboard edits are driven through Chromium's own IME pipeline via CDP (Input.imeSetComposition with replacement ranges, Input.insertText), against a fake PTY socket that applies DEL like a line editor.

    • On pre-fix code, 5 of 6 mobile scenarios fail with the samples' signatures:
      • …spoke what have you done since we last spoke.
      • check afaincheck again.
      • ciecumstances
      • a lost iOS replacement
    • With the fix, all 11 pass, also under --repeat-each=3. They include a desktop control (frames byte-identical to stock) and two guards added after review: soft backspace (keydown 229 + deleteContentBackward), blur then refocus with no desync alarm, and (after the integration review) a real TUI query: the fake PTY sends ESC[6n mid-typing, real xterm answers through onData, and a later autocorrect still replaces; and a real native paste (a CDP paste editing command, with clipboard permission) followed by autocorrecting the pasted word. That test fails if the mirror's paste bookkeeping ran after the browser's insert, which settles a review question about event order in Chromium. Without the blur handling, the latter fails on real xterm with expectedLength: 6, actualLength: 0.
  • Component tests (jsdom): Terminal.ime-replace.test.tsx covers:

    • Enter, Backspace, arrows, sticky Ctrl-C, paste and virtual Esc/Tab;
    • an iPad hardware keyboard, and desktop unchanged;
    • the loud desync;
    • after review: soft backspace right after a virtual Tab, and keyboard dismissal (blur);
    • after the integration review: a steady-state CPR reply, and a DA reply filtered during replay, neither stopping a later autocorrect (both fail on the previous commit); a key sent alongside a reply still counts. Also: soft-keyboard Cmd-C and Cmd-V swallowing their character, and a virtual Tab dropped by a closed socket (all three fail on the previous commit).

    Of the original 11, 9 fail on pre-fix Terminal.tsx; the 2 that pass are the must-not-change controls (iPad, desktop).

  • Unit tests: imeInput.test.ts covers reconcileComposition with the issue's three samples decomposed, plus append, last-word replace, mid-sentence replace, whole-value re-emit, empty commit and emoji. It also covers the mirror (floors, paste then autocorrect, multi-line paste, divergence) and the bridge, including cut, undo/redo, drop, long-press backspace and swallowed edits (41 tests).

  • Build and tsc -b pass. apps/web now type-checks its Playwright harness (tsconfig.json include, pnpm check-types, a step in the web-browser CI job). packages/codev 7229 tests pass.

  • Manual on a real phone (owner): type a sentence on Android Chrome and on iOS Safari, accepting at least two suggestions, and confirm it arrives once with no fragments. I could only emulate.

Notes:

…text

A soft keyboard's autocomplete, autocorrect and smart punctuation edit text
already committed in xterm's hidden textarea. xterm's textarea handlers
assume append-only edits: on keydown 229 _handleAnyTextareaChanges resends
the whole textarea once the old value is no longer a substring, and
compositionend sends a tail misaligned with a recomposed word. The PTY got
the partial word and the preceding clause again.

On coarse-pointer devices the Terminal now owns IME text: an IME bridge
keeps composition/input events and keydown 229 away from xterm and sends
each textarea edit as reconcileComposition(mirror, value). A mirror floor
stops any DEL from reaching text that reached the PTY another way (keys,
paste, sticky modifiers, virtual Esc/Tab). A desync logs
[Terminal IME #1883] and resyncs from textarea.value. Desktop is unchanged.

Tests: unit (reconcileComposition with the issue's samples, mirror,
bridge); jsdom component tests for Enter, Backspace, arrows, sticky Ctrl-C,
paste, virtual keys, an iPad hardware keyboard and desktop; a Playwright
spec driving Chromium's IME pipeline against the real xterm.js and
Terminal, which fails on the pre-fix code with the samples' signatures. A
new CI job runs it.
… on unretractable replaces

Addresses the PR review:
- Follow xterm's textarea clear on blur, so dismissing the keyboard no longer trips the desync alarm.
- Split the mirror floor in two. A replace never reaches back past other input, and text that never reached the PTY is never deleted. A soft backspace after a virtual key now deletes, where before it sent nothing.
- Accept the browser's paste insert as already on the PTY (last line only), so autocorrecting pasted text replaces it.
- Log a replace that cannot be retracted. Log lengths only, never the command line.
- Add soft-backspace and blur tests at the unit, component and browser levels.
@waleedkadous

Copy link
Copy Markdown
Contributor Author

Excellent work. The reproduction through Chromium's real IME path, the two-floor mirror, and the fail-loud resync are exactly the shape I hoped for, and every condition I set has a named test. Thank you.

Integration review (3-way): gemini APPROVE, codex REQUEST_CHANGES, claude REQUEST_CHANGES. Both change requests land on the same spot, and I agree with them. I would like three changes before merge:

1. Rebase the mirror only for input that actually reached the PTY. In Terminal.tsx's onData, noteForeignInput() runs before the socket check, before the #517 dedup drop, and before the initialPhase reply filter, so dropped data still raises replaceFloor. Codex traced a filtered DA reply during replay doing exactly that. And in steady state the three reply regexes are off entirely, so a CPR or DECRPM landing mid-typing raises the floor and the next autocorrect re-creates the #1883 duplicate, on phone plus TUI, which is the environment we care most about. Fix: move the noteForeignInput() call to after every drop point, and skip it for payloads matching the three reply regexes already inline at the initialPhase filter. That answers your (a)/(b)/(c) question: neither the shared-table move nor xterm internals; reuse the inline regexes now, and file the follow-up to move the reply table into codev-types so the server gate, the initialPhase filter and this skip share one source.

2. Edits that change the textarea without reaching the PTY must not detach silently. deleteByCut, deleteByDrag, drop, yank and history undo/redo currently detach, so cutting already-sent text leaves the line permanently divergent with no alarm. Either sync them like any other edit (a cut of sent text is a delete, and the mirror can express it) or alarm so it is visible.

3. Type-check the Playwright harness. packages/artifact-canvas/tsconfig.json already includes its playwright directory, so there is a closer precedent than __tests__. Include apps/web/playwright/** in a no-emit check.

Smaller, your call: an expected closed-socket during reconnect should not share console.error severity with a genuine desync; the PR body should state the CJK behaviour change on touch (composition overlay never activates, kana stream and retract); a one-line note in codev/resources/arch.md on the invariant that every non-onData PTY writer must call noteForeignInput(), since the next virtual key added will otherwise break the mirror; onKeySent could be a useCallback.

Please also file the #517 iPad key-repeat follow-up you identified. The real-phone pass stays the acceptance gate; the owner has been asked which device produced the samples.

…PTY; sync every textarea edit

Integration review changes:
- onData: call noteForeignInput() after every drop point (closed socket, dedup, initial-phase filter, sticky Cmd-C/Cmd-V), and skip payloads that are only terminal replies (DA, CPR, DECRPM). The three regexes are now shared as stripTerminalReplies with the initial-phase filter.
- Sync cut, drag, drop, yank and undo/redo like any other edit instead of detaching silently. Only paste stays special.
- Type-check the Playwright harness: tsconfig include, check-types script, and a web-browser CI step.
- Log a closed-socket edit with console.warn, keeping console.error for real desyncs.
- Make onKeySent a useCallback, and note the noteForeignInput() invariant in arch.md.
- Tests: reply skip (jsdom and real xterm via ESC[6n), cut/undo/drop. The phone afterEach now unmounts before asserting. The desktop control types spaces as real keys.
…ped virtual keys and bulk deletes

Review changes (codex round 3):
- Sticky modifiers: a soft-keyboard character Cmd swallows, or Ctrl turns into a control character, is marked as never sent (noteSwallowedEdit). Backspacing it no longer sends a DEL into real text.
- VirtualKeyboard: sendRawKey reports whether it sent; onKeySent fires only then.
- TextareaMirror: only a backspace-type delete may delete past other input. A cut, drag or undo that would fails loud.
- Playwright: a real native paste (CDP paste editing command), confirming in Chromium that the mirror's paste bookkeeping runs before the browser's insert, with autocorrect of the pasted word.
@waleedkadous

Copy link
Copy Markdown
Contributor Author

All three changes verified at head: the mirror rebase now sits after the socket, dedup, reply-filter and modifier drop points and skips pure terminal replies; cut/drag/undo edits sync or fail loud; the Playwright harness is type-checked in CI. The three extra bugs codex found in round 3 are fixed with tests that fail on the prior head, and the paste-ordering claim was disproved with a real-paste test rather than argued. Follow-ups #1885, #1886 and #1887 cover the rest. Thank you for a thorough round.

My integration review is satisfied. Codex's remaining request is the real-device pass, which is the owner's acceptance gate; merge waits on that word.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mobile terminal: autocomplete replacement re-inserts the partial word and the preceding clause (IME replace events reach the PTY as keystrokes)

1 participant