From cda5d96451701dd2fd690f1593a8b4a225918a84 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:16:13 +0100 Subject: [PATCH] fix(web): exact iOS caret, review fixes and round-eight items (#830) Toolbar Enter spends one-shot Ctrl; Backspace finds the last grapheme with Segments.containing(); accessory Shift+Tab keeps the draft like a typed one. Pass the captured session to Compose uploads, voice compose and held CJK drafts; clear Ctrl on deletion-only native edits; path picker clears predictions. Clear xterm dead-key state on native commits; restore a borrowed clipboard field before classifying a key; overlay removeChar spans the pending/flushed boundary. Place the trackpad caret from the overlay layout (getInputAnchor, committedText) or validated xterm cells, hiding when unproven; no end-minus-width arithmetic. Grapheme-aware replay Backspace; docs, README rows, changeset and comment updates. --- .changeset/830-ios-keyboard.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- docs/ios-native-input.md | 11 +- packages/xterm-zerolag-input/README.md | 2 + .../src/overlay-renderer.ts | 16 +- .../src/zerolag-input-addon.ts | 116 ++++++- .../test/overlay-renderer.test.ts | 23 ++ .../test/zerolag-input-addon.test.ts | 190 +++++++++++- scripts/prepare-test-vendor.mjs | 2 +- src/web/public/input-cjk.js | 23 +- src/web/public/keyboard-accessory.js | 14 +- src/web/public/terminal-ios-native-input.js | 163 +++++++--- src/web/public/terminal-tile.js | 2 + src/web/public/terminal-ui.js | 18 +- src/web/public/voice-input.js | 5 +- test/fixtures/ios-native-replay.js | 67 ++++- test/input-cjk-hold.test.ts | 32 +- test/ios-native-input.browser.test.ts | 88 +++++- test/mobile-prompt-composer.test.ts | 7 +- test/path-picker-ui.test.ts | 18 ++ test/terminal-input-fifo.test.ts | 88 +++++- test/terminal-ios-native-input.test.ts | 282 ++++++++++++++++-- test/terminal-tile-input.test.ts | 24 +- test/voice-input-target.test.ts | 37 +++ test/xterm-private-api.test.ts | 8 +- 26 files changed, 1072 insertions(+), 170 deletions(-) diff --git a/.changeset/830-ios-keyboard.md b/.changeset/830-ios-keyboard.md index f5464ffa..4ef4cd9b 100644 --- a/.changeset/830-ios-keyboard.md +++ b/.changeset/830-ios-keyboard.md @@ -3,4 +3,4 @@ '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 against the visible input, including emoji-safe deletion. +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 d8561361..6a66b3c1 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 diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 2c145cac..b10baf03 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. **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 in order into `_enqueueReliableInput`. ⚠️ 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`). +**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 diff --git a/docs/ios-native-input.md b/docs/ios-native-input.md index 64e5e677..24011e9d 100644 --- a/docs/ios-native-input.md +++ b/docs/ios-native-input.md @@ -2,7 +2,14 @@ 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. With local echo, caret geometry comes from the overlay's input-end anchor, and unavailable geometry hides the marker. +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 }`, with projected text and a UTF-16 offset into that projection (CRLF and LF each become one space). 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. After a native text change it also hides until the next `onWriteParsed`, rather than mistaking old output for a delivered edit. + +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. @@ -13,7 +20,7 @@ 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; the 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 `getInputEndAnchor` before running these tests. +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. diff --git a/packages/xterm-zerolag-input/README.md b/packages/xterm-zerolag-input/README.md index 12e535dd..0a00d7d8 100644 --- a/packages/xterm-zerolag-input/README.md +++ b/packages/xterm-zerolag-input/README.md @@ -263,6 +263,7 @@ 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 @@ -278,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/overlay-renderer.ts b/packages/xterm-zerolag-input/src/overlay-renderer.ts index c6b82446..e55529f3 100644 --- a/packages/xterm-zerolag-input/src/overlay-renderer.ts +++ b/packages/xterm-zerolag-input/src/overlay-renderer.ts @@ -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): InputEndAnchor | null { +export function renderOverlay(container: HTMLDivElement, params: RenderParams): OverlayPlacement { const { lines, compositionStart, @@ -252,7 +259,12 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams): } container.style.display = ''; - return lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 }; + return { + end: lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 }, + firstVisible, + topRow, + keepsPromptLine, + }; } /** diff --git a/packages/xterm-zerolag-input/src/zerolag-input-addon.ts b/packages/xterm-zerolag-input/src/zerolag-input-addon.ts index 16b8498a..fca8c07a 100644 --- a/packages/xterm-zerolag-input/src/zerolag-input-addon.ts +++ b/packages/xterm-zerolag-input/src/zerolag-input-addon.ts @@ -19,8 +19,27 @@ 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): Iterable<{ segment: string }>; + segment(input: string): { containing(index: number): { segment: string } | undefined }; }; const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => { @@ -36,15 +55,15 @@ const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => { } })(); -/** UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string). */ +/** + * 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 (GRAPHEME_SEGMENTER) { - let width = 1; - for (const { segment } of GRAPHEME_SEGMENTER.segment(text)) { - width = segment.length; - } - return width; - } + 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); @@ -110,6 +129,7 @@ export class ZerolagInputAddon implements XtermAddon { private _lastRenderKey = ''; private _lastPromptPos: PromptPosition | null = null; private _inputEndAnchor: InputEndAnchor | null = null; + private _layout: InputLayout | null = null; private _layoutListeners = new Set<() => void>(); // Font cache @@ -166,6 +186,7 @@ export class ZerolagInputAddon implements XtermAddon { if (!promptRowInViewport(this._terminal!)) { this._overlay!.style.display = 'none'; this._inputEndAnchor = null; + this._layout = null; this._notifyLayout(); if (this._scrollTimer) { clearTimeout(this._scrollTimer); @@ -237,7 +258,9 @@ export class ZerolagInputAddon implements XtermAddon { * 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'` * @@ -245,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 @@ -257,13 +280,21 @@ export class ZerolagInputAddon implements XtermAddon { const droppedComposition = this._composition.length > 0; this._composition = ''; if (this._pendingText.length > 0) { - this._pendingText = this._pendingText.slice(0, -lastGraphemeWidth(this._pendingText)); + 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'; + return flushedWidth > 0 ? 'flushed' : 'pending'; } // Both empty — try detecting text already on the prompt line @@ -353,6 +384,29 @@ export class ZerolagInputAddon implements XtermAddon { 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); @@ -636,6 +690,7 @@ export class ZerolagInputAddon implements XtermAddon { this._overlay.innerHTML = ''; this._overlay.style.display = 'none'; this._inputEndAnchor = null; + this._layout = null; this._notifyLayout(); } @@ -700,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; @@ -721,37 +777,51 @@ export class ZerolagInputAddon implements XtermAddon { 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; - this._inputEndAnchor = renderOverlay(this._overlay, { + const placement = renderOverlay(this._overlay, { lines, compositionStart: this._composition ? compositionStart : undefined, startCol, @@ -767,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. @@ -775,7 +856,10 @@ export class ZerolagInputAddon implements XtermAddon { this._overlay.style.display = 'none'; } } finally { - if (this._overlay.style.display === 'none') this._inputEndAnchor = null; + 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 77b6eb9c..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,4 +1,4 @@ -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'; @@ -103,6 +103,28 @@ describe('ZerolagInputAddon', () => { 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😀'); @@ -141,6 +163,34 @@ describe('ZerolagInputAddon', () => { 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; @@ -1051,4 +1101,142 @@ describe('input end anchor and layout subscriptions', () => { 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/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/public/input-cjk.js b/src/web/public/input-cjk.js index 4d2038b0..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 * @@ -91,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 = {}; @@ -690,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; } @@ -785,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 diff --git a/src/web/public/keyboard-accessory.js b/src/web/public/keyboard-accessory.js index 5fed0c68..b3b93bc0 100644 --- a/src/web/public/keyboard-accessory.js +++ b/src/web/public/keyboard-accessory.js @@ -1231,7 +1231,9 @@ const KeyboardAccessoryBar = { 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'); @@ -1401,9 +1403,10 @@ const KeyboardAccessoryBar = { /** 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) { - const sessionId = this._prepareInput(undefined, 'accessory-key', { flushEcho: true }); + * 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(); app._enqueueInput(sessionId, [{ write: escapeSequence }]); @@ -1422,6 +1425,7 @@ const KeyboardAccessoryBar = { directoriesOnly: false, onSelect: (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); @@ -1637,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 diff --git a/src/web/public/terminal-ios-native-input.js b/src/web/public/terminal-ios-native-input.js index f4bd5c17..4ca2210a 100644 --- a/src/web/public/terminal-ios-native-input.js +++ b/src/web/public/terminal-ios-native-input.js @@ -35,8 +35,8 @@ function editBetween(previous, next) { // A pure append (including a combining mark or tone typed onto the last letter) - // is sent as-is, as on master: re-typing the extended cluster would make a - // code-point line editor (zsh) double the base 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); @@ -213,29 +213,26 @@ const caret = guard( 'caret', function () { - const value = Array.from(project(textarea.value)); - const index = Array.from(project(textarea.value.slice(0, textarea.selectionEnd))).length; - const tail = value.slice(index).join(''); - let cellsFromEnd = value.length - index; - const unicode = core.unicodeService; - if (unicode && typeof unicode.getStringCellWidth === 'function') { - try { - cellsFromEnd = unicode.getStringCellWidth(tail); - } catch (_) { - /* Older xterm builds use the code-point fallback. */ - } - } + 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 && - index < value.length, - cellsFromEnd, + 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, cellsFromEnd: 0 } + { visible: false, text: '', offset: 0, generation: 0 } ); let previousCaret; notifyCaret = function () { @@ -243,7 +240,9 @@ if ( previousCaret && previousCaret.visible === current.visible && - previousCaret.cellsFromEnd === current.cellsFromEnd + previousCaret.text === current.text && + previousCaret.offset === current.offset && + previousCaret.generation === current.generation ) return; previousCaret = current; @@ -352,6 +351,7 @@ sendTransaction(ops); } catch (error) { record({ type: 'error', hook: 'sendTransaction', error }); + invalidated = true; } } // Empty/deletion-only compositions still settle the visual preview. @@ -389,6 +389,7 @@ 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(); @@ -418,7 +419,8 @@ target.addEventListener(type, listener, true); } - patch(core, '_inputEvent', function () { + patch(core, '_inputEvent', function (ev) { + if (ev && ev.data && ev.inputType === 'insertText') core._unprocessedDeadKey = false; return false; }); patch(helper, '_handleAnyTextareaChanges', schedule); @@ -499,6 +501,7 @@ direction: textarea.selectionDirection, synced, }; + notifyCaret(); }, terminal.element ); @@ -557,20 +560,80 @@ } } - // This is a visual projection only: native caret changes never become keys. - // `options.anchor()` returns the viewport cell `{col, row}` where the VISIBLE line - // ends (where the next typed character would appear), 'hide' to hide the - // marker, or null/undefined to use xterm's cursor. A throwing anchor hides it. Codeman's local echo shows unsent text in an overlay while xterm's own - // cursor stays at the prompt, so the overlay must supply that anchor. Without an - // anchor the xterm cursor is used, which is right whenever every byte reached - // the PTY (local echo off, tiles). - // `options.subscribe(callback)` returns a disposer and is used to reposition - // when the anchor moves without an xterm render (overlay repaint). + // 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; @@ -586,6 +649,7 @@ 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'); @@ -597,41 +661,50 @@ const core = terminal._core; const dimensions = core && core._renderService && core._renderService.dimensions; const cell = dimensions && dimensions.css && dimensions.css.cell; - const buffer = terminal.buffer.active; if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) { marker.style.display = 'none'; return; } - let end = null; + let target = null; if (anchor) { try { - end = anchor(); + target = anchor(caret); } catch (_) { - end = 'hide'; + target = 'hide'; } } - if (end === '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; } - if (end == null) end = { col: buffer.cursorX, row: buffer.cursorY + buffer.baseY - buffer.viewportY }; - let column = end.col - caret.cellsFromEnd; - let row = end.row; - if (column < 0) { - const rows = Math.ceil(-column / terminal.cols); - column += rows * terminal.cols; - row -= rows; - } - marker.style.display = row < 0 || row >= terminal.rows ? 'none' : 'block'; - marker.style.left = column * cell.width + 'px'; - marker.style.top = row * cell.height + 'px'; + 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(position)); + 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); diff --git a/src/web/public/terminal-tile.js b/src/web/public/terminal-tile.js index 5b7acafc..d9e4a1a8 100644 --- a/src/web/public/terminal-tile.js +++ b/src/web/public/terminal-tile.js @@ -660,6 +660,7 @@ 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; } @@ -678,6 +679,7 @@ // 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. diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 0984e13e..a48484cc 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -766,7 +766,7 @@ Object.assign(CodemanApp.prototype, { }); if (this._iosNativeInput) { this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, { - anchor: () => this._nativeInputAnchor(), + anchor: (caret) => this._nativeInputCaretAnchor(caret), subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback), }); return; @@ -787,11 +787,16 @@ Object.assign(CodemanApp.prototype, { } }, - _nativeInputAnchor() { + _nativeInputCaretAnchor(caret) { const overlay = this._localEchoOverlay; - if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(this.activeSessionId) && - (overlay?.pendingText || overlay?.getFlushed?.().count)) { - return overlay.getInputEndAnchor?.() || 'hide'; + 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; }, @@ -865,6 +870,8 @@ Object.assign(CodemanApp.prototype, { 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; @@ -887,6 +894,7 @@ Object.assign(CodemanApp.prototype, { 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]; diff --git a/src/web/public/voice-input.js b/src/web/public/voice-input.js index ba01dd88..40363ca3 100644 --- a/src/web/public/voice-input.js +++ b/src/web/public/voice-input.js @@ -1097,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; @@ -1216,10 +1217,10 @@ const VoiceInput = { /** Show an editable compose overlay so the user can review/edit before sending */ _showComposeOverlay(text) { - const target = this._targetSession(); 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 = `