Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

9.6 KB
Raw Blame
import { useEffect, useState } from 'react'
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
import { GitPullRequestArrow, Link2, RefreshCw } from 'lucide-react-native'
import { colors } from '../../theme/mobile-theme'
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import type { RpcClient } from '../../transport/rpc-client'
import type { ConnectionState } from '../../transport/types'
import type { MobileGitStatusResult } from '../../source-control/mobile-git-status'
import {
  getMobileCommitFailureStagedEntries,
  type MobileCommitFailureRecovery
} from '../../source-control/mobile-commit-failure-recovery'
import { useMobileCommitFailureRecovery } from '../../source-control/use-mobile-commit-failure-recovery'
import { MobileCommitFailurePanel } from '../../source-control/MobileCommitFailurePanel'
import { mobileHostedReviewCreateIntentProgressMessage } from '../../source-control/mobile-hosted-review-create-intent'
import type { MobileHostedReviewCreateIntentProgress } from '../../source-control/mobile-hosted-review-create-intent'
import {
  isMobileHostedReviewCommitFailure,
  runMobileHostedReviewCreateIntent
} from '../../source-control/mobile-hosted-review-create-intent-runner'
import { fetchWorktreeGitHubPRLink } from '../../source-control/mobile-pr-link'
import { openMobilePrUrl } from '../mobile-pr-url'
import { MobileLinkPrForm } from './MobileLinkPrForm'
import { prCreateEmptyStateStyles as styles } from './pr-create-empty-state-styles'

type Props = {
  client: RpcClient | null
  worktreeId: string
  gitBranch: string | null
  gitStatus: MobileGitStatusResult | null
  connState: ConnectionState
  /** Named when the commit-recovery agent starts. */
  workspaceLabel: string | null
  // Refetches the sidebar after create or an explicit empty-state refresh.
  onCreated: () => void
}

type Mode = 'choose' | 'link'

// Offer create or link when branch has no PR; empty state is mobile’s linking entry point.
export function PrSidebarCreateEmptyState({
  client,
  worktreeId,
  gitBranch,
  gitStatus,
  connState,
  workspaceLabel,
  onCreated
}: Props) {
  useMobileColorScheme()
  const t = useMobileTranslation()
  const [mode, setMode] = useState<Mode>('choose')
  const [loading, setLoading] = useState(false)
  const [createWarning, setCreateWarning] = useState<string | null>(null)
  const [commitFailureRecovery, setCommitFailureRecovery] =
    useState<MobileCommitFailureRecovery | null>(null)
  // Persisted linkedPR with no resolved PR warrants notice while preserving relink action.
  const [orphanLinkedPR, setOrphanLinkedPR] = useState<number | null>(null)
  const commitFailureRecoveryAction = useMobileCommitFailureRecovery({
    client,
    connState,
    worktreeId,
    workspaceLabel,
    failure: commitFailureRecovery
  })

  const refreshPrState = () => {
    setCreateWarning(null)
    setCommitFailureRecovery(null)
    onCreated()
  }

  useEffect(() => {
    let cancelled = false
    if (!client) {
      setOrphanLinkedPR(null)
      return
    }
    void fetchWorktreeGitHubPRLink(client, worktreeId)
      .then((link) => {
        if (!cancelled) {
          setOrphanLinkedPR(link.linkedPR)
        }
      })
      .catch(() => {
        if (!cancelled) {
          setOrphanLinkedPR(null)
        }
      })
    return () => {
      cancelled = true
    }
  }, [client, worktreeId])

  const openComposer = async (): Promise<void> => {
    if (!client || loading) {
      return
    }
    setCreateWarning(null)
    setCommitFailureRecovery(null)
    setLoading(true)
    try {
      if (!gitBranch) {
        setCreateWarning(
          t(
            'pullRequest.prSidebarCreateEmptyState.branchRequired',
            'Check out a branch before creating a pull request.'
          )
        )
        return
      }
      // Skip local compose and use hosted create flow to match automated review path.
      let progress: MobileHostedReviewCreateIntentProgress | null = null
      const outcome = await runMobileHostedReviewCreateIntent(client, worktreeId, {
        branch: gitBranch,
        title: gitBranch,
        status: gitStatus,
        onProgress: (nextProgress) => {
          progress = nextProgress
          setCreateWarning(mobileHostedReviewCreateIntentProgressMessage(nextProgress))
        }
      })
      if (!outcome.ok) {
        if (isMobileHostedReviewCommitFailure(outcome, progress)) {
          const outcomeStagedEntries = getMobileCommitFailureStagedEntries(outcome.status?.entries)
          setCommitFailureRecovery({
            error: outcome.error,
            commitMessage: outcome.commitMessage ?? gitBranch,
            stagedEntries:
              outcomeStagedEntries.length > 0
                ? outcomeStagedEntries
                : getMobileCommitFailureStagedEntries(gitStatus?.entries)
          })
        }
        setCreateWarning(outcome.error)
        return
      }
      setCreateWarning(outcome.warning ?? null)
      openMobilePrUrl(outcome.url)
      onCreated()
    } catch (err) {
      setCreateWarning(
        err instanceof Error
          ? err.message
          : t(
              'pullRequest.prSidebarCreateEmptyState.createFailed',
              'Failed to create pull request.'
            )
      )
    } finally {
      setLoading(false)
    }
  }

  const canCreate = !!client && !!gitBranch

  if (mode === 'link') {
    return (
      <View style={styles.composerArea}>
        <MobileLinkPrForm
          client={client}
          worktreeId={worktreeId}
          onCancel={() => setMode('choose')}
          onLinked={() => {
            setMode('choose')
            refreshPrState()
          }}
        />
      </View>
    )
  }

  return (
    <View style={styles.section}>
      <View style={styles.header}>
        <View style={styles.headerTitle}>
          <GitPullRequestArrow size={14} color={colors.textSecondary} strokeWidth={2.2} />
          <Text style={styles.headerLabel}>
            {t('pullRequest.prSidebarCreateEmptyState.title', 'Pull request')}
          </Text>
        </View>
        <View style={styles.headerActions}>
          <Pressable
            style={({ pressed }) => [styles.iconButton, pressed && styles.iconButtonPressed]}
            onPress={refreshPrState}
            accessibilityRole="button"
            accessibilityLabel={t(
              'pullRequest.prSidebarCreateEmptyState.refreshPullRequest',
              'Refresh pull request'
            )}
            hitSlop={6}
          >
            <RefreshCw size={16} color={colors.textSecondary} strokeWidth={2.2} />
          </Pressable>
          <Pressable
            style={[styles.createButton, (!canCreate || loading) && styles.createButtonDisabled]}
            onPress={() => void openComposer()}
            disabled={!canCreate || loading}
            accessibilityRole="button"
            accessibilityLabel={t(
              'pullRequest.prSidebarCreateEmptyState.createPullRequest',
              'Create pull request'
            )}
          >
            {loading ? (
              <ActivityIndicator color={colors.bgBase} />
            ) : (
              <GitPullRequestArrow size={14} color={colors.bgBase} strokeWidth={2.2} />
            )}
            <Text style={styles.createButtonText}>
              {t('pullRequest.prSidebarCreateEmptyState.createPr', 'Create PR')}
            </Text>
          </Pressable>
        </View>
      </View>
      <View style={styles.body}>
        <Text style={styles.bodyTitle}>
          {orphanLinkedPR
            ? t(
                'pullRequest.prSidebarCreateEmptyState.linkedPrUnavailable',
                'Linked PR #{{number}} unavailable',
                { number: orphanLinkedPR }
              )
            : t('pullRequest.prSidebarCreateEmptyState.noOpenPullRequest', 'No open pull request')}
        </Text>
        <Text style={styles.bodyText}>
          {orphanLinkedPR
            ? t(
                'pullRequest.prSidebarCreateEmptyState.refreshOrCreate',
                'Refresh to check again, or create a new PR for this branch.'
              )
            : gitBranch
              ? t(
                  'pullRequest.prSidebarCreateEmptyState.branchNotLinked',
                  '{{branch}} is not linked to an open PR.',
                  { branch: gitBranch }
                )
              : t(
                  'pullRequest.prSidebarCreateEmptyState.currentBranchNotLinked',
                  'The current branch is not linked to an open PR.'
                )}
        </Text>
        {commitFailureRecovery ? (
          <MobileCommitFailurePanel
            failure={commitFailureRecovery}
            action={commitFailureRecoveryAction}
          />
        ) : createWarning ? (
          <Text style={styles.bodyText}>{createWarning}</Text>
        ) : null}
        <Pressable
          style={({ pressed }) => [
            styles.linkButton,
            !client && styles.linkButtonDisabled,
            pressed && styles.linkButtonPressed
          ]}
          onPress={() => setMode('link')}
          disabled={!client}
          accessibilityRole="button"
          accessibilityLabel={t(
            'pullRequest.prSidebarCreateEmptyState.linkExistingPullRequest',
            'Link an existing pull request'
          )}
          accessibilityState={{ disabled: !client }}
          hitSlop={6}
        >
          <Link2
            size={14}
            color={client ? colors.textSecondary : colors.textMuted}
            strokeWidth={2.2}
          />
          <Text style={styles.linkButtonText}>
            {t('pullRequest.prSidebarCreateEmptyState.linkExistingPr', 'Link an existing PR')}
          </Text>
        </Pressable>
      </View>
    </View>
  )
}