Files
PaperClipAI/ui/src/lib/inboxArchiveCache.ts
T
19a7381398 feat: restore personal archiving in task views (#22358)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People use Tasks to see shared work and manage the work that needs
their attention.
> - The old inbox already let each person archive a task and undo that
action.
> - The combined Tasks surface needs the same controls in Unread and in
task table rows.
> - The existing inbox archive rules determine when new activity brings
a task back.
> - This pull request adds an Archived view so people can find and
restore their archived tasks.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Personal task archiving in Tasks. Related work includes the combined
Inbox and Tasks surface (#15100), the Coordinator workspace (#17983),
moving Mine into Tasks (#19363), and the existing inbox archive rules
(#9931).

**Subsystem affected**

Cross-cutting. The UI and task list API reuse the existing inbox archive
state.

**Current behavior**

Mine has an archive action. Unread and the task table have no equivalent
action. The Tasks menu has no dedicated view for restoring archived
tasks.

**Proposed behavior**

Add Archive and Undo to the task views. Let people restore tasks from
Archived. Keep archived tasks available in All tasks.

**Reason and benefit**

People can clear their personal lists and still find the original task.

**Breaking changes**

The task list API adds an optional archive filter and viewer archive
field. Existing callers use the same response and filters unless they
opt in.

## What Changed

- Reuse the current inbox archive and restore actions, activity rules,
and authorization.
- Add Archive and Restore to task table rows, Archive and Undo to
Unread, and a personal Archived view.
- Give each archived task its own Undo control, including when people
archive tasks quickly.
- Add tests for the archive list, account isolation, new activity, row
actions, and Undo.
- Document the archive flow and API filter. Refresh the generated SDK
source input registry.

## Verification

- Passed 287 focused tests in 12 Vitest files. These cover the task
views, row actions, archive cache, and PostgreSQL routes.
- Passed local server and UI typechecks. The source input registry check
also passed.
- Reproduced a missing Undo action when archiving two tasks in a row.
After the fix, the 158 task and inbox tests and the 2 toast tests
passed.
- On macOS with Chrome, archived a task from Mine and restored it using
Undo. Archived another task from All tasks, reloaded Archived, restored
it, and verified its Todo status and return to Mine.
- A human tester also verified Archive, Undo, and Restore in the local
browser.

- On commit `c5526fd9b1`, GitHub's
[verification](https://github.com/paperclipai/paperclip/actions/runs/44630156078/job/135950130662)
and [browser
tests](https://github.com/paperclipai/paperclip/actions/runs/44630156078/job/135946228919)
passed. A targeted retry passed after the first attempt hit a watchdog
self-test failure and two cancelled jobs.
- [Greptile scored
5/5](https://github.com/paperclipai/paperclip/pull/22358#issuecomment-7024083610)
on the same commit. Both review threads are resolved.

## Risks

- An incorrect visibility rule could hide a task from a personal list.
The archived filter uses the same activity predicate as Mine. The
PostgreSQL test covers isolation between people and resurfacing after a
reply.
- The archive state is already stored per person and company. No
database migration is required.

## Model Used

- OpenAI Codex, GPT-6, with shell, code editing, and browser
verification tools. The serving model ID and context size were
unavailable in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-19 16:22:07 -08:00

277 lines
9.2 KiB
TypeScript

import { useSyncExternalStore } from "react";
import type { QueryClient, QueryKey } from "@tanstack/react-query";
import type { Issue } from "@paperclipai/shared";
import { queryKeys } from "./queryKeys";
export const PERSONAL_ARCHIVE_QUERY_KEY = "personal-archive";
export type InboxIssueCacheSnapshot = Array<readonly [QueryKey, Issue[] | undefined]>;
export const INBOX_ARCHIVE_CONFIRMATION_GRACE_MS = 5_000;
const INBOX_ARCHIVE_MAX_GUARD_MS = 30_000;
const EMPTY_ARCHIVED_ISSUE_IDS: ReadonlySet<string> = new Set();
type InboxArchiveGuardState = {
issueIds: ReadonlySet<string>;
tokens: Map<string, symbol>;
listeners: Set<() => void>;
confirmationTimers: Map<string, ReturnType<typeof setTimeout>>;
maximumTimers: Map<string, ReturnType<typeof setTimeout>>;
};
const inboxArchiveGuards = new Map<string, InboxArchiveGuardState>();
function pruneInboxArchiveGuard(companyId: string, state: InboxArchiveGuardState) {
if (
state.issueIds.size === 0
&& state.listeners.size === 0
&& state.confirmationTimers.size === 0
&& state.maximumTimers.size === 0
&& inboxArchiveGuards.get(companyId) === state
) {
inboxArchiveGuards.delete(companyId);
}
}
function getInboxArchiveGuard(companyId: string): InboxArchiveGuardState {
const existing = inboxArchiveGuards.get(companyId);
if (existing) return existing;
const created: InboxArchiveGuardState = {
issueIds: EMPTY_ARCHIVED_ISSUE_IDS,
tokens: new Map(),
listeners: new Set(),
confirmationTimers: new Map(),
maximumTimers: new Map(),
};
inboxArchiveGuards.set(companyId, created);
return created;
}
function publishInboxArchiveGuard(state: InboxArchiveGuardState, issueIds: Set<string>) {
state.issueIds = issueIds.size > 0 ? issueIds : EMPTY_ARCHIVED_ISSUE_IDS;
for (const listener of state.listeners) listener();
}
function clearArchiveGuardTimer(
timers: Map<string, ReturnType<typeof setTimeout>>,
issueId: string,
) {
const timer = timers.get(issueId);
if (timer) clearTimeout(timer);
timers.delete(issueId);
}
export function beginLocalInboxArchive(companyId: string, issueId: string) {
const state = getInboxArchiveGuard(companyId);
const token = Symbol();
state.tokens.set(issueId, token);
clearArchiveGuardTimer(state.confirmationTimers, issueId);
clearArchiveGuardTimer(state.maximumTimers, issueId);
const issueIds = new Set(state.issueIds);
issueIds.add(issueId);
publishInboxArchiveGuard(state, issueIds);
return () => {
if (state.tokens.get(issueId) === token) clearLocalInboxArchive(companyId, issueId);
};
}
export function boundLocalInboxArchive(companyId: string, issueId: string) {
const state = inboxArchiveGuards.get(companyId);
if (!state?.issueIds.has(issueId)) return;
clearArchiveGuardTimer(state.maximumTimers, issueId);
state.maximumTimers.set(issueId, setTimeout(() => {
clearLocalInboxArchive(companyId, issueId);
}, INBOX_ARCHIVE_MAX_GUARD_MS));
}
export function confirmLocalInboxArchive(companyId: string, issueId: string) {
const state = inboxArchiveGuards.get(companyId);
if (!state?.issueIds.has(issueId)) return;
clearArchiveGuardTimer(state.confirmationTimers, issueId);
state.confirmationTimers.set(issueId, setTimeout(() => {
clearLocalInboxArchive(companyId, issueId);
}, INBOX_ARCHIVE_CONFIRMATION_GRACE_MS));
}
export function clearLocalInboxArchive(companyId: string, issueId: string) {
const state = inboxArchiveGuards.get(companyId);
if (!state) return;
state.tokens.delete(issueId);
clearArchiveGuardTimer(state.confirmationTimers, issueId);
clearArchiveGuardTimer(state.maximumTimers, issueId);
if (!state.issueIds.has(issueId)) {
pruneInboxArchiveGuard(companyId, state);
return;
}
const issueIds = new Set(state.issueIds);
issueIds.delete(issueId);
publishInboxArchiveGuard(state, issueIds);
pruneInboxArchiveGuard(companyId, state);
}
export function getLocalInboxArchiveIssueIds(companyId: string | null | undefined): ReadonlySet<string> {
if (!companyId) return EMPTY_ARCHIVED_ISSUE_IDS;
return inboxArchiveGuards.get(companyId)?.issueIds ?? EMPTY_ARCHIVED_ISSUE_IDS;
}
export function useLocalInboxArchiveIssueIds(companyId: string | null | undefined): ReadonlySet<string> {
return useSyncExternalStore(
(listener) => {
if (!companyId) return () => undefined;
const state = getInboxArchiveGuard(companyId);
state.listeners.add(listener);
return () => {
state.listeners.delete(listener);
pruneInboxArchiveGuard(companyId, state);
};
},
() => getLocalInboxArchiveIssueIds(companyId),
() => EMPTY_ARCHIVED_ISSUE_IDS,
);
}
export function filterLocalInboxArchivedIssues(
companyId: string | null | undefined,
issues: Issue[],
): Issue[] {
const issueIds = getLocalInboxArchiveIssueIds(companyId);
if (issueIds.size === 0) return issues;
return issues.filter((issue) => !issueIds.has(issue.id));
}
function inboxIssueCompanyIdFromQueryKey(queryKey: QueryKey): string | null {
const inboxQueryKind = String(queryKey[2]);
if (
queryKey[0] !== "issues"
|| typeof queryKey[1] !== "string"
|| !["compact", "mine-by-me", "touched-by-me", "unread-touched-by-me"].includes(inboxQueryKind)
) {
return null;
}
return queryKey[1];
}
export function filterLocalInboxArchivedQueryData<TData>(queryKey: QueryKey, data: TData): TData {
const companyId = inboxIssueCompanyIdFromQueryKey(queryKey);
if (!companyId || !Array.isArray(data)) return data;
return filterLocalInboxArchivedIssues(companyId, data as Issue[]) as TData;
}
function inboxIssueQueryPrefixes(companyId: string) {
return [
[...queryKeys.issues.list(companyId), "compact"],
queryKeys.issues.listMineByMe(companyId),
queryKeys.issues.listTouchedByMe(companyId),
queryKeys.issues.listUnreadTouchedByMe(companyId),
] as const;
}
function resolveRestoreIndex(currentData: Issue[], previousData: Issue[], previousIndex: number) {
for (let index = previousIndex - 1; index >= 0; index -= 1) {
const beforeIndex = currentData.findIndex((issue) => issue.id === previousData[index]?.id);
if (beforeIndex >= 0) return beforeIndex + 1;
}
for (let index = previousIndex + 1; index < previousData.length; index += 1) {
const afterIndex = currentData.findIndex((issue) => issue.id === previousData[index]?.id);
if (afterIndex >= 0) return afterIndex;
}
return Math.min(previousIndex, currentData.length);
}
export async function cancelInboxIssueQueries(queryClient: QueryClient, companyId: string) {
await Promise.all(
inboxIssueQueryPrefixes(companyId).map((queryKey) =>
queryClient.cancelQueries({ queryKey }),
),
);
}
export function snapshotInboxIssueCaches(
queryClient: QueryClient,
companyId: string,
): InboxIssueCacheSnapshot {
return inboxIssueQueryPrefixes(companyId).flatMap((queryKey) =>
queryClient.getQueriesData<Issue[]>({ queryKey }),
);
}
export function removeIssueFromInboxCaches(
queryClient: QueryClient,
companyId: string,
issueId: string,
) {
for (const queryKey of inboxIssueQueryPrefixes(companyId)) {
queryClient.setQueriesData<Issue[]>(
{ queryKey },
(cached) => cached?.filter((issue) => issue.id !== issueId),
);
}
}
export function restoreIssueToInboxCaches(
queryClient: QueryClient,
snapshot: InboxIssueCacheSnapshot,
issueId: string,
) {
for (const [queryKey, previousData] of snapshot) {
if (!previousData) continue;
const previousIndex = previousData.findIndex((issue) => issue.id === issueId);
if (previousIndex < 0) continue;
const issueToRestore = previousData[previousIndex];
queryClient.setQueryData<Issue[]>(queryKey, (currentData) => {
if (currentData?.some((issue) => issue.id === issueId)) return currentData;
const nextData = [...(currentData ?? [])];
nextData.splice(resolveRestoreIndex(nextData, previousData, previousIndex), 0, issueToRestore);
return nextData;
});
}
}
export function invalidateInboxIssueQueries(queryClient: QueryClient, companyId: string) {
return Promise.all([
...inboxIssueQueryPrefixes(companyId).map((queryKey) =>
queryClient.invalidateQueries({ queryKey }),
),
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(companyId) }),
queryClient.invalidateQueries({ queryKey: queryKeys.issues.summaries(companyId) }),
]);
}
export function invalidateTaskArchiveQueries(queryClient: QueryClient, companyId: string) {
return Promise.all([
invalidateInboxIssueQueries(queryClient, companyId),
queryClient.invalidateQueries({
queryKey: queryKeys.issues.list(companyId),
predicate: ({ queryKey }) => queryKey.includes(PERSONAL_ARCHIVE_QUERY_KEY),
}),
]);
}
export function getIssuePresenceInActiveInboxCaches(
queryClient: QueryClient,
companyId: string,
issueId: string,
): "absent" | "present" | "unknown" {
const activeQueries = inboxIssueQueryPrefixes(companyId).flatMap((queryKey) =>
queryClient.getQueryCache().findAll({ queryKey })
.filter((query) => query.getObserversCount() > 0),
);
if (activeQueries.length === 0) return "unknown";
const isPresent = activeQueries.some((query) => {
const data = query.state.data;
return Array.isArray(data) && data.some((issue) => (issue as Issue).id === issueId);
});
return isPresent ? "present" : "absent";
}