diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index 79ae55092..a6ceb2dfe 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -471,6 +471,33 @@ test("All changes combines committed and pending edits and preserves an unfinish }); }); +test("Changes offers Push for a branch that was never pushed and the push sets its upstream", async ({ + page, +}) => { + const workspace = await createWorkspaceWithRemote((repoPath) => { + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoPath }); + }); + await openWorkspaceChangesSurface(page, workspace); + const primary = page.getByTestId("changes-primary-cta"); + + await test.step("committing the edit makes Push the primary action", async () => { + await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 }); + commitAllWithGit(workspace.repoPath, "Feature work"); + await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 }); + }); + await test.step("Push sends the branch and sets its upstream", async () => { + await primary.click(); + await expect + .poll(() => remoteBranchHead(workspace, "feature"), { timeout: 30_000 }) + .toBe(localHead(workspace)); + // git writes the upstream after the remote has the branch, so wait for it too. + await expect + .poll(() => branchUpstream(workspace, "feature"), { timeout: 30_000 }) + .toBe("origin/feature"); + await expect(primary).not.toHaveAccessibleName("Push", { timeout: 30_000 }); + }); +}); + test("Changes selects exact local and remote bases and retains the selection after reload", async ({ page, }, testInfo) => { @@ -2122,6 +2149,68 @@ async function createWorkspaceWithMountedTabDiff( return { id: createdWorkspace.workspace.id, repoPath: repo.path }; } +interface RemoteWorkspace extends DirtyWorkspace { + remotePath: string; +} + +// A regular checkout with a local bare remote and one uncommitted edit. +async function createWorkspaceWithRemote( + prepare: (repoPath: string) => void, +): Promise { + const repo = await createTempGitRepo("changes-push-", { + withRemote: true, + files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }], + }); + const client = await connectSeedClient(); + cleanupTasks.push({ + run: async () => { + await client.close(); + await repo.cleanup(); + }, + }); + // The helper keeps the bare remote inside the checkout; keep it out of the status. + await writeFile(path.join(repo.path, ".git/info/exclude"), "remote.git/\n"); + prepare(repo.path); + await writeFile(path.join(repo.path, "tracked.ts"), "export const tracked = 2;\n"); + const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } }); + if (!created.workspace) { + throw new Error(created.error ?? `Failed to create workspace ${repo.path}`); + } + return { + id: created.workspace.id, + repoPath: repo.path, + remotePath: path.join(repo.path, "remote.git"), + }; +} + +// The app's Commit asks an agent provider for a message, and this harness has none. +function commitAllWithGit(repoPath: string, message: string): void { + execFileSync("git", ["commit", "-am", message], { cwd: repoPath, stdio: "ignore" }); +} + +function localHead(workspace: RemoteWorkspace): string { + return execFileSync("git", ["rev-parse", "HEAD"], { + cwd: workspace.repoPath, + encoding: "utf8", + }).trim(); +} + +function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string | null { + const line = execFileSync("git", ["ls-remote", "--heads", workspace.remotePath, branch], { + encoding: "utf8", + }).trim(); + return line ? (line.split("\t")[0] ?? null) : null; +} + +// Empty until the branch has an upstream. +function branchUpstream(workspace: RemoteWorkspace, branch: string): string { + return execFileSync( + "git", + ["for-each-ref", "--format=%(upstream:short)", `refs/heads/${branch}`], + { cwd: workspace.repoPath, encoding: "utf8" }, + ).trim(); +} + async function createWorkspaceWithNetDiff(): Promise { const repo = await createTempGitRepo("changes-net-", { files: [{ path: "a-tracked.ts", content: "base\n" }], diff --git a/packages/app/src/git/policy.test.ts b/packages/app/src/git/policy.test.ts index 34f6e93d1..c49d55a39 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, + readUpstreamState, type BuildGitActionsInput, } from "./policy"; import { deriveMergeCapability, type ForgeSpecificStatusFacts } from "./merge-capability"; @@ -76,6 +77,8 @@ function createInput( pullRequestMergeable: "UNKNOWN", mergeCapability: deriveMergeCapability(pullRequestGithub), hasRemote: false, + hasFirstPushRemote: rest.hasRemote ?? false, + upstream: "tracked", isPaseoOwnedWorktree: false, isOnBaseBranch: true, canMergeLocally: true, @@ -169,6 +172,10 @@ function createInput( }; } +function pushActionOf(actions: ReturnType) { + return actions.secondary.find((action) => action.id === "push"); +} + describe("git-actions-policy", () => { afterEach(async () => { await i18n.changeLanguage("en"); @@ -346,6 +353,7 @@ describe("git-actions-policy", () => { const actions = buildGitActions( createInput({ hasRemote: true, + upstream: "none", isPaseoOwnedWorktree: true, isOnBaseBranch: false, aheadCount: 1, @@ -361,6 +369,207 @@ describe("git-actions-policy", () => { }); }); + it("re-publishes a Paseo worktree branch whose remote copy was deleted", () => { + const actions = buildGitActions( + createInput({ + hasRemote: true, + upstream: "gone", + isPaseoOwnedWorktree: true, + isOnBaseBranch: false, + aheadCount: 2, + aheadOfOrigin: null, + behindOfOrigin: null, + shipDefault: "pr", + }), + ); + const pushAction = actions.secondary.find((action) => action.id === "push"); + + expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + expect(pushAction).toMatchObject({ disabled: false, unavailableMessage: undefined }); + }); + + describe("a never-pushed branch in a regular checkout", () => { + const neverPushed = { + hasRemote: true, + upstream: "none", + isOnBaseBranch: false, + aheadCount: 1, + aheadOfOrigin: null, + behindOfOrigin: null, + } as const; + + it("offers Push first, ahead of Create PR", () => { + const actions = buildGitActions(createInput({ ...neverPushed, shipDefault: "pr" })); + + expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + }); + + it("offers Push first, ahead of Merge locally", () => { + const actions = buildGitActions( + createInput({ ...neverPushed, githubFeaturesEnabled: false, shipDefault: "merge" }), + ); + + expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + }); + + it("does not offer Push when it has no commits of its own", () => { + const actions = buildGitActions(createInput({ ...neverPushed, aheadCount: 0 })); + const pushAction = pushActionOf(actions); + + expect(actions.primary?.id).not.toBe("push"); + expect(pushAction?.unavailableMessage).toBe( + "Push isn't available because there is nothing new to send", + ); + }); + + it("does not offer Push when the repository has no origin", () => { + const actions = buildGitActions(createInput({ ...neverPushed, hasRemote: false })); + const pushAction = pushActionOf(actions); + + expect(actions.primary?.id).not.toBe("push"); + expect(pushAction?.unavailableMessage).toBe( + "Push isn't available here because this branch is not connected to a remote yet", + ); + }); + + it("does not offer Push when Git pushes the branch to another remote", () => { + const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false })); + const pushAction = pushActionOf(actions); + + expect(actions.primary?.id).not.toBe("push"); + expect(pushAction?.unavailableMessage).toBe( + "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", () => { + const actions = buildGitActions( + createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }), + ); + + expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + }); + }); + + it("does not offer a first push when the branch's remote copy was deleted", () => { + const actions = buildGitActions( + createInput({ + hasRemote: true, + upstream: "gone", + isOnBaseBranch: false, + aheadCount: 2, + aheadOfOrigin: null, + behindOfOrigin: null, + shipDefault: "pr", + }), + ); + const pushAction = actions.secondary.find((action) => action.id === "push"); + + expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" }); + expect(pushAction?.unavailableMessage).toBe( + "Push isn't available because the branch this one tracks no longer exists", + ); + }); + + describe("a published branch whose upstream the daemon cannot read", () => { + const unreadableUpstream = { + hasRemote: true, + upstream: "unknown", + isOnBaseBranch: false, + aheadCount: 2, + aheadOfOrigin: null, + behindOfOrigin: null, + shipDefault: "pr", + } as const; + + it("does not offer a first push in a regular checkout", () => { + const actions = buildGitActions(createInput(unreadableUpstream)); + + expect(actions.primary).toMatchObject({ id: "pr", label: "Create PR" }); + expect(pushActionOf(actions)?.unavailableMessage).toEqual(expect.any(String)); + }); + + it("keeps offering Push in a Paseo worktree", () => { + const actions = buildGitActions( + createInput({ ...unreadableUpstream, isPaseoOwnedWorktree: true }), + ); + + expect(actions.primary).toMatchObject({ id: "push", label: "Push" }); + expect(pushActionOf(actions)).toMatchObject({ + disabled: false, + unavailableMessage: undefined, + }); + }); + }); + + describe("readUpstreamState", () => { + it("uses the upstream state the daemon reports", () => { + expect( + readUpstreamState({ + upstreamState: "none", + aheadOfOrigin: null, + isPaseoOwnedWorktree: false, + }), + ).toBe("none"); + expect( + readUpstreamState({ + upstreamState: "gone", + aheadOfOrigin: null, + isPaseoOwnedWorktree: true, + }), + ).toBe("gone"); + }); + + it("keeps the old guess for daemons that predate upstream states", () => { + expect( + readUpstreamState({ + upstreamState: undefined, + aheadOfOrigin: 1, + isPaseoOwnedWorktree: false, + }), + ).toBe("tracked"); + expect( + readUpstreamState({ + upstreamState: undefined, + aheadOfOrigin: null, + isPaseoOwnedWorktree: true, + }), + ).toBe("none"); + expect( + readUpstreamState({ + upstreamState: undefined, + aheadOfOrigin: null, + isPaseoOwnedWorktree: false, + }), + ).toBe("unknown"); + }); + + it("keeps an old daemon's never-pushed regular branch off Push", () => { + const actions = buildGitActions( + createInput({ + hasRemote: true, + upstream: readUpstreamState({ + upstreamState: undefined, + aheadOfOrigin: null, + isPaseoOwnedWorktree: false, + }), + isOnBaseBranch: false, + aheadCount: 1, + aheadOfOrigin: null, + behindOfOrigin: null, + githubFeaturesEnabled: false, + shipDefault: "merge", + }), + ); + const pushAction = pushActionOf(actions); + + expect(actions.primary).toMatchObject({ id: "merge-branch" }); + expect(pushAction?.unavailableMessage).toBe( + "Push isn't available because there is nothing new to send", + ); + }); + }); + it("prioritizes push over pull request merge when local commits are unpushed", () => { const actions = buildGitActions( createInput({ diff --git a/packages/app/src/git/policy.ts b/packages/app/src/git/policy.ts index 9f18e6575..37f898c0e 100644 --- a/packages/app/src/git/policy.ts +++ b/packages/app/src/git/policy.ts @@ -2,7 +2,11 @@ import type { ReactElement } from "react"; import type { ActionStatus } from "@/components/ui/dropdown-menu"; import { i18n } from "@/i18n/i18next"; -import type { CheckoutPrMergeMethod, PullRequestMergeable } from "@getpaseo/protocol/messages"; +import type { + CheckoutPrMergeMethod, + CheckoutStatusResponse, + PullRequestMergeable, +} from "@getpaseo/protocol/messages"; import type { MergeCapability } from "./merge-capability"; @@ -73,6 +77,25 @@ export function canMergeIntoLocalBase( return currentBranch !== localTarget; } +type CheckoutStatusPayload = CheckoutStatusResponse["payload"]; + +export type GitUpstreamState = NonNullable; + +export function readUpstreamState( + status: Pick, +): GitUpstreamState { + if (status.upstreamState !== undefined) { + return status.upstreamState; + } + // COMPAT(checkoutUpstreamState): added in v0.17.4, remove after 2027-05-23 once the daemon + // floor reports upstreamState. Older daemons send a null upstream for both a never-pushed and + // a deleted remote branch. Only a Paseo worktree's null was trusted as never pushed. + if (status.aheadOfOrigin !== null) { + return "tracked"; + } + return status.isPaseoOwnedWorktree ? "none" : "unknown"; +} + export interface BuildGitActionsInput { isGit: boolean; githubFeaturesEnabled: boolean; @@ -89,6 +112,9 @@ export interface BuildGitActionsInput { 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; canMergeLocally: boolean; @@ -554,12 +580,22 @@ function canPush(input: BuildGitActionsInput): boolean { } function hasPushableCommits(input: BuildGitActionsInput): boolean { - if ((input.aheadOfOrigin ?? 0) > 0) { - return true; + switch (input.upstream) { + case "tracked": + 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); + case "gone": + case "unknown": + // The branch has an upstream that is deleted or unreadable, so nothing counts the commits + // left to send. Paseo worktrees publish whenever the branch is ahead of its base, for + // example after a merged PR. Regular checkouts do not: Push would re-create a branch that + // was deleted. + return input.isPaseoOwnedWorktree && input.aheadCount > 0; } - // No-upstream Paseo worktrees are first-pushable: the daemon push sets upstream with `git push -u`. - // Do not fold this into aheadOfOrigin; null also covers deleted/pruned upstream branches. - return input.isPaseoOwnedWorktree && input.aheadOfOrigin === null && input.aheadCount > 0; } function canMergeFromBase(input: BuildGitActionsInput): boolean { @@ -664,10 +700,16 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi if ((input.behindOfOrigin ?? 0) > 0) { return i18n.t("workspace.git.actions.unavailable.pushBehind"); } - if (!hasPushableCommits(input)) { - return i18n.t("workspace.git.actions.unavailable.pushNothing"); + if (hasPushableCommits(input)) { + return undefined; } - return undefined; + 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 { diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index 649a8ec5c..2d3a82cc7 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -15,9 +15,11 @@ import { isCurrentBranchBase, canMergeIntoLocalBase, narrowPullRequestState, + readUpstreamState, type BuildGitActionsInput, type GitAction, type GitActions, + type GitUpstreamState, } from "@/git/policy"; import { deriveMergeCapability } from "@/git/merge-capability"; import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages"; @@ -129,6 +131,8 @@ interface DerivedGitActionsState { behindOfOrigin: number | null; hasPullRequest: boolean; hasRemote: boolean; + hasFirstPushRemote: boolean; + upstream: GitUpstreamState; isPaseoOwnedWorktree: boolean; isOnBaseBranch: boolean; canMergeLocally: boolean; @@ -180,6 +184,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio ...extractGitCommitCounts(gitStatus), hasPullRequest: Boolean(prStatus?.url), hasRemote: gitStatus?.hasRemote ?? false, + hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null, + upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown", isPaseoOwnedWorktree, isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef), canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef), @@ -668,6 +674,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use behindOfOrigin, hasPullRequest, hasRemote, + hasFirstPushRemote, + upstream, isPaseoOwnedWorktree, isOnBaseBranch, canMergeLocally, @@ -699,6 +707,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN", mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github), hasRemote, + hasFirstPushRemote, + upstream, isPaseoOwnedWorktree, isOnBaseBranch, canMergeLocally, @@ -807,6 +817,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use }, [ isGit, hasRemote, + hasFirstPushRemote, + upstream, hasPullRequest, prStatus?.url, prStatus?.state, diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 6642a0d76..cf35f8293 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -912,6 +912,7 @@ export const ar: TranslationResources = { pushNoRemote: "الدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد", pushBehind: "الدفع غير متاح حتى الآن نظرًا لوجود تغييرات أحدث يجب إدخالها أولاً", pushNothing: "خدمة الدفع غير متاحة لأنه لا يوجد شيء جديد لإرساله", + pushUpstreamGone: "الدفع غير متاح لأن الفرع الذي يتتبعه هذا الفرع لم يعد موجودًا", pullAndPushNoRemote: "السحب والدفع غير متاح هنا لأن هذا الفرع غير متصل بجهاز التحكم عن بعد بعد", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index d36956e5b..eee3ac578 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -913,6 +913,8 @@ export const en = { "Push isn't available here because this branch is not connected to a remote yet", pushBehind: "Push isn't available yet because there are newer changes to bring in first", pushNothing: "Push isn't available because there is nothing new to send", + pushUpstreamGone: + "Push isn't available because the branch this one tracks no longer exists", pullAndPushNoRemote: "Pull and push isn't available here because this branch is not connected to a remote yet", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 56d1eeeb0..630119dfa 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -925,6 +925,8 @@ export const es: TranslationResources = { pushBehind: "Push aún no está disponible porque hay cambios más nuevos que implementar primero", pushNothing: "Push no está disponible porque no hay nada nuevo que enviar", + pushUpstreamGone: + "Push no está disponible porque la rama que sigue esta rama ya no existe", pullAndPushNoRemote: "Tirar y empujar no está disponible aquí porque esta rama aún no está conectada a un control remoto", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 8448dc543..c96a46dbc 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -926,6 +926,7 @@ export const fr: TranslationResources = { pushBehind: "Push indisponible pour l’instant : des modifications plus récentes doivent d’abord être récupérées", pushNothing: "Push indisponible : il n’y a rien de nouveau à pousser", + pushUpstreamGone: "Push indisponible : la branche suivie par cette branche n’existe plus", pullAndPushNoRemote: "Pull et push indisponibles : cette branche n’est pas encore liée à un dépôt distant", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 88913c858..51c344681 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -919,6 +919,8 @@ export const ja: TranslationResources = { "このブランチはまだリモートに接続されていないため、プッシュはここでは利用できません", pushBehind: "取り込む必要がある新しい変更があるため、まだプッシュは利用できません", pushNothing: "プッシュする変更がないため、プッシュは利用できません", + pushUpstreamGone: + "このブランチが追跡しているブランチが存在しないため、プッシュは利用できません", pullAndPushNoRemote: "このブランチはまだリモートに接続されていないため、プル&プッシュはここでは利用できません", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index fad9469e9..7b4a2e59c 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -913,6 +913,7 @@ export const ko: TranslationResources = { "이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 푸시를 사용할 수 없습니다", pushBehind: "먼저 가져와야 할 최신 변경 사항이 있어 아직 푸시를 사용할 수 없습니다", pushNothing: "새로 보낼 항목이 없어 푸시를 사용할 수 없습니다", + pushUpstreamGone: "이 브랜치가 추적하는 브랜치가 더 이상 없어 푸시를 사용할 수 없습니다", pullAndPushNoRemote: "이 브랜치가 아직 원격에 연결되어 있지 않아 여기서 풀 후 푸시를 사용할 수 없습니다", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index e264f670b..fce007307 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -921,6 +921,8 @@ export const ptBR: TranslationResources = { pushBehind: "Push ainda não está disponível porque há alterações mais recentes para trazer primeiro", pushNothing: "Push não está disponível porque não há nada novo para enviar", + pushUpstreamGone: + "Push não está disponível porque a branch que esta branch acompanha não existe mais", pullAndPushNoRemote: "Pull e push não estão disponíveis aqui porque esta branch ainda não está conectada a um remoto", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 6813b83e7..37a5392f3 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -924,6 +924,8 @@ export const ru: TranslationResources = { "Отправка изменений недоступна: эта ветка ещё не связана с удалённым репозиторием.", pushBehind: "Отправка изменений пока недоступна: сначала получите более новые изменения.", pushNothing: "Отправка изменений недоступна: нет новых изменений для отправки.", + pushUpstreamGone: + "Отправка изменений недоступна: ветка, которую отслеживает эта ветка, больше не существует.", pullAndPushNoRemote: "Получение и отправка изменений недоступны: эта ветка ещё не связана с удалённым репозиторием.", pullAndPushDirty: diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index aa91dd793..62a67ad4a 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -908,6 +908,7 @@ export const zhCN: TranslationResources = { pushNoRemote: "此处无法 push,因为此分支尚未连接到 remote", pushBehind: "暂时无法 push,因为需要先拉取更新的变更", pushNothing: "无法 push,因为没有新的内容可发送", + pushUpstreamGone: "无法 push,因为此分支跟踪的分支已不存在", pullAndPushNoRemote: "此处无法 pull 并 push,因为此分支尚未连接到 remote", pullAndPushDirty: "有本地变更时无法 pull 并 push,请先 commit 或 stash", pullAndPushNoIncoming: "无法 pull 并 push,因为没有需要先 pull 的传入变更", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 7ef069480..679774f66 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -5818,6 +5818,17 @@ const CheckoutStatusCommonSchema = z.object({ // upstream branch name is not necessarily currentBranch, so composing one is wrong. // aheadOfOrigin/behindOfOrigin are measured against exactly this ref. upstreamRef: z.string().nullable().optional(), + // How currentBranch relates to its upstream: "tracked" (upstreamRef and the counts are set), + // "none" (never pushed; Push does a first push), "gone" (the upstream's remote-tracking ref no + // longer exists, as after the remote branch is deleted), or "unknown" (the daemon cannot tell, + // 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. + firstPushRemote: z.string().nullable().optional(), forgeWeb: ForgeWebSchema.optional(), }); diff --git a/packages/server/src/server/checkout/status-projection.ts b/packages/server/src/server/checkout/status-projection.ts index 00f9ce05c..b2a2232dd 100644 --- a/packages/server/src/server/checkout/status-projection.ts +++ b/packages/server/src/server/checkout/status-projection.ts @@ -67,7 +67,9 @@ export function buildCheckoutStatusPayloadFromSnapshot({ upstreamRef: snapshot.git.upstreamRef ?? null, aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null, behindOfOrigin: snapshot.git.behindOfOrigin ?? null, + upstreamState: snapshot.git.upstreamState, hasRemote: snapshot.git.hasRemote, + firstPushRemote: snapshot.git.firstPushRemote, remoteUrl: snapshot.git.remoteUrl, ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: true, @@ -90,7 +92,9 @@ export function buildCheckoutStatusPayloadFromSnapshot({ upstreamRef: snapshot.git.upstreamRef ?? null, aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null, behindOfOrigin: snapshot.git.behindOfOrigin ?? null, + upstreamState: snapshot.git.upstreamState, hasRemote: snapshot.git.hasRemote, + firstPushRemote: snapshot.git.firstPushRemote, remoteUrl: snapshot.git.remoteUrl, ...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}), isPaseoOwnedWorktree: false, diff --git a/packages/server/src/server/session.test.ts b/packages/server/src/server/session.test.ts index a3da96067..69722c4d4 100644 --- a/packages/server/src/server/session.test.ts +++ b/packages/server/src/server/session.test.ts @@ -4075,7 +4075,11 @@ describe("session checkout pull and push handling", () => { requestId: "request-push", }); - expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith("/tmp/request-worktree"); + expect(checkoutGitMocks.pushCurrentBranch).toHaveBeenCalledWith( + "/tmp/request-worktree", + undefined, + { paseoHome: "/tmp/paseo-home", worktreesRoot: undefined }, + ); expect(workspaceGitService.getSnapshot).toHaveBeenCalledWith("/tmp/request-worktree", { force: true, reason: "push", diff --git a/packages/server/src/server/session.workspaces.test.ts b/packages/server/src/server/session.workspaces.test.ts index f14a6e94d..f55a657f0 100644 --- a/packages/server/src/server/session.workspaces.test.ts +++ b/packages/server/src/server/session.workspaces.test.ts @@ -10049,6 +10049,8 @@ test("workspace PR status survives session cleanup and reconnect", async () => { comparisonBaseRef: null, branchRemoteName: "origin", branchMergeRef: "refs/heads/feature", + upstreamStatus: { state: "none" }, + firstPushRemote: null, pullRequestLookupTarget: { headRef: "feature" }, }; const githubStub = { diff --git a/packages/server/src/server/session/checkout/checkout-session.ts b/packages/server/src/server/session/checkout/checkout-session.ts index 689cd36b0..a063b22b6 100644 --- a/packages/server/src/server/session/checkout/checkout-session.ts +++ b/packages/server/src/server/session/checkout/checkout-session.ts @@ -956,7 +956,10 @@ export class CheckoutSession { const { cwd, requestId } = msg; try { - await pushCurrentBranch(cwd); + await pushCurrentBranch(cwd, undefined, { + paseoHome: this.paseoHome, + worktreesRoot: this.worktreesRoot, + }); await this.gitMutation.notifyGitMutation(cwd, "push", { invalidateForge: true }); this.host.emit({ type: "checkout_push_response", diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 239f76510..252ea81f5 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -246,7 +246,9 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna upstreamRef: null, aheadOfOrigin: null, behindOfOrigin: null, + upstreamState: "none", hasRemote: false, + firstPushRemote: null, diffStat: null, }, forge: { 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 cbed2c8e5..e15cfae9b 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 @@ -41,6 +41,8 @@ function createFacts(cwd: string): CheckoutSnapshotFacts { comparisonBaseRef: null, branchRemoteName: null, branchMergeRef: null, + upstreamStatus: { state: "none" }, + firstPushRemote: 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 c73e2de27..2ab85f4bc 100644 --- a/packages/server/src/server/workspace-git-service.observation.test.ts +++ b/packages/server/src/server/workspace-git-service.observation.test.ts @@ -72,6 +72,8 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts { comparisonBaseRef: null, branchRemoteName: null, branchMergeRef: null, + upstreamStatus: { state: "none" }, + firstPushRemote: null, pullRequestLookupTarget: { headRef: "main" }, }; } @@ -1017,7 +1019,8 @@ describe("WorkspaceGitService checkout observation", () => { comparisonBaseRef: null, branchRemoteName: null, branchMergeRef: null, - upstreamStatus: null, + upstreamStatus: { state: "none" }, + firstPushRemote: null, }; }); const runGitFetch = vi.fn(async () => ({ @@ -1160,7 +1163,8 @@ describe("WorkspaceGitService checkout observation", () => { comparisonBaseRef: "refs/heads/main", branchRemoteName: "origin", branchMergeRef: `refs/heads/${branch}`, - upstreamStatus: null, + upstreamStatus: { state: "none" }, + firstPushRemote: 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 b969c7315..4e831a7d0 100644 --- a/packages/server/src/server/workspace-git-service.primitive.test.ts +++ b/packages/server/src/server/workspace-git-service.primitive.test.ts @@ -80,6 +80,8 @@ function createCheckoutFacts( comparisonBaseRef: null, branchRemoteName: null, branchMergeRef: null, + upstreamStatus: { state: "none" }, + firstPushRemote: 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 d2aeb1a04..c3c7171de 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -171,6 +171,8 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts { comparisonBaseRef: null, branchRemoteName: "origin", branchMergeRef: "refs/heads/main", + upstreamStatus: { state: "none" }, + firstPushRemote: 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 6c598d0ad..cff002532 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -7,13 +7,14 @@ import pLimit from "p-limit"; import type pino from "pino"; import type { ForgeWeb, ProjectCheckoutLitePayload } from "@getpaseo/protocol/messages"; import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote"; -import type { CheckoutContext } from "../utils/checkout-git.js"; +import type { CheckoutContext, UpstreamState } from "../utils/checkout-git.js"; import { type BranchCheckoutResolution, type BranchSuggestion, type CheckoutSnapshotFacts, type CheckoutDiffCompare, type CheckoutDiffResult, + configuredUpstreamRef, getCheckoutDiff, getCheckoutRefDerivedState, getCheckoutSnapshotFacts, @@ -22,6 +23,7 @@ import { getCheckoutWorktreeState, getPullRequestStatus, forgeAuthStateFromError, + projectUpstreamStatus, hasOriginRemote, listBranchSuggestions, resolveRepositoryDefaultBranch, @@ -181,7 +183,9 @@ export interface WorkspaceGitRuntimeSnapshot { upstreamRef: string | null; aheadOfOrigin: number | null; behindOfOrigin: number | null; + upstreamState: UpstreamState; hasRemote: boolean; + firstPushRemote: string | null; diffStat: { additions: number; deletions: number } | null; }; forge: { @@ -2882,7 +2886,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { facts.storedBaseRef, facts.resolvedBaseRef, facts.comparisonBaseRef, - facts.upstreamStatus?.ref, + configuredUpstreamRef(facts.upstreamStatus), ]; const usesBranch = dependentRefs.some( (ref) => ref === branch || ref === `refs/heads/${branch}`, @@ -2919,7 +2923,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { facts.storedBaseRef, facts.resolvedBaseRef, facts.comparisonBaseRef, - facts.upstreamStatus?.ref, + configuredUpstreamRef(facts.upstreamStatus), configuredRemoteRef, shortstatRemoteRef, ]; @@ -3684,9 +3688,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { ...latestGit, aheadBehind: derived.aheadBehind, diffStat: derived.diffStat, - upstreamRef: derived.upstreamStatus?.ref ?? null, - aheadOfOrigin: derived.upstreamStatus?.aheadBehind.ahead ?? null, - behindOfOrigin: derived.upstreamStatus?.aheadBehind.behind ?? null, + ...projectUpstreamStatus(derived.upstreamStatus), }; const loadedAtMs = this.deps.now().getTime(); target.latestGitLoadedAtMs = loadedAtMs; @@ -3781,7 +3783,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { upstreamRef: checkoutStatus.upstreamRef, aheadOfOrigin: checkoutStatus.aheadOfOrigin, behindOfOrigin: checkoutStatus.behindOfOrigin, + upstreamState: checkoutStatus.upstreamState, hasRemote: checkoutStatus.hasRemote, + firstPushRemote: checkoutStatus.firstPushRemote, diffStat, }; const loadedAtMs = this.deps.now().getTime(); @@ -4436,7 +4440,9 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot { upstreamRef: null, aheadOfOrigin: null, behindOfOrigin: null, + upstreamState: "none", hasRemote: false, + firstPushRemote: null, diffStat: null, }, forge: buildForgeUnavailableSnapshot(), 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 ddafaab6b..0b3566fbe 100644 --- a/packages/server/src/utils/checkout-git-ref-derived.test.ts +++ b/packages/server/src/utils/checkout-git-ref-derived.test.ts @@ -63,9 +63,11 @@ function seedFeatureCheckout(): { branchRemoteName: "origin", branchMergeRef: "refs/heads/main", upstreamStatus: { + state: "tracked", ref: "refs/remotes/origin/main", aheadBehind: { ahead: 0, behind: 0 }, }, + firstPushRemote: "origin", pullRequestLookupTarget: { headRef: "feature" }, }, }; @@ -105,9 +107,11 @@ function seedMainCheckout(): { branchRemoteName: "origin", branchMergeRef: "refs/heads/main", upstreamStatus: { + state: "tracked", ref: "refs/remotes/origin/main", aheadBehind: { ahead: 1, behind: 0 }, }, + firstPushRemote: "origin", pullRequestLookupTarget: { headRef: "main" }, }, }; @@ -127,6 +131,7 @@ test("one comparison refresh updates a shared base and upstream ref", async () = expect(result.aheadBehind).toEqual({ ahead: 1, behind: 0 }); expect(result.upstreamStatus).toEqual({ + state: "tracked", ref: "refs/remotes/origin/main", aheadBehind: { ahead: 1, behind: 0 }, }); @@ -154,6 +159,7 @@ test("an upstream move refreshes the main checkout shortstat", async () => { aheadBehind: null, diffStat: null, upstreamStatus: { + state: "tracked", ref: "refs/remotes/origin/main", aheadBehind: { ahead: 0, behind: 0 }, }, @@ -166,7 +172,7 @@ test("an origin move refreshes an untracked main checkout shortstat", async () = ...seeded.facts, branchRemoteName: null, branchMergeRef: null, - upstreamStatus: null, + upstreamStatus: { state: "none" as const }, }; git(seeded.cwd, [ "update-ref", @@ -181,5 +187,5 @@ test("an origin move refreshes an untracked main checkout shortstat", async () = { aheadBehind: null, diffStat: { additions: 1, deletions: 0 } }, new Set(["origin/main"]), ), - ).toEqual({ aheadBehind: null, diffStat: null, upstreamStatus: null }); + ).toEqual({ aheadBehind: null, diffStat: null, upstreamStatus: { state: "none" } }); }); diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index 154382b88..cebfb86fd 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -924,15 +924,23 @@ const x = 1; }); it("exposes hasRemote when origin is configured", async () => { + const withoutRemote = await getCheckoutStatus(repoDir); + expect(withoutRemote).toMatchObject({ + isGit: true, + hasRemote: false, + upstreamState: "none", + }); + const remoteDir = join(tempDir, "remote.git"); execFileSync("git", ["init", "--bare", "-b", "main", remoteDir]); execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir }); const status = await getCheckoutStatus(repoDir); - expect(status.isGit).toBe(true); - if (status.isGit) { - expect(status.hasRemote).toBe(true); - } + expect(status).toMatchObject({ + isGit: true, + hasRemote: true, + upstreamState: "none", + }); }); it("reports ahead/behind relative to origin on the base branch", async () => { @@ -1005,6 +1013,7 @@ const x = 1; return; } expect(status.upstreamRef).toBe("refs/remotes/upstream/main"); + expect(status.upstreamState).toBe("tracked"); }); it("reports the upstream branch name when it differs from the local branch name", async () => { @@ -1034,6 +1043,191 @@ const x = 1; } expect(status.upstreamRef).toBe("refs/remotes/upstream/main"); expect(status.aheadOfOrigin).toBe(0); + expect(status.hasRemote).toBe(false); + expect(status.upstreamState).toBe("tracked"); + }); + + it("reports origin as the first push remote for a never-pushed branch", async () => { + setupRemoteTrackingMain(repoDir, tempDir); + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + + const status = await getCheckoutStatus(repoDir); + + expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: "origin" }); + }); + + // The daemon's first push goes to origin. When git would send the branch to a fork instead, + // the status must not present origin as the place to publish it, and Push must not send it. + it.each([ + { name: "the branch's pushRemote", key: "branch.feature.pushRemote" }, + { name: "remote.pushDefault", key: "remote.pushDefault" }, + ])("does not publish to origin when $name sends the branch to a fork", async ({ key }) => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir }); + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + execFileSync("git", ["config", key, "fork"], { cwd: repoDir }); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + + const status = await getCheckoutStatus(repoDir); + await expect(pushCurrentBranch(repoDir)).rejects.toThrow( + "Git is set to push this branch to 'fork'", + ); + + expect(status).toMatchObject({ + upstreamState: "none", + hasRemote: true, + firstPushRemote: null, + }); + const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"]) + .toString() + .trim(); + expect(originBranches).toBe("* main"); + }); + + it("still publishes a branch that tracks a local branch to origin", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + execFileSync("git", ["checkout", "-b", "feature", "--track", "main"], { cwd: repoDir }); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + + await pushCurrentBranch(repoDir); + + const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir }) + .toString() + .trim(); + const remoteHead = execFileSync("git", [ + "--git-dir", + remoteDir, + "rev-parse", + "refs/heads/feature", + ]) + .toString() + .trim(); + expect(remoteHead).toBe(localHead); + }); + + // With a tag of the same name, git spells the current branch "heads/release". Its settings and + // its ref are still stored under "release". + describe("a branch that shares its name with a tag", () => { + it("does not publish to origin when the branch's pushRemote sends it to a fork", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir }); + execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir }); + execFileSync("git", ["config", "branch.release.pushRemote", "fork"], { cwd: repoDir }); + commitFile(repoDir, "release.txt", "release\n", "release commit"); + execFileSync("git", ["tag", "release"], { cwd: repoDir }); + + const status = await getCheckoutStatus(repoDir); + await expect(pushCurrentBranch(repoDir)).rejects.toThrow( + "Git is set to push this branch to 'fork'", + ); + + expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: null }); + const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"]) + .toString() + .trim(); + expect(originBranches).toBe("* main"); + }); + + it("does not report a branch whose remote copy was deleted as never pushed", async () => { + setupRemoteTrackingMain(repoDir, tempDir); + execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir }); + commitFile(repoDir, "release.txt", "release\n", "release commit"); + execFileSync("git", ["push", "-u", "origin", "release"], { cwd: repoDir }); + execFileSync("git", ["tag", "release"], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "--delete", "refs/heads/release"], { cwd: repoDir }); + execFileSync("git", ["fetch", "--prune", "origin"], { cwd: repoDir }); + + const status = await getCheckoutStatus(repoDir); + + expect(status).toMatchObject({ upstreamState: "gone", aheadOfOrigin: null }); + }); + + it("pushes a branch that tracks a fork to the fork", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir }); + execFileSync("git", ["checkout", "-b", "release"], { cwd: repoDir }); + commitFile(repoDir, "release.txt", "release\n", "release commit"); + execFileSync("git", ["push", "-u", "fork", "release"], { cwd: repoDir }); + execFileSync("git", ["tag", "release"], { cwd: repoDir }); + commitFile(repoDir, "release.txt", "release two\n", "second release commit"); + + await pushCurrentBranch(repoDir); + + const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir }) + .toString() + .trim(); + const forkHead = execFileSync("git", [ + "--git-dir", + forkDir, + "rev-parse", + "refs/heads/release", + ]) + .toString() + .trim(); + expect(forkHead).toBe(localHead); + const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"]) + .toString() + .trim(); + expect(originBranches).toBe("* main"); + }); + }); + + it("still publishes a never-pushed Paseo worktree branch to origin in a fork setup", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir }); + execFileSync("git", ["config", "remote.pushDefault", "fork"], { cwd: repoDir }); + const worktree = await createLegacyWorktreeForTest({ + branchName: "worktree-feature", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "worktree-feature", + paseoHome, + }); + const worktreeDir = worktree.worktreePath; + commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit"); + + await pushCurrentBranch(worktreeDir, undefined, { paseoHome }); + + const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir }) + .toString() + .trim(); + const remoteHead = execFileSync("git", [ + "--git-dir", + remoteDir, + "rev-parse", + "refs/heads/worktree-feature", + ]) + .toString() + .trim(); + expect(remoteHead).toBe(localHead); + }); + + // Push's first push targets origin, so without origin a never-pushed branch has nowhere to go. + it("reports a never-pushed branch and refuses its first push when origin is missing", async () => { + const forkDir = join(tempDir, "fork.git"); + execFileSync("git", ["init", "--bare", "-b", "main", forkDir]); + execFileSync("git", ["remote", "add", "upstream", forkDir], { cwd: repoDir }); + execFileSync("git", ["checkout", "-b", "local-only"], { cwd: repoDir }); + commitFile(repoDir, "local-only.txt", "local\n", "local commit"); + + const status = await getCheckoutStatus(repoDir); + + expect(status).toMatchObject({ + isGit: true, + upstreamState: "none", + hasRemote: false, + firstPushRemote: null, + }); + await expect(pushCurrentBranch(repoDir)).rejects.toThrow("Remote 'origin' is not configured."); }); // A legal local branch named "origin/main" shadows the short form "origin/main" in git's @@ -1067,6 +1261,8 @@ const x = 1; } expect(status.upstreamRef).toBeNull(); expect(status.aheadOfOrigin).toBeNull(); + expect(status.upstreamState).toBe("none"); + expect(status.aheadBehind).toEqual({ ahead: 1, behind: 0 }); }); it("reports a PR worktree as not ahead when its branch is pushed to the configured PR remote", async () => { @@ -1170,6 +1366,79 @@ const x = 1; } expect(status.aheadOfOrigin).toBeNull(); expect(status.behindOfOrigin).toBeNull(); + expect(status.upstreamRef).toBeNull(); + expect(status.upstreamState).toBe("gone"); + }); + + it("does not report a published branch as never pushed when the clone fetches only main", async () => { + setupRemoteTrackingMain(repoDir, tempDir); + // What `git clone --single-branch` and `--depth` leave behind: no tracking ref for other branches. + execFileSync( + "git", + ["config", "remote.origin.fetch", "+refs/heads/main:refs/remotes/origin/main"], + { cwd: repoDir }, + ); + execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir }); + commitFile(repoDir, "feature.txt", "feature\n", "feature commit"); + execFileSync("git", ["push", "-u", "origin", "feature"], { cwd: repoDir }); + execFileSync("git", ["push", "origin", "--delete", "feature"], { cwd: repoDir }); + execFileSync("git", ["fetch", "--prune", "origin"], { cwd: repoDir }); + + const status = await getCheckoutStatus(repoDir); + + expect(status).toMatchObject({ + isGit: true, + aheadBehind: { ahead: 1, behind: 0 }, + upstreamRef: null, + aheadOfOrigin: null, + upstreamState: "unknown", + }); + }); + + it("re-publishes a Paseo worktree branch whose remote copy was deleted and pruned", async () => { + const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir); + const worktree = await createLegacyWorktreeForTest({ + branchName: "merged-feature", + cwd: repoDir, + baseBranch: "main", + worktreeSlug: "merged-feature", + paseoHome, + }); + const worktreeDir = worktree.worktreePath; + commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit"); + execFileSync("git", ["push", "-u", "origin", "merged-feature"], { cwd: worktreeDir }); + execFileSync("git", ["push", "origin", "--delete", "merged-feature"], { cwd: worktreeDir }); + execFileSync("git", ["fetch", "--prune", "origin"], { cwd: worktreeDir }); + + const gone = await getCheckoutStatus(worktreeDir, { paseoHome }); + expect(gone).toMatchObject({ + isPaseoOwnedWorktree: true, + aheadBehind: { ahead: 1, behind: 0 }, + aheadOfOrigin: null, + upstreamState: "gone", + }); + + await pushCurrentBranch(worktreeDir); + + const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir }) + .toString() + .trim(); + const remoteHead = execFileSync("git", [ + "--git-dir", + remoteDir, + "rev-parse", + "refs/heads/merged-feature", + ]) + .toString() + .trim(); + expect(remoteHead).toBe(localHead); + const republished = await getCheckoutStatus(worktreeDir, { paseoHome }); + expect(republished).toMatchObject({ + upstreamRef: "refs/remotes/origin/merged-feature", + upstreamState: "tracked", + aheadOfOrigin: 0, + behindOfOrigin: 0, + }); }); it("does not report full history as unpushed for fresh no-track Paseo worktrees", async () => { diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 7d345a889..81f3b6acd 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -908,7 +908,9 @@ export interface CheckoutStatusGitNonPaseo { upstreamRef: string | null; aheadOfOrigin: number | null; behindOfOrigin: number | null; + upstreamState: UpstreamState; hasRemote: boolean; + firstPushRemote: string | null; remoteUrl: string | null; isPaseoOwnedWorktree: false; } @@ -926,7 +928,9 @@ export interface CheckoutStatusGitPaseo { upstreamRef: string | null; aheadOfOrigin: number | null; behindOfOrigin: number | null; + upstreamState: UpstreamState; hasRemote: boolean; + firstPushRemote: string | null; remoteUrl: string | null; isPaseoOwnedWorktree: true; } @@ -983,7 +987,8 @@ export type CheckoutSnapshotFacts = comparisonBaseRef: string | null; branchRemoteName: string | null; branchMergeRef: string | null; - upstreamStatus: UpstreamStatus | null; + upstreamStatus: UpstreamStatus; + firstPushRemote: string | null; pullRequestLookupTarget: PullRequestStatusLookupTarget | null; }; @@ -1870,9 +1875,48 @@ async function getAheadBehind( return getAheadBehindForComparisonRef(cwd, comparisonBaseRef, currentBranch, context); } -export interface UpstreamStatus { - ref: string; - aheadBehind: AheadBehind; +// How the current branch relates to its upstream. "none" means no upstream is configured: the +// branch was never pushed. "gone" is git's `[gone]`: an upstream is configured but its +// remote-tracking ref no longer exists, as after the remote branch is deleted and pruned. +// "unknown" means git cannot say: the read failed, or an upstream is configured that this clone +// keeps no remote-tracking ref for, as in a `--single-branch` or `--depth` clone. +export type UpstreamStatus = + | { state: "tracked"; ref: string; aheadBehind: AheadBehind } + | { state: "gone"; ref: string } + | { state: "none" } + | { state: "unknown" }; + +export type UpstreamState = UpstreamStatus["state"]; + +export interface CheckoutUpstreamFields { + upstreamRef: string | null; + aheadOfOrigin: number | null; + behindOfOrigin: number | null; + upstreamState: UpstreamState; +} + +// The status fields that describe the upstream. upstreamRef and the counts stay null unless the +// upstream is tracked, as they were before upstreamState existed. +export function projectUpstreamStatus(status: UpstreamStatus): CheckoutUpstreamFields { + if (status.state === "tracked") { + return { + upstreamRef: status.ref, + aheadOfOrigin: status.aheadBehind.ahead, + behindOfOrigin: status.aheadBehind.behind, + upstreamState: "tracked", + }; + } + return { + upstreamRef: null, + aheadOfOrigin: null, + behindOfOrigin: null, + upstreamState: status.state, + }; +} + +// The configured upstream ref, whether or not its remote-tracking ref still exists. +export function configuredUpstreamRef(status: UpstreamStatus): string | null { + return status.state === "tracked" || status.state === "gone" ? status.ref : null; } async function getAheadBehindForComparisonRef( @@ -1894,32 +1938,123 @@ async function getAheadBehindForComparisonRef( return { ahead, behind }; } -async function getUpstreamStatus( +// The name git stores a branch's settings and ref under. getCurrentBranch returns git's short +// spelling of the branch, which gains a "heads/" prefix when another ref, such as a tag, shares +// the name. That spelling is right for a revision or a refspec and wrong for these lookups. +async function readStoredBranchName( cwd: string, currentBranch: string, context?: CheckoutContext, -): Promise { +): Promise { + const branchRefPrefix = "refs/heads/"; + if (!currentBranch.startsWith("heads/") && !currentBranch.startsWith(branchRefPrefix)) { + return currentBranch; + } + try { + const { stdout } = await getRunGitCommand(context)(["symbolic-ref", "--quiet", "HEAD"], { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + }); + const headRef = stdout.trim(); + return headRef.startsWith(branchRefPrefix) + ? headRef.slice(branchRefPrefix.length) + : currentBranch; + } catch { + return currentBranch; + } +} + +// What git reports for a branch's upstream: its remote-tracking ref and how the branch tracks it. +// Both are blank when git resolves no upstream. +interface UpstreamTracking { + ref: string; + track: string; +} + +async function readUpstreamTracking( + cwd: string, + storedBranchName: string | null, + context?: CheckoutContext, +): Promise { + if (!storedBranchName) { + return { ref: "", track: "" }; + } try { const { stdout } = await getRunGitCommand(context)( [ "for-each-ref", "--format=%(upstream)%00%(upstream:track,nobracket)", - `refs/heads/${currentBranch}`, + `refs/heads/${storedBranchName}`, ], { cwd, envOverlay: READ_ONLY_GIT_ENV, logger: context?.logger }, ); const [ref = "", track = ""] = stdout.trim().split("\0", 2); - if (!ref || track === "gone") { - return null; - } - const ahead = Number.parseInt(track.match(/ahead (\d+)/)?.[1] ?? "0", 10); - const behind = Number.parseInt(track.match(/behind (\d+)/)?.[1] ?? "0", 10); - return { ref, aheadBehind: { ahead, behind } }; + return { ref, track }; } catch { return null; } } +function resolveUpstreamStatus( + tracking: UpstreamTracking | null, + hasConfiguredUpstream: boolean, +): UpstreamStatus { + if (!tracking) { + return { state: "unknown" }; + } + if (!tracking.ref) { + return hasConfiguredUpstream ? { state: "unknown" } : { state: "none" }; + } + if (tracking.track === "gone") { + return { state: "gone", ref: tracking.ref }; + } + const ahead = Number.parseInt(tracking.track.match(/ahead (\d+)/)?.[1] ?? "0", 10); + const behind = Number.parseInt(tracking.track.match(/behind (\d+)/)?.[1] ?? "0", 10); + return { state: "tracked", ref: tracking.ref, aheadBehind: { ahead, behind } }; +} + +// The remote git pushes a branch to: branch..pushRemote, then remote.pushDefault, then the +// branch's own remote, then origin. +async function readGitPushRemote(input: { + cwd: string; + storedBranchName: string; + branchRemoteName: string | null; + context?: CheckoutContext; +}): Promise { + const { cwd, storedBranchName, context } = input; + const [branchPushRemote, pushDefault] = await Promise.all([ + getGitConfigValue(cwd, `branch.${storedBranchName}.pushRemote`, context), + getGitConfigValue(cwd, "remote.pushDefault", context), + ]); + 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; @@ -2210,24 +2345,28 @@ export async function getCheckoutSnapshotFacts( let branchRemoteName: string | null = null; let branchMergeRef: string | null = null; let branchRemoteUrl: string | null = null; - const upstreamStatusPromise = inspected.currentBranch - ? getUpstreamStatus(cwd, inspected.currentBranch, context) - : Promise.resolve(null); - if (inspected.currentBranch) { - branchRemoteName = await getGitConfigValue( - cwd, - `branch.${inspected.currentBranch}.remote`, - context, - ); + const storedBranchName = inspected.currentBranch + ? await readStoredBranchName(cwd, inspected.currentBranch, context) + : null; + const upstreamTrackingPromise = readUpstreamTracking(cwd, storedBranchName, context); + if (storedBranchName) { + branchRemoteName = await getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context); if (branchRemoteName) { [branchMergeRef, branchRemoteUrl] = await Promise.all([ - getGitConfigValue(cwd, `branch.${inspected.currentBranch}.merge`, context), + getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context), branchRemoteName === "origin" ? inspected.remoteUrl : resolveGitRemoteUrl({ cwd, remote: branchRemoteName, context }), ]); } } + const firstPushRemotePromise = readFirstPushRemote({ + cwd, + storedBranchName, + branchRemoteName, + hasOrigin: inspected.remoteUrl !== null, + context, + }); let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({ cwd, inspected, @@ -2243,7 +2382,10 @@ export async function getCheckoutSnapshotFacts( pullRequestLookupTarget, context, ); - const upstreamStatus = await upstreamStatusPromise; + const upstreamStatus = resolveUpstreamStatus( + await upstreamTrackingPromise, + branchRemoteName !== null && branchMergeRef !== null, + ); return { isGit: true, @@ -2260,6 +2402,7 @@ export async function getCheckoutSnapshotFacts( branchRemoteName, branchMergeRef, upstreamStatus, + firstPushRemote: await firstPushRemotePromise, pullRequestLookupTarget, }; } @@ -2432,14 +2575,11 @@ export async function getCheckoutStatus( baseRef && currentBranch ? await getAheadBehind(cwd, baseRef, currentBranch, factsContext) : null; - const upstreamStatus = facts.upstreamStatus; // The wire carries the display name: clients label the base with it and send it back to // request diffs and merges. The exact ref stays in worktree.json and in facts, where the // comparisons and actions read it. const displayBaseRef = baseRef ? branchNameFromRef(baseRef) : null; - const upstreamRef = upstreamStatus?.ref ?? null; - const aheadOfOrigin = upstreamStatus?.aheadBehind.ahead ?? null; - const behindOfOrigin = upstreamStatus?.aheadBehind.behind ?? null; + const upstream = projectUpstreamStatus(facts.upstreamStatus); if (paseoWorktree.isPaseoOwnedWorktree && baseRef) { return { @@ -2452,10 +2592,9 @@ export async function getCheckoutStatus( baseRefExact: baseRef, comparisonBaseRef, aheadBehind, - upstreamRef, - aheadOfOrigin, - behindOfOrigin, + ...upstream, hasRemote, + firstPushRemote: facts.firstPushRemote, remoteUrl, isPaseoOwnedWorktree: true, }; @@ -2472,10 +2611,9 @@ export async function getCheckoutStatus( baseRefExact: baseRef, comparisonBaseRef, aheadBehind, - upstreamRef, - aheadOfOrigin, - behindOfOrigin, + ...upstream, hasRemote, + firstPushRemote: facts.firstPushRemote, remoteUrl, isPaseoOwnedWorktree: false, }; @@ -3107,7 +3245,7 @@ export async function getCheckoutShortstat( export interface CheckoutRefDerivedState { aheadBehind: AheadBehind | null; diffStat: CheckoutShortstat | null; - upstreamStatus: UpstreamStatus | null; + upstreamStatus: UpstreamStatus; } function normalizeRemoteTrackingRef(ref: string): string { @@ -3150,7 +3288,8 @@ function getCheckoutRefMovement( .filter((ref): ref is string => Boolean(ref)) .map(normalizeRemoteTrackingRef) .some((ref) => normalizedMoves.has(ref)); - const upstreamRef = facts.upstreamStatus?.ref ?? checkoutFactsConfiguredRemoteRef(facts); + const upstreamRef = + configuredUpstreamRef(facts.upstreamStatus) ?? checkoutFactsConfiguredRemoteRef(facts); const upstreamMoved = upstreamRef ? normalizedMoves.has(normalizeRemoteTrackingRef(upstreamRef)) : false; @@ -3206,10 +3345,11 @@ export async function getCheckoutRefDerivedState( : await getAheadBehindForComparisonRef(cwd, upstreamRef, currentBranch, context); upstreamStatus = upstreamAheadBehind ? { - ref: facts.upstreamStatus?.ref ?? `refs/remotes/${normalizedUpstream}`, + state: "tracked", + ref: configuredUpstreamRef(facts.upstreamStatus) ?? `refs/remotes/${normalizedUpstream}`, aheadBehind: upstreamAheadBehind, } - : null; + : { state: "unknown" }; } return { aheadBehind, diffStat, upstreamStatus }; @@ -4192,24 +4332,29 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService } } -export async function pushCurrentBranch(cwd: string, forgeService?: ForgeService): Promise { +export async function pushCurrentBranch( + cwd: string, + forgeService?: ForgeService, + context?: CheckoutContext, +): Promise { await requireGitRepo(cwd); const currentBranch = await getCurrentBranch(cwd); if (!currentBranch || currentBranch === "HEAD") { throw new Error("Unable to determine current branch for push"); } - const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, currentBranch); + 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, currentBranch, configuredPushTarget); + await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, configuredPushTarget); forgeService?.invalidate({ cwd }); return; } - const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, currentBranch); + const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName); if (upstreamTarget) { await runGitCommand( ["push", "-u", upstreamTarget.remoteName, `HEAD:refs/heads/${upstreamTarget.headRef}`], @@ -4223,10 +4368,44 @@ export async function pushCurrentBranch(cwd: string, forgeService?: ForgeService if (!hasRemote) { throw new Error("Remote 'origin' is not configured."); } - await runGitCommand(["push", "-u", "origin", currentBranch], { cwd, timeout: 120_000 }); + 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 { + 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. + if (branchRemoteName !== null && branchMergeRef !== null) { + return; + } + const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { context }); + if (paseoWorktree.isPaseoOwnedWorktree) { + return; + } + const gitPushRemote = await readGitPushRemote({ + cwd, + storedBranchName, + 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.`, + ); + } +} + async function getCurrentBranchConfiguredPushTarget( cwd: string, currentBranch: string,