Merge #839: fix(web): synchronize iOS keyboard edits (#830) (@HadrienKerlero)

This commit is contained in:
Codeman maintainer committed 2026-11-25 16:11:57 +01:00
commit eb40f4aaa5
55 files changed
+6950 -1039

No files matched your search

+22 -6
View File
@@ -158,6 +158,11 @@ describe('a held draft survives a reload of the same session', () => {
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
// Nothing in the same-session reload block may clear the field ahead of
// that flag: a CjkInput.clear() there wipes the held draft keepCjkDraft keeps.
const start = appJs.indexOf('if (this.activeSessionId === sessionId && forceReload) {');
const block = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
expect(block).not.toContain('CjkInput.clear');
});
});
@@ -178,13 +183,24 @@ describe('Send on Enter field layout and strings', () => {
expect(base).toContain('overflow-y: auto;');
});
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
it('the phone toolbar Enter presses Enter in the visible CJK field, not a bare terminal Enter', () => {
// 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));
expect(body).toContain("classList.contains('cjk-input-visible')");
expect(body).toContain('CjkInput.submit?.();');
// The real sendEnterKey from session-ui.js, run with and without the field.
for (const visible of [true, false]) {
const submit = vi.fn();
const field = { classList: { contains: (name: string) => visible && name === 'cjk-input-visible' } };
const context = vm.createContext({
CodemanApp: function CodemanApp() {},
CjkInput: { submit },
document: { getElementById: (id: string) => (id === 'cjkInput' ? field : null) },
});
vm.runInContext(`${read('session-ui.js')}\nglobalThis.__mixin = CodemanApp.prototype;`, context);
const mixin = (context as unknown as { __mixin: { sendEnterKey(this: object): void } }).__mixin;
const submitFromToolbar = vi.fn();
mixin.sendEnterKey.call({ submitFromToolbar });
expect(submit).toHaveBeenCalledTimes(visible ? 1 : 0);
expect(submitFromToolbar).toHaveBeenCalledTimes(visible ? 0 : 1);
}
});
it('has zh-CN strings for both field placeholders', () => {
+25 -13
View File
@@ -40,6 +40,16 @@ let untrustedWorkdir: string;
let sessionId: string;
const createdSessions: string[] = [];
/** The transport edge the recorders wrap: every typed producer reaches it through the session FIFO. */
type ReliableSend = (sid: string, data: string, opts?: unknown) => void;
interface RecorderWindow {
app: { _enqueueReliableInput: ReliableSend };
__dbg: Array<[string, string]>;
__trace: string[];
__origSend?: ReliableSend;
__origSend2?: ReliableSend;
}
function hasCodex(): boolean {
try {
execSync(`PATH="${CODEX_BIN_DIR}:$PATH" codex --version`, { stdio: 'pipe' });
@@ -324,12 +334,13 @@ d('codex predictive echo E2E (real codex TUI)', () => {
await resetComposer();
const pidBefore = execSync(`${TMUX} list-panes -a -F '#{pane_id} #{pane_pid}'`, { encoding: 'utf8' }).trim();
await page.evaluate(() => {
const app = (window as any).app;
(window as any).__dbg = [];
if (!(window as any).__origSend2) (window as any).__origSend2 = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return (window as any).__origSend2(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__dbg = [];
const original = (w.__origSend2 ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__dbg.push([sid.slice(0, 8), JSON.stringify(data)]);
return original(sid, data, opts);
};
});
await page.keyboard.type('abc', { delay: 30 });
@@ -471,15 +482,16 @@ d('codex predictive echo E2E (real codex TUI)', () => {
const record = () =>
page.evaluate(() => {
const app = (window as any).app;
(window as any).__trace = [];
if (!(window as any).__origSend) (window as any).__origSend = app._sendInputAsync.bind(app);
app._sendInputAsync = (sid: string, data: string, opts?: unknown) => {
(window as any).__trace.push(data);
return (window as any).__origSend(sid, data, opts);
const w = window as unknown as RecorderWindow;
const app = w.app;
w.__trace = [];
const original = (w.__origSend ??= app._enqueueReliableInput.bind(app));
app._enqueueReliableInput = (sid, data, opts) => {
w.__trace.push(data);
return original(sid, data, opts);
};
});
const trace = () => page.evaluate(() => ((window as any).__trace as string[]).join(''));
const trace = () => page.evaluate(() => (window as unknown as RecorderWindow).__trace.join(''));
await record();
await script();
+188
View File
@@ -0,0 +1,188 @@
/** @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;
const segments = new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value.slice(0, start));
start -= Array.from(segments).pop().segment.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);
+4 -16
View File
@@ -191,7 +191,6 @@ function loadPasteHarness(options: PasteHarnessOptions = {}): Harness {
if (options.localEchoPending !== undefined) {
pendingEcho = options.localEchoPending;
app._localEchoEnabled = true;
app._pendingInput = '';
app._localEchoOverlay = {
get pendingText() {
return pendingEcho;
@@ -206,14 +205,6 @@ function loadPasteHarness(options: PasteHarnessOptions = {}): Harness {
};
app._flushedOffsets = new Map();
app._flushedTexts = new Map();
app._flushLocalEchoPending = function (this: Record<string, any>) {
const pending = this._localEchoOverlay?.pendingText || '';
this._localEchoOverlay.clear();
this._localEchoOverlay.suppressBufferDetection();
this._flushedOffsets?.delete(this.activeSessionId);
this._flushedTexts?.delete(this.activeSessionId);
if (pending) this._pendingInput += pending;
};
}
const toasts: string[] = [];
app.showToast = (message: string) => toasts.push(message);
@@ -260,7 +251,6 @@ function loadImageInputApp() {
const app = new CodemanApp();
app.activeSessionId = 'session-1';
app.showToast = vi.fn();
app.sendInput = vi.fn(async () => {});
app._sendInputAsync = vi.fn();
app._normalizeImageForUpload = vi.fn(async (file) => file);
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => file.path);
@@ -481,7 +471,6 @@ describe('image upload insertion policy', () => {
const paths = await app._uploadAndInsertImages(files, { insert: false });
expect(Array.from(paths)).toEqual(['/tmp/first.png', '/tmp/second.png']);
expect(app.sendInput).not.toHaveBeenCalled();
expect(app._sendInputAsync).not.toHaveBeenCalled();
});
@@ -491,15 +480,15 @@ describe('image upload insertion policy', () => {
const paths = await app._uploadAndInsertImages([{ path: '/tmp/legacy.png' }]);
expect(Array.from(paths)).toEqual(['/tmp/legacy.png']);
// The same delivery sendInput() uses (durable queue, useMux for the POST
// fallback), but addressed to the session the batch was uploaded to.
// Durable delivery with useMux for the POST fallback, addressed to the
// captured session the batch was uploaded to.
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/legacy.png', { useMux: true });
});
it('inserts into the session the upload started in, even after a tab switch mid-upload', async () => {
const app = loadImageInputApp();
// The user switches tabs while the upload is in flight. sendInput() re-read
// activeSessionId after the awaits, so the paths used to land in session-2.
// The user switches tabs while the upload is in flight. The captured session
// must remain the destination after the awaits, rather than the active tab.
app._uploadPasteImage = vi.fn(async (_sessionId, file: { path: string }) => {
app.activeSessionId = 'session-2';
return file.path;
@@ -509,7 +498,6 @@ describe('image upload insertion policy', () => {
expect(app._uploadPasteImage).toHaveBeenCalledWith('session-1', { path: '/tmp/shot.png' });
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/tmp/shot.png', { useMux: true });
expect(app.sendInput).not.toHaveBeenCalled();
});
it('uploads to and inserts into an explicitly named session', async () => {
+31 -1
View File
@@ -54,7 +54,14 @@ function load({
promptResult = true,
touch = true,
translate,
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
captureTarget,
}: {
hold?: boolean;
promptResult?: boolean;
touch?: boolean;
translate?: (s: string) => string;
captureTarget?: () => string;
} = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
@@ -88,6 +95,7 @@ function load({
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({
captureTarget,
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
@@ -438,6 +446,28 @@ describe('CJK input: Send on Enter', () => {
expect(prompts).toEqual([]);
});
it.each([true, false])('a captured target owns the draft across clear (explicit stash: %s)', (stash) => {
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
CjkInput.restoreDraft('session-a');
type(textarea, 'answer for b');
if (stash) CjkInput.stashDraft('session-a');
CjkInput.clear();
CjkInput.restoreDraft('session-a');
expect(textarea.value).toBe(PHANTOM);
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM + 'answer for b');
});
it('clear({ discard }) also drops a stash under the captured target', () => {
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
CjkInput.restoreDraft('session-a');
type(textarea, 'answer for b');
CjkInput.stashDraft('session-b');
CjkInput.clear({ discard: true });
CjkInput.restoreDraft('session-b');
expect(textarea.value).toBe(PHANTOM);
});
it('a restored draft is held text: Backspace edits it without a DEL', () => {
const { CjkInput, textarea, sent } = load();
type(textarea, 'ok');
+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();
+500
View File
@@ -0,0 +1,500 @@
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;
cols: number;
scrollToTop(): void;
buffer: { active: { cursorX: number; cursorY: number; viewportY: number; baseY: number } };
_core: {
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } };
_customKeyEventHandler(event: KeyboardEvent): boolean;
};
}
interface NativeOwner {
reset(reason: string): void;
}
interface TestApp {
terminal: TestTerminal;
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
syncTerminalGeometry(): { cols: number; rows: number } | null;
_resizeTimeout: number | null;
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);
}
async function markerCell() {
return page.evaluate(() => {
const terminal = (window as unknown as TestWindow).app.terminal;
const marker = terminal.element.querySelector<HTMLElement>('.ios-native-caret')!;
const cell = terminal._core._renderService.dimensions.css.cell;
return {
display: marker.style.display,
col: Math.round(parseFloat(marker.style.left) / cell.width),
row: Math.round(parseFloat(marker.style.top) / cell.height),
};
});
}
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 at cell (4, 0) 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);"
);
expect(await markerCell()).toEqual({ display: 'block', col: 4, row: 0 });
});
it(`a你b wide wrap maps offsets to (78, 0), (0, 1), (2, 1) (echo ${echo})`, async () => {
await setup(echo);
await page.evaluate(async () => {
const app = (window as unknown as TestWindow).app;
const container = app.terminal.element.parentElement!;
const proposed = app.fitAddon.proposeDimensions()!;
const cell = app.terminal._core._renderService.dimensions.css.cell;
// A raw terminal.resize(80, ...) is undone by the app's ResizeObserver.
// Size its real box instead, so every subsequent auto-fit also yields 80.
const width = parseFloat(getComputedStyle(container).width) + (80 - proposed.cols) * cell.width;
container.style.width = container.style.minWidth = container.style.maxWidth = `${width}px`;
app.syncTerminalGeometry();
const layout = Promise.withResolvers<void>();
requestAnimationFrame(() => requestAnimationFrame(() => layout.resolve()));
await layout.promise;
});
// The real 300ms resize handler can clear the viewport; let it finish
// before installing the prompt and typing the native field.
await page.waitForFunction(() => {
const app = (window as unknown as TestWindow).app;
return app.terminal.cols === 80 && app._resizeTimeout === null;
});
await page.evaluate(async () => {
const app = (window as unknown as TestWindow).app;
const written = Promise.withResolvers<void>();
app.terminal.write('\x1bc' + '.'.repeat(76) + '❯ ', written.resolve);
await written.promise;
});
await run(
"await type('a你b'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('a你b', resolve));"
);
for (const [offset, col, row] of [
[0, 78, 0],
[1, 0, 1],
[2, 2, 1],
]) {
await run(`r.caret(ta, ${offset});`);
expect(await page.evaluate(() => (window as unknown as TestWindow).app.terminal.cols)).toBe(80);
expect(await markerCell()).toEqual({ display: 'block', col, row });
}
});
it(`typing while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
await setup(echo);
const scrolled = await page.evaluate(async () => {
const terminal = (window as unknown as TestWindow).app.terminal;
const written = Promise.withResolvers<void>();
terminal.write('line\r\n'.repeat(200) + '❯ ', written.resolve);
await written.promise;
terminal.scrollToTop();
return { viewportY: terminal.buffer.active.viewportY, baseY: terminal.buffer.active.baseY };
});
expect(scrolled.viewportY).toBe(0);
expect(scrolled.baseY).toBeGreaterThan(0);
const result = await run("await type('h');");
expect(result.sent.map((x) => x.input)).toEqual(echo ? [] : ['h']);
const viewport = await page.evaluate(() => {
const buffer = (window as unknown as TestWindow).app.terminal.buffer.active;
return { viewportY: buffer.viewportY, baseY: buffer.baseY };
});
expect(viewport.viewportY).toBe(viewport.baseY);
});
it(`toolbar Enter while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
await setup(echo);
const scrolled = await page.evaluate(async () => {
const terminal = (window as unknown as TestWindow).app.terminal;
const written = Promise.withResolvers<void>();
terminal.write('line\r\n'.repeat(200) + '❯ ', written.resolve);
await written.promise;
terminal.scrollToTop();
return { viewportY: terminal.buffer.active.viewportY, baseY: terminal.buffer.active.baseY };
});
expect(scrolled.viewportY).toBe(0);
expect(scrolled.baseY).toBeGreaterThan(0);
await page
.locator('button[onclick="app.sendEnterKey()"]')
.evaluate((button: HTMLButtonElement) => button.click());
// Echo on delivers the CR after the local-echo gap: wait for it on the wire.
await page.waitForFunction(() => (window as unknown as TestWindow).__sent.some((x) => x.input === '\r'));
const sent = await page.evaluate(() => (window as unknown as TestWindow).__sent.map((x) => x.input));
expect(sent).toEqual(['\r']);
const viewport = await page.evaluate(() => {
const buffer = (window as unknown as TestWindow).app.terminal.buffer.active;
return { viewportY: buffer.viewportY, baseY: buffer.baseY };
});
expect(viewport.viewportY).toBe(viewport.baseY);
});
}
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([]);
});
for (const echo of [false, true]) {
it.each([
['red heart', '\u2764\uFE0F'],
['skin-tone thumbs up', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
])(`deletes a whole %s grapheme with one backspace (echo ${echo})`, async (_name, emoji) => {
await setup(echo);
const result = await run(`await type(${JSON.stringify('ok' + emoji)}); r.backspace(ta);`);
expect(result.value).toBe('ok');
expect(result.pending).toBe(echo ? 'ok' : '');
expect(result.sent.map((x) => x.input)).toEqual(echo ? [] : [...('ok' + emoji), '\x7f']);
});
}
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');
+40 -22
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();
});
@@ -369,6 +386,7 @@ describe('mobile prompt composer', () => {
it('uploads images without writing into the PTY and inserts their paths into the draft', async () => {
const { app, bar, document } = loadComposer();
app._focusedPane = () => ({ sessionId: 'session-2', isPrimary: false });
let finishUpload!: (paths: string[]) => void;
app._uploadAndInsertImages.mockImplementation(
() => new Promise<string[]>((resolveUpload) => (finishUpload = resolveUpload))
@@ -388,7 +406,7 @@ describe('mobile prompt composer', () => {
finishUpload(['/tmp/image-one.png']);
await vi.waitFor(() => expect(input.value).toBe('review /tmp/image-one.png'));
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false, sessionId: 'session-2' });
expect((document.querySelector('.paste-send') as HTMLButtonElement).disabled).toBe(false);
expect(app.terminal.paste).not.toHaveBeenCalled();
expect(app._sendInputAsync).not.toHaveBeenCalled();
@@ -603,7 +621,7 @@ describe('mobile prompt composer', () => {
Object.defineProperty(fileInput, 'files', { configurable: true, value: [video, pdf, script] });
fileInput.dispatchEvent(new document.defaultView!.Event('change', { bubbles: true }));
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false, sessionId: 'session-1' });
expect(app.showToast).toHaveBeenCalledWith('1 file skipped: unsupported type', 'info');
await vi.waitFor(() => expect(textarea(document).value).toContain('/tmp/image-one.png'));
});
@@ -668,7 +686,7 @@ describe('mobile prompt composer', () => {
});
input.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false });
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false, sessionId: 'session-1' });
});
});
@@ -697,11 +715,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 +728,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 +739,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 +749,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 +758,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 +771,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 +834,7 @@ describe('mobile shell Paste', () => {
send.click();
runTimers();
expect(app._sendInputAsync).not.toHaveBeenCalled();
expect(app._enqueueInput).not.toHaveBeenCalled();
expect(document.querySelector('.paste-overlay')).toBeNull();
});
});
+74 -67
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 };
}
@@ -549,27 +554,43 @@ describe('one-shot Ctrl through the CJK input field', () => {
});
describe('Send on Enter: a held answer goes out with Enter as its own write', () => {
// _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one
// character goes to the composer's _sendComposedPrompt with the session
// captured at Enter, so the delayed Enter cannot follow a tab switch.
// _sendCjkPrompt is CjkInput's sendPrompt callback, called with the session
// CjkInput captured for the text (_targetForSend). Anything longer than one
// character goes to the composer's _sendComposedPrompt for that session; one
// character, the 120 ms gap and Enter are reserved on that session's FIFO, so
// the delayed Enter cannot follow a tab switch.
type PromptApp = {
activeSessionId: string | null;
sessions: Map<string, { mode: string }>;
pendingHooks?: Map<string, Set<string>>;
_focusedPane(): { sessionId: string | null; terminal: object; isPrimary: boolean } | null;
_paneForSession(id: string): null;
_enqueueReliableInput(id: string, input: string, opts?: { useMux?: boolean }): void;
_sendCjkPrompt(text: string, sessionId?: string): boolean;
};
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
const app = Object.create(CodemanApp.prototype) as PromptApp;
app.activeSessionId = 'session-a';
app.sessions = new Map([
['session-a', { mode: 'claude' }],
['session-b', { mode: 'claude' }],
]);
app._focusedPane = () => ({ sessionId: app.activeSessionId, terminal: {}, isPrimary: true });
app._paneForSession = () => null;
const writes: Array<[string, string, boolean]> = [];
app._enqueueReliableInput = (id, input, opts) => void writes.push([id, input, opts?.useMux === true]);
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
return { app, bar, composed, writes };
}
it('sends through the composer path, bound to the session active at Enter', () => {
it('sends through the composer path for the captured session, not the active one', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(app._sendCjkPrompt('line one\nline two', 'session-a')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
@@ -577,28 +598,28 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
app._sendCjkPrompt('x'.repeat(100), 'session-a');
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('types a single character, then Enter ~120 ms later to the same session', () => {
it('types a single character, then Enter 120 ms later on the same session FIFO across a switch', () => {
// Codex folds an Enter that arrives in the same burst as the text into a
// paste, even for `1\r`; a selection dialog ignores a pasted digit. Same
// split as TmuxManager.sendInput (submitsAsKeys).
// split as the tmux manager's submitsAsKeys path.
vi.useFakeTimers();
try {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) =>
writes.push([id, input, opts]);
expect(app._sendCjkPrompt('1')).toBe(true);
expect(writes).toEqual([['session-a', '1', undefined]]);
const { app, composed, writes } = promptApp();
expect(app._sendCjkPrompt('1', 'session-a')).toBe(true);
expect(writes).toEqual([['session-a', '1', false]]);
app.activeSessionId = 'session-b';
vi.advanceTimersByTime(119);
expect(writes).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
expect(writes).toEqual([
['session-a', '1', false],
['session-a', '\r', true],
]);
expect(composed).not.toHaveBeenCalled();
composed.mockRestore();
} finally {
@@ -613,19 +634,11 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
vi.useFakeTimers();
try {
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt('2')).toBe(true);
const { app, composed, writes } = promptApp();
app.pendingHooks = new Map([['session-a', new Set([hook])]]);
expect(app._sendCjkPrompt('2', 'session-a')).toBe(true);
vi.advanceTimersByTime(500);
expect(writes).toEqual([['session-a', '2', undefined]]);
expect(writes).toEqual([['session-a', '2', false]]);
composed.mockRestore();
}
} finally {
@@ -641,21 +654,13 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
['permission_prompt', 'y'],
];
for (const [hook, text] of cases) {
const { app, composed } = promptApp();
const writes: Array<[string, string, unknown]> = [];
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
id: string,
input: string,
opts?: unknown
) => writes.push([id, input, opts]);
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
['session-a', new Set([hook])],
]);
expect(app._sendCjkPrompt(text)).toBe(true);
const { app, composed, writes } = promptApp();
app.pendingHooks = new Map([['session-a', new Set([hook])]]);
expect(app._sendCjkPrompt(text, 'session-a')).toBe(true);
vi.advanceTimersByTime(120);
expect(writes).toEqual([
['session-a', text, undefined],
['session-a', '\r', { useMux: true }],
['session-a', text, false],
['session-a', '\r', true],
]);
composed.mockRestore();
}
@@ -666,19 +671,22 @@ describe('Send on Enter: a held answer goes out with Enter as its own write', ()
it('pastes even a short word: only one character is typed', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('yes')).toBe(true);
expect(app._sendCjkPrompt('yes', 'session-a')).toBe(true);
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
const { app, composed, writes } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('x'.repeat(100), 'session-a')).toBe(false);
// A captured session that closed meanwhile, or no session at all, sends nothing.
expect(app._sendCjkPrompt('1', 'session-gone')).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(app._sendCjkPrompt('1')).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
expect(writes).toEqual([]);
composed.mockRestore();
});
});
@@ -724,14 +732,15 @@ describe('composer nav keys from the bar', () => {
const app = loaded.app as unknown as Record<string, unknown>;
app._localEchoEnabled = true;
app._localEchoOverlay = overlay;
app.sendInput = vi.fn();
app._flushedOffsets = new Map([['session-1', 3]]);
app._flushedTexts = new Map([['session-1', 'dra']]);
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 +753,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 +773,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,15 +801,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(app.sendInput).not.toHaveBeenCalled();
expect(sentKeys(app._enqueueInput as ReturnType<typeof vi.fn>)).toEqual(['\x1b[A', '\x1b[B', '\x1b[D', '\x1b[C']);
});
});
+13 -13
View File
@@ -865,7 +865,7 @@ describe('Virtual Keyboard', () => {
},
suppressBufferDetection() {},
};
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1018,7 +1018,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1074,7 +1074,7 @@ describe('Virtual Keyboard', () => {
mode: 'codex',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1120,7 +1120,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'working',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1179,7 +1179,7 @@ describe('Virtual Keyboard', () => {
cliVersion: '2.1.220',
status: 'working',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1273,7 +1273,7 @@ describe('Virtual Keyboard', () => {
mode: 'codex',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1317,7 +1317,7 @@ describe('Virtual Keyboard', () => {
mode: 'claude',
status: 'running',
});
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
app.hideWelcome();
@@ -1461,7 +1461,7 @@ describe('Virtual Keyboard', () => {
status: 'running',
});
app.hideWelcome();
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1542,7 +1542,7 @@ describe('Virtual Keyboard', () => {
status: 'running',
});
app.hideWelcome();
app._sendInputAsync = (_sessionId: string, input: string) => {
app._enqueueReliableInput = (_sessionId: string, input: string) => {
window.__sentInputs.push(input);
};
const settings = app.loadAppSettingsFromStorage();
@@ -1591,7 +1591,7 @@ describe('Virtual Keyboard', () => {
// applied to the next character typed on the SYSTEM keyboard, which on a
// phone reaches the app as xterm onData text, not a key event. These drive
// the real xterm instance with page.keyboard.type() and assert on what would
// go out on the wire (_sendInputAsync), not on DOM state alone.
// go out on the wire (_enqueueReliableInput, behind the session FIFO), not on DOM state alone.
describe('Shell keyboard bar', () => {
let context: BrowserContext;
@@ -1620,14 +1620,14 @@ describe('Virtual Keyboard', () => {
async function typeAndCapture(text: string): Promise<string[]> {
await page.evaluate(`(function () {
window.__sent = [];
if (!app.__origSend) app.__origSend = app._sendInputAsync;
app._sendInputAsync = function (sessionId, input) { window.__sent.push(input); };
if (!app.__origSend) app.__origSend = app._enqueueReliableInput;
app._enqueueReliableInput = function (sessionId, input) { window.__sent.push(input); };
app.terminal.focus();
})()`);
await page.keyboard.type(text);
await page.waitForTimeout(200);
const sent = (await page.evaluate(`window.__sent`)) as string[];
await page.evaluate(`(function () { app._sendInputAsync = app.__origSend; })()`);
await page.evaluate(`(function () { app._enqueueReliableInput = app.__origSend; })()`);
return sent;
}
+120 -37
View File
@@ -43,7 +43,15 @@ function loadKeyboardModule() {
terminal: { focus: vi.fn() },
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,
_localEchoPolicy: 'off',
_predictiveEcho: { clearPredictions: vi.fn() },
_localEchoOverlay: { appendText: vi.fn() },
_prepareExternalInput: vi.fn(),
};
const fetchMock = vi.fn(() => Promise.resolve({ ok: true }));
const context = vm.createContext({
@@ -85,11 +93,32 @@ describe('accessory Tab key', () => {
const { app, bar, fetchMock } = loadKeyboardModule();
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,21 @@ 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();
context.__mixin.sendEnterKey.call({ submitFromToolbar });
expect(submitFromToolbar).toHaveBeenCalledOnce();
});
});
@@ -130,7 +167,6 @@ describe('mobile filesystem picker actions', () => {
bar.handleAction('clear-input');
expect(app.clearTerminalInput).toHaveBeenCalledOnce();
expect(app.sendInput).not.toHaveBeenCalled();
expect(keyboardSource).toContain('data-action="clear-input"');
expect(keyboardSource).toContain('data-action="clear" title="/clear"');
});
@@ -149,8 +185,60 @@ 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.sendInput).not.toHaveBeenCalled();
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/mnt/d/AI/project/file.ts', { useMux: true });
});
it.each([false, true])('clears primary predictions before inserting a path (buffered=%s)', (buffered) => {
const { app, bar, picker } = loadKeyboardModule();
app._localEchoPolicy = 'predict';
app._localEchoEnabled = buffered;
picker.open = vi.fn();
bar.handleAction('pick-path');
picker.open.mock.calls[0][0].onSelect('/project/file.ts');
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalledOnce();
const insert = buffered ? app._localEchoOverlay.appendText : app._sendInputAsync;
expect(app._predictiveEcho.clearPredictions.mock.invocationCallOrder[0]).toBeLessThan(
insert.mock.invocationCallOrder[0]
);
});
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', () => {
@@ -171,33 +259,30 @@ describe('mobile filesystem picker actions', () => {
it('inserts a selected path into the editable local-echo prompt without sending it', () => {
const appendText = vi.fn();
const sendInput = vi.fn();
const focus = vi.fn();
const app = {
activeSessionId: 'session-1',
_localEchoEnabled: true,
_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');
expect(appendText).toHaveBeenCalledWith('/mnt/d/AI/project');
expect(sendInput).not.toHaveBeenCalled();
expect(focus).toHaveBeenCalledOnce();
});
it('clears pending and already-flushed prompt text without invoking /clear', () => {
const clear = vi.fn();
const suppressBufferDetection = vi.fn();
const sendInput = vi.fn(() => Promise.resolve());
const showToast = vi.fn();
const focus = vi.fn();
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: 'pending text',
_localEchoEnabled: true,
_localEchoOverlay: {
getFlushed: () => ({ count: 4, text: 'a😀b' }),
@@ -206,18 +291,22 @@ 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(app._flushedOffsets.size).toBe(0);
expect(app._flushedTexts.size).toBe(0);
expect(showToast).toHaveBeenCalledWith('Input cleared', 'success');
@@ -227,7 +316,6 @@ describe('mobile filesystem picker actions', () => {
it('sends a picked path to the tile or Pane B that holds the keyboard, never the parked main overlay', () => {
const appendText = vi.fn();
const sendInput = vi.fn();
const _sendInputAsync = vi.fn();
const mainFocus = vi.fn();
const tileFocus = vi.fn();
@@ -236,8 +324,8 @@ describe('mobile filesystem picker actions', () => {
_localEchoEnabled: true,
_localEchoOverlay: { appendText },
terminal: { focus: mainFocus },
sendInput,
_sendInputAsync,
_prepareExternalInput: vi.fn(),
_focusedPane: () => ({ terminal: { focus: tileFocus }, sessionId: 'tile-2', isPrimary: false, tile: {} }),
};
@@ -245,25 +333,22 @@ describe('mobile filesystem picker actions', () => {
expect(_sendInputAsync).toHaveBeenCalledWith('tile-2', '/mnt/d/AI/project');
expect(appendText).not.toHaveBeenCalled();
expect(sendInput).not.toHaveBeenCalled();
expect(tileFocus).toHaveBeenCalledOnce();
expect(mainFocus).not.toHaveBeenCalled();
});
it('clears the prompt of the tile or Pane B that holds the keyboard with Ctrl+U, leaving the main overlay alone', () => {
const clear = vi.fn();
const sendInput = vi.fn(() => Promise.resolve());
const _sendInputAsync = vi.fn();
const showToast = vi.fn();
const tileFocus = vi.fn();
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: 'main pane text',
_localEchoEnabled: true,
_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: {} }),
@@ -272,28 +357,26 @@ describe('mobile filesystem picker actions', () => {
terminalHarness.mixin.clearTerminalInput.call(app);
expect(_sendInputAsync).toHaveBeenCalledWith('tile-2', '\x15');
expect(sendInput).not.toHaveBeenCalled();
expect(clear).not.toHaveBeenCalled();
expect(app._pendingInput).toBe('main pane text');
expect(showToast).toHaveBeenCalledWith('Input cleared', 'success');
expect(tileFocus).toHaveBeenCalledOnce();
});
it('uses Ctrl+U to clear the TUI-owned prompt when local echo is disabled', () => {
const sendInput = vi.fn(() => Promise.resolve());
const app = {
activeSessionId: 'session-1',
_inputFlushTimeout: null,
_pendingInput: '',
_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 });
});
});
+6 -3
View File
@@ -3,19 +3,22 @@
// 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.
// ev.type === 'keydown'; only the send-key fetch is. The main pane may add an
// iOS clause after the modifier test (#830), which must not test ev.type either.
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');
const GATE = /if \(ev\.key === 'Enter' && \(ev\.shiftKey \|\| ev\.ctrlKey\)(.*)\) \{/;
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'/);
const gate = src.match(GATE);
expect(gate, 'Shift/Ctrl+Enter gate not found').not.toBeNull();
expect(gate![0]).not.toContain('ev.type');
});
});
+51 -19
View File
@@ -38,6 +38,25 @@ interface Pressed {
focused: boolean;
}
/** The slice of the page's `app` and probe globals that pressMain() swaps and restores. */
interface MainProbeWindow {
app: {
activeSessionId: string | null;
_localEchoEnabled: boolean;
_enqueueReliableInput: (sessionId: string, chunk: string) => void;
_pendingInput?: Map<string, string>;
sessions: Map<string, { id: string; mode: string }>;
terminal: { focus(): void; textarea?: HTMLTextAreaElement };
};
__mainSaved?: {
id: string | null;
echo: boolean;
send: (sessionId: string, chunk: string) => void;
};
__mainData: string[];
__sendKeys: string[];
}
describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be swallowed too)', () => {
let server: WebServer;
let browser: Browser;
@@ -105,36 +124,49 @@ describe('Shift/Ctrl+Enter through the shipped key handlers (keypress must be sw
/**
* Press `key` in the main pane. `sessionId` null is the welcome screen; otherwise the app thinks
* that session is active, local echo is off (the desktop default) and its real send path,
* `_sendInputAsync`, is recorded instead of posting.
* that session is active, local echo is off (the desktop default), the probe id is registered in
* `app.sessions` (the session FIFO drops input for unknown ids), and the transport edge,
* `_enqueueReliableInput`, is recorded instead of posting.
*/
async function pressMain(key: string, sessionId: string | null): Promise<Pressed> {
await page.evaluate((id) => {
const w = window as any;
const w = window as unknown as MainProbeWindow;
const app = w.app;
w.__mainSaved ??= { id: app.activeSessionId, echo: app._localEchoEnabled, send: app._sendInputAsync };
w.__mainData = [] as string[];
w.__mainSaved ??= { id: app.activeSessionId, echo: app._localEchoEnabled, send: app._enqueueReliableInput };
w.__mainData = [];
w.__sendKeys.length = 0;
app.activeSessionId = id;
app._localEchoEnabled = false;
app._pendingInput = '';
app._sendInputAsync = (_sid: string, chunk: string) => void w.__mainData.push(chunk);
if (id) {
app._pendingInput?.delete(id);
app.sessions.set(id, { id, mode: 'claude' });
}
app._enqueueReliableInput = (_sid: string, chunk: string) => void w.__mainData.push(chunk);
app.terminal.focus();
}, sessionId);
const focused = await page.evaluate(() => document.activeElement === (window as any).app.terminal.textarea);
const focused = await page.evaluate(
() => document.activeElement === (window as unknown as MainProbeWindow).app.terminal.textarea
);
await page.keyboard.press(key);
// The main pane batches onData through a short flush timer before _sendInputAsync.
// The main pane batches onData through a short flush timer before the session FIFO.
await page.waitForTimeout(150);
return page.evaluate((f) => {
const w = window as any;
const app = w.app;
const out = { data: [...w.__mainData], sendKeys: [...w.__sendKeys], focused: f };
app.activeSessionId = w.__mainSaved.id;
app._localEchoEnabled = w.__mainSaved.echo;
app._sendInputAsync = w.__mainSaved.send;
app._pendingInput = '';
return out;
}, focused);
return page.evaluate(
({ f, id }) => {
const w = window as unknown as MainProbeWindow;
const app = w.app;
const saved = w.__mainSaved!;
const out = { data: [...w.__mainData], sendKeys: [...w.__sendKeys], focused: f };
app.activeSessionId = saved.id;
app._localEchoEnabled = saved.echo;
app._enqueueReliableInput = saved.send;
if (id) {
app._pendingInput?.delete(id);
app.sessions.delete(id);
}
return out;
},
{ f: focused, id: sessionId }
);
}
async function pressIn(which: 'paneB' | 'old', key: string): Promise<Pressed> {
File diff suppressed because it is too large. Load diff
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 = '';
+64 -1
View File
@@ -13,6 +13,14 @@
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
import { ZerolagInputAddon } from '../packages/xterm-zerolag-input/src/zerolag-input-addon.js';
const MULTI_CODE_POINT_EMOJI = [
['red heart', '\u2764\uFE0F'],
['skin tone', '\u{1F44D}\u{1F3FD}'],
['flag', '\u{1F1EB}\u{1F1F7}'],
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
] as const;
type Listener = (event: Record<string, unknown>) => void;
@@ -741,6 +749,58 @@ describe('edit-based sync of the helper textarea (autocorrect replacements)', ()
expect(e.sent.slice(2)).toEqual(['\x7f']);
});
it.each(MULTI_CODE_POINT_EMOJI)('deletes a whole %s with one DEL', (_name, emoji) => {
const e = editSyncHarness();
e.create(true);
typeKeys(e, 'ok');
e.keydown();
e.edit(`ok${emoji}`);
e.flush();
const before = e.sent.length;
e.keydown();
e.edit('ok');
e.flush();
expect(e.sent.slice(before)).toEqual(['\x7f']);
});
it.each([
['Thai', '\u0E01\u0E34\u0E48'],
['Hindi', '\u0915\u094D\u0937'],
])('types %s combining marks one field state at a time as plain appends', (_name, word) => {
// Each keystroke extends the last grapheme cluster; re-typing that cluster would
// make a code-point line editor (zsh) double the base letter.
const e = editSyncHarness();
e.create(true);
typeKeys(e, word);
expect(e.sent).toEqual(Array.from(word));
expect(e.line()).toBe(word);
});
it.each(MULTI_CODE_POINT_EMOJI)(
'keeps the local-echo draft at ok when the %s is deleted (real overlay)',
(_name, emoji) => {
const e = editSyncHarness();
e.create(true);
typeKeys(e, 'ok');
e.keydown();
e.edit(`ok${emoji}`);
e.flush();
// Local echo buffers what the recovery emits; each DEL drops one overlay grapheme.
const overlay = new ZerolagInputAddon();
overlay.appendText(e.sent.join(''));
expect(overlay.pendingText).toBe(`ok${emoji}`);
const before = e.sent.length;
e.keydown();
e.edit('ok');
e.flush();
for (const data of e.sent.slice(before)) {
if (data === '\x7f') expect(overlay.removeChar()).toBe('pending');
else overlay.appendText(data);
}
expect(overlay.pendingText).toBe('ok');
}
);
it('stays out of the way while composing, and leaves xterm alone without its internals', () => {
const h = editSyncHarness();
h.create(true);
@@ -770,12 +830,15 @@ describe('edit-based sync of the helper textarea (autocorrect replacements)', ()
expect(terminalSource).toMatch(/getCompositionHelper:\s*\(\)\s*=>\s*this\.terminal\?\._core\?\._compositionHelper/);
});
it('editBetween counts code points and replaces everything after the common prefix', () => {
it('editBetween counts grapheme clusters and replaces everything after the common prefix', () => {
const { editBetween } = editSyncHarness().exposed.CodemanKeyCode229Recovery;
expect(editBetween('abc', 'abcd')).toEqual({ deleted: 0, inserted: 'd' });
expect(editBetween('abc', 'ab')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('testing the peompt', 'testing the prompt ')).toEqual({ deleted: 5, inserted: 'rompt ' });
expect(editBetween('x😀', 'x')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('x\u{1F44D}\u{1F3FD}', 'x')).toEqual({ deleted: 1, inserted: '' });
expect(editBetween('', '')).toEqual({ deleted: 0, inserted: '' });
// A mark typed onto the last letter is a plain append, not a DEL and a re-typed cluster.
expect(editBetween('\u0E01', '\u0E01\u0E34')).toEqual({ deleted: 0, inserted: '\u0E34' });
});
});
+215 -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,214 @@ 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 parsed-buffer marker without an anchor, 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('falls back to the 229 recovery when the iOS module refuses to create an owner', async () => {
const native = install();
native.create.mockReturnValueOnce(null);
const { tile } = await connectTile(makeApp());
expect(native.create).toHaveBeenCalledOnce();
expect(native.attachCaretMarker).not.toHaveBeenCalled();
expect((tile as ControllerTile)._keyCode229Recovery).not.toBeNull();
});
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('spends Ctrl on a deletion-only transaction without resetting the owner', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
let armed = true;
const consumeCtrl = vi.fn(() => {
armed = false;
return '\x03';
});
context.KeyboardAccessoryBar = {
isCtrlArmed: () => armed,
consumeCtrl,
clearCtrl: () => {
armed = false;
},
};
await connectTile(app);
native.send(['\x7f']);
expect(armed).toBe(false);
native.send(['c']);
expect(app._enqueueInput.mock.calls).toEqual([
['s-tile', [{ write: '\x7f' }]],
['s-tile', [{ write: 'c' }]],
]);
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);
});
-1
View File
@@ -49,7 +49,6 @@ function loadToolbar(sessionId: string | null = 'session-1', localEcho = true, k
const app = new CodemanApp();
app.activeSessionId = sessionId;
app.showToast = vi.fn();
app.sendInput = vi.fn(async () => {});
app.terminal = { focus: vi.fn() };
app._isMobileTerminalInputFocused = vi.fn(() => keyboardUp);
app._blurMobileTerminalInput = vi.fn();
+139 -32
View File
@@ -36,7 +36,6 @@ type Voice = {
type Pane = { sessionId: string; isPrimary?: boolean; terminal?: { focus: () => void } };
function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string; tiles?: boolean; pane?: Pane } = {}) {
const sendInput = vi.fn(async () => {});
const sendInputAsync = vi.fn();
const appendText = vi.fn();
const overlayClear = vi.fn();
@@ -57,8 +56,9 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
['session-a', {}],
['session-b', {}],
]),
sendInput,
_sendInputAsync: sendInputAsync,
_enqueueInput: vi.fn(),
_prepareExternalInput: vi.fn(),
showToast,
terminal: { focus: vi.fn() },
_localEchoEnabled: !!opts.localEcho,
@@ -74,7 +74,13 @@ 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 doc = {
querySelector: (sel: string): unknown => (sel === '.btn-settings' ? gear : null),
createElement: (): unknown => ({}),
body: { appendChild: () => {} },
};
const context = vm.createContext({
console,
setTimeout: (fn: () => void) => fn(),
@@ -87,11 +93,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
key === 'codeman-voice-settings' ? JSON.stringify({ insertMode: opts.insertMode || 'direct' }) : null,
setItem: () => {},
},
document: {
querySelector: (sel: string) => (sel === '.btn-settings' ? gear : null),
createElement: () => ({}),
body: { appendChild: () => {} },
},
document: doc,
window: {},
navigator: {},
});
@@ -100,7 +102,7 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
// Recording itself is out of scope: start() only has to pick the target.
voice._resolveProvider = () => 'webspeech';
voice._startWebSpeech = vi.fn();
return { voice, app, sendInput, sendInputAsync, appendText, overlayClear, showToast, gear };
return { voice, app, sendInputAsync, appendText, overlayClear, showToast, gear, doc };
}
function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] } } }) {
@@ -110,24 +112,23 @@ function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] }
describe('dictation target', () => {
it('sends to the session recording started in, even after a tab switch', () => {
const { voice, app, sendInput, sendInputAsync } = load();
const { voice, app, sendInputAsync } = load();
voice.start();
app.activeSessionId = 'session-b'; // user switched tabs while speaking
voice._insertText('fix the login bug');
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'fix the login bug', { useMux: true });
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, sendInputAsync } = load({ pane: { sessionId: 'session-a', isPrimary: true } });
voice.start();
voice._insertText('hello');
expect(sendInput).toHaveBeenCalledWith('hello');
expect(sendInputAsync).not.toHaveBeenCalled();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'hello', { useMux: true });
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send');
});
it('never types another session dictation into the active local-echo overlay', () => {
@@ -142,13 +143,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 } = load({
localEcho: true,
pane: { sessionId: 'session-a', isPrimary: true },
});
voice.start();
voice._insertText('typed locally');
expect(appendText).toHaveBeenCalledWith('typed locally');
expect(sendInput).not.toHaveBeenCalled();
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-insert');
});
it('takes its target from the focused pane when one is reported', () => {
@@ -161,7 +165,7 @@ describe('dictation target', () => {
});
it('the green send button sends Enter to the dictation target', () => {
const { voice, app, gear, sendInput, sendInputAsync } = load();
const { voice, app, gear, sendInputAsync } = load();
voice.start();
voice._insertText('ship it');
app.activeSessionId = 'session-b';
@@ -170,26 +174,23 @@ 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);
});
it('drops dictation for a session that closed meanwhile, with a toast', () => {
const { voice, app, sendInput, sendInputAsync, showToast } = load();
const { voice, app, sendInputAsync, showToast } = load();
voice.start();
app.activeSessionId = 'session-b';
(app.sessions as Map<string, unknown>).delete('session-a');
voice._insertText('too late');
expect(sendInput).not.toHaveBeenCalled();
expect(sendInputAsync).not.toHaveBeenCalled();
expect(showToast).toHaveBeenCalledWith('That session has closed; dictation not sent', 'warning');
});
it('with the tile grid open, dictation goes to the focused tile, not the parked overlay', () => {
const tileTerminal = { focus: vi.fn() };
const { voice, app, appendText, sendInput, sendInputAsync } = load({
const { voice, app, appendText, sendInputAsync } = load({
localEcho: true,
tiles: true,
pane: { sessionId: 'session-a', isPrimary: false, terminal: tileTerminal },
@@ -199,8 +200,7 @@ describe('dictation target', () => {
voice._insertText('into the tile');
expect(appendText).not.toHaveBeenCalled();
expect(sendInput).toHaveBeenCalledWith('into the tile');
expect(sendInputAsync).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 +208,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, sendInputAsync, overlayClear } = load({
localEcho: true,
tiles: true,
pane: { sessionId: 'session-a', isPrimary: false, terminal: tileTerminal },
@@ -221,29 +221,136 @@ describe('dictation target', () => {
clickGreenSend(gear);
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, 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(sendInput).not.toHaveBeenCalled();
expect((app.terminal as { focus: ReturnType<typeof vi.fn> }).focus).toHaveBeenCalled();
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(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();
});
it('compose Send delivers only the reviewed dictation and leaves the typed draft in the overlay', () => {
const { voice, app, appendText, overlayClear, sendInputAsync, doc } = load({
insertMode: 'compose',
localEcho: true,
pane: { sessionId: 'session-a', isPrimary: true },
});
const overlay = app._localEchoOverlay as { pendingText: string };
overlay.pendingText = 'hel';
const handlers = new Map<string, () => void>();
const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 };
doc.createElement = () => ({
className: '',
dataset: {},
innerHTML: '',
remove: vi.fn(),
addEventListener: vi.fn(),
querySelector: (sel: string) =>
sel === 'textarea'
? textarea
: { addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler) },
});
voice.start();
voice._insertText('Please fix the bug');
// The dialog's <textarea> gets the text through innerHTML; this stub has no
// HTML parser, so the user's reviewed text is set directly before Send.
textarea.value = 'Please fix the bug';
handlers.get('.paste-send')!();
expect(sendInputAsync).toHaveBeenCalledOnce();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'Please fix the bug\r', { useMux: true });
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send');
expect(overlay.pendingText).toBe('hel');
expect(appendText).not.toHaveBeenCalled();
expect(overlayClear).not.toHaveBeenCalled();
});
it('retargets an existing compose overlay for the next dictation', () => {
const { voice, sendInputAsync, doc } = load({ insertMode: 'compose' });
const handlers = new Map<string, () => void>();
const textarea = {
value: '',
focus: vi.fn(),
blur: vi.fn(),
selectionStart: 0,
selectionEnd: 0,
closest: (): { dataset: Record<string, string> } => overlay,
};
const overlay = {
dataset: {},
className: '',
innerHTML: '',
remove: vi.fn(),
addEventListener: vi.fn(),
querySelector: (sel: string) =>
sel === 'textarea'
? textarea
: {
addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler),
},
};
doc.createElement = () => overlay;
voice._targetSessionId = 'session-a';
voice._insertText('first dictation');
doc.querySelector = (sel: string) => (sel === '.voice-compose-overlay .paste-textarea' ? textarea : null);
voice._targetSessionId = 'session-b';
voice._insertText('second dictation');
handlers.get('.paste-send')!();
expect(sendInputAsync).toHaveBeenCalledExactlyOnceWith('session-b', 'second dictation\r', { useMux: true });
});
it('refuses to start with no session at all', () => {
const { voice, app, showToast } = load();
app.activeSessionId = null;
+17 -3
View File
@@ -51,7 +51,9 @@ describe('xterm private-API dependency guard', () => {
'CompositionHelper fields installEditSync() uses (terminal-keycode229-recovery.js: ' +
'_handleAnyTextareaChanges, _coreService, _isComposing, _isSendingComposition, _dataAlreadySent) ' +
'and the mouse-encoding read _shouldForwardTouchToApp makes (terminal-ui.js: ' +
'_core.coreMouseService.activeEncoding), then update VERIFIED_XTERM_VERSION here. ' +
'_core.coreMouseService.activeEncoding) and the iOS native-input owner (terminal-ios-native-input.js: ' +
'_core._inputEvent, _core._handleTextAreaBlur, _compositionHelper._finalizeComposition, ' +
'_compositionHelper._compositionView), then update VERIFIED_XTERM_VERSION here. ' +
'The accessor is optional-chained, so a renamed field ' +
'degrades to a silent no-op and the freeze it heals comes back unnoticed.'
).toBe(VERIFIED_XTERM_VERSION);
@@ -67,6 +69,12 @@ describe('xterm private-API dependency guard', () => {
// only to an app that asked for SGR mouse reports; if either name changes the read is undefined
// and touch quietly stops forwarding to native SGR tracking apps. Property names survive
// minification, so a string check on the shipped bundle catches a rename on upgrade.
// terminal-ios-native-input.js wraps `_inputEvent`, `_handleTextAreaBlur` and `_finalizeComposition`
// and reads `_compositionView`; if any is missing its create() returns null, and iOS falls back
// to the keyCode-229 recovery, so #830 (suggestions, phrase replacement, held delete) returns
// without a signal.
// The iOS owner also clears `_unprocessedDeadKey` when native input commits text,
// so the next terminal command is not swallowed as part of the dead-key sequence.
it('still ships the composition-helper and mouse-service fields terminal input depends on', () => {
const bundle = readFileSync(resolve(root, 'node_modules/@xterm/xterm/lib/xterm.js'), 'utf8');
for (const name of [
@@ -78,12 +86,18 @@ describe('xterm private-API dependency guard', () => {
'_dataAlreadySent',
'coreMouseService',
'activeEncoding',
'_inputEvent',
'_unprocessedDeadKey',
'_handleTextAreaBlur',
'_finalizeComposition',
'_compositionView',
]) {
expect(
bundle,
`xterm no longer mentions ${name}: re-verify terminal-keycode229-recovery.js installEditSync() ` +
'against the new CompositionHelper, and terminal-ui.js _shouldForwardTouchToApp against the ' +
'new CoreMouseService (both in src/web/public), before bumping VERIFIED_XTERM_VERSION'
'against the new CompositionHelper, terminal-ios-native-input.js create() against the new ' +
'CoreBrowserTerminal and CompositionHelper, and terminal-ui.js _shouldForwardTouchToApp against the ' +
'new CoreMouseService (all in src/web/public), before bumping VERIFIED_XTERM_VERSION'
).toContain(name);
}
});