diff --git a/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts b/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts index 7162a52b2..f32812cf1 100644 --- a/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts +++ b/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts @@ -5,27 +5,34 @@ import path from "node:path"; import type { Dialog, Page } from "@playwright/test"; import { expect, test } from "../support/fixtures"; import { gotoAppShell } from "../support/helpers/app"; +import { daemonWsRoutePattern } from "../support/helpers/daemon-port"; import { archiveWorkspaceFromDaemon, connectNewWorkspaceDaemonClient, createWorktreeViaDaemon, openProjectViaDaemon, } from "../support/helpers/new-workspace"; +import { expectAppRoute } from "../support/helpers/route-assertions"; import { getServerId } from "../support/helpers/server-id"; import { clickArchiveWorkspaceMenuItem, expectWorkspaceAbsentFromSidebar, } from "../support/helpers/sidebar"; import { createTempGitRepo } from "../support/helpers/workspace"; +import { + rowArchiveButton, + undoButton, + workspaceRow, +} from "../support/helpers/workspace-archive-undo"; import { waitForSidebarHydration, waitForWorkspaceInSidebar, } from "../support/helpers/workspace-ui"; +import { buildHostWorkspaceRoute } from "@/utils/host-routes"; -async function seedRiskyWorktree( - client: Awaited>, - worktreeDirectory: string, -): Promise { +type DaemonClient = Awaited>; + +async function seedRiskyWorktree(client: DaemonClient, worktreeDirectory: string): Promise { // The daemon only reports unpushed commits when the branch has a configured // upstream (aheadOfOrigin is computed against `branch..merge`). Push the // worktree branch at its current head first so it tracks origin with 0 ahead, @@ -55,35 +62,189 @@ async function seedRiskyWorktree( const dirtyFile = path.join(worktreeDirectory, "DIRTY.md"); await writeFile(dirtyFile, "# dirty\n"); - const refreshed = await client.checkoutRefresh(worktreeDirectory); + await refreshCheckout(client, worktreeDirectory); +} + +async function refreshCheckout(client: DaemonClient, directory: string): Promise { + const refreshed = await client.checkoutRefresh(directory); if (!refreshed.success) { - throw new Error(`Failed to refresh checkout for ${worktreeDirectory}`); + throw new Error(`Failed to refresh checkout for ${directory}`); } } -// The archive confirmation is a synchronous web `window.confirm()`. The click that -// opens it does not resolve until the dialog is answered, so the handler must -// accept/dismiss inline — awaiting the dialog only *after* the click deadlocks, as -// the click waits for an answer that is gated behind that same click. -async function clickArchiveAndAnswerWarning( +// The archive confirmation is a synchronous web `window.confirm()` that opens once the app has +// read the worktree's git state from the host. Wait for the dialog itself: on web the click does +// not resolve until it is answered, so answer it from the event. +async function answerArchiveWarning( page: Page, - workspaceId: string, answer: "accept" | "dismiss", + openArchive: () => Promise, ): Promise { - let warning: Dialog | undefined; - page.once("dialog", (dialog) => { - warning = dialog; - void (answer === "accept" ? dialog.accept() : dialog.dismiss()); + const warning = page.waitForEvent("dialog", { timeout: 10_000 }).then(async (dialog) => { + await (answer === "accept" ? dialog.accept() : dialog.dismiss()); + return dialog; }); - await clickArchiveWorkspaceMenuItem(page, workspaceId); - if (!warning) { - throw new Error("Expected an archive confirmation dialog, but none was shown."); + await openArchive(); + return await warning; +} + +// A clean Paseo worktree's primary git action in the workspace header is Archive. +function gitActionsArchiveButton(page: Page) { + return page.getByTestId("changes-primary-cta").and(page.getByLabel("Archive workspace")); +} + +async function clickRowArchiveButton(page: Page, workspaceId: string): Promise { + await workspaceRow(page, workspaceId).hover(); + await rowArchiveButton(page, workspaceId).click(); +} + +interface SessionEnvelope { + type?: unknown; + message?: { + type?: unknown; + workspaceId?: unknown; + cwd?: unknown; + payload?: Record; + }; +} + +function parseSessionEnvelope(message: string): SessionEnvelope | null { + try { + return JSON.parse(message) as SessionEnvelope; + } catch { + return null; } - return warning; +} + +function removeGitStatusFromDescriptors(value: unknown, workspaceId: string): number { + if (Array.isArray(value)) { + return value.reduce( + (count, item) => count + removeGitStatusFromDescriptors(item, workspaceId), + 0, + ); + } + if (!value || typeof value !== "object") return 0; + const record = value as Record; + let count = 0; + if (record.id === workspaceId && "workspaceDirectory" in record) { + delete record.gitRuntime; + record.diffStat = null; + count += 1; + } + for (const child of Object.values(record)) { + count += removeGitStatusFromDescriptors(child, workspaceId); + } + return count; +} + +/** + * Relays the app's connection to the daemon. Every workspace descriptor for `workspaceId` reaches + * the app without git status, as the host sends it before its first checkout snapshot of the + * worktree, so the sidebar row has nothing cached to warn from. `failCheckoutStatusFor` turns the + * host's checkout status answer for that directory into a git error. + */ +async function relayDaemon( + page: Page, + input: { workspaceId: string; failCheckoutStatusFor?: string }, +) { + let descriptorRewrites = 0; + let archiveRequests = 0; + await page.routeWebSocket(daemonWsRoutePattern(), (browser) => { + const server = browser.connectToServer(); + browser.onMessage((message) => { + if (typeof message === "string") { + const request = parseSessionEnvelope(message)?.message; + if ( + request?.type === "archive_workspace_request" && + request.workspaceId === input.workspaceId + ) { + archiveRequests += 1; + } + } + server.send(message); + }); + server.onMessage((message) => { + if (typeof message !== "string") { + browser.send(message); + return; + } + const envelope = parseSessionEnvelope(message); + const response = envelope?.message; + if ( + input.failCheckoutStatusFor && + response?.type === "checkout_status_response" && + response.payload?.cwd === input.failCheckoutStatusFor + ) { + response.payload = { + ...response.payload, + isGit: false, + isPaseoOwnedWorktree: false, + repoRoot: null, + currentBranch: null, + isDirty: null, + baseRef: null, + aheadBehind: null, + aheadOfOrigin: null, + behindOfOrigin: null, + hasRemote: false, + remoteUrl: null, + error: { code: "UNKNOWN", message: "git status failed" }, + }; + browser.send(JSON.stringify(envelope)); + return; + } + if (!envelope || !message.includes(input.workspaceId)) { + browser.send(message); + return; + } + descriptorRewrites += removeGitStatusFromDescriptors(envelope, input.workspaceId); + browser.send(JSON.stringify(envelope)); + }); + }); + return { + descriptorRewrites: () => descriptorRewrites, + archiveRequests: () => archiveRequests, + }; +} + +/** + * Holds the app's next checkout status request for `directory` once armed, so a test can act + * while the archive waits for the host's answer. + */ +async function holdCheckoutStatusRequest(page: Page, directory: string) { + let armed = false; + let held: (() => void) | null = null; + await page.routeWebSocket(daemonWsRoutePattern(), (browser) => { + const server = browser.connectToServer(); + browser.onMessage((message) => { + const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null; + if ( + armed && + !held && + request?.type === "checkout_status_request" && + request.cwd === directory + ) { + held = () => server.send(message); + return; + } + server.send(message); + }); + server.onMessage((message) => browser.send(message)); + }); + return { + arm: () => { + armed = true; + }, + waitForHeld: () => expect.poll(() => held !== null).toBe(true), + release: () => { + if (!held) throw new Error("No checkout status request is held"); + held(); + }, + }; } test.describe("Workspace archive risk warning for worktree backing", () => { - let client: Awaited>; + let client: DaemonClient; let tempRepo: { path: string; cleanup: () => Promise }; const createdWorktreeDirectories = new Set(); @@ -103,36 +264,53 @@ test.describe("Workspace archive risk warning for worktree backing", () => { await tempRepo?.cleanup().catch(() => undefined); }); - test("a risky workspace archive is gated by confirmation and removes its worktree after acceptance", async ({ - page, - }) => { - const serverId = getServerId(); - await openProjectViaDaemon(client, tempRepo.path); + async function createWorktree(slug: string) { + const project = await openProjectViaDaemon(client, tempRepo.path); const worktree = await createWorktreeViaDaemon(client, { cwd: tempRepo.path, - slug: `archive-risk-${Date.now()}`, + slug: `${slug}-${Date.now()}`, }); createdWorktreeDirectories.add(worktree.workspaceDirectory); expect(existsSync(worktree.workspaceDirectory)).toBe(true); + return { ...worktree, project }; + } - await seedRiskyWorktree(client, worktree.workspaceDirectory); - + async function openSidebarRow(page: Page, workspaceId: string): Promise { await gotoAppShell(page); await waitForSidebarHydration(page); - await waitForWorkspaceInSidebar(page, { serverId, workspaceId: worktree.workspaceId }); + await waitForWorkspaceInSidebar(page, { serverId: getServerId(), workspaceId }); + } - const firstWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "dismiss"); + async function expectWorktreeKept(page: Page, worktree: { workspaceId: string }) { + await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 10_000 }); + } + + async function hostListsWorkspace(workspaceId: string): Promise { + const { entries } = await client.fetchWorkspaces(); + return entries.some((entry) => entry.id === workspaceId); + } + + test("a risky workspace archive is gated by confirmation and removes its worktree after acceptance", async ({ + page, + }) => { + const worktree = await createWorktree("archive-risk"); + await seedRiskyWorktree(client, worktree.workspaceDirectory); + await openSidebarRow(page, worktree.workspaceId); + + const firstWarning = await answerArchiveWarning(page, "dismiss", () => + clickArchiveWorkspaceMenuItem(page, worktree.workspaceId), + ); expect(firstWarning.type()).toBe("confirm"); expect(firstWarning.message()).toContain(`Archive "${worktree.workspaceName}"?`); expect(firstWarning.message()).toContain("Uncommitted changes"); expect(firstWarning.message()).toContain("1 unpushed commit"); - await expect( - page.getByTestId(`sidebar-workspace-row-${serverId}:${worktree.workspaceId}`), - ).toBeVisible({ timeout: 10_000 }); + await expectWorktreeKept(page, worktree); expect(existsSync(worktree.workspaceDirectory)).toBe(true); - const secondWarning = await clickArchiveAndAnswerWarning(page, worktree.workspaceId, "accept"); + const secondWarning = await answerArchiveWarning(page, "accept", () => + clickArchiveWorkspaceMenuItem(page, worktree.workspaceId), + ); expect(secondWarning.message()).toContain("Uncommitted changes"); expect(secondWarning.message()).toContain("1 unpushed commit"); @@ -143,4 +321,128 @@ test.describe("Workspace archive risk warning for worktree backing", () => { createdWorktreeDirectories.delete(worktree.workspaceDirectory); }); + + test("the row's archive button warns from the host's git state while the row has none, and Cancel keeps the worktree", async ({ + page, + }) => { + const worktree = await createWorktree("archive-risk-uncached"); + await seedRiskyWorktree(client, worktree.workspaceDirectory); + const relay = await relayDaemon(page, { workspaceId: worktree.workspaceId }); + await openSidebarRow(page, worktree.workspaceId); + expect(relay.descriptorRewrites()).toBeGreaterThan(0); + + const warning = await answerArchiveWarning(page, "dismiss", () => + clickRowArchiveButton(page, worktree.workspaceId), + ); + expect(warning.message()).toContain(`Archive "${worktree.workspaceName}"?`); + expect(warning.message()).toContain("Uncommitted changes"); + expect(warning.message()).toContain("1 unpushed commit"); + + await expectWorktreeKept(page, worktree); + expect(relay.archiveRequests()).toBe(0); + expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true); + }); + + test("a worktree holding only new files warns when the repository hides untracked files", async ({ + page, + }) => { + execSync("git config status.showUntrackedFiles no", { cwd: tempRepo.path, stdio: "ignore" }); + const worktree = await createWorktree("archive-risk-untracked"); + await writeFile(path.join(worktree.workspaceDirectory, "NEW.md"), "# not yet added\n"); + await refreshCheckout(client, worktree.workspaceDirectory); + await openSidebarRow(page, worktree.workspaceId); + + const warning = await answerArchiveWarning(page, "dismiss", () => + clickRowArchiveButton(page, worktree.workspaceId), + ); + expect(warning.message()).toContain(`Archive "${worktree.workspaceName}"?`); + expect(warning.message()).toContain("Uncommitted changes"); + + await expectWorktreeKept(page, worktree); + expect(existsSync(path.join(worktree.workspaceDirectory, "NEW.md"))).toBe(true); + }); + + test("a failed git read shows its error and keeps the worktree", async ({ page }) => { + const worktree = await createWorktree("archive-risk-read-failure"); + await seedRiskyWorktree(client, worktree.workspaceDirectory); + const relay = await relayDaemon(page, { + workspaceId: worktree.workspaceId, + failCheckoutStatusFor: worktree.workspaceDirectory, + }); + await openSidebarRow(page, worktree.workspaceId); + + await clickRowArchiveButton(page, worktree.workspaceId); + + await expect(page.getByTestId("app-toast-message")).toHaveText("git status failed"); + await expectWorktreeKept(page, worktree); + expect(relay.archiveRequests()).toBe(0); + expect(existsSync(worktree.workspaceDirectory)).toBe(true); + }); + + // Archives the open worktree with `startArchive`, opens the project's main workspace while the + // host's checkout status answer is held, then lets the answer through. + async function archiveWhileOpeningAnotherWorkspace( + page: Page, + slug: string, + startArchive: (worktree: { workspaceId: string }) => Promise, + ): Promise { + const serverId = getServerId(); + const worktree = await createWorktree(slug); + const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory); + await openSidebarRow(page, worktree.workspaceId); + await workspaceRow(page, worktree.workspaceId).click(); + await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId)); + + statusRequest.arm(); + await startArchive(worktree); + await statusRequest.waitForHeld(); + await workspaceRow(page, worktree.project.workspaceId).click(); + const openedRoute = buildHostWorkspaceRoute(serverId, worktree.project.workspaceId); + await expectAppRoute(page, openedRoute); + + statusRequest.release(); + await expect(undoButton(page)).toBeVisible(); + // The redirect runs before the archive request, so once the host has archived the worktree + // any redirect has already happened. + await expect + .poll(() => hostListsWorkspace(worktree.workspaceId), { timeout: 30_000 }) + .toBe(false); + return openedRoute; + } + + test("opening another workspace while the host answers keeps it open after a row archive", async ({ + page, + }) => { + const openedRoute = await archiveWhileOpeningAnotherWorkspace( + page, + "archive-risk-switch-row", + (worktree) => clickRowArchiveButton(page, worktree.workspaceId), + ); + await expectAppRoute(page, openedRoute); + }); + + test("opening another workspace while the host answers keeps it open after a git actions archive", async ({ + page, + }) => { + const openedRoute = await archiveWhileOpeningAnotherWorkspace( + page, + "archive-risk-switch-git", + () => gitActionsArchiveButton(page).click(), + ); + await expectAppRoute(page, openedRoute); + }); + + test("archiving the open worktree from its git actions leaves it for a new workspace", async ({ + page, + }) => { + const worktree = await createWorktree("archive-risk-git-redirect"); + await openSidebarRow(page, worktree.workspaceId); + await workspaceRow(page, worktree.workspaceId).click(); + await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId)); + + await gitActionsArchiveButton(page).click(); + + await expect.poll(() => new URL(page.url()).pathname).toBe("/new"); + await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId); + }); }); diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index 8bc520025..8b7489f5f 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -87,7 +87,6 @@ import { import { ProjectLeadingVisual } from "@/components/sidebar/project-leading-visual"; import { useToast } from "@/contexts/toast-context"; import { getForgePresentation, normalizeForge } from "@/git/forge"; -import { toWorktreeArchiveRisk } from "@/git/worktree-archive-warning"; import { hasVisibleOrderChanged, mergeWithRemainder } from "@/utils/sidebar-reorder"; import { confirmDialog } from "@/utils/confirm-dialog"; import type { SidebarStateBucket } from "@/utils/sidebar-agent-state"; @@ -1252,8 +1251,9 @@ function WorkspaceRowWithMenu({ serverId: workspace.serverId, workspaceId: workspace.workspaceId, workspaceKind: workspace.workspaceKind, + workspaceDirectory: workspace.workspaceDirectory, name: workspace.name, - ...toWorktreeArchiveRisk(workspace), + diffStat: workspace.diffStat, onArchiveStarted: redirectAfterArchive, onSetHiding: setIsHidingWorkspace, }); diff --git a/packages/app/src/components/sidebar/sidebar-status-list.tsx b/packages/app/src/components/sidebar/sidebar-status-list.tsx index 945b62566..38c898101 100644 --- a/packages/app/src/components/sidebar/sidebar-status-list.tsx +++ b/packages/app/src/components/sidebar/sidebar-status-list.tsx @@ -38,7 +38,6 @@ import { useSidebarWorkspaceRename } from "@/workspace-rename"; import { useWorkspaceClipboardActions } from "@/hooks/use-workspace-clipboard-actions"; import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect"; import { useWorkspaceArchive } from "@/workspace/use-workspace-archive"; -import { toWorktreeArchiveRisk } from "@/git/worktree-archive-warning"; import type { ShortcutKey } from "@/utils/format-shortcut"; import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; @@ -656,8 +655,9 @@ function StatusWorkspaceRowWithMenu({ serverId: workspace.serverId, workspaceId: workspace.workspaceId, workspaceKind: workspace.workspaceKind, + workspaceDirectory: workspace.workspaceDirectory, name: workspace.name, - ...toWorktreeArchiveRisk(workspace), + diffStat: workspace.diffStat, onArchiveStarted: redirectAfterArchive, onSetHiding: setIsHidingWorkspace, }); diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index 13f758762..877efa769 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -291,21 +291,13 @@ function useWorkspaceScreenArchiveController({ serverId, workspaceId: workspaceDescriptor?.id ?? "", workspaceKind: workspaceDescriptor?.workspaceKind ?? "directory", + workspaceDirectory: workspaceDescriptor?.workspaceDirectory ?? "", name: workspaceDescriptor?.name ?? branchLabel, - isDirty: archiveRisk.isDirty, - aheadOfOrigin: archiveRisk.aheadOfOrigin, diffStat: workspaceDescriptor?.diffStat ?? null, warningLabels: getWorktreeArchiveWarningLabels(t), onSetHiding: setIsHidingWorkspace, - onArchiveStarted: () => { - if (!activeWorkspaceSelection) { - return; - } - redirectIfArchivingActiveWorkspace({ - serverId, - workspaceId: activeWorkspaceSelection.workspaceId, - activeWorkspaceSelection, - }); + onArchiveStarted: (archived) => { + redirectIfArchivingActiveWorkspace({ ...archived, activeWorkspaceSelection }); }, }); diff --git a/packages/app/src/git/worktree-archive-warning.test.ts b/packages/app/src/git/worktree-archive-warning.test.ts index ddf60c774..185c37dcb 100644 --- a/packages/app/src/git/worktree-archive-warning.test.ts +++ b/packages/app/src/git/worktree-archive-warning.test.ts @@ -1,11 +1,87 @@ import { describe, expect, it } from "vitest"; +import type { CheckoutStatusClient, CheckoutStatusPayload } from "@/git/checkout-status-cache"; import { buildWorktreeArchiveConfirmationMessage, buildWorktreeArchiveRiskReasons, + readWorktreeArchiveRisk, toWorktreeArchiveRisk, } from "@/git/worktree-archive-warning"; +const WORKTREE = "/home/me/.paseo/worktrees/repo/feature"; + +function hostAnswering(status: CheckoutStatusPayload): CheckoutStatusClient & { asked: string[] } { + const asked: string[] = []; + return { + asked, + getCheckoutStatus: async (cwd) => { + asked.push(cwd); + return status; + }, + }; +} + +const NOT_GIT = { + cwd: WORKTREE, + requestId: "status", + isGit: false, + isPaseoOwnedWorktree: false, + repoRoot: null, + currentBranch: null, + isDirty: null, + baseRef: null, + aheadBehind: null, + aheadOfOrigin: null, + behindOfOrigin: null, + hasRemote: false, + remoteUrl: null, + error: null, +} satisfies CheckoutStatusPayload; + +describe("reading a worktree's archive risk from its host", () => { + it("reads uncommitted changes and unpushed commits from the worktree's checkout status", async () => { + const host = hostAnswering({ + cwd: WORKTREE, + requestId: "status", + isGit: true, + isPaseoOwnedWorktree: true, + repoRoot: WORKTREE, + mainRepoRoot: "/home/me/repo", + currentBranch: "feature", + isDirty: true, + baseRef: "main", + aheadBehind: { ahead: 2, behind: 0 }, + aheadOfOrigin: 2, + behindOfOrigin: 0, + hasRemote: true, + remoteUrl: "git@example.com:me/repo.git", + error: null, + }); + + expect(await readWorktreeArchiveRisk(host, WORKTREE)).toEqual({ + isDirty: true, + aheadOfOrigin: 2, + }); + expect(host.asked).toEqual([WORKTREE]); + }); + + it("finds nothing to lose in a directory that is no longer a git checkout", async () => { + expect(await readWorktreeArchiveRisk(hostAnswering(NOT_GIT), WORKTREE)).toEqual({ + isDirty: false, + aheadOfOrigin: null, + }); + }); + + it("rejects with the host's error when it can't read the worktree", async () => { + const host = hostAnswering({ + ...NOT_GIT, + error: { code: "UNKNOWN", message: "git status failed" }, + }); + + await expect(readWorktreeArchiveRisk(host, WORKTREE)).rejects.toThrow("git status failed"); + }); +}); + describe("workspace archive warning for worktree backing", () => { it("does not require a confirmation for clean and pushed worktrees", () => { expect( diff --git a/packages/app/src/git/worktree-archive-warning.ts b/packages/app/src/git/worktree-archive-warning.ts index f7405cd2b..3935eef3c 100644 --- a/packages/app/src/git/worktree-archive-warning.ts +++ b/packages/app/src/git/worktree-archive-warning.ts @@ -1,3 +1,4 @@ +import type { CheckoutStatusClient } from "@/git/checkout-status-cache"; import { confirmDialog } from "@/utils/confirm-dialog"; import { i18n } from "@/i18n/i18next"; @@ -49,6 +50,21 @@ export const DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS: WorktreeArchiveWarningLabe : i18n.t("workspace.git.actions.archiveWarning.unpushedCommits", { count }), }; +/** + * Reads the worktree's uncommitted changes and unpushed commits from its host. A directory the + * host no longer reads as a git checkout has neither. Rejects when the host can't read it. + */ +export async function readWorktreeArchiveRisk( + client: CheckoutStatusClient, + workspaceDirectory: string, +): Promise> { + const status = await client.getCheckoutStatus(workspaceDirectory); + if (status.error) { + throw new Error(status.error.message); + } + return { isDirty: status.isDirty ?? false, aheadOfOrigin: status.aheadOfOrigin }; +} + export function toWorktreeArchiveRisk(input: WorktreeArchiveRiskInput): WorktreeArchiveRisk { return { isDirty: input.archiveHasUncommittedChanges, diff --git a/packages/app/src/workspace/use-workspace-archive.ts b/packages/app/src/workspace/use-workspace-archive.ts index 9608cef0c..82255f6e9 100644 --- a/packages/app/src/workspace/use-workspace-archive.ts +++ b/packages/app/src/workspace/use-workspace-archive.ts @@ -1,17 +1,21 @@ -import { useCallback } from "react"; +import { useCallback, useRef } from "react"; import { useTranslation } from "react-i18next"; import { getHostRuntimeStore } from "@/runtime/host-runtime"; import { useToast } from "@/contexts/toast-context"; import { confirmRiskyWorktreeArchive, DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS, + readWorktreeArchiveRisk, type WorktreeArchiveWarningLabels, } from "@/git/worktree-archive-warning"; import type { WorkspaceDescriptor } from "@/stores/session-store"; import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store"; import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo"; -import { archiveWorkspaceOptimistically } from "@/workspace/workspace-archive"; +import { + archiveWorkspaceOptimistically, + type WorkspaceArchiveTarget, +} from "@/workspace/workspace-archive"; function purgeArchivedWorkspaceState(input: { serverId: string; workspaceId: string }): void { const workspaceKey = buildWorkspaceTabPersistenceKey(input); @@ -24,12 +28,13 @@ export interface ArchiveWorkspaceInput { serverId: string; workspaceId: string; workspaceKind: WorkspaceDescriptor["workspaceKind"]; + workspaceDirectory: string; name: string; - isDirty?: boolean | null; - aheadOfOrigin?: number | null; + /** Labels the warning's line counts. Whether to warn comes from the host's git state. */ diffStat?: { additions: number; deletions: number } | null; warningLabels?: WorktreeArchiveWarningLabels; - onArchiveStarted: () => void; + /** Runs once the archive starts, with the workspace being archived. */ + onArchiveStarted: (workspace: WorkspaceArchiveTarget) => void; onSetHiding?: (hiding: boolean) => void; } @@ -42,9 +47,8 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch serverId, workspaceId, workspaceKind, + workspaceDirectory, name, - isDirty, - aheadOfOrigin, diffStat, warningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS, onArchiveStarted, @@ -52,6 +56,11 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch } = input; const { t } = useTranslation(); const toast = useToast(); + const confirmingRef = useRef(false); + // The archive starts after the host answers and you confirm. By then you may have opened another + // workspace, so the redirect reads the selection from the latest render. + const onArchiveStartedRef = useRef(onArchiveStarted); + onArchiveStartedRef.current = onArchiveStarted; const archiveWorkspaceRecord = useCallback(async () => { const client = getHostRuntimeStore().getClient(serverId); @@ -62,7 +71,7 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch const workspace = { serverId, workspaceId }; onSetHiding?.(true); try { - onArchiveStarted(); + onArchiveStartedRef.current(workspace); if (supportsWorkspaceArchiveUndo(serverId)) { await archiveWorkspaceWithUndo({ client, @@ -82,35 +91,54 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch } finally { onSetHiding?.(false); } - }, [onArchiveStarted, onSetHiding, serverId, t, toast, workspaceId]); + }, [onSetHiding, serverId, t, toast, workspaceId]); + + // The host removes a worktree it archives, uncommitted work included. Ask it what that would + // lose: the sidebar row's git status is empty until the row receives it. + const confirmWorktreeArchive = useCallback(async (): Promise => { + const client = getHostRuntimeStore().getClient(serverId); + if (!client) { + toast.error(t("sidebar.workspace.toasts.hostDisconnected")); + return false; + } + const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch( + (error: unknown) => { + toast.error( + error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"), + ); + return null; + }, + ); + if (!risk) { + return false; + } + return await confirmRiskyWorktreeArchive( + { workspaceName: name, diffStat, ...risk }, + warningLabels, + ); + }, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]); const archive = useCallback(() => { + // A second press while the host answers or the warning is open would ask twice. + if (confirmingRef.current) { + return; + } void (async () => { if (workspaceKind === "worktree") { - const confirmed = await confirmRiskyWorktreeArchive( - { - workspaceName: name, - isDirty, - aheadOfOrigin, - diffStat, - }, - warningLabels, - ); + confirmingRef.current = true; + let confirmed: boolean; + try { + confirmed = await confirmWorktreeArchive(); + } finally { + confirmingRef.current = false; + } if (!confirmed) { return; } } await archiveWorkspaceRecord(); })(); - }, [ - aheadOfOrigin, - archiveWorkspaceRecord, - diffStat, - isDirty, - name, - warningLabels, - workspaceKind, - ]); + }, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]); return { archive, diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index 075f7ebda..13944108e 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -30,6 +30,7 @@ import { getCheckoutShortstat, getPullRequestStatus, getCheckoutStatus, + getCheckoutWorktreeState, checkoutResolvedBranch, listBranchSuggestions, setCheckoutBaseBranch, @@ -572,6 +573,15 @@ describe("checkout git utilities", () => { expect(message).toBe("update file"); }); + it("counts untracked files as dirty when the repository hides them from status", async () => { + execFileSync("git", ["config", "status.showUntrackedFiles", "no"], { cwd: repoDir }); + writeFileSync(join(repoDir, "new-file.txt"), "not yet added\n"); + expect(execFileSync("git", ["status", "--porcelain"], { cwd: repoDir }).toString()).toBe(""); + + expect((await getCheckoutStatus(repoDir)).isDirty).toBe(true); + expect((await getCheckoutWorktreeState(repoDir, {})).isDirty).toBe(true); + }); + it("honors commit signing configuration", async () => { execFileSync("git", ["config", "commit.gpgsign", "true"], { cwd: repoDir }); execFileSync("git", ["config", "gpg.format", "openpgp"], { cwd: repoDir }); diff --git a/packages/server/src/utils/checkout-git.ts b/packages/server/src/utils/checkout-git.ts index 2bb295b37..2738f184d 100644 --- a/packages/server/src/utils/checkout-git.ts +++ b/packages/server/src/utils/checkout-git.ts @@ -1413,12 +1413,17 @@ function resolveOperationBaseRef(input: { return input.storedBaseRef ?? input.requestedBaseRef ?? input.resolvedBaseRef; } +// Untracked files count whatever `status.showUntrackedFiles` says: archive warns from this before +// it removes a worktree, and a file nobody added yet is still work to lose. async function isWorkingTreeDirty(cwd: string, context?: CheckoutContext): Promise { - const { stdout } = await getRunGitCommand(context)(["status", "--porcelain"], { - cwd, - envOverlay: READ_ONLY_GIT_ENV, - logger: context?.logger, - }); + const { stdout } = await getRunGitCommand(context)( + ["status", "--porcelain", "--untracked-files=normal"], + { + cwd, + envOverlay: READ_ONLY_GIT_ENV, + logger: context?.logger, + }, + ); return stdout.trim().length > 0; }