Skip to content

armgit / orca

Public Imported from GitHub
0

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.

fix(mobile): keep shortcut swipes from sending keys (#36116)

Kelvin Amoaba960332fc7207
diff --git a/config/scripts/mobile-web-app/mobile-web-app-held-press-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-held-press-render.test.mjs
index 05cc3d39132..64960718451 100644
--- a/config/scripts/mobile-web-app/mobile-web-app-held-press-render.test.mjs
+++ b/config/scripts/mobile-web-app/mobile-web-app-held-press-render.test.mjs
@@ -72,7 +72,8 @@ beforeAll(async () => {
join(routeDir, 'command-dock-probe.tsx'),
commandDockProbeRouteSource({
commandDockModule: join(sessionDir, 'MobileSessionCommandDock'),
- keyDefinitionsModule: join(terminalDir, 'terminal-key-definitions')
+ keyDefinitionsModule: join(terminalDir, 'terminal-key-definitions'),
+ accessorySelectionModule: join(sessionDir, 'use-mobile-session-accessory-selection')
})
)
await writeFile(
@@ -136,6 +137,7 @@ async function openProbe(pathname) {
async function holdLikeAndroidWebView(page, selector, { holdMs, read }) {
// A handle, not a locator: a label the selector matches can change as soon as the press lands.
const target = await page.waitForSelector(selector)
+ await target.scrollIntoViewIfNeeded()
const box = await target.boundingBox()
const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
const input = await page.context().newCDPSession(page)
@@ -172,6 +174,29 @@ async function holdLikeAndroidWebView(page, selector, { holdMs, read }) {
return { midHold, afterRelease: await read(target) }
}
+async function beginRepeatKeyTouch(page) {
+ const key = await page.waitForSelector(`[aria-label="${REPEAT_KEY_LABEL}"]`)
+ await key.scrollIntoViewIfNeeded()
+ const box = await key.boundingBox()
+ const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
+ const input = await page.context().newCDPSession(page)
+ await input.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] })
+ return { input, key, point }
+}
+
+const keyScrollOffset = (key) =>
+ key.evaluate((node) => {
+ for (let parent = node.parentElement; parent; parent = parent.parentElement) {
+ if (
+ parent.scrollWidth > parent.clientWidth &&
+ getComputedStyle(parent).overflowX !== 'visible'
+ ) {
+ return parent.scrollLeft
+ }
+ }
+ throw new Error('Key bar does not overflow')
+ })
+
const pressOuts = (page) => page.evaluate(() => globalThis.__orcaHeldPressProbe.pressOuts())
describeRender(
@@ -227,7 +252,7 @@ describeRender(
})
describe('the key bar', () => {
- it('starts repeat on press and stops it only when the finger lifts', async () => {
+ it('repeats a held key without an extra send when the finger lifts', async () => {
const { errors, page } = await openProbe(ROUTES.keys)
const { midHold, afterRelease } = await holdLikeAndroidWebView(
page,
@@ -235,20 +260,144 @@ describeRender(
{
holdMs: 1500,
read: () =>
- page.evaluate(() => ({ repeats: globalThis.__orcaHeldPressProbe.repeats() }))
+ page.evaluate(() => ({
+ repeats: globalThis.__orcaHeldPressProbe.repeats(),
+ sent: globalThis.__orcaHeldPressProbe.sent()
+ }))
}
)
- // The repeat controller owns the first send, so the press must not send on its own.
expect(midHold).toEqual({
selectable: false,
- repeats: [{ kind: 'start', bytes: '\x1b[A' }]
+ repeats: [{ kind: 'start', bytes: '\x1b[A' }],
+ sent: expect.arrayContaining(['\x1b[A'])
})
- expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
+ expect(midHold.sent.length).toBeGreaterThan(1)
+ expect(afterRelease.sent).toEqual(midHold.sent)
expect(afterRelease.repeats).toEqual([{ kind: 'start', bytes: '\x1b[A' }, { kind: 'stop' }])
expect(errors).toEqual([])
await page.close()
}, 300_000)
+ it('sends a repeatable tap once on release without waiting for the hold delay', async () => {
+ const { errors, page } = await openProbe(ROUTES.keys)
+ const { input } = await beginRepeatKeyTouch(page)
+ await page.clock.runFor(100)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
+ await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
+ await page.clock.runFor(1)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([
+ '\x1b[A'
+ ])
+ await page.clock.runFor(1000)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([
+ '\x1b[A'
+ ])
+ expect(errors).toEqual([])
+ await page.close()
+ }, 300_000)
+
+ it('does not repeat after movement cancels long-press recognition', async () => {
+ const { errors, page } = await openProbe(ROUTES.keys)
+ const { input, point } = await beginRepeatKeyTouch(page)
+ await page.clock.runFor(100)
+ await input.send('Input.dispatchTouchEvent', {
+ type: 'touchMove',
+ touchPoints: [{ ...point, y: point.y + 20 }]
+ })
+ await page.clock.runFor(1000)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
+ await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
+ await page.clock.runFor(1000)
+ expect(
+ await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent().length)
+ ).toBeLessThanOrEqual(1)
+ expect(errors).toEqual([])
+ await page.close()
+ }, 300_000)
+
+ it('drops a prepared tap after switching terminals and accepts a new accessibility click', async () => {
+ const { errors, page } = await openProbe(ROUTES.keys)
+ const { input, key } = await beginRepeatKeyTouch(page)
+ await page.clock.runFor(100)
+ await page.evaluate(() => globalThis.__orcaHeldPressProbe.switchTerminal())
+ await page.waitForFunction(
+ () => globalThis.__orcaHeldPressProbe.activeHandle === 'other-terminal'
+ )
+ await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
+ await page.clock.runFor(1000)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
+ await key.evaluate((node) => node.click())
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual([
+ { bytes: '\x1b[A', target: 'other-terminal' }
+ ])
+ expect(errors).toEqual([])
+ await page.close()
+ }, 300_000)
+
+ it.each([
+ [100, false],
+ [700, false],
+ [700, true]
+ ])(
+ 'keeps Enter activation bound to keydown terminal with hold=%sms and switch=%s',
+ async (holdMs, switchTerminal) => {
+ const { errors, page } = await openProbe(ROUTES.keys)
+ const key = await page.waitForSelector(`[aria-label="${REPEAT_KEY_LABEL}"]`)
+ await key.focus()
+ await page.keyboard.down('Enter')
+ await page.clock.runFor(100)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual([
+ { bytes: '\x1b[A', target: 'held-press-terminal' }
+ ])
+ if (switchTerminal) {
+ await page.evaluate(() => globalThis.__orcaHeldPressProbe.switchTerminal())
+ await page.waitForFunction(
+ () => globalThis.__orcaHeldPressProbe.activeHandle === 'other-terminal'
+ )
+ }
+ await page.clock.runFor(holdMs - 100)
+ const beforeRelease = await page.evaluate(() =>
+ globalThis.__orcaHeldPressProbe.deliveries()
+ )
+ if (holdMs === 100 || switchTerminal) {
+ expect(beforeRelease).toHaveLength(1)
+ } else {
+ expect(beforeRelease.length).toBeGreaterThan(1)
+ }
+ expect(beforeRelease).toEqual(
+ beforeRelease.map(() => ({ bytes: '\x1b[A', target: 'held-press-terminal' }))
+ )
+ await page.keyboard.up('Enter')
+ await page.clock.runFor(1000)
+ expect(errors).toEqual([])
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.deliveries())).toEqual(
+ beforeRelease
+ )
+ await page.close()
+ },
+ 300_000
+ )
+
+ it('scrolls across a repeatable key without sending it', async () => {
+ const { errors, page } = await openProbe(ROUTES.keys)
+ const { input, key, point } = await beginRepeatKeyTouch(page)
+ const before = await keyScrollOffset(key)
+ await page.clock.runFor(70)
+ for (let step = 1; step <= 8; step += 1) {
+ await input.send('Input.dispatchTouchEvent', {
+ type: 'touchMove',
+ touchPoints: [{ ...point, x: point.x - step * 20 }]
+ })
+ await page.clock.runFor(20)
+ }
+ await input.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] })
+ await page.clock.runFor(1000)
+ expect(await keyScrollOffset(key)).toBeGreaterThan(before)
+ expect(await page.evaluate(() => globalThis.__orcaHeldPressProbe.sent())).toEqual([])
+ expect(errors).toEqual([])
+ await page.close()
+ }, 300_000)
+
it('selects nothing on a long-press of a tap key', async () => {
const { errors, page } = await openProbe(ROUTES.keys)
const { midHold } = await holdLikeAndroidWebView(page, `[aria-label="${TAP_KEY_LABEL}"]`, {
diff --git a/config/scripts/mobile-web-app/preview/mobile-web-app-held-press-probe-routes.mjs b/config/scripts/mobile-web-app/preview/mobile-web-app-held-press-probe-routes.mjs
index dc198f698d0..ea738595942 100644
--- a/config/scripts/mobile-web-app/preview/mobile-web-app-held-press-probe-routes.mjs
+++ b/config/scripts/mobile-web-app/preview/mobile-web-app-held-press-probe-routes.mjs
@@ -66,32 +66,63 @@ export default function HoldDictationProbeRoute() {
export const REPEAT_KEY_LABEL = 'Arrow Up'
export const TAP_KEY_LABEL = 'Escape'
-export function commandDockProbeRouteSource({ commandDockModule, keyDefinitionsModule }) {
- return `import { useRef } from 'react'
+export function commandDockProbeRouteSource({
+ commandDockModule,
+ keyDefinitionsModule,
+ accessorySelectionModule
+}) {
+ return `import { useLayoutEffect, useRef, useState } from 'react'
import { MobileSessionCommandDock } from ${JSON.stringify(commandDockModule)}
import { TERMINAL_ACCESSORY_KEY_DEFINITIONS } from ${JSON.stringify(keyDefinitionsModule)}
+import { useMobileSessionAccessorySelection } from ${JSON.stringify(accessorySelectionModule)}
const noop = () => {}
-const KEYS = TERMINAL_ACCESSORY_KEY_DEFINITIONS.filter((key) => ['arrowUp', 'escape'].includes(key.id))
+const KEYS = TERMINAL_ACCESSORY_KEY_DEFINITIONS
const IDLE = { isStarting: false, isRecording: false, isProcessing: false }
export default function CommandDockProbeRoute() {
const sentRef = useRef([])
+ const deliveriesRef = useRef([])
const repeatRef = useRef([])
- const send = (input) => {
+ const [activeHandle, setActiveHandle] = useState('held-press-terminal')
+ const activeHandleRef = useRef(activeHandle)
+ const clientRef = useRef({
+ getGeneration: () => 1,
+ sendRequest: () => Promise.resolve({ id: 'settings', ok: false, error: { code: 'unavailable' } })
+ })
+ const connStateRef = useRef('connected')
+ const activeSessionTabTypeRef = useRef('terminal')
+ useLayoutEffect(() => { activeHandleRef.current = activeHandle }, [activeHandle])
+ const send = (input, target = activeHandleRef.current, isCurrent = () => true) => {
+ if (!isCurrent()) return Promise.resolve(false)
sentRef.current.push(input.bytes)
- return Promise.resolve()
+ deliveriesRef.current.push({ bytes: input.bytes, target })
+ return Promise.resolve(true)
}
+ const accessory = useMobileSessionAccessorySelection({
+ client: clientRef.current,
+ clientRef,
+ connState: 'connected',
+ connStateRef,
+ activeHandle,
+ activeHandleRef,
+ activeSessionTabTypeRef,
+ worktreeId: 'held-press-workspace',
+ handleAccessoryKey: send
+ })
globalThis.__orcaHeldPressProbe = {
sent: () => [...sentRef.current],
- repeats: () => [...repeatRef.current]
+ deliveries: () => [...deliveriesRef.current],
+ repeats: () => [...repeatRef.current],
+ activeHandle,
+ switchTerminal: () => setActiveHandle('other-terminal')
}
const controller = {
insets: { top: 0, bottom: 0, left: 0, right: 0 },
bufferedTerminalDraftState: { input: '', setInput: noop },
autocompleteEnabled: false,
liveInputCapture: '',
- activeHandle: 'held-press-terminal',
+ activeHandle,
customKeys: [],
setShowCustomKeyModal: noop,
setDeleteKeyTarget: noop,
@@ -118,8 +149,21 @@ export default function CommandDockProbeRoute() {
handleAccessoryKey: send,
dismissSoftwareKeyboard: noop,
toggleLiveInput: noop,
- stopAccessoryRepeat: () => repeatRef.current.push({ kind: 'stop' }),
- startAccessoryRepeat: (input) => repeatRef.current.push({ kind: 'start', bytes: input.bytes }),
+ stopAccessoryRepeat: () => {
+ repeatRef.current.push({ kind: 'stop' })
+ accessory.stopAccessoryRepeat()
+ },
+ cancelAccessoryRepeat: accessory.cancelAccessoryRepeat,
+ prepareAccessoryPress: (input) => {
+ const press = accessory.prepareAccessoryPress(input)
+ return {
+ tap: press.tap,
+ hold: (firstRepeatDelayMs) => {
+ repeatRef.current.push({ kind: 'start', bytes: input.bytes })
+ press.hold(firstRepeatDelayMs)
+ }
+ }
+ },
handlePaste: () => Promise.resolve(),
isAttaching: false,
attachImage: () => Promise.resolve(),
diff --git a/mobile/src/session/MobileSessionAccessoryKeys.tsx b/mobile/src/session/MobileSessionAccessoryKeys.tsx
index f451dbe5c47..fa131747720 100644
--- a/mobile/src/session/MobileSessionAccessoryKeys.tsx
+++ b/mobile/src/session/MobileSessionAccessoryKeys.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from 'react'
+import { useEffect, useRef } from 'react'
import { View, Text, ScrollView, Pressable } from 'react-native'
import {
ChevronDown,
@@ -10,7 +10,7 @@ import {
} from 'lucide-react-native'
import { triggerMediumImpact } from '../platform/haptics'
import { createTerminalLiveAccessoryInput } from '../terminal/terminal-live-accessory-input'
-import { keepHeldPressThroughLongPress } from './held-press-long-press'
+import { TERMINAL_ACCESSORY_REPEAT_DELAY_MS } from '../terminal/terminal-accessory-repeat'
import { isTerminalPhoneDisplayMode } from './mobile-session-route-helpers'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
@@ -45,13 +45,15 @@ export function MobileSessionAccessoryKeys({
dismissSoftwareKeyboard,
toggleLiveInput,
stopAccessoryRepeat,
- startAccessoryRepeat,
+ cancelAccessoryRepeat,
+ prepareAccessoryPress,
handlePaste,
keyboardLift
} = controller
+ const accessoryPresses = useRef(new Map<string, ReturnType<typeof prepareAccessoryPress>>())
const keepsKeyboard = useKeyboardPersistingTaps('always')
// An unmounting Pressable never fires onPressOut, so a held key would outlive its strip.
- useEffect(() => stopAccessoryRepeat, [stopAccessoryRepeat])
+ useEffect(() => cancelAccessoryRepeat, [cancelAccessoryRepeat])
return (
<View ref={keepsKeyboard} style={vertical ? styles.accessoryRail : styles.accessoryBar}>
{/* Why: fixed keyboard escape hatch; outside ScrollView + shortcut path so it can't scroll away or be hidden (#5106). */}
@@ -89,6 +91,7 @@ export function MobileSessionAccessoryKeys({
showsVerticalScrollIndicator={false}
contentContainerStyle={vertical ? styles.accessoryContentVertical : styles.accessoryContent}
keyboardShouldPersistTaps="always"
+ onScrollBeginDrag={cancelAccessoryRepeat}
>
<Pressable
style={({ pressed }) => [
@@ -175,24 +178,41 @@ export function MobileSessionAccessoryKeys({
!canSend && styles.accessoryKeyDisabled
]}
disabled={!canSend}
- onPressIn={() => {
+ onPressIn={(event) => {
if (!key.repeatable) {
return
}
- startAccessoryRepeat(createTerminalLiveAccessoryInput(key))
+ const press = prepareAccessoryPress(createTerminalLiveAccessoryInput(key))
+ accessoryPresses.current.set(key.id, press)
+ if (event.type === 'keydown') {
+ press.hold(TERMINAL_ACCESSORY_REPEAT_DELAY_MS)
+ }
}}
onPressOut={() => {
if (key.repeatable) {
stopAccessoryRepeat()
}
}}
- onPress={() => {
+ onPress={(event) => {
if (key.repeatable) {
+ // Accessibility clicks have no touch-down to prepare a sender.
+ const accessibilityClick =
+ event.type === 'click' &&
+ 'detail' in event.nativeEvent &&
+ event.nativeEvent.detail === 0
+ const press =
+ (!accessibilityClick && accessoryPresses.current.get(key.id)) ||
+ prepareAccessoryPress(createTerminalLiveAccessoryInput(key))
+ accessoryPresses.current.delete(key.id)
+ void press.tap()
return
}
void handleAccessoryKey(createTerminalLiveAccessoryInput(key))
}}
- onLongPress={key.repeatable ? keepHeldPressThroughLongPress : undefined}
+ onLongPress={
+ key.repeatable ? () => accessoryPresses.current.get(key.id)?.hold() : undefined
+ }
+ delayLongPress={TERMINAL_ACCESSORY_REPEAT_DELAY_MS}
accessibilityLabel={
key.accessibilityLabel ??
t('session.accessoryKeys.sendKey', 'Send {{label}}', { label: key.label })
diff --git a/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx b/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx
index 64f540e8cf9..3e2cb542325 100644
--- a/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx
+++ b/mobile/src/session/mobile-session-accessory-repeat-lifecycle.test.tsx
@@ -161,7 +161,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
'unmount'
] as const)('retires a hold across %s and does not restart it on return', async (cutover) => {
const view = await mount()
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(445)
expect(view.writes().length).toBeGreaterThan(0)
view.client.sendRequest.mockClear()
@@ -210,7 +210,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
finishPreflight = resolve
})
)
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
if (cutover === 'terminal') {
await view.update({ handle: 'b' })
await view.update({ handle: 'a' })
@@ -229,15 +229,54 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
}
)
+ it.each(['terminal', 'background'] as const)(
+ 'retires a prepared tap and hold after %s returns to the same owner',
+ async (cutover) => {
+ const view = await mount()
+ const press = view.current().prepareAccessoryPress(input)
+ if (cutover === 'terminal') {
+ await view.update({ handle: 'b' })
+ await view.update({ handle: 'a' })
+ } else {
+ act(() => lifecycle.listeners.forEach((listener) => listener('background')))
+ act(() => lifecycle.listeners.forEach((listener) => listener('active')))
+ }
+
+ await expect(press.tap()).resolves.toBe(false)
+ act(() => press.hold())
+ await view.advance(500)
+ expect(view.writes()).toHaveLength(0)
+ }
+ )
+
+ it('dispatches distinct taps while earlier host acknowledgments are pending', async () => {
+ const view = await mount()
+ const replies: ((reply: RpcResponse) => void)[] = []
+ view.client.sendRequest.mockImplementation(
+ () => new Promise<RpcResponse>((resolve) => replies.push(resolve))
+ )
+ const taps: Promise<boolean>[] = []
+ await act(async () => {
+ for (let index = 0; index < 5; index += 1) {
+ taps.push(view.current().prepareAccessoryPress(input).tap())
+ }
+ })
+ expect(view.writes()).toHaveLength(5)
+ replies.forEach((reply) => reply(accepted))
+ await expect(Promise.all(taps)).resolves.toEqual([true, true, true, true, true])
+ await view.advance(1000)
+ expect(view.writes()).toHaveLength(5)
+ })
+
it.each([
- ['handled', 3],
+ ['handled', 10],
['suppress-raw', 1]
] as const)(
'follows the live editor’s %s result when repeating a local edit',
async (kind, expectedEdits) => {
const view = await mount()
view.preflight.mockResolvedValue({ kind })
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(445)
expect(view.preflight).toHaveBeenCalledTimes(expectedEdits)
expect(view.writes()).toHaveLength(0)
@@ -246,7 +285,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
it('repeats through the latest live editor when live input turns on mid-hold', async () => {
const view = await mount()
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(445)
expect(view.writes().length).toBeGreaterThan(0)
const liveEditor = vi.fn<() => Promise<TerminalLiveAccessoryInputCommitResult>>(async () => ({
@@ -268,7 +307,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
answerSend = resolve
})
)
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(1000)
expect(view.writes()).toHaveLength(1)
act(() => view.current().stopAccessoryRepeat())
@@ -283,7 +322,7 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
finishPreflight = resolve
})
)
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.update({ handle: 'b' })
await act(async () => finishPreflight({ kind: 'allow-raw' }))
expect(view.writes()).toHaveLength(0)
@@ -302,13 +341,13 @@ describe('mounted accessory-repeat delivery lifecycle', () => {
} else {
view.client.sendRequest.mockRejectedValue(new Error('Disconnected'))
}
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(1000)
expect(view.writes()).toHaveLength(1)
view.client.sendRequest.mockResolvedValue(accepted)
await view.advance(1000)
expect(view.writes()).toHaveLength(1)
- act(() => view.current().startAccessoryRepeat(input))
+ act(() => view.current().prepareAccessoryPress(input).hold())
await view.advance(445)
expect(view.writes().length).toBeGreaterThan(2)
expect(
diff --git a/mobile/src/session/use-mobile-session-accessory-selection.ts b/mobile/src/session/use-mobile-session-accessory-selection.ts
index ab3704015ee..353a188291f 100644
--- a/mobile/src/session/use-mobile-session-accessory-selection.ts
+++ b/mobile/src/session/use-mobile-session-accessory-selection.ts
@@ -92,7 +92,7 @@ export function useMobileSessionAccessorySelection(scope: MobileSessionTerminalI
() => cancelAccessoryRepeat,
[activeHandle, client, connState, worktreeId, cancelAccessoryRepeat]
)
- const startAccessoryRepeat = useCallback(
+ const prepareAccessoryPress = useCallback(
(input: ReturnType<typeof createTerminalLiveAccessoryInput>) => {
const pressedClient = clientRef.current
const pressedGeneration = pressedClient?.getGeneration?.() ?? 0
@@ -112,7 +112,14 @@ export function useMobileSessionAccessorySelection(scope: MobileSessionTerminalI
activeSessionTabTypeRef.current === 'terminal',
(...args) => handleAccessoryKeyRef.current(...args)
)
- accessoryRepeat.start(input, sender)
+ let holdStarted = false
+ return {
+ tap: () => (holdStarted ? Promise.resolve(false) : sender(input)),
+ hold: (firstRepeatDelayMs?: number) => {
+ holdStarted = true
+ accessoryRepeat.start(input, sender, firstRepeatDelayMs)
+ }
+ }
},
[accessoryRepeat]
)
@@ -264,7 +271,8 @@ export function useMobileSessionAccessorySelection(scope: MobileSessionTerminalI
}, [clipboardContents, setCanPaste])
return {
stopAccessoryRepeat,
- startAccessoryRepeat,
+ cancelAccessoryRepeat,
+ prepareAccessoryPress,
setMobileSessionRootRef,
handleSelectionMode,
handleSelectionCopy,
diff --git a/mobile/src/terminal/terminal-accessory-repeat.test.ts b/mobile/src/terminal/terminal-accessory-repeat.test.ts
index eab103eac15..f4437c38e9f 100644
--- a/mobile/src/terminal/terminal-accessory-repeat.test.ts
+++ b/mobile/src/terminal/terminal-accessory-repeat.test.ts
@@ -17,34 +17,42 @@ function deferred() {
describe('terminal accessory repeat', () => {
afterEach(() => vi.useRealTimers())
- it('keeps one send in flight and preserves repeat order under host latency', async () => {
- vi.useFakeTimers()
- const first = deferred()
- const second = deferred()
- const sent: string[] = []
- const send = vi.fn((input: string) => {
- sent.push(input)
- return (sent.length === 1 ? first.promise : second.promise).then(() => true)
- })
- const repeat = createTerminalAccessoryRepeatController<string>()
-
- repeat.start('down', send)
- expect(sent).toEqual(['down'])
-
- await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_DELAY_MS + 500)
- expect(sent).toEqual(['down'])
-
- first.resolve()
- await vi.advanceTimersByTimeAsync(0)
- expect(sent).toEqual(['down', 'down'])
-
- await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS + 500)
- expect(sent).toEqual(['down', 'down'])
-
- second.resolve()
- await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS)
- expect(sent).toEqual(['down', 'down', 'down'])
- })
+ it.each([
+ ['recognized hold', undefined],
+ ['keyboard hold', TERMINAL_ACCESSORY_REPEAT_DELAY_MS]
+ ] as const)(
+ 'keeps one send in flight for a %s under host latency',
+ async (_, firstRepeatDelayMs) => {
+ vi.useFakeTimers()
+ const first = deferred()
+ const second = deferred()
+ const sent: string[] = []
+ const send = vi.fn((input: string) => {
+ sent.push(input)
+ return (sent.length === 1 ? first.promise : second.promise).then(() => true)
+ })
+ const repeat = createTerminalAccessoryRepeatController<string>()
+
+ repeat.start('down', send, firstRepeatDelayMs)
+ expect(sent).toEqual(['down'])
+
+ await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_DELAY_MS + 500)
+ expect(sent).toEqual(['down'])
+
+ first.resolve()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(sent).toEqual(firstRepeatDelayMs === undefined ? ['down'] : ['down', 'down'])
+ await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS)
+ expect(sent).toEqual(['down', 'down'])
+
+ await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS + 500)
+ expect(sent).toEqual(['down', 'down'])
+
+ second.resolve()
+ await vi.advanceTimersByTimeAsync(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS)
+ expect(sent).toEqual(['down', 'down', 'down'])
+ }
+ )
it('does not schedule another repeat after release while a send is pending', async () => {
vi.useFakeTimers()
@@ -60,7 +68,7 @@ describe('terminal accessory repeat', () => {
expect(send).toHaveBeenCalledTimes(1)
})
- it('dispatches distinct taps without waiting for prior acknowledgements', async () => {
+ it('starts distinct holds without waiting for prior acknowledgements', async () => {
vi.useFakeTimers()
const pending = Array.from({ length: 5 }, () => deferred())
const sent: string[] = []
@@ -71,18 +79,18 @@ describe('terminal accessory repeat', () => {
const repeat = createTerminalAccessoryRepeatController<string>()
for (let index = 0; index < pending.length; index += 1) {
- repeat.start(`tap-${index}`, send)
+ repeat.start(`hold-${index}`, send)
repeat.stop()
}
- expect(sent).toEqual(['tap-0', 'tap-1', 'tap-2', 'tap-3', 'tap-4'])
+ expect(sent).toEqual(['hold-0', 'hold-1', 'hold-2', 'hold-3', 'hold-4'])
pending.forEach(({ resolve }) => resolve())
await vi.runAllTimersAsync()
expect(send).toHaveBeenCalledTimes(5)
})
- it('cancels repeats without dropping a distinct tap already dispatched by the user', async () => {
+ it('does not drop an in-flight send when a new hold is canceled', async () => {
vi.useFakeTimers()
const first = deferred()
const sent: string[] = []
diff --git a/mobile/src/terminal/terminal-accessory-repeat.ts b/mobile/src/terminal/terminal-accessory-repeat.ts
index 2b354b42d59..401816f5f67 100644
--- a/mobile/src/terminal/terminal-accessory-repeat.ts
+++ b/mobile/src/terminal/terminal-accessory-repeat.ts
@@ -35,41 +35,40 @@ export function createTerminalAccessoryRepeatController<TInput>() {
const cancel = stop
- const start = (input: TInput, send: TerminalAccessoryRepeatSender<TInput>) => {
+ const start = (
+ input: TInput,
+ send: TerminalAccessoryRepeatSender<TInput>,
+ firstRepeatDelayMs?: number
+ ) => {
stop()
const activeGeneration = generation
- const pressedAt = Date.now()
+ const startedAt = Date.now()
+ let nextRepeatDelayMs = firstRepeatDelayMs
- const schedule = (delayMs: number) => {
- timer = setTimeout(() => {
- timer = null
- if (generation !== activeGeneration) {
- return
- }
- void send(input).then(
- (sent) => {
- if (sent && generation === activeGeneration) {
- schedule(TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS)
- }
- },
- () => undefined
- )
- }, delayMs)
+ const sendNext = () => {
+ timer = null
+ if (generation !== activeGeneration) {
+ return
+ }
+ void send(input).then(
+ (sent) => {
+ if (sent && generation === activeGeneration) {
+ const delayMs =
+ nextRepeatDelayMs === undefined
+ ? TERMINAL_ACCESSORY_REPEAT_INTERVAL_MS
+ : Math.min(
+ nextRepeatDelayMs,
+ Math.max(0, nextRepeatDelayMs - (Date.now() - startedAt))
+ )
+ nextRepeatDelayMs = undefined
+ timer = setTimeout(sendNext, delayMs)
+ }
+ },
+ () => undefined
+ )
}
- void send(input).then(
- (sent) => {
- if (sent && generation === activeGeneration) {
- schedule(
- Math.min(
- TERMINAL_ACCESSORY_REPEAT_DELAY_MS,
- Math.max(0, TERMINAL_ACCESSORY_REPEAT_DELAY_MS - (Date.now() - pressedAt))
- )
- )
- }
- },
- () => undefined
- )
+ sendNext()
}
return { cancel, start, stop }