diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 4186660911..491ffe41f7 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -1175,25 +1175,12 @@ export async function createPaseoDaemon( untrustedSource: workspace.untrustedSource, })); }; - const markWorkspaceArchivingExternal = (workspaceIds: Iterable, archivingAt: string) => { - const workspaceIdList = Array.from(workspaceIds); - for (const session of wsServer?.listSessions() ?? []) { - session.markWorkspaceArchivingForExternalMutation(workspaceIdList, archivingAt); - } - }; - const clearWorkspaceArchivingExternal = (workspaceIds: Iterable) => { - const workspaceIdList = Array.from(workspaceIds); - for (const session of wsServer?.listSessions() ?? []) { - session.clearWorkspaceArchivingForExternalMutation(workspaceIdList); - } - }; + const markWorkspaceArchiving = (workspaceIds: Iterable, archivingAt: string) => + workspaceArchiveOperations.markArchiving(workspaceIds, archivingAt); + const clearWorkspaceArchiving = (workspaceIds: Iterable) => + workspaceArchiveOperations.clearArchiving(workspaceIds); const emitWorkspaceUpdatesExternal = async (workspaceIds: Iterable) => { - const workspaceIdList = Array.from(workspaceIds); - await Promise.all( - (wsServer?.listSessions() ?? []).map((session) => - session.emitWorkspaceUpdatesForExternalWorkspaceIds(workspaceIdList), - ), - ); + await wsServer?.publishWorkspaceUpdates(workspaceIds); }; const ensureWorkspaceForCreateAndBroadcastExternal = async ( cwd: string, @@ -1247,8 +1234,8 @@ export async function createPaseoDaemon( getAutoArchivedChangeRequestUrl: async (workspaceId) => (await workspaceRegistry.get(workspaceId))?.autoArchivedChangeRequestUrl ?? null, archiveWorkspaceRecord: archiveWorkspaceRecordExternal, - markWorkspaceArchiving: markWorkspaceArchivingExternal, - clearWorkspaceArchiving: clearWorkspaceArchivingExternal, + markWorkspaceArchiving, + clearWorkspaceArchiving, emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, }); @@ -1336,8 +1323,8 @@ export async function createPaseoDaemon( archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) => archiveWorkspaceRecordExternal(workspaceIdToArchive, undefined, archivedAt), emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, - markWorkspaceArchiving: markWorkspaceArchivingExternal, - clearWorkspaceArchiving: clearWorkspaceArchivingExternal, + markWorkspaceArchiving, + clearWorkspaceArchiving, killTerminalsForWorkspace: (workspaceIdToKill) => killTerminalsForWorkspace({ terminalManager, sessionLogger: logger }, workspaceIdToKill), stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop), @@ -1368,8 +1355,8 @@ export async function createPaseoDaemon( emit: emitExternalSessionMessage, emitAgentRemove: async () => undefined, emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, - markWorkspaceArchiving: markWorkspaceArchivingExternal, - clearWorkspaceArchiving: clearWorkspaceArchivingExternal, + markWorkspaceArchiving, + clearWorkspaceArchiving, killTerminalsForWorkspace: (workspaceId) => killTerminalsForWorkspace({ terminalManager, sessionLogger: logger }, workspaceId), logger, @@ -1465,8 +1452,8 @@ export async function createPaseoDaemon( archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) => archiveWorkspaceRecordExternal(workspaceIdToArchive, undefined, archivedAt), emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, - markWorkspaceArchiving: markWorkspaceArchivingExternal, - clearWorkspaceArchiving: clearWorkspaceArchivingExternal, + markWorkspaceArchiving, + clearWorkspaceArchiving, killTerminalsForWorkspace: (workspaceIdToKill) => killTerminalsForWorkspace( { @@ -1644,8 +1631,8 @@ export async function createPaseoDaemon( assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, workspaceId), getGlobalServicePorts: () => daemonConfigStore.readServicePorts(), }), - markWorkspaceArchiving: markWorkspaceArchivingExternal, - clearWorkspaceArchiving: clearWorkspaceArchivingExternal, + markWorkspaceArchiving, + clearWorkspaceArchiving, ensureWorkspaceForCreate: createAgentCommandDependencies.ensureWorkspaceForCreate, createPaseoWorktree: createAgentCommandDependencies.createPaseoWorktree, browserToolsEnabled: browserToolsPolicy.isEnabled(), diff --git a/packages/server/src/server/owned-subscriptions.e2e.test.ts b/packages/server/src/server/owned-subscriptions.e2e.test.ts index 75822ffeca..83269fc443 100644 --- a/packages/server/src/server/owned-subscriptions.e2e.test.ts +++ b/packages/server/src/server/owned-subscriptions.e2e.test.ts @@ -15,6 +15,7 @@ import { TerminalStreamOpcode, } from "@getpaseo/protocol/binary-frames/index"; import { DaemonClient } from "./test-utils/daemon-client.js"; +import { createTestAgentClients } from "./test-utils/fake-agent-client.js"; import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js"; import { withTimeout } from "../utils/promise-timeout.js"; import { @@ -1977,6 +1978,77 @@ test("public project subscriptions request updates and release their producer de } }); +test("another session lists and receives the archiving timestamp during agent teardown", async () => { + const teardownStarted = Promise.withResolvers(); + const teardownReleased = Promise.withResolvers(); + const daemon = await createTestPaseoDaemon({ + agentClients: createTestAgentClients({ + closeSession: async () => { + teardownStarted.resolve(); + await teardownReleased.promise; + }, + }), + }); + const url = `ws://127.0.0.1:${daemon.port}/ws`; + const initiator = new DaemonClient({ url }); + const observer = new DaemonClient({ url }); + const paseo = createPaseoApi(observer); + + try { + await Promise.all([initiator.connect(), observer.connect()]); + const created = await initiator.createWorkspace({ + source: { kind: "directory", path: daemon.staticDir }, + }); + if (!created.workspace) throw new Error(created.error ?? "Failed to create workspace"); + const workspaceId = created.workspace.id; + await initiator.createAgent({ provider: "codex", cwd: daemon.staticDir, workspaceId }); + + const initial = await paseo.workspaces.list({ subscribe: {} }); + expect(initial.entries.find((entry) => entry.id === workspaceId)?.archivingAt).toBeNull(); + const timestamps: Array = []; + initial.subscription.subscribe({ + snapshot: () => {}, + update: ({ type, payload }) => { + if ( + type === "workspace_update" && + payload.kind === "upsert" && + payload.workspace.id === workspaceId + ) { + timestamps.push(payload.workspace.archivingAt); + } + }, + }); + + const archive = initiator.archiveWorkspace(workspaceId); + try { + await Promise.race([ + teardownStarted.promise, + archive.then(() => { + throw new Error("Archive completed before agent teardown started"); + }), + ]); + + const initiating = await initiator.fetchWorkspaces(); + const archivingAt = initiating.entries.find((entry) => entry.id === workspaceId)?.archivingAt; + expect(archivingAt).toEqual(expect.any(String)); + + const observed = await paseo.workspaces.list(); + expect(observed.entries.find((entry) => entry.id === workspaceId)?.archivingAt).toBe( + archivingAt, + ); + expect(timestamps).toContain(archivingAt); + } finally { + teardownReleased.resolve(); + await archive; + } + } finally { + teardownReleased.resolve(); + await paseo.dispose(); + await Promise.all([initiator.close(), observer.close()]); + await daemon.close(); + } +}); + test.each([ { closed: false, batch: false }, { closed: true, batch: false }, diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index a3d5976508..f86193f9a6 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -506,6 +506,7 @@ export interface SessionOptions { getTransportBufferedAmount?: (source?: object) => number | null; getConnectedHostBufferedAmount?: () => number | null; onLifecycleIntent?: (intent: SessionLifecycleIntent) => void; + publishWorkspaceArchiveUpdates?: (workspaceIds: Iterable) => Promise; onWorkspaceRecovered?: (workspace: PersistedWorkspaceRecord) => Promise; publishScriptStatusUpdate?: (message: ScriptStatusUpdateMessage) => void; logger: pino.Logger; @@ -803,6 +804,7 @@ export class Session { | null; private readonly getTransportBufferedAmount: (source?: object) => number | null; private readonly onLifecycleIntent: ((intent: SessionLifecycleIntent) => void) | null; + private readonly onWorkspaceArchiveUpdate: SessionOptions["publishWorkspaceArchiveUpdates"]; private readonly onWorkspaceRecovered: | ((workspace: PersistedWorkspaceRecord) => Promise) | null; @@ -978,6 +980,7 @@ export class Session { : null; this.getTransportBufferedAmount = getTransportBufferedAmount ?? (() => 0); this.onLifecycleIntent = onLifecycleIntent ?? null; + this.onWorkspaceArchiveUpdate = options.publishWorkspaceArchiveUpdates; this.onWorkspaceRecovered = onWorkspaceRecovered ?? null; this.pushNotifications = pushNotifications; this.paseoHome = paseoHome; @@ -1308,8 +1311,7 @@ export class Session { archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId), emit: (message) => this.emit(message), emitAgentRemove: (agentId) => this.agentUpdates.removeAgent(agentId), - emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) => - this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds), + emitWorkspaceUpdatesForWorkspaceIds: this.publishWorkspaceArchiveUpdates, markWorkspaceArchiving: (workspaceIds, archivingAt) => this.markWorkspaceArchiving(workspaceIds, archivingAt), clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds), @@ -1361,6 +1363,7 @@ export class Session { getGlobalServicePorts: () => this.daemonConfigStore.readServicePorts(), }); this.workspaceDirectory = new WorkspaceDirectory({ + getArchivingAt: (workspaceId) => this.workspaceArchiveOperations.getArchivingAt(workspaceId), logger: this.sessionLogger, projectRegistry: this.projectRegistry, workspaceRegistry: this.workspaceRegistry, @@ -1684,16 +1687,11 @@ export class Session { }); } - markWorkspaceArchivingForExternalMutation( + private readonly publishWorkspaceArchiveUpdates = ( workspaceIds: Iterable, - archivingAt: string, - ): void { - this.markWorkspaceArchiving(workspaceIds, archivingAt); - } - - clearWorkspaceArchivingForExternalMutation(workspaceIds: Iterable): void { - this.clearWorkspaceArchiving(workspaceIds); - } + ): Promise => + this.onWorkspaceArchiveUpdate?.(workspaceIds) ?? + this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds); async emitWorkspaceUpdatesForExternalWorkspaceIds(workspaceIds: Iterable): Promise { await this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds); @@ -4217,13 +4215,12 @@ export class Session { .filter((workspace) => !workspace.archivedAt) .map((workspace) => workspace.workspaceId); - if (activeWorkspaceIds.length > 0) { - this.markWorkspaceArchiving(activeWorkspaceIds, new Date().toISOString()); - await this.emitWorkspaceUpdatesForWorkspaceIds(activeWorkspaceIds); - } - const removedWorkspaceIds: string[] = []; + this.markWorkspaceArchiving(activeWorkspaceIds, new Date().toISOString()); try { + if (activeWorkspaceIds.length > 0) { + await this.publishWorkspaceArchiveUpdates(activeWorkspaceIds); + } for (const workspaceId of activeWorkspaceIds) { const archivedAt = new Date().toISOString(); await archiveWorkspaceContents( @@ -4251,20 +4248,19 @@ export class Session { "Failed to clean up removed project icon", ); }); + + const updateIds = + removedWorkspaceIds.length > 0 + ? removedWorkspaceIds + : [projectWorkspaces[0]?.workspaceId ?? projectId]; + await this.emitWorkspaceUpdatesForWorkspaceIds(updateIds, { removedProjectId: projectId }); } finally { + this.clearWorkspaceArchiving(activeWorkspaceIds); if (activeWorkspaceIds.length > 0) { - this.clearWorkspaceArchiving(activeWorkspaceIds); + await this.publishWorkspaceArchiveUpdates(activeWorkspaceIds); } } - const updateIds = - removedWorkspaceIds.length > 0 - ? removedWorkspaceIds - : [projectWorkspaces[0]?.workspaceId ?? projectId]; - await this.emitWorkspaceUpdatesForWorkspaceIds(updateIds, { - removedProjectId: projectId, - }); - this.emit({ type: "project.remove.response", payload: { @@ -5835,8 +5831,7 @@ export class Session { archiveWorkspaceRecord: (workspaceId, archivedAt) => this.archiveWorkspaceRecord(workspaceId, archivedAt), emit: (message) => this.emit(message), - emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) => - this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds), + emitWorkspaceUpdatesForWorkspaceIds: this.publishWorkspaceArchiveUpdates, markWorkspaceArchiving: (workspaceIds, archivingAt) => this.markWorkspaceArchiving(workspaceIds, archivingAt), clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds), @@ -6403,11 +6398,11 @@ export class Session { } markWorkspaceArchiving(workspaceIds: Iterable, archivingAt: string): void { - this.workspaceDirectory.markArchiving(workspaceIds, archivingAt); + this.workspaceArchiveOperations.markArchiving(workspaceIds, archivingAt); } clearWorkspaceArchiving(workspaceIds: Iterable): void { - this.workspaceDirectory.clearArchiving(workspaceIds); + this.workspaceArchiveOperations.clearArchiving(workspaceIds); } private async buildWorkspaceDescriptorMap(options: { @@ -8253,8 +8248,7 @@ export class Session { listActiveWorkspaces: () => this.listActiveWorkspaceRefs(), archiveWorkspaceRecord: (workspaceId, archivedAt) => this.archiveWorkspaceRecord(workspaceId, archivedAt), - emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) => - this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds), + emitWorkspaceUpdatesForWorkspaceIds: this.publishWorkspaceArchiveUpdates, markWorkspaceArchiving: (workspaceIds, archivingAt) => this.markWorkspaceArchiving(workspaceIds, archivingAt), clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds), diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 4a683907a4..2d23e2b4ba 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -1086,6 +1086,19 @@ export class VoiceAssistantWebSocketServer { ); } + public async publishWorkspaceUpdates(workspaceIds: Iterable): Promise { + const ids = Array.from(workspaceIds); + await Promise.all( + this.listSessions().map(async (session) => { + try { + await session.emitWorkspaceUpdatesForExternalWorkspaceIds(ids); + } catch (error) { + this.logger.warn({ err: error }, "Failed to publish workspace updates"); + } + }), + ); + } + public publishProjectUpdate(update: ProjectUpdate): void { for (const session of this.listSessions()) { void session @@ -1689,6 +1702,7 @@ export class VoiceAssistantWebSocketServer { getTransportBufferedAmount: options.getTransportBufferedAmount, onLifecycleIntent: options.onLifecycleIntent, logger: options.connectionLogger.child({ module: "session" }), + publishWorkspaceArchiveUpdates: (workspaceIds) => this.publishWorkspaceUpdates(workspaceIds), onWorkspaceRecovered: async (workspace) => { await Promise.all( this.listSessions().map((activeSession) => diff --git a/packages/server/src/server/workspace-archive-operations.ts b/packages/server/src/server/workspace-archive-operations.ts index 44ba6f4caf..144d7846db 100644 --- a/packages/server/src/server/workspace-archive-operations.ts +++ b/packages/server/src/server/workspace-archive-operations.ts @@ -48,6 +48,30 @@ export class WorkspaceArchiveOperations { private readonly lanes = new Map(); private readonly checkoutGates = new Map>(); + // Project removal can overlap a checkout-scoped archive of the same workspace. + private readonly archiving = new Map(); + + getArchivingAt(workspaceId: string): string | null { + return this.archiving.get(workspaceId)?.startedAt ?? null; + } + + markArchiving(workspaceIds: Iterable, startedAt: string): void { + for (const id of workspaceIds) { + const current = this.archiving.get(id); + if (current) current.count += 1; + else this.archiving.set(id, { startedAt, count: 1 }); + } + } + + clearArchiving(workspaceIds: Iterable): void { + for (const id of workspaceIds) { + const current = this.archiving.get(id); + if (!current) continue; + current.count -= 1; + if (current.count === 0) this.archiving.delete(id); + } + } + archive( workspaceId: string, run: (signal: AbortSignal) => Promise, diff --git a/packages/server/src/server/workspace-directory.test.ts b/packages/server/src/server/workspace-directory.test.ts index 2f8902956e..8a36ec8a4b 100644 --- a/packages/server/src/server/workspace-directory.test.ts +++ b/packages/server/src/server/workspace-directory.test.ts @@ -79,6 +79,7 @@ class WorkspaceStatus { activity: TerminalActivity | null; }> = []; private readonly directory = new WorkspaceDirectory({ + getArchivingAt: () => null, logger: createTestLogger(), projectRegistry: { list: async () => [this.project] }, workspaceRegistry: { @@ -632,6 +633,7 @@ describe("WorkspaceDirectory empty projects", () => { workspaces: PersistedWorkspaceRecord[]; }): WorkspaceDirectory { return new WorkspaceDirectory({ + getArchivingAt: () => null, logger: createTestLogger(), projectRegistry: { list: async () => input.projects }, workspaceRegistry: { @@ -793,6 +795,7 @@ test("Git observation targets exclude archived records without hydrating app des throw new Error("Watcher reconciliation hydrated app data"); }; const directory = new WorkspaceDirectory({ + getArchivingAt: () => null, logger: createTestLogger(), projectRegistry: { list: async () => [project("active"), project("archived", NOW)] }, workspaceRegistry: { @@ -964,6 +967,7 @@ test("scoped descriptor builds allocate independently of archived history", asyn isStoredProviderAvailable: () => true, }); const directory = new WorkspaceDirectory({ + getArchivingAt: () => null, logger, workspaceRegistry: registry, projectRegistry: { diff --git a/packages/server/src/server/workspace-directory.ts b/packages/server/src/server/workspace-directory.ts index 0166e76002..31c2a8e95f 100644 --- a/packages/server/src/server/workspace-directory.ts +++ b/packages/server/src/server/workspace-directory.ts @@ -78,6 +78,7 @@ export interface WorkspaceDirectoryDeps { listActive(): Promise; get(id: string): Promise; }; + getArchivingAt(workspaceId: string): string | null; listAgentPayloads(workspaceIds?: Iterable): Promise; workspaceLastUserMessageTimes( workspaceIds?: Iterable, @@ -171,7 +172,6 @@ function activeWorkspaceRecords( } export class WorkspaceDirectory { - private readonly archivingByWorkspaceId = new Map(); /** * Per-workspace last-seen winning bucket + entered-at. Persists across * `buildDescriptorMap` calls inside the daemon process; reset on cold start. @@ -205,18 +205,6 @@ export class WorkspaceDirectory { constructor(private readonly deps: WorkspaceDirectoryDeps) {} - markArchiving(workspaceIds: Iterable, archivingAt: string): void { - for (const workspaceId of workspaceIds) { - this.archivingByWorkspaceId.set(workspaceId, archivingAt); - } - } - - clearArchiving(workspaceIds: Iterable): void { - for (const workspaceId of workspaceIds) { - this.archivingByWorkspaceId.delete(workspaceId); - } - } - async buildDescriptorMap(options: { includeGitData: boolean; workspaceIds?: Iterable; @@ -273,7 +261,7 @@ export class WorkspaceDirectory { ...workspaceDescriptors[i], createdAt: includedWorkspaces[i].createdAt, lastUserMessageAt: lastUserMessageTimes.get(workspaceId) ?? null, - archivingAt: this.archivingByWorkspaceId.get(workspaceId) ?? null, + archivingAt: this.deps.getArchivingAt(workspaceId), }); }