Files
orca/mobile/src/source-control/use-mobile-source-control-runners.ts
T
Jinjing 43f639ddda Consolidate mobile source control into a single tabbed hub (#7923)
* Consolidate mobile source control into a single tabbed hub

Unify the changes list, pull request details, and commit history into
a single multi-segment panel. This improves navigation and state sharing
across different lenses of a worktree's source control.

- Add a segmented control to switch between Changes, PR, and History
- Introduce a persistent branch status card with an integrated PR chip
- Redirect standalone PR and history routes to the new unified hub
- Extract reusable UI and logic for the history list and PR summary

* Keep mobile source control tabs mounted to preserve view state

* Keep PR and History segments mounted (using display: 'none' when hidden) to preserve fetch, scroll, and expand states during tab switches.
* Decouple the History list from blocking on Git status loading.
* Support deep linking directly into the history tab of the main panel instead of using a standalone route.
* Enable retrying failed loads by reviving the transport loop if parked.
* Fix PR chip accessibility label and comment check.

* Optimize and integrate mobile PR view within source control hub

- Lazy-load heavy PR comments and descriptions (Phase 2) only when the
  PR tab is active, using fast metadata (Phase 1) for the branch chip.
- Unmount the PR body when inactive to avoid unnecessary comment tree
  re-renders and preserve WebView resources during commit text editing.
- Implement soft-refresh on HEAD advancement to keep the ready UI
  visible while re-fetching checks post-commit.
- Display the "Aborting..." label only when a merge or rebase abort
  is actively in flight.
- Memoize the git history list and skip branch identity RPCs when
  gating the dock icon.

* Improve mobile git views and concurrent rendering safety

- Pass the `origin` parameter through history and PR redirect routes.
- Move source control panel ref updates to `useEffect` to prevent side
  effects during concurrent renders.
- Resolve commit file changes to empty if disconnected to avoid a stuck
  loading spinner.
- Standardize PR sidebar header button styling and accessibility labels.

* Resolve PR repo probe without active branch to avoid forever spinner

Previously, checking if a repository is a GitHub remote required an
active branch. In a detached HEAD or mid-rebase state (where the branch
is null), the probe never resolved, leaving the PR panel on a forever
spinner.

Decouple the repository probe from the branch presence so the panel
can correctly display the "Current branch unavailable" state. Also,
hide the PR status chip when no branch is active to avoid a spinner
on the chip.
2026-07-09 19:23:36 -07:00

323 lines
9.0 KiB
TypeScript

import { useCallback, type MutableRefObject } from 'react'
import { useRouter } from 'expo-router'
import type { RpcClient } from '../transport/rpc-client'
import { triggerError, triggerSuccess } from '../platform/haptics'
import { useMobileCommitMessageGeneration } from './use-mobile-commit-message-generation'
import { useMobileSourceControlCommitRunners } from './use-mobile-source-control-commit-runners'
import { useMobileSourceControlActionSheetRunners } from './use-mobile-source-control-action-sheet-runners'
import { useMobileCreatePrRunner } from './use-mobile-create-pr-runner'
import type { RuntimeGitLocalBranches } from '../../../src/shared/runtime-types'
import type { MobileGitStatusResult } from './mobile-git-status'
import type { LoadStatusOptions } from './mobile-source-control-screen-state'
import type {
MobileCommitFailureRecovery,
RecordMobileCommitFailure
} from './mobile-commit-failure-recovery'
type GitStep = { method: string; params?: Record<string, unknown> }
type SendGitRequest = <T>(method: string, params?: Record<string, unknown>) => Promise<T>
type Params = {
client: RpcClient | null
hostId: string
worktreeId: string
status: MobileGitStatusResult | null
branchLabel: string
commitMessage: string
stagedEntries: MobileCommitFailureRecovery['stagedEntries']
generatingMessage: boolean
stageablePaths: string[]
unstageablePaths: string[]
router: ReturnType<typeof useRouter>
sendGitRequest: SendGitRequest
sendCommitRequest: (message: string) => Promise<unknown>
runGitSyncSteps: () => Promise<void>
loadStatus: (options?: LoadStatusOptions) => Promise<boolean>
mountedRef: MutableRefObject<boolean>
busyActionRef: MutableRefObject<string | null>
setBusyAction: (next: string | null) => void
setActionError: (next: string | null) => void
setCommitMessage: (next: string) => void
setGeneratingMessage: (next: boolean) => void
setShowActionSheet: (next: boolean) => void
setLocalBranches: (next: RuntimeGitLocalBranches | null) => void
setShowBranchPicker: (next: boolean) => void
setCreatedPrUrl: (next: string | null) => void
setCreatedPrWarning: (next: string | null) => void
recordCommitFailure: RecordMobileCommitFailure
// Hub override: switch to the History segment instead of pushing the route.
onOpenHistory?: () => void
}
// All git workflow + action-sheet runners for the source-control panel. Split
// out of the state hook to keep each file under the line limit; behavior is
// unchanged from the original inline definitions.
export function useMobileSourceControlRunners(params: Params) {
const {
client,
hostId,
worktreeId,
status,
branchLabel,
commitMessage,
stagedEntries,
generatingMessage,
stageablePaths,
unstageablePaths,
router,
sendGitRequest,
sendCommitRequest,
runGitSyncSteps,
loadStatus,
mountedRef,
busyActionRef,
setBusyAction,
setActionError,
setCommitMessage,
setGeneratingMessage,
setShowActionSheet,
setLocalBranches,
setShowBranchPicker,
setCreatedPrUrl,
setCreatedPrWarning,
recordCommitFailure,
onOpenHistory
} = params
const runGitWorkflow = useCallback(
async (
actionId: string,
runner: () => Promise<void>,
options?: { clearCommitMessage?: boolean }
) => {
if (busyActionRef.current) {
return false
}
busyActionRef.current = actionId
setBusyAction(actionId)
setActionError(null)
recordCommitFailure(null)
try {
await runner()
if (!mountedRef.current) {
return false
}
if (options?.clearCommitMessage) {
setCommitMessage('')
}
triggerSuccess()
await loadStatus({ preserveReadyOnFailure: true, force: true })
return true
} catch (err) {
if (!mountedRef.current) {
return false
}
triggerError()
setActionError(err instanceof Error ? err.message : 'Source control action failed')
return false
} finally {
if (busyActionRef.current === actionId) {
busyActionRef.current = null
if (mountedRef.current) {
setBusyAction(null)
}
}
}
},
[
busyActionRef,
loadStatus,
mountedRef,
recordCommitFailure,
setActionError,
setBusyAction,
setCommitMessage
]
)
const runGitAction = useCallback(
async (actionId: string, method: string, p: Record<string, unknown>) => {
return await runGitWorkflow(actionId, async () => {
await sendGitRequest<unknown>(method, p)
})
},
[runGitWorkflow, sendGitRequest]
)
const runGitSequence = useCallback(
async (actionId: string, steps: GitStep[], options?: { clearCommitMessage?: boolean }) => {
return await runGitWorkflow(
actionId,
async () => {
for (const step of steps) {
await sendGitRequest<unknown>(step.method, step.params)
}
},
options
)
},
[runGitWorkflow, sendGitRequest]
)
const runGitSync = useCallback(
async (actionId: string) => await runGitWorkflow(actionId, runGitSyncSteps),
[runGitSyncSteps, runGitWorkflow]
)
const stageAll = useCallback(async () => {
if (stageablePaths.length === 0) {
return
}
await runGitAction('stage-all', 'git.bulkStage', { filePaths: stageablePaths })
}, [runGitAction, stageablePaths])
const unstageAll = useCallback(async () => {
if (unstageablePaths.length === 0) {
return
}
await runGitAction('unstage-all', 'git.bulkUnstage', { filePaths: unstageablePaths })
}, [runGitAction, unstageablePaths])
const { commit, runCommitSequence, runCommitSyncSequence } = useMobileSourceControlCommitRunners({
commitMessage,
stagedEntries,
sendGitRequest,
sendCommitRequest,
runGitSyncSteps,
runGitWorkflow,
loadStatus,
mountedRef,
busyActionRef,
setBusyAction,
setActionError,
setCommitMessage,
recordCommitFailure
})
const { generateCommitMessage, cancelGenerateCommitMessage } = useMobileCommitMessageGeneration({
client,
worktreeId,
generatingMessage,
mountedRef,
busyActionRef,
setGeneratingMessage,
setCommitMessage,
setActionError
})
const createPr = useMobileCreatePrRunner({
client,
worktreeId,
status,
branchLabel,
commitMessage,
stagedEntries,
mountedRef,
runGitWorkflow,
loadStatus,
setActionError,
setCommitMessage,
setShowActionSheet,
setCreatedPrUrl,
setCreatedPrWarning,
recordCommitFailure
})
const openBranchPicker = useCallback(() => {
setShowActionSheet(false)
setLocalBranches(null)
setShowBranchPicker(true)
if (client) {
void sendGitRequest<RuntimeGitLocalBranches>('git.localBranches')
.then((result) => {
if (mountedRef.current) {
setLocalBranches(result)
}
})
.catch(() => {
if (mountedRef.current) {
setLocalBranches({ current: null, branches: [] })
}
})
}
}, [
client,
mountedRef,
sendGitRequest,
setLocalBranches,
setShowActionSheet,
setShowBranchPicker
])
const openHistory = useCallback(() => {
setShowActionSheet(false)
// Inside the hub, History is a segment — switch to it rather than pushing a
// route. Fallback pushes the hub with `tab=history` (not the redirecting
// /history route) so deep links land in one hop.
if (onOpenHistory) {
onOpenHistory()
return
}
if (hostId && worktreeId) {
router.push({
pathname: '/h/[hostId]/source-control/[worktreeId]',
params: {
hostId,
worktreeId,
tab: 'history'
}
} as Parameters<typeof router.push>[0])
}
}, [hostId, onOpenHistory, router, setShowActionSheet, worktreeId])
// Switch to a local branch, then reload status.
const checkoutBranch = useCallback(
async (branch: string) => {
setShowBranchPicker(false)
await runGitAction('checkout', 'git.checkout', { branch })
},
[runGitAction, setShowBranchPicker]
)
const actionSheetRunners = useMobileSourceControlActionSheetRunners({
client,
worktreeId,
sendGitRequest,
runGitWorkflow,
runGitSequence,
runGitSync,
commit,
runCommitSequence,
runCommitSyncSequence,
setShowActionSheet
})
// 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]
)
return {
runGitAction,
stageAll,
unstageAll,
commit,
generateCommitMessage,
cancelGenerateCommitMessage,
createPr,
openBranchPicker,
openHistory,
checkoutBranch,
abortConflictOperation,
...actionSheetRunners
}
}