fix(server): coordinate archive, undo, and restore across daemon checkout boundary

This commit is contained in:
Mohamed Boudra
2026-11-20 12:55:35 +01:00
parent 1a54471e29
commit b2679012ff
11 changed files with 576 additions and 78 deletions
@@ -4,7 +4,11 @@ import type pino from "pino";
import type { ForgeService } from "../../services/forge-service.js";
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-service.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
} from "../workspace-archive-service.js";
import type {
CreatePaseoWorktreeWorkflowFn,
CreatePaseoWorktreeWorkflowResult,
@@ -23,6 +27,8 @@ interface CreateAgentLifecycleDispatchDependencies {
paseoHome: string;
worktreesRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -187,11 +193,13 @@ export class CreateAgentLifecycleDispatch {
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
workspaceArchiveOperations: this.dependencies.workspaceArchiveOperations,
github: this.dependencies.github,
workspaceGitService: this.dependencies.workspaceGitService,
agentManager: this.dependencies.agentManager,
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: this.dependencies.emitWorkspaceUpdatesForWorkspaceIds,
@@ -140,6 +140,7 @@ export interface PaseoToolHostDependencies {
>;
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
@@ -3411,11 +3412,15 @@ function archiveWorktreeDependencies(
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: context.agentManager,
agentStorage: context.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
...(options.workspaceRegistry
? { getWorkspace: (workspaceId: string) => options.workspaceRegistry!.get(workspaceId) }
: {}),
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: options.archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: options.emitWorkspaceUpdatesForWorkspaceIds,
@@ -6,6 +6,7 @@ import type { DaemonConfigStore } from "../daemon-config-store.js";
import {
archiveByScope,
type ActiveWorkspaceRef,
type ArchiveDependencies,
killTerminalsForWorkspace,
} from "../workspace-archive-service.js";
import type {
@@ -22,6 +23,8 @@ export interface AutoArchiveArchiveOptions {
paseoHome: string;
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -102,11 +105,13 @@ export async function archiveIfSafe(input: {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
github: options.github,
workspaceGitService: options.workspaceGitService,
agentManager: options.agentManager,
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
options.archiveWorkspaceRecord(
+10
View File
@@ -181,6 +181,7 @@ import {
killTerminalsForWorkspace,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js";
import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js";
import type { TerminalManager } from "../terminal/terminal-manager.js";
@@ -740,6 +741,7 @@ export async function createPaseoDaemon(
});
const scriptRuntimeStore = new WorkspaceScriptRuntimeStore();
const workspaceSetupRuntime = new WorkspaceSetupRuntime();
const workspaceArchiveOperations = new WorkspaceArchiveOperations();
let configuredHostnames = config.hostnames ?? config.allowedHosts;
let appBaseUrl = config.appBaseUrl ?? "https://app.paseo.sh";
daemonConfigStore.onFieldChange("hostnames", (value) => {
@@ -1221,6 +1223,7 @@ export async function createPaseoDaemon(
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
daemonConfigStore,
workspaceGitService,
github,
@@ -1229,6 +1232,7 @@ export async function createPaseoDaemon(
terminalManager,
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
(await workspaceRegistry.get(workspaceId))?.autoArchivedChangeRequestUrl ?? null,
@@ -1311,6 +1315,7 @@ export async function createPaseoDaemon(
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1336,6 +1341,8 @@ export async function createPaseoDaemon(
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
agentManager,
agentStorage,
github,
@@ -1435,6 +1442,7 @@ export async function createPaseoDaemon(
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
github,
workspaceGitService,
agentManager,
@@ -1585,6 +1593,7 @@ export async function createPaseoDaemon(
github,
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
@@ -1932,6 +1941,7 @@ export async function createPaseoDaemon(
pluginRuntime,
orchestrationSkills,
workspaceLabelService,
workspaceArchiveOperations,
);
pluginRuntime.bindPaseoSessionHost(wsServer);
await pluginRuntime.start();
@@ -943,3 +943,187 @@ export default function contribute(server) {
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("restore waits for an in-flight CLI worktree archive remove before recreating the checkout", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-cli-archive-race-"));
const repository = await createRepo(path.join(root, "repo"));
const removeStartedMarker = path.join(root, "remove-started");
const releaseRemoveMarker = path.join(root, "release-remove");
const pluginDir = path.join(root, "slow-remove-manager");
await mkdir(pluginDir);
await writeFile(
path.join(pluginDir, "paseo-plugin.json"),
JSON.stringify({ id: "slow-remove-manager", requirements: { paseo: ">=0.16.0" } }),
);
await writeFile(
path.join(pluginDir, "index.server.ts"),
`import { execFileSync } from "node:child_process";
import { existsSync, writeFileSync } from "node:fs";
import path from "node:path";
export default function contribute(server) {
return server.registerWorktreeManager({
async create(request) {
const target = path.join(path.dirname(request.repoRoot), "managed-" + request.branch);
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "created", path: target };
},
async remove(request) {
writeFileSync(${JSON.stringify(removeStartedMarker)}, "paused");
const deadline = Date.now() + 15_000;
while (!existsSync(${JSON.stringify(releaseRemoveMarker)})) {
if (Date.now() > deadline) throw new Error("test did not release remove");
await new Promise((resolve) => setTimeout(resolve, 20));
}
execFileSync("git", ["worktree", "remove", request.path, "--force"], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "removed" };
},
async restore(request) {
if (request.target.type !== "branch") return;
execFileSync("git", ["worktree", "add", request.path, request.target.branch], {
cwd: request.repoRoot,
stdio: "pipe",
});
return { type: "restored", path: request.path };
},
});
}
`,
);
const daemon = await createTestPaseoDaemon();
const client1 = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const client2 = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await Promise.all([client1.connect(), client2.connect()]);
await client1.patchDaemonConfig({ pluginsEnabled: true });
expect((await client1.installDirectoryPlugin(pluginDir)).status).toBe("running");
const created = await client1.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "cli-race-branch" },
});
expect(created.error).toBeNull();
const workspaceId = created.workspace!.id;
const worktreePath = created.workspace!.workspaceDirectory;
// Client 1 starts a CLI worktree archive; pause inside manager.remove after the record is archived.
const cliArchive = client1.archivePaseoWorktree({ worktreePath });
await expect
.poll(() =>
stat(removeStartedMarker).then(
() => true,
() => false,
),
)
.toBe(true);
// Client 2 restores while manager.remove still holds the checkout: restore must wait, not unarchive early.
let restoreSettled = false;
const restorePromise = client2.restoreWorkspace(workspaceId);
void restorePromise.then(
() => {
restoreSettled = true;
return undefined;
},
() => {
restoreSettled = true;
return undefined;
},
);
await new Promise((resolve) => setTimeout(resolve, 150));
expect(restoreSettled).toBe(false);
// Release manager.remove to delete the checkout; restore then runs and recreates it cleanly.
await writeFile(releaseRemoveMarker, "go");
const archiveResult = await cliArchive;
expect(archiveResult.success).toBe(true);
await restorePromise;
expect((await stat(worktreePath)).isDirectory()).toBe(true);
expect(git(worktreePath, ["branch", "--show-current"])).toBe("cli-race-branch");
} finally {
await client1.close();
await client2.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
test("undo after a restore queued behind a running archive still cancels before checkout removal", async () => {
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-restore-undo-race-"));
const repository = await createRepo(path.join(root, "repo"));
const teardownStartedMarker = path.join(root, "teardown-started");
const releaseTeardownMarker = path.join(root, "release-teardown");
const teardownScript = path.join(root, "wait-teardown.mjs");
await writeFile(
teardownScript,
`import { existsSync, writeFileSync } from "node:fs";
writeFileSync(${JSON.stringify(teardownStartedMarker)}, "paused");
const deadline = Date.now() + 15_000;
while (!existsSync(${JSON.stringify(releaseTeardownMarker)})) {
if (Date.now() > deadline) throw new Error("test did not release teardown");
await new Promise((resolve) => setTimeout(resolve, 20));
}
`,
);
await writeFile(
path.join(repository, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [`"${process.execPath}" "${teardownScript}"`],
},
}),
);
git(repository, ["add", "paseo.json"]);
git(repository, ["commit", "-m", "add teardown hook"]);
const daemon = await createTestPaseoDaemon();
const client1 = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const client2 = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await Promise.all([client1.connect(), client2.connect()]);
const created = await client1.createWorkspace({
source: { kind: "worktree", cwd: repository, branchName: "undo-race-branch" },
});
expect(created.error).toBeNull();
const workspaceId = created.workspace!.id;
const worktreePath = created.workspace!.workspaceDirectory;
const uncommittedFile = path.join(worktreePath, "uncommitted.txt");
await writeFile(uncommittedFile, "keep-me");
const archivePromise = client1.archiveWorkspace(workspaceId);
await expect
.poll(() =>
stat(teardownStartedMarker).then(
() => true,
() => false,
),
)
.toBe(true);
// Send Restore, then Undo while teardown is still running.
const restorePromise = client2.restoreWorkspace(workspaceId);
await new Promise((resolve) => setTimeout(resolve, 100));
const undoPromise = client1.undoWorkspaceArchive(workspaceId);
await new Promise((resolve) => setTimeout(resolve, 100));
await writeFile(releaseTeardownMarker, "go");
const archiveResult = await archivePromise;
expect(archiveResult.canceled).toBe(true);
await Promise.all([restorePromise, undoPromise]);
expect(await readFile(uncommittedFile, "utf8")).toBe("keep-me");
} finally {
await client1.close();
await client2.close();
await daemon.close();
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
}, 60_000);
+32 -7
View File
@@ -287,7 +287,11 @@ import {
handleWorkspaceSetupStatusRequest as handleWorkspaceSetupStatusRequestMessage,
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
} from "./worktree-session.js";
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
import {
archiveByScope,
resolveWorkspaceBackingPath,
type ActiveWorkspaceRef,
} from "./workspace-archive-service.js";
import {
WorkspaceArchiveOperations,
type WorkspaceArchiveUndoInput,
@@ -1256,10 +1260,13 @@ export class Session {
),
logger: this.sessionLogger,
});
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
agentManager: this.agentManager,
agentStorage: this.agentStorage,
github: this.github,
@@ -1298,7 +1305,6 @@ export class Session {
},
);
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
@@ -5787,11 +5793,13 @@ export class Session {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
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, archivedAt) =>
this.archiveWorkspaceRecord(workspaceId, archivedAt),
@@ -6508,11 +6516,25 @@ export class Session {
};
}
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceArchiveOperations.restore(workspaceId, async () => {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run();
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceArchiveOperations.restore(workspaceId, () =>
this.withWorkspaceCheckout(workspaceId, async () => {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
}),
);
}
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
@@ -8141,6 +8163,7 @@ export class Session {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
@@ -8219,7 +8242,9 @@ export class Session {
): Promise<void> {
try {
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
this.withWorkspaceCheckout(request.workspaceId, () =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
),
);
this.emit({
type: "workspace.archive.undo.response",
+11 -3
View File
@@ -70,6 +70,12 @@ 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";
function resolveWorkspaceArchiveOperations(
operations: WorkspaceArchiveOperations | undefined,
): WorkspaceArchiveOperations {
return operations ?? new WorkspaceArchiveOperations();
}
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";
@@ -618,9 +624,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();
// One lane per workspace and per checkout across the daemon, so archive, undo, and restore
// from any client or background caller coordinate through one boundary.
private readonly workspaceArchiveOperations: WorkspaceArchiveOperations;
private readonly providerSnapshotManager: ProviderSnapshotManager;
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
private onBranchChanged!:
@@ -711,9 +717,11 @@ export class VoiceAssistantWebSocketServer {
pluginRuntime?: SessionOptions["pluginRuntime"],
orchestrationSkills?: SessionOptions["orchestrationSkills"],
workspaceLabelService?: WorkspaceLabelService,
workspaceArchiveOperations?: WorkspaceArchiveOperations,
) {
this.logger = logger.child({ module: "websocket-server" });
this.workspaceSetupRuntime = workspaceSetupRuntime;
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.advertiseDaemonStatusRpc = wsConfig.daemonStatusRpc !== false;
this.advertiseRelayConfig = wsConfig.relayConfig !== false;
this.connectionLifecycle = wsConfig.startPaused === true ? "starting" : "accepting";
@@ -301,4 +301,118 @@ describe("WorkspaceArchiveOperations", () => {
});
expect(calls).toBe(2);
});
test("undo after a restore queued behind a running archive still aborts the archive and shares the undo outcome", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
let restoreCalls = 0;
const archiveDone = operations.archive("ws", async (signal) => {
try {
return await archive.run(signal);
} finally {
order.push("archive stopped");
}
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
order.push("restore");
});
expect(archive.aborted).toBe(false);
const undoDone = operations.undo("ws", async ({ archivedAt }) => {
order.push(`undo:${archivedAt}`);
});
expect(archive.aborted).toBe(true);
archive.release();
await expect(archiveDone).resolves.toEqual({ kind: "canceled", archivedAt: "stamp" });
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(0);
expect(order).toEqual(["archive stopped", "undo:stamp"]);
});
test("restore queued behind a running archive waits without aborting it when no undo arrives", async () => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const order: string[] = [];
const archiveDone = operations.archive("ws", async (signal) => {
const result = await archive.run(signal);
order.push("archived");
return result;
});
await archive.started;
const restoreDone = operations.restore("ws", async () => {
order.push("restored");
});
expect(archive.aborted).toBe(false);
archive.release();
await expect(archiveDone).resolves.toMatchObject({ kind: "archived" });
await restoreDone;
expect(order).toEqual(["archived", "restored"]);
});
test("undo after restore has already started joins the running restore", async () => {
const operations = new WorkspaceArchiveOperations();
await operations.archive("ws", async () => archived(["agent-a"]));
const restoreGate = deferred();
let restoreCalls = 0;
let undoCalls = 0;
const restoreDone = operations.restore("ws", async () => {
restoreCalls += 1;
await restoreGate.promise;
});
// Flush microtask so restore has moved past any settled archive check.
await Promise.resolve();
const undoDone = operations.undo("ws", async () => {
undoCalls += 1;
});
restoreGate.resolve();
await Promise.all([restoreDone, undoDone]);
expect(restoreCalls).toBe(1);
expect(undoCalls).toBe(0);
});
test("withCheckout serializes operations on the same checkout path while allowing independent checkouts in parallel", async () => {
const operations = new WorkspaceArchiveOperations();
const firstGate = deferred();
const firstStarted = deferred();
const order: string[] = [];
const first = operations.withCheckout("/tmp/paseo-checkout-a", async () => {
order.push("a1-start");
firstStarted.resolve();
await firstGate.promise;
order.push("a1-end");
return "first";
});
await firstStarted.promise;
const second = operations.withCheckout("/tmp/paseo-checkout-a/", async () => {
order.push("a2");
return "second";
});
const other = operations.withCheckout("/tmp/paseo-checkout-b", async () => {
order.push("b");
return "other";
});
await expect(other).resolves.toBe("other");
expect(order).toEqual(["a1-start", "b"]);
firstGate.resolve();
await expect(first).resolves.toBe("first");
await expect(second).resolves.toBe("second");
expect(order).toEqual(["a1-start", "b", "a1-end", "a2"]);
});
});
@@ -1,3 +1,6 @@
import { resolve } from "node:path";
import { normalizePathForIdentity } from "../utils/path.js";
import { type ArchiveResult, WorkspaceArchiveCanceledError } from "./workspace-archive-service.js";
export type WorkspaceArchiveOutcome =
@@ -8,23 +11,42 @@ export interface WorkspaceArchiveUndoInput {
archivedAt?: string;
}
interface PendingArchive {
controller: AbortController;
done: Promise<WorkspaceArchiveOutcome>;
}
type LaneEntry =
| { kind: "archiving"; controller: AbortController; done: Promise<WorkspaceArchiveOutcome> }
| {
kind: "restoring";
pendingArchive: PendingArchive | null;
supersededBy: Promise<void> | null;
done: Promise<void>;
}
| { kind: "undoing"; done: Promise<void> };
/**
* One lane per workspace for archive and its undo, shared by every session on the daemon.
* Daemon-wide coordinator for workspace archive, undo, and restore operations.
*
* Per-workspace lanes:
* - 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.
* - An undo while an archive runs (including when a restore queued behind it) aborts the archive,
* waits for it to stop, then restores.
* - A restore while an archive runs waits for the archive without aborting it, then restores.
* - An archive while an undo or restore runs waits for it, then archives.
* - A duplicate undo or restore while recovery 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.
* Per-checkout gates:
* - Any archive or recovery mutating the same backing checkout directory (including CLI worktree
* archives covering multiple workspace records, background auto-archives, and sibling workspaces
* sharing one checkout) serializes through `withCheckout` so a restore cannot inspect or unarchive
* a checkout while an archive is still deleting it.
* - Lock order is strictly workspace lane -> checkout gate, preventing deadlocks.
*/
export class WorkspaceArchiveOperations {
private readonly lanes = new Map<string, LaneEntry>();
private readonly checkoutGates = new Map<string, Promise<void>>();
archive(
workspaceId: string,
@@ -57,12 +79,23 @@ export class WorkspaceArchiveOperations {
if (current?.kind === "undoing") {
return current.done;
}
current?.controller.abort();
if (current?.kind === "restoring" && current.pendingArchive === null) {
return current.done;
}
let pendingArchive: PendingArchive | null = null;
if (current?.kind === "archiving") {
pendingArchive = { controller: current.controller, done: current.done };
} else if (current?.kind === "restoring") {
pendingArchive = current.pendingArchive;
}
pendingArchive?.controller.abort();
const done = (async () => {
const outcome =
current?.kind === "archiving" ? await current.done.catch(() => undefined) : undefined;
const outcome = pendingArchive ? await pendingArchive.done.catch(() => undefined) : undefined;
await restore({ archivedAt: outcome?.kind === "canceled" ? outcome.archivedAt : undefined });
})();
if (current?.kind === "restoring") {
current.supersededBy = done;
}
this.claim(workspaceId, { kind: "undoing", done });
return done;
}
@@ -70,18 +103,66 @@ export class WorkspaceArchiveOperations {
/**
* Run a workspace recovery restore on the per-workspace lane so concurrent restores
* across daemon sessions share one outcome and wait for checkout + validation to settle.
* When queued behind an in-flight archive, the archive stays cancelable by a subsequent undo.
*/
restore(workspaceId: string, run: () => Promise<void>): Promise<void> {
const current = this.lanes.get(workspaceId);
if (current?.kind === "undoing") {
if (current?.kind === "undoing" || current?.kind === "restoring") {
return current.done;
}
const done = (async () => {
await settled(current?.done);
const pendingArchive: PendingArchive | null =
current?.kind === "archiving" ? { controller: current.controller, done: current.done } : null;
const entry: Extract<LaneEntry, { kind: "restoring" }> = {
kind: "restoring",
pendingArchive,
supersededBy: null,
done: Promise.resolve(),
};
entry.done = (async () => {
if (pendingArchive) {
await settled(pendingArchive.done);
entry.pendingArchive = null;
if (entry.supersededBy) {
await entry.supersededBy;
return;
}
} else {
await settled(current?.done);
}
await run();
})();
this.claim(workspaceId, { kind: "undoing", done });
return done;
this.claim(workspaceId, entry);
return entry.done;
}
/**
* Serialize mutations touching the same backing checkout directory across all daemon callers
* (UI archive, CLI worktree archive, background auto-archive, undo, and recovery restore).
*/
withCheckout<T>(checkoutPath: string, run: () => Promise<T>): Promise<T> {
const key = normalizePathForIdentity(resolve(checkoutPath));
const previous = this.checkoutGates.get(key);
let release!: () => void;
const current = new Promise<void>((resolveGate) => {
release = resolveGate;
});
const gate = previous ? previous.then(() => current) : current;
this.checkoutGates.set(key, gate);
const cleanup = () => {
if (this.checkoutGates.get(key) === gate) {
this.checkoutGates.delete(key);
}
};
void gate.then(cleanup, cleanup);
return (async () => {
await settled(previous);
try {
return await run();
} finally {
release();
}
})();
}
private claim(workspaceId: string, entry: LaneEntry): void {
@@ -23,6 +23,7 @@ import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
export type ActiveWorkspaceRef = Pick<
PersistedWorkspaceRecord,
@@ -37,6 +38,7 @@ export interface ArchiveDependencies {
// Base directory that may hold worktrees across repositories.
paseoWorktreesBaseRoot?: string;
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: Pick<WorkspaceArchiveOperations, "withCheckout">;
github: ForgeService;
workspaceGitService: Pick<WorkspaceGitService, "getSnapshot" | "invalidateWorktrees">;
agentManager: Pick<AgentManager, "listAgents" | "getAgent" | "archiveAgent" | "archiveSnapshot">;
@@ -149,6 +151,13 @@ export async function resolveWorkspaceIdAtPath(
return dependencies.findWorkspaceIdForCwd(targetPath);
}
export async function resolveWorkspaceBackingPath(
workspace: ActiveWorkspaceRef,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<string> {
return (await resolveWorkspaceBackingDirectory(workspace, dependencies)).path;
}
// Resolves the in-scope record set, tears each down
// (agents + terminals + record), then removes the backing directory iff it is
// Paseo-owned AND no active workspace still references it.
@@ -171,69 +180,98 @@ async function archiveByScopeWithPriority(
};
checkpoint();
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
const runArchive = async (): Promise<ArchiveResult> => {
checkpoint();
const target = await resolveArchiveTarget(dependencies, request.scope);
const targetWorkspaceIds = target.workspaceIds;
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
await stopWorkspaceSetups(dependencies, target.setupWorkspaceIds, request.requestId);
checkpoint();
if (targetWorkspaceIds.length > 0) {
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
}
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
try {
if (targetWorkspaceIds.length > 0) {
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
dependencies.markWorkspaceArchiving(targetWorkspaceIds, new Date().toISOString());
}
checkpoint();
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
let removedDirectory = false;
let directoryLeftBehind: ArchiveResult["directoryLeftBehind"];
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
try {
if (targetWorkspaceIds.length > 0) {
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
checkpoint();
const { archivedAgents, archivedWorkspaceIds } = await archiveTargetRecords(
dependencies,
targetWorkspaceIds,
{ requestId: request.requestId, checkpoint, archivedAt },
);
checkpoint();
if (target.backing?.mainRepoRoot) {
try {
await dependencies.workspaceGitService.getSnapshot(target.backing.mainRepoRoot, {
force: true,
reason: "archive-worktree",
});
} catch (error) {
dependencies.sessionLogger?.warn(
{ err: error, cwd: target.backing.mainRepoRoot, requestId: request.requestId },
"Failed to force-refresh workspace git snapshot after archiving",
);
}
}
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
);
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
return {
archivedAgentIds: Array.from(archivedAgents),
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
}
};
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
target,
archivedWorkspaceIds,
);
removedDirectory = removal.removedDirectory;
directoryLeftBehind = removal.directoryLeftBehind;
}
return {
archivedAgentIds: Array.from(archivedAgents),
archivedWorkspaceIds,
removedDirectory,
...(directoryLeftBehind ? { directoryLeftBehind } : {}),
};
} finally {
if (targetWorkspaceIds.length > 0) {
dependencies.clearWorkspaceArchiving(targetWorkspaceIds);
await dependencies.emitWorkspaceUpdatesForWorkspaceIds(targetWorkspaceIds);
}
const checkoutPath = dependencies.workspaceArchiveOperations
? await resolveArchiveCheckoutPath(dependencies, request.scope)
: null;
if (dependencies.workspaceArchiveOperations && checkoutPath) {
return dependencies.workspaceArchiveOperations.withCheckout(checkoutPath, runArchive);
}
return runArchive();
}
async function resolveArchiveCheckoutPath(
dependencies: ArchiveDependencies,
scope: ArchiveScope,
): Promise<string | null> {
if (scope.kind === "workspace") {
const record =
(await dependencies.getWorkspace?.(scope.workspaceId)) ??
(await dependencies.listActiveWorkspaces()).find(
(workspace) => workspace.workspaceId === scope.workspaceId,
);
if (!record) {
return null;
}
return resolveWorkspaceBackingPath(record, dependencies);
}
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
}
async function resolveArchiveTarget(
+21 -1
View File
@@ -78,7 +78,7 @@ export function isPathInsideRoot(root: string, candidate: string): boolean {
}
export function normalizePathForIdentity(value: string): string {
const canonicalPath = resolveRealpathVariants(value)[0] ?? value;
const canonicalPath = resolveNearestExistingAncestorRealpath(value);
return normalizePathForComparison(canonicalPath, looksLikeDefiniteWindowsPath(canonicalPath));
}
@@ -150,6 +150,26 @@ function resolveRealpathVariants(value: string): string[] {
return variants;
}
function resolveNearestExistingAncestorRealpath(value: string): string {
if (process.platform !== "win32" && looksLikeDefiniteWindowsPath(value)) {
return value;
}
const tail: string[] = [];
let current = value;
while (true) {
const resolved = resolveRealpathVariants(current)[0];
if (resolved) {
return tail.length === 0 ? resolved : nodePath.join(resolved, ...tail.toReversed());
}
const parent = nodePath.dirname(current);
if (parent === current) {
return value;
}
tail.push(nodePath.basename(current));
current = parent;
}
}
function shouldCompareAsWindows(left: string, right: string): boolean {
return looksLikeDefiniteWindowsPath(left) || looksLikeDefiniteWindowsPath(right);
}