checkpoint mobile terminal streaming work

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo-H
2026-04-30 18:03:53 -04:00
co-authored by Orca
parent 42e9ed2ca1
commit 2c6f710b56
24 changed files with 1745 additions and 284 deletions
+12
View File
@@ -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 \
<deviceToken> <serverPublicKeyB64> "id:<worktreeId>"
```
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:
+4 -5
View File
@@ -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() {
<NewWorktreeModal
visible={showNewWorktree}
client={client}
onCreated={(worktreeId, worktreeName, agentCommand) => {
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)}
+195 -109
View File
@@ -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<ConnectionState, string> = {
'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 (
<View
pointerEvents={active ? 'auto' : 'none'}
style={[styles.terminalPane, !active && styles.terminalPaneHidden]}
>
<TerminalWebView ref={setRef} style={styles.terminalWebView} />
</View>
)
}
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<RpcClient | null>(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<Set<string>>(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<Set<string>>(new Set())
const agentCommandConsumedRef = useRef(false)
const termRef = useRef<TerminalWebViewHandle>(null)
const unsubRef = useRef<(() => void) | null>(null)
const terminalRefs = useRef<Map<string, TerminalWebViewHandle>>(new Map())
const terminalUnsubsRef = useRef<Map<string, () => void>>(new Map())
const subscribingHandlesRef = useRef<Set<string>>(new Set())
const initializedHandlesRef = useRef<Set<string>>(new Set())
const locallyCreatedHandlesRef = useRef<Set<string>>(new Set())
const activeHandleRef = useRef<string | null>(null)
const subscribeSeqRef = useRef(0)
const subscribeSeqRef = useRef<Map<string, number>>(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<string, unknown>
@@ -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<string, unknown>
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() {
</View>
) : (
<View style={styles.terminalFrame}>
<TerminalWebView ref={termRef} />
{terminals.map((terminal) => (
<TerminalPaneView
key={terminal.handle}
handle={terminal.handle}
active={terminal.handle === activeHandle}
onRef={setTerminalWebViewRef}
/>
))}
</View>
)}
@@ -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',
+2 -2
View File
@@ -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}
+341
View File
@@ -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 <deviceToken> <serverPublicKeyB64> <worktreeSelector> [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<string, unknown>
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 <deviceToken> <serverPublicKeyB64> <worktreeSelector> [handleA] [handleB]'
)
process.exit(1)
}
let reqId = 0
const pending = new Map<string, PendingRequest>()
const streamListeners = new Map<string, (result: Record<string, unknown>) => 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<RpcResponse> {
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<Array<{ handle: string; title: string | null }>> {
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<string> {
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<Snapshot> {
const id = nextId()
const snapshot = await new Promise<Snapshot>((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<string, string | number | null> {
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<void> {
ws.send(
JSON.stringify({
type: 'e2ee_hello',
publicKeyB64: toBase64(clientKeys.publicKey),
deviceToken: token
})
)
await new Promise<void>((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)
})
+655
View File
@@ -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<string, string> = {
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 (
<Svg width={size} height={size} viewBox="0 0 24 24">
<Path
d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z"
fill="#D97757"
fillRule="nonzero"
/>
</Svg>
)
}
function OpenAIIcon({ size = 16 }: { size?: number }) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24">
<Path
d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"
fill={colors.textPrimary}
fillRule="evenodd"
/>
</Svg>
)
}
function PiIcon({ size = 16 }: { size?: number }) {
return (
<Svg width={size} height={size} viewBox="0 0 800 800">
<Path
fill={colors.textPrimary}
fillRule="evenodd"
d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"
/>
<Path fill={colors.textPrimary} d="M517.36 400 H634.72 V634.72 H517.36 Z" />
</Svg>
)
}
function AiderIcon({ size = 16 }: { size?: number }) {
return (
<Svg width={size} height={size} viewBox="0 0 436 436">
<G transform="translate(0,436) scale(0.1,-0.1)" fill={colors.textPrimary} stroke="none">
<Path d="M0 2180 l0 -2180 2180 0 2180 0 0 2180 0 2180 -2180 0 -2180 0 0 -2180z m2705 1818 c20 -20 28 -121 30 -398 l2 -305 216 -5 c118 -3 218 -8 222 -12 3 -3 10 -46 15 -95 5 -48 16 -126 25 -172 17 -86 17 -81 -17 -233 -14 -67 -13 -365 2 -438 21 -100 22 -159 5 -247 -24 -122 -24 -363 1 -458 23 -88 23 -213 1 -330 -9 -49 -17 -109 -17 -132 l0 -43 203 0 c111 0 208 -4 216 -9 10 -6 18 -51 27 -148 8 -76 16 -152 20 -168 7 -39 -23 -361 -37 -387 -10 -18 -21 -19 -214 -16 -135 2 -208 7 -215 14 -22 22 -33 301 -21 501 6 102 8 189 5 194 -8 13 -417 12 -431 -2 -12 -12 -8 -146 8 -261 8 -55 8 -95 1 -140 -6 -35 -14 -99 -17 -143 -9 -123 -14 -141 -41 -154 -18 -8 -217 -11 -679 -11 l-653 0 -11 33 c-31 97 -43 336 -27 533 5 56 6 113 2 128 l-6 26 -194 0 c-211 0 -252 4 -261 28 -12 33 -17 392 -6 522 15 186 -2 174 260 180 115 3 213 8 217 12 4 4 1 52 -5 105 -7 54 -17 130 -22 168 -7 56 -5 91 11 171 10 55 22 130 26 166 4 36 10 72 15 79 7 12 128 15 665 19 l658 5 8 30 c5 18 4 72 -3 130 -12 115 -7 346 11 454 10 61 10 75 -1 82 -8 5 -300 9 -650 9 l-636 0 -27 25 c-18 16 -26 34 -26 57 0 18 -5 87 -10 153 -10 128 5 449 22 472 5 7 26 13 46 15 78 6 1281 3 1287 -4z" />
<Path d="M1360 1833 c0 -5 -1 -164 -3 -356 l-2 -347 625 -1 c704 -1 708 -1 722 7 5 4 7 20 4 38 -29 141 -32 491 -6 595 9 38 8 45 -7 57 -15 11 -139 13 -675 14 -362 0 -658 -3 -658 -7z" />
</G>
</Svg>
)
}
function FaviconIcon({ domain, size = 16 }: { domain: string; size?: number }) {
return (
<Image
source={{ uri: `https://www.google.com/s2/favicons?domain=${domain}&sz=64` }}
style={{ width: size, height: size, borderRadius: 2 }}
/>
)
}
function AgentLetterIcon({ letter, size = 16 }: { letter: string; size?: number }) {
return (
<View
style={[
styles.letterIcon,
{
width: size,
height: size,
borderRadius: size * 0.22,
backgroundColor: colors.textMuted + '33'
}
]}
>
<Text style={[styles.letterIconText, { fontSize: size * 0.55, color: colors.textPrimary }]}>
{letter}
</Text>
</View>
)
}
function AgentIcon({ agentId, size = 16 }: { agentId: string; size?: number }) {
if (agentId === 'claude') return <ClaudeIcon size={size} />
if (agentId === 'codex') return <OpenAIIcon size={size} />
if (agentId === 'pi') return <PiIcon size={size} />
if (agentId === 'aider') return <AiderIcon size={size} />
if (agentId === '__blank__') return <Terminal size={size} color={colors.textMuted} />
const agent = AGENT_OPTIONS.find((a) => a.id === agentId)
if (agent?.faviconDomain) {
return <FaviconIcon domain={agent.faviconDomain} size={size} />
}
const label = agent?.label ?? agentId
return <AgentLetterIcon letter={label.charAt(0).toUpperCase()} size={size} />
}
// ── 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<T extends { id: string; label: string }>({
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 (
<Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
<Pressable style={styles.backdrop} onPress={onClose}>
<View style={styles.pickerCard} onStartShouldSetResponder={() => true}>
<Text style={styles.pickerTitle}>{title}</Text>
<FlatList
data={items}
keyExtractor={(item) => item.id}
style={styles.pickerList}
renderItem={({ item }) => {
const selected = item.id === selectedId
return (
<Pressable
style={[styles.pickerItem, selected && styles.pickerItemSelected]}
onPress={() => {
onSelect(item)
onClose()
}}
>
{renderIcon?.(item)}
<Text
style={[styles.pickerItemText, selected && styles.pickerItemTextSelected]}
numberOfLines={1}
>
{item.label}
</Text>
{selected && <Check size={14} color={colors.textPrimary} />}
</Pressable>
)
}}
/>
<Pressable style={styles.pickerCancel} onPress={onClose}>
<Text style={styles.pickerCancelText}>Cancel</Text>
</Pressable>
</View>
</Pressable>
</Modal>
)
}
// ── 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<Repo[]>([])
const [selectedRepo, setSelectedRepo] = useState<Repo | null>(null)
const [showRepoPicker, setShowRepoPicker] = useState(false)
const [selectedAgent, setSelectedAgent] = useState<AgentOption>(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 (
<>
<Modal visible={visible} transparent animationType="fade" onRequestClose={onClose}>
<Pressable style={styles.backdrop} onPress={onClose}>
<View style={styles.card} onStartShouldSetResponder={() => true}>
<View style={styles.header}>
<View>
<Text style={styles.title}>New Worktree</Text>
<Text style={styles.subtitle}>Pick a repository and agent</Text>
</View>
<Pressable style={styles.closeButton} onPress={onClose} hitSlop={8}>
<X size={18} color={colors.textSecondary} />
</Pressable>
</View>
{loading ? (
<View style={styles.loadingContainer}>
<ActivityIndicator size="small" color={colors.textSecondary} />
</View>
) : repos.length === 0 ? (
<View style={styles.loadingContainer}>
<Text style={styles.emptyText}>No repositories found</Text>
</View>
) : (
<>
{/* Repository */}
<View style={styles.field}>
<Text style={styles.label}>Repository</Text>
<Pressable style={styles.fieldButton} onPress={() => setShowRepoPicker(true)}>
<Text
style={[
styles.fieldButtonText,
!selectedRepo && styles.fieldButtonPlaceholder
]}
numberOfLines={1}
>
{selectedRepo?.displayName ?? 'Select a repository'}
</Text>
<ChevronDown size={14} color={colors.textMuted} />
</Pressable>
</View>
{/* Name */}
<View style={styles.field}>
<Text style={styles.label}>Name</Text>
<TextInput
style={styles.input}
value={name}
onChangeText={(t) => {
setName(t)
setError('')
}}
placeholder="my-feature"
placeholderTextColor={colors.textMuted}
autoCapitalize="none"
autoCorrect={false}
autoFocus={repos.length <= 1}
returnKeyType="done"
onSubmitEditing={() => {
if (canCreate) void handleCreate()
}}
/>
</View>
{/* Agent */}
<View style={styles.field}>
<Text style={styles.label}>Agent</Text>
<Pressable style={styles.fieldButton} onPress={() => setShowAgentPicker(true)}>
<AgentIcon agentId={selectedAgent.id} size={16} />
<Text style={styles.fieldButtonText} numberOfLines={1}>
{selectedAgent.label}
</Text>
<ChevronDown size={14} color={colors.textMuted} />
</Pressable>
</View>
{error ? <Text style={styles.error}>{error}</Text> : null}
<View style={styles.actions}>
<Pressable style={styles.cancelButton} onPress={onClose}>
<Text style={styles.cancelText}>Cancel</Text>
</Pressable>
<Pressable
style={[styles.createButton, !canCreate && styles.createButtonDisabled]}
disabled={!canCreate}
onPress={() => void handleCreate()}
>
{creating ? (
<ActivityIndicator size="small" color={colors.bgBase} />
) : (
<Text style={styles.createText}>Create</Text>
)}
</Pressable>
</View>
</>
)}
</View>
</Pressable>
</Modal>
{/* Sub-modals for pickers — rendered outside the main modal so they
layer on top and scroll without touch conflicts. */}
<PickerListModal
visible={showRepoPicker}
title="Repository"
items={repos.map((r) => ({ id: r.id, label: r.displayName, _repo: r }))}
selectedId={selectedRepo?.id ?? ''}
onSelect={(item) => setSelectedRepo((item as { _repo: Repo })._repo)}
onClose={() => setShowRepoPicker(false)}
/>
<PickerListModal
visible={showAgentPicker}
title="Agent"
items={ALL_AGENTS}
selectedId={selectedAgent.id}
onSelect={(agent) => setSelectedAgent(agent)}
onClose={() => setShowAgentPicker(false)}
renderIcon={(agent) => <AgentIcon agentId={agent.id} size={18} />}
/>
</>
)
}
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'
}
})
+7
View File
@@ -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.
})
}
+193 -126
View File
@@ -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<ViewStyle>
}
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 = `<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/css/xterm.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@6.1.0-beta.198/css/xterm.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
@@ -61,18 +63,24 @@ const XTERM_HTML = `<!DOCTYPE html>
<div id="terminal-container">
<div id="terminal-surface"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/@xterm/xterm@5.5.0/lib/xterm.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@xterm/xterm@6.1.0-beta.198/lib/xterm.min.js"></script>
<script>
(function() {
var surface = document.getElementById('terminal-surface');
var ESC = String.fromCharCode(27);
var term = null;
var writeQueue = [];
var writesDraining = false;
var afterDrainCallbacks = [];
var ready = false;
var currentScale = 1;
var userScale = 1;
var panX = 0;
var panY = 0;
var initRows = 24;
var terminalGeneration = 0;
var activeAltScreenSnapshot = false;
var handledMessageIds = [];
function computeFitScale() {
if (!term) return 1;
@@ -131,6 +139,10 @@ const XTERM_HTML = `<!DOCTYPE html>
// original init row count to avoid clipping active terminal content.
function adjustRowsForViewport() {
if (!term || !term.element) return;
// Why: active alternate-screen TUIs (Claude Code, vim, etc.) are exact
// screen snapshots. Locally resizing the mobile xterm after replay can
// mutate the alt buffer and drop cell attributes, which shows as white text.
if (activeAltScreenSnapshot) return;
var cellHeight = getCellHeight();
if (cellHeight > 0 && currentScale > 0) {
var vpHeight = window.innerHeight;
@@ -154,10 +166,56 @@ const XTERM_HTML = `<!DOCTYPE html>
adjustRowsForViewport();
}
function init(cols, rows) {
function isAltScreenActive(data) {
if (typeof data !== 'string') return false;
var on = data.lastIndexOf(ESC + '[?1049h');
var off = data.lastIndexOf(ESC + '[?1049l');
return on !== -1 && on > off;
}
function normalizeInitialData(data) {
if (!isAltScreenActive(data)) return data;
var on = data.lastIndexOf(ESC + '[?1049h');
// Why: SerializeAddon can include normal-buffer scrollback before the
// active alternate-screen snapshot. Replaying both into a fresh mobile
// xterm duplicates TUI frames and can flatten SGR attributes.
return on > 0 ? data.slice(on) : data;
}
function pumpWrites(gen) {
if (!ready || !term || writesDraining || gen !== terminalGeneration) return;
var next = writeQueue.shift();
if (typeof next !== 'string') {
var callbacks = afterDrainCallbacks;
afterDrainCallbacks = [];
for (var i = 0; i < callbacks.length; i++) callbacks[i]();
return;
}
writesDraining = true;
// Why: xterm.write() parses asynchronously. Row adjustment/resizing must
// wait until replayed SGR attributes have landed in the buffer.
term.write(next, function() {
if (gen !== terminalGeneration) return;
writesDraining = false;
pumpWrites(gen);
});
}
function afterWritesDrained(callback) {
afterDrainCallbacks.push(callback);
pumpWrites(terminalGeneration);
}
function init(cols, rows, initialData) {
terminalGeneration++;
var gen = terminalGeneration;
ready = false;
writeQueue = [];
writesDraining = false;
afterDrainCallbacks = [];
initRows = rows || 24;
var replayData = normalizeInitialData(initialData);
activeAltScreenSnapshot = isAltScreenActive(replayData);
if (term) term.dispose();
term = new Terminal({
@@ -197,6 +255,9 @@ const XTERM_HTML = `<!DOCTYPE html>
allowProposedApi: true
});
term.open(surface);
if (typeof replayData === 'string' && replayData.length > 0) {
writeQueue.push(replayData);
}
// Why: prevent taps from being interpreted as cursor positioning or
// mouse-report events by the TUI running in the terminal. On mobile
@@ -337,22 +398,19 @@ const XTERM_HTML = `<!DOCTYPE html>
}, { capture: true, passive: true });
requestAnimationFrame(function() {
if (gen !== terminalGeneration) return;
ready = true;
for (var i = 0; i < writeQueue.length; i++) {
term.write(writeQueue[i]);
}
writeQueue = [];
applyFitScale();
notify({ type: 'ready', cols: cols, rows: rows });
afterWritesDrained(function() {
if (gen !== terminalGeneration) return;
applyFitScale();
notify({ type: 'ready', cols: cols, rows: rows });
});
});
}
function write(data) {
if (ready && term) {
term.write(data);
} else {
writeQueue.push(data);
}
writeQueue.push(data);
pumpWrites(terminalGeneration);
}
function notify(msg) {
@@ -388,12 +446,18 @@ const XTERM_HTML = `<!DOCTYPE html>
}
function handleMsg(msg) {
if (typeof msg.id === 'number') {
if (handledMessageIds.indexOf(msg.id) !== -1) return;
handledMessageIds.push(msg.id);
if (handledMessageIds.length > 256) handledMessageIds.shift();
}
if (msg.type === 'init') {
init(msg.cols, msg.rows);
init(msg.cols, msg.rows, msg.initialData);
} else if (msg.type === 'write') {
write(msg.data);
} else if (msg.type === 'clear') {
writeQueue = [];
afterDrainCallbacks = [];
if (term) { term.clear(); term.reset(); }
} else if (msg.type === 'measure') {
measureFitDimensions();
@@ -430,117 +494,120 @@ const XTERM_HTML = `<!DOCTYPE html>
</body>
</html>`
export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(
function TerminalWebView(_props, ref) {
const webViewRef = useRef<WebView>(null)
const isWebReadyRef = useRef(false)
const pendingMessagesRef = useRef<TerminalMessage[]>([])
const measureResolveRef = useRef<
((result: { cols: number; rows: number } | null) => void) | null
>(null)
export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(function TerminalWebView(
{ style },
ref
) {
const webViewRef = useRef<WebView>(null)
const isWebReadyRef = useRef(false)
const pendingMessagesRef = useRef<TerminalMessage[]>([])
const messageIdRef = useRef(0)
const measureResolveRef = useRef<
((result: { cols: number; rows: number } | null) => void) | null
>(null)
const sendToWebView = useCallback((msg: TerminalMessage) => {
webViewRef.current?.postMessage(JSON.stringify(msg))
}, [])
const sendToWebView = useCallback((msg: TerminalMessage) => {
messageIdRef.current += 1
webViewRef.current?.postMessage(JSON.stringify({ ...msg, id: messageIdRef.current }))
}, [])
const flushPendingMessages = useCallback(() => {
const pending = pendingMessagesRef.current
pendingMessagesRef.current = []
for (const msg of pending) {
sendToWebView(msg)
const flushPendingMessages = useCallback(() => {
const pending = pendingMessagesRef.current
pendingMessagesRef.current = []
for (const msg of pending) {
sendToWebView(msg)
}
}, [sendToWebView])
const postMessage = useCallback(
(msg: TerminalMessage) => {
if (!isWebReadyRef.current) {
pendingMessagesRef.current.push(msg)
return
}
}, [sendToWebView])
sendToWebView(msg)
},
[sendToWebView]
)
const postMessage = useCallback(
(msg: TerminalMessage) => {
if (!isWebReadyRef.current) {
pendingMessagesRef.current.push(msg)
return
const handleMessage = useCallback(
(event: WebViewMessageEvent) => {
let msg: Record<string, unknown>
try {
msg = JSON.parse(event.nativeEvent.data) as Record<string, unknown>
} catch {
return
}
if (msg.type === 'web-ready') {
isWebReadyRef.current = true
flushPendingMessages()
} else if (msg.type === 'measure-result') {
const resolve = measureResolveRef.current
measureResolveRef.current = null
if (resolve) {
const cols = typeof msg.cols === 'number' ? msg.cols : null
const rows = typeof msg.rows === 'number' ? msg.rows : null
resolve(cols && rows && cols >= 20 && rows >= 8 ? { cols, rows } : null)
}
sendToWebView(msg)
}
},
[flushPendingMessages]
)
const handleLoadStart = useCallback(() => {
isWebReadyRef.current = false
}, [])
useImperativeHandle(
ref,
() => ({
write(data: string) {
postMessage({ type: 'write', data })
},
[sendToWebView]
)
const handleMessage = useCallback(
(event: WebViewMessageEvent) => {
let msg: Record<string, unknown>
try {
msg = JSON.parse(event.nativeEvent.data) as Record<string, unknown>
} catch {
return
}
if (msg.type === 'web-ready') {
isWebReadyRef.current = true
flushPendingMessages()
} else if (msg.type === 'measure-result') {
const resolve = measureResolveRef.current
measureResolveRef.current = null
if (resolve) {
const cols = typeof msg.cols === 'number' ? msg.cols : null
const rows = typeof msg.rows === 'number' ? msg.rows : null
resolve(cols && rows && cols >= 20 && rows >= 8 ? { cols, rows } : null)
}
}
init(cols: number, rows: number, initialData?: string) {
postMessage({ type: 'init', cols, rows, initialData })
},
[flushPendingMessages]
)
clear() {
postMessage({ type: 'clear' })
},
measureFitDimensions(): Promise<{ cols: number; rows: number } | null> {
if (!isWebReadyRef.current) return Promise.resolve(null)
return new Promise((resolve) => {
measureResolveRef.current = resolve
sendToWebView({ type: 'measure' })
// Why: if the WebView doesn't respond within 2s (e.g., xterm
// failed to load), resolve null so the caller can disable
// Fit to Phone rather than hanging indefinitely.
setTimeout(() => {
if (measureResolveRef.current === resolve) {
measureResolveRef.current = null
resolve(null)
}
}, 2000)
})
},
resetZoom() {
postMessage({ type: 'reset-zoom' })
}
}),
[postMessage, sendToWebView]
)
const handleLoadStart = useCallback(() => {
isWebReadyRef.current = false
}, [])
useImperativeHandle(
ref,
() => ({
write(data: string) {
postMessage({ type: 'write', data })
},
init(cols: number, rows: number) {
postMessage({ type: 'init', cols, rows })
},
clear() {
postMessage({ type: 'clear' })
},
measureFitDimensions(): Promise<{ cols: number; rows: number } | null> {
if (!isWebReadyRef.current) return Promise.resolve(null)
return new Promise((resolve) => {
measureResolveRef.current = resolve
sendToWebView({ type: 'measure' })
// Why: if the WebView doesn't respond within 2s (e.g., xterm
// failed to load), resolve null so the caller can disable
// Fit to Phone rather than hanging indefinitely.
setTimeout(() => {
if (measureResolveRef.current === resolve) {
measureResolveRef.current = null
resolve(null)
}
}, 2000)
})
},
resetZoom() {
postMessage({ type: 'reset-zoom' })
}
}),
[postMessage, sendToWebView]
)
return (
<WebView
ref={webViewRef}
source={{ html: XTERM_HTML }}
style={styles.webview}
originWhitelist={['*']}
javaScriptEnabled
scrollEnabled={true}
scalesPageToFit={false}
onLoadStart={handleLoadStart}
onMessage={handleMessage}
/>
)
}
)
return (
<WebView
ref={webViewRef}
source={{ html: XTERM_HTML }}
style={[styles.webview, style]}
originWhitelist={['*']}
javaScriptEnabled
scrollEnabled={true}
scalesPageToFit={false}
onLoadStart={handleLoadStart}
onMessage={handleMessage}
/>
)
})
const styles = StyleSheet.create({
webview: {
+26 -12
View File
@@ -12,16 +12,24 @@ nacl.setPRNG((_x: Uint8Array, n: number) => {
_x.set(bytes)
})
export function generateKeyPair(): nacl.BoxKeyPair {
return nacl.box.keyPair()
// Why: tweetnacl uses `instanceof Uint8Array` checks internally. On Hermes,
// values from native modules (expo-crypto), TextEncoder, or typed array
// operations can return objects that fail this check despite being
// functionally identical. Wrapping with `new Uint8Array(x)` guarantees
// the correct prototype chain.
function u8(x: Uint8Array): Uint8Array {
return new Uint8Array(x)
}
export function generateKeyPair(): { publicKey: Uint8Array; secretKey: Uint8Array } {
const kp = nacl.box.keyPair()
return { publicKey: u8(kp.publicKey), secretKey: u8(kp.secretKey) }
}
export function deriveSharedKey(ourSecretKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array {
return nacl.box.before(peerPublicKey, ourSecretKey)
return u8(nacl.box.before(u8(peerPublicKey), u8(ourSecretKey)))
}
// Why: React Native doesn't have Node's Buffer. Use atob/btoa which are
// available in the Hermes JS engine.
function uint8ToBase64(bytes: Uint8Array): string {
let binary = ''
for (let i = 0; i < bytes.length; i++) {
@@ -40,7 +48,13 @@ function base64ToUint8(b64: string): Uint8Array {
}
export function publicKeyFromBase64(b64: string): Uint8Array {
return base64ToUint8(b64)
const key = base64ToUint8(b64)
if (key.length !== 32) {
throw new Error(
`Invalid public key: expected 32 bytes, got ${key.length} from "${b64.slice(0, 20)}..."`
)
}
return key
}
export function publicKeyToBase64(key: Uint8Array): string {
@@ -48,9 +62,9 @@ export function publicKeyToBase64(key: Uint8Array): string {
}
export function encrypt(plaintext: string, sharedKey: Uint8Array): string {
const nonce = nacl.randomBytes(nacl.box.nonceLength)
const messageBytes = new TextEncoder().encode(plaintext)
const ciphertext = nacl.box.after(messageBytes, nonce, sharedKey)
const nonce = u8(nacl.randomBytes(nacl.box.nonceLength))
const messageBytes = u8(new TextEncoder().encode(plaintext))
const ciphertext = nacl.box.after(messageBytes, nonce, u8(sharedKey))
const bundle = new Uint8Array(nonce.length + ciphertext.length)
bundle.set(nonce)
@@ -65,9 +79,9 @@ export function decrypt(encrypted: string, sharedKey: Uint8Array): string | null
return null
}
const nonce = new Uint8Array(bundle.subarray(0, nacl.box.nonceLength))
const ciphertext = new Uint8Array(bundle.subarray(nacl.box.nonceLength))
const plaintext = nacl.box.open.after(ciphertext, nonce, sharedKey)
const nonce = u8(bundle.subarray(0, nacl.box.nonceLength))
const ciphertext = u8(bundle.subarray(nacl.box.nonceLength))
const plaintext = nacl.box.open.after(ciphertext, nonce, u8(sharedKey))
if (!plaintext) {
return null
+7 -2
View File
@@ -147,8 +147,13 @@ export function connect(
return
}
// Why: post-handshake, all messages are encrypted. Decrypt before processing.
const plaintext = decrypt(raw, sharedKey!)
// Why: guard against decrypt with an invalid key — sharedKey can be null
// after destroy() or if a message arrives during a reconnect race.
if (!sharedKey || sharedKey.length !== 32) {
return
}
const plaintext = decrypt(raw, sharedKey)
if (plaintext === null) {
return
}
+6 -2
View File
@@ -9,6 +9,10 @@ export type HeadlessEmulatorOptions = {
scrollback?: number
}
export type HeadlessSnapshotOptions = {
scrollbackRows?: number
}
const DEFAULT_SCROLLBACK = 5000
function parseFileUriPath(uri: string): string | null {
@@ -87,10 +91,10 @@ export class HeadlessEmulator {
this.terminal.resize(cols, rows)
}
getSnapshot(): TerminalSnapshot {
getSnapshot(opts: HeadlessSnapshotOptions = {}): TerminalSnapshot {
const modes = this.getModes()
return {
snapshotAnsi: this.serializer.serialize(),
snapshotAnsi: this.serializer.serialize({ scrollback: opts.scrollbackRows }),
scrollbackAnsi: '',
rehydrateSequences: this.buildRehydrateSequences(modes),
cwd: this.cwd,
+10 -9
View File
@@ -729,20 +729,21 @@ export function registerPtyHandlers(
if (effectiveShellOverride !== undefined) {
spawnOptions.shellOverride = effectiveShellOverride
}
if (effectiveSessionId !== undefined) {
// Why: daemon PTYs can emit prompt/startup bytes before spawn()
// resolves. Runtime headless snapshots need the real pane geometry
// for those early bytes; otherwise they default to 80x24 and wrap TUIs.
ptySizes.set(effectiveSessionId, { cols: args.cols, rows: args.rows })
}
let result: PtySpawnResult
try {
result = await provider.spawn(spawnOptions)
} catch (err) {
if (effectiveSessionId !== undefined) {
ptySizes.delete(effectiveSessionId)
}
// Why: when buildPtyHostEnv materialized a Pi overlay for this id
// but provider.spawn failed, the overlay would leak. Sweep per-PTY
// state for the minted id so it isn't orphaned. Safe to call even
// when no overlay was created (clearProviderPtyState is a no-op in
// that case).
//
// Only clean up when we MINTED the id in this request. Caller-supplied
// ids may correspond to existing PTYs whose state (OpenCode hooks, Pi
// overlay, agent-hook pane caches) we MUST NOT clear on a retry/attach
// failure.
// but provider.spawn failed, the overlay would leak.
if (isMintedSessionId && effectiveSessionId !== undefined) {
clearProviderPtyState(effectiveSessionId)
}
+90
View File
@@ -379,6 +379,96 @@ describe('OrcaRuntimeService', () => {
expect(writes).toEqual(['continue', '\r'])
})
it('serializes terminal state from runtime-tracked PTY output when renderer has no buffer', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
write: () => true,
kill: () => true,
getSize: () => ({ cols: 100, rows: 30 }),
serializeBuffer: vi.fn().mockResolvedValue(null)
})
runtime.onPtyData('pty-1', '\x1b[31mred text\x1b[0m\n', 123)
const serialized = await runtime.serializeTerminalBuffer('pty-1')
expect(serialized).toMatchObject({ cols: 100, rows: 30 })
expect(serialized?.data).toContain('red text')
expect(serialized?.data).toContain('[31m')
})
it('prefers runtime-tracked screen snapshots over renderer scrollback snapshots', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
write: () => true,
kill: () => true,
getSize: () => ({ cols: 100, rows: 30 }),
serializeBuffer: vi.fn().mockResolvedValue({
data: 'renderer scrollback that should not win',
cols: 100,
rows: 30
})
})
runtime.onPtyData('pty-1', '\x1b[32mruntime screen\x1b[0m\n', 123)
const serialized = await runtime.serializeTerminalBuffer('pty-1')
expect(serialized?.data).toContain('runtime screen')
expect(serialized?.data).not.toContain('renderer scrollback')
})
it('does not list renderer placeholder leaves alongside live PTY fallback terminals', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
write: () => true,
kill: () => true,
listProcesses: vi.fn().mockResolvedValue([
{ id: 'pty-1', cwd: '/tmp/worktree-a', title: 'setup' },
{ id: 'pty-2', cwd: '/tmp/worktree-a', title: 'Claude Code' }
])
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-setup',
worktreeId: 'repo-1::/tmp/worktree-a',
title: 'setup',
activeLeafId: 'pane:1',
layout: null
},
{
tabId: 'tab-claude',
worktreeId: 'repo-1::/tmp/worktree-a',
title: 'Claude Code',
activeLeafId: 'pane:2',
layout: null
}
],
leaves: [
{
tabId: 'tab-setup',
worktreeId: 'repo-1::/tmp/worktree-a',
leafId: 'pane:1',
paneRuntimeId: 1,
ptyId: null
},
{
tabId: 'tab-claude',
worktreeId: 'repo-1::/tmp/worktree-a',
leafId: 'pane:2',
paneRuntimeId: 2,
ptyId: null
}
]
})
const terminals = await runtime.listTerminals('branch:feature/foo')
expect(terminals.terminals).toHaveLength(2)
expect(terminals.terminals.every((terminal) => terminal.connected)).toBe(true)
expect(new Set(terminals.terminals.map((terminal) => terminal.handle)).size).toBe(2)
})
it('waits for terminal exit and resolves with the exit status', async () => {
const runtime = new OrcaRuntimeService(store)
+113 -6
View File
@@ -14,7 +14,7 @@ import { join } from 'path'
import { rm } from 'fs/promises'
import { OrchestrationDb } from './orchestration/db'
import { formatMessagesForInjection } from './orchestration/formatter'
import type { CreateWorktreeResult, Repo } from '../../shared/types'
import type { CreateWorktreeResult, Repo, WorktreeStartupLaunch } from '../../shared/types'
import { isFolderRepo } from '../../shared/repo-kind'
import type {
RuntimeGraphStatus,
@@ -106,6 +106,7 @@ import {
areWorktreePathsEqual
} from '../ipc/worktree-logic'
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
import { HeadlessEmulator } from '../daemon/headless-emulator'
type RuntimeStore = {
getRepos: Store['getRepos']
@@ -153,6 +154,11 @@ type RuntimePtyWorktreeRecord = {
preview: string
}
type RuntimeHeadlessTerminal = {
emulator: HeadlessEmulator
writeChain: Promise<void>
}
type RuntimePtyController = {
write(ptyId: string, data: string): boolean
kill(ptyId: string): boolean
@@ -166,7 +172,12 @@ type RuntimePtyController = {
type RuntimeNotifier = {
worktreesChanged(repoId: string): void
reposChanged(): void
activateWorktree(repoId: string, worktreeId: string, setup?: CreateWorktreeResult['setup']): void
activateWorktree(
repoId: string,
worktreeId: string,
setup?: CreateWorktreeResult['setup'],
startup?: WorktreeStartupLaunch
): void
createTerminal(worktreeId: string, opts: { command?: string; title?: string }): void
splitTerminal(
tabId: string,
@@ -271,6 +282,7 @@ export class OrcaRuntimeService {
private dataListeners = new Map<string, Set<(data: string) => void>>()
private subscriptionCleanups = new Map<string, () => void>()
private ptysById = new Map<string, RuntimePtyWorktreeRecord>()
private headlessTerminals = new Map<string, RuntimeHeadlessTerminal>()
// Why: mobile-fit overrides are keyed by ptyId (not terminal handle) because
// handles can be reissued while the PTY identity is stable. In-memory only —
// a stale phone override should not survive an app restart.
@@ -503,6 +515,7 @@ export class OrcaRuntimeService {
// Agent detection runs on raw data before leaf processing, since the
// tail buffer logic normalizes away the OSC sequences we need.
this.agentDetector?.onData(ptyId, data, at)
this.trackHeadlessTerminalData(ptyId, data)
// Why: extract OSC title from raw PTY data before tail-buffer processing
// strips the escape sequences. Agent CLIs (Claude Code, Gemini, etc.)
@@ -584,13 +597,89 @@ export class OrcaRuntimeService {
serializeTerminalBuffer(
ptyId: string
): Promise<{ data: string; cols: number; rows: number } | null> {
return this.ptyController?.serializeBuffer?.(ptyId) ?? Promise.resolve(null)
return this.serializeTerminalBufferFromAvailableState(ptyId)
}
getTerminalSize(ptyId: string): { cols: number; rows: number } | null {
return this.ptyController?.getSize?.(ptyId) ?? null
}
private trackHeadlessTerminalData(ptyId: string, data: string): void {
const state = this.getOrCreateHeadlessTerminal(ptyId)
state.writeChain = state.writeChain
.then(() => state.emulator.write(data))
.catch(() => {
// Best-effort state tracking; live streaming must continue even if
// xterm rejects a malformed or raced write during shutdown.
})
}
private getOrCreateHeadlessTerminal(ptyId: string): RuntimeHeadlessTerminal {
const existing = this.headlessTerminals.get(ptyId)
if (existing) {
return existing
}
const size = this.getTerminalSize(ptyId) ?? { cols: 80, rows: 24 }
const state: RuntimeHeadlessTerminal = {
emulator: new HeadlessEmulator({ cols: size.cols, rows: size.rows }),
writeChain: Promise.resolve()
}
this.headlessTerminals.set(ptyId, state)
return state
}
private resizeHeadlessTerminal(ptyId: string, cols: number, rows: number): void {
this.headlessTerminals.get(ptyId)?.emulator.resize(cols, rows)
}
private async serializeTerminalBufferFromAvailableState(
ptyId: string
): Promise<{ data: string; cols: number; rows: number } | null> {
const headlessSnapshot = await this.serializeHeadlessTerminalBuffer(ptyId)
if (headlessSnapshot) {
return headlessSnapshot
}
let rendererSnapshot: { data: string; cols: number; rows: number } | null = null
try {
rendererSnapshot = await (this.ptyController?.serializeBuffer?.(ptyId) ??
Promise.resolve(null))
} catch {
// Why: mobile scrollback should not depend on a mounted renderer pane.
// If renderer serialization races reload/unmount, the runtime snapshot
// below can still preserve colored terminal state.
}
if (rendererSnapshot && rendererSnapshot.data.length > 0) {
return rendererSnapshot
}
return rendererSnapshot
}
private async serializeHeadlessTerminalBuffer(
ptyId: string
): Promise<{ data: string; cols: number; rows: number } | null> {
const state = this.headlessTerminals.get(ptyId)
if (!state) {
return null
}
await state.writeChain
// Why: terminal.subscribe needs the current visible screen, not the full
// launch history. Full scrollback plus a normal-buffer TUI can replay the
// shell prompt and active TUI frame together, which looks duplicated.
const snapshot = state.emulator.getSnapshot({ scrollbackRows: 0 })
const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi
return data.length > 0 ? { data, cols: snapshot.cols, rows: snapshot.rows } : null
}
private disposeHeadlessTerminal(ptyId: string): void {
const state = this.headlessTerminals.get(ptyId)
if (!state) {
return
}
this.headlessTerminals.delete(ptyId)
state.writeChain.finally(() => state.emulator.dispose()).catch(() => state.emulator.dispose())
}
resolveLeafForHandle(handle: string): { ptyId: string | null } | null {
const record = this.handles.get(handle)
if (!record) {
@@ -662,6 +751,7 @@ export class OrcaRuntimeService {
this.terminalFitOverrides.delete(ptyId)
throw new Error('resize_failed')
}
this.resizeHeadlessTerminal(ptyId, clampedCols, clampedRows)
this.notifier?.terminalFitOverrideChanged(ptyId, 'mobile-fit', clampedCols, clampedRows)
@@ -697,6 +787,7 @@ export class OrcaRuntimeService {
// current pane geometry, which is harmless (SIGWINCH is idempotent).
if (prevCols != null && prevRows != null) {
this.ptyController?.resize?.(ptyId, prevCols, prevRows)
this.resizeHeadlessTerminal(ptyId, prevCols, prevRows)
}
// Why: send the restored dimensions so the renderer can fall back to a
@@ -746,6 +837,7 @@ export class OrcaRuntimeService {
this.terminalFitOverrides.delete(ptyId)
this.notifier?.terminalFitOverrideChanged(ptyId, 'desktop-fit', 0, 0)
}
this.disposeHeadlessTerminal(ptyId)
this.agentDetector?.onExit(ptyId)
const pty = this.ptysById.get(ptyId)
if (pty) {
@@ -821,20 +913,31 @@ export class OrcaRuntimeService {
const worktreesById = await this.getResolvedWorktreeMap()
this.assertStableReadyGraph(graphEpoch)
const resolvedWorktrees = [...worktreesById.values()]
await this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees)
const livePtyWorktreeIds = new Set<string>()
for (const pty of this.ptysById.values()) {
if (pty.connected) {
livePtyWorktreeIds.add(pty.worktreeId)
}
}
const terminals: RuntimeTerminalSummary[] = []
const ptyIdsFromLeaves = new Set<string>()
for (const leaf of this.leaves.values()) {
if (targetWorktreeId && leaf.worktreeId !== targetWorktreeId) {
continue
}
if (!leaf.ptyId && livePtyWorktreeIds.has(leaf.worktreeId)) {
continue
}
if (leaf.ptyId) {
ptyIdsFromLeaves.add(leaf.ptyId)
}
terminals.push(this.buildTerminalSummary(leaf, worktreesById))
}
const resolvedWorktrees = [...worktreesById.values()]
await this.refreshPtyWorktreeRecordsFromController(resolvedWorktrees)
// Why: worktree.ps can classify active worktrees from PTY records even when
// the renderer graph is missing a leaf. terminal.list needs the same fallback
// so mobile does not show a false "No terminals" create flow.
@@ -1492,7 +1595,11 @@ export class OrcaRuntimeService {
// renderer-side consequence of activating a worktree. CLI-created
// worktrees must trigger that same activation path or they will exist on
// disk without becoming the active workspace in the UI.
this.notifier?.activateWorktree(repo.id, worktree.id, setup)
if (args.startup) {
this.notifier?.activateWorktree(repo.id, worktree.id, setup, args.startup)
} else {
this.notifier?.activateWorktree(repo.id, worktree.id, setup)
}
this.invalidateResolvedWorktreeCache()
// Why: the filesystem-auth layer maintains a separate cache of registered
// worktree roots used by git IPC handlers (branchCompare, diff, status, etc.)
+13 -3
View File
@@ -4,7 +4,7 @@ import path from 'node:path'
import { app, clipboard, ipcMain, nativeImage, session, systemPreferences } from 'electron'
import type { BrowserWindow, MediaAccessPermissionRequest } from 'electron'
import type { Store } from '../persistence'
import type { CreateWorktreeResult } from '../../shared/types'
import type { CreateWorktreeResult, WorktreeStartupLaunch } from '../../shared/types'
import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
import { registerRepoHandlers } from '../ipc/repos'
import { registerWorktreeHandlers } from '../ipc/worktrees'
@@ -211,9 +211,19 @@ function registerRuntimeWindowLifecycle(
mainWindow.webContents.send('repos:changed')
}
},
activateWorktree: (repoId, worktreeId, setup?: CreateWorktreeResult['setup']) => {
activateWorktree: (
repoId,
worktreeId,
setup?: CreateWorktreeResult['setup'],
startup?: WorktreeStartupLaunch
) => {
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('ui:activateWorktree', { repoId, worktreeId, setup })
mainWindow.webContents.send('ui:activateWorktree', {
repoId,
worktreeId,
...(setup ? { setup } : {}),
...(startup ? { startup } : {})
})
}
},
createTerminal: (worktreeId, opts) => {
+7 -1
View File
@@ -54,6 +54,7 @@ import type {
Worktree,
WorktreeMeta,
WorktreeSetupLaunch,
WorktreeStartupLaunch,
WorkspaceSessionState
} from '../shared/types'
import type {
@@ -788,7 +789,12 @@ export type PreloadApi = {
onToggleStatusBar: (callback: () => void) => () => void
onExportPdfRequested: (callback: () => void) => () => void
onActivateWorktree: (
callback: (data: { repoId: string; worktreeId: string; setup?: WorktreeSetupLaunch }) => void
callback: (data: {
repoId: string
worktreeId: string
setup?: WorktreeSetupLaunch
startup?: WorktreeStartupLaunch
}) => void
) => () => void
onCreateTerminal: (
callback: (data: { worktreeId: string; command?: string; title?: string }) => void
+2
View File
@@ -1407,6 +1407,7 @@ const api = {
repoId: string
worktreeId: string
setup?: { runnerScriptPath: string; envVars: Record<string, string> }
startup?: { command: string; env?: Record<string, string> }
}) => void
): (() => void) => {
const listener = (
@@ -1415,6 +1416,7 @@ const api = {
repoId: string
worktreeId: string
setup?: { runnerScriptPath: string; envVars: Record<string, string> }
startup?: { command: string; env?: Record<string, string> }
}
) => callback(data)
ipcRenderer.on('ui:activateWorktree', listener)
@@ -3,7 +3,8 @@
// serialize functions keyed by ptyId, and handles IPC requests from the
// main process to serialize a specific terminal's buffer.
type SerializeFn = () => { data: string; cols: number; rows: number } | null
type SerializedBuffer = { data: string; cols: number; rows: number }
type SerializeFn = () => SerializedBuffer | null | Promise<SerializedBuffer | null>
const serializersByPtyId = new Map<string, SerializeFn>()
let listenerAttached = false
@@ -24,7 +25,12 @@ function ensureSerializerListener(): void {
window.api.pty.onSerializeBufferRequest((request) => {
const serializer = serializersByPtyId.get(request.ptyId)
const result = serializer?.()
window.api.pty.sendSerializedBuffer(request.requestId, result ?? null)
void Promise.resolve(serializer?.() ?? null)
.then((result) => {
window.api.pty.sendSerializedBuffer(request.requestId, result ?? null)
})
.catch(() => {
window.api.pty.sendSerializedBuffer(request.requestId, null)
})
})
}
@@ -236,7 +236,8 @@ describe('connectPanePty', () => {
},
pty: {
signal: vi.fn(),
ackColdRestore: vi.fn()
ackColdRestore: vi.fn(),
onSerializeBufferRequest: vi.fn(() => vi.fn())
},
notifications: {
dispatch: vi.fn()
@@ -11,7 +11,7 @@ import { shouldSeedCacheTimerOnInitialTitle } from './cache-timer-seeding'
import type { PtyConnectionDeps } from './pty-connection-types'
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
import { getFitOverrideForPane, bindPanePtyId } from '@/lib/pane-manager/mobile-fit-overrides'
import { isPaneReplaying, replayIntoTerminal } from './replay-guard'
import { isPaneReplaying, replayIntoTerminal, replayIntoTerminalAsync } from './replay-guard'
import {
paneLeafId,
POST_REPLAY_MODE_RESET,
@@ -564,8 +564,16 @@ export function connectPanePty(
// Why: mobile terminal streaming needs the exact screen state from
// xterm.js. Register a serializer for this ptyId so the main process
// can request a buffer snapshot when a mobile client subscribes.
const unregisterSerializer = registerPtySerializer(ptyId, () => {
const unregisterSerializer = registerPtySerializer(ptyId, async () => {
try {
const pending = deps.pendingWritesRef.current.get(pane.id)
if (pending) {
deps.pendingWritesRef.current.set(pane.id, '')
// Why: hidden/background panes buffer PTY output instead of writing
// to xterm. Mobile snapshots must include that pending output, and
// replay guard prevents xterm query auto-replies from hitting stdin.
await replayIntoTerminalAsync(pane, deps.replayingPanesRef, pending)
}
return {
data: pane.serializeAddon.serialize(),
cols: pane.terminal.cols,
@@ -53,3 +53,26 @@ export function replayIntoTerminal(
}
})
}
export function replayIntoTerminalAsync(
pane: ManagedPane,
replayingPanesRef: ReplayingPanesRef,
data: string
): Promise<void> {
if (!data) {
return Promise.resolve()
}
const map = replayingPanesRef.current
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
return new Promise((resolve) => {
pane.terminal.write(data, () => {
const remaining = (map.get(pane.id) ?? 1) - 1
if (remaining <= 0) {
map.delete(pane.id)
} else {
map.set(pane.id, remaining)
}
resolve()
})
})
}
@@ -199,6 +199,10 @@ describe('useIpcEvents updater integration', () => {
get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }),
onUpdate: () => () => {}
},
runtime: {
getTerminalFitOverrides: () => Promise.resolve([]),
onTerminalFitOverrideChanged: () => () => {}
},
ssh: {
listTargets: () => Promise.resolve([]),
listPortForwards: () => Promise.resolve([]),
@@ -386,6 +390,10 @@ describe('useIpcEvents updater integration', () => {
get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }),
onUpdate: () => () => {}
},
runtime: {
getTerminalFitOverrides: () => Promise.resolve([]),
onTerminalFitOverrideChanged: () => () => {}
},
ssh: {
listTargets: () => Promise.resolve([]),
listPortForwards: () => Promise.resolve([]),
@@ -574,6 +582,10 @@ describe('useIpcEvents updater integration', () => {
get: () => Promise.resolve({ limits: {}, lastUpdatedAt: Date.now() }),
onUpdate: () => () => {}
},
runtime: {
getTerminalFitOverrides: () => Promise.resolve([]),
onTerminalFitOverrideChanged: () => () => {}
},
ssh: {
listTargets: () => Promise.resolve([]),
listPortForwards: () => Promise.resolve([]),
+1 -1
View File
@@ -169,7 +169,7 @@ export function useIpcEvents(): void {
)
unsubs.push(
window.api.ui.onActivateWorktree(({ repoId, worktreeId, setup }) => {
window.api.ui.onActivateWorktree(({ repoId, worktreeId, setup, startup }) => {
void (async () => {
// Why: fetch worktrees first so the activation helper can resolve
// the CLI-created worktree via findWorktreeById — it arrived from
+5
View File
@@ -688,6 +688,11 @@ export type SparsePreset = {
updatedAt: number
}
export type WorktreeStartupLaunch = {
command: string
env?: Record<string, string>
}
export type CreateWorktreeArgs = {
repoId: string
name: string