fix(web): synchronize iOS keyboard edits (#830)

Keep one native-input owner per iOS terminal and reconcile keyboard edits without duplicate producers.
Preserve session-bound input ordering, local-echo Unicode deletion, and visual caret geometry.
Cover device event sequences and lifecycle handoffs; remove obsolete helpers and source-text-only regression tests.

Fixes #830
This commit is contained in:
Hadrien Kerlero committed 2026-11-20 20:13:30 +01:00
1 parent 5548c17c4a
commit c4b382b727
39 files changed
+5292 -824

No files matched your search

+5
View File
@@ -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.
+1
View File
@@ -38,6 +38,7 @@ export const BROWSER_TEST_GLOBS = [
'test/webgl-fallback.test.ts',
'test/terminal-copy-shortcut.test.ts',
'test/terminal-keycode229-recovery.browser.test.ts',
'test/ios-native-input.browser.test.ts',
'test/capture-load-window.browser.test.ts',
'test/capture-geometry-retry.browser.test.ts',
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
+20
View File
@@ -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.
+1
View File
@@ -23,6 +23,7 @@
"test:watch": "vitest --config config/vitest.ci.config.ts",
"test:coverage": "vitest run --config config/vitest.ci.config.ts --coverage",
"test:ci": "vitest run --config config/vitest.ci.config.ts",
"pretest:browser": "node scripts/prepare-test-vendor.mjs",
"test:browser": "vitest run --config config/vitest.browser.config.ts",
"test:perf": "vitest run --config config/vitest.perf.config.ts",
"test:all": "vitest run --config config/vitest.config.ts",
@@ -8,6 +8,7 @@ export type {
ZerolagInputState,
PromptFinder,
PromptPosition,
InputEndAnchor,
CellDimensions,
} from './types.js';
export type { PredictiveEchoOptions, PredictionState } from './predictive-echo-addon.js';
@@ -1,4 +1,4 @@
import type { RenderParams, FontStyle, XtermTerminal } from './types.js';
import type { RenderParams, FontStyle, XtermTerminal, InputEndAnchor } from './types.js';
// ─── CJK / fullwidth character width detection ───────────────────────
@@ -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 };
}
/**
@@ -66,6 +66,14 @@ export interface PromptPosition {
col: number;
}
/** Viewport position at the end of the visible overlay input. */
export interface InputEndAnchor {
/** Column (0-based); equals the column count at a full line's right edge. */
col: number;
/** Viewport-relative row (0 = top of viewport). */
row: number;
}
/**
* Prompt detection strategy.
*
@@ -6,6 +6,7 @@ import type {
PromptPosition,
PromptFinder,
FontStyle,
InputEndAnchor,
} from './types.js';
import { getCellDimensions } from './cell-dimensions.js';
import { findPrompt, readTextAfterPrompt, promptRowInViewport } from './prompt-finder.js';
@@ -18,6 +19,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();
}
}
}
@@ -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]);
});
});
+2
View File
@@ -114,6 +114,7 @@ appendFileSync(
// 4. Minify frontend assets
run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --outfile=dist/web/public/input-cjk.js --allow-overwrite');
run('minify mobile-ime-preview.js', 'npx esbuild dist/web/public/mobile-ime-preview.js --minify --outfile=dist/web/public/mobile-ime-preview.js --allow-overwrite');
run('minify terminal-ios-native-input.js', 'npx esbuild dist/web/public/terminal-ios-native-input.js --minify --outfile=dist/web/public/terminal-ios-native-input.js --allow-overwrite');
run('minify terminal-keycode229-recovery.js', 'npx esbuild dist/web/public/terminal-keycode229-recovery.js --minify --outfile=dist/web/public/terminal-keycode229-recovery.js --allow-overwrite');
run('minify i18n.js', 'npx esbuild dist/web/public/i18n.js --minify --outfile=dist/web/public/i18n.js --allow-overwrite');
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
@@ -145,6 +146,7 @@ console.log('\n[build] content-hash cache busting');
'keyboard-accessory.js',
'input-cjk.js',
'mobile-ime-preview.js',
'terminal-ios-native-input.js',
'terminal-keycode229-recovery.js',
'sanitize-html.js',
'tab-layout-browser.js',
+3 -1
View File
@@ -32,6 +32,8 @@
Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. Load order is the `<script>` order in `index.html` (each module's `@loadorder` tag mirrors it). `i18n.js` translates static + newly inserted application DOM while skipping terminal/response/file/user-name surfaces; `input-cjk.js` handles CJK IME composition via an always-visible textarea below the terminal (`window.cjkActive` blocks xterm's onData). `terminal-keycode229-recovery.js` forwards a committed `input` event that xterm's `_inputEvent` guard drops (Chrome-on-Android soft keyboards send `composed: true` after a keydown), and only when xterm emitted no canonical data for that keystroke. ⚠️ **That decision is settled at the NEXT keydown as well as on its own zero-delay timer** (#441): the drain runs from xterm's custom key handler, which fires BEFORE xterm processes that key, so a soft keyboard that commits the last character and sends Enter in one InputConnection transaction puts the character on the wire ahead of the `\r`. On the timer alone that character is not merely late, it is LOST: xterm emits the `\r` first and bumps the canonical counter past the candidate's snapshot, so the candidate stands down (measured, `hell\r` where the user typed `hello`). The edit-based diff described below is settled first at that keydown, so the drain decides with the evidence the timer had and Enter's textarea clear cannot turn the pending line into DELs. Ordering is pinned by `test/terminal-keycode229-recovery.browser.test.ts`, which the CI gate does NOT run. The same module replaces xterm's `_handleAnyTextareaChanges` (an append-only `newValue.replace(oldValue, '')` diff) with an edit-based one, so an Android autocorrect on space (delete + insert) reaches the PTY once instead of duplicating the line; ⚠️ that diff is settled at the NEXT keydown, before xterm handles that key, because xterm clears the textarea for Enter and a pending diff would then send one DEL per character ahead of the submitted line (except a composition xterm finalizes synchronously at that key, which stays xterm's). ⚠️ Every xterm that takes keyboard input wires its OWN controller from this module (`create()` returns null unless `matchMedia('(pointer: coarse)')` matches or the user agent is Android, so a desktop dead key is not forwarded twice, #716, while an Android device whose mouse, trackpad cover or stylus Chromium reports as the fine primary pointer keeps the soft-keyboard recovery): the primary pane (terminal-ui.js `initTerminal()`) and each `TerminalTile` (terminal-tile.js `_createKeyCode229Recovery()`, so every grid tile and the split's Pane B, which a wide Android tablet reaches), each on its own textarea, composition helper and session; in both, `handleKeyEvent` must run ABOVE the custom key handler's keyCode-229 early return, and `notifyCanonicalData` sits in the onData lambda, never in the send path the recovered bytes also take. `mobile-ime-preview.js` (iOS WebKit only) paints the text an IME is composing: an iOS IME commit is routed into the local-echo overlay through the ordinary printable/paste branch and then `_transferMobileImeCommitToLocalEcho`, and without local echo the preview clears only on output parsed AFTER the commit (or its 2 s fallback). ⚠️ It watches keydown in the capture phase on `terminal.element`, never on the textarea, because xterm finalizes the composition and emits the commit in its own capture listener on the textarea.
**iOS native input ownership (#830)**: `terminal-ios-native-input.js` loads after `mobile-ime-preview.js` and before the terminal hosts. `MobileImePreview.isIosWebKitTouch` is the shared gate: supported main panes and tiles install `_iosNativeInput`, never `_keyCode229Recovery`. The owner retains the native textarea line, reconciles replacements/deletions as one transaction, and projects trackpad selection through `.ios-native-caret` without sending arrows. The main marker uses the local-echo layout anchor while the overlay owns the line; missing overlay geometry hides it. External producers call `_prepareExternalInput(pane, reason)` before sending. Toolbar Enter uses `submitFromToolbar()`, capturing the focused pane once; text, the 80ms gap and CR reserve that session's FIFO even across a switch. Browser regressions: `test/ios-native-input.browser.test.ts`; run `node scripts/prepare-test-vendor.mjs` first.
**Entrance animations** (`entrance-animations.js`, all OFF by default): opt-in animations for tabs, terminal, windows, connection lines and tile-grid tiles, chosen via `data-tab-anim` / `data-term-anim` / `data-win-anim` / `data-line-anim` / `data-tile-anim` on `<html>`; the default `legacy` theme short-circuits every hook (tiles keep the grid's own `settle`). ⚠️ Tabs and lines are destroyed mid-animation on re-render, so re-apply to the fresh element by id with a negative `animation-delay` (resume, never restart). ⚠️ Terminal-pane styles may animate only transform / opacity / clip-path (anything else resizes the PTY via FitAddon); `blur` is the ONE sanctioned `filter` exception, do not generalise it. ⚠️ Line glow lives in `--line-glow` so blur keyframes interpolate. Every animation setting lives in App Settings → **Animations** (`#settings-animations`); put new ones there. ⚠️ Tiles are OFF by default (Animations → Tile Animations, default `settle` = the grid's own fade, no screen beat); a theme only presets it. A tile's FRAME animates transform/opacity only (six at once, no filter) with `tile-enter*`/`tile-leave*` keyframe names (what the mount and the still copy listen for); its SCREEN replays the pane style on `.tile-body.term-enter`; a reload's restore always settles. Persisted per-device in `codeman:*Anim` localStorage keys, never in `SettingsUpdateSchema`; lab at `?animlab=1`. Test: `test/entrance-animations.test.ts`. → [architecture-invariants#entrance-animations](../../docs/architecture-invariants.md#entrance-animations)
**Mobile tab strip scrolling** (issue #257): under 768px the tab strip scrolls horizontally, so the active tab must be kept reachable. `_updateActiveTabImmediate()` reveals it via `computeTabScrollLeft()` (constants.js, rect math on the strip's own `scrollLeft`, never `scrollIntoView()`, which scrolls the document under the fixed header); `_fullRenderSessionTabs()` must restore `scrollLeft` across rebuilds and re-reveal only when the active tab changed (`_lastRenderedActiveTabId`) or, grouped by state, the ACTIVE tab moved to another state band (`_noteActiveTabBand()`, both render paths, scrolling row only; another tab's move never scrolls). ⚠️ The phone-block `min-width` on `.session-tab.active .tab-name` keeps the tab's centre off the gear/close icons, sized for numberless tabs 10+ (floor 40px); do not shrink it. With the opt-in tab "+" on (`showTabNewButton`, `html.tabs-show-new`) a third icon joins them and the reserve grows to 68px, still under the 80px `max-width`. ⚠️ Never reintroduce hoisting the active session to the front of the strip. Tests: `test/mobile-tab-tap-zones.test.ts`, `test/tab-triage.test.ts`. → [architecture-invariants#mobile-tab-strip-scrolling](../../docs/architecture-invariants.md#mobile-tab-strip-scrolling)
@@ -86,7 +88,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Phone toolbar: Enter replaces Shell** (post-1.8.0): inside `@media (max-width: 599px)` `btn-shell` is `display:none` and `btn-enter` takes its slot (`order: 4`); starting a shell moved into the Run dropdown (`Terminal / Shell` → `setRunMode('shell')` → `run()` → `runShell()`, button label "Run SH"). `runMode` is `z.string().max(20)` server-side, so new modes need no schema change. Desktop and tablet keep the green Run Shell button unchanged.
⚠️ **`sendEnterKey()` MUST go through `terminal._core.coreService.triggerDataEvent('\r', true)`** — not `sendInput()`, and never a raw POST to `/api/sessions/:id/input`. `localEchoEnabled` defaults to `MobileDetection.isTouchDevice()`, so on every phone the characters you type are buffered in the `LocalEchoOverlay` and have **never reached the PTY**; the `onData` Enter branch in terminal-ui.js is what flushes `pendingText` first and only then sends `\r` (after an 80ms delay so text lands first). Sending a bare `\r` submits an empty line and strands the typed text on screen, so the button looks dead. Replaying the keypress reuses the overlay flush, the flushed-offset cleanup and the ordering instead of reimplementing them. `KeyboardAccessory.sendKey()` is for escape sequences (arrows/Esc) and is the WRONG template to copy for input. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) and then Enter.
**`sendEnterKey()` must call `submitFromToolbar()`**, never a raw input POST. The semantic submit captures the focused pane once and calls `_prepareExternalInput` to settle/reset native ownership. For the main pane, it reuses local-echo Enter handling: pending text, the 80ms gap and the CR are reserved atomically in the captured session's FIFO. For a tile, the CR goes to the tile's session. A session switch cannot redirect the delayed CR, and a missing pane must not fall back to another session. The one deliberate exception: while the CJK field is visible (`#cjkInput.cjk-input-visible`), `onData` drops everything under `window.cjkActive`, so `sendEnterKey()` calls `CjkInput.submit()` instead, which sends what the field holds (a Send on Enter answer, or live text not yet flushed) then Enter, on the session `CjkInput` captured for that text (`_sendCjkPrompt` reserves the text, 120 ms gap and Enter on that session's FIFO).
⚠️ **Skin overrides outrank plain class rules.** `styles.css` nests its skin block inside `html:not([data-skin="og"]) { … }`, so a bare `.btn-toolbar` rule in there resolves to specificity **(0,2,1)** and beats a `.btn-toolbar.btn-x` rule **(0,2,0)** in `mobile.css` regardless of load order. Toolbar-button colors set from mobile.css therefore need `!important`: that is why mobile.css leans on it so heavily. Symptom: only your `!important` properties land and everything else silently renders in generic toolbar grey. Press feedback on the phone bars sidesteps this: the `:active` rules for `.btn-toolbar`, the mobile icon buttons and `.accessory-btn` (mobile.css) use `transform` and `filter` only, which nothing on these buttons sets at a higher specificity, so one rule reads the same on every skin; a background `:active` lost to the skin block on all but og, and an inset `box-shadow` lost to the skin hover rules, which is why neither is used. The light skins darken instead of brightening, and `prefers-reduced-motion` drops the scale.
+95 -20
View File
@@ -4134,6 +4134,68 @@ class CodemanApp {
}
}
// Session-owned reservations survive pane switches and terminal replacement.
_inputFifo(sessionId) {
if (!this._inputFifos) this._inputFifos = new Map();
if (!this._inputFifos.has(sessionId)) this._inputFifos.set(sessionId, { ops: [], timer: null, draining: false });
return this._inputFifos.get(sessionId);
}
_enqueueInput(sessionId, ops) {
if (!sessionId || (this.sessions && !this.sessions.has(sessionId))) return;
const fifo = this._inputFifo(sessionId);
fifo.ops.push(...ops);
this._drainInputFifo(sessionId, fifo);
}
_drainInputFifo(sessionId, fifo) {
if (fifo.timer !== null || fifo.draining) return;
fifo.draining = true;
try {
while (fifo.ops.length && this._inputFifos.get(sessionId) === fifo) {
const op = fifo.ops.shift();
if (op.gap !== undefined) {
fifo.timer = setTimeout(() => {
fifo.timer = null;
if (this._inputFifos.get(sessionId) === fifo) this._drainInputFifo(sessionId, fifo);
}, op.gap);
break;
}
if (op.key) {
fetch(`/api/sessions/${sessionId}/send-key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: op.key }),
}).catch(() => {});
} else if (op.write) {
this._enqueueReliableInput(sessionId, op.write, { useMux: op.useMux });
}
}
} finally {
fifo.draining = false;
}
}
_sealPendingInput(sessionId) {
const timer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(timer);
this._inputFlushTimeout?.delete(sessionId);
const text = this._pendingInput?.get(sessionId);
this._pendingInput?.delete(sessionId);
if (text) this._enqueueInput(sessionId, [{ write: text }]);
}
_settleMainInput(reason) {
const sessionId = this.activeSessionId;
this._iosNativeInput?.settle?.();
this._sealPendingInput(sessionId);
if (sessionId) this._flushLocalEchoTo(sessionId);
this._iosNativeInput?.reset?.(reason);
this._mobileImePreview?.reset?.();
this._mobileImeCommitOutputSeq = null;
this._localEchoOverlay?.clear();
}
/**
* Public input entry point — name/signature kept for all call sites.
* Records the input durably, then delivers it reliably (exactly-once). Never
@@ -4143,6 +4205,12 @@ class CodemanApp {
* @param {{useMux?: boolean}} [opts] - useMux only affects the POST fallback.
*/
_sendInputAsync(sessionId, input, opts) {
this._sealPendingInput(sessionId);
this._enqueueInput(sessionId, [{ write: input, ...opts }]);
}
// Durable delivery starts here; FIFO gaps order enqueueing, not ACK completion.
_enqueueReliableInput(sessionId, input, opts) {
if (!sessionId || !input) return;
const useMux = opts?.useMux === true;
// Both transports refuse a frame over the server's limit (issue #484), and a
@@ -9385,6 +9453,24 @@ class CodemanApp {
// `skipSnapshot`: the tile grid opening on the session it parks
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
this._settleMainInput('session');
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
// exact view on switch-back rather than replaying codex's byte stream, which
@@ -9434,24 +9520,6 @@ class CodemanApp {
// Close WebSocket for previous session (new one opens after buffer load)
this._disconnectWs();
// Clear CJK input to prevent sending stale text to the wrong session.
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
// pending flush timers armed and drops the phantom char it relies on.
// A held Send on Enter draft survives a reload of the same session: nothing
// switched, and the answer would be gone. On a real switch it is stashed for
// the session being left (selectSession restores it on the way back), so a
// stray swipe does not lose it. Live mode still clears, since a pending
// debounced flush could fire mid-reconnect.
if (typeof CjkInput !== 'undefined') {
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) {
if (this.activeSessionId) CjkInput.stashDraft?.(this.activeSessionId);
CjkInput.clear();
}
} else {
const cjkEl = document.getElementById('cjkInput');
if (cjkEl) cjkEl.value = '';
}
// Clean up flicker filter state when switching sessions
this._clearTimer('flickerFilterTimeout');
this.flickerFilterBuffer = '';
@@ -9497,7 +9565,6 @@ class CodemanApp {
if (ta) ta.dispatchEvent(new CompositionEvent('compositionend', { data: '' }));
}
} catch {}
this._flushLocalEchoTo(this.activeSessionId);
this._localEchoOverlay?.clear();
// Predictions are ephemeral + already sent: nothing to save/restore
// across a tab switch (unlike the buffer overlay's setFlushed machinery)
@@ -10017,7 +10084,7 @@ class CodemanApp {
// hides this one from it. Flush first or the characters are cleared
// unread. The geometry replay re-enters here with no gesture behind it,
// so on a touch device this fires while the user is still typing.
this._flushLocalEchoTo(sessionId);
this._settleMainInput('session');
this.activeSessionId = null;
}
// Focus terminal SYNCHRONOUSLY before any await — iOS Safari only honors
@@ -10830,6 +10897,14 @@ class CodemanApp {
this._activeRename.cancel();
}
this.sessions.delete(sessionId);
const fifo = this._inputFifos?.get(sessionId);
clearTimeout(fifo?.timer);
this._inputFifos?.delete(sessionId);
const inputTimer = this._inputFlushTimeout?.get(sessionId);
clearTimeout(inputTimer);
this._inputFlushTimeout?.delete(sessionId);
this._pendingInput?.delete(sessionId);
this._lastKeystrokeTime?.delete(sessionId);
// Remove from tab order
const orderIndex = this.sessionOrder.indexOf(sessionId);
if (orderIndex !== -1) {
+5
View File
@@ -142,6 +142,8 @@ Object.assign(CodemanApp.prototype, {
return;
}
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'toolbar-attachment');
const stillActive = this.activeSessionId === sessionId;
// The overlay holds the prompt only while local echo actually owns it. A
// session handed back to plain PTY echo by a composer nav key (echo
@@ -152,6 +154,7 @@ Object.assign(CodemanApp.prototype, {
// goes to the PTY like any other background write.
const overlayOwnsPrompt =
stillActive &&
(!pane || (pane.isPrimary && pane.sessionId === sessionId)) &&
!this._tilesOwnTerminal?.() &&
this._localEchoEnabled &&
this._localEchoOverlay &&
@@ -398,6 +401,8 @@ Object.assign(CodemanApp.prototype, {
// activeSessionId, and after the awaits above that is whatever tab the
// user switched to mid-upload, so the paths landed in the wrong session.
// Same delivery sendInput() uses (durable queue, useMux for the POST path).
const pane = this._paneForSession?.(sessionId);
if (pane) this._prepareExternalInput?.(pane, 'upload-insert', { flushEcho: true });
this._sendInputAsync(sessionId, paths.join(' '), { useMux: true });
}
+1
View File
@@ -4547,6 +4547,7 @@
<script defer src="mobile-ime-preview.js"></script>
<!-- Forwards committed input events that xterm drops on Android/GBoard soft keyboards. Must precede terminal-ui.js. -->
<script defer src="terminal-keycode229-recovery.js"></script>
<script defer src="terminal-ios-native-input.js"></script>
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
<script defer src="sanitize-html.js"></script>
<!-- Owner tab layout projection (grouped vertical rail); pure, read by app.js. -->
+47 -14
View File
@@ -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;
},
+80 -54
View File
@@ -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');
+28 -3
View File
@@ -42,7 +42,9 @@
const KEEP_COMPOSING_KEYCODES = new Set([20, 229, 16, 17, 18]);
const CONTROL_OR_LINE_BREAK = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
function isIosWebKitTouch(nav = navigator) {
// Shared with CodemanIosNativeInput.isSupported(); keep platform gating here
// because the preview predates and loads before the native input owner.
function isIosWebKitTouch(nav = global.navigator) {
const userAgent = String(nav && nav.userAgent ? nav.userAgent : '');
const platform = String(nav && nav.platform ? nav.platform : '');
const touchPoints = Number(nav && nav.maxTouchPoints ? nav.maxTouchPoints : 0);
@@ -59,6 +61,12 @@
const render = typeof options.render === 'function' ? options.render : function () {};
const clear = typeof options.clear === 'function' ? options.clear : function () {};
const onCommit = typeof options.onCommit === 'function' ? options.onCommit : function () {};
const ownsNativeInput =
typeof options.ownsNativeInput === 'function'
? options.ownsNativeInput
: function () {
return false;
};
const scheduleFrame = options.scheduleFrame || global.requestAnimationFrame.bind(global);
const cancelFrame = options.cancelFrame || global.cancelAnimationFrame.bind(global);
const setTimer = options.setTimer || global.setTimeout.bind(global);
@@ -73,6 +81,7 @@
let frameToken = null;
let timerToken = null;
let finalizedByKeydown = false;
let compositionStart = 0;
let destroyed = false;
let invokingClear = false;
@@ -140,17 +149,19 @@
cleanup();
if (destroyed) return;
composing = true;
compositionStart = textarea.selectionStart == null ? textarea.value.length : textarea.selectionStart;
}
function updateComposition(event) {
if (!composing) return;
latestValue = event.data == null ? '' : String(event.data);
const segment = safely(ownsNativeInput) ? textarea.value.slice(compositionStart, textarea.selectionEnd) : '';
latestValue = event.data == null ? segment : String(event.data);
scheduleLatestPreview('provisional');
}
function onComposingInput(event) {
if (!event.isComposing) return;
updateComposition({ data: event.data == null ? textarea.value : event.data });
updateComposition({ data: event.data == null && !safely(ownsNativeInput) ? textarea.value : event.data });
}
function armFallbackTimer(isCurrent) {
@@ -203,6 +214,9 @@
// finalizes it. `isComposing` and `key` are deliberately not consulted,
// because xterm does not consult them.
function onKeydown(event) {
// Native ownership, not xterm's terminal-key heuristic, decides when the
// retained field has finished composing.
if (safely(ownsNativeInput)) return;
if (keydownTarget !== textarea && event.target !== textarea) return;
if (!composing || KEEP_COMPOSING_KEYCODES.has(event.keyCode)) return;
finalizeComposition(latestValue, true);
@@ -246,6 +260,16 @@
return true;
}
function nativeTransaction({ inserted, deleted, composition }) {
if (destroyed || !awaitingCommit) return false;
if (inserted && consumeTerminalData(inserted)) return true;
// No inserted text (or unsafe terminal controls): nothing can display a
// commit later. In particular deletion-only/unchanged compositions settle
// now instead of leaving unrelated input to consume the 2 s fallback.
cleanup();
return false;
}
function completeCommit(result) {
if (destroyed || !result || result.predicted !== true || !committed) return;
cleanup();
@@ -275,6 +299,7 @@
return {
consumeTerminalData,
nativeTransaction,
completeCommit,
noteAuthoritativeOutput,
reset,
+2 -19
View File
@@ -2070,18 +2070,8 @@ Object.assign(CodemanApp.prototype, {
}
},
/** Send Enter to the active session (phone toolbar button).
*
* MUST go through xterm's onData path, NOT straight to sendInput()/the API.
* With local echo on (the mobile default) the characters you typed are still
* buffered in the LocalEchoOverlay and have NEVER reached the PTY. The onData
* Enter branch (terminal-ui.js) is what flushes that pending text and only
* then sends \r. Send a bare \r instead and you submit an empty line while the
* typed text stays stranded on screen — which reads as "the button does
* nothing". triggerDataEvent replays it exactly as if the key were pressed,
* so overlay flush, flushed-offset cleanup and ordering are all reused. */
/** Submit the focused pane through the shared native-input/echo boundary. */
sendEnterKey() {
if (!this.activeSessionId) return;
// While the CJK field is visible, onData drops everything (cjkActive), this
// Enter included. Press Enter in the field instead: it sends what the field
// holds (a Send on Enter answer, or live text not yet flushed), then Enter.
@@ -2092,14 +2082,7 @@ Object.assign(CodemanApp.prototype, {
CjkInput.submit?.();
return;
}
const coreService = this.terminal?._core?.coreService;
if (coreService && typeof coreService.triggerDataEvent === 'function') {
coreService.triggerDataEvent('\r', true);
return;
}
// Fallback only if xterm's private core API moves: correct when local echo
// is off, and still better than doing nothing.
this.sendInput('\r');
this.submitFromToolbar();
},
_initRunMode() {
+624
View File
@@ -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);
+63 -1
View File
@@ -54,6 +54,7 @@
* @dependency constants.js (window.CodemanTerminalFont, window.CodemanFetchDeadline, DEFAULT_SCROLLBACK, TERMINAL_TAIL_SIZE, SHELL_LOAD_BASE_QUERY, SHELL_LOAD_QUERY, TERMINAL_CHUNK_SIZE)
* @dependency terminal-ui.js (codemanCurrentXtermTheme, codemanCurrentSkinIsLight, CodemanTerminalInput.shouldSuppressTerminalQueryResponse/isTerminalFocusOrMouseReport/wheelDeltaLines/wheelTicksForGesture/coalesceScrollBytes/sgrWheelReports/pageKeysForGesture, app._shouldForwardWheelToApp/_localScrollbackIsHollow/_terminalViewportAtBottom/_clientPointToCell/_handleDesktopTerminalClick, app.tabAlerts)
* @dependency terminal-keycode229-recovery.js (window.CodemanKeyCode229Recovery, optional: absent, xterm's own textarea handling stands)
* @dependency terminal-ios-native-input.js (window.CodemanIosNativeInput, optional iOS native editing owner)
* @loadorder 7.4 of 16, loaded after terminal-ui.js and before terminal-split.js
*/
@@ -227,6 +228,8 @@
// The soft-keyboard controller (terminal-keycode229-recovery.js): created
// in connect() once the xterm is open, torn down in destroy().
this._keyCode229Recovery = null;
this._iosNativeInput = null;
this._iosCaretMarker = null;
}
async connect() {
@@ -275,7 +278,7 @@
this._onFocusIn = () => global.app?._noteFocusedTile?.(this);
this.terminal.textarea?.addEventListener('focus', this._onFocusIn);
this._createKeyCode229Recovery();
this._createInputOwner();
// The twin of terminal-ui.js's onData gate (initTerminal; keep the two in
// step). Canonical xterm data tells the controller this keystroke was
// delivered, but not a query reply or a focus/mouse report, which xterm
@@ -309,6 +312,7 @@
// here too. Ctrl+V goes through the primary pane's paste trap
// (image-input.js), aimed at this pane (below).
this.terminal.attachCustomKeyEventHandler((ev) => {
if (this._iosNativeInput?.keyFilter(ev) === false) return false;
// FIRST, above the IME early return below, as in terminal-ui.js: every
// keydown settles this pane's pending textarea edit and drains a
// pending recovery BEFORE xterm handles the key, so a character an
@@ -639,6 +643,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-
File diff suppressed because it is too large. Load diff
+24 -11
View File
@@ -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 = () => {
+1 -1
View File
@@ -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?.();');
});
+153
View File
@@ -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(/<LF>/g, '\n').replace(/<CR>/g, '\r').replace(/<NBSP>/g, '\u00a0');
let pending;
for (const record of records) {
if (record.kind !== 'ev' || !['beforeinput', 'input'].includes(record.type)) continue;
const data = record.data === 'null' || record.data == null ? null : decode(record.data);
if (record.type === 'beforeinput') {
if (record.sel[0] !== record.sel[1]) select.call(ta, ...record.sel);
const event = iev(record.type, record.inputType, data, record);
ta.dispatchEvent(event);
if (afterEvent) afterEvent(record);
pending = event.defaultPrevented ? null : { inputType: record.inputType, data };
} else {
if (pending) applyEdit(ta, pending.inputType, pending.data);
pending = null;
ta.dispatchEvent(iev(record.type, record.inputType, data, record));
if (afterInput) afterInput(record);
if (afterEvent) afterEvent(record);
}
}
}
function typeKey(ta, text) {
const first = text.codePointAt(0);
const keyCode = text === ' ' ? 32 : String.fromCodePoint(first).toUpperCase().codePointAt(0);
const down = kev('keydown', text, keyCode);
ta.dispatchEvent(down);
if (!down.defaultPrevented) {
const press = kev('keypress', text, first);
ta.dispatchEvent(press);
if (!press.defaultPrevented) edit(ta, 'insertText', text);
}
ta.dispatchEvent(kev('keyup', text, keyCode));
}
function backspace(ta) {
const down = kev('keydown', 'Backspace', 8);
ta.dispatchEvent(down);
if (!down.defaultPrevented) edit(ta, 'deleteContentBackward');
ta.dispatchEvent(kev('keyup', 'Backspace', 8));
}
function holdDeleteRepeat(ta, burst) {
const down = kev('keydown', 'Backspace', 8);
ta.dispatchEvent(down);
if (!down.defaultPrevented) edit(ta, 'deleteContentBackward');
for (let i = 0; i < burst; i += 1) edit(ta, 'deleteContentBackward');
ta.dispatchEvent(kev('keyup', 'Backspace', 8));
}
function replaceSuggestion(ta, start, end, text) {
return edit(ta, 'insertReplacementText', text, [start, end]);
}
function enter(ta) {
const down = kev('keydown', 'Enter', 13);
ta.dispatchEvent(down);
if (!down.defaultPrevented) {
const press = kev('keypress', 'Enter', 13);
ta.dispatchEvent(press);
if (!press.defaultPrevented) edit(ta, 'insertLineBreak');
}
ta.dispatchEvent(kev('keyup', 'Enter', 13));
}
function caret(ta, index) {
ta.setSelectionRange(index, index);
ta.ownerDocument.dispatchEvent(new Event('selectionchange'));
}
function composition(ta, type, data = '') {
ta.dispatchEvent(new CompositionEvent(type, { data, bubbles: true, composed: true }));
}
function paste(ta, text) {
const clipboardData = new DataTransfer();
clipboardData.setData('text/plain', text);
ta.dispatchEvent(new ClipboardEvent('paste', {
clipboardData, bubbles: true, cancelable: true, composed: true,
}));
}
global.IosReplay = Object.freeze({
kev, iev, edit, capturedEdits, typeKey, backspace, holdDeleteRepeat, replaceSuggestion, enter, caret, composition, paste,
});
})(window);
+91 -3
View File
@@ -63,9 +63,10 @@ function makeTextarea(): FakeTextarea {
const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0';
const IOS_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko)';
function loadCjkHarness({ ua = ANDROID_UA }: { ua?: string } = {}) {
function loadCjkHarness({ ua = ANDROID_UA, captureTarget }: { ua?: string; captureTarget?: () => string } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const targets: Array<string | undefined> = [];
const windowObj: Record<string, unknown> = {};
const documentObj = {
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
@@ -88,10 +89,16 @@ function loadCjkHarness({ ua = ANDROID_UA }: { ua?: string } = {}) {
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({ send: (text: string) => sent.push(text) });
CjkInput.init({
captureTarget,
send: (text: string, target?: string) => {
sent.push(text);
targets.push(target);
},
});
textarea.fire('focus');
return { CjkInput, textarea, sent, windowObj, documentObj };
return { CjkInput, textarea, sent, targets, windowObj, documentObj };
}
describe('CJK input module', () => {
@@ -103,6 +110,87 @@ describe('CJK input module', () => {
vi.useRealTimers();
});
it.each(['input', 'keydown', 'compositionstart'])(
'captures the destination at the first %s and releases it after flush',
(start) => {
let target = 'B';
const captureTarget = vi.fn(() => target);
const { CjkInput, textarea, sent, targets } = loadCjkHarness({ captureTarget });
if (start === 'keydown') textarea.fire('keydown', { key: 'x' });
if (start === 'compositionstart') textarea.fire('compositionstart');
textarea.value = PHANTOM + '你好';
if (start === 'input') textarea.fire('input', { inputType: 'insertText', isComposing: false });
target = 'A';
if (start === 'keydown') textarea.fire('input', { inputType: 'insertText', isComposing: false });
if (start === 'compositionstart') textarea.fire('compositionend');
vi.runAllTimers();
CjkInput.flushNow();
expect(sent).toEqual(['你好']);
expect(targets).toEqual(['B']);
expect(captureTarget).toHaveBeenCalledTimes(1);
textarea.value = PHANTOM + '再见';
textarea.fire('input', { inputType: 'insertText', isComposing: false });
vi.runAllTimers();
expect(targets).toEqual(['B', 'A']);
}
);
it.each(['clear', 'escape'])('drops the held destination on %s', (action) => {
let target = 'B';
const { CjkInput, textarea, targets } = loadCjkHarness({ captureTarget: () => target });
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'discard';
if (action === 'clear') CjkInput.clear();
else textarea.fire('keydown', { key: 'Escape' });
target = 'A';
textarea.value = PHANTOM + 'send';
textarea.fire('input', { inputType: 'insertText', isComposing: false });
vi.runAllTimers();
expect(targets).toEqual(['A']);
});
it.each([
{ key: 'Enter' },
{ key: 'c', ctrlKey: true },
{ key: 'ArrowUp' },
{ key: 'End', ctrlKey: true },
{ key: 'Backspace' },
])('routes direct $key control keys through the held or fresh destination', (key) => {
let target = 'B';
const { CjkInput, textarea, targets } = loadCjkHarness({ captureTarget: () => target });
textarea.fire('compositionstart');
textarea.fire('compositionend');
target = 'A';
textarea.fire('keydown', key);
expect(targets).toEqual(['B']);
CjkInput.clear();
textarea.fire('keydown', key);
expect(targets).toEqual(['B', 'A']);
});
it('routes phantom deletion to a freshly captured destination', () => {
const { textarea, sent, targets } = loadCjkHarness({ captureTarget: () => 'B' });
textarea.value = '';
textarea.fire('input', { inputType: 'deleteContentBackward', isComposing: false });
expect(sent).toEqual(['\x7f']);
expect(targets).toEqual(['B']);
});
it('flushNow leaves provisional composition untouched until it commits', () => {
const { CjkInput, textarea, sent } = loadCjkHarness();
textarea.fire('compositionstart');
textarea.value = PHANTOM + '你好';
CjkInput.flushNow();
vi.runAllTimers();
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + '你好');
textarea.fire('compositionend');
CjkInput.flushNow();
expect(sent).toEqual(['你好']);
vi.runAllTimers();
expect(sent).toEqual(['你好']);
});
it('sends committed text after a normal composition cycle', () => {
const { textarea, sent } = loadCjkHarness();
+392
View File
@@ -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<string, { id: string; mode: string; status?: string }>;
_localEchoEnabled: boolean;
_isLoadingBuffer: boolean;
_echoPassthroughSessions?: Set<string>;
_localEchoOverlay: { clear(): void; pendingText: string; getInputEndAnchor(): CellAnchor | null };
_iosNativeInput: NativeOwner;
_keyCode229Recovery: unknown;
_enqueueReliableInput(id: string, input: string): unknown;
}
interface TestWindow extends Window {
app: TestApp;
__sent: SentInput[];
CodemanIosNativeInput: { isSupported(): boolean };
IosReplay: {
typeKey(ta: HTMLTextAreaElement, text: string): void;
kev(type: string, key: string, keyCode: number, extra?: { shiftKey?: boolean; ctrlKey?: boolean }): KeyboardEvent;
edit(ta: HTMLTextAreaElement, inputType: string, data: string): boolean;
};
TerminalTile: new (
id: string,
mount: HTMLElement,
options: { mode: string }
) => {
connect(): Promise<void>;
destroy(): void;
terminal: TestTerminal;
_iosNativeInput: NativeOwner;
_keyCode229Recovery: unknown;
};
}
// Real platform timers intentionally cover native reconciliation and the FIFO's 80ms gap.
const IOS_UA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5.2 Mobile/15E148 Safari/604.1';
const SESSION = 'ios830-browser';
describe('iOS native input served-app wiring (#830)', () => {
let server: WebServer;
let browser: Browser;
let context: BrowserContext;
let page: Page;
let baseUrl: string;
beforeAll(async () => {
server = new WebServer(0, false, true);
await server.start();
baseUrl = `http://localhost:${server.boundPort}`;
browser = await chromium.launch({ headless: true });
context = await browser.newContext({
userAgent: IOS_UA,
hasTouch: true,
permissions: ['clipboard-read', 'clipboard-write'],
});
await context.addInitScript(() => {
Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 5 });
const native = window.matchMedia.bind(window);
window.matchMedia = (query) => {
const result = native(query);
if (query === '(pointer: coarse)') Object.defineProperty(result, 'matches', { value: true });
return result;
};
});
}, 90000);
afterAll(async () => {
await browser?.close();
await server?.stop();
}, 60000);
async function setup(echo: boolean) {
if (page) await page.close();
page = await context.newPage();
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => (window as unknown as TestWindow).app?._iosNativeInput, null, { timeout: 30000 });
await page.evaluate(
async ({ echo, session }) => {
const w = window as unknown as TestWindow;
const app = w.app;
app.activeSessionId = session;
app.sessions.set(session, { id: session, mode: 'shell', status: 'idle' });
app._localEchoEnabled = echo;
app._isLoadingBuffer = false;
app._echoPassthroughSessions?.delete(session);
app._localEchoOverlay.clear();
app._iosNativeInput.reset('test');
w.__sent = [];
// Observe the real FIFO/handleTerminalData boundary, not _sendInputAsync.
app._enqueueReliableInput = (id: string, input: string) =>
w.__sent.push({ id, input, time: performance.now() });
await new Promise<void>((resolve) => app.terminal.write('\x1bc❯ ', resolve));
app.terminal.textarea.focus();
},
{ echo, session: SESSION }
);
expect(
await page.evaluate(() => ({
supported: (window as unknown as TestWindow).CodemanIosNativeInput.isSupported(),
recovery: (window as unknown as TestWindow).app._keyCode229Recovery,
}))
).toEqual({ supported: true, recovery: null });
await page.addScriptTag({ path: resolve(import.meta.dirname, 'fixtures/ios-native-replay.js') });
}
async function run(action: string) {
return page.evaluate(async (action) => {
const w = window as unknown as TestWindow;
const app = w.app;
const ta = app.terminal.textarea;
const r = w.IosReplay;
const type = async (text: string) => {
for (const ch of text) {
r.typeKey(ta, ch);
await new Promise((resolve) => setTimeout(resolve, 20));
}
};
await new Function('app', 'ta', 'r', 'type', `return (async () => { ${action} })()`)(app, ta, r, type);
await new Promise((resolve) => setTimeout(resolve, 30));
return { sent: w.__sent, pending: app._localEchoOverlay.pendingText, value: ta.value };
}, action);
}
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<HTMLElement>('.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('');
}
+23 -34
View File
@@ -20,6 +20,7 @@ import { performance } from 'node:perf_hooks';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
type OverlayStub = {
pendingText: string;
@@ -28,6 +29,7 @@ type OverlayStub = {
prompts: unknown[];
clear(): void;
suppressBufferDetection(): void;
getFlushed(): { count: number; text: string };
setPrompt(p: unknown): void;
appendText: ReturnType<typeof vi.fn>;
};
@@ -38,14 +40,15 @@ type AppInstance = {
terminal?: { focus: () => void };
_localEchoEnabled?: boolean;
_localEchoOverlay?: OverlayStub;
_pendingInput: string;
_pendingInput: Map<string, string>;
_inputFlushTimeout: Map<string, NodeJS.Timeout>;
_lastKeystrokeTime: Map<string, number>;
_flushedOffsets?: Map<string, number>;
_flushedTexts?: Map<string, string>;
_echoPassthroughSessions?: Set<string>;
loadAppSettingsFromStorage: () => Record<string, unknown>;
sendInput: ReturnType<typeof vi.fn>;
_enqueueReliableInput: Mock;
_updateLocalEchoState(): void;
_flushLocalEchoPending(): void;
insertTerminalText(text: string): void;
};
@@ -111,6 +114,7 @@ function makeOverlay(pending = ''): OverlayStub {
setPrompt(p: unknown) {
this.prompts.push(p);
},
getFlushed: () => ({ count: 0, text: '' }),
appendText: vi.fn(),
};
}
@@ -120,11 +124,14 @@ function makeApp(mode: string, overlay = makeOverlay()): AppInstance {
app.activeSessionId = 's1';
app.sessions = new Map([['s1', { mode }]]);
app._localEchoOverlay = overlay;
app._pendingInput = '';
app._pendingInput = new Map();
app._inputFlushTimeout = new Map();
app._lastKeystrokeTime = new Map();
app.terminal = { focus: vi.fn() };
app._flushedOffsets = new Map([['s1', 3]]);
app._flushedTexts = new Map([['s1', 'abc']]);
app.loadAppSettingsFromStorage = () => ({ localEchoEnabled: true });
app.sendInput = vi.fn().mockResolvedValue(undefined);
app._enqueueReliableInput = vi.fn();
return app;
}
@@ -179,6 +186,7 @@ describe('_updateLocalEchoState mode gating', () => {
it('disables the overlay for codex sessions even with the setting ON (issues #218/#219/#220/#222)', () => {
const overlay = makeOverlay('pending');
const app = makeApp('codex', overlay);
app._localEchoEnabled = true; // Pending overlay text belongs to an enabled buffer policy.
app._updateLocalEchoState();
expect(app._localEchoEnabled).toBe(false);
expect(overlay.cleared).toBeGreaterThan(0);
@@ -199,25 +207,6 @@ describe('_updateLocalEchoState mode gating', () => {
});
});
describe('_flushLocalEchoPending', () => {
it('moves pending text into _pendingInput and resets overlay + flushed tracking', () => {
const overlay = makeOverlay('hello');
const app = makeApp('claude', overlay);
app._flushLocalEchoPending();
expect(app._pendingInput).toBe('hello');
expect(overlay.cleared).toBe(1);
expect(overlay.suppressed).toBe(1);
expect(app._flushedOffsets!.has('s1')).toBe(false);
expect(app._flushedTexts!.has('s1')).toBe(false);
});
it('appends nothing when the overlay is empty', () => {
const app = makeApp('claude', makeOverlay(''));
app._flushLocalEchoPending();
expect(app._pendingInput).toBe('');
});
});
describe('insertTerminalText pass-through routing', () => {
it('appends to the overlay while local echo is buffering', () => {
const overlay = makeOverlay();
@@ -225,7 +214,7 @@ describe('insertTerminalText pass-through routing', () => {
app._localEchoEnabled = true;
app.insertTerminalText('path.txt');
expect(overlay.appendText).toHaveBeenCalledWith('path.txt');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
it('sends directly while the session is in nav-key pass-through', () => {
@@ -234,7 +223,7 @@ describe('insertTerminalText pass-through routing', () => {
app._localEchoEnabled = true;
app._echoPassthroughSessions = new Set(['s1']);
app.insertTerminalText('path.txt');
expect(app.sendInput).toHaveBeenCalledWith('path.txt');
expect(app._enqueueReliableInput).toHaveBeenCalledWith('s1', 'path.txt', { useMux: true });
expect(overlay.appendText).not.toHaveBeenCalled();
});
});
@@ -425,12 +414,12 @@ describe('_predictHookOnData (wire neutrality)', () => {
it('never touches _pendingInput and never sends (visual-only pin)', () => {
const app = makePredictApp();
app._pendingInput = 'queued';
app._pendingInput.set('s1', 'queued');
for (const data of ['h', 'i', '\x7f', '\r', '\x1b[A', 'multi char', '\x1b[200~x\x1b[201~']) {
app._predictHookOnData(data);
}
expect(app._pendingInput).toBe('queued');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._pendingInput.get('s1')).toBe('queued');
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
it('is inert under buffer/off policies and without a predictor', () => {
@@ -451,21 +440,21 @@ describe('_predictHookOnData (wire neutrality)', () => {
app._predictiveEcho!.predictChar.mockImplementation(() => {
throw new Error('boom');
});
app._pendingInput = 'queued';
app._pendingInput.set('s1', 'queued');
expect(() => app._predictHookOnData('h')).not.toThrow();
expect(app._pendingInput).toBe('queued');
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._pendingInput.get('s1')).toBe('queued');
expect(app._enqueueReliableInput).not.toHaveBeenCalled();
});
});
describe('insertTerminalText under predict policy', () => {
it('routes to sendInput (not the overlay) and clears predictions', () => {
it('routes to reliable input (not the overlay) and clears predictions', () => {
const overlay = makeOverlay();
const app = makeApp('codex', overlay) as PredictiveApp;
app._predictiveEcho = makePredictor();
app._updateLocalEchoState(); // predict; _localEchoEnabled false
app.insertTerminalText('path.txt');
expect(app.sendInput).toHaveBeenCalledWith('path.txt');
expect(app._enqueueReliableInput).toHaveBeenCalledWith('s1', 'path.txt', { useMux: true });
expect(overlay.appendText).not.toHaveBeenCalled();
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled();
});
+54 -45
View File
@@ -428,52 +428,42 @@ describe('mobile IME preview lifecycle', () => {
);
});
/**
* Rebuilds the real `handleTerminalData` closure from initTerminal's source,
* so these cases exercise the shipped routing rather than a copy of it.
*/
/** Runs the real session-bound preprocessing method with deterministic FIFO gaps. */
function loadHandleTerminalData(app: App, sent: string[]) {
const marker = 'const handleTerminalData = (data) => {';
const start = terminalSource.indexOf(marker);
if (start < 0) throw new Error('handleTerminalData definition not found');
const bodyStart = start + marker.length;
const end = terminalSource.indexOf('\n };', bodyStart);
if (end < 0) throw new Error('handleTerminalData boundary not found');
const timers: Array<() => void> = [];
const pending = new Map<string, string>();
const queues = new Map<string, Array<{ write?: string; gap?: number }>>();
const draining = new Set<string>();
app._sendInputAsync = (_sessionId: string, data: string) => sent.push(data);
const context = vm.createContext({
console,
performance,
setTimeout: (callback: () => void) => {
timers.push(callback);
return timers.length;
},
clearTimeout: vi.fn(),
document: { activeElement: null, getElementById: vi.fn(() => null) },
window: {
cjkActive: false,
CodemanTerminalInput: {
BRACKETED_PASTE_START: '\x1b[200~',
shouldSuppressTerminalQueryResponse: () => false,
isTerminalFocusOrMouseReport: () => false,
isComposerNavKey: () => false,
},
},
_crashDiag: { log: vi.fn() },
flushInput: () => {
app._inputFlushTimeout = null;
if (app._pendingInput && app.activeSessionId) {
const input = app._pendingInput;
app._pendingInput = '';
app._sendInputAsync(app.activeSessionId, input);
app._sealPendingInput = (sessionId: string) => {
const data = pending.get(sessionId);
pending.delete(sessionId);
if (data) app._enqueueInput(sessionId, [{ write: data }]);
};
app._appendPendingInput = (sessionId: string, data: string) => {
pending.set(sessionId, (pending.get(sessionId) || '') + data);
timers.push(() => app._sealPendingInput(sessionId));
};
app._enqueueInput = (sessionId: string, ops: Array<{ write?: string; gap?: number }>) => {
const queue = queues.get(sessionId) || [];
queue.push(...ops);
queues.set(sessionId, queue);
if (draining.has(sessionId)) return;
draining.add(sessionId);
function drain() {
while (queue.length) {
const op = queue.shift()!;
if (op.gap !== undefined) {
timers.push(drain);
return;
}
if (op.write !== undefined) app._sendInputAsync(sessionId, op.write);
}
},
});
const handler = vm.runInContext(`(function (data) {${terminalSource.slice(bodyStart, end)}\n})`, context) as (
this: App,
data: string
) => void;
return { handle: (data: string) => handler.call(app, data), timers };
draining.delete(sessionId);
}
drain();
};
return { handle: (data: string) => app._handleTerminalData(data, app.activeSessionId), timers };
}
describe('mobile IME commit onData routing', () => {
@@ -521,9 +511,9 @@ describe('mobile IME commit onData routing', () => {
_echoPassthroughSessions: new Set(),
_flushedOffsets: new Map(),
_flushedTexts: new Map(),
_pendingInput: '',
_inputFlushTimeout: null,
_lastKeystrokeTime: 0,
_pendingInput: new Map(),
_inputFlushTimeout: new Map(),
_lastKeystrokeTime: new Map(),
_terminalOutputSeq: 5,
_mobileImePreview: controller,
});
@@ -720,3 +710,22 @@ describe('mobile IME commit and authoritative terminal output', () => {
expect(controller.noteAuthoritativeOutput).toHaveBeenCalledOnce();
});
});
describe('native owner and preview shared platform gate', () => {
it('loads the preview first and delegates native support to its single predicate', () => {
const exposed: {
navigator: { userAgent: string; maxTouchPoints: number };
MobileImePreview?: { isIosWebKitTouch(nav: unknown): boolean };
CodemanIosNativeInput?: { isSupported(): boolean };
} = {
navigator: { userAgent: 'iPhone AppleWebKit/605.1.15', maxTouchPoints: 5 },
};
const context = vm.createContext({ window: exposed, globalThis: exposed });
vm.runInContext(read('src/web/public/mobile-ime-preview.js'), context);
vm.runInContext(read('src/web/public/terminal-ios-native-input.js'), context);
expect(exposed.CodemanIosNativeInput!.isSupported()).toBe(true);
const shared = vi.spyOn(exposed.MobileImePreview!, 'isIosWebKitTouch').mockReturnValue(false);
expect(exposed.CodemanIosNativeInput!.isSupported()).toBe(false);
expect(shared).toHaveBeenCalledWith(exposed.navigator);
});
});
+95
View File
@@ -55,6 +55,8 @@ class FakeNode {
class FakeTextarea extends FakeNode {
value = 'unchanged';
selectionStart = 0;
selectionEnd = 0;
}
type Scheduled = { id: number; callback: () => void; delay?: number };
@@ -133,8 +135,101 @@ function harness(
}
describe('MobileImePreview', () => {
test('native composition ignores xterm terminal-key finalization heuristics', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionupdate', { data: 'に' });
h.textarea.dispatch('keydown', { key: 'x', keyCode: 88 });
expect(h.controller.state.composing).toBe(true);
expect(h.controller.state.awaitingCommit).toBe(false);
h.textarea.dispatch('compositionupdate', { data: '日本' });
h.textarea.dispatch('compositionend', { data: '日本' });
expect(h.controller.nativeTransaction({ inserted: '日本', deleted: 0, composition: true })).toBe(true);
expect(h.onCommit).toHaveBeenCalledWith('日本');
});
beforeEach(() => vi.restoreAllMocks());
test.each([
{ inserted: '', deleted: 2, composition: true },
{ inserted: '', deleted: 0, composition: true },
{ inserted: '', deleted: 0, composition: false },
])('settles an awaiting native transaction immediately: %j', (transaction) => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionupdate', { data: 'draft' });
h.textarea.dispatch('compositionend', { data: '' });
expect(h.controller.state.awaitingCommit).toBe(true);
h.clear.mockClear();
expect(h.controller.nativeTransaction(transaction)).toBe(false);
expect(h.controller.state.awaitingCommit).toBe(false);
expect(h.controller.state.committed).toBe(false);
expect(h.frames).toHaveLength(0);
expect(h.timers).toHaveLength(0);
expect(h.clear).toHaveBeenCalledOnce();
expect(h.controller.consumeTerminalData('unrelated')).toBe(false);
expect(h.onCommit).not.toHaveBeenCalled();
});
test('hands native inserted text through the existing commit lifecycle exactly once', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionend', { data: 'teh' });
expect(h.controller.nativeTransaction({ inserted: 'the', deleted: 3, composition: true })).toBe(true);
expect(h.onCommit).toHaveBeenCalledExactlyOnceWith('the');
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'the', phase: 'committed' });
expect(h.controller.nativeTransaction({ inserted: 'the', deleted: 0, composition: true })).toBe(false);
expect(h.onCommit).toHaveBeenCalledOnce();
h.controller.completeCommit({ predicted: true });
expect(h.timers).toHaveLength(0);
});
test('null-data native provisional input extracts only the composition segment', () => {
const h = harness({ ownsNativeInput: () => true });
h.textarea.value = 'retained suffix';
h.textarea.selectionStart = h.textarea.selectionEnd = 9;
h.textarea.dispatch('compositionstart');
h.textarea.value = 'retained 日本suffix';
h.textarea.selectionStart = h.textarea.selectionEnd = 11;
h.textarea.dispatch('input', { data: null, isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: '日本', phase: 'provisional' });
h.textarea.dispatch('compositionupdate', { data: null });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: '日本', phase: 'provisional' });
h.textarea.dispatch('input', { data: 'event wins', isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'event wins', phase: 'provisional' });
expect(h.textarea.value).toBe('retained 日本suffix');
});
test.each([undefined, () => false])(
'keeps whole-value provisional fallback without native ownership (%s)',
(ownsNativeInput) => {
const h = harness({ ownsNativeInput });
h.textarea.value = 'retained ';
h.textarea.selectionStart = h.textarea.selectionEnd = 9;
h.textarea.dispatch('compositionstart');
h.textarea.value = 'retained 日本';
h.textarea.selectionStart = h.textarea.selectionEnd = 11;
h.textarea.dispatch('input', { data: null, isComposing: true });
h.flushFrame();
expect(h.render).toHaveBeenLastCalledWith({ text: 'retained 日本', phase: 'provisional' });
}
);
test('ignores native notifications outside an awaiting commit and after destruction', () => {
const h = harness();
expect(h.controller.nativeTransaction({ inserted: 'ordinary', deleted: 0, composition: false })).toBe(false);
h.textarea.dispatch('compositionstart');
h.textarea.dispatch('compositionend');
h.controller.destroy();
expect(h.controller.nativeTransaction({ inserted: 'late', deleted: 0, composition: true })).toBe(false);
expect(h.onCommit).not.toHaveBeenCalled();
});
test('collapses 500 composition updates into one latest-state frame', () => {
const h = harness();
h.textarea.dispatch('compositionstart');
+36 -19
View File
@@ -50,6 +50,10 @@ function loadComposer(sessionId = 'session-1') {
_echoPassthroughSessions: new Set<string>(),
_predictiveEcho: { clearPredictions: vi.fn() },
_sendInputAsync: vi.fn(),
_enqueueInput: vi.fn(),
_focusedPane: () => ({ sessionId: app.activeSessionId, isPrimary: true }),
_paneForSession: (id: string) => (id === app.activeSessionId ? app._focusedPane() : null),
_prepareExternalInput: vi.fn(),
_uploadAndInsertImages: vi.fn(async () => ['/tmp/image-one.png']),
_promptAttachKind: (file: { type: string; name?: string }) =>
file.type.startsWith('image/')
@@ -265,12 +269,21 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledOnce();
expect(app._sendInputAsync).toHaveBeenNthCalledWith(1, 'session-1', '\x1b[200~first line\rsecond line\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: '\x1b[200~first line\rsecond line\x1b[201~' },
{ gap: 120 },
{ write: '\r', useMux: true },
]);
expect(app._prepareExternalInput).toHaveBeenLastCalledWith(
{ sessionId: 'session-1', isPrimary: true },
'accessory-compose-send',
{ flushEcho: true }
);
expect(composeButton.classList.contains('has-draft')).toBe(false);
expect(timers).toContainEqual(expect.objectContaining({ delay: 120 }));
expect(timers.some((timer) => timer.delay === 120)).toBe(false);
runTimers();
expect(app._sendInputAsync).toHaveBeenNthCalledWith(2, 'session-1', '\r', { useMux: true });
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(document.querySelector('.prompt-composer-overlay')).toBeNull();
bar.composePrompt();
@@ -287,11 +300,15 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '\x1b[200~still\rmultiline\x1b[201~');
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: '\x1b[200~still\rmultiline\x1b[201~' },
{ gap: 120 },
{ write: '\r', useMux: true },
]);
expect(document.querySelector('.prompt-composer-overlay')).toBeNull();
expect(app.showToast).not.toHaveBeenCalled();
runTimers();
expect(app._sendInputAsync).toHaveBeenLastCalledWith('session-1', '\r', { useMux: true });
expect(app._enqueueInput).toHaveBeenCalledOnce();
});
it('releases echo passthrough after a composed prompt is queued', () => {
@@ -343,8 +360,8 @@ describe('mobile prompt composer', () => {
(document.querySelector('.paste-send') as HTMLButtonElement).click();
expect(app._sendInputAsync).toHaveBeenCalledOnce();
expect((app._sendInputAsync.mock.calls[0][1] as string).length).toBe(64 * 1024);
expect(app._enqueueInput).toHaveBeenCalledOnce();
expect(app._enqueueInput.mock.calls[0][1][0].write.length).toBe(64 * 1024);
expect(app.showToast).not.toHaveBeenCalled();
});
@@ -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();
});
});
+23 -17
View File
@@ -160,6 +160,7 @@ function loadBar(sessionMode = 'claude') {
activeSessionId: 'session-1',
sessions: new Map<string, { mode: string }>([['session-1', { mode: sessionMode }]]),
terminal: { focus: vi.fn() },
_enqueueInput: vi.fn(),
};
const fetchMock = vi.fn(() => Promise.resolve({ ok: true, catch: () => {} }));
const barElement = fakeBarElement();
@@ -499,10 +500,14 @@ describe('one-shot Ctrl through the CJK input field', () => {
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string;
_sendInputAsync: ReturnType<typeof vi.fn>;
_focusedPane: () => { terminal: object; sessionId: string; isPrimary: boolean };
_prepareExternalInput: (...args: unknown[]) => void;
_handleCjkInput(text: string): void;
};
app.activeSessionId = 'cjk-session';
app._sendInputAsync = vi.fn();
app._focusedPane = () => ({ terminal: {}, sessionId: app.activeSessionId, isPrimary: true });
app._prepareExternalInput = vi.fn();
return { app, bar };
}
@@ -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<string>)]).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<typeof vi.fn>)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']);
expect(app.sendInput).not.toHaveBeenCalled();
});
});
+105 -16
View File
@@ -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<string, number> })._flushedOffsets.has('session-1')).toBe(false);
expect((app as { _flushedTexts: Map<string, string> })._flushedTexts.has('session-1')).toBe(false);
expect(app.sendInput).toHaveBeenCalledWith('git sta');
expect(fetchMock).toHaveBeenCalledOnce();
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ input: '\t' });
// Text must reach the PTY before the completion request.
const sendInputOrder = (app.sendInput as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0];
const fetchOrder = fetchMock.mock.invocationCallOrder[0];
expect(sendInputOrder).toBeLessThan(fetchOrder);
expect(app._enqueueInput).toHaveBeenCalledWith('session-1', [
{ write: 'git sta', useMux: true },
{ gap: 120 },
{ write: '\t' },
]);
});
});
describe('toolbar Enter', () => {
it('uses semantic submit instead of replaying native textarea data', () => {
const context = vm.createContext({ CodemanApp: function () {} });
vm.runInContext(`${sessionSource}\nglobalThis.__mixin = CodemanApp.prototype;`, context);
const submitFromToolbar = vi.fn();
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 });
});
});
@@ -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'/);
});
});
+863
View File
@@ -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<string, (event: object) => 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<string, (event: object) => 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']]);
});
});
File diff suppressed because it is too large. Load diff
@@ -66,6 +66,8 @@ describe('orphaned terminal input recovery wiring', () => {
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => (window as any).app?.terminal, null, { timeout: 30000 });
await page.waitForFunction(() => (window as any).app?._keyCode229Recovery, null, { timeout: 30000 });
expect(await page.evaluate(() => (window as any).app._iosNativeInput)).toBeNull();
expect(await page.evaluate(() => Boolean((window as any).app._keyCode229Recovery))).toBe(true);
}, 90000);
afterAll(async () => {
@@ -96,19 +98,16 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
let xtermEmitted = 0;
const rec = app._keyCode229Recovery;
try {
app.activeSessionId = 'cod388-browser-regression';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-regression', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
// The controller object is Object.freeze()d, so count xterm's own
// canonical emissions by swapping the (writable) property on app.
app._keyCode229Recovery = {
@@ -138,13 +137,14 @@ describe('orphaned terminal input recovery wiring', () => {
}
await new Promise((resolve) => setTimeout(resolve, 60));
return { sent, xtermEmitted };
return { sent: sent.map(([, chunk]) => chunk), xtermEmitted };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-regression');
app._pendingInput.delete('cod388-browser-regression');
app._lastKeystrokeTime.delete('cod388-browser-regression');
app._keyCode229Recovery = rec;
textarea.value = '';
}
@@ -207,17 +207,14 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
try {
app.activeSessionId = 'cod388-browser-batched';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-batched', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.focus();
// One task, no awaits between the three dispatches.
@@ -245,14 +242,16 @@ describe('orphaned terminal input recovery wiring', () => {
Object.defineProperties(enterDown, { keyCode: { value: 13 }, which: { value: 13 } });
textarea.dispatchEvent(enterDown);
await new Promise((resolve) => setTimeout(resolve, 80));
return { wire: sent.join('') };
// Keep real browser timers: this exercises xterm's platform-clock recovery and FIFO gaps.
await new Promise((resolve) => setTimeout(resolve, 150));
return { wire: sent.map(([, chunk]) => chunk).join('') };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-batched');
app._pendingInput.delete('cod388-browser-batched');
app._lastKeystrokeTime.delete('cod388-browser-batched');
textarea.value = '';
}
}, data);
@@ -283,10 +282,8 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
const key229 = () => {
const down = new KeyboardEvent('keydown', { key: 'Unidentified', bubbles: true, cancelable: true });
Object.defineProperties(down, { keyCode: { value: 229 }, which: { value: 229 } });
@@ -296,9 +293,8 @@ describe('orphaned terminal input recovery wiring', () => {
try {
app.activeSessionId = 'cod388-browser-autocorrect';
app._localEchoEnabled = false;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-autocorrect', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.value = '';
textarea.focus();
@@ -316,17 +312,18 @@ describe('orphaned terminal input recovery wiring', () => {
await new Promise((resolve) => setTimeout(resolve, 80));
const line: string[] = [];
for (const ch of sent.join('')) {
for (const ch of sent.map(([, chunk]) => chunk).join('')) {
if (ch === '\x7f') line.pop();
else line.push(ch);
}
return { raw: sent.join(''), line: line.join(''), textarea: textarea.value };
return { raw: sent.map(([, chunk]) => chunk).join(''), line: line.join(''), textarea: textarea.value };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-autocorrect');
app._pendingInput.delete('cod388-browser-autocorrect');
app._lastKeystrokeTime.delete('cod388-browser-autocorrect');
textarea.value = '';
}
});
@@ -353,10 +350,8 @@ describe('orphaned terminal input recovery wiring', () => {
const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement;
const originalSessionId = app.activeSessionId;
const originalLocalEcho = app._localEchoEnabled;
const originalSendInput = app._sendInputAsync;
const originalPendingInput = app._pendingInput;
const originalLastKeystrokeTime = app._lastKeystrokeTime;
const sent: string[] = [];
const originalSendInput = app._enqueueReliableInput;
const sent: Array<[string, string]> = [];
const keydown = (init: KeyboardEventInit, keyCode: number) => {
const down = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });
Object.defineProperties(down, { keyCode: { value: keyCode }, which: { value: keyCode } });
@@ -367,9 +362,8 @@ describe('orphaned terminal input recovery wiring', () => {
try {
app.activeSessionId = 'cod388-browser-edit-enter';
app._localEchoEnabled = localEcho;
app._pendingInput = '';
app._lastKeystrokeTime = 0;
app._sendInputAsync = (_sessionId: string, chunk: string) => sent.push(chunk);
app.sessions.set('cod388-browser-edit-enter', { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
textarea.value = '';
textarea.focus();
@@ -394,17 +388,18 @@ describe('orphaned terminal input recovery wiring', () => {
await new Promise((resolve) => setTimeout(resolve, 250)); // local echo delays the \r by 80 ms
const line: string[] = [];
for (const ch of sent.join('')) {
for (const ch of sent.map(([, chunk]) => chunk).join('')) {
if (ch === '\x7f') line.pop();
else line.push(ch);
}
return { raw: sent.join(''), line: line.join('') };
return { raw: sent.map(([, chunk]) => chunk).join(''), line: line.join('') };
} finally {
app.activeSessionId = originalSessionId;
app._localEchoEnabled = originalLocalEcho;
app._sendInputAsync = originalSendInput;
app._pendingInput = originalPendingInput;
app._lastKeystrokeTime = originalLastKeystrokeTime;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete('cod388-browser-edit-enter');
app._pendingInput.delete('cod388-browser-edit-enter');
app._lastKeystrokeTime.delete('cod388-browser-edit-enter');
textarea.value = '';
}
}, options);
@@ -480,7 +475,7 @@ describe('orphaned terminal input recovery wiring', () => {
const app = w.app;
const tile = w.__tile229;
const textarea = document.querySelector('#tile229Mount .xterm-helper-textarea') as HTMLTextAreaElement;
const originalSendInput = app._sendInputAsync;
const originalSendInput = app._enqueueReliableInput;
const originalSessionId = app.activeSessionId;
const rec = tile._keyCode229Recovery;
const sent: Array<[string, string]> = [];
@@ -509,7 +504,8 @@ describe('orphaned terminal input recovery wiring', () => {
};
try {
app.activeSessionId = 'cod541-not-the-tile';
app._sendInputAsync = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
app.sessions.set(tileId, { mode: 'shell' });
app._enqueueReliableInput = (sessionId: string, chunk: string) => sent.push([sessionId, chunk]);
if (scenario === 'selfRescued') {
// Counts xterm's own canonical emissions: the tile's onData reads the property at
// call time, and the controller object itself is frozen.
@@ -569,7 +565,8 @@ describe('orphaned terminal input recovery wiring', () => {
tileId,
};
} finally {
app._sendInputAsync = originalSendInput;
app._enqueueReliableInput = originalSendInput;
app.sessions.delete(tileId);
app.activeSessionId = originalSessionId;
tile._keyCode229Recovery = rec;
textarea.value = '';
+190 -1
View File
@@ -94,10 +94,11 @@ function loadContext() {
return {
CodemanApp: (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp,
windowStub,
context,
};
}
const { CodemanApp, windowStub } = loadContext();
const { CodemanApp, windowStub, context } = loadContext();
type App = Record<string, unknown> & {
_pendingDeliveries: Map<string, Array<{ seq: number; data: string }>>;
@@ -163,6 +164,8 @@ afterEach(() => {
beforeEach(() => {
windowStub.__coarsePointer = true;
delete windowStub.CodemanIosNativeInput;
delete context.KeyboardAccessoryBar;
FakeTerminal.coreFactory = null;
FakeFit.proposed = { cols: 80, rows: 24 };
FakeSocket.instances = [];
@@ -1519,3 +1522,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');
});
}
});
+3 -1
View File
@@ -297,7 +297,9 @@ describe('xterm key handlers swallow a chord that applies', () => {
const src = read('terminal-ui.js');
const handler = src.slice(src.indexOf('this.terminal.attachCustomKeyEventHandler((ev) => {'));
const gate = handler.indexOf('if (this.tileShortcutFor?.(ev)) return false;');
const enter = handler.indexOf("if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)) {");
// Prefix only: the gate also carries an iOS keyCode guard (#830), so an iOS
// suggestion word "Enter" with Shift held is text, not a Shift+Enter chord.
const enter = handler.indexOf("if (ev.key === 'Enter' && (ev.shiftKey || ev.ctrlKey)");
expect(gate).toBeGreaterThan(0);
expect(gate).toBeLessThan(enter);
});
+60 -15
View File
@@ -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<typeof vi.fn> }).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<typeof vi.fn> }).clearPredictions
).not.toHaveBeenCalled();
});
it('split view is unchanged: a Pane A dictation keeps the overlay and refocuses the main terminal', () => {
it('preserves Pane A pending text and dictation ordering when focus moves to B', () => {
const paneB = { focus: vi.fn() };
const { voice, app, appendText, sendInput } = load({ localEcho: true, focused: 'session-a' });
const { voice, app, appendText, overlayClear, gear, 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<typeof vi.fn> }).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();
});