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
114 changes: 114 additions & 0 deletions apps/desktop/src/main/bootstrap/thread-context-actions.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, expect, it, vi } from "vitest";

import type {
WorktreeSetupStageEvent,
WorktreeSetupStageReporter,
} from "../git/git-service";
import { createThreadContextActions } from "./thread-context-actions";

function createThread(id: string, worktreeId: string) {
Expand Down Expand Up @@ -331,6 +335,7 @@ describe("createThreadContextActions", () => {
branchName: "feature/branch",
worktreePath: "/Users/test/.pi-desktop/repo/feature-branch",
baseBranch: "main",
onStage: expect.any(Function),
});
expect(buildThreadContext).toHaveBeenCalledWith(
"repo-1",
Expand All @@ -341,6 +346,115 @@ describe("createThreadContextActions", () => {
);
});

it("keeps the checkout when opening it fails and retries against the same path", async () => {
const worktreePath = "/Users/test/.pi-desktop/repo/feature-branch";
const thread = createThread("thread-1", worktreePath);
const stages: WorktreeSetupStageEvent[] = [];
const onStage: WorktreeSetupStageReporter = (event) => stages.push(event);
// The git layer is idempotent: a second call for an existing
// checkout returns the same path instead of duplicating it.
const createdPaths = new Set<string>();
const createWorktree = vi.fn(
(input: {
repositoryRoot: string;
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}) => {
input.onStage?.({ stage: "ready", status: "completed" });
createdPaths.add(input.worktreePath);
return input.worktreePath;
},
);
let inspectCreatedAttempts = 0;
const buildThreadContext = vi.fn(() => ({
repositoryId: "repo-1",
worktreePath,
thread,
socketPath: "/tmp/pi-desktop/thread.sock",
runtimeId: "runtime-1",
command: ["node", "/tmp/session-server.mjs"],
agentMode: "mock" as const,
agentDirectory: "/tmp/repo/.pi/agent",
runtimeAgentDirectory: "/tmp/repo/.pi/agent/threads/thread-1",
}));

const actions = createThreadContextActions({
inspectWorktreeOrThrow: vi.fn((targetPath: string) => {
if (targetPath === worktreePath) {
inspectCreatedAttempts += 1;
if (inspectCreatedAttempts === 1) {
throw new Error("checkout not inspectable yet");
}
}
return {
rootPath: "/tmp/repo",
currentWorktreePath:
targetPath === worktreePath ? worktreePath : "/tmp/repo",
worktrees: [],
defaultBranch: "main",
};
}),
upsertRepository: vi.fn(() => ({ id: "repo-1", rootPath: "/tmp/repo" })),
getRepository: vi.fn(() => ({ id: "repo-1", rootPath: "/tmp/repo" })),
setLastSelectedWorktree: vi.fn(),
replaceSelection: vi.fn(),
listThreadsByWorktree: vi.fn(() => [thread]),
createThread: vi.fn(),
getDefaultThreadTitle: () => "Pi",
buildThreadContext,
environment: { NODE_ENV: "test" },
runtimeSocketDirectory: "/tmp/pi-desktop/sockets",
execPath: "/usr/local/bin/node",
sessionServerEntryPath: "/tmp/session-server.mjs",
ensureDirectory: vi.fn(),
resolveRuntimeOptions: vi.fn(() => ({
mode: "mock" as const,
cwd: "/tmp/repo",
agentDir: "/tmp/repo/.pi/agent",
})),
createLaunchDetails: vi.fn(() => ({
socketPath: "/tmp/pi-desktop/thread.sock",
runtimeId: "runtime-1",
command: ["node", "/tmp/session-server.mjs"],
})),
getHomePath: () => "/Users/test",
isRepository: vi.fn(() => true),
createWorktree,
ensureThreadRuntime: vi.fn(),
restartThreadRuntime: vi.fn(),
connectAgentHost: vi.fn(),
});

await expect(
actions.createWorktreeContext("repo-1", "feature/branch", onStage),
).rejects.toThrow("checkout not inspectable yet");

expect(stages).toContainEqual({ stage: "ready", status: "completed" });
expect(stages).toContainEqual({
stage: "open-worktree",
status: "failed",
message: "checkout not inspectable yet",
});
// The failed attempt kept the checkout: it is still the one and
// only created path, and the retry targets it again.
expect([...createdPaths]).toEqual([worktreePath]);

await expect(
actions.createWorktreeContext("repo-1", "feature/branch", onStage),
).resolves.toEqual(expect.objectContaining({ worktreePath }));

expect(createWorktree).toHaveBeenCalledTimes(2);
expect(createWorktree.mock.calls[0]?.[0].worktreePath).toBe(worktreePath);
expect(createWorktree.mock.calls[1]?.[0].worktreePath).toBe(worktreePath);
expect([...createdPaths]).toEqual([worktreePath]);
expect(stages).toContainEqual({
stage: "open-worktree",
status: "completed",
});
});

it("allows the bootstrap wrapper to preserve its shared default agent directory", () => {
const createLaunchDetails = vi.fn(() => ({
socketPath: "/tmp/pi-desktop/thread.sock",
Expand Down
37 changes: 36 additions & 1 deletion apps/desktop/src/main/bootstrap/thread-context-actions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import path from "node:path";
import type { ThreadCatalogEntry } from "../catalogs/thread-catalog";
import type {
WorktreeSetupStageEvent,
WorktreeSetupStageReporter,
} from "../git/git-service";
import type { ThreadRuntimeLaunchSpec } from "../thread-runtime-manager";
import type {
ResolvedRepositoryInspection,
Expand Down Expand Up @@ -84,6 +88,7 @@ type CreateThreadContextActionsDependencies<
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}): string;
ensureThreadRuntime(spec: ThreadRuntimeLaunchSpec): Promise<unknown>;
restartThreadRuntime(spec: ThreadRuntimeLaunchSpec): Promise<unknown>;
Expand Down Expand Up @@ -149,7 +154,15 @@ export function createThreadContextActions<
async function createWorktreeContext(
repositoryId: string,
branchName: string,
onStage?: WorktreeSetupStageReporter,
): Promise<SelectedThreadContext<TThread> | null> {
const reportStage = (event: WorktreeSetupStageEvent) => {
try {
onStage?.(event);
} catch {
// A broken progress reporter must never fail setup itself.
}
};
const repository = deps.getRepository(repositoryId);
if (!repository) {
throw new Error(`Unknown repository: ${repositoryId}`);
Expand All @@ -173,14 +186,36 @@ export function createThreadContextActions<
path.basename(repository.rootPath),
trimmedBranchName.replace(/[\\/]+/g, "-"),
);
// If opening the new checkout fails below, the checkout is kept:
// nothing here removes it, and a retry reuses the same path (the
// git layer returns the existing worktree instead of duplicating
// it), so setup can be retried safely (issue #12).
const createdWorktreePath = deps.createWorktree({
repositoryRoot: repository.rootPath,
branchName: trimmedBranchName,
worktreePath,
baseBranch: inspection.defaultBranch ?? undefined,
onStage: reportStage,
});

return resolveDefaultThreadContext(createdWorktreePath);
reportStage({ stage: "open-worktree", status: "started" });
try {
const context = await resolveDefaultThreadContext(createdWorktreePath);
if (!context) {
throw new Error(
"Failed to create a default thread for the new worktree",
);
}
reportStage({ stage: "open-worktree", status: "completed" });
return context;
} catch (error) {
reportStage({
stage: "open-worktree",
status: "failed",
message: error instanceof Error ? error.message : String(error),
});
throw error;
}
}

function buildFastThreadContext(options: {
Expand Down
7 changes: 6 additions & 1 deletion apps/desktop/src/main/effect/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import type {
import { Context, Effect } from "effect";
import type { PersistentJsonFileOptions } from "../catalogs/persistent-json-file";
import type { RepositoryCatalogEntry } from "../catalogs/repository-catalog";
import type { GitRepositoryInspection } from "../git/git-service";
import type {
GitRepositoryInspection,
WorktreeSetupStageReporter,
} from "../git/git-service";
import type { TerminalInstance } from "../terminal-manager";
import {
type FileSystemError,
Expand Down Expand Up @@ -85,6 +88,7 @@ export interface GitServiceOps {
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}) => Effect.Effect<string, GitError>;
readonly removeWorktree: (options: {
worktreePath: string;
Expand Down Expand Up @@ -150,6 +154,7 @@ export class GitServiceEffect extends Effect.Service<GitServiceEffect>()(
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}) => Effect.fail(new GitError({ message: "not implemented" })),
removeWorktree: (_options: {
worktreePath: string;
Expand Down
45 changes: 17 additions & 28 deletions apps/desktop/src/main/git/git-service-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ import {
} from "./status-changing-commands";
import { type ParsedWorktree, parseWorktreeBlocks } from "./status-parsers";
import type { GitRepositoryInspection, GitWorktreeSummary } from "./types";
import { buildCreateWorktreeCommand } from "./worktree-creation";
import {
inspectWorktreeGitSummary,
inspectWorktreeGitSummaryAsync,
Expand All @@ -68,6 +67,10 @@ import {
inspectParsedWorktree,
inspectParsedWorktreeAsync,
} from "./worktree-inspection";
import {
runCreateWorktreeWithStages,
type WorktreeSetupStageReporter,
} from "./worktree-setup";

export class GitServiceImpl {
private static readonly INSPECTION_CACHE_TTL = 2000;
Expand Down Expand Up @@ -184,34 +187,20 @@ export class GitServiceImpl {
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}): string {
const repositoryRoot = normalizePathId(options.repositoryRoot);
const worktreePath = path.resolve(options.worktreePath);
const branchName = options.branchName.trim();

if (!branchName) {
throw new Error("Worktree branch name must not be empty");
}

fs.mkdirSync(path.dirname(worktreePath), { recursive: true });

const args = buildCreateWorktreeCommand(this.runGit, {
repositoryRoot,
branchName,
worktreePath,
baseBranch: options.baseBranch,
});

const result = this.runGit(repositoryRoot, args);
if (result.error || result.status !== 0) {
throw new Error(
result.error?.message ||
result.stderr.trim() ||
`Failed to create worktree for branch ${branchName}`,
);
}

return normalizePathId(worktreePath);
// Staged setup lives in worktree-setup.ts: it reports real
// creation stages, keeps the checkout on failure, and reuses an
// already-registered worktree for the branch on retry (#12).
return runCreateWorktreeWithStages(
{
runGit: this.runGit,
ensureParentDirectory: (worktreePath) =>
fs.mkdirSync(path.dirname(worktreePath), { recursive: true }),
normalizePath: normalizePathId,
},
{ ...options, worktreePath: path.resolve(options.worktreePath) },
);
}

removeWorktree(options: {
Expand Down
9 changes: 9 additions & 0 deletions apps/desktop/src/main/git/git-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import type { Effect } from "effect";
import type { GitError } from "../effect/errors";
import { GitServiceImpl } from "./git-service-impl";
import type { GitRepositoryInspection } from "./types";
import type { WorktreeSetupStageReporter } from "./worktree-setup";

export type {
WorktreeSetupStageEvent,
WorktreeSetupStageId,
WorktreeSetupStageReporter,
WorktreeSetupStageStatus,
} from "./worktree-setup";

/**
* Public Git capability used by IPC, shell snapshot, and Effect Layers.
Expand All @@ -19,6 +27,7 @@ export type GitService = {
branchName: string;
worktreePath: string;
baseBranch?: string;
onStage?: WorktreeSetupStageReporter;
}): string;
removeWorktree(options: {
worktreePath: string;
Expand Down
Loading
Loading