diff --git a/packages/app/e2e/browser/sidebar-workspace-archive-shortcut.spec.ts b/packages/app/e2e/browser/sidebar-workspace-archive-shortcut.spec.ts new file mode 100644 index 000000000..4c5c702d0 --- /dev/null +++ b/packages/app/e2e/browser/sidebar-workspace-archive-shortcut.spec.ts @@ -0,0 +1,149 @@ +import { test, expect, type Page } from "../support/fixtures"; +import { gotoAppShell } from "../support/helpers/app"; +import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client"; +import { selectSidebarStatusGrouping } from "../support/helpers/sidebar"; +import { + createGatedTeardown, + pressArchiveShortcut, + workspaceRow, +} from "../support/helpers/workspace-archive-undo"; + +// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever +// the row was unmounted — a collapsed project section being the common case. It now lives in a +// single always-mounted handler keyed on the active route selection, like the pin shortcut. +// Returns the workspace route, so the test can assert archiving redirected off it. +async function openWorkspace(page: Page, workspaceId: string): Promise { + const row = workspaceRow(page, workspaceId); + await expect(row).toBeVisible({ timeout: 30_000 }); + await row.click(); + await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), { + timeout: 30_000, + }); + return page.url(); +} + +async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise { + const header = page + .locator('[data-testid^="sidebar-project-row-"]') + .filter({ hasText: project.projectDisplayName }); + await expect(header).toHaveCount(1, { timeout: 30_000 }); + + await header.click(); + await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 }); +} + +async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise { + const rows = page + .locator('[data-testid^="sidebar-status-group-rows-"]') + .filter({ has: workspaceRow(page, workspaceId) }); + await expect(rows).toHaveCount(1, { timeout: 30_000 }); + + const rowsTestId = await rows.getAttribute("data-testid"); + const bucket = rowsTestId?.replace("sidebar-status-group-rows-", ""); + expect(bucket).toBeTruthy(); + + await page.getByTestId(`sidebar-status-group-${bucket}`).click(); + await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 }); +} + +async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) { + await expect(page).not.toHaveURL(workspaceUrl); + await expect + .poll(async () => { + const { entries } = await workspace.client.fetchWorkspaces(); + return entries.some((entry) => entry.id === workspace.workspaceId); + }) + .toBe(false); +} + +test.describe("Archive workspace shortcut", () => { + test("archives the active workspace while its row is rendered", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" }); + + try { + await gotoAppShell(page); + const workspaceUrl = await openWorkspace(page, workspace.workspaceId); + + await pressArchiveShortcut(page); + + await expectArchived(page, workspace, workspaceUrl); + } finally { + await workspace.cleanup(); + } + }); + + test("archives the active workspace while its project section is collapsed", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" }); + + try { + await gotoAppShell(page); + const workspaceUrl = await openWorkspace(page, workspace.workspaceId); + await collapseProjectSection(page, workspace); + + await pressArchiveShortcut(page); + + await expectArchived(page, workspace, workspaceUrl); + } finally { + await workspace.cleanup(); + } + }); + + test("archives the active workspace while its status group is collapsed", async ({ page }) => { + const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" }); + + try { + await gotoAppShell(page); + const workspaceUrl = await openWorkspace(page, workspace.workspaceId); + await selectSidebarStatusGrouping(page); + await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({ + timeout: 10_000, + }); + await collapseStatusGroupContaining(page, workspace.workspaceId); + + await pressArchiveShortcut(page); + + await expectArchived(page, workspace, workspaceUrl); + } finally { + await workspace.cleanup(); + } + }); + + test("archives a different workspace while the first worktree is still tearing down", async ({ + page, + }) => { + const teardown = createGatedTeardown(); + const project = await seedWorkspace({ + repoPrefix: "archive-shortcut-teardown-", + repo: { paseoConfig: teardown.paseoConfig }, + }); + const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" }); + + try { + const { workspace: worktree, error } = await project.client.createWorkspace({ + source: { + kind: "worktree", + cwd: project.repoPath, + worktreeSlug: "archive-shortcut-teardown", + }, + }); + if (!worktree) throw new Error(error ?? "Could not seed the worktree"); + await gotoAppShell(page); + + await test.step("start the first archive and wait for its teardown", async () => { + await openWorkspace(page, worktree.id); + await pressArchiveShortcut(page); + await teardown.expectStarted(); + }); + + await test.step("archive the second workspace before the first archive finishes", async () => { + const workspaceUrl = await openWorkspace(page, next.workspaceId); + await pressArchiveShortcut(page); + await expectArchived(page, next, workspaceUrl); + }); + } finally { + teardown.release(); + await project.cleanup(); + await next.cleanup(); + } + }); +}); diff --git a/packages/app/e2e/browser/workspace-archive-undo.spec.ts b/packages/app/e2e/browser/workspace-archive-undo.spec.ts index 219871d78..983bff732 100644 --- a/packages/app/e2e/browser/workspace-archive-undo.spec.ts +++ b/packages/app/e2e/browser/workspace-archive-undo.spec.ts @@ -318,6 +318,37 @@ test.describe("Workspace archive undo", () => { } }); + test("archives a restored workspace while its undo is queued", async ({ page }) => { + const teardown = createGatedTeardown(); + const repo = await createTempGitRepo("archive-undo-archive-", { + paseoConfig: teardown.paseoConfig, + }); + + try { + await openProjectViaDaemon(client, repo.path); + const worktree = await createWorktreeViaDaemon(client, { + cwd: repo.path, + slug: "archive-undo-archive", + }); + worktreeDirectories.add(worktree.workspaceDirectory); + await gotoAppShell(page); + await archiveFromRowButton(page, worktree.workspaceId); + await teardown.expectStarted(); + + await undoButton(page).click(); + await workspaceRow(page, worktree.workspaceId).click(); + await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`)); + + await pressArchiveShortcut(page); + await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId); + teardown.release(); + await expectDirectoryPresence(worktree.workspaceDirectory, false); + } finally { + teardown.release(); + await repo.cleanup(); + } + }); + test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => { const worktree = await seedWorktree(page, "archive-undo-none"); 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 f32812cf1..e418abdbf 100644 --- a/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts +++ b/packages/app/e2e/browser/worktree-archive-risk-warning.spec.ts @@ -20,6 +20,7 @@ import { } from "../support/helpers/sidebar"; import { createTempGitRepo } from "../support/helpers/workspace"; import { + pressArchiveShortcut, rowArchiveButton, undoButton, workspaceRow, @@ -98,6 +99,18 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise { + const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle(); + if (!rowBeforeThemeChange) + throw new Error("The workspace row must be mounted before cycling the theme"); + await page.keyboard.press("ControlOrMeta+Alt+t"); + await expect + .poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), { + message: "the sidebar remounts after the theme changes", + }) + .toBe(false); +} + interface SessionEnvelope { type?: unknown; message?: { @@ -211,18 +224,28 @@ async function relayDaemon( * 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) { +async function holdCheckoutStatusRequest( + page: Page, + worktree: { workspaceDirectory: string; workspaceId: string }, +) { let armed = false; let held: (() => void) | null = null; + let archiveRequests = 0; await page.routeWebSocket(daemonWsRoutePattern(), (browser) => { const server = browser.connectToServer(); browser.onMessage((message) => { const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null; + if ( + request?.type === "archive_workspace_request" && + request.workspaceId === worktree.workspaceId + ) { + archiveRequests += 1; + } if ( armed && !held && request?.type === "checkout_status_request" && - request.cwd === directory + request.cwd === worktree.workspaceDirectory ) { held = () => server.send(message); return; @@ -236,6 +259,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) { armed = true; }, waitForHeld: () => expect.poll(() => held !== null).toBe(true), + archiveRequests: () => archiveRequests, release: () => { if (!held) throw new Error("No checkout status request is held"); held(); @@ -388,7 +412,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => { ): Promise { const serverId = getServerId(); const worktree = await createWorktree(slug); - const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory); + const statusRequest = await holdCheckoutStatusRequest(page, worktree); await openSidebarRow(page, worktree.workspaceId); await workspaceRow(page, worktree.workspaceId).click(); await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId)); @@ -432,6 +456,82 @@ test.describe("Workspace archive risk warning for worktree backing", () => { await expectAppRoute(page, openedRoute); }); + async function openWorktreeWithCheckoutHeld(page: Page, slug: string) { + const worktree = await createWorktree(slug); + const statusRequest = await holdCheckoutStatusRequest(page, worktree); + // Opening the workspace can start a checkout read that the archive reuses. + statusRequest.arm(); + await openSidebarRow(page, worktree.workspaceId); + await workspaceRow(page, worktree.workspaceId).click(); + await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId)); + return { worktree, statusRequest }; + } + + test("the archive shortcut works in another workspace while a checkout check is pending", async ({ + page, + }) => { + const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld( + page, + "archive-risk-switch-shortcut", + ); + + await pressArchiveShortcut(page); + await statusRequest.waitForHeld(); + try { + const otherWorkspaceId = worktree.project.workspaceId; + await workspaceRow(page, otherWorkspaceId).click(); + await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId)); + + await pressArchiveShortcut(page); + await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false); + } finally { + statusRequest.release(); + } + await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false); + }); + + test("the row button and shortcut send one archive for the same worktree", async ({ page }) => { + const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld( + page, + "archive-risk-repeat-shortcut", + ); + + await clickRowArchiveButton(page, worktree.workspaceId); + await statusRequest.waitForHeld(); + try { + await pressArchiveShortcut(page); + } finally { + statusRequest.release(); + } + + await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false); + expect(statusRequest.archiveRequests()).toBe(1); + }); + + test("keeps the newly opened workspace after a theme change during an archive check", async ({ + page, + }) => { + const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld( + page, + "archive-risk-theme", + ); + + await pressArchiveShortcut(page); + await statusRequest.waitForHeld(); + const otherWorkspaceId = worktree.project.workspaceId; + const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId); + try { + await cycleThemeAndWaitForSidebar(page, otherWorkspaceId); + await workspaceRow(page, otherWorkspaceId).click(); + await expectAppRoute(page, otherRoute); + } finally { + statusRequest.release(); + } + + await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false); + await expectAppRoute(page, otherRoute); + }); + test("archiving the open worktree from its git actions leaves it for a new workspace", async ({ page, }) => { diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index e1204e72e..bc4b84c4b 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl import { DesktopWindowControls } from "@/components/desktop/window-controls"; import { SidebarModelProvider } from "@/components/sidebar/sidebar-model"; import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler"; +import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler"; import { WorkspaceRenameHost } from "@/components/workspace-rename-host"; import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo"; import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture"; @@ -537,6 +538,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon {workspaceChrome} + {!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? ( diff --git a/packages/app/src/components/sidebar-workspace-list.tsx b/packages/app/src/components/sidebar-workspace-list.tsx index d79a8f170..a3566ab0b 100644 --- a/packages/app/src/components/sidebar-workspace-list.tsx +++ b/packages/app/src/components/sidebar-workspace-list.tsx @@ -128,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip import { Shortcut } from "@/components/ui/shortcut"; import type { ShortcutKey } from "@/utils/format-shortcut"; import { useShortcutKeys } from "@/hooks/use-shortcut-keys"; -import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state"; import type { PrHint } from "@/git/use-pr-status-query"; import { @@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({ }); }, [markUnread, toast]); - useKeyboardActionHandler({ - handlerId: `workspace-archive-${workspace.workspaceKey}`, - actions: ["workspace.archive"], - enabled: selected && !isArchiving, - priority: 0, - handle: () => { - handleArchive(); - return true; - }, - }); - return ( <> { - handleArchive(); - return true; - }, - }); - return ( <> ({ + id: workspace.id, + workspaceKind: workspace.workspaceKind, + workspaceDirectory: workspace.workspaceDirectory, + name: workspace.name, + archivingAt: workspace.archivingAt, + diffStat: workspace.diffStat, + })); + + // useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is + // routed when the archive starts, after any confirmation. It is the descriptor id, which is what + // the redirect compares against. + const activeWorkspaceId = fields?.id ?? null; + const redirectAfterArchive = useCallback( + (workspace: WorkspaceArchiveTarget) => { + redirectIfArchivingActiveWorkspace({ + ...workspace, + activeWorkspaceSelection: + serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null, + }); + }, + [activeWorkspaceId, serverId], + ); + + const archiveController = useWorkspaceArchive({ + serverId: serverId ?? "", + workspaceId: fields?.id ?? "", + workspaceKind: fields?.workspaceKind ?? "directory", + workspaceDirectory: fields?.workspaceDirectory ?? "", + name: fields?.name ?? "", + diffStat: fields?.diffStat, + onArchiveStarted: redirectAfterArchive, + }); + + const canArchive = fields !== null && fields.archivingAt === null; + + const handle = useCallback(() => { + if (!canArchive || !serverId) { + return false; + } + // Archiving hides its target immediately. Read the store in case the shortcut + // runs again before React renders that update. + if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) { + return false; + } + archiveController.archive(); + return true; + }, [archiveController, canArchive, fields, serverId]); + + useKeyboardActionHandler({ + handlerId: "workspace-archive-global", + actions: WORKSPACE_ARCHIVE_ACTIONS, + enabled: canArchive, + priority: 0, + handle, + }); +} diff --git a/packages/app/src/workspace/use-workspace-archive.ts b/packages/app/src/workspace/use-workspace-archive.ts index 82255f6e9..5a01b1015 100644 --- a/packages/app/src/workspace/use-workspace-archive.ts +++ b/packages/app/src/workspace/use-workspace-archive.ts @@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model"; import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo"; import { archiveWorkspaceOptimistically, + runWorkspaceArchiveAttempt, type WorkspaceArchiveTarget, } from "@/workspace/workspace-archive"; @@ -56,7 +57,6 @@ 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); @@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch }, [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") { - confirmingRef.current = true; - let confirmed: boolean; - try { - confirmed = await confirmWorktreeArchive(); - } finally { - confirmingRef.current = false; - } - if (!confirmed) { - return; - } - } - await archiveWorkspaceRecord(); - })(); - }, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]); + void runWorkspaceArchiveAttempt({ + workspace: { serverId, workspaceId }, + confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined, + archive: archiveWorkspaceRecord, + }); + }, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]); return { archive, diff --git a/packages/app/src/workspace/workspace-archive.ts b/packages/app/src/workspace/workspace-archive.ts index 956945570..fcd44abd6 100644 --- a/packages/app/src/workspace/workspace-archive.ts +++ b/packages/app/src/workspace/workspace-archive.ts @@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget { workspaceId: string; } +const pendingArchiveAttempts = new Set(); + +/** Checks and starts one archive at a time for a workspace. */ +export async function runWorkspaceArchiveAttempt(input: { + workspace: WorkspaceArchiveTarget; + confirm?: () => Promise; + archive: () => Promise; +}): Promise { + const { serverId, workspaceId } = input.workspace; + const key = JSON.stringify([serverId, workspaceId]); + if (pendingArchiveAttempts.has(key)) return; + + pendingArchiveAttempts.add(key); + try { + if (input.confirm && !(await input.confirm())) return; + if (!isWorkspaceListed(input.workspace)) return; + // Archive hides the row synchronously. Undo can restore it and start a new + // archive while the previous daemon request is still settling. + return input.archive(); + } finally { + pendingArchiveAttempts.delete(key); + } +} + interface WorkspaceArchiveClient { archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>; }