Skip to content
Draft
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
2 changes: 2 additions & 0 deletions packages/core/src/task-detail/taskCreationHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export interface CreateWorkspaceArgs {
folderPath: string;
mode: WorkspaceMode;
branch?: string;
allowRemoteBranchCheckout?: boolean;
reuseExistingWorktree?: boolean;
}

export interface CreatedWorkspaceInfo {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/task-detail/taskCreationSaga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export class TaskCreationSaga extends Saga<
folderPath: repoPath,
mode: workspaceMode,
branch: branch ?? undefined,
allowRemoteBranchCheckout: input.allowRemoteBranchCheckout,
reuseExistingWorktree: input.reuseExistingWorktree,
});
},
rollback: async () => {
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/task-detail/taskInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface PrepareTaskInputOptions {
githubUserIntegrationId?: string;
workspaceMode: WorkspaceMode;
branch?: string | null;
allowRemoteBranchCheckout?: boolean;
reuseExistingWorktree?: boolean;
executionMode?: ExecutionMode;
adapter?: "claude" | "codex";
model?: string;
Expand Down Expand Up @@ -37,6 +39,8 @@ export function prepareTaskInput(
githubUserIntegrationId: options.githubUserIntegrationId,
workspaceMode: options.workspaceMode,
branch: options.branch,
allowRemoteBranchCheckout: options.allowRemoteBranchCheckout,
reuseExistingWorktree: options.reuseExistingWorktree,
executionMode: options.executionMode,
adapter: options.adapter,
model: options.model,
Expand Down
33 changes: 33 additions & 0 deletions packages/git/src/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,39 @@ export async function branchExists(
);
}

/**
* Checks whether a branch exists on the remote without fetching it.
* Uses `git ls-remote --heads`, which is read-only and reaches the remote.
*/
export async function remoteBranchExists(
baseDir: string,
branchName: string,
options?: CreateGitClientOptions & { remote?: string },
): Promise<boolean> {
const manager = getGitOperationManager();
const remote = options?.remote ?? "origin";
return manager.executeRead(
baseDir,
async (git) => {
try {
const output = await git.raw([
"ls-remote",
"--heads",
remote,
branchName,
]);
const target = `refs/heads/${branchName}`;
return output
.split("\n")
.some((line) => line.trim().endsWith(`\t${target}`));
} catch {
return false;
}
},
{ signal: options?.abortSignal },
);
}

export async function listWorktrees(
baseDir: string,
options?: CreateGitClientOptions,
Expand Down
93 changes: 93 additions & 0 deletions packages/git/src/worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,99 @@ export class WorktreeManager {
};
}

/**
* Fetches a branch that exists on the remote but not locally, then creates a
* worktree with a new local branch tracking `origin/<branch>`. Used when the
* user opts in to checking out a remote-only branch (e.g. a contributor's PR).
*/
async createWorktreeForRemoteBranch(
branch: string,
preferredName?: string,
options?: { onOutput?: (data: string) => void; remote?: string },
): Promise<WorktreeInfo> {
const manager = getGitOperationManager();
const remote = options?.remote ?? "origin";
const remoteRef = `${remote}/${branch}`;

options?.onOutput?.(`Fetching ${remoteRef}...\n`);
const fetched = await manager.executeWrite(this.mainRepoPath, (git) =>
fetchRef(git, remote, branch),
);
if (!fetched) {
throw new Error(`Failed to fetch branch '${branch}' from ${remote}`);
}

const worktreeName = await this.resolveAvailableWorktreeName(preferredName);

if (!this.usesExternalPath()) {
await this.ensureArrayDirIgnored();
}

const worktreePath = this.getWorktreePath(worktreeName);
const parentDir = path.dirname(worktreePath);
await fs.mkdir(parentDir, { recursive: true });

const targetPath = this.usesExternalPath()
? worktreePath
: `./${WORKTREE_FOLDER_NAME}/${worktreeName}/${this.repoName}`;

// `-b <branch> <remoteRef>` creates a local branch at the fetched remote ref
// and sets it up to track the remote branch.
const output = await manager.executeWrite(this.mainRepoPath, async () => {
return this.spawnWorktreeAdd(["-b", branch, targetPath, remoteRef], {
onOutput: options?.onOutput,
});
});

await this.symlinkClaudeConfig(worktreePath);
await processWorktreeLink(this.mainRepoPath, worktreePath, {
onOutput: options?.onOutput,
});
await processWorktreeInclude(this.mainRepoPath, worktreePath, {
onOutput: options?.onOutput,
});
await runPostCheckoutHook(this.mainRepoPath, worktreePath, {
onOutput: options?.onOutput,
});

return {
worktreePath,
worktreeName,
branchName: branch,
baseBranch: remoteRef,
createdAt: new Date().toISOString(),
output: output.trim() || undefined,
};
}

/**
* Resolves a worktree name that does not collide with an existing worktree,
* falling back to a freshly generated unique name when the preferred (or
* default) name is already registered or present on disk.
*/
private async resolveAvailableWorktreeName(
preferredName?: string,
): Promise<string> {
let worktreeName = preferredName ?? this.generateWorktreeName();

if (preferredName) {
const worktreePath = this.getWorktreePath(preferredName);
const existingWorktrees = await this.listWorktrees();
const isRegistered = existingWorktrees.some(
(wt) => wt.worktreePath === worktreePath,
);
const existsOnDisk = await this.worktreeExists(preferredName);

if (isRegistered || existsOnDisk) {
worktreeName = `${this.generateWorktreeName()}${Date.now()}`;
}
} else if (await this.worktreeExists(worktreeName)) {
worktreeName = `${this.generateWorktreeName()}${Date.now()}`;
}

return worktreeName;
}

async createDetachedWorktreeAtCommit(
commit: string,
preferredName?: string,
Expand Down
9 changes: 9 additions & 0 deletions packages/host-router/src/routers/workspace.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { WORKSPACE_SERVICE } from "@posthog/workspace-server/services/workspace/
import {
cachedPrUrlInput,
cachedPrUrlOutput,
checkWorktreeBranchInput,
checkWorktreeBranchOutput,
createWorkspaceInput,
createWorkspaceOutput,
deleteWorkspaceInput,
Expand Down Expand Up @@ -81,6 +83,13 @@ export const workspaceRouter = router({
getService(ctx.container).createWorkspace(input),
),

checkWorktreeBranch: publicProcedure
.input(checkWorktreeBranchInput)
.output(checkWorktreeBranchOutput)
.query(({ ctx, input }) =>
getService(ctx.container).checkWorktreeBranch(input),
),

reconcileCloudWorkspaces: publicProcedure
.input(reconcileCloudWorkspacesInput)
.output(reconcileCloudWorkspacesOutput)
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/src/task-creation-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ export interface TaskCreationInput {
repository?: string | null;
workspaceMode?: WorkspaceMode;
branch?: string | null;
// When the branch exists only on the remote, opt in to fetching and checking
// it out locally into the worktree (set after the user confirms).
allowRemoteBranchCheckout?: boolean;
// When a worktree is already checked out on the branch, opt in to reusing it
// for this task instead of creating a new one (set after the user confirms).
reuseExistingWorktree?: boolean;
githubIntegrationId?: number;
githubUserIntegrationId?: string;
executionMode?: ExecutionMode;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { FolderOpen } from "@phosphor-icons/react";
import { AlertDialog, Button, Code, Flex } from "@radix-ui/themes";
import { useExistingWorktreeConfirmStore } from "../stores/existingWorktreeConfirmStore";

/**
* Globally-mounted confirmation shown when a user starts a worktree task on a
* branch that already has a worktree checked out. Confirming reuses that
* worktree for the task instead of creating a new one.
*/
export function ExistingWorktreeDialog() {
const isOpen = useExistingWorktreeConfirmStore((s) => s.isOpen);
const branch = useExistingWorktreeConfirmStore((s) => s.branch);
const worktreePath = useExistingWorktreeConfirmStore((s) => s.worktreePath);
const accept = useExistingWorktreeConfirmStore((s) => s.accept);
const cancel = useExistingWorktreeConfirmStore((s) => s.cancel);

return (
<AlertDialog.Root
open={isOpen}
onOpenChange={(open) => {
if (!open) cancel();
}}
>
<AlertDialog.Content maxWidth="460px" size="2">
<AlertDialog.Title className="text-base">
<Flex align="center" gap="2">
<FolderOpen size={18} weight="bold" color="var(--accent-9)" />
Worktree already exists
</Flex>
</AlertDialog.Title>
<AlertDialog.Description className="text-sm">
A worktree is already checked out on{" "}
{branch ? <Code>{branch}</Code> : "this branch"}
{worktreePath ? (
<>
{" "}
at <Code>{worktreePath}</Code>
</>
) : null}
. Continue and use that worktree for this task?
</AlertDialog.Description>

<Flex justify="end" gap="2" mt="4">
<AlertDialog.Cancel>
<Button variant="soft" color="gray" size="1" onClick={cancel}>
Cancel
</Button>
</AlertDialog.Cancel>
<AlertDialog.Action>
<Button variant="solid" size="1" onClick={accept}>
Use existing worktree
</Button>
</AlertDialog.Action>
</Flex>
</AlertDialog.Content>
</AlertDialog.Root>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { GitBranch } from "@phosphor-icons/react";
import { AlertDialog, Button, Code, Flex } from "@radix-ui/themes";
import { useRemoteBranchConfirmStore } from "../stores/remoteBranchConfirmStore";

/**
* Globally-mounted confirmation shown when a user starts a worktree task on a
* branch that exists only on the remote. Confirming fetches the branch and
* checks it out locally into the new worktree.
*/
export function RemoteBranchCheckoutDialog() {
const isOpen = useRemoteBranchConfirmStore((s) => s.isOpen);
const branch = useRemoteBranchConfirmStore((s) => s.branch);
const accept = useRemoteBranchConfirmStore((s) => s.accept);
const cancel = useRemoteBranchConfirmStore((s) => s.cancel);

return (
<AlertDialog.Root
open={isOpen}
onOpenChange={(open) => {
if (!open) cancel();
}}
>
<AlertDialog.Content maxWidth="440px" size="2">
<AlertDialog.Title className="text-base">
<Flex align="center" gap="2">
<GitBranch size={18} weight="bold" color="var(--accent-9)" />
Check out remote branch?
</Flex>
</AlertDialog.Title>
<AlertDialog.Description className="text-sm">
{branch ? <Code>{branch}</Code> : "This branch"} doesn't exist locally
but was found on the remote. Check it out into a new worktree to
continue working on it?
</AlertDialog.Description>

<Flex justify="end" gap="2" mt="4">
<AlertDialog.Cancel>
<Button variant="soft" color="gray" size="1" onClick={cancel}>
Cancel
</Button>
</AlertDialog.Cancel>
<AlertDialog.Action>
<Button variant="solid" size="1" onClick={accept}>
Check out branch
</Button>
</AlertDialog.Action>
</Flex>
</AlertDialog.Content>
</AlertDialog.Root>
);
}
39 changes: 39 additions & 0 deletions packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ import { useSettingsStore } from "../../settings/settingsStore";
import { useCreateTask } from "../../tasks/useTaskCrudMutations";
import { useTourStore } from "../../tour/tourStore";
import { createFirstTaskTour } from "../../tour/tours/createFirstTaskTour";
import { useExistingWorktreeConfirmStore } from "../stores/existingWorktreeConfirmStore";
import { useRemoteBranchConfirmStore } from "../stores/remoteBranchConfirmStore";

const log = logger.scope("task-creation");

Expand Down Expand Up @@ -179,6 +181,41 @@ export function useTaskCreation({
return false;
}

// Confirm a couple of worktree branch situations before starting the
// task. Done before the pending view so a dialog (and a cancel) don't
// leave a half-started task on screen. An existing worktree takes
// priority: a branch with one already checked out also exists locally.
let allowRemoteBranchCheckout = false;
let reuseExistingWorktree = false;
if (workspaceMode === "worktree" && branch && selectedDirectory) {
try {
const { status, existingWorktreePath } =
await hostClient.workspace.checkWorktreeBranch.query({
mainRepoPath: selectedDirectory,
branch,
});
if (existingWorktreePath) {
const confirmed = await useExistingWorktreeConfirmStore
.getState()
.confirm(branch, existingWorktreePath);
if (!confirmed) {
return false;
}
reuseExistingWorktree = true;
} else if (status === "remote-only") {
const confirmed = await useRemoteBranchConfirmStore
.getState()
.confirm(branch);
if (!confirmed) {
return false;
}
allowRemoteBranchCheckout = true;
}
} catch (error) {
log.warn("Failed to check worktree branch availability", { error });
}
}

setIsCreatingTask(true);

const content = contentOverride ?? editor.getContent();
Expand Down Expand Up @@ -219,6 +256,8 @@ export function useTaskCreation({
githubUserIntegrationId,
workspaceMode,
branch,
allowRemoteBranchCheckout,
reuseExistingWorktree,
executionMode,
adapter,
model,
Expand Down
Loading
Loading