diff --git a/.changeset/830-ios-keyboard.md b/.changeset/830-ios-keyboard.md
new file mode 100644
index 00000000..d7bb1c98
--- /dev/null
+++ b/.changeset/830-ios-keyboard.md
@@ -0,0 +1,5 @@
+---
+'aicodeman': 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.
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/ios-native-input.md b/docs/ios-native-input.md
new file mode 100644
index 00000000..6628b916
--- /dev/null
+++ b/docs/ios-native-input.md
@@ -0,0 +1,20 @@
+# 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. With local echo, caret geometry comes from the overlay's input-end anchor, and unavailable geometry hides the marker.
+
+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; 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 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 original phone cases live in `IOS_DIAG.md` in the diagnostic case repository.
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/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..c6b82446 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 ───────────────────────
@@ -102,7 +102,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): InputEndAnchor | null {
const {
lines,
compositionStart,
@@ -233,11 +233,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 +252,7 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
}
container.style.display = '';
+ return lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 };
}
/**
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..9fc0533c 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,13 @@ const DEFAULT_BG = '#0d0d0d';
const DEFAULT_FG = '#eeeeee';
const DEFAULT_CURSOR = '#e0e0e0';
+/** UTF-16 width of the final code point (one for an empty legacy flushed string). */
+function lastCodePointWidth(text: string): number {
+ 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 +84,8 @@ export class ZerolagInputAddon implements XtermAddon {
// Render cache
private _lastRenderKey = '';
private _lastPromptPos: PromptPosition | null = null;
+ private _inputEndAnchor: InputEndAnchor | null = null;
+ private _layoutListeners = new Set<() => void>();
// Font cache
private _font: FontStyle = {
@@ -130,6 +140,8 @@ export class ZerolagInputAddon implements XtermAddon {
try {
if (!promptRowInViewport(this._terminal!)) {
this._overlay!.style.display = 'none';
+ this._inputEndAnchor = null;
+ this._notifyLayout();
if (this._scrollTimer) {
clearTimeout(this._scrollTimer);
this._scrollTimer = null;
@@ -171,6 +183,7 @@ export class ZerolagInputAddon implements XtermAddon {
this._scrollViewport = null;
this._scrollHandler = null;
this._terminal = null;
+ this._layoutListeners.clear();
}
// ─── Input methods ────────────────────────────────────────────────
@@ -196,7 +209,7 @@ export class ZerolagInputAddon implements XtermAddon {
}
/**
- * Remove the last character from the overlay.
+ * Remove the last Unicode code point from the overlay.
*
* Cascade order:
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
@@ -219,7 +232,7 @@ 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);
+ this._pendingText = this._pendingText.slice(0, -lastCodePointWidth(this._pendingText));
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
this._render();
} else {
@@ -228,23 +241,13 @@ export class ZerolagInputAddon implements XtermAddon {
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';
- }
-
// 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 = lastCodePointWidth(this._flushedText);
+ this._flushedOffset -= width;
+ this._flushedText = this._flushedText.slice(0, -width);
if (this._flushedOffset > 0) {
this._render();
} else {
@@ -320,6 +323,19 @@ 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;
+ }
+
+ /** 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 +594,34 @@ 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._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
@@ -612,7 +640,7 @@ export class ZerolagInputAddon implements XtermAddon {
} else {
this._lastPromptPos = prompt;
}
- } else if (!this._lastPromptPos) {
+ } else {
this._overlay.style.display = 'none';
return;
}
@@ -658,7 +686,10 @@ 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)
@@ -695,7 +726,7 @@ export class ZerolagInputAddon implements XtermAddon {
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
- renderOverlay(this._overlay, {
+ this._inputEndAnchor = renderOverlay(this._overlay, {
lines,
compositionStart: this._composition ? compositionStart : undefined,
startCol,
@@ -718,6 +749,9 @@ export class ZerolagInputAddon implements XtermAddon {
this._overlay.innerHTML = '';
this._overlay.style.display = 'none';
}
+ } finally {
+ if (this._overlay.style.display === 'none') this._inputEndAnchor = null;
+ if (layoutChanged) this._notifyLayout();
}
}
}
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..677d0b8c 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 { 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,41 @@ 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('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);
+ });
+
it('returns false when nothing to remove', () => {
const { addon } = tracked();
expect(addon.removeChar()).toBe(false);
@@ -831,3 +867,164 @@ 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('returns null when a previously visible prompt is no longer found', () => {
+ const { addon, mock } = layoutSetup();
+ addon.appendText('abc');
+ mock.setLines(['output without a prompt']);
+ addon.rerender();
+ expect(addon.getInputEndAnchor()).toBeNull();
+ expect(addon.state.visible).toBe(false);
+ });
+
+ 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]);
+ });
+});
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/src/web/CLAUDE.md b/src/web/CLAUDE.md
index 5260666a..cacc7b86 100644
--- a/src/web/CLAUDE.md
+++ b/src/web/CLAUDE.md
@@ -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..4ebf200a 100644
--- a/src/web/public/input-cjk.js
+++ b/src/web/public/input-cjk.js
@@ -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;
@@ -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();
@@ -397,11 +414,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 +479,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 +534,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 +546,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 +558,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 +573,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 +585,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 +612,7 @@ const CjkInput = (() => {
if (_composing) return;
if (_isEffectivelyEmpty()) {
_cancelDebouncedFlush();
- _send('\x7f');
+ _send('\x7f', _targetForSend());
_resetToPhantom();
return;
}
@@ -640,6 +661,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
@@ -802,6 +832,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..ae0d1dc8 100644
--- a/src/web/public/keyboard-accessory.js
+++ b/src/web/public/keyboard-accessory.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,7 +1228,7 @@ 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');
@@ -1268,6 +1268,7 @@ const KeyboardAccessoryBar = {
this.pickPath();
break;
case 'clear-input':
+ this._prepareInput(undefined, 'accessory-clear');
app.clearTerminalInput?.();
break;
case 'dismiss':
@@ -1331,38 +1332,52 @@ 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. */
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', { flushEcho: true });
+ 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 +1395,39 @@ 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.
+ const sessionId = this._prepareInput(undefined, 'accessory-key', { 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._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 +1437,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 +1477,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 +1500,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 +1520,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
@@ -1687,10 +1709,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 +1762,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..ea176e4b
--- /dev/null
+++ b/src/web/public/terminal-ios-native-input.js
@@ -0,0 +1,624 @@
+/**
+ * @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';
+
+ function editBetween(previous, next) {
+ const a = Array.from(previous);
+ const b = Array.from(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 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. */
+ }
+ }
+ return {
+ visible:
+ !destroyed &&
+ textarea.ownerDocument.activeElement === textarea &&
+ !composing &&
+ textarea.selectionStart === textarea.selectionEnd &&
+ index < value.length,
+ cellsFromEnd,
+ };
+ },
+ { visible: false, cellsFromEnd: 0 }
+ );
+ let previousCaret;
+ notifyCaret = function () {
+ const current = caret();
+ if (
+ previousCaret &&
+ previousCaret.visible === current.visible &&
+ previousCaret.cellsFromEnd === current.cellsFromEnd
+ )
+ 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) {
+ try {
+ sendTransaction(ops);
+ } catch (error) {
+ record({ type: 'error', hook: 'sendTransaction', error });
+ }
+ }
+ // 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;
+ 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 () {
+ 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,
+ };
+ },
+ 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;
+ }
+ }
+
+ // 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).
+ function attachCaretMarker(terminal, owner, options) {
+ const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
+ const disposables = [];
+ let marker;
+ let disposed = 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;
+ 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;
+ const buffer = terminal.buffer.active;
+ if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
+ marker.style.display = 'none';
+ return;
+ }
+ let end = null;
+ if (anchor) {
+ try {
+ end = anchor();
+ } catch (_) {
+ end = 'hide';
+ }
+ }
+ if (end === 'hide') {
+ 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.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));
+ 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-tile.js b/src/web/public/terminal-tile.js
index 3d1e2e7c..93230b25 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,62 @@
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) {
+ this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
+ }
+ }
+
+ _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');
+ }
+ // 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 +1614,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..0c1a6990 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,397 @@ 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,
+ });
+ this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, {
+ anchor: () => this._nativeInputAnchor(),
+ subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback),
+ });
+ } else {
+ 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;
+ }
+ }
+ },
+
+ _nativeInputAnchor() {
+ const overlay = this._localEchoOverlay;
+ if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(this.activeSessionId) &&
+ (overlay?.pendingText || overlay?.getFlushed?.().count)) {
+ return overlay.getInputEndAnchor?.() || '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);
+ 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;
+ 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));
+ }
+ 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.setFlushed(detected.length, detected);
+ 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 +1208,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 +1354,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 +1450,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 +2114,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 +2131,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 +4408,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 +4426,14 @@ 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();
+ const shouldEnable = !!(echoEnabled && session && session.mode !== 'shell' && session.mode !== 'codex');
+ 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 +4471,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
@@ -4543,11 +4542,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 +4567,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 +4579,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 +4590,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 +4602,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 +5079,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 +5125,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 +5156,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 +5180,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');
diff --git a/src/web/public/voice-input.js b/src/web/public/voice-input.js
index 97e5dbe8..b0c9d641 100644
--- a/src/web/public/voice-input.js
+++ b/src/web/public/voice-input.js
@@ -1071,19 +1071,16 @@ 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();
}
+ const pane = app._paneForSession?.(target);
+ if (pane) app._prepareExternalInput?.(pane, 'voice-send', { flushEcho: true });
app._sendInputAsync(target, text, { useMux: true });
return Promise.resolve();
},
@@ -1113,7 +1110,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 +1161,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');
@@ -1202,6 +1214,7 @@ 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';
@@ -1219,7 +1232,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(target, 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..cc6804ce 100644
--- a/test/cjk-hold-per-device-setting.test.ts
+++ b/test/cjk-hold-per-device-setting.test.ts
@@ -182,7 +182,7 @@ describe('Send on Enter field layout and strings', () => {
// 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));
+ const body = sessionUi.slice(start, sessionUi.indexOf('submitFromToolbar()', start));
expect(body).toContain("classList.contains('cjk-input-visible')");
expect(body).toContain('CjkInput.submit?.();');
});
diff --git a/test/fixtures/ios-native-replay.js b/test/fixtures/ios-native-replay.js
new file mode 100644
index 00000000..98347b31
--- /dev/null
+++ b/test/fixtures/ios-native-replay.js
@@ -0,0 +1,153 @@
+/** @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;
+ start -= Array.from(value.slice(0, start)).pop().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/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..43c5b7b5
--- /dev/null
+++ b/test/ios-native-input.browser.test.ts
@@ -0,0 +1,392 @@
+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;
+ buffer: { active: { cursorX: number; cursorY: number } };
+ _core: {
+ _renderService: { dimensions: { css: { cell: { width: number } } } };
+ _customKeyEventHandler(event: KeyboardEvent): boolean;
+ };
+}
+interface NativeOwner {
+ reset(reason: string): void;
+}
+interface TestApp {
+ terminal: TestTerminal;
+ 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);
+ }
+
+ 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 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);"
+ );
+ const geometry = await page.evaluate(() => {
+ const app = (window as unknown as TestWindow).app;
+ const marker = app.terminal.element.querySelector('.ios-native-caret')!;
+ const cell = app.terminal._core._renderService.dimensions.css.cell;
+ const end = app._localEchoEnabled
+ ? app._localEchoOverlay.getInputEndAnchor()
+ : { col: app.terminal.buffer.active.cursorX, row: app.terminal.buffer.active.cursorY };
+ return {
+ display: marker.style.display,
+ col: parseFloat(marker.style.left) / cell.width,
+ expected: end!.col - 3,
+ };
+ });
+ expect(geometry.display).not.toBe('none');
+ expect(geometry.col).toBeCloseTo(geometry.expected, 1);
+ });
+ }
+
+ 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([]);
+ });
+
+ 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..c17565ee 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();
});
@@ -697,11 +714,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 +727,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 +738,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 +748,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 +757,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 +770,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 +833,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..875d0b27 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 };
}
@@ -730,8 +735,10 @@ describe('composer nav keys from the bar', () => {
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 +751,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 +771,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,14 +799,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(sentKeys(app._enqueueInput as ReturnType)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']);
expect(app.sendInput).not.toHaveBeenCalled();
});
});
diff --git a/test/path-picker-ui.test.ts b/test/path-picker-ui.test.ts
index 6fa30b3a..348d62ca 100644
--- a/test/path-picker-ui.test.ts
+++ b/test/path-picker-ui.test.ts
@@ -44,6 +44,13 @@ function loadKeyboardModule() {
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,
+ _localEchoOverlay: { appendText: vi.fn() },
+ _prepareExternalInput: vi.fn(),
};
const fetchMock = vi.fn(() => Promise.resolve({ ok: true }));
const context = vm.createContext({
@@ -86,10 +93,32 @@ describe('accessory Tab key', () => {
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,23 @@ 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();
+ const sendInput = vi.fn();
+ context.__mixin.sendEnterKey.call({ submitFromToolbar, sendInput });
+ expect(submitFromToolbar).toHaveBeenCalledOnce();
+ expect(sendInput).not.toHaveBeenCalled();
});
});
@@ -149,10 +188,47 @@ 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._sendInputAsync).toHaveBeenCalledWith('session-1', '/mnt/d/AI/project/file.ts', { useMux: true });
expect(app.sendInput).not.toHaveBeenCalled();
});
+ 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', () => {
expect(indexSource).toContain('onclick="app.openLinkCasePathPicker()"');
expect(indexSource).toContain('id="linkCasePath"');
@@ -179,6 +255,8 @@ describe('mobile filesystem picker actions', () => {
_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');
@@ -207,17 +285,23 @@ 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(sendInput).not.toHaveBeenCalled();
expect(app._flushedOffsets.size).toBe(0);
expect(app._flushedTexts.size).toBe(0);
expect(showToast).toHaveBeenCalledWith('Input cleared', 'success');
@@ -238,6 +322,7 @@ describe('mobile filesystem picker actions', () => {
terminal: { focus: mainFocus },
sendInput,
_sendInputAsync,
+ _prepareExternalInput: vi.fn(),
_focusedPane: () => ({ terminal: { focus: tileFocus }, sessionId: 'tile-2', isPrimary: false, tile: {} }),
};
@@ -264,6 +349,7 @@ describe('mobile filesystem picker actions', () => {
_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: {} }),
@@ -288,12 +374,15 @@ describe('mobile filesystem picker actions', () => {
_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
deleted file mode 100644
index 5ffe3d14..00000000
--- a/test/shift-enter-keypress-swallowed.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// @vitest-environment node
-// Regression guard: xterm runs the custom key handler for keydown AND keypress.
-// 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.
-
-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');
-
-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'/);
- });
-});
diff --git a/test/terminal-input-fifo.test.ts b/test/terminal-input-fifo.test.ts
new file mode 100644
index 00000000..641493a9
--- /dev/null
+++ b/test/terminal-input-fifo.test.ts
@@ -0,0 +1,863 @@
+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: '',
+ 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';
+ },
+ getInputEndAnchor: 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 },
+ context: vm.Context
+) {
+ 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),
+ });
+ 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('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('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', 'voice', 'Esc', 'command', '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 === 'voice') {
+ await vm.runInContext("VoiceInput._sendToTarget('old', 'world')", context);
+ expect(wire).toEqual([
+ ['old', 'hel'],
+ ['old', 'world'],
+ ]);
+ } else if (producer === 'Esc') {
+ vm.runInContext("KeyboardAccessoryBar.sendKey('\\x1b')", context);
+ expect(wire).toEqual([
+ ['old', 'hel'],
+ ['old', '\x1b'],
+ ]);
+ } else if (producer === 'command') {
+ vm.runInContext("KeyboardAccessoryBar.sendCommand('/help')", context);
+ expect(wire).toEqual([
+ ['old', 'hel'],
+ ['old', '/help'],
+ ]);
+ vi.advanceTimersByTime(120);
+ expect(wire.at(-1)).toEqual(['old', '\r']);
+ } 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('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('hides the caret when a buffering overlay cannot supply an anchor', () => {
+ const { app } = harness();
+ expect(app._nativeInputAnchor()).toBeNull();
+ app._localEchoOverlay.pendingText = 'text';
+ expect(app._nativeInputAnchor()).toEqual({ col: 8, row: 2 });
+ app._localEchoOverlay.getInputEndAnchor = () => null;
+ expect(app._nativeInputAnchor()).toBe('hide');
+ delete app._localEchoOverlay.getInputEndAnchor;
+ expect(app._nativeInputAnchor()).toBe('hide');
+ app._echoPassthroughSessions = new Set(['old']);
+ expect(app._nativeInputAnchor()).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('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()).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('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..7ad1bd8c
--- /dev/null
+++ b/test/terminal-ios-native-input.test.ts
@@ -0,0 +1,1417 @@
+/**
+ * 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;
+ cellsFromEnd: 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?: () => { 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(): unknown;
+ _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 FakeTerminal {
+ textarea: FakeTextarea;
+ element: FakeNode;
+ _core: FakeCore;
+ cols: number;
+ rows: number;
+ buffer: { active: { cursorX: number; cursorY: number; baseY: number; viewportY: number } };
+ options: { theme: { cursor: string }; screenReaderMode: boolean };
+ onRender(callback: () => void): { dispose(): void };
+ onCursorMove(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>;
+ 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, ' ');
+const trimPoint = (value: string) => Array.from(value).slice(0, -1).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 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 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 } },
+ options: { theme: { cursor: '#fff' }, screenReaderMode: !!options.screenReaderMode },
+ onRender: (callback: () => void) => subscribe(renders, callback),
+ onCursorMove: (callback: () => void) => subscribe(moves, 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 = trimPoint(pending);
+ else line = trimPoint(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;
+ start -= Array.from(textarea.value.slice(0, start)).at(-1)!.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,
+ 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' });
+ 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');
+ },
+ ],
+ [
+ '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()).toEqual({ visible: true, cellsFromEnd: 3 });
+ 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()).toEqual({ visible: true, cellsFromEnd: 3 });
+ h.clearSent();
+ h.selection(6);
+ expect(marker.style.display).toBe('none');
+ h.bytes([]);
+ h.selection(3);
+ h.terminal.buffer.active.cursorX = 0;
+ h.terminal.buffer.active.cursorY = 1;
+ for (const callback of h.renders) callback();
+ expect([marker.style.left, marker.style.top]).toEqual(['56px', '0px']);
+ h.terminal.buffer.active.cursorY = 0;
+ for (const callback of h.moves) callback();
+ expect(marker.style.display).toBe('none');
+ dispose();
+ dispose();
+ expect(h.screen.children).toHaveLength(0);
+ expect(h.renders.size + h.moves.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()).toEqual({ visible: true, cellsFromEnd: 2 });
+ }
+ h.core.unicodeService.getStringCellWidth = undefined;
+ expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 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).toEqual([{ visible: true, cellsFromEnd: 3 }]);
+ 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 code-point caret',
+ (h) => {
+ h.edit('a👍\nb');
+ h.clearSent();
+ h.selection(4);
+ expect(h.owner.caret().cellsFromEnd).toBe(1);
+ h.selection(3);
+ expect(h.owner.caret().cellsFromEnd).toBe(2);
+ h.selection(1);
+ expect(h.owner.caret().cellsFromEnd).toBe(h.core.unicodeService.getStringCellWidth!('👍 b'));
+ 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()).toEqual({ visible: true, cellsFromEnd: 2 });
+ 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);
+ }
+ },
+ ],
+];
+
+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('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('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.edit('X')).not.toThrow();
+ expect(h.owner.state().synced).toBe('heXllo');
+ 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() {
+ 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(['40px', '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-tile-input.test.ts b/test/terminal-tile-input.test.ts
index ec262d72..a363851e 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,189 @@ 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 xterm-cursor marker, 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('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('does not consume Ctrl for a deletion-only transaction', async () => {
+ const native = install();
+ const app = makeApp();
+ app._enqueueInput = vi.fn();
+ const consumeCtrl = vi.fn();
+ context.KeyboardAccessoryBar = { isCtrlArmed: () => true, consumeCtrl };
+ await connectTile(app);
+ native.send(['\x7f']);
+ 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/voice-input-target.test.ts b/test/voice-input-target.test.ts
index f33fb21e..44de29f2 100644
--- a/test/voice-input-target.test.ts
+++ b/test/voice-input-target.test.ts
@@ -59,6 +59,8 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
]),
sendInput,
_sendInputAsync: sendInputAsync,
+ _enqueueInput: vi.fn(),
+ _prepareExternalInput: vi.fn(),
showToast,
terminal: { focus: vi.fn() },
_localEchoEnabled: !!opts.localEcho,
@@ -74,6 +76,7 @@ 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 context = vm.createContext({
console,
@@ -120,14 +123,17 @@ describe('dictation target', () => {
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, sendInput, sendInputAsync } = load({ pane: { sessionId: 'session-a', isPrimary: true } });
voice.start();
voice._insertText('hello');
- expect(sendInput).toHaveBeenCalledWith('hello');
- expect(sendInputAsync).not.toHaveBeenCalled();
+ expect(sendInput).not.toHaveBeenCalled();
+ expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'hello', { useMux: true });
+ expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send', {
+ flushEcho: true,
+ });
});
it('never types another session dictation into the active local-echo overlay', () => {
@@ -142,12 +148,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, sendInput } = load({
+ localEcho: true,
+ pane: { sessionId: 'session-a', isPrimary: true },
+ });
voice.start();
voice._insertText('typed locally');
expect(appendText).toHaveBeenCalledWith('typed locally');
+ expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-insert');
expect(sendInput).not.toHaveBeenCalled();
});
@@ -170,8 +180,7 @@ 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);
+ expect(sendInput).not.toHaveBeenCalled();
});
it('drops dictation for a session that closed meanwhile, with a toast', () => {
@@ -199,8 +208,8 @@ describe('dictation target', () => {
voice._insertText('into the tile');
expect(appendText).not.toHaveBeenCalled();
- expect(sendInput).toHaveBeenCalledWith('into the tile');
- expect(sendInputAsync).not.toHaveBeenCalled();
+ expect(sendInput).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 +217,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, sendInput, sendInputAsync, overlayClear } = load({
localEcho: true,
tiles: true,
pane: { sessionId: 'session-a', isPrimary: false, terminal: tileTerminal },
@@ -222,25 +231,61 @@ describe('dictation target', () => {
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, sendInput, 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(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(sendInput).not.toHaveBeenCalled();
- expect((app.terminal as { focus: ReturnType }).focus).toHaveBeenCalled();
+ 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();
});