fix(web): exact iOS caret, review fixes and round-eight items (#830)

Toolbar Enter spends one-shot Ctrl; Backspace finds the last grapheme with Segments.containing(); accessory Shift+Tab keeps the draft like a typed one.
Pass the captured session to Compose uploads, voice compose and held CJK drafts; clear Ctrl on deletion-only native edits; path picker clears predictions.
Clear xterm dead-key state on native commits; restore a borrowed clipboard field before classifying a key; overlay removeChar spans the pending/flushed boundary.
Place the trackpad caret from the overlay layout (getInputAnchor, committedText) or validated xterm cells, hiding when unproven; no end-minus-width arithmetic.
Grapheme-aware replay Backspace; docs, README rows, changeset and comment updates.
This commit is contained in:
Hadrien Kerlero committed 2026-11-21 21:16:13 +01:00
1 parent 414dd51eb2
commit cda5d96451
26 files changed
+1072 -170

No files matched your search

+51 -16
View File
@@ -6,22 +6,32 @@
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,
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 },
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,
inputType,
data: data ?? null,
bubbles: true,
cancelable: type === 'beforeinput',
composed: true,
isComposing: !!options.isComposing,
});
}
@@ -35,12 +45,17 @@
if (inputType === 'deleteContentBackward') {
if (start === end) {
if (start === 0) return false;
start -= Array.from(value.slice(0, start)).pop().length;
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') {
} 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.
@@ -66,7 +81,11 @@
// 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');
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;
@@ -142,12 +161,28 @@
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,
}));
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,
kev,
iev,
edit,
capturedEdits,
typeKey,
backspace,
holdDeleteRepeat,
replaceSuggestion,
enter,
caret,
composition,
paste,
});
})(window);
+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');
+74 -14
View File
@@ -9,10 +9,11 @@ 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 } } } };
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } };
_customKeyEventHandler(event: KeyboardEvent): boolean;
};
}
@@ -21,6 +22,9 @@ interface NativeOwner {
}
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;
@@ -143,6 +147,19 @@ describe('iOS native input served-app wiring (#830)', () => {
}, 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);
@@ -194,26 +211,54 @@ describe('iOS native input served-app wiring (#830)', () => {
if (echo) expect(result.pending).toBe('lo');
});
it(`trackpad caret marker sits after he in hello (echo ${echo})`, async () => {
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);"
);
const geometry = await page.evaluate(() => {
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 marker = app.terminal.element.querySelector<HTMLElement>('.ios-native-caret')!;
const container = app.terminal.element.parentElement!;
const proposed = app.fitAddon.proposeDimensions()!;
const cell = app.terminal._core._renderService.dimensions.css.cell;
const end = app._localEchoEnabled
? app._localEchoOverlay.getInputEndAnchor()
: { col: app.terminal.buffer.active.cursorX, row: app.terminal.buffer.active.cursorY };
return {
display: marker.style.display,
col: parseFloat(marker.style.left) / cell.width,
expected: end!.col - 3,
};
// 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;
});
expect(geometry.display).not.toBe('none');
expect(geometry.col).toBeCloseTo(geometry.expected, 1);
// 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 () => {
@@ -386,6 +431,21 @@ describe('iOS native input served-app wiring (#830)', () => {
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 () => {
+4 -3
View File
@@ -386,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))
@@ -405,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();
@@ -620,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'));
});
@@ -685,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' });
});
});
+18
View File
@@ -48,6 +48,8 @@ function loadKeyboardModule() {
_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(),
};
@@ -186,6 +188,22 @@ describe('mobile filesystem picker actions', () => {
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) => {
+77 -11
View File
@@ -47,6 +47,9 @@ function harness() {
app._localEchoOverlay = {
pendingText: '',
flushed: '',
get committedText() {
return this.flushed + this.pendingText;
},
addChar(text: string) {
this.pendingText += text;
},
@@ -68,7 +71,7 @@ function harness() {
this[key] = Array.from(this[key]).slice(0, -1).join('');
return key === 'pendingText' ? 'pending' : 'flushed';
},
getInputEndAnchor: vi.fn(() => ({ col: 8, row: 2 })),
getInputAnchor: vi.fn(() => ({ col: 8, row: 2 })),
};
const wire: Array<[string, string]> = [];
app._enqueueReliableInput = vi.fn((id: string, text: string) => wire.push([id, text]));
@@ -367,6 +370,27 @@ describe('native main transactions and boundaries', () => {
);
});
it('spends Ctrl on a deletion-only transaction without resetting the owner', () => {
const { app, wire, context } = harness();
loadProducerModules(app, context);
app._localEchoEnabled = false;
app._iosNativeInput = { reset: vi.fn() };
const bar = vm.runInContext('KeyboardAccessoryBar', context);
bar.toggleCtrl();
app._sendNativeInputTransaction(['\x7f']);
expect(wire).toEqual([['old', '\x7f']]);
expect(bar.isCtrlArmed()).toBe(false);
expect(app._iosNativeInput.reset).not.toHaveBeenCalled();
app._sendNativeInputTransaction(['c']);
expect(wire).toEqual([
['old', '\x7f'],
['old', 'c'],
]);
expect(app._iosNativeInput.reset).not.toHaveBeenCalled();
});
it('settles, seals, flushes, resets owner and preview before session cleanup', () => {
const { app, wire } = harness();
attachCleanupStubs(app);
@@ -817,17 +841,21 @@ describe('native main transactions and boundaries', () => {
expect(app._localEchoOverlay.pendingText).toBe('hel /p ');
});
it('hides the caret when a buffering overlay cannot supply an anchor', () => {
it('maps the native suffix after a non-BMP committed prefix and hides mismatches or missing cells', () => {
const { app } = harness();
expect(app._nativeInputAnchor()).toBeNull();
app._localEchoOverlay.pendingText = 'text';
expect(app._nativeInputAnchor()).toEqual({ col: 8, row: 2 });
app._localEchoOverlay.getInputEndAnchor = () => null;
expect(app._nativeInputAnchor()).toBe('hide');
delete app._localEchoOverlay.getInputEndAnchor;
expect(app._nativeInputAnchor()).toBe('hide');
const caret = { visible: true, text: 'hello', offset: 2 };
expect(app._nativeInputCaretAnchor(caret)).toBeNull();
app._localEchoOverlay.flushed = '👍';
app._localEchoOverlay.pendingText = 'hello';
expect(app._nativeInputCaretAnchor(caret)).toEqual({ col: 8, row: 2 });
expect(app._localEchoOverlay.getInputAnchor).toHaveBeenLastCalledWith(4);
expect(app._nativeInputCaretAnchor({ ...caret, text: 'hullo' })).toBe('hide');
app._localEchoOverlay.getInputAnchor = () => null;
expect(app._nativeInputCaretAnchor(caret)).toBe('hide');
delete app._localEchoOverlay.getInputAnchor;
expect(app._nativeInputCaretAnchor(caret)).toBe('hide');
app._echoPassthroughSessions = new Set(['old']);
expect(app._nativeInputAnchor()).toBeNull();
expect(app._nativeInputCaretAnchor(caret)).toBeNull();
});
it('prepares only the captured tile owner, not the primary owner', () => {
@@ -854,6 +882,44 @@ describe('native main transactions and boundaries', () => {
app.submitFromToolbar();
expect(wire).toHaveLength(2);
});
it('toolbar Enter spends an armed one-shot Ctrl, so the next typed c stays a c', () => {
for (const echo of [true, false]) {
const { app, wire, context } = harness();
loadProducerModules(app, context);
app._localEchoEnabled = echo;
const bar = vm.runInContext('KeyboardAccessoryBar', context);
bar.toggleCtrl();
expect(bar.isCtrlArmed()).toBe(true);
app.submitFromToolbar();
vi.advanceTimersByTime(80);
expect(bar.isCtrlArmed()).toBe(false);
wire.length = 0;
app._handleTerminalData('c', 'old');
app.submitFromToolbar();
vi.advanceTimersByTime(80);
expect(wire).toEqual([
['old', 'c'],
['old', '\r'],
]);
}
});
it('accessory Shift+Tab leaves the unsent draft in the overlay, as a typed Shift+Tab does', () => {
const { app, wire, context } = harness();
loadProducerModules(app, context);
app._handleTerminalData('hel', 'old');
vm.runInContext("KeyboardAccessoryBar.handleAction('shift-tab')", context);
expect(wire).toEqual([['old', '\x1b[Z']]);
expect(app._localEchoOverlay.pendingText).toBe('hel');
// The typed key takes the same path: the draft stays put.
app._handleTerminalData('\x1b[Z', 'old');
expect(wire).toEqual([
['old', '\x1b[Z'],
['old', '\x1b[Z'],
]);
expect(app._localEchoOverlay.pendingText).toBe('hel');
});
it('resets native ownership before dispatching synthetic compositionend', () => {
const { app, context } = harness();
attachCleanupStubs(app);
@@ -916,7 +982,7 @@ describe('native main transactions and boundaries', () => {
options.onTransaction(transaction);
expect(app._mobileImePreview.nativeTransaction).toHaveBeenCalledWith(transaction);
const markerOptions = native.attachCaretMarker.mock.calls[0][2];
expect(markerOptions.anchor()).toBeNull();
expect(markerOptions.anchor({ visible: true, text: 'native', offset: 2 })).toBeNull();
expect(markerOptions.subscribe(vi.fn())).toBe(unsubscribe);
app._initTerminalInputOwner();
expect(owner.destroy).toHaveBeenCalledOnce();
+255 -27
View File
@@ -11,7 +11,8 @@ import { describe, expect, it, vi } from 'vitest';
type Event = Record<string, unknown>;
interface Caret {
visible: boolean;
cellsFromEnd: number;
text: string;
offset: number;
}
interface Transaction {
inserted: string;
@@ -45,7 +46,7 @@ interface NativeApi {
terminal: FakeTerminal,
owner: NativeOwner,
options?: {
anchor?: () => { col: number; row: number } | 'hide' | null | undefined;
anchor?: (caret: Caret) => { col: number; row: number } | 'hide' | null | undefined;
subscribe?: (callback: () => void) => () => void;
}
): () => void;
@@ -65,23 +66,41 @@ interface FakeHelper {
_isSendingComposition: boolean;
}
interface FakeCore {
_inputEvent(): unknown;
_inputEvent(ev?: Event): unknown;
_unprocessedDeadKey?: boolean;
_handleTextAreaBlur(): void;
_compositionHelper: FakeHelper;
coreService: { triggerDataEvent(): void; decPrivateModes?: { applicationCursorKeys: boolean } };
unicodeService: { getStringCellWidth?: (text: string) => number };
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } | null };
}
interface BufferCell {
getChars(): string;
getWidth(): number;
}
interface BufferLine {
isWrapped: boolean;
getCell(col: number): BufferCell | undefined;
}
interface FakeTerminal {
textarea: FakeTextarea;
element: FakeNode;
_core: FakeCore;
cols: number;
rows: number;
buffer: { active: { cursorX: number; cursorY: number; baseY: number; viewportY: number } };
buffer: {
active: {
cursorX: number;
cursorY: number;
baseY: number;
viewportY: number;
getLine(row: number): BufferLine | undefined;
};
};
options: { theme: { cursor: string }; screenReaderMode: boolean };
onRender(callback: () => void): { dispose(): void };
onCursorMove(callback: () => void): { dispose(): void };
onWriteParsed(callback: () => void): { dispose(): void };
}
interface Harness {
api: NativeApi;
@@ -108,6 +127,7 @@ interface Harness {
screen: FakeNode;
renders: Set<() => void>;
moves: Set<() => void>;
parsed: Set<() => void>;
owner: NativeOwner;
tick(): void;
selection(start: number, end?: number, direction?: string): void;
@@ -252,6 +272,18 @@ class FakeTextarea extends FakeNode {
}
}
function bufferLine(cells: Array<string | [string, number]>, isWrapped = false): BufferLine {
return {
isWrapped,
getCell(col) {
const value = cells[col];
if (value === undefined) return undefined;
const [chars, width] = typeof value === 'string' ? [value, 1] : value;
return { getChars: () => chars, getWidth: () => width };
},
};
}
function harness(
mode = 'direct',
options: {
@@ -324,6 +356,7 @@ function harness(
element.querySelector = (selector: string) => (selector === '.xterm-screen' ? screen : null);
const renders = new Set<() => void>();
const moves = new Set<() => void>();
const parsed = new Set<() => void>();
const subscribe = (set: Set<() => void>, callback: () => void) => {
set.add(callback);
return { dispose: () => set.delete(callback) };
@@ -334,10 +367,22 @@ function harness(
_core: core,
cols: 10,
rows: 5,
buffer: { active: { cursorX: 5, cursorY: 2, baseY: 0, viewportY: 0 } },
buffer: {
active: {
cursorX: 5,
cursorY: 2,
baseY: 0,
viewportY: 0,
getLine: (row) =>
row === terminal.buffer.active.baseY + terminal.buffer.active.cursorY
? bufferLine(Array.from(line + pending))
: undefined,
},
},
options: { theme: { cursor: '#fff' }, screenReaderMode: !!options.screenReaderMode },
onRender: (callback: () => void) => subscribe(renders, callback),
onCursorMove: (callback: () => void) => subscribe(moves, callback),
onWriteParsed: (callback: () => void) => subscribe(parsed, callback),
};
const originals = [
{ target: core, name: '_inputEvent' },
@@ -511,6 +556,7 @@ function harness(
screen,
renders,
moves,
parsed,
consume,
get owner() {
return owner;
@@ -1048,7 +1094,7 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
h.clearSent();
h.selection(2);
h.bytes([]);
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 3 });
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 });
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
const marker = h.screen.children[0];
expect(marker.attributes['aria-hidden']).toBe('true');
@@ -1062,23 +1108,20 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
h.edit('X');
h.bytes([...dels(3), 'Xllo']);
expect(h.value()).toBe('heXllo');
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 3 });
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 3 });
h.clearSent();
h.selection(6);
expect(marker.style.display).toBe('none');
h.bytes([]);
h.selection(3);
h.terminal.buffer.active.cursorX = 0;
h.terminal.buffer.active.cursorY = 1;
for (const callback of h.renders) callback();
expect([marker.style.left, marker.style.top]).toEqual(['56px', '0px']);
h.terminal.buffer.active.cursorY = 0;
for (const callback of h.moves) callback();
expect(marker.style.display).toBe('none');
expect(marker.style.display).toBe('none'); // No parsed echo of the edit yet.
h.terminal.buffer.active.cursorX = 6;
for (const callback of h.parsed) callback();
expect([marker.style.left, marker.style.top, marker.style.display]).toEqual(['24px', '32px', 'block']);
dispose();
dispose();
expect(h.screen.children).toHaveLength(0);
expect(h.renders.size + h.moves.size).toBe(0);
expect(h.renders.size + h.moves.size + h.parsed.size).toBe(0);
},
],
[
@@ -1142,10 +1185,10 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
h.core.coreService.decPrivateModes = { applicationCursorKeys };
h.selection(1);
h.bytes([]);
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 2 });
expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 });
}
h.core.unicodeService.getStringCellWidth = undefined;
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 1 });
expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 });
h.selection(2);
expect(h.owner.caret().visible).toBe(false);
},
@@ -1159,7 +1202,8 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
const unsubscribe = h.owner.onCaret((caret: Caret) => changes.push(caret));
h.selection(2);
h.selection(2);
expect(changes).toEqual([{ visible: true, cellsFromEnd: 3 }]);
expect(changes).toMatchObject([{ visible: true, text: 'hello', offset: 2 }]);
expect(changes).toHaveLength(1);
h.blur();
const before = h.caretChanges.length;
h.document.fire('selectionchange');
@@ -1179,16 +1223,16 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
},
],
[
'31 projected code-point caret',
'31 projected UTF-16 caret',
(h) => {
h.edit('a👍\nb');
h.clearSent();
h.selection(4);
expect(h.owner.caret().cellsFromEnd).toBe(1);
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 4 });
h.selection(3);
expect(h.owner.caret().cellsFromEnd).toBe(2);
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 3 });
h.selection(1);
expect(h.owner.caret().cellsFromEnd).toBe(h.core.unicodeService.getStringCellWidth!('👍 b'));
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 1 });
h.selection(3);
h.edit('X');
h.bytes([DEL, DEL, 'X b']);
@@ -1231,7 +1275,7 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
});
h.edit('X', [2, 2], 'insertText', false, false);
h.bytes(['hello', ...dels(3), 'Xllo']);
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 2 });
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 4 });
h.invariant();
},
],
@@ -1280,6 +1324,19 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
}
},
],
[
'contextmenu clipboard snapshot restores before empty-line Backspace classification',
(h) => {
expect(h.textarea.value).toBe('');
h.terminal.element.fire('contextmenu');
// xterm's bubble handler writes a selection before its next capture keydown.
h.textarea.value = 'clipboard';
h.selection(0, 9);
expect(h.owner.keyFilter({ type: 'keydown', key: 'Backspace', keyCode: 8 })).toBe(true);
expect(h.textarea.value).toBe('');
h.bytes([]);
},
],
];
for (const mode of ['direct', 'local-echo']) {
@@ -1289,6 +1346,166 @@ for (const mode of ['direct', 'local-echo']) {
}
describe('CodemanIosNativeInput integration contract', () => {
it('projects CRLF and LF prefixes into UTF-16 caret offsets', () => {
const h = harness();
h.edit('a👍\r\nb\nc');
for (const [selection, offset] of [
[1, 1],
[3, 3],
[5, 4],
[7, 6],
]) {
h.selection(selection);
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b c', offset });
}
});
it('hides pending, invalidated and foreign native snapshots', () => {
const h = harness();
h.type('hello');
h.selection(2);
expect(h.owner.caret().visible).toBe(true);
h.textarea.value = 'hellox';
h.selection(2);
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hellox', offset: 2 });
h.textarea.fire('beforeinput');
expect(h.owner.caret().visible).toBe(false);
h.owner.reset('test');
h.type('hello');
h.selection(2);
h.terminal.element.fire('contextmenu');
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 });
});
it('maps a你b through validated wide-wrap padding to explicit cells', () => {
const h = harness();
h.type('a你b');
h.terminal.cols = 80;
const lines = new Map([
[0, bufferLine([...Array(78).fill(' '), 'a', ''])],
[1, bufferLine([['你', 2], ['', 0], 'b'], true)],
]);
Object.assign(h.terminal.buffer.active, { cursorX: 3, cursorY: 1, getLine: (row: number) => lines.get(row) });
h.selection(0);
const snapshot = h.snapshot();
const sent = [...h.sent];
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
const marker = h.screen.children[0];
for (const [offset, col, row] of [
[0, 78, 0],
[1, 0, 1],
[2, 2, 1],
]) {
h.selection(offset);
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual([
'block',
`${col * 8}px`,
`${row * 16}px`,
]);
}
h.selection(0);
expect(h.snapshot()).toEqual(snapshot);
expect(h.sent).toEqual(sent);
expect(h.document.activeElement).toBe(h.textarea);
h.terminal.buffer.active.viewportY = 1;
for (const callback of h.renders) callback();
expect(marker.style.display).toBe('none');
dispose();
});
it.each(['e\u0301', '👩‍💻'])('hides offsets inside one buffer cluster %s but maps its start', (cluster) => {
const h = harness();
h.type(cluster + 'b');
Object.assign(h.terminal.buffer.active, {
cursorX: 3,
cursorY: 0,
getLine: () => bufferLine([[cluster, 2], ['', 0], 'b']),
});
h.selection(1);
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
const marker = h.screen.children[0];
expect(marker.style.display).toBe('none');
h.selection(0);
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '0px', '0px']);
dispose();
});
it('hides an old identical hello until the next parsed write', () => {
const h = harness();
h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello'));
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
h.type('hello');
h.selection(2);
const marker = h.screen.children[0];
expect(marker.style.display).toBe('none');
for (const callback of h.renders) callback();
for (const callback of h.moves) callback();
expect(marker.style.display).toBe('none');
for (const callback of h.parsed) callback();
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '16px', '32px']);
dispose();
});
it('keeps the marker after a copy borrows and restores the native field, with no new output', () => {
const h = harness();
h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello'));
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
h.type('hello');
h.selection(2);
for (const callback of h.parsed) callback();
const marker = h.screen.children[0];
expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']);
// xterm's right-click handler lends the field to native Copy: a different
// terminal selection, then the copy timer restores the draft. No input is
// sent and no xterm write follows.
h.terminal.element.fire('contextmenu');
h.textarea.value = 'other selection';
h.selection(0, 15);
expect(marker.style.display).toBe('none');
h.document.fire('copy');
h.tick();
h.selection(2);
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 });
expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']);
dispose();
});
it('does not treat an unwritten cell as a native space', () => {
const h = harness();
h.type('a b');
h.selection(1);
Object.assign(h.terminal.buffer.active, { cursorX: 3, getLine: () => bufferLine(['a', '', 'b']) });
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
expect(h.screen.children[0].style.display).toBe('none');
dispose();
});
it('never crosses a hard line break while matching the native field', () => {
const h = harness();
h.type('ab');
h.selection(0);
const lines = new Map([
[0, bufferLine(['a'])],
[1, bufferLine(['b'])],
]);
Object.assign(h.terminal.buffer.active, { cursorX: 1, cursorY: 1, getLine: (row: number) => lines.get(row) });
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
expect(h.screen.children[0].style.display).toBe('none');
dispose();
});
it.each(['hellohello', 'hullo', 'xhello'])('checks the full buffer suffix and repetition for %s', (text) => {
const h = harness();
h.type('hello');
Object.assign(h.terminal.buffer.active, { cursorX: text.length, getLine: () => bufferLine(Array.from(text)) });
h.selection(2);
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
const marker = h.screen.children[0];
expect(marker.style.display).toBe(text === 'xhello' ? 'block' : 'none');
if (text === 'xhello') expect([marker.style.left, marker.style.top]).toEqual(['24px', '32px']);
dispose();
});
it('requires a transaction sink and leaves unsupported xterm internals untouched', () => {
const h = harness();
h.owner.destroy();
@@ -1311,6 +1528,16 @@ describe('CodemanIosNativeInput integration contract', () => {
expect(h.silent('input').defaultPrevented).toBe(false);
});
it('clears the pending dead key on committed native text without emitting xterm data', () => {
const h = harness();
h.core._unprocessedDeadKey = true;
expect(h.core._inputEvent({ data: 'é', inputType: 'insertText' })).toBe(false);
expect(h.core._unprocessedDeadKey).toBe(false);
expect(h.rawProducer).not.toHaveBeenCalled();
h.tick();
h.bytes([]);
});
it('notifies every settled edit, deletion-only/unchanged composition, and reset', () => {
const h = harness();
h.type('ab');
@@ -1363,8 +1590,8 @@ describe('CodemanIosNativeInput integration contract', () => {
expect(() => h.edit('hello')).not.toThrow();
expect(h.owner.state().synced).toBe('hello');
h.selection(2);
expect(() => h.edit('X')).not.toThrow();
expect(h.owner.state().synced).toBe('heXllo');
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 });
expect(h.owner.state().invalidated).toBe(true);
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('sendTransaction');
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('onTransaction');
});
@@ -1416,7 +1643,8 @@ describe('CodemanIosNativeInput integration contract', () => {
let layout = () => {};
const unsubscribe = vi.fn();
const dispose = h.api.attachCaretMarker(h.terminal, h.owner, {
anchor() {
anchor(caret) {
expect(caret).toMatchObject({ visible: true, text: 'hello', offset: 2 });
if (fail) throw new Error('layout');
return anchor;
},
@@ -1426,7 +1654,7 @@ describe('CodemanIosNativeInput integration contract', () => {
},
});
const marker = h.screen.children[0];
expect([marker.style.left, marker.style.top]).toEqual(['40px', '48px']);
expect([marker.style.left, marker.style.top]).toEqual(['64px', '48px']);
anchor = 'hide';
layout();
expect(marker.style.display).toBe('none');
+20 -4
View File
@@ -1543,7 +1543,7 @@ describe('TerminalTile iOS native input ownership', () => {
return { owner, create, attachCaretMarker, dispose, send: (ops: string[]) => options.sendTransaction(ops) };
};
it('creates an owner and xterm-cursor marker, but no 229 recovery, on iOS', async () => {
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();
@@ -1676,14 +1676,30 @@ describe('TerminalTile iOS native input ownership', () => {
expect(native.owner.reset).toHaveBeenCalledExactlyOnceWith('ctrl');
});
it('does not consume Ctrl for a deletion-only transaction', async () => {
it('spends Ctrl on a deletion-only transaction without resetting the owner', async () => {
const native = install();
const app = makeApp();
app._enqueueInput = vi.fn();
const consumeCtrl = vi.fn();
context.KeyboardAccessoryBar = { isCtrlArmed: () => true, consumeCtrl };
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();
});
+37
View File
@@ -290,6 +290,7 @@ describe('dictation target', () => {
const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 };
doc.createElement = () => ({
className: '',
dataset: {},
innerHTML: '',
remove: vi.fn(),
addEventListener: vi.fn(),
@@ -314,6 +315,42 @@ describe('dictation target', () => {
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;
+6 -2
View File
@@ -70,8 +70,11 @@ describe('xterm private-API dependency guard', () => {
// 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 then gets
// neither the native-input owner nor the keyCode-229 recovery, so #830 returns without a signal.
// 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 [
@@ -84,6 +87,7 @@ describe('xterm private-API dependency guard', () => {
'coreMouseService',
'activeEncoding',
'_inputEvent',
'_unprocessedDeadKey',
'_handleTextAreaBlur',
'_finalizeComposition',
'_compositionView',