fix(web): bind Send on Enter to the captured session, keep the voice draft (#830)

Held-mode Ctrl, Backspace and restored drafts send to the session their text was typed for; a Ctrl-only field releases it.
Voice compose Send settles the iOS owner without flushing the unsent local-echo draft.
Cover Send on Enter across focus moves, the toolbar Enter in the CJK field and the same-session reload.
Describe Pane B iOS input ownership; drop a stub for a removed helper.
This commit is contained in:
Hadrien Kerlero committed 2026-11-20 21:11:33 +01:00
1 parent eb22f10fd4
commit ddb5a647ba
8 files changed
+254 -85

No files matched your search

+1 -1
View File
@@ -1083,7 +1083,7 @@ Tests: `test/tab-rail-search.test.ts` (gate) and `test/tab-rail-search.browser.t
### Split-pane sessions
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own keyCode-229 soft-keyboard controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring terminal-ui.js's reasoning: in a plain shell it is the user's own job-control tool, everywhere else it silently suspends an unattenLine truncated
**Split-pane sessions** (`showSplitButton`, header button, default OFF, per-device like `showFileViewerButton` — not in `SettingsUpdateSchema`, `displayKeys` in settings-ui.js): shows two live sessions side-by-side in one Codeman window. Pane A is the untouched, existing singleton terminal (`this.terminal`/`this._ws` in terminal-ui.js); Pane B is an independent `TerminalTile` (terminal-tile.js, constructed by the orchestration in terminal-split.js) with its own xterm instance and its own `/ws/sessions/:id/terminal` WebSocket, whose `cid` is the tab's identity with a `:tile` suffix, so it can never supersede the primary pane's socket (the registry supersedes by cid per session). ⚠️ **Pane B is deliberately plainer than Pane A** — no local-echo overlay, no CJK IME, no touch/mobile handlers, no keyboard accessory bar (it does carry the primary pane's hollow-buffer wheel paging and desktop click report, through terminal-ui.js's own gates aimed at the tile, and its own soft-keyboard input owner: the iOS native-input owner (`_iosNativeInput`, terminal-ios-native-input.js, #830) on iOS WebKit touch, otherwise the keyCode-229 controller from terminal-keycode229-recovery.js, the #441 next-keydown drain and #541's edit-based diff for Android autocorrect, since the 1180px width gate is reachable by a wide Android tablet; see terminal-tile.js's fileoverview) — since this is a desktop-only feature (a split view needs a wide viewport) and those features exist for mobile/touch input; `.btn-split` is hard-hidden below 1180px regardless of the setting by the `@media (max-width: 1179px)` rule in styles.css (mobile.css only carries a comment pointing at it: that file loads up to 1023px, so it cannot cover the 1024-1179px tablet range the feature also needs to stay off), and the per-device setting means turning it on at a desk can never sync it onto a phone in the first place. No persistence: closing the browser tab or reloading always returns to the normal single-pane view; there is no localStorage key for split state. ⚠️ Splitting a session against itself is disallowed (the picker excludes the active session), **as is splitting against a popped-out (detached) session** — `buildSplitPickerSessions()` excludes `detachedSessions` because a detached session's own window is already claiming its PTY size, and `MAX_WS_PER_SESSION` needs no change since Pane A/B are always two different sessions. ⚠️ Either pane's session ending (deleted locally or from another client) auto-collapses the split — Pane A's session ending promotes Pane B to the new single pane via `selectSession(id, { auto: true })` (an app-driven selection, so it must not spend the session's idle alert — see the Approvals Inbox note above), never by trying to hot-swap the lightweight `TerminalTile` object into the primary singleton state. ⚠️ Pane B refits on every window/sidebar/tab-rail resize via the SAME trailing-edge `ResizeObserver` callback that resizes Pane A (`throttledResize` in terminal-ui.js) — it only ever measured Pane A's own container, so without the explicit `this._forEachTile?.((tile) => tile.fit(), { grid: false })` call there (grid tiles are left out: the grid's own observer refits them on the same resize) Pane B silently kept its stale PTY size through every resize that did not happen to be a divider drag. ⚠️ A dropped WebSocket writes a `[disconnected, reconnecting…]` marker into Pane B and reconnects on the primary pane's backoff ladder (`CodemanWsReconnect` plus jitter; the attempt count resets only on a successful open), then refreshes the buffer to close the output gap. ⚠️ The open handler clears `_wsClosed`/`_markerOwed` BEFORE that refresh, or the refresh re-owes the marker and stamps it under a healthy pane. ⚠️ 4003/4004/4009/4010 stop the pane for good, report once through `onExit(code)` and write a marker saying why (`CodemanWsReconnect` alone would retry 4003). ⚠️ A replacement socket detaches the old one first and every handler ignores a socket that is no longer `this.ws`, so a late 4010 from a superseded socket cannot stop its successor; `destroy()` cancels a pending reconnect. Related but distinct: `detachSession()` already opens one session in a separate OS-level browser window (`isSoloWindow`) — that is prior art for "two sessions visible at once" but not for one window with a draggable in-page divider, which is what this feature adds. ⚠️ Pane B installs its own `attachCustomKeyEventHandler` gating the same app-level chords Pane A's own handler gates (command palette, Alt+1-9/[/] tab nav, Alt+B sidebar toggle, Ctrl+Z suspend, Shift/Ctrl+Enter newline, smart-copy Ctrl+C) — without it the document capture-phase handler's `preventDefault()` (which never stops xterm) let each chord ALSO write its raw byte/escape sequence into Pane B's live PTY on top of whatever the app action did to Pane A (COD-153). Ctrl+Z is swallowed unless Pane B's own session is `mode === 'shell'`, mirroring Line truncated
### Tile grid
+16 -5
View File
@@ -353,10 +353,17 @@ const CjkInput = (() => {
return;
}
_t('hold ctrl key');
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
_send(now[at]);
// The control key goes to the session this field's text was captured for;
// with no draft left, the next answer captures its own destination.
const target = _targetForSend();
if (!before) {
_resetToPhantom();
} else {
_textarea.value = PHANTOM + before;
_textarea.setSelectionRange(1 + at, 1 + at);
_heldBase = before;
}
_send(now[at], target);
}
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
@@ -370,7 +377,7 @@ const CjkInput = (() => {
const wasEmpty = !_heldBase;
_heldBase = _strip(_textarea.value);
if (!_heldBase) {
if (wasEmpty) _send('\x7f');
if (wasEmpty) _send('\x7f', _targetForSend());
_resetToPhantom();
} else if (!_textarea.value.startsWith(PHANTOM)) {
// Backspace at the very start of the text deleted the phantom: put it
@@ -801,6 +808,10 @@ const CjkInput = (() => {
_textarea.value = PHANTOM + draft;
_textarea.setSelectionRange(_textarea.value.length, _textarea.value.length);
_heldBase = draft;
// The restored text belongs to this session: Enter after a focus move to
// another pane must still send it here (see _targetForSend).
_target = sessionId;
_hasTarget = true;
_autoGrow();
},
+3 -1
View File
@@ -1079,8 +1079,10 @@ const VoiceInput = {
app.showToast?.('That session has closed; dictation not sent', 'warning');
return Promise.resolve();
}
// Settle the destination's iOS owner, but leave an unsent local-echo draft
// in the overlay: flushing it would prepend it to the reviewed dictation.
const pane = app._paneForSession?.(target);
if (pane) app._prepareExternalInput?.(pane, 'voice-send', { flushEcho: true });
if (pane) app._prepareExternalInput?.(pane, 'voice-send');
app._sendInputAsync(target, text, { useMux: true });
return Promise.resolve();
},
+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('submitFromToolbar()', 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', () => {
-8
View File
@@ -206,14 +206,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);
+50 -47
View File
@@ -554,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();
});
@@ -582,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).
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 {
@@ -618,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 {
@@ -646,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();
}
@@ -671,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();
});
});
+118 -8
View File
@@ -86,7 +86,11 @@ function loadProducerModules(app: object, context: vm.Context) {
}
function attachCjk(
app: { _focusedPane: () => { sessionId: string } | null; _handleCjkInput: (text: string, sessionId: string) => void },
app: {
_focusedPane: () => { sessionId: string } | null;
_handleCjkInput: (text: string, sessionId: string) => void;
_sendCjkPrompt: (text: string, sessionId: string) => boolean;
},
context: vm.Context
) {
const listeners = new Map<string, (event: object) => void>();
@@ -94,6 +98,8 @@ function attachCjk(
value: '',
selectionStart: 1,
selectionEnd: 1,
style: {},
setAttribute: vi.fn(),
setSelectionRange: vi.fn(),
addEventListener: (name: string, fn: (event: object) => void) => listeners.set(name, fn),
removeEventListener: vi.fn(),
@@ -105,6 +111,7 @@ function attachCjk(
cjk.init({
captureTarget: () => app._focusedPane()?.sessionId,
send: (text: string, sessionId: string) => app._handleCjkInput(text, sessionId),
sendPrompt: (text: string, sessionId: string) => app._sendCjkPrompt(text, sessionId),
});
return { cjk, field, fire: (name: string, event = {}) => listeners.get(name)!(event) };
}
@@ -491,6 +498,102 @@ describe('native main transactions and boundaries', () => {
cjk.destroy();
});
it('Send on Enter keeps a held answer, its gap and Enter on the session it was typed for', () => {
const { app, wire, context } = harness();
context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false };
const { cjk, field, fire } = attachCjk(app, context);
cjk.setHoldUntilEnter(true);
field.value = '\u200By';
fire('input', { inputType: 'insertText', isComposing: false });
// Focus moves to Pane B before Enter; the held answer still belongs to A.
const tile = { sessionId: 'new', terminal: {} };
app._splitPane = tile;
app._noteFocusedTile(tile);
fire('keydown', { key: 'Enter', preventDefault: vi.fn() });
expect(wire).toEqual([['old', 'y']]);
vi.advanceTimersByTime(120);
expect(wire).toEqual([
['old', 'y'],
['old', '\r'],
]);
cjk.destroy();
});
it('Send on Enter sends a restored draft to its own session after focus moves, without an edit', () => {
const { app, wire, context } = harness();
context.KeyboardAccessoryBar = { clearCtrl: vi.fn(), isCtrlArmed: () => false };
const { cjk, field, fire } = attachCjk(app, context);
cjk.setHoldUntilEnter(true);
// A draft typed for `old` is stashed on a switch and restored on the way back.
field.value = '\u200By';
fire('input', { inputType: 'insertText', isComposing: false });
cjk.stashDraft('old');
cjk.clear();
cjk.restoreDraft('old');
expect(field.value).toBe('\u200By');
// Focus moves to Pane B; Enter is pressed without touching the draft.
const tile = { sessionId: 'new', terminal: {} };
app._splitPane = tile;
app._noteFocusedTile(tile);
fire('keydown', { key: 'Enter', preventDefault: vi.fn() });
vi.advanceTimersByTime(120);
expect(wire).toEqual([
['old', 'y'],
['old', '\r'],
]);
cjk.destroy();
});
it('Send on Enter sends a held-mode Ctrl key to the session it was typed for across a focus move', () => {
const { app, wire, context } = harness();
loadProducerModules(app, context);
const bar = vm.runInContext('KeyboardAccessoryBar', context);
const { cjk, field, fire } = attachCjk(app, context);
cjk.setHoldUntilEnter(true);
field.value = '\u200Bab';
fire('input', { inputType: 'insertText', isComposing: false });
bar.toggleCtrl();
fire('compositionstart');
// Focus moves to Pane B before the composition commits `c`.
const tile = { sessionId: 'new', terminal: {} };
app._splitPane = tile;
app._noteFocusedTile(tile);
field.value = '\u200Babc';
fire('compositionend');
vi.advanceTimersByTime(0);
expect(wire).toEqual([['old', '\x03']]);
expect(field.value).toBe('\u200Bab');
cjk.destroy();
});
it('Send on Enter lets the next answer capture its own session after Ctrl empties the field', () => {
const { app, wire, context } = harness();
loadProducerModules(app, context);
const bar = vm.runInContext('KeyboardAccessoryBar', context);
const { cjk, field, fire } = attachCjk(app, context);
cjk.setHoldUntilEnter(true);
bar.toggleCtrl();
fire('keydown', { key: 'c' });
field.value = '\u200Bc';
fire('input', { inputType: 'insertText', isComposing: false });
expect(wire).toEqual([['old', '\x03']]);
// Focus moves to Pane B; a fresh answer typed there belongs to B.
const tile = { sessionId: 'new', terminal: {} };
app._splitPane = tile;
app._noteFocusedTile(tile);
fire('keydown', { key: 'y' });
field.value = '\u200By';
fire('input', { inputType: 'insertText', isComposing: false });
fire('keydown', { key: 'Enter', preventDefault: vi.fn() });
vi.advanceTimersByTime(120);
expect(wire).toEqual([
['old', '\x03'],
['new', 'y'],
['new', '\r'],
]);
cjk.destroy();
});
it('keeps an unfinished CJK composition on B after focus moves to A', () => {
const { app, wire, context } = harness();
const { cjk, field, fire } = attachCjk(app, context);
@@ -620,7 +723,7 @@ describe('native main transactions and boundaries', () => {
}
);
it.each(['upload', 'voice', 'Esc', 'paste'])(
it.each(['upload', 'Esc', 'paste'])(
'%s preserves the typed prefix before direct writes with echo on or off',
async (producer) => {
for (const echo of [true, false]) {
@@ -656,12 +759,6 @@ describe('native main transactions and boundaries', () => {
['old', '/p'],
['old', '\r'],
]);
} else if (producer === 'voice') {
await vm.runInContext("VoiceInput._sendToTarget('old', 'world')", context);
expect(wire).toEqual([
['old', 'hel'],
['old', 'world'],
]);
} else if (producer === 'Esc') {
vm.runInContext("KeyboardAccessoryBar.sendKey('\\x1b')", context);
expect(wire).toEqual([
@@ -694,6 +791,19 @@ describe('native main transactions and boundaries', () => {
}
});
it('sends voice dictation without submitting the unsent local-echo draft', async () => {
for (const echo of [true, false]) {
const { app, wire, context } = harness();
loadProducerModules(app, context);
app._localEchoEnabled = echo;
app._handleTerminalData('hel', 'old');
await vm.runInContext("VoiceInput._sendToTarget('old', 'world\\r')", context);
// Echo on: `hel` stays in the overlay. Echo off: it was already typed into the PTY.
expect(wire).toEqual([...(echo ? [] : [['old', 'hel']]), ['old', 'world\r']]);
expect(app._localEchoOverlay.pendingText).toBe(echo ? 'hel' : '');
}
});
it('keeps the typed prefix in the overlay when a toolbar attachment appends', async () => {
const { app, wire, context } = harness();
loadProducerModules(app, context);
+44 -9
View File
@@ -78,6 +78,11 @@ function load(opts: { insertMode?: string; localEcho?: boolean; focused?: string
}
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(),
@@ -90,11 +95,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: {},
});
@@ -103,7 +104,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, sendInput, sendInputAsync, appendText, overlayClear, showToast, gear, doc };
}
function clickGreenSend(gear: { addEventListener: { mock: { calls: unknown[][] } } }) {
@@ -131,9 +132,7 @@ describe('dictation target', () => {
expect(sendInput).not.toHaveBeenCalled();
expect(sendInputAsync).toHaveBeenCalledWith('session-a', 'hello', { useMux: true });
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send', {
flushEcho: true,
});
expect(app._prepareExternalInput).toHaveBeenCalledWith({ sessionId: 'session-a', isPrimary: true }, 'voice-send');
});
it('never types another session dictation into the active local-echo overlay', () => {
@@ -289,6 +288,42 @@ describe('dictation target', () => {
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: '',
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('refuses to start with no session at all', () => {
const { voice, app, showToast } = load();
app.activeSessionId = null;