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

+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();
});