Files
orca/mobile/src/source-control/MobileSourceControlPanel.tsx
T
Jinwoo HongandClaude 65cde9bb80 fix(mobile): name the source-control Back controls and split the dock's Close from Back (OTA phase C, C4.3) (#21739)
* fix(mobile): name the custom-key drawer's Back for the accessibility tree (OTA phase C, C4.3)

`CustomKeyModal`'s Back is a bare `Pressable` with a label and no role, so
a screen reader has nothing to announce it as. It is reachable today from
the session sheets and the terminal shortcut settings, so this is a gap
now, not only inside the page.

It surfaces here because `screenTree` takes a screen's directory: C4.4
registering the review route puts the whole of `src/components` under the
Back rule. Fixing it in the PR that registers would make a route entry
carry unrelated accessibility work, so the census gains a case that holds
the arriving trees to the same two rules before the rows land. Red first
it printed exactly what the rule would:

  src/components/CustomKeyModal.tsx:191 role=none label=Back

Once `PAGE_SERVED_SCREENS` has the two rows, `CONTROLS` covers these trees
and the new case becomes a second reading of the same thing; it says so.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): split the source-control header's Close from its Back (OTA phase C, C4.3)

One `Pressable` served both modes — `onPress={onBack}` with a conditional
label, `X` docked and `ChevronLeft` full-screen. The Back census reads a
control by what its handler does, so it sees that one as a Back and then
requires a label starting with "Back", in a mode where the control
dismisses the dock beside the terminal. The cheap way to go green is to
call a close "Back", which satisfies the rule by making the wording wrong.

So the modes become two controls. Embedded presses `onClose` and is named
"Close source control"; otherwise it presses `onBack` and is named "Back
to session". Both carry the button role. The panel stops choosing by mode
and passes both handlers; the dock keeps exactly the behaviour it had, its
dismiss still `onRequestClose` falling back to a pop.

Probed before it was written: run through the census's own predicate, the
post-split shape yields one back control rather than two — `onClose`
matches neither the handler pattern nor a declaration this file holds,
being a destructured prop — so the Close is invisible to the rule and the
presence precondition still holds on the Back.

The component test is what the census cannot do. Nothing else pins this:
no golden names this component and no parity census covers
`src/source-control`. Red first against the single control, both cases
failed on the missing role. And renaming the Close to "Back to close
source control" — the gaming this split exists to prevent — reds the
component test while leaving the census green, which is the whole argument
for having both.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): assert a Back per arriving tree, and name the refresh control (OTA phase C, C4.3 round 1)

The arriving-trees presence case counted controls over the union of both
trees, so one tree answered for the other. Per tree now, in the shape the
block above it already uses per screen module.

Red first, with the mutation round 1 named: rename the route branch's
handler to `onDismiss` and its label to `Return to session`, and the only
Back in `src/source-control` disappears. The per-tree case names that
tree. The same mutation against the union count passes all six cases,
which is what the change is for.

The refresh control had a label and no role, so react-native-web renders
a `div` carrying `aria-label` and a screen reader announces no control.
Its two siblings in this header already carry one.

Two claims in my round-1 report were wrong and I am the reason the body
carried them. The Close pressing `onBack` reds the census's label rule as
well as the component test, not the component test alone; and no fixture
of the post-split shape exists — the shape is read from the real file.
Both were stated from reasoning rather than from a run.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): assert an arriving Back per screen, not per tree (OTA phase C, C4.3 round 2)

Round 1 moved the arriving-trees presence assertion from the union to
each tree, which was not far enough. `src/components` holds two Backs, so
the tree answers for both: renaming `MobileDiffReviewHeader`'s handler to
`onDismiss` and its label to `Return to session` leaves every case in the
file green, with `CustomKeyModal.tsx:191` standing in for the screen that
just lost its Back. Reproduced before the change — six passed with the
review header's Back gone.

Per screen module now, which is what the table above already does and for
the same reason its docstring gives: a directory with more than one
control cannot say which one a rule was written about. The two modules
are named and the trees derive from them, so the pair C4.4 adds to
`PAGE_SERVED_SCREENS` is the same pair spelled once here.

Both mutations red on the new case and name the file: the review header's
rename names `src/components/MobileDiffReviewHeader.tsx`, and round 1's
source-control rename still names its own, so this does not trade one
cover for another.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-19 20:51:47 -04:00

356 lines
13 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { colors } from '../theme/mobile-theme'
import { useMobileSourceControlState } from './use-mobile-source-control-state'
import { useMobileSourceControlActionSheet } from './use-mobile-source-control-action-sheet'
import { MobileSourceControlHeader } from './MobileSourceControlHeader'
import { MobileSourceControlContent } from './MobileSourceControlContent'
import { MobileSourceControlModals } from './MobileSourceControlModals'
import { MobileSourceControlSegments } from './MobileSourceControlSegments'
import { MobileSourceControlBranchCard } from './MobileSourceControlBranchCard'
import { MobileGitHistoryList } from './MobileGitHistoryList'
import { styles } from './mobile-source-control-styles'
import { hubStyles } from './mobile-source-control-hub-styles'
import type { SourceControlHubTab } from './mobile-source-control-hub-tab'
import { buildMobilePrChipSummary, countUnresolvedReviewThreads } from './mobile-pr-chip-summary'
import { isMobileConflictAborting } from './mobile-source-control-conflict-abort'
import { useMobilePrSidebarController } from '../session/use-mobile-pr-sidebar-controller'
import { prSidebarDetailsNeedFetch } from '../session/mobile-pr-sidebar-state'
import { MobilePrViewPanelBody } from '../components/pr-sidebar/MobilePrViewPanel'
import { openMobilePrUrl } from '../components/mobile-pr-url'
export type MobileSourceControlPanelProps = {
hostId: string
worktreeId: string
name?: string
/** Where the panel was launched from; drives the file-open dismissal path. */
origin?: string
embedded?: boolean
/** Initial hub segment (from the route's `tab` deep-link param). */
initialTab?: SourceControlHubTab
onRequestClose?: () => void
onFileOpenStart?: () => void
onOpenedFileDiff?: (relativePath: string) => void
}
export function MobileSourceControlPanel({
hostId,
worktreeId,
name = '',
origin = '',
embedded = false,
initialTab = 'changes',
onRequestClose,
onFileOpenStart,
onOpenedFileDiff
}: MobileSourceControlPanelProps) {
const [activeTab, setActiveTab] = useState<SourceControlHubTab>(initialTab)
// Track first visit so Changes/History stay mounted (keep scroll) after first open; PR still unmounts when inactive.
const [visitedTabs, setVisitedTabs] = useState<ReadonlySet<SourceControlHubTab>>(
() => new Set<SourceControlHubTab>([initialTab])
)
const [historyRefreshNonce, setHistoryRefreshNonce] = useState(0)
// expo-router reuses the screen instance when only query params change, so adopt the new tab.
useEffect(() => {
setActiveTab(initialTab)
setVisitedTabs((prev) => {
if (prev.has(initialTab)) {
return prev
}
const next = new Set(prev)
next.add(initialTab)
return next
})
}, [initialTab])
const selectTab = useCallback((tab: SourceControlHubTab) => {
setActiveTab(tab)
setVisitedTabs((prev) => {
if (prev.has(tab)) {
return prev
}
const next = new Set(prev)
next.add(tab)
return next
})
}, [])
const openHistoryTab = useCallback(() => selectTab('history'), [selectTab])
const openPrTab = useCallback(() => selectTab('pr'), [selectTab])
const state = useMobileSourceControlState({
hostId,
worktreeId,
name,
origin,
embedded,
onRequestClose,
onFileOpenStart,
onOpenedFileDiff,
onOpenHistory: openHistoryTab
})
const actionSheetActions = useMobileSourceControlActionSheet(state)
const {
client,
connState,
forceReconnect,
insets,
router,
setRootRef,
worktreeLabel,
screenState,
busyAction,
openingPath,
openingBranchPath,
loadStatus,
status,
branchCompareResult,
branchLabel,
syncLabel,
unstagedCount,
stagedCount,
branchEntries,
abortConflictOperation
} = state
const ioBusy = busyAction !== null || openingPath !== null || openingBranchPath !== null
const ready = screenState.kind === 'ready'
// Keep last-known branch/head across a transient status unload so the PR controller isn't wiped ready → hidden → cold start.
const lastPrBranchRef = useRef<string | null>(null)
const lastPrHeadRef = useRef<string | null>(null)
useEffect(() => {
lastPrBranchRef.current = null
lastPrHeadRef.current = null
}, [worktreeId])
const statusBranch = status?.branch ?? null
const statusHead = status?.head ?? branchCompareResult?.summary.headOid ?? null
// Write last-known identity in an effect, not render: a discarded concurrent render must not leave the fallback stale.
useEffect(() => {
if (statusBranch) {
lastPrBranchRef.current = statusBranch
}
if (statusHead) {
lastPrHeadRef.current = statusHead
}
}, [statusBranch, statusHead])
const prBranch = statusBranch ?? lastPrBranchRef.current
const prHeadSha = statusHead ?? lastPrHeadRef.current
const prController = useMobilePrSidebarController({
client,
connState,
worktreeId,
branch: prBranch,
headSha: prHeadSha
})
const isHostedRepo = prController.prSidebarIsGithubRepo
const prSidebarKind = prController.prSidebarState.kind
const refetchPr = prController.refetchPRSidebar
const ensurePrDetails = prController.ensurePrSidebarDetails
// Refs so tab effects do not re-fire when headSha recreates load() (soft refresh).
const refetchPrRef = useRef(refetchPr)
refetchPrRef.current = refetchPr
const ensurePrDetailsRef = useRef(ensurePrDetails)
ensurePrDetailsRef.current = ensurePrDetails
// Chip bootstrap: phase-1 only (PR + checks); full payload waits for the PR segment so opening SC to stage doesn't pull details.
useEffect(() => {
if (activeTab === 'pr') {
return
}
if (prBranch && isHostedRepo && prSidebarKind === 'hidden') {
void refetchPrRef.current({ includeDetails: false })
}
}, [activeTab, prBranch, isHostedRepo, prSidebarKind])
// Keyed by PR number, not a boolean, so a same-branch PR swap re-arms phase 2 for the new PR.
const prDetailsMissingFor =
prController.prSidebarState.kind === 'ready' &&
prSidebarDetailsNeedFetch(prController.prSidebarState.data.details)
? prController.prSidebarState.data.pr.number
: null
// PR segment full load / phase-2 fill-in; key on prBranch so a branch arriving while open still loads (kind stays 'hidden').
useEffect(() => {
if (activeTab !== 'pr' || !isHostedRepo || !prBranch) {
return
}
if (prSidebarKind === 'hidden') {
void refetchPrRef.current({ includeDetails: true })
return
}
if (prDetailsMissingFor != null) {
void ensurePrDetailsRef.current()
}
}, [activeTab, isHostedRepo, prBranch, prSidebarKind, prDetailsMissingFor])
const prChip = useMemo(() => {
// No branch (detached HEAD / mid-rebase) never loads a PR, so state stays 'hidden'; hide the chip or it spins forever.
if (!isHostedRepo || !prBranch) {
return null
}
const commentCount =
prController.prSidebarState.kind === 'ready'
? countUnresolvedReviewThreads(prController.prSidebarState.data.details?.comments)
: null
return buildMobilePrChipSummary(prController.prSidebarState, commentCount)
}, [isHostedRepo, prBranch, prController.prSidebarState])
// Refresh the active segment plus git.status (branch card stays honest on History); preserve ready on failure so the PR chip isn't wiped.
const onRefresh = useCallback(() => {
void loadStatus({ preserveReadyOnFailure: true })
if (activeTab === 'history') {
setHistoryRefreshNonce((n) => n + 1)
return
}
if (!isHostedRepo) {
return
}
if (activeTab === 'pr') {
void refetchPr({ includeDetails: true })
return
}
// Changes: light chip refresh so the branch card stays current without comments.
void refetchPr({ includeDetails: false })
}, [activeTab, isHostedRepo, loadStatus, refetchPr])
// Embedded mode docks beside the terminal: close the dock instead of popping a route; skip
// safe-area chrome (the dock column owns it). Two handlers rather than one chosen by mode,
// because the header renders a Close or a Back and they are not the same control.
const onBack = () => router.back()
const onClose = onRequestClose ?? (() => router.back())
// Chromeless PR body has no header, so surface open-on-web on the hub chrome while the PR segment is active.
const prWebUrl =
activeTab === 'pr' &&
prController.prSidebarState.kind === 'ready' &&
prController.prSidebarState.data.pr.url
? prController.prSidebarState.data.pr.url
: null
const prWebNumber =
prController.prSidebarState.kind === 'ready' ? prController.prSidebarState.data.pr.number : null
const header = (
<MobileSourceControlHeader
embedded={embedded}
worktreeLabel={worktreeLabel}
ioBusy={ioBusy}
onBack={onBack}
onClose={onClose}
onRefresh={onRefresh}
onOpenPrWeb={prWebUrl ? () => openMobilePrUrl(prWebUrl) : undefined}
prNumber={prWebNumber}
/>
)
const statusGate =
screenState.kind === 'loading' ? (
<View style={styles.state}>
<ActivityIndicator size="small" color={colors.textSecondary} />
</View>
) : screenState.kind === 'error' || screenState.kind === 'unavailable' ? (
<View style={styles.state}>
<Text style={styles.stateTitle}>
{screenState.kind === 'unavailable' ? 'Source Control Unavailable' : 'Unable to Load'}
</Text>
<Text style={styles.stateText}>{screenState.message}</Text>
{screenState.kind === 'error' ? (
<Pressable
style={styles.retryButton}
onPress={() => {
// Why: a parked reconnect loop makes retry useless — revive the connection instead (issue #5049); loadStatus re-runs on reconnect.
if (connState !== 'connected' && hostId) {
void forceReconnect(hostId)
return
}
void loadStatus()
}}
>
<Text style={styles.retryText}>Retry</Text>
</Pressable>
) : null}
</View>
) : null
// History only needs the RPC client, so it isn't gated on git.status; Changes/PR need status (branch, files, head).
const showChanges = ready && (activeTab === 'changes' || visitedTabs.has('changes'))
const showHistory = activeTab === 'history' || visitedTabs.has('history')
// Only mount PR body while active: keep-mounting retained Mermaid WebViews and re-rendered the comment tree per keystroke.
const showPrBody = ready && activeTab === 'pr'
const conflictOperation = status?.conflictOperation ?? null
// Git status always reports a conflictOperation enum; 'unknown' means none.
const hasActiveConflict = conflictOperation != null && conflictOperation !== 'unknown'
const conflictAborting = isMobileConflictAborting(busyAction, conflictOperation)
return (
<View ref={setRootRef} style={styles.container}>
{embedded ? (
<View style={styles.header}>{header}</View>
) : (
<SafeAreaView style={styles.header} edges={['top']}>
{header}
</SafeAreaView>
)}
<MobileSourceControlSegments active={activeTab} onSelect={selectTab} />
{/* On the PR tab the branch card duplicates the ready PR body, so hide it there — unless a conflict is active, which only this card can abort. */}
{ready && (activeTab !== 'pr' || hasActiveConflict) ? (
<MobileSourceControlBranchCard
branchLabel={branchLabel}
syncLabel={syncLabel}
unstagedCount={unstagedCount}
stagedCount={stagedCount}
branchCount={branchEntries.length}
conflictOperation={conflictOperation}
conflictBusy={busyAction !== null}
conflictAborting={conflictAborting}
onAbortConflict={(operation) => void abortConflictOperation(operation)}
prChip={prChip}
onOpenPr={openPrTab}
/>
) : null}
{showChanges ? (
<View style={activeTab === 'changes' ? hubStyles.tabBody : hubStyles.tabBodyHidden}>
<MobileSourceControlContent state={state} />
</View>
) : activeTab === 'changes' ? (
statusGate
) : null}
{showPrBody ? (
<View style={hubStyles.tabBody}>
<MobilePrViewPanelBody
client={client}
connState={connState}
worktreeId={worktreeId}
branch={prBranch}
headSha={prHeadSha}
gitStatus={status}
isGithubRepo={isHostedRepo}
// Gate on the probe too: isGithubRepo=false mid-probe must render loading, not flash "unavailable".
branchContextLoaded={ready && prController.prSidebarRepoProbeLoaded}
controller={prController}
/>
</View>
) : activeTab === 'pr' ? (
statusGate
) : null}
{showHistory ? (
<View style={activeTab === 'history' ? hubStyles.tabBody : hubStyles.tabBodyHidden}>
<MobileGitHistoryList
client={client}
connState={connState}
worktreeId={worktreeId}
hostId={hostId}
bottomInset={insets.bottom}
refreshNonce={historyRefreshNonce}
/>
</View>
) : null}
<MobileSourceControlModals state={state} actionSheetActions={actionSheetActions} />
</View>
)
}