mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 04:59:34 +01:00
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:
1 parent
b8a4466643
commit
95fb147e9c
9 files changed
+474
-33
No files matched your search
@@ -70,8 +70,11 @@ sequences, so word jumps and history keys keep working.
|
||||
On a phone, **Input Field: Send on Enter** (beside CJK input) turns that field into a chat box:
|
||||
typed text stays in it until Enter, so you can scroll the terminal back to a question and edit
|
||||
your answer before sending. Shift+Enter adds a line, Esc clears the field, and autocorrect is on.
|
||||
A one-line answer is sent as typed, so CLI menus that take a digit still work; several lines go
|
||||
as one paste followed by Enter.
|
||||
A short one-line answer is sent as typed, so CLI menus that take a digit still work; a longer
|
||||
answer, or several lines, goes like the prompt composer's Send: one paste, then Enter to the same
|
||||
session. With the keyboard bar's one-shot Ctrl armed, the next key you type goes out as a control
|
||||
key (Ctrl, then `c` is Ctrl+C) instead of being held. With the keyboard down the field stays one
|
||||
line tall, and tapping the tab you are on keeps the draft.
|
||||
|
||||
## Voice dictation
|
||||
|
||||
|
||||
+11
-3
@@ -9384,7 +9384,7 @@ class CodemanApp {
|
||||
|
||||
// `skipSnapshot`: the tile grid opening on the session it parks
|
||||
// (tile-grid.js openTileGrid), whose snapshot closing the grid discards.
|
||||
_cleanupPreviousSession(newSessionId, { skipSnapshot = false } = {}) {
|
||||
_cleanupPreviousSession(newSessionId, { skipSnapshot = false, keepCjkDraft = false } = {}) {
|
||||
// Snapshot the OUTGOING session's xterm rendered state (viewport + scrollback +
|
||||
// colors/attrs) before the terminal gets cleared/reset. Lets us restore the
|
||||
// exact view on switch-back rather than replaying codex's byte stream, which
|
||||
@@ -9437,8 +9437,11 @@ class CodemanApp {
|
||||
// Clear CJK input to prevent sending stale text to the wrong session.
|
||||
// Must go through CjkInput.clear() — a raw value wipe leaves the module's
|
||||
// pending flush timers armed and drops the phantom char it relies on.
|
||||
// A held Send on Enter draft survives a reload of the same session: nothing
|
||||
// switched, and the answer would be gone. Live mode still clears, since a
|
||||
// pending debounced flush could fire mid-reconnect.
|
||||
if (typeof CjkInput !== 'undefined') {
|
||||
CjkInput.clear();
|
||||
if (!(keepCjkDraft && CjkInput.holdUntilEnter)) CjkInput.clear();
|
||||
} else {
|
||||
const cjkEl = document.getElementById('cjkInput');
|
||||
if (cjkEl) cjkEl.value = '';
|
||||
@@ -9982,7 +9985,12 @@ class CodemanApp {
|
||||
// with no active id, the switch below snapshots none of it.
|
||||
this.activeSessionId = null;
|
||||
}
|
||||
// A reload of the session already shown (tapping its own tab, the geometry
|
||||
// retry) is not a switch: _cleanupPreviousSession keeps a Send on Enter
|
||||
// draft for it, which it cannot tell on its own once activeSessionId is null.
|
||||
let reloadingSameSession = false;
|
||||
if (this.activeSessionId === sessionId && forceReload) {
|
||||
reloadingSameSession = true;
|
||||
this.terminalBufferCache?.delete(sessionId);
|
||||
this._xtermSnapshots?.delete(sessionId);
|
||||
try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {}
|
||||
@@ -10029,7 +10037,7 @@ class CodemanApp {
|
||||
// A session tab takes the stage back from any active web tab.
|
||||
this._hideWebviewLayer?.();
|
||||
|
||||
this._cleanupPreviousSession(sessionId);
|
||||
this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });
|
||||
this.activeSessionId = sessionId;
|
||||
this._activateFileBrowserSession?.(sessionId);
|
||||
// A keyboard row hold belongs to the session it was taken for: release it here
|
||||
|
||||
@@ -744,6 +744,8 @@
|
||||
'对于本地 Claude 会话,打开屏幕键盘时会保持会话尺寸并改为滚动视图,这样 Claude 不会重绘屏幕而丢失对话记录行。全屏界面(Codex、Claude 的全屏模式)仍像以前一样调整尺寸。',
|
||||
'CJK Input': '中日韩输入',
|
||||
'Input Field: Send on Enter': '输入框:按 Enter 发送',
|
||||
'CJK input (Enter = send, Esc = clear)': '中日韩输入(Enter 发送,Esc 清除)',
|
||||
'Type, Enter to send (Shift+Enter: new line, Esc: clear)': '输入文字,按 Enter 发送(Shift+Enter 换行,Esc 清除)',
|
||||
'With CJK Input on, keep typed text in the field until Enter instead of sending it as you type, so you can scroll the terminal and edit before sending. Autocorrect is on in this mode.':
|
||||
'开启中日韩输入后,输入的文字会保留在输入框中,直到按下 Enter 才发送,而不是边输入边发送,这样可以先滚动终端、编辑后再发送。此模式下会开启自动更正。',
|
||||
'Extended Keyboard Bar': '扩展键盘栏',
|
||||
|
||||
+102
-13
@@ -61,6 +61,13 @@ const CjkInput = (() => {
|
||||
// field until Enter, like a chat box, instead of streaming to the PTY as it is
|
||||
// typed. Lets a phone user scroll the terminal and edit an answer before sending.
|
||||
let _hold = false;
|
||||
// Send-on-Enter: the held text as of the last settled input event (phantom
|
||||
// stripped). Tells a deletion that emptied the field from a Backspace on a field
|
||||
// that was already empty, and finds the one character an armed Ctrl applies to.
|
||||
let _heldBase = '';
|
||||
// Send-on-Enter: delivers a held prompt that is long or multi-line to the
|
||||
// session it was typed for (terminal-ui.js passes the composer's send path).
|
||||
let _sendPrompt = null;
|
||||
const _listeners = {};
|
||||
|
||||
const PHANTOM = '';
|
||||
@@ -110,6 +117,13 @@ const CjkInput = (() => {
|
||||
const DEBOUNCE_DICTATION_MS = 1500;
|
||||
const DICTATION_DECAY_MS = 3000;
|
||||
|
||||
// Send-on-Enter: the longest single line still written as `<text>\r` in one
|
||||
// go. Claude Code takes a burst of about a hundred characters or more as a
|
||||
// paste (src/web/route-helpers.ts) and turns its \r into a newline, so the
|
||||
// answer would sit unsent. Short answers (a menu digit, a word) keep the
|
||||
// one-write form; anything longer goes out as a prompt with a separate Enter.
|
||||
const HELD_DIRECT_MAX = 64;
|
||||
|
||||
const PASSTHROUGH_KEYS = {
|
||||
ArrowUp: '\x1b[A',
|
||||
ArrowDown: '\x1b[B',
|
||||
@@ -164,6 +178,7 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
function _resetToPhantom() {
|
||||
_heldBase = '';
|
||||
// Skip redundant writes: every programmatic value/selection mutation can
|
||||
// desync an Android IME's input session (InputConnection) — after which
|
||||
// the keyboard composes in its own UI but NO events ever reach the page.
|
||||
@@ -196,6 +211,7 @@ const CjkInput = (() => {
|
||||
// Send-on-Enter: nothing leaves the field until Enter (keydown handler).
|
||||
if (_hold) {
|
||||
_t('flush SKIP hold');
|
||||
_holdSettle();
|
||||
_autoGrow();
|
||||
return;
|
||||
}
|
||||
@@ -219,21 +235,86 @@ const CjkInput = (() => {
|
||||
}
|
||||
}
|
||||
|
||||
/** Send-on-Enter: deliver the held text as one prompt, then Enter. One line
|
||||
* goes as typed text + CR in one write (what live mode's Enter sends, so CLI
|
||||
* menus that answer to a digit keep working). Several lines go as one
|
||||
* bracketed paste with Enter as a separate, delayed write, the same bytes as
|
||||
* the mobile prompt composer (keyboard-accessory.js _sendComposedPrompt), so
|
||||
* embedded newlines don't submit early. */
|
||||
/** Send-on-Enter: deliver the held text, then Enter. Returns false when the
|
||||
* text was refused (too long, no session), so the field keeps it.
|
||||
* A short single line goes as typed text + CR in one write: what live mode's
|
||||
* Enter sends, so CLI menus that answer to a digit keep working. Anything
|
||||
* longer, or with several lines, goes through `_sendPrompt`: the mobile prompt
|
||||
* composer's path (KeyboardAccessoryBar._sendComposedPrompt), one bracketed
|
||||
* paste and then Enter as a separate, delayed write bound to the session the
|
||||
* text was typed for, so neither a long line nor an embedded newline submits
|
||||
* early and a tab switch cannot take the Enter elsewhere. */
|
||||
function _sendHeld(val) {
|
||||
if (!/\n/.test(val)) {
|
||||
if (!/\n/.test(val) && val.length <= HELD_DIRECT_MAX) {
|
||||
_send(val + '\r');
|
||||
return true;
|
||||
}
|
||||
if (!_sendPrompt) {
|
||||
_t('hold send DROP no-prompt-path');
|
||||
return false;
|
||||
}
|
||||
return _sendPrompt(val) !== false;
|
||||
}
|
||||
|
||||
function _ctrlArmed() {
|
||||
return typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.() === true;
|
||||
}
|
||||
|
||||
/** Index of the one character `after` adds to `before`, or -1 when the change
|
||||
* is anything else (several characters, a deletion, a rewrite). */
|
||||
function _singleInsertionAt(before, after) {
|
||||
if (after.length !== before.length + 1) return -1;
|
||||
let i = 0;
|
||||
while (i < before.length && before[i] === after[i]) i++;
|
||||
return after.slice(i + 1) === before.slice(i) ? i : -1;
|
||||
}
|
||||
|
||||
/** Send-on-Enter: settle the field after an input event. With the shell bar's
|
||||
* one-shot Ctrl armed, a single typed character is not held: it leaves the
|
||||
* field and goes to the PTY, where _handleCjkInput turns it into the control
|
||||
* byte (`c` → Ctrl+C). Any other change spends the modifier, the same rule
|
||||
* live mode follows for a multi-character chunk. */
|
||||
function _holdSettle() {
|
||||
const before = _heldBase;
|
||||
const now = _strip(_textarea.value);
|
||||
_heldBase = now;
|
||||
if (now === before || !_ctrlArmed()) return;
|
||||
const at = _singleInsertionAt(before, now);
|
||||
if (at < 0 || now[at] === '\n') {
|
||||
KeyboardAccessoryBar.clearCtrl?.();
|
||||
return;
|
||||
}
|
||||
let text = val;
|
||||
while (/\x1b\[20[01]~/.test(text)) text = text.replace(/\x1b\[20[01]~/g, '');
|
||||
_send(`\x1b[200~${text.replace(/\r?\n/g, '\r')}\x1b[201~`);
|
||||
setTimeout(() => _send('\r'), 120);
|
||||
_t('hold ctrl key');
|
||||
_textarea.value = PHANTOM + before;
|
||||
_textarea.setSelectionRange(1 + at, 1 + at);
|
||||
_heldBase = before;
|
||||
_send(now[at]);
|
||||
}
|
||||
|
||||
/** Send-on-Enter input handling: nothing is flushed, the field only settles.
|
||||
* A deletion forwards Backspace to the PTY only when the field was ALREADY
|
||||
* empty, i.e. the phantom itself was deleted. Deleting the last held
|
||||
* character (or select-all + delete) must not also delete a character from
|
||||
* the CLI's own composer, which Attach, image paste, Path and the mic fill. */
|
||||
function _holdInput(e) {
|
||||
if (_composing) return; // composed text settles at compositionend (_flush)
|
||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||
const wasEmpty = !_heldBase;
|
||||
_heldBase = _strip(_textarea.value);
|
||||
if (!_heldBase) {
|
||||
if (wasEmpty) _send('\x7f');
|
||||
_resetToPhantom();
|
||||
} else if (!_textarea.value.startsWith(PHANTOM)) {
|
||||
// Backspace at the very start of the text deleted the phantom: put it
|
||||
// back with the caret where it was, at the start of the text.
|
||||
_textarea.value = PHANTOM + _textarea.value;
|
||||
_textarea.setSelectionRange(1, 1);
|
||||
}
|
||||
_autoGrow();
|
||||
return;
|
||||
}
|
||||
_holdSettle();
|
||||
_autoGrow();
|
||||
}
|
||||
|
||||
/** Cancel any pending debounced flush */
|
||||
@@ -265,10 +346,11 @@ const CjkInput = (() => {
|
||||
}
|
||||
|
||||
return {
|
||||
init({ send }) {
|
||||
init({ send, sendPrompt = null }) {
|
||||
if (_initialized) this.destroy();
|
||||
|
||||
_send = send;
|
||||
_sendPrompt = sendPrompt;
|
||||
_composing = false;
|
||||
_printableKeydownAt = null;
|
||||
_flushTimer = null;
|
||||
@@ -366,7 +448,8 @@ const CjkInput = (() => {
|
||||
_cancelDebouncedFlush();
|
||||
const val = _strip(_textarea.value);
|
||||
if (_hold && val) {
|
||||
_sendHeld(val);
|
||||
// Refused (too long, no session): keep the text so nothing is lost.
|
||||
if (!_sendHeld(val)) return;
|
||||
} else if (val) {
|
||||
_send(val + '\r');
|
||||
} else {
|
||||
@@ -454,6 +537,11 @@ const CjkInput = (() => {
|
||||
_composing = false;
|
||||
}
|
||||
|
||||
if (_hold) {
|
||||
_holdInput(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Backspace / delete detection ──
|
||||
if (e.inputType === 'deleteContentBackward' || e.inputType === 'deleteWordBackward') {
|
||||
if (_composing) return;
|
||||
@@ -532,6 +620,7 @@ const CjkInput = (() => {
|
||||
setHoldUntilEnter(on) {
|
||||
_hold = !!on;
|
||||
if (!_textarea) return;
|
||||
_heldBase = _strip(_textarea.value);
|
||||
const v = _hold ? 'on' : 'off';
|
||||
_textarea.setAttribute('autocorrect', v);
|
||||
_textarea.setAttribute('autocapitalize', _hold ? 'sentences' : 'off');
|
||||
|
||||
@@ -14235,6 +14235,13 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
|
||||
bottom: calc(var(--safe-area-bottom) + 84px);
|
||||
}
|
||||
|
||||
/* Send on Enter grows the field with its text, but with the keyboard down .main
|
||||
reserves a fixed 84px (below), so a grown field would cover the terminal's
|
||||
last rows. Keep it one line tall there; the text scrolls inside. */
|
||||
.touch-device:not(.keyboard-visible) #cjkInput.cjk-input-visible {
|
||||
max-height: 34px;
|
||||
}
|
||||
|
||||
body.touch-device.cjk-input-visible .main {
|
||||
padding-bottom: calc(84px + var(--safe-area-bottom));
|
||||
}
|
||||
|
||||
@@ -1083,6 +1083,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
send: (text) => {
|
||||
this._handleCjkInput(text);
|
||||
},
|
||||
// Send on Enter: a long or multi-line held answer goes out like the
|
||||
// mobile prompt composer's Send (one bracketed paste, then Enter as a
|
||||
// separate delayed write), bound to the session it was typed for.
|
||||
sendPrompt: (text) => this._sendCjkPrompt(text),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4564,6 +4568,27 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._sendInputAsync(this.activeSessionId, text);
|
||||
},
|
||||
|
||||
/**
|
||||
* Send on Enter (CjkInput, setting cjkInputHoldUntilEnter): deliver a held
|
||||
* answer that is too long for one `<text>\r` write, or has several lines.
|
||||
* Claude Code takes a long burst as a paste and its \r as a newline, so it goes
|
||||
* through the composer's path instead: the session is captured now, so the
|
||||
* delayed Enter cannot follow a tab switch, and the length check applies.
|
||||
* Returns false when nothing was sent, so the field keeps the text.
|
||||
*/
|
||||
_sendCjkPrompt(text) {
|
||||
const sessionId = this.activeSessionId;
|
||||
if (!sessionId || typeof KeyboardAccessoryBar === 'undefined') {
|
||||
_crashDiag.log(`CJK prompt DROP no-session len=${text.length}`);
|
||||
return false;
|
||||
}
|
||||
// A multi-character chunk spends an armed one-shot Ctrl (same rule as
|
||||
// _handleCjkInput); leaving it armed would modify the next keystroke.
|
||||
KeyboardAccessoryBar.clearCtrl?.();
|
||||
_crashDiag.log(`CJK prompt→${sessionId.slice(0, 8)} len=${text.length}`);
|
||||
return KeyboardAccessoryBar._sendComposedPrompt(sessionId, text);
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-assert a history anchor captured before a terminal write (#358).
|
||||
*
|
||||
|
||||
@@ -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
@@ -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');
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
Reference in new issue
Block a user