Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
336 changes: 334 additions & 2 deletions apps/server/src/git/GitManager.test.ts

Large diffs are not rendered by default.

39 changes: 35 additions & 4 deletions apps/server/src/git/GitManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2676,6 +2676,36 @@ export const make = Effect.gen(function* () {
return { pullRequest };
});

const ensureNoTrackedChanges = Effect.fn("ensureNoTrackedChanges")(function* (
cwd: string,
pullRequestNumber: number,
) {
const trackedChanges = yield* gitCore.execute({
operation: "GitManager.preparePullRequestThread.trackedChanges",
cwd,
args: ["status", "--porcelain", "--untracked-files=no"],
});
if (trackedChanges.stdout.trim().length > 0) {
return yield* new GitManagerError({
operation: "preparePullRequestThread",
cwd,
detail: `This repository has uncommitted changes. Commit or stash them before checking out pull request #${pullRequestNumber} here, or check it out in its own folder.`,
});
}
});

// Some hosts only switch branches on checkout; use the existing lossless refresh to advance them.
const moveToPullRequestHead = (cwd: string, headSha: string | undefined) =>
headSha === undefined || !/^[0-9a-f]{7,64}$/i.test(headSha)
? Effect.succeed(false)
: gitCore.resolveCommit({ cwd, revision: headSha }).pipe(
Effect.flatMap(({ commitSha }) =>
gitCore.refreshCheckedOutBranch({ cwd, targetCommit: commitSha }),
),
Effect.map((refreshed) => refreshed.onTarget),
Effect.orElseSucceed(() => false),
);

const preparePullRequestThread: GitManager["Service"]["preparePullRequestThread"] = Effect.fn(
"preparePullRequestThread",
)(function* (input) {
Expand Down Expand Up @@ -2709,25 +2739,26 @@ export const make = Effect.gen(function* () {
const pullRequest = toResolvedPullRequest(pullRequestSummary);

if (input.mode === "local") {
yield* ensureNoTrackedChanges(input.cwd, pullRequest.number);
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
});
const details = yield* gitCore.statusDetails(input.cwd);
const branch = details.branch ?? pullRequest.headBranch;
yield* configurePullRequestHeadUpstream(
input.cwd,
{
...pullRequest,
...toPullRequestHeadRemoteInfo(pullRequestSummary),
},
details.branch ?? pullRequest.headBranch,
branch,
);
return {
pullRequest,
branch: details.branch ?? pullRequest.headBranch,
branch,
worktreePath: null,
isOnPullRequestHead: true,
isOnPullRequestHead: yield* moveToPullRequestHead(input.cwd, pullRequestSummary.headSha),
};
}

Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/git/GitWorkflowService.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert, describe, expect, it, vi } from "@effect/vitest";
import { assert, expect, it, vi } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -30,7 +30,7 @@ function layer(input: {
);
}

describe("GitWorkflowService", () => {
it.layer(NodeServices.layer)("GitWorkflowService", (it) => {
it.effect("reports a non-Git VCS repository as not a Git repository", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService.GitWorkflowService;
Expand Down
46 changes: 39 additions & 7 deletions apps/server/src/git/GitWorkflowService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";

import {
GitManagerError,
Expand Down Expand Up @@ -31,6 +32,7 @@ import {
import * as GitManager from "./GitManager.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";

export class GitWorkflowService extends Context.Service<
GitWorkflowService,
Expand Down Expand Up @@ -171,6 +173,14 @@ export const make = Effect.gen(function* () {
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const git = yield* GitVcsDriver.GitVcsDriver;
const gitManager = yield* GitManager.GitManager;
const fileSystem = yield* FileSystem.FileSystem;

// Nested projects and path aliases must share the checkout's branch-mutation lease.
const withCheckoutLease = <A, E, R>(rootPath: string, effect: Effect.Effect<A, E, R>) =>
fileSystem.realPath(rootPath).pipe(
Effect.orElseSucceed(() => rootPath),
Effect.flatMap((cwd) => withWorkspaceLease(cwd, effect)),
);

const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
operation: string,
Expand All @@ -194,6 +204,7 @@ export const make = Effect.gen(function* () {
detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
});
}
return handle;
});

const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
Expand All @@ -220,6 +231,7 @@ export const make = Effect.gen(function* () {
detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
});
}
return handle;
});

const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
Expand Down Expand Up @@ -360,16 +372,30 @@ export const make = Effect.gen(function* () {
),
runStackedAction: (input, options) =>
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
Effect.andThen(gitManager.runStackedAction(input, options)),
Effect.flatMap((handle) =>
input.featureBranch
? withCheckoutLease(
handle.repository.rootPath,
gitManager.runStackedAction(input, options),
)
: gitManager.runStackedAction(input, options),
),
),
resolvePullRequest: routeGitManager(
"GitWorkflowService.resolvePullRequest",
gitManager.resolvePullRequest,
),
preparePullRequestThread: routeGitManager(
"GitWorkflowService.preparePullRequestThread",
gitManager.preparePullRequestThread,
),
preparePullRequestThread: (input) =>
ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
Effect.flatMap((handle) =>
input.mode === "local"
? withCheckoutLease(
handle.repository.rootPath,
gitManager.preparePullRequestThread(input),
)
: gitManager.preparePullRequestThread(input),
),
),
listRefs: (input) =>
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
Expand Down Expand Up @@ -422,11 +448,17 @@ export const make = Effect.gen(function* () {
),
createRef: (input) =>
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
Effect.andThen(git.createRef(input)),
Effect.flatMap((handle) =>
input.switchRef
? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
: git.createRef(input),
),
),
switchRef: (input) =>
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
Effect.andThen(Effect.scoped(git.switchRef(input))),
Effect.flatMap((handle) =>
withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
),
),
renameBranch: (input) =>
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/PullRequestThreadDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ vi.mock("~/state/git", () => ({
return AsyncResult.success({
branch: "feature/pr",
worktreePath: mode === "worktree" ? "/worktree" : null,
isOnPullRequestHead: true,
});
},
},
Expand All @@ -102,6 +103,7 @@ vi.mock("~/state/vcs", () => ({
vi.mock("./ui/button", () => ({ Button: "Button" }));
vi.mock("./ui/input", () => ({ Input: "Input" }));
vi.mock("./ui/spinner", () => ({ Spinner: "Spinner" }));
vi.mock("./ui/toast", () => ({ toastManager: { add: vi.fn() } }));
vi.mock("./ui/dialog", () => ({
Dialog: "Dialog",
DialogDescription: "DialogDescription",
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/components/PullRequestThreadDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { useEnvironmentQuery } from "~/state/query";
import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import { vcsEnvironment } from "~/state/vcs";
import { OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST } from "./pullRequest/pullRequestCheckoutToast";
import { Button } from "./ui/button";
import {
Dialog,
Expand All @@ -33,6 +34,7 @@ import {
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Spinner } from "./ui/spinner";
import { toastManager } from "./ui/toast";

interface PullRequestThreadDialogProps {
open: boolean;
Expand Down Expand Up @@ -171,6 +173,9 @@ export function PullRequestThreadDialog({
branch: result.value.branch,
worktreePath: result.value.worktreePath,
});
if (!result.value.isOnPullRequestHead) {
toastManager.add(OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST);
}
onOpenChange(false);
};

Expand Down
11 changes: 3 additions & 8 deletions apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ import {
} from "~/keybindings";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { usePullRequestDefaultMergeMethodResolver } from "./usePullRequestActions";
import { OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST } from "./pullRequestCheckoutToast";
import { changeRequestRepositoryUrl, gitHubPullRequestBrowserUrl } from "~/lib/openPullRequestLink";
import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
import { cn } from "~/lib/utils";
Expand Down Expand Up @@ -1246,12 +1247,6 @@ export function PullRequestDetailPanel({
return;
}
setHandoff(null);
const staleCheckoutToast = {
type: "warning",
title: "Checked out, but not on the latest commits",
description:
"The checkout could not be moved onto the pull request's latest commits, so the code there is older than the pull request. Uncommitted work or local commits keep it where it is.",
} as const;
if (task === null) {
toastManager.update(
toastId,
Expand All @@ -1264,7 +1259,7 @@ export function PullRequestDetailPanel({
? "This repository is on the pull request's branch, with a thread open on it."
: "The pull request is in its own worktree, with a thread open on it.",
}
: staleCheckoutToast,
: OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST,
);
return;
}
Expand All @@ -1277,7 +1272,7 @@ export function PullRequestDetailPanel({
title: "Checkout ready",
description: "The task is in the composer — read it over, then send.",
}
: staleCheckoutToast,
: OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST,
);
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST = {
type: "warning",
title: "Checked out, but not confirmed on the latest commit",
description:
"This checkout could not be confirmed at the pull request's latest commit, so its code may differ. Local commits or uncommitted work keep a checkout where it is.",
} as const;
11 changes: 3 additions & 8 deletions apps/web/src/components/pullRequest/usePullRequestActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import type { ReviewCommentContext } from "~/reviewCommentContext";
import { pullRequestEnvironment } from "~/state/pullRequests";

import { toastManager } from "../ui/toast";
import { OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST } from "./pullRequestCheckoutToast";
import {
checkoutFailureDescription,
handoffPrompt,
Expand Down Expand Up @@ -372,12 +373,6 @@ export function usePullRequestHandoffs({
return;
}
setHandoff(null);
const staleCheckoutToast = {
type: "warning",
title: "Checked out, but not on the latest commits",
description:
"The checkout could not be moved onto the pull request's latest commits, so the code there is older than the pull request. Uncommitted work or local commits keep it where it is.",
} as const;
if (task === null) {
toastManager.update(
toastId,
Expand All @@ -390,7 +385,7 @@ export function usePullRequestHandoffs({
? "This repository is on the pull request's branch, with a thread open on it."
: "The pull request is in its own worktree, with a thread open on it.",
}
: staleCheckoutToast,
: OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST,
);
return;
}
Expand All @@ -403,7 +398,7 @@ export function usePullRequestHandoffs({
title: "Checkout ready",
description: "The task is in the composer — read it over, then send.",
}
: staleCheckoutToast,
: OFF_HEAD_PULL_REQUEST_CHECKOUT_TOAST,
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe("AzureDevOpsCli.layer", () => {
title: "Add Azure provider",
sourceRefName: "refs/heads/feature/source-control",
targetRefName: "refs/heads/main",
lastMergeSourceCommit: { commitId: "a".repeat(40) },
status: "active",
creationDate: "2026-01-02T00:00:00.000Z",
closedDate: null,
Expand All @@ -67,6 +68,7 @@ describe("AzureDevOpsCli.layer", () => {
assert.strictEqual(result.url, "https://dev.azure.com/acme/project/_git/repo/pullrequest/42");
assert.strictEqual(result.baseRefName, "main");
assert.strictEqual(result.headRefName, "feature/source-control");
assert.strictEqual(result.headSha, "a".repeat(40));
assert.strictEqual(result.state, "open");
assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0], {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
baseRefName: "main",
headRefName: "feature/source-control",
headSha: "a".repeat(40),
state: "closed",
isCrossRepository: false,
closedAt: "2026-08-23T10:00:00Z",
Expand All @@ -42,6 +43,7 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
baseRefName: "main",
headRefName: "feature/source-control",
headSha: "a".repeat(40),
state: "closed",
closedAt: "2026-08-23T10:00:00Z",
mergedAt: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";

import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import type { NormalizedAzureDevOpsPullRequestRecord } from "./azureDevOpsPullRequests.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import {
combinedAuthOutput,
Expand Down Expand Up @@ -54,26 +55,15 @@ export const discovery = {
"Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
} satisfies SourceControlCliDiscoverySpec;

function toChangeRequest(summary: {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state: "open" | "closed" | "merged";
readonly isDraft?: boolean;
readonly isCrossRepository: boolean;
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: ChangeRequest["updatedAt"];
}): ChangeRequest {
function toChangeRequest(summary: NormalizedAzureDevOpsPullRequestRecord): ChangeRequest {
return {
provider: SourceControlProviderKind.make("azure-devops"),
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
state: summary.state,
...(summary.isDraft === true ? { isDraft: true } : {}),
closedAt: summary.closedAt ?? null,
Expand Down
Loading
Loading