From 2c6f710b561d93a8d295847a1dc6e1ebe838a2c2 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 28 Apr 2026 23:56:07 -0400 Subject: [PATCH] checkpoint mobile terminal streaming work Co-authored-by: Orca --- mobile/README.md | 12 + mobile/app/h/[hostId]/index.tsx | 9 +- .../app/h/[hostId]/session/[worktreeId].tsx | 304 +++++--- mobile/app/index.tsx | 4 +- mobile/scripts/repro-terminal-colors.ts | 341 +++++++++ mobile/src/components/NewWorktreeModal.tsx | 655 ++++++++++++++++++ mobile/src/platform/haptics.ts | 7 + mobile/src/terminal/TerminalWebView.tsx | 319 +++++---- mobile/src/transport/e2ee.ts | 38 +- mobile/src/transport/rpc-client.ts | 9 +- src/main/daemon/headless-emulator.ts | 8 +- src/main/ipc/pty.ts | 19 +- src/main/runtime/orca-runtime.test.ts | 90 +++ src/main/runtime/orca-runtime.ts | 119 +++- .../window/attach-main-window-services.ts | 16 +- src/preload/api-types.ts | 8 +- src/preload/index.ts | 2 + .../terminal-pane/pty-buffer-serializer.ts | 12 +- .../terminal-pane/pty-connection.test.ts | 3 +- .../terminal-pane/pty-connection.ts | 12 +- .../components/terminal-pane/replay-guard.ts | 23 + src/renderer/src/hooks/useIpcEvents.test.ts | 12 + src/renderer/src/hooks/useIpcEvents.ts | 2 +- src/shared/types.ts | 5 + 24 files changed, 1745 insertions(+), 284 deletions(-) create mode 100644 mobile/scripts/repro-terminal-colors.ts create mode 100644 mobile/src/components/NewWorktreeModal.tsx create mode 100644 mobile/src/platform/haptics.ts diff --git a/mobile/README.md b/mobile/README.md index 48d40d685..ab4e85833 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -114,6 +114,18 @@ readSawMarker: true If this repro fails, debug the desktop runtime/PTY path before the mobile WebView. If it passes but the phone is blank, debug the session screen or `TerminalWebView` readiness/queueing path. +## Terminal Color Repro Without A Phone + +Use this when terminal colors disappear after switching tabs. Open a Claude Code terminal and at least one other terminal in the target worktree, then run: + +```bash +cd mobile +ORCA_MOBILE_WS_URL=ws://127.0.0.1:6768 pnpm exec tsx scripts/repro-terminal-colors.ts \ + "id:" +``` + +The script captures `terminal.subscribe` snapshots in an A → B → A sequence and writes raw snapshots to `mobile/terminal-color-repro/`. If the two A snapshots have different `sgrColor` counts, the desktop snapshot changed during the switch. If they match, the ANSI color data is still present and the bug is in mobile replay/rendering. + ## Validation Run these checks before committing mobile terminal changes: diff --git a/mobile/app/h/[hostId]/index.tsx b/mobile/app/h/[hostId]/index.tsx index 43e25e4ff..ddd229281 100644 --- a/mobile/app/h/[hostId]/index.tsx +++ b/mobile/app/h/[hostId]/index.tsx @@ -10,7 +10,6 @@ import { } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { useLocalSearchParams, useRouter } from 'expo-router' -import * as Haptics from 'expo-haptics' import { Search, X, @@ -28,6 +27,7 @@ import { import { connect, type RpcClient } from '../../../src/transport/rpc-client' import { loadHosts, updateLastConnected, removeHost } from '../../../src/transport/host-store' import type { ConnectionState, RpcSuccess } from '../../../src/transport/types' +import { triggerMediumImpact } from '../../../src/platform/haptics' import { StatusDot } from '../../../src/components/StatusDot' import { NewWorktreeModal } from '../../../src/components/NewWorktreeModal' import { AgentSpinner } from '../../../src/components/AgentSpinner' @@ -606,7 +606,7 @@ export default function HostScreen() { disabled={isReadOnly} onPress={() => openWorktreeSession(item)} onLongPress={() => { - void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium) + triggerMediumImpact() setActionTarget(item) }} delayLongPress={400} @@ -763,10 +763,9 @@ export default function HostScreen() { { + onCreated={(worktreeId, worktreeName) => { void fetchWorktrees() - const params = new URLSearchParams({ name: worktreeName }) - if (agentCommand) params.set('agent', agentCommand) + const params = new URLSearchParams({ name: worktreeName, created: '1' }) router.push(`/h/${hostId}/session/${encodeURIComponent(worktreeId)}?${params.toString()}`) }} onClose={() => setShowNewWorktree(false)} diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index 664dc4985..f36274c54 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -12,11 +12,11 @@ import { } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { useLocalSearchParams, useRouter } from 'expo-router' -import * as Haptics from 'expo-haptics' import { ArrowUp, ChevronLeft, Monitor, Plus, Smartphone } from 'lucide-react-native' import { connect, type RpcClient } from '../../../../src/transport/rpc-client' import { loadHosts } from '../../../../src/transport/host-store' import type { ConnectionState, RpcSuccess } from '../../../../src/transport/types' +import { triggerMediumImpact } from '../../../../src/platform/haptics' import { TerminalWebView, type TerminalWebViewHandle @@ -66,17 +66,43 @@ const STATUS_LABELS: Record = { 'auth-failed': 'Auth failed' } +function TerminalPaneView({ + handle, + active, + onRef +}: { + handle: string + active: boolean + onRef: (handle: string, ref: TerminalWebViewHandle | null) => void +}) { + const setRef = useCallback( + (ref: TerminalWebViewHandle | null) => { + onRef(handle, ref) + }, + [handle, onRef] + ) + + return ( + + + + ) +} + export default function SessionScreen() { const { hostId, worktreeId, name: worktreeName, - agent: agentCommand + created } = useLocalSearchParams<{ hostId: string worktreeId: string name?: string - agent?: string + created?: string }>() const router = useRouter() const [client, setClient] = useState(null) @@ -115,21 +141,39 @@ export default function SessionScreen() { // Why: tracks terminals the user explicitly restored to desktop size. // Without this, switching away and back would auto-fit them again. const manuallyRestoredRef = useRef>(new Set()) - // Why: only auto-fit terminals created during this mobile session. - // Existing desktop terminals should keep their desktop dimensions until - // the user explicitly chooses "Fit to Phone". - const mobileCreatedHandlesRef = useRef>(new Set()) - const agentCommandConsumedRef = useRef(false) - const termRef = useRef(null) - const unsubRef = useRef<(() => void) | null>(null) + const terminalRefs = useRef>(new Map()) + const terminalUnsubsRef = useRef void>>(new Map()) + const subscribingHandlesRef = useRef>(new Set()) + const initializedHandlesRef = useRef>(new Set()) + const locallyCreatedHandlesRef = useRef>(new Set()) const activeHandleRef = useRef(null) - const subscribeSeqRef = useRef(0) + const subscribeSeqRef = useRef>(new Map()) const canSend = connState === 'connected' && activeHandle != null - const formatLines = useCallback((lines: string[] | string | undefined) => { - const text = Array.isArray(lines) ? lines.join('\r\n') : (lines ?? '') - return text && Array.isArray(lines) ? `${text}\r\n` : text + const getTerminalRef = useCallback((handle: string | null) => { + return handle ? terminalRefs.current.get(handle) : undefined + }, []) + + const unsubscribeTerminal = useCallback((handle: string) => { + terminalUnsubsRef.current.get(handle)?.() + terminalUnsubsRef.current.delete(handle) + subscribingHandlesRef.current.delete(handle) + subscribeSeqRef.current.set(handle, (subscribeSeqRef.current.get(handle) ?? 0) + 1) + }, []) + + const clearTerminalCache = useCallback(() => { + for (const unsub of terminalUnsubsRef.current.values()) { + unsub() + } + terminalUnsubsRef.current.clear() + subscribingHandlesRef.current.clear() + initializedHandlesRef.current.clear() + locallyCreatedHandlesRef.current.clear() + subscribeSeqRef.current.clear() + for (const term of terminalRefs.current.values()) { + term.clear() + } }, []) // Why: after a fit/restore resize the PTY grid changes, so we must @@ -139,20 +183,24 @@ export default function SessionScreen() { // takes effect. const resubscribeWithoutFocus = useCallback( (handle: string) => { - unsubRef.current?.() + unsubscribeTerminal(handle) if (!client) return - termRef.current?.clear() - const seq = subscribeSeqRef.current + 1 - subscribeSeqRef.current = seq + const term = getTerminalRef(handle) + term?.clear() + initializedHandlesRef.current.delete(handle) + subscribingHandlesRef.current.add(handle) + const seq = (subscribeSeqRef.current.get(handle) ?? 0) + 1 + subscribeSeqRef.current.set(handle, seq) void (async () => { - if (subscribeSeqRef.current !== seq || activeHandleRef.current !== handle) { + if (subscribeSeqRef.current.get(handle) !== seq) { + subscribingHandlesRef.current.delete(handle) return } const unsub = client.subscribe('terminal.subscribe', { terminal: handle }, (result) => { - if (subscribeSeqRef.current !== seq || activeHandleRef.current !== handle) { + if (subscribeSeqRef.current.get(handle) !== seq) { return } const data = result as Record @@ -162,21 +210,24 @@ export default function SessionScreen() { const initialData = typeof data.serialized === 'string' && data.serialized.length > 0 ? data.serialized - : formatLines(data.lines as string[] | string | undefined) - termRef.current?.init(cols, rows, initialData) + : '' + getTerminalRef(handle)?.init(cols, rows, initialData) + initializedHandlesRef.current.add(handle) } else if (data.type === 'data') { - termRef.current?.write(data.chunk as string) + const chunk = data.chunk as string + getTerminalRef(handle)?.write(chunk) } }) - if (subscribeSeqRef.current === seq && activeHandleRef.current === handle) { - unsubRef.current = unsub + if (subscribeSeqRef.current.get(handle) === seq) { + terminalUnsubsRef.current.set(handle, unsub) } else { unsub() } + subscribingHandlesRef.current.delete(handle) })() }, - [client, formatLines] + [client, getTerminalRef, unsubscribeTerminal] ) // Why: extracted so both manual "Fit to Phone" and auto-fit-on-subscribe @@ -187,7 +238,7 @@ export default function SessionScreen() { const clientId = deviceTokenRef.current if (!clientId) return - const dims = await termRef.current?.measureFitDimensions() + const dims = await getTerminalRef(handle)?.measureFitDimensions() if (!dims) return const response = await rpcClient.sendRequest('terminal.resizeForClient', { @@ -201,9 +252,9 @@ export default function SessionScreen() { updateFittedHandles((prev) => new Set(prev).add(handle)) resubscribeWithoutFocus(handle) - setTimeout(() => termRef.current?.resetZoom(), 500) + setTimeout(() => getTerminalRef(handle)?.resetZoom(), 500) }, - [resubscribeWithoutFocus, updateFittedHandles] + [getTerminalRef, resubscribeWithoutFocus, updateFittedHandles] ) const handleFitToPhone = useCallback(async () => { @@ -239,11 +290,11 @@ export default function SessionScreen() { return next }) resubscribeWithoutFocus(handle) - setTimeout(() => termRef.current?.resetZoom(), 500) + setTimeout(() => getTerminalRef(handle)?.resetZoom(), 500) } catch { // Restore failed — keep current state. } - }, [client, activeHandle, resubscribeWithoutFocus, updateFittedHandles]) + }, [client, activeHandle, getTerminalRef, resubscribeWithoutFocus, updateFittedHandles]) useEffect(() => { let rpcClient: RpcClient | null = null @@ -259,28 +310,36 @@ export default function SessionScreen() { })() return () => { - unsubRef.current?.() + clearTerminalCache() rpcClient?.close() } - }, [hostId]) + }, [clearTerminalCache, hostId]) useEffect(() => { - unsubRef.current?.() - unsubRef.current = null + clearTerminalCache() activeHandleRef.current = null setActiveHandle(null) setTerminals([]) - termRef.current?.clear() - }, [worktreeId]) + }, [clearTerminalCache, worktreeId]) const subscribeToTerminal = useCallback( (handle: string) => { - unsubRef.current?.() - if (!client) return + if (!client) { + return + } + if (terminalUnsubsRef.current.has(handle)) { + return + } + if (subscribingHandlesRef.current.has(handle)) { + return + } + if (!getTerminalRef(handle)) { + return + } - termRef.current?.clear() - const seq = subscribeSeqRef.current + 1 - subscribeSeqRef.current = seq + subscribingHandlesRef.current.add(handle) + const seq = (subscribeSeqRef.current.get(handle) ?? 0) + 1 + subscribeSeqRef.current.set(handle, seq) const rpcClient = client // Why: phone-fitted terminals skip terminal.focus (which would cause @@ -291,11 +350,14 @@ export default function SessionScreen() { // If they don't match (desktop auto-restored while we were away), // we refit — but only then. const shouldAutoFit = - !manuallyRestoredRef.current.has(handle) && - (mobileCreatedHandlesRef.current.has(handle) || fittedHandlesRef.current.has(handle)) + !manuallyRestoredRef.current.has(handle) && fittedHandlesRef.current.has(handle) void (async () => { - if (!shouldAutoFit) { + if ( + !shouldAutoFit && + activeHandleRef.current === handle && + !locallyCreatedHandlesRef.current.has(handle) + ) { try { await client.sendRequest('terminal.focus', { terminal: handle }) await new Promise((resolve) => setTimeout(resolve, 150)) @@ -304,51 +366,62 @@ export default function SessionScreen() { } } - if (subscribeSeqRef.current !== seq || activeHandleRef.current !== handle) { + if (subscribeSeqRef.current.get(handle) !== seq) { + subscribingHandlesRef.current.delete(handle) return } const unsub = client.subscribe('terminal.subscribe', { terminal: handle }, (result) => { - if (subscribeSeqRef.current !== seq || activeHandleRef.current !== handle) { + if (subscribeSeqRef.current.get(handle) !== seq) { return } const data = result as Record if (data.type === 'scrollback') { + if (initializedHandlesRef.current.has(handle)) { + return + } const cols = (data.cols as number) || 80 const rows = (data.rows as number) || 24 const initialData = typeof data.serialized === 'string' && data.serialized.length > 0 ? data.serialized - : formatLines(data.lines as string[] | string | undefined) - termRef.current?.init(cols, rows, initialData) + : '' + getTerminalRef(handle)?.init(cols, rows, initialData) + initializedHandlesRef.current.add(handle) + locallyCreatedHandlesRef.current.delete(handle) // Why: only refit if the scrollback geometry doesn't match // the phone WebView dimensions. This avoids unnecessary // resize→SIGWINCH cycles on tab switches when the terminal // is already at the correct phone size. if (shouldAutoFit && !fitPendingRef.current) { void (async () => { - const dims = await termRef.current?.measureFitDimensions() + const dims = await getTerminalRef(handle)?.measureFitDimensions() if (!dims) return if (cols !== dims.cols || rows !== dims.rows) { - if (activeHandleRef.current === handle && subscribeSeqRef.current === seq) { + if ( + activeHandleRef.current === handle && + subscribeSeqRef.current.get(handle) === seq + ) { void fitToPhoneCore(handle, rpcClient) } } })() } } else if (data.type === 'data') { - termRef.current?.write(data.chunk as string) + const chunk = data.chunk as string + getTerminalRef(handle)?.write(chunk) } }) - if (subscribeSeqRef.current === seq && activeHandleRef.current === handle) { - unsubRef.current = unsub + if (subscribeSeqRef.current.get(handle) === seq) { + terminalUnsubsRef.current.set(handle, unsub) } else { unsub() } + subscribingHandlesRef.current.delete(handle) })() }, - [client, formatLines, fitToPhoneCore] + [client, fitToPhoneCore, getTerminalRef] ) const fetchTerminals = useCallback( @@ -362,6 +435,14 @@ export default function SessionScreen() { }) if (response.ok) { const result = (response as RpcSuccess).result as { terminals: Terminal[] } + const liveHandles = new Set(result.terminals.map((terminal) => terminal.handle)) + for (const handle of Array.from(terminalUnsubsRef.current.keys())) { + if (!liveHandles.has(handle)) { + unsubscribeTerminal(handle) + terminalRefs.current.delete(handle) + initializedHandlesRef.current.delete(handle) + } + } const current = activeHandleRef.current if (current && result.terminals.length === 0) { return @@ -381,11 +462,8 @@ export default function SessionScreen() { setActiveHandle(active.handle) subscribeToTerminal(active.handle) } else { - unsubRef.current?.() - unsubRef.current = null activeHandleRef.current = null setActiveHandle(null) - termRef.current?.clear() } } } @@ -393,14 +471,17 @@ export default function SessionScreen() { // Failed to list terminals } }, - [client, worktreeId, subscribeToTerminal] + [client, worktreeId, subscribeToTerminal, unsubscribeTerminal] ) useEffect(() => { if (connState === 'connected') { setTerminalsLoaded(false) void (async () => { - if (client) { + // Why: worktree.create already asks the desktop renderer to activate + // with startup/setup payloads. A second plain activation can race ahead + // and create a blank first terminal before those payloads are applied. + if (client && created !== '1') { await client .sendRequest('worktree.activate', { worktree: `id:${worktreeId}` @@ -410,9 +491,23 @@ export default function SessionScreen() { await fetchTerminals({ allowEmptyLoaded: false }) setTimeout(() => void fetchTerminals({ allowEmptyLoaded: false }), 750) setTimeout(() => void fetchTerminals({ allowEmptyLoaded: true }), 1500) + if (client && created === '1') { + setTimeout(() => { + if (activeHandleRef.current) return + void (async () => { + await client + .sendRequest('worktree.activate', { + worktree: `id:${worktreeId}` + }) + .catch(() => null) + await fetchTerminals({ allowEmptyLoaded: true }) + setTimeout(() => void fetchTerminals({ allowEmptyLoaded: true }), 750) + })() + }, 1800) + } })() } - }, [client, connState, fetchTerminals, worktreeId]) + }, [client, connState, created, fetchTerminals, worktreeId]) useEffect(() => { if (connState !== 'connected') return @@ -422,53 +517,27 @@ export default function SessionScreen() { return () => clearInterval(interval) }, [connState, fetchTerminals]) - // Why: when navigating here from the "New Worktree" modal with an agent - // command, create the terminal from the session page (not the modal) so - // it goes through the normal mobile-created → auto-fit-to-phone flow. - // The modal can't do this because the terminal would start at the desktop's - // default geometry before the mobile WebView is mounted. - useEffect(() => { - if ( - !agentCommand || - !client || - connState !== 'connected' || - !terminalsLoaded || - agentCommandConsumedRef.current - ) { - return - } - agentCommandConsumedRef.current = true - - void (async () => { - try { - const response = await client.sendRequest('terminal.create', { - worktree: `id:${worktreeId}`, - command: agentCommand - }) - if (response.ok) { - const result = (response as RpcSuccess).result as TerminalCreateResult - const created = result.terminal - mobileCreatedHandlesRef.current.add(created.handle) - activeHandleRef.current = created.handle - setActiveHandle(created.handle) - setTerminals((prev) => [ - ...prev, - { handle: created.handle, title: created.title || 'Terminal', isActive: true } - ]) - subscribeToTerminal(created.handle) - } - } catch { - // Agent terminal creation failed — user can create manually via + - } - })() - }, [agentCommand, client, connState, terminalsLoaded, worktreeId, subscribeToTerminal]) - const switchTab = useCallback( (handle: string) => { activeHandleRef.current = handle setActiveHandle(handle) + if (!fittedHandlesRef.current.has(handle)) { + void client?.sendRequest('terminal.focus', { terminal: handle }).catch(() => null) + } subscribeToTerminal(handle) }, + [client, subscribeToTerminal] + ) + + const setTerminalWebViewRef = useCallback( + (handle: string, ref: TerminalWebViewHandle | null) => { + if (ref) { + terminalRefs.current.set(handle, ref) + subscribeToTerminal(handle) + } else { + terminalRefs.current.delete(handle) + } + }, [subscribeToTerminal] ) @@ -516,7 +585,7 @@ export default function SessionScreen() { if (response.ok) { const result = (response as RpcSuccess).result as TerminalCreateResult const created = result.terminal - mobileCreatedHandlesRef.current.add(created.handle) + locallyCreatedHandlesRef.current.add(created.handle) activeHandleRef.current = created.handle setActiveHandle(created.handle) setTerminals((prev) => [ @@ -569,6 +638,10 @@ export default function SessionScreen() { terminal: target.handle }) if (response.ok) { + unsubscribeTerminal(target.handle) + terminalRefs.current.delete(target.handle) + initializedHandlesRef.current.delete(target.handle) + locallyCreatedHandlesRef.current.delete(target.handle) const next = terminals.filter((terminal) => terminal.handle !== target.handle) setTerminals(next) if (activeHandleRef.current === target.handle) { @@ -577,10 +650,6 @@ export default function SessionScreen() { setActiveHandle(replacement?.handle ?? null) if (replacement) { subscribeToTerminal(replacement.handle) - } else { - unsubRef.current?.() - unsubRef.current = null - termRef.current?.clear() } } setTimeout(() => void fetchTerminals(), 300) @@ -646,7 +715,7 @@ export default function SessionScreen() { style={[styles.tab, t.handle === activeHandle && styles.tabActive]} onPress={() => switchTab(t.handle)} onLongPress={() => { - void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium) + triggerMediumImpact() setActionTarget(t) }} delayLongPress={400} @@ -696,7 +765,14 @@ export default function SessionScreen() { ) : ( - + {terminals.map((terminal) => ( + + ))} )} @@ -912,8 +988,18 @@ const styles = StyleSheet.create({ terminalFrame: { flex: 1, minHeight: 0, + position: 'relative', overflow: 'hidden' }, + terminalPane: { + ...StyleSheet.absoluteFillObject + }, + terminalPaneHidden: { + opacity: 0 + }, + terminalWebView: { + flex: 1 + }, emptyState: { flex: 1, alignItems: 'center', diff --git a/mobile/app/index.tsx b/mobile/app/index.tsx index 61018a917..e1f32dded 100644 --- a/mobile/app/index.tsx +++ b/mobile/app/index.tsx @@ -2,11 +2,11 @@ import { useState, useCallback, useEffect, useMemo } from 'react' import { View, Text, StyleSheet, Pressable, FlatList } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { useRouter, useFocusEffect } from 'expo-router' -import * as Haptics from 'expo-haptics' import { MoreHorizontal, QrCode, Server } from 'lucide-react-native' import { loadHosts, removeHost, renameHost } from '../src/transport/host-store' import { connect } from '../src/transport/rpc-client' import type { ConnectionState, HostProfile } from '../src/transport/types' +import { triggerMediumImpact } from '../src/platform/haptics' import { OrcaLogo } from '../src/components/OrcaLogo' import { StatusDot } from '../src/components/StatusDot' import { TextInputModal } from '../src/components/TextInputModal' @@ -116,7 +116,7 @@ export default function HomeScreen() { style={({ pressed }) => [styles.hostCard, pressed && styles.hostCardPressed]} onPress={() => router.push(`/h/${item.id}`)} onLongPress={() => { - void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium) + triggerMediumImpact() setActionTarget(item) }} delayLongPress={400} diff --git a/mobile/scripts/repro-terminal-colors.ts b/mobile/scripts/repro-terminal-colors.ts new file mode 100644 index 000000000..100643d57 --- /dev/null +++ b/mobile/scripts/repro-terminal-colors.ts @@ -0,0 +1,341 @@ +/** + * Minimal mobile terminal color repro. + * + * Captures terminal.subscribe snapshots in the same sequence that tab switching + * uses: terminal A, terminal B, terminal A again. The report tells us whether + * ANSI SGR color attributes disappeared in the desktop serialized scrollback + * or are still present and therefore being lost during mobile WebView replay. + * + * Usage: + * ORCA_MOBILE_WS_URL=ws://127.0.0.1:6768 \ + * pnpm exec tsx scripts/repro-terminal-colors.ts [handleA] [handleB] + */ +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import nacl from 'tweetnacl' +import WebSocket from 'ws' + +const WS_URL = process.env.ORCA_MOBILE_WS_URL ?? 'ws://127.0.0.1:6768' +const token = process.argv[2] +const serverPublicKeyB64 = process.argv[3] +const worktreeSelector = process.argv[4] +const explicitHandleA = process.argv[5] +const explicitHandleB = process.argv[6] +const ESC = String.fromCharCode(27) + +type RpcResponse = { + id: string + ok: boolean + streaming?: true + result?: Record + error?: { code: string; message: string } +} + +type PendingRequest = { + method: string + resolve: (response: RpcResponse) => void + reject: (error: Error) => void +} + +type Snapshot = { + label: string + handle: string + cols: number | null + rows: number | null + serialized: string + lines: string +} + +if (!token || !serverPublicKeyB64 || !worktreeSelector) { + console.error( + 'Usage: pnpm exec tsx scripts/repro-terminal-colors.ts [handleA] [handleB]' + ) + process.exit(1) +} + +let reqId = 0 +const pending = new Map() +const streamListeners = new Map) => void>() +const clientKeys = nacl.box.keyPair() +const serverPublicKey = Buffer.from(serverPublicKeyB64, 'base64') +const sharedKey = nacl.box.before(new Uint8Array(serverPublicKey), clientKeys.secretKey) + +function nextId(): string { + reqId += 1 + return `color-repro-${reqId}` +} + +function toBase64(bytes: Uint8Array): string { + return Buffer.from(bytes).toString('base64') +} + +function fromBase64(value: string): Uint8Array { + return new Uint8Array(Buffer.from(value, 'base64')) +} + +function encrypt(plaintext: string): string { + const nonce = nacl.randomBytes(nacl.box.nonceLength) + const message = new TextEncoder().encode(plaintext) + const ciphertext = nacl.box.after(message, nonce, sharedKey) + const bundle = new Uint8Array(nonce.length + ciphertext.length) + bundle.set(nonce) + bundle.set(ciphertext, nonce.length) + return toBase64(bundle) +} + +function decrypt(payload: string): string | null { + const bundle = fromBase64(payload) + const nonce = bundle.subarray(0, nacl.box.nonceLength) + const ciphertext = bundle.subarray(nacl.box.nonceLength) + const plaintext = nacl.box.open.after(ciphertext, nonce, sharedKey) + return plaintext ? new TextDecoder().decode(plaintext) : null +} + +function sendRaw(ws: WebSocket, payload: unknown): void { + ws.send(encrypt(JSON.stringify(payload))) +} + +function send(ws: WebSocket, method: string, params?: unknown): Promise { + const id = nextId() + sendRaw(ws, { id, deviceToken: token, method, params }) + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pending.delete(id) + streamListeners.delete(id) + reject(new Error(`Timed out waiting for ${method}`)) + }, 10_000) + pending.set(id, { + method, + resolve: (response) => { + clearTimeout(timeout) + resolve(response) + }, + reject: (error) => { + clearTimeout(timeout) + reject(error) + } + }) + }) +} + +function formatError(response: RpcResponse): string { + return JSON.stringify(response.error ?? response.result ?? response).slice(0, 1000) +} + +async function listHandles( + ws: WebSocket +): Promise> { + const response = await send(ws, 'terminal.list', { worktree: worktreeSelector }) + if (!response.ok) { + throw new Error(`terminal.list failed: ${formatError(response)}`) + } + return ( + (response.result?.terminals ?? []) as Array<{ handle: string; title?: string | null }> + ).map((terminal) => ({ + handle: terminal.handle, + title: terminal.title ?? null + })) +} + +async function ensureSecondHandle(ws: WebSocket, handleA: string): Promise { + const terminals = await listHandles(ws) + const existing = terminals.find((terminal) => terminal.handle !== handleA) + if (existing) return existing.handle + + const created = await send(ws, 'terminal.create', { + worktree: worktreeSelector, + title: 'color-repro-switch-target' + }) + if (!created.ok) { + throw new Error(`terminal.create failed: ${formatError(created)}`) + } + const handle = (created.result?.terminal as { handle?: string } | undefined)?.handle + if (!handle) { + throw new Error(`terminal.create returned no handle: ${formatError(created)}`) + } + return handle +} + +async function captureSnapshot(ws: WebSocket, label: string, handle: string): Promise { + const id = nextId() + const snapshot = await new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pending.delete(id) + streamListeners.delete(id) + reject(new Error(`Timed out waiting for scrollback snapshot ${label}`)) + }, 10_000) + + pending.set(id, { + method: 'terminal.subscribe', + resolve: () => {}, + reject: (error) => { + clearTimeout(timeout) + reject(error) + } + }) + streamListeners.set(id, (result) => { + if (result.type !== 'scrollback') return + clearTimeout(timeout) + pending.delete(id) + streamListeners.delete(id) + const serialized = typeof result.serialized === 'string' ? result.serialized : '' + const rawLines = result.lines + const lines = Array.isArray(rawLines) ? rawLines.join('\n') : String(rawLines ?? '') + resolve({ + label, + handle, + cols: typeof result.cols === 'number' ? result.cols : null, + rows: typeof result.rows === 'number' ? result.rows : null, + serialized, + lines + }) + }) + + sendRaw(ws, { + id, + deviceToken: token, + method: 'terminal.subscribe', + params: { terminal: handle } + }) + }) + + await send(ws, 'terminal.unsubscribe', { subscriptionId: handle }).catch(() => null) + return snapshot +} + +function countMatches(value: string, pattern: RegExp): number { + return value.match(pattern)?.length ?? 0 +} + +function summarize(snapshot: Snapshot): Record { + const data = snapshot.serialized + return { + label: snapshot.label, + handle: snapshot.handle, + cols: snapshot.cols, + rows: snapshot.rows, + serializedBytes: Buffer.byteLength(data), + sgrTotal: countMatches(data, new RegExp(`${ESC}\\[[0-9;:]*m`, 'g')), + sgrColor: countMatches( + data, + new RegExp( + `${ESC}\\[(?:[0-9;:]*[;:])?(?:3[0-7]|4[0-7]|9[0-7]|10[0-7]|38[;:]|48[;:])[0-9;:]*m`, + 'g' + ) + ), + sgrReset: countMatches(data, new RegExp(`${ESC}\\[(?:0|39|49|0;39;49)m`, 'g')), + altScreen: data.includes(`${ESC}[?1049h`) ? 'yes' : 'no', + containsTruecolor: data.includes('38;2') || data.includes('38:2') ? 'yes' : 'no', + containsPaletteColor: data.includes('38;5') || data.includes('38:5') ? 'yes' : 'no' + } +} + +function saveSnapshots(snapshots: Snapshot[]): string { + const dir = join(process.cwd(), 'terminal-color-repro') + mkdirSync(dir, { recursive: true }) + for (const snapshot of snapshots) { + const base = snapshot.label.replace(/[^a-z0-9_-]/gi, '-') + writeFileSync(join(dir, `${base}.ansi`), snapshot.serialized || snapshot.lines) + writeFileSync( + join(dir, `${base}.escaped.txt`), + JSON.stringify(snapshot.serialized || snapshot.lines) + ) + } + writeFileSync(join(dir, 'summary.json'), JSON.stringify(snapshots.map(summarize), null, 2)) + return dir +} + +async function run(ws: WebSocket): Promise { + ws.send( + JSON.stringify({ + type: 'e2ee_hello', + publicKeyB64: toBase64(clientKeys.publicKey), + deviceToken: token + }) + ) + + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error('Timed out waiting for e2ee_ready')), 5000) + ws.once('message', (data) => { + clearTimeout(timeout) + const msg = JSON.parse(data.toString()) as { type?: string } + if (msg.type !== 'e2ee_ready') { + reject(new Error(`Unexpected handshake response: ${data.toString()}`)) + return + } + resolve() + }) + }) + + const terminals = await listHandles(ws) + if (terminals.length === 0 && !explicitHandleA) { + throw new Error('No terminals found. Open a Claude Code terminal first, then rerun.') + } + + const handleA = explicitHandleA ?? terminals[0]!.handle + const handleB = explicitHandleB ?? (await ensureSecondHandle(ws, handleA)) + + console.log(`A: ${handleA}`) + console.log(`B: ${handleB}`) + + const firstA = await captureSnapshot(ws, 'a-before-switch', handleA) + const firstB = await captureSnapshot(ws, 'b-during-switch', handleB) + const secondA = await captureSnapshot(ws, 'a-after-switch', handleA) + const snapshots = [firstA, firstB, secondA] + const dir = saveSnapshots(snapshots) + + console.table(snapshots.map(summarize)) + console.log(`saved: ${dir}`) + if (summarize(firstA).sgrColor !== summarize(secondA).sgrColor) { + console.log( + 'color SGR count changed between A snapshots: serialization/state changed on desktop' + ) + } else { + console.log('A snapshots have the same color SGR count: likely mobile replay/render path') + } +} + +const ws = new WebSocket(WS_URL) + +ws.on('open', () => { + run(ws) + .then(() => { + ws.close() + process.exit(0) + }) + .catch((error) => { + console.error(error.message) + ws.close() + process.exit(1) + }) +}) + +ws.on('message', (data) => { + const plaintext = decrypt(data.toString()) + if (!plaintext) return + + const response = JSON.parse(plaintext) as RpcResponse + const result = response.result + const streamListener = streamListeners.get(response.id) + if (streamListener && response.ok && (response.streaming || result?.type === 'scrollback')) { + streamListener(result ?? {}) + return + } + + const request = pending.get(response.id) + if (!request || request.method === 'terminal.subscribe') return + pending.delete(response.id) + request.resolve(response) +}) + +ws.on('close', () => { + for (const request of pending.values()) { + request.reject(new Error('WebSocket closed')) + } + pending.clear() +}) + +ws.on('error', (error) => { + console.error(`WebSocket error: ${error.message}`) + process.exit(1) +}) diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx new file mode 100644 index 000000000..a018facc1 --- /dev/null +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -0,0 +1,655 @@ +import { useState, useEffect } from 'react' +import { + Modal, + View, + Text, + TextInput, + Pressable, + StyleSheet, + Platform, + ActivityIndicator, + Image, + FlatList +} from 'react-native' +import { ChevronDown, Check, Terminal, X } from 'lucide-react-native' +import Svg, { Path, G } from 'react-native-svg' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import { colors, spacing, radii, typography } from '../theme/mobile-theme' + +type Repo = { + id: string + displayName: string + path: string +} + +type AgentOption = { + id: string + label: string + faviconDomain?: string +} + +// Why: matches the AGENT_CATALOG ordering and faviconDomain values from +// src/renderer/src/lib/agent-catalog.tsx so mobile uses the same icon sources. +const AGENT_OPTIONS: AgentOption[] = [ + { id: 'claude', label: 'Claude' }, + { id: 'codex', label: 'Codex' }, + { id: 'copilot', label: 'GitHub Copilot', faviconDomain: 'github.com' }, + { id: 'opencode', label: 'OpenCode', faviconDomain: 'opencode.ai' }, + { id: 'pi', label: 'Pi' }, + { id: 'gemini', label: 'Gemini', faviconDomain: 'gemini.google.com' }, + { id: 'aider', label: 'Aider' }, + { id: 'goose', label: 'Goose', faviconDomain: 'goose-docs.ai' }, + { id: 'amp', label: 'Amp', faviconDomain: 'ampcode.com' }, + { id: 'kilo', label: 'Kilocode', faviconDomain: 'kilo.ai' }, + { id: 'kiro', label: 'Kiro', faviconDomain: 'kiro.dev' }, + { id: 'crush', label: 'Charm', faviconDomain: 'charm.sh' }, + { id: 'aug', label: 'Auggie', faviconDomain: 'augmentcode.com' }, + { id: 'cline', label: 'Cline', faviconDomain: 'cline.bot' }, + { id: 'codebuff', label: 'Codebuff', faviconDomain: 'codebuff.com' }, + { id: 'continue', label: 'Continue', faviconDomain: 'continue.dev' }, + { id: 'cursor', label: 'Cursor', faviconDomain: 'cursor.com' }, + { id: 'droid', label: 'Droid', faviconDomain: 'factory.ai' }, + { id: 'kimi', label: 'Kimi', faviconDomain: 'moonshot.cn' }, + { id: 'mistral-vibe', label: 'Mistral Vibe', faviconDomain: 'mistral.ai' }, + { id: 'qwen-code', label: 'Qwen Code', faviconDomain: 'qwenlm.github.io' }, + { id: 'rovo', label: 'Rovo Dev', faviconDomain: 'atlassian.com' }, + { id: 'hermes', label: 'Hermes', faviconDomain: 'nousresearch.com' } +] + +const BLANK_TERMINAL: AgentOption = { id: '__blank__', label: 'Blank Terminal' } +const ALL_AGENTS = [...AGENT_OPTIONS, BLANK_TERMINAL] + +// Why: mirrors launchCmd from src/shared/tui-agent-config.ts so terminal.create +// gets the correct binary name for each agent. +const AGENT_COMMANDS: Record = { + claude: 'claude', + codex: 'codex', + copilot: 'copilot', + opencode: 'opencode', + pi: 'pi', + gemini: 'gemini', + aider: 'aider', + goose: 'goose', + amp: 'amp', + kilo: 'kilo', + kiro: 'kiro', + crush: 'crush', + aug: 'auggie', + cline: 'cline', + codebuff: 'codebuff', + continue: 'continue', + cursor: 'cursor-agent', + droid: 'droid', + kimi: 'kimi', + 'mistral-vibe': 'mistral-vibe', + 'qwen-code': 'qwen-code', + rovo: 'rovo', + hermes: 'hermes' +} + +// ── Agent icons ───────────────────────────────────────────────────── +// SVG paths sourced from the desktop codebase: +// Claude & OpenAI: src/renderer/src/components/status-bar/icons.tsx +// Pi & Aider: src/renderer/src/lib/agent-catalog.tsx +// Agents with a faviconDomain use Google's favicon service (same as desktop). + +function ClaudeIcon({ size = 16 }: { size?: number }) { + return ( + + + + ) +} + +function OpenAIIcon({ size = 16 }: { size?: number }) { + return ( + + + + ) +} + +function PiIcon({ size = 16 }: { size?: number }) { + return ( + + + + + ) +} + +function AiderIcon({ size = 16 }: { size?: number }) { + return ( + + + + + + + ) +} + +function FaviconIcon({ domain, size = 16 }: { domain: string; size?: number }) { + return ( + + ) +} + +function AgentLetterIcon({ letter, size = 16 }: { letter: string; size?: number }) { + return ( + + + {letter} + + + ) +} + +function AgentIcon({ agentId, size = 16 }: { agentId: string; size?: number }) { + if (agentId === 'claude') return + if (agentId === 'codex') return + if (agentId === 'pi') return + if (agentId === 'aider') return + if (agentId === '__blank__') return + + const agent = AGENT_OPTIONS.find((a) => a.id === agentId) + if (agent?.faviconDomain) { + return + } + const label = agent?.label ?? agentId + return +} + +// ── Picker sub-modal ──────────────────────────────────────────────── +// Why: inline dropdowns with position:absolute + ScrollView have persistent +// touch-conflict issues in React Native. A separate modal for the picker +// list is the standard mobile pattern — it scrolls reliably and feels native. + +function PickerListModal({ + visible, + title, + items, + selectedId, + onSelect, + onClose, + renderIcon +}: { + visible: boolean + title: string + items: T[] + selectedId: string + onSelect: (item: T) => void + onClose: () => void + renderIcon?: (item: T) => React.ReactNode +}) { + return ( + + + true}> + {title} + item.id} + style={styles.pickerList} + renderItem={({ item }) => { + const selected = item.id === selectedId + return ( + { + onSelect(item) + onClose() + }} + > + {renderIcon?.(item)} + + {item.label} + + {selected && } + + ) + }} + /> + + Cancel + + + + + ) +} + +// ── Main modal ────────────────────────────────────────────────────── + +type Props = { + visible: boolean + client: RpcClient | null + onCreated: (worktreeId: string, name: string) => void + onClose: () => void +} + +export function NewWorktreeModal({ visible, client, onCreated, onClose }: Props) { + const [repos, setRepos] = useState([]) + const [selectedRepo, setSelectedRepo] = useState(null) + const [showRepoPicker, setShowRepoPicker] = useState(false) + const [selectedAgent, setSelectedAgent] = useState(AGENT_OPTIONS[0]!) + const [showAgentPicker, setShowAgentPicker] = useState(false) + const [name, setName] = useState('') + const [creating, setCreating] = useState(false) + const [error, setError] = useState('') + const [loading, setLoading] = useState(true) + + useEffect(() => { + if (!visible || !client) return + setName('') + setError('') + setCreating(false) + setShowRepoPicker(false) + setShowAgentPicker(false) + setSelectedAgent(AGENT_OPTIONS[0]!) + setLoading(true) + + void (async () => { + try { + const response = await client.sendRequest('repo.list') + if (response.ok) { + const result = (response as RpcSuccess).result as { repos: Repo[] } + setRepos(result.repos) + if (result.repos.length === 1) { + setSelectedRepo(result.repos[0]!) + } else { + setSelectedRepo(null) + } + } + } catch { + setRepos([]) + } finally { + setLoading(false) + } + })() + }, [visible, client]) + + async function handleCreate() { + if (!client || !selectedRepo || !name.trim()) return + setCreating(true) + setError('') + + try { + const command = + selectedAgent.id !== '__blank__' ? AGENT_COMMANDS[selectedAgent.id] : undefined + + const response = await client.sendRequest('worktree.create', { + repo: `id:${selectedRepo.id}`, + name: name.trim(), + startupCommand: command + }) + + if (response.ok) { + const result = (response as RpcSuccess).result as { worktree: { id: string } } + const worktreeId = result.worktree.id + + onClose() + onCreated(worktreeId, name.trim()) + } else { + setError(response.error.message) + } + } catch (e) { + setError(e instanceof Error ? e.message : 'Failed to create worktree') + } finally { + setCreating(false) + } + } + + const canCreate = selectedRepo != null && name.trim().length > 0 && !creating + + return ( + <> + + + true}> + + + New Worktree + Pick a repository and agent + + + + + + + {loading ? ( + + + + ) : repos.length === 0 ? ( + + No repositories found + + ) : ( + <> + {/* Repository */} + + Repository + setShowRepoPicker(true)}> + + {selectedRepo?.displayName ?? 'Select a repository'} + + + + + + {/* Name */} + + Name + { + setName(t) + setError('') + }} + placeholder="my-feature" + placeholderTextColor={colors.textMuted} + autoCapitalize="none" + autoCorrect={false} + autoFocus={repos.length <= 1} + returnKeyType="done" + onSubmitEditing={() => { + if (canCreate) void handleCreate() + }} + /> + + + {/* Agent */} + + Agent + setShowAgentPicker(true)}> + + + {selectedAgent.label} + + + + + + {error ? {error} : null} + + + + Cancel + + void handleCreate()} + > + {creating ? ( + + ) : ( + Create + )} + + + + )} + + + + + {/* Sub-modals for pickers — rendered outside the main modal so they + layer on top and scroll without touch conflicts. */} + ({ id: r.id, label: r.displayName, _repo: r }))} + selectedId={selectedRepo?.id ?? ''} + onSelect={(item) => setSelectedRepo((item as { _repo: Repo })._repo)} + onClose={() => setShowRepoPicker(false)} + /> + + setSelectedAgent(agent)} + onClose={() => setShowAgentPicker(false)} + renderIcon={(agent) => } + /> + + ) +} + +const styles = StyleSheet.create({ + backdrop: { + flex: 1, + backgroundColor: 'rgba(0,0,0,0.6)', + justifyContent: 'center', + alignItems: 'center', + padding: spacing.xl + }, + card: { + width: '100%', + maxWidth: 340, + backgroundColor: colors.bgPanel, + borderRadius: 14, + padding: spacing.xl, + ...Platform.select({ + ios: { + shadowColor: '#000', + shadowOffset: { width: 0, height: 4 }, + shadowOpacity: 0.3, + shadowRadius: 12 + }, + android: { elevation: 8 } + }) + }, + header: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'flex-start', + marginBottom: spacing.lg + }, + title: { + fontSize: 17, + fontWeight: '600', + color: colors.textPrimary + }, + subtitle: { + fontSize: 12, + color: colors.textSecondary, + marginTop: 2 + }, + closeButton: { + padding: spacing.xs + }, + loadingContainer: { + paddingVertical: spacing.xl, + alignItems: 'center' + }, + emptyText: { + color: colors.textSecondary, + fontSize: typography.bodySize + }, + field: { + marginBottom: spacing.md + }, + label: { + fontSize: 12, + fontWeight: '500', + color: colors.textSecondary, + textTransform: 'uppercase', + letterSpacing: 0.5, + marginBottom: spacing.xs + }, + fieldButton: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + backgroundColor: colors.bgRaised, + borderRadius: radii.input, + paddingHorizontal: spacing.md, + paddingVertical: Platform.OS === 'ios' ? spacing.sm + 2 : spacing.sm, + borderWidth: 1, + borderColor: colors.borderSubtle + }, + fieldButtonText: { + flex: 1, + fontSize: typography.bodySize, + color: colors.textPrimary + }, + fieldButtonPlaceholder: { + color: colors.textMuted + }, + input: { + backgroundColor: colors.bgRaised, + color: colors.textPrimary, + borderRadius: radii.input, + paddingHorizontal: spacing.md, + paddingVertical: Platform.OS === 'ios' ? spacing.sm + 2 : spacing.sm, + fontSize: typography.bodySize, + borderWidth: 1, + borderColor: colors.borderSubtle + }, + error: { + color: colors.statusRed, + fontSize: 13, + marginBottom: spacing.md + }, + actions: { + flexDirection: 'row', + justifyContent: 'flex-end', + gap: spacing.sm, + marginTop: spacing.sm + }, + cancelButton: { + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + borderRadius: radii.button + }, + cancelText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + fontWeight: '500' + }, + createButton: { + backgroundColor: colors.textPrimary, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + borderRadius: radii.button, + minWidth: 72, + alignItems: 'center' + }, + createButtonDisabled: { + opacity: 0.4 + }, + createText: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '600' + }, + letterIcon: { + alignItems: 'center', + justifyContent: 'center' + }, + letterIconText: { + fontWeight: '700' + }, + + // Picker sub-modal styles + pickerCard: { + width: '100%', + maxWidth: 320, + maxHeight: '70%', + backgroundColor: colors.bgPanel, + borderRadius: 14, + overflow: 'hidden', + ...Platform.select({ + ios: { + shadowColor: '#000', + shadowOffset: { width: 0, height: 4 }, + shadowOpacity: 0.3, + shadowRadius: 12 + }, + android: { elevation: 8 } + }) + }, + pickerTitle: { + fontSize: 15, + fontWeight: '600', + color: colors.textSecondary, + textTransform: 'uppercase', + letterSpacing: 0.5, + paddingHorizontal: spacing.lg, + paddingTop: spacing.lg, + paddingBottom: spacing.sm + }, + pickerList: { + flexGrow: 0 + }, + pickerItem: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingVertical: spacing.sm + 2, + paddingHorizontal: spacing.lg + }, + pickerItemSelected: { + backgroundColor: colors.bgRaised + }, + pickerItemText: { + flex: 1, + fontSize: typography.bodySize, + color: colors.textPrimary + }, + pickerItemTextSelected: { + fontWeight: '600' + }, + pickerCancel: { + alignItems: 'center', + paddingVertical: spacing.md, + borderTopWidth: 1, + borderTopColor: colors.borderSubtle, + marginTop: spacing.xs + }, + pickerCancelText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + fontWeight: '500' + } +}) diff --git a/mobile/src/platform/haptics.ts b/mobile/src/platform/haptics.ts new file mode 100644 index 000000000..f26a6b841 --- /dev/null +++ b/mobile/src/platform/haptics.ts @@ -0,0 +1,7 @@ +import * as Haptics from 'expo-haptics' + +export function triggerMediumImpact(): void { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => { + // Why: Expo haptics can be unavailable on some Android builds/emulators. + }) +} diff --git a/mobile/src/terminal/TerminalWebView.tsx b/mobile/src/terminal/TerminalWebView.tsx index 92e6aef5b..11806e000 100644 --- a/mobile/src/terminal/TerminalWebView.tsx +++ b/mobile/src/terminal/TerminalWebView.tsx @@ -1,25 +1,27 @@ import { useRef, useCallback, forwardRef, useImperativeHandle } from 'react' -import { StyleSheet } from 'react-native' +import { StyleSheet, type StyleProp, type ViewStyle } from 'react-native' import { WebView } from 'react-native-webview' import type { WebViewMessageEvent } from 'react-native-webview' import { colors } from '../theme/mobile-theme' export type TerminalWebViewHandle = { write: (data: string) => void - init: (cols: number, rows: number) => void + init: (cols: number, rows: number, initialData?: string) => void clear: () => void measureFitDimensions: () => Promise<{ cols: number; rows: number } | null> resetZoom: () => void } -type Props = object +type Props = { + style?: StyleProp +} type TerminalMessage = - | { type: 'write'; data: string } - | { type: 'init'; cols: number; rows: number } - | { type: 'clear' } - | { type: 'measure' } - | { type: 'reset-zoom' } + | { type: 'write'; id?: number; data: string } + | { type: 'init'; id?: number; cols: number; rows: number; initialData?: string } + | { type: 'clear'; id?: number } + | { type: 'measure'; id?: number } + | { type: 'reset-zoom'; id?: number } // Why: TUI apps (Claude Code / Ink) emit escape codes with absolute cursor // positioning designed for the desktop's terminal dimensions (~150+ cols). @@ -35,7 +37,7 @@ const XTERM_HTML = ` - +