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.8 KB
Raw Blame
import { translate } from '../i18n/mobile-i18n'
import { requestMobileCommitMessage } from './mobile-commit-message-ai'
import { getStageablePaths, type MobileGitStatusResult } from './mobile-git-status'
import { getMobilePrEligibilityReadiness } from './mobile-open-pr-prefill'
import { resolveMobilePrPrefill, type MobilePrPrefill } from './mobile-pr-create'
import { isBehindOnlyUpstream } from '../../../src/shared/git-upstream-status'
import {
  commitMobileHostedReviewStagedChanges,
  fastForwardMobileHostedReviewBranch,
  mobileHostedReviewBranchStillMatches,
  readMobileHostedReviewGitStatus,
  stageMobileHostedReviewPaths
} from './mobile-hosted-review-git-preparation'
import { applyMobileHostedReviewRemotePrerequisite } from './mobile-hosted-review-remote-prerequisite'
import type { RpcOperationSender } from '../transport/rpc-operation-sender'

export { mobileHostedReviewCreateIntentProgressMessage } from './hosted-review-copy'

export type MobileHostedReviewCreateIntentProgress =
  | 'fast_forwarding'
  | 'staging'
  | 'generating_commit_message'
  | 'committing'
  | 'publishing'
  | 'pushing'
  | 'force_pushing'
  | 'creating_review'

type MobileHostedReviewCreateIntentFailure = {
  ok: false
  error: string
  committed?: boolean
  status?: MobileGitStatusResult | null
  commitMessage?: string
}

export type MobileHostedReviewCreateIntentOutcome =
  | {
      ok: true
      prefill: MobilePrPrefill
      status: MobileGitStatusResult | null
      committed: boolean
    }
  | MobileHostedReviewCreateIntentFailure

type PrepareInput = {
  branch: string
  title: string
  status: MobileGitStatusResult | null
  commitMessage?: string
  // The live composer text, so a message typed during generation is not overwritten.
  readCommitMessage?: () => string
  onProgress?: (progress: MobileHostedReviewCreateIntentProgress) => void
}

function hasUnresolvedConflicts(status: MobileGitStatusResult | null): boolean {
  return status?.entries.some((entry) => entry.conflictStatus === 'unresolved') === true
}

async function resolvePrefillFromStatus(
  client: RpcOperationSender,
  worktreeId: string,
  branch: string,
  title: string,
  status: MobileGitStatusResult | null
): Promise<MobilePrPrefill> {
  return resolveMobilePrPrefill(client, worktreeId, {
    branch,
    title,
    ...getMobilePrEligibilityReadiness(status)
  })
}

async function ensureLocalChangesCommitted(
  client: RpcOperationSender,
  worktreeId: string,
  input: PrepareInput,
  currentStatus: MobileGitStatusResult | null
): Promise<
  | { ok: true; status: MobileGitStatusResult | null; committed: boolean }
  | MobileHostedReviewCreateIntentFailure
> {
  if ((currentStatus?.entries.length ?? 0) === 0) {
    return { ok: true, status: currentStatus, committed: false }
  }
  if (hasUnresolvedConflicts(currentStatus)) {
    return {
      ok: false,
      error: translate(
        'sourceControl.hostedReviewCreateIntent.resolveConflicts',
        'Resolve conflicts before creating a pull request.'
      ),
      committed: false,
      status: currentStatus
    }
  }

  const stagePaths = getStageablePaths(currentStatus?.entries ?? [])
  if (stagePaths.length > 0) {
    input.onProgress?.('staging')
    const staged = await stageMobileHostedReviewPaths(client, worktreeId, stagePaths)
    if (!staged.ok) {
      return staged
    }
    const stagedStatus = await readMobileHostedReviewGitStatus(client, worktreeId)
    if (!stagedStatus.ok) {
      return {
        ok: false,
        error: stagedStatus.error,
        committed: false,
        status: currentStatus
      }
    }
    currentStatus = stagedStatus.status
    if (!mobileHostedReviewBranchStillMatches(input.branch, currentStatus)) {
      return {
        ok: false,
        error: translate(
          'sourceControl.hostedReviewCreateIntent.branchChanged',
          'Branch changed while preparing the pull request.'
        ),
        committed: false,
        status: currentStatus
      }
    }
  }

  const hasStagedChanges = currentStatus?.entries.some((entry) => entry.area === 'staged') === true
  if (!hasStagedChanges) {
    return {
      ok: false,
      error: translate(
        'sourceControl.hostedReviewCreateIntent.resolveOrStageChanges',
        'Resolve or stage changes before creating a pull request.'
      ),
      committed: false,
      status: currentStatus
    }
  }

  let message = input.commitMessage?.trim() ?? ''
  if (!message) {
    input.onProgress?.('generating_commit_message')
    const generated = await requestMobileCommitMessage(client, worktreeId)
    if (!generated.success) {
      return {
        ok: false,
        error: translate(
          'sourceControl.hostedReviewCreateIntent.generateMessageFailed',
          'Could not generate a commit message. Add one in Source Control, then retry.'
        ),
        committed: false,
        status: currentStatus
      }
    }
    if (input.readCommitMessage?.().trim()) {
      return {
        ok: false,
        error: translate(
          'sourceControl.hostedReviewCreateIntent.reviewCommitMessage',
          'Review the commit message, then retry Create PR.'
        ),
        committed: false,
        status: currentStatus
      }
    }
    message = generated.message
  }

  input.onProgress?.('committing')
  const committed = await commitMobileHostedReviewStagedChanges(client, worktreeId, message)
  if (!committed.ok) {
    // Hooks may rewrite files during a failed commit; restage them so a retry commits what they wrote.
    // Best effort: the commit failure, not this recovery, is what the caller reports.
    const failedStatus = await readMobileHostedReviewGitStatus(client, worktreeId).catch(() => null)
    if (
      failedStatus?.ok &&
      mobileHostedReviewBranchStillMatches(input.branch, failedStatus.status)
    ) {
      const restagePaths = getStageablePaths(failedStatus.status?.entries ?? [])
      if (restagePaths.length > 0) {
        await stageMobileHostedReviewPaths(client, worktreeId, restagePaths).catch(() => null)
      }
    }
    return { ...committed, committed: false, status: currentStatus, commitMessage: message }
  }
  const committedStatus = await readMobileHostedReviewGitStatus(client, worktreeId)
  if (!committedStatus.ok) {
    return {
      ok: false,
      error: committedStatus.error,
      committed: true,
      status: currentStatus
    }
  }
  currentStatus = committedStatus.status
  if (!mobileHostedReviewBranchStillMatches(input.branch, currentStatus)) {
    return {
      ok: false,
      error: translate(
        'sourceControl.hostedReviewCreateIntent.branchChanged',
        'Branch changed while preparing the pull request.'
      ),
      committed: true,
      status: currentStatus
    }
  }
  return { ok: true, status: currentStatus, committed: true }
}

export async function prepareMobileHostedReviewCreateIntent(
  client: RpcOperationSender,
  worktreeId: string,
  input: PrepareInput
): Promise<MobileHostedReviewCreateIntentOutcome> {
  const initialStatus = await readMobileHostedReviewGitStatus(client, worktreeId)
  let currentStatus = initialStatus.ok ? initialStatus.status : input.status
  if (!mobileHostedReviewBranchStillMatches(input.branch, currentStatus)) {
    return {
      ok: false,
      error: initialStatus.ok
        ? translate(
            'sourceControl.hostedReviewCreateIntent.branchChanged',
            'Branch changed while preparing the pull request.'
          )
        : initialStatus.error,
      status: currentStatus
    }
  }

  // Like desktop, catch up a behind-only branch first so the new commit does not diverge it.
  if (isBehindOnlyUpstream(currentStatus?.upstreamStatus)) {
    input.onProgress?.('fast_forwarding')
    const updated = await fastForwardMobileHostedReviewBranch(client, worktreeId)
    if (!updated.ok) {
      return { ok: false, error: updated.error, status: currentStatus }
    }
    const updatedStatus = await readMobileHostedReviewGitStatus(client, worktreeId)
    if (!updatedStatus.ok) {
      return { ok: false, error: updatedStatus.error, status: currentStatus }
    }
    currentStatus = updatedStatus.status
    if (!mobileHostedReviewBranchStillMatches(input.branch, currentStatus)) {
      return {
        ok: false,
        error: translate(
          'sourceControl.hostedReviewCreateIntent.branchChanged',
          'Branch changed while preparing the pull request.'
        ),
        status: currentStatus
      }
    }
  }

  const committed = await ensureLocalChangesCommitted(client, worktreeId, input, currentStatus)
  if (!committed.ok) {
    return committed
  }
  currentStatus = committed.status

  let prefill = await resolvePrefillFromStatus(
    client,
    worktreeId,
    input.branch,
    input.title,
    currentStatus
  )
  for (let attempts = 0; attempts < 2; attempts++) {
    const remote = await applyMobileHostedReviewRemotePrerequisite(client, worktreeId, prefill, {
      ...input,
      status: currentStatus
    })
    if (!remote.ok) {
      return { ...remote, committed: committed.committed, status: currentStatus }
    }
    if (!remote.ran) {
      break
    }
    const refreshedStatus = await readMobileHostedReviewGitStatus(client, worktreeId)
    if (!refreshedStatus.ok) {
      return {
        ok: false,
        error: refreshedStatus.error,
        committed: committed.committed,
        status: currentStatus
      }
    }
    currentStatus = refreshedStatus.status
    if (!mobileHostedReviewBranchStillMatches(input.branch, currentStatus)) {
      return {
        ok: false,
        error: translate(
          'sourceControl.hostedReviewCreateIntent.branchChanged',
          'Branch changed while preparing the pull request.'
        ),
        committed: committed.committed,
        status: currentStatus
      }
    }
    prefill = await resolvePrefillFromStatus(
      client,
      worktreeId,
      input.branch,
      input.title,
      currentStatus
    )
  }

  return { ok: true, prefill, status: currentStatus, committed: committed.committed }
}