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.

14.9 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import type { PRCheckDetail } from '../../../src/shared/github/check-types'
import type { PRInfo } from '../../../src/shared/github/pull-request-types'
import type { GitHubWorkItemDetails } from '../../../src/shared/github/work-item-types'
import type { HostedReviewInfo } from '../../../src/shared/hosted-review'
import { fetchPRChecks, type GitHubPrReadOutcome } from './github-pr-rpc'
import {
  classifyPrSidebarFailure,
  emptyPrSidebarDetails,
  isPrSidebarDetailsPlaceholder,
  prSidebarDetailsNeedFetch,
  loadPrSidebarData,
  loadPrSidebarDetails,
  resolvePrSidebarDetailsAfterPhase2,
  shouldApplyResult,
  shouldSoftRefreshPrSidebarOnHeadChange,
  type PrSidebarLoadDeps
} from './mobile-pr-sidebar-state'
import { buildMobilePrSidebarIdentity } from './use-mobile-pr-sidebar-controller'
import type { RpcResponse } from '../transport/types'

function ok<T>(result: T): GitHubPrReadOutcome<T> {
  return { ok: true, result }
}
function fail<T>(error: string): GitHubPrReadOutcome<T> {
  return { ok: false, error }
}

const PR: PRInfo = {
  number: 7,
  title: 'Feat',
  state: 'open',
  url: 'u',
  checksStatus: 'success',
  updatedAt: 'now',
  mergeable: 'MERGEABLE',
  reviewDecision: null,
  headSha: 'sha-pr'
} as unknown as PRInfo
const DETAILS = { item: { number: 7 }, checks: [] } as unknown as GitHubWorkItemDetails
const CHECKS: PRCheckDetail[] = [
  { name: 'ci', status: 'completed', conclusion: 'success', url: null }
]

const RESULT_ABSENT_REPLY: RpcResponse = {
  id: 'x',
  ok: true,
  result: undefined,
  _meta: { runtimeId: 'r' }
}

function ghInfo(over: Partial<HostedReviewInfo> = {}): HostedReviewInfo {
  return {
    provider: 'github',
    number: 7,
    title: 'Feat',
    state: 'open',
    url: 'u',
    status: 'success',
    updatedAt: 'now',
    mergeable: 'MERGEABLE',
    ...over
  } as HostedReviewInfo
}

describe('classifyPrSidebarFailure', () => {
  it('routes permission/auth messages to blocked', () => {
    expect(classifyPrSidebarFailure('permission denied')).toBe('blocked')
    expect(classifyPrSidebarFailure('GitHub account not connected')).toBe('blocked')
    expect(classifyPrSidebarFailure('HTTP 403 Forbidden')).toBe('blocked')
    expect(classifyPrSidebarFailure('401 Unauthorized')).toBe('blocked')
  })

  it('routes network/transient messages to error', () => {
    expect(classifyPrSidebarFailure('network timeout')).toBe('error')
    expect(classifyPrSidebarFailure('socket hang up')).toBe('error')
  })
})

describe('loadPrSidebarData', () => {
  function deps(over: Partial<PrSidebarLoadDeps> = {}): PrSidebarLoadDeps {
    return {
      fetchForBranch: vi.fn(async () => ok<HostedReviewInfo | null>(ghInfo())),
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: null,
        suppressedGitHubPR: null,
        pushTarget: null
      })),
      clearWorktreeReviewLink: vi.fn(async () => {}),
      fetchPRForBranch: vi.fn(async () => ok<PRInfo | null>(PR)),
      fetchWorkItemDetails: vi.fn(async () => ok<GitHubWorkItemDetails | null>(DETAILS)),
      fetchPRChecks: vi.fn(async () => ok<PRCheckDetail[]>(CHECKS)),
      ...over
    }
  }

  it('phase 1 loads pr + checks into ready with details=null (comments deferred)', async () => {
    const d = deps()
    const out = await loadPrSidebarData(d, {
      worktreeId: 'w',
      branch: 'feat',
      headSha: 'sha-status'
    })
    expect(out).toEqual({
      kind: 'ready',
      data: { pr: PR, details: null, checks: CHECKS, checksError: null, pushTarget: null }
    })
    expect(d.fetchWorkItemDetails).not.toHaveBeenCalled()
    expect(d.fetchPRForBranch).toHaveBeenCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: null,
      fallbackPRNumber: 7,
      currentHeadOid: 'sha-status'
    })
    expect(d.fetchPRChecks).toHaveBeenCalledWith('w', {
      prNumber: 7,
      headSha: 'sha-pr',
      prRepo: null
    })
  })

  it('passes a null hint when forBranch and the worktree linkedPR are both empty', async () => {
    const d = deps({ fetchForBranch: vi.fn(async () => ok<HostedReviewInfo | null>(null)) })
    await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(d.fetchPRForBranch).toHaveBeenCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: null,
      fallbackPRNumber: null,
      currentHeadOid: null
    })
  })

  it('falls back to the worktree linkedPR when forBranch has no open PR (closed/merged)', async () => {
    const merged = { ...PR, number: 42, state: 'merged' } as unknown as PRInfo
    const d = deps({
      fetchForBranch: vi.fn(async () => ok<HostedReviewInfo | null>(null)),
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: 42,
        suppressedGitHubPR: null,
        pushTarget: null
      })),
      fetchPRForBranch: vi.fn(async () => ok<PRInfo | null>(merged))
    })
    const out = await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(d.fetchPRForBranch).toHaveBeenCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: 42,
      fallbackPRNumber: null,
      currentHeadOid: null
    })
    expect(out).toEqual({
      kind: 'ready',
      data: { pr: merged, details: null, checks: CHECKS, checksError: null, pushTarget: null }
    })
  })

  it('sends the explicit link over the branch PR, which stays only a fallback', async () => {
    const d = deps({
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: 42,
        suppressedGitHubPR: null,
        pushTarget: null
      }))
    })
    await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(d.fetchPRForBranch).toHaveBeenCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: 42,
      fallbackPRNumber: null,
      currentHeadOid: null
    })
  })

  it('re-resolves by branch when the linked merged PR no longer contains this head', async () => {
    const stale: PRInfo = {
      ...PR,
      number: 42,
      state: 'merged',
      headSha: 'old',
      headDivergedFromMergedPRAtOid: 'head-now'
    }
    const fetchPRForBranch = vi
      .fn()
      .mockResolvedValueOnce(ok<PRInfo | null>(stale))
      .mockResolvedValueOnce(ok<PRInfo | null>(PR))
    const d = deps({
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: 42,
        suppressedGitHubPR: null,
        pushTarget: null
      })),
      fetchPRForBranch
    })
    const out = await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat', headSha: 'head-now' })
    expect(fetchPRForBranch).toHaveBeenLastCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: null,
      fallbackPRNumber: 7,
      currentHeadOid: 'head-now'
    })
    expect(out).toMatchObject({ kind: 'ready', data: { pr: PR } })
    // The clear re-checks the worktree, so a link chosen meanwhile survives.
    const [[worktreeId, shouldApply]] = vi.mocked(d.clearWorktreeReviewLink).mock.calls
    expect(worktreeId).toBe('w')
    const worktree = {
      baseRef: null,
      linkedPR: 42,
      suppressedGitHubPR: null,
      pushTarget: null,
      branch: 'feat',
      head: 'head-now',
      isBare: false,
      isArchived: false
    }
    expect(shouldApply(worktree)).toBe(true)
    expect(shouldApply({ ...worktree, linkedPR: 99 })).toBe(false)
  })

  it('hides the branch PR the user unlinked', async () => {
    const d = deps({
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: null,
        suppressedGitHubPR: 7,
        pushTarget: null
      }))
    })
    expect(await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })).toEqual({
      kind: 'none'
    })
    expect(d.fetchPRChecks).not.toHaveBeenCalled()
  })

  it('does not pass non-GitHub hosted-review hints into the GitHub PR lookup', async () => {
    const d = deps({
      fetchForBranch: vi.fn(async () =>
        ok<HostedReviewInfo | null>(ghInfo({ provider: 'gitlab', number: 99 }))
      ),
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: null,
        suppressedGitHubPR: null,
        pushTarget: null
      }))
    })
    await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(d.fetchPRForBranch).toHaveBeenCalledWith('w', {
      branch: 'feat',
      linkedPRNumber: null,
      fallbackPRNumber: null,
      currentHeadOid: null
    })
  })

  it('is non-fatal when forBranch errors — prForBranch still resolves', async () => {
    const d = deps({ fetchForBranch: vi.fn(async () => fail<HostedReviewInfo | null>('timeout')) })
    const out = await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(out.kind).toBe('ready')
  })

  it('returns the `none` empty state when the branch has no open/linked PR', async () => {
    const out = await loadPrSidebarData(
      deps({ fetchPRForBranch: vi.fn(async () => ok<PRInfo | null>(null)) }),
      { worktreeId: 'w', branch: 'feat' }
    )
    expect(out).toEqual({ kind: 'none' })
  })

  // Checks failure must preserve the PR’s unrelated title/comments/merge controls.
  it('keeps the PR rendered when the checks read fails, carrying the message', async () => {
    const out = await loadPrSidebarData(
      deps({ fetchPRChecks: vi.fn(async () => fail<PRCheckDetail[]>('403 forbidden')) }),
      { worktreeId: 'w', branch: 'feat' }
    )
    expect(out).toEqual({
      kind: 'ready',
      data: { pr: PR, details: null, checks: [], checksError: '403 forbidden', pushTarget: null }
    })
  })

  // Reject malformed check payloads while retaining the PR and readable check-error feedback.
  it('keeps the PR rendered when the host sends a checks reply the reader refuses', async () => {
    const sendRequest = vi.fn(async () => RESULT_ABSENT_REPLY)
    const out = await loadPrSidebarData(
      deps({
        fetchPRChecks: (worktreeId, args) => fetchPRChecks({ sendRequest }, worktreeId, args)
      }),
      { worktreeId: 'repo-1::/w', branch: 'feat' }
    )
    expect(out).toEqual({
      kind: 'ready',
      data: {
        pr: PR,
        details: null,
        checks: [],
        checksError: 'The host sent a reply this app could not read (github.prChecks)',
        pushTarget: null
      }
    })
    expect(sendRequest).toHaveBeenCalledOnce()
  })

  it('returns an error state when a dep rejects (no escaping rejection)', async () => {
    const d = deps({
      fetchPRForBranch: vi.fn(async () => {
        throw new Error('transport closed')
      })
    })
    const out = await loadPrSidebarData(d, { worktreeId: 'w', branch: 'feat' })
    expect(out).toEqual({ kind: 'error', message: 'transport closed' })
  })
})

describe('loadPrSidebarDetails (phase 2)', () => {
  function deps(over: Partial<PrSidebarLoadDeps> = {}): PrSidebarLoadDeps {
    return {
      fetchForBranch: vi.fn(async () => ok<HostedReviewInfo | null>(ghInfo())),
      fetchWorktreeGitHubPRLink: vi.fn(async () => ({
        linkedPR: null,
        suppressedGitHubPR: null,
        pushTarget: null
      })),
      clearWorktreeReviewLink: vi.fn(async () => {}),
      fetchPRForBranch: vi.fn(async () => ok<PRInfo | null>(PR)),
      fetchWorkItemDetails: vi.fn(async () => ok<GitHubWorkItemDetails | null>(DETAILS)),
      fetchPRChecks: vi.fn(async () => ok<PRCheckDetail[]>(CHECKS)),
      ...over
    }
  }

  it('returns the fetched details', async () => {
    expect(await loadPrSidebarDetails(deps(), 'w', 7)).toBe(DETAILS)
  })

  it('is non-fatal — a details failure yields null rather than erroring the sidebar', async () => {
    const d = deps({
      fetchWorkItemDetails: vi.fn(async () => fail<GitHubWorkItemDetails | null>('network down'))
    })
    expect(await loadPrSidebarDetails(d, 'w', 7)).toBeNull()
  })

  it('is non-fatal when fetchWorkItemDetails rejects (no escaping rejection)', async () => {
    const d = deps({
      fetchWorkItemDetails: vi.fn(async () => {
        throw new Error('transport closed')
      })
    })
    expect(await loadPrSidebarDetails(d, 'w', 7)).toBeNull()
  })
})

describe('shouldApplyResult', () => {
  it('applies only the latest load sequence', () => {
    expect(shouldApplyResult(3, 3)).toBe(true)
    expect(shouldApplyResult(2, 3)).toBe(false)
  })
})

describe('shouldSoftRefreshPrSidebarOnHeadChange', () => {
  it('restarts ready/none/loading so mid-flight head advances are not stuck', () => {
    expect(shouldSoftRefreshPrSidebarOnHeadChange('ready')).toBe(true)
    expect(shouldSoftRefreshPrSidebarOnHeadChange('none')).toBe(true)
    expect(shouldSoftRefreshPrSidebarOnHeadChange('loading')).toBe(true)
  })

  it('skips hidden and terminal failures (chip bootstrap / retry own those)', () => {
    expect(shouldSoftRefreshPrSidebarOnHeadChange('hidden')).toBe(false)
    expect(shouldSoftRefreshPrSidebarOnHeadChange('error')).toBe(false)
    expect(shouldSoftRefreshPrSidebarOnHeadChange('blocked')).toBe(false)
  })
})

describe('resolvePrSidebarDetailsAfterPhase2', () => {
  it('prefers a successful fetch over prior details', () => {
    const prior = emptyPrSidebarDetails(PR)
    expect(resolvePrSidebarDetailsAfterPhase2({ fetched: DETAILS, prior, pr: PR })).toBe(DETAILS)
  })

  it('keeps prior details when the fetch is non-fatal null', () => {
    const prior = emptyPrSidebarDetails(PR)
    expect(resolvePrSidebarDetailsAfterPhase2({ fetched: null, prior, pr: PR })).toBe(prior)
  })

  it('uses empty details when phase 2 fails with nothing prior (no forever spinner)', () => {
    const empty = resolvePrSidebarDetailsAfterPhase2({
      fetched: null,
      prior: null,
      pr: PR
    })
    expect(empty.body).toBe('')
    expect(empty.comments).toEqual([])
    expect(empty.item.number).toBe(7)
    expect(empty.item.type).toBe('pr')
    expect(isPrSidebarDetailsPlaceholder(empty)).toBe(true)
  })
})

describe('isPrSidebarDetailsPlaceholder / prSidebarDetailsNeedFetch', () => {
  it('detects the synthetic hyphen id, not the host pr:n shape', () => {
    const placeholder = emptyPrSidebarDetails(PR)
    expect(isPrSidebarDetailsPlaceholder(placeholder)).toBe(true)
    expect(isPrSidebarDetailsPlaceholder(DETAILS)).toBe(false)
    expect(
      isPrSidebarDetailsPlaceholder({
        ...DETAILS,
        item: { ...DETAILS.item, id: `pr:${PR.number}` }
      })
    ).toBe(false)
  })

  it('needs fetch for null and placeholders, not real details', () => {
    expect(prSidebarDetailsNeedFetch(null)).toBe(true)
    expect(prSidebarDetailsNeedFetch(undefined)).toBe(true)
    expect(prSidebarDetailsNeedFetch(emptyPrSidebarDetails(PR))).toBe(true)
    expect(prSidebarDetailsNeedFetch(DETAILS)).toBe(false)
  })
})

describe('buildMobilePrSidebarIdentity', () => {
  it('keys identity on worktree and branch', () => {
    expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'feat' })).toBe('w1\u0000feat')
  })

  it('is null without a branch and changes when branch or worktree changes', () => {
    expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: null })).toBeNull()
    expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'a' })).not.toBe(
      buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'b' })
    )
    expect(buildMobilePrSidebarIdentity({ worktreeId: 'w1', branch: 'a' })).not.toBe(
      buildMobilePrSidebarIdentity({ worktreeId: 'w2', branch: 'a' })
    )
  })
})