mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-06 08:24:46 +00:00
feat(app): archive a workspace from its sidebar row and undo it
Hovering a workspace row on desktop shows an archive button next to the row menu. Archiving shows a toast with Undo and a Cmd/Ctrl+Z shortcut so a mis-click costs one keystroke instead of a trip through History. The daemon serializes archive and undo per workspace across every connection. An undo that lands while an archive is still tearing down aborts it at the next checkpoint and restores only the agents that archive took down; deleting the worktree directory is the point of no return, after which undo recreates the worktree.
This commit is contained in:
@@ -259,6 +259,24 @@ archived workspace. History navigation must not infer workspace lifecycle from `
|
||||
or mutate either lifecycle. The workspace route asks the daemon for authoritative recovery state;
|
||||
only the route's explicit Unarchive or Restore action changes the archived workspace.
|
||||
|
||||
Workspace archive is undoable from the archived toast, or with Cmd/Ctrl+Z, while the toast is up.
|
||||
The daemon runs one archive lane per workspace, shared by every connection
|
||||
(`packages/server/src/server/workspace-archive-operations.ts`):
|
||||
|
||||
| A request arrives while | Result |
|
||||
| ------------------------ | --------------------------------------------------------- |
|
||||
| an archive runs: archive | joins the running archive |
|
||||
| an archive runs: undo | aborts the archive, waits for it to settle, then restores |
|
||||
| an undo runs: archive | waits for the undo, then archives |
|
||||
| an undo runs: undo | joins the running undo |
|
||||
|
||||
An aborted archive stops at its next checkpoint and reports `canceled`; the undo unarchives only
|
||||
the agents that archive itself archived. Deleting the worktree directory is the point of no
|
||||
return: an undo after it recreates the worktree through workspace recovery. The client shows or
|
||||
hides the row by the latest local intent, so a late remove or upsert from a superseded request
|
||||
does not flip it back. Tabs and layout are purged only once the undo window closes with the
|
||||
archive committed.
|
||||
|
||||
History navigation opens the selected agent without changing either archive state. Workspace
|
||||
**Restore** recovers only the workspace; the selected archived agent stays open with its callout.
|
||||
The agent's **Unarchive** runs the provider's native unarchive hook before interactive resume and
|
||||
|
||||
@@ -84,3 +84,10 @@ its DOM-derived scope.
|
||||
Escape interrupts an agent only in the message input or an unclaimed surface.
|
||||
A focused terminal excludes that binding. The source leaves terminal Escape alone;
|
||||
terminal Escape/Ctrl forwarding is a separate feature.
|
||||
|
||||
## Keys shared with text editing
|
||||
|
||||
A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for
|
||||
workspace archive undo, declares `editable: false` and registers its handler with
|
||||
`isActive` true only while it has work. An inactive handler leaves the key
|
||||
unhandled, so the pipeline skips `preventDefault` and the platform's own undo runs.
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
archiveWorkspaceFromDaemon,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
createWorktreeViaDaemon,
|
||||
openProjectViaDaemon,
|
||||
} from "../support/helpers/new-workspace";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { expectWorkspaceAbsentFromSidebar } from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
waitForSidebarHydration,
|
||||
waitForWorkspaceInSidebar,
|
||||
} from "../support/helpers/workspace-ui";
|
||||
|
||||
const UNDO_SHORTCUT = process.platform === "darwin" ? "Meta+Z" : "Control+Z";
|
||||
|
||||
function workspaceRow(page: Page, workspaceId: string) {
|
||||
return page.getByTestId(`sidebar-workspace-row-${getServerId()}:${workspaceId}`);
|
||||
}
|
||||
|
||||
function archiveButton(page: Page, workspaceId: string) {
|
||||
return page.getByTestId(`sidebar-workspace-archive-button-${getServerId()}:${workspaceId}`);
|
||||
}
|
||||
|
||||
async function titleWidth(page: Page, workspaceId: string): Promise<number> {
|
||||
const box = await page
|
||||
.getByTestId(`sidebar-workspace-title-${getServerId()}:${workspaceId}`)
|
||||
.boundingBox();
|
||||
if (!box) throw new Error(`Title of ${workspaceId} is not laid out`);
|
||||
return box.width;
|
||||
}
|
||||
|
||||
test.describe("Workspace archive undo", () => {
|
||||
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
|
||||
let tempRepo: { path: string; cleanup: () => Promise<void> };
|
||||
const worktreeDirectories = new Set<string>();
|
||||
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
test.beforeEach(async () => {
|
||||
client = await connectNewWorkspaceDaemonClient();
|
||||
tempRepo = await createTempGitRepo("archive-undo-");
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
for (const directory of worktreeDirectories) {
|
||||
await archiveWorkspaceFromDaemon(client, directory).catch(() => undefined);
|
||||
}
|
||||
worktreeDirectories.clear();
|
||||
await client?.close().catch(() => undefined);
|
||||
await tempRepo?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
async function activeWorkspaceIds(): Promise<string[]> {
|
||||
const { entries } = await client.fetchWorkspaces();
|
||||
return entries.map((entry) => entry.id);
|
||||
}
|
||||
|
||||
async function seedWorktree(page: Page, slug: string) {
|
||||
await openProjectViaDaemon(client, tempRepo.path);
|
||||
const worktree = await createWorktreeViaDaemon(client, {
|
||||
cwd: tempRepo.path,
|
||||
slug: `${slug}-${Date.now()}`,
|
||||
});
|
||||
worktreeDirectories.add(worktree.workspaceDirectory);
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await waitForWorkspaceInSidebar(page, {
|
||||
serverId: getServerId(),
|
||||
workspaceId: worktree.workspaceId,
|
||||
});
|
||||
return worktree;
|
||||
}
|
||||
|
||||
test("the hover archive button overlays the title instead of narrowing it", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-button-overlay");
|
||||
const row = workspaceRow(page, worktree.workspaceId);
|
||||
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(archiveButton(page, worktree.workspaceId)).toHaveCount(0);
|
||||
const restingWidth = await titleWidth(page, worktree.workspaceId);
|
||||
|
||||
await row.hover();
|
||||
await expect(archiveButton(page, worktree.workspaceId)).toBeVisible();
|
||||
await expect(page.getByTestId("sidebar-workspace-trailing-scrim")).toBeVisible();
|
||||
expect(await titleWidth(page, worktree.workspaceId)).toBe(restingWidth);
|
||||
|
||||
const kebab = page.getByTestId(
|
||||
`sidebar-workspace-kebab-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
const [buttonBox, kebabBox] = await Promise.all([
|
||||
archiveButton(page, worktree.workspaceId).boundingBox(),
|
||||
kebab.boundingBox(),
|
||||
]);
|
||||
expect(buttonBox && kebabBox && buttonBox.x + buttonBox.width <= kebabBox.x).toBe(true);
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+Z right after archiving keeps the worktree", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-shortcut");
|
||||
|
||||
page.once("dialog", (dialog) => void dialog.accept());
|
||||
await workspaceRow(page, worktree.workspaceId).hover();
|
||||
await archiveButton(page, worktree.workspaceId).click();
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
await expect(page.getByTestId("workspace-archived-toast-undo")).toBeVisible();
|
||||
|
||||
await page.keyboard.press(UNDO_SHORTCUT);
|
||||
|
||||
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
|
||||
await expect(page.getByTestId("workspace-archived-toast-undo")).toHaveCount(0);
|
||||
await expect.poll(activeWorkspaceIds).toContain(worktree.workspaceId);
|
||||
expect(existsSync(worktree.workspaceDirectory)).toBe(true);
|
||||
// A late remove from the canceled archive must not take the row back out.
|
||||
await page.waitForTimeout(1500);
|
||||
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
|
||||
});
|
||||
|
||||
test("Undo after the worktree was removed recreates it", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-recreate");
|
||||
|
||||
page.once("dialog", (dialog) => void dialog.accept());
|
||||
await workspaceRow(page, worktree.workspaceId).hover();
|
||||
await archiveButton(page, worktree.workspaceId).click();
|
||||
const undo = page.getByTestId("workspace-archived-toast-undo");
|
||||
// Hovering the toast holds it, and with it the undo, open while the archive finishes.
|
||||
await undo.hover();
|
||||
await expect
|
||||
.poll(() => existsSync(worktree.workspaceDirectory), { timeout: 30_000 })
|
||||
.toBe(false);
|
||||
|
||||
await undo.click();
|
||||
|
||||
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 30_000 });
|
||||
await expect
|
||||
.poll(() => existsSync(worktree.workspaceDirectory), { timeout: 30_000 })
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-none");
|
||||
|
||||
await page.keyboard.press(UNDO_SHORTCUT);
|
||||
|
||||
await expect(page.getByTestId("workspace-archived-toast-undo")).toHaveCount(0);
|
||||
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -55,6 +55,7 @@ import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
|
||||
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
|
||||
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
|
||||
import { ProviderSettingsHost } from "@/components/provider-settings-host";
|
||||
import { WorkspaceSetupDialog } from "@/components/workspace-setup-dialog";
|
||||
@@ -557,6 +558,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<PluginCommandCenterActions />
|
||||
<WorkspacePinShortcutHandler />
|
||||
<WorkspaceRenameHost />
|
||||
<WorkspaceArchiveUndoShortcutHost />
|
||||
<CommandCenter />
|
||||
<AddProjectFlowHost />
|
||||
<HostChooserModal />
|
||||
|
||||
@@ -649,6 +649,7 @@ function WorkspaceRowRightGroup({
|
||||
const {
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -675,6 +676,8 @@ function WorkspaceRowRightGroup({
|
||||
<SidebarWorkspaceTrailingActionOverlay
|
||||
visible={kebab.showKebab}
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
>
|
||||
{onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
|
||||
@@ -872,6 +872,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
const {
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -951,6 +952,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
trailing={trailing}
|
||||
trailingPresentation={trailingPresentation}
|
||||
showKebab={showKebabInSlot}
|
||||
showArchiveButton={showArchiveButton}
|
||||
showScrim={showScrim}
|
||||
reserveSlotWidth={reserveSlotWidth}
|
||||
isPinned={isPinned}
|
||||
@@ -982,6 +984,7 @@ function StatusWorkspaceActionSlot({
|
||||
trailing,
|
||||
trailingPresentation,
|
||||
showKebab,
|
||||
showArchiveButton,
|
||||
showScrim,
|
||||
reserveSlotWidth,
|
||||
isPinned,
|
||||
@@ -1002,6 +1005,7 @@ function StatusWorkspaceActionSlot({
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showScrim: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
isPinned?: boolean;
|
||||
@@ -1026,6 +1030,8 @@ function StatusWorkspaceActionSlot({
|
||||
<SidebarWorkspaceTrailingActionOverlay
|
||||
visible={kebab.showKebab}
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
>
|
||||
{kebab.showKebab && onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type PressableStateCallbackType } from "react-native";
|
||||
import type { PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
Archive,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
PinOff,
|
||||
Tag,
|
||||
} from "lucide-react-native";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { getForgePresentation, normalizeForge } from "@/git/forge";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
@@ -72,6 +73,9 @@ const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedCol
|
||||
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
|
||||
/** Pointer-only, so it is always the kebab's pointer size. */
|
||||
export const ARCHIVE_BUTTON_SIZE = 18;
|
||||
|
||||
const triggerIconProps = densityIconProps("sm", foregroundMutedColorMapping);
|
||||
const triggerIconHoveredProps = densityIconProps("sm", foregroundColorMapping);
|
||||
|
||||
@@ -79,6 +83,33 @@ function renderTriggerIcon({ hovered }: { hovered?: boolean }) {
|
||||
return <ThemedMoreVertical uniProps={hovered ? triggerIconHoveredProps : triggerIconProps} />;
|
||||
}
|
||||
|
||||
function renderArchiveIcon({ hovered }: PressableStateCallbackType & { hovered?: boolean }) {
|
||||
return <ThemedArchive uniProps={hovered ? triggerIconHoveredProps : triggerIconProps} />;
|
||||
}
|
||||
|
||||
/** One-click archive beside the kebab, for pointer rows that reveal it on hover. */
|
||||
export function SidebarWorkspaceArchiveButton({
|
||||
workspaceKey,
|
||||
onArchive,
|
||||
}: {
|
||||
workspaceKey: string;
|
||||
onArchive: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<PressHighlight
|
||||
hitSlop={4}
|
||||
style={archiveButtonStyle}
|
||||
onPress={onArchive}
|
||||
accessibilityRole={isWeb ? undefined : "button"}
|
||||
accessibilityLabel={t("sidebar.workspace.actions.archiveWorkspace")}
|
||||
testID={`sidebar-workspace-archive-button-${workspaceKey}`}
|
||||
>
|
||||
{renderArchiveIcon}
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
export interface SidebarWorkspaceMenuProps {
|
||||
workspaceKey: string;
|
||||
serverId?: string;
|
||||
@@ -437,6 +468,12 @@ function triggerStyle({ hovered = false }: PressableStateCallbackType & { hovere
|
||||
return [styles.trigger, hovered && styles.triggerHovered];
|
||||
}
|
||||
|
||||
function archiveButtonStyle({
|
||||
hovered = false,
|
||||
}: PressableStateCallbackType & { hovered?: boolean }) {
|
||||
return [styles.archiveButton, hovered && styles.triggerHovered];
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
trigger: {
|
||||
// Larger on touch so the kebab is an easy tap target.
|
||||
@@ -455,4 +492,13 @@ const styles = StyleSheet.create((theme) => ({
|
||||
triggerHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
// The kebab's box without its offsets: the archive glyph fills its view box, so it needs
|
||||
// none of the nudging the three dots do. The kebab's marginLeft is the gap between them.
|
||||
archiveButton: {
|
||||
width: ARCHIVE_BUTTON_SIZE,
|
||||
height: ARCHIVE_BUTTON_SIZE,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: 4,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -29,7 +29,11 @@ import { shouldRenderSyncedStatusLoader } from "@/utils/status-loader";
|
||||
import { StatusRing } from "@/components/status-ring";
|
||||
import { resolveSidebarWorkspacePrimaryLabel } from "@/components/sidebar/sidebar-workspace-title";
|
||||
import { DensityIcon } from "@/components/ui/density-icon";
|
||||
import { TrailingActionScrim } from "@/components/ui/trailing-action-scrim";
|
||||
import { SCRIM_WIDTH, TrailingActionScrim } from "@/components/ui/trailing-action-scrim";
|
||||
import {
|
||||
ARCHIVE_BUTTON_SIZE,
|
||||
SidebarWorkspaceArchiveButton,
|
||||
} from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { useWorkspaceLabelDefinitions } from "@/workspace-labels";
|
||||
|
||||
const needsInputColorMapping = (theme: Theme) => ({
|
||||
@@ -156,7 +160,11 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
)}
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
<Text style={workspaceBranchTextStyle} numberOfLines={1}>
|
||||
<Text
|
||||
style={workspaceBranchTextStyle}
|
||||
numberOfLines={1}
|
||||
testID={`sidebar-workspace-title-${workspace.workspaceKey}`}
|
||||
>
|
||||
{workspaceLabel}
|
||||
</Text>
|
||||
<View style={sidebarWorkspaceRowStyles.rowRight}>{children}</View>
|
||||
@@ -330,6 +338,8 @@ export const sidebarWorkspaceRowStyles = StyleSheet.create((theme) => ({
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -370,6 +380,7 @@ export function resolveTrailingActionVisibility({
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showScrim: boolean;
|
||||
renderSlot: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
@@ -384,6 +395,9 @@ export function resolveTrailingActionVisibility({
|
||||
return {
|
||||
trailingPresentation,
|
||||
showKebab,
|
||||
// One-click archive is a pointer affordance: on touch it would sit a few pixels from the
|
||||
// kebab and turn a miss into an archive.
|
||||
showArchiveButton: showKebab && isHovered && !isTouchPlatform,
|
||||
// The scrim paints the row's own hover background, so it can only be drawn on a hovered
|
||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||
// touch, which shows the kebab without ever hovering, never gets one.
|
||||
@@ -432,23 +446,46 @@ export function SidebarWorkspaceTrailingActionBase({
|
||||
);
|
||||
}
|
||||
|
||||
// The archive button plus the kebab's marginLeft, which is the gap between them.
|
||||
const ARCHIVE_BUTTON_SCRIM_WIDTH = ARCHIVE_BUTTON_SIZE + 2;
|
||||
|
||||
export function SidebarWorkspaceTrailingActionOverlay({
|
||||
visible,
|
||||
scrimBackdrop,
|
||||
workspaceKey,
|
||||
onArchiveButtonPress,
|
||||
children,
|
||||
}: {
|
||||
visible: boolean;
|
||||
/** Fade the row into the kebab when something (the diff stat) is still rendered behind it. */
|
||||
scrimBackdrop?: SidebarSurfaceBackdrop;
|
||||
workspaceKey: string;
|
||||
/**
|
||||
* Shows the archive button left of the kebab. It overlays the title like the kebab does, so
|
||||
* the scrim widens to cover it rather than the slot reserving its width.
|
||||
*/
|
||||
onArchiveButtonPress?: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
if (!visible || !children) return null;
|
||||
return (
|
||||
<>
|
||||
{scrimBackdrop ? (
|
||||
<TrailingActionScrim backdrop={scrimBackdrop} testID="sidebar-workspace-trailing-scrim" />
|
||||
<TrailingActionScrim
|
||||
backdrop={scrimBackdrop}
|
||||
width={onArchiveButtonPress ? SCRIM_WIDTH + ARCHIVE_BUTTON_SCRIM_WIDTH : SCRIM_WIDTH}
|
||||
testID="sidebar-workspace-trailing-scrim"
|
||||
/>
|
||||
) : null}
|
||||
<View style={sidebarWorkspaceRowStyles.trailingActionOverlay}>{children}</View>
|
||||
<View style={sidebarWorkspaceRowStyles.trailingActionOverlay}>
|
||||
{onArchiveButtonPress ? (
|
||||
<SidebarWorkspaceArchiveButton
|
||||
workspaceKey={workspaceKey}
|
||||
onArchive={onArchiveButtonPress}
|
||||
/>
|
||||
) : null}
|
||||
{children}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -404,6 +404,7 @@ function WorkspaceRowTrailingActions({
|
||||
const {
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -430,6 +431,8 @@ function WorkspaceRowTrailingActions({
|
||||
<SidebarWorkspaceTrailingActionOverlay
|
||||
visible={kebab.showKebab}
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
>
|
||||
{onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
|
||||
@@ -32,4 +32,25 @@ describe("useToastHost", () => {
|
||||
act(() => dismissUploading());
|
||||
expect(result.current.toast?.content).toBe("Image uploaded");
|
||||
});
|
||||
|
||||
it("tells a toast when it leaves the screen, once, however it leaves", () => {
|
||||
const { result } = renderHook(() => useToastHost());
|
||||
const left: string[] = [];
|
||||
|
||||
let dismissFirst = () => {};
|
||||
act(() => {
|
||||
dismissFirst = result.current.api.show("Archived", {
|
||||
durationMs: null,
|
||||
onDismiss: () => left.push("replaced"),
|
||||
});
|
||||
});
|
||||
act(() => {
|
||||
result.current.api.show("Copied", { onDismiss: () => left.push("dismissed") });
|
||||
});
|
||||
act(() => dismissFirst());
|
||||
act(() => result.current.dismiss());
|
||||
act(() => result.current.dismiss());
|
||||
|
||||
expect(left).toEqual(["replaced", "dismissed"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,6 +35,8 @@ export interface ToastShowOptions {
|
||||
durationMs?: number | null;
|
||||
nativeAndroid?: boolean;
|
||||
testID?: string;
|
||||
/** Runs once when this toast leaves the screen: timed out, dismissed, or replaced. */
|
||||
onDismiss?: () => void;
|
||||
}
|
||||
|
||||
export interface ToastState {
|
||||
@@ -45,6 +47,7 @@ export interface ToastState {
|
||||
variant: ToastVariant;
|
||||
durationMs: number | null;
|
||||
testID?: string;
|
||||
onDismiss?: () => void;
|
||||
}
|
||||
|
||||
/** Dismisses the toast it was returned for; a no-op once another toast replaced it. */
|
||||
@@ -78,40 +81,56 @@ export function useToastHost(): {
|
||||
dismiss: () => void;
|
||||
} {
|
||||
const { t } = useTranslation();
|
||||
const [toast, setToast] = useState<ToastState | null>(null);
|
||||
const [toast, setToastState] = useState<ToastState | null>(null);
|
||||
const toastRef = useRef<ToastState | null>(null);
|
||||
const idRef = useRef(0);
|
||||
|
||||
const show = useCallback((content: ReactNode, options?: ToastShowOptions): DismissToast => {
|
||||
const nativeMessage = typeof content === "string" ? content.trim() : null;
|
||||
if (!content || nativeMessage === "") {
|
||||
return noopDismiss;
|
||||
}
|
||||
|
||||
const variant = options?.variant ?? "default";
|
||||
const durationMs = options?.durationMs === undefined ? DEFAULT_DURATION_MS : options.durationMs;
|
||||
const nativeAndroid = options?.nativeAndroid ?? false;
|
||||
|
||||
if (Platform.OS === "android" && nativeAndroid && nativeMessage) {
|
||||
const duration =
|
||||
durationMs !== null && durationMs <= 2500 ? ToastAndroid.SHORT : ToastAndroid.LONG;
|
||||
ToastAndroid.showWithGravity(nativeMessage, duration, ToastAndroid.TOP);
|
||||
return noopDismiss;
|
||||
}
|
||||
|
||||
idRef.current += 1;
|
||||
const id = idRef.current;
|
||||
setToast({
|
||||
id,
|
||||
content,
|
||||
nativeMessage,
|
||||
icon: options?.icon,
|
||||
variant,
|
||||
durationMs,
|
||||
testID: options?.testID,
|
||||
});
|
||||
return () => setToast((current) => (current?.id === id ? null : current));
|
||||
const setToast = useCallback((next: ToastState | null) => {
|
||||
const previous = toastRef.current;
|
||||
if (previous === next) return;
|
||||
toastRef.current = next;
|
||||
setToastState(next);
|
||||
previous?.onDismiss?.();
|
||||
}, []);
|
||||
|
||||
const show = useCallback(
|
||||
(content: ReactNode, options?: ToastShowOptions): DismissToast => {
|
||||
const nativeMessage = typeof content === "string" ? content.trim() : null;
|
||||
if (!content || nativeMessage === "") {
|
||||
return noopDismiss;
|
||||
}
|
||||
|
||||
const variant = options?.variant ?? "default";
|
||||
const durationMs =
|
||||
options?.durationMs === undefined ? DEFAULT_DURATION_MS : options.durationMs;
|
||||
const nativeAndroid = options?.nativeAndroid ?? false;
|
||||
|
||||
if (Platform.OS === "android" && nativeAndroid && nativeMessage) {
|
||||
const duration =
|
||||
durationMs !== null && durationMs <= 2500 ? ToastAndroid.SHORT : ToastAndroid.LONG;
|
||||
ToastAndroid.showWithGravity(nativeMessage, duration, ToastAndroid.TOP);
|
||||
return noopDismiss;
|
||||
}
|
||||
|
||||
idRef.current += 1;
|
||||
const id = idRef.current;
|
||||
setToast({
|
||||
id,
|
||||
content,
|
||||
nativeMessage,
|
||||
icon: options?.icon,
|
||||
variant,
|
||||
durationMs,
|
||||
testID: options?.testID,
|
||||
onDismiss: options?.onDismiss,
|
||||
});
|
||||
return () => {
|
||||
if (toastRef.current?.id === id) setToast(null);
|
||||
};
|
||||
},
|
||||
[setToast],
|
||||
);
|
||||
|
||||
const api = useMemo<ToastApi>(
|
||||
() => ({
|
||||
show,
|
||||
@@ -127,7 +146,7 @@ export function useToastHost(): {
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
setToast(null);
|
||||
}, []);
|
||||
}, [setToast]);
|
||||
|
||||
return { api, toast, dismiss };
|
||||
}
|
||||
|
||||
@@ -6,9 +6,18 @@ import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
export const SCRIM_WIDTH = 48;
|
||||
const SCRIM_SOLID_OFFSET = "55%";
|
||||
// The fade is a fixed length so a wider scrim only adds solid surface under its actions.
|
||||
const SCRIM_FADE_WIDTH = SCRIM_WIDTH * 0.55;
|
||||
|
||||
function TrailingActionScrimSvg({ gradientId, color }: { gradientId: string; color: string }) {
|
||||
function TrailingActionScrimSvg({
|
||||
gradientId,
|
||||
color,
|
||||
solidOffset,
|
||||
}: {
|
||||
gradientId: string;
|
||||
color: string;
|
||||
solidOffset: string;
|
||||
}) {
|
||||
return (
|
||||
<Svg width="100%" height="100%" preserveAspectRatio="none">
|
||||
<Defs>
|
||||
@@ -16,7 +25,7 @@ function TrailingActionScrimSvg({ gradientId, color }: { gradientId: string; col
|
||||
{/* Vary opacity rather than interpolating toward `transparent`, which crosses black in
|
||||
some engines and leaves a grey fringe. */}
|
||||
<Stop offset="0%" stopColor={color} stopOpacity={0} />
|
||||
<Stop offset={SCRIM_SOLID_OFFSET} stopColor={color} stopOpacity={1} />
|
||||
<Stop offset={solidOffset} stopColor={color} stopOpacity={1} />
|
||||
<Stop offset="100%" stopColor={color} stopOpacity={1} />
|
||||
</SvgLinearGradient>
|
||||
</Defs>
|
||||
@@ -39,17 +48,22 @@ const backdropColorMappings: Record<SurfaceBackdrop, (theme: Theme) => { color:
|
||||
/** Fades trailing content into the surface beneath an absolutely overlaid action. */
|
||||
export function TrailingActionScrim({
|
||||
backdrop,
|
||||
width = SCRIM_WIDTH,
|
||||
testID,
|
||||
}: {
|
||||
backdrop: SurfaceBackdrop;
|
||||
/** Covers more than one trailing action; the fade keeps its length. */
|
||||
width?: number;
|
||||
testID?: string;
|
||||
}) {
|
||||
// React-generated ids contain characters that are invalid inside SVG fragment references.
|
||||
const gradientId = `trailing-action-scrim-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
|
||||
const solidOffset = `${Math.round((SCRIM_FADE_WIDTH / width) * 100)}%`;
|
||||
return (
|
||||
<View style={styles.scrim} pointerEvents="none" testID={testID}>
|
||||
<View style={styles.scrim(width)} pointerEvents="none" testID={testID}>
|
||||
<ThemedTrailingActionScrimSvg
|
||||
gradientId={gradientId}
|
||||
solidOffset={solidOffset}
|
||||
uniProps={backdropColorMappings[backdrop]}
|
||||
/>
|
||||
</View>
|
||||
@@ -57,11 +71,11 @@ export function TrailingActionScrim({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
scrim: {
|
||||
scrim: (width: number) => ({
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
width: SCRIM_WIDTH,
|
||||
},
|
||||
width,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -2,9 +2,12 @@ import { describe, expect, it } from "vitest";
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import {
|
||||
clearWorkspaceArchivePending,
|
||||
clearWorkspaceArchiveUndoPending,
|
||||
isWorkspaceArchivePending,
|
||||
markWorkspaceArchivePending,
|
||||
markWorkspaceArchiveUndoPending,
|
||||
shouldSuppressWorkspaceForLocalArchive,
|
||||
shouldSuppressWorkspaceRemovalForLocalUndo,
|
||||
} from "@/contexts/session-workspace-upserts";
|
||||
|
||||
const baseWorkspace: WorkspaceDescriptor = {
|
||||
@@ -116,3 +119,36 @@ describe("workspace archive pending suppression", () => {
|
||||
clearWorkspaceArchivePending({ serverId: "server-1", workspaceId: "/repo/worktree" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace archive undo intent", () => {
|
||||
const target = { serverId: "server-1", workspaceId: "/repo/worktree" };
|
||||
|
||||
it("lets host upserts through and holds host removes while an undo is pending", () => {
|
||||
markWorkspaceArchivePending(target);
|
||||
markWorkspaceArchiveUndoPending(target);
|
||||
|
||||
expect({
|
||||
upsertSuppressed: shouldSuppressWorkspaceForLocalArchive({
|
||||
serverId: target.serverId,
|
||||
workspace: workspace({ archivingAt: null }),
|
||||
}),
|
||||
removeSuppressed: shouldSuppressWorkspaceRemovalForLocalUndo(target),
|
||||
}).toEqual({ upsertSuppressed: false, removeSuppressed: true });
|
||||
|
||||
clearWorkspaceArchiveUndoPending(target);
|
||||
expect(shouldSuppressWorkspaceRemovalForLocalUndo(target)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a newer intent when the request behind an older one settles late", () => {
|
||||
markWorkspaceArchivePending(target);
|
||||
markWorkspaceArchiveUndoPending(target);
|
||||
clearWorkspaceArchivePending(target);
|
||||
expect(shouldSuppressWorkspaceRemovalForLocalUndo(target)).toBe(true);
|
||||
|
||||
markWorkspaceArchivePending(target);
|
||||
clearWorkspaceArchiveUndoPending(target);
|
||||
expect(isWorkspaceArchivePending(target)).toBe(true);
|
||||
|
||||
clearWorkspaceArchivePending(target);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,77 +1,102 @@
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
|
||||
|
||||
interface PendingWorkspaceArchive {
|
||||
workspaceId: string;
|
||||
/**
|
||||
* What this client last asked the host to do with a workspace, while the host catches up.
|
||||
*
|
||||
* - `archive`: the row is hidden; host upserts for it are dropped until its remove arrives.
|
||||
* - `undo`: the row is back; host removes for it are dropped until the undo response arrives.
|
||||
*
|
||||
* Only the request that set an intent may clear it, so a late response for an earlier
|
||||
* request never clears the intent of a newer one.
|
||||
*/
|
||||
type LocalWorkspaceArchiveIntent = "archive" | "undo";
|
||||
|
||||
const intentsByServer = new Map<string, Map<string, LocalWorkspaceArchiveIntent>>();
|
||||
|
||||
interface WorkspaceIntentTarget {
|
||||
serverId: string;
|
||||
workspaceId?: string | null;
|
||||
}
|
||||
|
||||
const pendingWorkspaceArchivesByServer = new Map<string, Map<string, PendingWorkspaceArchive>>();
|
||||
function resolveTarget(
|
||||
input: WorkspaceIntentTarget,
|
||||
): { serverId: string; workspaceId: string } | null {
|
||||
const serverId = input.serverId.trim();
|
||||
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
|
||||
if (!serverId || !workspaceId) return null;
|
||||
return { serverId, workspaceId };
|
||||
}
|
||||
|
||||
function pendingArchiveKey(input: { serverId: string; workspaceId: string }): string {
|
||||
return `${input.serverId.trim()}::${input.workspaceId.trim()}`;
|
||||
function readIntent(input: WorkspaceIntentTarget): LocalWorkspaceArchiveIntent | null {
|
||||
const target = resolveTarget(input);
|
||||
if (!target) return null;
|
||||
return intentsByServer.get(target.serverId)?.get(target.workspaceId) ?? null;
|
||||
}
|
||||
|
||||
function setIntent(input: WorkspaceIntentTarget, intent: LocalWorkspaceArchiveIntent): void {
|
||||
const target = resolveTarget(input);
|
||||
if (!target) return;
|
||||
const intents = intentsByServer.get(target.serverId) ?? new Map();
|
||||
intents.set(target.workspaceId, intent);
|
||||
intentsByServer.set(target.serverId, intents);
|
||||
}
|
||||
|
||||
function clearIntent(input: WorkspaceIntentTarget, intent: LocalWorkspaceArchiveIntent): void {
|
||||
const target = resolveTarget(input);
|
||||
if (!target) return;
|
||||
const intents = intentsByServer.get(target.serverId);
|
||||
if (intents?.get(target.workspaceId) !== intent) return;
|
||||
intents.delete(target.workspaceId);
|
||||
if (intents.size === 0) intentsByServer.delete(target.serverId);
|
||||
}
|
||||
|
||||
export function markWorkspaceArchivePending(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): void {
|
||||
const serverId = input.serverId.trim();
|
||||
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
|
||||
if (!serverId || !workspaceId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const archives = pendingWorkspaceArchivesByServer.get(serverId) ?? new Map();
|
||||
archives.set(pendingArchiveKey({ serverId, workspaceId }), {
|
||||
workspaceId,
|
||||
});
|
||||
pendingWorkspaceArchivesByServer.set(serverId, archives);
|
||||
setIntent(input, "archive");
|
||||
}
|
||||
|
||||
export function clearWorkspaceArchivePending(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): void {
|
||||
const serverId = input.serverId.trim();
|
||||
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
|
||||
if (!serverId || !workspaceId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const archives = pendingWorkspaceArchivesByServer.get(serverId);
|
||||
if (!archives) {
|
||||
return;
|
||||
}
|
||||
archives.delete(pendingArchiveKey({ serverId, workspaceId }));
|
||||
if (archives.size === 0) {
|
||||
pendingWorkspaceArchivesByServer.delete(serverId);
|
||||
}
|
||||
clearIntent(input, "archive");
|
||||
}
|
||||
|
||||
export function isWorkspaceArchivePending(input: {
|
||||
export function isWorkspaceArchivePending(input: WorkspaceIntentTarget): boolean {
|
||||
return readIntent(input) === "archive";
|
||||
}
|
||||
|
||||
export function markWorkspaceArchiveUndoPending(input: {
|
||||
serverId: string;
|
||||
workspaceId?: string | null;
|
||||
}): boolean {
|
||||
const serverId = input.serverId.trim();
|
||||
if (!serverId) {
|
||||
return false;
|
||||
}
|
||||
workspaceId: string;
|
||||
}): void {
|
||||
setIntent(input, "undo");
|
||||
}
|
||||
|
||||
const archives = pendingWorkspaceArchivesByServer.get(serverId);
|
||||
if (!archives) {
|
||||
return false;
|
||||
}
|
||||
export function clearWorkspaceArchiveUndoPending(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): void {
|
||||
clearIntent(input, "undo");
|
||||
}
|
||||
|
||||
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
|
||||
return Boolean(workspaceId && archives.has(pendingArchiveKey({ serverId, workspaceId })));
|
||||
export function isWorkspaceArchiveUndoPending(input: WorkspaceIntentTarget): boolean {
|
||||
return readIntent(input) === "undo";
|
||||
}
|
||||
|
||||
export function shouldSuppressWorkspaceForLocalArchive(input: {
|
||||
serverId: string;
|
||||
workspace: WorkspaceDescriptor;
|
||||
}): boolean {
|
||||
return isWorkspaceArchivePending({
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspace.id,
|
||||
});
|
||||
return isWorkspaceArchivePending({ serverId: input.serverId, workspaceId: input.workspace.id });
|
||||
}
|
||||
|
||||
export function shouldSuppressWorkspaceRemovalForLocalUndo(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): boolean {
|
||||
return isWorkspaceArchiveUndoPending(input);
|
||||
}
|
||||
|
||||
@@ -1341,6 +1341,9 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
hideFailed: "فشل في إخفاء مساحة العمل",
|
||||
archiveFailed: "فشل في أرشفة مساحة العمل",
|
||||
archived: "تمت أرشفة مساحة العمل",
|
||||
undoArchive: "تراجع",
|
||||
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1349,6 +1349,9 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
hideFailed: "Failed to hide workspace",
|
||||
archiveFailed: "Failed to archive workspace",
|
||||
archived: "Workspace archived",
|
||||
undoArchive: "Undo",
|
||||
undoArchiveFailed: "Couldn't undo the archive",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1377,6 +1377,9 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
hideFailed: "No se pudo ocultar el espacio de trabajo",
|
||||
archiveFailed: "No se pudo archivar el espacio de trabajo",
|
||||
archived: "Espacio de trabajo archivado",
|
||||
undoArchive: "Deshacer",
|
||||
undoArchiveFailed: "No se pudo deshacer el archivado",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1371,6 +1371,9 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
hideFailed: "Impossible de masquer l’espace de travail",
|
||||
archiveFailed: "Impossible d’archiver l’espace de travail",
|
||||
archived: "Espace de travail archivé",
|
||||
undoArchive: "Annuler",
|
||||
undoArchiveFailed: "Impossible d’annuler l’archivage",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1355,6 +1355,9 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
hideFailed: "ワークスペースの非表示に失敗しました",
|
||||
archiveFailed: "ワークスペースのアーカイブに失敗しました",
|
||||
archived: "ワークスペースをアーカイブしました",
|
||||
undoArchive: "元に戻す",
|
||||
undoArchiveFailed: "アーカイブを元に戻せませんでした",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1348,6 +1348,9 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
hideFailed: "워크스페이스를 숨기지 못했습니다",
|
||||
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
|
||||
archived: "워크스페이스를 보관했습니다",
|
||||
undoArchive: "실행 취소",
|
||||
undoArchiveFailed: "보관을 취소하지 못했습니다",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1367,6 +1367,9 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
hideFailed: "Falha ao ocultar workspace",
|
||||
archiveFailed: "Falha ao arquivar workspace",
|
||||
archived: "Workspace arquivado",
|
||||
undoArchive: "Desfazer",
|
||||
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1359,6 +1359,9 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
hideFailed: "Не удалось скрыть рабочее пространство",
|
||||
archiveFailed: "Не удалось архивировать рабочее пространство",
|
||||
archived: "Рабочее пространство архивировано",
|
||||
undoArchive: "Отменить",
|
||||
undoArchiveFailed: "Не удалось отменить архивацию",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1330,6 +1330,9 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
hideFailed: "隐藏 workspace 失败",
|
||||
archiveFailed: "归档工作区失败",
|
||||
archived: "工作区已归档",
|
||||
undoArchive: "撤销",
|
||||
undoArchiveFailed: "无法撤销归档",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -52,6 +52,7 @@ export type KeyboardActionId =
|
||||
| "workspace.project.pick"
|
||||
| "worktree.new"
|
||||
| "workspace.archive"
|
||||
| "workspace.archive.undo"
|
||||
| "workspace.pin"
|
||||
| "view.toggle.focus"
|
||||
| "theme.cycle"
|
||||
|
||||
@@ -51,6 +51,7 @@ export type KeyboardActionId =
|
||||
| "workspace.project.pick"
|
||||
| "worktree.new"
|
||||
| "workspace.archive"
|
||||
| "workspace.archive.undo"
|
||||
| "workspace.pin"
|
||||
// Command-center only: no keybind, so these are absent from route-shortcut.ts.
|
||||
| "workspace.rename"
|
||||
@@ -109,6 +110,7 @@ export type KeyboardActionDefinition =
|
||||
| { id: "workspace.project.pick"; scope: KeyboardActionScope }
|
||||
| { id: "worktree.new"; scope: KeyboardActionScope }
|
||||
| { id: "workspace.archive"; scope: KeyboardActionScope }
|
||||
| { id: "workspace.archive.undo"; scope: KeyboardActionScope }
|
||||
| { id: "workspace.pin"; scope: KeyboardActionScope }
|
||||
| { id: "workspace.rename"; scope: KeyboardActionScope }
|
||||
| { id: "workspace.setup.show"; scope: KeyboardActionScope };
|
||||
|
||||
@@ -408,6 +408,25 @@ describe("keyboard-shortcuts", () => {
|
||||
},
|
||||
);
|
||||
|
||||
describe("undo archive workspace", () => {
|
||||
it.each([
|
||||
{ isMac: true, event: { key: "z", code: "KeyZ", metaKey: true } },
|
||||
{ isMac: false, event: { key: "z", code: "KeyZ", ctrlKey: true } },
|
||||
])("routes Cmd/Ctrl+Z outside text and terminals (mac: $isMac)", ({ isMac, event }) => {
|
||||
expectShortcutResolution({ event, context: { isMac }, action: "workspace.archive.undo" });
|
||||
});
|
||||
|
||||
it.each(["editable", "message-input", "terminal"] as const)(
|
||||
"leaves Cmd+Z to the focused %s",
|
||||
(focusScope) => {
|
||||
expectNoShortcutResolution({
|
||||
event: { key: "z", code: "KeyZ", metaKey: true },
|
||||
context: { isMac: true, focusScope },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves Escape to an editable field", () => {
|
||||
expectNoShortcutResolution({
|
||||
event: { key: "Escape", code: "Escape" },
|
||||
|
||||
@@ -169,6 +169,7 @@ export const SHORTCUT_HELP_ROW_ORDER: Record<ShortcutSectionId, readonly string[
|
||||
"workspace-next",
|
||||
"pin-workspace",
|
||||
"archive-workspace",
|
||||
"undo-archive-workspace",
|
||||
],
|
||||
"tabs-panes": [
|
||||
"workspace-tab-new",
|
||||
@@ -361,6 +362,31 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
|
||||
},
|
||||
},
|
||||
|
||||
// --- Undo archive workspace ---
|
||||
// Only claims the key while an archive can be undone; otherwise text undo runs as usual.
|
||||
{
|
||||
id: "workspace-archive-undo-cmd-z-mac",
|
||||
action: "workspace.archive.undo",
|
||||
combo: "Cmd+Z",
|
||||
when: { mac: true, commandCenter: false, editable: false, terminal: false },
|
||||
help: {
|
||||
id: "undo-archive-workspace",
|
||||
section: "workspaces",
|
||||
label: "Undo archive workspace",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "workspace-archive-undo-ctrl-z-non-mac",
|
||||
action: "workspace.archive.undo",
|
||||
combo: "Ctrl+Z",
|
||||
when: { mac: false, commandCenter: false, editable: false, terminal: false },
|
||||
help: {
|
||||
id: "undo-archive-workspace",
|
||||
section: "workspaces",
|
||||
label: "Undo archive workspace",
|
||||
},
|
||||
},
|
||||
|
||||
// --- Pin workspace ---
|
||||
{
|
||||
id: "workspace-pin-cmd-shift-p-mac",
|
||||
|
||||
@@ -48,6 +48,7 @@ const PASSTHROUGH_DISPATCH: Record<string, KeyboardActionDefinition> = {
|
||||
"workspace.new": { id: "workspace.new", scope: "sidebar" },
|
||||
"workspace.project.pick": { id: "workspace.project.pick", scope: "workspace" },
|
||||
"workspace.archive": { id: "workspace.archive", scope: "sidebar" },
|
||||
"workspace.archive.undo": { id: "workspace.archive.undo", scope: "global" },
|
||||
"workspace.pin": { id: "workspace.pin", scope: "sidebar" },
|
||||
"worktree.new": { id: "worktree.new", scope: "sidebar" },
|
||||
"workspace.terminal.new": { id: "workspace.terminal.new", scope: "workspace" },
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
} from "@/stores/session-store";
|
||||
import {
|
||||
clearWorkspaceArchivePending,
|
||||
clearWorkspaceArchiveUndoPending,
|
||||
markWorkspaceArchivePending,
|
||||
markWorkspaceArchiveUndoPending,
|
||||
} from "@/contexts/session-workspace-upserts";
|
||||
import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
|
||||
import { WorkspaceDirectoryReplica } from "./workspace-replica";
|
||||
@@ -378,3 +380,26 @@ it("restores a missing workspace after an archive failure without replacing a li
|
||||
store.clearSession(serverId);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a workspace whose archive is being undone when the host reports its removal", () => {
|
||||
const serverId = "workspace-archive-undo";
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, null as unknown as DaemonClient);
|
||||
const replica = new WorkspaceDirectoryReplica(serverId);
|
||||
const restored = normalizeWorkspaceDescriptor(workspace("restored"));
|
||||
|
||||
try {
|
||||
replica.acceptWorkspaces([restored]);
|
||||
markWorkspaceArchiveUndoPending({ serverId, workspaceId: restored.id });
|
||||
|
||||
expect(replica.applyDelta({ kind: "remove", id: restored.id })).toEqual([]);
|
||||
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has(restored.id)).toBe(true);
|
||||
|
||||
clearWorkspaceArchiveUndoPending({ serverId, workspaceId: restored.id });
|
||||
replica.applyDelta({ kind: "remove", id: restored.id });
|
||||
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has(restored.id)).toBe(false);
|
||||
} finally {
|
||||
clearWorkspaceArchiveUndoPending({ serverId, workspaceId: restored.id });
|
||||
store.clearSession(serverId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
|
||||
import {
|
||||
clearWorkspaceArchivePending,
|
||||
shouldSuppressWorkspaceForLocalArchive,
|
||||
shouldSuppressWorkspaceRemovalForLocalUndo,
|
||||
} from "@/contexts/session-workspace-upserts";
|
||||
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
|
||||
import type { DirectoryReplicaMutation } from "@/runtime/replica-cache";
|
||||
@@ -173,6 +174,12 @@ export class WorkspaceDirectoryReplica {
|
||||
kind: "remove";
|
||||
},
|
||||
): DirectoryReplicaMutation[] {
|
||||
// The archive this remove reports is being undone; the host publishes the restored row.
|
||||
if (
|
||||
shouldSuppressWorkspaceRemovalForLocalUndo({ serverId: this.serverId, workspaceId: delta.id })
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
this.deleteWorkspace(delta.id);
|
||||
const mutations: DirectoryReplicaMutation[] = [
|
||||
{ kind: "workspace", type: "delete", id: delta.id },
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
archiveWorkspaceWithUndo,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "./internal/undo-window";
|
||||
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
|
||||
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
|
||||
export function supportsWorkspaceArchiveUndo(serverId: string): boolean {
|
||||
return (
|
||||
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.workspaceArchiveUndo ===
|
||||
true
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { hasUndoableWorkspaceArchive, undoLatestWorkspaceArchive } from "./undo-window";
|
||||
|
||||
const UNDO_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive.undo"];
|
||||
|
||||
/**
|
||||
* Cmd/Ctrl+Z for the archive toast. Mounted once at the app root because the row that started
|
||||
* the archive unmounts as soon as its workspace hides. It claims the key only while an archive
|
||||
* can be undone, so the key falls through to text undo the rest of the time.
|
||||
*/
|
||||
export function WorkspaceArchiveUndoShortcutHost(): null {
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-undo-global",
|
||||
actions: UNDO_ARCHIVE_ACTIONS,
|
||||
enabled: true,
|
||||
priority: 0,
|
||||
isActive: hasUndoableWorkspaceArchive,
|
||||
handle: undoLatestWorkspaceArchive,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ReactNode } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { ToastApi, ToastShowOptions } from "@/components/toast-host";
|
||||
import { clearWorkspaceArchivePending } from "@/contexts/session-workspace-upserts";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { seedSessionHosts } from "@/test/seed-session";
|
||||
import {
|
||||
archiveWorkspaceWithUndo,
|
||||
hasUndoableWorkspaceArchive,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "./undo-window";
|
||||
|
||||
const SERVER_ID = "workspace-archive-undo-window";
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}
|
||||
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function workspace(id: string): WorkspaceDescriptor {
|
||||
return {
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
id,
|
||||
projectId: "project",
|
||||
projectDisplayName: "Project",
|
||||
projectRootPath: "/repo/project",
|
||||
workspaceDirectory: `/repo/project/${id}`,
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: id,
|
||||
status: "done",
|
||||
archivingAt: null,
|
||||
statusEnteredAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** A toast host with one slot, like the app's: a new toast replaces the shown one. */
|
||||
function createToastHost() {
|
||||
let shown: { content: ReactNode; options?: ToastShowOptions; dismiss: () => void } | null = null;
|
||||
const errors: string[] = [];
|
||||
const api: ToastApi = {
|
||||
show: (content, options) => {
|
||||
const previous = shown;
|
||||
const entry = {
|
||||
content,
|
||||
options,
|
||||
dismiss: () => {
|
||||
if (shown !== entry) return;
|
||||
shown = null;
|
||||
options?.onDismiss?.();
|
||||
},
|
||||
};
|
||||
shown = entry;
|
||||
previous?.options?.onDismiss?.();
|
||||
return entry.dismiss;
|
||||
},
|
||||
copied: () => {},
|
||||
error: (message) => {
|
||||
errors.push(message);
|
||||
api.show(message);
|
||||
},
|
||||
};
|
||||
return {
|
||||
api,
|
||||
errors,
|
||||
get shownTestID() {
|
||||
return shown?.options?.testID ?? null;
|
||||
},
|
||||
timeOut: () => shown?.dismiss(),
|
||||
};
|
||||
}
|
||||
|
||||
type ArchivePayload = Awaited<ReturnType<UndoableWorkspaceArchiveClient["archiveWorkspace"]>>;
|
||||
|
||||
function createClient() {
|
||||
const archives = new Map<string, Deferred<ArchivePayload>>();
|
||||
const undos = new Map<string, Deferred<void>>();
|
||||
const client: UndoableWorkspaceArchiveClient = {
|
||||
archiveWorkspace: (workspaceId) => {
|
||||
const response = deferred<ArchivePayload>();
|
||||
archives.set(workspaceId, response);
|
||||
return response.promise;
|
||||
},
|
||||
undoWorkspaceArchive: (workspaceId) => {
|
||||
const response = deferred<void>();
|
||||
undos.set(workspaceId, response);
|
||||
return response.promise;
|
||||
},
|
||||
};
|
||||
return {
|
||||
client,
|
||||
finishArchive: (workspaceId: string, payload: Partial<ArchivePayload> = {}) =>
|
||||
archives.get(workspaceId)?.resolve({ error: null, ...payload }),
|
||||
undoRequested: (workspaceId: string) => undos.has(workspaceId),
|
||||
finishUndo: (workspaceId: string) => undos.get(workspaceId)?.resolve(),
|
||||
failUndo: (workspaceId: string, error: Error) => undos.get(workspaceId)?.reject(error),
|
||||
};
|
||||
}
|
||||
|
||||
function storedWorkspace(id: string): WorkspaceDescriptor | undefined {
|
||||
return useSessionStore.getState().sessions[SERVER_ID]?.workspaces.get(id);
|
||||
}
|
||||
|
||||
function startArchive(input: {
|
||||
host: ReturnType<typeof createClient>;
|
||||
toast: ReturnType<typeof createToastHost>;
|
||||
workspaceId: string;
|
||||
committed: string[];
|
||||
}) {
|
||||
return archiveWorkspaceWithUndo({
|
||||
client: input.host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: input.workspaceId },
|
||||
toast: input.toast.api,
|
||||
onArchiveCommitted: () => input.committed.push(input.workspaceId),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
seedSessionHosts([SERVER_ID]);
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, {} as DaemonClient);
|
||||
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace("a"), workspace("b")]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
undoLatestWorkspaceArchive();
|
||||
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "a" });
|
||||
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "b" });
|
||||
seedSessionHosts([]);
|
||||
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
|
||||
});
|
||||
|
||||
describe("archiveWorkspaceWithUndo", () => {
|
||||
it("commits the archive only once its toast is gone", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed });
|
||||
expect(toast.shownTestID).toBe("workspace-archived-toast");
|
||||
host.finishArchive("a");
|
||||
await archive;
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
toast.timeOut();
|
||||
expect({ committed, undoable: hasUndoableWorkspaceArchive() }).toEqual({
|
||||
committed: ["a"],
|
||||
undoable: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("commits when the archive finishes after its toast already timed out", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed });
|
||||
toast.timeOut();
|
||||
expect(committed).toEqual([]);
|
||||
host.finishArchive("a");
|
||||
await archive;
|
||||
|
||||
expect(committed).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("undo during a running archive brings the row back and never commits", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed });
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({
|
||||
row: storedWorkspace("a"),
|
||||
undoRequested: host.undoRequested("a"),
|
||||
toast: toast.shownTestID,
|
||||
}).toEqual({ row: workspace("a"), undoRequested: true, toast: null });
|
||||
|
||||
host.finishArchive("a", { canceled: true, error: "Workspace archive was undone" });
|
||||
await archive;
|
||||
host.finishUndo("a");
|
||||
toast.timeOut();
|
||||
|
||||
expect({ committed, errors: toast.errors, row: storedWorkspace("a") }).toEqual({
|
||||
committed: [],
|
||||
errors: [],
|
||||
row: workspace("a"),
|
||||
});
|
||||
});
|
||||
|
||||
it("does not claim Cmd+Z when no archive can be undone", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(false);
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
|
||||
host.finishArchive("a");
|
||||
await archive;
|
||||
toast.timeOut();
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(false);
|
||||
expect(host.undoRequested("a")).toBe(false);
|
||||
});
|
||||
|
||||
it("a newer archive takes over undo and commits the older one", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const first = startArchive({ host, toast, workspaceId: "a", committed });
|
||||
host.finishArchive("a");
|
||||
await first;
|
||||
const second = startArchive({ host, toast, workspaceId: "b", committed });
|
||||
expect(committed).toEqual(["a"]);
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
|
||||
undoA: false,
|
||||
undoB: true,
|
||||
});
|
||||
host.finishArchive("b", { canceled: true });
|
||||
await second;
|
||||
});
|
||||
|
||||
it("reports a failed undo and hides the row again", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
|
||||
host.finishArchive("a");
|
||||
await archive;
|
||||
undoLatestWorkspaceArchive();
|
||||
host.failUndo("a", new Error("Branch is gone"));
|
||||
await expect.poll(() => toast.errors).toEqual(["Branch is gone"]);
|
||||
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stays quiet about an archive that failed after the user undid it", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
|
||||
undoLatestWorkspaceArchive();
|
||||
host.finishArchive("a", { error: "registry unavailable" });
|
||||
|
||||
await expect(archive).resolves.toBeUndefined();
|
||||
expect(toast.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a failed archive, closes its toast and puts the row back", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
|
||||
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
|
||||
host.finishArchive("a", { error: "registry unavailable" });
|
||||
|
||||
await expect(archive).rejects.toThrow("registry unavailable");
|
||||
expect({
|
||||
toast: toast.shownTestID,
|
||||
undoable: hasUndoableWorkspaceArchive(),
|
||||
row: storedWorkspace("a"),
|
||||
}).toEqual({ toast: null, undoable: false, row: workspace("a") });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { DismissToast, ToastApi } from "@/components/toast-host";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import {
|
||||
beginOptimisticWorkspaceArchive,
|
||||
undoWorkspaceArchiveOptimistically,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
import { WorkspaceArchivedToast } from "./workspace-archived-toast";
|
||||
|
||||
/** How long the archived toast, and with it the chance to undo, stays up. */
|
||||
export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000;
|
||||
|
||||
export interface UndoableWorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
interface UndoWindowInput {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
toast: ToastApi;
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
onArchiveCommitted: () => void;
|
||||
}
|
||||
|
||||
let latest: UndoWindow | null = null;
|
||||
|
||||
/**
|
||||
* One archive's chance to be undone. It opens when the row hides and closes when its toast
|
||||
* leaves the screen (timeout, replaced by another toast, or undo).
|
||||
*
|
||||
* - `open`: undo is offered.
|
||||
* - `closed`: undo is no longer offered; the archive stands.
|
||||
* - `undone`: the user took the archive back.
|
||||
*/
|
||||
class UndoWindow {
|
||||
phase: "open" | "closed" | "undone" = "open";
|
||||
private archived = false;
|
||||
private readonly dismissToast: DismissToast;
|
||||
|
||||
constructor(private readonly input: UndoWindowInput) {
|
||||
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
|
||||
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
|
||||
testID: "workspace-archived-toast",
|
||||
onDismiss: this.close,
|
||||
});
|
||||
}
|
||||
|
||||
/** The host finished the archive. It commits now if undo is no longer offered. */
|
||||
archiveFinished(): void {
|
||||
this.archived = true;
|
||||
if (this.phase === "closed") this.input.onArchiveCommitted();
|
||||
}
|
||||
|
||||
/** The archive failed on the host, so there is nothing left to undo. */
|
||||
archiveFailed(): void {
|
||||
this.close();
|
||||
this.dismissToast();
|
||||
}
|
||||
|
||||
readonly close = (): void => {
|
||||
if (this.phase !== "open") return;
|
||||
this.phase = "closed";
|
||||
this.release();
|
||||
if (this.archived) this.input.onArchiveCommitted();
|
||||
};
|
||||
|
||||
readonly undo = (): boolean => {
|
||||
if (this.phase !== "open") return false;
|
||||
this.phase = "undone";
|
||||
this.release();
|
||||
this.dismissToast();
|
||||
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
|
||||
this.input.toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: i18n.t("sidebar.workspace.toasts.undoArchiveFailed"),
|
||||
);
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
private release(): void {
|
||||
if (latest === this) latest = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Archives a workspace and offers to undo it until the toast goes away.
|
||||
*
|
||||
* `onArchiveCommitted` runs once the archive both finished on the host and can no longer be
|
||||
* undone, so local state the undo would want back (tabs, layout) survives the window.
|
||||
* Rejects when the archive fails and was not undone; the row is back by then.
|
||||
*/
|
||||
export async function archiveWorkspaceWithUndo(input: {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
toast: ToastApi;
|
||||
onArchiveCommitted: () => void;
|
||||
}): Promise<void> {
|
||||
const archive = beginOptimisticWorkspaceArchive(input);
|
||||
const window = new UndoWindow({ ...input, hidden: archive.hidden });
|
||||
latest = window;
|
||||
|
||||
let outcome: Awaited<typeof archive.done>;
|
||||
try {
|
||||
outcome = await archive.done;
|
||||
} catch (error) {
|
||||
if (window.phase === "undone") return;
|
||||
window.archiveFailed();
|
||||
throw error;
|
||||
}
|
||||
if (outcome === "archived") window.archiveFinished();
|
||||
}
|
||||
|
||||
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
|
||||
export function undoLatestWorkspaceArchive(): boolean {
|
||||
return latest ? latest.undo() : false;
|
||||
}
|
||||
|
||||
export function hasUndoableWorkspaceArchive(): boolean {
|
||||
return latest !== null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
|
||||
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const undoKeys = useShortcutKeys("undo-archive-workspace");
|
||||
const undoShortcut = useMemo(() => (undoKeys ? <Shortcut chord={undoKeys} /> : null), [undoKeys]);
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={onUndo}
|
||||
testID="workspace-archived-toast-undo"
|
||||
trailing={undoShortcut}
|
||||
>
|
||||
{t("sidebar.workspace.toasts.undoArchive")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
message: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
}));
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
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";
|
||||
|
||||
function purgeArchivedWorkspaceState(input: { serverId: string; workspaceId: string }): void {
|
||||
@@ -58,17 +59,22 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return;
|
||||
}
|
||||
const workspace = { serverId, workspaceId };
|
||||
onSetHiding?.(true);
|
||||
try {
|
||||
onArchiveStarted();
|
||||
await archiveWorkspaceOptimistically({
|
||||
client,
|
||||
workspace: {
|
||||
serverId,
|
||||
workspaceId,
|
||||
},
|
||||
});
|
||||
purgeArchivedWorkspaceState({ serverId, workspaceId });
|
||||
if (supportsWorkspaceArchiveUndo(serverId)) {
|
||||
await archiveWorkspaceWithUndo({
|
||||
client,
|
||||
workspace,
|
||||
toast,
|
||||
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
|
||||
});
|
||||
} else {
|
||||
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
|
||||
await archiveWorkspaceOptimistically({ client, workspace });
|
||||
purgeArchivedWorkspaceState(workspace);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
|
||||
|
||||
@@ -4,12 +4,16 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
clearWorkspaceArchivePending,
|
||||
clearWorkspaceArchiveUndoPending,
|
||||
isWorkspaceArchivePending,
|
||||
isWorkspaceArchiveUndoPending,
|
||||
} from "@/contexts/session-workspace-upserts";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
archiveWorkspacesOptimistically,
|
||||
beginOptimisticWorkspaceArchive,
|
||||
undoWorkspaceArchiveOptimistically,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
@@ -21,12 +25,14 @@ type ArchiveWorkspacePayload = Awaited<ReturnType<DaemonClient["archiveWorkspace
|
||||
function archivePayload(input: {
|
||||
workspaceId: string;
|
||||
error?: string | null;
|
||||
canceled?: boolean;
|
||||
}): ArchiveWorkspacePayload {
|
||||
return {
|
||||
requestId: "request",
|
||||
workspaceId: input.workspaceId,
|
||||
archivedAt: null,
|
||||
error: input.error ?? null,
|
||||
...(input.canceled ? { canceled: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,6 +105,7 @@ afterEach(() => {
|
||||
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "workspace-2" });
|
||||
clearWorkspaceArchivePending({ serverId: SECOND_SERVER_ID, workspaceId: "workspace-1" });
|
||||
clearWorkspaceArchivePending({ serverId: SECOND_SERVER_ID, workspaceId: "workspace-2" });
|
||||
clearWorkspaceArchiveUndoPending({ serverId: SERVER_ID, workspaceId: "workspace-1" });
|
||||
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
|
||||
});
|
||||
|
||||
@@ -224,3 +231,87 @@ describe("archiveWorkspacesOptimistically", () => {
|
||||
expect(storedWorkspaceOn(SECOND_SERVER_ID, second.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("undoWorkspaceArchiveOptimistically", () => {
|
||||
it("brings the row back while the host undoes the archive it is still running", async () => {
|
||||
const archived = workspace();
|
||||
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
|
||||
const archiveResponse = deferred<ArchiveWorkspacePayload>();
|
||||
const undoResponse = deferred<void>();
|
||||
const archive = beginOptimisticWorkspaceArchive({
|
||||
client: createClient(async () => archiveResponse.promise),
|
||||
workspace: target(),
|
||||
});
|
||||
|
||||
const undo = undoWorkspaceArchiveOptimistically({
|
||||
client: { undoWorkspaceArchive: async () => undoResponse.promise },
|
||||
workspace: target(),
|
||||
hidden: archive.hidden,
|
||||
});
|
||||
expect(storedWorkspace(archived.id)).toEqual(archived);
|
||||
|
||||
// The host answers the canceled archive before the undo.
|
||||
archiveResponse.resolve(archivePayload({ workspaceId: archived.id, canceled: true }));
|
||||
await expect(archive.done).resolves.toBe("canceled");
|
||||
undoResponse.resolve();
|
||||
await undo;
|
||||
|
||||
expect({
|
||||
row: storedWorkspace(archived.id),
|
||||
archivePending: isWorkspaceArchivePending(target()),
|
||||
undoPending: isWorkspaceArchiveUndoPending(target()),
|
||||
}).toEqual({ row: archived, archivePending: false, undoPending: false });
|
||||
});
|
||||
|
||||
it("hides the row again when the host cannot undo the archive", async () => {
|
||||
const archived = workspace();
|
||||
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
|
||||
const archive = beginOptimisticWorkspaceArchive({
|
||||
client: createClient(async () => archivePayload({ workspaceId: archived.id })),
|
||||
workspace: target(),
|
||||
});
|
||||
await archive.done;
|
||||
|
||||
await expect(
|
||||
undoWorkspaceArchiveOptimistically({
|
||||
client: {
|
||||
undoWorkspaceArchive: async () => {
|
||||
throw new Error("Branch is gone");
|
||||
},
|
||||
},
|
||||
workspace: target(),
|
||||
hidden: archive.hidden,
|
||||
}),
|
||||
).rejects.toThrow("Branch is gone");
|
||||
|
||||
expect(storedWorkspace(archived.id)).toBeUndefined();
|
||||
expect(isWorkspaceArchiveUndoPending(target())).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves a re-archived row hidden when the earlier undo settles", async () => {
|
||||
const archived = workspace();
|
||||
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
|
||||
const undoResponse = deferred<void>();
|
||||
const first = beginOptimisticWorkspaceArchive({
|
||||
client: createClient(async () => archivePayload({ workspaceId: archived.id })),
|
||||
workspace: target(),
|
||||
});
|
||||
await first.done;
|
||||
const undo = undoWorkspaceArchiveOptimistically({
|
||||
client: { undoWorkspaceArchive: async () => undoResponse.promise },
|
||||
workspace: target(),
|
||||
hidden: first.hidden,
|
||||
});
|
||||
|
||||
const rearchive = beginOptimisticWorkspaceArchive({
|
||||
client: createClient(async () => new Promise<ArchiveWorkspacePayload>(() => {})),
|
||||
workspace: target(),
|
||||
});
|
||||
undoResponse.resolve();
|
||||
await undo;
|
||||
|
||||
expect(rearchive.hidden).toEqual(archived);
|
||||
expect(storedWorkspace(archived.id)).toBeUndefined();
|
||||
expect(isWorkspaceArchivePending(target())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import {
|
||||
clearWorkspaceArchivePending,
|
||||
clearWorkspaceArchiveUndoPending,
|
||||
isWorkspaceArchiveUndoPending,
|
||||
markWorkspaceArchivePending,
|
||||
markWorkspaceArchiveUndoPending,
|
||||
} from "@/contexts/session-workspace-upserts";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
|
||||
@@ -13,7 +16,20 @@ export interface WorkspaceArchiveTarget {
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null }>;
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveUndoClient {
|
||||
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
/** `canceled`: an undo stopped the archive on the host before it finished. */
|
||||
export type WorkspaceArchiveOutcome = "archived" | "canceled";
|
||||
|
||||
export interface OptimisticWorkspaceArchive {
|
||||
/** The row as it was before the archive hid it, for undo to put back. */
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
done: Promise<WorkspaceArchiveOutcome>;
|
||||
}
|
||||
|
||||
interface OptimisticWorkspaceArchiveSnapshot {
|
||||
@@ -72,31 +88,72 @@ function restoreOptimisticallyHiddenWorkspace(input: {
|
||||
async function archiveWorkspaceOrThrow(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspaceId: string;
|
||||
}): Promise<void> {
|
||||
}): Promise<WorkspaceArchiveOutcome> {
|
||||
const payload = await input.client.archiveWorkspace(input.workspaceId);
|
||||
if (payload.canceled) {
|
||||
return "canceled";
|
||||
}
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error);
|
||||
}
|
||||
return "archived";
|
||||
}
|
||||
|
||||
/** Hides the row now and archives it on the host. A failed archive puts the row back. */
|
||||
export function beginOptimisticWorkspaceArchive(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
}): OptimisticWorkspaceArchive {
|
||||
const snapshot = hideWorkspaceOptimistically(input.workspace);
|
||||
const done = (async () => {
|
||||
try {
|
||||
return await archiveWorkspaceOrThrow({
|
||||
client: input.client,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
});
|
||||
} catch (error) {
|
||||
restoreOptimisticallyHiddenWorkspace({
|
||||
serverId: input.workspace.serverId,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
snapshot,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
return { hidden: snapshot.workspace, done };
|
||||
}
|
||||
|
||||
export async function archiveWorkspaceOptimistically(input: {
|
||||
client: WorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
}): Promise<void> {
|
||||
const snapshot = hideWorkspaceOptimistically(input.workspace);
|
||||
}): Promise<WorkspaceArchiveOutcome> {
|
||||
return beginOptimisticWorkspaceArchive(input).done;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the archived row back now and asks the host to undo the archive, whether it is still
|
||||
* running or already finished. A failed undo hides the row again, unless the user archived
|
||||
* it again in the meantime.
|
||||
*/
|
||||
export async function undoWorkspaceArchiveOptimistically(input: {
|
||||
client: WorkspaceArchiveUndoClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
}): Promise<void> {
|
||||
const { serverId, workspaceId } = input.workspace;
|
||||
markWorkspaceArchiveUndoPending({ serverId, workspaceId });
|
||||
if (input.hidden) {
|
||||
getHostRuntimeStore().acceptWorkspaceSnapshots(serverId, [input.hidden]);
|
||||
}
|
||||
try {
|
||||
await archiveWorkspaceOrThrow({
|
||||
client: input.client,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
});
|
||||
await input.client.undoWorkspaceArchive(workspaceId);
|
||||
} catch (error) {
|
||||
restoreOptimisticallyHiddenWorkspace({
|
||||
serverId: input.workspace.serverId,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
snapshot,
|
||||
});
|
||||
if (isWorkspaceArchiveUndoPending({ serverId, workspaceId })) {
|
||||
getHostRuntimeStore().removeWorkspaceSnapshot(serverId, workspaceId);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearWorkspaceArchiveUndoPending({ serverId, workspaceId });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3628,6 +3628,23 @@ export class DaemonClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects when the host could not put the workspace back; an old host has no such RPC. */
|
||||
async undoWorkspaceArchive(workspaceId: string, requestId?: string): Promise<void> {
|
||||
const payload =
|
||||
await this.sendNamespacedCorrelatedSessionRequest<"workspace.archive.undo.response">({
|
||||
requestId,
|
||||
message: {
|
||||
type: "workspace.archive.undo.request",
|
||||
workspaceId,
|
||||
},
|
||||
// Undoing a finished worktree archive recreates the worktree, like recovery does.
|
||||
timeout: 150_000,
|
||||
});
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "The host could not undo the workspace archive");
|
||||
}
|
||||
}
|
||||
|
||||
async resumeAgent(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
|
||||
@@ -1105,6 +1105,14 @@ export const WorkspaceRecoveryRestoreRequestSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
// Undoes the latest archive of a workspace: cancels it if it is still running, otherwise
|
||||
// restores the workspace, then unarchives the agents that archive took down.
|
||||
export const WorkspaceArchiveUndoRequestSchema = z.object({
|
||||
type: z.literal("workspace.archive.undo.request"),
|
||||
workspaceId: z.string(),
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const SetVoiceModeMessageSchema = z.object({
|
||||
type: z.literal("set_voice_mode"),
|
||||
enabled: z.boolean(),
|
||||
@@ -2249,6 +2257,16 @@ export const WorkspaceRecoveryRestoreResponseSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const WorkspaceArchiveUndoResponseSchema = z.object({
|
||||
type: z.literal("workspace.archive.undo.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
workspaceId: z.string(),
|
||||
accepted: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const SetVoiceModeResponseMessageSchema = z.object({
|
||||
type: z.literal("set_voice_mode_response"),
|
||||
payload: z.object({
|
||||
@@ -3355,6 +3373,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceLabelDeleteInspectRequestSchema,
|
||||
WorkspaceRecoveryInspectRequestSchema,
|
||||
WorkspaceRecoveryRestoreRequestSchema,
|
||||
WorkspaceArchiveUndoRequestSchema,
|
||||
SetVoiceModeMessageSchema,
|
||||
SendAgentMessageRequestSchema,
|
||||
WaitForFinishRequestSchema,
|
||||
@@ -3820,6 +3839,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
worktreeRestore: z.boolean().optional(),
|
||||
// COMPAT(workspaceRecovery): added in v0.1.105, remove after 2027-01-11 once daemon floor >= v0.1.105.
|
||||
workspaceRecovery: z.boolean().optional(),
|
||||
// COMPAT(workspaceArchiveUndo): added in v0.15.3, remove gate after 2027-05-06.
|
||||
workspaceArchiveUndo: z.boolean().optional(),
|
||||
// COMPAT(workspaceFileEditing): added in v0.2.0, remove after 2027-01-18 once daemon floor >= v0.2.0.
|
||||
workspaceFileEditing: z.boolean().optional(),
|
||||
// COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20.
|
||||
@@ -4796,6 +4817,8 @@ export const ArchiveWorkspaceResponseMessageSchema = z.object({
|
||||
workspaceId: z.string(),
|
||||
archivedAt: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
// An undo stopped this archive before it finished; `error` carries the reason.
|
||||
canceled: z.boolean().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -7231,6 +7254,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
WorkspaceBaseBranchSetResponseSchema,
|
||||
WorkspaceRecoveryInspectResponseSchema,
|
||||
WorkspaceRecoveryRestoreResponseSchema,
|
||||
WorkspaceArchiveUndoResponseSchema,
|
||||
WaitForFinishResponseMessageSchema,
|
||||
AgentPermissionRequestMessageSchema,
|
||||
AgentPermissionResolvedMessageSchema,
|
||||
@@ -7444,6 +7468,7 @@ export type WorkspaceRecoveryInspectResponse = z.infer<
|
||||
export type WorkspaceRecoveryRestoreResponse = z.infer<
|
||||
typeof WorkspaceRecoveryRestoreResponseSchema
|
||||
>;
|
||||
export type WorkspaceArchiveUndoResponse = z.infer<typeof WorkspaceArchiveUndoResponseSchema>;
|
||||
export type WorkspaceCreateRequest = z.infer<typeof WorkspaceCreateRequestSchema>;
|
||||
export type WorkspaceCreateResponse = z.infer<typeof WorkspaceCreateResponseSchema>;
|
||||
export type ProjectRenameResponsePayload = z.infer<typeof ProjectRenameResponsePayloadSchema>;
|
||||
@@ -7593,6 +7618,7 @@ export type WorkspacePinSetRequest = z.infer<typeof WorkspacePinSetRequestSchema
|
||||
export type WorkspaceBaseBranchSetRequest = z.infer<typeof WorkspaceBaseBranchSetRequestSchema>;
|
||||
export type WorkspaceRecoveryInspectRequest = z.infer<typeof WorkspaceRecoveryInspectRequestSchema>;
|
||||
export type WorkspaceRecoveryRestoreRequest = z.infer<typeof WorkspaceRecoveryRestoreRequestSchema>;
|
||||
export type WorkspaceArchiveUndoRequest = z.infer<typeof WorkspaceArchiveUndoRequestSchema>;
|
||||
export type SetAgentModeRequestMessage = z.infer<typeof SetAgentModeRequestMessageSchema>;
|
||||
export type SetAgentModelRequestMessage = z.infer<typeof SetAgentModelRequestMessageSchema>;
|
||||
export type SetAgentThinkingRequestMessage = z.infer<typeof SetAgentThinkingRequestMessageSchema>;
|
||||
|
||||
@@ -2540,16 +2540,20 @@ export class AgentManager {
|
||||
if (this.agents.has(agentId)) await this.closeAgentRuntime(agentId);
|
||||
await this.syncNativeArchiveState(record.provider, record.persistence, "restore");
|
||||
|
||||
await registry.upsert({
|
||||
const nextRecord: StoredAgentRecord = {
|
||||
...record,
|
||||
...(updates?.workspaceId ? { workspaceId: updates.workspaceId } : {}),
|
||||
...(updates?.labels ? { labels: applyLabelPatch(record.labels, updates.labels) } : {}),
|
||||
archivedAt: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
await registry.upsert(nextRecord);
|
||||
|
||||
if (this.getAgent(agentId)) {
|
||||
this.notifyAgentState(agentId);
|
||||
} else if (!nextRecord.internal) {
|
||||
// Same publication archiveSnapshot makes, so a stored-only agent reappears for every client.
|
||||
this.dispatchStoredAgentState(nextRecord);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -219,6 +219,7 @@ const INBOUND_PERMISSION = {
|
||||
"workspace.base_branch.set.request": "workspace.write",
|
||||
"workspace.recovery.inspect.request": ["workspace.read", "hub.execute"],
|
||||
"workspace.recovery.restore.request": ["workspace.manage", "hub.execute"],
|
||||
"workspace.archive.undo.request": ["workspace.manage", "hub.execute"],
|
||||
"workspace.script.list.request": "workspace.read",
|
||||
"workspace.script.start.request": "workspace.write",
|
||||
"workspace.script.stop.request": "workspace.write",
|
||||
@@ -462,6 +463,7 @@ const OUTBOUND_PERMISSION = {
|
||||
"workspace.base_branch.set.response": "workspace.write",
|
||||
"workspace.recovery.inspect.response": ["workspace.read", "hub.execute"],
|
||||
"workspace.recovery.restore.response": ["workspace.manage", "hub.execute"],
|
||||
"workspace.archive.undo.response": ["workspace.manage", "hub.execute"],
|
||||
"workspace.script.list.response": "workspace.read",
|
||||
"workspace.script.start.response": "workspace.write",
|
||||
"workspace.script.stop.response": "workspace.write",
|
||||
|
||||
@@ -278,6 +278,10 @@ import {
|
||||
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
|
||||
} from "./worktree-session.js";
|
||||
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
|
||||
import {
|
||||
WorkspaceArchiveOperations,
|
||||
type WorkspaceArchiveUndoInput,
|
||||
} from "./workspace-archive-operations.js";
|
||||
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
|
||||
import { SessionAuthorization, type DaemonPermission } from "./authorization/index.js";
|
||||
|
||||
@@ -286,6 +290,12 @@ function resolveWorkspaceSetupRuntime(
|
||||
): WorkspaceSetupRuntime {
|
||||
return runtime ?? new WorkspaceSetupRuntime();
|
||||
}
|
||||
|
||||
function resolveWorkspaceArchiveOperations(
|
||||
operations: WorkspaceArchiveOperations | undefined,
|
||||
): WorkspaceArchiveOperations {
|
||||
return operations ?? new WorkspaceArchiveOperations();
|
||||
}
|
||||
import { WorktreeRequestError, toWorktreeWireError } from "./worktree-errors.js";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import {
|
||||
@@ -566,6 +576,8 @@ export interface SessionOptions {
|
||||
scriptRuntimeStore?: WorkspaceScriptRuntimeStore;
|
||||
workspaceSetupObservation?: WorkspaceSetupObservation;
|
||||
workspaceSetupRuntime?: WorkspaceSetupRuntime;
|
||||
/** Shared by every session so an undo from any connection reaches the archive it cancels. */
|
||||
workspaceArchiveOperations?: WorkspaceArchiveOperations;
|
||||
onBranchChanged?: (
|
||||
workspaceId: string,
|
||||
oldBranch: string | null,
|
||||
@@ -837,6 +849,7 @@ export class Session {
|
||||
private readonly workspaceSetupObservation: WorkspaceSetupObservation;
|
||||
private readonly unsubscribeSetupObservation: () => void;
|
||||
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
|
||||
private readonly workspaceArchiveOperations: WorkspaceArchiveOperations;
|
||||
private readonly workspaceGitObserver: WorkspaceGitObserverService;
|
||||
private readonly workspaceDirectory: WorkspaceDirectory;
|
||||
private readonly voiceSessions: VoiceSessions;
|
||||
@@ -902,6 +915,7 @@ export class Session {
|
||||
scriptRuntimeStore,
|
||||
workspaceSetupObservation,
|
||||
workspaceSetupRuntime,
|
||||
workspaceArchiveOperations,
|
||||
onBranchChanged,
|
||||
getDaemonTcpPort,
|
||||
getDaemonTcpHost,
|
||||
@@ -1249,6 +1263,7 @@ export class Session {
|
||||
},
|
||||
);
|
||||
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
|
||||
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
|
||||
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
|
||||
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
|
||||
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
|
||||
@@ -3306,6 +3321,8 @@ export class Session {
|
||||
return this.handleWorkspaceRecoveryInspectRequest(msg);
|
||||
case "workspace.recovery.restore.request":
|
||||
return this.handleWorkspaceRecoveryRestoreRequest(msg);
|
||||
case "workspace.archive.undo.request":
|
||||
return this.handleWorkspaceArchiveUndoRequest(msg);
|
||||
case "workspace.clear_attention.request":
|
||||
return this.handleWorkspaceClearAttentionRequest(msg);
|
||||
case "workspace.mark_unread.request":
|
||||
@@ -6180,6 +6197,10 @@ export class Session {
|
||||
|
||||
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
|
||||
await this.workspaceRecovery.restore(workspaceId);
|
||||
await this.publishRecoveredWorkspace(workspaceId);
|
||||
}
|
||||
|
||||
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
|
||||
const workspace = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!workspace) {
|
||||
throw new Error(`Recovered workspace record not found: ${workspaceId}`);
|
||||
@@ -7791,36 +7812,55 @@ export class Session {
|
||||
throw new Error(`Workspace not found: ${request.workspaceId}`);
|
||||
}
|
||||
|
||||
await archiveByScope(
|
||||
{
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
agentManager: this.agentManager,
|
||||
agentStorage: this.agentStorage,
|
||||
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
|
||||
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
|
||||
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
|
||||
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
|
||||
this.markWorkspaceArchiving(workspaceIds, archivingAt),
|
||||
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
killTerminalsForWorkspace: (workspaceId) =>
|
||||
this.terminalController.killTerminalsForWorkspace(workspaceId),
|
||||
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
|
||||
sessionLogger: this.sessionLogger,
|
||||
},
|
||||
{
|
||||
scope: { kind: "workspace", workspaceId: existing.workspaceId },
|
||||
requestId: request.requestId,
|
||||
},
|
||||
const outcome = await this.workspaceArchiveOperations.archive(
|
||||
existing.workspaceId,
|
||||
(signal) =>
|
||||
archiveByScope(
|
||||
{
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
agentManager: this.agentManager,
|
||||
agentStorage: this.agentStorage,
|
||||
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
|
||||
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
|
||||
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
|
||||
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
|
||||
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
|
||||
this.markWorkspaceArchiving(workspaceIds, archivingAt),
|
||||
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
|
||||
assertWorkspaceAutomationAllowed: (workspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
|
||||
killTerminalsForWorkspace: (workspaceId) =>
|
||||
this.terminalController.killTerminalsForWorkspace(workspaceId),
|
||||
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
|
||||
sessionLogger: this.sessionLogger,
|
||||
},
|
||||
{
|
||||
scope: { kind: "workspace", workspaceId: existing.workspaceId },
|
||||
requestId: request.requestId,
|
||||
signal,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (outcome.kind === "canceled") {
|
||||
this.emit({
|
||||
type: "archive_workspace_response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
workspaceId: request.workspaceId,
|
||||
archivedAt: null,
|
||||
error: "Workspace archive was undone",
|
||||
canceled: true,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const archivedWorkspace = await this.workspaceRegistry.get(request.workspaceId);
|
||||
const archivedAt = archivedWorkspace?.archivedAt ?? new Date().toISOString();
|
||||
this.emit({
|
||||
@@ -7850,6 +7890,69 @@ export class Session {
|
||||
}
|
||||
}
|
||||
|
||||
private async handleWorkspaceArchiveUndoRequest(
|
||||
request: Extract<SessionInboundMessage, { type: "workspace.archive.undo.request" }>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
|
||||
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
|
||||
);
|
||||
this.emit({
|
||||
type: "workspace.archive.undo.response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
workspaceId: request.workspaceId,
|
||||
accepted: true,
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
this.sessionLogger.warn(
|
||||
{ err: error, workspaceId: request.workspaceId, requestId: request.requestId },
|
||||
"session: workspace.archive.undo.request rejected",
|
||||
);
|
||||
this.emit({
|
||||
type: "workspace.archive.undo.response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
workspaceId: request.workspaceId,
|
||||
accepted: false,
|
||||
error: getErrorMessageOr(error, "Failed to undo the workspace archive"),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Runs on the archive lane after any in-flight archive has stopped, so the record reflects how
|
||||
// far it got: still active when it was canceled early, archived (directory kept or removed)
|
||||
// otherwise.
|
||||
private async restoreArchivedWorkspaceAndAgents(
|
||||
workspaceId: string,
|
||||
input: WorkspaceArchiveUndoInput,
|
||||
): Promise<void> {
|
||||
const workspace = await this.workspaceRegistry.get(workspaceId);
|
||||
if (!workspace) {
|
||||
throw new Error(`Workspace not found: ${workspaceId}`);
|
||||
}
|
||||
if (workspace.archivedAt) {
|
||||
await this.workspaceRecovery.restore(workspaceId);
|
||||
}
|
||||
const results = await Promise.allSettled(
|
||||
input.agentIds.map((agentId) =>
|
||||
unarchiveAgentState(this.agentStorage, this.agentManager, agentId),
|
||||
),
|
||||
);
|
||||
for (const [index, result] of results.entries()) {
|
||||
if (result.status === "rejected") {
|
||||
this.sessionLogger.warn(
|
||||
{ err: result.reason, workspaceId, agentId: input.agentIds[index] },
|
||||
"Failed to unarchive agent while undoing workspace archive",
|
||||
);
|
||||
}
|
||||
}
|
||||
await this.publishRecoveredWorkspace(workspaceId);
|
||||
}
|
||||
|
||||
private async handleWorkspaceClearAttentionRequest(
|
||||
request: Extract<SessionInboundMessage, { type: "workspace.clear_attention.request" }>,
|
||||
): Promise<void> {
|
||||
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
import type { HubRelationshipManagement } from "./hub/relationship-controller.js";
|
||||
import { WorkspaceSetupObservation } from "./workspace-setup-observation.js";
|
||||
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
|
||||
import type { AgentProvider } from "./agent/agent-sdk-types.js";
|
||||
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
|
||||
@@ -609,6 +610,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
private readonly voiceCallerContexts = new Map<string, VoiceCallerContext>();
|
||||
private readonly workspaceSetupObservation = new WorkspaceSetupObservation();
|
||||
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
|
||||
// One lane per workspace across every connection, so an undo from any client can cancel an
|
||||
// archive another connection started.
|
||||
private readonly workspaceArchiveOperations = new WorkspaceArchiveOperations();
|
||||
private readonly providerSnapshotManager: ProviderSnapshotManager;
|
||||
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
|
||||
private onBranchChanged!:
|
||||
@@ -1697,6 +1701,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
scriptRuntimeStore: this.scriptRuntimeStore ?? undefined,
|
||||
workspaceSetupObservation: this.workspaceSetupObservation,
|
||||
workspaceSetupRuntime: this.workspaceSetupRuntime,
|
||||
workspaceArchiveOperations: this.workspaceArchiveOperations,
|
||||
onBranchChanged: this.onBranchChanged ?? undefined,
|
||||
getDaemonTcpPort: this.getDaemonTcpPort ?? undefined,
|
||||
getDaemonTcpHost: this.getDaemonTcpHost ?? undefined,
|
||||
@@ -2120,6 +2125,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
worktreeRestore: true,
|
||||
// COMPAT(workspaceRecovery): added in v0.1.105, remove after 2027-01-11 once daemon floor >= v0.1.105.
|
||||
workspaceRecovery: true,
|
||||
// COMPAT(workspaceArchiveUndo): added in v0.15.3, remove gate after 2027-05-06.
|
||||
workspaceArchiveUndo: true,
|
||||
// COMPAT(workspaceFileEditing): added in v0.2.0, remove after 2027-01-18 once daemon floor >= v0.2.0.
|
||||
workspaceFileEditing: true,
|
||||
// COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20.
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}
|
||||
|
||||
function deferred<T = void>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function archived(newlyArchivedAgentIds: string[]): ArchiveResult {
|
||||
return {
|
||||
archivedAgentIds: newlyArchivedAgentIds,
|
||||
newlyArchivedAgentIds,
|
||||
archivedWorkspaceIds: ["ws"],
|
||||
removedDirectory: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An archive that parks until released, then honours its abort signal the way archiveByScope's
|
||||
* checkpoints do: an aborted run reports the agents it already took down.
|
||||
*/
|
||||
function parkedArchive(agentIds: string[]) {
|
||||
const release = deferred();
|
||||
const started = deferred();
|
||||
let signal: AbortSignal | null = null;
|
||||
return {
|
||||
release: () => release.resolve(),
|
||||
started: started.promise,
|
||||
get aborted() {
|
||||
return signal?.aborted ?? false;
|
||||
},
|
||||
run: async (runSignal: AbortSignal) => {
|
||||
signal = runSignal;
|
||||
started.resolve();
|
||||
await release.promise;
|
||||
if (runSignal.aborted) throw new WorkspaceArchiveCanceledError(agentIds, false);
|
||||
return archived(agentIds);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("WorkspaceArchiveOperations", () => {
|
||||
test("an undo during a running archive aborts it and restores the agents it took down", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const archive = parkedArchive(["agent-a", "agent-b"]);
|
||||
const restored: string[][] = [];
|
||||
|
||||
const archiveDone = operations.archive("ws", archive.run);
|
||||
await archive.started;
|
||||
const undoDone = operations.undo("ws", async ({ agentIds }) => {
|
||||
restored.push(agentIds);
|
||||
});
|
||||
|
||||
expect(archive.aborted).toBe(true);
|
||||
expect(restored).toEqual([]);
|
||||
archive.release();
|
||||
|
||||
await expect(archiveDone).resolves.toEqual({ kind: "canceled" });
|
||||
await undoDone;
|
||||
expect(restored).toEqual([["agent-a", "agent-b"]]);
|
||||
});
|
||||
|
||||
test("an undo after the archive finished restores the agents that archive took down", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
|
||||
const restored: string[][] = [];
|
||||
await operations.undo("ws", async ({ agentIds }) => {
|
||||
restored.push(agentIds);
|
||||
});
|
||||
|
||||
expect(restored).toEqual([["agent-a"]]);
|
||||
});
|
||||
|
||||
test("restore runs only after the aborted archive has stopped", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const archive = parkedArchive([]);
|
||||
const order: string[] = [];
|
||||
|
||||
const archiveDone = operations
|
||||
.archive("ws", async (signal) => {
|
||||
try {
|
||||
return await archive.run(signal);
|
||||
} finally {
|
||||
order.push("archive stopped");
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await archive.started;
|
||||
const undoDone = operations.undo("ws", async () => {
|
||||
order.push("restore");
|
||||
});
|
||||
archive.release();
|
||||
await Promise.all([archiveDone, undoDone]);
|
||||
|
||||
expect(order).toEqual(["archive stopped", "restore"]);
|
||||
});
|
||||
|
||||
test("a second archive while one runs joins it instead of archiving twice", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const archive = parkedArchive(["agent-a"]);
|
||||
let runs = 0;
|
||||
const run = (signal: AbortSignal) => {
|
||||
runs += 1;
|
||||
return archive.run(signal);
|
||||
};
|
||||
|
||||
const first = operations.archive("ws", run);
|
||||
const second = operations.archive("ws", run);
|
||||
archive.release();
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ kind: "archived", result: archived(["agent-a"]) },
|
||||
{ kind: "archived", result: archived(["agent-a"]) },
|
||||
]);
|
||||
expect(runs).toBe(1);
|
||||
});
|
||||
|
||||
test("an archive requested during an undo runs after the undo, and wins", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
|
||||
const restoreGate = deferred();
|
||||
const order: string[] = [];
|
||||
const undoDone = operations.undo("ws", async () => {
|
||||
await restoreGate.promise;
|
||||
order.push("restored");
|
||||
});
|
||||
const rearchive = operations.archive("ws", async () => {
|
||||
order.push("archived again");
|
||||
return archived(["agent-a"]);
|
||||
});
|
||||
|
||||
restoreGate.resolve();
|
||||
await undoDone;
|
||||
await expect(rearchive).resolves.toMatchObject({ kind: "archived" });
|
||||
expect(order).toEqual(["restored", "archived again"]);
|
||||
});
|
||||
|
||||
test("archive, undo, archive in quick succession leaves the workspace archived", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const first = parkedArchive(["agent-a"]);
|
||||
const restored: string[][] = [];
|
||||
|
||||
const firstDone = operations.archive("ws", first.run);
|
||||
await first.started;
|
||||
const undoDone = operations.undo("ws", async ({ agentIds }) => {
|
||||
restored.push(agentIds);
|
||||
});
|
||||
// The re-archive must not join the archive the undo just aborted.
|
||||
const secondDone = operations.archive("ws", async () => archived(["agent-a"]));
|
||||
first.release();
|
||||
|
||||
await expect(firstDone).resolves.toEqual({ kind: "canceled" });
|
||||
await undoDone;
|
||||
await expect(secondDone).resolves.toMatchObject({ kind: "archived" });
|
||||
expect(restored).toEqual([["agent-a"]]);
|
||||
});
|
||||
|
||||
test("a second undo while one runs joins it", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
const restoreGate = deferred();
|
||||
let restores = 0;
|
||||
const restore = async () => {
|
||||
restores += 1;
|
||||
await restoreGate.promise;
|
||||
};
|
||||
|
||||
const first = operations.undo("ws", restore);
|
||||
const second = operations.undo("ws", restore);
|
||||
restoreGate.resolve();
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(restores).toBe(1);
|
||||
});
|
||||
|
||||
test("a failed restore keeps the agents for a retry", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
|
||||
await expect(
|
||||
operations.undo("ws", async () => {
|
||||
throw new Error("worktree recreation failed");
|
||||
}),
|
||||
).rejects.toThrow("worktree recreation failed");
|
||||
|
||||
const restored: string[][] = [];
|
||||
await operations.undo("ws", async ({ agentIds }) => {
|
||||
restored.push(agentIds);
|
||||
});
|
||||
expect(restored).toEqual([["agent-a"]]);
|
||||
});
|
||||
|
||||
test("an undo restores the archive's agents once; a repeat undo restores none", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
const restored: string[][] = [];
|
||||
const restore = async ({ agentIds }: { agentIds: string[] }) => {
|
||||
restored.push(agentIds);
|
||||
};
|
||||
|
||||
await operations.undo("ws", restore);
|
||||
await operations.undo("ws", restore);
|
||||
|
||||
expect(restored).toEqual([["agent-a"], []]);
|
||||
});
|
||||
|
||||
test("an undo after the retention window restores the workspace without agents", async () => {
|
||||
let now = 0;
|
||||
const operations = new WorkspaceArchiveOperations({ undoRetentionMs: 1000, now: () => now });
|
||||
await operations.archive("ws", async () => archived(["agent-a"]));
|
||||
now = 1000;
|
||||
|
||||
const restored: string[][] = [];
|
||||
await operations.undo("ws", async ({ agentIds }) => {
|
||||
restored.push(agentIds);
|
||||
});
|
||||
expect(restored).toEqual([[]]);
|
||||
});
|
||||
|
||||
test("workspaces have independent lanes", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
const archive = parkedArchive(["agent-a"]);
|
||||
|
||||
const parked = operations.archive("ws-a", archive.run);
|
||||
await archive.started;
|
||||
await expect(operations.archive("ws-b", async () => archived(["agent-b"]))).resolves.toEqual({
|
||||
kind: "archived",
|
||||
result: archived(["agent-b"]),
|
||||
});
|
||||
await operations.undo("ws-b", async () => {});
|
||||
|
||||
expect(archive.aborted).toBe(false);
|
||||
archive.release();
|
||||
await expect(parked).resolves.toMatchObject({ kind: "archived" });
|
||||
});
|
||||
|
||||
test("a failed archive frees the lane for the next request", async () => {
|
||||
const operations = new WorkspaceArchiveOperations();
|
||||
await expect(
|
||||
operations.archive("ws", async () => {
|
||||
throw new Error("registry unavailable");
|
||||
}),
|
||||
).rejects.toThrow("registry unavailable");
|
||||
|
||||
await expect(operations.archive("ws", async () => archived([]))).resolves.toMatchObject({
|
||||
kind: "archived",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
|
||||
|
||||
export type WorkspaceArchiveOutcome =
|
||||
| { kind: "archived"; result: ArchiveResult }
|
||||
| { kind: "canceled" };
|
||||
|
||||
export interface WorkspaceArchiveUndoInput {
|
||||
/** Agents the undone archive took down. Empty when the daemon no longer remembers it. */
|
||||
agentIds: string[];
|
||||
}
|
||||
|
||||
type LaneEntry =
|
||||
| { kind: "archiving"; controller: AbortController; done: Promise<WorkspaceArchiveOutcome> }
|
||||
| { kind: "undoing"; done: Promise<void> };
|
||||
|
||||
interface UndoableArchive {
|
||||
agentIds: string[];
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const DEFAULT_UNDO_RETENTION_MS = 10 * 60_000;
|
||||
|
||||
/**
|
||||
* One lane per workspace for archive and its undo, shared by every session on the daemon.
|
||||
*
|
||||
* - An archive while one runs joins it.
|
||||
* - An undo while an archive runs aborts it, waits for it to stop, then restores.
|
||||
* - An archive while an undo runs waits for the undo, then archives.
|
||||
* - An undo while an undo runs joins it.
|
||||
*
|
||||
* Each call claims the lane synchronously, so whichever request arrives last decides the
|
||||
* workspace's final state no matter how the earlier work interleaves.
|
||||
*
|
||||
* The agents an archive took down are kept in memory for the undo window. After a daemon
|
||||
* restart, undo still restores the workspace but its agents stay archived.
|
||||
*/
|
||||
export class WorkspaceArchiveOperations {
|
||||
private readonly lanes = new Map<string, LaneEntry>();
|
||||
private readonly undoable = new Map<string, UndoableArchive>();
|
||||
private readonly undoRetentionMs: number;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(options: { undoRetentionMs?: number; now?: () => number } = {}) {
|
||||
this.undoRetentionMs = options.undoRetentionMs ?? DEFAULT_UNDO_RETENTION_MS;
|
||||
this.now = options.now ?? Date.now;
|
||||
}
|
||||
|
||||
archive(
|
||||
workspaceId: string,
|
||||
run: (signal: AbortSignal) => Promise<ArchiveResult>,
|
||||
): Promise<WorkspaceArchiveOutcome> {
|
||||
const current = this.lanes.get(workspaceId);
|
||||
if (current?.kind === "archiving") {
|
||||
return current.done;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const done = (async (): Promise<WorkspaceArchiveOutcome> => {
|
||||
await settled(current?.done);
|
||||
try {
|
||||
const result = await run(controller.signal);
|
||||
this.retainUndoable(workspaceId, result.newlyArchivedAgentIds);
|
||||
return { kind: "archived", result };
|
||||
} catch (error) {
|
||||
if (!(error instanceof WorkspaceArchiveCanceledError)) throw error;
|
||||
this.retainUndoable(workspaceId, error.newlyArchivedAgentIds);
|
||||
return { kind: "canceled" };
|
||||
}
|
||||
})();
|
||||
this.claim(workspaceId, { kind: "archiving", controller, done });
|
||||
return done;
|
||||
}
|
||||
|
||||
undo(
|
||||
workspaceId: string,
|
||||
restore: (input: WorkspaceArchiveUndoInput) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const current = this.lanes.get(workspaceId);
|
||||
if (current?.kind === "undoing") {
|
||||
return current.done;
|
||||
}
|
||||
current?.controller.abort();
|
||||
const done = (async () => {
|
||||
await settled(current?.done);
|
||||
const agentIds = this.takeUndoable(workspaceId);
|
||||
try {
|
||||
await restore({ agentIds });
|
||||
} catch (error) {
|
||||
// Keep the agents for a retry; the archive they came from is still the latest one.
|
||||
this.retainUndoable(workspaceId, agentIds);
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
this.claim(workspaceId, { kind: "undoing", done });
|
||||
return done;
|
||||
}
|
||||
|
||||
private claim(workspaceId: string, entry: LaneEntry): void {
|
||||
this.lanes.set(workspaceId, entry);
|
||||
const release = () => {
|
||||
if (this.lanes.get(workspaceId) === entry) this.lanes.delete(workspaceId);
|
||||
};
|
||||
void (entry.done as Promise<unknown>).then(release, release);
|
||||
}
|
||||
|
||||
private retainUndoable(workspaceId: string, agentIds: string[]): void {
|
||||
const now = this.now();
|
||||
for (const [id, entry] of this.undoable) {
|
||||
if (entry.expiresAt <= now) this.undoable.delete(id);
|
||||
}
|
||||
this.undoable.set(workspaceId, { agentIds, expiresAt: now + this.undoRetentionMs });
|
||||
}
|
||||
|
||||
private takeUndoable(workspaceId: string): string[] {
|
||||
const entry = this.undoable.get(workspaceId);
|
||||
this.undoable.delete(workspaceId);
|
||||
if (!entry || entry.expiresAt <= this.now()) return [];
|
||||
return entry.agentIds;
|
||||
}
|
||||
}
|
||||
|
||||
async function settled(promise: Promise<unknown> | undefined): Promise<void> {
|
||||
if (!promise) return;
|
||||
try {
|
||||
await promise;
|
||||
} catch {
|
||||
// The earlier request reports its own failure; this one only waits for the lane.
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type ArchiveDependencies,
|
||||
type ArchiveResult,
|
||||
resolveWorkspaceIdAtPath,
|
||||
WorkspaceArchiveCanceledError,
|
||||
} from "./workspace-archive-service.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
|
||||
@@ -1019,6 +1020,179 @@ describe("archiveByScope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function gate(): {
|
||||
wait: Promise<void>;
|
||||
open: () => void;
|
||||
reached: Promise<void>;
|
||||
reach: () => void;
|
||||
} {
|
||||
let open!: () => void;
|
||||
let reach!: () => void;
|
||||
const wait = new Promise<void>((resolve) => {
|
||||
open = resolve;
|
||||
});
|
||||
const reached = new Promise<void>((resolve) => {
|
||||
reach = resolve;
|
||||
});
|
||||
return { wait, open, reached, reach };
|
||||
}
|
||||
|
||||
async function canceledArchive(promise: Promise<unknown>): Promise<WorkspaceArchiveCanceledError> {
|
||||
const error = await promise.then(
|
||||
() => null,
|
||||
(reason: unknown) => reason,
|
||||
);
|
||||
if (!(error instanceof WorkspaceArchiveCanceledError)) {
|
||||
throw new Error(`Expected the archive to be canceled, got ${String(error)}`);
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
describe("archiveByScope cancellation", () => {
|
||||
function storedAgents(
|
||||
workspaceId: string,
|
||||
agents: Array<{ id: string; archivedAt: string | null }>,
|
||||
) {
|
||||
return {
|
||||
listByWorkspace: async () =>
|
||||
agents.map((agent) => ({ ...agent, workspaceId })) as StoredAgentRecord[],
|
||||
} as Pick<AgentStorage, "listByWorkspace">;
|
||||
}
|
||||
|
||||
test("an abort while agents archive keeps the record and reports only the agents it took down", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "cancel-agents");
|
||||
const workspaceId = "ws-cancel-agents";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome,
|
||||
activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }],
|
||||
});
|
||||
deps.agentStorage = storedAgents(workspaceId, [
|
||||
{ id: "agent-active", archivedAt: null },
|
||||
{ id: "agent-already-archived", archivedAt: "2026-01-01T00:00:00.000Z" },
|
||||
]);
|
||||
const agentArchive = gate();
|
||||
deps.agentManager.archiveSnapshot = vi.fn(async (agentId: string) => {
|
||||
agentArchive.reach();
|
||||
await agentArchive.wait;
|
||||
deps.archivedSnapshotIds.push(agentId);
|
||||
return {} as StoredAgentRecord;
|
||||
});
|
||||
const controller = new AbortController();
|
||||
|
||||
const archive = archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-cancel-agents",
|
||||
signal: controller.signal,
|
||||
});
|
||||
await agentArchive.reached;
|
||||
controller.abort();
|
||||
agentArchive.open();
|
||||
const error = await canceledArchive(archive);
|
||||
|
||||
expect({
|
||||
newlyArchivedAgentIds: error.newlyArchivedAgentIds,
|
||||
recordArchived: error.recordArchived,
|
||||
activeWorkspaceIds: (await deps.listActiveWorkspaces()).map((w) => w.workspaceId),
|
||||
directoryExists: existsSync(worktree.worktreePath),
|
||||
}).toEqual({
|
||||
newlyArchivedAgentIds: ["agent-active"],
|
||||
recordArchived: false,
|
||||
activeWorkspaceIds: [workspaceId],
|
||||
directoryExists: true,
|
||||
});
|
||||
// The archiving marker never outlives a canceled archive.
|
||||
expect(deps.clearWorkspaceArchiving).toHaveBeenCalledWith([workspaceId]);
|
||||
});
|
||||
|
||||
test("an abort after the record archived keeps the worktree directory", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "cancel-record");
|
||||
const workspaceId = "ws-cancel-record";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome,
|
||||
activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }],
|
||||
});
|
||||
const recordArchive = gate();
|
||||
const archiveRecord = deps.archiveWorkspaceRecord;
|
||||
deps.archiveWorkspaceRecord = async (id: string) => {
|
||||
recordArchive.reach();
|
||||
await recordArchive.wait;
|
||||
await archiveRecord(id);
|
||||
};
|
||||
const controller = new AbortController();
|
||||
|
||||
const archive = archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-cancel-record",
|
||||
signal: controller.signal,
|
||||
});
|
||||
await recordArchive.reached;
|
||||
controller.abort();
|
||||
recordArchive.open();
|
||||
const error = await canceledArchive(archive);
|
||||
|
||||
expect({
|
||||
recordArchived: error.recordArchived,
|
||||
activeWorkspaceIds: (await deps.listActiveWorkspaces()).map((w) => w.workspaceId),
|
||||
directoryExists: existsSync(worktree.worktreePath),
|
||||
}).toEqual({ recordArchived: true, activeWorkspaceIds: [], directoryExists: true });
|
||||
});
|
||||
|
||||
test("an archive aborted before it starts touches nothing", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "cancel-before");
|
||||
const workspaceId = "ws-cancel-before";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome,
|
||||
activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }],
|
||||
});
|
||||
deps.agentStorage = storedAgents(workspaceId, [{ id: "agent-active", archivedAt: null }]);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
|
||||
const error = await canceledArchive(
|
||||
archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-cancel-before",
|
||||
signal: controller.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error.newlyArchivedAgentIds).toEqual([]);
|
||||
expect(deps.archivedSnapshotIds).toEqual([]);
|
||||
expect(deps.markWorkspaceArchiving).not.toHaveBeenCalled();
|
||||
expect(existsSync(worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("a completed archive reports the agents it newly archived", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "newly-archived");
|
||||
const workspaceId = "ws-newly-archived";
|
||||
const deps = createArchiveDeps({
|
||||
paseoHome,
|
||||
activeWorkspaces: [{ workspaceId, cwd: worktree.worktreePath, kind: "worktree" }],
|
||||
});
|
||||
deps.agentStorage = storedAgents(workspaceId, [
|
||||
{ id: "agent-active", archivedAt: null },
|
||||
{ id: "agent-already-archived", archivedAt: "2026-01-01T00:00:00.000Z" },
|
||||
]);
|
||||
|
||||
const result = await archiveByScope(deps, {
|
||||
scope: { kind: "workspace", workspaceId },
|
||||
requestId: "req-newly-archived",
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result.archivedAgentIds.sort()).toEqual(["agent-active", "agent-already-archived"]);
|
||||
expect(result.newlyArchivedAgentIds).toEqual(["agent-active"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkspaceIdAtPath", () => {
|
||||
test("prefers the worktree-kind record on an exact cwd tie", async () => {
|
||||
const targetPath = "/worktrees/repo/feature";
|
||||
|
||||
@@ -67,6 +67,9 @@ export type ArchiveScope =
|
||||
|
||||
export interface ArchiveResult {
|
||||
archivedAgentIds: string[];
|
||||
// Agents this request moved from active to archived. `archivedAgentIds` also lists agents that
|
||||
// were already archived; undo must restore only the ones this archive took down.
|
||||
newlyArchivedAgentIds: string[];
|
||||
archivedWorkspaceIds: string[];
|
||||
removedDirectory: boolean;
|
||||
// Set when the record archived but its worktree directory was left on
|
||||
@@ -78,6 +81,24 @@ export interface ArchiveResult {
|
||||
export interface ArchiveByScopeRequest {
|
||||
scope: ArchiveScope;
|
||||
requestId: string;
|
||||
// Aborting cancels the archive at its next checkpoint. Removing the worktree directory is the
|
||||
// point of no return: once it starts the archive completes.
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* The archive stopped at a checkpoint because its signal aborted. Whatever ran before the
|
||||
* checkpoint stays done; `newlyArchivedAgentIds` and `recordArchived` say how far it got so the
|
||||
* canceller can put it back.
|
||||
*/
|
||||
export class WorkspaceArchiveCanceledError extends Error {
|
||||
constructor(
|
||||
public readonly newlyArchivedAgentIds: string[],
|
||||
public readonly recordArchived: boolean,
|
||||
) {
|
||||
super("Workspace archive was canceled");
|
||||
this.name = "WorkspaceArchiveCanceledError";
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireActiveWorkspaceForArchive(
|
||||
@@ -144,10 +165,22 @@ async function archiveByScopeWithPriority(
|
||||
dependencies: ArchiveDependencies,
|
||||
request: ArchiveByScopeRequest,
|
||||
): Promise<ArchiveResult> {
|
||||
const progress: ArchiveProgress = { newlyArchivedAgentIds: new Set(), recordArchived: false };
|
||||
const checkpoint = () => {
|
||||
if (request.signal?.aborted) {
|
||||
throw new WorkspaceArchiveCanceledError(
|
||||
Array.from(progress.newlyArchivedAgentIds),
|
||||
progress.recordArchived,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
checkpoint();
|
||||
const target = await resolveArchiveTarget(dependencies, request.scope);
|
||||
const targetWorkspaceIds = target.workspaceIds;
|
||||
|
||||
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
|
||||
checkpoint();
|
||||
|
||||
if (targetWorkspaceIds.length > 0) {
|
||||
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
|
||||
@@ -160,12 +193,14 @@ async function archiveByScopeWithPriority(
|
||||
if (targetWorkspaceIds.length > 0) {
|
||||
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
|
||||
}
|
||||
checkpoint();
|
||||
|
||||
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
|
||||
dependencies,
|
||||
targetWorkspaceIds,
|
||||
request.requestId,
|
||||
{ requestId: request.requestId, checkpoint, progress },
|
||||
);
|
||||
checkpoint();
|
||||
|
||||
if (target.backing?.mainRepoRoot) {
|
||||
try {
|
||||
@@ -184,7 +219,7 @@ async function archiveByScopeWithPriority(
|
||||
if (target.backing !== null) {
|
||||
const removal = await maybeRemoveDirectory(
|
||||
dependencies,
|
||||
request,
|
||||
{ requestId: request.requestId, checkpoint },
|
||||
target,
|
||||
archivedWorkspaceIds,
|
||||
);
|
||||
@@ -194,6 +229,7 @@ async function archiveByScopeWithPriority(
|
||||
|
||||
return {
|
||||
archivedAgentIds: Array.from(archivedAgents),
|
||||
newlyArchivedAgentIds: Array.from(progress.newlyArchivedAgentIds),
|
||||
archivedWorkspaceIds,
|
||||
removedDirectory,
|
||||
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
|
||||
@@ -206,6 +242,11 @@ async function archiveByScopeWithPriority(
|
||||
}
|
||||
}
|
||||
|
||||
interface ArchiveProgress {
|
||||
newlyArchivedAgentIds: Set<string>;
|
||||
recordArchived: boolean;
|
||||
}
|
||||
|
||||
async function resolveArchiveTarget(
|
||||
dependencies: ArchiveDependencies,
|
||||
scope: ArchiveScope,
|
||||
@@ -352,16 +393,23 @@ async function resolveBackingDirectory(
|
||||
async function archiveTargetRecords(
|
||||
dependencies: ArchiveDependencies,
|
||||
targetWorkspaceIds: string[],
|
||||
requestId: string,
|
||||
options: { requestId: string; checkpoint: () => void; progress: ArchiveProgress },
|
||||
): Promise<{ archivedAgents: Set<string>; archivedWorkspaceIds: string[] }> {
|
||||
const archivedAgents = new Set<string>();
|
||||
const archivedWorkspaceIds: string[] = [];
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
targetWorkspaceIds.map(async (workspaceId) => {
|
||||
const agents = await archiveWorkspaceContents(dependencies, workspaceId);
|
||||
const contents = await archiveWorkspaceContentsWithProgress(dependencies, workspaceId);
|
||||
for (const agentId of contents.newlyArchivedAgentIds) {
|
||||
options.progress.newlyArchivedAgentIds.add(agentId);
|
||||
}
|
||||
// Agents and terminals are down, the record is not: an abort here leaves the workspace
|
||||
// listed, and the canceller restores the agents it reports.
|
||||
options.checkpoint();
|
||||
await dependencies.archiveWorkspaceRecord(workspaceId);
|
||||
return { workspaceId, agents };
|
||||
options.progress.recordArchived = true;
|
||||
return { workspaceId, agents: contents.agentIds };
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -371,9 +419,14 @@ async function archiveTargetRecords(
|
||||
for (const agentId of result.value.agents) {
|
||||
archivedAgents.add(agentId);
|
||||
}
|
||||
} else if (result.reason instanceof WorkspaceArchiveCanceledError) {
|
||||
throw new WorkspaceArchiveCanceledError(
|
||||
Array.from(options.progress.newlyArchivedAgentIds),
|
||||
options.progress.recordArchived,
|
||||
);
|
||||
} else {
|
||||
dependencies.sessionLogger?.warn(
|
||||
{ err: result.reason, requestId },
|
||||
{ err: result.reason, requestId: options.requestId },
|
||||
"archiveByScope workspace teardown failed; continuing",
|
||||
);
|
||||
}
|
||||
@@ -384,7 +437,7 @@ async function archiveTargetRecords(
|
||||
|
||||
async function maybeRemoveDirectory(
|
||||
dependencies: ArchiveDependencies,
|
||||
request: Pick<ArchiveByScopeRequest, "requestId">,
|
||||
request: { requestId: string; checkpoint: () => void },
|
||||
target: ArchiveTarget,
|
||||
archivedWorkspaceIds: string[],
|
||||
): Promise<{
|
||||
@@ -423,6 +476,7 @@ async function maybeRemoveDirectory(
|
||||
teardownTargets,
|
||||
);
|
||||
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
|
||||
request.checkpoint();
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: backing.path,
|
||||
teardownCwd: teardownTarget.cwd,
|
||||
@@ -452,6 +506,9 @@ async function maybeRemoveDirectory(
|
||||
return { removedDirectory: false };
|
||||
}
|
||||
|
||||
// Last chance to keep the directory. Teardown commands already ran, so a cancel here restores
|
||||
// a workspace whose teardown hooks fired; that beats deleting what the user asked to keep.
|
||||
request.checkpoint();
|
||||
try {
|
||||
await deletePaseoWorktree({
|
||||
cwd: backing.mainRepoRoot,
|
||||
@@ -518,6 +575,13 @@ export async function archiveWorkspaceContents(
|
||||
dependencies: ArchiveWorkspaceContentsDependencies,
|
||||
workspaceId: string,
|
||||
): Promise<Set<string>> {
|
||||
return (await archiveWorkspaceContentsWithProgress(dependencies, workspaceId)).agentIds;
|
||||
}
|
||||
|
||||
async function archiveWorkspaceContentsWithProgress(
|
||||
dependencies: ArchiveWorkspaceContentsDependencies,
|
||||
workspaceId: string,
|
||||
): Promise<{ agentIds: Set<string>; newlyArchivedAgentIds: string[] }> {
|
||||
const archivedAgents = new Set<string>();
|
||||
|
||||
const liveAgents = dependencies.agentManager
|
||||
@@ -542,29 +606,48 @@ export async function archiveWorkspaceContents(
|
||||
}
|
||||
|
||||
const archivedAt = new Date().toISOString();
|
||||
const agentIdsToArchive = new Set([
|
||||
...liveAgents.map((agent) => agent.id),
|
||||
...matchingStoredRecords.filter((record) => !record.archivedAt).map((record) => record.id),
|
||||
]);
|
||||
const archiveResults = await Promise.allSettled([
|
||||
...[...agentIdsToArchive].map((agentId) =>
|
||||
dependencies.agentManager.getAgent(agentId)
|
||||
? dependencies.agentManager.archiveAgent(agentId)
|
||||
: dependencies.agentManager.archiveSnapshot(agentId, archivedAt),
|
||||
const agentIdsToArchive = [
|
||||
...new Set([
|
||||
...liveAgents.map((agent) => agent.id),
|
||||
...matchingStoredRecords.filter((record) => !record.archivedAt).map((record) => record.id),
|
||||
]),
|
||||
];
|
||||
// Internal agents are retired rather than archived: nothing on disk can bring them back.
|
||||
const restorableAgentIds = new Set(agentIdsToArchive);
|
||||
for (const agent of liveAgents) {
|
||||
if (agent.internal) restorableAgentIds.delete(agent.id);
|
||||
}
|
||||
const [agentResults, [terminalResult]] = await Promise.all([
|
||||
Promise.allSettled(
|
||||
agentIdsToArchive.map((agentId) =>
|
||||
dependencies.agentManager.getAgent(agentId)
|
||||
? dependencies.agentManager.archiveAgent(agentId)
|
||||
: dependencies.agentManager.archiveSnapshot(agentId, archivedAt),
|
||||
),
|
||||
),
|
||||
dependencies.killTerminalsForWorkspace(workspaceId),
|
||||
Promise.allSettled([dependencies.killTerminalsForWorkspace(workspaceId)]),
|
||||
]);
|
||||
|
||||
for (const result of archiveResults) {
|
||||
const newlyArchivedAgentIds: string[] = [];
|
||||
for (const [index, result] of agentResults.entries()) {
|
||||
const agentId = agentIdsToArchive[index]!;
|
||||
if (result.status === "rejected") {
|
||||
dependencies.sessionLogger?.warn(
|
||||
{ err: result.reason, workspaceId },
|
||||
{ err: result.reason, workspaceId, agentId },
|
||||
"Workspace archive teardown step failed; continuing",
|
||||
);
|
||||
} else if (restorableAgentIds.has(agentId)) {
|
||||
newlyArchivedAgentIds.push(agentId);
|
||||
}
|
||||
}
|
||||
if (terminalResult?.status === "rejected") {
|
||||
dependencies.sessionLogger?.warn(
|
||||
{ err: terminalResult.reason, workspaceId },
|
||||
"Workspace archive teardown step failed; continuing",
|
||||
);
|
||||
}
|
||||
|
||||
return archivedAgents;
|
||||
return { agentIds: archivedAgents, newlyArchivedAgentIds };
|
||||
}
|
||||
|
||||
// True when, after archiving
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
|
||||
import { getFullAccessConfig } from "./daemon-e2e/agent-configs.js";
|
||||
import { createDaemonTestContext, type DaemonTestContext } from "./test-utils/index.js";
|
||||
|
||||
// Undo of a workspace archive, end to end through a real daemon. The archive is parked inside a
|
||||
// worktree teardown command that waits on a file, so the undo lands at a known point.
|
||||
|
||||
let ctx: DaemonTestContext;
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
ctx = await createDaemonTestContext();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx.cleanup();
|
||||
for (const tempRoot of tempRoots.splice(0)) {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
interface GatedRepo {
|
||||
repoDir: string;
|
||||
teardownStartedPath: string;
|
||||
releaseTeardown: () => void;
|
||||
}
|
||||
|
||||
function git(repoDir: string, args: string[]): void {
|
||||
execFileSync("git", args, { cwd: repoDir, stdio: "pipe" });
|
||||
}
|
||||
|
||||
/** A repo whose worktree teardown parks until released. */
|
||||
function createRepoWithGatedTeardown(): GatedRepo {
|
||||
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-"));
|
||||
tempRoots.push(tempRoot);
|
||||
const repoDir = path.join(tempRoot, "repo");
|
||||
const teardownStartedPath = path.join(tempRoot, "teardown-started");
|
||||
const releasePath = path.join(tempRoot, "release-teardown");
|
||||
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
|
||||
git(repoDir, ["config", "user.email", "test@getpaseo.local"]);
|
||||
git(repoDir, ["config", "user.name", "Paseo Test"]);
|
||||
const teardown = `node -e "const fs=require('fs');fs.writeFileSync('${teardownStartedPath}','started');const timer=setInterval(()=>{if(fs.existsSync('${releasePath}'))clearInterval(timer)},20)"`;
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({ worktree: { teardown: [teardown] } }),
|
||||
);
|
||||
git(repoDir, ["add", "paseo.json"]);
|
||||
git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "gated teardown"]);
|
||||
return {
|
||||
repoDir,
|
||||
teardownStartedPath,
|
||||
releaseTeardown: () => writeFileSync(releasePath, "release\n"),
|
||||
};
|
||||
}
|
||||
|
||||
async function createWorktreeWorkspaceWithAgent(repoDir: string, slug: string) {
|
||||
const result = await ctx.client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, worktreeSlug: slug, baseBranch: "main" },
|
||||
});
|
||||
const workspace = result.workspace;
|
||||
if (!workspace?.workspaceDirectory) {
|
||||
throw new Error(result.error ?? "Failed to create worktree workspace");
|
||||
}
|
||||
const agent = await ctx.client.createAgent({
|
||||
...getFullAccessConfig("codex"),
|
||||
cwd: workspace.workspaceDirectory,
|
||||
workspaceId: workspace.id,
|
||||
title: "Undo agent",
|
||||
});
|
||||
return { workspaceId: workspace.id, directory: workspace.workspaceDirectory, agentId: agent.id };
|
||||
}
|
||||
|
||||
async function isWorkspaceActive(workspaceId: string): Promise<boolean> {
|
||||
const workspaces = await ctx.client.fetchWorkspaces();
|
||||
return workspaces.entries.some((entry) => entry.id === workspaceId);
|
||||
}
|
||||
|
||||
async function isAgentArchived(agentId: string): Promise<boolean> {
|
||||
const agents = await ctx.client.fetchAgents({ filter: { includeArchived: true } });
|
||||
const entry = agents.entries.find((candidate) => candidate.agent.id === agentId);
|
||||
if (!entry) throw new Error(`Agent ${agentId} is missing`);
|
||||
return entry.agent.archivedAt !== null && entry.agent.archivedAt !== undefined;
|
||||
}
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"an undo while teardown runs cancels the archive before the worktree is deleted",
|
||||
async () => {
|
||||
const repo = createRepoWithGatedTeardown();
|
||||
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
|
||||
repo.repoDir,
|
||||
"undo-during-teardown",
|
||||
);
|
||||
|
||||
try {
|
||||
const archive = ctx.client.archiveWorkspace(workspaceId);
|
||||
await expect.poll(() => existsSync(repo.teardownStartedPath), { timeout: 15000 }).toBe(true);
|
||||
const undo = ctx.client.undoWorkspaceArchive(workspaceId);
|
||||
repo.releaseTeardown();
|
||||
|
||||
const [archiveResponse] = await Promise.all([archive, undo]);
|
||||
|
||||
expect({
|
||||
canceled: archiveResponse.canceled,
|
||||
archivedAt: archiveResponse.archivedAt,
|
||||
workspaceActive: await isWorkspaceActive(workspaceId),
|
||||
directoryExists: existsSync(directory),
|
||||
agentArchived: await isAgentArchived(agentId),
|
||||
}).toEqual({
|
||||
canceled: true,
|
||||
archivedAt: null,
|
||||
workspaceActive: true,
|
||||
directoryExists: true,
|
||||
agentArchived: false,
|
||||
});
|
||||
} finally {
|
||||
repo.releaseTeardown();
|
||||
}
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"an undo after the archive finished recreates the worktree and its agents",
|
||||
async () => {
|
||||
const repo = createRepoWithGatedTeardown();
|
||||
repo.releaseTeardown();
|
||||
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
|
||||
repo.repoDir,
|
||||
"undo-after-archive",
|
||||
);
|
||||
|
||||
const archived = await ctx.client.archiveWorkspace(workspaceId);
|
||||
expect(archived.error).toBeNull();
|
||||
expect(existsSync(directory)).toBe(false);
|
||||
expect(await isAgentArchived(agentId)).toBe(true);
|
||||
|
||||
await ctx.client.undoWorkspaceArchive(workspaceId);
|
||||
|
||||
expect({
|
||||
workspaceActive: await isWorkspaceActive(workspaceId),
|
||||
directoryExists: existsSync(directory),
|
||||
agentArchived: await isAgentArchived(agentId),
|
||||
}).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false });
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"archive, undo, archive leaves the workspace archived",
|
||||
async () => {
|
||||
const repo = createRepoWithGatedTeardown();
|
||||
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
|
||||
repo.repoDir,
|
||||
"archive-undo-archive",
|
||||
);
|
||||
|
||||
try {
|
||||
const first = ctx.client.archiveWorkspace(workspaceId);
|
||||
await expect.poll(() => existsSync(repo.teardownStartedPath), { timeout: 15000 }).toBe(true);
|
||||
const undo = ctx.client.undoWorkspaceArchive(workspaceId);
|
||||
const second = ctx.client.archiveWorkspace(workspaceId);
|
||||
repo.releaseTeardown();
|
||||
|
||||
const [firstResponse, , secondResponse] = await Promise.all([first, undo, second]);
|
||||
|
||||
expect({
|
||||
firstCanceled: firstResponse.canceled,
|
||||
secondError: secondResponse.error,
|
||||
secondCanceled: secondResponse.canceled ?? false,
|
||||
workspaceActive: await isWorkspaceActive(workspaceId),
|
||||
directoryExists: existsSync(directory),
|
||||
agentArchived: await isAgentArchived(agentId),
|
||||
}).toEqual({
|
||||
firstCanceled: true,
|
||||
secondError: null,
|
||||
secondCanceled: false,
|
||||
workspaceActive: false,
|
||||
directoryExists: false,
|
||||
agentArchived: true,
|
||||
});
|
||||
} finally {
|
||||
repo.releaseTeardown();
|
||||
}
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test("an undo on a workspace that was never archived leaves it as it was", async () => {
|
||||
const repo = createRepoWithGatedTeardown();
|
||||
repo.releaseTeardown();
|
||||
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
|
||||
repo.repoDir,
|
||||
"undo-without-archive",
|
||||
);
|
||||
|
||||
await ctx.client.undoWorkspaceArchive(workspaceId);
|
||||
|
||||
expect({
|
||||
workspaceActive: await isWorkspaceActive(workspaceId),
|
||||
directoryExists: existsSync(directory),
|
||||
agentArchived: await isAgentArchived(agentId),
|
||||
}).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false });
|
||||
}, 60000);
|
||||
Reference in New Issue
Block a user