Show linked PRs from worktree metadata (#2055)

This commit is contained in:
Neil
2026-05-15 21:19:08 -07:00
committed by GitHub
parent 2248c0168a
commit ae8e58e379
7 changed files with 320 additions and 68 deletions
@@ -0,0 +1,109 @@
import { renderToStaticMarkup } from 'react-dom/server'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Repo, Worktree, WorktreeCardProperty } from '../../../../shared/types'
const fetchHostedReviewForBranch = vi.fn()
const fetchIssue = vi.fn()
const openModal = vi.fn()
const updateWorktreeMeta = vi.fn()
let worktreeCardProperties: WorktreeCardProperty[] = ['pr']
let hostedReviewCache: Record<string, unknown> = {}
vi.mock('@/store', () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({
deleteStateByWorktreeId: {},
fetchHostedReviewForBranch,
fetchIssue,
gitConflictOperationByWorktree: {},
hostedReviewCache,
issueCache: {},
openModal,
remoteBranchConflictByWorktreeId: {},
settings: null,
sshConnectionStates: new Map(),
sshTargetLabels: new Map(),
updateWorktreeMeta,
worktreeCardProperties
})
}))
vi.mock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
vi.mock('./use-worktree-activity-status', () => ({
useWorktreeActivityStatus: () => 'idle'
}))
vi.mock('./CacheTimer', () => ({
default: () => null
}))
vi.mock('./WorktreeCardAgents', () => ({
default: () => null
}))
vi.mock('./SshDisconnectedDialog', () => ({
SshDisconnectedDialog: () => null
}))
vi.mock('./WorktreeContextMenu', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
CLOSE_ALL_CONTEXT_MENUS_EVENT: 'orca:test-close-context-menus',
WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope'
}))
function makeRepo(): Repo {
return {
id: 'repo-1',
path: '/repo',
displayName: 'orca',
badgeColor: '#999999',
addedAt: 1
}
}
function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: 'repo-1::/repo/worktrees/pr-456',
repoId: 'repo-1',
path: '/repo/worktrees/pr-456',
displayName: 'Fix stale GH PR',
branch: 'feature/local-branch',
head: 'abc123',
isBare: false,
isMainWorktree: false,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1,
...overrides
}
}
describe('WorktreeCard linked PR display', () => {
beforeEach(() => {
vi.clearAllMocks()
worktreeCardProperties = ['pr']
hostedReviewCache = {}
})
it('keeps the linked GH PR visible before hosted review details are cached', async () => {
const { default: WorktreeCard } = await import('./WorktreeCard')
const markup = renderToStaticMarkup(
<WorktreeCard worktree={makeWorktree({ linkedPR: 456 })} repo={makeRepo()} isActive={false} />
)
expect(markup).toContain('PR #456')
expect(markup).toContain('Loading PR')
})
})
@@ -37,6 +37,7 @@ import {
import { IssueSection, ReviewSection, CommentSection } from './WorktreeCardMeta'
import { writeWorkspaceDragData } from './workspace-status'
import { useWorktreeActivityStatus } from './use-worktree-activity-status'
import { getWorktreeCardPrDisplay } from './worktree-card-pr-display'
type WorktreeCardProps = {
worktree: Worktree
@@ -174,6 +175,7 @@ const WorktreeCard = React.memo(function WorktreeCard({
const hostedReview: HostedReviewInfo | null | undefined =
hostedReviewEntry !== undefined ? hostedReviewEntry.data : undefined
const prDisplay = getWorktreeCardPrDisplay(hostedReview, worktree.linkedPR)
const issue: IssueInfo | null | undefined = worktree.linkedIssue
? issueEntry !== undefined
? issueEntry.data
@@ -574,18 +576,14 @@ const WorktreeCard = React.memo(function WorktreeCard({
Layout coupling: spacing here is used to derive size estimates in
WorktreeList's estimateSize. Update that function if changing spacing. */}
{((cardProps.includes('issue') && issueDisplay) ||
(cardProps.includes('pr') && hostedReview) ||
(cardProps.includes('pr') && prDisplay) ||
(cardProps.includes('comment') && worktree.comment)) && (
<div className="flex flex-col gap-[3px] mt-0.5">
{cardProps.includes('issue') && issueDisplay && (
<IssueSection issue={issueDisplay} onClick={handleEditIssue} />
)}
{cardProps.includes('pr') && hostedReview && (
<ReviewSection
review={hostedReview}
onEdit={handleEditPr}
onRemove={handleRemovePr}
/>
{cardProps.includes('pr') && prDisplay && (
<ReviewSection review={prDisplay} onEdit={handleEditPr} onRemove={handleRemovePr} />
)}
{cardProps.includes('comment') && worktree.comment && (
<CommentSection comment={worktree.comment} onDoubleClick={handleEditComment} />
@@ -17,11 +17,11 @@ import { CircleDot, GitMerge, Pencil, Unlink } from 'lucide-react'
import { cn } from '@/lib/utils'
import CommentMarkdown from './CommentMarkdown'
import { PullRequestIcon, prStateLabel, checksLabel } from './WorktreeCardHelpers'
import type { WorktreeCardPrDisplay } from './worktree-card-pr-display'
import {
CLOSE_ALL_CONTEXT_MENUS_EVENT,
WORKTREE_CONTEXT_MENU_SCOPE_ATTR
} from './WorktreeContextMenu'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
import type { IssueInfo } from '../../../../shared/types'
// ── Issue section ────────────────────────────────────────────────────
@@ -93,16 +93,16 @@ export function IssueSection({ issue, onClick }: IssueSectionProps): React.JSX.E
// ── Hosted review section ────────────────────────────────────────────
type ReviewSectionProps = {
review: HostedReviewInfo
review: WorktreeCardPrDisplay
onEdit: () => void
onRemove: () => void
}
function getReviewLabel(review: HostedReviewInfo): 'MR' | 'PR' {
function getReviewLabel(review: WorktreeCardPrDisplay): 'MR' | 'PR' {
return review.provider === 'gitlab' ? 'MR' : 'PR'
}
function getProviderName(review: HostedReviewInfo): string {
function getProviderName(review: WorktreeCardPrDisplay): string {
if (review.provider === 'gitlab') {
return 'GitLab'
}
@@ -115,7 +115,7 @@ function getProviderName(review: HostedReviewInfo): string {
return 'GitHub'
}
function ReviewIcon({ review }: { review: HostedReviewInfo }): React.JSX.Element {
function ReviewIcon({ review }: { review: WorktreeCardPrDisplay }): React.JSX.Element {
const Icon = review.provider === 'gitlab' ? GitMerge : PullRequestIcon
return (
<Icon
@@ -137,47 +137,72 @@ export function ReviewSection({ review, onEdit, onRemove }: ReviewSectionProps):
const [menuPoint, setMenuPoint] = React.useState({ x: 0, y: 0 })
const label = getReviewLabel(review)
const providerName = getProviderName(review)
const hasChecks = review.status !== 'neutral'
const checksText =
review.status !== undefined && review.status !== 'neutral' ? checksLabel(review.status) : null
const canManageGitHubLink = review.provider === 'github'
const stateLabel = review.state ? prStateLabel(review.state) : null
const reviewRow = (
<>
<ReviewIcon review={review} />
<div className="flex-1 min-w-0 flex items-center gap-1.5 text-[11.5px] leading-none">
<span className="text-foreground opacity-80 shrink-0 group-hover/meta:underline">
{label} #{review.number}
</span>
<span className="text-muted-foreground truncate group-hover/meta:text-foreground transition-colors">
{review.title}
</span>
</div>
</>
)
const trigger = review.url ? (
<a
href={review.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1.5 min-w-0 cursor-pointer group/meta -mx-1.5 px-1.5 py-0.5 rounded transition-colors hover:bg-background/40"
onClick={(e) => e.stopPropagation()}
>
{reviewRow}
</a>
) : (
<button
type="button"
className="flex w-full items-center gap-1.5 min-w-0 cursor-pointer group/meta -mx-1.5 px-1.5 py-0.5 rounded transition-colors hover:bg-background/40 text-left"
onClick={(e) => {
e.stopPropagation()
onEdit()
}}
>
{reviewRow}
</button>
)
const content = (
<HoverCard openDelay={300}>
<HoverCardTrigger asChild>
<a
href={review.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1.5 min-w-0 cursor-pointer group/meta -mx-1.5 px-1.5 py-0.5 rounded transition-colors hover:bg-background/40"
onClick={(e) => e.stopPropagation()}
>
<ReviewIcon review={review} />
<div className="flex-1 min-w-0 flex items-center gap-1.5 text-[11.5px] leading-none">
<span className="text-foreground opacity-80 shrink-0 group-hover/meta:underline">
{label} #{review.number}
</span>
<span className="text-muted-foreground truncate group-hover/meta:text-foreground transition-colors">
{review.title}
</span>
</div>
</a>
</HoverCardTrigger>
<HoverCardTrigger asChild>{trigger}</HoverCardTrigger>
<HoverCardContent side="right" align="start" className="w-72 p-3 text-xs space-y-1.5">
<div className="font-semibold text-[13px]">
{label} #{review.number} {review.title}
</div>
<div className="flex items-center gap-2 text-muted-foreground">
<span>State: {prStateLabel(review.state)}</span>
{hasChecks && <span>Checks: {checksLabel(review.status)}</span>}
</div>
<a
href={review.url}
target="_blank"
rel="noreferrer"
className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
onClick={(e) => e.stopPropagation()}
>
View on {providerName}
</a>
{(stateLabel || checksText) && (
<div className="flex items-center gap-2 text-muted-foreground">
{stateLabel && <span>State: {stateLabel}</span>}
{checksText && <span>Checks: {checksText}</span>}
</div>
)}
{review.url && (
<a
href={review.url}
target="_blank"
rel="noreferrer"
className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
onClick={(e) => e.stopPropagation()}
>
View on {providerName}
</a>
)}
</HoverCardContent>
</HoverCard>
)
@@ -1,13 +1,14 @@
import { describe, expect, it } from 'vitest'
import type { PRInfo } from '../../../../shared/types'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
import { getWorktreeCardPrDisplay } from './worktree-card-pr-display'
const pr: PRInfo = {
const pr: HostedReviewInfo = {
provider: 'github',
number: 123,
title: 'Ready PR',
state: 'open',
url: 'https://github.com/stablyai/orca/pull/123',
checksStatus: 'success',
status: 'success',
updatedAt: '2026-05-13T00:00:00.000Z',
mergeable: 'MERGEABLE'
}
@@ -19,6 +20,7 @@ describe('getWorktreeCardPrDisplay', () => {
it('falls back to linkedPR while PR details load', () => {
expect(getWorktreeCardPrDisplay(undefined, 456)).toEqual({
provider: 'github',
number: 456,
title: 'Loading PR...'
})
@@ -26,6 +28,7 @@ describe('getWorktreeCardPrDisplay', () => {
it('keeps linkedPR visible when PR details are unavailable', () => {
expect(getWorktreeCardPrDisplay(null, 456)).toEqual({
provider: 'github',
number: 456,
title: 'PR details unavailable'
})
@@ -1,21 +1,22 @@
import type { PRInfo } from '../../../../shared/types'
import type { HostedReviewInfo } from '../../../../shared/hosted-review'
export type WorktreeCardPrDisplay =
| PRInfo
| HostedReviewInfo
| {
provider: 'github'
number: number
title: string
state?: PRInfo['state']
state?: HostedReviewInfo['state']
url?: string
checksStatus?: PRInfo['checksStatus']
status?: HostedReviewInfo['status']
}
export function getWorktreeCardPrDisplay(
pr: PRInfo | null | undefined,
review: HostedReviewInfo | null | undefined,
linkedPR: number | null
): WorktreeCardPrDisplay | null {
if (pr) {
return pr
if (review) {
return review
}
if (linkedPR === null) {
@@ -23,9 +24,10 @@ export function getWorktreeCardPrDisplay(
}
return {
provider: 'github',
number: linkedPR,
// Why: linked PR metadata is persisted before GitHub details are cached.
// Keep the row visible on cold first render while the PR lookup catches up.
title: pr === null ? 'PR details unavailable' : 'Loading PR...'
title: review === null ? 'PR details unavailable' : 'Loading PR...'
}
}
@@ -123,4 +123,82 @@ describe('hosted review slice', () => {
linkedGiteaPR: null
})
})
it('refetches a fresh null branch result when a linked PR hint is later available', async () => {
mockApi.hostedReview.forBranch.mockResolvedValueOnce(null).mockResolvedValueOnce(review)
const store = makeStore()
await expect(store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr')).resolves.toBe(
null
)
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
).resolves.toEqual(review)
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(2)
})
it('honors the cache TTL after a linked PR miss with the same hint', async () => {
mockApi.hostedReview.forBranch.mockResolvedValue(null)
const store = makeStore()
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
).resolves.toBeNull()
await expect(
store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
).resolves.toBeNull()
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(1)
})
it('does not dedupe a linked PR hint onto a weaker in-flight branch lookup', async () => {
let resolveBranchLookup: (value: null) => void = () => {}
const branchLookup = new Promise<null>((resolve) => {
resolveBranchLookup = resolve
})
mockApi.hostedReview.forBranch.mockReturnValueOnce(branchLookup).mockResolvedValueOnce(review)
const store = makeStore()
const plainFetch = store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr')
const linkedFetch = store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(2)
resolveBranchLookup(null)
await expect(plainFetch).resolves.toBeNull()
await expect(linkedFetch).resolves.toEqual(review)
})
it('dedupes repeated linked PR retries while a stronger lookup is in flight', async () => {
let resolveLinkedLookup: (value: typeof review) => void = () => {}
const linkedLookup = new Promise<typeof review>((resolve) => {
resolveLinkedLookup = resolve
})
mockApi.hostedReview.forBranch.mockResolvedValueOnce(null).mockReturnValueOnce(linkedLookup)
const store = makeStore()
await expect(store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr')).resolves.toBe(
null
)
const firstLinkedFetch = store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
const secondLinkedFetch = store.getState().fetchHostedReviewForBranch('/repo', 'feature/pr', {
linkedGitHubPR: 42
})
expect(mockApi.hostedReview.forBranch).toHaveBeenCalledTimes(2)
resolveLinkedLookup(review)
await expect(firstLinkedFetch).resolves.toEqual(review)
await expect(secondLinkedFetch).resolves.toEqual(review)
})
})
+49 -12
View File
@@ -10,14 +10,25 @@ import type { GlobalSettings } from '../../../../shared/types'
import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
import type { AppState } from '../types'
type CacheEntry<T> = { data: T | null; fetchedAt: number }
type CacheEntry<T> = { data: T | null; fetchedAt: number; linkedReviewHintKey?: string }
type FetchOptions = { force?: boolean; repoId?: string }
type LinkedReviewHints = {
linkedGitHubPR?: number | null
linkedGitLabMR?: number | null
linkedBitbucketPR?: number | null
linkedGiteaPR?: number | null
}
const CACHE_TTL_MS = 60_000
const inflightHostedReviewRequests = new Map<
string,
{ promise: Promise<HostedReviewInfo | null>; force: boolean; generation: number }
{
promise: Promise<HostedReviewInfo | null>
force: boolean
generation: number
linkedReviewHintKey: string
}
>()
const requestGenerations = new Map<string, number>()
@@ -25,6 +36,32 @@ function isFresh<T>(entry: CacheEntry<T> | undefined): entry is CacheEntry<T> {
return entry !== undefined && Date.now() - entry.fetchedAt < CACHE_TTL_MS
}
// Why: a branch-only null is weaker than a null after trying the persisted
// linked review number. Track that distinction without changing the cache key.
function linkedReviewHintKey(options?: LinkedReviewHints): string {
const hints = [
['github', options?.linkedGitHubPR ?? null],
['gitlab', options?.linkedGitLabMR ?? null],
['bitbucket', options?.linkedBitbucketPR ?? null],
['gitea', options?.linkedGiteaPR ?? null]
] as const
return hints
.filter(([, number]) => number !== null)
.map(([provider, number]) => `${provider}:${number}`)
.join('|')
}
function shouldRefetchNullForLinkedHint(
cached: CacheEntry<HostedReviewInfo> | undefined,
hintKey: string
): boolean {
return cached?.data === null && hintKey !== '' && (cached.linkedReviewHintKey ?? '') !== hintKey
}
function canReuseInflightHint(inflightHintKey: string, nextHintKey: string): boolean {
return nextHintKey === '' || inflightHintKey === nextHintKey
}
export function getHostedReviewCacheKey(
repoPath: string,
branch: string,
@@ -137,18 +174,17 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
const target = getActiveRuntimeTarget(settings)
const cacheKey = getHostedReviewCacheKey(repoPath, branch, settings, options?.repoId)
const cached = get().hostedReviewCache[cacheKey]
const linkedRefetch =
cached?.data === null &&
((options?.linkedGitHubPR ?? null) !== null ||
(options?.linkedGitLabMR ?? null) !== null ||
(options?.linkedBitbucketPR ?? null) !== null ||
(options?.linkedGiteaPR ?? null) !== null)
const hintKey = linkedReviewHintKey(options)
const linkedRefetch = shouldRefetchNullForLinkedHint(cached, hintKey)
if (!options?.force && !linkedRefetch && isFresh(cached)) {
return cached.data
}
const inflightRequest = inflightHostedReviewRequests.get(cacheKey)
if (inflightRequest && (!options?.force || inflightRequest.force) && !linkedRefetch) {
const inflightHasRequestedHint =
inflightRequest !== undefined &&
canReuseInflightHint(inflightRequest.linkedReviewHintKey, hintKey)
if (inflightRequest && (!options?.force || inflightRequest.force) && inflightHasRequestedHint) {
return inflightRequest.promise
}
@@ -182,7 +218,7 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
set((state) => ({
hostedReviewCache: {
...state.hostedReviewCache,
[cacheKey]: { data: review, fetchedAt: Date.now() }
[cacheKey]: { data: review, fetchedAt: Date.now(), linkedReviewHintKey: hintKey }
}
}))
}
@@ -193,7 +229,7 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
set((state) => ({
hostedReviewCache: {
...state.hostedReviewCache,
[cacheKey]: { data: null, fetchedAt: Date.now() }
[cacheKey]: { data: null, fetchedAt: Date.now(), linkedReviewHintKey: hintKey }
}
}))
}
@@ -209,7 +245,8 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
inflightHostedReviewRequests.set(cacheKey, {
promise: request,
force: Boolean(options?.force),
generation
generation,
linkedReviewHintKey: hintKey
})
return request
}