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): return typed terminal input to the prompt (#36122)
Kelvin Amoabaa7c63de35e26
diff --git a/mobile/src/session/mobile-image-live-input-order.test.tsx b/mobile/src/session/mobile-image-live-input-order.test.tsxindex 283a1ad2f22..446452623ee 100644--- a/mobile/src/session/mobile-image-live-input-order.test.tsx+++ b/mobile/src/session/mobile-image-live-input-order.test.tsx@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'import { createElement } from 'react'import { act, create, type ReactTestRenderer } from 'react-test-renderer'import { afterEach, beforeEach, expect, it, vi } from 'vitest'@@ -82,6 +83,7 @@ function fixture(title = 'Terminal', imagePath = '/tmp/orca-image.png', launchAgconst liveInputRef = ref(null)const sendLiveTerminalInputRef = ref<TerminalLiveInputSender>(async () => false)const scope = {+ sendTerminalUserInput: terminalInputSend.request,client,clientRef: ref(client),activeHandle: 'term-1',diff --git a/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx b/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsxindex 3e2cb542325..c7ae8eb8677 100644--- a/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx+++ b/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'import { createElement, useLayoutEffect, useRef } from 'react'import { act, create, type ReactTestRenderer } from 'react-test-renderer'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -85,6 +86,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {connStateRef.current = props.state}, [props.client, props.handle, props.state])const scope = {+ sendTerminalUserInput: terminalInputSend.request,client: props.client,clientRef,activeHandle: props.handle,diff --git a/mobile/src/session/mobile-worker-takeover-send-sites.test.ts b/mobile/src/session/mobile-worker-takeover-send-sites.test.tsindex 01d5e3641e0..bd989bc6a96 100644--- a/mobile/src/session/mobile-worker-takeover-send-sites.test.ts+++ b/mobile/src/session/mobile-worker-takeover-send-sites.test.ts@@ -3,6 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer'import { beforeEach, afterEach, expect, it, vi } from 'vitest'import type { RpcClient } from '../transport/rpc-client'import { resetWorkerTerminalTakeoverReportsForTest } from '../terminal/worker-terminal-takeover-report'+import { useMobileSessionTerminalWebview } from './use-mobile-session-terminal-webview'import { useMobileSessionTerminalSendActions } from './use-mobile-session-terminal-send-actions'import { useMobileSessionTerminalInput } from './use-mobile-session-terminal-input'import { useMobileTerminalPaste } from './use-mobile-terminal-paste'@@ -18,7 +19,8 @@ import { pasteMobileNativeChatImagePaths } from './native-chat/composer/mobile-nvi.mock('react-native', () => ({ Keyboard: { dismiss: vi.fn() } }))vi.mock('../platform/haptics', () => ({ triggerError: vi.fn(), triggerSuccess: vi.fn() }))-vi.mock('expo-clipboard', () => ({ getStringAsync: async () => 'pasted text' }))+const clipboard = vi.hoisted(() => ({ text: 'pasted text' }))+vi.mock('expo-clipboard', () => ({ getStringAsync: async () => clipboard.text }))vi.mock('./mobile-image-source-picker', () => ({pickMobileImage: vi.fn(),pickMobileImages: vi.fn()@@ -47,7 +49,9 @@ function mountSendSites(client: ReturnType<typeof clientFixture>, handle = 'termconst activeHandleRef = ref<string | null>(handle)const activeSessionTabTypeRef = ref<string | null>('terminal')const sendLiveTerminalInputRef = ref(async (_handle: string, _text: string) => false)+ const scrollToBottom = vi.fn()const scope = {+ terminalRefs: ref(new Map([[handle, { scrollToBottom }]])),client,clientRef: ref(client),activeHandle: handle,@@ -94,13 +98,24 @@ function mountSendSites(client: ReturnType<typeof clientFixture>, handle = 'termsendLiveTerminalInputRef,setLiveInputCapture: vi.fn()})+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only supplied view refs are read; unrelated subscription callbacks never run.+ const webview = useMobileSessionTerminalWebview(scope as never)+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies the send routes; unrelated session model fields are unused.actions = useMobileSessionTerminalSendActions({...scope,+ ...webview,handleLiveInputAccessoryBytes: live.handleLiveInputAccessoryBytes} as never)- gestures = useMobileSessionTerminalInput(scope as never)+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies gesture refs; unrelated file-action callbacks are unused.+ gestures = useMobileSessionTerminalInput({+ ...scope,+ liveInputTerminalHandlesRef: ref(new Set([handle])),+ sendLiveInputClick: live.sendLiveInputClick+ } as never)+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies paste dependencies; unrelated session callbacks are unused.paste = useMobileTerminalPaste({...scope,+ sendTerminalUserInput: webview.sendTerminalUserInput,flushPendingLiveInputBeforeExternalSend: live.flushPendingLiveInputBeforeExternalSend,getActiveWorktreeConnectionId: async () => null,onError: vi.fn(),@@ -124,11 +139,18 @@ function mountSendSites(client: ReturnType<typeof clientFixture>, handle = 'term})let text = ''return {+ scrollToBottom,'live field': async () => {text += 'x'live.handleLiveInputChange({ nativeEvent: { text, isComposing: false } })await live.flushPendingLiveInputBeforeExternalSend(handle)},+ 'mouse-shaped live field': async () => {+ live.handleLiveInputChange({+ nativeEvent: { text: '\x1b[<0;2;2M', isComposing: false }+ })+ await live.flushPendingLiveInputBeforeExternalSend(handle)+ },'live submit': () => live.handleLiveInputSubmit(),'live accessory': async () => {live.handleLiveInputChange({ nativeEvent: { text: 'composing', isComposing: true } })@@ -136,10 +158,24 @@ function mountSendSites(client: ReturnType<typeof clientFixture>, handle = 'term},'raw accessory': () => actions.handleAccessoryKey({ bytes: '\x1b[A' } as never),'buffered submit': () => actions.handleSend(),+ 'mouse-shaped composer': () => {+ scope.bufferedTerminalDraftState.input = '\x1b[<0;2;2M'+ return actions.handleSend()+ },+ 'mouse-shaped paste': () => {+ clipboard.text = '\x1b[<0;2;2M'+ return paste()+ },+ 'accessory tab': () => actions.handleAccessoryKey({ bytes: '\t' }),'gesture arrows': async () => {await gestures.handleTerminalInput(handle, '\x1b[A')await gestures.flushTerminalGestureInput(handle)},+ 'gesture wheel': async () => {+ await gestures.handleTerminalInput(handle, '\x1b[<64;2;2M')+ await gestures.flushTerminalGestureInput(handle)+ },+ 'gesture click': () => gestures.handleTerminalInput(handle, '\x1b[<0;2;2M', { click: true }),paste: () => paste(),dictation: async () => {const route = routeDictationTranscript('dictated text', true)@@ -186,6 +222,7 @@ beforeEach(() => {vi.useFakeTimers()vi.setSystemTime(1_000)resetWorkerTerminalTakeoverReportsForTest()+ clipboard.text = 'pasted text'})afterEach(() => {act(() => {@@ -264,3 +301,39 @@ it.each(realSites)('%s does not report a rejected send', async (site) => {})expect(client.sendRequest.mock.calls.filter(([method]) => method === REPORT)).toHaveLength(0)})++it.each([+ 'live field',+ 'live submit',+ 'live accessory',+ 'raw accessory',+ 'accessory tab',+ 'buffered submit',+ 'mouse-shaped live field',+ 'mouse-shaped composer',+ 'mouse-shaped paste',+ 'paste',+ 'dictation'+] as const)('%s returns to the prompt once per typed send', async (site) => {+ const client = clientFixture()+ const sites = mountSendSites(client)+ await act(async () => {+ await sites[site]()+ })+ const sends = client.sendRequest.mock.calls.filter(([method]) => method === 'terminal.send')+ expect(sends.length).toBeGreaterThan(0)+ expect(sites.scrollToBottom).toHaveBeenCalledTimes(sends.length)+})++it.each(['query reply', 'gesture arrows', 'gesture wheel', 'gesture click'] as const)(+ '%s preserves the reading position',+ async (site) => {+ const client = clientFixture()+ const sites = mountSendSites(client)+ await act(async () => {+ await sites[site]()+ })+ expect(client.sendRequest.mock.calls.some(([method]) => method === 'terminal.send')).toBe(true)+ expect(sites.scrollToBottom).not.toHaveBeenCalled()+ }+)diff --git a/mobile/src/session/terminal-field-submit-binding-send.test.tsx b/mobile/src/session/terminal-field-submit-binding-send.test.tsxindex 2526eddfb9d..254be9734c0 100644--- a/mobile/src/session/terminal-field-submit-binding-send.test.tsx+++ b/mobile/src/session/terminal-field-submit-binding-send.test.tsx@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'// @vitest-environment happy-domimport { createElement, useEffect, useRef, type RefObject } from 'react'import { act, create, type ReactTestRenderer } from 'react-test-renderer'@@ -59,6 +60,7 @@ let restoredDrafts: string[] = []function buildScope(session: Session): MobileSessionTerminalWebviewModel {const noop = (): void => {}const scope = {+ sendTerminalUserInput: terminalInputSend.request,client: session.client,activeHandle: session.activeHandle,activeSessionTab: null,diff --git a/mobile/src/session/terminal-tap-click-delivery.test.ts b/mobile/src/session/terminal-tap-click-delivery.test.tsindex b803006bc11..f8f1e75ba88 100644--- a/mobile/src/session/terminal-tap-click-delivery.test.ts+++ b/mobile/src/session/terminal-tap-click-delivery.test.ts@@ -112,7 +112,7 @@ it('sends a click at once for a terminal without the live field, past a wheel inexpect(request).toHaveBeenCalledTimes(1)await actions.handleTerminalInput(handle, click, { click: true })await vi.advanceTimersByTimeAsync(300)- expect(sendLiveTerminalInput).toHaveBeenCalledWith(handle, click)+ expect(sendLiveTerminalInput).toHaveBeenCalledWith(handle, click, 'pointer')expect(sendLiveInputClick).not.toHaveBeenCalled()release()await settle()diff --git a/mobile/src/session/use-mobile-session-attachments.ts b/mobile/src/session/use-mobile-session-attachments.tsindex 4f9814cdc84..8b33b6e0f89 100644--- a/mobile/src/session/use-mobile-session-attachments.ts+++ b/mobile/src/session/use-mobile-session-attachments.ts@@ -54,6 +54,7 @@ export function useMobileSessionAttachments(scope: MobileSessionAccessorySelectinativeChatController.nativeChatAgent)const handlePaste = useMobileTerminalPaste({+ sendTerminalUserInput: scope.sendTerminalUserInput,client,agent,activeHandle,diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.tsindex 529c4efc3fb..8ee7721f49a 100644--- a/mobile/src/session/use-mobile-session-terminal-input.ts+++ b/mobile/src/session/use-mobile-session-terminal-input.ts@@ -225,7 +225,7 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod// A deliberate click must survive wheel limits and follow text queued for the old cursor.void (liveInputTerminalHandlesRef.current.has(handle)? sendLiveInputClick(handle, bytes)- : sendLiveTerminalInputRef.current(handle, bytes))+ : sendLiveTerminalInputRef.current(handle, bytes, 'pointer'))return}if (!allowTerminalGestureInput(handle, sequenceCount)) {diff --git a/mobile/src/session/use-mobile-session-terminal-resubscribe-snapshot.test.tsx b/mobile/src/session/use-mobile-session-terminal-resubscribe-snapshot.test.tsxindex 0cea20ec4dd..fda9ec6a248 100644--- a/mobile/src/session/use-mobile-session-terminal-resubscribe-snapshot.test.tsx+++ b/mobile/src/session/use-mobile-session-terminal-resubscribe-snapshot.test.tsx@@ -79,6 +79,7 @@ function harness(phone: Terminal) {reflow: vi.fn(),clear: vi.fn(),fitDimensions: vi.fn(() => ({ cols: COLS, rows: ROWS })),+ scrollToBottom: vi.fn(),resetZoom: vi.fn(),cancelSelect: vi.fn(),doSelectAll: vi.fn(),diff --git a/mobile/src/session/use-mobile-session-terminal-send-actions.ts b/mobile/src/session/use-mobile-session-terminal-send-actions.tsindex e9ddf5957d5..fb8ffcf4c44 100644--- a/mobile/src/session/use-mobile-session-terminal-send-actions.ts+++ b/mobile/src/session/use-mobile-session-terminal-send-actions.ts@@ -26,6 +26,7 @@ import type { MobileSessionTerminalWebviewModel } from './use-mobile-session-terexport function useMobileSessionTerminalSendActions(scope: MobileSessionTerminalWebviewModel) {const {client,+ sendTerminalUserInput: sendUserInput,activeHandle,activeSessionTab,setActionTarget,@@ -124,7 +125,7 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminaltry {// Fail/restore immediately so reconnect cannot execute stale text long after the tap.- const response = await terminalInputSend.request(+ const response = await sendUserInput(client,buildTerminalSendParams({terminal: activeHandle,@@ -180,6 +181,7 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminal}return sendTerminalLiveAccessoryRawBytes({client,+ sendTerminalUserInput: sendUserInput,targetHandle,activeHandle: activeHandleRef.current,activeSessionTabType: activeSessionTabTypeRef.current,@@ -190,7 +192,7 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminal}const sendLiveTerminalInput = useCallback(- async (handle: string, bytes: string): Promise<boolean> => {+ async (handle: string, bytes: string, origin?: 'pointer'): Promise<boolean> => {const text = encodeTerminalKeyForModes(normalizeTerminalTextInput(bytes),ptyModesRef.current.get(handle)@@ -220,29 +222,28 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminalreturn false}// Discard live-mirror deltas behind a dying send so reconnect cannot replay stale bytes.- return terminalInputSend- .request(- rpc,- buildTerminalSendParams({- terminal: handle,- text,- enter: false,- deviceToken: deviceTokenRef.current- }),- TERMINAL_INPUT_SEND_OPTIONS- )- .then(- (response) => {- const accepted = terminalInputSend.interpret(response) === true- if (accepted) {- reportWorkerTerminalUserInput(rpc, handle)- }- return accepted- },- () => false- )+ const send = origin === 'pointer' ? terminalInputSend.request : sendUserInput+ return send(+ rpc,+ buildTerminalSendParams({+ terminal: handle,+ text,+ enter: false,+ deviceToken: deviceTokenRef.current+ }),+ TERMINAL_INPUT_SEND_OPTIONS+ ).then(+ (response) => {+ const accepted = terminalInputSend.interpret(response) === true+ if (accepted) {+ reportWorkerTerminalUserInput(rpc, handle)+ }+ return accepted+ },+ () => false+ )},- [showToast]+ [sendUserInput, showToast])sendLiveTerminalInputRef.current = sendLiveTerminalInputdiff --git a/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx b/mobile/src/session/use-mobile-session-terminal-subscription.test.tsxindex df8c0ac2c21..2d39ff695a6 100644--- a/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx+++ b/mobile/src/session/use-mobile-session-terminal-subscription.test.tsx@@ -48,6 +48,7 @@ function subscriptionHarness(opts: {reflow: vi.fn(),clear: vi.fn(),fitDimensions: vi.fn(() => fit),+ scrollToBottom: vi.fn(),resetZoom: vi.fn(),cancelSelect: vi.fn(),doSelectAll: vi.fn(),diff --git a/mobile/src/session/use-mobile-session-terminal-webview.ts b/mobile/src/session/use-mobile-session-terminal-webview.tsindex fe123e7e659..3906f9c5277 100644--- a/mobile/src/session/use-mobile-session-terminal-webview.ts+++ b/mobile/src/session/use-mobile-session-terminal-webview.ts@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'import { pendingSelectionHandle, pendingSelectionWantsHandle } from './pending-session-selection'import { useEffect, useCallback } from 'react'import type { TerminalWebViewHandle } from '../terminal/terminal-webview-contract'@@ -28,6 +29,13 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitchingnotifyTerminalFrameHeight,notifyTerminalFrameWidth} = scope+ const sendTerminalUserInput = useCallback<typeof terminalInputSend.request>(+ (client, params, options) => {+ terminalRefs.current.get(params.terminal)?.scrollToBottom()+ return terminalInputSend.request(client, params, options)+ },+ [terminalRefs]+ )// Store the ref but subscribe only after web-ready so init cannot precede xterm loading.const setTerminalWebViewRef = useCallback((handle: string, ref: TerminalWebViewHandle | null) => {terminalDiagnosticsRef.current.webViewRef(handle, ref != null)@@ -125,6 +133,7 @@ export function useMobileSessionTerminalWebview(scope: MobileSessionTabSwitching}}, [activeSessionTab, fileDocs, readFileTab])return {+ sendTerminalUserInput,setTerminalWebViewRef,handleTerminalWebReady,notifyTerminalFramediff --git a/mobile/src/session/use-mobile-terminal-paste-dropped.test.ts b/mobile/src/session/use-mobile-terminal-paste-dropped.test.tsindex 21174744590..2c72934658f 100644--- a/mobile/src/session/use-mobile-terminal-paste-dropped.test.ts+++ b/mobile/src/session/use-mobile-terminal-paste-dropped.test.ts@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'import { beforeEach, describe, expect, it, vi } from 'vitest'import type { RpcClient } from '../transport/rpc-client'import type { ConnectionState } from '../transport/types'@@ -46,6 +47,7 @@ function setup() {const showToast = vi.fn()let beforeSend = (): boolean => trueconst options: Parameters<typeof useMobileTerminalPaste>[0] = {+ sendTerminalUserInput: terminalInputSend.request,agent: null,activeHandle: 'term-1',activeHandleRef,diff --git a/mobile/src/session/use-mobile-terminal-paste.test.ts b/mobile/src/session/use-mobile-terminal-paste.test.tsindex 4af8b5d7bb5..c501a8c87d6 100644--- a/mobile/src/session/use-mobile-terminal-paste.test.ts+++ b/mobile/src/session/use-mobile-terminal-paste.test.ts@@ -1,3 +1,4 @@+import { terminalInputSend } from '../terminal/mobile-terminal-operations'import { describe, expect, it, vi } from 'vitest'import type { RpcClient } from '../transport/rpc-client'import type { ConnectionState } from '../transport/types'@@ -42,6 +43,7 @@ describe('mobile clipboard image followed by typing', () => {close: vi.fn()}const paste = useMobileTerminalPaste({+ sendTerminalUserInput: terminalInputSend.request,agent,activeHandle: 'term-1',activeHandleRef: { current: 'term-1' },@@ -94,6 +96,7 @@ describe('mobile clipboard image followed by typing', () => {})const onSuccess = vi.fn()const paste = useMobileTerminalPaste({+ sendTerminalUserInput: terminalInputSend.request,agent: null,activeHandle: 'term-1',activeHandleRef,@@ -154,6 +157,7 @@ describe('mobile clipboard text paste', () => {close: vi.fn()}const paste = useMobileTerminalPaste({+ sendTerminalUserInput: terminalInputSend.request,agent: null,activeHandle: 'term-1',activeHandleRef: { current: 'term-1' },diff --git a/mobile/src/session/use-mobile-terminal-paste.ts b/mobile/src/session/use-mobile-terminal-paste.tsindex 9421499d8bb..472f9b7be35 100644--- a/mobile/src/session/use-mobile-terminal-paste.ts+++ b/mobile/src/session/use-mobile-terminal-paste.ts@@ -29,6 +29,7 @@ function buildMobileTerminalClipboardTextPayload(}type UseMobileTerminalPasteOptions = {+ readonly sendTerminalUserInput: typeof terminalInputSend.requestreadonly agent?: string | nullreadonly activeHandle: string | nullreadonly activeHandleRef: RefObject<string | null>@@ -49,6 +50,7 @@ type UseMobileTerminalPasteOptions = {}export function useMobileTerminalPaste({+ sendTerminalUserInput,activeHandle,agent,activeHandleRef,@@ -148,7 +150,7 @@ export function useMobileTerminalPaste({showToast(translate('session.useTerminalPaste.pasteFailed', 'Paste failed'), 1500)return}- const response = await terminalInputSend.request(currentClient, {+ const response = await sendTerminalUserInput(currentClient, {terminal: targetHandle,text: payload,enter: false,@@ -181,6 +183,7 @@ export function useMobileTerminalPaste({}}}, [+ sendTerminalUserInput,activeHandle,agent,activeHandleRef,diff --git a/mobile/src/terminal/document/host-message-router.ts b/mobile/src/terminal/document/host-message-router.tsindex e6ab29d016d..aef33776802 100644--- a/mobile/src/terminal/document/host-message-router.ts+++ b/mobile/src/terminal/document/host-message-router.ts@@ -87,6 +87,13 @@ export function handleMsg(scope: TerminalDocumentScope, msg: TerminalHostMessagereflow(scope, msg.cols!, msg.rows!)} else if (msg.type === 'write') {write(scope, msg.data!)+ } else if (msg.type === 'scroll-to-bottom') {+ scope.pendingReplayScrollAnchorRows = 0+ suspendSurfaceTouchGestures(scope)+ scope.committedTerm?.scrollToBottom()+ if (scope.term !== scope.committedTerm) {+ scope.term?.scrollToBottom()+ }} else if (msg.type === 'clear') {scope.pendingReplayScrollAnchorRows = nullscope.terminalGeneration++diff --git a/mobile/src/terminal/document/terminal-init.ts b/mobile/src/terminal/document/terminal-init.tsindex c2594a17403..a0e721126d5 100644--- a/mobile/src/terminal/document/terminal-init.ts+++ b/mobile/src/terminal/document/terminal-init.ts@@ -197,11 +197,10 @@ export function init(scope.surface!.style.visibility = ''}// Replay lands at bottom; restore only readers who had scrolled upward before reflow.- if (scrollAnchorRows > 0 && scope.term && scope.term.buffer && scope.term.buffer.active) {+ const anchorRows = scope.pendingReplayScrollAnchorRows ?? 0+ if (anchorRows > 0 && scope.term && scope.term.buffer && scope.term.buffer.active) {try {- scope.term.scrollToLine(- Math.max(0, (scope.term.buffer.active.baseY || 0) - scrollAnchorRows)- )+ scope.term.scrollToLine(Math.max(0, (scope.term.buffer.active.baseY || 0) - anchorRows))} catch {}}captureInitialOscLinkTexts(scope)diff --git a/mobile/src/terminal/document/terminal-replay-scroll.test.ts b/mobile/src/terminal/document/terminal-replay-scroll.test.tsindex c987c42261b..bf0d1d583c6 100644--- a/mobile/src/terminal/document/terminal-replay-scroll.test.ts+++ b/mobile/src/terminal/document/terminal-replay-scroll.test.ts@@ -8,6 +8,7 @@ import { terminalDocumentDouble } from './document-terminal-double.test-support'import type { TerminalDocumentTerminal } from './document-terminal-shape'import { handleMsg } from './host-message-router'import { afterWritesDrained } from './write-queue'+import { startEdgeScroll } from './selection-overlay'const scopes: TerminalDocumentScope[] = []@@ -130,6 +131,7 @@ afterEach(() => {stopTerminalDocument(scope)}vi.unstubAllGlobals()+ vi.useRealTimers()})describe('mobile terminal replay reading position', () => {@@ -166,3 +168,46 @@ describe('mobile terminal replay reading position', () => {expect(buffer.viewportY).toBe(buffer.baseY)})})++it('returns to the prompt during a replay and keeps it there when ready', async () => {+ const harness = createReplayHarness()+ harness.replay(false, 80)+ await harness.drain()+ const visible = harness.terminals[0]+ if (!visible) {+ throw new Error('Missing visible terminal')+ }+ visible.scrollToLine(40)+ harness.holdReplays(true)+ harness.replay(true, 81)+ await harness.parse()+ handleMsg(harness.scope, { type: 'scroll-to-bottom' })+ expect(visible.buffer.active.viewportY).toBe(visible.buffer.active.baseY)+ harness.releaseHeldReplays()+ await harness.drain()+ const ready = harness.scope.committedTerm+ expect(ready?.buffer.active.viewportY).toBe(ready?.buffer.active.baseY)+})++it('keeps the prompt visible after interrupting selection edge scrolling', async () => {+ const harness = createReplayHarness()+ harness.replay(false, 80)+ await harness.drain()+ const terminal = harness.terminals[0]+ if (!terminal) {+ throw new Error('Missing terminal')+ }+ terminal.scrollToLine(40)+ vi.useFakeTimers()+ startEdgeScroll(harness.scope, -1)+ vi.advanceTimersByTime(120)+ expect(terminal.buffer.active.viewportY).toBe(38)++ handleMsg(harness.scope, { type: 'scroll-to-bottom' })+ vi.advanceTimersByTime(180)+ expect(terminal.buffer.active.viewportY).toBe(terminal.buffer.active.baseY)++ startEdgeScroll(harness.scope, -1)+ vi.advanceTimersByTime(60)+ expect(terminal.buffer.active.viewportY).toBe(terminal.buffer.active.baseY - 1)+})diff --git a/mobile/src/terminal/terminal-cell-box-refit.test.tsx b/mobile/src/terminal/terminal-cell-box-refit.test.tsxindex 2de281aadf7..10a744cedd6 100644--- a/mobile/src/terminal/terminal-cell-box-refit.test.tsx+++ b/mobile/src/terminal/terminal-cell-box-refit.test.tsx@@ -24,6 +24,7 @@ function refitHarness(cellWidth: number) {cols: Math.floor(frame.width / cellWidth),rows: 47})),+ scrollToBottom: vi.fn(),resetZoom: vi.fn(),cancelSelect: vi.fn(),doSelectAll: vi.fn(),diff --git a/mobile/src/terminal/terminal-foreground-recovery.test.ts b/mobile/src/terminal/terminal-foreground-recovery.test.tsindex df807708aae..155df9fd5f5 100644--- a/mobile/src/terminal/terminal-foreground-recovery.test.ts+++ b/mobile/src/terminal/terminal-foreground-recovery.test.ts@@ -28,6 +28,7 @@ function terminalHandle(): TerminalWebViewHandle {reflow: vi.fn(),clear: vi.fn(),fitDimensions: vi.fn(() => null),+ scrollToBottom: vi.fn(),resetZoom: vi.fn(),cancelSelect: vi.fn(),doSelectAll: vi.fn(),diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.test.tsindex cacd5d1bfd9..d86534c8d76 100644--- a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts+++ b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts@@ -1,3 +1,4 @@+import { terminalInputSend } from './mobile-terminal-operations'import { describe, expect, it, vi } from 'vitest'import { sendTerminalLiveAccessoryRawBytes } from './terminal-live-accessory-raw-send'import type { RpcClient } from '../transport/rpc-client'@@ -16,6 +17,7 @@ function captureClient(}const BASE_ARGS = {+ sendTerminalUserInput: terminalInputSend.request,targetHandle: 'terminal-a',activeHandle: 'terminal-a',activeSessionTabType: 'terminal',diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.tsindex e9bef27d782..5e2b07eea8c 100644--- a/mobile/src/terminal/terminal-live-accessory-raw-send.ts+++ b/mobile/src/terminal/terminal-live-accessory-raw-send.ts@@ -6,6 +6,7 @@ import type { RpcOperationSender } from '../transport/rpc-operation-sender'import type { ConnectionState } from '../transport/types'type TerminalLiveAccessoryRawSendArgs = {+ readonly sendTerminalUserInput: typeof terminalInputSend.requestreadonly client: RpcOperationSender | nullreadonly targetHandle: stringreadonly activeHandle: string | null@@ -27,8 +28,8 @@ export async function sendTerminalLiveAccessoryRawBytes(if (!args.client || !rawSendTarget || args.connState !== 'connected') {return false}- return terminalInputSend- .request(+ return args+ .sendTerminalUserInput(args.client,buildTerminalSendParams({terminal: rawSendTarget,diff --git a/mobile/src/terminal/terminal-live-input-sender.ts b/mobile/src/terminal/terminal-live-input-sender.tsindex c3538d1f723..72d5585045b 100644--- a/mobile/src/terminal/terminal-live-input-sender.ts+++ b/mobile/src/terminal/terminal-live-input-sender.ts@@ -1 +1,5 @@-export type TerminalLiveInputSender = (handle: string, bytes: string) => Promise<boolean>+export type TerminalLiveInputSender = (+ handle: string,+ bytes: string,+ origin?: 'pointer'+) => Promise<boolean>diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.tsindex 8c82f709fbe..3dd6ad093a6 100644--- a/mobile/src/terminal/terminal-webview-contract.ts+++ b/mobile/src/terminal/terminal-webview-contract.ts@@ -118,6 +118,7 @@ export type TerminalWebViewHandle = {// Rewrap local scrollback after PTY width changes; alternate screens use full repaints instead.reflow: (cols: number, rows: number, frame: TerminalFrame | null) => voidclear: () => void+ scrollToBottom: () => voidfitDimensions: (frame: TerminalFrame) => TerminalFitDimensions | nullresetZoom: () => voidcancelSelect: () => voiddiff --git a/mobile/src/terminal/terminal-webview-messages.ts b/mobile/src/terminal/terminal-webview-messages.tsindex 2c6ad6031ee..8b26a0f4176 100644--- a/mobile/src/terminal/terminal-webview-messages.ts+++ b/mobile/src/terminal/terminal-webview-messages.ts@@ -25,6 +25,7 @@ export type TerminalWebViewCommand =| { type: 'resize'; id?: number; cols: number; rows: number; frame: TerminalFrame | null }| { type: 'reflow'; id?: number; cols: number; rows: number; frame: TerminalFrame | null }| { type: 'clear'; id?: number }+ | { type: 'scroll-to-bottom'; id?: number }| { type: 'reset-zoom'; id?: number }| { type: 'cancel-select'; id?: number }| { type: 'do-select-all'; id?: number }diff --git a/mobile/src/terminal/use-terminal-live-input-click.test.ts b/mobile/src/terminal/use-terminal-live-input-click.test.tsindex 3026f5b8c93..9ab6eca0d61 100644--- a/mobile/src/terminal/use-terminal-live-input-click.test.ts+++ b/mobile/src/terminal/use-terminal-live-input-click.test.ts@@ -36,9 +36,9 @@ function createClickHarness(sender?: TerminalLiveInputSender): ClickHarness {}const sent: string[] = []const sendLiveTerminalInputRef: RefObject<TerminalLiveInputSender> = {- current: async (handle, bytes) => {+ current: async (handle, bytes, origin) => {sent.push(bytes)- return sender ? sender(handle, bytes) : true+ return sender ? sender(handle, bytes, origin) : true}}let handlers: Handlers | null = null@@ -150,7 +150,30 @@ describe('terminal live input around a click', () => {release()expect(await clicked).toBe(true)- await vi.waitFor(() => expect(sent).toEqual(['abc', CLICK + 'X']))+ await vi.waitFor(() => expect(sent.join('')).toBe(`abc${CLICK}X`))+ } finally {+ unmount()+ }+ })++ it('retires a queued click and later text when their prefix fails', async () => {+ let fail = (): void => {}+ const { handlers, sent, unmount } = createClickHarness((_handle, bytes) =>+ bytes === 'abc'+ ? new Promise<boolean>((resolve) => {+ fail = () => resolve(false)+ })+ : Promise.resolve(true)+ )+ try {+ change(handlers, 'abc')+ const clicked = handlers.sendLiveInputClick('terminal-a', CLICK)+ change(handlers, 'X')+ fail()+ expect(await clicked).toBe(false)+ expect(sent).toEqual(['abc'])+ change(handlers, 'fresh')+ await vi.waitFor(() => expect(sent).toEqual(['abc', 'fresh']))} finally {unmount()}diff --git a/mobile/src/terminal/use-terminal-live-input-commit.ts b/mobile/src/terminal/use-terminal-live-input-commit.tsindex 8af5e6a86ef..3dec3273ffc 100644--- a/mobile/src/terminal/use-terminal-live-input-commit.ts+++ b/mobile/src/terminal/use-terminal-live-input-commit.ts@@ -168,15 +168,20 @@ export function useTerminalLiveInputCommit<TTabType extends string>({)// Clicks, Return and held-text controls leave the mirror’s assumed field; start a new editing session.- const endFieldSessionThenSend = useCallback(- (handle: string, bytes: string): Promise<boolean> => {+ const endFieldSessionThenSend = useCallback<TerminalLiveInputSender>(+ (handle, bytes, origin) => {advanceLiveInputInteractionGeneration()recordEndedSession(handle)- return endLiveInputSessionThenSend(handle, bytes)+ return endLiveInputSessionThenSend(handle, bytes, origin)},[advanceLiveInputInteractionGeneration, endLiveInputSessionThenSend, recordEndedSession])+ const sendLiveInputClick = useCallback(+ (handle: string, bytes: string) => endFieldSessionThenSend(handle, bytes, 'pointer'),+ [endFieldSessionThenSend]+ )+// Ignore the cleared field’s native echo or it would retype old text at the new cursor.const dropEndedSessionEcho = useCallback((text: string): boolean => {@@ -318,6 +323,6 @@ export function useTerminalLiveInputCommit<TTabType extends string>({handleLiveInputChange,handleLiveInputKeyPress,handleLiveInputSubmit,- sendLiveInputClick: endFieldSessionThenSend+ sendLiveInputClick}}diff --git a/mobile/src/terminal/use-terminal-live-pending-input-flush.ts b/mobile/src/terminal/use-terminal-live-pending-input-flush.tsindex b06f19a5caf..8dea8001077 100644--- a/mobile/src/terminal/use-terminal-live-pending-input-flush.ts+++ b/mobile/src/terminal/use-terminal-live-pending-input-flush.ts@@ -48,12 +48,12 @@ type TerminalLivePendingInputFlush = {composing?: boolean) => Promise<boolean>readonly clearPendingLiveInputCommit: () => void- readonly endLiveInputSessionThenSend: (handle: string, bytes: string) => Promise<boolean>+ readonly endLiveInputSessionThenSend: TerminalLiveInputSenderreadonly flushPendingLiveInputText: (expectedHandle: string | null) => Promise<boolean>readonly heldLiveInputTextRef: RefObject<string>readonly liveInputComposingRef: RefObject<boolean | undefined>readonly pendingLiveInputHandleRef: RefObject<string | null>- readonly queueLiveInputControl: (handle: string, bytes: string) => Promise<boolean>+ readonly queueLiveInputControl: TerminalLiveInputSenderreadonly sentLiveInputTextRef: RefObject<string>readonly waitForPendingLiveInputFlush: () => Promise<boolean>}@@ -121,6 +121,12 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({[sendLiveTerminalInputRef])+ const sendQueuedPointerPayload = useCallback(+ (handle: string, payload: string): Promise<boolean> =>+ sendLiveTerminalInputRef.current(handle, payload, 'pointer'),+ [sendLiveTerminalInputRef]+ )+// A single append this long is an OS paste, or an edit before one; frame it like a paste.const isFramedPasteAppend = useCallback((handle: string, step: TerminalLiveMirrorStep): boolean =>@@ -255,23 +261,23 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({)// Queue at key time; waiting for the drain would let text typed meanwhile go first.- const queueLiveInputControl = useCallback(- (handle: string, bytes: string): Promise<boolean> => {+ const queueLiveInputControl = useCallback<TerminalLiveInputSender>(+ (handle, bytes, origin) => {// Own the queued bytes so a terminal switch retires them even with an empty field.pendingLiveInputHandleRef.current = handlereturn queueTerminalLiveControlSend(pendingLiveInputFlushRef.current,handle,bytes,- sendQueuedMirrorPayload+ origin === 'pointer' ? sendQueuedPointerPayload : sendQueuedMirrorPayload)},- [sendQueuedMirrorPayload]+ [sendQueuedMirrorPayload, sendQueuedPointerPayload])// Queue held text and the control synchronously so the next keystroke follows them.- const endLiveInputSessionThenSend = useCallback(- (handle: string, bytes: string): Promise<boolean> => {+ const endLiveInputSessionThenSend = useCallback<TerminalLiveInputSender>(+ (handle, bytes, origin) => {const pendingHandle = pendingLiveInputHandleRef.currentconst flushState = pendingLiveInputFlushRef.currentif (pendingHandle && pendingHandle !== handle) {@@ -289,7 +295,7 @@ export function useTerminalLivePendingInputFlush<TTabType extends string>({void queueTerminalLiveMirrorSend(flushState, handle, payload, sendQueuedMirrorPayload)}}- const sent = queueLiveInputControl(handle, bytes)+ const sent = queueLiveInputControl(handle, bytes, origin)clearHeldCommitTimer()heldLiveInputTextRef.current = ''liveInputComposingRef.current = undefineddiff --git a/mobile/src/terminal/use-terminal-webview-controller.ts b/mobile/src/terminal/use-terminal-webview-controller.tsindex e82e3fcf16c..03789cdcd86 100644--- a/mobile/src/terminal/use-terminal-webview-controller.ts+++ b/mobile/src/terminal/use-terminal-webview-controller.ts@@ -278,6 +278,10 @@ export function useTerminalWebViewController(postMessage({ type: 'clear' })},fitDimensions,+ scrollToBottom() {+ writeCoalescer.flushNow()+ postMessage({ type: 'scroll-to-bottom' })+ },resetZoom() {postMessage({ type: 'reset-zoom' })},diff --git a/mobile/src/test-support/rpc-recording/adapters/session-terminal-input-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-terminal-input-mount-adapters.tsindex 89eacb69a32..3721e4faff8 100644--- a/mobile/src/test-support/rpc-recording/adapters/session-terminal-input-mount-adapters.ts+++ b/mobile/src/test-support/rpc-recording/adapters/session-terminal-input-mount-adapters.ts@@ -1,3 +1,4 @@+import type * as MobileTerminalOperations from '../../../terminal/mobile-terminal-operations'import { hookScreenMount } from '../mounted-screen-tree'import { mountFixture } from '../recorder-fixture-shape'import type { operationModuleLoader } from '../operation-module-loader'@@ -42,6 +43,9 @@ function mountTerminalClipboard(const useTerminalPaste = modules.load<typeof import('../../../session/use-mobile-terminal-paste')>('mobile/src/session/use-mobile-terminal-paste.ts').useMobileTerminalPaste+ const { terminalInputSend } = modules.load<typeof MobileTerminalOperations>(+ 'mobile/src/terminal/mobile-terminal-operations.ts'+ )const takeover = modules.load<typeof import('../../../terminal/worker-terminal-takeover-report')>('mobile/src/terminal/worker-terminal-takeover-report.ts')@@ -73,6 +77,7 @@ function mountTerminalClipboard(selection = modelpaste = useTerminalPaste(mountFixture<Parameters<typeof useTerminalPaste>[0]>({+ sendTerminalUserInput: terminalInputSend.request,activeHandle: HANDLE,activeHandleRef: { current: HANDLE },activeSessionTabTypeRef: { current: 'terminal' },@@ -146,6 +151,9 @@ function mountTerminalInputSend(const useDrafts = modules.load<typeof import('../../../terminal/use-buffered-terminal-drafts')>('mobile/src/terminal/use-buffered-terminal-drafts.ts').useBufferedTerminalDrafts+ const { terminalInputSend } = modules.load<typeof MobileTerminalOperations>(+ 'mobile/src/terminal/mobile-terminal-operations.ts'+ )const takeover = modules.load<typeof import('../../../terminal/worker-terminal-takeover-report')>('mobile/src/terminal/worker-terminal-takeover-report.ts')@@ -171,6 +179,7 @@ function mountTerminalInputSend(drafts = draftStateactions = useSendActions(mountFixture<Parameters<typeof useSendActions>[0]>({+ sendTerminalUserInput: terminalInputSend.request,client,activeHandle: HANDLE,activeSessionTab,diff --git a/mobile/src/test-support/rpc-recording/adapters/terminal-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/terminal-mount-adapters.tsindex 3e621c6f4cd..3f3eb7f48f0 100644--- a/mobile/src/test-support/rpc-recording/adapters/terminal-mount-adapters.ts+++ b/mobile/src/test-support/rpc-recording/adapters/terminal-mount-adapters.ts@@ -1,3 +1,4 @@+import type * as MobileTerminalOperations from '../../../terminal/mobile-terminal-operations'import type { MountAdapter, MountContext } from '../recording-scenario'import { hookMount } from '../hook-mount'import type { operationModuleLoader } from '../operation-module-loader'@@ -52,6 +53,9 @@ export function terminalMountAdapters(}},'terminal.accessory-raw-send': ({ client }) => {+ const { terminalInputSend } = modules.load<typeof MobileTerminalOperations>(+ 'mobile/src/terminal/mobile-terminal-operations.ts'+ )const send = modules.load<typeof import('../../../terminal/terminal-live-accessory-raw-send')>('mobile/src/terminal/terminal-live-accessory-raw-send.ts').sendTerminalLiveAccessoryRawBytes@@ -60,6 +64,7 @@ export function terminalMountAdapters(action: (_name, args) =>send({client,+ sendTerminalUserInput: terminalInputSend.request,targetHandle: HANDLE,activeHandle: args.activeHandle === null ? null : String(args.activeHandle ?? HANDLE),activeSessionTabType: String(args.tabType ?? 'terminal'),