:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): make archiving a task idempotent (#85518)
Phil Haack2eb6d3b4153c
diff --git a/products/desktop/packages/core/src/archive/archiveOrchestration.test.ts b/products/desktop/packages/core/src/archive/archiveOrchestration.test.tsindex c7d289786637..7c71da03bcbc 100644--- a/products/desktop/packages/core/src/archive/archiveOrchestration.test.ts+++ b/products/desktop/packages/core/src/archive/archiveOrchestration.test.ts@@ -112,6 +112,7 @@ describe("archiveTask", () => {expect(harness.ids).not.toContain(TASK_ID);expect(harness.list).toEqual([]);expect(harness.deps.togglePin).toHaveBeenCalledWith(TASK_ID);+ expect(harness.deps.cache.invalidatePathFilter).toHaveBeenCalled();});it("archives when reading task pins fails", async () => {diff --git a/products/desktop/packages/core/src/archive/archiveOrchestration.ts b/products/desktop/packages/core/src/archive/archiveOrchestration.tsindex 8771b03b1a75..10a8982d09e5 100644--- a/products/desktop/packages/core/src/archive/archiveOrchestration.ts+++ b/products/desktop/packages/core/src/archive/archiveOrchestration.ts@@ -134,6 +134,10 @@ export async function archiveTask(deps.cache.setArchivedTaskIds((old) => removeArchivedTaskId(old, taskId));deps.cache.setArchiveList((old) => removeArchivedTask(old, taskId));+ // The rollback above assumes the failure left the task unarchived, which is+ // a guess — the host may have stored the archive and failed afterwards. Ask+ // it, so a task that is archived stays out of the sidebar either way.+ deps.cache.invalidatePathFilter();if (wasPinned) {try {await deps.togglePin(taskId);diff --git a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.tsindex c60da80c1e50..f5c9a3f516a6 100644--- a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts+++ b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts@@ -437,15 +437,36 @@ describe("ArchiveService integration", () => {expect(await pathExists(worktreePath)).toBe(false);}));- it("throws when trying to archive already archived task", () =>+ it("archiving an already archived task returns the existing record", () =>withTestContext({}, async (ctx) => {await ctx.setupWorktree("detached");await ctx.service.archiveTask(ctx.archiveInput());+ const second = await ctx.service.archiveTask(ctx.archiveInput());- await expect(+ expect(second).toEqual(ctx.service.getArchivedTasks()[0]);+ expect(ctx.service.getArchivedTaskIds()).toEqual([TASK_ID]);+ }));++ it("overlapping archive requests share one archive", () =>+ withTestContext({}, async (ctx) => {+ const { worktreePath } = await ctx.setupWorktree("detached");+ await fs.writeFile(path.join(worktreePath, "file.txt"), "content");++ // Both requests start before either finishes, so neither can see the+ // other's archive row. A second teardown would delete the checkpoint+ // the surviving archive restores from.+ const [first, second] = await Promise.all([+ ctx.service.archiveTask(ctx.archiveInput()),ctx.service.archiveTask(ctx.archiveInput()),- ).rejects.toThrow("already archived");+ ]);++ expect(second).toEqual(first);+ expect(ctx.archiveRepo.findAll()).toHaveLength(1);+ expect(first.checkpointId).toBeTruthy();+ expect(ctx.git("for-each-ref --format='%(refname)'")).toContain(+ first.checkpointId,+ );}));it("archive finds worktree at legacy path format", () =>@@ -599,12 +620,13 @@ describe("ArchiveService integration", () => {);}));- it("rejects archiving a rowless task that is already archived", () =>+ it("archiving an already archived rowless task returns the existing record", () =>withTestContext({ hasWorkspace: false }, async (ctx) => {await ctx.service.archiveTask({ taskId: "nonexistent" });- await expect(- ctx.service.archiveTask({ taskId: "nonexistent" }),- ).rejects.toThrow("already archived");+ const second = await ctx.service.archiveTask({ taskId: "nonexistent" });++ expect(second).toEqual(ctx.service.getArchivedTasks()[0]);+ expect(ctx.service.getArchivedTaskIds()).toEqual(["nonexistent"]);}));// Unarchive and delete are parallel "remove a rowless task from the archiveddiff --git a/products/desktop/packages/workspace-server/src/services/archive/archive.ts b/products/desktop/packages/workspace-server/src/services/archive/archive.tsindex 794249b0dc68..01cfe214ea48 100644--- a/products/desktop/packages/workspace-server/src/services/archive/archive.ts+++ b/products/desktop/packages/workspace-server/src/services/archive/archive.ts@@ -92,8 +92,31 @@ export class ArchiveService {private readonly log: ScopedLogger;private recoveryStarted = false;+ private readonly inFlightArchives = new Map<string, Promise<ArchivedTask>>();++ /**+ * Idempotent: an already-archived task returns its existing record, so a+ * caller that asks twice isn't left with a failure it can't act on.+ *+ * Overlapping requests join the running one, because the existing-record+ * check can't see them: it runs before the awaited teardown and the archive+ * row lands after, so both requests pass it, and the loser's rollback would+ * delete the checkpoint the winner's restore point points at.+ */+ archiveTask(input: ArchiveTaskInput): Promise<ArchivedTask> {+ const inFlight = this.inFlightArchives.get(input.taskId);+ if (inFlight) {+ this.log.info(`Joining the archive already running for ${input.taskId}`);+ return inFlight;+ }+ const run = this.runArchive(input).finally(() => {+ this.inFlightArchives.delete(input.taskId);+ });+ this.inFlightArchives.set(input.taskId, run);+ return run;+ }- async archiveTask(input: ArchiveTaskInput): Promise<ArchivedTask> {+ private async runArchive(input: ArchiveTaskInput): Promise<ArchivedTask> {this.log.info(`Archiving task ${input.taskId}`);const rollbacks: RollbackFn[] = [];@@ -137,7 +160,7 @@ export class ArchiveService {// `getArchivedTaskIds` never reports it and the row reappears on refetch.const existing = this.taskMetadataRepo.findByTaskId(taskId);if (existing?.archivedAt) {- throw new Error(`Task ${taskId} is already archived`);+ return this.toRowlessArchivedTask(existing);}const archivedAt = new Date().toISOString();await step(@@ -169,7 +192,7 @@ export class ArchiveService {const existingArchive = this.archiveRepo.findByWorkspaceId(workspace.id);if (existingArchive) {- throw new Error(`Task ${taskId} is already archived`);+ return this.toArchivedTask(workspace, existingArchive);}const suspension = this.suspensionRepo.findByWorkspaceId(workspace.id);@@ -513,30 +536,10 @@ export class ArchiveService {const workspace = this.workspaceRepo.findById(archive.workspaceId,) as Workspace;- const worktree = this.worktreeRepo.findByWorkspaceId(workspace.id);- return this.toArchivedTask(- workspace,- archive,- worktree?.name ?? null,- worktree?.path ?? null,- );+ return this.toArchivedTask(workspace, archive);});- const rowless = this.rowlessArchived().map(- (meta): ArchivedTask => ({- taskId: meta.taskId,- // `rowlessArchived` only returns rows with a non-null `archivedAt`.- archivedAt: meta.archivedAt as string,- folderId: "",- mode: "cloud",- worktreeName: null,- branchName: null,- checkpointId: null,- title:- meta.archivedTitle ?? `Unknown task (${meta.taskId.slice(0, 8)})`,- taskCreatedAt: meta.archivedTaskCreatedAt ?? meta.createdAt,- repository: meta.archivedRepository,- recoveryPending: !meta.archivedTitle,- }),+ const rowless = this.rowlessArchived().map((meta) =>+ this.toRowlessArchivedTask(meta),);return [...fromWorkspaces, ...rowless];}@@ -685,12 +688,9 @@ export class ArchiveService {this.log.info(`Deleted archived task ${taskId}`);}- private toArchivedTask(- workspace: Workspace,- archive: Archive,- worktreeName: string | null,- worktreePath: string | null,- ): ArchivedTask {+ private toArchivedTask(workspace: Workspace, archive: Archive): ArchivedTask {+ const worktree = this.worktreeRepo.findByWorkspaceId(workspace.id);+ const worktreeName = worktree?.name ?? null;const repository =!archive.repository && workspace.repositoryId? this.repositoryRepo.findById(workspace.repositoryId)@@ -711,11 +711,30 @@ export class ArchiveService {worktreeName,),taskCreatedAt: archive.taskCreatedAt ?? workspace.createdAt,- repository: archive.repository ?? repository?.path ?? worktreePath,+ repository:+ archive.repository ?? repository?.path ?? worktree?.path ?? null,recoveryPending: !archive.title,};}+ private toRowlessArchivedTask(meta: TaskMetadataRow): ArchivedTask {+ return {+ taskId: meta.taskId,+ // Only reached for rows with a non-null `archivedAt`.+ archivedAt: meta.archivedAt as string,+ folderId: "",+ mode: "cloud",+ worktreeName: null,+ branchName: null,+ checkpointId: null,+ title:+ meta.archivedTitle ?? this.unknownTaskTitle(meta.taskId, null, null),+ taskCreatedAt: meta.archivedTaskCreatedAt ?? meta.createdAt,+ repository: meta.archivedRepository,+ recoveryPending: !meta.archivedTitle,+ };+ }+private unknownTaskTitle(taskId: string,branchName: string | null,