From b2679012ff7e425e519cb752c11de7f3e430aa10 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 12:55:35 +0100 Subject: [PATCH] fix(server): coordinate archive, undo, and restore across daemon checkout boundary --- .../agent/create-agent-lifecycle-dispatch.ts | 10 +- .../src/server/agent/tools/paseo-tools.ts | 5 + .../auto-archive-on-merge/archive-if-safe.ts | 5 + packages/server/src/server/bootstrap.ts | 10 + .../plugins/worktree-manager.e2e.test.ts | 184 ++++++++++++++++++ packages/server/src/server/session.ts | 39 +++- .../server/src/server/websocket-server.ts | 14 +- .../workspace-archive-operations.test.ts | 114 +++++++++++ .../server/workspace-archive-operations.ts | 109 +++++++++-- .../src/server/workspace-archive-service.ts | 142 +++++++++----- packages/server/src/utils/path.ts | 22 ++- 11 files changed, 576 insertions(+), 78 deletions(-) diff --git a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts index 6c040c50d3..25697a968e 100644 --- a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts +++ b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts @@ -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; + 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, diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 364a1da2ca..11863088e6 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -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, diff --git a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts index df493f2744..aaec4cd006 100644 --- a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts +++ b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts @@ -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; + 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( diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index ed18b8a517..f87c600f28 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -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(); diff --git a/packages/server/src/server/plugins/worktree-manager.e2e.test.ts b/packages/server/src/server/plugins/worktree-manager.e2e.test.ts index 0016bbebd7..026025d662 100644 --- a/packages/server/src/server/plugins/worktree-manager.e2e.test.ts +++ b/packages/server/src/server/plugins/worktree-manager.e2e.test.ts @@ -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); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 16508729a7..6d4e3dfe45 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -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 { - await this.workspaceArchiveOperations.restore(workspaceId, async () => { - await this.workspaceRecovery.restore(workspaceId); - await this.publishRecoveredWorkspace(workspaceId); + private async withWorkspaceCheckout(workspaceId: string, run: () => Promise): Promise { + 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 { + await this.workspaceArchiveOperations.restore(workspaceId, () => + this.withWorkspaceCheckout(workspaceId, async () => { + await this.workspaceRecovery.restore(workspaceId); + await this.publishRecoveredWorkspace(workspaceId); + }), + ); } private async publishRecoveredWorkspace(workspaceId: string): Promise { @@ -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 { 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", diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 7aabed0d23..4a683907a4 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -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(); 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"; diff --git a/packages/server/src/server/workspace-archive-operations.test.ts b/packages/server/src/server/workspace-archive-operations.test.ts index 68df2631cc..b3bc8cb38c 100644 --- a/packages/server/src/server/workspace-archive-operations.test.ts +++ b/packages/server/src/server/workspace-archive-operations.test.ts @@ -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"]); + }); }); diff --git a/packages/server/src/server/workspace-archive-operations.ts b/packages/server/src/server/workspace-archive-operations.ts index 120097e0e5..44ba6f4caf 100644 --- a/packages/server/src/server/workspace-archive-operations.ts +++ b/packages/server/src/server/workspace-archive-operations.ts @@ -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; +} + type LaneEntry = | { kind: "archiving"; controller: AbortController; done: Promise } + | { + kind: "restoring"; + pendingArchive: PendingArchive | null; + supersededBy: Promise | null; + done: Promise; + } | { kind: "undoing"; done: Promise }; /** - * 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(); + private readonly checkoutGates = new Map>(); 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): Promise { 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 = { + 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(checkoutPath: string, run: () => Promise): Promise { + const key = normalizePathForIdentity(resolve(checkoutPath)); + const previous = this.checkoutGates.get(key); + let release!: () => void; + const current = new Promise((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 { diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 8650aa2596..2d065f7f65 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -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; + workspaceArchiveOperations?: Pick; github: ForgeService; workspaceGitService: Pick; agentManager: Pick; @@ -149,6 +151,13 @@ export async function resolveWorkspaceIdAtPath( return dependencies.findWorkspaceIdForCwd(targetPath); } +export async function resolveWorkspaceBackingPath( + workspace: ActiveWorkspaceRef, + dependencies: Pick, +): Promise { + 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 => { + 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 { + 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( diff --git a/packages/server/src/utils/path.ts b/packages/server/src/utils/path.ts index 45cb8b01b5..d7cbeaa454 100644 --- a/packages/server/src/utils/path.ts +++ b/packages/server/src/utils/path.ts @@ -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); }