diff --git a/mobile/.oxlintrc.json b/mobile/.oxlintrc.json index 5b0c202ea..b4b5ef57f 100644 --- a/mobile/.oxlintrc.json +++ b/mobile/.oxlintrc.json @@ -28,19 +28,19 @@ { "files": ["src/terminal/TerminalWebView.tsx"], "rules": { - "max-lines": ["error", { "max": 369, "skipBlankLines": true, "skipComments": true }] + "max-lines": ["error", { "max": 379, "skipBlankLines": true, "skipComments": true }] } }, { "files": ["src/terminal/terminal-webview-html.ts"], "rules": { - "max-lines": ["error", { "max": 1773, "skipBlankLines": true, "skipComments": true }] + "max-lines": ["error", { "max": 1778, "skipBlankLines": true, "skipComments": true }] } }, { "files": ["app/h/*/source-control/*.tsx"], "rules": { - "max-lines": ["error", { "max": 2004, "skipBlankLines": true, "skipComments": true }] + "max-lines": ["error", { "max": 2152, "skipBlankLines": true, "skipComments": true }] } }, { @@ -58,7 +58,7 @@ { "files": ["app/index.tsx"], "rules": { - "max-lines": ["error", { "max": 1419, "skipBlankLines": true, "skipComments": true }] + "max-lines": ["error", { "max": 1422, "skipBlankLines": true, "skipComments": true }] } }, { diff --git a/mobile/app.json b/mobile/app.json index 1381fc041..211bb7703 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -2,7 +2,7 @@ "expo": { "name": "Orca", "slug": "orca-mobile", - "version": "0.0.13", + "version": "0.0.14", "orientation": "default", "icon": "./assets/icon.png", "userInterfaceStyle": "automatic", @@ -16,10 +16,11 @@ "ios": { "supportsTablet": true, "bundleIdentifier": "com.stably.orca.mobile", - "buildNumber": "2", + "buildNumber": "1", "infoPlist": { "NSLocalNetworkUsageDescription": "Orca connects to the desktop app on your local network.", "NSMicrophoneUsageDescription": "Allow Orca to record voice dictation and transcribe it on your paired desktop.", + "NSPhotoLibraryUsageDescription": "Allow Orca to attach photos from your library to a terminal session on your paired desktop.", "NSAppTransportSecurity": { "NSAllowsLocalNetworking": true, "NSExceptionDomains": { @@ -94,6 +95,12 @@ "recordAudioAndroid": false } ], + [ + "expo-image-picker", + { + "photosPermission": "Allow Orca to attach photos from your library to a terminal session on your paired desktop." + } + ], [ "expo-build-properties", { diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 4572790c9..bb4042157 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -165,6 +165,7 @@ export default function RootLayout() { + diff --git a/mobile/app/h/[hostId]/history/[worktreeId].tsx b/mobile/app/h/[hostId]/history/[worktreeId].tsx new file mode 100644 index 000000000..8ac0eb8a8 --- /dev/null +++ b/mobile/app/h/[hostId]/history/[worktreeId].tsx @@ -0,0 +1,207 @@ +import { useCallback, useEffect, useState } from 'react' +import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native' +import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' +import { useLocalSearchParams, useRouter } from 'expo-router' +import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react-native' +import { useHostClient } from '../../../../src/transport/client-context' +import type { RpcSuccess } from '../../../../src/transport/types' +import { colors, spacing, typography } from '../../../../src/theme/mobile-theme' +import { + fetchMobileGitHistory, + mapMobileCommitRows, + type MobileCommitRow +} from '../../../../src/source-control/mobile-git-history' +import type { GitBranchChangeEntry } from '../../../../../src/shared/types' + +function firstParam(value: string | string[] | undefined): string { + return Array.isArray(value) ? (value[0] ?? '') : (value ?? '') +} + +export default function HistoryScreen() { + const params = useLocalSearchParams<{ + hostId?: string | string[] + worktreeId?: string | string[] + }>() + const hostId = firstParam(params.hostId) + const worktreeId = firstParam(params.worktreeId) + const router = useRouter() + const insets = useSafeAreaInsets() + const { client, state: connState } = useHostClient(hostId) + + const [rows, setRows] = useState(null) + const [error, setError] = useState(null) + const [expanded, setExpanded] = useState(null) + const [filesById, setFilesById] = useState>({}) + + useEffect(() => { + let active = true + if (!client || connState !== 'connected' || !worktreeId) { + return + } + // Reset prior error/rows so a successful retry doesn't stay stuck behind a + // stale error (error wins render precedence). + setError(null) + setRows(null) + void (async () => { + try { + const result = await fetchMobileGitHistory(client, worktreeId) + if (active) { + setRows(mapMobileCommitRows(result, Date.now())) + } + } catch (err) { + if (active) { + setError(err instanceof Error ? err.message : 'Failed to load history') + } + } + })() + return () => { + active = false + } + }, [client, connState, worktreeId]) + + const toggleCommit = useCallback( + (row: MobileCommitRow) => { + const next = expanded === row.id ? null : row.id + setExpanded(next) + if (next && client && !filesById[row.id]) { + setFilesById((prev) => ({ ...prev, [row.id]: 'loading' })) + void client + .sendRequest('git.commitCompare', { worktree: `id:${worktreeId}`, commitId: row.id }) + .then((response) => { + const entries = response.ok + ? ((response as RpcSuccess).result as { entries: GitBranchChangeEntry[] }).entries + : [] + setFilesById((prev) => ({ ...prev, [row.id]: entries })) + }) + .catch(() => setFilesById((prev) => ({ ...prev, [row.id]: [] }))) + } + }, + [client, expanded, filesById, worktreeId] + ) + + const renderCommit = useCallback( + ({ item }: { item: MobileCommitRow }) => { + const files = filesById[item.id] + const isOpen = expanded === item.id + return ( + + [styles.commitHeader, pressed && styles.commitHeaderPressed]} + onPress={() => toggleCommit(item)} + > + {isOpen ? ( + + ) : ( + + )} + + + {item.subject} + + + {item.shortId} · {item.author} · {item.relativeTime} + + + + {isOpen ? ( + + {files === 'loading' || files === undefined ? ( + + ) : files.length === 0 ? ( + No file changes + ) : ( + files.map((file) => ( + + + {file.path} + + + {file.added ? +{file.added} : null} + {file.removed ? -{file.removed} : null} + + + )) + )} + + ) : null} + + ) + }, + [expanded, filesById, toggleCommit] + ) + + return ( + + + router.back()} accessibilityLabel="Back"> + + + Commit History + + {error ? ( + + {error} + + ) : rows === null ? ( + + + + ) : rows.length === 0 ? ( + + No commits. + + ) : ( + row.id} + contentContainerStyle={{ paddingBottom: spacing.lg + insets.bottom }} + /> + )} + + ) +} + +const styles = StyleSheet.create({ + container: { flex: 1, backgroundColor: colors.bgBase }, + header: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + gap: spacing.sm + }, + back: { padding: spacing.xs }, + title: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' }, + state: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.lg }, + stateText: { color: colors.textMuted, fontSize: typography.bodySize }, + commit: { borderBottomWidth: 1, borderBottomColor: colors.borderSubtle }, + commitHeader: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm + 2 + }, + commitHeaderPressed: { backgroundColor: colors.bgRaised }, + commitMain: { flex: 1, minWidth: 0 }, + commitSubject: { color: colors.textPrimary, fontSize: typography.bodySize }, + commitMeta: { + color: colors.textMuted, + fontSize: typography.metaSize, + fontFamily: typography.monoFamily, + marginTop: 2 + }, + files: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm, gap: 4 }, + fileRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + filePath: { + flex: 1, + color: colors.textSecondary, + fontSize: typography.metaSize, + fontFamily: typography.monoFamily + }, + fileStat: { fontSize: typography.metaSize, fontFamily: typography.monoFamily }, + add: { color: colors.gitDecorationAdded }, + del: { color: colors.gitDecorationDeleted }, + empty: { color: colors.textMuted, fontSize: typography.metaSize } +}) diff --git a/mobile/app/h/[hostId]/index.tsx b/mobile/app/h/[hostId]/index.tsx index e271c64a2..3ee2c1cbb 100644 --- a/mobile/app/h/[hostId]/index.tsx +++ b/mobile/app/h/[hostId]/index.tsx @@ -14,9 +14,7 @@ import { Search, X, Pin, - Bell, GitBranch, - GitPullRequest, List, SlidersHorizontal, Layers, @@ -43,10 +41,13 @@ import { type ConnectionVerdict } from '../../../src/transport/connection-health' import type { 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' +import { MobileRepoIcon } from '../../../src/components/MobileRepoIcon' +import { WorktreeListRow } from '../../../src/components/WorktreeListRow' +import { useNow } from '../../../src/hooks/use-now' +import { useActiveWorktreeScroll } from '../../../src/hooks/use-active-worktree-scroll' +import type { RepoIcon } from '../../../../src/shared/repo-icon' import { PickerModal, type PickerOption } from '../../../src/components/PickerModal' import { ActionSheetContent } from '../../../src/components/ActionSheetModal' import { ConfirmModal } from '../../../src/components/ConfirmModal' @@ -57,17 +58,27 @@ import { getCachedWorktrees } from '../../../src/cache/worktree-cache' import { colors, radii, spacing, typography } from '../../../src/theme/mobile-theme' import { useResponsiveLayout } from '../../../src/layout/responsive-layout' import { evaluateCompat, type CompatVerdict } from '../../../src/transport/protocol-compat' -import { - loadPinnedIds, - savePinnedIds, - loadPreferences, - savePreferences -} from '../../../src/storage/preferences' +import { loadPinnedIds, savePinnedIds } from '../../../src/storage/preferences' import { createInitialHostRouteActionState, resolveHostRouteActionState, setHostRouteNewWorktreeVisible } from '../../../src/host-route-action-state' +import { + applyDesktopViewSettings, + groupModeToDesktop, + type MobileGroupMode, + type MobileSortMode, + type MobileViewState, + type WorkspaceViewSettings +} from '../../../src/worktree/workspace-view-settings' +import { + buildSections, + getWorktreeStatus, + isWorktreePinned, + type FilterState, + type Worktree +} from '../../../src/worktree/workspace-list-sections' // Why: locally-typed subset of the desktop's RuntimeStatus we read from // `status.get`. Only the version fields matter to mobile today; everything @@ -78,268 +89,34 @@ type DesktopStatus = { minCompatibleMobileVersion?: number } -type Worktree = { - worktreeId: string - repo: string - branch: string - displayName: string - // Why: on-disk worktree directory path. Needed by NewWorktreeModal so the - // marine-creature fallback dedupes against the actual filesystem basenames - // (matching the desktop's collision check), not against displayName which - // the user may have renamed. - path: string - liveTerminalCount: number - hasAttachedPty: boolean - preview: string - unread: boolean - lastOutputAt?: number - isPinned: boolean - linkedPR: { number: number; state: string } | null - status?: 'working' | 'active' | 'permission' | 'done' | 'inactive' -} - +// repo.list response item — captures id (desktop filter key) plus the visual +// metadata keyed by displayName the section headers/rows already use. type RepoSummary = { + id: string displayName: string badgeColor?: string -} - -type SortMode = 'smart' | 'name' | 'recent' | 'repo' -type _FilterMode = 'all' | 'active' -type GroupMode = 'none' | 'workspaceStatus' | 'repo' | 'prStatus' - -type FilterState = { - activeOnly: boolean - selectedRepos: Set + repoIcon?: RepoIcon | null } function isErrorVerdict(v: ConnectionVerdict): boolean { return v.kind === 'warning' || v.kind === 'unreachable' || v.kind === 'auth-failed' } -const SORT_OPTIONS: PickerOption[] = [ +const SORT_OPTIONS: PickerOption[] = [ { value: 'smart', label: 'Smart', subtitle: 'Unread and active first' }, { value: 'name', label: 'Name', subtitle: 'Alphabetical by name' }, { value: 'recent', label: 'Recent', subtitle: 'Most recent output first' }, - { value: 'repo', label: 'Repo', subtitle: 'Repository, then workspace name' } + { value: 'repo', label: 'Repo', subtitle: 'Repository, then workspace name' }, + { value: 'manual', label: 'Manual', subtitle: 'Server order' } ] -const GROUP_OPTIONS: PickerOption[] = [ +const GROUP_OPTIONS: PickerOption[] = [ { value: 'none', label: 'No Grouping' }, { value: 'workspaceStatus', label: 'Status' }, { value: 'repo', label: 'Repository' }, { value: 'prStatus', label: 'PR Status' } ] -function getWorktreeStatus(w: Worktree): 'working' | 'active' | 'permission' | 'done' | 'inactive' { - if (w.status) { - return w.status - } - if (w.liveTerminalCount > 0) { - return 'active' - } - return 'inactive' -} - -// Why: the previous 10-minute lastOutputAt window was too strict — most -// worktrees with idle terminal prompts had no recent output and were excluded. -// Any worktree with live terminals or unread output counts as "active". -function isWorktreeActive(w: Worktree): boolean { - if (w.unread) { - return true - } - if (w.status) { - return w.status !== 'inactive' - } - if (w.liveTerminalCount > 0) { - return true - } - return false -} - -const WORKSPACE_STATUS_LABELS: Record, string> = { - permission: 'Needs Permission', - working: 'Working', - done: 'Done', - active: 'Active', - inactive: 'Inactive' -} - -const WORKSPACE_STATUS_ORDER: ReturnType[] = [ - 'permission', - 'working', - 'done', - 'active', - 'inactive' -] - -function sortWorktrees(worktrees: Worktree[], mode: SortMode): Worktree[] { - return [...worktrees].sort((a, b) => { - if (mode === 'name') { - return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - } - if (mode === 'recent') { - return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) - } - if (mode === 'repo') { - const repoComparison = a.repo.localeCompare(b.repo, undefined, { sensitivity: 'base' }) - return repoComparison || (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - } - // 'smart' — attention-first - if (a.unread !== b.unread) { - return a.unread ? -1 : 1 - } - const aStatus = getWorktreeStatus(a) - const bStatus = getWorktreeStatus(b) - const statusOrder = { permission: 0, working: 1, done: 2, active: 3, inactive: 4 } - if (statusOrder[aStatus] !== statusOrder[bStatus]) { - return statusOrder[aStatus] - statusOrder[bStatus] - } - if ((a.lastOutputAt ?? 0) !== (b.lastOutputAt ?? 0)) { - return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) - } - return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) - }) -} - -function filterWorktrees(worktrees: Worktree[], filters: FilterState, search: string): Worktree[] { - let result = worktrees - if (filters.activeOnly) { - result = result.filter(isWorktreeActive) - } - if (filters.selectedRepos.size > 0) { - result = result.filter((w) => filters.selectedRepos.has(w.repo)) - } - if (search.trim()) { - const q = search.toLowerCase() - result = result.filter( - (w) => - (w.displayName || w.repo).toLowerCase().includes(q) || - w.branch.toLowerCase().includes(q) || - w.repo.toLowerCase().includes(q) - ) - } - return result -} - -type Section = { title: string; icon?: 'pin'; data: Worktree[] } - -// Why: matches desktop's PR_GROUP_META naming from worktree-list-groups.ts. -// no PR/draft/unknown → "In Progress", open → "In Review", merged → "Done", closed → "Closed" -type PRGroupKey = 'done' | 'in-review' | 'in-progress' | 'closed' - -const PR_GROUP_LABELS: Record = { - done: 'Done', - 'in-review': 'In Review', - 'in-progress': 'In Progress', - closed: 'Closed' -} - -const PR_GROUP_ORDER: PRGroupKey[] = ['done', 'in-review', 'in-progress', 'closed'] - -function getPRGroupKey(w: Worktree): PRGroupKey { - if (!w.linkedPR) { - return 'in-progress' - } - const s = w.linkedPR.state.toLowerCase() - if (s === 'merged') { - return 'done' - } - if (s === 'closed') { - return 'closed' - } - if (s === 'draft') { - return 'in-progress' - } - return 'in-review' -} - -function isWorktreePinned(w: Worktree, localPins: Set): boolean { - return w.isPinned || localPins.has(w.worktreeId) -} - -function buildSections( - worktrees: Worktree[], - sortMode: SortMode, - filters: FilterState, - search: string, - groupMode: GroupMode, - pinnedIds: Set -): Section[] { - const filtered = filterWorktrees(worktrees, filters, search) - const sorted = sortWorktrees(filtered, sortMode) - - const pinned = sorted.filter((w) => isWorktreePinned(w, pinnedIds)) - const unpinned = sorted.filter((w) => !isWorktreePinned(w, pinnedIds)) - const active = unpinned.filter(isWorktreeActive) - const inactive = unpinned.filter((w) => !isWorktreeActive(w)) - - const sections: Section[] = [] - if (pinned.length > 0) { - sections.push({ title: 'Pinned', icon: 'pin', data: pinned }) - } - - if (groupMode === 'none') { - if (active.length > 0) { - // Why: without explicit grouping, mobile's primary workflow is jumping - // back into running sessions before browsing the full worktree archive. - sections.push({ title: 'Active', data: active }) - } - if (inactive.length > 0) { - sections.push({ title: pinned.length > 0 || active.length > 0 ? 'All' : '', data: inactive }) - } - } else if (groupMode === 'repo') { - const byRepo = new Map() - for (const w of unpinned) { - const key = w.repo || 'Unknown' - const list = byRepo.get(key) - if (list) { - list.push(w) - } else { - byRepo.set(key, [w]) - } - } - for (const [repo, items] of byRepo) { - sections.push({ title: repo, data: items }) - } - } else if (groupMode === 'workspaceStatus') { - const byStatus = new Map, Worktree[]>() - for (const w of unpinned) { - const key = getWorktreeStatus(w) - const list = byStatus.get(key) - if (list) { - list.push(w) - } else { - byStatus.set(key, [w]) - } - } - for (const status of WORKSPACE_STATUS_ORDER) { - const items = byStatus.get(status) - if (items && items.length > 0) { - sections.push({ title: WORKSPACE_STATUS_LABELS[status], data: items }) - } - } - } else if (groupMode === 'prStatus') { - const byGroup = new Map() - for (const w of unpinned) { - const key = getPRGroupKey(w) - const list = byGroup.get(key) - if (list) { - list.push(w) - } else { - byGroup.set(key, [w]) - } - } - for (const groupKey of PR_GROUP_ORDER) { - const items = byGroup.get(groupKey) - if (items && items.length > 0) { - sections.push({ title: PR_GROUP_LABELS[groupKey], data: items }) - } - } - } - - return sections -} - export default function HostScreen() { const { hostId, action } = useLocalSearchParams<{ hostId: string; action?: string }>() const router = useRouter() @@ -360,19 +137,31 @@ export default function HostScreen() { const forceReconnectHost = useForceReconnect() const [worktrees, setWorktrees] = useState(initialCache ?? []) const [worktreesLoaded, setWorktreesLoaded] = useState(initialCache != null) + // Why: opening a worktree activates it on the host, but the active-row + // highlight otherwise waits for the next worktree.ps poll to reflect it. + // Track the locally-opened worktree so the highlight moves instantly. + const [optimisticActiveWorktreeId, setOptimisticActiveWorktreeId] = useState(null) + // One tick drives every visible agent row's relative timestamp. + const now = useNow(30_000) const [repoColorsByName, setRepoColorsByName] = useState>(new Map()) + const [repoIconsByName, setRepoIconsByName] = useState>(new Map()) const [hostName, setHostName] = useState('') const [error, setError] = useState('') const [compatVerdict, setCompatVerdict] = useState({ kind: 'ok' }) const [lastKnownWorktrees, setLastKnownWorktrees] = useState(initialCache ?? []) const [search, setSearch] = useState('') const [showSearch, setShowSearch] = useState(false) - const [sortMode, setSortMode] = useState('recent') + const [sortMode, setSortMode] = useState('recent') const [filters, setFilters] = useState({ - activeOnly: false, - selectedRepos: new Set() + filterRepoIds: new Set(), + hideSleeping: false, + hideDefaultBranch: false }) - const [groupMode, setGroupMode] = useState('repo') + const [groupMode, setGroupMode] = useState('repo') + // displayName → repo id, populated from repo.list. The filter model keys on + // repo ids (desktop's PersistedUIState), but the section headers/rows key on + // displayName, so we bridge the two here. + const [repoIdsByName, setRepoIdsByName] = useState>(new Map()) // Modals const [showSortPicker, setShowSortPicker] = useState(false) @@ -388,9 +177,70 @@ export default function HostScreen() { // Persisted pin state const [pinnedIds, setPinnedIds] = useState>(new Set()) - const [_prefsLoaded, setPrefsLoaded] = useState(false) const [collapsedGroups, setCollapsedGroups] = useState>(new Set()) + // Why: snapshot of the synced view settings so the focus-effect ui.get merge + // and the optimistic ui.set writes read the latest values without forcing the + // callbacks to re-create on every state change. + const viewStateRef = useRef({ + groupMode: 'repo', + sortMode: 'recent', + hideSleeping: false, + hideDefaultBranch: false, + filterRepoIds: [], + collapsedGroups: [] + }) + + // Keep the snapshot ref aligned with the individual view-setting states. + useEffect(() => { + viewStateRef.current = { + groupMode, + sortMode, + hideSleeping: filters.hideSleeping, + hideDefaultBranch: filters.hideDefaultBranch, + filterRepoIds: [...filters.filterRepoIds], + collapsedGroups: [...collapsedGroups] + } + }, [groupMode, sortMode, filters, collapsedGroups]) + + // Apply a MobileViewState (e.g. from a desktop ui.get) onto the individual + // states and the snapshot ref in one shot. + const applyViewState = useCallback((next: MobileViewState) => { + viewStateRef.current = next + setGroupMode(next.groupMode) + setSortMode(next.sortMode) + setCollapsedGroups(new Set(next.collapsedGroups)) + setFilters({ + filterRepoIds: new Set(next.filterRepoIds), + hideSleeping: next.hideSleeping, + hideDefaultBranch: next.hideDefaultBranch + }) + }, []) + + // Optimistically apply a partial change locally, then push the full mapped + // settings to the desktop's shared store via ui.set so both apps stay in sync. + const persistViewSettings = useCallback( + (patch: Partial) => { + const next: MobileViewState = { ...viewStateRef.current, ...patch } + applyViewState(next) + if (!client) { + return + } + const payload: WorkspaceViewSettings = { + groupBy: groupModeToDesktop(next.groupMode), + sortBy: next.sortMode, + hideSleepingWorkspaces: next.hideSleeping, + hideDefaultBranchWorkspace: next.hideDefaultBranch, + filterRepoIds: next.filterRepoIds, + collapsedGroups: next.collapsedGroups + } + void client.sendRequest('ui.set', payload).catch(() => { + // Best-effort: view settings are a convenience preference. + }) + }, + [client, applyViewState] + ) + const resolvedRouteActionState = resolveHostRouteActionState(routeActionState, action) // Why: `action=newWorktree` is a route-derived open edge. Resolve it before // commit, but don't reopen after the user closes while the same URL remains. @@ -402,32 +252,49 @@ export default function HostScreen() { setRouteActionState((current) => setHostRouteNewWorktreeVisible(current, visible)) }, []) - // Load persisted pins and preferences + // Load persisted pins from the local cache. View settings are no longer + // stored locally — they sync from the desktop's shared store via ui.get. useEffect(() => { if (!hostId) { return } let stale = false void (async () => { - const [pins, prefs] = await Promise.all([loadPinnedIds(hostId), loadPreferences(hostId)]) + const pins = await loadPinnedIds(hostId) if (stale) { return } setPinnedIds(pins) - setSortMode(prefs.sortMode as SortMode) - setFilters({ - activeOnly: prefs.filterMode === 'active', - selectedRepos: new Set(prefs.selectedRepos ?? []) - }) - setGroupMode(prefs.groupMode as GroupMode) - setCollapsedGroups(new Set(prefs.collapsedGroups)) - setPrefsLoaded(true) })() return () => { stale = true } }, [hostId]) + // Read the desktop's shared view settings (PersistedUIState) and merge them + // onto local state. Runs on connect and on screen focus so changes made on + // desktop appear on the phone. + const syncViewSettingsFromDesktop = useCallback(async () => { + if (!client || connState !== 'connected') { + return + } + const requestClient = client + const requestHostId = hostId + try { + const response = await requestClient.sendRequest('ui.get') + if (clientRef.current !== requestClient || hostId !== requestHostId || !response.ok) { + return + } + const ui = ((response as RpcSuccess).result as { ui?: WorkspaceViewSettings }).ui + if (!ui) { + return + } + applyViewState(applyDesktopViewSettings(viewStateRef.current, ui)) + } catch { + // Transient transport failure; retry on the next focus/connect. + } + }, [client, connState, hostId, applyViewState]) + // Why: keep clientRef in sync so existing imperative call sites work // unchanged. Also re-seed the cached worktree list on hostId change // since the useState initializer only runs on first mount. @@ -440,6 +307,7 @@ export default function HostScreen() { setError('') setCompatVerdict({ kind: 'ok' }) setRepoColorsByName(new Map()) + setRepoIconsByName(new Map()) // Why: re-seed from the current host's cache on every hostId change. // The useState initializer only runs on first mount, so if Expo Router // reuses this screen with a different hostId, we must reset here. @@ -482,7 +350,9 @@ export default function HostScreen() { const requestHostId = hostId try { - const response = await requestClient.sendRequest('worktree.ps') + // Why: worktree.ps defaults to 200 and silently truncates; match the + // desktop's high cap so large hosts don't drop workspaces on mobile. + const response = await requestClient.sendRequest('worktree.ps', { limit: 10000 }) if (clientRef.current !== requestClient || hostId !== requestHostId) { return } @@ -491,6 +361,14 @@ export default function HostScreen() { setWorktrees(result.worktrees) setLastKnownWorktrees(result.worktrees) setWorktreesLoaded(true) + // Drop the optimistic active override once the host confirms it (the + // activate RPC has landed and worktree.ps now reports it active), so we + // stop overriding and respect any later desktop-driven change. + setOptimisticActiveWorktreeId((pending) => + pending && result.worktrees.some((w) => w.worktreeId === pending && w.isActive) + ? null + : pending + ) void requestClient .sendRequest('repo.list') @@ -510,6 +388,14 @@ export default function HostScreen() { ]) ) ) + setRepoIconsByName( + new Map( + repoResult.repos.flatMap((repo) => + repo.repoIcon ? [[repo.displayName, repo.repoIcon] as const] : [] + ) + ) + ) + setRepoIdsByName(new Map(repoResult.repos.map((repo) => [repo.displayName, repo.id]))) }) .catch(() => null) @@ -602,13 +488,16 @@ export default function HostScreen() { return } void fetchWorktrees() + // Pull desktop's shared view settings on focus so desktop-side changes + // show up here without a manual refresh. + void syncViewSettingsFromDesktop() // Why: React Navigation keeps previous stack screens mounted; only // poll the host list while this route is visible. const interval = setInterval(() => { void fetchWorktrees() }, 3000) return () => clearInterval(interval) - }, [connState, fetchWorktrees]) + }, [connState, fetchWorktrees, syncViewSettingsFromDesktop]) ) const updateLocalPins = useCallback( @@ -702,6 +591,8 @@ export default function HostScreen() { const openWorktreeSession = useCallback( (item: Worktree) => { + // Highlight the row immediately; the next worktree.ps poll confirms it. + setOptimisticActiveWorktreeId(item.worktreeId) if (client && connState === 'connected') { void client .sendRequest('worktree.activate', { @@ -717,70 +608,54 @@ export default function HostScreen() { ) const handleSortChange = useCallback( - (value: SortMode) => { - setSortMode(value) - if (hostId) { - void savePreferences(hostId, { sortMode: value }) - } + (value: MobileSortMode) => { + persistViewSettings({ sortMode: value }) }, - [hostId] + [persistViewSettings] ) - const toggleActiveFilter = useCallback(() => { - setFilters((prev) => { - const next = { ...prev, activeOnly: !prev.activeOnly } - if (hostId) { - void savePreferences(hostId, { - filterMode: next.activeOnly ? 'active' : 'all' - }) - } - return next - }) - }, [hostId]) + const toggleHideSleeping = useCallback(() => { + persistViewSettings({ hideSleeping: !viewStateRef.current.hideSleeping }) + }, [persistViewSettings]) + + const toggleHideDefaultBranch = useCallback(() => { + persistViewSettings({ hideDefaultBranch: !viewStateRef.current.hideDefaultBranch }) + }, [persistViewSettings]) const toggleRepoFilter = useCallback( - (repo: string) => { - setFilters((prev) => { - const next = new Set(prev.selectedRepos) - if (next.has(repo)) { - next.delete(repo) - } else { - next.add(repo) - } - const updated = { ...prev, selectedRepos: next } - if (hostId) { - void savePreferences(hostId, { selectedRepos: [...next] }) - } - return updated - }) + (repoId: string) => { + const next = new Set(viewStateRef.current.filterRepoIds) + if (next.has(repoId)) { + next.delete(repoId) + } else { + next.add(repoId) + } + persistViewSettings({ filterRepoIds: [...next] }) }, - [hostId] + [persistViewSettings] ) const clearFilters = useCallback(() => { - setFilters({ activeOnly: false, selectedRepos: new Set() }) - if (hostId) { - void savePreferences(hostId, { filterMode: 'all', selectedRepos: [] }) - } - }, [hostId]) + persistViewSettings({ hideSleeping: false, hideDefaultBranch: false, filterRepoIds: [] }) + }, [persistViewSettings]) const activeFilterCount = useMemo(() => { let count = 0 - if (filters.activeOnly) { + if (filters.hideSleeping) { count++ } - count += filters.selectedRepos.size + if (filters.hideDefaultBranch) { + count++ + } + count += filters.filterRepoIds.size return count }, [filters]) const handleGroupChange = useCallback( - (value: GroupMode) => { - setGroupMode(value) - if (hostId) { - void savePreferences(hostId, { groupMode: value }) - } + (value: MobileGroupMode) => { + persistViewSettings({ groupMode: value }) }, - [hostId] + [persistViewSettings] ) const displayWorktrees = useMemo(() => { @@ -788,25 +663,35 @@ export default function HostScreen() { connState === 'disconnected' || connState === 'reconnecting' || connState === 'auth-failed' ? lastKnownWorktrees : worktrees - if (sleptIds.size === 0) { + if (sleptIds.size === 0 && optimisticActiveWorktreeId === null) { return base } - return base.map((w) => - sleptIds.has(w.worktreeId) - ? { ...w, liveTerminalCount: 0, hasAttachedPty: false, status: 'inactive' as const } - : w - ) - }, [connState, worktrees, lastKnownWorktrees, sleptIds]) + return base.map((w) => { + const slept = sleptIds.has(w.worktreeId) + ? { liveTerminalCount: 0, hasAttachedPty: false, status: 'inactive' as const } + : null + // Force the just-opened worktree active (and the rest inactive) until the + // next poll confirms it, so the highlight doesn't lag the navigation. + const active = + optimisticActiveWorktreeId !== null + ? { isActive: w.worktreeId === optimisticActiveWorktreeId } + : null + return slept || active ? { ...w, ...slept, ...active } : w + }) + }, [connState, worktrees, lastKnownWorktrees, sleptIds, optimisticActiveWorktreeId]) const uniqueRepos = useMemo(() => { - const repos = new Map() + const repos = new Map() for (const w of displayWorktrees) { if (!repos.has(w.repo)) { - repos.set(w.repo, repoColorsByName.get(w.repo) ?? repoColor(w.repo)) + repos.set(w.repo, { + id: repoIdsByName.get(w.repo) ?? w.repoId, + color: repoColorsByName.get(w.repo) ?? repoColor(w.repo) + }) } } - return [...repos.entries()].map(([name, color]) => ({ name, color })) - }, [displayWorktrees, repoColorsByName]) + return [...repos.entries()].map(([name, { id, color }]) => ({ name, id, color })) + }, [displayWorktrees, repoColorsByName, repoIdsByName]) const uniqueRepoColors = useMemo( () => new Map(uniqueRepos.map((repo) => [repo.name, repo.color])), @@ -815,20 +700,15 @@ export default function HostScreen() { const toggleCollapsed = useCallback( (title: string) => { - setCollapsedGroups((prev) => { - const next = new Set(prev) - if (next.has(title)) { - next.delete(title) - } else { - next.add(title) - } - if (hostId) { - void savePreferences(hostId, { collapsedGroups: [...next] }) - } - return next - }) + const next = new Set(viewStateRef.current.collapsedGroups) + if (next.has(title)) { + next.delete(title) + } else { + next.add(title) + } + persistViewSettings({ collapsedGroups: [...next] }) }, - [hostId] + [persistViewSettings] ) const rawSections = useMemo( @@ -845,6 +725,8 @@ export default function HostScreen() { [rawSections, collapsedGroups] ) + const { sectionListRef, onScrollToIndexFailed } = useActiveWorktreeScroll(sections) + const isReadOnly = connState === 'auth-failed' if (error) { @@ -929,13 +811,7 @@ export default function HostScreen() { setShowSortPicker(true)}> - {sortMode === 'smart' - ? 'Smart' - : sortMode === 'name' - ? 'Name' - : sortMode === 'repo' - ? 'Repo' - : 'Recent'} + {SORT_OPTIONS.find((o) => o.value === sortMode)?.label ?? 'Recent'} @@ -1054,9 +930,11 @@ export default function HostScreen() { {/* Worktree list */} {sections.length > 0 && ( w.worktreeId} stickySectionHeadersEnabled={false} + onScrollToIndexFailed={onScrollToIndexFailed} // Why: edge-to-edge — the list scrolls under the system nav bar // while reserving insets.bottom keeps the last worktree row reachable // above the Samsung 3-button nav / iOS home indicator. @@ -1074,6 +952,7 @@ export default function HostScreen() { const count = rawSection?.data.length ?? 0 const repoSectionColor = groupMode === 'repo' ? uniqueRepoColors.get(section.title) : null + const repoSectionIcon = groupMode === 'repo' ? repoIconsByName.get(section.title) : null return ( )} - {repoSectionColor ? ( - + {groupMode === 'repo' ? ( + + + ) : null} {section.title} {count} @@ -1097,71 +982,17 @@ export default function HostScreen() { }} ItemSeparatorComponent={ListSeparator} renderItem={({ item }) => ( - [styles.worktreeRow, pressed && styles.worktreeRowPressed]} - disabled={isReadOnly} - onPress={() => openWorktreeSession(item)} - onLongPress={() => { - triggerMediumImpact() - setActionTarget(item) - }} - delayLongPress={400} - > - {/* Left indicator */} - - - {item.unread && ( - - )} - - - {/* Main content */} - - - - {item.displayName || item.repo} - - {item.linkedPR && ( - - - #{item.linkedPR.number} - - )} - - - - - {item.repo} - - - {item.branch} - - - {item.preview ? ( - - {item.preview} - - ) : null} - - - {/* Terminal count */} - {item.liveTerminalCount > 0 && ( - {item.liveTerminalCount} - )} - + )} /> )} @@ -1197,11 +1028,16 @@ export default function HostScreen() { )} - Status + Workspaces - - Active only - {filters.activeOnly && } + + Hide sleeping + {filters.hideSleeping && } + + + + Hide default branch + {filters.hideDefaultBranch && } @@ -1210,14 +1046,14 @@ export default function HostScreen() { Repositories {uniqueRepos.map((repo, i) => ( - + {i > 0 && } - toggleRepoFilter(repo.name)}> + toggleRepoFilter(repo.id)}> {repo.name} - {filters.selectedRepos.has(repo.name) && ( + {filters.filterRepoIds.has(repo.id) && ( )} @@ -1517,10 +1353,7 @@ const styles = StyleSheet.create({ sectionIcon: { marginRight: spacing.xs }, - sectionRepoDot: { - width: 8, - height: 8, - borderRadius: 4, + sectionRepoIcon: { marginRight: spacing.xs }, sectionTitle: { @@ -1541,91 +1374,6 @@ const styles = StyleSheet.create({ marginLeft: spacing.lg + 24, marginRight: spacing.lg }, - worktreeRow: { - flexDirection: 'row', - alignItems: 'flex-start', - paddingVertical: spacing.sm + 2, - paddingHorizontal: spacing.lg - }, - worktreeRowPressed: { - backgroundColor: colors.bgRaised - }, - indicatorCol: { - width: 20, - alignItems: 'center', - paddingTop: 6, - marginRight: spacing.sm, - gap: 4 - }, - unreadBell: { - marginTop: 2 - }, - worktreeMain: { - flex: 1, - marginRight: spacing.sm - }, - worktreeNameRow: { - flexDirection: 'row', - alignItems: 'center', - gap: spacing.sm - }, - worktreeName: { - fontSize: 14, - fontWeight: '600', - color: colors.textPrimary, - flexShrink: 1 - }, - textReadOnly: { - opacity: 0.5 - }, - prBadge: { - flexDirection: 'row', - alignItems: 'center', - gap: 3, - backgroundColor: colors.bgRaised, - paddingHorizontal: 5, - paddingVertical: 1, - borderRadius: 4 - }, - prNumber: { - fontSize: 10, - color: colors.textSecondary - }, - worktreeMetaRow: { - flexDirection: 'row', - alignItems: 'center', - marginTop: 2, - gap: spacing.xs - }, - repoDot: { - width: 6, - height: 6, - borderRadius: 3 - }, - repoName: { - fontSize: 11, - color: colors.textSecondary, - maxWidth: 100 - }, - branchName: { - fontSize: 11, - color: colors.textMuted, - fontFamily: typography.monoFamily, - flexShrink: 1 - }, - worktreePreview: { - fontSize: 11, - color: colors.textMuted, - fontFamily: typography.monoFamily, - marginTop: 2 - }, - terminalCount: { - fontSize: typography.metaSize, - color: colors.textMuted, - minWidth: 16, - textAlign: 'right', - paddingTop: 3 - }, filterModalHeader: { flexDirection: 'row', alignItems: 'center', diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index 039f9cf57..d44a552bd 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -4,6 +4,7 @@ import * as Clipboard from 'expo-clipboard' import { BackHandler, FlatList, + Image, View, Text, ScrollView, @@ -32,6 +33,7 @@ import { FileText, GitBranch, Globe, + ImagePlus, Keyboard as KeyboardIcon, MessageSquare, Mic, @@ -44,6 +46,7 @@ import { X } from 'lucide-react-native' import type { RpcClient } from '../../../../src/transport/rpc-client' +import type { RuntimeTerminalPathResolution } from '../../../../../src/shared/runtime-types' import { loadHosts } from '../../../../src/transport/host-store' import { loadTerminalAutocompleteEnabled, @@ -130,6 +133,14 @@ import { buildMobileImagePastePayload, saveMobileClipboardImageAsTempFile } from '../../../../src/session/mobile-clipboard-image' +import { useMobileImageAttachment } from '../../../../src/session/use-mobile-image-attachment' +import { classifyMobileArtifact } from '../../../../src/session/mobile-artifact-kind' +import { MobileHtmlPreview } from '../../../../src/components/MobileHtmlPreview' +import { MobileDictationSetupSheet } from '../../../../src/components/MobileDictationSetupSheet' +import { + fetchDictationSetup, + isDictationSetupRequiredError +} from '../../../../src/dictation/mobile-dictation-setup' import { TerminalPaneView } from '../../../../src/session/TerminalPaneView' import { getRepoIdFromMobileWorktreeId, @@ -594,7 +605,8 @@ function FileReader({ // Why: highlighting can create many nested Text nodes; defer it one tick so // large files show immediately as plain text before colors are applied. const timer = setTimeout(() => { - if (doc.kind === 'file') { + // file + html share the syntax-segment source view (html's "Source" toggle). + if (doc.kind === 'file' || doc.kind === 'html') { setFileSyntax({ doc, language: syntaxLanguage, @@ -602,11 +614,14 @@ function FileReader({ }) return } - setDiffSyntax({ - doc, - language: syntaxLanguage, - lines: highlightMobileDiffLines(doc.lines, syntaxLanguage) - }) + if (doc.kind === 'diff') { + setDiffSyntax({ + doc, + language: syntaxLanguage, + lines: highlightMobileDiffLines(doc.lines, syntaxLanguage) + }) + } + // image: no syntax highlighting. }, 0) return () => clearTimeout(timer) @@ -694,7 +709,28 @@ function FileReader({ ) } - return ( + if (doc.kind === 'image') { + return ( + + + + + + ) + } + + const renderSourceText = (content: string) => ( ) + + if (doc.kind === 'html') { + return ( + + renderSourceText(doc.content)} /> + + ) + } + + return renderSourceText(doc.content) } export default function SessionScreen() { @@ -826,6 +872,10 @@ export default function SessionScreen() { >(new Map()) const [selectModeActive, setSelectModeActive] = useState(false) const [canPaste, setCanPaste] = useState(false) + const [showDictationSetup, setShowDictationSetup] = useState(false) + // 'hold' makes the mic press-and-hold; 'toggle' makes it tap-to-start/stop. + // Mirrors Settings ▸ Voice ▸ Dictation Mode so the button matches the setting. + const [dictationMode, setDictationMode] = useState<'toggle' | 'hold'>('toggle') const [toastMessage, setToastMessage] = useState(null) const toastOpacityRef = useRef(new Animated.Value(0)) const toastHideTimerRef = useRef | null>(null) @@ -859,6 +909,13 @@ export default function SessionScreen() { const activeSessionTabTypeRef = useRef(null) const pendingActiveSessionTabIdRef = useRef(null) const pendingActiveTerminalHandleRef = useRef(null) + // Why: a browser tab opened from a terminal-tapped HTML must be focused as an + // Orca session tab (bridge auto-activate only flags the live webContents, not + // the app-level active tab). We remember the page id and, once its session tab + // syncs, activate it through the normal switchSessionTab path (which also makes + // switching back to the terminal work). A ref breaks the callback dep cycle. + const pendingBrowserFocusPageIdRef = useRef(null) + const switchSessionTabRef = useRef<((tab: MobileSessionTab) => void) | null>(null) const initialEmptySessionAutoCreateRef = useRef(null) const markdownSaveSeqRef = useRef>(new Map()) const markdownSaveInFlightRef = useRef>(new Set()) @@ -888,6 +945,10 @@ export default function SessionScreen() { activeSessionTab?.type !== 'browser' const liveInputEnabled = activeHandle ? liveInputTerminalHandles.has(activeHandle) : false const [browserScreencastSupported, setBrowserScreencastSupported] = useState(null) + // Why: stable callbacks (handleFileTap) read the live value via this ref, since + // the capability probe resolves after the callbacks are created. + const browserScreencastSupportedRef = useRef(browserScreencastSupported) + browserScreencastSupportedRef.current = browserScreencastSupported // Why: terminal gesture/input callbacks are intentionally stable and // imperative; keep their refs current before commit instead of one effect later. clientRef.current = client @@ -974,11 +1035,73 @@ export default function SessionScreen() { showToast('Dictation inserted') }, onError: (err) => { + // Dictation isn't set up on the desktop yet → open the setup sheet so the + // user can download a model + enable it from here, instead of a dead-end toast. + if (isDictationSetupRequiredError(err.message)) { + setShowDictationSetup(true) + return + } triggerError() showToast(err.message) } }) + const startDictation = useCallback(() => { + void dictation.start().catch((err) => { + triggerError() + showToast(err instanceof Error ? err.message : String(err)) + }) + }, [dictation, triggerError, showToast]) + + // Toggle mode: one tap starts, the next stops; long-press cancels mid-record. + const handleDictationToggle = useCallback(() => { + if (dictation.isProcessing) { + void dictation.cancel() + } else if (dictation.isStarting) { + return + } else if (dictation.isRecording) { + void dictation.stop() + } else { + startDictation() + } + }, [dictation, startDictation]) + + // Hold mode: press starts, release stops — like a walkie-talkie. + const handleDictationPressIn = useCallback(() => { + if (!dictation.isStarting && !dictation.isRecording && !dictation.isProcessing) { + startDictation() + } + }, [dictation, startDictation]) + + const handleDictationPressOut = useCallback(() => { + if (dictation.isRecording) { + void dictation.stop() + } else if (dictation.isStarting) { + // Released before recording began: cancel so we don't leave a live mic. + void dictation.cancel() + } + }, [dictation]) + + const refreshDictationMode = useCallback(async () => { + if (!client) { + return + } + try { + const setup = await fetchDictationSetup(client) + setDictationMode(setup.dictationMode) + } catch { + // Non-fatal: fall back to the default toggle behavior. + } + }, [client]) + + // Re-read on focus so a Dictation Mode change made in Settings ▸ Voice is + // reflected when the user returns to the session. + useFocusEffect( + useCallback(() => { + void refreshDictationMode() + }, [refreshDictationMode]) + ) + useEffect(() => { diffCommentsRef.current = diffComments }, [diffComments]) @@ -1591,6 +1714,32 @@ export default function SessionScreen() { ) return } + const artifactKind = classifyMobileArtifact(tab.relativePath) + if (artifactKind === 'image') { + const preview = await client.sendRequest('files.readPreview', { + worktree: `id:${worktreeId}`, + relativePath: tab.relativePath + }) + if (!preview.ok) { + throw new Error((preview as RpcFailure).error.message) + } + const result = (preview as RpcSuccess).result as { + content: string + isImage?: boolean + mimeType?: string + } + if (!result.isImage || !result.mimeType || result.content.length === 0) { + throw new Error('binary_file') + } + setFileDocs((prev) => + new Map(prev).set(tab.id, { + status: 'ready', + kind: 'image', + dataUri: `data:${result.mimeType};base64,${result.content}` + }) + ) + return + } const response = await client.sendRequest('files.read', { worktree: `id:${worktreeId}`, relativePath: tab.relativePath @@ -1603,6 +1752,16 @@ export default function SessionScreen() { truncated: boolean byteLength: number } + if (artifactKind === 'html') { + setFileDocs((prev) => + new Map(prev).set(tab.id, { + status: 'ready', + kind: 'html', + content: result.content + }) + ) + return + } setFileDocs((prev) => new Map(prev).set(tab.id, { status: 'ready', @@ -1968,6 +2127,18 @@ export default function SessionScreen() { } const result = (response as RpcSuccess).result as SessionTabsResult applySessionTabs(result) + // Focus a just-opened browser tab once it appears in the snapshot, via the + // normal activate path so it sticks and the user can still switch away. + const pendingPageId = pendingBrowserFocusPageIdRef.current + if (pendingPageId) { + const browserTab = result.tabs.find( + (tab) => tab.type === 'browser' && tab.browserPageId === pendingPageId + ) + if (browserTab) { + pendingBrowserFocusPageIdRef.current = null + switchSessionTabRef.current?.(browserTab) + } + } } catch { // Keep the last tab snapshot visible during reconnect/backoff. } finally { @@ -2168,6 +2339,7 @@ export default function SessionScreen() { activeSessionTabTypeRef.current = null pendingActiveSessionTabIdRef.current = null pendingActiveTerminalHandleRef.current = null + pendingBrowserFocusPageIdRef.current = null initialEmptySessionAutoCreateRef.current = null for (const queued of terminalGestureInputQueuesRef.current.values()) { if (queued.timer) { @@ -2455,6 +2627,9 @@ export default function SessionScreen() { }, [client, markdownDocs, readFileTab, readMarkdownTab, switchTab, unsubscribeTerminal, worktreeId] ) + // Keep the ref pointing at the latest switchSessionTab so fetchSessionTabs can + // activate a freshly-synced browser tab without a callback dependency cycle. + switchSessionTabRef.current = switchSessionTab // Why: just store the ref. Subscription is deferred to handleTerminalWebReady // which fires after the WebView has loaded xterm.js and is ready to process @@ -2633,6 +2808,59 @@ export default function SessionScreen() { [focusLiveInput] ) + // Tap on a file path in terminal output → resolve it on the host and open it + // as a file tab (mirrors desktop Cmd/Ctrl-click). Silent on a miss; the + // WebView only emits this when the tap landed on a detected path. + const handleFileTap = useCallback( + (handle: string, pathText: string) => { + if (handle !== activeHandleRef.current || !client) { + return + } + void (async () => { + try { + const worktree = `id:${worktreeId}` + const response = await client.sendRequest( + 'files.resolveTerminalPath', + { worktree, pathText }, + { timeoutMs: 10_000 } + ) + if (!response.ok) { + return + } + const resolved = (response as RpcSuccess).result as RuntimeTerminalPathResolution + if (!resolved.exists || resolved.isDirectory || !resolved.relativePath) { + return + } + // Confirm the tap landed on something openable before giving feedback. + triggerSelection() + // Why: HTML opens in a browser pane (streamed from the desktop), + // matching desktop's terminal-click behavior, instead of a file view. + if (classifyMobileArtifact(resolved.relativePath) === 'html' && resolved.absolutePath) { + void handleCreateBrowser('file://' + resolved.absolutePath) + return + } + const openResponse = await client.sendRequest( + 'files.open', + { worktree, relativePath: resolved.relativePath }, + { timeoutMs: 15_000 } + ) + if (!openResponse.ok) { + return + } + // Why: the desktop creates the file tab asynchronously; a single poll + // can race it, so refresh a few times to reliably pick it up and + // switch to it (the file browser gets this for free via router.back). + scheduleDelayedAction(() => void fetchSessionTabs(), 300) + scheduleDelayedAction(() => void fetchSessionTabs(), 900) + scheduleDelayedAction(() => void fetchSessionTabs(), 1800) + } catch { + // Resolution/open is best-effort; a failed tap silently no-ops. + } + })() + }, + [client, worktreeId, scheduleDelayedAction, fetchSessionTabs] + ) + const toggleLiveInput = useCallback(() => { if (!activeHandle) { return @@ -3131,6 +3359,18 @@ export default function SessionScreen() { showToast ]) + const { attachImage, isAttaching } = useMobileImageAttachment({ + client, + activeHandle, + canSend, + connState, + deviceTokenRef, + getActiveWorktreeConnectionId, + showToast, + onSuccess: triggerSelection, + onError: triggerError + }) + // Why: refresh canPaste on mount, AppState active, after paste. useEffect(() => { let mounted = true @@ -3383,7 +3623,9 @@ export default function SessionScreen() { if (!client || creatingBrowser) { return false } - if (browserScreencastSupported !== true) { + // Why: read via ref so a tap that fires before the capability probe resolves + // (or from a stale callback) still sees the live support value. + if (browserScreencastSupportedRef.current !== true) { showToast('Desktop update required for mobile browser streaming', 1600) return false } @@ -3402,14 +3644,25 @@ export default function SessionScreen() { 'browser.tabCreate', { worktree: `id:${worktreeId}`, - url + url, + // The user opened this tab (tapped HTML / address bar) → focus it. + activate: true }, { timeoutMs: 30_000 } ) if (!response.ok) { throw new Error((response as RpcFailure).error.message) } - scheduleDelayedAction(() => void fetchSessionTabs(), 300) + // Focus the new browser tab once it syncs (fetchSessionTabs activates it + // via the normal path). Refresh a few times since the desktop registers + // the tab asynchronously. + const created = (response as RpcSuccess).result as { browserPageId?: string } + if (created.browserPageId) { + pendingBrowserFocusPageIdRef.current = created.browserPageId + } + void fetchSessionTabs() + scheduleDelayedAction(() => void fetchSessionTabs(), 400) + scheduleDelayedAction(() => void fetchSessionTabs(), 1200) return true } catch (err) { const message = err instanceof Error ? err.message : 'Failed to create browser' @@ -4038,6 +4291,7 @@ export default function SessionScreen() { onHaptic={handleHaptic} onTerminalInput={handleTerminalInput} onTerminalTap={handleTerminalTap} + onFileTap={handleFileTap} /> ))} {toastMessage && ( @@ -4279,6 +4533,26 @@ export default function SessionScreen() { editable={canSend} onSubmitEditing={() => void handleSend()} /> + void attachImage('library')} + onLongPress={() => void attachImage('files')} + delayLongPress={350} + accessibilityLabel={isAttaching ? 'Sending image' : 'Attach a photo'} + accessibilityHint="Long press to attach a file instead" + > + {isAttaching ? ( + + ) : ( + + )} + { - if (dictation.isProcessing) { - void dictation.cancel() - } else if (dictation.isStarting) { - return - } else if (dictation.isRecording) { - void dictation.stop() - } else { - void dictation.start().catch((err) => { - triggerError() - showToast(err instanceof Error ? err.message : String(err)) - }) - } - }} - onLongPress={() => { - if (dictation.isRecording || dictation.isProcessing) { - void dictation.cancel() - } - }} + onPress={dictationMode === 'toggle' ? handleDictationToggle : undefined} + onPressIn={dictationMode === 'hold' ? handleDictationPressIn : undefined} + onPressOut={dictationMode === 'hold' ? handleDictationPressOut : undefined} + onLongPress={ + dictationMode === 'toggle' + ? () => { + if (dictation.isRecording || dictation.isProcessing) { + void dictation.cancel() + } + } + : undefined + } accessibilityLabel={ dictation.isRecording ? 'Stop voice dictation' @@ -4664,6 +4931,12 @@ export default function SessionScreen() { onKeysChanged={setCustomKeys} onManageShortcuts={handleManageShortcuts} /> + setShowDictationSetup(false)} + onReady={() => setShowDictationSetup(false)} + /> diff --git a/mobile/app/h/[hostId]/source-control/[worktreeId].tsx b/mobile/app/h/[hostId]/source-control/[worktreeId].tsx index 8cfbdcd7b..e289bb995 100644 --- a/mobile/app/h/[hostId]/source-control/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/source-control/[worktreeId].tsx @@ -14,27 +14,48 @@ import { import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useLocalSearchParams, useRouter } from 'expo-router' import { - ChevronLeft, ArrowDown, ArrowDownUp, ArrowUp, Check, + ChevronLeft, CloudUpload, FileText, GitBranch, GitPullRequest, + History, Minus, MoreHorizontal, Plus, RefreshCw, + Sparkles, Trash2, - X + X, + type LucideIcon } from 'lucide-react-native' +import type { MobileSourceControlActionIcon } from '../../../../src/source-control/mobile-source-control-actions' import { useHostClient, useForceReconnect } from '../../../../src/transport/client-context' import { getWorktreeLabel } from '../../../../src/session/worktree-label' import type { RpcSuccess } from '../../../../src/transport/types' import { MobileSourceControlReviewEntry } from '../../../../src/source-control/mobile-source-control-review-entry' import { resolveMobileBranchCompareBaseRef } from '../../../../src/source-control/mobile-branch-base-ref' +import { + cancelMobileCommitMessage, + requestMobileCommitMessage +} from '../../../../src/source-control/mobile-commit-message-ai' +import { buildMobileSourceControlActions } from '../../../../src/source-control/mobile-source-control-actions' +import { + MobilePrComposeSheet, + openMobilePrUrl +} from '../../../../src/components/MobilePrComposeSheet' +import { + resolveMobilePrPrefill, + type MobilePrPrefill +} from '../../../../src/source-control/mobile-pr-create' +import { PickerModal } from '../../../../src/components/PickerModal' +import type { RuntimeGitLocalBranches } from '../../../../../src/shared/runtime-types' + +type MobileGitLocalBranches = RuntimeGitLocalBranches import { ActionSheetModal, type ActionSheetAction @@ -142,6 +163,19 @@ type GitDiffTextResult = { } const KEYBOARD_COMMIT_BAR_CLEARANCE = 10 + +const SOURCE_CONTROL_ACTION_ICONS: Record = { + commit: Check, + push: ArrowUp, + pull: ArrowDown, + sync: ArrowDownUp, + fetch: RefreshCw, + publish: CloudUpload, + rebase: GitBranch, + pr: GitPullRequest, + branch: GitBranch, + history: History +} const SELECTOR_RETRY_COUNT = 3 const SELECTOR_RETRY_DELAY_MS = 250 @@ -201,6 +235,12 @@ export default function MobileSourceControlScreen() { ) const [busyAction, setBusyAction] = useState(null) const [commitMessage, setCommitMessage] = useState('') + const [generatingMessage, setGeneratingMessage] = useState(false) + const [showPrSheet, setShowPrSheet] = useState(false) + const [showBranchPicker, setShowBranchPicker] = useState(false) + const [localBranches, setLocalBranches] = useState(null) + const [createdPrUrl, setCreatedPrUrl] = useState(null) + const [prPrefill, setPrPrefill] = useState(null) const [discardTarget, setDiscardTarget] = useState(null) const [showActionSheet, setShowActionSheet] = useState(false) const [actionError, setActionError] = useState(null) @@ -637,6 +677,109 @@ export default function MobileSourceControlScreen() { ) }, [commitMessage, runGitWorkflow, sendCommitRequest]) + // AI-generate a commit message from the staged diff. Matches desktop: the + // button is always available; a missing model surfaces as a toast. + const generateCommitMessage = useCallback(async () => { + if (!client || generatingMessage || busyActionRef.current) { + return + } + setGeneratingMessage(true) + setActionError(null) + try { + const result = await requestMobileCommitMessage(client, worktreeId) + if (!mountedRef.current) { + return + } + if (result.success) { + setCommitMessage(result.message) + triggerSuccess() + } else if (!result.canceled) { + triggerError() + setActionError(result.error) + } + } finally { + if (mountedRef.current) { + setGeneratingMessage(false) + } + } + }, [client, generatingMessage, worktreeId]) + + const cancelGenerateCommitMessage = useCallback(() => { + if (client) { + void cancelMobileCommitMessage(client, worktreeId) + } + }, [client, worktreeId]) + + const openPrSheet = useCallback( + async (pushFirst: boolean) => { + setShowActionSheet(false) + if (pushFirst) { + const pushed = await runGitWorkflow('push-create-pr', async () => { + await sendGitRequest('git.push') + }) + if (!pushed || !mountedRef.current) { + return + } + } + const up = status?.upstreamStatus + const prefill: MobilePrPrefill = client + ? await resolveMobilePrPrefill(client, worktreeId, { + branch: status?.branch, + title: branchLabel, + hasUncommittedChanges: (status?.entries?.length ?? 0) > 0, + hasUpstream: up?.hasUpstream === true, + ahead: up?.ahead ?? 0, + behind: up?.behind ?? 0 + }) + : { provider: 'github', base: 'main', title: branchLabel, body: '' } + if (!mountedRef.current) { + return + } + setPrPrefill(prefill) + setShowPrSheet(true) + }, + [branchLabel, client, runGitWorkflow, sendGitRequest, status, worktreeId] + ) + + const openBranchPicker = useCallback(() => { + setShowActionSheet(false) + setLocalBranches(null) + setShowBranchPicker(true) + if (client) { + void sendGitRequest('git.localBranches') + .then((result) => { + if (mountedRef.current) { + setLocalBranches(result) + } + }) + .catch(() => { + if (mountedRef.current) { + setLocalBranches({ current: null, branches: [] }) + } + }) + } + }, [client, sendGitRequest]) + + const openHistory = useCallback(() => { + setShowActionSheet(false) + if (hostId && worktreeId) { + router.push( + `/h/${hostId}/history/${encodeURIComponent(worktreeId)}` as Parameters< + typeof router.push + >[0] + ) + } + }, [hostId, router, worktreeId]) + + // Switch to a local branch, then reload status. + const checkoutBranch = useCallback( + async (branch: string) => { + setShowBranchPicker(false) + await runGitAction('checkout', 'git.checkout', { branch }) + }, + [runGitAction] + ) + const runCommitFollowUps = useCallback( async (actionId: string, afterCommit: () => Promise) => { const message = commitMessage.trim() @@ -744,6 +887,33 @@ export default function MobileSourceControlScreen() { setShowActionSheet(false) }, [runGitSync]) + const runActionSheetRebase = useCallback(async () => { + await runGitWorkflow('rebase', async () => { + if (!client) { + throw new Error('Waiting for desktop...') + } + const baseRef = await resolveMobileBranchCompareBaseRef(client, worktreeId) + if (!baseRef) { + throw new Error('No base branch to rebase onto') + } + await sendGitRequest('git.rebaseFromBase', { baseRef }) + }) + setShowActionSheet(false) + }, [client, runGitWorkflow, sendGitRequest, worktreeId]) + + // Abort an in-progress merge/rebase from the conflict banner. + const abortConflictOperation = useCallback( + async (operation: string) => { + const method = + operation === 'merge' ? 'git.abortMerge' : operation === 'rebase' ? 'git.abortRebase' : null + if (!method) { + return + } + await runGitAction(`abort-${operation}`, method, {}) + }, + [runGitAction] + ) + const openFile = useCallback( async (entry: MobileGitStatusEntry) => { if (entry.status === 'deleted' || entry.conflictStatus === 'unresolved') { @@ -888,144 +1058,58 @@ export default function MobileSourceControlScreen() { [branchCompareState, client, connState, worktreeId] ) - const actionSheetActions = useMemo(() => { - const hasMessage = commitMessage.trim().length > 0 - const hasStaged = stagedCount > 0 - const hasUpstream = upstream?.hasUpstream === true - const ahead = upstream?.ahead ?? 0 - const behind = upstream?.behind ?? 0 - const busy = busyAction !== null || openingPath !== null || openingBranchPath !== null - const commitHint = !hasStaged - ? 'Stage at least one file' - : !hasMessage - ? 'Enter a commit message' - : undefined - const remoteHint = !upstreamKnown - ? 'Checking branch status...' - : hasUpstream - ? undefined - : 'Publish Branch first' - const createPrHint = 'Pull requests are not available on mobile yet' - - return [ - { - label: 'Commit', - icon: Check, - disabled: busy || !!commitHint, - hint: commitHint, - loading: busyAction === 'commit', - skipAutoClose: true, - onPress: () => void runActionSheetCommit() - }, - { - label: 'Commit & Push', - icon: ArrowUp, - disabled: busy || !!commitHint || !upstreamKnown || !hasUpstream, - hint: commitHint ?? remoteHint, - loading: busyAction === 'commit-push', - skipAutoClose: true, - onPress: () => void runActionSheetCommitSequence('commit-push', [{ method: 'git.push' }]) - }, - { - label: 'Commit & Sync', - icon: ArrowDownUp, - disabled: busy || !!commitHint || !upstreamKnown || !hasUpstream || behind === 0, - hint: - commitHint ?? - (!upstreamKnown || !hasUpstream - ? remoteHint - : behind === 0 - ? 'Nothing to pull' - : undefined), - loading: busyAction === 'commit-sync', - skipAutoClose: true, - onPress: () => void runActionSheetCommitSync() - }, - { - label: ahead > 0 ? `Push (${ahead})` : 'Push', - icon: ArrowUp, - disabled: busy || !upstreamKnown || !hasUpstream || ahead === 0, - hint: !hasUpstream ? remoteHint : ahead === 0 ? 'Nothing to push' : undefined, - loading: busyAction === 'push', - skipAutoClose: true, - onPress: () => void runActionSheetGitSequence('push', [{ method: 'git.push' }]) - }, - { - label: 'Create PR', - icon: GitPullRequest, - disabled: true, - hint: createPrHint, - onPress: () => {} - }, - { - label: 'Push & Create PR', - icon: GitPullRequest, - disabled: true, - hint: createPrHint, - onPress: () => {} - }, - { - label: behind > 0 ? `Pull (${behind})` : 'Pull', - icon: ArrowDown, - disabled: busy || !upstreamKnown || !hasUpstream || behind === 0, - hint: !hasUpstream ? remoteHint : behind === 0 ? 'Nothing to pull' : undefined, - loading: busyAction === 'pull', - skipAutoClose: true, - onPress: () => void runActionSheetGitSequence('pull', [{ method: 'git.pull' }]) - }, - { - label: ahead > 0 || behind > 0 ? `Sync (↓${behind} ↑${ahead})` : 'Sync', - icon: ArrowDownUp, - disabled: busy || !upstreamKnown || !hasUpstream || (ahead === 0 && behind === 0), - hint: - !upstreamKnown || !hasUpstream - ? remoteHint - : ahead === 0 && behind === 0 - ? 'Branch is up to date' - : undefined, - loading: busyAction === 'sync', - skipAutoClose: true, - onPress: () => void runActionSheetGitSync() - }, - { - label: 'Fetch', - icon: RefreshCw, - disabled: busy, - loading: busyAction === 'fetch', - skipAutoClose: true, - onPress: () => void runActionSheetGitSequence('fetch', [{ method: 'git.fetch' }]) - }, - { - label: 'Publish Branch', - icon: CloudUpload, - disabled: busy || !upstreamKnown || hasUpstream, - hint: !upstreamKnown - ? 'Checking branch status...' - : hasUpstream - ? 'Branch is already published' - : undefined, - loading: busyAction === 'publish', - skipAutoClose: true, - onPress: () => - void runActionSheetGitSequence('publish', [ - { method: 'git.push', params: { publish: true } } - ]) - } + const actionSheetActions = useMemo( + () => + buildMobileSourceControlActions({ + commitMessage, + stagedCount, + upstream: upstream ?? null, + upstreamKnown, + busyAction, + openingPath, + openingBranchPath, + prAvailable: upstreamKnown && upstream?.hasUpstream === true, + handlers: { + commit: () => void runActionSheetCommit(), + commitPush: () => + void runActionSheetCommitSequence('commit-push', [{ method: 'git.push' }]), + commitSync: () => void runActionSheetCommitSync(), + push: () => void runActionSheetGitSequence('push', [{ method: 'git.push' }]), + pull: () => void runActionSheetGitSequence('pull', [{ method: 'git.pull' }]), + sync: () => void runActionSheetGitSync(), + fetch: () => void runActionSheetGitSequence('fetch', [{ method: 'git.fetch' }]), + publish: () => + void runActionSheetGitSequence('publish', [ + { method: 'git.push', params: { publish: true } } + ]), + fastForward: () => + void runActionSheetGitSequence('fast-forward', [{ method: 'git.fastForward' }]), + rebase: () => void runActionSheetRebase(), + createPr: () => void openPrSheet(false), + pushAndCreatePr: () => void openPrSheet(true), + checkout: () => void openBranchPicker(), + history: () => void openHistory() + } + }).map((action) => ({ ...action, icon: SOURCE_CONTROL_ACTION_ICONS[action.iconKey] })), + [ + busyAction, + commitMessage, + openBranchPicker, + openHistory, + openingBranchPath, + openingPath, + openPrSheet, + runActionSheetCommit, + runActionSheetCommitSequence, + runActionSheetCommitSync, + runActionSheetGitSequence, + runActionSheetGitSync, + runActionSheetRebase, + stagedCount, + upstream, + upstreamKnown ] - }, [ - busyAction, - commitMessage, - openingBranchPath, - openingPath, - runActionSheetCommit, - runActionSheetCommitSequence, - runActionSheetCommitSync, - runActionSheetGitSequence, - runActionSheetGitSync, - stagedCount, - upstream, - upstreamKnown - ]) + ) const renderItem = useCallback< SectionListRenderItem< @@ -1412,7 +1496,23 @@ export default function MobileSourceControlScreen() { {branchEntries.length} on branch ) : null} {status && status.conflictOperation !== 'unknown' ? ( - {status.conflictOperation} + + {status.conflictOperation} + {(status.conflictOperation === 'merge' || + status.conflictOperation === 'rebase') && ( + [styles.abortButton, pressed && styles.abortPressed]} + disabled={busyAction !== null} + onPress={() => void abortConflictOperation(status.conflictOperation)} + > + + {busyAction === `abort-${status.conflictOperation}` + ? 'Aborting…' + : `Abort ${status.conflictOperation}`} + + + )} + ) : null} {actionError ? ( @@ -1554,6 +1654,30 @@ export default function MobileSourceControlScreen() { onSubmitEditing={() => void commit()} /> )} + [ + styles.generateButton, + (stagedCount === 0 || busyAction !== null) && styles.commitButtonDisabled, + pressed && styles.commitButtonPressed + ]} + // Why: stay tappable while generating so the press can cancel + // (disabling it here made the cancel branch below unreachable). + disabled={stagedCount === 0 || busyAction !== null} + onPress={() => + generatingMessage ? cancelGenerateCommitMessage() : void generateCommitMessage() + } + accessibilityLabel={ + generatingMessage + ? 'Cancel commit message generation' + : 'Generate commit message with AI' + } + > + {generatingMessage ? ( + + ) : ( + + )} + [ styles.commitButton, @@ -1613,6 +1737,52 @@ export default function MobileSourceControlScreen() { }} onCancel={() => setDiscardTarget(null)} /> + + setShowPrSheet(false)} + onCreated={(url) => { + setShowPrSheet(false) + setCreatedPrUrl(url) + void loadStatus({ preserveReadyOnFailure: true, force: true }) + }} + /> + + ({ + value: b, + label: b, + subtitle: b === localBranches?.current ? 'current' : undefined + }))} + selected={localBranches?.current ?? ''} + onSelect={(branch) => { + if (branch !== localBranches?.current) { + void checkoutBranch(branch) + } else { + setShowBranchPicker(false) + } + }} + onClose={() => setShowBranchPicker(false)} + /> + + { + if (createdPrUrl) { + openMobilePrUrl(createdPrUrl) + } + setCreatedPrUrl(null) + }} + onCancel={() => setCreatedPrUrl(null)} + /> ) } @@ -1713,11 +1883,32 @@ const styles = StyleSheet.create({ color: colors.textSecondary, fontSize: typography.metaSize }, + conflictRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm + }, conflictText: { color: colors.statusAmber, fontSize: typography.metaSize, textTransform: 'capitalize' }, + abortButton: { + paddingHorizontal: spacing.sm, + paddingVertical: 2, + borderRadius: radii.button, + borderWidth: 1, + borderColor: colors.statusAmber + }, + abortPressed: { + backgroundColor: colors.bgRaised + }, + abortText: { + color: colors.statusAmber, + fontSize: typography.metaSize, + fontWeight: '600', + textTransform: 'capitalize' + }, actionError: { marginTop: spacing.sm, paddingHorizontal: spacing.md, @@ -1923,6 +2114,14 @@ const styles = StyleSheet.create({ justifyContent: 'center', paddingHorizontal: spacing.md }, + generateButton: { + width: 42, + minHeight: 42, + borderRadius: radii.button, + backgroundColor: colors.bgRaised, + alignItems: 'center', + justifyContent: 'center' + }, commitButtonDisabled: { opacity: 0.45 }, diff --git a/mobile/app/index.tsx b/mobile/app/index.tsx index b0e011c0c..2e5b04298 100644 --- a/mobile/app/index.tsx +++ b/mobile/app/index.tsx @@ -23,6 +23,7 @@ import { } from '../src/components/AccountUsage' import AsyncStorage from '@react-native-async-storage/async-storage' import { loadHosts, removeHost, renameHost } from '../src/transport/host-store' +import { pickResumeWorktree } from '../src/worktree/resume-worktree' import type { RpcClient } from '../src/transport/rpc-client' import { useAllHostClients, @@ -73,6 +74,10 @@ type WorktreeSummary = { displayName: string liveTerminalCount: number status?: 'working' | 'active' | 'permission' | 'done' | 'inactive' + // The worktree the desktop currently has focused (exactly one is true). + isActive?: boolean + // Last terminal-output time (ms); breaks ties when nothing is focused. + lastOutputAt?: number } type HostWorktreeInfo = { @@ -179,7 +184,9 @@ function fetchWorktreeInfo( } client - .sendRequest('worktree.ps') + // Why: worktree.ps defaults to 200 and silently truncates; request the full + // set so the host worktree count and active count are accurate. + .sendRequest('worktree.ps', { limit: 10000 }) .then((response) => { if (disposed()) { return @@ -190,7 +197,8 @@ function fetchWorktreeInfo( setCachedWorktrees(hostId, worktrees) const activeStatuses = new Set(['working', 'active', 'permission']) const active = worktrees.filter((w) => w.status && activeStatuses.has(w.status)) - const lastActive = active.length > 0 ? active[0] : (worktrees[0] ?? null) + // Mirror the desktop's focused workspace (see pickResumeWorktree). + const lastActive = pickResumeWorktree(worktrees) setInfo((prev) => ({ ...prev, [hostId]: { diff --git a/mobile/app/settings.tsx b/mobile/app/settings.tsx index a189a8cd0..e9a38685e 100644 --- a/mobile/app/settings.tsx +++ b/mobile/app/settings.tsx @@ -9,6 +9,7 @@ import { Wrench, Shield, LifeBuoy, + Mic, Terminal as TerminalIcon } from 'lucide-react-native' import { colors, spacing, typography } from '../src/theme/mobile-theme' @@ -36,6 +37,15 @@ export default function SettingsScreen() { + [styles.row, pressed && styles.rowPressed]} + onPress={() => router.push('/voice-settings')} + > + + Voice + + + [styles.row, pressed && styles.rowPressed]} onPress={() => router.push('/notifications')} diff --git a/mobile/app/voice-settings.tsx b/mobile/app/voice-settings.tsx new file mode 100644 index 000000000..cfee1854f --- /dev/null +++ b/mobile/app/voice-settings.tsx @@ -0,0 +1,392 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + ActivityIndicator, + Pressable, + ScrollView, + StyleSheet, + Switch, + Text, + View +} from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { useRouter } from 'expo-router' +import { ChevronLeft, ChevronRight } from 'lucide-react-native' +import { colors, radii, spacing, typography } from '../src/theme/mobile-theme' +import { loadHosts } from '../src/transport/host-store' +import type { HostProfile } from '../src/transport/types' +import { useAllHostClients } from '../src/transport/client-context' +import type { RpcClient } from '../src/transport/rpc-client' +import { BottomDrawer } from '../src/components/BottomDrawer' +import { VoiceModelList } from '../src/components/VoiceModelList' +import { + downloadDictationModel, + fetchDictationSetup, + isModelInFlight, + setDictationConfig, + type MobileSpeechModel, + type MobileSpeechSetup +} from '../src/dictation/mobile-dictation-setup' + +const POLL_INTERVAL_MS = 1500 + +const DICTATION_MODES = [ + { value: 'toggle', label: 'Toggle' }, + { value: 'hold', label: 'Hold' } +] as const + +export default function VoiceSettingsScreen(): React.JSX.Element { + const router = useRouter() + const insets = useSafeAreaInsets() + + const [hosts, setHosts] = useState([]) + useEffect(() => { + void loadHosts().then(setHosts) + }, []) + const hostIds = useMemo(() => hosts.map((h) => h.id), [hosts]) + const hostClients = useAllHostClients(hostIds) + // Voice dictation runs on the paired desktop, so pick the first connected host. + const client: RpcClient | null = useMemo( + () => hostClients.find((entry) => entry.state === 'connected')?.client ?? null, + [hostClients] + ) + + const [setup, setSetup] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + const [busyModelId, setBusyModelId] = useState(null) + const [modelDrawerOpen, setModelDrawerOpen] = useState(false) + const pollRef = useRef | null>(null) + + const refresh = useCallback(async () => { + if (!client) { + return + } + try { + setSetup(await fetchDictationSetup(client)) + setError(null) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load voice settings') + } + }, [client]) + + // Initial load once a connected client is available. + useEffect(() => { + if (!client) { + return + } + setLoading(true) + setError(null) + void refresh().finally(() => setLoading(false)) + }, [client, refresh]) + + // Poll only while a model is downloading/extracting; stop otherwise. + useEffect(() => { + const inFlight = setup?.models.some(isModelInFlight) ?? false + if (inFlight && client) { + pollRef.current = setInterval(() => void refresh(), POLL_INTERVAL_MS) + return () => { + if (pollRef.current) { + clearInterval(pollRef.current) + pollRef.current = null + } + } + } + return undefined + }, [setup, client, refresh]) + + const handleToggleEnabled = useCallback( + async (enabled: boolean) => { + if (!client) { + return + } + setError(null) + // Optimistic flip so the switch responds instantly; reconcile below. + setSetup((prev) => (prev ? { ...prev, enabled } : prev)) + try { + setSetup(await setDictationConfig(client, { enabled })) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not update') + void refresh() + } + }, + [client, refresh] + ) + + const handleSelectMode = useCallback( + async (dictationMode: 'toggle' | 'hold') => { + if (!client) { + return + } + setError(null) + setSetup((prev) => (prev ? { ...prev, dictationMode } : prev)) + try { + setSetup(await setDictationConfig(client, { dictationMode })) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not update') + void refresh() + } + }, + [client, refresh] + ) + + const handleUseModel = useCallback( + async (model: MobileSpeechModel) => { + if (!client) { + return + } + setBusyModelId(model.id) + setError(null) + try { + setSetup(await setDictationConfig(client, { enabled: true, modelId: model.id })) + setModelDrawerOpen(false) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not select model') + } finally { + setBusyModelId(null) + } + }, + [client] + ) + + const handleDownload = useCallback( + async (model: MobileSpeechModel) => { + if (!client) { + return + } + setBusyModelId(model.id) + setError(null) + try { + await downloadDictationModel(client, model.id) + await refresh() + } catch (err) { + setError(err instanceof Error ? err.message : 'Download failed') + } finally { + setBusyModelId(null) + } + }, + [client, refresh] + ) + + const enabled = setup?.enabled ?? false + const selectedModel = setup?.models.find((m) => m.id === setup.selectedModelId) + const selectedModelLabel = selectedModel?.label ?? 'None selected' + + return ( + + + router.back()}> + + + Voice + + + {!client ? ( + + Connect to a desktop to manage voice settings. + + ) : loading && setup === null ? ( + + + + ) : setup === null ? ( + + {error ?? 'Failed to load voice settings.'} + + ) : ( + + DICTATION + + + + Enable Voice Dictation + + Dictate text into any focused pane on your desktop. + + + void handleToggleEnabled(v)} + trackColor={{ false: colors.bgRaised, true: colors.textSecondary }} + thumbColor={colors.textPrimary} + /> + + + + + + + Dictation Mode + + Toggle: press once to start, again to stop. Hold: dictate while held. + + + + {DICTATION_MODES.map((mode) => { + const active = setup.dictationMode === mode.value + return ( + void handleSelectMode(mode.value)} + style={[styles.segment, active && styles.segmentActive]} + > + + {mode.label} + + + ) + })} + + + + + SPEECH MODEL + + [ + styles.row, + !enabled && styles.disabled, + pressed && styles.rowPressed + ]} + disabled={!enabled} + onPress={() => setModelDrawerOpen(true)} + > + + Speech Model + + {selectedModelLabel} + + + + + + + {error ? {error} : null} + + )} + + setModelDrawerOpen(false)}> + Speech Model + {setup ? ( + void handleUseModel(m)} + onDownload={(m) => void handleDownload(m)} + /> + ) : null} + + + ) +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: colors.bgBase, + paddingHorizontal: spacing.lg + }, + topRow: { + flexDirection: 'row', + alignItems: 'center', + marginTop: spacing.sm, + marginBottom: spacing.lg + }, + backButton: { + width: 36, + height: 36, + borderRadius: 18, + alignItems: 'center', + justifyContent: 'center', + marginRight: spacing.sm + }, + heading: { + fontSize: 20, + fontWeight: '700', + color: colors.textPrimary + }, + scrollContent: { + paddingBottom: spacing.xl + }, + loading: { paddingVertical: spacing.xl, alignItems: 'center' }, + groupHeading: { + fontSize: 11, + fontWeight: '600', + color: colors.textMuted, + letterSpacing: 0.5, + marginBottom: spacing.xs, + paddingHorizontal: spacing.xs + }, + section: { + backgroundColor: colors.bgPanel, + borderRadius: radii.card, + overflow: 'hidden' + }, + sectionTopGap: { marginTop: spacing.sm }, + inputGroupGap: { marginTop: spacing.xl }, + disabled: { opacity: 0.5 }, + emptyText: { + fontSize: typography.bodySize, + color: colors.textSecondary, + padding: spacing.md + }, + errorText: { + fontSize: typography.bodySize, + color: colors.statusRed, + padding: spacing.md + }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm + 2, + paddingVertical: spacing.md, + paddingHorizontal: spacing.md + 2 + }, + rowPressed: { backgroundColor: colors.bgRaised }, + rowContent: { flex: 1 }, + rowLabel: { + fontSize: typography.bodySize, + fontWeight: '500', + color: colors.textPrimary + }, + drawerTitle: { + fontSize: typography.bodySize, + fontWeight: '700', + color: colors.textPrimary, + paddingHorizontal: spacing.md + 2, + paddingTop: spacing.sm, + paddingBottom: spacing.xs + }, + rowSublabel: { + fontSize: typography.bodySize - 2, + color: colors.textSecondary, + marginTop: 2 + }, + separator: { + height: StyleSheet.hairlineWidth, + backgroundColor: colors.borderSubtle, + marginHorizontal: spacing.md + }, + segmented: { + flexDirection: 'row', + alignItems: 'center', + backgroundColor: colors.bgBase, + borderRadius: radii.button, + padding: 2 + }, + segment: { + paddingHorizontal: spacing.md, + paddingVertical: 6, + borderRadius: radii.button - 1 + }, + segmentActive: { backgroundColor: colors.bgRaised }, + segmentText: { fontSize: typography.metaSize, color: colors.textSecondary, fontWeight: '600' }, + segmentTextActive: { color: colors.textPrimary }, + error: { color: colors.statusRed, fontSize: typography.metaSize, marginTop: spacing.md } +}) diff --git a/mobile/package.json b/mobile/package.json index 7d21a9210..9df74d8fa 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -24,7 +24,9 @@ "expo-constants": "^55.0.16", "expo-crypto": "^55.0.14", "expo-dev-client": "~55.0.35", + "expo-document-picker": "^55.0.13", "expo-haptics": "^55.0.14", + "expo-image-picker": "^55.0.20", "expo-linking": "^55.0.15", "expo-modules-core": "~55.0.25", "expo-network": "~55.0.14", diff --git a/mobile/pnpm-lock.yaml b/mobile/pnpm-lock.yaml index 26e4e4505..68e5ea7c2 100644 --- a/mobile/pnpm-lock.yaml +++ b/mobile/pnpm-lock.yaml @@ -38,9 +38,15 @@ importers: expo-dev-client: specifier: ~55.0.35 version: 55.0.35(expo@55.0.23) + expo-document-picker: + specifier: ^55.0.13 + version: 55.0.13(expo@55.0.23) expo-haptics: specifier: ^55.0.14 version: 55.0.14(expo@55.0.23) + expo-image-picker: + specifier: ^55.0.20 + version: 55.0.20(expo@55.0.23) expo-linking: specifier: ^55.0.15 version: 55.0.15(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6) @@ -1430,56 +1436,48 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [glibc] '@oxfmt/binding-linux-arm64-musl@0.52.0': resolution: {integrity: sha512-wZg6bLjDvh2KibyI3QFUYo8GTXneIFsd0JvehtvJiUmQ8WRPERgxd/VM4ctWb86U5FT1FkqgS8/wZKVB+AZScg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [musl] '@oxfmt/binding-linux-ppc64-gnu@0.52.0': resolution: {integrity: sha512-IngE8uxhNvxcMrLjZNDo9xNLY7rEK33AKnaMd2B46he1e/mz2CfcW6If/U1wUjdRZddm1QzQaciqZkuMkdh1FA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] - libc: [glibc] '@oxfmt/binding-linux-riscv64-gnu@0.52.0': resolution: {integrity: sha512-H3+DdFMv/efN3Efmhsv18jDrpiWWqKG7wsfAlQBqAt6z/E2Bx+TwEj2Nowe51CPOWB8/mFBC2dAMSgVFLvvowA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] - libc: [glibc] '@oxfmt/binding-linux-riscv64-musl@0.52.0': resolution: {integrity: sha512-zji+1kb7lJKohSDjzC1IsS+K/cKRs1hdVf0ZH0VbdbiakmtLvN9twBoXo/k8VdjFax7kfo+DyPxS7vv52br1aw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] - libc: [musl] '@oxfmt/binding-linux-s390x-gnu@0.52.0': resolution: {integrity: sha512-hcLBYedpCy7ToUvvBidWk7+11Yhg1oAZ4+6hKPic/mQI6NaqXJSXMps5nFlwUuX2ewhtLZZDPg63TI042qGKBg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] - libc: [glibc] '@oxfmt/binding-linux-x64-gnu@0.52.0': resolution: {integrity: sha512-IDO2loXK2OtTOhSPchU9MW25mWL2QCDGdJbjN8MXKZVS80qXe5gMTwQWu/gMJ3juoBHbkuUZNB2N1LHzNT7DoA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [glibc] '@oxfmt/binding-linux-x64-musl@0.52.0': resolution: {integrity: sha512-mAV2Hjn0SatJ+KoAzKUC3eJhdJ8wv+3m1KyuS0dTsbF0c5weq+QrCt/DRZZM+uj/XiKzCDEUKYsBF30e2qkcyw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [musl] '@oxfmt/binding-openharmony-arm64@0.52.0': resolution: {integrity: sha512-vd4npaUIwChxp7XzkqmepBWTT9YMcSe/NBApVGPC30/lLyOVaV3dvma1SKo03t8O73BPRAG7EyJzGlN5cJM5hQ==} @@ -1552,56 +1550,48 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [glibc] '@oxlint/binding-linux-arm64-musl@1.67.0': resolution: {integrity: sha512-zB/Tf6sUjmmvvbva9Gj3JTJ8rJ9t4I8/U0o6vSRtd0DRIsIuyegBwJAzhSUFQHdMijIRJkW0exs/yBhpw2S20w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [musl] '@oxlint/binding-linux-ppc64-gnu@1.67.0': resolution: {integrity: sha512-kgU40Gt74CK0TCsF51KZymkIwN9U0BajKsMijB52zPqOeZU9NAHkA/NSQkZDHEaCakx42DxhXkODiAqf2b4Gug==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] - libc: [glibc] '@oxlint/binding-linux-riscv64-gnu@1.67.0': resolution: {integrity: sha512-tOYhkk/iaG9aD3FvGpBFd1Lrw0x0RaVoJBxjUkfNzS50rC5NS5BteNCwgr8A2zCdADrIIoze6D7u6U5Ic++/iQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] - libc: [glibc] '@oxlint/binding-linux-riscv64-musl@1.67.0': resolution: {integrity: sha512-sEtywrPb+0b+tHYl1SDCrw903fiC4eyKoNqzP3v+f2JT3Xcv4NEYG+P8rj+eEnX7IWhqV/xj8/JmcmVj21CXaA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] - libc: [musl] '@oxlint/binding-linux-s390x-gnu@1.67.0': resolution: {integrity: sha512-BvR8Moa0zCLxroOx4vZaZN9nUfwAUpSTwjZdxZyKy4bv3PrzrXrxKR/ZQ0L9wNSvlPhnMJeZfa3q5w6ZCTuN6Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] - libc: [glibc] '@oxlint/binding-linux-x64-gnu@1.67.0': resolution: {integrity: sha512-mm2cxM6fksOpq6l0uFws8BUGKAR4dNa/cZCn37Npq7PFbhD5HDJqWfnoIvTaeRKMy5XdS2tO0MA0qbHDrnXAAA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [glibc] '@oxlint/binding-linux-x64-musl@1.67.0': resolution: {integrity: sha512-WmbMuLapKyDlobMkXAaAL0Y+Uczh4LETfIfQsUpbId4Ip8Ai82/jqeYTOoUCkuuhBFapgqP253+d83tLKOksJg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [musl] '@oxlint/binding-openharmony-arm64@1.67.0': resolution: {integrity: sha512-9g/PqxYJelzzTAOR5Y+RiRqdeydhEuXv2KxNeFcAKQ7UsvnWSY1OP4MsuPMbTO2Pf70tz7mFhl1j13H3fyh+8g==} @@ -2063,42 +2053,36 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-arm64-musl@1.0.0': resolution: {integrity: sha512-EIVjy2cgd7uuMMo94FVkBp7F6DhcZAUwNURkSG3RwUmvAXR6s0ISxM81U+IydcZByPG0pZIHsf1b6kTxoFDgJA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - libc: [musl] '@rolldown/binding-linux-ppc64-gnu@1.0.0': resolution: {integrity: sha512-JEwwOPcwTLAcpDQlqSmjEmfs63xJnSiUNIGvLcDLUHCWK4XowpS/7c7tUsUH6uT/ct6bMUTdXKfI8967FYj6mg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-s390x-gnu@1.0.0': resolution: {integrity: sha512-0wjCFhLrihtAubnT9iA0N++0pSV0z5Hg7tNGdNJ4RFaINceHadoF+kiFGyY1qSSNVIAZtLotG8Ju1bgDPkjnFA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] - libc: [glibc] '@rolldown/binding-linux-x64-gnu@1.0.0': resolution: {integrity: sha512-Dfn7iak9BcMMePxcoJfpSbWqnEyrp/dRF63/8qW/eHBdOZov6x5aShLLEYGYdIeSJ6vMLK/XCVB+lGIxm41bQA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [glibc] '@rolldown/binding-linux-x64-musl@1.0.0': resolution: {integrity: sha512-5/utzzDmD/pD/bmuaUcbTf/sZYy0aztwIVlfpoW1fTjCZ0BaPOMVWGZL1zvgxyi7ZIVYWlxKONHmSbHuiOh8Jw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [musl] '@rolldown/binding-openharmony-arm64@1.0.0': resolution: {integrity: sha512-ouJs8VcUomfLfpbUECqFMRqdV4x6aeAK3MA4m6vTrJJjKyWTV5KnxZx7Jd9G+GlDaQQxubcba00x16OyJ1meig==} @@ -3359,6 +3343,11 @@ packages: peerDependencies: expo: '*' + expo-document-picker@55.0.13: + resolution: {integrity: sha512-IhswJElhdzs3fKDEKW8KXYRoFkWGEsXRMYAZT46Yo56zqqy8yQXrczo33RSwD2hFzNQBdLT97SJL9N311UyS3g==} + peerDependencies: + expo: '*' + expo-file-system@55.0.19: resolution: {integrity: sha512-c4smCbMqELLI3YQrGpw21MwZIREXM2e53vQD/+KWQcae1q+hgw8J2TroEqcQ/jVOtFpZYVvyVfgu4HDKNEKmNw==} peerDependencies: @@ -3384,6 +3373,16 @@ packages: peerDependencies: expo: '*' + expo-image-loader@55.0.1: + resolution: {integrity: sha512-o8gCo1j59XpXDh0/llgNYPcnfecYQhafQAO0yw5pb+kukPizvNoEqea8tFQIIQmNYqxd6Ljgs7lLXed0gXpOdQ==} + peerDependencies: + expo: '*' + + expo-image-picker@55.0.20: + resolution: {integrity: sha512-lfWt/0rPWdKz8AdDEGmGHZIJSNlVc720Dlx5bfou10FU16ZV5wAbTU63nm2jkXd8hbXke4a/2Ha1dzxCVA+LQQ==} + peerDependencies: + expo: '*' + expo-image@55.0.10: resolution: {integrity: sha512-We+vq/Z8jy8zmGxcOP8vrhiWkkwyXFdSks8cSlPi0bpu6D0Ei6l9Nj2xHWCD+yoENh92aCEe1+QRujAwXbogGA==} peerDependencies: @@ -4331,28 +4330,24 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] - libc: [glibc] lightningcss-linux-arm64-musl@1.32.0: resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] - libc: [musl] lightningcss-linux-x64-gnu@1.32.0: resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] - libc: [glibc] lightningcss-linux-x64-musl@1.32.0: resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] - libc: [musl] lightningcss-win32-arm64-msvc@1.32.0: resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} @@ -9935,6 +9930,10 @@ snapshots: expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) expo-dev-menu-interface: 55.0.2(expo@55.0.23) + expo-document-picker@55.0.13(expo@55.0.23): + dependencies: + expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo-file-system@55.0.19(expo@55.0.23)(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6)): dependencies: expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) @@ -9957,6 +9956,15 @@ snapshots: dependencies: expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo-image-loader@55.0.1(expo@55.0.23): + dependencies: + expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + + expo-image-picker@55.0.20(expo@55.0.23): + dependencies: + expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) + expo-image-loader: 55.0.1(expo@55.0.23) + expo-image@55.0.10(expo@55.0.23)(react-native-web@0.21.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6): dependencies: expo: 55.0.23(@babel/core@7.29.0)(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-router@55.0.14)(react-dom@19.2.6(react@19.2.6))(react-native-webview@13.16.1(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native-worklets@0.8.3(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6))(react-native@0.83.9(@babel/core@7.29.0)(@react-native/metro-config@0.85.2(@babel/core@7.29.0))(@types/react@19.2.14)(react@19.2.6))(react@19.2.6)(typescript@5.9.3) diff --git a/mobile/src/components/AgentStateDot.tsx b/mobile/src/components/AgentStateDot.tsx new file mode 100644 index 000000000..916525ef3 --- /dev/null +++ b/mobile/src/components/AgentStateDot.tsx @@ -0,0 +1,65 @@ +import { useEffect, useRef } from 'react' +import { Animated, Easing, StyleSheet, View } from 'react-native' +import type { AgentDotState } from '../worktree/agent-row-display' + +// Per-agent state indicator, 1:1 with desktop AgentStateDot +// (src/renderer/src/components/AgentStateDot.tsx): yellow spinner for 'working', +// emerald for 'done', red for blocked/waiting/interrupted (attention), neutral +// for idle. Distinct from the worktree-level AgentSpinner, which collapses the +// agent vocabulary into the 5-state rollup the sidebar dot uses. +const DOT_COLORS: Record, string> = { + done: '#10b981', + blocked: '#ef4444', + waiting: '#ef4444', + interrupted: '#ef4444', + idle: 'rgba(115,115,115,0.4)' +} + +export function AgentStateDot({ state }: { state: AgentDotState }) { + const spinValue = useRef(new Animated.Value(0)).current + + useEffect(() => { + if (state === 'working') { + const animation = Animated.loop( + Animated.timing(spinValue, { + toValue: 1, + duration: 1000, + easing: Easing.linear, + useNativeDriver: true + }) + ) + animation.start() + return () => animation.stop() + } + spinValue.setValue(0) + return undefined + }, [state, spinValue]) + + if (state === 'working') { + const rotate = spinValue.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] }) + return ( + + + + ) + } + + return ( + + + + ) +} + +const styles = StyleSheet.create({ + wrapper: { width: 10, height: 10, alignItems: 'center', justifyContent: 'center' }, + dot: { width: 6, height: 6, borderRadius: 3 }, + spinner: { + width: 6, + height: 6, + borderRadius: 3, + borderWidth: 1.5, + borderColor: '#eab308', + borderTopColor: 'transparent' + } +}) diff --git a/mobile/src/components/MobileDictationSetupSheet.tsx b/mobile/src/components/MobileDictationSetupSheet.tsx new file mode 100644 index 000000000..f92a417ca --- /dev/null +++ b/mobile/src/components/MobileDictationSetupSheet.tsx @@ -0,0 +1,290 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + ActivityIndicator, + Pressable, + ScrollView, + StyleSheet, + Switch, + Text, + View +} from 'react-native' +import { Check, Download } from 'lucide-react-native' +import { BottomDrawer } from './BottomDrawer' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import type { RpcClient } from '../transport/rpc-client' +import { triggerError, triggerSuccess } from '../platform/haptics' +import { + downloadDictationModel, + fetchDictationSetup, + isModelInFlight, + setDictationConfig, + type MobileSpeechModel, + type MobileSpeechSetup +} from '../dictation/mobile-dictation-setup' + +const POLL_INTERVAL_MS = 1500 + +type Props = { + visible: boolean + client: RpcClient | null + onClose: () => void + // Called after the user reaches a ready+enabled state, so the caller can retry. + onReady?: () => void +} + +function formatSize(bytes: number | null): string { + if (!bytes) { + return '' + } + return `${Math.round(bytes / 1_000_000)} MB` +} + +// Lets the user enable dictation and download a speech model on the paired +// desktop, from the phone. Polls while a download is in flight. +export function MobileDictationSetupSheet({ visible, client, onClose, onReady }: Props) { + const [setup, setSetup] = useState(null) + const [error, setError] = useState(null) + const [busy, setBusy] = useState(null) + const pollRef = useRef | null>(null) + + const refresh = useCallback(async () => { + if (!client) { + return + } + try { + setSetup(await fetchDictationSetup(client)) + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load') + } + }, [client]) + + useEffect(() => { + if (visible) { + setError(null) + void refresh() + } + }, [visible, refresh]) + + // Poll only while something is downloading/extracting; stop otherwise. + useEffect(() => { + const inFlight = setup?.models.some(isModelInFlight) ?? false + if (visible && inFlight && client) { + pollRef.current = setInterval(() => void refresh(), POLL_INTERVAL_MS) + return () => { + if (pollRef.current) { + clearInterval(pollRef.current) + pollRef.current = null + } + } + } + return undefined + }, [visible, setup, client, refresh]) + + const handleDownload = useCallback( + async (model: MobileSpeechModel) => { + if (!client) { + return + } + setBusy(model.id) + setError(null) + try { + await downloadDictationModel(client, model.id) + await refresh() + } catch (err) { + triggerError() + setError(err instanceof Error ? err.message : 'Download failed') + } finally { + setBusy(null) + } + }, + [client, refresh] + ) + + const handleUseModel = useCallback( + async (model: MobileSpeechModel) => { + if (!client) { + return + } + setBusy(model.id) + setError(null) + try { + const next = await setDictationConfig(client, { enabled: true, modelId: model.id }) + setSetup(next) + triggerSuccess() + onReady?.() + } catch (err) { + triggerError() + setError(err instanceof Error ? err.message : 'Could not select model') + } finally { + setBusy(null) + } + }, + [client, onReady] + ) + + const handleToggleEnabled = useCallback( + async (enabled: boolean) => { + if (!client) { + return + } + setError(null) + try { + setSetup(await setDictationConfig(client, { enabled })) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not update') + } + }, + [client] + ) + + return ( + + + Set up voice dictation + + Download a model and enable dictation on your desktop — all from here. + + + {setup === null ? ( + + + + ) : ( + <> + + Dictation enabled + void handleToggleEnabled(v)} /> + + + {setup.models.map((model) => { + const isSelected = model.id === setup.selectedModelId + const inFlight = isModelInFlight(model) + const rowBusy = busy === model.id + return ( + + + + {model.label} + {model.recommended ? ( + Recommended + ) : null} + + + {model.provider === 'openai' ? 'OpenAI API' : formatSize(model.sizeBytes)} + {inFlight && model.progress != null + ? ` · ${Math.round(model.progress * 100)}%` + : model.status === 'extracting' + ? ' · extracting…' + : ''} + + + {model.provider === 'openai' ? ( + + {model.status === 'ready' ? 'API key set' : 'Set up on desktop'} + + ) : model.status === 'ready' ? ( + isSelected ? ( + + + In use + + ) : ( + [ + styles.actionButton, + pressed && styles.actionPressed + ]} + disabled={rowBusy} + onPress={() => void handleUseModel(model)} + > + Use + + ) + ) : inFlight ? ( + + ) : ( + [ + styles.actionButton, + pressed && styles.actionPressed + ]} + disabled={rowBusy} + onPress={() => void handleDownload(model)} + > + {rowBusy ? ( + + ) : ( + <> + + Download + + )} + + )} + + ) + })} + + )} + {error ? {error} : null} + + + ) +} + +const styles = StyleSheet.create({ + scroll: { maxHeight: 460 }, + heading: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '700' + }, + subtitle: { + color: colors.textSecondary, + fontSize: typography.metaSize, + marginTop: spacing.xs, + marginBottom: spacing.md + }, + loading: { paddingVertical: spacing.xl, alignItems: 'center' }, + enableRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingVertical: spacing.sm, + borderBottomWidth: 1, + borderBottomColor: colors.borderSubtle, + marginBottom: spacing.sm + }, + enableLabel: { color: colors.textPrimary, fontSize: typography.bodySize }, + modelRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: spacing.md, + paddingVertical: spacing.sm + }, + modelInfo: { flex: 1, minWidth: 0 }, + modelTitleRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + modelLabel: { color: colors.textPrimary, fontSize: typography.bodySize }, + recommended: { + color: colors.statusGreen, + fontSize: 10, + fontWeight: '700' + }, + modelMeta: { color: colors.textMuted, fontSize: typography.metaSize, marginTop: 2 }, + modelStateText: { color: colors.textMuted, fontSize: typography.metaSize }, + actionButton: { + flexDirection: 'row', + alignItems: 'center', + gap: 5, + paddingHorizontal: spacing.md, + paddingVertical: 6, + borderRadius: radii.button, + backgroundColor: colors.bgRaised + }, + actionPressed: { opacity: 0.7 }, + actionText: { color: colors.textSecondary, fontSize: typography.metaSize, fontWeight: '600' }, + selectedTag: { flexDirection: 'row', alignItems: 'center', gap: 4 }, + selectedText: { color: colors.statusGreen, fontSize: typography.metaSize, fontWeight: '600' }, + error: { color: colors.statusRed, fontSize: typography.metaSize, marginTop: spacing.md } +}) diff --git a/mobile/src/components/MobileHtmlPreview.tsx b/mobile/src/components/MobileHtmlPreview.tsx new file mode 100644 index 000000000..335d2600f --- /dev/null +++ b/mobile/src/components/MobileHtmlPreview.tsx @@ -0,0 +1,90 @@ +import { useState } from 'react' +import { Linking, Pressable, StyleSheet, Text, View } from 'react-native' +import { WebView } from 'react-native-webview' +import { Code, Eye } from 'lucide-react-native' +import { colors, spacing, typography } from '../theme/mobile-theme' + +type Props = { + html: string + // Rendered when the user flips to "Source" (the existing syntax view). + renderSource: () => React.ReactNode +} + +// Renders an agent-produced HTML artifact in a sandboxed WebView, with a +// Preview/Source toggle. Navigation is locked: only the initial inline document +// loads in-place; any link tap opens externally so a page can't hijack the +// review surface. +export function MobileHtmlPreview({ html, renderSource }: Props) { + const [mode, setMode] = useState<'preview' | 'source'>('preview') + + return ( + + + setMode('preview')} + accessibilityLabel="Preview rendered HTML" + > + + Preview + + setMode('source')} + accessibilityLabel="View HTML source" + > + + Source + + + {mode === 'preview' ? ( + { + if (request.url === 'about:blank' || request.url.startsWith('data:')) { + return true + } + void Linking.openURL(request.url).catch(() => {}) + return false + }} + /> + ) : ( + renderSource() + )} + + ) +} + +const styles = StyleSheet.create({ + container: { flex: 1 }, + toolbar: { + flexDirection: 'row', + gap: spacing.sm, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + borderBottomWidth: 1, + borderBottomColor: colors.borderSubtle + }, + toggle: { + flexDirection: 'row', + alignItems: 'center', + gap: 5, + paddingHorizontal: spacing.sm, + paddingVertical: 4, + borderRadius: 6, + backgroundColor: colors.bgRaised + }, + toggleActive: { + backgroundColor: colors.bgPanel, + borderWidth: 1, + borderColor: colors.borderSubtle + }, + toggleText: { color: colors.textSecondary, fontSize: typography.metaSize }, + webview: { flex: 1, backgroundColor: '#ffffff' } +}) diff --git a/mobile/src/components/MobilePrComposeSheet.tsx b/mobile/src/components/MobilePrComposeSheet.tsx new file mode 100644 index 000000000..46b2359ba --- /dev/null +++ b/mobile/src/components/MobilePrComposeSheet.tsx @@ -0,0 +1,281 @@ +import { useCallback, useEffect, useState } from 'react' +import { + ActivityIndicator, + Linking, + Pressable, + ScrollView, + StyleSheet, + Switch, + Text, + TextInput, + View +} from 'react-native' +import { Sparkles } from 'lucide-react-native' +import type { HostedReviewProvider } from '../../../src/shared/hosted-review' +import { BottomDrawer } from './BottomDrawer' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import { triggerError, triggerSuccess } from '../platform/haptics' +import { createMobilePr } from '../source-control/mobile-pr-create' + +type PrPrefill = { + base: string + title: string + body: string + provider: HostedReviewProvider +} + +type Props = { + visible: boolean + client: RpcClient | null + worktreeId: string + prefill: PrPrefill + onClose: () => void + onCreated: (url: string) => void +} + +// PR compose sheet: title/body/base/draft with AI prefill (git.generate +// PullRequestFields), submitting via hostedReview.create. Mirrors the desktop +// CreateHostedReviewComposer flow at mobile scale. +export function MobilePrComposeSheet({ + visible, + client, + worktreeId, + prefill, + onClose, + onCreated +}: Props) { + const [title, setTitle] = useState(prefill.title) + const [body, setBody] = useState(prefill.body) + const [base, setBase] = useState(prefill.base) + const [draft, setDraft] = useState(false) + const [generating, setGenerating] = useState(false) + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState(null) + + useEffect(() => { + if (visible) { + setTitle(prefill.title) + setBody(prefill.body) + setBase(prefill.base) + setDraft(false) + setError(null) + } + // Why: depend on the prefill *fields*, not the object identity — a parent + // rerender that produces a new prefill object would otherwise wipe the + // user's in-progress edits while the sheet is open. + }, [visible, prefill.title, prefill.body, prefill.base]) + + const generate = useCallback(async () => { + if (!client || generating) { + return + } + setGenerating(true) + setError(null) + try { + const response = await client.sendRequest('git.generatePullRequestFields', { + worktree: `id:${worktreeId}`, + base, + title, + body, + draft + }) + if (!response.ok) { + setError(response.error?.message || 'Failed to generate PR fields') + return + } + const result = (response as RpcSuccess).result as { + success?: boolean + fields?: { base: string; title: string; body: string; draft: boolean } + error?: string + } + if (result.success && result.fields) { + setBase(result.fields.base || base) + setTitle(result.fields.title || title) + setBody(result.fields.body || body) + setDraft(result.fields.draft) + } else if (result.error) { + setError(result.error) + } + } finally { + setGenerating(false) + } + }, [base, body, client, draft, generating, title, worktreeId]) + + const submit = useCallback(async () => { + if (!client || submitting || title.trim().length === 0) { + return + } + setSubmitting(true) + setError(null) + try { + const outcome = await createMobilePr(client, worktreeId, { + provider: prefill.provider, + base, + title, + body, + draft + }) + if (outcome.ok) { + triggerSuccess() + onCreated(outcome.url) + } else { + triggerError() + setError(outcome.error) + } + } finally { + setSubmitting(false) + } + }, [base, body, client, draft, onCreated, prefill.provider, submitting, title, worktreeId]) + + return ( + + + Create Pull Request + + Title + [styles.genButton, pressed && styles.genButtonPressed]} + disabled={generating || submitting} + onPress={() => void generate()} + accessibilityLabel="Generate PR fields with AI" + > + {generating ? ( + + ) : ( + + )} + + + + Base branch + + Description + + + Draft + + + {error ? {error} : null} + [ + styles.submit, + (submitting || title.trim().length === 0) && styles.submitDisabled, + pressed && styles.submitPressed + ]} + disabled={submitting || title.trim().length === 0} + onPress={() => void submit()} + > + {submitting ? ( + + ) : ( + Create Pull Request + )} + + + + ) +} + +export function openMobilePrUrl(url: string): void { + void Linking.openURL(url) +} + +const styles = StyleSheet.create({ + scroll: { maxHeight: 460 }, + heading: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '700', + marginBottom: spacing.sm + }, + fieldRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between' + }, + label: { + color: colors.textSecondary, + fontSize: typography.metaSize, + marginTop: spacing.md, + marginBottom: spacing.xs + }, + genButton: { + width: 32, + height: 32, + borderRadius: radii.button, + backgroundColor: colors.bgRaised, + alignItems: 'center', + justifyContent: 'center', + marginTop: spacing.sm + }, + genButtonPressed: { opacity: 0.7 }, + titleInput: { + backgroundColor: colors.bgRaised, + borderRadius: radii.input, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + color: colors.textPrimary, + fontSize: typography.bodySize + }, + bodyInput: { + backgroundColor: colors.bgRaised, + borderRadius: radii.input, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + color: colors.textPrimary, + fontSize: typography.bodySize, + minHeight: 96, + textAlignVertical: 'top' + }, + draftRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + marginTop: spacing.md + }, + error: { + color: colors.statusRed, + fontSize: typography.metaSize, + marginTop: spacing.md + }, + submit: { + marginTop: spacing.lg, + minHeight: 46, + borderRadius: radii.button, + backgroundColor: colors.textPrimary, + alignItems: 'center', + justifyContent: 'center' + }, + submitDisabled: { opacity: 0.45 }, + submitPressed: { opacity: 0.8 }, + submitText: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '600' + } +}) diff --git a/mobile/src/components/MobileRepoIcon.tsx b/mobile/src/components/MobileRepoIcon.tsx new file mode 100644 index 000000000..e4f7f9664 --- /dev/null +++ b/mobile/src/components/MobileRepoIcon.tsx @@ -0,0 +1,92 @@ +import { + Bot, + Box, + Braces, + Briefcase, + Building2, + Code2, + Cpu, + Database, + Folder, + Gauge, + Globe, + Layers, + type LucideIcon, + Package, + Palette, + Rocket, + Server, + Shapes, + Sparkles, + SquareTerminal, + Wrench +} from 'lucide-react-native' +import { Image, StyleSheet, Text, View } from 'react-native' +import type { RepoIcon } from '../../../src/shared/repo-icon' +import { colors } from '../theme/mobile-theme' + +// The lucide names the desktop repo-icon picker offers (src/renderer/src/ +// components/repo/repo-icon.tsx). Mobile renders the same glyph so the project +// header icon matches desktop instead of a bare colored dot. +const REPO_LUCIDE_ICONS: Record = { + Folder, + Code2, + SquareTerminal, + Bot, + Package, + Database, + Globe, + Server, + Layers, + Box, + Braces, + Briefcase, + Building2, + Cpu, + Gauge, + Palette, + Rocket, + Shapes, + Sparkles, + Wrench +} + +type Props = { + repoIcon?: RepoIcon | null + size?: number + color?: string +} + +// Renders a repo/project icon matching the desktop sidebar: a custom image +// (favicon/avatar/upload), an emoji, or a lucide glyph. Falls back to Folder, +// the desktop default, so a project always shows an icon rather than a dot. +export function MobileRepoIcon({ repoIcon, size = 14, color = colors.textSecondary }: Props) { + if (repoIcon?.type === 'image') { + return ( + + ) + } + if (repoIcon?.type === 'emoji') { + return {repoIcon.emoji} + } + const Icon = (repoIcon?.type === 'lucide' && REPO_LUCIDE_ICONS[repoIcon.name]) || Folder + return ( + + + + ) +} + +const styles = StyleSheet.create({ + emoji: { + textAlign: 'center' + }, + glyph: { + alignItems: 'center', + justifyContent: 'center' + } +}) diff --git a/mobile/src/components/VoiceModelList.tsx b/mobile/src/components/VoiceModelList.tsx new file mode 100644 index 000000000..4f74d18b5 --- /dev/null +++ b/mobile/src/components/VoiceModelList.tsx @@ -0,0 +1,151 @@ +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native' +import { Check, Download } from 'lucide-react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import { + isModelInFlight, + type MobileSpeechModel, + type MobileSpeechSetup +} from '../dictation/mobile-dictation-setup' + +type Props = { + setup: MobileSpeechSetup + // Disabled mirrors desktop: the model list greys out when dictation is off. + disabled: boolean + busyModelId: string | null + onUseModel: (model: MobileSpeechModel) => void + onDownload: (model: MobileSpeechModel) => void +} + +function formatSize(bytes: number | null): string { + if (!bytes) { + return '' + } + return `${Math.round(bytes / 1_000_000)} MB` +} + +function modelMeta(model: MobileSpeechModel): string { + if (model.provider === 'openai') { + return 'OpenAI API' + } + const inFlight = isModelInFlight(model) + if (inFlight && model.progress != null) { + return `${formatSize(model.sizeBytes)} · ${Math.round(model.progress * 100)}%` + } + if (model.status === 'extracting') { + return `${formatSize(model.sizeBytes)} · extracting…` + } + return formatSize(model.sizeBytes) +} + +// Renders the speech-model rows shared between the setup sheet and the Voice +// settings page: size/progress, recommended badge, selected check, download. +export function VoiceModelList({ + setup, + disabled, + busyModelId, + onUseModel, + onDownload +}: Props): React.JSX.Element { + return ( + + {setup.models.map((model, idx) => { + const isSelected = model.id === setup.selectedModelId + const inFlight = isModelInFlight(model) + const rowBusy = busyModelId === model.id + return ( + + {idx > 0 && } + + + + {model.label} + {model.recommended ? Recommended : null} + + {modelMeta(model)} + + {model.provider === 'openai' ? ( + + {model.status === 'ready' ? 'API key set' : 'Set up on desktop'} + + ) : model.status === 'ready' ? ( + isSelected ? ( + + + In use + + ) : ( + [styles.actionButton, pressed && styles.actionPressed]} + disabled={rowBusy} + onPress={() => onUseModel(model)} + > + Use + + ) + ) : inFlight ? ( + + ) : ( + [styles.iconButton, pressed && styles.actionPressed]} + disabled={rowBusy} + onPress={() => onDownload(model)} + accessibilityLabel={'Download ' + model.label} + > + {rowBusy ? ( + + ) : ( + + )} + + )} + + + ) + })} + + ) +} + +const styles = StyleSheet.create({ + disabled: { opacity: 0.5 }, + modelRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: spacing.md, + paddingVertical: spacing.md, + paddingHorizontal: spacing.md + 2 + }, + modelInfo: { flex: 1, minWidth: 0 }, + modelTitleRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + modelLabel: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '500' }, + recommended: { color: colors.statusGreen, fontSize: 10, fontWeight: '700' }, + modelMeta: { color: colors.textMuted, fontSize: typography.metaSize, marginTop: 2 }, + modelStateText: { color: colors.textMuted, fontSize: typography.metaSize }, + actionButton: { + flexDirection: 'row', + alignItems: 'center', + gap: 5, + paddingHorizontal: spacing.md, + paddingVertical: 6, + borderRadius: radii.button, + backgroundColor: colors.bgRaised + }, + actionPressed: { opacity: 0.7 }, + actionText: { color: colors.textSecondary, fontSize: typography.metaSize, fontWeight: '600' }, + iconButton: { + width: 34, + height: 34, + borderRadius: radii.button, + alignItems: 'center', + justifyContent: 'center', + backgroundColor: colors.bgRaised + }, + selectedTag: { flexDirection: 'row', alignItems: 'center', gap: 4 }, + selectedText: { color: colors.statusGreen, fontSize: typography.metaSize, fontWeight: '600' }, + separator: { + height: StyleSheet.hairlineWidth, + backgroundColor: colors.borderSubtle, + marginHorizontal: spacing.md + } +}) diff --git a/mobile/src/components/WorktreeAgentList.tsx b/mobile/src/components/WorktreeAgentList.tsx new file mode 100644 index 000000000..dc357ad68 --- /dev/null +++ b/mobile/src/components/WorktreeAgentList.tsx @@ -0,0 +1,39 @@ +import { useMemo } from 'react' +import { StyleSheet, View } from 'react-native' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { flattenAgentRowLineage } from '../worktree/agent-row-lineage' +import { WorktreeAgentRow } from './WorktreeAgentRow' + +type Props = { + agents: RuntimeWorktreeAgentRow[] + now: number + unvisited: boolean +} + +// Inline agent list for one worktree row: flattens the spawn lineage and renders +// a depth-indented WorktreeAgentRow per agent, mirroring the desktop sidebar's +// WorktreeCardAgents. +export function WorktreeAgentList({ agents, now, unvisited }: Props) { + // Why: rebuild the lineage tree only when the agent list changes, not on every + // re-render (the shared useNow tick re-renders this list every 30s). + const nodes = useMemo(() => flattenAgentRowLineage(agents), [agents]) + return ( + + {nodes.map((node) => ( + + ))} + + ) +} + +const styles = StyleSheet.create({ + list: { + marginTop: 3 + } +}) diff --git a/mobile/src/components/WorktreeAgentRow.tsx b/mobile/src/components/WorktreeAgentRow.tsx new file mode 100644 index 000000000..509b3f603 --- /dev/null +++ b/mobile/src/components/WorktreeAgentRow.tsx @@ -0,0 +1,60 @@ +import { StyleSheet, Text, View } from 'react-native' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { colors, spacing } from '../theme/mobile-theme' +import { agentDisplayLabel, agentDotState, formatTimeAgo } from '../worktree/agent-row-display' +import { AgentStateDot } from './AgentStateDot' +import { MobileAgentIcon } from './MobileAgentIcon' + +const INDENT_PER_DEPTH = 14 + +type Props = { + agent: RuntimeWorktreeAgentRow + depth: number + now: number + // Bold/foreground until the user has visited the worktree, mirroring desktop's + // unvisited rule (the workspace title and its agent rows share one signal). + unvisited: boolean +} + +// One inline agent row: state dot → identity → last message/prompt → time ago. +// Mirrors desktop DashboardAgentRow's compact in-card layout. +export function WorktreeAgentRow({ agent, depth, now, unvisited }: Props) { + const dotState = agentDotState(agent, now) + const label = agentDisplayLabel(agent, now) + const ts = formatTimeAgo(agent.stateStartedAt, now) + + return ( + + + {/* Agent identity logo (Claude/Codex/…), matching the desktop sidebar's + agent icons instead of a two-letter text code. */} + {agent.agentType ? : null} + + {label} + + {ts} + + ) +} + +const styles = StyleSheet.create({ + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.xs, + marginTop: 3 + }, + label: { + flex: 1, + fontSize: 11, + color: colors.textMuted + }, + labelUnvisited: { + color: colors.textPrimary, + fontWeight: '600' + }, + time: { + fontSize: 10, + color: colors.textMuted + } +}) diff --git a/mobile/src/components/WorktreeListRow.tsx b/mobile/src/components/WorktreeListRow.tsx new file mode 100644 index 000000000..0695a49e9 --- /dev/null +++ b/mobile/src/components/WorktreeListRow.tsx @@ -0,0 +1,239 @@ +import { Bell, GitPullRequest } from 'lucide-react-native' +import { Pressable, StyleSheet, Text, View } from 'react-native' +import type { RepoIcon } from '../../../src/shared/repo-icon' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { triggerMediumImpact } from '../platform/haptics' +import { colors, spacing, typography } from '../theme/mobile-theme' +import { AgentSpinner } from './AgentSpinner' +import { MobileRepoIcon } from './MobileRepoIcon' +import { WorktreeAgentList } from './WorktreeAgentList' +import { WorktreeMetaGlyphs, prStateColor } from './WorktreeMetaGlyphs' + +// Strip the refs/heads/ prefix for display, matching the desktop sidebar +// (WorktreeCardHelpers.formatBranchName). +function displayBranch(branch: string): string { + return branch.replace(/^refs\/heads\//, '') +} + +// Minimal row shape needed for rendering — a structural subset of the screen's +// Worktree so this component stays decoupled from the screen's local type. +export type WorktreeListRowItem = { + worktreeId: string + repo: string + branch: string + displayName: string + liveTerminalCount: number + preview: string + unread: boolean + isActive?: boolean + linkedPR: { number: number; state: string } | null + linkedIssue?: number | null + linkedLinearIssue?: string | null + linkedGitLabMR?: number | null + linkedGitLabIssue?: number | null + comment?: string + agents?: RuntimeWorktreeAgentRow[] +} + +type WorktreeRollupStatus = 'working' | 'active' | 'permission' | 'done' | 'inactive' + +type Props = { + item: T + isReadOnly: boolean + now: number + repoColor: string + repoIcon?: RepoIcon | null + // When the list is already grouped under this repo's section header, the row + // omits its own repo icon+name to avoid the redundant "📁 orca" on every row. + hideRepo?: boolean + status: WorktreeRollupStatus + onPress: (item: T) => void + onLongPress: (item: T) => void +} + +export function WorktreeListRow({ + item, + isReadOnly, + now, + repoColor, + repoIcon, + hideRepo = false, + status, + onPress, + onLongPress +}: Props) { + return ( + [ + styles.worktreeRow, + item.isActive && styles.worktreeRowActive, + pressed && styles.worktreeRowPressed + ]} + disabled={isReadOnly} + onPress={() => onPress(item)} + onLongPress={() => { + triggerMediumImpact() + onLongPress(item) + }} + delayLongPress={400} + > + + + {item.unread && ( + + )} + + + + + + {item.displayName || item.repo} + + {item.linkedPR && ( + + + + #{item.linkedPR.number} + + + )} + + + + {/* Repo glyph+name only when not already grouped under this repo; + MobileRepoIcon falls back to a Folder (matching desktop's default) + rather than a bare colored dot. */} + {!hideRepo && ( + <> + + + {item.repo} + + + )} + + {displayBranch(item.branch)} + + + {/* Only agents get a secondary activity line, matching desktop. A plain + terminal's shell-output tail is intentionally not surfaced here. */} + {item.agents && item.agents.length > 0 ? ( + + ) : null} + + + {item.liveTerminalCount > 0 && ( + {item.liveTerminalCount} + )} + + ) +} + +const styles = StyleSheet.create({ + worktreeRow: { + flexDirection: 'row', + alignItems: 'flex-start', + paddingVertical: spacing.sm + 2, + paddingHorizontal: spacing.lg, + // Reserve the active accent bar width so active/inactive rows align. + borderLeftWidth: 2, + borderLeftColor: 'transparent' + }, + worktreeRowPressed: { + backgroundColor: colors.bgRaised + }, + // Highlight the worktree currently focused on the desktop, mirroring the + // desktop sidebar's selected-card treatment (raised fill + left accent). + worktreeRowActive: { + backgroundColor: colors.bgPanel, + // Neutral grey accent, matching the desktop's active-tab indicator rather + // than a blue line. + borderLeftColor: colors.textSecondary + }, + indicatorCol: { + width: 20, + alignItems: 'center', + paddingTop: 6, + marginRight: spacing.sm, + gap: 4 + }, + unreadBell: { + marginTop: 2 + }, + worktreeMain: { + flex: 1, + marginRight: spacing.sm + }, + worktreeNameRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm + }, + worktreeName: { + fontSize: 14, + fontWeight: '600', + color: colors.textPrimary, + flexShrink: 1 + }, + worktreeNameUnread: { + fontWeight: '700' + }, + textReadOnly: { + opacity: 0.5 + }, + prBadge: { + flexDirection: 'row', + alignItems: 'center', + gap: 3, + backgroundColor: colors.bgRaised, + paddingHorizontal: 5, + paddingVertical: 1, + borderRadius: 4 + }, + prNumber: { + fontSize: 10, + color: colors.textSecondary + }, + worktreeMetaRow: { + flexDirection: 'row', + alignItems: 'center', + marginTop: 2, + gap: spacing.xs + }, + repoName: { + fontSize: 11, + color: colors.textSecondary, + maxWidth: 100 + }, + branchName: { + fontSize: 11, + color: colors.textMuted, + fontFamily: typography.monoFamily, + flexShrink: 1 + }, + terminalCount: { + fontSize: typography.metaSize, + color: colors.textMuted, + minWidth: 16, + textAlign: 'right', + paddingTop: 3 + } +}) diff --git a/mobile/src/components/WorktreeMetaGlyphs.tsx b/mobile/src/components/WorktreeMetaGlyphs.tsx new file mode 100644 index 000000000..38d67cc81 --- /dev/null +++ b/mobile/src/components/WorktreeMetaGlyphs.tsx @@ -0,0 +1,68 @@ +import { CircleDot, GitMerge, StickyNote } from 'lucide-react-native' +import { StyleSheet, Text, View } from 'react-native' +import { colors } from '../theme/mobile-theme' + +// PR chip color by state, mirroring the desktop ReviewIcon palette: merged = +// purple, open = green, closed = red, draft/unknown = muted. +export function prStateColor(state: string): string { + const s = state.toLowerCase() + if (s === 'merged') { + return '#a78bfa' + } + if (s === 'open') { + return colors.statusGreen + } + if (s === 'closed') { + return colors.statusRed + } + return colors.textSecondary +} + +type Props = { + comment?: string | null + linkedLinearIssue?: string | null + linkedGitLabMR?: number | null + linkedIssue?: number | null + linkedGitLabIssue?: number | null +} + +// Presence glyphs for linked notes / Linear / GitLab MR / issue, matching the +// desktop WorktreeCardMetaBadges row. Mobile shows presence only; the full +// detail (title/state/labels) is a follow-up detail sheet. +export function WorktreeMetaGlyphs({ + comment, + linkedLinearIssue, + linkedGitLabMR, + linkedIssue, + linkedGitLabIssue +}: Props) { + const hasNotes = (comment ?? '').trim().length > 0 + const hasLinear = Boolean(linkedLinearIssue) + const hasGitLabMR = linkedGitLabMR != null + const hasIssue = linkedIssue != null || linkedGitLabIssue != null + if (!hasNotes && !hasLinear && !hasGitLabMR && !hasIssue) { + return null + } + return ( + + {hasNotes && } + {hasIssue && } + {hasLinear && L} + {hasGitLabMR && } + + ) +} + +const styles = StyleSheet.create({ + metaGlyphs: { + flexDirection: 'row', + alignItems: 'center', + gap: 5, + marginLeft: 2 + }, + linearGlyph: { + fontSize: 10, + fontWeight: '700', + color: colors.textMuted + } +}) diff --git a/mobile/src/dictation/mobile-dictation-setup.test.ts b/mobile/src/dictation/mobile-dictation-setup.test.ts new file mode 100644 index 000000000..7fa1ca221 --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-setup.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' +import { + downloadDictationModel, + fetchDictationSetup, + isDictationReady, + isDictationSetupRequiredError, + isModelInFlight, + setDictationConfig, + type MobileSpeechModel, + type MobileSpeechSetup +} from './mobile-dictation-setup' + +function ok(result: unknown): RpcSuccess { + return { id: 'r', ok: true, result, _meta: { runtimeId: 'rt' } } +} +function fail(message: string): RpcFailure { + return { id: 'r', ok: false, error: { code: 'x', message }, _meta: { runtimeId: 'rt' } } +} +function clientWith(responses: RpcResponse[]): Pick & { + calls: Array<{ method: string; params: unknown }> +} { + const calls: Array<{ method: string; params: unknown }> = [] + return { + calls, + sendRequest: vi.fn(async (method: string, params?: unknown) => { + calls.push({ method, params }) + return responses.shift() ?? fail('unexpected') + }) + } +} + +function model(overrides: Partial = {}): MobileSpeechModel { + return { + id: 'm1', + label: 'M1', + provider: 'local', + sizeBytes: 100, + recommended: true, + status: 'not-downloaded', + progress: null, + ...overrides + } +} + +describe('isDictationSetupRequiredError', () => { + it('matches the setup-required error codes', () => { + expect(isDictationSetupRequiredError('voice_dictation_disabled')).toBe(true) + expect(isDictationSetupRequiredError('voice_model_not_selected')).toBe(true) + expect(isDictationSetupRequiredError('voice_model_not_ready:not-downloaded')).toBe(true) + expect(isDictationSetupRequiredError('dictation_already_active')).toBe(false) + expect(isDictationSetupRequiredError('network down')).toBe(false) + }) +}) + +describe('rpc wrappers', () => { + it('fetches setup', async () => { + const setup: MobileSpeechSetup = { enabled: false, selectedModelId: '', models: [] } + const client = clientWith([ok(setup)]) + await expect(fetchDictationSetup(client)).resolves.toEqual(setup) + expect(client.calls[0]).toEqual({ method: 'speech.models.list', params: null }) + }) + + it('starts a download', async () => { + const client = clientWith([ok({ started: true })]) + await downloadDictationModel(client, 'm1') + expect(client.calls[0]).toEqual({ method: 'speech.models.download', params: { modelId: 'm1' } }) + }) + + it('sets config', async () => { + const setup: MobileSpeechSetup = { enabled: true, selectedModelId: 'm1', models: [] } + const client = clientWith([ok(setup)]) + await expect(setDictationConfig(client, { enabled: true, modelId: 'm1' })).resolves.toEqual( + setup + ) + expect(client.calls[0]).toEqual({ + method: 'speech.dictation.setup', + params: { enabled: true, modelId: 'm1' } + }) + }) + + it('surfaces RPC failures as errors', async () => { + const client = clientWith([fail('disconnected')]) + await expect(fetchDictationSetup(client)).rejects.toThrow('disconnected') + }) +}) + +describe('state helpers', () => { + it('isModelInFlight covers downloading + extracting', () => { + expect(isModelInFlight(model({ status: 'downloading' }))).toBe(true) + expect(isModelInFlight(model({ status: 'extracting' }))).toBe(true) + expect(isModelInFlight(model({ status: 'ready' }))).toBe(false) + }) + + it('isDictationReady requires enabled + selected + ready', () => { + expect( + isDictationReady({ + enabled: true, + selectedModelId: 'm1', + models: [model({ status: 'ready' })] + }) + ).toBe(true) + expect( + isDictationReady({ + enabled: false, + selectedModelId: 'm1', + models: [model({ status: 'ready' })] + }) + ).toBe(false) + expect( + isDictationReady({ + enabled: true, + selectedModelId: 'm1', + models: [model({ status: 'not-downloaded' })] + }) + ).toBe(false) + expect(isDictationReady({ enabled: true, selectedModelId: '', models: [] })).toBe(false) + }) +}) diff --git a/mobile/src/dictation/mobile-dictation-setup.ts b/mobile/src/dictation/mobile-dictation-setup.ts new file mode 100644 index 000000000..9c822922b --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-setup.ts @@ -0,0 +1,60 @@ +import type { RuntimeSpeechSetupState } from '../../../src/shared/runtime-types' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' + +export type MobileSpeechSetup = RuntimeSpeechSetupState +export type MobileSpeechModel = RuntimeSpeechSetupState['models'][number] + +// Dictation-setup errors startMobileDictation throws when the desktop isn't +// configured. Mapping them lets the mic entry point open the setup sheet +// instead of dead-ending on a toast. +const SETUP_REQUIRED_CODES = new Set(['voice_dictation_disabled', 'voice_model_not_selected']) + +export function isDictationSetupRequiredError(message: string): boolean { + return SETUP_REQUIRED_CODES.has(message) || message.startsWith('voice_model_not_ready:') +} + +export async function fetchDictationSetup( + client: Pick +): Promise { + const response = await client.sendRequest('speech.models.list', null) + if (!response.ok) { + throw new Error(response.error?.message || 'Failed to load dictation models') + } + return (response as RpcSuccess).result as MobileSpeechSetup +} + +export async function downloadDictationModel( + client: Pick, + modelId: string +): Promise { + const response = await client.sendRequest('speech.models.download', { modelId }) + if (!response.ok) { + throw new Error(response.error?.message || 'Failed to start download') + } +} + +export async function setDictationConfig( + client: Pick, + params: { enabled?: boolean; modelId?: string; dictationMode?: 'toggle' | 'hold' } +): Promise { + const response = await client.sendRequest('speech.dictation.setup', params) + if (!response.ok) { + throw new Error(response.error?.message || 'Failed to update dictation settings') + } + return (response as RpcSuccess).result as MobileSpeechSetup +} + +// A model is mid-download (or extracting) and the sheet should keep polling. +export function isModelInFlight(model: MobileSpeechModel): boolean { + return model.status === 'downloading' || model.status === 'extracting' +} + +// Whether dictation can be used right now: enabled + a selected model that's ready. +export function isDictationReady(setup: MobileSpeechSetup): boolean { + if (!setup.enabled || !setup.selectedModelId) { + return false + } + const selected = setup.models.find((m) => m.id === setup.selectedModelId) + return selected?.status === 'ready' +} diff --git a/mobile/src/hooks/use-active-worktree-scroll.ts b/mobile/src/hooks/use-active-worktree-scroll.ts new file mode 100644 index 000000000..7600f3cea --- /dev/null +++ b/mobile/src/hooks/use-active-worktree-scroll.ts @@ -0,0 +1,85 @@ +import { useCallback, useEffect, useMemo, useRef } from 'react' +import type { SectionList, SectionListData } from 'react-native' + +type WithId = { worktreeId: string; isActive?: boolean } + +// Scrolls the desktop-focused worktree into view when the active selection +// changes, so the mobile list mirrors the desktop's current workspace. Fires +// only on a *change* of active id (not every re-render) so it never yanks the +// list while the user scrolls or searches. Returns the ref to attach to the +// SectionList and the onScrollToIndexFailed handler it needs for rows that +// aren't measured yet (variable heights from the inline agent list). +export function useActiveWorktreeScroll( + sections: ReadonlyArray & { data: readonly T[] }> +): { + sectionListRef: React.RefObject | null> + onScrollToIndexFailed: (info: { averageItemLength: number }) => void +} { + const sectionListRef = useRef>(null) + const lastScrolledActiveIdRef = useRef(null) + + const activeWorktreeId = useMemo(() => { + for (const section of sections) { + const match = section.data.find((w) => w.isActive) + if (match) { + return match.worktreeId + } + } + return null + }, [sections]) + + // Live mirror of the current active id so the deferred retry can bail if the + // selection changed during its timeout (avoids a brief scroll to a stale row). + const activeWorktreeIdRef = useRef(activeWorktreeId) + activeWorktreeIdRef.current = activeWorktreeId + + const scrollToWorktree = useCallback( + (worktreeId: string): boolean => { + for (let sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) { + const itemIndex = sections[sectionIndex].data.findIndex((w) => w.worktreeId === worktreeId) + if (itemIndex >= 0) { + sectionListRef.current?.scrollToLocation({ + sectionIndex, + itemIndex, + viewPosition: 0.5, + animated: true + }) + return true + } + } + return false + }, + [sections] + ) + + useEffect(() => { + if (!activeWorktreeId || activeWorktreeId === lastScrolledActiveIdRef.current) { + return + } + if (scrollToWorktree(activeWorktreeId)) { + lastScrolledActiveIdRef.current = activeWorktreeId + } + }, [activeWorktreeId, scrollToWorktree]) + + const onScrollToIndexFailed = useCallback( + (info: { averageItemLength: number }) => { + const target = lastScrolledActiveIdRef.current + if (!target) { + return + } + setTimeout( + () => { + // Bail if the active selection moved on while we waited — otherwise we'd + // scroll to a now-stale row before the effect corrects it. + if (activeWorktreeIdRef.current === target) { + scrollToWorktree(target) + } + }, + info.averageItemLength > 0 ? 120 : 0 + ) + }, + [scrollToWorktree] + ) + + return { sectionListRef, onScrollToIndexFailed } +} diff --git a/mobile/src/hooks/use-now.ts b/mobile/src/hooks/use-now.ts new file mode 100644 index 000000000..1114ff699 --- /dev/null +++ b/mobile/src/hooks/use-now.ts @@ -0,0 +1,14 @@ +import { useEffect, useState } from 'react' + +// One shared interval per caller, mirroring desktop's useNow: relative +// timestamps ("Xm") need a periodic re-render to stay honest. The worktree list +// owns a single tick that drives every visible agent row, rather than each row +// running its own interval. +export function useNow(intervalMs = 30_000): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + const id = setInterval(() => setNow(Date.now()), intervalMs) + return () => clearInterval(id) + }, [intervalMs]) + return now +} diff --git a/mobile/src/session/TerminalPaneView.tsx b/mobile/src/session/TerminalPaneView.tsx index 66d05ec9a..45d93a5b8 100644 --- a/mobile/src/session/TerminalPaneView.tsx +++ b/mobile/src/session/TerminalPaneView.tsx @@ -24,6 +24,7 @@ type TerminalPaneViewProps = { onHaptic: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void onTerminalInput: (handle: string, bytes: string) => void onTerminalTap: (handle: string) => void + onFileTap: (handle: string, pathText: string, line: number | null, column: number | null) => void onTextScaleChange: (scale: number) => void } @@ -43,6 +44,7 @@ export function TerminalPaneView({ onHaptic, onTerminalInput, onTerminalTap, + onFileTap, onTextScaleChange }: TerminalPaneViewProps) { const setRef = useCallback( @@ -77,6 +79,7 @@ export function TerminalPaneView({ onHaptic={onHaptic} onTerminalInput={(bytes) => onTerminalInput(handle, bytes)} onTerminalTap={() => onTerminalTap(handle)} + onFileTap={(pathText, line, column) => onFileTap(handle, pathText, line, column)} onTextScaleChange={onTextScaleChange} /> diff --git a/mobile/src/session/mobile-artifact-kind.test.ts b/mobile/src/session/mobile-artifact-kind.test.ts new file mode 100644 index 000000000..376d1da0c --- /dev/null +++ b/mobile/src/session/mobile-artifact-kind.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { classifyMobileArtifact } from './mobile-artifact-kind' + +describe('classifyMobileArtifact', () => { + it('classifies raster image extensions (case-insensitive)', () => { + for (const p of ['a.png', 'b.JPG', 'c/d.jpeg', 'e.gif', 'f.webp', 'g.bmp', 'h.ico']) { + expect(classifyMobileArtifact(p)).toBe('image') + } + }) + + it('treats svg as other (RN Image cannot decode svg data URIs; render as source)', () => { + expect(classifyMobileArtifact('logo.svg')).toBe('other') + }) + + it('classifies html extensions', () => { + expect(classifyMobileArtifact('index.html')).toBe('html') + expect(classifyMobileArtifact('a/b/page.HTM')).toBe('html') + }) + + it('treats code/text/unknown as other', () => { + for (const p of ['main.ts', 'README.md', 'data.csv', 'notes', 'a.pdf', 'x.json']) { + expect(classifyMobileArtifact(p)).toBe('other') + } + }) + + it('treats a dotfile or no-extension path as other', () => { + expect(classifyMobileArtifact('.gitignore')).toBe('other') + expect(classifyMobileArtifact('Makefile')).toBe('other') + expect(classifyMobileArtifact('dir/.env')).toBe('other') + }) +}) diff --git a/mobile/src/session/mobile-artifact-kind.ts b/mobile/src/session/mobile-artifact-kind.ts new file mode 100644 index 000000000..4c1cd31ed --- /dev/null +++ b/mobile/src/session/mobile-artifact-kind.ts @@ -0,0 +1,34 @@ +// Classifies a file path into how the mobile viewer should render it. Images +// route through files.readPreview (base64) and render as an ; HTML routes +// through files.read (text) and renders in a sandboxed WebView with a source +// toggle; everything else stays on the existing text/syntax path. +export type MobileArtifactKind = 'image' | 'html' | 'other' + +// Raster image extensions React Native's can decode from a base64 data +// URI (host returns these via files.readPreview). SVG is intentionally excluded: +// RN can't render image/svg+xml data URIs, so .svg falls through to the +// text path and renders as (meaningful) XML source instead of a blank image. +const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico']) + +const HTML_EXTENSIONS = new Set(['html', 'htm']) + +function extensionOf(path: string): string { + const base = path.split(/[\\/]/).pop() ?? '' + const dot = base.lastIndexOf('.') + // A leading dot (dotfile, no real extension) or no dot → no extension. + if (dot <= 0) { + return '' + } + return base.slice(dot + 1).toLowerCase() +} + +export function classifyMobileArtifact(path: string): MobileArtifactKind { + const ext = extensionOf(path) + if (IMAGE_EXTENSIONS.has(ext)) { + return 'image' + } + if (HTML_EXTENSIONS.has(ext)) { + return 'html' + } + return 'other' +} diff --git a/mobile/src/session/mobile-image-attachment.test.ts b/mobile/src/session/mobile-image-attachment.test.ts new file mode 100644 index 000000000..3a94348aa --- /dev/null +++ b/mobile/src/session/mobile-image-attachment.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcResponse, RpcSuccess } from '../transport/types' +import { attachMobileImageToTerminal } from './mobile-image-attachment' + +function ok(id: string, result: unknown): RpcSuccess { + return { id, ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +function clientWithResponses(responses: RpcResponse[]): Pick & { + calls: Array<{ method: string; params: unknown }> +} { + const calls: Array<{ method: string; params: unknown }> = [] + return { + calls, + sendRequest: vi.fn(async (method: string, params?: unknown) => { + calls.push({ method, params }) + const response = responses.shift() + if (!response) { + throw new Error(`unexpected request: ${method}`) + } + return response + }) + } +} + +describe('attachMobileImageToTerminal', () => { + it('uploads the picked image and pastes its bracketed path into the terminal', async () => { + // startImageUpload (method_not_found) falls back to single-frame saveImageAsTempFile. + const client = clientWithResponses([ + { + id: 'start', + ok: false, + error: { code: 'method_not_found', message: 'no' }, + _meta: { runtimeId: 'r' } + }, + ok('save', '/tmp/orca-attach.png'), + ok('send', { ok: true }) + ]) + + const sent = await attachMobileImageToTerminal('library', { + client, + terminal: 'term-1', + deviceToken: 'device-9', + getConnectionId: async () => 'conn-7', + pickImage: vi.fn().mockResolvedValue({ base64: 'AAAA' }) + }) + + expect(sent).toBe(true) + const sendCall = client.calls.find((c) => c.method === 'terminal.send') + expect(sendCall?.params).toEqual({ + terminal: 'term-1', + text: '\x1b[200~/tmp/orca-attach.png\x1b[201~', + enter: false, + client: { id: 'device-9', type: 'mobile' } + }) + }) + + it('passes the active worktree connectionId to the upload', async () => { + const client = clientWithResponses([ + { + id: 'start', + ok: false, + error: { code: 'method_not_found', message: 'no' }, + _meta: { runtimeId: 'r' } + }, + ok('save', '/tmp/x.png'), + ok('send', { ok: true }) + ]) + + await attachMobileImageToTerminal('files', { + client, + terminal: 'term-1', + deviceToken: null, + getConnectionId: async () => 'conn-ssh', + pickImage: vi.fn().mockResolvedValue({ base64: 'BBBB' }) + }) + + const saveCall = client.calls.find((c) => c.method === 'clipboard.saveImageAsTempFile') + expect(saveCall?.params).toMatchObject({ connectionId: 'conn-ssh' }) + }) + + it('does nothing and returns false when the picker is cancelled', async () => { + const client = clientWithResponses([]) + + const sent = await attachMobileImageToTerminal('library', { + client, + terminal: 'term-1', + deviceToken: null, + getConnectionId: async () => null, + pickImage: vi.fn().mockResolvedValue(null) + }) + + expect(sent).toBe(false) + expect(client.calls).toEqual([]) + }) + + it('omits the client field when there is no device token', async () => { + const client = clientWithResponses([ + { + id: 'start', + ok: false, + error: { code: 'method_not_found', message: 'no' }, + _meta: { runtimeId: 'r' } + }, + ok('save', '/tmp/y.png'), + ok('send', { ok: true }) + ]) + + await attachMobileImageToTerminal('library', { + client, + terminal: 'term-2', + deviceToken: null, + getConnectionId: async () => null, + pickImage: vi.fn().mockResolvedValue({ base64: 'CCCC' }) + }) + + const sendCall = client.calls.find((c) => c.method === 'terminal.send') + expect(sendCall?.params).not.toHaveProperty('client') + }) +}) diff --git a/mobile/src/session/mobile-image-attachment.ts b/mobile/src/session/mobile-image-attachment.ts new file mode 100644 index 000000000..507b58eb6 --- /dev/null +++ b/mobile/src/session/mobile-image-attachment.ts @@ -0,0 +1,55 @@ +import type { RpcClient } from '../transport/rpc-client' +import { + buildMobileImagePastePayload, + saveMobileClipboardImageAsTempFile +} from './mobile-clipboard-image' +import type { MobileImageSource, PickedMobileImage } from './mobile-image-source-picker' + +export type AttachMobileImageDeps = { + readonly client: Pick + readonly terminal: string + readonly deviceToken: string | null + readonly getConnectionId: () => Promise + // Injected so this module stays free of expo/react-native imports (and unit-testable). + readonly pickImage: (source: MobileImageSource) => Promise + // Fired once the user has picked an image and the host upload is about to + // start — lets the UI show a sending spinner only for the transfer, not the + // (potentially long) time the picker is open. + readonly onUploadStart?: () => void +} + +// Uploads a picked image to the host and pastes the resulting file path into the +// active terminal — the same bracketed-path payload desktop image paste sends, so +// TUIs (Claude Code, etc.) attach it exactly as a desktop paste. Returns false +// when the user cancelled the picker. +export async function attachMobileImageToTerminal( + source: MobileImageSource, + { + client, + terminal, + deviceToken, + getConnectionId, + pickImage, + onUploadStart + }: AttachMobileImageDeps +): Promise { + const picked = await pickImage(source) + if (!picked) { + return false + } + onUploadStart?.() + const connectionId = await getConnectionId() + const imagePath = await saveMobileClipboardImageAsTempFile(client, picked.base64, { + connectionId + }) + // Why: a generated image path is terminal image injection, so it's always + // bracketed (matching desktop paste) regardless of terminal mode. + const payload = buildMobileImagePastePayload(imagePath) + await client.sendRequest('terminal.send', { + terminal, + text: payload, + enter: false, + ...(deviceToken ? { client: { id: deviceToken, type: 'mobile' as const } } : {}) + }) + return true +} diff --git a/mobile/src/session/mobile-image-source-picker.test.ts b/mobile/src/session/mobile-image-source-picker.test.ts new file mode 100644 index 000000000..3e35a7bed --- /dev/null +++ b/mobile/src/session/mobile-image-source-picker.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('expo-image-picker', () => ({ + requestMediaLibraryPermissionsAsync: vi.fn(), + launchImageLibraryAsync: vi.fn() +})) +vi.mock('expo-document-picker', () => ({ + getDocumentAsync: vi.fn() +})) + +import { ImageLibraryPermissionError, pickMobileImage } from './mobile-image-source-picker' + +const granted = { granted: true } as Awaited< + ReturnType +> +const denied = { granted: false } as typeof granted + +describe('pickMobileImage', () => { + it('returns base64 from the photo library', async () => { + const result = await pickMobileImage('library', { + requestLibraryPermission: vi.fn().mockResolvedValue(granted), + launchLibrary: vi.fn().mockResolvedValue({ + canceled: false, + assets: [{ uri: 'file:///x.jpg', base64: 'AAAA' }] + }) + }) + + expect(result).toEqual({ base64: 'AAAA' }) + }) + + it('throws when photo library permission is denied', async () => { + await expect( + pickMobileImage('library', { + requestLibraryPermission: vi.fn().mockResolvedValue(denied), + launchLibrary: vi.fn() + }) + ).rejects.toBeInstanceOf(ImageLibraryPermissionError) + }) + + it('returns null when the library picker is cancelled', async () => { + const result = await pickMobileImage('library', { + requestLibraryPermission: vi.fn().mockResolvedValue(granted), + launchLibrary: vi.fn().mockResolvedValue({ canceled: true, assets: null }) + }) + + expect(result).toBeNull() + }) + + it('reads a picked file URI into base64 for the files source', async () => { + const bytes = new Uint8Array([1, 2, 3, 4]) + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(bytes.buffer, { headers: { 'content-type': 'image/png' } })) + + const result = await pickMobileImage('files', { + launchFiles: vi.fn().mockResolvedValue({ + canceled: false, + assets: [{ uri: 'file:///doc.png' }] + }) + }) + + expect(result).toEqual({ base64: Buffer.from(bytes).toString('base64') }) + fetchSpy.mockRestore() + }) + + it('returns null when the files picker is cancelled', async () => { + const result = await pickMobileImage('files', { + launchFiles: vi.fn().mockResolvedValue({ canceled: true, assets: null }) + }) + + expect(result).toBeNull() + }) +}) diff --git a/mobile/src/session/mobile-image-source-picker.ts b/mobile/src/session/mobile-image-source-picker.ts new file mode 100644 index 000000000..21231b7ad --- /dev/null +++ b/mobile/src/session/mobile-image-source-picker.ts @@ -0,0 +1,84 @@ +import { Buffer } from 'buffer' +import * as DocumentPicker from 'expo-document-picker' +import * as ImagePicker from 'expo-image-picker' + +export type MobileImageSource = 'library' | 'files' + +export type PickedMobileImage = { + // Raw base64 (no data: prefix); fed straight into the existing upload pipeline. + readonly base64: string +} + +export class ImageLibraryPermissionError extends Error { + constructor() { + super('Photo library permission denied') + this.name = 'ImageLibraryPermissionError' + } +} + +// Why: expo-document-picker returns a file URI, not base64. Read it through +// fetch + Buffer so we match the base64 contract the upload pipeline expects +// without pulling in expo-file-system. +async function readUriAsBase64(uri: string): Promise { + const response = await fetch(uri) + const bytes = new Uint8Array(await response.arrayBuffer()) + return Buffer.from(bytes).toString('base64') +} + +async function pickFromLibrary( + requestPermission: typeof ImagePicker.requestMediaLibraryPermissionsAsync = ImagePicker.requestMediaLibraryPermissionsAsync, + launch: typeof ImagePicker.launchImageLibraryAsync = ImagePicker.launchImageLibraryAsync +): Promise { + const permission = await requestPermission() + // Why: `granted` covers full + limited iOS access; only a hard denial blocks us. + if (!permission.granted) { + throw new ImageLibraryPermissionError() + } + const result = await launch({ + mediaTypes: ['images'], + base64: true, + allowsMultipleSelection: false, + quality: 1 + }) + if (result.canceled) { + return null + } + const asset = result.assets[0] + const base64 = asset?.base64 ?? (asset?.uri ? await readUriAsBase64(asset.uri) : null) + if (!base64) { + return null + } + return { base64 } +} + +async function pickFromFiles( + launch: typeof DocumentPicker.getDocumentAsync = DocumentPicker.getDocumentAsync +): Promise { + const result = await launch({ + type: 'image/*', + multiple: false, + copyToCacheDirectory: true + }) + if (result.canceled) { + return null + } + const asset = result.assets[0] + if (!asset?.uri) { + return null + } + return { base64: await readUriAsBase64(asset.uri) } +} + +export async function pickMobileImage( + source: MobileImageSource, + deps?: { + readonly requestLibraryPermission?: typeof ImagePicker.requestMediaLibraryPermissionsAsync + readonly launchLibrary?: typeof ImagePicker.launchImageLibraryAsync + readonly launchFiles?: typeof DocumentPicker.getDocumentAsync + } +): Promise { + if (source === 'library') { + return pickFromLibrary(deps?.requestLibraryPermission, deps?.launchLibrary) + } + return pickFromFiles(deps?.launchFiles) +} diff --git a/mobile/src/session/use-mobile-image-attachment.ts b/mobile/src/session/use-mobile-image-attachment.ts new file mode 100644 index 000000000..3894928f4 --- /dev/null +++ b/mobile/src/session/use-mobile-image-attachment.ts @@ -0,0 +1,103 @@ +import { useCallback, useState } from 'react' +import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState } from '../transport/types' +import { attachMobileImageToTerminal } from './mobile-image-attachment' +import { + ImageLibraryPermissionError, + pickMobileImage, + type MobileImageSource +} from './mobile-image-source-picker' + +type CurrentRef = { + readonly current: T +} + +type ShowToast = (message: string, durationMs?: number) => void + +type UseMobileImageAttachmentArgs = { + readonly client: RpcClient | null + readonly activeHandle: string | null + readonly canSend: boolean + readonly connState: ConnectionState + readonly deviceTokenRef: CurrentRef + readonly getActiveWorktreeConnectionId: () => Promise + readonly showToast: ShowToast + readonly onSuccess: () => void + readonly onError: () => void +} + +type MobileImageAttachment = { + readonly attachImage: (source: MobileImageSource) => Promise + // True only while the picked image is uploading to the host (not while the + // picker is open) — drives the send spinner so the 3-5s transfer isn't a no-op. + readonly isAttaching: boolean +} + +function getErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +export function useMobileImageAttachment({ + client, + activeHandle, + canSend, + connState, + deviceTokenRef, + getActiveWorktreeConnectionId, + showToast, + onSuccess, + onError +}: UseMobileImageAttachmentArgs): MobileImageAttachment { + const [isAttaching, setIsAttaching] = useState(false) + const attachImage = useCallback( + async (source: MobileImageSource): Promise => { + if (!client || !activeHandle || !canSend) { + return + } + try { + const sent = await attachMobileImageToTerminal(source, { + client, + terminal: activeHandle, + deviceToken: deviceTokenRef.current, + getConnectionId: getActiveWorktreeConnectionId, + pickImage: pickMobileImage, + onUploadStart: () => setIsAttaching(true) + }) + // Cancelled picker: no error, no toast. + if (sent) { + onSuccess() + } + } catch (error) { + onError() + if (connState !== 'connected') { + showToast('Attach failed (disconnected)', 1500) + return + } + if (error instanceof ImageLibraryPermissionError) { + showToast('Photo permission denied', 1500) + return + } + if (getErrorMessage(error) === 'Clipboard image is too large') { + showToast('Image too large to attach', 1500) + return + } + showToast('Attach failed', 1500) + } finally { + setIsAttaching(false) + } + }, + [ + activeHandle, + canSend, + client, + connState, + deviceTokenRef, + getActiveWorktreeConnectionId, + onError, + onSuccess, + showToast + ] + ) + + return { attachImage, isAttaching } +} diff --git a/mobile/src/source-control/mobile-commit-message-ai.test.ts b/mobile/src/source-control/mobile-commit-message-ai.test.ts new file mode 100644 index 000000000..f87fb3600 --- /dev/null +++ b/mobile/src/source-control/mobile-commit-message-ai.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' +import { cancelMobileCommitMessage, requestMobileCommitMessage } from './mobile-commit-message-ai' + +function ok(result: unknown): RpcSuccess { + return { id: 'r', ok: true, result, _meta: { runtimeId: 'rt' } } +} +function fail(message: string): RpcFailure { + return { id: 'r', ok: false, error: { code: 'x', message }, _meta: { runtimeId: 'rt' } } +} +function clientWith(responses: RpcResponse[]): Pick & { + calls: Array<{ method: string; params: unknown }> +} { + const calls: Array<{ method: string; params: unknown }> = [] + return { + calls, + sendRequest: vi.fn(async (method: string, params?: unknown) => { + calls.push({ method, params }) + return responses.shift() ?? fail('unexpected') + }) + } +} + +describe('requestMobileCommitMessage', () => { + it('returns the generated message on success', async () => { + const client = clientWith([ok({ success: true, message: 'feat: do the thing' })]) + await expect(requestMobileCommitMessage(client, 'wt-1')).resolves.toEqual({ + success: true, + message: 'feat: do the thing' + }) + expect(client.calls[0]).toEqual({ + method: 'git.generateCommitMessage', + params: { worktree: 'id:wt-1' } + }) + }) + + it('maps a host failure result to { success:false }', async () => { + const client = clientWith([ok({ success: false, error: 'no model configured' })]) + await expect(requestMobileCommitMessage(client, 'wt-1')).resolves.toEqual({ + success: false, + error: 'no model configured' + }) + }) + + it('coerces a malformed failure payload to a non-empty error string', async () => { + const client = clientWith([ok({ success: false })]) + const result = await requestMobileCommitMessage(client, 'wt-1') + expect(result.success).toBe(false) + expect(result).toMatchObject({ success: false, error: 'No commit message generated' }) + }) + + it('preserves the canceled flag', async () => { + const client = clientWith([ok({ success: false, error: 'canceled', canceled: true })]) + await expect(requestMobileCommitMessage(client, 'wt-1')).resolves.toEqual({ + success: false, + error: 'canceled', + canceled: true + }) + }) + + it('maps an RPC transport failure to { success:false }', async () => { + const client = clientWith([fail('disconnected')]) + await expect(requestMobileCommitMessage(client, 'wt-1')).resolves.toEqual({ + success: false, + error: 'disconnected' + }) + }) + + it('treats an empty message as failure', async () => { + const client = clientWith([ok({ success: true, message: '' })]) + const result = await requestMobileCommitMessage(client, 'wt-1') + expect(result.success).toBe(false) + }) +}) + +describe('cancelMobileCommitMessage', () => { + it('calls the cancel RPC', async () => { + const client = clientWith([ok({})]) + await cancelMobileCommitMessage(client, 'wt-1') + expect(client.calls[0]).toEqual({ + method: 'git.cancelGenerateCommitMessage', + params: { worktree: 'id:wt-1' } + }) + }) +}) diff --git a/mobile/src/source-control/mobile-commit-message-ai.ts b/mobile/src/source-control/mobile-commit-message-ai.ts new file mode 100644 index 000000000..6f85ebba4 --- /dev/null +++ b/mobile/src/source-control/mobile-commit-message-ai.ts @@ -0,0 +1,48 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' + +// Mirrors the host GenerateCommitMessageResult (src/main/text-generation/ +// commit-message-text-generation.ts) — a single resolved result, not a stream. +export type MobileGenerateCommitMessageResult = + | { success: true; message: string } + | { success: false; error: string; canceled?: boolean } + +// Normalizes the git.generateCommitMessage RPC into a discriminated result the +// UI can switch on. RPC transport failures and malformed payloads collapse to +// { success:false } so the caller never has to special-case them. +export async function requestMobileCommitMessage( + client: Pick, + worktreeId: string +): Promise { + const response = await client.sendRequest('git.generateCommitMessage', { + worktree: `id:${worktreeId}` + }) + if (!response.ok) { + return { success: false, error: response.error?.message || 'Failed to generate commit message' } + } + const result = (response as RpcSuccess).result as MobileGenerateCommitMessageResult | undefined + if (!result || typeof result !== 'object') { + return { success: false, error: 'Failed to generate commit message' } + } + if (result.success === true && typeof result.message === 'string' && result.message.length > 0) { + return { success: true, message: result.message } + } + // Why: a malformed `{ success:false }` payload could leave error undefined, + // breaking the result contract — always coerce to a non-empty string. + const hostError = + result.success === false && typeof result.error === 'string' && result.error.length > 0 + ? result.error + : 'No commit message generated' + return { + success: false, + error: hostError, + ...(result.success === false && result.canceled ? { canceled: true } : {}) + } +} + +export async function cancelMobileCommitMessage( + client: Pick, + worktreeId: string +): Promise { + await client.sendRequest('git.cancelGenerateCommitMessage', { worktree: `id:${worktreeId}` }) +} diff --git a/mobile/src/source-control/mobile-git-history.test.ts b/mobile/src/source-control/mobile-git-history.test.ts new file mode 100644 index 000000000..7357f76ae --- /dev/null +++ b/mobile/src/source-control/mobile-git-history.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import type { GitHistoryItem, GitHistoryResult } from '../../../src/shared/git-history-types' +import { formatCommitTime, mapMobileCommitRows, toMobileCommitRow } from './mobile-git-history' + +const NOW = 1_000_000_000_000 + +function item(overrides: Partial = {}): GitHistoryItem { + return { + id: 'a'.repeat(40), + parentIds: ['b'.repeat(40)], + subject: 'feat: thing', + message: 'feat: thing\n\nbody', + author: 'Jane', + timestamp: NOW / 1000 - 3600, + ...overrides + } +} + +describe('formatCommitTime', () => { + it('formats across thresholds', () => { + const s = NOW / 1000 + expect(formatCommitTime(s - 30, NOW)).toBe('just now') + expect(formatCommitTime(s - 5 * 60, NOW)).toBe('5m') + expect(formatCommitTime(s - 3 * 3600, NOW)).toBe('3h') + expect(formatCommitTime(s - 2 * 86400, NOW)).toBe('2d') + expect(formatCommitTime(s - 60 * 86400, NOW)).toBe('2mo') + expect(formatCommitTime(s - 800 * 86400, NOW)).toBe('2y') + }) + + it('returns empty for missing timestamp', () => { + expect(formatCommitTime(undefined, NOW)).toBe('') + }) + + it('formats a real epoch-0 timestamp instead of dropping it', () => { + // 0 is a valid (very old) timestamp, not "missing". + expect(formatCommitTime(0, NOW)).not.toBe('') + }) +}) + +describe('toMobileCommitRow', () => { + it('maps a history item to a row', () => { + const row = toMobileCommitRow(item(), NOW) + expect(row).toEqual({ + id: 'a'.repeat(40), + shortId: 'aaaaaaa', + subject: 'feat: thing', + author: 'Jane', + parentId: 'b'.repeat(40), + relativeTime: '1h' + }) + }) + + it('prefers displayId and falls back for empty subject / no parent', () => { + const row = toMobileCommitRow(item({ displayId: 'abc1234', subject: '', parentIds: [] }), NOW) + expect(row.shortId).toBe('abc1234') + expect(row.subject).toBe('(no commit message)') + expect(row.parentId).toBeNull() + }) +}) + +describe('mapMobileCommitRows', () => { + it('maps all items', () => { + const result = { items: [item(), item({ id: 'c'.repeat(40) })] } as GitHistoryResult + expect(mapMobileCommitRows(result, NOW)).toHaveLength(2) + }) +}) diff --git a/mobile/src/source-control/mobile-git-history.ts b/mobile/src/source-control/mobile-git-history.ts new file mode 100644 index 000000000..416b761d2 --- /dev/null +++ b/mobile/src/source-control/mobile-git-history.ts @@ -0,0 +1,71 @@ +import type { GitHistoryItem, GitHistoryResult } from '../../../src/shared/git-history-types' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' + +export type MobileCommitRow = { + id: string + shortId: string + subject: string + author: string + parentId: string | null + relativeTime: string +} + +// Short relative time for a commit list (just now / Xm / Xh / Xd / Xmo / Xy). +export function formatCommitTime(timestampSeconds: number | undefined, nowMs: number): string { + // Nullish — not falsy — so a real epoch-0 timestamp still formats. + if (timestampSeconds == null) { + return '' + } + const delta = nowMs - timestampSeconds * 1000 + if (delta < 60_000) { + return 'just now' + } + const minutes = Math.floor(delta / 60_000) + if (minutes < 60) { + return `${minutes}m` + } + const hours = Math.floor(minutes / 60) + if (hours < 24) { + return `${hours}h` + } + const days = Math.floor(hours / 24) + if (days < 30) { + return `${days}d` + } + const months = Math.floor(days / 30) + if (months < 12) { + return `${months}mo` + } + return `${Math.floor(months / 12)}y` +} + +export function toMobileCommitRow(item: GitHistoryItem, nowMs: number): MobileCommitRow { + return { + id: item.id, + shortId: item.displayId ?? item.id.slice(0, 7), + subject: item.subject || '(no commit message)', + author: item.author ?? '', + parentId: item.parentIds[0] ?? null, + relativeTime: formatCommitTime(item.timestamp, nowMs) + } +} + +export function mapMobileCommitRows(result: GitHistoryResult, nowMs: number): MobileCommitRow[] { + return result.items.map((item) => toMobileCommitRow(item, nowMs)) +} + +export async function fetchMobileGitHistory( + client: Pick, + worktreeId: string, + limit = 50 +): Promise { + const response = await client.sendRequest('git.history', { + worktree: `id:${worktreeId}`, + limit + }) + if (!response.ok) { + throw new Error(response.error?.message || 'Failed to load commit history') + } + return (response as RpcSuccess).result as GitHistoryResult +} diff --git a/mobile/src/source-control/mobile-pr-create.test.ts b/mobile/src/source-control/mobile-pr-create.test.ts new file mode 100644 index 000000000..3761091a9 --- /dev/null +++ b/mobile/src/source-control/mobile-pr-create.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' +import { + buildMobilePrCreateParams, + createMobilePr, + mobileRepoSelectorFromWorktreeId, + resolveMobilePrPrefill +} from './mobile-pr-create' + +function ok(result: unknown): RpcSuccess { + return { id: 'r', ok: true, result, _meta: { runtimeId: 'rt' } } +} +function fail(message: string): RpcFailure { + return { id: 'r', ok: false, error: { code: 'x', message }, _meta: { runtimeId: 'rt' } } +} +function clientWith(responses: RpcResponse[]): Pick & { + calls: Array<{ method: string; params: unknown }> +} { + const calls: Array<{ method: string; params: unknown }> = [] + return { + calls, + sendRequest: vi.fn(async (method: string, params?: unknown) => { + calls.push({ method, params }) + return responses.shift() ?? fail('unexpected') + }) + } +} + +describe('mobileRepoSelectorFromWorktreeId', () => { + it('extracts the repo id before the :: separator', () => { + expect(mobileRepoSelectorFromWorktreeId('repo-1::/tmp/wt')).toBe('id:repo-1') + expect(mobileRepoSelectorFromWorktreeId('repo-1')).toBe('id:repo-1') + }) +}) + +describe('buildMobilePrCreateParams', () => { + it('trims fields and drops empty optionals', () => { + expect( + buildMobilePrCreateParams('repo-1::/tmp/wt', { + provider: 'github', + base: 'main', + title: ' Add feature ', + body: ' ', + draft: false + }) + ).toEqual({ + repo: 'id:repo-1', + worktree: 'id:repo-1::/tmp/wt', + provider: 'github', + base: 'main', + title: 'Add feature', + draft: false + }) + }) + + it('keeps a non-empty body and head', () => { + const params = buildMobilePrCreateParams('repo-1::/tmp/wt', { + provider: 'gitlab', + base: 'main', + head: 'feature/x', + title: 'T', + body: 'Body text', + draft: true + }) + expect(params).toMatchObject({ head: 'feature/x', body: 'Body text', draft: true }) + }) +}) + +describe('createMobilePr', () => { + it('returns the url on success', async () => { + const client = clientWith([ok({ ok: true, number: 42, url: 'https://github.com/o/r/pull/42' })]) + await expect( + createMobilePr(client, 'repo-1::/tmp/wt', { + provider: 'github', + base: 'main', + title: 'T', + body: '', + draft: false + }) + ).resolves.toEqual({ ok: true, number: 42, url: 'https://github.com/o/r/pull/42' }) + expect(client.calls[0].method).toBe('hostedReview.create') + }) + + it('maps a host failure result to { ok:false }', async () => { + const client = clientWith([ok({ ok: false, code: 'needs_push', error: 'Push first' })]) + await expect( + createMobilePr(client, 'repo-1::/tmp/wt', { + provider: 'github', + base: 'main', + title: 'T', + body: '', + draft: false + }) + ).resolves.toEqual({ ok: false, error: 'Push first' }) + }) + + it('maps an RPC transport failure to { ok:false }', async () => { + const client = clientWith([fail('disconnected')]) + const result = await createMobilePr(client, 'repo-1::/tmp/wt', { + provider: 'github', + base: 'main', + title: 'T', + body: '', + draft: false + }) + expect(result).toEqual({ ok: false, error: 'disconnected' }) + }) +}) + +describe('resolveMobilePrPrefill', () => { + const baseArgs = { + branch: 'feature/x', + title: 'feature/x', + hasUncommittedChanges: false, + hasUpstream: true, + ahead: 1, + behind: 0 + } + + it('derives provider/base/title/body from eligibility (non-GitHub honored)', async () => { + const client = clientWith([ + ok({ + provider: 'gitlab', + canCreate: true, + review: null, + blockedReason: null, + nextAction: null, + defaultBaseRef: 'develop', + title: 'Add feature', + body: 'Body' + }) + ]) + await expect(resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs)).resolves.toEqual({ + provider: 'gitlab', + base: 'develop', + title: 'Add feature', + body: 'Body' + }) + }) + + it('falls back to github/main when eligibility is unavailable', async () => { + const client = clientWith([fail('nope')]) + await expect(resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', baseArgs)).resolves.toEqual({ + provider: 'github', + base: 'main', + title: 'feature/x', + body: '' + }) + }) + + it('falls back without calling the RPC when there is no branch', async () => { + const client = clientWith([]) + const result = await resolveMobilePrPrefill(client, 'repo-1::/tmp/wt', { + ...baseArgs, + branch: undefined + }) + expect(result.provider).toBe('github') + expect(client.calls).toEqual([]) + }) +}) diff --git a/mobile/src/source-control/mobile-pr-create.ts b/mobile/src/source-control/mobile-pr-create.ts new file mode 100644 index 000000000..cada7dad3 --- /dev/null +++ b/mobile/src/source-control/mobile-pr-create.ts @@ -0,0 +1,153 @@ +import type { + CreateHostedReviewResult, + HostedReviewCreationEligibility, + HostedReviewProvider +} from '../../../src/shared/hosted-review' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' + +// The mobile worktree id is `${repoId}::${path}`; the repo selector the host +// hosted-review RPCs expect is `id:${repoId}`. +export function mobileRepoSelectorFromWorktreeId(worktreeId: string): string { + const separatorIdx = worktreeId.indexOf('::') + const repoId = separatorIdx === -1 ? worktreeId : worktreeId.slice(0, separatorIdx) + return `id:${repoId}` +} + +export type MobilePrEligibilityInput = { + branch: string + base?: string | null + hasUncommittedChanges: boolean + hasUpstream: boolean + ahead: number + behind: number + linkedGitHubPR?: number | null + linkedGitLabMR?: number | null +} + +export async function fetchMobilePrEligibility( + client: Pick, + worktreeId: string, + input: MobilePrEligibilityInput +): Promise { + const response = await client.sendRequest('hostedReview.getCreationEligibility', { + repo: mobileRepoSelectorFromWorktreeId(worktreeId), + worktree: `id:${worktreeId}`, + branch: input.branch, + base: input.base ?? null, + hasUncommittedChanges: input.hasUncommittedChanges, + hasUpstream: input.hasUpstream, + ahead: input.ahead, + behind: input.behind, + linkedGitHubPR: input.linkedGitHubPR ?? null, + linkedGitLabMR: input.linkedGitLabMR ?? null + }) + if (!response.ok) { + return null + } + return (response as RpcSuccess).result as HostedReviewCreationEligibility +} + +export type MobilePrPrefill = { + provider: HostedReviewProvider + base: string + title: string + body: string +} + +// Fetches hosted-review eligibility and derives the PR compose prefill from it +// — so non-GitHub repos (e.g. GitLab) get the right provider/base instead of a +// hardcoded one. Falls back to a github/main default (with the branch label as +// title) when branch/eligibility is unavailable. +export async function resolveMobilePrPrefill( + client: Pick, + worktreeId: string, + args: { + branch: string | undefined + title: string + hasUncommittedChanges: boolean + hasUpstream: boolean + ahead: number + behind: number + } +): Promise { + const fallback: MobilePrPrefill = { + provider: 'github', + base: 'main', + title: args.title, + body: '' + } + if (!args.branch) { + return fallback + } + try { + const eligibility = await fetchMobilePrEligibility(client, worktreeId, { + branch: args.branch, + hasUncommittedChanges: args.hasUncommittedChanges, + hasUpstream: args.hasUpstream, + ahead: args.ahead, + behind: args.behind + }) + if (!eligibility) { + return fallback + } + return { + provider: eligibility.provider, + base: eligibility.defaultBaseRef || 'main', + title: eligibility.title || args.title, + body: eligibility.body || '' + } + } catch { + return fallback + } +} + +export type MobilePrCreateInput = { + provider: HostedReviewProvider + base: string + head?: string + title: string + body: string + draft: boolean +} + +// Builds the hostedReview.create params, trimming title/body and dropping empty +// optional fields so the host's required-string validation passes cleanly. +export function buildMobilePrCreateParams( + worktreeId: string, + input: MobilePrCreateInput +): Record { + return { + repo: mobileRepoSelectorFromWorktreeId(worktreeId), + worktree: `id:${worktreeId}`, + provider: input.provider, + base: input.base, + ...(input.head && input.head.length > 0 ? { head: input.head } : {}), + title: input.title.trim(), + ...(input.body.trim().length > 0 ? { body: input.body.trim() } : {}), + draft: input.draft + } +} + +export type MobilePrCreateOutcome = + | { ok: true; url: string; number: number } + | { ok: false; error: string } + +export async function createMobilePr( + client: Pick, + worktreeId: string, + input: MobilePrCreateInput +): Promise { + const response = await client.sendRequest( + 'hostedReview.create', + buildMobilePrCreateParams(worktreeId, input) + ) + if (!response.ok) { + return { ok: false, error: response.error?.message || 'Failed to create pull request' } + } + const result = (response as RpcSuccess).result as CreateHostedReviewResult + if (result.ok) { + return { ok: true, url: result.url, number: result.number } + } + return { ok: false, error: result.error || 'Failed to create pull request' } +} diff --git a/mobile/src/source-control/mobile-source-control-actions.test.ts b/mobile/src/source-control/mobile-source-control-actions.test.ts new file mode 100644 index 000000000..5ed3deb23 --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-actions.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it, vi } from 'vitest' +import type { MobileGitUpstreamStatus } from './mobile-git-status' +import { + buildMobileSourceControlActions, + type MobileSourceControlActionArgs +} from './mobile-source-control-actions' + +function noopHandlers(): MobileSourceControlActionArgs['handlers'] { + return { + commit: vi.fn(), + commitPush: vi.fn(), + commitSync: vi.fn(), + push: vi.fn(), + pull: vi.fn(), + sync: vi.fn(), + fetch: vi.fn(), + publish: vi.fn(), + fastForward: vi.fn(), + rebase: vi.fn(), + createPr: vi.fn(), + pushAndCreatePr: vi.fn(), + checkout: vi.fn(), + history: vi.fn() + } +} + +function args( + overrides: Partial = {} +): MobileSourceControlActionArgs { + return { + commitMessage: 'msg', + stagedCount: 1, + upstream: { hasUpstream: true, ahead: 0, behind: 0 } as MobileGitUpstreamStatus, + upstreamKnown: true, + busyAction: null, + openingPath: null, + openingBranchPath: null, + prAvailable: true, + handlers: noopHandlers(), + ...overrides + } +} + +function action(actions: ReturnType, label: string) { + return actions.find((a) => a.label.startsWith(label)) +} + +describe('buildMobileSourceControlActions', () => { + it('includes the new parity actions', () => { + const actions = buildMobileSourceControlActions(args()) + const labels = actions.map((a) => a.label) + expect(labels.some((l) => l.startsWith('Fast-forward'))).toBe(true) + expect(labels).toContain('Rebase onto base') + expect(labels).toContain('Switch branch') + expect(labels).toContain('History') + expect(labels).toContain('Create PR') + }) + + it('enables Create PR only when a PR provider is available', () => { + expect( + action(buildMobileSourceControlActions(args({ prAvailable: true })), 'Create PR')?.disabled + ).toBe(false) + expect( + action(buildMobileSourceControlActions(args({ prAvailable: false })), 'Create PR')?.disabled + ).toBe(true) + }) + + it('disables fast-forward when ahead of upstream (would lose local commits)', () => { + const actions = buildMobileSourceControlActions( + args({ upstream: { hasUpstream: true, ahead: 2, behind: 3 } as MobileGitUpstreamStatus }) + ) + expect(action(actions, 'Fast-forward')?.disabled).toBe(true) + }) + + it('enables fast-forward when behind and not ahead', () => { + const actions = buildMobileSourceControlActions( + args({ upstream: { hasUpstream: true, ahead: 0, behind: 3 } as MobileGitUpstreamStatus }) + ) + expect(action(actions, 'Fast-forward')?.disabled).toBe(false) + }) + + it('blocks commit when no staged files', () => { + const actions = buildMobileSourceControlActions(args({ stagedCount: 0 })) + const commit = action(actions, 'Commit') + expect(commit?.disabled).toBe(true) + expect(commit?.hint).toBe('Stage at least one file') + }) + + it('wires handlers to their actions', () => { + const handlers = noopHandlers() + const actions = buildMobileSourceControlActions(args({ handlers })) + action(actions, 'Switch branch')?.onPress() + action(actions, 'History')?.onPress() + expect(handlers.checkout).toHaveBeenCalled() + expect(handlers.history).toHaveBeenCalled() + }) +}) diff --git a/mobile/src/source-control/mobile-source-control-actions.ts b/mobile/src/source-control/mobile-source-control-actions.ts new file mode 100644 index 000000000..0e504c5a2 --- /dev/null +++ b/mobile/src/source-control/mobile-source-control-actions.ts @@ -0,0 +1,226 @@ +import type { MobileGitUpstreamStatus } from './mobile-git-status' + +// Icon identifier resolved to a lucide component by the screen. Kept as a string +// here so this module stays free of the native lucide import and unit-testable. +export type MobileSourceControlActionIcon = + | 'commit' + | 'push' + | 'pull' + | 'sync' + | 'fetch' + | 'publish' + | 'rebase' + | 'pr' + | 'branch' + | 'history' + +export type MobileSourceControlAction = { + label: string + iconKey: MobileSourceControlActionIcon + disabled?: boolean + hint?: string + loading?: boolean + skipAutoClose?: boolean + onPress: () => void +} + +export type MobileSourceControlActionArgs = { + commitMessage: string + stagedCount: number + upstream: MobileGitUpstreamStatus | null + upstreamKnown: boolean + busyAction: string | null + openingPath: string | null + openingBranchPath: string | null + prAvailable: boolean + handlers: { + commit: () => void + commitPush: () => void + commitSync: () => void + push: () => void + pull: () => void + sync: () => void + fetch: () => void + publish: () => void + fastForward: () => void + rebase: () => void + createPr: () => void + pushAndCreatePr: () => void + checkout: () => void + history: () => void + } +} + +// Builds the source-control bottom-sheet action list. Pure (no hooks) so it can +// be unit-tested and keeps the screen file lean. Enable/disable rules mirror the +// desktop primary-action gating. +export function buildMobileSourceControlActions( + args: MobileSourceControlActionArgs +): MobileSourceControlAction[] { + const { commitMessage, stagedCount, upstream, upstreamKnown, handlers } = args + const hasMessage = commitMessage.trim().length > 0 + const hasStaged = stagedCount > 0 + const hasUpstream = upstream?.hasUpstream === true + const ahead = upstream?.ahead ?? 0 + const behind = upstream?.behind ?? 0 + const busy = + args.busyAction !== null || args.openingPath !== null || args.openingBranchPath !== null + const commitHint = !hasStaged + ? 'Stage at least one file' + : !hasMessage + ? 'Enter a commit message' + : undefined + const remoteHint = !upstreamKnown + ? 'Checking branch status...' + : hasUpstream + ? undefined + : 'Publish Branch first' + const prHint = !upstreamKnown + ? 'Checking branch status...' + : !args.prAvailable + ? 'Pull requests are not available for this repo' + : undefined + + return [ + { + label: 'Commit', + iconKey: 'commit', + disabled: busy || !!commitHint, + hint: commitHint, + loading: args.busyAction === 'commit', + skipAutoClose: true, + onPress: handlers.commit + }, + { + label: 'Commit & Push', + iconKey: 'push', + disabled: busy || !!commitHint || !upstreamKnown || !hasUpstream, + hint: commitHint ?? remoteHint, + loading: args.busyAction === 'commit-push', + skipAutoClose: true, + onPress: handlers.commitPush + }, + { + label: 'Commit & Sync', + iconKey: 'sync', + disabled: busy || !!commitHint || !upstreamKnown || !hasUpstream || behind === 0, + hint: + commitHint ?? + (!upstreamKnown || !hasUpstream + ? remoteHint + : behind === 0 + ? 'Nothing to pull' + : undefined), + loading: args.busyAction === 'commit-sync', + skipAutoClose: true, + onPress: handlers.commitSync + }, + { + label: ahead > 0 ? `Push (${ahead})` : 'Push', + iconKey: 'push', + disabled: busy || !upstreamKnown || !hasUpstream || ahead === 0, + hint: !hasUpstream ? remoteHint : ahead === 0 ? 'Nothing to push' : undefined, + loading: args.busyAction === 'push', + skipAutoClose: true, + onPress: handlers.push + }, + { + label: 'Create PR', + iconKey: 'pr', + disabled: busy || !args.prAvailable, + hint: prHint, + loading: args.busyAction === 'create-pr', + skipAutoClose: true, + onPress: handlers.createPr + }, + { + label: 'Push & Create PR', + iconKey: 'pr', + disabled: busy || !upstreamKnown || !hasUpstream || ahead === 0 || !args.prAvailable, + hint: prHint ?? (!hasUpstream ? remoteHint : undefined), + loading: args.busyAction === 'push-create-pr', + skipAutoClose: true, + onPress: handlers.pushAndCreatePr + }, + { + label: behind > 0 ? `Pull (${behind})` : 'Pull', + iconKey: 'pull', + disabled: busy || !upstreamKnown || !hasUpstream || behind === 0, + hint: !hasUpstream ? remoteHint : behind === 0 ? 'Nothing to pull' : undefined, + loading: args.busyAction === 'pull', + skipAutoClose: true, + onPress: handlers.pull + }, + { + label: ahead > 0 || behind > 0 ? `Sync (↓${behind} ↑${ahead})` : 'Sync', + iconKey: 'sync', + disabled: busy || !upstreamKnown || !hasUpstream || (ahead === 0 && behind === 0), + hint: + !upstreamKnown || !hasUpstream + ? remoteHint + : ahead === 0 && behind === 0 + ? 'Branch is up to date' + : undefined, + loading: args.busyAction === 'sync', + skipAutoClose: true, + onPress: handlers.sync + }, + { + label: 'Fetch', + iconKey: 'fetch', + disabled: busy, + loading: args.busyAction === 'fetch', + skipAutoClose: true, + onPress: handlers.fetch + }, + { + label: 'Publish Branch', + iconKey: 'publish', + disabled: busy || !upstreamKnown || hasUpstream, + hint: !upstreamKnown + ? 'Checking branch status...' + : hasUpstream + ? 'Branch is already published' + : undefined, + loading: args.busyAction === 'publish', + skipAutoClose: true, + onPress: handlers.publish + }, + { + label: behind > 0 ? `Fast-forward (${behind})` : 'Fast-forward', + iconKey: 'pull', + disabled: busy || !upstreamKnown || !hasUpstream || behind === 0 || ahead > 0, + hint: !hasUpstream + ? remoteHint + : behind === 0 + ? 'Nothing to fast-forward' + : ahead > 0 + ? 'Local commits would be lost; pull instead' + : undefined, + loading: args.busyAction === 'fast-forward', + skipAutoClose: true, + onPress: handlers.fastForward + }, + { + label: 'Rebase onto base', + iconKey: 'branch', + disabled: busy, + loading: args.busyAction === 'rebase', + skipAutoClose: true, + onPress: handlers.rebase + }, + { + label: 'Switch branch', + iconKey: 'branch', + disabled: busy, + skipAutoClose: true, + onPress: handlers.checkout + }, + { + label: 'History', + iconKey: 'history', + disabled: busy, + onPress: handlers.history + } + ] +} diff --git a/mobile/src/storage/preferences.ts b/mobile/src/storage/preferences.ts index 82f2c65e0..a7439d950 100644 --- a/mobile/src/storage/preferences.ts +++ b/mobile/src/storage/preferences.ts @@ -1,7 +1,6 @@ import AsyncStorage from '@react-native-async-storage/async-storage' const PINS_PREFIX = 'orca:pins:' -const PREFS_PREFIX = 'orca:prefs:' const NOTIF_KEY = 'orca:pushNotificationsEnabled' // Why: default-off so the iOS notification permission prompt never @@ -74,35 +73,12 @@ export async function saveTerminalAutocompleteEnabled(enabled: boolean): Promise await AsyncStorage.setItem(AUTOCOMPLETE_KEY, String(enabled)) } -export type HostPreferences = { - sortMode: string - filterMode: string - groupMode: string - collapsedGroups: string[] - selectedRepos: string[] -} - -const DEFAULT_PREFS: HostPreferences = { - sortMode: 'recent', - filterMode: 'all', - groupMode: 'repo', - collapsedGroups: [], - selectedRepos: [] -} -const SORT_MODES = new Set(['smart', 'recent', 'name', 'repo']) -const FILTER_MODES = new Set(['all', 'active']) -const GROUP_MODES = new Set(['none', 'workspaceStatus', 'repo', 'prStatus']) - function stringArray(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [] } -function allowedString(value: unknown, allowed: Set, fallback: string): string { - return typeof value === 'string' && allowed.has(value) ? value : fallback -} - export async function loadPinnedIds(hostId: string): Promise> { try { const raw = await AsyncStorage.getItem(PINS_PREFIX + hostId) @@ -118,31 +94,3 @@ export async function loadPinnedIds(hostId: string): Promise> { export async function savePinnedIds(hostId: string, ids: Set): Promise { await AsyncStorage.setItem(PINS_PREFIX + hostId, JSON.stringify([...ids])) } - -export async function loadPreferences(hostId: string): Promise { - try { - const raw = await AsyncStorage.getItem(PREFS_PREFIX + hostId) - if (!raw) { - return DEFAULT_PREFS - } - const parsed = JSON.parse(raw) as Partial - return { - sortMode: allowedString(parsed.sortMode, SORT_MODES, DEFAULT_PREFS.sortMode), - filterMode: allowedString(parsed.filterMode, FILTER_MODES, DEFAULT_PREFS.filterMode), - groupMode: allowedString(parsed.groupMode, GROUP_MODES, DEFAULT_PREFS.groupMode), - collapsedGroups: stringArray(parsed.collapsedGroups), - selectedRepos: stringArray(parsed.selectedRepos) - } - } catch { - return DEFAULT_PREFS - } -} - -export async function savePreferences( - hostId: string, - prefs: Partial -): Promise { - const current = await loadPreferences(hostId) - const merged = { ...current, ...prefs } - await AsyncStorage.setItem(PREFS_PREFIX + hostId, JSON.stringify(merged)) -} diff --git a/mobile/src/terminal/TerminalWebView.tsx b/mobile/src/terminal/TerminalWebView.tsx index 7208b1779..816ea1dde 100644 --- a/mobile/src/terminal/TerminalWebView.tsx +++ b/mobile/src/terminal/TerminalWebView.tsx @@ -33,6 +33,8 @@ export type TerminalSelectionEvents = { onHaptic?: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void onTerminalInput?: (bytes: string) => void onTerminalTap?: () => void + // Tap landed on a detected file path; RN resolves + opens it. + onFileTap?: (pathText: string, line: number | null, column: number | null) => void // Why: pinch-to-zoom in the terminal snaps to a text-size preset and reports it // here so the app persists it and keeps Settings + other panes in sync. onTextScaleChange?: (scale: number) => void @@ -100,6 +102,7 @@ export const TerminalWebView = forwardRef(function onHaptic, onTerminalInput, onTerminalTap, + onFileTap, onTextScaleChange }, ref @@ -247,6 +250,13 @@ export const TerminalWebView = forwardRef(function } } else if (msg.type === 'terminal-tap') { onTerminalTap?.() + } else if (msg.type === 'terminal-file-tap') { + const pathText = typeof msg.pathText === 'string' ? msg.pathText : '' + if (pathText.length > 0) { + const line = typeof msg.line === 'number' ? msg.line : null + const column = typeof msg.column === 'number' ? msg.column : null + onFileTap?.(pathText, line, column) + } } else if (msg.type === 'keyboard-avoidance-metrics') { const cursorY = typeof msg.cursorY === 'number' ? msg.cursorY : 0 const rows = typeof msg.rows === 'number' ? msg.rows : 0 @@ -286,6 +296,7 @@ export const TerminalWebView = forwardRef(function onHaptic, onTerminalInput, onTerminalTap, + onFileTap, onTextScaleChange ] ) diff --git a/mobile/src/terminal/terminal-path-tap-injected.ts b/mobile/src/terminal/terminal-path-tap-injected.ts new file mode 100644 index 000000000..71b24de40 --- /dev/null +++ b/mobile/src/terminal/terminal-path-tap-injected.ts @@ -0,0 +1,72 @@ +// Plain-JS file-path-under-tap detection, injected verbatim into the terminal +// WebView's xterm script (XTERM_HTML). It is interpolated with ${...}, so the +// regex backslashes here are single (the real runtime form) — not the doubled +// form a backtick template literal would otherwise require. +// +// This mirrors the unit-tested mobile/src/terminal/terminal-path-tap.ts; keep +// the two in sync. The TS module is the source of truth for the algorithm and +// has the regression tests; this string only exists because the WebView can't +// import RN modules. +// +// Matches both slash-bearing paths AND bare filenames with an extension +// (README.md, src/index.ts:5) — like desktop, we propose candidates and let the +// host's files.resolveTerminalPath existence check reject non-files. Agents +// often print a bare filename (the markdown link target is consumed, leaving +// only the label text), so requiring a slash would miss the common case. +export const TERMINAL_PATH_TAP_JS = String.raw` + var FILE_PATH_RE = /(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/]|(?=[A-Za-z0-9._-]*\.[A-Za-z0-9]))[A-Za-z0-9._~\-\/%+@\\()[\]]*(?::\d+)?(?::\d+)?/g; + var PATH_LEADING_TRIM = { '(': 1, '[': 1, '{': 1, '"': 1, "'": 1 }; + var PATH_TRAILING_TRIM = { ')': 1, ']': 1, '}': 1, '"': 1, "'": 1, ',': 1, ';': 1, '.': 1 }; + + function parsePathLineCol(value) { + var m = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(value); + if (!m) return null; + var pathText = m[1]; + var last = pathText.charAt(pathText.length - 1); + if (!pathText || last === '/' || last === '\\') return null; + var line = m[2] ? parseInt(m[2], 10) : null; + var column = m[3] ? parseInt(m[3], 10) : null; + if ((line !== null && line < 1) || (column !== null && column < 1)) return null; + return { pathText: pathText, line: line, column: column }; + } + + function matchFilePathAtColumn(lineText, col) { + FILE_PATH_RE.lastIndex = 0; + var match; + while ((match = FILE_PATH_RE.exec(lineText)) !== null) { + var raw = match[0]; + if (raw.length === 0) { FILE_PATH_RE.lastIndex += 1; continue; } + var start = 0, end = raw.length; + while (start < end && PATH_LEADING_TRIM[raw.charAt(start)]) start += 1; + while (end > start && PATH_TRAILING_TRIM[raw.charAt(end - 1)]) end -= 1; + if (start >= end) continue; + var spanStart = match.index + start; + var spanEnd = match.index + end; + if (col < spanStart || col > spanEnd) continue; + var parsed = parsePathLineCol(raw.slice(start, end)); + if (parsed) return parsed; + } + return null; + } + + // Emits terminal-file-tap when the tap lands on a path candidate, else + // terminal-tap. The host resolves + existence-checks the candidate, so a + // false positive (a non-file word) just opens nothing. Relies on + // viewportToCell/getLineText/notify from the host script scope. + function notifyTapOrFilePath(originX, originY) { + var tapCell = viewportToCell(originX, originY); + var tappedPath = tapCell + ? matchFilePathAtColumn(getLineText(tapCell.row), tapCell.col) + : null; + if (tappedPath) { + notify({ + type: 'terminal-file-tap', + pathText: tappedPath.pathText, + line: tappedPath.line, + column: tappedPath.column + }); + } else { + notify({ type: 'terminal-tap' }); + } + } +` diff --git a/mobile/src/terminal/terminal-path-tap.test.ts b/mobile/src/terminal/terminal-path-tap.test.ts new file mode 100644 index 000000000..e31971b6e --- /dev/null +++ b/mobile/src/terminal/terminal-path-tap.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { matchFilePathAtColumn, parsePathWithOptionalLineColumn } from './terminal-path-tap' + +// Returns the column of the first occurrence of `needle` in `line` (+offset). +function colOf(line: string, needle: string, offset = 0): number { + return line.indexOf(needle) + offset +} + +describe('parsePathWithOptionalLineColumn', () => { + it('splits trailing :line:col suffixes', () => { + expect(parsePathWithOptionalLineColumn('src/a.ts')).toEqual({ + pathText: 'src/a.ts', + line: null, + column: null + }) + expect(parsePathWithOptionalLineColumn('src/a.ts:42')).toEqual({ + pathText: 'src/a.ts', + line: 42, + column: null + }) + expect(parsePathWithOptionalLineColumn('src/a.ts:42:7')).toEqual({ + pathText: 'src/a.ts', + line: 42, + column: 7 + }) + }) + + it('rejects directory-only and zero line/col', () => { + expect(parsePathWithOptionalLineColumn('src/')).toBeNull() + expect(parsePathWithOptionalLineColumn('src/a.ts:0')).toBeNull() + }) +}) + +describe('matchFilePathAtColumn', () => { + it('matches an absolute path under the tap', () => { + const line = 'created /tmp/out/report.html for you' + const result = matchFilePathAtColumn(line, colOf(line, 'report')) + expect(result?.pathText).toBe('/tmp/out/report.html') + }) + + it('matches a relative path and parses line:col', () => { + const line = 'see src/components/Button.tsx:12:7 here' + const result = matchFilePathAtColumn(line, colOf(line, 'Button')) + expect(result).toEqual({ pathText: 'src/components/Button.tsx', line: 12, column: 7 }) + }) + + it('matches a tilde path', () => { + const line = 'wrote ~/Documents/notes.md' + const result = matchFilePathAtColumn(line, colOf(line, 'notes')) + expect(result?.pathText).toBe('~/Documents/notes.md') + }) + + it('yields the tight whitespace-bounded segment under the tap', () => { + // On a path whose dir name has a space, tapping the file segment yields the + // openable sub-path after the space (still resolves against the worktree). + const line = '/Users/me/My Project/readme.md done' + const result = matchFilePathAtColumn(line, colOf(line, 'readme')) + expect(result?.pathText).toBe('Project/readme.md') + }) + + it('trims surrounding punctuation', () => { + const line = 'open (src/a.ts) now' + const result = matchFilePathAtColumn(line, colOf(line, 'a.ts')) + expect(result?.pathText).toBe('src/a.ts') + }) + + it('returns null when the tap is not on a path', () => { + const line = 'just some prose with no path here' + expect(matchFilePathAtColumn(line, colOf(line, 'prose'))).toBeNull() + }) + + it('returns null when the tap is left of the path span', () => { + const line = 'prefix /tmp/x.ts' + expect(matchFilePathAtColumn(line, 0)).toBeNull() + }) + + it('matches a bare filename with an extension (no slash)', () => { + // Why: agents commonly print a bare filename (e.g. a markdown link whose + // target was consumed). The host existence-check rejects non-files. + const line = '• Here you go: README.md' + const result = matchFilePathAtColumn(line, colOf(line, 'README')) + expect(result?.pathText).toBe('README.md') + }) + + it('does not match a plain word without an extension', () => { + const line = '• Here you go: README.md' + expect(matchFilePathAtColumn(line, colOf(line, 'Here'))).toBeNull() + }) +}) diff --git a/mobile/src/terminal/terminal-path-tap.ts b/mobile/src/terminal/terminal-path-tap.ts new file mode 100644 index 000000000..7c9d29515 --- /dev/null +++ b/mobile/src/terminal/terminal-path-tap.ts @@ -0,0 +1,91 @@ +// File-path detection for a single tap in the terminal. Mirrors the desktop +// link detection (src/renderer/src/lib/terminal-links.ts) but only finds the +// one path span containing the tapped column — mobile opens a tapped path, it +// does not render hover links over the whole line. + +export type TappedFilePath = { + pathText: string + line: number | null + column: number | null +} + +// Separator-anchored path tokens (absolute, relative, ~/, drive-letter, UNC) OR +// a bare filename with an extension (README.md, index.ts), optionally suffixed +// with :line or :line:col. Like desktop, we propose candidates and let the host +// existence-check reject non-files — agents often print a bare filename, so +// requiring a slash would miss the common case. The desktop's spaced-path +// variants are intentionally not ported: a tap always lands inside one +// whitespace-bounded segment, so this already covers the real cases. +const LOCAL_PATH_REGEX = + /(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/]|(?=[A-Za-z0-9._-]*\.[A-Za-z0-9]))[A-Za-z0-9._~\-/%+@\\()[\]]*(?::\d+)?(?::\d+)?/g + +const LEADING_TRIM_CHARS = new Set(['(', '[', '{', '"', "'"]) +const TRAILING_TRIM_CHARS = new Set([')', ']', '}', '"', "'", ',', ';', '.']) + +type Span = { startIndex: number; endIndex: number } + +function trimBoundaryPunctuation( + value: string, + startIndex: number +): (Span & { text: string }) | null { + let start = 0 + let end = value.length + while (start < end && LEADING_TRIM_CHARS.has(value[start])) { + start += 1 + } + while (end > start && TRAILING_TRIM_CHARS.has(value[end - 1])) { + end -= 1 + } + if (start >= end) { + return null + } + return { + text: value.slice(start, end), + startIndex: startIndex + start, + endIndex: startIndex + end + } +} + +export function parsePathWithOptionalLineColumn(value: string): TappedFilePath | null { + const match = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(value) + if (!match) { + return null + } + const pathText = match[1] + // Reject a directory-only token (trailing separator) for either slash style. + if (!pathText || pathText.endsWith('/') || pathText.endsWith('\\')) { + return null + } + const line = match[2] ? Number.parseInt(match[2], 10) : null + const column = match[3] ? Number.parseInt(match[3], 10) : null + if ((line !== null && line < 1) || (column !== null && column < 1)) { + return null + } + return { pathText, line, column } +} + +// Returns the file-path span (after punctuation trim) that contains `col`, or +// null when the tap isn't on a path. +export function matchFilePathAtColumn(lineText: string, col: number): TappedFilePath | null { + LOCAL_PATH_REGEX.lastIndex = 0 + let match: RegExpExecArray | null + while ((match = LOCAL_PATH_REGEX.exec(lineText)) !== null) { + if (match[0].length === 0) { + LOCAL_PATH_REGEX.lastIndex += 1 + continue + } + const trimmed = trimBoundaryPunctuation(match[0], match.index) + if (!trimmed) { + continue + } + // Inclusive of the trailing edge so a tap on the last glyph still counts. + if (col < trimmed.startIndex || col > trimmed.endIndex) { + continue + } + const parsed = parsePathWithOptionalLineColumn(trimmed.text) + if (parsed) { + return parsed + } + } + return null +} diff --git a/mobile/src/terminal/terminal-webview-html.ts b/mobile/src/terminal/terminal-webview-html.ts index e909ceb13..4814f443c 100644 --- a/mobile/src/terminal/terminal-webview-html.ts +++ b/mobile/src/terminal/terminal-webview-html.ts @@ -3,6 +3,7 @@ import type { RuntimeMobileTerminalTheme } from '../../../src/shared/runtime-types' import { colors } from '../theme/mobile-theme' import { TERMINAL_TEXT_SCALES } from '../storage/preferences' +import { TERMINAL_PATH_TAP_JS } from './terminal-path-tap-injected' const DEFAULT_TERMINAL_THEME: RuntimeMobileTerminalTheme['theme'] = { background: colors.terminalBg, @@ -1315,6 +1316,10 @@ export const XTERM_HTML = ` return line.translateToString(false); } + // File-path-under-tap detection (matchFilePathAtColumn). See + // terminal-path-tap-injected.ts; mirrors the unit-tested terminal-path-tap.ts. + ${TERMINAL_PATH_TAP_JS} + function seedWordSelection(col, absRow) { var line = getLineText(absRow); if (!line) { @@ -1636,7 +1641,8 @@ export const XTERM_HTML = ` if (clickInput) { notify({ type: 'terminal-input', bytes: clickInput }); } else if (!isClickMouseTrackingMode(getMouseTrackingMode())) { - notify({ type: 'terminal-tap' }); + // Tap on a file path → terminal-file-tap (RN opens it); else focus. + notifyTapOrFilePath(longPressOrigin.x, longPressOrigin.y); } } clearLongPress(); diff --git a/mobile/src/terminal/terminal-webview-scroll-routing.test.ts b/mobile/src/terminal/terminal-webview-scroll-routing.test.ts index 8a5a07328..0651050db 100644 --- a/mobile/src/terminal/terminal-webview-scroll-routing.test.ts +++ b/mobile/src/terminal/terminal-webview-scroll-routing.test.ts @@ -188,8 +188,11 @@ describe('TerminalWebView scroll routing', () => { "document.addEventListener('touchend'", '}, { capture: true, passive: true });' ) + // Why: mouse-click synthesis must precede the tap/file-path fallback so a + // bound mouse mode wins. The fallback now routes through notifyTapOrFilePath + // (which emits terminal-file-tap on a path, else terminal-tap). expect(touchEndBlock.indexOf('var clickInput = buildMouseClickInput')).toBeLessThan( - touchEndBlock.indexOf("notify({ type: 'terminal-tap' });") + touchEndBlock.indexOf('notifyTapOrFilePath(') ) expect(touchEndBlock).toContain("notify({ type: 'terminal-input', bytes: clickInput });") expect(touchEndBlock).toContain( diff --git a/mobile/src/worktree/agent-row-display.test.ts b/mobile/src/worktree/agent-row-display.test.ts new file mode 100644 index 000000000..80889753d --- /dev/null +++ b/mobile/src/worktree/agent-row-display.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { + AGENT_STATUS_STALE_AFTER_MS, + agentDisplayLabel, + agentDotState, + agentIdentityLabel, + formatTimeAgo +} from './agent-row-display' + +function row(overrides: Partial = {}): RuntimeWorktreeAgentRow { + return { + paneKey: 'p', + parentPaneKey: null, + state: 'working', + agentType: 'claude', + prompt: '', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: 0, + updatedAt: 0, + ...overrides + } +} + +describe('agentDotState', () => { + it('maps known states through and unknown to idle', () => { + expect(agentDotState(row({ state: 'working', updatedAt: 0 }), 0)).toBe('working') + expect(agentDotState(row({ state: 'blocked', updatedAt: 0 }), 0)).toBe('blocked') + expect(agentDotState(row({ state: 'waiting', updatedAt: 0 }), 0)).toBe('waiting') + expect(agentDotState(row({ state: 'done', updatedAt: 0 }), 0)).toBe('done') + expect(agentDotState(row({ state: 'unknown-state' as never }), 0)).toBe('idle') + }) + + it('reports interrupted regardless of state', () => { + expect(agentDotState(row({ state: 'done', interrupted: true }), 0)).toBe('interrupted') + }) + + it('decays a stale active state to idle, matching desktop', () => { + const stale = AGENT_STATUS_STALE_AFTER_MS + 1 + // Active states past the staleness window read as idle… + expect(agentDotState(row({ state: 'working', updatedAt: 0 }), stale)).toBe('idle') + expect(agentDotState(row({ state: 'blocked', updatedAt: 0 }), stale)).toBe('idle') + expect(agentDotState(row({ state: 'waiting', updatedAt: 0 }), stale)).toBe('idle') + // …exactly at the threshold it is still fresh (decay is strictly past it). + expect( + agentDotState(row({ state: 'working', updatedAt: 0 }), AGENT_STATUS_STALE_AFTER_MS) + ).toBe('working') + // 'done' never decays; interrupted still wins. + expect(agentDotState(row({ state: 'done', updatedAt: 0 }), stale)).toBe('done') + expect(agentDotState(row({ state: 'working', updatedAt: 0, interrupted: true }), stale)).toBe( + 'interrupted' + ) + }) +}) + +describe('agentDisplayLabel', () => { + it('prefers last message, then prompt, then state label', () => { + expect(agentDisplayLabel(row({ lastAssistantMessage: 'hello there' }), 0)).toBe('hello there') + expect(agentDisplayLabel(row({ lastAssistantMessage: ' ', prompt: 'do the thing' }), 0)).toBe( + 'do the thing' + ) + expect(agentDisplayLabel(row({ state: 'working', prompt: '', updatedAt: 0 }), 0)).toBe( + 'Working' + ) + }) + + it('falls back to the decayed state label when stale', () => { + expect( + agentDisplayLabel( + row({ state: 'working', prompt: '', updatedAt: 0 }), + AGENT_STATUS_STALE_AFTER_MS + 1 + ) + ).toBe('Idle') + }) +}) + +describe('agentIdentityLabel', () => { + it('maps known agent types and falls back to initials', () => { + expect(agentIdentityLabel('claude')).toBe('CL') + expect(agentIdentityLabel('codex')).toBe('CX') + expect(agentIdentityLabel('mystery')).toBe('MY') + expect(agentIdentityLabel(null)).toBe('') + }) +}) + +describe('formatTimeAgo', () => { + const now = 10_000_000 + it('formats across thresholds', () => { + expect(formatTimeAgo(now - 30_000, now)).toBe('just now') + expect(formatTimeAgo(now - 5 * 60_000, now)).toBe('5m') + expect(formatTimeAgo(now - 3 * 3_600_000, now)).toBe('3h') + expect(formatTimeAgo(now - 2 * 86_400_000, now)).toBe('2d') + }) +}) diff --git a/mobile/src/worktree/agent-row-display.ts b/mobile/src/worktree/agent-row-display.ts new file mode 100644 index 000000000..f052f603c --- /dev/null +++ b/mobile/src/worktree/agent-row-display.ts @@ -0,0 +1,104 @@ +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' + +// Mirrors the desktop AGENT_STATUS_STALE_AFTER_MS (src/shared/agent-status-types.ts: +// 30 min). Defined locally rather than imported because a runtime-value import +// from a root .ts breaks mobile's vitest transform (no tsconfig in the +// mobile-only checkout); root type-only imports stay fine. +export const AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000 + +// Mirrors the desktop AgentStateDot vocabulary. The wire `state` is the agent +// status state; 'blocked'/'waiting' read as attention states, 'done' as +// complete, everything else idle. +export type AgentDotState = 'working' | 'blocked' | 'waiting' | 'done' | 'idle' | 'interrupted' + +export function agentDotState( + row: Pick, + now: number +): AgentDotState { + if (row.interrupted) { + return 'interrupted' + } + switch (row.state) { + case 'working': + case 'blocked': + case 'waiting': + // Why: an agent that exits without a final report would otherwise read as + // active forever. Decay a stale active state to idle, matching desktop's + // renderer-side staleness decay (worktree-agent-rows.ts). + return now - row.updatedAt > AGENT_STATUS_STALE_AFTER_MS ? 'idle' : row.state + case 'done': + return 'done' + } + return 'idle' +} + +// Mirrors desktop agentStateLabel. +export function agentStateLabel(state: AgentDotState): string { + switch (state) { + case 'working': + return 'Working' + case 'blocked': + return 'Blocked' + case 'waiting': + return 'Waiting for input' + case 'interrupted': + return 'Interrupted' + case 'done': + return 'Done' + case 'idle': + return 'Idle' + } +} + +// Primary row text: prefer the agent's last message, then the user prompt, then +// a human-readable state label so a row is never blank. Matches the desktop +// DashboardAgentRow displayLabel fallback chain. +export function agentDisplayLabel(row: RuntimeWorktreeAgentRow, now: number): string { + const message = row.lastAssistantMessage?.trim() + if (message) { + return message + } + const prompt = row.prompt.trim() + if (prompt) { + return prompt + } + return agentStateLabel(agentDotState(row, now)) +} + +// Short agent identity label by type (Claude/Codex/Gemini/…), used when no +// identity icon is available on mobile. Falls back to the first two letters. +export function agentIdentityLabel(agentType: string | null): string { + if (!agentType) { + return '' + } + const normalized = agentType.toLowerCase() + const known: Record = { + claude: 'CL', + codex: 'CX', + gemini: 'GM', + cursor: 'CR', + copilot: 'CP', + amp: 'AM', + aider: 'AI', + opencode: 'OC' + } + return known[normalized] ?? normalized.slice(0, 2).toUpperCase() +} + +// Relative time, matching desktop formatTimeAgo thresholds (just now / Xm / Xh / Xd). +export function formatTimeAgo(ts: number, now: number): string { + const delta = now - ts + if (delta < 60_000) { + return 'just now' + } + const minutes = Math.floor(delta / 60_000) + if (minutes < 60) { + return `${minutes}m` + } + const hours = Math.floor(minutes / 60) + if (hours < 24) { + return `${hours}h` + } + const days = Math.floor(hours / 24) + return `${days}d` +} diff --git a/mobile/src/worktree/agent-row-lineage.test.ts b/mobile/src/worktree/agent-row-lineage.test.ts new file mode 100644 index 000000000..468f21202 --- /dev/null +++ b/mobile/src/worktree/agent-row-lineage.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { buildAgentRowLineageTree, flattenAgentRowLineage } from './agent-row-lineage' + +function row( + paneKey: string, + parentPaneKey: string | null = null, + overrides: Partial = {} +): RuntimeWorktreeAgentRow { + return { + paneKey, + parentPaneKey, + state: 'working', + agentType: 'claude', + prompt: '', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: 0, + updatedAt: 0, + ...overrides + } +} + +describe('buildAgentRowLineageTree', () => { + it('groups children under their parent and leaves roots flat', () => { + const rows = [row('a'), row('b', 'a'), row('c', 'a'), row('d')] + const { rootRows, childrenByParentPaneKey } = buildAgentRowLineageTree(rows) + + expect(rootRows.map((r) => r.paneKey)).toEqual(['a', 'd']) + expect(childrenByParentPaneKey.get('a')?.map((r) => r.paneKey)).toEqual(['b', 'c']) + }) + + it('treats a dangling parent pointer as a root', () => { + const rows = [row('a', 'missing-parent'), row('b')] + const { rootRows } = buildAgentRowLineageTree(rows) + + expect(rootRows.map((r) => r.paneKey).sort()).toEqual(['a', 'b']) + }) + + it('keeps all rows visible when the parent links form a cycle', () => { + const rows = [row('a', 'b'), row('b', 'a')] + const { rootRows, childrenByParentPaneKey } = buildAgentRowLineageTree(rows) + + expect(rootRows.map((r) => r.paneKey).sort()).toEqual(['a', 'b']) + expect(childrenByParentPaneKey.size).toBe(0) + }) + + it('ignores a self-referential parent', () => { + const { rootRows } = buildAgentRowLineageTree([row('a', 'a')]) + expect(rootRows.map((r) => r.paneKey)).toEqual(['a']) + }) +}) + +describe('flattenAgentRowLineage', () => { + it('emits parent then descendants with increasing depth', () => { + const rows = [row('a'), row('b', 'a'), row('c', 'b'), row('d')] + const flat = flattenAgentRowLineage(rows) + + expect(flat.map((n) => [n.row.paneKey, n.depth])).toEqual([ + ['a', 0], + ['b', 1], + ['c', 2], + ['d', 0] + ]) + }) + + it('keeps a cyclic component visible even when other roots exist', () => { + // 'root' is a normal root; a<->b form a disconnected cycle that has no root + // entry and is unreachable from 'root' — it must still be surfaced. + const rows = [row('root'), row('a', 'b'), row('b', 'a')] + const flat = flattenAgentRowLineage(rows) + expect(flat.map((n) => n.row.paneKey).sort()).toEqual(['a', 'b', 'root']) + }) +}) diff --git a/mobile/src/worktree/agent-row-lineage.ts b/mobile/src/worktree/agent-row-lineage.ts new file mode 100644 index 000000000..4d3fe7ffe --- /dev/null +++ b/mobile/src/worktree/agent-row-lineage.ts @@ -0,0 +1,88 @@ +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' + +export type AgentRowNode = { + row: RuntimeWorktreeAgentRow + depth: number + children: AgentRowNode[] +} + +export type AgentRowLineageTree = { + rootRows: RuntimeWorktreeAgentRow[] + childrenByParentPaneKey: Map +} + +// Mirrors the desktop buildAgentRowLineageTree: groups a flat agent list into a +// spawn tree by parentPaneKey. The wire rows already carry a resolved +// parentPaneKey (the server reads the orchestration db), so this only has to +// group and guard against malformed (cyclic / dangling-parent) metadata. +export function buildAgentRowLineageTree( + rows: readonly RuntimeWorktreeAgentRow[] +): AgentRowLineageTree { + const byPaneKey = new Map() + for (const row of rows) { + if (!byPaneKey.has(row.paneKey)) { + byPaneKey.set(row.paneKey, row) + } + } + + const childrenByParentPaneKey = new Map() + const childPaneKeys = new Set() + for (const row of rows) { + const parentPaneKey = row.parentPaneKey + // Why: ignore a parent that points at the row itself or at a pane not in + // this list — treat those as roots rather than dropping them. + if (!parentPaneKey || parentPaneKey === row.paneKey || !byPaneKey.has(parentPaneKey)) { + continue + } + childPaneKeys.add(row.paneKey) + const siblings = childrenByParentPaneKey.get(parentPaneKey) + if (siblings) { + siblings.push(row) + } else { + childrenByParentPaneKey.set(parentPaneKey, [row]) + } + } + + const rootRows = rows.filter((row) => !childPaneKeys.has(row.paneKey)) + if (rootRows.length === 0 && rows.length > 0) { + // Why: a closed cycle leaves no root. Keep every agent visible as a flat + // root instead of hiding all participants. + return { rootRows: [...rows], childrenByParentPaneKey: new Map() } + } + + return { rootRows, childrenByParentPaneKey } +} + +// Flattens the lineage tree into depth-tagged nodes in render order +// (parent immediately followed by its descendants). Cycle-guarded. +export function flattenAgentRowLineage(rows: readonly RuntimeWorktreeAgentRow[]): AgentRowNode[] { + const { rootRows, childrenByParentPaneKey } = buildAgentRowLineageTree(rows) + const out: AgentRowNode[] = [] + const seen = new Set() + const visit = (row: RuntimeWorktreeAgentRow, depth: number, ancestors: ReadonlySet) => { + if (ancestors.has(row.paneKey)) { + return + } + seen.add(row.paneKey) + const node: AgentRowNode = { row, depth, children: [] } + out.push(node) + const nextAncestors = new Set(ancestors) + nextAncestors.add(row.paneKey) + for (const child of childrenByParentPaneKey.get(row.paneKey) ?? []) { + visit(child, depth + 1, nextAncestors) + } + } + for (const root of rootRows) { + visit(root, 0, new Set()) + } + // Why: a cyclic component that coexists with a normal rooted tree has no entry + // in rootRows and is unreachable from any root, so it would silently vanish. + // Surface any not-yet-emitted rows as depth-0 so every agent stays visible. + for (const row of rows) { + if (!seen.has(row.paneKey)) { + seen.add(row.paneKey) + out.push({ row, depth: 0, children: [] }) + } + } + return out +} diff --git a/mobile/src/worktree/resume-worktree.test.ts b/mobile/src/worktree/resume-worktree.test.ts new file mode 100644 index 000000000..8a49e9edb --- /dev/null +++ b/mobile/src/worktree/resume-worktree.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { pickResumeWorktree } from './resume-worktree' + +const wt = (id: string, extra: { isActive?: boolean; lastOutputAt?: number } = {}) => ({ + id, + ...extra +}) + +describe('pickResumeWorktree', () => { + it('returns null for an empty list', () => { + expect(pickResumeWorktree([])).toBeNull() + }) + + it('prefers the desktop-active worktree over list order and output time', () => { + const list = [ + wt('a', { lastOutputAt: 999 }), + wt('b', { isActive: true, lastOutputAt: 1 }), + wt('c', { lastOutputAt: 500 }) + ] + expect(pickResumeWorktree(list)?.id).toBe('b') + }) + + it('falls back to the most recent output when none is desktop-active', () => { + const list = [wt('a', { lastOutputAt: 10 }), wt('b', { lastOutputAt: 99 }), wt('c')] + expect(pickResumeWorktree(list)?.id).toBe('b') + }) + + it('falls back to the first when there is no output timing', () => { + const list = [wt('a'), wt('b'), wt('c')] + expect(pickResumeWorktree(list)?.id).toBe('a') + }) +}) diff --git a/mobile/src/worktree/resume-worktree.ts b/mobile/src/worktree/resume-worktree.ts new file mode 100644 index 000000000..f963836e7 --- /dev/null +++ b/mobile/src/worktree/resume-worktree.ts @@ -0,0 +1,27 @@ +// Picks the worktree the home-screen Resume card falls back to for a host when +// there's no mobile session history yet. Mirrors the desktop's focused +// workspace (worktree.ps marks exactly one isActive) rather than an arbitrary +// list-order pick, so a cold launch resumes the right thing. + +export type ResumeCandidate = { + isActive?: boolean + lastOutputAt?: number +} + +export function pickResumeWorktree(worktrees: T[]): T | null { + if (worktrees.length === 0) { + return null + } + const desktopActive = worktrees.find((w) => w.isActive) + if (desktopActive) { + return desktopActive + } + // No desktop focus → most recent terminal output, else the first. + let best = worktrees[0] + for (const w of worktrees) { + if ((w.lastOutputAt ?? 0) > (best.lastOutputAt ?? 0)) { + best = w + } + } + return best +} diff --git a/mobile/src/worktree/workspace-list-sections.ts b/mobile/src/worktree/workspace-list-sections.ts new file mode 100644 index 000000000..bc1ea0525 --- /dev/null +++ b/mobile/src/worktree/workspace-list-sections.ts @@ -0,0 +1,274 @@ +// Pure data transforms for the host workspaces list: status derivation, +// filtering, sorting, and grouping into SectionList sections. Kept out of the +// screen component so the screen stays under its line cap and the logic is +// unit-testable in isolation. + +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { MobileGroupMode, MobileSortMode } from './workspace-view-settings' + +export type Worktree = { + worktreeId: string + repoId: string + repo: string + branch: string + displayName: string + // Why: on-disk worktree directory path. Needed by NewWorktreeModal so the + // marine-creature fallback dedupes against the actual filesystem basenames + // (matching the desktop's collision check), not against displayName which + // the user may have renamed. + path: string + liveTerminalCount: number + hasAttachedPty: boolean + preview: string + unread: boolean + lastOutputAt?: number + isPinned: boolean + isActive?: boolean + linkedPR: { number: number; state: string } | null + linkedIssue?: number | null + linkedLinearIssue?: string | null + linkedGitLabMR?: number | null + linkedGitLabIssue?: number | null + comment?: string + status?: 'working' | 'active' | 'permission' | 'done' | 'inactive' + agents?: RuntimeWorktreeAgentRow[] +} + +// Desktop's filter model (shared via PersistedUIState): repos selected by id, +// plus two hide toggles. There is no "active only" — hideSleeping is the +// inverse intent. +export type FilterState = { + filterRepoIds: Set + hideSleeping: boolean + hideDefaultBranch: boolean +} + +export type Section = { title: string; icon?: 'pin'; data: Worktree[] } + +export function getWorktreeStatus( + w: Worktree +): 'working' | 'active' | 'permission' | 'done' | 'inactive' { + if (w.status) { + return w.status + } + if (w.liveTerminalCount > 0) { + return 'active' + } + return 'inactive' +} + +// Why: the previous 10-minute lastOutputAt window was too strict — most +// worktrees with idle terminal prompts had no recent output and were excluded. +// Any worktree with live terminals or unread output counts as "active". +export function isWorktreeActive(w: Worktree): boolean { + if (w.unread) { + return true + } + if (w.status) { + return w.status !== 'inactive' + } + if (w.liveTerminalCount > 0) { + return true + } + return false +} + +// Why: mobile worktree.ps carries no per-repo default branch, so we treat the +// conventional main/master as the default for the hideDefaultBranch filter. +function isOnDefaultBranch(w: Worktree): boolean { + const branch = w.branch.replace(/^refs\/heads\//, '') + return branch === 'main' || branch === 'master' +} + +export const WORKSPACE_STATUS_LABELS: Record, string> = { + permission: 'Needs Permission', + working: 'Working', + done: 'Done', + active: 'Active', + inactive: 'Inactive' +} + +export const WORKSPACE_STATUS_ORDER: ReturnType[] = [ + 'permission', + 'working', + 'done', + 'active', + 'inactive' +] + +export function sortWorktrees(worktrees: Worktree[], mode: MobileSortMode): Worktree[] { + // 'manual' keeps the server (worktree.ps) order untouched. + if (mode === 'manual') { + return worktrees + } + return [...worktrees].sort((a, b) => { + if (mode === 'name') { + return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) + } + if (mode === 'recent') { + return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) + } + if (mode === 'repo') { + const repoComparison = a.repo.localeCompare(b.repo, undefined, { sensitivity: 'base' }) + return repoComparison || (a.displayName || a.repo).localeCompare(b.displayName || b.repo) + } + // 'smart' — attention-first + if (a.unread !== b.unread) { + return a.unread ? -1 : 1 + } + const aStatus = getWorktreeStatus(a) + const bStatus = getWorktreeStatus(b) + const statusOrder = { permission: 0, working: 1, done: 2, active: 3, inactive: 4 } + if (statusOrder[aStatus] !== statusOrder[bStatus]) { + return statusOrder[aStatus] - statusOrder[bStatus] + } + if ((a.lastOutputAt ?? 0) !== (b.lastOutputAt ?? 0)) { + return (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) + } + return (a.displayName || a.repo).localeCompare(b.displayName || b.repo) + }) +} + +export function filterWorktrees( + worktrees: Worktree[], + filters: FilterState, + search: string +): Worktree[] { + let result = worktrees + if (filters.hideSleeping) { + result = result.filter((w) => getWorktreeStatus(w) !== 'inactive') + } + if (filters.hideDefaultBranch) { + result = result.filter((w) => !isOnDefaultBranch(w)) + } + if (filters.filterRepoIds.size > 0) { + result = result.filter((w) => filters.filterRepoIds.has(w.repoId)) + } + if (search.trim()) { + const q = search.toLowerCase() + result = result.filter( + (w) => + (w.displayName || w.repo).toLowerCase().includes(q) || + w.branch.toLowerCase().includes(q) || + w.repo.toLowerCase().includes(q) + ) + } + return result +} + +// Why: matches desktop's PR_GROUP_META naming from worktree-list-groups.ts. +// no PR/draft/unknown → "In Progress", open → "In Review", merged → "Done", closed → "Closed" +type PRGroupKey = 'done' | 'in-review' | 'in-progress' | 'closed' + +const PR_GROUP_LABELS: Record = { + done: 'Done', + 'in-review': 'In Review', + 'in-progress': 'In Progress', + closed: 'Closed' +} + +const PR_GROUP_ORDER: PRGroupKey[] = ['done', 'in-review', 'in-progress', 'closed'] + +function getPRGroupKey(w: Worktree): PRGroupKey { + if (!w.linkedPR) { + return 'in-progress' + } + const s = w.linkedPR.state.toLowerCase() + if (s === 'merged') { + return 'done' + } + if (s === 'closed') { + return 'closed' + } + if (s === 'draft') { + return 'in-progress' + } + return 'in-review' +} + +export function isWorktreePinned(w: Worktree, localPins: Set): boolean { + return w.isPinned || localPins.has(w.worktreeId) +} + +export function buildSections( + worktrees: Worktree[], + sortMode: MobileSortMode, + filters: FilterState, + search: string, + groupMode: MobileGroupMode, + pinnedIds: Set +): Section[] { + const filtered = filterWorktrees(worktrees, filters, search) + const sorted = sortWorktrees(filtered, sortMode) + + const pinned = sorted.filter((w) => isWorktreePinned(w, pinnedIds)) + const unpinned = sorted.filter((w) => !isWorktreePinned(w, pinnedIds)) + const active = unpinned.filter(isWorktreeActive) + const inactive = unpinned.filter((w) => !isWorktreeActive(w)) + + const sections: Section[] = [] + if (pinned.length > 0) { + sections.push({ title: 'Pinned', icon: 'pin', data: pinned }) + } + + if (groupMode === 'none') { + if (active.length > 0) { + // Why: without explicit grouping, mobile's primary workflow is jumping + // back into running sessions before browsing the full worktree archive. + sections.push({ title: 'Active', data: active }) + } + if (inactive.length > 0) { + sections.push({ title: pinned.length > 0 || active.length > 0 ? 'All' : '', data: inactive }) + } + } else if (groupMode === 'repo') { + const byRepo = new Map() + for (const w of unpinned) { + const key = w.repo || 'Unknown' + const list = byRepo.get(key) + if (list) { + list.push(w) + } else { + byRepo.set(key, [w]) + } + } + for (const [repo, items] of byRepo) { + sections.push({ title: repo, data: items }) + } + } else if (groupMode === 'workspaceStatus') { + const byStatus = new Map, Worktree[]>() + for (const w of unpinned) { + const key = getWorktreeStatus(w) + const list = byStatus.get(key) + if (list) { + list.push(w) + } else { + byStatus.set(key, [w]) + } + } + for (const status of WORKSPACE_STATUS_ORDER) { + const items = byStatus.get(status) + if (items && items.length > 0) { + sections.push({ title: WORKSPACE_STATUS_LABELS[status], data: items }) + } + } + } else if (groupMode === 'prStatus') { + const byGroup = new Map() + for (const w of unpinned) { + const key = getPRGroupKey(w) + const list = byGroup.get(key) + if (list) { + list.push(w) + } else { + byGroup.set(key, [w]) + } + } + for (const groupKey of PR_GROUP_ORDER) { + const items = byGroup.get(groupKey) + if (items && items.length > 0) { + sections.push({ title: PR_GROUP_LABELS[groupKey], data: items }) + } + } + } + + return sections +} diff --git a/mobile/src/worktree/workspace-view-settings.test.ts b/mobile/src/worktree/workspace-view-settings.test.ts new file mode 100644 index 000000000..bfd8100c8 --- /dev/null +++ b/mobile/src/worktree/workspace-view-settings.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { + applyDesktopViewSettings, + groupModeFromDesktop, + groupModeToDesktop, + sortModeFromDesktop, + type MobileViewState +} from './workspace-view-settings' + +const base: MobileViewState = { + groupMode: 'repo', + sortMode: 'recent', + hideSleeping: false, + hideDefaultBranch: false, + filterRepoIds: [], + collapsedGroups: [] +} + +describe('group mode mapping', () => { + it('round-trips every mobile group mode through the desktop value', () => { + for (const mode of ['none', 'workspaceStatus', 'repo', 'prStatus'] as const) { + expect(groupModeFromDesktop(groupModeToDesktop(mode))).toBe(mode) + } + }) + + it('maps the desktop kebab-case values back to mobile', () => { + expect(groupModeFromDesktop('workspace-status')).toBe('workspaceStatus') + expect(groupModeFromDesktop('pr-status')).toBe('prStatus') + expect(groupModeFromDesktop(undefined)).toBeNull() + }) +}) + +describe('sort mode mapping', () => { + it('accepts shared sort values and rejects unknown', () => { + expect(sortModeFromDesktop('manual')).toBe('manual') + expect(sortModeFromDesktop('smart')).toBe('smart') + expect(sortModeFromDesktop(undefined)).toBeNull() + expect(sortModeFromDesktop('bogus' as never)).toBeNull() + }) +}) + +describe('applyDesktopViewSettings', () => { + it('applies provided desktop fields and leaves missing ones untouched', () => { + const next = applyDesktopViewSettings(base, { + groupBy: 'pr-status', + hideSleepingWorkspaces: true, + filterRepoIds: ['repo-1'] + }) + expect(next).toEqual({ + groupMode: 'prStatus', + sortMode: 'recent', // unchanged (sortBy absent) + hideSleeping: true, + hideDefaultBranch: false, // unchanged + filterRepoIds: ['repo-1'], + collapsedGroups: [] + }) + }) + + it('keeps current values when the desktop payload is empty', () => { + expect(applyDesktopViewSettings(base, {})).toEqual(base) + }) + + it('ignores an unrecognized groupBy rather than blanking the mode', () => { + const next = applyDesktopViewSettings(base, { groupBy: 'mystery' as never }) + expect(next.groupMode).toBe('repo') + }) +}) diff --git a/mobile/src/worktree/workspace-view-settings.ts b/mobile/src/worktree/workspace-view-settings.ts new file mode 100644 index 000000000..34af85f62 --- /dev/null +++ b/mobile/src/worktree/workspace-view-settings.ts @@ -0,0 +1,79 @@ +// Bi-directional mapping between the mobile workspaces screen's local view model +// and the desktop's shared PersistedUIState (read/written via the ui.get/ui.set +// RPCs). Keeping these settings in the same global store is what lets a grouping +// or filter change on the phone show up on desktop and vice-versa. + +export type MobileGroupMode = 'none' | 'workspaceStatus' | 'repo' | 'prStatus' +// Desktop sort adds 'manual'; mobile renders it but sorts by server order. +export type MobileSortMode = 'smart' | 'name' | 'recent' | 'repo' | 'manual' + +// Desktop PersistedUIState fields this screen syncs (a structural subset). +export type WorkspaceViewSettings = { + groupBy?: 'none' | 'workspace-status' | 'repo' | 'pr-status' + sortBy?: 'name' | 'smart' | 'recent' | 'repo' | 'manual' + hideSleepingWorkspaces?: boolean + hideDefaultBranchWorkspace?: boolean + filterRepoIds?: string[] + collapsedGroups?: string[] +} + +const GROUP_TO_DESKTOP: Record> = { + none: 'none', + workspaceStatus: 'workspace-status', + repo: 'repo', + prStatus: 'pr-status' +} + +const GROUP_FROM_DESKTOP: Record, MobileGroupMode> = { + none: 'none', + 'workspace-status': 'workspaceStatus', + repo: 'repo', + 'pr-status': 'prStatus' +} + +const SORT_VALUES: readonly MobileSortMode[] = ['smart', 'name', 'recent', 'repo', 'manual'] + +export function groupModeToDesktop( + mode: MobileGroupMode +): NonNullable { + return GROUP_TO_DESKTOP[mode] +} + +export function groupModeFromDesktop( + groupBy: WorkspaceViewSettings['groupBy'] +): MobileGroupMode | null { + return groupBy ? (GROUP_FROM_DESKTOP[groupBy] ?? null) : null +} + +export function sortModeFromDesktop( + sortBy: WorkspaceViewSettings['sortBy'] +): MobileSortMode | null { + return sortBy && SORT_VALUES.includes(sortBy) ? sortBy : null +} + +export type MobileViewState = { + groupMode: MobileGroupMode + sortMode: MobileSortMode + hideSleeping: boolean + hideDefaultBranch: boolean + filterRepoIds: string[] + collapsedGroups: string[] +} + +// Apply a desktop PersistedUIState onto the local view state, leaving any field +// the desktop hasn't set untouched (so a partial ui.get doesn't clobber). +export function applyDesktopViewSettings( + current: MobileViewState, + settings: WorkspaceViewSettings +): MobileViewState { + const groupMode = groupModeFromDesktop(settings.groupBy) + const sortMode = sortModeFromDesktop(settings.sortBy) + return { + groupMode: groupMode ?? current.groupMode, + sortMode: sortMode ?? current.sortMode, + hideSleeping: settings.hideSleepingWorkspaces ?? current.hideSleeping, + hideDefaultBranch: settings.hideDefaultBranchWorkspace ?? current.hideDefaultBranch, + filterRepoIds: settings.filterRepoIds ?? current.filterRepoIds, + collapsedGroups: settings.collapsedGroups ?? current.collapsedGroups + } +} diff --git a/src/main/git/checkout.ts b/src/main/git/checkout.ts new file mode 100644 index 000000000..128cd1a27 --- /dev/null +++ b/src/main/git/checkout.ts @@ -0,0 +1,66 @@ +import { gitExecFileAsync } from './runner' + +/** + * Reject branch names git would parse as an option (`-`/`--…`) or that aren't a + * valid ref. Defense-in-depth: callers also validate at the RPC schema, but the + * relay entrypoint is reachable independently, so the helper guards too. + */ +export function assertValidBranchName(branch: string): void { + if (branch.length === 0 || branch.startsWith('-')) { + throw new Error('invalid_branch_name') + } +} + +/** + * Switch the worktree to an existing local branch. Git itself refuses (and + * surfaces a "would be overwritten by checkout" error) when uncommitted changes + * would conflict, so we let that message propagate to the caller rather than + * forcing — mobile shows it as a toast. Flag-injection is prevented by + * `assertValidBranchName` (rejects `-…`); the trailing `--` marks that no + * pathspecs follow, so the token is unambiguously treated as a branch ref. + */ +export async function checkoutBranch(worktreePath: string, branch: string): Promise { + assertValidBranchName(branch) + await gitExecFileAsync(['checkout', branch, '--'], { cwd: worktreePath }) +} + +/** + * List local branch short-names for the branch picker, current branch first. + * Uses `for-each-ref` (stable, scriptable output) instead of `branch` to avoid + * locale-dependent decoration. + */ +export async function listLocalBranches( + worktreePath: string +): Promise<{ current: string | null; branches: string[] }> { + const { stdout } = await gitExecFileAsync( + ['for-each-ref', '--format=%(HEAD)%09%(refname:short)', 'refs/heads/'], + { cwd: worktreePath } + ) + let current: string | null = null + const branches: string[] = [] + for (const line of stdout.split('\n')) { + if (line.length === 0) { + continue + } + const [marker, name] = line.split('\t') + if (!name) { + continue + } + if (marker === '*') { + current = name + } + branches.push(name) + } + // Why: surface the checked-out branch first so the picker reads "you are here" + // at the top, then the rest in git's ref order. + branches.sort((a, b) => { + if (a === current) { + return -1 + } + if (b === current) { + return 1 + } + return 0 + }) + return { current, branches } +} diff --git a/src/main/index.ts b/src/main/index.ts index fb3f4c791..aa86038de 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1335,7 +1335,10 @@ app.whenReady().then(async () => { onPtyStopped: clearProviderPtyState, onTerminalAgentStatus: (event) => { agentHookServer.ingestTerminalStatus(event) - } + }, + // Why: hook-reported agent status is the same source the desktop sidebar + // reads. worktree.ps pulls it at query time so mobile shows the same agents. + getAgentStatusSnapshot: () => agentHookServer.getStatusSnapshot() }) runtime = runtimeService automations = new AutomationService(store, { diff --git a/src/main/ipc/ui.ts b/src/main/ipc/ui.ts index 2f2624b34..d2746aa3e 100644 --- a/src/main/ipc/ui.ts +++ b/src/main/ipc/ui.ts @@ -1,9 +1,20 @@ -import { ipcMain } from 'electron' +import { BrowserWindow, ipcMain } from 'electron' import type { Store } from '../persistence' import type { PersistedUIState } from '../../shared/types' import { isFeatureInteractionId } from '../../shared/feature-interactions' export function registerUIHandlers(store: Store): void { + // Why: UI view-state is shared between the desktop renderer and mobile (ui.set + // RPC). Broadcast every change so the desktop re-hydrates when mobile (or + // another window) updates it — bi-directional sync, mirroring settings:changed. + store.onUIChanged((ui) => { + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed()) { + window.webContents.send('ui:stateChanged', ui) + } + } + }) + ipcMain.handle('ui:get', () => { return store.getUI() }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 7f28b6472..f925c202f 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2167,6 +2167,7 @@ export class Store { originWebContentsId?: number ) => void >() + private uiChangeListeners = new Set<(ui: PersistedState['ui']) => void>() constructor() { const loaded = this.load() @@ -4386,6 +4387,27 @@ export class Store { } } + // Why: UI view-state (group/sort/filters etc.) is written from both the + // desktop renderer and mobile (via the ui.set RPC) into one shared store. + // Without this, a mobile change persisted but the desktop renderer — which + // hydrates UI state once — never learned of it, breaking bi-directional sync. + onUIChanged(listener: (ui: PersistedState['ui']) => void): () => void { + this.uiChangeListeners.add(listener) + return () => { + this.uiChangeListeners.delete(listener) + } + } + + private notifyUIChanged(): void { + if (this.uiChangeListeners.size === 0) { + return + } + const ui = this.getUI() + for (const listener of this.uiChangeListeners) { + listener(ui) + } + } + updateSettings( updates: Partial, options: { notifyListeners?: boolean; originWebContentsId?: number } = {} @@ -4642,6 +4664,7 @@ export class Store { : normalizeFeatureInteractions(this.state.ui?.featureInteractions) } this.scheduleSave() + this.notifyUIChanged() } recordFeatureInteraction(id: FeatureInteractionId): PersistedState['ui'] { diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index 9abb43510..99386613d 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -363,6 +363,19 @@ export class SshGitProvider implements IGitProvider { await this.mux.request('git.abortRebase', { worktreePath }) } + async checkoutBranch(worktreePath: string, branch: string): Promise { + await this.mux.request('git.checkout', { worktreePath, branch }) + } + + async listLocalBranches( + worktreePath: string + ): Promise<{ current: string | null; branches: string[] }> { + return (await this.mux.request('git.localBranches', { worktreePath })) as { + current: string | null + branches: string[] + } + } + async getBranchCompare(worktreePath: string, baseRef: string): Promise { return (await this.mux.request('git.branchCompare', { worktreePath, diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 807bd7859..85c5017ad 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -182,6 +182,8 @@ export type IGitProvider = { detectConflictOperation(worktreePath: string): Promise abortMerge(worktreePath: string): Promise abortRebase(worktreePath: string): Promise + checkoutBranch(worktreePath: string, branch: string): Promise + listLocalBranches(worktreePath: string): Promise<{ current: string | null; branches: string[] }> getBranchCompare(worktreePath: string, baseRef: string): Promise getCommitCompare(worktreePath: string, commitId: string): Promise getUpstreamStatus(worktreePath: string, pushTarget?: GitPushTarget): Promise diff --git a/src/main/runtime/orca-runtime-browser.ts b/src/main/runtime/orca-runtime-browser.ts index b130eda02..8a93c9bee 100644 --- a/src/main/runtime/orca-runtime-browser.ts +++ b/src/main/runtime/orca-runtime-browser.ts @@ -1306,6 +1306,7 @@ export class RuntimeBrowserCommands { worktree?: string profileId?: string waitForRegistration?: boolean + activate?: boolean }): Promise<{ browserPageId: string }> { const url = params.url ?? 'about:blank' const worktreeId = params.worktree @@ -1320,7 +1321,8 @@ export class RuntimeBrowserCommands { const { browserPageId } = await this.createBrowserTabInRenderer( url, worktreeId, - params.profileId + params.profileId, + params.activate ) // Why: the renderer creates the Zustand tab immediately, but the webview must @@ -1700,7 +1702,8 @@ export class RuntimeBrowserCommands { private async createBrowserTabInRenderer( url: string, worktreeId?: string, - profileId?: string + profileId?: string, + activate?: boolean ): Promise<{ browserPageId: string }> { const win = this.host.getAuthoritativeWindow() const requestId = randomUUID() @@ -1731,7 +1734,8 @@ export class RuntimeBrowserCommands { requestId, url, worktreeId, - sessionProfileId: profileId + sessionProfileId: profileId, + activate }) }) diff --git a/src/main/runtime/orca-runtime-files.test.ts b/src/main/runtime/orca-runtime-files.test.ts index 885d289cc..4c290052a 100644 --- a/src/main/runtime/orca-runtime-files.test.ts +++ b/src/main/runtime/orca-runtime-files.test.ts @@ -411,4 +411,113 @@ describe('RuntimeFileCommands', () => { expect(child.listenerCount('error')).toBe(0) expect(child.listenerCount('close')).toBe(0) }) + + describe('resolveTerminalPath', () => { + function statAsFile() { + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + statMock.mockResolvedValue({ isDirectory: () => false }) + } + + it('resolves an absolute path inside the worktree to a relative path', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + statAsFile() + + const result = await commands.resolveTerminalPath('id:wt-1', '/repo/src/index.ts') + + expect(result).toEqual({ + worktree: 'wt-1', + relativePath: 'src/index.ts', + absolutePath: '/repo/src/index.ts', + exists: true, + isDirectory: false + }) + }) + + it('resolves a relative path against the provided cwd', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + statAsFile() + + const result = await commands.resolveTerminalPath('id:wt-1', 'index.ts', '/repo/src') + + expect(result).toMatchObject({ relativePath: 'src/index.ts', exists: true }) + }) + + it('resolves a relative path against the worktree root when no cwd is given', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + statAsFile() + + const result = await commands.resolveTerminalPath('id:wt-1', 'docs/readme.md') + + expect(result).toMatchObject({ relativePath: 'docs/readme.md', exists: true }) + }) + + it('reports a directory', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + statMock.mockResolvedValue({ isDirectory: () => true }) + + const result = await commands.resolveTerminalPath('id:wt-1', '/repo/src') + + expect(result).toMatchObject({ relativePath: 'src', isDirectory: true, exists: true }) + }) + + it('returns null relativePath for a path outside the worktree', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + + const result = await commands.resolveTerminalPath('id:wt-1', '/etc/passwd') + + expect(result).toEqual({ + worktree: 'wt-1', + relativePath: null, + absolutePath: null, + exists: false, + isDirectory: false + }) + expect(statMock).not.toHaveBeenCalled() + }) + + it('reports a nonexistent in-worktree path as not existing', async () => { + const { commands } = createRuntimeFileCommands({ path: '/repo' }) + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) + + const result = await commands.resolveTerminalPath('id:wt-1', 'src/missing.ts') + + expect(result).toMatchObject({ relativePath: 'src/missing.ts', exists: false }) + }) + + it('does not expand ~/ on a remote worktree (home is unknown)', async () => { + const { commands, store } = createRuntimeFileCommands({ path: '/repo' }) + store.getRepo.mockReturnValue({ connectionId: 'ssh-1' }) + const stat = vi.fn() + vi.mocked(getSshFilesystemProvider).mockReturnValue({ stat } as never) + + const result = await commands.resolveTerminalPath('id:wt-1', '~/notes.md') + + expect(result).toMatchObject({ relativePath: null, exists: false }) + expect(stat).not.toHaveBeenCalled() + }) + + it('reports a missing remote file as not existing', async () => { + const { commands, store } = createRuntimeFileCommands({ path: '/repo' }) + store.getRepo.mockReturnValue({ connectionId: 'ssh-1' }) + const stat = vi.fn().mockRejectedValue(new Error('ENOENT: no such file')) + vi.mocked(getSshFilesystemProvider).mockReturnValue({ stat } as never) + + const result = await commands.resolveTerminalPath('id:wt-1', 'src/missing.ts') + + expect(result).toMatchObject({ relativePath: 'src/missing.ts', exists: false }) + }) + + it('rethrows a remote transport error instead of reporting not-found', async () => { + const { commands, store } = createRuntimeFileCommands({ path: '/repo' }) + store.getRepo.mockReturnValue({ connectionId: 'ssh-1' }) + const stat = vi.fn().mockRejectedValue(new Error('Remote connection dropped')) + vi.mocked(getSshFilesystemProvider).mockReturnValue({ stat } as never) + + await expect(commands.resolveTerminalPath('id:wt-1', 'src/x.ts')).rejects.toThrow( + 'Remote connection dropped' + ) + }) + }) }) diff --git a/src/main/runtime/orca-runtime-files.ts b/src/main/runtime/orca-runtime-files.ts index 62deef6b6..1f755256e 100644 --- a/src/main/runtime/orca-runtime-files.ts +++ b/src/main/runtime/orca-runtime-files.ts @@ -14,6 +14,7 @@ import { stat, writeFile } from 'fs/promises' +import { homedir } from 'os' import { basename, dirname, extname, join } from 'path' import type { DirEntry, @@ -24,11 +25,17 @@ import type { SearchResult, Worktree } from '../../shared/types' +import { + isRuntimePathAbsolute, + relativePathInsideRoot, + resolveRuntimePath +} from '../../shared/cross-platform-path' import type { RuntimeFileListResult, RuntimeFileOpenResult, RuntimeFilePreviewResult, - RuntimeFileReadResult + RuntimeFileReadResult, + RuntimeTerminalPathResolution } from '../../shared/runtime-types' import { watchFileExplorerInWorker } from './file-watcher-host' import { wslAwareSpawn } from '../git/runner' @@ -243,6 +250,95 @@ export class RuntimeFileCommands { } } + // Resolves a path tapped in the mobile terminal (absolute, relative, or ~/…) + // to a worktree-relative path the file RPCs can open, plus existence. + // Relative paths resolve against `cwd` when the caller supplies it, else + // against the worktree root. NOTE: the mobile tap path does not yet forward a + // cwd, so a token relative to a subdirectory currently resolves against the + // root and may miss — absolute and root-relative paths always resolve. + // (Threading the terminal's tracked cwd is a follow-up.) + async resolveTerminalPath( + worktreeSelector: string, + pathText: string, + cwd?: string | null + ): Promise { + const store = this.host.requireStore() + const worktree = await this.host.resolveWorktreeSelector(worktreeSelector) + const repo = store.getRepo(worktree.repoId) + const connectionId = repo?.connectionId ?? undefined + const base = cwd && cwd.trim().length > 0 ? cwd : worktree.path + + const empty: RuntimeTerminalPathResolution = { + worktree: worktree.id, + relativePath: null, + absolutePath: null, + exists: false, + isDirectory: false + } + + // `~/…` is home-relative. The local home is known (os.homedir); the remote + // home is not, so don't guess — a tapped `~/…` on a remote worktree would + // mis-resolve under cwd/worktree-root, so treat it as not-openable instead. + const isTilde = pathText.startsWith('~/') || pathText.startsWith('~\\') + if (isTilde && connectionId) { + return empty + } + const expanded = isTilde ? resolveRuntimePath(homedir(), pathText.slice(2)) : pathText + const absolutePath = isRuntimePathAbsolute(expanded) + ? expanded + : resolveRuntimePath(base, expanded) + const relativePath = relativePathInsideRoot(worktree.path, absolutePath) + + // Outside the worktree, or not a safe relative path → not openable here. + if (relativePath === null || relativePath === '' || !isSafeMobileRelativePath(relativePath)) { + return empty + } + + try { + const stats = connectionId + ? await this.statRemoteTerminalPath(absolutePath, connectionId) + : await stat(await resolveAuthorizedPath(absolutePath, store)) + return { + worktree: worktree.id, + relativePath, + absolutePath, + exists: true, + isDirectory: stats.isDirectory() + } + } catch (error) { + // A genuine "not found" → the path simply doesn't exist (report it, not an + // error). Transport/permission/provider failures must surface so a remote + // session doesn't silently report every tapped path as missing. + if ( + isENOENT(error) || + (connectionId && RuntimeFileCommands.isRemoteNotFoundErrorMessage(error)) + ) { + return { ...empty, relativePath, absolutePath } + } + throw error + } + } + + // A remote stat failure that means "the file isn't there" vs a transport / + // permission / provider error. The mux drops the ErrnoException `code`, so the + // message is the only signal — match the not-found shapes the relay surfaces. + private static isRemoteNotFoundErrorMessage(error: unknown): boolean { + const message = error instanceof Error ? error.message : String(error) + return /\bENOENT\b|no such file|not found|does not exist/i.test(message) + } + + private async statRemoteTerminalPath( + absolutePath: string, + connectionId: string + ): Promise<{ isDirectory: () => boolean }> { + const provider = getSshFilesystemProvider(connectionId) + if (!provider) { + throw new Error(SSH_FILESYSTEM_PROVIDER_UNAVAILABLE_MESSAGE) + } + const stats = await provider.stat(absolutePath) + return { isDirectory: () => stats.type === 'directory' } + } + async readFileExplorerDir(worktreeSelector: string, relativePath: string): Promise { const target = await this.resolveFileExplorerPath(worktreeSelector, relativePath) const provider = target.connectionId ? getSshFilesystemProvider(target.connectionId) : null diff --git a/src/main/runtime/orca-runtime-git.test.ts b/src/main/runtime/orca-runtime-git.test.ts index 603372cee..f8f6a630d 100644 --- a/src/main/runtime/orca-runtime-git.test.ts +++ b/src/main/runtime/orca-runtime-git.test.ts @@ -11,6 +11,8 @@ import { RuntimeGitCommands, type ResolvedRuntimeGitWorktree } from './orca-runt const mocks = vi.hoisted(() => ({ abortMerge: vi.fn(), abortRebase: vi.fn(), + checkoutBranch: vi.fn(), + listLocalBranches: vi.fn(), getStagedCommitContext: vi.fn(), getPullRequestDraftContext: vi.fn(), generateCommitMessageFromContext: vi.fn(), @@ -26,6 +28,11 @@ vi.mock('../git/status', async () => ({ getStagedCommitContext: mocks.getStagedCommitContext })) +vi.mock('../git/checkout', () => ({ + checkoutBranch: mocks.checkoutBranch, + listLocalBranches: mocks.listLocalBranches +})) + vi.mock('../text-generation/commit-message-text-generation', async () => ({ ...(await vi.importActual( '../text-generation/commit-message-text-generation' @@ -80,6 +87,8 @@ describe('RuntimeGitCommands', () => { mocks.generatePullRequestFieldsFromContext.mockReset() mocks.resolveCommitMessageSettings.mockReset() mocks.getSshGitProvider.mockReset() + mocks.checkoutBranch.mockReset() + mocks.listLocalBranches.mockReset() }) afterEach(() => { @@ -144,6 +153,76 @@ describe('RuntimeGitCommands', () => { expect(mocks.abortRebase).not.toHaveBeenCalled() }) + it('checks out a local branch through the resolved worktree', async () => { + const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-')) + tempDirs.push(worktreePath) + const commands = makeCommands(worktreePath) + mocks.checkoutBranch.mockResolvedValue(undefined) + + await expect(commands.checkoutRuntimeGitBranch('id:wt-1', 'feature/x')).resolves.toEqual({ + ok: true, + branch: 'feature/x' + }) + + expect(mocks.checkoutBranch).toHaveBeenCalledWith(worktreePath, 'feature/x') + }) + + it('checks out a remote branch through the SSH git provider', async () => { + const provider = { checkoutBranch: vi.fn().mockResolvedValue(undefined) } + mocks.getSshGitProvider.mockReturnValue(provider) + const commands = new RuntimeGitCommands({ + resolveRuntimeGitTarget: async () => ({ + worktree: makeWorktree('/remote/repo'), + connectionId: 'conn-1' + }), + getRuntimeSettings: () => ({}) as GlobalSettings + }) + + await expect(commands.checkoutRuntimeGitBranch('id:wt-1', 'feature/x')).resolves.toEqual({ + ok: true, + branch: 'feature/x' + }) + + expect(provider.checkoutBranch).toHaveBeenCalledWith('/remote/repo', 'feature/x') + expect(mocks.checkoutBranch).not.toHaveBeenCalled() + }) + + it('lists local branches through the resolved worktree', async () => { + const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-')) + tempDirs.push(worktreePath) + const commands = makeCommands(worktreePath) + mocks.listLocalBranches.mockResolvedValue({ current: 'main', branches: ['main', 'feature/x'] }) + + await expect(commands.listRuntimeGitLocalBranches('id:wt-1')).resolves.toEqual({ + current: 'main', + branches: ['main', 'feature/x'] + }) + + expect(mocks.listLocalBranches).toHaveBeenCalledWith(worktreePath) + }) + + it('lists remote local branches through the SSH git provider', async () => { + const provider = { + listLocalBranches: vi.fn().mockResolvedValue({ current: 'main', branches: ['main'] }) + } + mocks.getSshGitProvider.mockReturnValue(provider) + const commands = new RuntimeGitCommands({ + resolveRuntimeGitTarget: async () => ({ + worktree: makeWorktree('/remote/repo'), + connectionId: 'conn-1' + }), + getRuntimeSettings: () => ({}) as GlobalSettings + }) + + await expect(commands.listRuntimeGitLocalBranches('id:wt-1')).resolves.toEqual({ + current: 'main', + branches: ['main'] + }) + + expect(provider.listLocalBranches).toHaveBeenCalledWith('/remote/repo') + expect(mocks.listLocalBranches).not.toHaveBeenCalled() + }) + it('rejects slash-only git mutation paths before they can target the worktree root', async () => { const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-')) tempDirs.push(worktreePath) diff --git a/src/main/runtime/orca-runtime-git.ts b/src/main/runtime/orca-runtime-git.ts index 08cb27d1c..52e65e6d1 100644 --- a/src/main/runtime/orca-runtime-git.ts +++ b/src/main/runtime/orca-runtime-git.ts @@ -43,6 +43,8 @@ import { stageFile, unstageFile } from '../git/status' +import { checkoutBranch, listLocalBranches } from '../git/checkout' +import type { RuntimeGitCheckoutResult, RuntimeGitLocalBranches } from '../../shared/runtime-types' import { getHistory as getGitHistory } from '../git/history' import { getUpstreamStatus } from '../git/upstream' import { gitFastForward, gitFetch, gitPull, gitPullRebaseFromBase, gitPush } from '../git/remote' @@ -213,6 +215,35 @@ export class RuntimeGitCommands { return { ok: true } } + async checkoutRuntimeGitBranch( + worktreeSelector: string, + branch: string + ): Promise { + const target = await this.host.resolveRuntimeGitTarget(worktreeSelector) + const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null + if (target.connectionId) { + if (!provider) { + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) + } + await provider.checkoutBranch(target.worktree.path, branch) + return { ok: true, branch } + } + await checkoutBranch(target.worktree.path, branch) + return { ok: true, branch } + } + + async listRuntimeGitLocalBranches(worktreeSelector: string): Promise { + const target = await this.host.resolveRuntimeGitTarget(worktreeSelector) + const provider = target.connectionId ? getSshGitProvider(target.connectionId) : null + if (target.connectionId) { + if (!provider) { + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) + } + return provider.listLocalBranches(target.worktree.path) + } + return listLocalBranches(target.worktree.path) + } + async getRuntimeGitDiff( worktreeSelector: string, filePath: string, diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 5e79c6caf..c6aabcf54 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -10926,13 +10926,19 @@ describe('OrcaRuntimeService', () => { displayName: 'foo', linkedIssue: 123, linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + comment: '', isPinned: false, + isActive: false, status: 'active', unread: false, liveTerminalCount: 1, hasAttachedPty: true, lastOutputAt: 321, - preview: 'build green' + preview: 'build green', + agents: [] } ], totalCount: 1, @@ -10940,6 +10946,124 @@ describe('OrcaRuntimeService', () => { }) }) + it('attaches inline agent rows from the latest OSC 9999 status', async () => { + const runtime = new OrcaRuntimeService(store) + const leafId = '22222222-2222-4222-8222-222222222222' + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: leafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId, + paneRuntimeId: 1, + ptyId: 'pty-1' + } + ] + }) + + runtime.onPtyData( + 'pty-1', + '\x1b]9999;{"state":"working","prompt":"ship it","agentType":"codex","lastAssistantMessage":"on it"}\x07', + 321 + ) + + const { worktrees } = await runtime.getWorktreePs() + const summary = worktrees.find((w) => w.worktreeId === TEST_WORKTREE_ID) + expect(summary?.agents).toEqual([ + expect.objectContaining({ + paneKey: `tab-1:${leafId}`, + parentPaneKey: null, + state: 'working', + agentType: 'codex', + prompt: 'ship it', + lastAssistantMessage: 'on it', + interrupted: false, + stateStartedAt: expect.any(Number), + updatedAt: expect.any(Number) + }) + ]) + }) + + it('attaches inline agent rows from hook-reported status (not just OSC)', async () => { + // Why: agent status normally arrives via hooks, not OSC terminal output; + // worktree.ps reads the hook snapshot so mobile surfaces those agents too. + const leafId = '33333333-3333-4333-8333-333333333333' + const paneKey = `tab-1:${leafId}` + const runtime = new OrcaRuntimeService(store, undefined, { + getAgentStatusSnapshot: () => [ + { + paneKey, + worktreeId: TEST_WORKTREE_ID, + tabId: 'tab-1', + state: 'working', + prompt: 'ship it', + agentType: 'claude', + lastAssistantMessage: 'on it', + connectionId: null, + receivedAt: 1000, + stateStartedAt: 900 + } + ] + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: leafId, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + leafId, + paneRuntimeId: 1, + ptyId: 'pty-1' + } + ] + }) + + const { worktrees } = await runtime.getWorktreePs() + const summary = worktrees.find((w) => w.worktreeId === TEST_WORKTREE_ID) + expect(summary?.agents).toEqual([ + expect.objectContaining({ + paneKey, + state: 'working', + agentType: 'claude', + prompt: 'ship it', + lastAssistantMessage: 'on it', + stateStartedAt: 900, + updatedAt: 1000 + }) + ]) + }) + + it('marks the desktop-active worktree as isActive', async () => { + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( + makeWorkspaceSessionWithHeadlessTerminal() + ) + const runtime = new OrcaRuntimeService(runtimeStore as never) + + const { worktrees } = await runtime.getWorktreePs() + const active = worktrees.filter((w) => w.isActive) + expect(active).toHaveLength(1) + expect(active[0]?.worktreeId).toBe(TEST_WORKTREE_ID) + }) + it('includes SSH-backed worktrees in the mobile worktree summary', async () => { const remoteRepo = { id: 'repo-ssh', diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 76040de9b..124093675 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -10,6 +10,7 @@ import { import type { AgentStatus } from '../../shared/agent-detection' import { AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusIpcPayload, type ParsedAgentStatusPayload, type AgentStatusOrchestrationContext, type AgentStatusEntry @@ -216,7 +217,10 @@ import type { RuntimeTerminalWaitBlockedReason, RuntimeTerminalWaitCondition, RuntimeWorktreePsSummary, + RuntimeWorktreeAgentRow, RuntimeWorktreeStatus, + RuntimeSpeechModelSummary, + RuntimeSpeechSetupState, RuntimeTerminalShow, RuntimeTerminalSummary, RuntimeSyncedLeaf, @@ -587,6 +591,7 @@ import type { ClaudeRateLimitAccountsState, CodexRateLimitAccountsState } from ' import type { RateLimitState } from '../../shared/rate-limit-types' import type { VoiceSettings } from '../../shared/speech-types' import { getSpeechModelManager, getSpeechSttService } from '../speech/speech-runtime-service' +import { getCatalogModel, isLocalSpeechModel, SPEECH_MODEL_CATALOG } from '../speech/model-catalog' import type { CommitMessageAgentEnvironmentResolvers } from '../text-generation/commit-message-agent-environment' import { scanNestedRepos } from '../project-groups/nested-repo-discovery' import { @@ -840,6 +845,21 @@ export type RuntimeTerminalAgentStatusEvent = { payload: ParsedAgentStatusPayload } +// Why: the full OSC 9999 payload flows through emitTerminalAgentStatusEvents and +// is then forwarded to the renderer and dropped. Mobile is served by the main +// process and has no renderer store, so we retain the latest payload per pane +// here to feed worktree.ps's inline agent rows (1:1 with the desktop sidebar). +type RuntimeAgentRowSnapshot = { + paneKey: string + ptyId: string + worktreeId?: string + tabId?: string + payload: ParsedAgentStatusPayload + // When the current payload.state was first observed for this pane (ms). + stateStartedAt: number + updatedAt: number +} + type RuntimeHeadlessTerminal = { emulator: HeadlessEmulator // Why: serialize can race with newer writes appended to writeChain; return @@ -1680,6 +1700,10 @@ export class OrcaRuntimeService { string, ReturnType >() + // Why: latest agent-status payload per pane, retained so worktree.ps can serve + // mobile the same inline agent rows the desktop sidebar renders. Cleared on pty + // teardown so dead agents don't linger. See RuntimeAgentRowSnapshot. + private latestAgentStatusByPaneKey = new Map() // Why: per-PTY hydration state guards against double-hydration. Keys: // 'pending' → maybeHydrateHeadlessFromRenderer is in flight // 'done' → hydration completed (success or skip); never run again @@ -1883,6 +1907,7 @@ export class OrcaRuntimeService { private readonly getLocalProviderFn: (() => IPtyProvider) | null private readonly onPtyStopped: ((ptyId: string) => void) | null private readonly onTerminalAgentStatus: ((event: RuntimeTerminalAgentStatusEvent) => void) | null + private readonly getAgentStatusSnapshotFn: (() => AgentStatusIpcPayload[]) | null private accountServices: RuntimeAccountServices | null = null private commitMessageAgentEnv: CommitMessageAgentEnvironmentResolvers | null = null private automationService: AutomationService | null = null @@ -1905,6 +1930,10 @@ export class OrcaRuntimeService { getLocalProvider?: () => IPtyProvider onPtyStopped?: (ptyId: string) => void onTerminalAgentStatus?: (event: RuntimeTerminalAgentStatusEvent) => void + // Why: agent status mostly arrives via hooks (agent-hooks/server), not OSC + // terminal output. worktree.ps reads this at query time so mobile shows the + // same inline agent rows the desktop sidebar does — same source, 1:1. + getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] } ) { this.store = store @@ -1912,6 +1941,7 @@ export class OrcaRuntimeService { this.stats = stats this.agentDetector = new AgentDetector(stats) } + this.getAgentStatusSnapshotFn = deps?.getAgentStatusSnapshot ?? null // Why: the daemon adapter is installed via `setLocalPtyProvider()` during // attachMainWindowServices, AFTER this service is constructed. Capturing // `getLocalPtyProvider()` at construction time would freeze a reference to @@ -3504,6 +3534,8 @@ export class OrcaRuntimeService { readMobileFile: RuntimeFileCommands['readMobileFile'] = this.fileCommands.readMobileFile.bind( this.fileCommands ) + resolveTerminalPath: RuntimeFileCommands['resolveTerminalPath'] = + this.fileCommands.resolveTerminalPath.bind(this.fileCommands) readFileExplorerDir: RuntimeFileCommands['readFileExplorerDir'] = this.fileCommands.readFileExplorerDir.bind(this.fileCommands) watchFileExplorer: RuntimeFileCommands['watchFileExplorer'] = @@ -3558,6 +3590,10 @@ export class OrcaRuntimeService { this.gitCommands.abortRuntimeGitMerge.bind(this.gitCommands) abortRuntimeGitRebase: RuntimeGitCommands['abortRuntimeGitRebase'] = this.gitCommands.abortRuntimeGitRebase.bind(this.gitCommands) + checkoutRuntimeGitBranch: RuntimeGitCommands['checkoutRuntimeGitBranch'] = + this.gitCommands.checkoutRuntimeGitBranch.bind(this.gitCommands) + listRuntimeGitLocalBranches: RuntimeGitCommands['listRuntimeGitLocalBranches'] = + this.gitCommands.listRuntimeGitLocalBranches.bind(this.gitCommands) getRuntimeGitDiff: RuntimeGitCommands['getRuntimeGitDiff'] = this.gitCommands.getRuntimeGitDiff.bind(this.gitCommands) getRuntimeGitBranchCompare: RuntimeGitCommands['getRuntimeGitBranchCompare'] = @@ -3853,7 +3889,10 @@ export class OrcaRuntimeService { } private emitTerminalAgentStatusEvents(ptyId: string, chunk: ProcessedAgentStatusChunk): void { - if (!this.onTerminalAgentStatus || chunk.payloads.length === 0) { + // Why: snapshot retention (for mobile worktree.ps) must run even when no + // renderer listener is attached, so we don't early-return on a missing + // onTerminalAgentStatus — only the per-target emit below is gated on it. + if (chunk.payloads.length === 0) { return } const targets = new Map< @@ -3889,6 +3928,10 @@ export class OrcaRuntimeService { } for (const payload of chunk.payloads) { for (const target of targets.values()) { + this.retainAgentRowSnapshot(ptyId, target.paneKey, target.worktreeId, target.tabId, payload) + if (!this.onTerminalAgentStatus) { + continue + } try { this.onTerminalAgentStatus({ ptyId, @@ -3908,6 +3951,39 @@ export class OrcaRuntimeService { } } + private retainAgentRowSnapshot( + ptyId: string, + paneKey: string, + worktreeId: string | undefined, + tabId: string | undefined, + payload: ParsedAgentStatusPayload + ): void { + const now = Date.now() + const previous = this.latestAgentStatusByPaneKey.get(paneKey) + // Why: stateStartedAt must mark the transition into the current state, not + // every within-state ping (tool/prompt updates keep the state but refresh + // updatedAt) — mirrors AgentStatusEntry.stateStartedAt on the desktop side. + const stateStartedAt = + previous && previous.payload.state === payload.state ? previous.stateStartedAt : now + this.latestAgentStatusByPaneKey.set(paneKey, { + paneKey, + ptyId, + worktreeId, + tabId, + payload, + stateStartedAt, + updatedAt: now + }) + } + + private clearAgentRowSnapshotsForPty(ptyId: string): void { + for (const [paneKey, snapshot] of this.latestAgentStatusByPaneKey) { + if (snapshot.ptyId === ptyId) { + this.latestAgentStatusByPaneKey.delete(paneKey) + } + } + } + getPtyOutputSequence(ptyId: string): number { return this.ptyOutputSequenceById.get(ptyId) ?? 0 } @@ -4450,6 +4526,84 @@ export class OrcaRuntimeService { return this.commitMessageAgentEnv ?? undefined } + // Lists the speech-model catalog joined with live download/ready state, plus + // the current enabled flag + selected model, so mobile can present a dictation + // setup sheet and drive remote enable/download. Always targets this (paired) + // desktop — speech never routes to a worktree's SSH host. + async listMobileSpeechModels(): Promise { + if (!this.store) { + throw new Error('voice_dictation_unavailable') + } + const voice = this.store.getSettings().voice ?? getDefaultVoiceSettings() + const states = await getSpeechModelManager(this.store).getModelStates() + const stateById = new Map(states.map((state) => [state.id, state])) + const models: RuntimeSpeechModelSummary[] = SPEECH_MODEL_CATALOG.map((manifest) => { + const state = stateById.get(manifest.id) + return { + id: manifest.id, + label: manifest.label, + provider: manifest.provider === 'openai' ? 'openai' : 'local', + sizeBytes: manifest.sizeBytes ?? null, + recommended: manifest.recommended === true, + status: state?.status ?? 'not-downloaded', + progress: state?.progress ?? null + } + }) + return { + enabled: voice.enabled === true, + selectedModelId: voice.sttModel ?? '', + dictationMode: voice.dictationMode === 'hold' ? 'hold' : 'toggle', + models + } + } + + // Fire-and-forget model download; the ModelManager writes progress into its + // per-model state, which mobile reads back via listMobileSpeechModels polling. + async downloadMobileSpeechModel(modelId: string): Promise<{ started: true }> { + if (!this.store) { + throw new Error('voice_dictation_unavailable') + } + const manifest = getCatalogModel(modelId) + if (!manifest || !isLocalSpeechModel(manifest)) { + throw new Error('voice_model_not_downloadable') + } + // Why: do not await — downloads run for tens of seconds; the call returns + // immediately and mobile polls for progress/ready. + void getSpeechModelManager(this.store) + .downloadModel(modelId) + .catch((err) => { + console.error('[runtime] mobile speech model download failed', { modelId, err }) + }) + return { started: true } + } + + // Enables/disables dictation and/or selects the model, merging into the + // existing voice settings so other voice fields are preserved. + async configureMobileDictation(params: { + enabled?: boolean + modelId?: string + dictationMode?: 'toggle' | 'hold' + }): Promise { + if (!this.store?.getSettings || !this.store.updateSettings) { + throw new Error('voice_dictation_unavailable') + } + const current = this.store.getSettings().voice ?? getDefaultVoiceSettings() + // An explicit '' clears the selected model (the OptionalString RPC schema + // maps '' → undefined, so this only matters for direct callers); any other + // non-empty modelId must be a known catalog entry. + if (params.modelId !== undefined && params.modelId !== '' && !getCatalogModel(params.modelId)) { + throw new Error('voice_model_unknown') + } + const nextVoice: VoiceSettings = { + ...current, + ...(params.enabled !== undefined ? { enabled: params.enabled } : {}), + ...(params.modelId !== undefined ? { sttModel: params.modelId } : {}), + ...(params.dictationMode !== undefined ? { dictationMode: params.dictationMode } : {}) + } + this.store.updateSettings({ voice: nextVoice }, { notifyListeners: true }) + return this.listMobileSpeechModels() + } + async startMobileDictation(params: { dictationId: string modelId?: string @@ -5034,6 +5188,7 @@ export class OrcaRuntimeService { this.recentPtyOutputById.delete(ptyId) this.ptyOutputSequenceById.delete(ptyId) this.agentStatusOscProcessorsByPtyId.delete(ptyId) + this.clearAgentRowSnapshotsForPty(ptyId) // Layout state machine: clear `layouts` and `layoutQueues`. Any // already-queued applyLayout work for this ptyId will run, but every // applyLayout re-checks `layouts.has(ptyId)` (or fresh-subscribe) and @@ -6730,13 +6885,19 @@ export class OrcaRuntimeService { displayName: worktree.displayName, linkedIssue: worktree.linkedIssue, linkedPR, + linkedLinearIssue: meta?.linkedLinearIssue ?? null, + linkedGitLabMR: meta?.linkedGitLabMR ?? null, + linkedGitLabIssue: meta?.linkedGitLabIssue ?? null, + comment: meta?.comment ?? '', isPinned: meta?.isPinned ?? false, + isActive: false, unread: meta?.isUnread ?? false, liveTerminalCount: 0, hasAttachedPty: false, lastOutputAt: null, preview: '', - status: 'inactive' + status: 'inactive', + agents: [] }) } @@ -6816,6 +6977,22 @@ export class OrcaRuntimeService { } } + // Why: surface the desktop's focused worktree so mobile can scroll it into + // view and highlight it. Resolve through getSummaryForRuntimeWorktreeId so + // SSH/remote path-projected ids match the same way tabsByWorktree does. + if (session?.activeWorktreeId) { + const activeSummary = this.getSummaryForRuntimeWorktreeId( + summaries, + resolvedWorktrees, + session.activeWorktreeId + ) + if (activeSummary) { + activeSummary.isActive = true + } + } + + this.attachAgentRowsToSummaries(summaries) + const sorted = [...summaries.values()].sort(compareWorktreePs) return { worktrees: sorted.slice(0, limit), @@ -6824,6 +7001,101 @@ export class OrcaRuntimeService { } } + // Why: maps the retained per-pane agent snapshots into each worktree's inline + // agent list, mirroring the desktop sidebar. Lineage parent is resolved from + // the orchestration db (paneKey-keyed), not the OSC payload, since spawn + // hierarchy is pane-level state tracked separately from terminal output. + private attachAgentRowsToSummaries(summaries: Map): void { + // Why: most agents report via hooks (agent-hooks/server), not OSC, so the + // hook snapshot is the primary source — same one the desktop sidebar reads. + // OSC-only entries (no hook) are merged in as a fallback, keyed by paneKey. + const rowSources = new Map< + string, + { + paneKey: string + worktreeId?: string + state: ParsedAgentStatusPayload['state'] + agentType: string | null + prompt: string + lastAssistantMessage: string | null + toolName: string | null + toolInput: string | null + interrupted: boolean + stateStartedAt: number + updatedAt: number + } + >() + for (const snapshot of this.latestAgentStatusByPaneKey.values()) { + const { payload } = snapshot + rowSources.set(snapshot.paneKey, { + paneKey: snapshot.paneKey, + worktreeId: snapshot.worktreeId, + state: payload.state, + agentType: payload.agentType ?? null, + prompt: payload.prompt, + lastAssistantMessage: payload.lastAssistantMessage ?? null, + toolName: payload.toolName ?? null, + toolInput: payload.toolInput ?? null, + interrupted: payload.interrupted ?? false, + stateStartedAt: snapshot.stateStartedAt, + updatedAt: snapshot.updatedAt + }) + } + for (const entry of this.getAgentStatusSnapshotFn?.() ?? []) { + rowSources.set(entry.paneKey, { + paneKey: entry.paneKey, + worktreeId: entry.worktreeId, + state: entry.state, + agentType: entry.agentType ?? null, + prompt: entry.prompt, + lastAssistantMessage: entry.lastAssistantMessage ?? null, + toolName: entry.toolName ?? null, + toolInput: entry.toolInput ?? null, + interrupted: entry.interrupted ?? false, + stateStartedAt: entry.stateStartedAt, + updatedAt: entry.receivedAt + }) + } + if (rowSources.size === 0) { + return + } + const orchestrationByPaneKey = this.buildAgentOrchestrationByPaneKey() + const rowsByWorktree = new Map() + for (const src of rowSources.values()) { + const worktreeId = src.worktreeId + if (!worktreeId || !summaries.has(worktreeId)) { + continue + } + const row: RuntimeWorktreeAgentRow = { + paneKey: src.paneKey, + parentPaneKey: orchestrationByPaneKey?.[src.paneKey]?.parentPaneKey ?? null, + state: src.state, + agentType: src.agentType, + prompt: src.prompt, + lastAssistantMessage: src.lastAssistantMessage, + toolName: src.toolName, + toolInput: src.toolInput, + interrupted: src.interrupted, + stateStartedAt: src.stateStartedAt, + updatedAt: src.updatedAt + } + const rows = rowsByWorktree.get(worktreeId) + if (rows) { + rows.push(row) + } else { + rowsByWorktree.set(worktreeId, [row]) + } + } + for (const [worktreeId, rows] of rowsByWorktree) { + // Oldest-started first, matching the desktop dashboard's start-order sort. + rows.sort((a, b) => a.stateStartedAt - b.stateStartedAt) + const summary = summaries.get(worktreeId) + if (summary) { + summary.agents = rows + } + } + } + listRepos(): Repo[] { return this.store?.getRepos() ?? [] } @@ -13822,6 +14094,7 @@ export class OrcaRuntimeService { this.recentPtyOutputById.delete(ptyId) this.ptyOutputSequenceById.delete(ptyId) this.agentStatusOscProcessorsByPtyId.delete(ptyId) + this.clearAgentRowSnapshotsForPty(ptyId) const handle = this.handleByPtyId.get(ptyId) if (handle) { this.handleByPtyId.delete(ptyId) diff --git a/src/main/runtime/rpc/methods/browser-schemas.ts b/src/main/runtime/rpc/methods/browser-schemas.ts index a49376930..50b854efe 100644 --- a/src/main/runtime/rpc/methods/browser-schemas.ts +++ b/src/main/runtime/rpc/methods/browser-schemas.ts @@ -118,7 +118,9 @@ export const TabCreate = z.object({ url: OptionalString, worktree: OptionalString, profileId: OptionalString, - waitForRegistration: z.boolean().optional() + waitForRegistration: z.boolean().optional(), + // User-initiated opens focus the tab; agent/automation opens stay background. + activate: z.boolean().optional() }) export const TabShow = z.object({ @@ -153,9 +155,7 @@ export const ProfileCreate = z.object({ scope: z.enum(['isolated', 'imported']) }) -export const ProfileDelete = z.object({ - profileId: requiredString('Missing required --profile') -}) +export const ProfileDelete = z.object({ profileId: requiredString('Missing required --profile') }) export const ProfileImportFromBrowser = z.object({ profileId: requiredString('Missing required --profile'), diff --git a/src/main/runtime/rpc/methods/files.test.ts b/src/main/runtime/rpc/methods/files.test.ts index 7843ba4bb..e1195b7f1 100644 --- a/src/main/runtime/rpc/methods/files.test.ts +++ b/src/main/runtime/rpc/methods/files.test.ts @@ -284,6 +284,37 @@ describe('file RPC methods', () => { }) }) + it('resolves a tapped terminal path for a selected worktree', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + resolveTerminalPath: vi.fn().mockResolvedValue({ + worktree: 'wt-1', + relativePath: 'src/index.ts', + exists: true, + isDirectory: false + }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('files.resolveTerminalPath', { + worktree: 'id:wt-1', + pathText: '/repo/src/index.ts', + cwd: '/repo' + }) + ) + + expect(runtime.resolveTerminalPath).toHaveBeenCalledWith( + 'id:wt-1', + '/repo/src/index.ts', + '/repo' + ) + expect(response).toMatchObject({ + ok: true, + result: { relativePath: 'src/index.ts', exists: true, isDirectory: false } + }) + }) + it('reads a preview file for a selected worktree', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/files.ts b/src/main/runtime/rpc/methods/files.ts index 1060081ba..185f85eec 100644 --- a/src/main/runtime/rpc/methods/files.ts +++ b/src/main/runtime/rpc/methods/files.ts @@ -26,6 +26,18 @@ const FileOpen = WorktreeSelector.extend({ .pipe(z.string().min(1, 'Missing relative path')) }) +const ResolveTerminalPath = WorktreeSelector.extend({ + pathText: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing path text')), + cwd: z + .unknown() + .transform((v) => (typeof v === 'string' && v.length > 0 ? v : null)) + .nullable() + .optional() +}) + const FileOpenDiff = FileOpen.extend({ staged: z.boolean().optional() }) @@ -151,6 +163,12 @@ export const FILE_METHODS: RpcAnyMethod[] = [ handler: async (params, { runtime }) => runtime.readMobileFile(params.worktree, params.relativePath) }), + defineMethod({ + name: 'files.resolveTerminalPath', + params: ResolveTerminalPath, + handler: async (params, { runtime }) => + runtime.resolveTerminalPath(params.worktree, params.pathText, params.cwd ?? null) + }), defineMethod({ name: 'files.readPreview', params: FileOpen, diff --git a/src/main/runtime/rpc/methods/git-params.ts b/src/main/runtime/rpc/methods/git-params.ts index c22be6ef3..e668670b3 100644 --- a/src/main/runtime/rpc/methods/git-params.ts +++ b/src/main/runtime/rpc/methods/git-params.ts @@ -215,6 +215,19 @@ export const GitRebaseFromBase = WorktreeSelector.extend({ ) }) +export const GitCheckout = WorktreeSelector.extend({ + branch: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe( + z + .string() + .min(1, 'Missing branch') + // Why: never let a branch arg be parsed as a git flag (arg injection). + .refine((value) => !value.startsWith('-'), 'Branch must not start with -') + ) +}) + export const GitRemoteFileUrl = WorktreeSelector.extend({ relativePath: z .unknown() diff --git a/src/main/runtime/rpc/methods/git.test.ts b/src/main/runtime/rpc/methods/git.test.ts index 1ec05bb79..227f6394c 100644 --- a/src/main/runtime/rpc/methods/git.test.ts +++ b/src/main/runtime/rpc/methods/git.test.ts @@ -604,4 +604,54 @@ describe('git RPC methods', () => { expect(response.ok).toBe(false) expect(runtime.getRuntimeGitHistory).not.toHaveBeenCalled() }) + + it('checks out a branch', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + checkoutRuntimeGitBranch: vi.fn().mockResolvedValue({ ok: true, branch: 'feature/x' }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: GIT_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('git.checkout', { worktree: 'id:wt-1', branch: 'feature/x' }) + ) + + expect(runtime.checkoutRuntimeGitBranch).toHaveBeenCalledWith('id:wt-1', 'feature/x') + expect(response).toMatchObject({ ok: true, result: { ok: true, branch: 'feature/x' } }) + }) + + it('rejects a checkout branch that starts with a dash', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + checkoutRuntimeGitBranch: vi.fn() + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: GIT_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('git.checkout', { worktree: 'id:wt-1', branch: '--force' }) + ) + + expect(response.ok).toBe(false) + expect(runtime.checkoutRuntimeGitBranch).not.toHaveBeenCalled() + }) + + it('lists local branches', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + listRuntimeGitLocalBranches: vi + .fn() + .mockResolvedValue({ current: 'main', branches: ['main', 'feature/x'] }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: GIT_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('git.localBranches', { worktree: 'id:wt-1' }) + ) + + expect(runtime.listRuntimeGitLocalBranches).toHaveBeenCalledWith('id:wt-1') + expect(response).toMatchObject({ + ok: true, + result: { current: 'main', branches: ['main', 'feature/x'] } + }) + }) }) diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index 7b6039217..eef0ed2f6 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -7,6 +7,7 @@ import { GitBranchDiff, GitBulkPaths, GitCheckIgnored, + GitCheckout, GitCommit, GitCommitCompare, GitCommitDiff, @@ -121,6 +122,17 @@ export const GIT_METHODS: RpcMethod[] = [ params: WorktreeSelector, handler: async (params, { runtime }) => runtime.abortRuntimeGitRebase(params.worktree) }), + defineMethod({ + name: 'git.checkout', + params: GitCheckout, + handler: async (params, { runtime }) => + runtime.checkoutRuntimeGitBranch(params.worktree, params.branch) + }), + defineMethod({ + name: 'git.localBranches', + params: WorktreeSelector, + handler: async (params, { runtime }) => runtime.listRuntimeGitLocalBranches(params.worktree) + }), defineMethod({ name: 'git.diff', params: GitDiff, diff --git a/src/main/runtime/rpc/methods/speech.test.ts b/src/main/runtime/rpc/methods/speech.test.ts index 4f31ee386..7218836c2 100644 --- a/src/main/runtime/rpc/methods/speech.test.ts +++ b/src/main/runtime/rpc/methods/speech.test.ts @@ -71,4 +71,51 @@ describe('speech RPC methods', () => { expect(response).toMatchObject({ ok: false }) expect(runtime.feedMobileDictation).not.toHaveBeenCalled() }) + + it('lists speech models', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + listMobileSpeechModels: vi + .fn() + .mockResolvedValue({ enabled: false, selectedModelId: '', models: [] }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SPEECH_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('speech.models.list', null)) + + expect(runtime.listMobileSpeechModels).toHaveBeenCalled() + expect(response).toMatchObject({ ok: true, result: { enabled: false, models: [] } }) + }) + + it('starts a model download', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + downloadMobileSpeechModel: vi.fn().mockResolvedValue({ started: true }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SPEECH_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('speech.models.download', { modelId: 'parakeet-tdt-0.6b-v3-int8' }) + ) + + expect(runtime.downloadMobileSpeechModel).toHaveBeenCalledWith('parakeet-tdt-0.6b-v3-int8') + expect(response).toMatchObject({ ok: true, result: { started: true } }) + }) + + it('configures dictation enable + model selection', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + configureMobileDictation: vi + .fn() + .mockResolvedValue({ enabled: true, selectedModelId: 'm1', models: [] }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: SPEECH_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('speech.dictation.setup', { enabled: true, modelId: 'm1' }) + ) + + expect(runtime.configureMobileDictation).toHaveBeenCalledWith({ enabled: true, modelId: 'm1' }) + expect(response).toMatchObject({ ok: true, result: { enabled: true, selectedModelId: 'm1' } }) + }) }) diff --git a/src/main/runtime/rpc/methods/speech.ts b/src/main/runtime/rpc/methods/speech.ts index 8e1ceafd5..fcbcd5bb0 100644 --- a/src/main/runtime/rpc/methods/speech.ts +++ b/src/main/runtime/rpc/methods/speech.ts @@ -38,7 +38,37 @@ const DictationHandle = z.object({ dictationId: requiredString('Missing dictation ID') }) +const SpeechModelDownload = z.object({ + modelId: requiredString('Missing model ID') +}) + +const DictationSetup = z.object({ + enabled: z.boolean().optional(), + modelId: OptionalString, + dictationMode: z.enum(['toggle', 'hold']).optional() +}) + export const SPEECH_METHODS: RpcMethod[] = [ + defineMethod({ + name: 'speech.models.list', + params: null, + handler: async (_params, { runtime }) => runtime.listMobileSpeechModels() + }), + defineMethod({ + name: 'speech.models.download', + params: SpeechModelDownload, + handler: async (params, { runtime }) => runtime.downloadMobileSpeechModel(params.modelId) + }), + defineMethod({ + name: 'speech.dictation.setup', + params: DictationSetup, + handler: async (params, { runtime }) => + runtime.configureMobileDictation({ + ...(params.enabled !== undefined ? { enabled: params.enabled } : {}), + ...(params.modelId !== undefined ? { modelId: params.modelId } : {}), + ...(params.dictationMode !== undefined ? { dictationMode: params.dictationMode } : {}) + }) + }), defineMethod({ name: 'speech.dictation.start', params: DictationStart, diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index b316ccb3e..61f905a7e 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -980,7 +980,9 @@ describe('OrcaRuntimeRpcServer', () => { await server['handleWebSocketMessage']( JSON.stringify({ id: 'req_forbidden', - method: 'git.generateCommitMessage', + // files.delete is a real registered RPC intentionally kept off the + // mobile allowlist — mobile clients must never delete host files. + method: 'files.delete', deviceToken: mobile.token, params: { worktree: 'id:wt-1' } }), diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 8c8fe8c51..361dfa1d9 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -152,18 +152,30 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'files.open', 'files.openDiff', 'files.read', + 'files.readPreview', + 'files.resolveTerminalPath', 'git.abortMerge', 'git.abortRebase', 'git.bulkStage', 'git.bulkUnstage', 'git.branchCompare', 'git.branchDiff', + 'git.cancelGenerateCommitMessage', + 'git.cancelGeneratePullRequestFields', + 'git.checkout', 'git.commit', + 'git.commitCompare', + 'git.commitDiff', 'git.discard', + 'git.discoverCommitMessageModels', 'git.diff', 'git.fetch', 'git.forkSync', 'git.fastForward', + 'git.generateCommitMessage', + 'git.generatePullRequestFields', + 'git.history', + 'git.localBranches', 'git.pull', 'git.push', 'git.rebaseFromBase', @@ -226,6 +238,8 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'host.pwsh.isAvailable', 'host.wsl.isAvailable', 'host.wsl.listDistros', + 'hostedReview.create', + 'hostedReview.getCreationEligibility', 'linear.getCustomView', 'linear.getIssue', 'linear.getProject', @@ -285,7 +299,10 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'speech.dictation.cancel', 'speech.dictation.chunk', 'speech.dictation.finish', + 'speech.dictation.setup', 'speech.dictation.start', + 'speech.models.download', + 'speech.models.list', 'stats.summary', 'status.get', 'agentTeams.prepareLaunch', diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 2eef2edb4..3f0dbbbb0 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -2272,6 +2272,7 @@ export type PreloadApi = { get: () => Promise set: (args: Partial) => Promise recordFeatureInteraction: (id: FeatureInteractionId) => Promise + onStateChanged: (callback: (ui: PersistedUIState) => void) => () => void onOpenSettings: (callback: () => void) => () => void onOpenSetupGuide: (callback: () => void) => () => void onOpenFeatureTour: (callback: () => void) => () => void @@ -2299,6 +2300,7 @@ export type PreloadApi = { url: string worktreeId?: string sessionProfileId?: string + activate?: boolean }) => void ) => () => void replyTabCreate: (reply: { requestId: string; browserPageId?: string; error?: string }) => void diff --git a/src/preload/index.ts b/src/preload/index.ts index c6d7bb64e..ba03435ee 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -38,6 +38,7 @@ import type { NotificationSoundResult, NestedRepoScanResult, OnboardingState, + PersistedUIState, FloatingTerminalCwdRequest, MarkdownDocument, SearchResult, @@ -2665,6 +2666,12 @@ const api = { get: () => ipcRenderer.invoke('ui:get'), set: (args) => ipcRenderer.invoke('ui:set', args), recordFeatureInteraction: (id) => ipcRenderer.invoke('ui:recordFeatureInteraction', id), + onStateChanged: (callback: (ui: PersistedUIState) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, ui: PersistedUIState): void => + callback(ui) + ipcRenderer.on('ui:stateChanged', listener) + return () => ipcRenderer.removeListener('ui:stateChanged', listener) + }, onOpenSettings: (callback: () => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent) => callback() ipcRenderer.on('ui:openSettings', listener) @@ -2774,11 +2781,18 @@ const api = { url: string worktreeId?: string sessionProfileId?: string + activate?: boolean }) => void ): (() => void) => { const listener = ( _event: Electron.IpcRendererEvent, - data: { requestId: string; url: string; worktreeId?: string; sessionProfileId?: string } + data: { + requestId: string + url: string + worktreeId?: string + sessionProfileId?: string + activate?: boolean + } ) => callback(data) ipcRenderer.on('browser:requestTabCreate', listener) return () => ipcRenderer.removeListener('browser:requestTabCreate', listener) diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index 06778e770..6141ddfcb 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -71,6 +71,8 @@ describe('GitHandler', () => { expect(methods).toContain('git.bulkUnstage') expect(methods).toContain('git.abortMerge') expect(methods).toContain('git.abortRebase') + expect(methods).toContain('git.checkout') + expect(methods).toContain('git.localBranches') expect(methods).toContain('git.discard') expect(methods).toContain('git.bulkDiscard') expect(methods).toContain('git.conflictOperation') @@ -155,6 +157,43 @@ describe('GitHandler', () => { }) }) + describe('checkout / localBranches', () => { + it('switches to an existing local branch and lists branches current-first', async () => { + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'file.txt'), 'base\n') + gitCommit(tmpDir, 'initial') + const baseBranch = execFileSync('git', ['branch', '--show-current'], { + cwd: tmpDir, + encoding: 'utf-8', + stdio: 'pipe' + }).trim() + execFileSync('git', ['branch', 'feature'], { cwd: tmpDir, stdio: 'pipe' }) + + const before = (await dispatcher.callRequest('git.localBranches', { + worktreePath: tmpDir + })) as { current: string | null; branches: string[] } + expect(before.current).toBe(baseBranch) + expect(before.branches).toContain('feature') + expect(before.branches[0]).toBe(baseBranch) + + await dispatcher.callRequest('git.checkout', { worktreePath: tmpDir, branch: 'feature' }) + + expect( + execFileSync('git', ['branch', '--show-current'], { + cwd: tmpDir, + encoding: 'utf-8', + stdio: 'pipe' + }).trim() + ).toBe('feature') + + const after = (await dispatcher.callRequest('git.localBranches', { + worktreePath: tmpDir + })) as { current: string | null; branches: string[] } + expect(after.current).toBe('feature') + expect(after.branches[0]).toBe('feature') + }) + }) + describe('renameCurrentBranch', () => { it('renames only the checked-out branch through the narrow RPC', async () => { gitInit(tmpDir) diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 9fb28d839..d624f2c61 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -73,6 +73,8 @@ export class GitHandler { this.dispatcher.onRequest('git.bulkUnstage', (p) => this.bulkUnstage(p)) this.dispatcher.onRequest('git.abortMerge', (p) => this.abortMerge(p)) this.dispatcher.onRequest('git.abortRebase', (p) => this.abortRebase(p)) + this.dispatcher.onRequest('git.checkout', (p) => this.checkout(p)) + this.dispatcher.onRequest('git.localBranches', (p) => this.localBranches(p)) this.dispatcher.onRequest('git.discard', (p) => this.discard(p)) this.dispatcher.onRequest('git.bulkDiscard', (p) => this.bulkDiscard(p)) this.dispatcher.onRequest('git.conflictOperation', (p) => this.conflictOperation(p)) @@ -223,6 +225,45 @@ export class GitHandler { await this.git(['rebase', '--abort'], worktreePath) } + private async checkout(params: Record) { + const worktreePath = params.worktreePath as string + const branch = params.branch as string + // Defense-in-depth: reject option-like branch tokens (the RPC schema also + // validates, but this relay entrypoint is reachable independently). The + // `startsWith('-')` guard is what prevents flag injection; the trailing `--` + // marks that no pathspecs follow so the token is treated as a branch ref. + if (typeof branch !== 'string' || branch.length === 0 || branch.startsWith('-')) { + throw new Error('invalid_branch_name') + } + await this.git(['checkout', branch, '--'], worktreePath) + return { ok: true as const, branch } + } + + private async localBranches(params: Record) { + const worktreePath = params.worktreePath as string + const { stdout } = await this.git( + ['for-each-ref', '--format=%(HEAD)%09%(refname:short)', 'refs/heads/'], + worktreePath + ) + let current: string | null = null + const branches: string[] = [] + for (const line of stdout.split('\n')) { + if (line.length === 0) { + continue + } + const [marker, name] = line.split('\t') + if (!name) { + continue + } + if (marker === '*') { + current = name + } + branches.push(name) + } + branches.sort((a, b) => (a === current ? -1 : b === current ? 1 : 0)) + return { current, branches } + } + private normalizeGitPathForCompare(filePath: string): string { return filePath.replace(/\\/g, '/').replace(/\/+$/, '') } diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index 08d4de7a1..1b2ee8722 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -538,6 +538,7 @@ describe('useIpcEvents browser tab create routing', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -756,6 +757,7 @@ describe('useIpcEvents updater integration', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -993,6 +995,7 @@ describe('useIpcEvents updater integration', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -1383,6 +1386,7 @@ describe('useIpcEvents updater integration', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -1913,6 +1917,7 @@ describe('useIpcEvents browser tab close routing', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -2127,6 +2132,7 @@ describe('useIpcEvents browser tab close routing', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -2336,6 +2342,7 @@ describe('useIpcEvents browser tab close routing', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -2563,6 +2570,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -2816,6 +2824,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { }, runtimeEnvironments: { subscribe: runtimeSubscribe }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, @@ -3042,6 +3051,7 @@ describe('useIpcEvents agent status snapshot integration', () => { onRemoteBranchConflict: () => () => {} }, ui: { + onStateChanged: () => () => {}, onOpenSettings: () => () => {}, onOpenFeatureTour: () => () => {}, onToggleLeftSidebar: () => () => {}, diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index 939e5730f..fa9fd1061 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -1062,6 +1062,15 @@ export function useIpcEvents(): void { }) ) + // Why: UI view-state (group/sort/filters, collapsed groups, etc.) is shared + // with mobile via the ui.set RPC. When mobile changes it, main broadcasts so + // the desktop re-hydrates and the sidebar reflects it live — bi-directional. + unsubs.push( + window.api.ui.onStateChanged((ui) => { + useAppStore.getState().hydratePersistedUI(ui) + }) + ) + if (window.api.keybindings) { unsubs.push( window.api.keybindings.onChanged((snapshot) => { @@ -1955,11 +1964,15 @@ export function useIpcEvents(): void { ) : undefined + // Why: a user-initiated open (data.activate, e.g. mobile tapping an HTML + // path) foregrounds the tab so it lands in the active group's order and + // publishes to mobile in the right place. Agent/automation opens stay in + // the background (activate:false) in the active browser group. const workspace = store.createBrowserTab(worktreeId, data.url, { title: data.url, - targetGroupId: activeBrowserUnifiedTab?.groupId, + targetGroupId: data.activate ? undefined : activeBrowserUnifiedTab?.groupId, sessionProfileId: data.sessionProfileId, - activate: false + activate: data.activate === true }) // Why: registerGuest fires with the page ID (not workspace ID) as // browserPageId. Return the page ID so waitForTabRegistration can diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 39306a9c5..9742da1da 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1977,6 +1977,9 @@ function createWebUiApi(): NonNullable['ui']> { onOpenSetupGuide: () => noopUnsubscribe, onOpenFeatureTour: () => noopUnsubscribe, onOpenCrashReport: () => noopUnsubscribe, + // No desktop main process to push state changes; the web client re-reads + // via ui.get on interaction instead. + onStateChanged: () => noopUnsubscribe, onToggleLeftSidebar: () => noopUnsubscribe, onToggleRightSidebar: () => noopUnsubscribe, onToggleWorktreePalette: () => noopUnsubscribe, diff --git a/src/shared/remote-runtime-client-error.ts b/src/shared/remote-runtime-client-error.ts new file mode 100644 index 000000000..b6429620c --- /dev/null +++ b/src/shared/remote-runtime-client-error.ts @@ -0,0 +1,16 @@ +/** + * Error type for the remote-runtime client, split out from + * `remote-runtime-client.ts` so type-only consumers can reference it without + * pulling in that module's `ws`/`tweetnacl` value imports. Mobile reaches this + * type transitively (runtime-types → shared-control-types) and its typecheck + * has no Node-only deps installed. + */ +export class RemoteRuntimeClientError extends Error { + readonly code: string + + constructor(code: string, message: string) { + super(message) + this.name = 'RemoteRuntimeClientError' + this.code = code + } +} diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 3eeb1a34b..aab868a92 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -20,19 +20,15 @@ import { RuntimeRpcEnvelopeSchema, type RuntimeRpcResponse } from './runtime-rpc-envelope' +// Re-export so existing value importers of `RemoteRuntimeClientError` are +// unaffected; the class lives in a ws-free module so type-only consumers +// (and mobile's typecheck) don't compile this file's Node-only deps. +import { RemoteRuntimeClientError } from './remote-runtime-client-error' + +export { RemoteRuntimeClientError } from './remote-runtime-client-error' type HandshakeState = 'awaiting_ready' | 'awaiting_authenticated' | 'ready' -export class RemoteRuntimeClientError extends Error { - readonly code: string - - constructor(code: string, message: string) { - super(message) - this.name = 'RemoteRuntimeClientError' - this.code = code - } -} - function ignoreSettledRemoteRuntimeSocketError(): void {} function formatRemoteRuntimeCloseMessage(code: number, reason: Buffer): string { diff --git a/src/shared/remote-runtime-shared-control-connection.ts b/src/shared/remote-runtime-shared-control-connection.ts index 35074ac74..2ea957e9f 100644 --- a/src/shared/remote-runtime-shared-control-connection.ts +++ b/src/shared/remote-runtime-shared-control-connection.ts @@ -1,7 +1,7 @@ import WebSocket from 'ws' import type { PairingOffer } from './pairing' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' -import type { RemoteRuntimeClientError } from './remote-runtime-client' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import { openSharedControlSocket } from './remote-runtime-shared-control-open' import { handleSharedControlTextFrame } from './remote-runtime-shared-control-frame-handler' diff --git a/src/shared/remote-runtime-shared-control-frame-handler.ts b/src/shared/remote-runtime-shared-control-frame-handler.ts index 1da4f975b..761804e48 100644 --- a/src/shared/remote-runtime-shared-control-frame-handler.ts +++ b/src/shared/remote-runtime-shared-control-frame-handler.ts @@ -1,5 +1,5 @@ import { parseAuthenticatedFrame, parseReadyFrame } from './remote-runtime-request-frames' -import type { RemoteRuntimeClientError } from './remote-runtime-client' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' import { dispatchSharedControlFrame } from './remote-runtime-shared-control-frame-dispatch' import { parseSharedControlFrame } from './remote-runtime-shared-control-protocol' import { resolveSharedControlReadyWaiters } from './remote-runtime-shared-control-state' diff --git a/src/shared/remote-runtime-shared-control-open.ts b/src/shared/remote-runtime-shared-control-open.ts index 16bfeb938..6381f58dd 100644 --- a/src/shared/remote-runtime-shared-control-open.ts +++ b/src/shared/remote-runtime-shared-control-open.ts @@ -1,6 +1,6 @@ import type WebSocket from 'ws' import type { PairingOffer } from './pairing' -import type { RemoteRuntimeClientError } from './remote-runtime-client' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import { openRemoteRuntimeWebSocket, diff --git a/src/shared/remote-runtime-shared-control-state.ts b/src/shared/remote-runtime-shared-control-state.ts index ad07c08b1..9c22198f7 100644 --- a/src/shared/remote-runtime-shared-control-state.ts +++ b/src/shared/remote-runtime-shared-control-state.ts @@ -1,4 +1,4 @@ -import type { RemoteRuntimeClientError } from './remote-runtime-client' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import type { diff --git a/src/shared/remote-runtime-shared-control-types.ts b/src/shared/remote-runtime-shared-control-types.ts index 6a16e32c7..9f784faa8 100644 --- a/src/shared/remote-runtime-shared-control-types.ts +++ b/src/shared/remote-runtime-shared-control-types.ts @@ -1,5 +1,5 @@ import type { RuntimeRpcResponse } from './runtime-rpc-envelope' -import type { RemoteRuntimeClientError } from './remote-runtime-client' +import type { RemoteRuntimeClientError } from './remote-runtime-client-error' export type SharedControlConnectionState = | 'closed' diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 94100eb54..a8d801a3e 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -1,5 +1,10 @@ /* eslint-disable max-lines -- Why: shared type definitions for all runtime RPC methods live in one file for discoverability and import simplicity. */ -import type { AgentStatusEntry, AgentStatusOrchestrationContext } from './agent-status-types' +import type { + AgentStatusEntry, + AgentStatusOrchestrationContext, + AgentStatusState, + AgentType +} from './agent-status-types' import type { BaseRefSearchResult, BrowserCookieImportResult, @@ -291,6 +296,19 @@ export type RuntimeFileReadResult = { byteLength: number } +/** Result of resolving a file path tapped in the mobile terminal against the + * worktree root (+ optional cwd). relativePath is null when the path resolves + * outside the worktree (not openable via the worktree-scoped file RPCs). */ +export type RuntimeTerminalPathResolution = { + worktree: string + relativePath: string | null + /** Absolute on-disk path (or remote path), present when relativePath is. + * Used to build a file:// URL for opening HTML in a browser tab. */ + absolutePath: string | null + exists: boolean + isDirectory: boolean +} + export type RuntimeFilePreviewResult = { content: string isBinary: boolean @@ -394,6 +412,25 @@ export type RuntimeTerminalWait = { blockedReason?: RuntimeTerminalWaitBlockedReason } +/** One agent's live status as carried to mobile in a worktree.ps summary. + * Flat shape (parentPaneKey points to another row in the same worktree's list) + * so the client can rebuild the spawn-lineage tree desktop renders inline. */ +export type RuntimeWorktreeAgentRow = { + paneKey: string + /** paneKey of the orchestration parent, or null for a root agent. */ + parentPaneKey: string | null + state: AgentStatusState + agentType: AgentType | null + prompt: string + lastAssistantMessage: string | null + toolName: string | null + toolInput: string | null + interrupted: boolean + /** When the current `state` was first reported (ms). Drives "Xm ago". */ + stateStartedAt: number + updatedAt: number +} + export type RuntimeWorktreePsSummary = { worktreeId: string repoId: string @@ -405,13 +442,54 @@ export type RuntimeWorktreePsSummary = { displayName: string linkedIssue: number | null linkedPR: { number: number; state: string } | null + linkedLinearIssue: string | null + linkedGitLabMR: number | null + linkedGitLabIssue: number | null + comment: string isPinned: boolean + /** True for the worktree currently focused on the desktop/host + * (session.activeWorktreeId). Mobile scrolls it into view and highlights it + * so the list reflects the desktop's current selection. */ + isActive: boolean unread: boolean liveTerminalCount: number hasAttachedPty: boolean lastOutputAt: number | null preview: string status: RuntimeWorktreeStatus + /** Live agents in this worktree, newest-state-first. Empty for shell-only + * worktrees. Mirrors desktop's inline agent list (WorktreeCardAgents). */ + agents: RuntimeWorktreeAgentRow[] +} + +export type RuntimeGitLocalBranches = { + current: string | null + branches: string[] +} + +/** One speech model as presented to the mobile dictation-setup sheet: catalog + * metadata joined with live download/ready state. */ +export type RuntimeSpeechModelSummary = { + id: string + label: string + provider: 'local' | 'openai' + sizeBytes: number | null + recommended: boolean + status: 'ready' | 'not-downloaded' | 'downloading' | 'extracting' | 'error' + progress: number | null +} + +export type RuntimeSpeechSetupState = { + enabled: boolean + selectedModelId: string + /** 'toggle' = press once to start/stop; 'hold' = dictate while held. */ + dictationMode: 'toggle' | 'hold' + models: RuntimeSpeechModelSummary[] +} + +export type RuntimeGitCheckoutResult = { + ok: true + branch: string } export type RuntimeWorktreeStatus = 'active' | 'working' | 'permission' | 'done' | 'inactive'