From a138bea3eefd20b748fb3514f613506ac3e8f036 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Fri, 20 Nov 2026 22:52:28 +0700 Subject: [PATCH] fix(app): hold workspace updates that arrive while the directory cache loads A project update received while the cached directory was being read went straight into the replica. It advanced the project cursor before any refresh had established a baseline, and saved that cursor to the cache. On an install damaged before the eviction fix, that write replaced the version 1 checkpoint with a version 2 one before the reader could reject it. The refresh then asked for project changes after the live update, the daemon had none, and projects missing from the cache stayed missing across restarts. Agents already open a transaction before the cache load, so their updates are recorded and applied over the refreshed snapshot. Workspaces now do the same. An update during the load also stops the cached cursors being adopted, so the refresh fetches full snapshots, which is the recovery a damaged cache needs. --- .../src/runtime/directory-sync/index.test.ts | 140 +++++++++++++++++- .../app/src/runtime/directory-sync/index.ts | 47 ++++-- 2 files changed, 171 insertions(+), 16 deletions(-) diff --git a/packages/app/src/runtime/directory-sync/index.test.ts b/packages/app/src/runtime/directory-sync/index.test.ts index e4db5dfb71..a5e34f5673 100644 --- a/packages/app/src/runtime/directory-sync/index.test.ts +++ b/packages/app/src/runtime/directory-sync/index.test.ts @@ -10,7 +10,10 @@ import type { DaemonClient, WorkspaceLabelListPayload, } from "@getpaseo/client/internal/daemon-client"; -import type { SessionOutboundMessage } from "@getpaseo/protocol/messages"; +import type { + SessionOutboundMessage, + WorkspaceDescriptorPayload, +} from "@getpaseo/protocol/messages"; import { normalizeProjectDescriptor, normalizeWorkspaceDescriptor, @@ -1667,6 +1670,141 @@ it("fills every cached workspace beneath live updates received during the SQLite database.close(); }); +it("re-syncs every project when a project update lands while an untrusted cache loads", async () => { + const serverId = "untrusted-checkpoint-race"; + serverIds.add(serverId); + const { cache, database, storage, reopen, holdRead } = createSqliteCache(); + cache.setHosts([serverId]); + const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({ + id, + projectId, + projectDisplayName: projectId, + projectRootPath: `/repo/${projectId}`, + workspaceDirectory: `/repo/${projectId}`, + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + status: "done", + statusEnteredAt: null, + activityAt: null, + archivingAt: null, + diffStat: null, + scripts: [], + }); + const project = (projectId: string, projectDisplayName: string) => ({ + projectId, + projectDisplayName, + projectRootPath: `/repo/${projectId}`, + projectKind: "git" as const, + }); + const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")]; + // An install damaged before the fix: workspaces survived eviction, project rows did not, and a + // version 1 checkpoint still claims the project directory is current. + cache.replaceDirectoryBaseline(serverId, { + agents: new Map(), + workspaces: new Map( + workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]), + ), + projects: new Map(), + }); + await cache.flush(); + await storage.apply({ + deletes: [], + upserts: [ + { + serverId, + kind: "checkpoint", + id: "singleton", + payload: JSON.stringify({ + version: 1, + cursors: { projects: { generation: "g", afterSeq: 5 } }, + }), + }, + ], + }); + const reopened = reopen(); + reopened.setHosts([serverId]); + const client = new FakeDirectoryClient(); + client.listProjects = async (options?: unknown): Promise => { + client.lastProjectOptions = options; + const resumesAfterRename = + (options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === 6; + return resumesAfterRename + ? { + requestId: "projects", + projects: [], + sync: { generation: "g", headSeq: 6, mode: "changes", removals: [] }, + } + : { + requestId: "projects", + projects: [project("A", "Renamed"), project("B", "B")], + sync: { generation: "g", headSeq: 6, mode: "snapshot", removals: [] }, + }; + }; + client.fetchWorkspaces = async (): Promise => ({ + requestId: "workspaces", + entries: workspaceEntries, + emptyProjects: [], + pageInfo: { hasMore: false, nextCursor: null, prevCursor: null }, + sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] }, + }); + const directory = new DirectorySync( + serverId, + { + onAgentStoppedRunning: () => {}, + markAgentLoading: () => {}, + markAgentReady: () => {}, + markAgentError: () => {}, + }, + reopened, + ); + const store = useSessionStore.getState(); + store.initializeSession(serverId, client as unknown as DaemonClient, 1); + store.updateSessionServerInfo(serverId, { + serverId, + hostname: null, + version: "test", + features: { workspaceMultiplicity: true, directorySync: true, projectList: true }, + }); + directory.connectionChanged({ + client: client as unknown as DaemonClient, + status: "online", + source: { clientGeneration: 1, connectionEpoch: 1 }, + }); + let renamed = false; + holdRead(async () => { + if (renamed) return; + renamed = true; + client.emit({ + type: "project.update", + payload: { kind: "upsert", project: project("A", "Renamed"), generation: "g", seq: 6 }, + }); + }); + + try { + directory.setDemand({}, true); + await directory.refreshDemand(); + + expect(renamed).toBe(true); + expect(client.lastProjectOptions).toEqual({ sync: {} }); + expect([...useSessionStore.getState().sessions[serverId].projects.keys()].sort()).toEqual([ + "A", + "B", + ]); + await reopened.flush(); + const restarted = reopen(); + restarted.setHosts([serverId]); + expect([...(await restarted.readDirectory(serverId)).projects.keys()].sort()).toEqual([ + "A", + "B", + ]); + } finally { + directory.dispose(); + await reopened.flush(); + database.close(); + } +}); + function createWorkspaceLabelDirectory(serverId: string) { const { client, directory } = createDirectory(serverId, { workspaceLabels: true }); const store = useSessionStore.getState(); diff --git a/packages/app/src/runtime/directory-sync/index.ts b/packages/app/src/runtime/directory-sync/index.ts index 0f539a2b1d..9c08c3aa87 100644 --- a/packages/app/src/runtime/directory-sync/index.ts +++ b/packages/app/src/runtime/directory-sync/index.ts @@ -566,24 +566,16 @@ export class DirectorySync { input: { subscribe?: boolean } | undefined, loadDirectoryCache: boolean, ): Promise { - if (loadDirectoryCache) await this.loadCachedDirectory(); + if (loadDirectoryCache) { + this.primeWorkspaceTransactionForCacheLoad(); + await this.loadCachedDirectory(); + } const onlineConnection = this.getOnlineConnection(); if (!onlineConnection) return; const { client, source } = onlineConnection; - const transaction = this.workspaceTransactions.begin(source, () => { - const baseline = this.workspaces.snapshot(); - return { - workspaces: new Map(baseline.workspaces), - projects: new Map(baseline.projects), - // Cache hydration can advance the live replica while these requests await responses. - // Every page must use the cursors belonging to the maps captured here. - requestCursors: { ...this.cursors }, - syncCursors: {}, - syncModes: {}, - touchedWorkspaceIds: new Set(), - touchedProjectIds: new Set(), - }; - }); + const transaction = this.workspaceTransactions.begin(source, () => + this.createWorkspaceRefreshSnapshot(), + ); try { await this.waitForSessionMetadata(client, source); const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo; @@ -807,6 +799,31 @@ export class DirectorySync { })); } + // Updates that arrive before a refresh completes have no trusted baseline to advance from. + // Holding them keeps their cursor out of the cache until the refresh they are applied over. + private primeWorkspaceTransactionForCacheLoad(): void { + const connection = this.getOnlineConnection(); + if (!connection) return; + this.workspaceTransactions.begin(connection.source, () => + this.createWorkspaceRefreshSnapshot(), + ); + } + + private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot { + const baseline = this.workspaces.snapshot(); + return { + workspaces: new Map(baseline.workspaces), + projects: new Map(baseline.projects), + // Cache hydration can advance the live replica while these requests await responses. + // Every page must use the cursors belonging to the maps captured here. + requestCursors: { ...this.cursors }, + syncCursors: {}, + syncModes: {}, + touchedWorkspaceIds: new Set(), + touchedProjectIds: new Set(), + }; + } + private supportsDirectorySync(): boolean { return ( useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync ===