: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
feat(desktop): add per-space auto-archive settings (#91175)
Dylan Martin0bab806f87a2
diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.tsindex c4816cf07d97..617843e4e6e2 100644--- a/products/desktop/apps/code/src/renderer/desktop-services.ts+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts@@ -139,6 +139,10 @@ container.bind(GIT_CACHE_KEY_PROVIDER).toConstantValue(gitCacheKeyProvider);// archivecontainer.load(archiveModule);container.bind(ARCHIVE_CLIENT).toConstantValue({+ archive: (input) => hostTrpcClient.archive.archive.mutate(input),+ refreshArchiveState: async () => {+ await queryClient.invalidateQueries({ queryKey: [["archive"]] });+ },unarchive: (input) => hostTrpcClient.archive.unarchive.mutate(input),delete: (input) => hostTrpcClient.archive.delete.mutate(input),showArchivedTaskContextMenu: (input) =>diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.tsindex 6fd0187d0b0c..4d4bed06a16f 100644--- a/products/desktop/apps/web/src/web-container.ts+++ b/products/desktop/apps/web/src/web-container.ts@@ -670,11 +670,14 @@ container.bind(SHELL_CLIENT).toConstantValue(webShellClient);// ── Archive (sidebar's ArchivedTasksController) ──// The controller resolves eagerly for the sidebar; UnarchiveService needs an-// ARCHIVE_CLIENT. Its methods are user actions (unarchive/delete/context menu)-// backed by workspace-server on desktop — not available on web, so reject. The-// archived-task LIST comes from the api-client, not this client.+// ARCHIVE_CLIENT. User-initiated restore and delete remain unavailable on web,+// while server archive sync uses the web host's local archive implementation.container.load(archiveModule);container.bind(ARCHIVE_CLIENT).toConstantValue({+ archive: (input) => hostTrpcClient.archive.archive.mutate(input),+ refreshArchiveState: async () => {+ await queryClient.invalidateQueries({ queryKey: [["archive"]] });+ },unarchive: () =>Promise.reject(new Error("Unarchive is not available on the web")),delete: () => Promise.reject(new Error("Delete is not available on the web")),diff --git a/products/desktop/docs/AUTO-ARCHIVE.md b/products/desktop/docs/AUTO-ARCHIVE.mdnew file mode 100644index 000000000000..9939f5ab1395--- /dev/null+++ b/products/desktop/docs/AUTO-ARCHIVE.md@@ -0,0 +1,9 @@+# Automatic task archiving++Each space can archive inactive tasks after 1, 3, 7, 14, or 30 days, or use a custom threshold from 1 to 365 days. Automatic archiving is off by default.++Open a space's options menu to see whether auto-archive is on and change its rule. The dialog has a separate on/off control and inactivity threshold. Project admins manage shared-space rules, which apply to everyone. Personal-space rules apply only to that personal space and can be managed by its owner.++Task activity includes new messages and task-run activity. The server checks hourly and skips pinned tasks, tasks being viewed, and tasks with queued or active runs.++Automatic archiving uses the same shared archive state as manual archiving. It does not automatically unarchive a task. Use the archive view to unarchive a task before continuing it.diff --git a/products/desktop/docs/LOCAL-DEVELOPMENT.md b/products/desktop/docs/LOCAL-DEVELOPMENT.mdindex 7f7b9551d173..e363f7fae48c 100644--- a/products/desktop/docs/LOCAL-DEVELOPMENT.md+++ b/products/desktop/docs/LOCAL-DEVELOPMENT.md@@ -192,6 +192,8 @@ but issues a token without that scope.`GET /api/projects/:id/desktop/access/` requires it (`required_scopes` on the desktop access endpoint),so the request returns 403 and the app shows "Couldn't check Desktop access".On older PostHog checkouts the same misconfiguration failed sign-in with `invalid_scope` instead.+Once the token has this scope, authenticated users are allowed through the access policy while+Django runs with `DEBUG=True`; local development does not depend on production billing or flag services.(A current `generate_demo_data` seeds a ceiling that already covers the scope.)Fix: seed the ceiling with the defaults plus that one privileged scope,diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 96aa17c122f7..0093ab9bdb23 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -10,6 +10,30 @@ import {} from "./posthog-client";describe("PostHogAPIClient", () => {+ describe("updateTaskChannelAutoArchive", () => {+ it("rejects a successful response that did not save the setting", async () => {+ const fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ id: "channel-1", name: "personal" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const client = new PostHogAPIClient(+ "https://app.posthog.test",+ async () => "token",+ async () => "token",+ 42,+ { fetch },+ );++ await expect(+ client.updateTaskChannelAutoArchive("channel-1", 7),+ ).rejects.toThrow(+ "Automatic archiving isn't available on this server yet",+ );+ });+ });+describe("setUserSpendLimit", () => {// The shared fetcher throws on non-2xx, so the endpoint's `detail` must be// unwrapped for the settings toast rather than the raw fetcher string.@@ -392,6 +416,28 @@ describe("PostHogAPIClient", () => {});});+ it("fetches every task page when requested", async () => {+ const client = new PostHogAPIClient(+ "https://app.posthog.test",+ async () => "token",+ async () => "token",+ 42,+ );+ const getTasksPage = vi+ .spyOn(client, "getTasksPage")+ .mockResolvedValueOnce({ tasks: [{ id: "task-1" } as Task], count: 3 })+ .mockResolvedValueOnce({ tasks: [{ id: "task-2" } as Task], count: 3 })+ .mockResolvedValueOnce({ tasks: [{ id: "task-3" } as Task], count: 3 });++ await expect(+ client.getTasksWithStatus(undefined, { fetchAll: true }),+ ).resolves.toMatchObject({+ isComplete: true,+ tasks: [{ id: "task-1" }, { id: "task-2" }, { id: "task-3" }],+ });+ expect(getTasksPage).toHaveBeenCalledTimes(3);+ });+it.each([["pinned", { pinned: true }, "pinned", "true"],["commented-by", { commentedBy: 17 }, "commented_by", "17"],diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex b70197f00624..c068e3e8c88e 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2597,9 +2597,11 @@ export class PostHogAPIClient {async getTasksWithStatus(options?: TaskListOptions,- pagination?: { maxPages?: number },+ pagination?: { maxPages?: number; fetchAll?: boolean },): Promise<{ tasks: Task[]; isComplete: boolean }> {- const maxPages = pagination?.maxPages ?? 1;+ const maxPages = pagination?.fetchAll+ ? Number.POSITIVE_INFINITY+ : (pagination?.maxPages ?? 1);const pageSize = Math.min(options?.limit ?? 100, 100);const tasks: Task[] = [];let count = 0;@@ -3074,6 +3076,34 @@ export class PostHogAPIClient {return (await response.json()) as TaskChannel;}+ async updateTaskChannelAutoArchive(+ id: string,+ inactivityDays: number | null,+ ): Promise<TaskChannel> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/task_channels/${encodeURIComponent(id)}/`;+ const response = await this.api.fetcher.fetch({+ method: "patch",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ overrides: {+ body: JSON.stringify({ auto_archive_after_days: inactivityDays }),+ },+ });+ if (!response.ok) {+ throw new Error(+ `Failed to update automatic archiving: ${response.statusText}`,+ );+ }+ const updatedChannel = (await response.json()) as TaskChannel;+ if (updatedChannel.auto_archive_after_days !== inactivityDays) {+ throw new Error(+ "Automatic archiving isn't available on this server yet. Try again after it has been updated.",+ );+ }+ return updatedChannel;+ }+async deleteTaskChannel(id: string): Promise<void> {const teamId = await this.getTeamId();const urlPath = `/api/projects/${teamId}/task_channels/${encodeURIComponent(id)}/`;diff --git a/products/desktop/packages/core/src/archive/identifiers.ts b/products/desktop/packages/core/src/archive/identifiers.tsindex 664565388a83..4f6750db936c 100644--- a/products/desktop/packages/core/src/archive/identifiers.ts+++ b/products/desktop/packages/core/src/archive/identifiers.ts@@ -7,6 +7,14 @@ export const ARCHIVE_CLIENT = Symbol.for("posthog.core.archiveClient");export type ArchivedTaskContextMenuAction = "restore" | "delete";export interface ArchiveClient {+ archive(input: {+ taskId: string;+ title?: string;+ taskCreatedAt?: string;+ repository?: string | null;+ serverArchiveScope?: string;+ }): Promise<unknown>;+ refreshArchiveState(): Promise<void>;unarchive(input: {taskId: string;recreateBranch?: boolean;diff --git a/products/desktop/packages/core/src/archive/unarchiveService.test.ts b/products/desktop/packages/core/src/archive/unarchiveService.test.tsindex 8bf5417e8ea5..dbc4bc6621d6 100644--- a/products/desktop/packages/core/src/archive/unarchiveService.test.ts+++ b/products/desktop/packages/core/src/archive/unarchiveService.test.ts@@ -6,6 +6,8 @@ const TASK_ID = "task-1";function makeClient(): ArchiveClient {return {+ archive: vi.fn().mockResolvedValue(undefined),+ refreshArchiveState: vi.fn().mockResolvedValue(undefined),unarchive: vi.fn().mockResolvedValue(undefined),delete: vi.fn().mockResolvedValue(undefined),showArchivedTaskContextMenu: vi.fn().mockResolvedValue({ action: null }),diff --git a/products/desktop/packages/host-router/src/routers/archive.router.ts b/products/desktop/packages/host-router/src/routers/archive.router.tsindex c525f29199d9..dd9f31994877 100644--- a/products/desktop/packages/host-router/src/routers/archive.router.ts+++ b/products/desktop/packages/host-router/src/routers/archive.router.ts@@ -3,6 +3,7 @@ import type { ArchiveService } from "@posthog/workspace-server/services/archive/import { ARCHIVE_SERVICE } from "@posthog/workspace-server/services/archive/identifiers";import {archivedTaskIdsOutput,+ archiveScopeInput,archiveTaskInput,archiveTaskOutput,deleteArchivedTaskInput,@@ -30,15 +31,21 @@ export const archiveRouter = router({),list: publicProcedure+ .input(archiveScopeInput).output(listArchivedTasksOutput)- .query(({ ctx }) =>- ctx.container.get<ArchiveService>(ARCHIVE_SERVICE).listArchivedTasks(),+ .query(({ ctx, input }) =>+ ctx.container+ .get<ArchiveService>(ARCHIVE_SERVICE)+ .listArchivedTasks(input.serverArchiveScope),),archivedTaskIds: publicProcedure+ .input(archiveScopeInput).output(archivedTaskIdsOutput)- .query(({ ctx }) =>- ctx.container.get<ArchiveService>(ARCHIVE_SERVICE).getArchivedTaskIds(),+ .query(({ ctx, input }) =>+ ctx.container+ .get<ArchiveService>(ARCHIVE_SERVICE)+ .getArchivedTaskIds(input.serverArchiveScope),),delete: publicProcedurediff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex e66626c1cf6a..da67413d0d81 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -1070,6 +1070,7 @@ type ChannelActionType =| "view_more_tasks"| "create"| "rename"+ | "auto_archive_update"| "delete"| "star"| "unstar"@@ -1119,6 +1120,8 @@ export interface ChannelActionProperties {tab?: string;/** Whether the underlying mutation resolved successfully. */success?: boolean;+ /** For auto_archive_update: the selected inactivity window. Null disables it. */+ inactivity_days?: number | null;}type DashboardActionType =diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 05a641322bce..f1ee61ab0190 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -129,6 +129,7 @@ export interface TaskChannel {starred: boolean;github_integration?: number | null;repositories?: string[];+ auto_archive_after_days?: number | null;created_at: string;created_by?: UserBasic | null;system_role?: "personal" | "general" | null;diff --git a/products/desktop/packages/ui/src/features/archive/ArchivedTasksView.tsx b/products/desktop/packages/ui/src/features/archive/ArchivedTasksView.tsxindex 92be85e31ade..80182152022b 100644--- a/products/desktop/packages/ui/src/features/archive/ArchivedTasksView.tsx+++ b/products/desktop/packages/ui/src/features/archive/ArchivedTasksView.tsx@@ -45,6 +45,7 @@ import {shouldLoadMoreArchivedTasks,} from "./archiveListPagination";import { useArchivedTaskSummaries } from "./useArchivedTaskSummaries";+import { useServerArchiveScope } from "./useServerArchiveScope";import { useUnarchiveTask } from "./useUnarchiveTask";const ICON_SIZE = 12;@@ -520,8 +521,9 @@ export function ArchivedTasksViewPresentation({export function ArchivedTasksView() {const trpc = useHostTRPC();const queryClient = useQueryClient();+ const serverArchiveScope = useServerArchiveScope();const { data: archivedTasks = [], isLoading: isLoadingArchived } = useQuery({- ...trpc.archive.list.queryOptions(),+ ...trpc.archive.list.queryOptions({ serverArchiveScope }),refetchInterval: (query) =>query.state.data?.some((task) => task.recoveryPending) ? 1_000 : false,});diff --git a/products/desktop/packages/ui/src/features/archive/serverArchiveSyncStore.ts b/products/desktop/packages/ui/src/features/archive/serverArchiveSyncStore.tsindex 1351c16d697f..54b05d0362be 100644--- a/products/desktop/packages/ui/src/features/archive/serverArchiveSyncStore.ts+++ b/products/desktop/packages/ui/src/features/archive/serverArchiveSyncStore.ts@@ -19,10 +19,13 @@ interface ServerArchiveSyncStore {* pass reads the local archive, which the restore just removed it from.*/pendingUnarchiveTaskIds: string[];+ /** Next archived-task offset to import for each account and project. */+ archiveImportOffsets: Record<string, number>;markSynced: (taskId: string) => void;forgetSynced: (taskId: string) => void;queueUnarchive: (taskId: string) => void;clearUnarchive: (taskId: string) => void;+ setArchiveImportOffset: (serverArchiveScope: string, offset: number) => void;}export const useServerArchiveSyncStore = create<ServerArchiveSyncStore>()(@@ -30,6 +33,7 @@ export const useServerArchiveSyncStore = create<ServerArchiveSyncStore>()((set) => ({syncedTaskIds: [],pendingUnarchiveTaskIds: [],+ archiveImportOffsets: {},markSynced: (taskId) =>set((state) => ({syncedTaskIds: [@@ -58,6 +62,13 @@ export const useServerArchiveSyncStore = create<ServerArchiveSyncStore>()((id) => id !== taskId,),})),+ setArchiveImportOffset: (serverArchiveScope, offset) =>+ set((state) => ({+ archiveImportOffsets: {+ ...state.archiveImportOffsets,+ [serverArchiveScope]: offset,+ },+ })),}),{ name: "server-archive-sync" },),diff --git a/products/desktop/packages/ui/src/features/archive/useArchivedTaskIds.ts b/products/desktop/packages/ui/src/features/archive/useArchivedTaskIds.tsindex 9e10d586bb25..7a016d7701f7 100644--- a/products/desktop/packages/ui/src/features/archive/useArchivedTaskIds.ts+++ b/products/desktop/packages/ui/src/features/archive/useArchivedTaskIds.ts@@ -1,9 +1,13 @@import { useHostTRPC } from "@posthog/host-router/react";import { useQuery } from "@tanstack/react-query";import { useMemo } from "react";+import { useServerArchiveScope } from "./useServerArchiveScope";export function useArchivedTaskIds(): Set<string> {const trpc = useHostTRPC();- const { data } = useQuery(trpc.archive.archivedTaskIds.queryOptions());+ const serverArchiveScope = useServerArchiveScope();+ const { data } = useQuery(+ trpc.archive.archivedTaskIds.queryOptions({ serverArchiveScope }),+ );return useMemo(() => new Set(data ?? []), [data]);}diff --git a/products/desktop/packages/ui/src/features/archive/useServerArchiveScope.ts b/products/desktop/packages/ui/src/features/archive/useServerArchiveScope.tsnew file mode 100644index 000000000000..d99c20e188c2--- /dev/null+++ b/products/desktop/packages/ui/src/features/archive/useServerArchiveScope.ts@@ -0,0 +1,23 @@+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";++export function useServerArchiveScope(): string | null {+ const client = useOptionalAuthenticatedClient();+ const authState = useAuthStateValue((state) => state);+ const { data: currentUser } = useCurrentUser({ client });++ if (+ !currentUser ||+ !authState.cloudRegion ||+ authState.currentProjectId === null+ ) {+ return null;+ }++ return JSON.stringify([+ authState.cloudRegion,+ currentUser.uuid,+ authState.currentProjectId,+ ]);+}diff --git a/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.test.tsx b/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.test.tsxindex 72703d4b4330..e7562790b726 100644--- a/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.test.tsx+++ b/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.test.tsx@@ -3,12 +3,29 @@ import { act, renderHook, waitFor } from "@testing-library/react";import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";-const apiClient = vi.hoisted(() => ({ setTaskArchived: vi.fn() }));+const apiClient = vi.hoisted(() => ({+ getTasksPage: vi.fn(),+ setTaskArchived: vi.fn(),+}));+const archiveLocally = vi.hoisted(() => vi.fn());+const refreshArchiveState = vi.hoisted(() => vi.fn());+const serverArchiveScope = '["us","user-a",42]';vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => apiClient,}));+vi.mock("./useServerArchiveScope", () => ({+ useServerArchiveScope: () => serverArchiveScope,+}));++vi.mock("@posthog/di/react", () => ({+ useService: () => ({+ archive: archiveLocally,+ refreshArchiveState,+ }),+}));+const archivedIds = vi.hoisted(() => ({ current: new Set<string>() }));vi.mock("@posthog/ui/features/archive/useArchivedTaskIds", () => ({@@ -28,10 +45,17 @@ function wrapper({ children }: { children: ReactNode }) {describe("useServerArchiveSync", () => {beforeEach(() => {vi.clearAllMocks();+ apiClient.getTasksPage.mockResolvedValue({+ tasks: [],+ count: 0,+ });+ archiveLocally.mockResolvedValue(undefined);+ refreshArchiveState.mockResolvedValue(undefined);archivedIds.current = new Set();useServerArchiveSyncStore.setState({syncedTaskIds: [],pendingUnarchiveTaskIds: [],+ archiveImportOffsets: {},});queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -112,4 +136,98 @@ describe("useServerArchiveSync", () => {expect(state.pendingUnarchiveTaskIds).not.toContain("t1");expect(state.syncedTaskIds).not.toContain("t1");});++ it("imports a task archived on the server into the local archive", async () => {+ apiClient.getTasksPage.mockResolvedValue({+ tasks: [+ {+ id: "t1",+ title: "Archived elsewhere",+ created_at: "2026-08-20T10:00:00Z",+ repository: "posthog/example",+ },+ ],+ count: 1,+ });++ renderHook(() => useServerArchiveSync(), { wrapper });++ await waitFor(() =>+ expect(archiveLocally).toHaveBeenCalledWith({+ taskId: "t1",+ title: "Archived elsewhere",+ taskCreatedAt: "2026-08-20T10:00:00Z",+ repository: "posthog/example",+ serverArchiveScope,+ }),+ );+ expect(useServerArchiveSyncStore.getState().syncedTaskIds).toContain("t1");+ expect(apiClient.getTasksPage).toHaveBeenCalledWith({+ archived: true,+ limit: 100,+ offset: 0,+ });+ expect(refreshArchiveState).toHaveBeenCalledOnce();+ });++ it("continues a large server archive from its durable offset", async () => {+ useServerArchiveSyncStore.setState({+ archiveImportOffsets: { [serverArchiveScope]: 100 },+ });+ apiClient.getTasksPage.mockResolvedValue({+ tasks: [+ {+ id: "t101",+ title: "Older archived task",+ created_at: "2026-08-01T10:00:00Z",+ repository: null,+ },+ ],+ count: 500,+ });++ const { rerender } = renderHook(() => useServerArchiveSync(), { wrapper });++ await waitFor(() => expect(archiveLocally).toHaveBeenCalledOnce());+ archivedIds.current = new Set(["t101"]);+ await act(async () => rerender());+ expect(apiClient.getTasksPage).toHaveBeenCalledOnce();+ expect(apiClient.getTasksPage).toHaveBeenCalledWith({+ archived: true,+ limit: 100,+ offset: 100,+ });+ expect(+ useServerArchiveSyncStore.getState().archiveImportOffsets[+ serverArchiveScope+ ],+ ).toBe(101);+ });++ it("does not rearchive a local restore while its server update is pending", async () => {+ apiClient.setTaskArchived.mockRejectedValue(new Error("offline"));+ apiClient.getTasksPage.mockResolvedValue({+ tasks: [+ {+ id: "t1",+ title: "Restored here",+ created_at: "2026-08-20T10:00:00Z",+ repository: null,+ },+ ],+ count: 1,+ });+ useServerArchiveSyncStore.setState({+ syncedTaskIds: [],+ pendingUnarchiveTaskIds: ["t1"],+ });++ renderHook(() => useServerArchiveSync(), { wrapper });++ await waitFor(() => expect(apiClient.getTasksPage).toHaveBeenCalled());+ expect(archiveLocally).not.toHaveBeenCalled();+ expect(+ useServerArchiveSyncStore.getState().pendingUnarchiveTaskIds,+ ).toContain("t1");+ });});diff --git a/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.ts b/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.tsindex 6759d0903638..6f06bea7500c 100644--- a/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.ts+++ b/products/desktop/packages/ui/src/features/archive/useServerArchiveSync.ts@@ -1,13 +1,20 @@+import {+ ARCHIVE_CLIENT,+ type ArchiveClient,+} from "@posthog/core/archive/identifiers";import { pendingServerArchiveIds } from "@posthog/core/archive/serverArchiveSync";+import { useService } from "@posthog/di/react";import { useServerArchiveSyncStore } from "@posthog/ui/features/archive/serverArchiveSyncStore";import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";import { logger } from "@posthog/ui/shell/logger";import { useQueryClient } from "@tanstack/react-query";-import { useEffect, useRef } from "react";+import { useEffect, useRef, useState } from "react";+import { useServerArchiveScope } from "./useServerArchiveScope";const log = logger.scope("server-archive-sync");+const SERVER_ARCHIVE_IMPORT_LIMIT = 100;/*** A restore that couldn't reach the server. Until the clear lands the session@@ -26,25 +33,11 @@ export function forgetServerArchive(taskId: string): void {useServerArchiveSyncStore.getState().forgetSynced(taskId);}-/**- * Tell the server about the sessions this device has archived.- *- * Archiving has always been local, so the server kept listing sessions the app- * hides. Its count is what a space row's "view all" number is drawn from, which- * left that number reading hundreds above the list it leads to. Marking the- * task archived server-side drops it from the same list every count comes from,- * and carries the archive to the user's other devices.- *- * The work list is the local archive itself, diffed against a durable record of- * what this device has already mirrored — not a task-list page. Pages are- * capped at the newest hundred rows, and an archive is precisely the sessions- * too old to be there: discovery through a page synced whatever happened to be- * recent and then starved. The drain runs once per backlog ever (the record- * survives relaunch), sequentially, so it never competes with requests the- * user is waiting on.- */+/** Keep the local archive and the shared server archive aligned across devices. */export function useServerArchiveSync(): void {const client = useOptionalAuthenticatedClient();+ const serverArchiveScope = useServerArchiveScope();+ const archiveClient = useService<ArchiveClient>(ARCHIVE_CLIENT);const archivedTaskIds = useArchivedTaskIds();const queryClient = useQueryClient();// Queued restores re-fire the effect. Mirrored-id progress deliberately@@ -53,112 +46,165 @@ export function useServerArchiveSync(): void {const pendingUnarchive = useServerArchiveSyncStore((s) => s.pendingUnarchiveTaskIds,);+ const [drainGeneration, setDrainGeneration] = useState(0);const running = useRef(false);+ const rerunRequested = useRef(false);const archivedRef = useRef(archivedTaskIds);const clientRef = useRef(client);+ const archiveClientRef = useRef(archiveClient);+ const importedScopes = useRef(new Set<string>());- // The drain loop re-reads these between passes, so a session archived while- // it runs is picked up by the loop that's already going, and the effect that- // fires for it lands on the `running` guard and is skipped. Written after the- // render rather than during it, and before the drain effect below, which runs- // later in the same commit — so the drain never reads a ref left behind by a- // render React went on to discard.+ // The drain loop re-reads these between passes. If a trigger lands too late+ // for the running drain to see it, rerunRequested starts another pass.useEffect(() => {archivedRef.current = archivedTaskIds;clientRef.current = client;+ archiveClientRef.current = archiveClient;});useEffect(() => {- if (!client || running.current) return;- // The triggers, checked directly: don't start a drain that would find- // nothing. The loop below re-reads both sources fresh each pass.+ if (!client) return;+ if (running.current) {+ rerunRequested.current = true;+ return;+ }const mirrored = new Set(useServerArchiveSyncStore.getState().syncedTaskIds,);- if (- pendingUnarchive.length === 0 &&- pendingServerArchiveIds(archivedTaskIds, mirrored).length === 0- ) {- // Distinguishes "nothing to mirror" from "never ran" — the two are- // otherwise identical in the console, and each app instance has its own- // archive DB (dev vs packaged), so an unexpectedly small count here is- // the tell that you're looking at the other instance's backlog.- log.debug("Archive sync idle", {- archivedLocally: archivedTaskIds.size,- alreadyMirrored: mirrored.size,- });- return;- }running.current = true;void (async () => {// Ids this run has already tried and the server refused — retried on the// next launch or trigger, but not by the very next pass of this loop.const attempted = new Set<string>();- let changed = 0;- // The drain's outcome IS the diagnosis when a count reads wrong, and a- // run that finds work is rare (once per backlog) — so say what was found- // and what happened to it, not just the failures.- log.info("Draining archive state to the server", {+ let serverChanges = 0;+ let imported = 0;+ log.info("Synchronizing archive state", {archivedLocally: archivedTaskIds.size,alreadyMirrored: mirrored.size,+ drainGeneration,pendingUnarchive: pendingUnarchive.length,});+ for (;;) {+ const api = clientRef.current;+ if (!api) break;+ const store = useServerArchiveSyncStore.getState();+ const unarchive = store.pendingUnarchiveTaskIds.filter(+ (id) => !attempted.has(id),+ );+ const archive = pendingServerArchiveIds(+ archivedRef.current,+ new Set([...store.syncedTaskIds, ...attempted]),+ );+ // No await stands between this read and the guard release below, so+ // a trigger either lands early enough for the next pass to see it or+ // late enough to start its own drain. There is no gap to lose one in.+ if (unarchive.length === 0 && archive.length === 0) break;++ // Restores lead: a session the server still has archived is+ // invisible everywhere, which is worse than a count that reads high.+ for (const taskId of unarchive) {+ try {+ await api.setTaskArchived(taskId, false);+ store.clearUnarchive(taskId);+ store.forgetSynced(taskId);+ serverChanges++;+ } catch (error) {+ attempted.add(taskId);+ log.warn(`Failed to unarchive task ${taskId} on the server`, error);+ }+ }+ for (const taskId of archive) {+ try {+ await api.setTaskArchived(taskId, true);+ store.markSynced(taskId);+ serverChanges++;+ } catch (error) {+ attempted.add(taskId);+ log.warn(`Failed to archive task ${taskId} on the server`, error);+ }+ }+ }try {- for (;;) {- const api = clientRef.current;- if (!api) break;+ const api = clientRef.current;+ if (+ api &&+ serverArchiveScope !== null &&+ !importedScopes.current.has(serverArchiveScope)+ ) {+ importedScopes.current.add(serverArchiveScope);const store = useServerArchiveSyncStore.getState();- const unarchive = store.pendingUnarchiveTaskIds.filter(- (id) => !attempted.has(id),- );- const archive = pendingServerArchiveIds(- archivedRef.current,- new Set([...store.syncedTaskIds, ...attempted]),- );- // No await stands between this read and the guard release below, so- // a trigger either lands early enough for the next pass to see it or- // late enough to start its own drain. There is no gap to lose one in.- if (unarchive.length === 0 && archive.length === 0) break;-- // Restores lead: a session the server still has archived is- // invisible everywhere, which is worse than a count that reads high.- for (const taskId of unarchive) {+ const offset = store.archiveImportOffsets[serverArchiveScope] ?? 0;+ const serverArchive = await api.getTasksPage({+ archived: true,+ limit: SERVER_ARCHIVE_IMPORT_LIMIT,+ offset,+ });+ const pendingUnarchiveIds = new Set(store.pendingUnarchiveTaskIds);+ let importFailed = false;+ for (const task of serverArchive.tasks) {+ if (pendingUnarchiveIds.has(task.id)) {+ continue;+ }+ if (archivedRef.current.has(task.id)) {+ useServerArchiveSyncStore.getState().markSynced(task.id);+ continue;+ }try {- await api.setTaskArchived(taskId, false);- store.clearUnarchive(taskId);- store.forgetSynced(taskId);- changed++;+ await archiveClientRef.current.archive({+ taskId: task.id,+ title: task.title,+ taskCreatedAt: task.created_at,+ repository: task.repository,+ serverArchiveScope,+ });+ useServerArchiveSyncStore.getState().markSynced(task.id);+ imported++;} catch (error) {- attempted.add(taskId);+ importFailed = true;log.warn(- `Failed to unarchive task ${taskId} on the server`,+ `Failed to import archived task ${task.id} from the server`,error,);}}- for (const taskId of archive) {- try {- await api.setTaskArchived(taskId, true);- store.markSynced(taskId);- changed++;- } catch (error) {- attempted.add(taskId);- log.warn(`Failed to archive task ${taskId} on the server`, error);- }+ if (!importFailed) {+ const reachedEnd =+ serverArchive.tasks.length === 0 ||+ offset + serverArchive.tasks.length >= serverArchive.count;+ store.setArchiveImportOffset(+ serverArchiveScope,+ reachedEnd ? 0 : offset + serverArchive.tasks.length,+ );}}- } finally {- running.current = false;+ } catch (error) {+ log.warn("Failed to read archived tasks from the server", error);}log.info("Archive drain finished", {- synced: changed,+ synced: serverChanges,+ imported,refused: attempted.size,});- if (changed === 0) return;- // Refetches the lists the drain just shortened, which is what moves the- // space counts drawn from them.- await queryClient.invalidateQueries({ queryKey: taskKeys.lists() });- })();- }, [client, archivedTaskIds, pendingUnarchive, queryClient]);+ if (serverChanges > 0 || imported > 0) {+ await queryClient.invalidateQueries({ queryKey: taskKeys.lists() });+ }+ if (imported > 0) {+ await archiveClientRef.current.refreshArchiveState();+ }+ })().finally(() => {+ running.current = false;+ if (rerunRequested.current) {+ rerunRequested.current = false;+ setDrainGeneration((value) => value + 1);+ }+ });+ }, [+ archivedTaskIds,+ client,+ pendingUnarchive,+ queryClient,+ drainGeneration,+ serverArchiveScope,+ ]);}diff --git a/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.stories.tsxnew file mode 100644index 000000000000..8136f6ce64a3--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.stories.tsx@@ -0,0 +1,47 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { AutoArchiveSettingsDialog } from "./AutoArchiveSettingsDialog";++const meta = {+ title: "Canvas/AutoArchiveSettingsDialog",+ component: AutoArchiveSettingsDialog,+ args: {+ channel: {+ id: "channel-1",+ name: "growth-engineering",+ channelType: "public",+ starred: true,+ repositories: [],+ createdBy: null,+ autoArchiveAfterDays: 7,+ },+ open: true,+ onOpenChange: () => {},+ onSave: async () => true,+ isSaving: false,+ },+} satisfies Meta<typeof AutoArchiveSettingsDialog>;++export default meta;+type Story = StoryObj<typeof meta>;++export const SharedSpace: Story = {};++export const PersonalSpace: Story = {+ args: {+ channel: {+ ...meta.args.channel,+ name: "personal",+ channelType: "personal",+ autoArchiveAfterDays: null,+ },+ },+};++export const CustomThreshold: Story = {+ args: {+ channel: {+ ...meta.args.channel,+ autoArchiveAfterDays: 45,+ },+ },+};diff --git a/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.test.tsxnew file mode 100644index 000000000000..ef36e9ac29f0--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.test.tsx@@ -0,0 +1,46 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { AutoArchiveSettingsDialog } from "./AutoArchiveSettingsDialog";++describe("AutoArchiveSettingsDialog", () => {+ it("saves a custom inactivity threshold", async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockResolvedValue(true);++ render(+ <AutoArchiveSettingsDialog+ channel={{+ id: "channel-1",+ name: "personal",+ channelType: "personal",+ starred: true,+ repositories: [],+ createdBy: null,+ autoArchiveAfterDays: null,+ }}+ open+ onOpenChange={vi.fn()}+ onSave={onSave}+ isSaving={false}+ />,+ );++ await user.click(+ screen.getByRole("switch", { name: "Auto-archive inactive tasks" }),+ );+ await user.click(+ screen.getByRole("combobox", { name: "Inactivity period" }),+ );+ await user.click(await screen.findByRole("option", { name: "Custom…" }));+ await user.type(+ screen.getByRole("textbox", {+ name: "Days of inactivity before auto-archive",+ }),+ "45",+ );+ await user.click(screen.getByRole("button", { name: "Save" }));++ expect(onSave).toHaveBeenCalledWith(45);+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.tsx b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.tsxnew file mode 100644index 000000000000..1bbd1afdf170--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/components/AutoArchiveSettingsDialog.tsx@@ -0,0 +1,227 @@+import {+ Button,+ Dialog,+ DialogBody,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldLabel,+ NumberFieldGroup,+ NumberFieldInput,+ NumberFieldRoot,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+} from "@posthog/quill";+import type { Channel } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useEffect, useState } from "react";++export type AutoArchiveAfterDays = number;++const CUSTOM = "custom";+const MIN_THRESHOLD_DAYS = 1;+const MAX_THRESHOLD_DAYS = 365;+const DEFAULT_THRESHOLD_DAYS = 7;+const PRESET_DAYS = new Set([1, 3, 7, 14, 30]);+const OPTIONS: { value: string; label: string }[] = [+ { value: "1", label: "After 1 day" },+ { value: "3", label: "After 3 days" },+ { value: "7", label: "After 7 days" },+ { value: "14", label: "After 14 days" },+ { value: "30", label: "After 30 days" },+ { value: CUSTOM, label: "Custom…" },+];++function toSelection(days: AutoArchiveAfterDays | null | undefined): string {+ if (days == null) return String(DEFAULT_THRESHOLD_DAYS);+ return PRESET_DAYS.has(days) ? String(days) : CUSTOM;+}++function toCustomDays(+ days: AutoArchiveAfterDays | null | undefined,+): number | null {+ return days != null && !PRESET_DAYS.has(days) ? days : null;+}++function isValidThreshold(days: number | null): days is number {+ return (+ days !== null &&+ Number.isInteger(days) &&+ days >= MIN_THRESHOLD_DAYS &&+ days <= MAX_THRESHOLD_DAYS+ );+}++export function AutoArchiveSettingsDialog({+ channel,+ open,+ onOpenChange,+ onSave,+ isSaving,+}: {+ channel: Channel;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onSave: (days: AutoArchiveAfterDays | null) => Promise<boolean>;+ isSaving: boolean;+}) {+ const currentDays = channel.autoArchiveAfterDays ?? null;+ const currentSelection = toSelection(currentDays);+ const [enabled, setEnabled] = useState(currentDays !== null);+ const [selection, setSelection] = useState(currentSelection);+ const [customDays, setCustomDays] = useState<number | null>(() =>+ toCustomDays(currentDays),+ );++ useEffect(() => {+ if (open) {+ setEnabled(currentDays !== null);+ setSelection(currentSelection);+ setCustomDays(toCustomDays(currentDays));+ }+ }, [currentDays, currentSelection, open]);++ const selectedDays = !enabled+ ? null+ : selection === CUSTOM+ ? isValidThreshold(customDays)+ ? customDays+ : undefined+ : Number(selection);+ const isUnchanged = selectedDays === currentDays;++ const submit = async (): Promise<void> => {+ if (isSaving || selectedDays === undefined || isUnchanged) return;+ if (await onSave(selectedDays)) onOpenChange(false);+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!isSaving) onOpenChange(next);+ }}+ >+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>Auto-archive tasks</DialogTitle>+ <DialogDescription>+ Choose when inactive tasks in {channel.name} are archived. This+ setting applies to{" "}+ {channel.channelType === "personal"+ ? "your personal space"+ : "everyone in this space"}+ .+ </DialogDescription>+ </DialogHeader>+ <DialogBody viewportClassName="flex flex-col gap-3">+ <Field orientation="horizontal">+ <FieldContent>+ <FieldLabel htmlFor="auto-archive-enabled">+ Auto-archive inactive tasks+ </FieldLabel>+ <FieldDescription>+ Turn this on to archive finished tasks after a period of+ inactivity.+ </FieldDescription>+ </FieldContent>+ <Switch+ id="auto-archive-enabled"+ size="sm"+ checked={enabled}+ onCheckedChange={setEnabled}+ disabled={isSaving}+ />+ </Field>+ {enabled && (+ <Field>+ <FieldLabel htmlFor="auto-archive-after-days">+ Inactivity period+ </FieldLabel>+ <Select+ value={selection}+ onValueChange={(next) =>+ setSelection(next ?? String(DEFAULT_THRESHOLD_DAYS))+ }+ items={OPTIONS}+ disabled={isSaving}+ >+ <SelectTrigger+ id="auto-archive-after-days"+ aria-label="Inactivity period"+ className="w-full"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="start" side="bottom" sideOffset={6}>+ {OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ New messages and task runs reset this period. Tasks being+ viewed, pinned, or actively running are not archived.+ </FieldDescription>+ </Field>+ )}+ {enabled && selection === CUSTOM && (+ <Field orientation="horizontal">+ <FieldContent>+ <FieldLabel htmlFor="custom-auto-archive-days">+ Days of inactivity before auto-archive+ </FieldLabel>+ <FieldDescription>+ Choose a value from 1 to 365 days.+ </FieldDescription>+ </FieldContent>+ <NumberFieldRoot+ id="custom-auto-archive-days"+ value={customDays}+ onValueChange={setCustomDays}+ min={MIN_THRESHOLD_DAYS}+ max={MAX_THRESHOLD_DAYS}+ step={1}+ disabled={isSaving}+ className="w-20 shrink-0"+ >+ <NumberFieldGroup>+ <NumberFieldInput className="text-start" />+ </NumberFieldGroup>+ </NumberFieldRoot>+ </Field>+ )}+ </DialogBody>+ <DialogFooter>+ <DialogClose+ render={+ <Button variant="outline" disabled={isSaving}>+ Cancel+ </Button>+ }+ />+ <Button+ variant="primary"+ loading={isSaving}+ disabled={selectedDays === undefined || isUnchanged}+ data-attr="save-space-auto-archive"+ onClick={() => void submit()}+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsxindex 5a8b8bb60a28..39346d3f2e02 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx@@ -39,7 +39,12 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({}));vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({useChannels: () => ({ channels: mocks.channels, isLoading: false }),- useChannelMutations: () => ({ deleteChannel: vi.fn(), isDeleting: false }),+ useChannelMutations: () => ({+ deleteChannel: vi.fn(),+ isDeleting: false,+ updateAutoArchive: vi.fn(),+ isUpdatingAutoArchive: false,+ }),}));vi.mock("@posthog/ui/features/canvas/hooks/useChannelStars", () => ({useChannelStarToggle: () => ({@@ -261,6 +266,22 @@ describe("ChannelsList", () => {expect(me.parentElement?.textContent).toMatch(/personal(⌘|Ctrl)/);});+ it.each(["personal", "engineering"])(+ "offers automatic archiving for the %s space",+ async (spaceName) => {+ const user = userEvent.setup();+ renderList();++ await user.click(+ screen.getByRole("button", { name: `Options for ${spaceName}` }),+ );++ expect(+ await screen.findByRole("menuitem", { name: "Auto-archive: off…" }),+ ).toBeVisible();+ },+ );+describe("group headings", () => {beforeEach(() => {mocks.channels = [ME, { ...ENG, starred: true }, DESIGN];diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsxindex 775d64514245..0c91e98ec344 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx@@ -1,5 +1,6 @@import { Collapsible } from "@base-ui/react/collapsible";import {+ ArchiveBoxIcon,ArrowRightIcon,CaretDownIcon,CaretRightIcon,@@ -46,6 +47,10 @@ import {} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import {+ type AutoArchiveAfterDays,+ AutoArchiveSettingsDialog,+} from "@posthog/ui/features/canvas/components/AutoArchiveSettingsDialog";import {ChannelItemHoverCard,SpaceHoverCard,@@ -119,7 +124,6 @@ import { toast } from "@posthog/ui/primitives/toast";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";import { logger } from "@posthog/ui/shell/logger";-import { Box, Flex } from "@radix-ui/themes";import { useNavigate, useRouterState } from "@tanstack/react-router";import {type ComponentProps,@@ -696,11 +700,14 @@ function SpaceTaskRows({);}-// The channel actions (star, copy link, rename, delete) plus the rename-modal-// state they drive. Single source of truth so the dropdown and context menus-// stay in lockstep — add an action here and both surfaces pick it up.+// The channel actions and their dialogs. Single source of truth so the dropdown+// and context menus stay in lockstep.function useChannelActions(channel: Channel): {actions: ChannelActionItem[];+ autoArchiveOpen: boolean;+ setAutoArchiveOpen: (open: boolean) => void;+ saveAutoArchive: (days: AutoArchiveAfterDays | null) => Promise<boolean>;+ isUpdatingAutoArchive: boolean;renameOpen: boolean;setRenameOpen: (open: boolean) => void;confirmDeleteOpen: boolean;@@ -711,6 +718,7 @@ function useChannelActions(channel: Channel): {const spacesLayout = useChannelsLayout();const noun = spacesLayout ? "space" : "channel";const [renameOpen, setRenameOpen] = useState(false);+ const [autoArchiveOpen, setAutoArchiveOpen] = useState(false);// "Delete channel" opens a confirmation dialog rather than deleting inline —// the action is destructive and irreversible.const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);@@ -718,7 +726,12 @@ function useChannelActions(channel: Channel): {const insideChannel = useRouterState({select: (s) => s.location.pathname.startsWith(`/spaces/${channel.id}`),});- const { deleteChannel, isDeleting } = useChannelMutations();+ const {+ deleteChannel,+ isDeleting,+ updateAutoArchive,+ isUpdatingAutoArchive,+ } = useChannelMutations();const { isStarred, toggleStar } = useChannelStarToggle(channel);// Runs the actual delete once confirmed. Returns whether it succeeded so the@@ -775,24 +788,85 @@ function useChannelActions(channel: Channel): {}};+ const saveAutoArchive = async (+ days: AutoArchiveAfterDays | null,+ ): Promise<boolean> => {+ try {+ await updateAutoArchive(channel.id, days);+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {+ action_type: "auto_archive_update",+ surface: "sidebar",+ channel_id: channel.id,+ inactivity_days: days,+ success: true,+ });+ if (days === null) {+ toast.success("Auto-archive is off");+ } else {+ toast.success("Auto-archive is on", {+ description: `Inactive tasks will be archived after ${days} ${days === 1 ? "day" : "days"}.`,+ });+ }+ return true;+ } catch (error) {+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {+ action_type: "auto_archive_update",+ surface: "sidebar",+ channel_id: channel.id,+ inactivity_days: days,+ success: false,+ });+ toast.error("Couldn't update automatic archiving", {+ description: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ };+// Memoized because it travels to the shared preview card as the space// trigger's payload, which is written to the card's store whenever its// identity changes.- const actions: ChannelActionItem[] = useMemo(- () => [- {- key: "star",- label: isStarred ? `Unstar ${noun}` : `Star ${noun}`,- icon: <StarIcon size={14} weight={isStarred ? "fill" : "regular"} />,- onSelect: () => {- track(ANALYTICS_EVENTS.CHANNEL_ACTION, {- action_type: isStarred ? "unstar" : "star",- surface: "sidebar",- channel_id: channel.id,- });- toggleStar();- },- },+ const actions: ChannelActionItem[] = useMemo(() => {+ const sharedSpaceActions: ChannelActionItem[] =+ channel.channelType === "personal"+ ? []+ : [+ {+ key: "star",+ label: isStarred ? `Unstar ${noun}` : `Star ${noun}`,+ icon: (+ <StarIcon size={14} weight={isStarred ? "fill" : "regular"} />+ ),+ onSelect: () => {+ track(ANALYTICS_EVENTS.CHANNEL_ACTION, {+ action_type: isStarred ? "unstar" : "star",+ surface: "sidebar",+ channel_id: channel.id,+ });+ toggleStar();+ },+ },+ ];+ const editableSpaceActions: ChannelActionItem[] =+ channel.channelType === "personal"+ ? []+ : [+ {+ key: "rename",+ label: `Rename ${noun}…`,+ icon: <PencilSimpleIcon size={14} />,+ onSelect: () => setRenameOpen(true),+ },+ {+ key: "delete",+ label: `Delete ${noun}…`,+ icon: <TrashIcon size={14} />,+ variant: "destructive",+ onSelect: () => setConfirmDeleteOpen(true),+ },+ ];+ return [+ ...sharedSpaceActions,{key: "copy-link",label: "Copy link",@@ -800,25 +874,32 @@ function useChannelActions(channel: Channel): {onSelect: () => void copyChannelLink(channel.id, "sidebar"),},{- key: "rename",- label: `Rename ${noun}…`,- icon: <PencilSimpleIcon size={14} />,+ key: "auto-archive",+ label:+ channel.autoArchiveAfterDays == null+ ? "Auto-archive: off…"+ : `Auto-archive: ${channel.autoArchiveAfterDays} ${channel.autoArchiveAfterDays === 1 ? "day" : "days"}…`,+ icon: <ArchiveBoxIcon size={14} />,separatorBefore: true,- onSelect: () => setRenameOpen(true),- },- {- key: "delete",- label: `Delete ${noun}…`,- icon: <TrashIcon size={14} />,- variant: "destructive",- onSelect: () => setConfirmDeleteOpen(true),+ onSelect: () => setAutoArchiveOpen(true),},- ],- [channel.id, isStarred, noun, toggleStar],- );+ ...editableSpaceActions,+ ];+ }, [+ channel.autoArchiveAfterDays,+ channel.channelType,+ channel.id,+ isStarred,+ noun,+ toggleStar,+ ]);return {actions,+ autoArchiveOpen,+ setAutoArchiveOpen,+ saveAutoArchive,+ isUpdatingAutoArchive,renameOpen,setRenameOpen,confirmDeleteOpen,@@ -975,6 +1056,10 @@ const ChannelSection = memo(// the same star / edit / rename / delete actions.const {actions,+ autoArchiveOpen,+ setAutoArchiveOpen,+ saveAutoArchive,+ isUpdatingAutoArchive,renameOpen,setRenameOpen,confirmDeleteOpen,@@ -1028,7 +1113,7 @@ const ChannelSection = memo(return (<>- <Box+ <divclassName="group/chan relative"{...hoverProps}// Warm the sessions while the pointer is on the row, so opening the@@ -1235,7 +1320,14 @@ const ChannelSection = memo(</AlertDialogFooter></AlertDialogContent></ConfirmDialog>- </Box>+ <AutoArchiveSettingsDialog+ channel={channel}+ open={autoArchiveOpen}+ onOpenChange={setAutoArchiveOpen}+ onSave={saveAutoArchive}+ isSaving={isUpdatingAutoArchive}+ />+ </div>{expanded && (<SpaceTaskRowsspaceId={channel.id}@@ -1265,6 +1357,7 @@ const ChannelSection = memo(prev.channel.name === next.channel.name &&prev.channel.starred === next.channel.starred &&prev.channel.channelType === next.channel.channelType &&+ prev.channel.autoArchiveAfterDays === next.channel.autoArchiveAfterDays &&prev.channel.createdBy?.uuid === next.channel.createdBy?.uuid &&// By content: the poll hands out a new array even when the repos are the// same, and the space's card draws them.@@ -1366,6 +1459,22 @@ const PersonalChannelRow = memo(function PersonalChannelRow({// Startup provisions #me, so `undefined` means the list has not loaded yet.const meChannel = channels.find((c) => c.channelType === "personal");+ const channelForActions = meChannel ?? {+ id: "",+ name: PERSONAL_CHANNEL_LABEL,+ channelType: "personal" as const,+ starred: true,+ repositories: [],+ createdBy: null,+ };+ const [menuOpen, setMenuOpen] = useState(false);+ const {+ actions,+ autoArchiveOpen,+ setAutoArchiveOpen,+ saveAutoArchive,+ isUpdatingAutoArchive,+ } = useChannelActions(channelForActions);const isUnread = useIsChannelUnread()(meChannel?.id);const unreadSessions = useUnreadSessionCount()(meChannel?.id);const blockedSessions = useBlockedSessionCount()(meChannel?.id);@@ -1405,7 +1514,7 @@ const PersonalChannelRow = memo(function PersonalChannelRow({return (<>- <Box className="group/chan relative">+ <div className="group/chan relative"><SpaceRowSurfaceasOption={spacesLayout}optionValue={meChannel?.id ?? PERSONAL_ROW_VALUE}@@ -1432,7 +1541,7 @@ const PersonalChannelRow = memo(function PersonalChannelRow({>{PERSONAL_CHANNEL_LABEL}</span>- <span className="mt-[2px] flex shrink-0 items-center gap-1">+ <span className="mt-[2px] flex shrink-0 items-center gap-1 group-hover/chan:mr-11"><SpaceAttentionDotcount={blockedSessions}tone="blocked"@@ -1447,24 +1556,43 @@ const PersonalChannelRow = memo(function PersonalChannelRow({)}</SpaceRowSurface><div className="absolute top-0 right-1">- <Tooltip>- <TooltipTrigger- render={- <Button- variant="outline"- size="icon-xs"- aria-label={`New task in ${PERSONAL_CHANNEL_LABEL}`}- className="gap-1 opacity-0 transition-opacity group-hover:border-border group-hover/chan:opacity-100"- onClick={newTask}- >- <PlusIcon size={12} weight="bold" />- </Button>- }- />- <TooltipContent side="top">New task</TooltipContent>- </Tooltip>+ <ButtonGroup>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="icon-xs"+ aria-label={`New task in ${PERSONAL_CHANNEL_LABEL}`}+ className="gap-1 opacity-0 transition-opacity group-hover:border-border group-hover/chan:opacity-100"+ onClick={newTask}+ >+ <PlusIcon size={12} weight="bold" />+ </Button>+ }+ />+ <TooltipContent side="top">New task</TooltipContent>+ </Tooltip>+ {meChannel && (+ <ChannelMenu+ channelName={PERSONAL_CHANNEL_LABEL}+ actions={actions}+ open={menuOpen}+ onOpenChange={setMenuOpen}+ />+ )}+ </ButtonGroup></div>- </Box>+ {meChannel && (+ <AutoArchiveSettingsDialog+ channel={meChannel}+ open={autoArchiveOpen}+ onOpenChange={setAutoArchiveOpen}+ onSave={saveAutoArchive}+ isSaving={isUpdatingAutoArchive}+ />+ )}+ </div>{expanded && meChannel && (<SpaceTaskRowsspaceId={meChannel.id}@@ -1921,7 +2049,7 @@ export function ChannelsList() {);const body = (- <Flex direction="column" className="h-full min-h-0">+ <div className="flex h-full min-h-0 flex-col">{channelsLayout && (<SidebarSearchHeadertitle="Spaces"@@ -1937,11 +2065,9 @@ export function ChannelsList() {// pane opens rather than only once you've typed something.<AutocompleteList className={listClass}>{rows}</AutocompleteList>) : (- <Flex direction="column" gap="px" className={scrollClass}>- {rows}- </Flex>+ <div className={cn("flex flex-col gap-px", scrollClass)}>{rows}</div>)}- </Flex>+ </div>);return (diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.test.tsxindex ceecb83141db..cc91e658ec26 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.test.tsx@@ -8,6 +8,7 @@ const mockClient = vi.hoisted(() => ({getTaskChannels: vi.fn(),resolveTaskChannel: vi.fn(),starTaskChannel: vi.fn(),+ updateTaskChannelAutoArchive: vi.fn(),}));vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => mockClient,@@ -160,4 +161,32 @@ describe("useChannelMutations", () => {expect(mockClient.starTaskChannel).not.toHaveBeenCalled();});++ it("updates the shared channel cache after changing automatic archiving", async () => {+ const existing = taskChannel("1", "alpha");+ const updated = {+ ...existing,+ auto_archive_after_days: 7,+ };+ mockClient.getTaskChannels+ .mockResolvedValueOnce([existing])+ .mockResolvedValue([updated]);+ mockClient.updateTaskChannelAutoArchive.mockResolvedValue(updated);++ const list = renderHook(() => useChannels(), { wrapper });+ await waitFor(() => expect(list.result.current.isLoading).toBe(false));+ const mutations = renderHook(() => useChannelMutations(), { wrapper });++ await act(async () => {+ await mutations.result.current.updateAutoArchive("1", 7);+ });++ expect(mockClient.updateTaskChannelAutoArchive).toHaveBeenCalledWith(+ "1",+ 7,+ );+ await waitFor(() =>+ expect(list.result.current.channels[0]?.autoArchiveAfterDays).toBe(7),+ );+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.tsindex a957aca09418..5e853057e6f6 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannels.ts@@ -19,6 +19,8 @@ export interface Channel {starred: boolean;/** The repos the space is wired to. Empty where none are. */repositories: string[];+ /** Days of inactivity before tasks are archived. Null disables the rule. */+ autoArchiveAfterDays?: number | null;/** Who made the space, where the backend knows. */createdBy: UserBasic | null;}@@ -32,6 +34,7 @@ function toChannel(channel: TaskChannel): Channel {channelType: channel.channel_type,starred: channel.starred,repositories: channel.repositories ?? NO_REPOSITORIES,+ autoArchiveAfterDays: channel.auto_archive_after_days ?? null,createdBy: channel.created_by ?? null,};}@@ -128,14 +131,40 @@ export function useChannelMutations() {onSuccess: invalidate,});+ const autoArchiveMutation = useMutation({+ mutationFn: async ({+ id,+ inactivityDays,+ }: {+ id: string;+ inactivityDays: number | null;+ }) => {+ if (!client) throw new Error("Not authenticated");+ return client.updateTaskChannelAutoArchive(id, inactivityDays);+ },+ onSuccess: (updatedChannel) => {+ queryClient.setQueryData<TaskChannel[]>(+ TASK_CHANNELS_QUERY_KEY,+ (channels) =>+ channels?.map((channel) =>+ channel.id === updatedChannel.id ? updatedChannel : channel,+ ),+ );+ invalidate();+ },+ });+return {createChannel: (name: string, options: { star: boolean }) =>createMutation.mutateAsync({ name, star: options.star }).then(toChannel),deleteChannel: (id: string) => deleteMutation.mutateAsync(id),renameChannel: (id: string, name: string) =>renameMutation.mutateAsync({ id, name }).then(toChannel),+ updateAutoArchive: (id: string, inactivityDays: number | null) =>+ autoArchiveMutation.mutateAsync({ id, inactivityDays }).then(toChannel),isCreating: createMutation.isPending,isDeleting: deleteMutation.isPending,isRenaming: renameMutation.isPending,+ isUpdatingAutoArchive: autoArchiveMutation.isPending,};}diff --git a/products/desktop/packages/workspace-server/src/db/migrations/0024_exotic_hammerhead.sql b/products/desktop/packages/workspace-server/src/db/migrations/0024_exotic_hammerhead.sqlnew file mode 100644index 000000000000..f976fc13aa6d--- /dev/null+++ b/products/desktop/packages/workspace-server/src/db/migrations/0024_exotic_hammerhead.sql@@ -0,0 +1 @@+ALTER TABLE `task_metadata` ADD `server_archive_scope` text;diff --git a/products/desktop/packages/workspace-server/src/db/migrations/meta/0024_snapshot.json b/products/desktop/packages/workspace-server/src/db/migrations/meta/0024_snapshot.jsonnew file mode 100644index 000000000000..911b1aa908c7--- /dev/null+++ b/products/desktop/packages/workspace-server/src/db/migrations/meta/0024_snapshot.json@@ -0,0 +1,1093 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "f96fee91-b655-43a4-b043-96bc2563e1b6",+ "prevId": "fc7564a5-1e11-4c07-b085-b914e86d5fd7",+ "tables": {+ "archives": {+ "name": "archives",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "branch_name": {+ "name": "branch_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkpoint_id": {+ "name": "checkpoint_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "task_created_at": {+ "name": "task_created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "repository": {+ "name": "repository",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "archives_workspaceId_unique": {+ "name": "archives_workspaceId_unique",+ "columns": ["workspace_id"],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "archives_workspace_id_workspaces_id_fk": {+ "name": "archives_workspace_id_workspaces_id_fk",+ "tableFrom": "archives",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_org_project_preferences": {+ "name": "auth_org_project_preferences",+ "columns": {+ "account_key": {+ "name": "account_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cloud_region": {+ "name": "cloud_region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "org_id": {+ "name": "org_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_selected_project_id": {+ "name": "last_selected_project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "auth_org_project_account_region_org_idx": {+ "name": "auth_org_project_account_region_org_idx",+ "columns": ["account_key", "cloud_region", "org_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_preferences": {+ "name": "auth_preferences",+ "columns": {+ "account_key": {+ "name": "account_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cloud_region": {+ "name": "cloud_region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_selected_project_id": {+ "name": "last_selected_project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_selected_org_id": {+ "name": "last_selected_org_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "auth_preferences_account_region_idx": {+ "name": "auth_preferences_account_region_idx",+ "columns": ["account_key", "cloud_region"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_sessions": {+ "name": "auth_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token_encrypted": {+ "name": "refresh_token_encrypted",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cloud_region": {+ "name": "cloud_region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "selected_project_id": {+ "name": "selected_project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope_version": {+ "name": "scope_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "autoresearch_runs": {+ "name": "autoresearch_runs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "autoresearch_runs_task_id_idx": {+ "name": "autoresearch_runs_task_id_idx",+ "columns": ["task_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "browser_tabs": {+ "name": "browser_tabs",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "window_id": {+ "name": "window_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "href": {+ "name": "href",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "view_state": {+ "name": "view_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dashboard_id": {+ "name": "dashboard_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "channel_id": {+ "name": "channel_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "channel_section": {+ "name": "channel_section",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "app_view": {+ "name": "app_view",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "scroll_state": {+ "name": "scroll_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_active_at": {+ "name": "last_active_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "browser_tabs_window_idx": {+ "name": "browser_tabs_window_idx",+ "columns": ["window_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "browser_tabs_window_id_browser_windows_id_fk": {+ "name": "browser_tabs_window_id_browser_windows_id_fk",+ "tableFrom": "browser_tabs",+ "tableTo": "browser_windows",+ "columnsFrom": ["window_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "browser_windows": {+ "name": "browser_windows",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "is_primary": {+ "name": "is_primary",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "bounds": {+ "name": "bounds",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_tab_id": {+ "name": "active_tab_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "claude_session_imports": {+ "name": "claude_session_imports",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "source_session_id": {+ "name": "source_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "imported_session_id": {+ "name": "imported_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repo_path": {+ "name": "repo_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_mtime_ms": {+ "name": "source_mtime_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_size_bytes": {+ "name": "source_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source_last_entry_uuid": {+ "name": "source_last_entry_uuid",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "claude_session_imports_importedSessionId_unique": {+ "name": "claude_session_imports_importedSessionId_unique",+ "columns": ["imported_session_id"],+ "isUnique": true+ },+ "claude_session_imports_source_idx": {+ "name": "claude_session_imports_source_idx",+ "columns": ["source_session_id"],+ "isUnique": false+ },+ "claude_session_imports_task_idx": {+ "name": "claude_session_imports_task_idx",+ "columns": ["task_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "default_additional_directories": {+ "name": "default_additional_directories",+ "columns": {+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "repositories": {+ "name": "repositories",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "remote_url": {+ "name": "remote_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_accessed_at": {+ "name": "last_accessed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "repositories_path_unique": {+ "name": "repositories_path_unique",+ "columns": ["path"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "suspensions": {+ "name": "suspensions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "branch_name": {+ "name": "branch_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "checkpoint_id": {+ "name": "checkpoint_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "suspended_at": {+ "name": "suspended_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "suspensions_workspaceId_unique": {+ "name": "suspensions_workspaceId_unique",+ "columns": ["workspace_id"],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "suspensions_workspace_id_workspaces_id_fk": {+ "name": "suspensions_workspace_id_workspaces_id_fk",+ "tableFrom": "suspensions",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "task_metadata": {+ "name": "task_metadata",+ "columns": {+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_viewed_at": {+ "name": "last_viewed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_activity_at": {+ "name": "last_activity_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "archived_title": {+ "name": "archived_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "archived_task_created_at": {+ "name": "archived_task_created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "archived_repository": {+ "name": "archived_repository",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "server_archive_scope": {+ "name": "server_archive_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pi_session_file": {+ "name": "pi_session_file",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "workspaces": {+ "name": "workspaces",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "repository_id": {+ "name": "repository_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "mode": {+ "name": "mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "linked_branch": {+ "name": "linked_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pinned_at": {+ "name": "pinned_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_viewed_at": {+ "name": "last_viewed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_activity_at": {+ "name": "last_activity_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "additional_directories": {+ "name": "additional_directories",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "pr_url": {+ "name": "pr_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pr_state": {+ "name": "pr_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "pr_urls": {+ "name": "pr_urls",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "workspaces_taskId_unique": {+ "name": "workspaces_taskId_unique",+ "columns": ["task_id"],+ "isUnique": true+ },+ "workspaces_repository_id_idx": {+ "name": "workspaces_repository_id_idx",+ "columns": ["repository_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "workspaces_repository_id_repositories_id_fk": {+ "name": "workspaces_repository_id_repositories_id_fk",+ "tableFrom": "workspaces",+ "tableTo": "repositories",+ "columnsFrom": ["repository_id"],+ "columnsTo": ["id"],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "worktrees": {+ "name": "worktrees",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(CURRENT_TIMESTAMP)"+ }+ },+ "indexes": {+ "worktrees_workspaceId_unique": {+ "name": "worktrees_workspaceId_unique",+ "columns": ["workspace_id"],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "worktrees_workspace_id_workspaces_id_fk": {+ "name": "worktrees_workspace_id_workspaces_id_fk",+ "tableFrom": "worktrees",+ "tableTo": "workspaces",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json b/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.jsonindex 4a009af979d1..6943828fd43a 100644--- a/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json+++ b/products/desktop/packages/workspace-server/src/db/migrations/meta/_journal.json@@ -169,6 +169,13 @@"when": 1785600000000,"tag": "0023_browser_tab_href","breakpoints": true+ },+ {+ "idx": 24,+ "version": "6",+ "when": 1788187751331,+ "tag": "0024_exotic_hammerhead",+ "breakpoints": true}]}diff --git a/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.mock.ts b/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.mock.tsindex 0d20965e9e78..4fb62b00857e 100644--- a/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.mock.ts+++ b/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.mock.ts@@ -45,6 +45,10 @@ export function createMockTaskMetadataRepository(): MockTaskMetadataRepository {"archivedRepository" in patch? (patch.archivedRepository ?? null): (existing?.archivedRepository ?? null),+ serverArchiveScope:+ "serverArchiveScope" in patch+ ? (patch.serverArchiveScope ?? null)+ : (existing?.serverArchiveScope ?? null),piSessionFile:"piSessionFile" in patch? (patch.piSessionFile ?? null)diff --git a/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.ts b/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.tsindex 67ad562e9f58..680113e3339b 100644--- a/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.ts+++ b/products/desktop/packages/workspace-server/src/db/repositories/task-metadata-repository.ts@@ -17,6 +17,7 @@ export interface TaskMetadataPatch {archivedTitle?: string | null;archivedTaskCreatedAt?: string | null;archivedRepository?: string | null;+ serverArchiveScope?: string | null;piSessionFile?: string | null;}diff --git a/products/desktop/packages/workspace-server/src/db/schema.ts b/products/desktop/packages/workspace-server/src/db/schema.tsindex c4d0e5f809f3..6b872464398e 100644--- a/products/desktop/packages/workspace-server/src/db/schema.ts+++ b/products/desktop/packages/workspace-server/src/db/schema.ts@@ -63,6 +63,7 @@ export const taskMetadata = sqliteTable("task_metadata", {archivedTitle: text(),archivedTaskCreatedAt: text(),archivedRepository: text(),+ serverArchiveScope: text(),piSessionFile: text(),createdAt: createdAt(),updatedAt: updatedAt(),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 f5c9a3f516a6..757b7dba8ca4 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@@ -629,6 +629,29 @@ describe("ArchiveService integration", () => {expect(ctx.service.getArchivedTaskIds()).toEqual(["nonexistent"]);}));+ it("only lists a server-imported archive for its account and project", () =>+ withTestContext({ hasWorkspace: false }, async (ctx) => {+ await ctx.service.archiveTask({+ taskId: "server-archive",+ title: "Private server task",+ serverArchiveScope: "us:user-a:42",+ });+ await ctx.service.archiveTask({ taskId: "local-archive" });++ expect(ctx.service.getArchivedTaskIds("us:user-a:42")).toEqual([+ "server-archive",+ "local-archive",+ ]);+ expect(ctx.service.getArchivedTaskIds("us:user-b:42")).toEqual([+ "local-archive",+ ]);+ expect(+ ctx.service+ .getArchivedTasks("us:user-b:42")+ .map((task) => task.title),+ ).not.toContain("Private server task");+ }));+// Unarchive and delete are parallel "remove a rowless task from the archived// list" operations sharing the same arrange step; the per-case `extraAssert`// covers what's unique (delete also drops the metadata row, not just thediff --git a/products/desktop/packages/workspace-server/src/services/archive/archive.ts b/products/desktop/packages/workspace-server/src/services/archive/archive.tsindex 01cfe214ea48..4e6dab40791f 100644--- a/products/desktop/packages/workspace-server/src/services/archive/archive.ts+++ b/products/desktop/packages/workspace-server/src/services/archive/archive.ts@@ -170,6 +170,7 @@ export class ArchiveService {archivedTitle: input.title ?? null,archivedTaskCreatedAt: input.taskCreatedAt ?? null,archivedRepository: input.repository ?? null,+ serverArchiveScope: input.serverArchiveScope ?? null,});},async () => {@@ -531,20 +532,22 @@ export class ArchiveService {return { taskId, worktreeName: restoredWorktreeName };}- getArchivedTasks(): ArchivedTask[] {+ getArchivedTasks(serverArchiveScope: string | null = null): ArchivedTask[] {const fromWorkspaces = this.archiveRepo.findAll().map((archive) => {const workspace = this.workspaceRepo.findById(archive.workspaceId,) as Workspace;return this.toArchivedTask(workspace, archive);});- const rowless = this.rowlessArchived().map((meta) =>+ const rowless = this.rowlessArchived(serverArchiveScope).map((meta) =>this.toRowlessArchivedTask(meta),);return [...fromWorkspaces, ...rowless];}- async listArchivedTasks(): Promise<ArchivedTask[]> {+ async listArchivedTasks(+ serverArchiveScope: string | null = null,+ ): Promise<ArchivedTask[]> {if (!this.recoveryStarted) {this.recoveryStarted = true;void this.recoverArchivedTaskDetails().catch((error) => {@@ -552,7 +555,7 @@ export class ArchiveService {this.log.warn("Failed to recover archived task details", { error });});}- return this.getArchivedTasks();+ return this.getArchivedTasks(serverArchiveScope);}private async recoverArchivedTaskDetails(): Promise<void> {@@ -615,13 +618,20 @@ export class ArchiveService {// workspace row is owned by the `archives` table, so it's excluded here even// if an `archivedAt` lingers in its metadata — otherwise it would surface// twice in the archived lists.- private rowlessArchived(): TaskMetadataRow[] {+ private rowlessArchived(+ serverArchiveScope: string | null = null,+ ): TaskMetadataRow[] {return this.taskMetadataRepo.findAllArchived()- .filter((meta) => !this.workspaceRepo.findByTaskId(meta.taskId));+ .filter(+ (meta) =>+ !this.workspaceRepo.findByTaskId(meta.taskId) &&+ (meta.serverArchiveScope === null ||+ meta.serverArchiveScope === serverArchiveScope),+ );}- getArchivedTaskIds(): string[] {+ getArchivedTaskIds(serverArchiveScope: string | null = null): string[] {const fromWorkspaces = this.archiveRepo.findAll().map((archive) => {@@ -629,7 +639,9 @@ export class ArchiveService {return workspace?.taskId;}).filter((id): id is string => id !== undefined);- const rowless = this.rowlessArchived().map((meta) => meta.taskId);+ const rowless = this.rowlessArchived(serverArchiveScope).map(+ (meta) => meta.taskId,+ );return [...fromWorkspaces, ...rowless];}diff --git a/products/desktop/packages/workspace-server/src/services/archive/schemas.ts b/products/desktop/packages/workspace-server/src/services/archive/schemas.tsindex 55ccc3664a05..b0ea3be3db3a 100644--- a/products/desktop/packages/workspace-server/src/services/archive/schemas.ts+++ b/products/desktop/packages/workspace-server/src/services/archive/schemas.ts@@ -21,6 +21,7 @@ export const archiveTaskInput = z.object({title: z.string().optional(),taskCreatedAt: z.string().optional(),repository: z.string().nullable().optional(),+ serverArchiveScope: z.string().optional(),});export type ArchiveTaskInput = z.infer<typeof archiveTaskInput>;@@ -41,6 +42,10 @@ export const listArchivedTasksOutput = z.array(archivedTaskSchema);export const archivedTaskIdsOutput = z.array(z.string());+export const archiveScopeInput = z.object({+ serverArchiveScope: z.string().nullable(),+});+export const deleteArchivedTaskInput = z.object({taskId: z.string(),});