Files
PaperClipAI/ui/src/context/ToastContext.tsx
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

225 lines
5.9 KiB
TypeScript

import type { AgentAppearance } from "@paperclipai/shared";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
export type ToastTone = "info" | "success" | "warn" | "error";
export interface ToastAction {
label: string;
/** Navigate on click (mutually exclusive with `onClick`). */
href?: string;
/** Run a callback on click, e.g. an undo (mutually exclusive with `href`). */
onClick?: () => void;
}
export type ToastActor = {
type: "user" | "agent";
id: string;
name: string;
image?: string | null;
appearance?: AgentAppearance | null;
};
export interface ToastInput {
id?: string;
dedupe?: boolean;
dedupeKey?: string;
title: string;
body?: string;
tone?: ToastTone;
ttlMs?: number;
action?: ToastAction;
actor?: ToastActor;
}
export interface ToastItem {
id: string;
title: string;
body?: string;
tone: ToastTone;
ttlMs: number;
action?: ToastAction;
actor?: ToastActor;
createdAt: number;
}
interface ToastActionsContextValue {
pushToast: (input: ToastInput) => string | null;
dismissToast: (id: string) => void;
clearToasts: () => void;
}
interface ToastContextValue extends ToastActionsContextValue {
toasts: ToastItem[];
}
const DEFAULT_TTL_BY_TONE: Record<ToastTone, number> = {
info: 4000,
success: 3500,
warn: 8000,
error: 10000,
};
const MIN_TTL_MS = 1500;
const MAX_TTL_MS = 15000;
const MAX_TOASTS = 5;
const DEDUPE_WINDOW_MS = 3500;
const DEDUPE_MAX_AGE_MS = 20000;
const ToastStateContext = createContext<ToastItem[] | null>(null);
const ToastActionsContext = createContext<ToastActionsContextValue | null>(null);
function normalizeTtl(value: number | undefined, tone: ToastTone) {
const fallback = DEFAULT_TTL_BY_TONE[tone];
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
return Math.max(MIN_TTL_MS, Math.min(MAX_TTL_MS, Math.floor(value)));
}
function generateToastId() {
return `toast_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<ToastItem[]>([]);
const timersRef = useRef(new Map<string, number>());
const dedupeRef = useRef(new Map<string, number>());
const clearTimer = useCallback((id: string) => {
const handle = timersRef.current.get(id);
if (handle !== undefined) {
window.clearTimeout(handle);
timersRef.current.delete(id);
}
}, []);
const dismissToast = useCallback(
(id: string) => {
clearTimer(id);
setToasts((prev) => prev.filter((toast) => toast.id !== id));
},
[clearTimer],
);
const clearToasts = useCallback(() => {
for (const handle of timersRef.current.values()) {
window.clearTimeout(handle);
}
timersRef.current.clear();
setToasts([]);
}, []);
const pushToast = useCallback(
(input: ToastInput) => {
const now = Date.now();
const tone = input.tone ?? "info";
const ttlMs = normalizeTtl(input.ttlMs, tone);
const dedupeKey =
input.dedupeKey ?? input.id ?? `${tone}|${input.title}|${input.body ?? ""}|${input.action?.href ?? ""}`;
for (const [key, ts] of dedupeRef.current.entries()) {
if (now - ts > DEDUPE_MAX_AGE_MS) {
dedupeRef.current.delete(key);
}
}
// Distinct events (two runs, two status changes) can render the same
// visible text. Showing it twice reads as a duplicate, so match on that too.
const contentKey = `content|${tone}|${input.title}|${input.body ?? ""}`;
const recentlyShown = [dedupeKey, contentKey].some((key) => {
const lastSeen = dedupeRef.current.get(key);
return lastSeen !== undefined && now - lastSeen < DEDUPE_WINDOW_MS;
});
if (input.dedupe !== false) {
if (recentlyShown) return null;
dedupeRef.current.set(dedupeKey, now);
dedupeRef.current.set(contentKey, now);
}
const id = input.id ?? generateToastId();
clearTimer(id);
setToasts((prev) => {
const nextToast: ToastItem = {
id,
title: input.title,
body: input.body,
tone,
ttlMs,
action: input.action,
actor: input.actor,
createdAt: now,
};
const withoutCurrent = prev.filter((toast) => toast.id !== id);
return [nextToast, ...withoutCurrent].slice(0, MAX_TOASTS);
});
const timeout = window.setTimeout(() => {
dismissToast(id);
}, ttlMs);
timersRef.current.set(id, timeout);
return id;
},
[clearTimer, dismissToast],
);
useEffect(() => () => {
for (const handle of timersRef.current.values()) {
window.clearTimeout(handle);
}
timersRef.current.clear();
}, []);
const actions = useMemo<ToastActionsContextValue>(
() => ({
pushToast,
dismissToast,
clearToasts,
}),
[pushToast, dismissToast, clearToasts],
);
return (
<ToastActionsContext.Provider value={actions}>
<ToastStateContext.Provider value={toasts}>{children}</ToastStateContext.Provider>
</ToastActionsContext.Provider>
);
}
export function useToastState() {
const context = useContext(ToastStateContext);
if (!context) {
throw new Error("useToastState must be used within a ToastProvider");
}
return context;
}
export function useToastActions() {
const context = useContext(ToastActionsContext);
if (!context) {
throw new Error("useToastActions must be used within a ToastProvider");
}
return context;
}
export function useOptionalToastActions() {
return useContext(ToastActionsContext);
}
export function useOptionalToastState() {
return useContext(ToastStateContext);
}
export function useToast() {
const toasts = useToastState();
const actions = useToastActions();
return useMemo<ToastContextValue>(() => ({ toasts, ...actions }), [toasts, actions]);
}