diff --git a/mobile/app/h/[hostId]/review/[worktreeId].tsx b/mobile/app/h/[hostId]/review/[worktreeId].tsx index d15524078..3d88cef0a 100644 --- a/mobile/app/h/[hostId]/review/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/review/[worktreeId].tsx @@ -1,10 +1,11 @@ -import { useCallback } from 'react' +import { useCallback, useMemo } from 'react' import { useLocalSearchParams, useRouter } from 'expo-router' import { MobileDiffReviewScreenView } from '../../../../src/components/MobileDiffReviewScreenView' import { firstReviewParam, normalizeReviewFilterParam } from '../../../../src/session/mobile-diff-review-screen-model' +import { normalizeReviewAreaParam } from '../../../../src/session/mobile-diff-review-positioning' import { useMobileDiffReviewController } from '../../../../src/session/use-mobile-diff-review-controller' import { useForceReconnect, useHostClient } from '../../../../src/transport/client-context' @@ -14,11 +15,19 @@ export default function MobileDiffReviewScreen() { worktreeId?: string | string[] name?: string | string[] scope?: string | string[] + file?: string | string[] + area?: string | string[] }>() const hostId = firstReviewParam(params.hostId) const worktreeId = firstReviewParam(params.worktreeId) const name = firstReviewParam(params.name) const initialFilter = normalizeReviewFilterParam(firstReviewParam(params.scope)) + const initialFile = firstReviewParam(params.file) + const initialArea = normalizeReviewAreaParam(firstReviewParam(params.area)) + const initialTarget = useMemo( + () => (initialFile && initialArea ? { filePath: initialFile, area: initialArea } : null), + [initialArea, initialFile] + ) const router = useRouter() const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() @@ -37,6 +46,7 @@ export default function MobileDiffReviewScreen() { worktreeId, name, initialFilter, + initialTarget, onOpenSession: openSession, onReconnect: forceReconnect }) diff --git a/mobile/app/h/[hostId]/session/[worktreeId].tsx b/mobile/app/h/[hostId]/session/[worktreeId].tsx index 81b1dee8c..e23f0c57c 100644 --- a/mobile/app/h/[hostId]/session/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/session/[worktreeId].tsx @@ -202,6 +202,7 @@ import { } from '../../../../src/session/mobile-session-route-helpers' import { resolveMarkdownFloatingActionsBottom } from '../../../../src/session/markdown-floating-actions-layout' import { resolveTabStripScrollOffset } from '../../../../src/session/tab-strip-scroll' +import { activateOpenedSourceControlDiffTab } from '../../../../src/session/opened-mobile-session-tab' import { createMobileSessionCreateWarningState, dismissMobileSessionCreateWarningState, @@ -3315,6 +3316,48 @@ export default function SessionScreen() { [client, worktreeId, scheduleDelayedAction, fetchSessionTabs] ) + const handleOpenedFileDiffActivationSeqRef = useRef(0) + // Active tab captured at tap time (before the openDiff RPC). Capturing it when + // the diff finishes opening would misread a tab the user switched to mid-RPC + // as the tap-time tab, letting the retry steal focus back to the diff. + const fileOpenStartActiveTabIdRef = useRef(null) + const handleFileOpenStart = useCallback(() => { + fileOpenStartActiveTabIdRef.current = activeSessionTabIdRef.current + }, []) + const handleOpenedFileDiff = useCallback( + (relativePath: string) => { + const activationSeq = ++handleOpenedFileDiffActivationSeqRef.current + const activeTabIdAtTap = fileOpenStartActiveTabIdRef.current + + let activated = false + const activateOpenedTab = async (): Promise => { + // Route matching through the shared helper so the deterministic repro + // test exercises the same logic production runs. + const settled = await activateOpenedSourceControlDiffTab({ + relativePath, + activeTabIdAtTap, + fetchSessionTabs, + getTabs: () => sessionTabsRef.current, + getActiveTabId: () => activeSessionTabIdRef.current, + getActivationState: () => ({ + activated, + activationSeq, + latestActivationSeq: handleOpenedFileDiffActivationSeqRef.current + }), + switchSessionTab: (tab) => switchSessionTabRef.current?.(tab) + }) + if (settled) { + activated = true + } + } + + scheduleDelayedAction(() => void activateOpenedTab(), 300) + scheduleDelayedAction(() => void activateOpenedTab(), 900) + scheduleDelayedAction(() => void activateOpenedTab(), 1800) + }, + [fetchSessionTabs, scheduleDelayedAction] + ) + const handleTerminalOpenUrl = useCallback( (handle: string, url: string) => { if (handle !== activeHandleRef.current) { @@ -5199,6 +5242,8 @@ export default function SessionScreen() { branchContextLoaded={prContextLoaded && prRepoContextLoaded} availableWidth={sessionContentRowWidth} onRequestClose={() => setActivePanel(null)} + onFileOpenStart={handleFileOpenStart} + onOpenedFileDiff={handleOpenedFileDiff} /> )} diff --git a/mobile/app/h/_layout.tsx b/mobile/app/h/_layout.tsx index b8849edc3..7c7d1cc89 100644 --- a/mobile/app/h/_layout.tsx +++ b/mobile/app/h/_layout.tsx @@ -46,7 +46,7 @@ function HostStack({ animation }: { animation: 'none' | 'default' }) { name="[hostId]/source-control/[worktreeId]" options={{ title: 'Source Control' }} /> - + ) diff --git a/mobile/src/components/MobileDiffReviewHeader.tsx b/mobile/src/components/MobileDiffReviewHeader.tsx index 2feb51591..5f89f2950 100644 --- a/mobile/src/components/MobileDiffReviewHeader.tsx +++ b/mobile/src/components/MobileDiffReviewHeader.tsx @@ -55,7 +55,7 @@ export function MobileDiffReviewHeader({ - Review Changes + Changes {worktreeLabel} diff --git a/mobile/src/session/SessionDockColumn.tsx b/mobile/src/session/SessionDockColumn.tsx index 877973e5d..f02e89f73 100644 --- a/mobile/src/session/SessionDockColumn.tsx +++ b/mobile/src/session/SessionDockColumn.tsx @@ -24,6 +24,8 @@ type Props = { branchContextLoaded: boolean availableWidth: number onRequestClose: () => void + onFileOpenStart?: () => void + onOpenedFileDiff?: (relativePath: string) => void } type DockPanelContentProps = Omit @@ -46,7 +48,9 @@ export function SessionDockColumn({ isGithubRepo, branchContextLoaded, availableWidth, - onRequestClose + onRequestClose, + onFileOpenStart, + onOpenedFileDiff }: Props) { const { dockWidth, panHandlers } = useMobileDockResize(availableWidth) return ( @@ -67,6 +71,8 @@ export function SessionDockColumn({ isGithubRepo={isGithubRepo} branchContextLoaded={branchContextLoaded} onRequestClose={onRequestClose} + onFileOpenStart={onFileOpenStart} + onOpenedFileDiff={onOpenedFileDiff} /> ) @@ -86,7 +92,9 @@ const DockPanelContent = memo(function DockPanelContent({ gitStatus, isGithubRepo, branchContextLoaded, - onRequestClose + onRequestClose, + onFileOpenStart, + onOpenedFileDiff }: DockPanelContentProps) { if (activePanel === 'sourceControl') { return ( @@ -97,6 +105,8 @@ const DockPanelContent = memo(function DockPanelContent({ origin="session" embedded onRequestClose={onRequestClose} + onFileOpenStart={onFileOpenStart} + onOpenedFileDiff={onOpenedFileDiff} /> ) } diff --git a/mobile/src/session/mobile-diff-review-positioning.test.ts b/mobile/src/session/mobile-diff-review-positioning.test.ts new file mode 100644 index 000000000..32fe37a82 --- /dev/null +++ b/mobile/src/session/mobile-diff-review-positioning.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { + createMobileDiffReviewFileKey, + filterMobileDiffReviewQueue, + type MobileDiffReviewQueueItem +} from './mobile-diff-review-queue' +import { findMobileDiffReviewInitialIndex } from './mobile-diff-review-positioning' + +function item( + filePath: string, + area: MobileDiffReviewQueueItem['area'], + oldPath?: string +): MobileDiffReviewQueueItem { + const scope = area === 'staged' || area === 'branch' ? area : 'unstaged' + return { + key: createMobileDiffReviewFileKey(scope, area, filePath, oldPath), + scope, + area, + filePath, + oldPath, + status: oldPath ? 'renamed' : area === 'untracked' ? 'untracked' : 'modified', + title: filePath, + subtitle: scope, + canStage: area === 'unstaged' || area === 'untracked', + canUnstage: area === 'staged', + canDiscard: area !== 'staged' && area !== 'branch', + isGeneratedOrLockFile: false, + diffIdentity: `diff:${filePath}`, + noteCount: 0, + unsentNoteCount: 0, + staleNoteCount: 0, + isReviewed: false, + changedSinceReview: false + } +} + +describe('mobile diff review positioning', () => { + it('selects an untracked file without changing the all-files filter', () => { + const queue = [ + item('a.ts', 'unstaged'), + item('new file.ts', 'untracked'), + item('b.ts', 'staged') + ] + const filtered = filterMobileDiffReviewQueue(queue, 'all') + + expect( + findMobileDiffReviewInitialIndex(filtered, { + filePath: 'new file.ts', + area: 'untracked' + }) + ).toBe(1) + expect(filtered).toHaveLength(3) + }) + + it('matches renamed files by oldPath through the queue key', () => { + const queue = [item('new.ts', 'branch', 'old.ts'), item('other.ts', 'branch')] + + expect( + findMobileDiffReviewInitialIndex(queue, { + filePath: 'old.ts', + area: 'branch' + }) + ).toBe(0) + }) + + it('falls back to the first file when the target is missing', () => { + const queue = [item('a.ts', 'unstaged'), item('b.ts', 'staged')] + + expect( + findMobileDiffReviewInitialIndex(queue, { + filePath: 'missing.ts', + area: 'unstaged' + }) + ).toBe(0) + }) +}) diff --git a/mobile/src/session/mobile-diff-review-positioning.ts b/mobile/src/session/mobile-diff-review-positioning.ts new file mode 100644 index 000000000..afb03381a --- /dev/null +++ b/mobile/src/session/mobile-diff-review-positioning.ts @@ -0,0 +1,66 @@ +import type { DiffReviewScope } from '../../../src/shared/types' +import type { MobileGitStagingArea } from '../source-control/mobile-git-status' +import { + createMobileDiffReviewFileKey, + type MobileDiffReviewQueueItem +} from './mobile-diff-review-queue' + +export type MobileDiffReviewTargetArea = MobileGitStagingArea | 'branch' + +export type MobileDiffReviewInitialTarget = { + filePath: string + area: MobileDiffReviewTargetArea +} + +const VALID_TARGET_AREAS = new Set([ + 'unstaged', + 'untracked', + 'staged', + 'branch' +]) + +function scopeForTargetArea(area: MobileDiffReviewTargetArea): DiffReviewScope { + return area === 'staged' || area === 'branch' ? area : 'unstaged' +} + +export function normalizeReviewAreaParam(value: string): MobileDiffReviewTargetArea | null { + return VALID_TARGET_AREAS.has(value as MobileDiffReviewTargetArea) + ? (value as MobileDiffReviewTargetArea) + : null +} + +export function reviewInitialTargetKey( + target: MobileDiffReviewInitialTarget, + oldPath?: string +): string { + return createMobileDiffReviewFileKey( + scopeForTargetArea(target.area), + target.area, + target.filePath, + oldPath + ) +} + +export function findMobileDiffReviewInitialIndex( + queue: readonly MobileDiffReviewQueueItem[], + target: MobileDiffReviewInitialTarget | null +): number { + if (!target || queue.length === 0) { + return 0 + } + const index = queue.findIndex((item) => { + if (item.area !== target.area) { + return false + } + if (item.filePath === target.filePath) { + return item.key === reviewInitialTargetKey(target, item.oldPath) + } + if (item.oldPath === target.filePath) { + return ( + item.key === reviewInitialTargetKey({ ...target, filePath: item.filePath }, item.oldPath) + ) + } + return false + }) + return Math.max(index, 0) +} diff --git a/mobile/src/session/opened-mobile-session-tab.test.ts b/mobile/src/session/opened-mobile-session-tab.test.ts index 104ee312b..988a3ea31 100644 --- a/mobile/src/session/opened-mobile-session-tab.test.ts +++ b/mobile/src/session/opened-mobile-session-tab.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { activateOpenedMobileSessionTab, + activateOpenedSourceControlDiffTab, findOpenedMobileSessionTab, refreshOpenedMobileSessionTabs, shouldActivateOpenedMobileSessionTab, @@ -43,6 +44,15 @@ describe('findOpenedMobileSessionTab', () => { expect(findOpenedMobileSessionTab(tabs, 'assets/logo.png')?.id).toBe('image-1') }) + it('matches a diff tab opened from mobile source control', () => { + const tabs: OpenedMobileSessionTabCandidate[] = [ + { type: 'terminal', id: 'term' }, + { type: 'file', id: 'diff-1', mode: 'diff', relativePath: 'src/app.ts' } + ] + + expect(findOpenedMobileSessionTab(tabs, 'src/app.ts')?.id).toBe('diff-1') + }) + it('skips diff tabs when an edit tab has the same relative path', () => { const tabs: OpenedMobileSessionTabCandidate[] = [ { type: 'file', id: 'diff-1', mode: 'diff', relativePath: 'src/app.ts' }, @@ -51,6 +61,15 @@ describe('findOpenedMobileSessionTab', () => { expect(findOpenedMobileSessionTab(tabs, 'src/app.ts')?.id).toBe('edit-1') }) + + it('can prefer a diff tab when source control just opened one', () => { + const tabs: OpenedMobileSessionTabCandidate[] = [ + { type: 'markdown', id: 'edit-1', relativePath: 'README.md' }, + { type: 'file', id: 'diff-1', mode: 'diff', relativePath: 'README.md' } + ] + + expect(findOpenedMobileSessionTab(tabs, 'README.md', { preferMode: 'diff' })?.id).toBe('diff-1') + }) }) describe('refreshOpenedMobileSessionTabs', () => { @@ -188,6 +207,130 @@ describe('activateOpenedMobileSessionTab', () => { }) }) +describe('activateOpenedSourceControlDiffTab', () => { + const diffTab = { type: 'file', id: 'diff-1', mode: 'diff', relativePath: 'src/app.ts' } + + function createSourceControlHarness() { + let tabs: OpenedMobileSessionTabCandidate[] = [] + let activeTabId: string | null = 'terminal-1' + let activated = false + const activationSeq = 1 + let latestActivationSeq = 1 + const switched: string[] = [] + return { + setTabs(nextTabs: OpenedMobileSessionTabCandidate[]) { + tabs = nextTabs + }, + setActiveTabId(id: string | null) { + activeTabId = id + }, + markActivated() { + activated = true + }, + supersedeActivation() { + latestActivationSeq += 1 + }, + options(fetchSessionTabs: () => Promise) { + return { + relativePath: 'src/app.ts', + activeTabIdAtTap: 'terminal-1' as string | null, + fetchSessionTabs, + getTabs: () => tabs, + getActiveTabId: () => activeTabId, + getActivationState: () => ({ activated, activationSeq, latestActivationSeq }), + switchSessionTab: (tab: OpenedMobileSessionTabCandidate) => { + activeTabId = tab.id + switched.push(tab.id) + } + } + }, + switched + } + } + + it('refreshes tabs and switches to the opened diff tab', async () => { + const harness = createSourceControlHarness() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([diffTab]) + }) + ) + + expect(settled).toBe(true) + expect(harness.switched).toEqual(['diff-1']) + }) + + it('prefers the opened diff over an existing edit tab for the same path', async () => { + const harness = createSourceControlHarness() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([{ type: 'markdown', id: 'edit-1', relativePath: 'src/app.ts' }, diffTab]) + }) + ) + + expect(settled).toBe(true) + expect(harness.switched).toEqual(['diff-1']) + }) + + it('settles without switching when the snapshot already made the diff active', async () => { + const harness = createSourceControlHarness() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([diffTab]) + harness.setActiveTabId('diff-1') + }) + ) + + expect(settled).toBe(true) + expect(harness.switched).toEqual([]) + }) + + it('does not steal focus when the user moved to a different tab after the tap', async () => { + const harness = createSourceControlHarness() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([diffTab]) + harness.setActiveTabId('terminal-2') + }) + ) + + expect(settled).toBe(false) + expect(harness.switched).toEqual([]) + }) + + it('does not switch when a newer tap supersedes this attempt during refresh', async () => { + const harness = createSourceControlHarness() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([diffTab]) + harness.supersedeActivation() + }) + ) + + expect(settled).toBe(false) + expect(harness.switched).toEqual([]) + }) + + it('stops retrying after an earlier attempt already activated the tab', async () => { + const harness = createSourceControlHarness() + harness.markActivated() + + const settled = await activateOpenedSourceControlDiffTab( + harness.options(async () => { + harness.setTabs([diffTab]) + }) + ) + + expect(settled).toBe(false) + expect(harness.switched).toEqual([]) + }) +}) + describe('shouldActivateOpenedMobileSessionTab', () => { const currentTerminalState = { activationSeq: 2, diff --git a/mobile/src/session/opened-mobile-session-tab.ts b/mobile/src/session/opened-mobile-session-tab.ts index 16cecb0f3..17c8cff98 100644 --- a/mobile/src/session/opened-mobile-session-tab.ts +++ b/mobile/src/session/opened-mobile-session-tab.ts @@ -40,17 +40,75 @@ export async function refreshOpenedMobileSessionTabs( export function findOpenedMobileSessionTab( tabs: readonly T[], - relativePath: string + relativePath: string, + options: { preferMode?: 'diff' | 'edit' } = {} ): T | null { - return ( - tabs.find( - (tab) => - tab.type !== 'browser' && - tab.type !== 'terminal' && - tab.mode !== 'diff' && - tab.relativePath === relativePath - ) ?? null + const matches = tabs.filter( + (tab) => tab.type !== 'browser' && tab.type !== 'terminal' && tab.relativePath === relativePath ) + if (matches.length === 0) { + return null + } + if (options.preferMode === 'diff') { + return matches.find((tab) => tab.mode === 'diff') ?? matches[0] ?? null + } + return matches.find((tab) => tab.mode !== 'diff') ?? matches[0] ?? null +} + +export type OpenedSourceControlDiffActivationState = { + activated: boolean + activationSeq: number + latestActivationSeq: number +} + +export type ActivateOpenedSourceControlDiffTabOptions = { + relativePath: string + activeTabIdAtTap: string | null + fetchSessionTabs: () => Promise + getTabs: () => readonly T[] + getActiveTabId: () => string | null + getActivationState: () => OpenedSourceControlDiffActivationState + switchSessionTab: (tab: T) => void +} + +// Activation for a diff tab opened by tapping a changed file in the docked +// source-control panel. Unlike the terminal path there is no "source terminal" +// to guard against; instead we cancel if the user moved to a different tab +// after the tap (no focus steal) and treat the diff already being active as +// success. Returns true once activation is settled so retries can stop. +export async function activateOpenedSourceControlDiffTab( + options: ActivateOpenedSourceControlDiffTabOptions +): Promise { + const isSuperseded = (): boolean => { + const state = options.getActivationState() + return state.activated || state.activationSeq !== state.latestActivationSeq + } + if (isSuperseded()) { + return false + } + await options.fetchSessionTabs() + if (isSuperseded()) { + return false + } + const opened = findOpenedMobileSessionTab(options.getTabs(), options.relativePath, { + preferMode: 'diff' + }) + if (!opened) { + return false + } + const activeTabId = options.getActiveTabId() + // The post-open snapshot may already show the opened diff as active; that is + // success, not a focus steal, so settle without re-activating. + if (activeTabId === opened.id) { + return true + } + // No focus steal: if the user moved to a different tab after the tap, leave + // them there instead of yanking focus back to the diff. + if (activeTabId !== options.activeTabIdAtTap) { + return false + } + options.switchSessionTab(opened) + return true } export function shouldActivateOpenedMobileSessionTab( diff --git a/mobile/src/session/use-mobile-diff-review-controller.ts b/mobile/src/session/use-mobile-diff-review-controller.ts index cc19fb73e..5b1b5fcf9 100644 --- a/mobile/src/session/use-mobile-diff-review-controller.ts +++ b/mobile/src/session/use-mobile-diff-review-controller.ts @@ -12,6 +12,10 @@ import { type MobileDiffReviewQueueFilter, type MobileDiffReviewQueueItem } from './mobile-diff-review-queue' +import { + findMobileDiffReviewInitialIndex, + type MobileDiffReviewInitialTarget +} from './mobile-diff-review-positioning' import { loadMobileDiffReviewDiff, loadMobileDiffReviewSnapshot @@ -34,15 +38,27 @@ type ControllerInput = { worktreeId: string name: string initialFilter: MobileDiffReviewQueueFilter + initialTarget: MobileDiffReviewInitialTarget | null onOpenSession: () => void onReconnect: (hostId: string) => void | Promise } export function useMobileDiffReviewController(input: ControllerInput) { - const { client, connState, hostId, worktreeId, name, initialFilter, onOpenSession, onReconnect } = - input + const { + client, + connState, + hostId, + worktreeId, + name, + initialFilter, + initialTarget, + onOpenSession, + onReconnect + } = input const listRef = useRef | null>(null) const loadGenerationRef = useRef(0) + const seededInitialTargetRef = useRef(false) + const initialTargetKey = initialTarget ? `${initialTarget.area}\0${initialTarget.filePath}` : '' const [screenState, setScreenState] = useState({ kind: 'loading' }) const [diffState, setDiffState] = useState({ kind: 'idle' }) const [filter, setFilter] = useState(initialFilter) @@ -120,6 +136,20 @@ export function useMobileDiffReviewController(input: ControllerInput) { (item) => item.scope === 'unstaged' && item.isReviewed && item.canStage ).length + useEffect(() => { + seededInitialTargetRef.current = false + }, [initialTargetKey]) + + useEffect(() => { + if (seededInitialTargetRef.current || filteredQueue.length === 0) { + return + } + seededInitialTargetRef.current = true + // Why: review data loads asynchronously; seed the tapped file only after the + // first real queue exists so the clamp effect cannot reset it back to zero. + setCurrentIndex(findMobileDiffReviewInitialIndex(filteredQueue, initialTarget)) + }, [filteredQueue, initialTarget]) + useEffect(() => { if (filteredQueue.length === 0) { setCurrentIndex(0) diff --git a/mobile/src/source-control/MobileSourceControlContent.tsx b/mobile/src/source-control/MobileSourceControlContent.tsx index 9febe74bf..8a209d361 100644 --- a/mobile/src/source-control/MobileSourceControlContent.tsx +++ b/mobile/src/source-control/MobileSourceControlContent.tsx @@ -1,7 +1,7 @@ import { ActivityIndicator, Pressable, SectionList, Text, TextInput, View } from 'react-native' import { GitBranch, Minus, MoreHorizontal, Plus, Sparkles } from 'lucide-react-native' import { colors, spacing } from '../theme/mobile-theme' -import { MobileSourceControlReviewEntry } from './mobile-source-control-review-entry' +import { MobileSourceControlCreatePrEntry } from './MobileSourceControlCreatePrEntry' import { MobileCommitFailurePanel } from './MobileCommitFailurePanel' import { KEYBOARD_COMMIT_BAR_CLEARANCE } from './mobile-source-control-screen-state' import { makeRenderFileRow, BranchCompareFooter } from './MobileSourceControlFileRows' @@ -10,17 +10,12 @@ import { styles } from './mobile-source-control-styles' type Props = { state: MobileSourceControlState - hostId: string - worktreeId: string - name: string } // The ready-state body: summary card, changed-files list, and commit bar. -export function MobileSourceControlContent({ state, hostId, worktreeId, name }: Props) { +export function MobileSourceControlContent({ state }: Props) { const { - connState, insets, - screenState, busyAction, commitMessage, setCommitMessage, @@ -37,7 +32,6 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: sections, branchEntries, hasVisibleChanges, - reviewableCount, stageablePaths, unstageablePaths, stagedCount, @@ -45,6 +39,7 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: branchLabel, syncLabel, primaryAction, + createPrAction, stageAll, unstageAll, generateCommitMessage, @@ -56,6 +51,7 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: } = state const ioBusy = busyAction !== null || openingPath !== null || openingBranchPath !== null const shouldShowGenerateButton = stagedCount > 0 || generatingMessage + const createPrHeroActive = createPrAction.visible && !createPrAction.disabled return ( <> @@ -106,13 +102,7 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: ) : null} - + [ @@ -265,6 +255,7 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: [ styles.commitButton, + createPrHeroActive && styles.commitButtonSecondary, primaryAction.disabled && styles.commitButtonDisabled, pressed && styles.commitButtonPressed ]} @@ -274,9 +265,19 @@ export function MobileSourceControlContent({ state, hostId, worktreeId, name }: accessibilityHint={primaryAction.accessibilityHint} > {primaryAction.loading ? ( - + ) : ( - {primaryAction.label} + + {primaryAction.label} + )} diff --git a/mobile/src/source-control/MobileSourceControlCreatePrEntry.tsx b/mobile/src/source-control/MobileSourceControlCreatePrEntry.tsx new file mode 100644 index 000000000..7d14270cc --- /dev/null +++ b/mobile/src/source-control/MobileSourceControlCreatePrEntry.tsx @@ -0,0 +1,53 @@ +import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { GitPullRequestArrow } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import type { MobileCreatePrAction } from './mobile-create-pr-action' +import { styles } from './mobile-source-control-styles' + +type Props = { + action: MobileCreatePrAction +} + +export function MobileSourceControlCreatePrEntry({ action }: Props) { + if (!action.visible) { + return null + } + const enabled = !action.disabled + return ( + + [ + styles.createPrButton, + !enabled && styles.createPrButtonDisabled, + pressed && enabled && styles.createPrButtonPressed + ]} + disabled={action.disabled} + onPress={action.onPress} + accessibilityRole="button" + accessibilityLabel={action.label} + accessibilityHint={action.hint} + > + {action.loading ? ( + + ) : ( + + )} + + {action.label} + + + {action.hint ? ( + + {action.hint} + + ) : null} + + ) +} diff --git a/mobile/src/source-control/MobileSourceControlFileRows.tsx b/mobile/src/source-control/MobileSourceControlFileRows.tsx index e29a6bf3c..8d6f6354b 100644 --- a/mobile/src/source-control/MobileSourceControlFileRows.tsx +++ b/mobile/src/source-control/MobileSourceControlFileRows.tsx @@ -1,5 +1,5 @@ import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { FileText, Minus, Plus, Trash2 } from 'lucide-react-native' +import { ChevronRight, FileText, Minus, Plus, Trash2 } from 'lucide-react-native' import type { SectionListRenderItem } from 'react-native' import { colors } from '../theme/mobile-theme' import { MOBILE_GIT_STATUS_LABELS, type MobileSourceControlSection } from './mobile-git-status' @@ -128,6 +128,9 @@ export function makeRenderFileRow( ) : null} ) : null} + {!rowBusy && item.canOpen ? ( + + ) : null} ) } @@ -235,7 +238,11 @@ export function BranchCompareFooter({ state }: { state: FooterState }) { ) : null} - {rowBusy ? : null} + {rowBusy ? ( + + ) : entry.canOpen ? ( + + ) : null} ) }) diff --git a/mobile/src/source-control/MobileSourceControlPanel.tsx b/mobile/src/source-control/MobileSourceControlPanel.tsx index 49bdf92ff..256cb9c0a 100644 --- a/mobile/src/source-control/MobileSourceControlPanel.tsx +++ b/mobile/src/source-control/MobileSourceControlPanel.tsx @@ -16,6 +16,8 @@ export type MobileSourceControlPanelProps = { origin?: string embedded?: boolean onRequestClose?: () => void + onFileOpenStart?: () => void + onOpenedFileDiff?: (relativePath: string) => void } export function MobileSourceControlPanel({ @@ -24,7 +26,9 @@ export function MobileSourceControlPanel({ name = '', origin = '', embedded = false, - onRequestClose + onRequestClose, + onFileOpenStart, + onOpenedFileDiff }: MobileSourceControlPanelProps) { const state = useMobileSourceControlState({ hostId, @@ -32,7 +36,9 @@ export function MobileSourceControlPanel({ name, origin, embedded, - onRequestClose + onRequestClose, + onFileOpenStart, + onOpenedFileDiff }) const actionSheetActions = useMobileSourceControlActionSheet(state) const { @@ -104,12 +110,7 @@ export function MobileSourceControlPanel({ ) : null} ) : ( - + )} diff --git a/mobile/src/source-control/mobile-create-pr-action.test.ts b/mobile/src/source-control/mobile-create-pr-action.test.ts new file mode 100644 index 000000000..99b86cc85 --- /dev/null +++ b/mobile/src/source-control/mobile-create-pr-action.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it, vi } from 'vitest' +import type { + HostedReviewCreationBlockedReason, + HostedReviewCreationEligibility, + HostedReviewProvider +} from '../../../src/shared/hosted-review' +import { buildMobileCreatePrAction } from './mobile-create-pr-action' + +function eligibility( + overrides: Partial = {} +): HostedReviewCreationEligibility { + return { + provider: 'github', + review: null, + canCreate: true, + blockedReason: null, + nextAction: null, + defaultBaseRef: 'main', + title: 'feature', + body: '', + ...overrides + } +} + +function action( + overrides: { + branch?: string | null + eligibility?: HostedReviewCreationEligibility | null + busyAction?: string | null + } = {} +) { + const onCreatePr = vi.fn() + const descriptor = buildMobileCreatePrAction({ + branch: Object.hasOwn(overrides, 'branch') ? overrides.branch : 'feature', + eligibilityState: + overrides.eligibility === null + ? { kind: 'error' } + : { kind: 'ready', eligibility: overrides.eligibility ?? eligibility() }, + busyAction: overrides.busyAction ?? null, + onCreatePr + }) + return { descriptor, onCreatePr } +} + +describe('buildMobileCreatePrAction', () => { + it('enables create when eligibility can create', () => { + const { descriptor, onCreatePr } = action() + + expect(descriptor).toMatchObject({ + visible: true, + label: 'Create Pull Request', + disabled: false, + pushFirst: false + }) + descriptor.onPress() + expect(onCreatePr).toHaveBeenCalledWith(false) + }) + + it('uses merge-request copy for GitLab', () => { + const { descriptor } = action({ + eligibility: eligibility({ provider: 'gitlab' as HostedReviewProvider }) + }) + + expect(descriptor.label).toBe('Create Merge Request') + }) + + it('enables push-first creation when the branch needs push', () => { + const { descriptor, onCreatePr } = action({ + eligibility: eligibility({ + canCreate: false, + blockedReason: 'needs_push', + nextAction: 'push' + }) + }) + + expect(descriptor).toMatchObject({ visible: true, disabled: false, pushFirst: true }) + descriptor.onPress() + expect(onCreatePr).toHaveBeenCalledWith(true) + }) + + it.each([ + 'dirty', + 'no_upstream', + 'needs_sync', + 'default_branch', + 'auth_required' + ])('shows a disabled hinted action for locally actionable %s', (blockedReason) => { + const { descriptor } = action({ + eligibility: eligibility({ canCreate: false, blockedReason }) + }) + + expect(descriptor.visible).toBe(true) + expect(descriptor.disabled).toBe(true) + expect(descriptor.hint).toBeTruthy() + }) + + it('falls back to a disabled hinted action for other reachable blocked reasons', () => { + const { descriptor } = action({ + eligibility: eligibility({ canCreate: false, blockedReason: 'fork_head_unsupported' }) + }) + + expect(descriptor).toMatchObject({ visible: true, disabled: true }) + expect(descriptor.hint).toContain('fork') + }) + + it.each([ + 'existing_review', + 'unsupported_provider', + 'detached_head', + null + ])('hides %s', (blockedReason) => { + const { descriptor } = action({ + eligibility: eligibility({ canCreate: false, blockedReason }) + }) + + expect(descriptor.visible).toBe(false) + }) + + it('hides cold loading, errors, and missing branches', () => { + const onCreatePr = vi.fn() + + expect( + buildMobileCreatePrAction({ + branch: 'feature', + eligibilityState: { kind: 'loading', eligibility: null }, + busyAction: null, + onCreatePr + }).visible + ).toBe(false) + expect(action({ eligibility: null }).descriptor.visible).toBe(false) + expect(action({ branch: null }).descriptor.visible).toBe(false) + }) + + it('shows an in-flight spinner and disables the current action', () => { + const { descriptor } = action({ busyAction: 'create-pr' }) + + expect(descriptor).toMatchObject({ visible: true, disabled: true, loading: true }) + }) + + it('disables without a spinner during unrelated git work', () => { + const { descriptor, onCreatePr } = action({ busyAction: 'stage-all' }) + + expect(descriptor).toMatchObject({ visible: true, disabled: true, loading: false }) + descriptor.onPress() + // disabled is honored by the Pressable; onPress itself is a no-op guard here + expect(onCreatePr).not.toHaveBeenCalled() + }) + + it('hides any provider that does not support hosted-review creation', () => { + const { descriptor } = action({ + eligibility: eligibility({ provider: 'bitbucket' as HostedReviewProvider }) + }) + + expect(descriptor.visible).toBe(false) + }) + + it('keeps a creatable button visible but disabled while a newer eligibility loads', () => { + const onCreatePr = vi.fn() + const descriptor = buildMobileCreatePrAction({ + branch: 'feature', + // stale ready snapshot retained during the next request: chrome stays, action does not fire + eligibilityState: { kind: 'loading', eligibility: eligibility({ canCreate: true }) }, + busyAction: null, + onCreatePr + }) + + expect(descriptor).toMatchObject({ visible: true, disabled: true, loading: false }) + }) +}) diff --git a/mobile/src/source-control/mobile-create-pr-action.ts b/mobile/src/source-control/mobile-create-pr-action.ts new file mode 100644 index 000000000..0636fc015 --- /dev/null +++ b/mobile/src/source-control/mobile-create-pr-action.ts @@ -0,0 +1,122 @@ +import type { + HostedReviewCreationBlockedReason, + HostedReviewCreationEligibility +} from '../../../src/shared/hosted-review' +import { supportsHostedReviewCreation } from '../../../src/shared/hosted-review-creation-providers' +import { hostedReviewCopy } from './hosted-review-copy' +import { getMobilePrCreateBlockMessage } from './mobile-pr-create' + +export type MobileCreatePrEligibilityState = + | { kind: 'idle' } + | { kind: 'loading'; eligibility: HostedReviewCreationEligibility | null } + | { kind: 'ready'; eligibility: HostedReviewCreationEligibility } + | { kind: 'error' } + +export type MobileCreatePrAction = { + visible: boolean + label: string + disabled: boolean + hint?: string + loading: boolean + pushFirst: boolean + onPress: () => void +} + +export type BuildMobileCreatePrActionArgs = { + branch: string | null | undefined + eligibilityState: MobileCreatePrEligibilityState + busyAction: string | null + onCreatePr: (pushFirst: boolean) => void +} + +const HIDDEN_BLOCKED_REASONS = new Set([ + 'detached_head', + 'existing_review', + 'unsupported_provider', + null +]) + +const BUSY_ACTIONS = new Set(['create-pr', 'push-create-pr']) + +function hiddenAction(onPress: () => void): MobileCreatePrAction { + return { + visible: false, + label: 'Create Pull Request', + disabled: true, + loading: false, + pushFirst: false, + onPress + } +} + +export function buildMobileCreatePrAction({ + branch, + eligibilityState, + busyAction, + onCreatePr +}: BuildMobileCreatePrActionArgs): MobileCreatePrAction { + const noop = () => {} + if (!branch || eligibilityState.kind === 'idle' || eligibilityState.kind === 'error') { + return hiddenAction(noop) + } + const eligibility = eligibilityState.eligibility + if (!eligibility) { + return hiddenAction(noop) + } + // Why: mirror desktop's structural provider gate (supportsHostedReviewCreation) + // instead of relying on the host always emitting a hidden blockedReason for + // non-creatable providers like bitbucket. + if (!supportsHostedReviewCreation(eligibility.provider)) { + return hiddenAction(noop) + } + const copy = hostedReviewCopy(eligibility.provider) + const label = `Create ${copy.titleLabel}` + // Any in-flight git work blocks the action: runGitWorkflow no-ops while + // busyActionRef is set, so an enabled-looking button would silently do nothing. + const busy = busyAction !== null + const loading = busyAction !== null && BUSY_ACTIONS.has(busyAction) + // Why: while a newer eligibility request is loading we keep the prior ready + // snapshot for stable chrome, but must not act on it — treat stale-loading as + // disabled so a tap cannot fire against an out-of-date canCreate/pushFirst. + const stale = eligibilityState.kind === 'loading' + const pushFirst = eligibility.blockedReason === 'needs_push' + + if (eligibility.canCreate || pushFirst) { + const disabled = busy || stale + return { + visible: true, + label, + disabled, + loading, + pushFirst, + // Why: never hand a disabled descriptor a live handler — a tap must be a + // true no-op when busy/stale, not a deferred create against stale state. + onPress: disabled ? noop : () => onCreatePr(pushFirst) + } + } + + if (HIDDEN_BLOCKED_REASONS.has(eligibility.blockedReason)) { + return hiddenAction(noop) + } + + const hint = + getMobilePrCreateBlockMessage({ + provider: eligibility.provider, + base: eligibility.defaultBaseRef || 'main', + title: eligibility.title || branch, + body: eligibility.body || '', + canCreate: false, + blockedReason: eligibility.blockedReason, + nextAction: eligibility.nextAction + }) ?? `This branch is not ready for a ${copy.reviewLabel} yet.` + + return { + visible: true, + label, + disabled: true, + hint, + loading, + pushFirst: false, + onPress: noop + } +} diff --git a/mobile/src/source-control/mobile-review-route.test.ts b/mobile/src/source-control/mobile-review-route.test.ts new file mode 100644 index 000000000..8334092cf --- /dev/null +++ b/mobile/src/source-control/mobile-review-route.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { firstReviewParam } from '../session/mobile-diff-review-screen-model' +import { buildMobileReviewFileRoute, type MobileReviewRouteArea } from './mobile-review-route' + +function queryParams(route: string): URLSearchParams { + const query = route.split('?')[1] ?? '' + return new URLSearchParams(query) +} + +describe('buildMobileReviewFileRoute', () => { + it.each(['docs/a&b.md', 'foo#bar.ts', 'path with space.ts', 'src/üñî.ts'])( + 'round-trips file param %s', + (filePath) => { + const route = buildMobileReviewFileRoute({ + hostId: 'host/id', + worktreeId: 'repo::work tree', + worktreeName: 'My Repo', + filePath, + area: 'unstaged' + }) + const params = queryParams(route) + + expect(route).toContain('/h/host%2Fid/review/repo%3A%3Awork%20tree?') + expect(firstReviewParam(params.get('file') ?? undefined)).toBe(filePath) + expect(firstReviewParam(params.get('area') ?? undefined)).toBe('unstaged') + expect(firstReviewParam(params.get('scope') ?? undefined)).toBe('all') + expect(firstReviewParam(params.get('name') ?? undefined)).toBe('My Repo') + } + ) + + it.each(['unstaged', 'untracked', 'staged', 'branch'])( + 'preserves true area %s', + (area) => { + const params = queryParams( + buildMobileReviewFileRoute({ + hostId: 'host', + worktreeId: 'wt', + worktreeName: '', + filePath: 'a.ts', + area + }) + ) + + expect(params.get('area')).toBe(area) + } + ) +}) diff --git a/mobile/src/source-control/mobile-review-route.ts b/mobile/src/source-control/mobile-review-route.ts new file mode 100644 index 000000000..ee0939a7c --- /dev/null +++ b/mobile/src/source-control/mobile-review-route.ts @@ -0,0 +1,27 @@ +import type { MobileGitStagingArea } from './mobile-git-status' + +export type MobileReviewRouteArea = MobileGitStagingArea | 'branch' + +export type MobileReviewRouteTarget = { + hostId: string + worktreeId: string + worktreeName: string + filePath: string + area: MobileReviewRouteArea +} + +export function buildMobileReviewFileRoute(target: MobileReviewRouteTarget): string { + const params = new URLSearchParams() + // Why: open the tapped file first (via file/area) while keeping the full + // changed-file queue so next/previous still walks every file — scope is the + // queue filter, not the position, so it stays 'all'. + params.set('scope', 'all') + params.set('file', target.filePath) + params.set('area', target.area) + if (target.worktreeName) { + params.set('name', target.worktreeName) + } + return `/h/${encodeURIComponent(target.hostId)}/review/${encodeURIComponent( + target.worktreeId + )}?${params.toString()}` +} diff --git a/mobile/src/source-control/mobile-source-control-list-styles.ts b/mobile/src/source-control/mobile-source-control-list-styles.ts index a6fcfc55b..8fd304e54 100644 --- a/mobile/src/source-control/mobile-source-control-list-styles.ts +++ b/mobile/src/source-control/mobile-source-control-list-styles.ts @@ -161,6 +161,11 @@ export const listStyles = StyleSheet.create({ justifyContent: 'center', paddingHorizontal: spacing.md }, + commitButtonSecondary: { + backgroundColor: 'transparent', + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle + }, generateButton: { width: 42, minHeight: 42, @@ -180,6 +185,9 @@ export const listStyles = StyleSheet.create({ fontSize: typography.bodySize, fontWeight: '700' }, + commitButtonSecondaryText: { + color: colors.textPrimary + }, commitFailurePanel: { marginTop: spacing.sm, padding: spacing.sm, diff --git a/mobile/src/source-control/mobile-source-control-review-entry.tsx b/mobile/src/source-control/mobile-source-control-review-entry.tsx deleted file mode 100644 index 6d823d2c0..000000000 --- a/mobile/src/source-control/mobile-source-control-review-entry.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import { useCallback } from 'react' -import { useRouter } from 'expo-router' -import { FileText } from 'lucide-react-native' -import { Pressable, StyleSheet, Text } from 'react-native' -import { colors, radii, spacing, typography } from '../theme/mobile-theme' - -type MobileSourceControlReviewEntryProps = { - readonly count: number - readonly disabled: boolean - readonly hostId: string - readonly worktreeId: string - readonly worktreeName: string -} - -export function MobileSourceControlReviewEntry({ - count, - disabled, - hostId, - worktreeId, - worktreeName -}: MobileSourceControlReviewEntryProps) { - const router = useRouter() - const canOpenReview = count > 0 && !disabled - - const openReviewChanges = useCallback(() => { - if (!canOpenReview) { - return - } - const params = new URLSearchParams() - params.set('scope', 'all') - params.set('origin', 'source-control') - if (worktreeName) { - params.set('name', worktreeName) - } - const query = params.toString() - router.push( - `/h/${encodeURIComponent(hostId)}/review/${encodeURIComponent(worktreeId)}?${query}` - ) - }, [canOpenReview, hostId, router, worktreeId, worktreeName]) - - return ( - [ - styles.button, - !canOpenReview && styles.disabled, - pressed && canOpenReview && styles.pressed - ]} - onPress={openReviewChanges} - disabled={!canOpenReview} - accessibilityRole="button" - accessibilityLabel="Review changes" - > - - Review Changes - {count} - - ) -} - -const styles = StyleSheet.create({ - button: { - minHeight: 42, - borderRadius: radii.button, - backgroundColor: colors.textPrimary, - alignItems: 'center', - justifyContent: 'center', - flexDirection: 'row', - gap: spacing.xs, - marginTop: spacing.md, - paddingHorizontal: spacing.md - }, - disabled: { - opacity: 0.45 - }, - pressed: { - opacity: 0.78 - }, - text: { - color: colors.bgBase, - fontSize: typography.bodySize, - fontWeight: '700' - }, - count: { - marginLeft: spacing.xs, - color: colors.textMuted, - fontSize: typography.metaSize, - fontWeight: '700' - } -}) diff --git a/mobile/src/source-control/mobile-source-control-screen-state.ts b/mobile/src/source-control/mobile-source-control-screen-state.ts index 968196d4d..eb20cdaa3 100644 --- a/mobile/src/source-control/mobile-source-control-screen-state.ts +++ b/mobile/src/source-control/mobile-source-control-screen-state.ts @@ -19,10 +19,12 @@ import type { MobileGitBranchCompareResult, MobileGitBranchCompareSummary } from './mobile-branch-compare' -import type { - MobileGitFileStatus, - MobileGitStatusEntry, - MobileGitStatusResult +import { + isMobileGitDiscardableEntry, + isMobileGitStageableEntry, + type MobileGitFileStatus, + type MobileGitStatusEntry, + type MobileGitStatusResult } from './mobile-git-status' export type ScreenState = @@ -55,6 +57,23 @@ export type MobileGitStatusEntryView = MobileGitStatusEntry & { unstageActionId: string } +// Decorate raw status entries with the row-level capability/action-id fields the +// file list needs. Deleted/unresolved entries are not openable (matches the +// opener guards). +export function buildMobileGitStatusEntryViews( + entries: readonly MobileGitStatusEntry[] +): MobileGitStatusEntryView[] { + return 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}` + })) +} + export type MobileBranchCompareState = | { kind: 'idle' } | { kind: 'loading' } diff --git a/mobile/src/source-control/mobile-source-control-styles.ts b/mobile/src/source-control/mobile-source-control-styles.ts index 3535cef25..84dd6d166 100644 --- a/mobile/src/source-control/mobile-source-control-styles.ts +++ b/mobile/src/source-control/mobile-source-control-styles.ts @@ -172,6 +172,41 @@ const baseStyles = StyleSheet.create({ color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' + }, + createPrBlock: { + marginTop: spacing.md, + gap: spacing.xs + }, + createPrButton: { + minHeight: 42, + borderRadius: radii.button, + backgroundColor: colors.accentBlueCta, + alignItems: 'center', + justifyContent: 'center', + flexDirection: 'row', + gap: spacing.xs, + paddingHorizontal: spacing.md + }, + createPrButtonDisabled: { + backgroundColor: colors.bgRaised, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle + }, + createPrButtonPressed: { + opacity: 0.78 + }, + createPrButtonText: { + color: colors.onAccentBlue, + fontSize: typography.bodySize, + fontWeight: '700' + }, + createPrButtonTextDisabled: { + color: colors.textSecondary + }, + createPrHint: { + color: colors.textMuted, + fontSize: typography.metaSize, + lineHeight: 16 } }) diff --git a/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts b/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts new file mode 100644 index 000000000..cc1f4965d --- /dev/null +++ b/mobile/src/source-control/use-mobile-hosted-review-eligibility.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { + acceptsMobileHostedReviewEligibilityLoad, + buildMobileHostedReviewEligibilityLoadKey, + eligibilityStateAfterMobileHostedReviewError, + shouldFetchMobileHostedReviewEligibility +} from './use-mobile-hosted-review-eligibility' + +describe('mobile hosted review eligibility loader core', () => { + it('does not fetch while disconnected or detached', () => { + expect( + shouldFetchMobileHostedReviewEligibility({ + client: { sendRequest: async () => ({ ok: true }) } as never, + connState: 'disconnected', + branch: 'feature' + }) + ).toBe(false) + expect( + shouldFetchMobileHostedReviewEligibility({ + client: { sendRequest: async () => ({ ok: true }) } as never, + connState: 'connected', + branch: null + }) + ).toBe(false) + }) + + it('accepts only the latest generation for the current worktree branch identity', () => { + const first = buildMobileHostedReviewEligibilityLoadKey({ + worktreeId: 'wt-1', + branch: 'feature-a', + hasUpstream: true, + ahead: 0, + behind: 0, + hasUncommittedChanges: false + }) + const second = buildMobileHostedReviewEligibilityLoadKey({ + worktreeId: 'wt-1', + branch: 'feature-b', + hasUpstream: true, + ahead: 0, + behind: 0, + hasUncommittedChanges: false + }) + + expect( + acceptsMobileHostedReviewEligibilityLoad({ + generation: 1, + currentGeneration: 2, + identity: first.identity, + currentIdentity: second.identity + }) + ).toBe(false) + }) + + it('fails closed after errors', () => { + expect(eligibilityStateAfterMobileHostedReviewError()).toEqual({ kind: 'error' }) + }) +}) diff --git a/mobile/src/source-control/use-mobile-hosted-review-eligibility.ts b/mobile/src/source-control/use-mobile-hosted-review-eligibility.ts new file mode 100644 index 000000000..ff5a98c43 --- /dev/null +++ b/mobile/src/source-control/use-mobile-hosted-review-eligibility.ts @@ -0,0 +1,163 @@ +import { useEffect, useRef, useState } from 'react' +import type { HostedReviewCreationEligibility } from '../../../src/shared/hosted-review' +import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState } from '../transport/types' +import { + fetchMobileHostedReviewEligibility, + type MobileHostedReviewEligibilityInput +} from './mobile-hosted-review-service' +import type { MobileCreatePrEligibilityState } from './mobile-create-pr-action' + +export type MobileHostedReviewEligibilityLoaderInput = { + client: RpcClient | null + connState: ConnectionState + worktreeId: string + branch: string | null | undefined + hasUpstream: boolean | undefined + ahead: number | undefined + behind: number | undefined + hasUncommittedChanges: boolean +} + +export type MobileHostedReviewEligibilityLoadKey = { + identity: string + fetch: string +} + +export function buildMobileHostedReviewEligibilityLoadKey( + input: Omit +): MobileHostedReviewEligibilityLoadKey { + const branch = input.branch ?? '' + return { + identity: `${input.worktreeId}\0${branch}`, + fetch: [ + input.worktreeId, + branch, + String(input.hasUpstream ?? ''), + String(input.ahead ?? ''), + String(input.behind ?? ''), + String(input.hasUncommittedChanges) + ].join('\0') + } +} + +export function shouldFetchMobileHostedReviewEligibility( + input: Pick +): boolean { + return input.connState === 'connected' && input.client !== null && !!input.branch +} + +export function acceptsMobileHostedReviewEligibilityLoad(args: { + generation: number + currentGeneration: number + identity: string + currentIdentity: string +}): boolean { + return args.generation === args.currentGeneration && args.identity === args.currentIdentity +} + +export function eligibilityStateAfterMobileHostedReviewError(): MobileCreatePrEligibilityState { + return { kind: 'error' } +} + +export function useMobileHostedReviewEligibility( + input: MobileHostedReviewEligibilityLoaderInput +): MobileCreatePrEligibilityState { + const { + client, + connState, + worktreeId, + branch, + hasUpstream, + ahead, + behind, + hasUncommittedChanges + } = input + const shouldFetch = shouldFetchMobileHostedReviewEligibility({ client, connState, branch }) + const [state, setState] = useState({ kind: 'idle' }) + const generationRef = useRef(0) + const currentIdentityRef = useRef('') + const lastResetIdentityRef = useRef('') + const key = buildMobileHostedReviewEligibilityLoadKey({ + worktreeId, + branch, + hasUpstream, + ahead, + behind, + hasUncommittedChanges + }) + + if (lastResetIdentityRef.current !== key.identity) { + lastResetIdentityRef.current = key.identity + setState({ kind: 'idle' }) + } + currentIdentityRef.current = key.identity + + useEffect(() => { + const generation = generationRef.current + 1 + generationRef.current = generation + const isCurrent = () => + acceptsMobileHostedReviewEligibilityLoad({ + generation, + currentGeneration: generationRef.current, + identity: key.identity, + currentIdentity: currentIdentityRef.current + }) + + if (!shouldFetch) { + if (isCurrent()) { + setState({ kind: 'idle' }) + } + return + } + if (!client || !branch) { + return + } + + setState((prev) => ({ + kind: 'loading', + eligibility: prev.kind === 'ready' ? prev.eligibility : null + })) + const requestInput: MobileHostedReviewEligibilityInput = { + branch, + hasUncommittedChanges, + hasUpstream, + ahead, + behind + } + void fetchMobileHostedReviewEligibility(client, worktreeId, requestInput) + .then((eligibility: HostedReviewCreationEligibility | null) => { + if (!isCurrent()) { + return + } + if (!eligibility) { + setState({ kind: 'error' }) + return + } + setState({ kind: 'ready', eligibility }) + }) + .catch(() => { + if (isCurrent()) { + setState(eligibilityStateAfterMobileHostedReviewError()) + } + }) + }, [ + ahead, + behind, + branch, + client, + connState, + hasUncommittedChanges, + hasUpstream, + key.fetch, + key.identity, + shouldFetch, + worktreeId + ]) + + // Why: gate on shouldFetch so a disconnect/client-loss hides a stale `ready` + // snapshot in the same render, before the effect posts `idle` — otherwise the + // Create PR button could stay enabled for one paint after the worktree is + // no longer fetchable. + return shouldFetch ? state : { kind: 'idle' } +} diff --git a/mobile/src/source-control/use-mobile-source-control-create-pr-action.ts b/mobile/src/source-control/use-mobile-source-control-create-pr-action.ts new file mode 100644 index 000000000..44655d147 --- /dev/null +++ b/mobile/src/source-control/use-mobile-source-control-create-pr-action.ts @@ -0,0 +1,47 @@ +import { useMemo } from 'react' +import { buildMobileCreatePrAction } from './mobile-create-pr-action' +import { useMobileHostedReviewEligibility } from './use-mobile-hosted-review-eligibility' +import type { MobileGitStatusResult } from './mobile-git-status' + +type Params = { + client: Parameters[0]['client'] + connState: Parameters[0]['connState'] + worktreeId: string + status: MobileGitStatusResult | null + hasUncommittedChanges: boolean + busyAction: string | null + createPr: (pushFirst: boolean) => void +} + +export function useMobileSourceControlCreatePrAction({ + client, + connState, + worktreeId, + status, + hasUncommittedChanges, + busyAction, + createPr +}: Params) { + const upstream = status?.upstreamStatus + const eligibilityState = useMobileHostedReviewEligibility({ + client, + connState, + worktreeId, + branch: status?.branch, + hasUpstream: upstream?.hasUpstream, + ahead: upstream?.ahead, + behind: upstream?.behind, + hasUncommittedChanges + }) + + return useMemo( + () => + buildMobileCreatePrAction({ + branch: status?.branch, + eligibilityState, + busyAction, + onCreatePr: createPr + }), + [busyAction, createPr, eligibilityState, status?.branch] + ) +} diff --git a/mobile/src/source-control/use-mobile-source-control-keyboard-lift.ts b/mobile/src/source-control/use-mobile-source-control-keyboard-lift.ts new file mode 100644 index 000000000..7d3b274bc --- /dev/null +++ b/mobile/src/source-control/use-mobile-source-control-keyboard-lift.ts @@ -0,0 +1,25 @@ +import { useEffect, useState } from 'react' +import { Keyboard, Platform } from 'react-native' + +export function useMobileSourceControlKeyboardLift(): number { + const [keyboardLift, setKeyboardLift] = useState(0) + + 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() + } + }, []) + + return keyboardLift +} diff --git a/mobile/src/source-control/use-mobile-source-control-openers.ts b/mobile/src/source-control/use-mobile-source-control-openers.ts index f0857b895..be3febb4a 100644 --- a/mobile/src/source-control/use-mobile-source-control-openers.ts +++ b/mobile/src/source-control/use-mobile-source-control-openers.ts @@ -13,6 +13,7 @@ import { type MobileGitBranchChangeEntry } from './mobile-branch-compare' import { isMobileGitUnavailable, type MobileGitStatusEntry } from './mobile-git-status' +import { buildMobileReviewFileRoute } from './mobile-review-route' import type { GitDiffTextResult, MobileBranchCompareState, @@ -28,6 +29,11 @@ type Params = { origin: string embedded: boolean onRequestClose?: () => void + // Fired synchronously at tap time (before the openDiff RPC) so the session can + // snapshot the active tab then — capturing it post-await would misread a tab + // the user switched to during the RPC window as the tap-time tab. + onFileOpenStart?: () => void + onOpenedFileDiff?: (relativePath: string) => void branchCompareState: MobileBranchCompareState mountedRef: MutableRefObject busyActionRef: MutableRefObject @@ -46,6 +52,8 @@ export function useMobileSourceControlOpeners(params: Params) { origin, embedded, onRequestClose, + onFileOpenStart, + onOpenedFileDiff, branchCompareState, mountedRef, busyActionRef, @@ -79,6 +87,23 @@ export function useMobileSourceControlOpeners(params: Params) { setOpeningPath(entry.path) try { setActionError(null) + if (origin !== 'session') { + triggerSelection() + router.push( + buildMobileReviewFileRoute({ + hostId, + worktreeId, + worktreeName: name, + filePath: entry.path, + area: entry.area + }) as Parameters[0] + ) + return + } + // Snapshot the active tab now, at tap time, before the openDiff RPC — + // the session uses it to avoid stealing focus if the user switches tabs + // during the RPC window. + onFileOpenStart?.() let response = await client.sendRequest('files.openDiff', { worktree: `id:${worktreeId}`, relativePath: entry.path, @@ -97,26 +122,18 @@ export function useMobileSourceControlOpeners(params: Params) { return } triggerSelection() - if (origin === 'session') { - // Why: when launched from the session screen, opening a file dismisses - // this surface back to the session. In embedded mode there is nothing - // to pop (the panel docks beside the terminal), so close the dock - // instead of calling router.back(). - if (embedded) { - onRequestClose?.() - } else { - router.back() - } - return + onOpenedFileDiff?.(entry.path) + // Why: when launched from the session screen, opening a file dismisses + // this surface back to the session. In embedded mode there is nothing + // to pop (the panel docks beside the terminal), so close the dock + // instead of calling router.back() — falling back to router.back() when + // no close handler is wired, mirroring MobileSourceControlPanel, so the + // panel never sits on top of the activated diff tab. + if (embedded) { + ;(onRequestClose ?? (() => router.back()))() + } else { + router.back() } - const sessionParams = new URLSearchParams() - if (name) { - sessionParams.set('name', name) - } - const query = sessionParams.toString() - router.replace( - `/h/${encodeURIComponent(hostId)}/session/${encodeURIComponent(worktreeId)}${query ? `?${query}` : ''}` - ) } catch (err) { if (!mountedRef.current) { return @@ -140,6 +157,8 @@ export function useMobileSourceControlOpeners(params: Params) { hostId, mountedRef, name, + onFileOpenStart, + onOpenedFileDiff, onRequestClose, origin, router, @@ -170,6 +189,23 @@ export function useMobileSourceControlOpeners(params: Params) { openingBranchPathRef.current = entry.path setOpeningBranchPath(entry.path) + if (origin !== 'session') { + triggerSelection() + router.push( + buildMobileReviewFileRoute({ + hostId, + worktreeId, + worktreeName: name, + filePath: entry.path, + area: 'branch' + }) as Parameters[0] + ) + openingBranchPathRef.current = null + if (mountedRef.current) { + setOpeningBranchPath(null) + } + return + } setBranchDiffPreview({ kind: 'loading', entry }) try { const response = await client.sendRequest('git.branchDiff', { @@ -222,7 +258,19 @@ export function useMobileSourceControlOpeners(params: Params) { } } }, - [branchCompareState, busyActionRef, client, connState, mountedRef, setActionError, worktreeId] + [ + branchCompareState, + busyActionRef, + client, + connState, + hostId, + mountedRef, + name, + origin, + router, + setActionError, + worktreeId + ] ) return { diff --git a/mobile/src/source-control/use-mobile-source-control-state.ts b/mobile/src/source-control/use-mobile-source-control-state.ts index 2e9032e83..cc69b8905 100644 --- a/mobile/src/source-control/use-mobile-source-control-state.ts +++ b/mobile/src/source-control/use-mobile-source-control-state.ts @@ -1,5 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { Keyboard, Platform } from 'react-native' +import { useCallback, useMemo, useRef, useState } from 'react' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useHostClient, useForceReconnect } from '../transport/client-context' import { getWorktreeLabel } from '../session/worktree-label' @@ -8,6 +7,8 @@ import { useMobileSourceControlLoaders } from './use-mobile-source-control-loade 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 { useMobileSourceControlCreatePrAction } from './use-mobile-source-control-create-pr-action' +import { useMobileSourceControlKeyboardLift } from './use-mobile-source-control-keyboard-lift' import type { RuntimeGitLocalBranches } from '../../../src/shared/runtime-types' import { buildMobileBranchCompareSection, @@ -20,16 +21,14 @@ import { 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 { + buildMobileGitStatusEntryViews, formatBranchLabel, - type MobileBranchEntryView, - type MobileGitStatusEntryView + type MobileBranchEntryView } from './mobile-source-control-screen-state' type MobileGitLocalBranches = RuntimeGitLocalBranches @@ -41,10 +40,21 @@ export type MobileSourceControlStateParams = { origin: string embedded: boolean onRequestClose?: () => void + onFileOpenStart?: () => void + onOpenedFileDiff?: (relativePath: string) => void } export function useMobileSourceControlState(params: MobileSourceControlStateParams) { - const { hostId, worktreeId, name, origin, embedded, onRequestClose } = params + const { + hostId, + worktreeId, + name, + origin, + embedded, + onRequestClose, + onFileOpenStart, + onOpenedFileDiff + } = params const insets = useSafeAreaInsets() const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() @@ -58,7 +68,7 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara const [discardTarget, setDiscardTarget] = useState(null) const [showActionSheet, setShowActionSheet] = useState(false) const [actionError, setActionError] = useState(null) - const [keyboardLift, setKeyboardLift] = useState(0) + const keyboardLift = useMobileSourceControlKeyboardLift() const busyActionRef = useRef(null) const worktreeLabel = getWorktreeLabel(name, worktreeId) const statusIdentityKey = `${hostId}\0${worktreeId}` @@ -95,44 +105,17 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara origin, embedded, onRequestClose, + onFileOpenStart, + onOpenedFileDiff, 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( - () => - 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 derivedEntries = useMemo(() => buildMobileGitStatusEntryViews(entries), [entries]) const sections = useMemo(() => buildMobileSourceControlSections(derivedEntries), [derivedEntries]) const branchCompareResult = branchCompareState.kind === 'ready' ? branchCompareState.result : null const branchCompareSection = useMemo( @@ -159,7 +142,6 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara 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]) @@ -217,6 +199,15 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara setCreatedPrWarning, recordCommitFailure }) + const createPrAction = useMobileSourceControlCreatePrAction({ + client, + connState, + worktreeId, + status, + hasUncommittedChanges: entries.length > 0, + busyAction, + createPr: runners.createPr + }) const primaryAction = useMemo( () => buildMobileSourceControlPrimaryAction({ @@ -297,7 +288,6 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara branchEntries, shouldShowBranchCompareSection, hasVisibleChanges, - reviewableCount, stageablePaths, unstageablePaths, stagedCount, @@ -307,6 +297,7 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara upstreamKnown, syncLabel, primaryAction, + createPrAction, // actions loadStatus, openFile, diff --git a/mobile/src/theme/mobile-theme.ts b/mobile/src/theme/mobile-theme.ts index 76b14415a..f564f4739 100644 --- a/mobile/src/theme/mobile-theme.ts +++ b/mobile/src/theme/mobile-theme.ts @@ -18,6 +18,11 @@ export const colors = { surfaceBright: '#f5f5f5', accentBlue: '#3b82f6', + // Primary-CTA fill (darker than accentBlue) so white on-fill text/icons clear + // WCAG AA 4.5:1; accentBlue itself is ~3.7:1 on white and stays a link/accent tint. + accentBlueCta: '#2563eb', + // On-fill text/icon color for the primary-CTA button. + onAccentBlue: '#ffffff', statusGreen: '#22c55e', statusAmber: '#f59e0b',