diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index a6ceb2dfe0..b419cc6d8a 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -1,4 +1,5 @@ import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { type Locator, type Page } from "@playwright/test"; @@ -498,6 +499,56 @@ test("Changes offers Push for a branch that was never pushed and the push sets i }); }); +test("Changes pushes and pulls a branch whose only remote is not named origin", async ({ + page, +}) => { + const workspace = await createWorkspaceWithRemote((repoPath) => { + execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath }); + // git pull stops on a branch that is both ahead and behind until it is told how to combine them. + execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath }); + }); + await openWorkspaceChangesSurface(page, workspace); + const primary = page.getByTestId("changes-primary-cta"); + + await test.step("a branch that is ahead offers Push and the push updates the remote", async () => { + await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 }); + commitAllWithGit(workspace.repoPath, "Local work"); + expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]"); + await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 }); + await primary.click(); + await expectInSyncWithRemote(workspace); + expect(remoteBranchSubjects(workspace, "main")).toContain("Local work"); + await expectNoGitActionLeft(page); + }); + await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => { + pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]); + fetchRemote(workspace, "doras-mono"); + expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]"); + await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 }); + await primary.click(); + await expectInSyncWithRemote(workspace); + expect(localBranchSubjects(workspace)).toEqual( + expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]), + ); + await expectNoGitActionLeft(page); + }); + await test.step("a branch that is ahead and behind pulls and then pushes", async () => { + await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n"); + commitAllWithGit(workspace.repoPath, "More local work"); + pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]); + fetchRemote(workspace, "doras-mono"); + expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]"); + await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 }); + await page.getByTestId("changes-primary-cta-caret").click(); + await page.getByTestId("changes-menu-pull-and-push").click(); + await expectInSyncWithRemote(workspace); + expect(remoteBranchSubjects(workspace, "main")).toEqual( + expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]), + ); + await expectNoGitActionLeft(page); + }); +}); + test("Changes selects exact local and remote bases and retains the selection after reload", async ({ page, }, testInfo) => { @@ -2202,6 +2253,79 @@ function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string | return line ? (line.split("\t")[0] ?? null) : null; } +// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]". +function trackingStatus(workspace: RemoteWorkspace): string { + const status = execFileSync("git", ["status", "-sb"], { + cwd: workspace.repoPath, + encoding: "utf8", + }); + return status.split("\n")[0] ?? ""; +} + +// Neither ahead nor behind, which a push reaches only after the remote accepted it. +async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise { + await expect + .poll(() => trackingStatus(workspace), { timeout: 30_000 }) + .toMatch(/^## [^ ]+\.\.\.[^ ]+$/); +} + +// A clean main that is in sync with its remote has no git action, so the button is gone. +async function expectNoGitActionLeft(page: Page): Promise { + await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 }); +} + +function localBranchSubjects(workspace: RemoteWorkspace): string[] { + return commitSubjects(workspace.repoPath, "HEAD"); +} + +function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] { + return commitSubjects(workspace.remotePath, branch); +} + +function commitSubjects(repoPath: string, revision: string): string[] { + const log = execFileSync("git", ["log", "--format=%s", revision], { + cwd: repoPath, + encoding: "utf8", + }); + return log.trim().split("\n"); +} + +// Paseo fetches only origin in the background, so the checkout learns about another remote's +// commits when the user fetches it. +function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void { + execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath }); +} + +// Lands commits on the remote's main from a second clone, as a teammate's push does. +function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void { + const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-")); + try { + execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]); + for (const subject of subjects) { + execFileSync( + "git", + [ + "-c", + "user.name=Teammate", + "-c", + "user.email=teammate@paseo.test", + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "--allow-empty", + "-m", + subject, + ], + { cwd: clonePath }, + ); + } + execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath }); + } finally { + rmSync(clonePath, { recursive: true, force: true }); + } +} + // Empty until the branch has an upstream. function branchUpstream(workspace: RemoteWorkspace, branch: string): string { return execFileSync( diff --git a/packages/app/src/git/policy.test.ts b/packages/app/src/git/policy.test.ts index c49d55a395..d4b734c0bf 100644 --- a/packages/app/src/git/policy.test.ts +++ b/packages/app/src/git/policy.test.ts @@ -7,6 +7,7 @@ import { buildGitActions, isCurrentBranchBase, canMergeIntoLocalBase, + readSyncRemotes, readUpstreamState, type BuildGitActionsInput, } from "./policy"; @@ -60,9 +61,11 @@ function githubStatus(overrides: Partial = {}): GithubM function createInput( overrides: Partial> & { pullRequestGithub?: unknown; + // Shorthand for a branch that both Pull and Push have a remote for. + hasRemote?: boolean; } = {}, ): BuildGitActionsInput { - const { pullRequestGithub = null, ...rest } = overrides; + const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides; return { isGit: true, githubFeaturesEnabled: true, @@ -76,8 +79,8 @@ function createInput( pullRequestIsMerged: false, pullRequestMergeable: "UNKNOWN", mergeCapability: deriveMergeCapability(pullRequestGithub), - hasRemote: false, - hasFirstPushRemote: rest.hasRemote ?? false, + hasPullRemote: hasRemote, + hasPushRemote: hasRemote, upstream: "tracked", isPaseoOwnedWorktree: false, isOnBaseBranch: true, @@ -176,6 +179,10 @@ function pushActionOf(actions: ReturnType) { return actions.secondary.find((action) => action.id === "push"); } +function pullAndPushActionOf(actions: ReturnType) { + return actions.secondary.find((action) => action.id === "pull-and-push"); +} + describe("git-actions-policy", () => { afterEach(async () => { await i18n.changeLanguage("en"); @@ -433,7 +440,7 @@ describe("git-actions-policy", () => { }); it("does not offer Push when Git pushes the branch to another remote", () => { - const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false })); + const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false })); const pushAction = pushActionOf(actions); expect(actions.primary?.id).not.toBe("push"); @@ -441,13 +448,142 @@ describe("git-actions-policy", () => { "Push isn't available here because this branch is not connected to a remote yet", ); }); + }); - it("keeps offering Push in a Paseo worktree when Git pushes the branch to another remote", () => { + // The daemon reports where Pull and Push go for the branch, so the remote's name never matters. + describe("a branch that tracks a remote other than origin", () => { + const tracksDorasMono = readSyncRemotes({ + hasRemote: false, + pullRemote: "doras-mono", + pushRemote: "doras-mono", + upstreamState: "tracked", + aheadOfOrigin: 1, + isPaseoOwnedWorktree: false, + }); + + it("offers Push when the branch is ahead", () => { const actions = buildGitActions( - createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }), + createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }), ); expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + expect(pushActionOf(actions)).toMatchObject({ + disabled: false, + unavailableMessage: undefined, + }); + }); + + it("offers Pull when the branch is behind", () => { + const actions = buildGitActions( + createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }), + ); + + expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" }); + }); + + it("offers Pull first and Pull and push when the branch is ahead and behind", () => { + const actions = buildGitActions( + createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }), + ); + + expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" }); + expect(pullAndPushActionOf(actions)).toMatchObject({ + disabled: false, + unavailableMessage: undefined, + }); + expect(pushActionOf(actions)?.unavailableMessage).toBe( + "Push isn't available yet because there are newer changes to bring in first", + ); + }); + + // `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote. + const pullOnly = readSyncRemotes({ + hasRemote: false, + pullRemote: "upstream", + pushRemote: null, + upstreamState: "tracked", + aheadOfOrigin: 1, + isPaseoOwnedWorktree: false, + }); + + it("does not offer Push when it would land on a differently named upstream branch", () => { + const actions = buildGitActions( + createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }), + ); + + expect(actions.primary?.id).not.toBe("push"); + expect(pushActionOf(actions)?.unavailableMessage).toBe( + "Push isn't available here because this branch is not connected to a remote yet", + ); + }); + + it("still offers Pull for that branch, and not Pull and push", () => { + const actions = buildGitActions( + createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }), + ); + + expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" }); + expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe( + "Pull and push isn't available here because this branch is not connected to a remote yet", + ); + }); + }); + + describe("readSyncRemotes", () => { + it("uses the remotes the daemon reports", () => { + expect( + readSyncRemotes({ + hasRemote: true, + pullRemote: null, + pushRemote: "origin", + upstreamState: "none", + aheadOfOrigin: null, + isPaseoOwnedWorktree: false, + }), + ).toEqual({ hasPullRemote: false, hasPushRemote: true }); + }); + + // The rest covers a daemon that predates pullRemote and pushRemote. + const tracked = { + upstreamState: "tracked", + aheadOfOrigin: 1, + isPaseoOwnedWorktree: false, + } as const; + const neverPushed = { + upstreamState: "none", + aheadOfOrigin: null, + isPaseoOwnedWorktree: false, + } as const; + + it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => { + expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({ + hasPullRemote: true, + hasPushRemote: true, + }); + expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({ + hasPullRemote: false, + hasPushRemote: false, + }); + }); + + it("makes a regular checkout's first push only where an older daemon confirmed it", () => { + expect( + readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }), + ).toMatchObject({ hasPushRemote: true }); + expect( + readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }), + ).toMatchObject({ hasPushRemote: false }); + }); + + it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => { + expect( + readSyncRemotes({ + ...neverPushed, + hasRemote: true, + firstPushRemote: null, + isPaseoOwnedWorktree: true, + }), + ).toMatchObject({ hasPushRemote: true }); }); }); diff --git a/packages/app/src/git/policy.ts b/packages/app/src/git/policy.ts index 37f898c0e4..ed03f30085 100644 --- a/packages/app/src/git/policy.ts +++ b/packages/app/src/git/policy.ts @@ -96,7 +96,41 @@ export function readUpstreamState( return status.isPaseoOwnedWorktree ? "none" : "unknown"; } -export interface BuildGitActionsInput { +export interface SyncRemotes { + /** Pull has a remote to fetch the branch from. Not limited to origin. */ + hasPullRemote: boolean; + /** Push has a remote to send the branch to. Not limited to origin. */ + hasPushRemote: boolean; +} + +export function readSyncRemotes( + status: Pick< + CheckoutStatusPayload, + | "pullRemote" + | "pushRemote" + | "hasRemote" + | "firstPushRemote" + | "upstreamState" + | "aheadOfOrigin" + | "isPaseoOwnedWorktree" + >, +): SyncRemotes { + if (status.pullRemote !== undefined && status.pushRemote !== undefined) { + return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null }; + } + // COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor + // reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have + // origin. They make a first push from a Paseo worktree, and from a regular checkout only where + // they report firstPushRemote. + const isFirstPush = readUpstreamState(status) === "none"; + const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null; + return { + hasPullRemote: status.hasRemote, + hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush), + }; +} + +export interface BuildGitActionsInput extends SyncRemotes { isGit: boolean; githubFeaturesEnabled: boolean; /** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */ @@ -111,9 +145,6 @@ export interface BuildGitActionsInput { pullRequestIsMerged: boolean; pullRequestMergeable: PullRequestMergeable; mergeCapability: MergeCapability | null; - hasRemote: boolean; - /** The daemon confirmed where a first push publishes the branch. */ - hasFirstPushRemote: boolean; upstream: GitUpstreamState; isPaseoOwnedWorktree: boolean; isOnBaseBranch: boolean; @@ -572,11 +603,11 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable } function canPull(input: BuildGitActionsInput): boolean { - return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0; + return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0; } function canPush(input: BuildGitActionsInput): boolean { - return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0; + return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0; } function hasPushableCommits(input: BuildGitActionsInput): boolean { @@ -585,9 +616,7 @@ function hasPushableCommits(input: BuildGitActionsInput): boolean { return (input.aheadOfOrigin ?? 0) > 0; case "none": // A first push, which sets the upstream. The commits to send are the ones ahead of the base. - // Paseo worktrees always publish to origin. A regular checkout publishes only where the - // daemon confirmed Git would push the branch too, so a fork setup is not sent to origin. - return input.aheadCount > 0 && (input.isPaseoOwnedWorktree || input.hasFirstPushRemote); + return input.aheadCount > 0; case "gone": case "unknown": // The branch has an upstream that is deleted or unreadable, so nothing counts the commits @@ -678,7 +707,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean { } function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined { - if (!input.hasRemote) { + if (!input.hasPullRemote) { return i18n.t("workspace.git.actions.unavailable.pullNoRemote"); } if (input.hasUncommittedChanges) { @@ -694,7 +723,7 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi } function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined { - if (!input.hasRemote) { + if (!input.hasPushRemote) { return i18n.t("workspace.git.actions.unavailable.pushNoRemote"); } if ((input.behindOfOrigin ?? 0) > 0) { @@ -706,14 +735,11 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi if (input.upstream === "gone") { return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone"); } - if (input.upstream === "none" && input.aheadCount > 0) { - return i18n.t("workspace.git.actions.unavailable.pushNoRemote"); - } return i18n.t("workspace.git.actions.unavailable.pushNothing"); } function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined { - if (!input.hasRemote) { + if (!input.hasPullRemote || !input.hasPushRemote) { return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote"); } if (input.hasUncommittedChanges) { diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index 2d3a82cc7c..9b11e8a275 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -15,11 +15,13 @@ import { isCurrentBranchBase, canMergeIntoLocalBase, narrowPullRequestState, + readSyncRemotes, readUpstreamState, type BuildGitActionsInput, type GitAction, type GitActions, type GitUpstreamState, + type SyncRemotes, } from "@/git/policy"; import { deriveMergeCapability } from "@/git/merge-capability"; import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages"; @@ -123,15 +125,15 @@ interface DeriveGitActionsStateArgs { baseRef: string | undefined; } -interface DerivedGitActionsState { +const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false }; + +interface DerivedGitActionsState extends SyncRemotes { actionsDisabled: boolean; aheadCount: number; behindBaseCount: number; aheadOfOrigin: number | null; behindOfOrigin: number | null; hasPullRequest: boolean; - hasRemote: boolean; - hasFirstPushRemote: boolean; upstream: GitUpstreamState; isPaseoOwnedWorktree: boolean; isOnBaseBranch: boolean; @@ -183,8 +185,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio actionsDisabled, ...extractGitCommitCounts(gitStatus), hasPullRequest: Boolean(prStatus?.url), - hasRemote: gitStatus?.hasRemote ?? false, - hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null, + ...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES), upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown", isPaseoOwnedWorktree, isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef), @@ -673,8 +674,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use aheadOfOrigin, behindOfOrigin, hasPullRequest, - hasRemote, - hasFirstPushRemote, + hasPullRemote, + hasPushRemote, upstream, isPaseoOwnedWorktree, isOnBaseBranch, @@ -706,8 +707,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use pullRequestIsMerged: prStatus?.isMerged ?? false, pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN", mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github), - hasRemote, - hasFirstPushRemote, + hasPullRemote, + hasPushRemote, upstream, isPaseoOwnedWorktree, isOnBaseBranch, @@ -816,8 +817,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use }; }, [ isGit, - hasRemote, - hasFirstPushRemote, + hasPullRemote, + hasPushRemote, upstream, hasPullRequest, prStatus?.url, diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 679774f660..29f36feb28 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -5824,10 +5824,20 @@ const CheckoutStatusCommonSchema = z.object({ // as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that // predate it, which report all but "tracked" as a null upstreamRef. upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(), - // The remote a first push publishes currentBranch to, when the daemon can confirm git would - // push the branch there too. Null when there is no such remote, as when origin is missing or - // git is set to push the branch to another remote (branch..pushRemote, - // remote.pushDefault). Absent from daemons that predate it. + // The remote Pull fetches currentBranch from, as git names it: the remote of the branch's + // configured upstream, which is not necessarily origin, or "." when the upstream is a local + // branch. Null when the branch has no upstream. Absent from daemons that predate it, which + // pull only in checkouts that have origin (hasRemote). + pullRemote: z.string().nullable().optional(), + // The remote Push sends currentBranch to, resolved as the daemon's push resolves it. It is not + // necessarily origin. Null when Push has nowhere to send the branch, as when it has no upstream + // and origin is missing, or git is set to push it to another remote (branch..pushRemote, + // remote.pushDefault). Absent from daemons that predate it, which push only in checkouts that + // have origin (hasRemote). + pushRemote: z.string().nullable().optional(), + // "origin" when Push sends currentBranch to origin, and null otherwise. Clients that predate + // pushRemote read it to offer a first push; newer clients read pushRemote instead. Absent from + // daemons that predate it. firstPushRemote: z.string().nullable().optional(), forgeWeb: ForgeWebSchema.optional(), }); diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index e81fab14b3..b6e3fb5975 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -72,6 +72,41 @@ test("base selection RPCs are correlated while older checkout and branch message expect(WorkspaceBaseBranchSetResponseSchema.parse(response)).toEqual(response); }); +test("checkout status stays valid without pull and push remotes and retains them when sent", () => { + const olderDaemonPayload = { + cwd: "/repo", + requestId: "status", + error: null, + isGit: true, + isPaseoOwnedWorktree: false, + repoRoot: "/repo", + currentBranch: "main", + isDirty: false, + baseRef: "main", + aheadBehind: null, + aheadOfOrigin: 1, + behindOfOrigin: 2, + hasRemote: false, + remoteUrl: null, + upstreamRef: "refs/remotes/doras-mono/main", + upstreamState: "tracked", + firstPushRemote: null, + }; + const parse = (payload: Record) => + CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload; + + const older = parse(olderDaemonPayload); + expect(older.pullRemote).toBeUndefined(); + expect(older.pushRemote).toBeUndefined(); + expect( + parse({ ...olderDaemonPayload, pullRemote: "doras-mono", pushRemote: "doras-mono" }), + ).toMatchObject({ pullRemote: "doras-mono", pushRemote: "doras-mono" }); + expect(parse({ ...olderDaemonPayload, pullRemote: "upstream", pushRemote: null })).toMatchObject({ + pullRemote: "upstream", + pushRemote: null, + }); +}); + test("terminal listings accept older rows and retain new per-terminal directories", () => { const response = { type: "list_terminals_response", diff --git a/packages/server/src/server/checkout/status-projection.ts b/packages/server/src/server/checkout/status-projection.ts index b2a2232dde..7a8a800826 100644 --- a/packages/server/src/server/checkout/status-projection.ts +++ b/packages/server/src/server/checkout/status-projection.ts @@ -69,6 +69,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, upstreamState: snapshot.git.upstreamState, hasRemote: snapshot.git.hasRemote, + pullRemote: snapshot.git.pullRemote, + pushRemote: snapshot.git.pushRemote, firstPushRemote: snapshot.git.firstPushRemote, remoteUrl: snapshot.git.remoteUrl, ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), @@ -94,6 +96,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({ behindOfOrigin: snapshot.git.behindOfOrigin ?? null, upstreamState: snapshot.git.upstreamState, hasRemote: snapshot.git.hasRemote, + pullRemote: snapshot.git.pullRemote, + pushRemote: snapshot.git.pushRemote, firstPushRemote: snapshot.git.firstPushRemote, remoteUrl: snapshot.git.remoteUrl, ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index f55a657f08..a689429371 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -10050,7 +10050,7 @@ test("workspace PR status survives session cleanup and reconnect", async () => { branchRemoteName: "origin", branchMergeRef: "refs/heads/feature", upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, pullRequestLookupTarget: { headRef: "feature" }, }; const githubStub = { diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 252ea81f54..170499f1ec 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -248,6 +248,8 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna behindOfOrigin: null, upstreamState: "none", hasRemote: false, + pullRemote: null, + pushRemote: null, firstPushRemote: null, diffStat: null, }, diff --git a/packages/server/src/server/workspace-git-service.observation.integration.test.ts b/packages/server/src/server/workspace-git-service.observation.integration.test.ts index e15cfae9b4..1fa7148f36 100644 --- a/packages/server/src/server/workspace-git-service.observation.integration.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.integration.test.ts @@ -42,7 +42,7 @@ function createFacts(cwd: string): CheckoutSnapshotFacts { branchRemoteName: null, branchMergeRef: null, upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, pullRequestLookupTarget: { headRef: "main" }, }; } diff --git a/packages/server/src/server/workspace-git-service.observation.test.ts b/packages/server/src/server/workspace-git-service.observation.test.ts index 2ab85f4bc6..a47c6f793b 100644 --- a/packages/server/src/server/workspace-git-service.observation.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.test.ts @@ -73,7 +73,7 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts { branchRemoteName: null, branchMergeRef: null, upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, pullRequestLookupTarget: { headRef: "main" }, }; } @@ -1020,7 +1020,7 @@ describe("WorkspaceGitService checkout observation", () => { branchRemoteName: null, branchMergeRef: null, upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, }; }); const runGitFetch = vi.fn(async () => ({ @@ -1164,7 +1164,7 @@ describe("WorkspaceGitService checkout observation", () => { branchRemoteName: "origin", branchMergeRef: `refs/heads/${branch}`, upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, } satisfies CheckoutSnapshotFacts; }); const getCheckoutStatus = vi.fn(async (cwd: string) => diff --git a/packages/server/src/server/workspace-git-service.primitive.test.ts b/packages/server/src/server/workspace-git-service.primitive.test.ts index 4e831a7d01..c1fc132381 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -81,7 +81,7 @@ function createCheckoutFacts( branchRemoteName: null, branchMergeRef: null, upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, pullRequestLookupTarget: { headRef: "main" }, ...overrides, }; diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index c3c7171deb..b8b3b508a3 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -172,7 +172,7 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts { branchRemoteName: "origin", branchMergeRef: "refs/heads/main", upstreamStatus: { state: "none" }, - firstPushRemote: null, + pushTarget: null, pullRequestLookupTarget: { headRef: "main" }, }; } diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index cff0025322..2295adb557 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -185,6 +185,8 @@ export interface WorkspaceGitRuntimeSnapshot { behindOfOrigin: number | null; upstreamState: UpstreamState; hasRemote: boolean; + pullRemote: string | null; + pushRemote: string | null; firstPushRemote: string | null; diffStat: { additions: number; deletions: number } | null; }; @@ -3785,6 +3787,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { behindOfOrigin: checkoutStatus.behindOfOrigin, upstreamState: checkoutStatus.upstreamState, hasRemote: checkoutStatus.hasRemote, + pullRemote: checkoutStatus.pullRemote, + pushRemote: checkoutStatus.pushRemote, firstPushRemote: checkoutStatus.firstPushRemote, diffStat, }; @@ -4442,6 +4446,8 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot { behindOfOrigin: null, upstreamState: "none", hasRemote: false, + pullRemote: null, + pushRemote: null, firstPushRemote: null, diffStat: null, }, diff --git a/packages/server/src/utils/checkout-git-ref-derived.test.ts b/packages/server/src/utils/checkout-git-ref-derived.test.ts index 0b3566fbe5..aa13dd9109 100644 --- a/packages/server/src/utils/checkout-git-ref-derived.test.ts +++ b/packages/server/src/utils/checkout-git-ref-derived.test.ts @@ -67,7 +67,7 @@ function seedFeatureCheckout(): { ref: "refs/remotes/origin/main", aheadBehind: { ahead: 0, behind: 0 }, }, - firstPushRemote: "origin", + pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" }, pullRequestLookupTarget: { headRef: "feature" }, }, }; @@ -111,7 +111,7 @@ function seedMainCheckout(): { ref: "refs/remotes/origin/main", aheadBehind: { ahead: 1, behind: 0 }, }, - firstPushRemote: "origin", + pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" }, pullRequestLookupTarget: { headRef: "main" }, }, }; diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index cebfb86fdc..d6248fbd7b 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -251,12 +251,13 @@ function getBranchUpstream(cwd: string): string | null { function setupRemoteTrackingMain( repoDir: string, tempDir: string, + remoteName = "origin", ): { remoteDir: string; cloneDir: string } { const remoteDir = join(tempDir, "remote.git"); const cloneDir = join(tempDir, "upstream-clone"); execFileSync("git", ["init", "--bare", "-b", "main", remoteDir]); - execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir }); - execFileSync("git", ["push", "-u", "origin", "main"], { cwd: repoDir }); + execFileSync("git", ["remote", "add", remoteName, remoteDir], { cwd: repoDir }); + execFileSync("git", ["push", "-u", remoteName, "main"], { cwd: repoDir }); execFileSync("git", ["clone", remoteDir, cloneDir]); execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: cloneDir }); execFileSync("git", ["config", "user.name", "Test"], { cwd: cloneDir }); @@ -1028,6 +1029,7 @@ const x = 1; return; } expect(status.upstreamRef).toBe("refs/remotes/origin/other-name"); + expect(status).toMatchObject({ pullRemote: "origin", pushRemote: "origin" }); }); it("reports the upstream when the repo's only remote is not origin", async () => { @@ -1054,7 +1056,31 @@ const x = 1; const status = await getCheckoutStatus(repoDir); - expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: "origin" }); + expect(status).toMatchObject({ + upstreamState: "none", + pullRemote: null, + pushRemote: "origin", + firstPushRemote: "origin", + }); + }); + + // Apps that predate pushRemote offer a regular checkout's first push from firstPushRemote. + it("reports origin as the first push remote when a push refspec names the branch on origin", async () => { + setupRemoteTrackingMain(repoDir, tempDir); + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + execFileSync("git", ["config", "branch.feature.pushRemote", "origin"], { cwd: repoDir }); + execFileSync("git", ["config", "remote.origin.push", "HEAD:refs/heads/published"], { + cwd: repoDir, + }); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + + const status = await getCheckoutStatus(repoDir); + + expect(status).toMatchObject({ + upstreamState: "none", + pushRemote: "origin", + firstPushRemote: "origin", + }); }); // The daemon's first push goes to origin. When git would send the branch to a fork instead, @@ -1079,6 +1105,7 @@ const x = 1; expect(status).toMatchObject({ upstreamState: "none", hasRemote: true, + pushRemote: null, firstPushRemote: null, }); const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"]) @@ -1092,8 +1119,10 @@ const x = 1; execFileSync("git", ["checkout", "-b", "feature", "--track", "main"], { cwd: repoDir }); commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + const status = await getCheckoutStatus(repoDir); await pushCurrentBranch(repoDir); + expect(status).toMatchObject({ pullRemote: ".", pushRemote: "origin" }); const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir }) .toString() .trim(); @@ -1195,8 +1224,11 @@ const x = 1; const worktreeDir = worktree.worktreePath; commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit"); + const status = await getCheckoutStatus(worktreeDir, { paseoHome }); await pushCurrentBranch(worktreeDir, undefined, { paseoHome }); + expect(status).toMatchObject({ upstreamState: "none", pushRemote: "origin" }); + const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir }) .toString() .trim(); @@ -1225,9 +1257,238 @@ const x = 1; isGit: true, upstreamState: "none", hasRemote: false, + pullRemote: null, + pushRemote: null, firstPushRemote: null, }); await expect(pushCurrentBranch(repoDir)).rejects.toThrow("Remote 'origin' is not configured."); + await expect(pullCurrentBranch(repoDir)).rejects.toThrow( + "There is no tracking information for the current branch.", + ); + }); + + // Git decides whether a pull has something to pull. In a single-branch clone it pulls the one + // fetched branch into a branch that has no upstream. + it("pulls a branch with no upstream where git itself can pull", async () => { + const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir); + const singleBranchDir = join(tempDir, "single-branch"); + execFileSync("git", [ + "clone", + "--single-branch", + "--branch", + "main", + remoteDir, + singleBranchDir, + ]); + execFileSync("git", ["checkout", "-b", "local"], { cwd: singleBranchDir }); + commitFile(cloneDir, "remote.txt", "remote\n", "remote commit"); + execFileSync("git", ["push"], { cwd: cloneDir }); + + const status = await getCheckoutStatus(singleBranchDir); + await pullCurrentBranch(singleBranchDir); + + expect(status).toMatchObject({ upstreamState: "none", pullRemote: null }); + const pulledHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: singleBranchDir }); + const remoteHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: cloneDir }); + expect(pulledHead.toString()).toBe(remoteHead.toString()); + }); + + // A checkout does not need a remote named origin. Pull and Push follow the branch's upstream. + describe("a checkout whose only remote is not origin", () => { + function headOf(cwd: string, ref = "HEAD"): string { + return execFileSync("git", ["rev-parse", ref], { cwd }).toString().trim(); + } + + function branchesOf(gitDir: string): string { + return execFileSync("git", ["--git-dir", gitDir, "branch", "--list"]).toString().trim(); + } + + function pushRemoteCommits(cloneDir: string, count: number): void { + for (let index = 1; index <= count; index += 1) { + commitFile(cloneDir, `remote-${index}.txt`, "remote\n", `remote commit ${index}`); + } + execFileSync("git", ["push"], { cwd: cloneDir }); + } + + it("pushes a branch that is ahead to its upstream", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono"); + commitFile(repoDir, "local.txt", "local\n", "local commit"); + + const status = await getCheckoutStatus(repoDir); + await pushCurrentBranch(repoDir); + + expect(status).toMatchObject({ + upstreamRef: "refs/remotes/doras-mono/main", + upstreamState: "tracked", + aheadOfOrigin: 1, + behindOfOrigin: 0, + hasRemote: false, + pullRemote: "doras-mono", + pushRemote: "doras-mono", + }); + expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir)); + }); + + it("pulls a branch that is behind from its upstream", async () => { + const { cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono"); + pushRemoteCommits(cloneDir, 2); + execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir }); + + const status = await getCheckoutStatus(repoDir); + await pullCurrentBranch(repoDir); + + expect(status).toMatchObject({ + upstreamState: "tracked", + aheadOfOrigin: 0, + behindOfOrigin: 2, + pullRemote: "doras-mono", + }); + expect(headOf(repoDir)).toBe(headOf(cloneDir)); + }); + + it("pulls and then pushes a branch that is both ahead and behind", async () => { + const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono"); + // Git refuses to pull a diverged branch until it is told how to reconcile it. + execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoDir }); + pushRemoteCommits(cloneDir, 2); + commitFile(repoDir, "local.txt", "local\n", "local commit"); + const localCommit = headOf(repoDir); + execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir }); + + const status = await getCheckoutStatus(repoDir); + await pullCurrentBranch(repoDir); + await pushCurrentBranch(repoDir); + + expect(status).toMatchObject({ + upstreamState: "tracked", + aheadOfOrigin: 1, + behindOfOrigin: 2, + pullRemote: "doras-mono", + pushRemote: "doras-mono", + }); + expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir)); + execFileSync("git", ["merge-base", "--is-ancestor", localCommit, "refs/heads/main"], { + cwd: remoteDir, + }); + execFileSync("git", ["merge-base", "--is-ancestor", headOf(cloneDir), "refs/heads/main"], { + cwd: remoteDir, + }); + expect(await getCheckoutStatus(repoDir)).toMatchObject({ + aheadOfOrigin: 0, + behindOfOrigin: 0, + }); + }); + + // Git's default refuses this push. In a checkout that has origin Paseo has always made it, + // which is how a PR checkout reaches the contributor's branch. It is not extended to + // checkouts without origin, where the upstream is often a shared base branch. + it("does not push a branch to a differently named upstream branch", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream"); + execFileSync("git", ["checkout", "-b", "feature", "--track", "upstream/main"], { + cwd: repoDir, + }); + const remoteMainBefore = headOf(remoteDir, "refs/heads/main"); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + + const status = await getCheckoutStatus(repoDir); + await expect(pushCurrentBranch(repoDir)).rejects.toThrow( + "Push did not send 'feature' to 'upstream/main'", + ); + + expect(status).toMatchObject({ + upstreamState: "tracked", + aheadOfOrigin: 1, + pullRemote: "upstream", + pushRemote: null, + }); + expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore); + }); + + // Push follows the upstream only when `git push` would update it too. + it.each([ + { + name: "the branch's pushRemote names a fork", + config: [["branch.main.pushRemote", "fork"]], + }, + { name: "remote.pushDefault names a fork", config: [["remote.pushDefault", "fork"]] }, + { + name: "the branch's pushRemote has a push refspec", + config: [ + ["branch.main.pushRemote", "fork"], + ["remote.fork.push", "HEAD:refs/heads/published"], + ], + }, + { + name: "the upstream remote has a push refspec", + config: [["remote.upstream.push", "HEAD:refs/heads/other"]], + }, + { + name: "the push remote shares the upstream's remote-tracking refs", + config: [ + ["branch.main.pushRemote", "fork"], + ["remote.fork.fetch", "+refs/heads/*:refs/remotes/upstream/*"], + ], + }, + { name: "push.default is nothing", config: [["push.default", "nothing"]] }, + // Matching mode sends a branch only when the remote still has it, which the checkout + // cannot know. + { name: "push.default is matching", config: [["push.default", "matching"]] }, + ])("does not push when $name", async ({ config }) => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream"); + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir }); + for (const [key, value] of config) { + execFileSync("git", ["config", key, value], { cwd: repoDir }); + } + const remoteMainBefore = headOf(remoteDir, "refs/heads/main"); + commitFile(repoDir, "local.txt", "local\n", "local commit"); + + const status = await getCheckoutStatus(repoDir); + await expect(pushCurrentBranch(repoDir)).rejects.toThrow( + "Push did not send 'main' to 'upstream/main' because Git's push settings do not confirm", + ); + + expect(status).toMatchObject({ + upstreamState: "tracked", + aheadOfOrigin: 1, + pullRemote: "upstream", + pushRemote: null, + }); + expect(branchesOf(remoteDir)).toBe("* main"); + expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore); + expect(branchesOf(forkDir)).toBe(""); + }); + + // Paseo writes this configuration for a PR checkout, so that its push reaches the + // contributor's branch. + it("pushes a Paseo worktree to the push refspec Paseo configured for it", async () => { + setupRemoteTrackingMain(repoDir, tempDir, "upstream"); + const prRemoteDir = join(tempDir, "pr-remote.git"); + execFileSync("git", ["init", "--bare", "-b", "main", prRemoteDir]); + const worktree = await createLegacyWorktreeForTest({ + branchName: "contributor/feature", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "contributor-feature", + paseoHome, + }); + const worktreeDir = worktree.worktreePath; + execFileSync("git", ["remote", "add", "paseo-pr-7", prRemoteDir], { cwd: worktreeDir }); + execFileSync("git", ["config", "branch.contributor/feature.pushRemote", "paseo-pr-7"], { + cwd: worktreeDir, + }); + execFileSync("git", ["config", "remote.paseo-pr-7.push", "HEAD:refs/heads/feature"], { + cwd: worktreeDir, + }); + commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit"); + + const status = await getCheckoutStatus(worktreeDir, { paseoHome }); + await pushCurrentBranch(worktreeDir, undefined, { paseoHome }); + + expect(status).toMatchObject({ hasRemote: false, pushRemote: "paseo-pr-7" }); + expect(headOf(prRemoteDir, "refs/heads/feature")).toBe(headOf(worktreeDir)); + }); }); // A legal local branch named "origin/main" shadows the short form "origin/main" in git's diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 81f3b6acd1..253e042a7c 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -909,7 +909,14 @@ export interface CheckoutStatusGitNonPaseo { aheadOfOrigin: number | null; behindOfOrigin: number | null; upstreamState: UpstreamState; + // Whether origin is configured. Pull and Push do not need it; see pullRemote and pushRemote. hasRemote: boolean; + // The remote Pull fetches currentBranch from, as git names it: the remote of the branch's + // configured upstream, or "." when the upstream is a local branch. Null without an upstream. + pullRemote: string | null; + // The remote Push sends currentBranch to, resolved as pushCurrentBranch resolves it. Null when + // Push has nowhere to send the branch. + pushRemote: string | null; firstPushRemote: string | null; remoteUrl: string | null; isPaseoOwnedWorktree: false; @@ -930,6 +937,8 @@ export interface CheckoutStatusGitPaseo { behindOfOrigin: number | null; upstreamState: UpstreamState; hasRemote: boolean; + pullRemote: string | null; + pushRemote: string | null; firstPushRemote: string | null; remoteUrl: string | null; isPaseoOwnedWorktree: true; @@ -967,6 +976,9 @@ export interface CheckoutContext { logger?: Pick; facts?: CheckoutSnapshotFacts | null; runGitCommand?: RunGitCommand; + // `git config --get` results shared by the lookups of one snapshot, keyed by config key. + // Several lookups read the same keys; this keeps each to one process. + gitConfigReads?: Map>; } export type CheckoutSnapshotFacts = @@ -988,7 +1000,8 @@ export type CheckoutSnapshotFacts = branchRemoteName: string | null; branchMergeRef: string | null; upstreamStatus: UpstreamStatus; - firstPushRemote: string | null; + // Where Push sends the current branch. Null when Push has nowhere to send it. + pushTarget: PushTarget | null; pullRequestLookupTarget: PullRequestStatusLookupTarget | null; }; @@ -1441,16 +1454,7 @@ export async function getOriginRemoteUrl( cwd: string, context?: CheckoutContext, ): Promise { - try { - const { stdout } = await getRunGitCommand(context)(["config", "--get", "remote.origin.url"], { - cwd, - envOverlay: READ_ONLY_GIT_ENV, - }); - const url = stdout.trim(); - return url.length > 0 ? url : null; - } catch { - return null; - } + return getGitConfigValue(cwd, "remote.origin.url", context); } export async function hasOriginRemote(cwd: string): Promise { @@ -1462,6 +1466,23 @@ async function getGitConfigValue( cwd: string, key: string, context?: CheckoutContext, +): Promise { + const reads = context?.gitConfigReads; + if (!reads) { + return readGitConfigValue(cwd, key, context); + } + let read = reads.get(key); + if (!read) { + read = readGitConfigValue(cwd, key, context); + reads.set(key, read); + } + return read; +} + +async function readGitConfigValue( + cwd: string, + key: string, + context?: CheckoutContext, ): Promise { try { const { stdout } = await getRunGitCommand(context)(["config", "--get", key], { @@ -2029,32 +2050,6 @@ async function readGitPushRemote(input: { return branchPushRemote ?? pushDefault ?? input.branchRemoteName ?? "origin"; } -// pushCurrentBranch publishes a branch with no upstream here. -const FIRST_PUSH_REMOTE = "origin"; - -// Where a first push publishes the branch, when the daemon can confirm git would push it there -// too. When git picks another remote, as in a fork setup, this is null so that clients do not -// offer a first push that lands in a different repository than `git push` would use. -async function readFirstPushRemote(input: { - cwd: string; - storedBranchName: string | null; - branchRemoteName: string | null; - hasOrigin: boolean; - context?: CheckoutContext; -}): Promise { - const { cwd, storedBranchName, branchRemoteName, context } = input; - if (!storedBranchName || !input.hasOrigin) { - return null; - } - const gitPushRemote = await readGitPushRemote({ - cwd, - storedBranchName, - branchRemoteName, - context, - }); - return gitPushRemote === FIRST_PUSH_REMOTE ? FIRST_PUSH_REMOTE : null; -} - interface CheckoutInspectionContext { worktreeRoot: string; currentBranch: string | null; @@ -2314,7 +2309,13 @@ export async function getCheckoutSnapshotFacts( if (context?.facts) { return context.facts; } + return collectCheckoutSnapshotFacts(cwd, { ...context, gitConfigReads: new Map() }); +} +async function collectCheckoutSnapshotFacts( + cwd: string, + context: CheckoutContext, +): Promise { const inspected = await inspectCheckoutContext(cwd, context); if (!inspected) { return { isGit: false }; @@ -2360,13 +2361,14 @@ export async function getCheckoutSnapshotFacts( ]); } } - const firstPushRemotePromise = readFirstPushRemote({ - cwd, - storedBranchName, - branchRemoteName, - hasOrigin: inspected.remoteUrl !== null, - context, - }); + const pushTargetPromise = storedBranchName + ? resolvePushTarget({ + cwd, + storedBranchName, + paseoWorktree: inspected.paseoWorktree, + context, + }) + : null; let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({ cwd, inspected, @@ -2402,7 +2404,7 @@ export async function getCheckoutSnapshotFacts( branchRemoteName, branchMergeRef, upstreamStatus, - firstPushRemote: await firstPushRemotePromise, + pushTarget: pushTargetOrNull(await pushTargetPromise), pullRequestLookupTarget, }; } @@ -2580,6 +2582,16 @@ export async function getCheckoutStatus( // comparisons and actions read it. const displayBaseRef = baseRef ? branchNameFromRef(baseRef) : null; const upstream = projectUpstreamStatus(facts.upstreamStatus); + const pushRemote = facts.pushTarget?.remoteName ?? null; + const remotes = { + hasRemote, + pullRemote: resolvePullRemote(facts.branchRemoteName, facts.branchMergeRef), + pushRemote, + // COMPAT(checkoutFirstPushRemote): added in v0.17.5, remove after 2027-05-24 once the app + // floor reads pushRemote. v0.17.4 apps offer a regular checkout's first push only when this + // is set, and the daemon they shipped with set it when the push went to origin. + firstPushRemote: pushRemote === PUBLISH_REMOTE ? pushRemote : null, + }; if (paseoWorktree.isPaseoOwnedWorktree && baseRef) { return { @@ -2593,8 +2605,7 @@ export async function getCheckoutStatus( comparisonBaseRef, aheadBehind, ...upstream, - hasRemote, - firstPushRemote: facts.firstPushRemote, + ...remotes, remoteUrl, isPaseoOwnedWorktree: true, }; @@ -2612,8 +2623,7 @@ export async function getCheckoutStatus( comparisonBaseRef, aheadBehind, ...upstream, - hasRemote, - firstPushRemote: facts.firstPushRemote, + ...remotes, remoteUrl, isPaseoOwnedWorktree: false, }; @@ -4319,10 +4329,8 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService if (!currentBranch || currentBranch === "HEAD") { throw new Error("Unable to determine current branch for pull"); } - const hasRemote = await hasOriginRemote(cwd); - if (!hasRemote) { - throw new Error("Remote 'origin' is not configured."); - } + // Git decides whether there is something to pull from. It does not need origin, and it can + // pull some branches that have no upstream, as in a single-branch clone. try { await runGitCommand(["pull"], { cwd, timeout: 120_000 }); forgeService?.invalidate({ cwd }); @@ -4332,6 +4340,16 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService } } +// The remote `git pull` fetches a branch from when the branch has a configured upstream, which +// git names "." when the upstream is a local branch. Checkout status reports it so that clients +// offer Pull for any upstream, not only one on origin. +function resolvePullRemote( + branchRemoteName: string | null, + branchMergeRef: string | null, +): string | null { + return branchMergeRef === null ? null : branchRemoteName; +} + export async function pushCurrentBranch( cwd: string, forgeService?: ForgeService, @@ -4343,55 +4361,175 @@ export async function pushCurrentBranch( throw new Error("Unable to determine current branch for push"); } const storedBranchName = await readStoredBranchName(cwd, currentBranch, context); - const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName); - if (configuredPushTarget) { - await runGitCommand( - ["push", configuredPushTarget.remoteName, `HEAD:refs/heads/${configuredPushTarget.headRef}`], - { cwd, timeout: 120_000 }, - ); - await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, configuredPushTarget); - forgeService?.invalidate({ cwd }); - return; + // The status a client acted on can be older than the git configuration, so the destination is + // resolved again before anything is sent. + const target = await resolvePushTarget({ cwd, storedBranchName, context }); + switch (target.kind) { + case "refused": + throw new Error(target.reason); + case "configured": + await runGitCommand(["push", target.remoteName, `HEAD:refs/heads/${target.headRef}`], { + cwd, + timeout: 120_000, + }); + await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, target); + break; + case "upstream": + await runGitCommand(["push", "-u", target.remoteName, `HEAD:refs/heads/${target.headRef}`], { + cwd, + timeout: 120_000, + }); + break; + case "publish": + await runGitCommand(["push", "-u", target.remoteName, currentBranch], { + cwd, + timeout: 120_000, + }); + break; } - - const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName); - if (upstreamTarget) { - await runGitCommand( - ["push", "-u", upstreamTarget.remoteName, `HEAD:refs/heads/${upstreamTarget.headRef}`], - { cwd, timeout: 120_000 }, - ); - forgeService?.invalidate({ cwd }); - return; - } - - const hasRemote = await hasOriginRemote(cwd); - if (!hasRemote) { - throw new Error("Remote 'origin' is not configured."); - } - await requireFirstPushAgreesWithGit(cwd, storedBranchName, context); - await runGitCommand(["push", "-u", FIRST_PUSH_REMOTE, currentBranch], { cwd, timeout: 120_000 }); forgeService?.invalidate({ cwd }); } -// The status a client acted on can be older than the git configuration, so a first push checks -// the destination again before it sends anything. Paseo worktrees always publish to origin. -async function requireFirstPushAgreesWithGit( - cwd: string, - storedBranchName: string, - context?: CheckoutContext, -): Promise { +// A branch with no upstream on a remote is published here. +const PUBLISH_REMOTE = "origin"; + +// Where Push sends the current branch. In a checkout that has origin, in order: the branch's push +// remote with a HEAD push refspec, then its upstream, then origin under the branch's own name, +// which sets the upstream. Without origin, see resolvePushWithoutOrigin. Checkout status reports +// the remote of this target, so the Push offer and the push cannot disagree. +export type PushTarget = + | { kind: "configured"; remoteName: string; headRef: string } + | { kind: "upstream"; remoteName: string; headRef: string } + | { kind: "publish"; remoteName: typeof PUBLISH_REMOTE }; + +// Push has nowhere to send the branch. The reason is written for the user. +interface PushRefusal { + kind: "refused"; + reason: string; +} + +function pushTargetOrNull(resolved: PushTarget | PushRefusal | null): PushTarget | null { + return resolved === null || resolved.kind === "refused" ? null : resolved; +} + +interface ResolvePushTargetInput { + cwd: string; + storedBranchName: string; + // Known by the caller. Looked up when absent. + paseoWorktree?: PaseoWorktreeForCwd; + context?: CheckoutContext; +} + +async function resolvePushTarget(input: ResolvePushTargetInput): Promise { + const { cwd, storedBranchName, context } = input; + if ((await getOriginRemoteUrl(cwd, context)) === null) { + return resolvePushWithoutOrigin(input); + } + const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context); + if (configured) { + return { kind: "configured", ...configured }; + } + // In a checkout that has origin, Push has always followed the upstream, whatever the upstream + // branch is called. + const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context); + if (upstream) { + return { kind: "upstream", ...upstream }; + } + return resolvePublish(input); +} + +// Without origin, Push follows the upstream only when the upstream branch has the branch's own +// name and plain `git push` would update that same branch. A differently named upstream is often +// a shared base branch, as with `feature` tracking `upstream/main`. Git's own push settings +// (branch..pushRemote, remote.pushDefault, remote..push, push.default) can send the +// branch elsewhere, and then the push is left to the user. +async function resolvePushWithoutOrigin( + input: ResolvePushTargetInput, +): Promise { + const { cwd, storedBranchName, context } = input; + const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context })); + if (paseoWorktree.isPaseoOwnedWorktree) { + // Paseo writes this configuration for a PR checkout, so its push reaches the PR's branch. + const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context); + if (configured) { + return { kind: "configured", ...configured }; + } + } + const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context); + if (!upstream) { + return { kind: "refused", reason: `Remote '${PUBLISH_REMOTE}' is not configured.` }; + } + const upstreamName = `${upstream.remoteName}/${upstream.headRef}`; + if (upstream.headRef !== storedBranchName) { + return { + kind: "refused", + reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because the branch names differ. Push it from a terminal instead.`, + }; + } + const gitPushUpdatesUpstream = await doesGitPushUpdateUpstream({ + cwd, + storedBranchName, + upstreamRemoteName: upstream.remoteName, + context, + }); + if (!gitPushUpdatesUpstream) { + return { + kind: "refused", + reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because Git's push settings do not confirm that destination. Push it from a terminal instead.`, + }; + } + return { kind: "upstream", ...upstream }; +} + +// Whether plain `git push` on this branch updates the branch's upstream. Git resolves its push +// destination from its own settings and reports none when it cannot name a single one. The +// remote is compared by name as well, because two remotes can map onto one remote-tracking ref. +// Matching mode is left to the user: Git then sends the branch only when the remote still has +// it, and the checkout's remote-tracking refs can outlive a branch deleted on the remote. +async function doesGitPushUpdateUpstream(input: { + cwd: string; + storedBranchName: string; + upstreamRemoteName: string; + context?: CheckoutContext; +}): Promise { + if ((await getGitConfigValue(input.cwd, "push.default", input.context)) === "matching") { + return false; + } + try { + const { stdout } = await getRunGitCommand(input.context)( + [ + "for-each-ref", + "--format=%(push:remotename)%00%(push)%00%(upstream)", + `refs/heads/${input.storedBranchName}`, + ], + { cwd: input.cwd, envOverlay: READ_ONLY_GIT_ENV }, + ); + const [pushRemoteName, pushRef, upstreamRef] = stdout.trim().split("\0"); + return ( + pushRemoteName === input.upstreamRemoteName && Boolean(pushRef) && pushRef === upstreamRef + ); + } catch { + return false; + } +} + +// Publishing sends the branch to origin. A regular checkout needs git to push the branch there +// too, so that a fork setup is not published to origin. Paseo worktrees always publish to origin. +async function resolvePublish(input: ResolvePushTargetInput): Promise { + const { cwd, storedBranchName, context } = input; + const publish: PushTarget = { kind: "publish", remoteName: PUBLISH_REMOTE }; const [branchRemoteName, branchMergeRef] = await Promise.all([ getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context), getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context), ]); // A branch with a configured upstream gets here when that upstream is not a remote branch, as - // when it tracks a local branch. That is not a first push, and it goes to origin as before. + // when it tracks a local branch. It goes to origin as before. if (branchRemoteName !== null && branchMergeRef !== null) { - return; + return publish; } - const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { context }); + const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context })); if (paseoWorktree.isPaseoOwnedWorktree) { - return; + return publish; } const gitPushRemote = await readGitPushRemote({ cwd, @@ -4399,24 +4537,29 @@ async function requireFirstPushAgreesWithGit( branchRemoteName, context, }); - if (gitPushRemote !== FIRST_PUSH_REMOTE) { - throw new Error( - `Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${FIRST_PUSH_REMOTE}'. Push it from a terminal instead.`, - ); + if (gitPushRemote !== PUBLISH_REMOTE) { + return { + kind: "refused", + reason: `Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${PUBLISH_REMOTE}'. Push it from a terminal instead.`, + }; } + return publish; } async function getCurrentBranchConfiguredPushTarget( cwd: string, currentBranch: string, + context?: CheckoutContext, ): Promise<{ remoteName: string; headRef: string } | null> { - const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`); - const pushRefspec = remoteName ? await getGitConfigValue(cwd, `remote.${remoteName}.push`) : null; + const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`, context); + const pushRefspec = remoteName + ? await getGitConfigValue(cwd, `remote.${remoteName}.push`, context) + : null; const headRef = parseHeadPushRefspec(pushRefspec); if (!remoteName || !headRef) { return null; } - const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`); + const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context); return remoteUrl ? { remoteName, headRef } : null; } @@ -4483,16 +4626,17 @@ async function updateRemoteTrackingRef( async function getCurrentBranchUpstreamPushTarget( cwd: string, currentBranch: string, + context?: CheckoutContext, ): Promise<{ remoteName: string; headRef: string } | null> { - const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`); + const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`, context); const mergeRef = remoteName - ? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`) + ? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`, context) : null; const headRef = parseBranchMergeHeadRef(mergeRef); if (!remoteName || !headRef) { return null; } - const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`); + const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context); return remoteUrl ? { remoteName, headRef } : null; }