Files
orca/mobile/src/source-control/use-mobile-source-control-state.ts
T
Jinjing 8a39450b18 refs/heads/handle-mobile-pull-request-issues (#6598)
* feat(mobile): add commit failure recovery panel with AI fix action

- Surfaces a "Commit failed" panel with a one-tap AI fix button when a
  git commit fails in the source control view or PR creation flow
- Detects commit failures specifically during the committing progress
  step and captures staged entries and commit message for context
- Extracts commit failure summary and prompt logic into
  `src/shared/source-control-commit-failure.ts` and PR checks prompt
  into `src/shared/pr-checks-fix-prompt.ts` so both desktop and mobile
  share the same implementations
- Adds auto-find of an available Metro port starting from 8081 and
  extracts expo CLI bootstrap into `mobile-expo-cli.mjs` shared by
  `start-emulator` and a new `start-expo.mjs` wrapper

* Share source-control AI prompts and simplify mobile PR actions

- Extract conflict, check-fixing, and commit-failure prompt builders
  to shared modules for reuse by both desktop and mobile.
- Configure Metro in the mobile package to watch and bundle modules
  from the repository-root shared directory.
- Remove the desktop-style merge method picker from the mobile PR
  actions panel, opting to use repository defaults automatically.
- Refactor mobile hosted review creation and git preparation logic
  into dedicated helper files.
2026-06-28 00:58:17 -07:00

319 lines
10 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Keyboard, Platform } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useHostClient, useForceReconnect } from '../transport/client-context'
import { getWorktreeLabel } from '../session/worktree-label'
import { useMobileGitRequests } from './use-mobile-git-requests'
import { useMobileSourceControlLoaders } from './use-mobile-source-control-loaders'
import { useMobileSourceControlOpeners } from './use-mobile-source-control-openers'
import { buildMobileSourceControlPrimaryAction } from './mobile-source-control-primary-action'
import { useMobileSourceControlRunners } from './use-mobile-source-control-runners'
import type { RuntimeGitLocalBranches } from '../../../src/shared/runtime-types'
import {
buildMobileBranchCompareSection,
canOpenMobileBranchCompareDiff,
formatMobileBranchCompareSummary
} from './mobile-branch-compare'
import {
buildMobileSourceControlSections,
countStagedEntries,
countUnstagedEntries,
getStageablePaths,
getUnstageablePaths,
isMobileGitDiscardableEntry,
isMobileGitStageableEntry,
type MobileGitStatusEntry
} from './mobile-git-status'
import { getMobileCommitFailureStagedEntries } from './mobile-commit-failure-recovery'
import { useMobileSourceControlCommitFailure } from './use-mobile-source-control-commit-failure'
import {
formatBranchLabel,
type MobileBranchEntryView,
type MobileGitStatusEntryView
} from './mobile-source-control-screen-state'
type MobileGitLocalBranches = RuntimeGitLocalBranches
export type MobileSourceControlStateParams = {
hostId: string
worktreeId: string
name: string
origin: string
embedded: boolean
onRequestClose?: () => void
}
export function useMobileSourceControlState(params: MobileSourceControlStateParams) {
const { hostId, worktreeId, name, origin, embedded, onRequestClose } = params
const insets = useSafeAreaInsets()
const { client, state: connState } = useHostClient(hostId)
const forceReconnect = useForceReconnect()
const [busyAction, setBusyAction] = useState<string | null>(null)
const [commitMessage, setCommitMessage] = useState('')
const [generatingMessage, setGeneratingMessage] = useState(false)
const [showBranchPicker, setShowBranchPicker] = useState(false)
const [localBranches, setLocalBranches] = useState<MobileGitLocalBranches | null>(null)
const [createdPrUrl, setCreatedPrUrl] = useState<string | null>(null)
const [createdPrWarning, setCreatedPrWarning] = useState<string | null>(null)
const [discardTarget, setDiscardTarget] = useState<MobileGitStatusEntry | null>(null)
const [showActionSheet, setShowActionSheet] = useState(false)
const [actionError, setActionError] = useState<string | null>(null)
const [keyboardLift, setKeyboardLift] = useState(0)
const busyActionRef = useRef<string | null>(null)
const worktreeLabel = getWorktreeLabel(name, worktreeId)
const statusIdentityKey = `${hostId}\0${worktreeId}`
const { commitFailureRecovery, commitFailureRecoveryAction, recordCommitFailure } =
useMobileSourceControlCommitFailure({ client, connState, worktreeId })
const clearCommitFailureRecovery = useCallback(() => {
recordCommitFailure(null)
}, [recordCommitFailure])
const { screenState, branchCompareState, mountedRef, setRootRef, loadStatus } =
useMobileSourceControlLoaders({
client,
connState,
statusIdentityKey,
worktreeId,
setActionError,
onStatusLoadSuccess: clearCommitFailureRecovery
})
const {
router,
branchDiffPreview,
setBranchDiffPreview,
openingPath,
openingBranchPath,
openFile,
openBranchDiff
} = useMobileSourceControlOpeners({
client,
connState,
hostId,
worktreeId,
name,
origin,
embedded,
onRequestClose,
branchCompareState,
mountedRef,
busyActionRef,
setActionError
})
useEffect(() => {
const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow'
const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide'
const onShow = Keyboard.addListener(showEvent, (event) => {
// Why: iOS keyboard height already describes the obscured screen area.
// Subtracting the safe-area inset lets the commit bar tuck under the keyboard.
setKeyboardLift(Math.max(0, event.endCoordinates.height))
})
const onHide = Keyboard.addListener(hideEvent, () => setKeyboardLift(0))
return () => {
onShow.remove()
onHide.remove()
}
}, [])
const status = screenState.kind === 'ready' ? screenState.status : null
const entries = status?.entries ?? []
const derivedEntries = useMemo<MobileGitStatusEntryView[]>(
() =>
entries.map((entry) => ({
...entry,
canDiscard: isMobileGitDiscardableEntry(entry),
canOpen: entry.status !== 'deleted' && entry.conflictStatus !== 'unresolved',
canStage: isMobileGitStageableEntry(entry),
discardActionId: `discard:${entry.path}`,
stageActionId: `stage:${entry.path}`,
unstageActionId: `unstage:${entry.path}`
})),
[entries]
)
const sections = useMemo(() => buildMobileSourceControlSections(derivedEntries), [derivedEntries])
const branchCompareResult = branchCompareState.kind === 'ready' ? branchCompareState.result : null
const branchCompareSection = useMemo(
() => buildMobileBranchCompareSection(branchCompareResult?.entries ?? []),
[branchCompareResult]
)
const branchCompareSummaryText = branchCompareResult
? formatMobileBranchCompareSummary(branchCompareResult.summary)
: null
const branchCompareCanOpen = branchCompareResult
? canOpenMobileBranchCompareDiff(branchCompareResult.summary)
: false
const branchEntries = useMemo<MobileBranchEntryView[]>(
() =>
(branchCompareSection?.data ?? []).map((entry) => ({
...entry,
canOpen: branchCompareCanOpen
})),
[branchCompareCanOpen, branchCompareSection]
)
const shouldShowBranchCompareSection =
branchEntries.length > 0 ||
branchCompareState.kind === 'loading' ||
branchCompareState.kind === 'error' ||
(branchCompareResult !== null && branchCompareResult.summary.status !== 'ready')
const hasVisibleChanges = sections.length > 0 || shouldShowBranchCompareSection
const reviewableCount = entries.length + (branchCompareCanOpen ? branchEntries.length : 0)
const stageablePaths = useMemo(() => getStageablePaths(entries), [entries])
const unstageablePaths = useMemo(() => getUnstageablePaths(entries), [entries])
const stagedCount = useMemo(() => countStagedEntries(entries), [entries])
const stagedEntriesForRecovery = useMemo(
() => getMobileCommitFailureStagedEntries(entries),
[entries]
)
const unstagedCount = useMemo(() => countUnstagedEntries(entries), [entries])
const hasUnresolvedConflicts = useMemo(
() => entries.some((entry) => entry.conflictStatus === 'unresolved'),
[entries]
)
const branchLabel = formatBranchLabel(status?.branch, status?.head)
const upstream = status?.upstreamStatus
const upstreamKnown = upstream !== undefined
const syncLabel =
upstream && upstream.hasUpstream
? `${upstream.ahead} ahead, ${upstream.behind} behind`
: upstream && !upstream.hasUpstream
? 'No upstream'
: null
const { sendGitRequest, sendCommitRequest, runGitSyncSteps } = useMobileGitRequests({
client,
connState,
worktreeId
})
const runners = useMobileSourceControlRunners({
client,
hostId,
worktreeId,
status,
branchLabel,
commitMessage,
stagedEntries: stagedEntriesForRecovery,
generatingMessage,
stageablePaths,
unstageablePaths,
router,
sendGitRequest,
sendCommitRequest,
runGitSyncSteps,
loadStatus,
mountedRef,
busyActionRef,
setBusyAction,
setActionError,
setCommitMessage,
setGeneratingMessage,
setShowActionSheet,
setLocalBranches,
setShowBranchPicker,
setCreatedPrUrl,
setCreatedPrWarning,
recordCommitFailure
})
const primaryAction = useMemo(
() =>
buildMobileSourceControlPrimaryAction({
status,
hasUnresolvedConflicts,
stageablePaths,
stagedCount,
unstagedCount,
commitMessage,
busyAction,
openingPath,
openingBranchPath,
branchCompareResult,
handlers: {
commit: runners.commit,
stageAll: runners.stageAll,
runActionSheetGitSequence: runners.runActionSheetGitSequence,
runActionSheetGitSync: runners.runActionSheetGitSync
}
}),
[
branchCompareResult,
busyAction,
commitMessage,
hasUnresolvedConflicts,
openingBranchPath,
openingPath,
runners.commit,
runners.runActionSheetGitSequence,
runners.runActionSheetGitSync,
runners.stageAll,
stageablePaths,
stagedCount,
status,
unstagedCount
]
)
return {
client,
connState,
forceReconnect,
insets,
router,
setRootRef,
worktreeLabel,
// screen state
screenState,
branchCompareState,
branchDiffPreview,
setBranchDiffPreview,
busyAction,
commitMessage,
setCommitMessage,
generatingMessage,
showBranchPicker,
setShowBranchPicker,
localBranches,
createdPrUrl,
setCreatedPrUrl,
createdPrWarning,
setCreatedPrWarning,
discardTarget,
setDiscardTarget,
showActionSheet,
setShowActionSheet,
actionError,
commitFailureRecovery,
commitFailureRecoveryAction,
keyboardLift,
openingPath,
openingBranchPath,
// derived
status,
sections,
branchCompareResult,
branchCompareSummaryText,
branchEntries,
shouldShowBranchCompareSection,
hasVisibleChanges,
reviewableCount,
stageablePaths,
unstageablePaths,
stagedCount,
unstagedCount,
branchLabel,
upstream,
upstreamKnown,
syncLabel,
primaryAction,
// actions
loadStatus,
openFile,
openBranchDiff,
...runners
}
}
export type MobileSourceControlState = ReturnType<typeof useMobileSourceControlState>