fix: address pull reconciliation policy errors (#5562)

This commit is contained in:
Jinjing
2026-06-16 20:13:46 -07:00
committed by GitHub
parent dda576b8c1
commit 5903b4a742
8 changed files with 304 additions and 8 deletions
+2 -3
View File
@@ -213,9 +213,8 @@ async function gitPullWithArgs(
}
export async function gitPull(worktreePath: string, pushTarget?: GitPushTarget): Promise<void> {
// Why: plain `git pull` uses the user's configured pull strategy (merge by
// default) so diverged branches reconcile instead of erroring out. Conflicts
// surface through the existing conflict-resolution flow.
// Why: plain `git pull` honors the user's configured merge/rebase/ff policy.
// If no policy exists, Git's policy error is normalized with setup guidance.
await gitPullWithArgs(worktreePath, [], pushTarget)
}
@@ -0,0 +1,123 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { execFileSync } from 'child_process'
import { existsSync, mkdtempSync, writeFileSync } from 'fs'
import * as fs from 'fs/promises'
import * as path from 'path'
import { tmpdir } from 'os'
import { RelayContext } from './context'
import { GitHandler } from './git-handler'
import {
createMockDispatcher,
type MockDispatcher,
type RelayDispatcher
} from './git-handler-test-setup'
describe('GitHandler pull reconciliation', () => {
let dispatcher: MockDispatcher
let tmpDir: string
let gitEnv: NodeJS.ProcessEnv
let previousGitConfigGlobal: string | undefined
let previousGitConfigNosystem: string | undefined
beforeEach(() => {
tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-git-pull-reconciliation-'))
const globalGitConfigPath = path.join(tmpDir, 'global-gitconfig')
writeFileSync(globalGitConfigPath, '')
previousGitConfigGlobal = process.env.GIT_CONFIG_GLOBAL
previousGitConfigNosystem = process.env.GIT_CONFIG_NOSYSTEM
process.env.GIT_CONFIG_GLOBAL = globalGitConfigPath
process.env.GIT_CONFIG_NOSYSTEM = '1'
gitEnv = {
...process.env,
GIT_CONFIG_GLOBAL: globalGitConfigPath,
GIT_CONFIG_NOSYSTEM: '1'
}
dispatcher = createMockDispatcher()
const ctx = new RelayContext()
new GitHandler(dispatcher as unknown as RelayDispatcher, ctx)
})
afterEach(async () => {
restoreGitEnv('GIT_CONFIG_GLOBAL', previousGitConfigGlobal)
restoreGitEnv('GIT_CONFIG_NOSYSTEM', previousGitConfigNosystem)
await fs.rm(tmpDir, { recursive: true, force: true })
})
function execGit(cwd: string, args: string[]): string {
return execFileSync('git', args, {
cwd,
encoding: 'utf-8',
env: gitEnv,
stdio: 'pipe'
})
}
function configureIdentity(cwd: string): void {
execGit(cwd, ['config', 'user.email', 'test@test.com'])
execGit(cwd, ['config', 'user.name', 'Test'])
}
function commitAll(cwd: string, message: string): void {
execGit(cwd, ['add', '.'])
execGit(cwd, ['commit', '-m', message])
}
function createDivergentFixture(): string {
const bareDir = path.join(tmpDir, 'origin.git')
const consumerDir = path.join(tmpDir, 'consumer')
const producerDir = path.join(tmpDir, 'producer')
execGit(tmpDir, ['init', '--bare', bareDir])
execGit(tmpDir, ['clone', bareDir, consumerDir])
configureIdentity(consumerDir)
writeFileSync(path.join(consumerDir, 'base.txt'), 'base\n')
commitAll(consumerDir, 'initial')
execGit(consumerDir, ['push', '--set-upstream', 'origin', 'HEAD'])
execGit(tmpDir, ['clone', bareDir, producerDir])
configureIdentity(producerDir)
writeFileSync(path.join(producerDir, 'remote.txt'), 'remote\n')
commitAll(producerDir, 'remote')
execGit(producerDir, ['push'])
writeFileSync(path.join(consumerDir, 'local.txt'), 'local\n')
commitAll(consumerDir, 'local')
return consumerDir
}
it('explains how to configure a pull policy when divergent branches have no strategy', async () => {
const consumerDir = createDivergentFixture()
await expect(dispatcher.callRequest('git.pull', { worktreePath: consumerDir })).rejects.toThrow(
'Pull needs a Git pull policy for divergent branches. Configure one for this repository'
)
expect(execGit(consumerDir, ['status', '--short'])).toBe('')
})
it('preserves configured rebase pull semantics', async () => {
const consumerDir = createDivergentFixture()
execGit(consumerDir, ['config', 'pull.rebase', 'true'])
await expect(
dispatcher.callRequest('git.pull', { worktreePath: consumerDir })
).resolves.not.toThrow()
const parentRefs = execGit(consumerDir, ['log', '-1', '--pretty=%P']).trim().split(/\s+/)
expect(parentRefs).toHaveLength(1)
expect(existsSync(path.join(consumerDir, 'remote.txt'))).toBe(true)
expect(execGit(consumerDir, ['status', '--short'])).toBe('')
})
})
function restoreGitEnv(
name: 'GIT_CONFIG_GLOBAL' | 'GIT_CONFIG_NOSYSTEM',
value: string | undefined
): void {
if (value === undefined) {
delete process.env[name]
return
}
process.env[name] = value
}
+3 -3
View File
@@ -28,7 +28,7 @@ import {
import { refreshLocalBaseRefForWorktreeCreateOp } from './git-handler-local-base-ref-refresh'
import { checkIgnoredPathsOp, detectConflictOperation, getStatusOp } from './git-handler-status-ops'
import { resolveRelayPushTarget } from './git-handler-push-target'
import { normalizeGitErrorMessage, isNoUpstreamError } from '../shared/git-remote-error'
import { isNoUpstreamError, normalizeGitErrorMessage } from '../shared/git-remote-error'
import { upstreamOnlyCommitsArePatchEquivalent } from '../shared/git-upstream-status'
import { assertGitPushTargetShape } from '../shared/git-push-target-validation'
import { getPublishTargetStatus, type GitCommandRunner } from '../shared/git-publish-target-status'
@@ -658,8 +658,8 @@ export class GitHandler {
}
private async pull(params: Record<string, unknown>) {
// Why: plain `git pull` uses the user's configured pull strategy (merge by
// default) so diverged branches reconcile instead of erroring out.
// Why: plain `git pull` honors the user's configured merge/rebase/ff policy.
// If no policy exists, Git's policy error is normalized with setup guidance.
await this.pullWithArgs(params, [])
}
@@ -228,6 +228,22 @@ describe('CommitArea', () => {
expect(markup).toContain('commit-area-remote-error')
})
it('formats pull policy errors with command options', () => {
const markup = renderCommitArea({
...baseProps(),
remoteActionError:
'Pull needs a Git pull policy for divergent branches. Configure one for this repository or host, then try again: git config pull.rebase false (merge), git config pull.rebase true (rebase), or git config pull.ff only (fast-forward only).'
})
expect(markup).toContain('Pull needs a policy')
expect(markup).toContain('Diverged')
expect(markup).toContain('git config pull.rebase false')
expect(markup).toContain('git config pull.rebase true')
expect(markup).toContain('git config pull.ff only')
expect(markup).toContain('aria-label="Copy merge pull policy command"')
expect(markup).toContain('commit-area-remote-error')
})
it('keeps generation errors separate from commit and remote errors', () => {
const markup = renderCommitArea({
...baseProps(),
@@ -197,6 +197,10 @@ import {
type SourceControlRowOpenEvent
} from './source-control-split-open'
import { SourceControlAgentActionDialog } from './SourceControlAgentActionDialog'
import {
isPullPolicyRemoteActionError,
PullPolicyRemoteActionNotice
} from './source-control-pull-policy-error-notice'
import { SourceControlTextGenerationDialog } from './SourceControlTextGenerationDialog'
import { CreateHostedReviewComposer } from './CreateHostedReviewComposer'
import {
@@ -6356,7 +6360,9 @@ export function CommitArea({
</DialogContent>
</Dialog>
)}
{remoteActionError && (
{remoteActionError && isPullPolicyRemoteActionError(remoteActionError) ? (
<PullPolicyRemoteActionNotice id="commit-area-remote-error" />
) : remoteActionError ? (
<p
id="commit-area-remote-error"
role="alert"
@@ -6365,7 +6371,7 @@ export function CommitArea({
>
{remoteActionError}
</p>
)}
) : null}
{createPrIntentNotice && (
<div
id="commit-area-create-pr-intent"
@@ -0,0 +1,128 @@
import type React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { Check, Copy, TriangleAlert } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
const PULL_POLICY_ERROR_PREFIX = 'Pull needs a Git pull policy for divergent branches.'
const PULL_POLICY_OPTIONS = [
{
label: 'Merge',
description: 'Create a merge commit when local and remote both changed.',
command: 'git config pull.rebase false'
},
{
label: 'Rebase',
description: 'Replay local commits on top of the remote branch.',
command: 'git config pull.rebase true'
},
{
label: 'Fast-forward only',
description: 'Only pull when no merge or rebase is needed.',
command: 'git config pull.ff only'
}
] as const
export function isPullPolicyRemoteActionError(message: string): boolean {
return message.startsWith(PULL_POLICY_ERROR_PREFIX)
}
type PullPolicyRemoteActionNoticeProps = {
id: string
}
export function PullPolicyRemoteActionNotice({
id
}: PullPolicyRemoteActionNoticeProps): React.JSX.Element {
const [copiedCommand, setCopiedCommand] = useState<string | null>(null)
useEffect(() => {
if (!copiedCommand) {
return
}
const timeout = window.setTimeout(() => setCopiedCommand(null), 1400)
return () => window.clearTimeout(timeout)
}, [copiedCommand])
const handleCopyCommand = useCallback((command: string) => {
void window.api.ui.writeClipboardText(command)
setCopiedCommand(command)
}, [])
return (
<div
id={id}
role="alert"
aria-live="polite"
className="mt-2 min-w-0 overflow-hidden rounded-lg border border-destructive/20 bg-card text-card-foreground shadow-xs"
>
<div className="h-0.5 bg-destructive/70" aria-hidden="true" />
<div className="space-y-2.5 px-2.5 py-2.5">
<div className="grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-1.5">
<span className="mt-px inline-flex size-4 shrink-0 items-center justify-center rounded-full bg-destructive/10 text-destructive">
<TriangleAlert className="size-3" aria-hidden="true" />
</span>
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<span className="text-xs font-semibold text-foreground">Pull needs a policy</span>
<span className="shrink-0 rounded-full bg-destructive/10 px-1.5 py-px text-[10px] leading-4 font-semibold text-destructive">
Diverged
</span>
</div>
<p className="text-[11px] leading-4 text-muted-foreground">
This branch has local and remote commits. Run one command in this worktree or on the
SSH host, then try Pull or Sync again.
</p>
</div>
</div>
<div className="space-y-1.5">
{PULL_POLICY_OPTIONS.map((option) => {
const copied = copiedCommand === option.command
return (
<div
key={option.command}
className="rounded-md border border-border bg-muted/30 px-2 py-1.5"
>
<div className="flex min-w-0 items-start justify-between gap-2">
<div className="min-w-0">
<div className="text-[11px] leading-4 font-semibold text-foreground">
{option.label}
</div>
<p className="text-[11px] leading-4 text-muted-foreground">
{option.description}
</p>
</div>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
className="mt-0.5 shrink-0"
aria-label={`Copy ${option.label.toLowerCase()} pull policy command`}
onClick={() => handleCopyCommand(option.command)}
>
{copied ? (
<Check className="size-3" aria-hidden="true" />
) : (
<Copy className="size-3" aria-hidden="true" />
)}
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
{copied ? 'Copied' : 'Copy command'}
</TooltipContent>
</Tooltip>
</div>
<code className="mt-1 block rounded border border-border bg-background px-1.5 py-1 font-mono text-[11px] leading-4 break-words text-foreground">
{option.command}
</code>
</div>
)
})}
</div>
</div>
</div>
)
}
+14
View File
@@ -19,6 +19,20 @@ describe('normalizeGitErrorMessage', () => {
"Submodule 'find-cmux-followers' has remote changes. Pull inside the submodule, then try again."
)
})
it('explains how to configure a pull policy for divergent branches', () => {
const error = new Error(
'Command failed: git pull\n' +
'hint: You have divergent branches and need to specify how to reconcile them.\n' +
'fatal: Need to specify how to reconcile divergent branches.'
)
expect(normalizeGitErrorMessage(error, 'pull')).toBe(
'Pull needs a Git pull policy for divergent branches. Configure one for this repository ' +
'or host, then try again: git config pull.rebase false (merge), ' +
'git config pull.rebase true (rebase), or git config pull.ff only (fast-forward only).'
)
})
})
describe('formatSubmodulePushFailureDetail', () => {
+10
View File
@@ -16,6 +16,8 @@ const SUBMODULE_REMOTE_CHANGED_PATTERN =
/non-fast-forward|fetch first|updates were rejected|remote contains work that you do not have/i
const NORMALIZED_SUBMODULE_PUSH_FAILURE_PATTERN =
/(?:^|:\s)((?:Submodule '[^'\n]+'|A submodule) (?:has remote changes\. Pull inside the submodule, then try again\.|could not be pushed\. Resolve the submodule push error, then try again\.))(?:$|\s)/i
const DIVERGENT_PULL_RECONCILIATION_PATTERN =
/Need to specify how to reconcile divergent branches|divergent branches and need to specify how to reconcile them/i
export function stripCredentialsFromMessage(message: string): string {
return message.replace(USERPASS_URL_PATTERN, '$1').replace(HTTPS_TOKEN_URL_PATTERN, '$1')
@@ -97,6 +99,14 @@ export function normalizeGitErrorMessage(error: unknown, operation?: GitRemoteOp
return 'Branch has no upstream. Publish the branch first.'
}
if (operation === 'pull' && DIVERGENT_PULL_RECONCILIATION_PATTERN.test(raw)) {
return (
'Pull needs a Git pull policy for divergent branches. Configure one for this repository ' +
'or host, then try again: git config pull.rebase false (merge), ' +
'git config pull.rebase true (rebase), or git config pull.ff only (fast-forward only).'
)
}
if (
raw.includes('Your local changes to the following files would be overwritten') ||
raw.includes('Your local changes would be overwritten')