diff --git a/apps/desktop/src/main/bootstrap/thread-context-actions.spec.ts b/apps/desktop/src/main/bootstrap/thread-context-actions.spec.ts index d67aca9..101ee4e 100644 --- a/apps/desktop/src/main/bootstrap/thread-context-actions.spec.ts +++ b/apps/desktop/src/main/bootstrap/thread-context-actions.spec.ts @@ -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) { @@ -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", @@ -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(); + 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", diff --git a/apps/desktop/src/main/bootstrap/thread-context-actions.ts b/apps/desktop/src/main/bootstrap/thread-context-actions.ts index f039a25..6730dbe 100644 --- a/apps/desktop/src/main/bootstrap/thread-context-actions.ts +++ b/apps/desktop/src/main/bootstrap/thread-context-actions.ts @@ -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, @@ -84,6 +88,7 @@ type CreateThreadContextActionsDependencies< branchName: string; worktreePath: string; baseBranch?: string; + onStage?: WorktreeSetupStageReporter; }): string; ensureThreadRuntime(spec: ThreadRuntimeLaunchSpec): Promise; restartThreadRuntime(spec: ThreadRuntimeLaunchSpec): Promise; @@ -149,7 +154,15 @@ export function createThreadContextActions< async function createWorktreeContext( repositoryId: string, branchName: string, + onStage?: WorktreeSetupStageReporter, ): Promise | 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}`); @@ -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: { diff --git a/apps/desktop/src/main/effect/services.ts b/apps/desktop/src/main/effect/services.ts index ba017c3..97d34fe 100644 --- a/apps/desktop/src/main/effect/services.ts +++ b/apps/desktop/src/main/effect/services.ts @@ -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, @@ -85,6 +88,7 @@ export interface GitServiceOps { branchName: string; worktreePath: string; baseBranch?: string; + onStage?: WorktreeSetupStageReporter; }) => Effect.Effect; readonly removeWorktree: (options: { worktreePath: string; @@ -150,6 +154,7 @@ export class GitServiceEffect extends Effect.Service()( branchName: string; worktreePath: string; baseBranch?: string; + onStage?: WorktreeSetupStageReporter; }) => Effect.fail(new GitError({ message: "not implemented" })), removeWorktree: (_options: { worktreePath: string; diff --git a/apps/desktop/src/main/git/git-service-impl.ts b/apps/desktop/src/main/git/git-service-impl.ts index ec39ccd..7937264 100644 --- a/apps/desktop/src/main/git/git-service-impl.ts +++ b/apps/desktop/src/main/git/git-service-impl.ts @@ -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, @@ -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; @@ -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: { diff --git a/apps/desktop/src/main/git/git-service.ts b/apps/desktop/src/main/git/git-service.ts index e2dfb0c..c9b04eb 100644 --- a/apps/desktop/src/main/git/git-service.ts +++ b/apps/desktop/src/main/git/git-service.ts @@ -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. @@ -19,6 +27,7 @@ export type GitService = { branchName: string; worktreePath: string; baseBranch?: string; + onStage?: WorktreeSetupStageReporter; }): string; removeWorktree(options: { worktreePath: string; diff --git a/apps/desktop/src/main/git/worktree-setup.integration.spec.ts b/apps/desktop/src/main/git/worktree-setup.integration.spec.ts new file mode 100644 index 0000000..68bb8e7 --- /dev/null +++ b/apps/desktop/src/main/git/worktree-setup.integration.spec.ts @@ -0,0 +1,131 @@ +import { execFileSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { GitServiceImpl } from "./git-service-impl"; +import type { WorktreeSetupStageEvent } from "./worktree-setup"; + +/** + * Real-git coverage for the staged worktree setup (issue #12): + * stages are reported, a retry after creation reuses the checkout + * instead of duplicating it, and a failed attempt leaves the + * existing checkout untouched. + */ + +function git(cwd: string, args: string[]): string { + return execFileSync("git", args, { cwd, encoding: "utf8" }); +} + +describe("GitServiceImpl createWorktree (real git)", () => { + let root: string; + let repositoryRoot: string; + let worktreePath: string; + const service = new GitServiceImpl(); + + beforeEach(() => { + root = mkdtempSync(path.join(os.tmpdir(), "pi-desktop-wt-setup-")); + repositoryRoot = path.join(root, "repo"); + worktreePath = path.join(root, "worktrees", "feature"); + mkdirSync(repositoryRoot, { recursive: true }); + git(repositoryRoot, ["init", "-b", "main"]); + git(repositoryRoot, ["config", "user.email", "test@example.com"]); + git(repositoryRoot, ["config", "user.name", "Test"]); + writeFileSync(path.join(repositoryRoot, "README.md"), "hello\n"); + git(repositoryRoot, ["add", "README.md"]); + git(repositoryRoot, ["commit", "-m", "init"]); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + function worktreeListPaths(): string[] { + return git(repositoryRoot, ["worktree", "list", "--porcelain"]) + .split("\n") + .filter((line) => line.startsWith("worktree ")) + .map((line) => line.replace("worktree ", "")); + } + + it("creates a worktree and reports the setup stages", () => { + const events: WorktreeSetupStageEvent[] = []; + + const created = service.createWorktree({ + repositoryRoot, + branchName: "feature", + worktreePath, + onStage: (event) => events.push(event), + }); + + expect(created).toBe(worktreePath); + expect(existsSync(path.join(worktreePath, "README.md"))).toBe(true); + expect( + git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"]).trim(), + ).toBe("feature"); + expect(events.map((event) => `${event.stage}:${event.status}`)).toEqual([ + "validate:started", + "validate:completed", + "prepare-directory:started", + "prepare-directory:completed", + "resolve-branch:started", + "resolve-branch:completed", + "create-worktree:started", + "create-worktree:completed", + "ready:completed", + ]); + }); + + it("retrying creation reuses the checkout and creates no duplicate", () => { + service.createWorktree({ + repositoryRoot, + branchName: "feature", + worktreePath, + }); + + const events: WorktreeSetupStageEvent[] = []; + const retried = service.createWorktree({ + repositoryRoot, + branchName: "feature", + worktreePath, + onStage: (event) => events.push(event), + }); + + expect(retried).toBe(worktreePath); + expect( + worktreeListPaths().filter((entry) => entry === worktreePath), + ).toHaveLength(1); + expect(events).toContainEqual({ + stage: "create-worktree", + status: "completed", + message: "Existing worktree reused", + }); + }); + + it("keeps the existing checkout when a conflicting retry fails", () => { + service.createWorktree({ + repositoryRoot, + branchName: "feature", + worktreePath, + }); + + expect(() => + service.createWorktree({ + repositoryRoot, + branchName: "other", + worktreePath, + }), + ).toThrow("already registered for branch feature"); + + expect(existsSync(path.join(worktreePath, "README.md"))).toBe(true); + expect( + git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"]).trim(), + ).toBe("feature"); + expect(worktreeListPaths()).toContain(worktreePath); + }); +}); diff --git a/apps/desktop/src/main/git/worktree-setup.spec.ts b/apps/desktop/src/main/git/worktree-setup.spec.ts new file mode 100644 index 0000000..096b179 --- /dev/null +++ b/apps/desktop/src/main/git/worktree-setup.spec.ts @@ -0,0 +1,210 @@ +import { describe, expect, it, vi } from "vitest"; +import type { GitCommandResult, RunGit } from "./git-command-runner"; +import { + runCreateWorktreeWithStages, + type WorktreeSetupStageEvent, +} from "./worktree-setup"; + +function result(overrides: Partial = {}): GitCommandResult { + return { status: 0, stdout: "", stderr: "", error: null, ...overrides }; +} + +const MAIN_LIST = [ + "worktree /repo/main", + "HEAD abc123", + "branch refs/heads/main", + "", +].join("\n"); + +function createHarness(runGit: RunGit, events: WorktreeSetupStageEvent[] = []) { + const ensureParentDirectory = vi.fn(); + return { + events, + ensureParentDirectory, + deps: { + runGit, + ensureParentDirectory, + normalizePath: (p: string) => p, + }, + options: { + repositoryRoot: "/repo/main", + branchName: "feature", + worktreePath: "/repo/worktrees/feature", + onStage: (event: WorktreeSetupStageEvent) => events.push(event), + }, + }; +} + +describe("runCreateWorktreeWithStages", () => { + it("reports each stage in order for a fresh worktree", () => { + const calls: string[] = []; + const runGit: RunGit = (_cwd, args) => { + calls.push(args.join(" ")); + if (args[0] === "worktree" && args[1] === "list") { + return result({ stdout: MAIN_LIST }); + } + if (args[0] === "worktree" && args[1] === "add") { + return result(); + } + // Branch does not exist yet; create it from HEAD. + return result({ status: 1 }); + }; + const harness = createHarness(runGit); + + expect(runCreateWorktreeWithStages(harness.deps, harness.options)).toBe( + "/repo/worktrees/feature", + ); + + expect(harness.ensureParentDirectory).toHaveBeenCalledWith( + "/repo/worktrees/feature", + ); + expect(calls).toContain("worktree add -b feature /repo/worktrees/feature"); + expect(harness.events).toEqual([ + { stage: "validate", status: "started" }, + { stage: "validate", status: "completed" }, + { stage: "prepare-directory", status: "started" }, + { stage: "prepare-directory", status: "completed" }, + { stage: "resolve-branch", status: "started" }, + { stage: "resolve-branch", status: "completed" }, + { stage: "create-worktree", status: "started" }, + { stage: "create-worktree", status: "completed" }, + { stage: "ready", status: "completed" }, + ]); + }); + + it("reuses an existing worktree for the same branch without a duplicate add", () => { + const calls: string[] = []; + const list = [ + MAIN_LIST.trimEnd(), + "", + "worktree /repo/worktrees/feature", + "HEAD def456", + "branch refs/heads/feature", + "", + ].join("\n"); + const runGit: RunGit = (_cwd, args) => { + calls.push(args.join(" ")); + if (args[0] === "worktree" && args[1] === "list") { + return result({ stdout: list }); + } + return result(); + }; + const harness = createHarness(runGit); + + expect(runCreateWorktreeWithStages(harness.deps, harness.options)).toBe( + "/repo/worktrees/feature", + ); + + expect(calls.some((call) => call.startsWith("worktree add"))).toBe(false); + expect(harness.events).toContainEqual({ + stage: "create-worktree", + status: "completed", + message: "Existing worktree reused", + }); + expect(harness.events.at(-1)).toEqual({ + stage: "ready", + status: "completed", + }); + }); + + it("refuses to reuse a checkout registered for a different branch and keeps it", () => { + const calls: string[] = []; + const list = [ + MAIN_LIST.trimEnd(), + "", + "worktree /repo/worktrees/feature", + "HEAD def456", + "branch refs/heads/other", + "", + ].join("\n"); + const runGit: RunGit = (_cwd, args) => { + calls.push(args.join(" ")); + if (args[0] === "worktree" && args[1] === "list") { + return result({ stdout: list }); + } + return result(); + }; + const harness = createHarness(runGit); + + expect(() => + runCreateWorktreeWithStages(harness.deps, harness.options), + ).toThrow("already registered for branch other"); + + expect(calls.some((call) => call.startsWith("worktree add"))).toBe(false); + expect(calls.some((call) => call.startsWith("worktree remove"))).toBe( + false, + ); + expect(harness.events.at(-1)).toEqual({ + stage: "create-worktree", + status: "failed", + message: "Worktree path is already registered for branch other", + }); + }); + + it("fails at the create-worktree stage without issuing any removal when git add fails", () => { + const calls: string[] = []; + const runGit: RunGit = (_cwd, args) => { + calls.push(args.join(" ")); + if (args[0] === "worktree" && args[1] === "list") { + return result({ stdout: MAIN_LIST }); + } + if (args[0] === "worktree" && args[1] === "add") { + return result({ status: 1, stderr: "fatal: cannot lock ref" }); + } + return result({ status: 1 }); + }; + const harness = createHarness(runGit); + + expect(() => + runCreateWorktreeWithStages(harness.deps, harness.options), + ).toThrow("fatal: cannot lock ref"); + + expect(calls.some((call) => call.startsWith("worktree remove"))).toBe( + false, + ); + expect(harness.events.at(-1)).toEqual({ + stage: "create-worktree", + status: "failed", + message: "fatal: cannot lock ref", + }); + }); + + it("fails validation for an empty branch before touching git", () => { + const runGit = vi.fn(() => result()); + const harness = createHarness(runGit as unknown as RunGit); + + expect(() => + runCreateWorktreeWithStages(harness.deps, { + ...harness.options, + branchName: " ", + }), + ).toThrow("Worktree branch name must not be empty"); + + expect(runGit).not.toHaveBeenCalled(); + expect(harness.events.at(-1)?.stage).toBe("validate"); + expect(harness.events.at(-1)?.status).toBe("failed"); + }); + + it("fails at resolve-branch when the requested base branch is missing", () => { + const runGit: RunGit = (_cwd, args) => { + if (args[0] === "worktree" && args[1] === "list") { + return result({ stdout: MAIN_LIST }); + } + return result({ status: 1 }); + }; + const harness = createHarness(runGit); + + expect(() => + runCreateWorktreeWithStages(harness.deps, { + ...harness.options, + baseBranch: "missing-base", + }), + ).toThrow("Requested base branch does not exist: missing-base"); + + expect(harness.events.at(-1)).toEqual({ + stage: "resolve-branch", + status: "failed", + message: "Requested base branch does not exist: missing-base", + }); + }); +}); diff --git a/apps/desktop/src/main/git/worktree-setup.ts b/apps/desktop/src/main/git/worktree-setup.ts new file mode 100644 index 0000000..744f01c --- /dev/null +++ b/apps/desktop/src/main/git/worktree-setup.ts @@ -0,0 +1,172 @@ +import type { RunGit } from "./git-command-runner"; +import { normalizePathId } from "./path-utils"; +import { + type ParsedWorktree, + parseBranchName, + parseWorktreeBlocks, +} from "./status-parsers"; +import { buildCreateWorktreeCommand } from "./worktree-creation"; + +/** + * Staged worktree setup (issue #12). + * + * Creation runs as an explicit sequence of stages so callers can show + * real progress and, on failure, know exactly where setup stopped. + * Two guarantees hold across stages: + * + * - Keep the checkout: a failed stage never deletes a worktree that + * git created (or that already existed). Partial progress stays on + * disk so the user can inspect or repair it. + * - Retry is idempotent: if the target path is already a registered + * worktree for the requested branch, setup reuses it and returns + * success instead of asking git to create a duplicate. + * + * The `ready` stage means the checkout itself is ready; controllers + * may follow it with their own `open-worktree` stage when they open + * the checkout (thread creation, runtime attach, ...). + */ + +export type WorktreeSetupStageId = + | "validate" + | "prepare-directory" + | "resolve-branch" + | "create-worktree" + | "open-worktree" + | "ready"; + +export type WorktreeSetupStageStatus = "started" | "completed" | "failed"; + +export interface WorktreeSetupStageEvent { + stage: WorktreeSetupStageId; + status: WorktreeSetupStageStatus; + message?: string; +} + +export type WorktreeSetupStageReporter = ( + event: WorktreeSetupStageEvent, +) => void; + +export interface CreateWorktreeWithStagesOptions { + repositoryRoot: string; + branchName: string; + worktreePath: string; + baseBranch?: string; + onStage?: WorktreeSetupStageReporter; +} + +export interface WorktreeSetupDependencies { + runGit: RunGit; + /** Create the worktree's parent directory (recursive). */ + ensureParentDirectory(worktreePath: string): void; + /** Normalize a filesystem path the same way the git layer does. */ + normalizePath(worktreePath: string): string; +} + +export function findRegisteredWorktree( + worktrees: ParsedWorktree[], + worktreePath: string, +): ParsedWorktree | undefined { + const target = normalizePathId(worktreePath); + return worktrees.find( + (worktree) => normalizePathId(worktree.path) === target, + ); +} + +export function listRegisteredWorktrees( + runGit: RunGit, + repositoryRoot: string, +): ParsedWorktree[] { + const result = runGit(repositoryRoot, ["worktree", "list", "--porcelain"]); + if (result.error || result.status !== 0) { + return []; + } + return parseWorktreeBlocks(result.stdout); +} + +export function runCreateWorktreeWithStages( + deps: WorktreeSetupDependencies, + options: CreateWorktreeWithStagesOptions, +): string { + const report = (event: WorktreeSetupStageEvent) => { + try { + options.onStage?.(event); + } catch { + // A broken progress reporter must never fail the setup itself. + } + }; + + let stage: WorktreeSetupStageId = "validate"; + try { + report({ stage, status: "started" }); + const repositoryRoot = deps.normalizePath(options.repositoryRoot); + const worktreePath = options.worktreePath; + const branchName = options.branchName.trim(); + if (!branchName) { + throw new Error("Worktree branch name must not be empty"); + } + report({ stage, status: "completed" }); + + stage = "prepare-directory"; + report({ stage, status: "started" }); + deps.ensureParentDirectory(worktreePath); + report({ stage, status: "completed" }); + + stage = "create-worktree"; + const existing = findRegisteredWorktree( + listRegisteredWorktrees(deps.runGit, repositoryRoot), + worktreePath, + ); + if (existing) { + report({ stage, status: "started" }); + const existingBranch = parseBranchName(existing.branchRef); + if (existingBranch !== branchName) { + throw new Error( + existingBranch + ? `Worktree path is already registered for branch ${existingBranch}` + : "Worktree path is already registered for a detached HEAD", + ); + } + report({ + stage, + status: "completed", + message: "Existing worktree reused", + }); + report({ stage: "ready", status: "completed" }); + return deps.normalizePath(worktreePath); + } + + stage = "resolve-branch"; + report({ stage, status: "started" }); + const args = buildCreateWorktreeCommand(deps.runGit, { + repositoryRoot, + branchName, + worktreePath, + baseBranch: options.baseBranch, + }); + report({ stage, status: "completed" }); + + stage = "create-worktree"; + report({ stage, status: "started" }); + const result = deps.runGit(repositoryRoot, args); + if (result.error || result.status !== 0) { + // Deliberately no cleanup: git may have partially created the + // checkout, and keeping it lets a retry reuse or repair it. + throw new Error( + result.error?.message || + result.stderr.trim() || + `Failed to create worktree for branch ${branchName}`, + ); + } + report({ stage, status: "completed" }); + + report({ stage: "ready", status: "completed" }); + return deps.normalizePath(worktreePath); + } catch (error) { + report({ + stage, + status: "failed", + message: error instanceof Error ? error.message : String(error), + }); + throw error; + } +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx index 87b5961..9192d41 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx @@ -237,6 +237,14 @@ describe("ChatThreadPanel", () => { fireEvent.click(screen.getByTestId("message-edit")); expect(screen.getByTestId("message-inline-editor")).toBeInTheDocument(); + // "Edit and send again" semantics are spelled out in the editor: + // the edited text goes as a new message, the original stays. + expect( + screen.getByText(/sends the edited text as a new message/), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Edit and send again" }), + ).toBeInTheDocument(); const textarea = screen .getByTestId("message-inline-editor") diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript-turn.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript-turn.tsx index ce6ee0d..4760a4f 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript-turn.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript-turn.tsx @@ -6,6 +6,7 @@ import { SystemMessage } from "@/components/ui/system-message"; import { Tool, type ToolPart } from "@/components/ui/tool"; import type { ChatThreadTurn } from "./chat/chat-thread-turns"; import { FileChangeSummary } from "./chat/file-change-summary"; +import { summarizeFileChanges } from "./chat/file-changes"; import { InlineMessageEditor, MessageActions } from "./chat/message-actions"; import { MessageTimestamp } from "./chat/message-timestamp"; import { TokenCount } from "./chat/token-count"; @@ -35,30 +36,8 @@ export interface ChatThreadTranscriptTurnProps { onResubmitUserMessage?: (messageId: string, nextText: string) => void; } -const FILE_MUTATION_PREFIXES = ["write", "edit", "create", "delete"]; - type ToolState = "input-streaming" | "output-available" | "output-error"; -function isFileMutationTool(toolMsg: AgentMessageSnapshot): boolean { - const match = /^tool:([^:]+):/.exec(toolMsg.id); - const name = (match?.[1] ?? "").toLowerCase(); - if (!name) return false; - if (FILE_MUTATION_PREFIXES.some((prefix) => name.startsWith(prefix))) { - return true; - } - return name.includes("file"); -} - -function extractFilePath(toolMsg: AgentMessageSnapshot): string | null { - const rest = toolMsg.id.split(":").slice(2).join(":"); - if (!rest) return null; - - const pathMatch = rest.match(/([\w./\-@]+\.[a-zA-Z0-9]+)/); - if (pathMatch?.[1]) return pathMatch[1]; - - return null; -} - function getToolState(message: AgentMessageSnapshot): ToolState { switch (message.status) { case "error": @@ -268,14 +247,9 @@ export const ChatThreadTranscriptTurn = React.memo( (message) => message.role === "tool", ); const useToolRollup = toolMessages.length > 3; - const mutationTools = toolMessages.filter(isFileMutationTool); - const filePaths = Array.from( - new Set( - mutationTools - .map(extractFilePath) - .filter((path): path is string => path !== null), - ), - ); + // Unique successful file changes only: failed writes never count + // and repeated writes to one file are reported once (issue #12). + const fileChangeSummary = summarizeFileChanges(toolMessages); let runningIndex = 0; let toolRollupRendered = false; @@ -372,13 +346,10 @@ export const ChatThreadTranscriptTurn = React.memo( return renderMessage(message); })} - {mutationTools.length > 0 && + {fileChangeSummary.count > 0 && !turn.isStreaming && turn.lastAssistantTimestamp !== null ? ( - + ) : null} ); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.spec.tsx new file mode 100644 index 0000000..8f3b6de --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.spec.tsx @@ -0,0 +1,41 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import { FileChangeSummary } from "./file-change-summary"; + +afterEach(() => { + cleanup(); +}); + +describe("FileChangeSummary", () => { + it("reports unique files even when paths repeat", () => { + render( + , + ); + + expect(screen.getByText("2 files changed")).toBeInTheDocument(); + }); + + it("uses the singular label for one unique file", () => { + render(); + + expect(screen.getByText("1 file changed")).toBeInTheDocument(); + }); + + it("expands to list each unique path once", () => { + render(); + + fireEvent.click(screen.getByRole("button", { name: /1 file changed/ })); + + expect(screen.getAllByText("src/a.ts")).toHaveLength(1); + }); + + it("renders a disabled zero summary when nothing changed", () => { + render(); + + const button = screen.getByRole("button", { name: /0 files changed/ }); + expect(button).toBeDisabled(); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.tsx index ce55778..52ead34 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-change-summary.tsx @@ -3,16 +3,19 @@ import { cn } from "@pi-desktop/ui"; import * as React from "react"; export interface FileChangeSummaryProps { + /** Unique paths of files changed by successful tool calls. */ filePaths: string[]; - count: number; } -export function FileChangeSummary({ - filePaths, - count, -}: FileChangeSummaryProps) { +export function FileChangeSummary({ filePaths }: FileChangeSummaryProps) { const [expanded, setExpanded] = React.useState(false); - const hasPaths = filePaths.length > 0; + // Report unique files only: duplicate paths never inflate the count. + const uniquePaths = React.useMemo( + () => Array.from(new Set(filePaths)), + [filePaths], + ); + const count = uniquePaths.length; + const hasPaths = uniquePaths.length > 0; return (
@@ -36,9 +39,9 @@ export function FileChangeSummary({ {expanded && hasPaths && (
    - {filePaths.map((path, i) => ( + {uniquePaths.map((path) => (
  • {path} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.spec.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.spec.ts new file mode 100644 index 0000000..b2b7889 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.spec.ts @@ -0,0 +1,157 @@ +import type { AgentMessageSnapshot } from "@pi-desktop/shared"; +import { describe, expect, it } from "vitest"; +import { + extractToolFilePath, + isFileMutationToolMessage, + summarizeFileChanges, +} from "./file-changes"; + +function toolMessage( + overrides: Partial, +): AgentMessageSnapshot { + return { + id: "tool:write:call-1", + role: "tool", + text: "", + status: "complete", + timestamp: 1, + ...overrides, + }; +} + +describe("isFileMutationToolMessage", () => { + it("matches write/edit/create/delete and file tools", () => { + expect( + isFileMutationToolMessage(toolMessage({ id: "tool:write:c1" })), + ).toBe(true); + expect( + isFileMutationToolMessage(toolMessage({ id: "tool:edit_file:c1" })), + ).toBe(true); + expect( + isFileMutationToolMessage(toolMessage({ id: "tool:create:c1" })), + ).toBe(true); + expect(isFileMutationToolMessage(toolMessage({ id: "tool:read:c1" }))).toBe( + false, + ); + expect( + isFileMutationToolMessage( + toolMessage({ id: "tool:bash:c1", role: "assistant" }), + ), + ).toBe(false); + }); +}); + +describe("extractToolFilePath", () => { + it("reads the path from JSON tool arguments", () => { + expect( + extractToolFilePath( + toolMessage({ text: JSON.stringify({ path: "src/app.ts" }) }), + ), + ).toBe("src/app.ts"); + expect( + extractToolFilePath( + toolMessage({ text: JSON.stringify({ filePath: "docs/a.md" }) }), + ), + ).toBe("docs/a.md"); + }); + + it("falls back to a path-like token in the tool-call id", () => { + expect( + extractToolFilePath(toolMessage({ id: "tool:write:src/legacy.ts" })), + ).toBe("src/legacy.ts"); + }); + + it("returns null when no path is present", () => { + expect( + extractToolFilePath(toolMessage({ id: "tool:write:call-9", text: "ok" })), + ).toBeNull(); + }); +}); + +describe("summarizeFileChanges", () => { + it("counts each successfully changed file once, in first-change order", () => { + const summary = summarizeFileChanges([ + toolMessage({ + id: "tool:write:c1", + text: JSON.stringify({ path: "src/a.ts" }), + }), + toolMessage({ + id: "tool:edit:c2", + text: JSON.stringify({ path: "src/b.ts" }), + }), + toolMessage({ + id: "tool:edit:c3", + text: JSON.stringify({ path: "src/a.ts" }), + }), + toolMessage({ + id: "tool:write:c4", + text: JSON.stringify({ path: "src/a.ts" }), + }), + ]); + + expect(summary).toEqual({ + filePaths: ["src/a.ts", "src/b.ts"], + count: 2, + }); + }); + + it("excludes failed writes entirely", () => { + const summary = summarizeFileChanges([ + toolMessage({ + id: "tool:write:c1", + status: "error", + text: JSON.stringify({ path: "src/failed.ts" }), + }), + toolMessage({ + id: "tool:write:c2", + text: JSON.stringify({ path: "src/ok.ts" }), + }), + ]); + + expect(summary).toEqual({ filePaths: ["src/ok.ts"], count: 1 }); + }); + + it("does not let a later failure erase an earlier success for the same file", () => { + const summary = summarizeFileChanges([ + toolMessage({ + id: "tool:write:c1", + text: JSON.stringify({ path: "src/a.ts" }), + }), + toolMessage({ + id: "tool:edit:c2", + status: "error", + text: JSON.stringify({ path: "src/a.ts" }), + }), + ]); + + expect(summary).toEqual({ filePaths: ["src/a.ts"], count: 1 }); + }); + + it("excludes streaming (not yet successful) and non-mutation tools", () => { + const summary = summarizeFileChanges([ + toolMessage({ + id: "tool:write:c1", + status: "streaming", + text: JSON.stringify({ path: "src/pending.ts" }), + }), + toolMessage({ + id: "tool:read:c2", + text: JSON.stringify({ path: "src/read-only.ts" }), + }), + toolMessage({ + id: "tool:bash:c3", + text: JSON.stringify({ path: "src/not-a-file-tool.ts" }), + }), + ]); + + expect(summary).toEqual({ filePaths: [], count: 0 }); + }); + + it("ignores successful mutation calls without an identifiable path", () => { + const summary = summarizeFileChanges([ + toolMessage({ id: "tool:write:c1", text: "done" }), + ]); + + expect(summary).toEqual({ filePaths: [], count: 0 }); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.ts new file mode 100644 index 0000000..8818845 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/file-changes.ts @@ -0,0 +1,94 @@ +import type { AgentMessageSnapshot } from "@pi-desktop/shared"; + +/** + * Change reporting for a chat turn (issue #12). + * + * Only *successful* file-mutation tool calls count as file changes: + * a tool message whose status is "error" (failed write/edit) or + * "streaming" (still running) never counts, and a file written by + * several successful calls is reported once, in first-change order. + */ + +const FILE_MUTATION_PREFIXES = ["write", "edit", "create", "delete"]; + +export function getToolName(message: AgentMessageSnapshot): string | null { + const match = /^tool:([^:]+):/.exec(message.id); + return match?.[1] ?? null; +} + +export function isFileMutationToolMessage( + message: AgentMessageSnapshot, +): boolean { + if (message.role !== "tool") return false; + const name = (getToolName(message) ?? "").toLowerCase(); + if (!name) return false; + if (FILE_MUTATION_PREFIXES.some((prefix) => name.startsWith(prefix))) { + return true; + } + return name.includes("file"); +} + +/** + * Best-effort file path for a tool call. Pi tool arguments/results are + * carried in the message text (JSON with a `path`/`filePath` field for + * the built-in write/edit tools); fall back to a path-like token in the + * tool-call id segment for ids that embed one. + */ +export function extractToolFilePath( + message: AgentMessageSnapshot, +): string | null { + const fromText = extractPathFromToolText(message.text); + if (fromText) return fromText; + + const rest = message.id.split(":").slice(2).join(":"); + if (!rest) return null; + + const pathMatch = rest.match(/([\w./\-@]+\.[a-zA-Z0-9]+)/); + return pathMatch?.[1] ?? null; +} + +function extractPathFromToolText(text: string): string | null { + const trimmed = text.trim(); + if (!trimmed.startsWith("{")) return null; + + try { + const parsed: unknown = JSON.parse(trimmed); + if (typeof parsed !== "object" || parsed === null) return null; + const record = parsed as Record; + for (const key of ["path", "filePath"]) { + const value = record[key]; + if (typeof value === "string" && value.length > 0) return value; + } + } catch { + return null; + } + + return null; +} + +export interface FileChangeSummaryData { + /** Unique paths of files changed by successful tool calls. */ + filePaths: string[]; + /** Always `filePaths.length` — unique successful changes only. */ + count: number; +} + +export function summarizeFileChanges( + messages: AgentMessageSnapshot[], +): FileChangeSummaryData { + const seen = new Set(); + const filePaths: string[] = []; + + for (const message of messages) { + if (message.status !== "complete") continue; + if (!isFileMutationToolMessage(message)) continue; + + const filePath = extractToolFilePath(message); + if (!filePath || seen.has(filePath)) continue; + + seen.add(filePath); + filePaths.push(filePath); + } + + return { filePaths, count: filePaths.length }; +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/message-actions.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat/message-actions.tsx index 5e37930..358c4d6 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat/message-actions.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/message-actions.tsx @@ -106,7 +106,8 @@ export function MessageActions({ Edit @@ -137,6 +138,10 @@ export interface InlineMessageEditorProps { /** * Inline editor for a user message. Submits with Cmd/Ctrl+Enter, cancels * on Escape. Stays DOM-local so it plays nicely with virtualization. + * + * Semantics ("Edit and send again"): submitting sends the edited text + * as a brand-new prompt. It does not rewrite history — the original + * message and everything after it stay in the conversation. */ export function InlineMessageEditor({ initialText, @@ -194,6 +199,10 @@ export function InlineMessageEditor({ "placeholder:text-white/50 focus:outline-none", )} /> +

    + Edit and send again sends the edited text as a new message. The original + message stays in the conversation. +

    @@ -205,7 +214,7 @@ export function InlineMessageEditor({ disabled={value.trim().length === 0} > - Resubmit + Edit and send again
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-line.tsx b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-line.tsx new file mode 100644 index 0000000..9d0d511 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-line.tsx @@ -0,0 +1,136 @@ +import type { GitDiffLine } from "@pi-desktop/shared"; +import { cn } from "@pi-desktop/ui"; +import { computeCharDiff } from "./compute-char-diff"; + +function IntraLineSpan({ + text, + highlightStart, + highlight, + highlightClass, + defaultClass, +}: { + text: string; + highlightStart: number; + highlight: string; + highlightClass: string; + defaultClass: string; +}) { + if (!highlight) return {text}; + return ( + <> + {highlightStart > 0 && ( + {text.slice(0, highlightStart)} + )} + {highlight} + {highlightStart + highlight.length < text.length && ( + + {text.slice(highlightStart + highlight.length)} + + )} + + ); +} + +export interface DiffLineProps { + line: GitDiffLine; + pairedLine: GitDiffLine | null; + /** When true the row can be clicked to (de)select it for a question. */ + selectable?: boolean; + selected?: boolean; + onToggleSelect?: (line: GitDiffLine) => void; +} + +export function DiffLine({ + line, + pairedLine, + selectable = false, + selected = false, + onToggleSelect, +}: DiffLineProps) { + if (line.type === "hunk_header") { + return ( +
+ + + + {line.content} +
+ ); + } + + const isAdd = line.type === "add"; + const isRemove = line.type === "remove"; + const bgClass = isAdd ? "bg-emerald-500/10" : isRemove ? "bg-red-500/10" : ""; + const textClass = isAdd + ? "text-emerald-400" + : isRemove + ? "text-red-400" + : "text-white/50"; + const prefix = isAdd ? "+" : isRemove ? "-" : " "; + const lineNumber = isRemove + ? line.oldLineNumber + : isAdd + ? line.newLineNumber + : line.newLineNumber; + const emptyLineNum = isRemove ? "" : isAdd ? "" : line.oldLineNumber; + + const charDiff = + pairedLine && (isAdd || isRemove) + ? computeCharDiff( + isRemove ? line.content : pairedLine.content, + isAdd ? line.content : pairedLine.content, + ) + : null; + const middle = isRemove ? charDiff?.oldMiddle : charDiff?.newMiddle; + const middleStart = charDiff ? charDiff.prefix.length : 0; + + return ( +
onToggleSelect?.(line), + onKeyDown: (event: React.KeyboardEvent) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onToggleSelect?.(line); + } + }, + } + : {})} + > + + {isRemove ? lineNumber : emptyLineNum} + + + {isAdd ? lineNumber : emptyLineNum} + + + {prefix} + + + {charDiff && middle ? ( + + ) : ( + {line.content} + )} + +
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.spec.ts b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.spec.ts new file mode 100644 index 0000000..98db651 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.spec.ts @@ -0,0 +1,161 @@ +import type { GitDiffLine, GitFileDiff } from "@pi-desktop/shared"; +import { describe, expect, it } from "vitest"; +import { + coordinateForDiffLine, + type DiffLineCoordinate, + formatDiffSelectionQuestion, + isDiffLineSelected, + toggleDiffLineSelection, +} from "./git-diff-selection"; + +function mustCoordinate(lineValue: GitDiffLine): DiffLineCoordinate { + const coordinate = coordinateForDiffLine(lineValue); + if (!coordinate) throw new Error("expected a selectable diff line"); + return coordinate; +} + +function line(overrides: Partial): GitDiffLine { + return { + type: "context", + content: "code", + oldLineNumber: 1, + newLineNumber: 1, + ...overrides, + }; +} + +const diff: GitFileDiff = { + filePath: "src/app.ts", + oldFilePath: null, + status: "modified", + binary: false, + hunks: [], +}; + +describe("coordinateForDiffLine", () => { + it("keeps removed lines on the old side with both coordinates", () => { + expect( + coordinateForDiffLine( + line({ type: "remove", oldLineNumber: 12, newLineNumber: null }), + ), + ).toEqual({ + side: "old", + oldLineNumber: 12, + newLineNumber: null, + type: "remove", + content: "code", + }); + }); + + it("keeps added lines on the new side with both coordinates", () => { + expect( + coordinateForDiffLine( + line({ type: "add", oldLineNumber: null, newLineNumber: 30 }), + ), + ).toEqual({ + side: "new", + oldLineNumber: null, + newLineNumber: 30, + type: "add", + content: "code", + }); + }); + + it("retains both line numbers for context lines", () => { + expect( + coordinateForDiffLine( + line({ type: "context", oldLineNumber: 4, newLineNumber: 9 }), + ), + ).toEqual({ + side: "new", + oldLineNumber: 4, + newLineNumber: 9, + type: "context", + content: "code", + }); + }); + + it("returns null for hunk headers", () => { + expect(coordinateForDiffLine(line({ type: "hunk_header" }))).toBeNull(); + }); +}); + +describe("toggleDiffLineSelection", () => { + it("adds, sorts, and removes coordinates by side and line number", () => { + const add = line({ type: "add", oldLineNumber: null, newLineNumber: 30 }); + const remove = line({ + type: "remove", + oldLineNumber: 12, + newLineNumber: null, + }); + + let selection = toggleDiffLineSelection([], add); + selection = toggleDiffLineSelection(selection, remove); + + expect(selection.map((entry) => entry.side)).toEqual(["old", "new"]); + expect(isDiffLineSelected(selection, add)).toBe(true); + expect(isDiffLineSelected(selection, remove)).toBe(true); + + selection = toggleDiffLineSelection(selection, add); + expect(selection).toHaveLength(1); + expect(isDiffLineSelected(selection, add)).toBe(false); + }); + + it("ignores hunk headers", () => { + expect(toggleDiffLineSelection([], line({ type: "hunk_header" }))).toEqual( + [], + ); + }); +}); + +describe("formatDiffSelectionQuestion", () => { + it("quotes selected lines with old and new coordinates", () => { + const selection = [ + mustCoordinate( + line({ + type: "remove", + content: "oldCall()", + oldLineNumber: 12, + newLineNumber: null, + }), + ), + mustCoordinate( + line({ + type: "add", + content: "newCall()", + oldLineNumber: null, + newLineNumber: 12, + }), + ), + ]; + + const question = formatDiffSelectionQuestion( + diff, + selection, + "Why did this call change?", + ); + + expect(question).toContain("src/app.ts"); + expect(question).toContain("old line 12 / new line — (old side)"); + expect(question).toContain("- oldCall()"); + expect(question).toContain("old line — / new line 12 (new side)"); + expect(question).toContain("+ newCall()"); + expect(question).toContain("Why did this call change?"); + }); + + it("omits the trailing question when none is supplied", () => { + const selection = [ + mustCoordinate( + line({ type: "context", oldLineNumber: 3, newLineNumber: 5 }), + ), + ]; + + const question = formatDiffSelectionQuestion(diff, selection); + + expect(question).toContain( + "Question about a selected diff line in src/app.ts:", + ); + expect(question).toContain("old line 3 / new line 5 (new side)"); + expect(question.endsWith("code")).toBe(true); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.ts b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.ts new file mode 100644 index 0000000..e77c01b --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-selection.ts @@ -0,0 +1,183 @@ +import type { GitDiffLine, GitFileDiff } from "@pi-desktop/shared"; + +/** + * Selected-diff-line questions (issue #12). + * + * A selection is a list of line coordinates. Every coordinate retains + * BOTH the old-side and the new-side line number (either may be null + * for added/removed lines) plus the side the user picked the line + * from, so a question built from the selection can be answered + * against either revision of the file. + */ + +export type DiffLineSide = "old" | "new"; + +export interface DiffLineCoordinate { + side: DiffLineSide; + oldLineNumber: number | null; + newLineNumber: number | null; + type: GitDiffLine["type"]; + content: string; +} + +export function coordinateForDiffLine( + line: GitDiffLine, +): DiffLineCoordinate | null { + switch (line.type) { + case "remove": + return { + side: "old", + oldLineNumber: line.oldLineNumber, + newLineNumber: line.newLineNumber, + type: line.type, + content: line.content, + }; + case "add": + case "context": + return { + side: "new", + oldLineNumber: line.oldLineNumber, + newLineNumber: line.newLineNumber, + type: line.type, + content: line.content, + }; + default: + return null; + } +} + +export function diffLineSelectionKey(coordinate: DiffLineCoordinate): string { + const lineNumber = + coordinate.side === "old" + ? coordinate.oldLineNumber + : coordinate.newLineNumber; + return `${coordinate.side}:${lineNumber ?? "?"}`; +} + +export function isDiffLineSelected( + selection: DiffLineCoordinate[], + line: GitDiffLine, +): boolean { + const coordinate = coordinateForDiffLine(line); + if (!coordinate) return false; + const key = diffLineSelectionKey(coordinate); + return selection.some((entry) => diffLineSelectionKey(entry) === key); +} + +export function toggleDiffLineSelection( + selection: DiffLineCoordinate[], + line: GitDiffLine, +): DiffLineCoordinate[] { + const coordinate = coordinateForDiffLine(line); + if (!coordinate) return selection; + + const key = diffLineSelectionKey(coordinate); + if (selection.some((entry) => diffLineSelectionKey(entry) === key)) { + return selection.filter((entry) => diffLineSelectionKey(entry) !== key); + } + + return [...selection, coordinate].sort(compareCoordinates); +} + +function compareCoordinates( + left: DiffLineCoordinate, + right: DiffLineCoordinate, +): number { + const leftLine = left.newLineNumber ?? left.oldLineNumber ?? 0; + const rightLine = right.newLineNumber ?? right.oldLineNumber ?? 0; + if (leftLine !== rightLine) return leftLine - rightLine; + if (left.side === right.side) return 0; + return left.side === "old" ? -1 : 1; +} + +function formatCoordinateLabel(coordinate: DiffLineCoordinate): string { + const oldLabel = + coordinate.oldLineNumber === null ? "—" : `${coordinate.oldLineNumber}`; + const newLabel = + coordinate.newLineNumber === null ? "—" : `${coordinate.newLineNumber}`; + return `old line ${oldLabel} / new line ${newLabel} (${coordinate.side} side)`; +} + +function formatCoordinatePrefix(coordinate: DiffLineCoordinate): string { + switch (coordinate.type) { + case "add": + return "+ "; + case "remove": + return "- "; + default: + return " "; + } +} + +/** + * Build the question prompt for the selected diff lines. The selected + * lines are quoted with their old/new coordinates so the agent can + * locate them in either revision; the user question is appended when + * one is supplied. + */ +export function formatDiffSelectionQuestion( + diff: GitFileDiff, + selection: DiffLineCoordinate[], + question?: string, +): string { + const sorted = [...selection].sort(compareCoordinates); + const lines = sorted.map( + (coordinate) => + `- [${formatCoordinateLabel(coordinate)}] ${formatCoordinatePrefix(coordinate)}${coordinate.content}`, + ); + const header = + selection.length === 1 + ? `Question about a selected diff line in ${diff.filePath}:` + : `Question about ${selection.length} selected diff lines in ${diff.filePath}:`; + const body = [header, ...lines].join("\n"); + const trimmedQuestion = question?.trim(); + return trimmedQuestion ? `${body}\n\n${trimmedQuestion}` : body; +} + +export function pairRemoveAddLines( + lines: GitDiffLine[], +): Map { + const paired = new Map(); + let lastRemoveIndex: number | null = null; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (!line) continue; + if (line.type === "remove") { + lastRemoveIndex = i; + } else if (line.type === "add" && lastRemoveIndex !== null) { + const removeLine = lines[lastRemoveIndex]; + if (removeLine) { + paired.set(lastRemoveIndex, line); + paired.set(i, removeLine); + } + lastRemoveIndex = null; + } else if (line.type === "context" || line.type === "hunk_header") { + lastRemoveIndex = null; + } + } + + return paired; +} + +/** + * Re-serialize a diff to a unified-ish text form suitable for clipboard copy. + * Not a strict git-format emitter; preserves +/- prefix and context space. + */ +export function serializeDiffForClipboard(diff: GitFileDiff): string { + const header = `--- a/${diff.oldFilePath ?? diff.filePath}\n+++ b/${diff.filePath}`; + const body = diff.hunks + .map((hunk) => { + const hunkHeader = `@@ -${hunk.oldStart},${hunk.oldCount} +${hunk.newStart},${hunk.newCount} @@`; + const lines = hunk.lines + .map((line) => { + const prefix = + line.type === "add" ? "+" : line.type === "remove" ? "-" : " "; + return `${prefix}${line.content}`; + }) + .join("\n"); + return `${hunkHeader}\n${lines}`; + }) + .join("\n"); + return `${header}\n${body}`; +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.spec.tsx index e495fed..a1ccef4 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.spec.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.spec.tsx @@ -1,6 +1,6 @@ import type { GitDiffLine } from "@pi-desktop/shared"; -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; import { GitDiffViewer, pairRemoveAddLines } from "./git-diff-viewer"; function makeLine( @@ -147,3 +147,69 @@ describe("GitDiffViewer line coloring", () => { expect(lineNumSpans.length).toBeGreaterThan(0); }); }); + +describe("GitDiffViewer line selection", () => { + function findLineRow(container: HTMLElement, text: string): HTMLElement { + const rows = container.querySelectorAll("[data-selected]"); + for (const row of rows) { + if (row.textContent?.includes(text)) return row; + } + throw new Error(`no selectable diff row containing ${text}`); + } + + it("does not make lines selectable without an ask handler", () => { + render( {}} />); + expect( + screen.queryByRole("button", { name: /Ask about selection/ }), + ).not.toBeInTheDocument(); + expect(document.querySelectorAll("[data-selected]").length).toBe(0); + }); + + it("sends a question with old/new coordinates for selected lines", () => { + const onAskAboutSelection = vi.fn(); + const { container } = render( + {}} + onAskAboutSelection={onAskAboutSelection} + />, + ); + + fireEvent.click(findLineRow(container, "old code here")); + fireEvent.click(findLineRow(container, "new code here")); + + expect(screen.getByText("2 lines selected")).toBeInTheDocument(); + + fireEvent.click( + screen.getByRole("button", { name: "Ask about selection" }), + ); + + expect(onAskAboutSelection).toHaveBeenCalledTimes(1); + const question = onAskAboutSelection.mock.calls[0]?.[0] as string; + expect(question).toContain("test.ts"); + expect(question).toContain("old line 2 / new line — (old side)"); + expect(question).toContain("- old code here"); + expect(question).toContain("old line — / new line 2 (new side)"); + expect(question).toContain("+ new code here"); + + // Selection clears after asking. + expect(screen.queryByText("2 lines selected")).not.toBeInTheDocument(); + }); + + it("toggles a line off when clicked twice", () => { + const { container } = render( + {}} + onAskAboutSelection={vi.fn()} + />, + ); + + const addedLine = findLineRow(container, "new code here"); + fireEvent.click(addedLine); + expect(screen.getByText("1 line selected")).toBeInTheDocument(); + + fireEvent.click(addedLine); + expect(screen.queryByText("1 line selected")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.tsx b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.tsx index f885822..a80dd94 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.tsx @@ -2,11 +2,27 @@ import type { GitDiffHunk, GitDiffLine, GitFileDiff } from "@pi-desktop/shared"; import { cn } from "@pi-desktop/ui"; import * as React from "react"; import { Check, Copy, X } from "@/components/ui/phosphor-icons"; -import { computeCharDiff } from "./compute-char-diff"; +import { DiffLine } from "./git-diff-line"; +import { + type DiffLineCoordinate, + formatDiffSelectionQuestion, + isDiffLineSelected, + pairRemoveAddLines, + serializeDiffForClipboard, + toggleDiffLineSelection, +} from "./git-diff-selection"; + +export { pairRemoveAddLines, serializeDiffForClipboard }; interface GitDiffViewerProps { diff: GitFileDiff; onClose: () => void; + /** + * When provided, diff lines become selectable and the user can send + * a question about the selected lines (with old/new coordinates) to + * the agent. When omitted, the viewer is read-only. + */ + onAskAboutSelection?: (question: string) => void; } /** @@ -50,133 +66,6 @@ export function detectLanguageHint(filePath: string): string { return LANGUAGE_BY_EXTENSION[ext] ?? ext; } -function IntraLineSpan({ - text, - highlightStart, - highlight, - highlightClass, - defaultClass, -}: { - text: string; - highlightStart: number; - highlight: string; - highlightClass: string; - defaultClass: string; -}) { - if (!highlight) return {text}; - return ( - <> - {highlightStart > 0 && ( - {text.slice(0, highlightStart)} - )} - {highlight} - {highlightStart + highlight.length < text.length && ( - - {text.slice(highlightStart + highlight.length)} - - )} - - ); -} - -function DiffLine({ - line, - pairedLine, -}: { - line: GitDiffLine; - pairedLine: GitDiffLine | null; -}) { - if (line.type === "hunk_header") { - return ( -
- - - - {line.content} -
- ); - } - - const isAdd = line.type === "add"; - const isRemove = line.type === "remove"; - const bgClass = isAdd ? "bg-emerald-500/10" : isRemove ? "bg-red-500/10" : ""; - const textClass = isAdd - ? "text-emerald-400" - : isRemove - ? "text-red-400" - : "text-white/50"; - const prefix = isAdd ? "+" : isRemove ? "-" : " "; - const lineNumber = isRemove - ? line.oldLineNumber - : isAdd - ? line.newLineNumber - : line.newLineNumber; - const emptyLineNum = isRemove ? "" : isAdd ? "" : line.oldLineNumber; - - const charDiff = - pairedLine && (isAdd || isRemove) - ? computeCharDiff( - isRemove ? line.content : pairedLine.content, - isAdd ? line.content : pairedLine.content, - ) - : null; - const middle = isRemove ? charDiff?.oldMiddle : charDiff?.newMiddle; - const middleStart = charDiff ? charDiff.prefix.length : 0; - - return ( -
- - {isRemove ? lineNumber : emptyLineNum} - - - {isAdd ? lineNumber : emptyLineNum} - - - {prefix} - - - {charDiff && middle ? ( - - ) : ( - {line.content} - )} - -
- ); -} - -export function pairRemoveAddLines( - lines: GitDiffLine[], -): Map { - const paired = new Map(); - let lastRemoveIndex: number | null = null; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (!line) continue; - if (line.type === "remove") { - lastRemoveIndex = i; - } else if (line.type === "add" && lastRemoveIndex !== null) { - const removeLine = lines[lastRemoveIndex]; - if (removeLine) { - paired.set(lastRemoveIndex, line); - paired.set(i, removeLine); - } - lastRemoveIndex = null; - } else if (line.type === "context" || line.type === "hunk_header") { - lastRemoveIndex = null; - } - } - - return paired; -} - function HunkHeader({ hunk }: { hunk: GitDiffHunk }) { return (
@@ -187,34 +76,44 @@ function HunkHeader({ hunk }: { hunk: GitDiffHunk }) { ); } -/** - * Re-serialize a diff to a unified-ish text form suitable for clipboard copy. - * Not a strict git-format emitter; preserves +/- prefix and context space. - */ -export function serializeDiffForClipboard(diff: GitFileDiff): string { - const header = `--- a/${diff.oldFilePath ?? diff.filePath}\n+++ b/${diff.filePath}`; - const body = diff.hunks - .map((hunk) => { - const hunkHeader = `@@ -${hunk.oldStart},${hunk.oldCount} +${hunk.newStart},${hunk.newCount} @@`; - const lines = hunk.lines - .map((line) => { - const prefix = - line.type === "add" ? "+" : line.type === "remove" ? "-" : " "; - return `${prefix}${line.content}`; - }) - .join("\n"); - return `${hunkHeader}\n${lines}`; - }) - .join("\n"); - return `${header}\n${body}`; -} - -export function GitDiffViewer({ diff, onClose }: GitDiffViewerProps) { +export function GitDiffViewer({ + diff, + onClose, + onAskAboutSelection, +}: GitDiffViewerProps) { const language = React.useMemo( () => detectLanguageHint(diff.filePath), [diff.filePath], ); const [copied, setCopied] = React.useState(false); + // Selection is keyed by file so it never leaks across diffs. + const [selection, setSelection] = React.useState<{ + filePath: string; + lines: DiffLineCoordinate[]; + }>({ filePath: diff.filePath, lines: [] }); + const selectedLines = + selection.filePath === diff.filePath ? selection.lines : []; + const selectable = Boolean(onAskAboutSelection); + + const handleToggleLine = React.useCallback( + (line: GitDiffLine) => { + setSelection((current) => { + const currentLines = + current.filePath === diff.filePath ? current.lines : []; + return { + filePath: diff.filePath, + lines: toggleDiffLineSelection(currentLines, line), + }; + }); + }, + [diff.filePath], + ); + + const handleAskAboutSelection = React.useCallback(() => { + if (!onAskAboutSelection || selectedLines.length === 0) return; + onAskAboutSelection(formatDiffSelectionQuestion(diff, selectedLines)); + setSelection({ filePath: diff.filePath, lines: [] }); + }, [diff, onAskAboutSelection, selectedLines]); const handleCopyDiff = React.useCallback(() => { const text = serializeDiffForClipboard(diff); @@ -319,6 +218,9 @@ export function GitDiffViewer({ diff, onClose }: GitDiffViewerProps) { key={j} line={line} pairedLine={paired.get(j) ?? null} + selectable={selectable} + selected={isDiffLineSelected(selectedLines, line)} + onToggleSelect={handleToggleLine} /> ))}
@@ -328,6 +230,30 @@ export function GitDiffViewer({ diff, onClose }: GitDiffViewerProps) { )} + + {selectable && selectedLines.length > 0 ? ( +
+ + {selectedLines.length}{" "} + {selectedLines.length === 1 ? "line" : "lines"} selected + + + + +
+ ) : null} ); } diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-panel-skeleton.tsx b/apps/desktop/src/renderer/src/features/workspace/components/git-panel-skeleton.tsx new file mode 100644 index 0000000..cfcf92e --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-panel-skeleton.tsx @@ -0,0 +1,18 @@ +export function GitPanelSkeleton() { + return ( +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/git-panel.tsx b/apps/desktop/src/renderer/src/features/workspace/components/git-panel.tsx index 43e5c16..3138857 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/git-panel.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/git-panel.tsx @@ -21,6 +21,7 @@ import { NO_GIT_CAPABILITIES, nextFocusIndex, } from "./git-panel-model"; +import { GitPanelSkeleton } from "./git-panel-skeleton"; export { buildGitPanelViewModel, @@ -60,6 +61,12 @@ export interface GitPanelProps { onUnstageAllFiles: (filePaths: string[]) => void | Promise; onDiscardFile: (filePath: string) => void | Promise; onViewDiff?: (filePath: string, staged: boolean) => void; + /** + * Ask the agent about diff lines selected in the diff viewer. The + * question text carries the selected lines' old/new coordinates. + * When omitted, diff lines are not selectable. + */ + onAskAboutDiffSelection?: (question: string) => void; /** Per-file revert. Called only when `capabilities.revertFile` is true. */ onRevertFile?: (filePath: string) => void | Promise; /** Amend toggle change. Called only when `capabilities.amend` is true. */ @@ -70,25 +77,6 @@ export interface GitPanelProps { onSwitchBranch?: (branchName: string) => void | Promise; } -function GitPanelSkeleton() { - return ( -
-
-
-
-
-
-
-
-
-
-
-
-
-
- ); -} - export function GitPanel({ className, projectName: _projectName, @@ -116,6 +104,7 @@ export function GitPanel({ onUnstageAllFiles, onDiscardFile, onViewDiff, + onAskAboutDiffSelection, onRevertFile, onAmendChange, onSwitchBranch, @@ -273,7 +262,11 @@ export function GitPanel({ /> {selectedDiff ? ( - + ) : diffLoading ? (
Loading diff... diff --git a/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell.tsx b/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell.tsx index 63e615b..3cb3379 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell.tsx @@ -240,7 +240,6 @@ function WorkspaceShellImpl({ }, [leftSidebarWidth]); const { - projectName, activeWorktree, hasActiveThread, hasChangesToCommit, @@ -270,7 +269,6 @@ function WorkspaceShellImpl({ const gitPanel = ( ); diff --git a/apps/desktop/src/renderer/src/features/workspace/use-workspace-prompt.ts b/apps/desktop/src/renderer/src/features/workspace/use-workspace-prompt.ts index 9b870ef..ccf615c 100644 --- a/apps/desktop/src/renderer/src/features/workspace/use-workspace-prompt.ts +++ b/apps/desktop/src/renderer/src/features/workspace/use-workspace-prompt.ts @@ -417,6 +417,9 @@ export function useWorkspacePrompt({ [activeThreadId, agentStatus, sendPrompt], ); + // "Edit and send again": the edited text is sent as a new prompt. + // The original message is not edited or removed, and later messages + // are not truncated — the conversation keeps its full history. const handleResubmitUserMessage = React.useCallback( (messageId: string, nextText: string) => { const trimmed = nextText.trim();