Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
fix(mobile): keep live input focus and recover failed sends (#36109)
Kelvin Amoabaf7bb5be8c22f
diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.jsonindex 7049b014374..51de6c2ae4b 100644--- a/mobile/src/i18n/locales/de.json+++ b/mobile/src/i18n/locales/de.json@@ -2518,7 +2518,8 @@"saveFailed": "Schnellbefehl konnte nicht gespeichert werden"},"useSessionTerminalSendActions": {- "inputTooLarge": "Eingabe zu groß (max. 256 KiB)"+ "inputTooLarge": "Eingabe zu groß (max. 256 KiB)",+ "liveInputInterrupted": "Live-Eingabe unterbrochen. Eingabefeld geleert; prüfe das Terminal, bevor du fortfährst."},"useStartup": {"wakeAgents": "Orca auf dem Host öffnen, um schlafende Agenten zu wecken."diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.jsonindex 1b983777d16..1d923043e64 100644--- a/mobile/src/i18n/locales/en.json+++ b/mobile/src/i18n/locales/en.json@@ -2250,7 +2250,8 @@"cleared": "Terminal cleared"},"useSessionTerminalSendActions": {- "inputTooLarge": "Input too large (max 256 KiB)"+ "inputTooLarge": "Input too large (max 256 KiB)",+ "liveInputInterrupted": "Live input interrupted. Field cleared; check the terminal before continuing."},"useTerminalPaste": {"clipboardReadFailed": "Couldn't read the clipboard",diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.jsonindex 5616d4e2c04..3186a84dd17 100644--- a/mobile/src/i18n/locales/es.json+++ b/mobile/src/i18n/locales/es.json@@ -2594,7 +2594,8 @@"saveFailed": "Error al guardar el comando rápido"},"useSessionTerminalSendActions": {- "inputTooLarge": "Entrada demasiado grande (máx. 256 KiB)"+ "inputTooLarge": "Entrada demasiado grande (máx. 256 KiB)",+ "liveInputInterrupted": "Se interrumpió la entrada en vivo. Se vació el campo; revisa la terminal antes de continuar."},"useStartup": {"wakeAgents": "Abre Orca en el host para reanudar los agentes en reposo."diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.jsonindex 8666cb6887e..c0f3989b696 100644--- a/mobile/src/i18n/locales/fr.json+++ b/mobile/src/i18n/locales/fr.json@@ -2594,7 +2594,8 @@"saveFailed": "Échec de l'enregistrement de la commande rapide"},"useSessionTerminalSendActions": {- "inputTooLarge": "Saisie trop volumineuse (max. 256 Kio)"+ "inputTooLarge": "Saisie trop volumineuse (max. 256 Kio)",+ "liveInputInterrupted": "Saisie en direct interrompue. Le champ a été vidé ; vérifiez le terminal avant de continuer."},"useStartup": {"wakeAgents": "Ouvrez Orca sur l'hôte pour réveiller les agents en veille."diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.jsonindex 9ca8cec74af..5c6750fef64 100644--- a/mobile/src/i18n/locales/ja.json+++ b/mobile/src/i18n/locales/ja.json@@ -2514,7 +2514,8 @@"saveFailed": "クイックコマンドの保存に失敗しました"},"useSessionTerminalSendActions": {- "inputTooLarge": "入力データが大きすぎます(最大 256 KiB)。"+ "inputTooLarge": "入力データが大きすぎます(最大 256 KiB)。",+ "liveInputInterrupted": "ライブ入力が中断されました。入力欄をクリアしました。続行する前にターミナルを確認してください。"},"useStartup": {"wakeAgents": "スリープ中の Agent を再開するには、ホストで Orca を開いてください。"diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.jsonindex 8fc38570e80..566f0288bf0 100644--- a/mobile/src/i18n/locales/ko.json+++ b/mobile/src/i18n/locales/ko.json@@ -2514,7 +2514,8 @@"saveFailed": "빠른 명령을 저장하지 못했습니다."},"useSessionTerminalSendActions": {- "inputTooLarge": "입력 내용이 너무 큼 (최대 256 KiB)"+ "inputTooLarge": "입력 내용이 너무 큼 (최대 256 KiB)",+ "liveInputInterrupted": "실시간 입력이 중단되었습니다. 입력란을 비웠습니다. 계속하기 전에 터미널을 확인하세요."},"useStartup": {"wakeAgents": "슬립 중인 에이전트를 활성화하려면 호스트에서 Orca를 실행하세요."diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.jsonindex 55c946b9ea9..60ea63ff0ff 100644--- a/mobile/src/i18n/locales/pt.json+++ b/mobile/src/i18n/locales/pt.json@@ -2594,7 +2594,8 @@"saveFailed": "Falha ao salvar o comando rápido"},"useSessionTerminalSendActions": {- "inputTooLarge": "Entrada grande demais (máx. 256 KiB)"+ "inputTooLarge": "Entrada grande demais (máx. 256 KiB)",+ "liveInputInterrupted": "A entrada ao vivo foi interrompida. O campo foi limpo; verifique o terminal antes de continuar."},"useStartup": {"wakeAgents": "Abra o Orca no host para ativar os agentes suspensos."diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.jsonindex 2e1681e7320..2d74841e404 100644--- a/mobile/src/i18n/locales/ru.json+++ b/mobile/src/i18n/locales/ru.json@@ -2670,7 +2670,8 @@"saveFailed": "Не удалось сохранить быструю команду"},"useSessionTerminalSendActions": {- "inputTooLarge": "Слишком большой объём ввода (макс. 256 КиБ)"+ "inputTooLarge": "Слишком большой объём ввода (макс. 256 КиБ)",+ "liveInputInterrupted": "Ввод в реальном времени прерван. Поле очищено; проверьте терминал, прежде чем продолжить."},"useStartup": {"wakeAgents": "Откройте Orca на сервере, чтобы разбудить спящих агентов."diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.jsonindex 2d6875eb5e8..3b8c1f0b2dc 100644--- a/mobile/src/i18n/locales/tr.json+++ b/mobile/src/i18n/locales/tr.json@@ -2518,7 +2518,8 @@"saveFailed": "Hızlı komut kaydedilemedi"},"useSessionTerminalSendActions": {- "inputTooLarge": "Girdi çok büyük (en fazla 256 KiB)"+ "inputTooLarge": "Girdi çok büyük (en fazla 256 KiB)",+ "liveInputInterrupted": "Canlı giriş kesildi. Alan temizlendi; devam etmeden önce terminali kontrol edin."},"useStartup": {"wakeAgents": "Uykudaki ajanları uyandırmak için sunucuda Orca'yı açın."diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.jsonindex 526e30598ff..08d7d26d6ed 100644--- a/mobile/src/i18n/locales/zh-Hant.json+++ b/mobile/src/i18n/locales/zh-Hant.json@@ -2514,7 +2514,8 @@"saveFailed": "儲存快速命令失敗"},"useSessionTerminalSendActions": {- "inputTooLarge": "輸入內容太大(上限為 256 KiB)"+ "inputTooLarge": "輸入內容太大(上限為 256 KiB)",+ "liveInputInterrupted": "即時輸入已中斷,輸入框已清空。繼續前請檢查終端。"},"useStartup": {"wakeAgents": "請在主機上開啟 Orca,以喚醒休眠中的代理程式。"diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.jsonindex 55c9ae900a0..bbec0109e3a 100644--- a/mobile/src/i18n/locales/zh.json+++ b/mobile/src/i18n/locales/zh.json@@ -2514,7 +2514,8 @@"saveFailed": "保存快速命令失败"},"useSessionTerminalSendActions": {- "inputTooLarge": "输入内容过大(最大 256 KiB)"+ "inputTooLarge": "输入内容过大(最大 256 KiB)",+ "liveInputInterrupted": "实时输入已中断,输入框已清空。继续前请检查终端。"},"useStartup": {"wakeAgents": "请在主机上打开 Orca,以唤醒睡眠中的智能体。"diff --git a/mobile/src/session/MobileSessionCommandDock.test.tsx b/mobile/src/session/MobileSessionCommandDock.test.tsxnew file mode 100644index 00000000000..c30a3254ff9--- /dev/null+++ b/mobile/src/session/MobileSessionCommandDock.test.tsx@@ -0,0 +1,140 @@+// @vitest-environment happy-dom+import { act, createElement, useLayoutEffect, useRef } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { TextInput } from 'react-native'+import { afterEach, expect, it, vi } from 'vitest'+import { MobileSessionCommandDock } from './MobileSessionCommandDock'+import { useTerminalLiveInputFocus } from '../terminal/use-terminal-live-input-focus'++vi.mock('react-native', async () => {+ const React = await import('react')+ const View = (props: { children?: React.ReactNode; 'aria-hidden'?: boolean }) =>+ React.createElement('div', { 'aria-hidden': props['aria-hidden'] }, props.children)+ return {+ View,+ Pressable: View,+ TextInput: React.forwardRef(+ (props: { accessibilityLabel?: string; placeholder?: string; tabIndex?: number }, ref) => {+ const node = React.useRef<HTMLInputElement>(null)+ React.useImperativeHandle(ref, () => ({+ focus: () => node.current?.focus(),+ blur: () => node.current?.blur(),+ isFocused: () => document.activeElement === node.current+ }))+ return React.createElement('input', {+ ref: node,+ 'aria-label': props.accessibilityLabel,+ placeholder: props.placeholder,+ tabIndex: props.tabIndex+ })+ }+ ),+ Platform: { OS: 'web', select: (values: { default: unknown }) => values.default },+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }+ }+})+vi.mock('lucide-react-native', () => ({ ArrowUp: () => null }))+vi.mock('./MobileTerminalInputActions', () => ({ MobileTerminalInputActions: () => null }))+vi.mock('./MobileTerminalLiveInputStatus', () => ({ MobileTerminalLiveInputStatus: () => null }))+vi.mock('./MobileTerminalCommandDictationPreview', () => ({+ MobileTerminalCommandDictationPreview: () => null+}))+vi.mock('./MobileSessionAccessoryKeys', () => ({ MobileSessionAccessoryKeys: () => null }))+vi.mock('../platform/host-os', () => ({ hostOs: () => 'ios' }))++type Selection = { handle: string; liveInputEnabled: boolean }+let root: Root | undefined+let container: HTMLDivElement | undefined++afterEach(() => {+ act(() => root?.unmount())+ container?.remove()+ vi.useRealTimers()+})++function Harness({ handle, liveInputEnabled }: Selection) {+ const liveInputRef = useRef<TextInput>(null)+ const commandInputRef = useRef<TextInput>(null)+ const activeHandleRef = useRef(handle)+ useLayoutEffect(() => {+ activeHandleRef.current = handle+ }, [handle])+ useTerminalLiveInputFocus({+ activeHandleRef,+ inputRef: liveInputRef,+ commandInputRef,+ canSend: true,+ keyboardHeight: 0,+ lifecycleIdentity: null,+ lifecycleKey: 'host:workspace:connected',+ liveInputEnabled,+ reopenFocusedInputWhenKeyboardHidden: false,+ timerRef: useRef(null)+ })+ const controller = {+ insets: { bottom: 0 },+ bufferedTerminalDraftState: { input: '', setInput: () => {} },+ liveInputCapture: '',+ liveInputEnabled,+ canSend: true,+ canCompose: true,+ dictation: { meter: null },+ commandFieldAnchorRef: { current: null },+ activeHandle: handle,+ keyboardLift: 0,+ bindCommandField: (field: TextInput | null) => {+ commandInputRef.current = field+ },+ bindLiveInputField: (field: TextInput | null) => {+ liveInputRef.current = field+ }+ }+ return createElement(MobileSessionCommandDock, {+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real dock reads these fields; action children are inert and no send/dictation handler is invoked.+ controller: controller as unknown as Parameters<+ typeof MobileSessionCommandDock+ >[0]['controller'],+ keysInRail: true+ })+}++it.each(['terminal selection', 'preference hydration'] as const)(+ 'keeps focus on the visible retained field after %s, leaving a closed keyboard alone',+ (transition) => {+ vi.useFakeTimers()+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)+ const render = (liveInputEnabled: boolean) =>+ act(() =>+ root?.render(+ createElement(Harness, {+ handle:+ liveInputEnabled && transition === 'terminal selection' ? 'terminal-b' : 'terminal-a',+ liveInputEnabled+ })+ )+ )+ render(false)+ const command = container.querySelector('input[placeholder="Type a command…"]')+ const live = container.querySelector('input[aria-label="Live terminal input"]')+ if (!(command instanceof HTMLInputElement) || !(live instanceof HTMLInputElement)) {+ throw new Error('Both dock fields must be mounted')+ }+ command.focus()++ render(true)+ expect(document.activeElement).toBe(live)+ expect(live.closest('[aria-hidden]')?.getAttribute('aria-hidden')).toBe('false')+ render(false)+ expect(document.activeElement).toBe(command)+ expect(command.closest('[aria-hidden]')?.getAttribute('aria-hidden')).toBe('false')+ expect(container.querySelector('input[aria-label="Live terminal input"]')).toBe(live)++ command.blur()+ render(true)+ render(false)+ expect(document.activeElement).toBe(document.body)+ expect(vi.getTimerCount()).toBe(0)+ }+)diff --git a/mobile/src/session/MobileSessionCommandDock.tsx b/mobile/src/session/MobileSessionCommandDock.tsxindex dbebb226645..a5a715f6c48 100644--- a/mobile/src/session/MobileSessionCommandDock.tsx+++ b/mobile/src/session/MobileSessionCommandDock.tsx@@ -16,6 +16,9 @@ import { useMobileTranslation } from '../i18n/use-mobile-translation'import { styles } from './mobile-session-styles'import type { MobileSessionController } from './use-mobile-session-controller'+// Both fields must remain focusable during the tap that hands the keyboard to the other mode.+const inactiveFieldStyle = { position: 'absolute', left: 0, right: 0, opacity: 0 } as const+// Markdown, file, browser and chat tabs bring their own input; only terminals get the dock and its keys.export function sessionCommandDockShown(controller: MobileSessionController): boolean {return (@@ -75,136 +78,133 @@ export function MobileSessionCommandDock({{}{keysInRail ? null : <MobileSessionAccessoryKeys controller={controller} />}{}- {liveInputEnabled ? (- <View style={styles.inputBar}>- <View style={styles.liveInputField}>- <TextInput- ref={bindLiveInputField}- style={[- styles.textInput,- styles.liveInputCapture,- !canSend && styles.liveInputCaptureDisabled- ]}- value={liveInputCapture}- onChange={handleLiveInputChange}- onKeyPress={handleLiveInputKeyPress}- onSubmitEditing={submitLiveInput}- placeholder={t('session.terminalLiveInputStatus.liveInput', 'Live input')}- placeholderTextColor={colors.textMuted}- selectionColor={colors.accentBlue}- accessibilityLabel={t('session.commandDock.liveInputLabel', 'Live terminal input')}- accessibilityHint={t(- 'session.commandDock.liveInputHint',- 'Typed text is sent directly to the active terminal'- )}- showSoftInputOnFocus- autoCapitalize="none"- autoCorrect={false}- spellCheck={false}- smartInsertDelete={false}- // Why: iOS textContentType overrides autoComplete and can narrow the keyboard; keep IME switching available.- autoComplete="off"- keyboardType={getTerminalLiveInputKeyboardType(hostOs())}- returnKeyType="default"- blurOnSubmit={false}- editable={canSend}- importantForAutofill="no"- />+ <View style={styles.inputBar}>+ <View+ style={[styles.liveInputField, !liveInputEnabled && inactiveFieldStyle]}+ pointerEvents={liveInputEnabled ? 'auto' : 'none'}+ aria-hidden={!liveInputEnabled}+ accessibilityElementsHidden={!liveInputEnabled}+ importantForAccessibility={liveInputEnabled ? 'auto' : 'no-hide-descendants'}+ >+ <TextInput+ ref={bindLiveInputField}+ style={[+ styles.textInput,+ styles.liveInputCapture,+ !canSend && styles.liveInputCaptureDisabled+ ]}+ value={liveInputCapture}+ onChange={handleLiveInputChange}+ onKeyPress={handleLiveInputKeyPress}+ onSubmitEditing={submitLiveInput}+ placeholder={t('session.terminalLiveInputStatus.liveInput', 'Live input')}+ placeholderTextColor={colors.textMuted}+ selectionColor={colors.accentBlue}+ accessibilityLabel={t('session.commandDock.liveInputLabel', 'Live terminal input')}+ accessibilityHint={t(+ 'session.commandDock.liveInputHint',+ 'Typed text is sent directly to the active terminal'+ )}+ showSoftInputOnFocus+ autoCapitalize="none"+ autoCorrect={false}+ spellCheck={false}+ smartInsertDelete={false}+ // Why: iOS textContentType overrides autoComplete and can narrow the keyboard; keep IME switching available.+ autoComplete="off"+ keyboardType={getTerminalLiveInputKeyboardType(hostOs())}+ returnKeyType="default"+ blurOnSubmit={false}+ editable={canSend}+ importantForAutofill="no"+ tabIndex={liveInputEnabled ? 0 : -1}+ />+ {liveInputEnabled ? (<MobileTerminalLiveInputStatusdictation={dictation}dictationMode={dictationMode}heard={liveDictationText}isAttaching={isAttaching}/>- </View>- <MobileTerminalInputActions- canSend={canSend}- isAttaching={isAttaching}- dictation={dictation}- dictationMode={dictationMode}- dictationEnabled={dictationEnabled}- buttonStyle={styles.dictationButton}- activeButtonStyle={styles.dictationButtonActive}- disabledButtonStyle={styles.sendButtonDisabled}- onAttachImage={() => void attachImage('library')}- onAttachFile={() => void attachImage('files')}- onDictationToggle={handleDictationToggle}- onDictationPressIn={handleDictationPressIn}- onDictationPressOut={handleDictationPressOut}- onDictationCancel={cancelDictation}- />+ ) : null}</View>- ) : (- <View style={styles.inputBar}>- <View style={styles.commandField}>- <TextInput- ref={bindCommandField}- // Why: Android caches IME inputType at mount, so toggling autocomplete must remount there; iOS updates in place.- key={- hostOs() === 'android'- ? autocompleteEnabled- ? 'cmd-input-ac-on'- : 'cmd-input-ac-off'- : 'cmd-input'- }- style={[- styles.textInput,- styles.commandFieldInput,- commandDictationPreview && styles.commandFieldInputHidden- ]}- value={bufferedTerminalDraftState.input}- // Why: iOS kills active dictation/IME if JS writes a value differing from native text; store raw, normalize at send.- onChangeText={bufferedTerminalDraftState.setInput}- onSelectionChange={(e) => {- commandFieldAnchorRef.current = {- handle: activeHandle,- anchor: readMobileDictationAnchor(e, bufferedTerminalDraftState.input)- }- }}- // The preview stands in for an empty draft, so its placeholder must not show through.- placeholder={- commandDictationPreview- ? undefined- : t('session.commandDock.commandPlaceholder', 'Type a command…')+ <View+ style={[styles.commandField, liveInputEnabled && inactiveFieldStyle]}+ pointerEvents={liveInputEnabled ? 'none' : 'auto'}+ aria-hidden={liveInputEnabled}+ accessibilityElementsHidden={liveInputEnabled}+ importantForAccessibility={liveInputEnabled ? 'no-hide-descendants' : 'auto'}+ >+ <TextInput+ ref={bindCommandField}+ // Why: Android caches IME inputType at mount, so toggling autocomplete must remount there; iOS updates in place.+ key={+ hostOs() === 'android'+ ? autocompleteEnabled+ ? 'cmd-input-ac-on'+ : 'cmd-input-ac-off'+ : 'cmd-input'+ }+ style={[+ styles.textInput,+ styles.commandFieldInput,+ commandDictationPreview && styles.commandFieldInputHidden+ ]}+ value={bufferedTerminalDraftState.input}+ // Why: iOS kills active dictation/IME if JS writes a value differing from native text; store raw, normalize at send.+ onChangeText={bufferedTerminalDraftState.setInput}+ onSelectionChange={(e) => {+ commandFieldAnchorRef.current = {+ handle: activeHandle,+ anchor: readMobileDictationAnchor(e, bufferedTerminalDraftState.input)}- placeholderTextColor={colors.textMuted}- autoCapitalize="none"- autoCorrect={autocompleteEnabled}- spellCheck={autocompleteEnabled}- smartInsertDelete={false}- // Why: not autofill content, but keyboard must stay default so non-Latin IMEs remain selectable.- autoComplete="off"- keyboardType={getTerminalCommandKeyboardType(hostOs(), autocompleteEnabled)}- returnKeyType="send"- blurOnSubmit={false}- // Why: composing is local — an outage must not lock the field or discard typed text (#6713).- editable={canCompose}- onSubmitEditing={() => void handleSend()}- />- {commandDictationPreview ? (- <MobileTerminalCommandDictationPreview- draft={bufferedTerminalDraftState.input}- preview={commandDictationPreview}- />- ) : null}- </View>- <MobileTerminalInputActions- canSend={canSend}- isAttaching={isAttaching}- dictation={dictation}- dictationMode={dictationMode}- dictationEnabled={dictationEnabled}- meterHalo={dictation.meter}- buttonStyle={styles.dictationButton}- activeButtonStyle={styles.dictationButtonActive}- disabledButtonStyle={styles.sendButtonDisabled}- onAttachImage={() => void attachImage('library')}- onAttachFile={() => void attachImage('files')}- onDictationToggle={handleDictationToggle}- onDictationPressIn={handleDictationPressIn}- onDictationPressOut={handleDictationPressOut}- onDictationCancel={cancelDictation}+ }}+ // The preview stands in for an empty draft, so its placeholder must not show through.+ placeholder={+ commandDictationPreview+ ? undefined+ : t('session.commandDock.commandPlaceholder', 'Type a command…')+ }+ placeholderTextColor={colors.textMuted}+ autoCapitalize="none"+ autoCorrect={autocompleteEnabled}+ spellCheck={autocompleteEnabled}+ smartInsertDelete={false}+ // Why: not autofill content, but keyboard must stay default so non-Latin IMEs remain selectable.+ autoComplete="off"+ keyboardType={getTerminalCommandKeyboardType(hostOs(), autocompleteEnabled)}+ returnKeyType="send"+ blurOnSubmit={false}+ // Why: composing is local — an outage must not lock the field or discard typed text (#6713).+ editable={canCompose}+ tabIndex={liveInputEnabled ? -1 : 0}+ onSubmitEditing={() => void handleSend()}/>+ {!liveInputEnabled && commandDictationPreview ? (+ <MobileTerminalCommandDictationPreview+ draft={bufferedTerminalDraftState.input}+ preview={commandDictationPreview}+ />+ ) : null}+ </View>+ <MobileTerminalInputActions+ canSend={canSend}+ isAttaching={isAttaching}+ dictation={dictation}+ dictationMode={dictationMode}+ dictationEnabled={dictationEnabled}+ meterHalo={liveInputEnabled ? undefined : dictation.meter}+ buttonStyle={styles.dictationButton}+ activeButtonStyle={styles.dictationButtonActive}+ disabledButtonStyle={styles.sendButtonDisabled}+ onAttachImage={() => void attachImage('library')}+ onAttachFile={() => void attachImage('files')}+ onDictationToggle={handleDictationToggle}+ onDictationPressIn={handleDictationPressIn}+ onDictationPressOut={handleDictationPressOut}+ onDictationCancel={cancelDictation}+ />+ {liveInputEnabled ? null : (<Pressablestyle={[styles.sendButton, !canSend && styles.sendButtonDisabled]}disabled={!canSend}@@ -213,8 +213,8 @@ export function MobileSessionCommandDock({><ArrowUp size={18} color={colors.textSecondary} strokeWidth={2.5} /></Pressable>- </View>- )}+ )}+ </View></View>))diff --git a/mobile/src/session/mobile-session-toast-owner-cleanup.test.tsx b/mobile/src/session/mobile-session-toast-owner-cleanup.test.tsxindex c3cdeb4d569..ec2244c1cdb 100644--- a/mobile/src/session/mobile-session-toast-owner-cleanup.test.tsx+++ b/mobile/src/session/mobile-session-toast-owner-cleanup.test.tsx@@ -92,6 +92,7 @@ function mounted(strict = false) {createWarningState: { source: '', visible: '' },setCreateWarningState: vi.fn(),setToastMessage,+ onLiveInputSendFailureRef: { current: vi.fn() },toastOpacityRef: { current: {} },toastHideTimerRef: { current: null },toastSeqRef: { current: 0 },@@ -169,6 +170,19 @@ function mounted(strict = false) {act(() => renderer.update(element(surfaceKey, visible)))}}+it('routes a Live input failure through the session toast and retires the callback on unmount', () => {+ const { root, scope, setToastMessage } = mounted()++ act(() => scope.onLiveInputSendFailureRef.current('delivery-unconfirmed'))++ expect(setToastMessage).toHaveBeenCalledExactlyOnceWith(+ 'Live input interrupted. Field cleared; check the terminal before continuing.'+ )+ act(() => root.unmount())+ scope.onLiveInputSendFailureRef.current('delivery-unconfirmed')+ expect(setToastMessage).toHaveBeenCalledTimes(1)+})+it.each([['success', false],['failure', false],diff --git a/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx b/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsxindex 47aa393a99b..78b1b4deefd 100644--- a/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx+++ b/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx@@ -116,6 +116,7 @@ async function mounted(initial: ReturnType<typeof peer>, sessionId: string, conncreateWarningState: { source: '', visible: '' },setCreateWarningState: vi.fn(),setToastMessage: vi.fn(),+ onLiveInputSendFailureRef: { current: vi.fn() },toastOpacityRef: { current: new Animated.Value(0) },toastHideTimerRef: { current: null },toastSeqRef: { current: 0 },diff --git a/mobile/src/session/use-mobile-session-feedback-capabilities.ts b/mobile/src/session/use-mobile-session-feedback-capabilities.tsindex 3f39886ea9f..87646a250ab 100644--- a/mobile/src/session/use-mobile-session-feedback-capabilities.ts+++ b/mobile/src/session/use-mobile-session-feedback-capabilities.ts@@ -1,5 +1,6 @@import { useState, useRef, useCallback, useEffect } from 'react'import { Animated } from 'react-native'+import { translate } from '../i18n/mobile-i18n'import { reconcileMobileSessionCreateWarningState } from './mobile-session-create-warning-state'import type { MobileSessionTerminalRuntimeModel } from './use-mobile-session-terminal-runtime'import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support'@@ -25,7 +26,8 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTerminaconnStateRef,activeSessionTabTypeRef,delayedActionTimersRef,- activeSessionTab+ activeSessionTab,+ onLiveInputSendFailureRef} = scopeconst [browserScreencastSupported, setBrowserScreencastSupported] = useState<boolean | null>(null)// Hide history entry when the host cannot serve it rather than opening a dead end.@@ -125,6 +127,25 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTermina},[clearToastHideTimer])+ useEffect(() => {+ onLiveInputSendFailureRef.current = (failure) => {+ showToast(+ failure === 'input-too-large'+ ? translate(+ 'session.useSessionTerminalSendActions.inputTooLarge',+ 'Input too large (max 256 KiB)'+ )+ : translate(+ 'session.useSessionTerminalSendActions.liveInputInterrupted',+ 'Live input interrupted. Field cleared; check the terminal before continuing.'+ ),+ 3000+ )+ }+ return () => {+ onLiveInputSendFailureRef.current = () => {}+ }+ }, [onLiveInputSendFailureRef, showToast])return {browserScreencastSupported,setBrowserScreencastSupported,diff --git a/mobile/src/session/use-mobile-session-terminal-input.test.ts b/mobile/src/session/use-mobile-session-terminal-input.test.tsnew file mode 100644index 00000000000..cd207cfb028--- /dev/null+++ b/mobile/src/session/use-mobile-session-terminal-input.test.ts@@ -0,0 +1,77 @@+import { createElement } from 'react'+import { act, create, type ReactTestRenderer } from 'react-test-renderer'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { useMobileSessionTerminalInput } from './use-mobile-session-terminal-input'++vi.mock('../terminal/mobile-terminal-operations', () => ({+ terminalInputSend: {},+ terminalBufferClear: {}+}))+vi.mock('../terminal/worker-terminal-takeover-report', () => ({+ reportWorkerTerminalUserInput: vi.fn()+}))++const renderers: ReactTestRenderer[] = []++function mountToggle(liveInputEnabled: boolean, keyboardHeight: number) {+ const liveInput = {+ focus: vi.fn(),+ blur: vi.fn(),+ isFocused: () => liveInputEnabled && keyboardHeight === 0+ }+ const commandInput = {+ focus: vi.fn(),+ blur: vi.fn(),+ isFocused: () => !liveInputEnabled && keyboardHeight === 0+ }+ const scope = {+ activeHandle: 'terminal-a',+ keyboardHeight,+ toggleTerminalLiveInput: () => !liveInputEnabled,+ clearPendingLiveInputCommit: vi.fn(),+ liveInputRef: { current: liveInput },+ commandInputRef: { current: commandInput },+ liveInputFocusTimerRef: { current: null }+ }+ let toggle = (): void => {}+ function Harness(): null {+ const actions = useMobileSessionTerminalInput(+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only toggleLiveInput runs; all fields it reads are supplied above.+ scope as unknown as Parameters<typeof useMobileSessionTerminalInput>[0]+ )+ toggle = actions.toggleLiveInput+ return null+ }+ act(() => {+ renderers.push(create(createElement(Harness)))+ })+ return { toggle, liveInput, commandInput }+}++afterEach(() => {+ act(() => renderers.splice(0).forEach((renderer) => renderer.unmount()))+ vi.clearAllTimers()+ vi.useRealTimers()+})++describe('Live input keyboard handoff', () => {+ it.each([+ [true, 0],+ [false, 0],+ [true, 280],+ [false, 280]+ ] as const)(+ 'hands focus off synchronously with Live input %s and keyboard height %s',+ (liveInputEnabled, keyboardHeight) => {+ vi.useFakeTimers()+ const { toggle, liveInput, commandInput } = mountToggle(liveInputEnabled, keyboardHeight)++ act(toggle)++ expect(liveInputEnabled ? commandInput.focus : liveInput.focus).toHaveBeenCalledTimes(1)+ expect(liveInput.blur).not.toHaveBeenCalled()+ expect(commandInput.blur).not.toHaveBeenCalled()+ expect(vi.getTimerCount()).toBe(0)+ }+ )+})diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.tsindex 727d3c84d35..529c4efc3fb 100644--- a/mobile/src/session/use-mobile-session-terminal-input.ts+++ b/mobile/src/session/use-mobile-session-terminal-input.ts@@ -37,6 +37,8 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsModclientRef,connStateRef,liveInputRef,+ commandInputRef,+ keyboardHeight,liveInputFocusTimerRef,terminalUnsubsRef,activeHandleRef,@@ -55,15 +57,22 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsModif (!activeHandle) {return}+ const keepKeyboard =+ keyboardHeight > 0 ||+ liveInputRef.current?.isFocused() === true ||+ commandInputRef.current?.isFocused() === true+ clearTerminalLiveInputFocusTimer(liveInputFocusTimerRef)const nextEnabled = toggleTerminalLiveInput(activeHandle)clearPendingLiveInputCommit()- if (nextEnabled) {+ if (keepKeyboard) {+ const target = nextEnabled ? liveInputRef : commandInputRef+ target.current?.focus()+ } else if (nextEnabled) {scheduleTerminalLiveInputFocus(liveInputFocusTimerRef, () => liveInputRef.current?.focus())} else {- clearTerminalLiveInputFocusTimer(liveInputFocusTimerRef)liveInputRef.current?.blur()}- }, [activeHandle, clearPendingLiveInputCommit, toggleTerminalLiveInput])+ }, [activeHandle, clearPendingLiveInputCommit, keyboardHeight, toggleTerminalLiveInput])const allowTerminalGestureInput = useCallback((handle: string, sequenceCount: number): boolean => {diff --git a/mobile/src/session/use-mobile-session-terminal-runtime.ts b/mobile/src/session/use-mobile-session-terminal-runtime.tsindex 123d950cb42..36bb3cab059 100644--- a/mobile/src/session/use-mobile-session-terminal-runtime.ts+++ b/mobile/src/session/use-mobile-session-terminal-runtime.ts@@ -9,6 +9,7 @@ import type { TerminalModes, TerminalWebViewHandle } from '../terminal/terminal-import { useTerminalLiveInputFocus } from '../terminal/use-terminal-live-input-focus'import { reopensFocusedInputWhenKeyboardHidden } from '../terminal/terminal-live-input-keyboard-reopen'import type { TerminalLiveInputSender } from '../terminal/terminal-live-input-sender'+import type { TerminalLiveInputFailure } from '../terminal/terminal-live-pending-flush-state'import { useTerminalLiveInputCommit } from '../terminal/use-terminal-live-input-commit'import { resolveMobileTerminalInputGate } from '../terminal/terminal-input-connection-gate'import { createInitialSessionAutoCreateState } from './use-initial-session-terminal-autocreate'@@ -62,6 +63,10 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateMconst commandInputRef = useRef<TextInput>(null)const liveInputFocusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)const sendLiveTerminalInputRef = useRef<TerminalLiveInputSender>(async () => false)+ const onLiveInputSendFailureRef = useRef<(failure: TerminalLiveInputFailure) => void>(() => {})+ const handleLiveInputSendFailure = useCallback((failure: TerminalLiveInputFailure) => {+ onLiveInputSendFailureRef.current(failure)+ }, [])const sessionTabActionSheetKeyboardHideSubRef = useRef<ReturnType<typeof Keyboard.addListener> | null>(null)@@ -141,6 +146,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateMactiveSessionTabType: activeSessionTab?.type,activeSessionTabTypeRef,framesLivePaste,+ onSendFailure: handleLiveInputSendFailure,connected: connState === 'connected',liveInputRef,liveInputTerminalHandles,@@ -159,6 +165,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateMconst { handleTerminalTap, resetLiveInputFocus } = useTerminalLiveInputFocus({activeHandleRef,canSend,+ commandInputRef,inputRef: liveInputRef,keyboardHeight,lifecycleIdentity: client,@@ -192,6 +199,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateMcommandInputRef,liveInputFocusTimerRef,sendLiveTerminalInputRef,+ onLiveInputSendFailureRef,sessionTabActionSheetKeyboardHideSubRef,sessionTabActionSheetRequestSeqRef,dictationRouteContextRef,diff --git a/mobile/src/terminal/terminal-live-pending-flush-state.test.ts b/mobile/src/terminal/terminal-live-pending-flush-state.test.tsindex 207fc339d17..56d0d1ee65a 100644--- a/mobile/src/terminal/terminal-live-pending-flush-state.test.ts+++ b/mobile/src/terminal/terminal-live-pending-flush-state.test.ts@@ -20,34 +20,48 @@ describe('terminal live pending flush state', () => {})describe('terminal live mirror send queue', () => {- it('settles queued input when the sender throws before returning a promise', async () => {- const state = createTerminalLivePendingFlushState()- const writes: string[] = []- const results: Array<boolean | null> = [null, null]- const sender = (_handle: string, payload: string): Promise<boolean> => {- writes.push(payload)- if (writes.length === 1) {- throw new Error('transport unavailable')+ it.each(['throw', 'reject', 'refuse', 'too-large'] as const)(+ 'retires dependent input after a send fails by %s',+ async (failure) => {+ const state = createTerminalLivePendingFlushState()+ const writes: string[] = []+ const onFailure = vi.fn()+ state.onFailure = onFailure+ const sender = (_handle: string, payload: string): Promise<boolean> => {+ writes.push(payload)+ if (writes.length === 1 && failure !== 'too-large') {+ if (failure === 'throw') {+ throw new Error('transport unavailable')+ }+ return failure === 'reject'+ ? Promise.reject(new Error('timeout'))+ : Promise.resolve(false)+ }+ return Promise.resolve(true)}- return Promise.resolve(true)- }- void queueTerminalLiveMirrorSend(state, 'terminal-1', 'first', sender).then((sent) => {- results[0] = sent- })- void queueTerminalLiveMirrorSend(state, 'terminal-1', 'second', sender).then((sent) => {- results[1] = sent- })+ const first = queueTerminalLiveMirrorSend(+ state,+ 'terminal-1',+ failure === 'too-large' ? 'a'.repeat(TERMINAL_LIVE_INPUT_MAX_BYTES + 1) : 'first',+ sender+ )+ const second = queueTerminalLiveMirrorSend(state, 'terminal-1', 'second', sender)- await waitForTerminalLivePendingFlush(state)+ await waitForTerminalLivePendingFlush(state)- expect(results).toEqual([false, true])- expect(writes).toEqual(['first', 'second'])- expect(state.activeRequests).toEqual([])- expect(state.pendingBatches).toEqual([])- await expect(queueTerminalLiveMirrorSend(state, 'terminal-1', 'fresh', sender)).resolves.toBe(- true- )- })+ await expect(Promise.all([first, second])).resolves.toEqual([false, false])+ expect(writes).toEqual(failure === 'too-large' ? [] : ['first'])+ expect(onFailure).toHaveBeenCalledExactlyOnceWith(+ 'terminal-1',+ failure === 'too-large' ? 'input-too-large' : 'delivery-unconfirmed'+ )+ expect(state.activeRequests).toEqual([])+ expect(state.pendingBatches).toEqual([])+ await expect(queueTerminalLiveMirrorSend(state, 'terminal-1', 'fresh', sender)).resolves.toBe(+ true+ )+ }+ )it.each(['a', '😀'])('keeps coalesced %s input within the live sender byte limit',@@ -109,36 +123,6 @@ describe('terminal live mirror send queue', () => {expect(payloads).toEqual(['a', 'bc'])})- it('Given a failed previous send When a mirror send queues Then it still runs in order', async () => {- const state = createTerminalLivePendingFlushState()- const order: string[] = []- const first = queueTerminalLiveMirrorSend(state, 'terminal-1', 'first', async () => {- order.push('first')- return false- })-- const second = queueTerminalLiveMirrorSend(state, 'terminal-1', 'second', async () => {- order.push('second')- return true- })-- await expect(first).resolves.toBe(false)- await expect(second).resolves.toBe(true)- expect(order).toEqual(['first', 'second'])- })-- it('Given a throwing send When a mirror send queues Then the promise resolves false and the chain continues', async () => {- const state = createTerminalLivePendingFlushState()- const first = queueTerminalLiveMirrorSend(state, 'terminal-1', 'first', async () => {- throw new Error('boom')- })-- const second = queueTerminalLiveMirrorSend(state, 'terminal-1', 'second', async () => true)-- await expect(first).resolves.toBe(false)- await expect(second).resolves.toBe(true)- })-it('batches repeated controls behind an in-flight send, apart from the text before them', async () => {const state = createTerminalLivePendingFlushState()const writes: string[] = []diff --git a/mobile/src/terminal/terminal-live-pending-flush-state.ts b/mobile/src/terminal/terminal-live-pending-flush-state.tsindex 9975502c115..283ff2b3479 100644--- a/mobile/src/terminal/terminal-live-pending-flush-state.ts+++ b/mobile/src/terminal/terminal-live-pending-flush-state.ts@@ -1,4 +1,5 @@type TerminalLiveMirrorSender = (handle: string, payload: string) => Promise<boolean>+export type TerminalLiveInputFailure = 'input-too-large' | 'delivery-unconfirmed'type TerminalLivePendingRequest = {readonly resolve: (sent: boolean) => void@@ -14,6 +15,7 @@ type TerminalLivePendingBatch = {}export type TerminalLivePendingFlushState = {+ onFailure: ((handle: string, failure: TerminalLiveInputFailure) => void) | nullcurrent: Promise<boolean> | nullcancelCurrent: (() => void) | nullactiveRequests: TerminalLivePendingRequest[]@@ -23,6 +25,7 @@ export type TerminalLivePendingFlushState = {export function createTerminalLivePendingFlushState(): TerminalLivePendingFlushState {return {+ onFailure: null,current: null,cancelCurrent: null,activeRequests: [],@@ -55,33 +58,41 @@ async function drainTerminalLiveMirrorSends(state: TerminalLivePendingFlushState,generation: number): Promise<boolean> {- let allSent = truewhile (state.generation === generation) {const batch = state.pendingBatches.shift()if (!batch) {state.current = null- return allSent+ return true}state.activeRequests = batch.requests- let sent = false- // A control after undelivered text could act on the wrong line, e.g. Return running a partial command.- if (allSent || !batch.control) {- let delivery: Promise<boolean>- try {- delivery = batch.sender(batch.handle, batch.payload)- } catch {- delivery = Promise.resolve(false)- }- sent = await delivery.catch(() => false)- if (state.generation !== generation) {- return false- }+ let delivery: Promise<boolean>+ try {+ delivery =+ batch.byteLength > TERMINAL_LIVE_INPUT_MAX_BYTES+ ? Promise.resolve(false)+ : batch.sender(batch.handle, batch.payload)+ } catch {+ delivery = Promise.resolve(false)+ }+ const sent = await delivery.catch(() => false)+ if (state.generation !== generation) {+ return false+ }+ if (!sent) {+ // Later deltas and controls depend on bytes whose delivery is now unknown.+ cancelTerminalLivePendingFlush(state)+ state.onFailure?.(+ batch.handle,+ batch.byteLength > TERMINAL_LIVE_INPUT_MAX_BYTES+ ? 'input-too-large'+ : 'delivery-unconfirmed'+ )+ return false}state.activeRequests = []batch.requests.forEach(({ resolve }) => resolve(sent))- allSent &&= sent}return false}diff --git a/mobile/src/terminal/use-terminal-live-input-commit.test.ts b/mobile/src/terminal/use-terminal-live-input-commit.test.tsindex bff3891bbbf..6c2c0dd4023 100644--- a/mobile/src/terminal/use-terminal-live-input-commit.test.ts+++ b/mobile/src/terminal/use-terminal-live-input-commit.test.ts@@ -23,6 +23,7 @@ function changeLiveInput(}type TerminalLiveInputCommitHarness = {+ readonly failures: ReturnType<typeof vi.fn>readonly captures: readonly string[]readonly getHandlers: () => TerminalLiveInputCommitHandlersreadonly handlers: TerminalLiveInputCommitHandlers@@ -35,11 +36,13 @@ type TerminalLiveInputCommitHarness = {type TerminalLiveInputCommitHarnessOptions = {readonly sendResult?: boolean+ readonly sender?: TerminalLiveInputSenderreadonly bracketedPaste?: boolean}function createTerminalLiveInputCommitHarness({sendResult = true,+ sender,bracketedPaste = false}: TerminalLiveInputCommitHarnessOptions = {}): TerminalLiveInputCommitHarness {const activeHandle = 'terminal-a'@@ -55,11 +58,12 @@ function createTerminalLiveInputCommitHarness({current: new Set([activeHandle])}const sent: string[] = []+ const failures = vi.fn()let currentSendResult = sendResultconst sendLiveTerminalInputRef: RefObject<TerminalLiveInputSender> = {- current: async (_handle, bytes) => {+ current: async (handle, bytes) => {sent.push(bytes)- return currentSendResult+ return sender ? sender(handle, bytes) : currentSendResult}}let currentActiveSessionTabType: string | undefined = 'terminal'@@ -74,6 +78,7 @@ function createTerminalLiveInputCommitHarness({activeSessionTabType: currentActiveSessionTabType,activeSessionTabTypeRef,connected: currentConnected,+ onSendFailure: failures,framesLivePaste: () => bracketedPaste,liveInputRef,liveInputTerminalHandles,@@ -92,6 +97,7 @@ function createTerminalLiveInputCommitHarness({}return {+ failures,captures,getHandlers: () => {if (!handlers) {@@ -125,6 +131,65 @@ function createTerminalLiveInputCommitHarness({}describe('terminal live input commit hook', () => {+ it.each(['refused', 'timed-out'] as const)(+ 'ends a %s field session once and drops edits and Return that depended on it',+ async (failure) => {+ let fail = (): void => {}+ const pending = new Promise<boolean>((resolve, reject) => {+ fail = () => (failure === 'refused' ? resolve(false) : reject(new Error('timeout')))+ })+ const sender = vi+ .fn<TerminalLiveInputSender>()+ .mockReturnValueOnce(pending)+ .mockResolvedValue(true)+ const { handlers, sent, captures, failures, unmount } = createTerminalLiveInputCommitHarness({+ sender+ })+ changeLiveInput(handlers, 'abc', false)+ changeLiveInput(handlers, 'ab', false)+ const submit = handlers.handleLiveInputSubmit()++ fail()+ await expect(submit).resolves.toBe(false)+ expect(sent).toEqual(['abc'])+ expect(captures.at(-1)).toBe('')+ expect(failures).toHaveBeenCalledTimes(1)++ changeLiveInput(handlers, 'ab', false)+ changeLiveInput(handlers, 'x', false)+ await vi.waitFor(() => expect(sent).toEqual(['abc', 'x']))+ changeLiveInput(handlers, '', false)+ await vi.waitFor(() => expect(sent).toEqual(['abc', 'x', '\x7f']))+ expect(failures).toHaveBeenCalledTimes(1)+ unmount()+ }+ )++ it('keeps a retired delivery failure from clearing or reporting in a fresh field session', async () => {+ let rejectRetired = (_error: Error): void => {}+ const retired = new Promise<boolean>((_resolve, reject) => {+ rejectRetired = reject+ })+ const sender = vi+ .fn<TerminalLiveInputSender>()+ .mockReturnValueOnce(retired)+ .mockResolvedValue(true)+ const { getHandlers, captures, sent, failures, setConnected, unmount } =+ createTerminalLiveInputCommitHarness({ sender })+ changeLiveInput(getHandlers(), 'old', false)+ setConnected(false)+ setConnected(true)+ changeLiveInput(getHandlers(), 'new', false)+ await vi.waitFor(() => expect(sent).toEqual(['old', 'new']))++ rejectRetired(new Error('retired timeout'))+ await new Promise<void>((resolve) => setImmediate(resolve))++ expect(captures.at(-1)).toBe('new')+ expect(failures).not.toHaveBeenCalled()+ unmount()+ })+it('frames a long OS paste, then ends the field session so later edits never erase into it', async () => {// Agents such as Codex collapse a framed paste into one token, so per-character DELs would desync.const { handlers, sent, captures } = createTerminalLiveInputCommitHarness({@@ -339,9 +404,10 @@ describe('terminal live input commit hook', () => {})it('Given a failed mirrored Backspace When accessory input commits Then reports failure', async () => {- const { handlers, sent } = createTerminalLiveInputCommitHarness({ sendResult: false })+ const { handlers, sent, setSendResult } = createTerminalLiveInputCommitHarness()changeLiveInput(handlers, 'a', false)await vi.waitFor(() => expect(sent).toEqual(['a']))+ setSendResult(false)const result = await handlers.handleLiveInputAccessoryBytes({bytes: '\x7f',diff --git a/mobile/src/terminal/use-terminal-live-input-commit.ts b/mobile/src/terminal/use-terminal-live-input-commit.tsindex 495d876b6da..8af5e6a86ef 100644--- a/mobile/src/terminal/use-terminal-live-input-commit.ts+++ b/mobile/src/terminal/use-terminal-live-input-commit.ts@@ -7,6 +7,7 @@ import type { TerminalLiveInputSender } from './terminal-live-input-sender'import { writeTerminalLiveInputText } from './terminal-live-input-text-write'import { normalizeTerminalTextInput } from './terminal-text-input-normalization'import { useTerminalLivePendingInputFlush } from './use-terminal-live-pending-input-flush'+import type { TerminalLiveInputFailure } from './terminal-live-pending-flush-state'import {readLiveInputSelection,useTerminalLiveAccessoryInputCommit,@@ -37,6 +38,7 @@ type TerminalLiveInputCommitOptions<TTabType extends string> = {readonly activeSessionTabType: TTabType | null | undefinedreadonly activeSessionTabTypeRef: RefObject<TTabType | null>readonly framesLivePaste?: (handle: string) => boolean+ readonly onSendFailure?: (failure: TerminalLiveInputFailure) => voidreadonly connected: booleanreadonly liveInputRef: RefObject<TextInput | null>readonly liveInputTerminalHandles: ReadonlySet<string>@@ -64,6 +66,7 @@ export function useTerminalLiveInputCommit<TTabType extends string>({activeSessionTabType,activeSessionTabTypeRef,framesLivePaste,+ onSendFailure,connected,liveInputRef,liveInputTerminalHandles,@@ -92,8 +95,9 @@ export function useTerminalLiveInputCommit<TTabType extends string>({// Drop the cleared field's late native echo of whatever session just ended.const recordEndedSession = useCallback((handle: string) => {const fieldText = liveInputTextRef.current- endedSessionTextRef.current =- fieldText.length > 0 ? { handle, text: fieldText, at: Date.now() } : null+ if (fieldText.length > 0) {+ endedSessionTextRef.current = { handle, text: fieldText, at: Date.now() }+ }}, [])const {applyLiveInputMirror,@@ -112,7 +116,8 @@ export function useTerminalLiveInputCommit<TTabType extends string>({framesLivePaste,liveInputRef,liveInputTerminalHandlesRef,- onPasteEndsFieldSession: recordEndedSession,+ onFieldSessionEnded: recordEndedSession,+ onSendFailure,sendLiveTerminalInputRef,setLiveInputCapture: updateLiveInputCapture})diff --git a/mobile/src/terminal/use-terminal-live-input-focus.test.ts b/mobile/src/terminal/use-terminal-live-input-focus.test.tsindex c7e9976db64..cd296dc1251 100644--- a/mobile/src/terminal/use-terminal-live-input-focus.test.ts+++ b/mobile/src/terminal/use-terminal-live-input-focus.test.ts@@ -11,6 +11,7 @@ type HarnessProps = {readonly activeHandleRef: RefObject<string | null>readonly canSend: booleanreadonly inputRef: RefObject<TerminalLiveInputFocusTarget | null>+ readonly commandInputRef: RefObject<TerminalLiveInputFocusTarget | null>readonly keyboardHeight?: numberreadonly lifecycleIdentity: object | nullreadonly lifecycleKey: string@@ -90,6 +91,7 @@ function connectedProps(activeHandleRef,canSend: true,inputRef,+ commandInputRef: { current: null },lifecycleIdentity: null,lifecycleKey: 'host-a:worktree-a:connected',liveInputEnabled: true,diff --git a/mobile/src/terminal/use-terminal-live-input-focus.ts b/mobile/src/terminal/use-terminal-live-input-focus.tsindex 36fa0f5272e..2b556f0e653 100644--- a/mobile/src/terminal/use-terminal-live-input-focus.ts+++ b/mobile/src/terminal/use-terminal-live-input-focus.ts@@ -18,6 +18,7 @@ type UseTerminalLiveInputFocusOptions<T extends TerminalLiveInputFocusTarget> =TerminalLiveInputFocusContext & {readonly activeHandleRef: RefObject<string | null>readonly inputRef: RefObject<T | null>+ readonly commandInputRef: RefObject<TerminalLiveInputFocusTarget | null>readonly lifecycleIdentity: object | nullreadonly lifecycleKey: stringreadonly timerRef: TerminalLiveInputFocusTimerRef@@ -32,6 +33,7 @@ type TerminalLiveInputFocusHandlers = {export function useTerminalLiveInputFocus<T extends TerminalLiveInputFocusTarget>({activeHandleRef,canSend,+ commandInputRef,inputRef,keyboardHeight,lifecycleIdentity,@@ -63,6 +65,15 @@ export function useTerminalLiveInputFocus<T extends TerminalLiveInputFocusTarget// Retained Expo routes must not carry focus work across navigation or reconnect scopes.useLayoutEffect(() => resetLiveInputFocus, [lifecycleIdentity, lifecycleKey, resetLiveInputFocus])+ useLayoutEffect(() => {+ const inactive = liveInputEnabled ? commandInputRef : inputRef+ if (inactive.current?.isFocused?.()) {+ clearTerminalLiveInputFocusTimer(timerRef)+ const active = liveInputEnabled ? inputRef : commandInputRef+ active.current?.focus()+ }+ }, [commandInputRef, inputRef, liveInputEnabled, timerRef])+const focusLiveInput = useCallback(() => {const context = contextRef.currentif (!context.canSend || !context.liveInputEnabled) {diff --git a/mobile/src/terminal/use-terminal-live-pending-input-flush.ts b/mobile/src/terminal/use-terminal-live-pending-input-flush.tsindex 27c405ca297..b06f19a5caf 100644--- a/mobile/src/terminal/use-terminal-live-pending-input-flush.ts+++ b/mobile/src/terminal/use-terminal-live-pending-input-flush.ts@@ -18,14 +18,16 @@ import {createTerminalLivePendingFlushState,queueTerminalLiveControlSend,queueTerminalLiveMirrorSend,- waitForTerminalLivePendingFlush+ waitForTerminalLivePendingFlush,+ type TerminalLiveInputFailure} from './terminal-live-pending-flush-state'type TerminalLivePendingInputFlushOptions<TTabType extends string> = {readonly activeHandleRef: RefObject<string | null>readonly activeSessionTabTypeRef: RefObject<TTabType | null>readonly framesLivePaste?: (handle: string) => boolean- readonly onPasteEndsFieldSession?: (handle: string) => void+ readonly onFieldSessionEnded?: (handle: string) => void+ readonly onSendFailure?: (failure: TerminalLiveInputFailure) => voidreadonly liveInputRef: RefObject<TextInput | null>readonly liveInputTerminalHandlesRef: RefObject<Set<string>>readonly sendLiveTerminalInputRef: RefObject<TerminalLiveInputSender>@@ -60,7 +62,8 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({activeHandleRef,activeSessionTabTypeRef,framesLivePaste,- onPasteEndsFieldSession,+ onFieldSessionEnded,+ onSendFailure,liveInputRef,liveInputTerminalHandlesRef,sendLiveTerminalInputRef,@@ -96,6 +99,18 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({writeTerminalLiveInputText(liveInputRef, '')}, [liveInputRef, resetMirrorState, setLiveInputCapture])+ useEffect(() => {+ const state = pendingLiveInputFlushRef.current+ state.onFailure = (handle, failure) => {+ onFieldSessionEnded?.(handle)+ clearPendingLiveInputCommit()+ onSendFailure?.(failure)+ }+ return () => {+ state.onFailure = null+ }+ }, [clearPendingLiveInputCommit, onFieldSessionEnded, onSendFailure])+const waitForPendingLiveInputFlush = useCallback(async (): Promise<boolean> => {return waitForTerminalLivePendingFlush(pendingLiveInputFlushRef.current)}, [])@@ -179,7 +194,7 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({sendQueuedMirrorPayload)if (pasted) {- onPasteEndsFieldSession?.(handle)+ onFieldSessionEnded?.(handle)clearHeldCommitTimer()heldLiveInputTextRef.current = ''liveInputComposingRef.current = undefined@@ -196,7 +211,7 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({clearHeldCommitTimer,isFramedPasteAppend,liveInputRef,- onPasteEndsFieldSession,+ onFieldSessionEnded,liveInputTerminalHandlesRef,resetMirrorState,sendQueuedMirrorPayload,@@ -293,19 +308,7 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({])- useEffect(() => {- return () => {- if (heldCommitTimerRef.current) {- clearTimeout(heldCommitTimerRef.current)- heldCommitTimerRef.current = null- }- heldLiveInputTextRef.current = ''- liveInputComposingRef.current = undefined- sentLiveInputTextRef.current = ''- pendingLiveInputHandleRef.current = null- cancelTerminalLivePendingFlush(pendingLiveInputFlushRef.current)- }- }, [])+ useEffect(() => resetMirrorState, [resetMirrorState])return {applyLiveInputMirror,