Keep Create PR intent pinned to original worktree (#5552)

* Make Create PR intent resilient to worktree switching

Co-authored-by: Orca <help@stably.ai>

* Restrict PR creation sidebar actions to foreground worktrees

- Prevent switching tabs and opening the PR URL when a background
  worktree's PR creation finishes.
- Extract commit eligibility checking into a dedicated module and
  disable the commit message textarea during operations or when
  ineligible.
- Fix flakiness in the remote runtime request connection test.

* Abort Create PR if branch changes during details generation

If the branch changes within the active worktree while review details
are being generated, the Create PR flow now aborts and shows a muted
notice prompting the user to retry.

- Allows worktree navigation during PR details generation without
  treating it as an intent conflict.
- Adds localized strings for the new retry notice.
- Uses platform-independent paths in tests for cross-platform support.

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinjing
2026-06-16 18:45:24 -07:00
committed by GitHub
co-authored by Orca
parent b6f45d0c27
commit 3f7e869f0c
17 changed files with 765 additions and 276 deletions
@@ -429,11 +429,11 @@ describe('remote runtime request connection integration', () => {
})
)
await waitFor(
() => subscriptionCleanups.size >= mixedSubscriptions.length + 1,
() =>
subscriptionCleanups.size >= mixedSubscriptions.length + 1 && mixedEvents.length > 0,
5000,
() => `cleanup count ${subscriptionCleanups.size}, event count ${mixedEvents.length}`
)
expect(mixedEvents.length).toBeGreaterThan(0)
expect(
(server as unknown as { wsConnectionIds: Map<unknown, unknown> }).wsConnectionIds.size
).toBe(1)
@@ -41,6 +41,7 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
isGenerating: false,
generateError: null as string | null,
stagedCount: inputs.stagedCount,
hasPartiallyStagedChanges: inputs.hasPartiallyStagedChanges,
hasUnresolvedConflicts: inputs.hasUnresolvedConflicts,
isRemoteOperationActive: inputs.isRemoteOperationActive,
inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null,
@@ -42,6 +42,7 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
isGenerating: false,
generateError: null as string | null,
stagedCount: inputs.stagedCount,
hasPartiallyStagedChanges: inputs.hasPartiallyStagedChanges,
hasUnresolvedConflicts: inputs.hasUnresolvedConflicts,
isRemoteOperationActive: inputs.isRemoteOperationActive,
inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null,
@@ -41,6 +41,7 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
isGenerating: false,
generateError: null as string | null,
stagedCount: inputs.stagedCount,
hasPartiallyStagedChanges: inputs.hasPartiallyStagedChanges,
hasUnresolvedConflicts: inputs.hasUnresolvedConflicts,
isRemoteOperationActive: inputs.isRemoteOperationActive,
inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null,
@@ -39,6 +39,7 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
isGenerating: false,
generateError: null as string | null,
stagedCount: inputs.stagedCount,
hasPartiallyStagedChanges: inputs.hasPartiallyStagedChanges,
hasUnresolvedConflicts: inputs.hasUnresolvedConflicts,
isRemoteOperationActive: inputs.isRemoteOperationActive,
inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null,
@@ -116,12 +117,31 @@ describe('CommitArea', () => {
expect(hasDisabledAttribute(firstButton(renderCommitArea(baseProps())))).toBe(false)
})
it('keeps the textarea enabled while the commit is in flight', () => {
it('disables the textarea while the commit is in flight', () => {
const markup = renderCommitArea({
...baseProps({ isCommitting: true }),
isCommitting: true
})
expect(textarea(markup)).not.toContain('disabled')
expect(hasDisabledAttribute(textarea(markup))).toBe(true)
})
it('disables the textarea when no files are staged', () => {
expect(hasDisabledAttribute(textarea(renderCommitArea(baseProps({ stagedCount: 0 }))))).toBe(
true
)
})
it('disables the textarea when unresolved conflicts exist', () => {
expect(
hasDisabledAttribute(textarea(renderCommitArea(baseProps({ hasUnresolvedConflicts: true }))))
).toBe(true)
})
it('keeps the textarea enabled when staged files need a commit message', () => {
const props = baseProps({ hasMessage: false })
expect(hasDisabledAttribute(textarea(renderCommitArea({ ...props, commitMessage: '' })))).toBe(
false
)
})
it('clears the message and keeps error hidden after a successful commit lifecycle', () => {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'
import {
canSubmitCommit,
COMMIT_MESSAGE_REQUIRED_REASON,
isCommitMessageFieldDisabled,
resolveCommitDisabledReason
} from './source-control-commit-eligibility'
function baseInputs(
overrides: Partial<Parameters<typeof canSubmitCommit>[0]> = {}
): Parameters<typeof canSubmitCommit>[0] {
return {
stagedCount: 1,
hasPartiallyStagedChanges: false,
hasMessage: true,
hasUnresolvedConflicts: false,
isCommitting: false,
isRemoteOperationActive: false,
...overrides
}
}
describe('source-control-commit-eligibility', () => {
it('returns null when commit prerequisites are satisfied', () => {
expect(resolveCommitDisabledReason(baseInputs())).toBeNull()
expect(canSubmitCommit(baseInputs())).toBe(true)
expect(isCommitMessageFieldDisabled(baseInputs())).toBe(false)
})
it('keeps the message field enabled when only the message is missing', () => {
const inputs = baseInputs({ hasMessage: false })
expect(resolveCommitDisabledReason(inputs)).toBe(COMMIT_MESSAGE_REQUIRED_REASON)
expect(canSubmitCommit(inputs)).toBe(false)
expect(isCommitMessageFieldDisabled(inputs)).toBe(false)
})
it('disables the message field when nothing is staged', () => {
const inputs = baseInputs({ stagedCount: 0 })
expect(isCommitMessageFieldDisabled(inputs)).toBe(true)
})
it('disables the message field while commit or remote work is in flight', () => {
expect(isCommitMessageFieldDisabled(baseInputs({ isCommitting: true }))).toBe(true)
expect(isCommitMessageFieldDisabled(baseInputs({ isRemoteOperationActive: true }))).toBe(true)
expect(isCommitMessageFieldDisabled(baseInputs({ isPullRequestOperationActive: true }))).toBe(
true
)
})
})
@@ -0,0 +1,54 @@
export const COMMIT_MESSAGE_REQUIRED_REASON = 'Enter a commit message to commit' as const
export type CommitEligibilityInputs = {
stagedCount: number
hasPartiallyStagedChanges: boolean
hasMessage: boolean
hasUnresolvedConflicts: boolean
isCommitting: boolean
isRemoteOperationActive: boolean
isPullRequestOperationActive?: boolean
}
export function resolveCommitDisabledReason(
inputs: Pick<
CommitEligibilityInputs,
'stagedCount' | 'hasPartiallyStagedChanges' | 'hasMessage' | 'hasUnresolvedConflicts'
>
): string | null {
if (inputs.hasUnresolvedConflicts) {
return 'Resolve conflicts before committing'
}
if (inputs.stagedCount === 0) {
return 'Stage at least one file to commit'
}
if (inputs.hasPartiallyStagedChanges) {
return 'Stage all changes before committing partially staged files'
}
if (!inputs.hasMessage) {
return COMMIT_MESSAGE_REQUIRED_REASON
}
return null
}
function isCommitGloballyBusy(inputs: CommitEligibilityInputs): boolean {
return (
inputs.isCommitting ||
inputs.isRemoteOperationActive ||
(inputs.isPullRequestOperationActive ?? false)
)
}
export function canSubmitCommit(inputs: CommitEligibilityInputs): boolean {
return !isCommitGloballyBusy(inputs) && resolveCommitDisabledReason(inputs) === null
}
// Why: the message field stays editable when the only blocker is an empty
// message; every other commit-disabled reason or in-flight op locks typing.
export function isCommitMessageFieldDisabled(inputs: CommitEligibilityInputs): boolean {
if (isCommitGloballyBusy(inputs)) {
return true
}
const commitDisabledReason = resolveCommitDisabledReason(inputs)
return commitDisabledReason !== null && commitDisabledReason !== COMMIT_MESSAGE_REQUIRED_REASON
}
@@ -1,6 +1,8 @@
import { join, sep } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import {
createCreatePrIntentRunToken,
createPrIntentCurrentTargetConflictsWithToken,
createPrIntentGitStatusMatchesToken,
createPrIntentRunTokenMatches,
getCreatePrIntentStagePaths,
@@ -44,6 +46,36 @@ describe('source-control Create PR intent flow helpers', () => {
expect(createPrIntentGitStatusMatchesToken(token, { branch: null })).toBe(false)
})
it('does not treat navigating to another worktree as an intent conflict', () => {
const wt1Path = join(sep, 'repo', 'wt-1')
const wt2Path = join(sep, 'repo', 'wt-2')
const token = createCreatePrIntentRunToken({
repoId: 'repo-1',
worktreeId: 'wt-1',
worktreePath: wt1Path,
branch: 'feature/pr'
})
expect(
createPrIntentCurrentTargetConflictsWithToken(token, {
repoId: 'repo-1',
worktreeId: 'wt-2',
worktreePath: wt2Path,
branch: 'other'
})
).toBe(false)
expect(
createPrIntentCurrentTargetConflictsWithToken(token, {
repoId: 'repo-1',
worktreeId: 'wt-1',
worktreePath: wt1Path,
branch: 'other'
})
).toBe(true)
})
it('stages only safe unstaged and untracked paths', () => {
const unresolved = {
path: 'conflicted.ts',
@@ -37,6 +37,18 @@ export function createPrIntentRunTokenMatches(
)
}
export function createPrIntentCurrentTargetConflictsWithToken(
token: CreatePrIntentRunToken,
current: CreatePrIntentCurrentTarget
): boolean {
// Worktree navigation is allowed during a run; only drift within the
// token's original worktree should be treated as a conflict.
if (current.worktreeId !== token.worktreeId) {
return false
}
return !createPrIntentRunTokenMatches(token, current)
}
export function createPrIntentGitStatusMatchesToken(
token: CreatePrIntentRunToken,
status: { branch?: string | null }
@@ -2,6 +2,7 @@
// Why: split from source-control-primary-action because the primary and dropdown are independent derivations with different priority ladders; together they exceed the max-lines budget and tangle unrelated concerns.
import type { PrimaryActionInputs } from './source-control-primary-action'
import { canSubmitCommit, resolveCommitDisabledReason } from './source-control-commit-eligibility'
import type { GitConflictOperation } from '../../../../shared/types'
import { shouldForcePushWithLeaseForUpstream } from '../../../../shared/git-upstream-status'
import { supportsHostedReviewCreation } from '../../../../shared/hosted-review-creation-providers'
@@ -177,22 +178,23 @@ export function resolveDropdownItems(inputs: DropdownActionInputs): DropdownEntr
// on a stale status snapshot.
const globalBusy = isCommitting || isRemoteOperationActive || isPullRequestOperationActive
const commitDisabledReason = (() => {
if (hasUnresolvedConflicts) {
return 'Resolve conflicts before committing'
}
if (!hasStaged) {
return 'Stage at least one file to commit'
}
if (hasPartiallyStagedChanges) {
return 'Stage all changes before committing partially staged files'
}
if (!hasMessage) {
return 'Enter a commit message to commit'
}
return null
})()
const canCommit = !globalBusy && commitDisabledReason === null
const commitDisabledReason = resolveCommitDisabledReason({
stagedCount,
hasPartiallyStagedChanges,
hasMessage,
hasUnresolvedConflicts
})
const canCommit =
!globalBusy &&
canSubmitCommit({
stagedCount,
hasPartiallyStagedChanges,
hasMessage,
hasUnresolvedConflicts,
isCommitting,
isRemoteOperationActive,
isPullRequestOperationActive
})
const commitItem: DropdownItem = {
kind: 'commit',
label: translate(
+1
View File
@@ -8408,6 +8408,7 @@
"createPrIntentPushing": "Pushing commits…",
"createPrIntentRemoteFailed": "Could not update the remote branch. Retry Create PR.",
"createPrIntentGeneratingDetails": "Generating review details…",
"createPrIntentBranchChangedDuringDetails": "Branch changed while generating review details. Retry Create PR.",
"createPrIntentCreatingReview": "Creating review…"
},
"SourceControlAgentActionDialog": {
+1
View File
@@ -8408,6 +8408,7 @@
"createPrIntentPushing": "Subiendo commits…",
"createPrIntentRemoteFailed": "No se pudo actualizar la rama remota. Vuelve a intentar Crear PR.",
"createPrIntentGeneratingDetails": "Generating review details…",
"createPrIntentBranchChangedDuringDetails": "Branch changed while generating review details. Retry Create PR.",
"createPrIntentCreatingReview": "Creating review…"
},
"SourceControlAgentActionDialog": {
+1
View File
@@ -8408,6 +8408,7 @@
"createPrIntentPushing": "コミットをプッシュ中…",
"createPrIntentRemoteFailed": "リモートブランチを更新できませんでした。Create PR を再試行してください。",
"createPrIntentGeneratingDetails": "Generating review details…",
"createPrIntentBranchChangedDuringDetails": "Branch changed while generating review details. Retry Create PR.",
"createPrIntentCreatingReview": "Creating review…"
},
"SourceControlAgentActionDialog": {
+1
View File
@@ -8408,6 +8408,7 @@
"createPrIntentPushing": "커밋을 푸시하는 중…",
"createPrIntentRemoteFailed": "원격 브랜치를 업데이트할 수 없습니다. Create PR을 다시 시도하세요.",
"createPrIntentGeneratingDetails": "Generating review details…",
"createPrIntentBranchChangedDuringDetails": "Branch changed while generating review details. Retry Create PR.",
"createPrIntentCreatingReview": "Creating review…"
},
"SourceControlAgentActionDialog": {
+1
View File
@@ -8408,6 +8408,7 @@
"createPrIntentPushing": "正在推送 commits…",
"createPrIntentRemoteFailed": "无法更新远程分支。请重试创建 PR。",
"createPrIntentGeneratingDetails": "Generating review details…",
"createPrIntentBranchChangedDuringDetails": "Branch changed while generating review details. Retry Create PR.",
"createPrIntentCreatingReview": "Creating review…"
},
"SourceControlAgentActionDialog": {
@@ -140,6 +140,196 @@ test.describe('Source Control AI PR generation worktree switching', () => {
})
})
test('keeps Create PR intent running after switching worktrees', async ({
orcaPage
}, testInfo) => {
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
const { primaryWorktreeId, prWorktreeId, prWorktreePath, primaryBranch } =
await seedCreatePrComposer(orcaPage)
const screenshotDir = path.join(
process.cwd(),
'validation-screenshots',
`create-pr-intent-switch-${Date.now()}`
)
mkdirSync(screenshotDir, { recursive: true })
await testInfo.attach('validation-screenshot-dir', {
body: screenshotDir,
contentType: 'text/plain'
})
await orcaPage.evaluate(
({ prWorktreeId, primaryBranch }) => {
const store =
window.__store ??
(() => {
throw new Error('window.__store is not available')
})()
const state = store.getState()
const worktree = Object.values(state.worktreesByRepo)
.flat()
.find((entry) => entry.id === prWorktreeId)
if (!worktree) {
throw new Error('Create PR intent worktree not found')
}
const repo = state.repos.find((entry) => entry.id === worktree.repoId)
if (!repo) {
throw new Error('Create PR intent repo not found')
}
const branch = worktree.branch.replace(/^refs\/heads\//, '')
type CreatePrIntentHostedReviewCall = {
repoPath: string
input: {
base?: string
head?: string
worktreePath?: string
}
}
const testWindow = window as unknown as {
__createPRIntentPayloads: CreatePrIntentHostedReviewCall[]
__createPRIntentPushStarted: boolean
__createPRIntentPushFinished: boolean
}
testWindow.__createPRIntentPayloads = []
testWindow.__createPRIntentPushStarted = false
testWindow.__createPRIntentPushFinished = false
store.setState((current) => ({
getHostedReviewCreationEligibility: async () => {
// Why: eligibility stays blocked until the delayed push completes,
// so this test exercises navigation during an in-flight intent run.
if (!testWindow.__createPRIntentPushFinished) {
return {
provider: 'github' as const,
review: null,
canCreate: false,
blockedReason: 'needs_push' as const,
nextAction: 'push' as const,
defaultBaseRef: primaryBranch,
head: branch
}
}
return {
provider: 'github' as const,
review: null,
canCreate: true,
blockedReason: null,
nextAction: null,
defaultBaseRef: primaryBranch,
title: 'Create PR intent after switching worktrees',
body: 'The intent flow should continue after navigation.',
head: branch
}
},
fetchHostedReviewForBranch: async () => null,
fetchPRForBranch: async () => null,
pushBranch: async (worktreeId) => {
if (worktreeId !== prWorktreeId) {
throw new Error(`Create PR intent pushed unexpected worktree ${worktreeId}`)
}
testWindow.__createPRIntentPushStarted = true
await new Promise((resolve) => setTimeout(resolve, 1500))
testWindow.__createPRIntentPushFinished = true
},
createHostedReview: async (repoPath, input) => {
testWindow.__createPRIntentPayloads.push({ repoPath, input })
return {
ok: true as const,
number: 74,
url: 'https://github.com/acme/orca/pull/74'
}
},
gitStatusByWorktree: {
...current.gitStatusByWorktree,
[worktree.id]: []
},
remoteStatusesByWorktree: {
...current.remoteStatusesByWorktree,
[worktree.id]: {
hasUpstream: true,
upstreamName: `origin/${branch}`,
ahead: 1,
behind: 0
}
}
}))
},
{ prWorktreeId, primaryBranch }
)
await openSourceControl(orcaPage, prWorktreeId)
const createPr = orcaPage.getByRole('button', { name: 'Create PR' }).first()
await expect(createPr).toBeVisible({ timeout: 10_000 })
await expect(createPr).toBeEnabled()
await createPr.click()
await expect
.poll(
() =>
orcaPage.evaluate(
() =>
(window as unknown as { __createPRIntentPushStarted: boolean })
.__createPRIntentPushStarted
),
{ timeout: 10_000 }
)
.toBe(true)
await openSourceControl(orcaPage, primaryWorktreeId)
await expect
.poll(
() =>
orcaPage.evaluate(
() =>
(window as unknown as { __createPRIntentPayloads: unknown[] })
.__createPRIntentPayloads.length
),
{ timeout: 10_000 }
)
.toBe(1)
const completedWhileSwitchedEvidence = await orcaPage.evaluate(() => {
const state = window.__store?.getState()
return {
activeWorktreeId: state?.activeWorktreeId,
rightSidebarTab: state?.rightSidebarTab
}
})
expect(completedWhileSwitchedEvidence.activeWorktreeId).toBe(primaryWorktreeId)
expect(completedWhileSwitchedEvidence.rightSidebarTab).toBe('source-control')
await openSourceControl(orcaPage, prWorktreeId)
const payloads = await orcaPage.evaluate(
() =>
(
window as unknown as {
__createPRIntentPayloads: {
repoPath: string
input: { base?: string; head?: string; worktreePath?: string }
}[]
}
).__createPRIntentPayloads
)
expect(payloads).toHaveLength(1)
expect(payloads[0]).toMatchObject({
input: {
base: primaryBranch,
head: 'e2e-secondary',
worktreePath: prWorktreePath
}
})
await orcaPage.screenshot({
path: path.join(screenshotDir, '01-create-pr-intent-completed-after-switch.png')
})
await writeEvidence(testInfo, screenshotDir, 'create-pr-intent-switch-evidence.json', {
expectedOriginalWorktreeId: prWorktreeId,
expectedOtherWorktreeId: primaryWorktreeId,
completedWhileSwitched: completedWhileSwitchedEvidence,
payloads
})
})
test('hydrates pending PR generation after Source Control remounts', async ({
orcaPage
}, testInfo) => {