fix(mobile): Send on Enter review fixes

- A long single line (over 64 characters) or several lines now go through
  the composer's _sendComposedPrompt: one bracketed paste, then Enter as a
  separate delayed write to the session captured at Enter. Claude Code took
  a long `<text>\r` burst as a paste and left it unsent, and the old delayed
  Enter followed a tab switch. A refused prompt keeps the text in the field.
- Deleting held text no longer sends Backspace to the PTY. It goes out only
  when the field was already empty (the phantom itself deleted), so
  select-all + delete is covered too.
- With the one-shot Ctrl armed, the next single typed character skips the
  hold and reaches _handleCjkInput, which turns it into the control byte;
  any other change spends the modifier, as in live mode.
- A reload of the session already shown (tapping its tab, the geometry
  retry) keeps a held draft.
- With the keyboard down the field stays one line tall, so it no longer
  covers the terminal's last rows.
- zh-CN strings for both field placeholders, and a test pinning
  cjkInputHoldUntilEnter as per-device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kamil KaliszandClaude Opus 5.5 committed 2026-11-16 14:18:18 +01:00
1 parent b8a4466643
commit 95fb147e9c
9 files changed
+474 -33

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
// test/cjk-hold-per-device-setting.test.ts
// Port: none (static analysis + vm, runs in CI, no browser/server).
//
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
// merge policy, stripped out of the object saveAppSettings() PUTs
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
// never declared in the schema. Plus the pieces around the mode: a held draft
// surviving a reload of the same session, the field staying one line tall with
// the keyboard down, and zh-CN strings for its placeholders.
import { describe, it, expect, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import vm from 'node:vm';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const PUBLIC = join(HERE, '../src/web/public');
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
const settingsUi = read('settings-ui.js');
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
it('is in the client-side displayKeys merge policy', () => {
const start = settingsUi.indexOf('const displayKeys = new Set([');
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
});
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
});
it('is never declared in the .strict() SettingsUpdateSchema', () => {
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
});
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
});
it('is loaded into and saved from its App Settings switch', () => {
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
expect(settingsUi).toContain(
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
);
});
});
describe('a held draft survives a reload of the same session', () => {
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
// activeSessionId before calling it on a same-session forceReload (tapping the
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
function cleanup(hold: boolean, keepCjkDraft: boolean) {
const clear = vi.fn();
const context = vm.createContext({
console,
setTimeout,
clearTimeout,
setInterval: vi.fn(),
clearInterval: vi.fn(),
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
fetch: vi.fn(),
URLSearchParams,
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
CjkInput: { holdUntilEnter: hold, clear },
});
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
};
app.activeSessionId = null;
app._clearTimer = vi.fn();
app._disconnectWs = vi.fn();
app._xtermSnapshots = new Map();
app.pendingWrites = [];
app._cleanupPreviousSession('s1', { keepCjkDraft });
return clear;
}
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
expect(cleanup(true, true)).not.toHaveBeenCalled();
});
it('still clears on a real switch', () => {
expect(cleanup(true, false)).toHaveBeenCalled();
});
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
expect(cleanup(false, true)).toHaveBeenCalled();
});
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
const appJs = read('app.js');
expect(appJs).toMatch(
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
);
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
});
});
describe('Send on Enter field layout and strings', () => {
it('keeps the field one line tall while the keyboard is down', () => {
// .main reserves a fixed 84px there; a grown field would cover the terminal.
expect(read('styles.css')).toMatch(
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
);
});
it('has zh-CN strings for both field placeholders', () => {
const i18n = read('i18n.js');
const cjk = read('input-cjk.js');
for (const placeholder of [
'CJK input (Enter = send, Esc = clear)',
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
]) {
expect(cjk).toContain(`'${placeholder}'`);
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
}
});
});
+148 -15
View File
@@ -45,15 +45,27 @@ function makeTextarea() {
};
}
function load({ hold = true } = {}) {
function load({ hold = true, promptResult = true } = {}) {
const textarea = makeTextarea();
const sent: string[] = [];
const prompts: string[] = [];
const layout = vi.fn();
// The shell bar's one-shot Ctrl, reduced to its armed flag.
const bar = {
armed: false,
isCtrlArmed() {
return this.armed;
},
clearCtrl() {
this.armed = false;
},
};
const context = vm.createContext({
window: {},
document: { getElementById: (id: string) => (id === 'cjkInput' ? textarea : null), activeElement: null },
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
KeyboardHandler: { updateLayoutForKeyboard: layout },
KeyboardAccessoryBar: bar,
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
performance: { now: () => performance.now() },
@@ -62,10 +74,16 @@ function load({ hold = true } = {}) {
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
vm.runInContext(src, context, { filename: 'input-cjk.js' });
const CjkInput = vm.runInContext('CjkInput', context);
CjkInput.init({ send: (t: string) => sent.push(t) });
CjkInput.init({
send: (t: string) => sent.push(t),
sendPrompt: (t: string) => {
prompts.push(t);
return promptResult;
},
});
CjkInput.setHoldUntilEnter(hold);
textarea.fire('focus');
return { CjkInput, textarea, sent, layout };
return { CjkInput, textarea, sent, prompts, layout, bar };
}
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
@@ -73,6 +91,14 @@ function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
}
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
textarea.value = valueAfter;
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
}
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
describe('CJK input: Send on Enter', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
@@ -127,20 +153,43 @@ describe('CJK input: Send on Enter', () => {
expect(sent).toEqual(['2\r']);
});
it('sends several lines as one bracketed paste, Enter as a later write', () => {
const { textarea, sent } = load();
type(textarea, 'line one\nline two');
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~']);
vi.advanceTimersByTime(150);
expect(sent).toEqual(['\x1b[200~line one\rline two\x1b[201~', '\r']);
it('sends a long single line as a prompt, never as one <text>\\r burst', () => {
// Claude Code takes a burst of ~100+ characters as a paste and its \r as a
// newline, so the answer would sit unsent (src/web/route-helpers.ts).
const { textarea, sent, prompts } = load();
const long = 'x'.repeat(150);
type(textarea, long);
enter(textarea);
expect(sent).toEqual([]);
expect(prompts).toEqual([long]);
expect(textarea.value).toBe(PHANTOM);
});
it('drops paste markers inside the held text', () => {
const { textarea, sent } = load();
type(textarea, 'a\x1b[201~b\nc');
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
expect(sent[0]).toBe('\x1b[200~ab\rc\x1b[201~');
it('keeps a line at the direct-write limit as one write, one over it as a prompt', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'a'.repeat(64));
enter(textarea);
type(textarea, 'b'.repeat(65));
enter(textarea);
expect(sent).toEqual(['a'.repeat(64) + '\r']);
expect(prompts).toEqual(['b'.repeat(65)]);
});
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
const { textarea, sent, prompts } = load();
type(textarea, 'line one\nline two');
enter(textarea);
vi.advanceTimersByTime(500);
expect(prompts).toEqual(['line one\nline two']);
expect(sent).toEqual([]);
});
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
const { textarea, prompts } = load({ promptResult: false });
type(textarea, 'line one\nline two');
enter(textarea);
expect(prompts).toHaveLength(1);
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
});
it('treats Shift+Enter as a newline, never a send', () => {
@@ -165,6 +214,90 @@ describe('CJK input: Send on Enter', () => {
expect(sent).toEqual(['\x7f']);
});
it('does not send Backspace when deleting the last held character', () => {
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
// a stray DEL would eat its last character.
const { textarea, sent } = load();
type(textarea, 'a');
type(textarea, 'ab');
backspace(textarea, PHANTOM + 'a');
backspace(textarea, PHANTOM);
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
backspace(textarea, '');
expect(sent).toEqual(['\x7f']);
expect(textarea.value).toBe(PHANTOM);
});
it('does not send Backspace for select-all + delete of held text', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, '');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM);
});
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
const { textarea, sent } = load();
type(textarea, 'a');
backspace(textarea, PHANTOM);
vi.advanceTimersByTime(2000);
expect(sent).toEqual([]);
});
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
const { textarea, sent } = load();
type(textarea, 'abc');
backspace(textarea, 'abc');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'abc');
});
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
// _handleCjkInput turns the single character into the control byte.
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'c');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
const { textarea, sent, bar } = load();
type(textarea, 'ab');
bar.armed = true;
type(textarea, 'abc');
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM + 'ab');
});
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
textarea.fire('compositionstart');
textarea.value = PHANTOM + 'c';
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
textarea.fire('compositionend');
vi.advanceTimersByTime(10);
expect(sent).toEqual(['c']);
expect(textarea.value).toBe(PHANTOM);
});
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
const { textarea, sent, bar } = load();
bar.armed = true;
type(textarea, 'hello');
expect(sent).toEqual([]);
expect(textarea.value).toBe(PHANTOM + 'hello');
expect(bar.armed).toBe(false);
});
it('Escape clears the held text without sending', () => {
const { textarea, sent } = load();
type(textarea, 'never mind');
+45
View File
@@ -547,6 +547,51 @@ describe('one-shot Ctrl through the CJK input field', () => {
});
});
describe('Send on Enter: a long or multi-line held answer goes out as a composed prompt', () => {
// _sendCjkPrompt is CjkInput's sendPrompt callback. It hands the text to the
// composer's _sendComposedPrompt with the session captured at Enter, so the
// delayed Enter cannot follow a tab switch.
function promptApp() {
const { CodemanApp, bar } = loadTerminalModule();
bar.clearCtrl();
const app = Object.create(CodemanApp.prototype) as {
activeSessionId: string | null;
_sendCjkPrompt(text: string): boolean;
};
app.activeSessionId = 'session-a';
const composed = vi
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
.mockReturnValue(true);
return { app, bar, composed };
}
it('sends through the composer path, bound to the session active at Enter', () => {
const { app, composed } = promptApp();
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
app.activeSessionId = 'session-b';
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
composed.mockRestore();
});
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
const { app, bar, composed } = promptApp();
bar.toggleCtrl();
app._sendCjkPrompt('x'.repeat(100));
expect(bar.isCtrlArmed()).toBe(false);
composed.mockRestore();
});
it('reports a refusal so the field keeps the text', () => {
const { app, composed } = promptApp();
composed.mockReturnValue(false);
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
app.activeSessionId = null;
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
expect(composed).toHaveBeenCalledTimes(1);
composed.mockRestore();
});
});
describe('armed styling survives the light-skin overrides', () => {
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');