diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index 5b6a0acd9a0..82ffb047b15 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -548,6 +548,12 @@ over. Unread, Recent, Blocked, and Everything are also task views. Organization views retain the task table and board. The table saves column selection and order per person and company. Old `/inbox/*` links redirect to their Tasks view. +Archive is personal. Use it from Mine, Unread, or a task-table row to +remove a task from your Mine and Unread views. All tasks and its status views +still include archived tasks. Use Undo after archiving, or open **Archived** +from the Views menu and restore a task. New replies from other people, mentions, +and other inbox activity such as a new decision request can bring a task back. + ### Combined Inbox + Task List In the Classic workspace, an opt-in setting (`enableCombinedInboxTasks`, off by default) diff --git a/docs/api/issues.md b/docs/api/issues.md index 4abe8e2b68b..54fca5809d1 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -37,9 +37,15 @@ Query parameters: | `parentIds` | One to 100 comma-separated parent UUIDs for batched child context; same projection restriction as `ids` | | `oneChildPerParent` | With `view=index` and `parentIds`, return at most one readable child per parent for collapsed-tree affordances | | `includeReadState` | Board-only `true` adds the current user's personal read state without removing read or untouched tasks | +| `inboxArchive` | `include` adds the viewer's archive state to each result. `archived` returns only tasks actively archived by the viewer. | Results sorted by priority. +`inboxArchive` requires a signed-in board user. The filter cannot be combined +with `attention`. When `inboxArchive` is present, each result includes the +boolean `isArchivedForMe`. Paperclip uses the same activity rules as Mine to +decide whether a task is still archived for the viewer. + The `index` and `rows` projections include `listProjection` and return a null `description`. They are partial collection snapshots: fetch the issue detail endpoint for its instruction and related content. Company and private-task access diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 5aef054bdb1..829a2f6d481 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1183,6 +1183,7 @@ export type { ExternalObjectSummary, ExternalObjectSummaryItem, CompactIssue, + IssueInboxArchiveFilter, IssueSummary, Issue, IssueVisibility, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 27184a4cd8e..90954cf80a1 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -729,6 +729,7 @@ export type { } from "./external-object.js"; export type { CompactIssue, + IssueInboxArchiveFilter, IssueSummary, Issue, IssueChangeReceiptEntry, diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 2ef360b54e5..849b293fb22 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -1038,6 +1038,7 @@ export interface Issue { lastActivityAt?: Date | null; isUnreadForMe?: boolean; unreadMessageCount?: number; + isArchivedForMe?: boolean; archivedAt?: Date | null; archivedByActorType?: "user" | "agent" | null; archivedByAgentId?: string | null; @@ -1046,6 +1047,8 @@ export interface Issue { updatedAt: Date; } +export type IssueInboxArchiveFilter = "include" | "archived"; + export type CompactIssue = Pick< Issue, | "listProjection" @@ -1102,6 +1105,7 @@ export type CompactIssue = Pick< lastExternalCommentAt?: Date | null; lastActivityAt?: Date | null; isUnreadForMe?: boolean; + isArchivedForMe?: boolean; archivedAt?: Date | null; archivedByActorType?: "user" | "agent" | null; archivedByAgentId?: string | null; diff --git a/server/src/__tests__/inbox-archive-routes.test.ts b/server/src/__tests__/inbox-archive-routes.test.ts index 73332aa157a..d6f054cb29a 100644 --- a/server/src/__tests__/inbox-archive-routes.test.ts +++ b/server/src/__tests__/inbox-archive-routes.test.ts @@ -195,6 +195,45 @@ describeEmbeddedPostgres("inbox archive routes", () => { .expect(({ body }) => expect(body).toEqual({ ok: true, userId: seeded.responsibleUserId })); }); + it("lists active archives for the signed-in person and keeps them in All tasks", async () => { + const seeded = await seed(); + const boardApp = (userId: string) => appFor({ + type: "board", + source: "session", + userId, + companyIds: [seeded.companyId], + memberships: [{ companyId: seeded.companyId, membershipRole: "operator", status: "active" }], + isInstanceAdmin: false, + }); + const app = boardApp(seeded.responsibleUserId); + const peer = boardApp(seeded.targetUserId); + const path = `/api/companies/${seeded.companyId}/issues`; + const list = (viewer: ReturnType, inboxArchive: string) => + request(viewer).get(path).query({ view: "index", inboxArchive }).expect(200); + + expect((await list(app, "archived")).body).toEqual([]); + await request(app).post(`/api/issues/${seeded.issueId}/inbox-archive`).send({}).expect(200); + expect((await list(app, "archived")).body).toMatchObject([{ id: seeded.issueId, isArchivedForMe: true }]); + expect((await list(app, "include")).body).toMatchObject([{ id: seeded.issueId, status: "todo", isArchivedForMe: true }]); + expect((await list(peer, "archived")).body).toEqual([]); + expect((await list(peer, "include")).body).toMatchObject([{ id: seeded.issueId, isArchivedForMe: false }]); + + await request(app).delete(`/api/issues/${seeded.issueId}/inbox-archive`).send({}).expect(200); + expect((await list(app, "archived")).body).toEqual([]); + + await request(app).post(`/api/issues/${seeded.issueId}/inbox-archive`).send({}).expect(200); + await db.insert(issueComments).values({ + companyId: seeded.companyId, + issueId: seeded.issueId, + authorUserId: seeded.targetUserId, + body: "New reply", + createdAt: new Date(Date.now() + 10_000), + }); + expect((await list(app, "archived")).body).toEqual([]); + expect((await list(app, "include")).body).toMatchObject([{ id: seeded.issueId, isArchivedForMe: false }]); + await request(appFor(agentActor(seeded))).get(path).query({ view: "index", inboxArchive: "archived" }).expect(403); + }); + it.each([false, true])("allows manual archive during human completion (existing archive: %s)", async (alreadyArchived) => { const seeded = await seed(); const svc = issueService(db); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 0df3332f67d..a4e55e2d33f 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -3121,6 +3121,9 @@ function toCompactIssue(issue: any): CompactIssue { ...(issue.isUnreadForMe !== undefined ? { isUnreadForMe: issue.isUnreadForMe } : {}), + ...(issue.isArchivedForMe !== undefined + ? { isArchivedForMe: issue.isArchivedForMe } + : {}), activeRecoveryAction: issue.activeRecoveryAction ?? null, interruption: issue.interruption ?? null, successfulRunHandoff: issue.successfulRunHandoff ?? null, @@ -8816,6 +8819,15 @@ export function issueRoutes( res.status(400).json({ error: "ids and parentIds require view=index or view=rows without attention" }); return; } + const inboxArchive = req.query.inboxArchive; + if (inboxArchive !== undefined && ((inboxArchive !== "include" && inboxArchive !== "archived") || attention)) { + res.status(400).json({ error: "inboxArchive must be include or archived and cannot be used with attention" }); + return; + } + if (inboxArchive && (req.actor.type !== "board" || !req.actor.userId)) { + res.status(403).json({ error: "inboxArchive requires board authentication" }); + return; + } const hasPlanDocument = parseOptionalBooleanQuery( req.query.hasPlanDocument, ); @@ -8983,6 +8995,9 @@ export function issueRoutes( assigneeUserId, touchedByUserId, inboxArchivedByUserId, + inboxArchive: inboxArchive && req.actor.type === "board" && req.actor.userId + ? { mode: inboxArchive, userId: req.actor.userId } + : undefined, unreadForUserId, readStateForUserId: includeReadState ? getActorInfo(req).actorId : undefined, projectId: uuidFilters.projectId, @@ -9040,7 +9055,7 @@ export function issueRoutes( requestKey, // The new collection projections must reflect read/archive/undo mutations // immediately. Keep in-flight coalescing and ETags, without a stale TTL body. - allowTtlCache: view === "compact", + allowTtlCache: view === "compact" && !inboxArchive, diagnostics: opts.issueListDiagnostics, compute: async () => { return prepareIssueListForActor(req, companyId, listFilters, view, { reportPagination: true }); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 8c4fbf67557..7b28f59f68a 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -2,7 +2,7 @@ import { recordMcpAttachmentCleanup, type McpAttachmentCleanup } from "./public- import { assertAgentInteraction } from "./agent-interaction-policy.js"; import { instancePublicOrigin, mayContainInventedHostLink, relativizeInventedHostLinks } from "./agent-invented-host-links.js"; import { currentPluginInteractionOrigin } from "./plugin-interaction-context.js"; -import type { IssueDisplayStatus } from "@paperclipai/shared"; +import type { IssueDisplayStatus, IssueInboxArchiveFilter } from "@paperclipai/shared"; import { issueDisplayStatusSql } from "./issue-display-status.js"; import { notifyStrandedAgentStatus, notifyActiveRunSilence } from "./live-run-recovery-notifications.js"; import { finishedIdleWake } from "./idle-work-proof.js"; @@ -1873,7 +1873,7 @@ export function parseStatusFilter( /** Closed, content-free phases of `issueService.list`, for response timing headers. */ export type IssueListPhase = | "candidates" | "query" | "labels" | "active_runs" | "user_stats" | "read_stats" | "last_activity" - | "archives" | "blocked_by" | "live_descendants" | "attention"; + | "archives" | "active_archives" | "blocked_by" | "live_descendants" | "attention"; export interface IssueListOptions { /** Wraps each internal read so callers can report per-phase timing. */ @@ -1914,6 +1914,7 @@ export interface IssueFilters { */ touchedCandidates?: "participation"; inboxArchivedByUserId?: string; + inboxArchive?: { userId: string; mode: IssueInboxArchiveFilter }; unreadForUserId?: string; /** Read projection only; never filters the result set by participation. */ readStateForUserId?: string; @@ -8591,11 +8592,16 @@ export function issueService(db: Db) { if (filters.parentIds.length === 0) return []; conditions.push(inArray(issues.parentId, filters.parentIds)); } + const inboxArchive = filters?.inboxArchive; + const archivedCondition = inboxArchive + ? sql`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})` + : undefined; + if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition); if (!filters?.q?.trim() && !filters?.issueIds) { conditions.push(isNull(issues.conversationAgentId)); // Explicit child navigation includes waiting chat tasks, just like // readable-child counts. Ambient lists still omit idle conversations. - if (!filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) { + if (!filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId && inboxArchive?.mode !== "archived") { conditions.push(nonIdleSlackIssueCondition()); } } @@ -8837,6 +8843,7 @@ export function issueService(db: Db) { readRows, lastActivityRows, archiveRows, + activeArchiveIds, blockedByMap, liveDescendantCountByIssueId, ] = await Promise.all([ @@ -8850,6 +8857,13 @@ export function issueService(db: Db) { contextUserId ? timePhase("archives", () => inboxArchiveRowsForIssues(db, companyId, contextUserId, issueIds)) : Promise.resolve([]), + inboxArchive?.mode === "include" && archivedCondition + ? timePhase("active_archives", async () => { + const archived = await db.select({ id: issues.id }).from(issues) + .where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds), archivedCondition)); + return new Set(archived.map(row => row.id)); + }) + : Promise.resolve(null), includeBlockedBy ? timePhase("blocked_by", () => blockedByMapForIssues(db, companyId, issueIds)) : Promise.resolve(new Map()), @@ -8882,6 +8896,10 @@ export function issueService(db: Db) { : Promise.resolve(new Map()), ])); + const archiveFields = (id: string) => inboxArchive + ? { isArchivedForMe: inboxArchive.mode === "archived" || activeArchiveIds?.has(id) === true } + : {}; + if (!contextUserId) { return withRuns.map((row) => { const activity = lastActivityByIssueId.get(row.id); @@ -8893,6 +8911,7 @@ export function issueService(db: Db) { ) ?? row.updatedAt; return { ...row, + ...archiveFields(row.id), ...(includeBlockedBy ? { blockedBy: blockedByMap.get(row.id) ?? [] } : {}), @@ -8934,6 +8953,7 @@ export function issueService(db: Db) { ) ?? row.updatedAt; return { ...row, + ...archiveFields(row.id), ...activeInboxArchiveFields( archiveByIssueId.get(row.id), lastActivityAt, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 0d08ad7b265..d04f5b48890 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -272,7 +272,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "5aef054bdb11de0e9e42a2d54bdf05b3f3bd4288", + "packages/shared/src/index.ts": "829a2f6d4816ee1844c3d5334937b22cac08457c", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -429,10 +429,10 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "27184a4cd8e340ac4cea30e8a16efeb125cdf1e5", + "packages/shared/src/types/index.ts": "90954cf80a138fb0e2f79468bcc9c405b1cead93", "packages/shared/src/types/instance.ts": "77b0052be0f64a5531c5ebf0fd078c9854084479", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "2ef360b54e5e44a1c516935ab93e9029526abb40", + "packages/shared/src/types/issue.ts": "849b293fb2263ed41d9a0a74276534ad5c2ff7b8", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts index bf2d4339821..0a7dea84395 100644 --- a/ui/src/api/issues.ts +++ b/ui/src/api/issues.ts @@ -1,4 +1,4 @@ -import type { SetIssueTitle } from "@paperclipai/shared"; +import type { IssueInboxArchiveFilter, SetIssueTitle } from "@paperclipai/shared"; import { ISSUE_CHAT_BOOTSTRAP_MAX_IDS, ISSUE_SUMMARIES_MAX_IDS, type IssueChatBootstrap } from "@paperclipai/shared"; import type { RunForIssue } from "./activity"; import type { ActiveRunForIssue, LiveRunForIssue } from "./heartbeats"; @@ -207,6 +207,7 @@ export type IssueListFilters = { assigneeUserId?: string; touchedByUserId?: string; inboxArchivedByUserId?: string; + inboxArchive?: IssueInboxArchiveFilter; unreadForUserId?: string; /** Add the current board user's read state without filtering task membership. */ includeReadState?: boolean; @@ -250,6 +251,7 @@ function issueListSearchParams(filters?: IssueListFilters) { params.set("assigneeUserId", filters.assigneeUserId); if (filters?.touchedByUserId) params.set("touchedByUserId", filters.touchedByUserId); + if (filters?.inboxArchive) params.set("inboxArchive", filters.inboxArchive); if (filters?.inboxArchivedByUserId) params.set("inboxArchivedByUserId", filters.inboxArchivedByUserId); if (filters?.unreadForUserId) diff --git a/ui/src/components/IssueRow.test.tsx b/ui/src/components/IssueRow.test.tsx index 852022bda7d..0d03ba29ac7 100644 --- a/ui/src/components/IssueRow.test.tsx +++ b/ui/src/components/IssueRow.test.tsx @@ -189,6 +189,28 @@ describe("IssueRow", () => { act(() => root.unmount()); }); + it("restores a task independently of its row link", () => { + const root = createRoot(container); + const restore = vi.fn(); + act(() => root.render( + + + , + )); + + const button = container.querySelector('button[aria-label="Restore from archive"]')!; + expect(button.closest("a")).toBeNull(); + act(() => button.click()); + expect(restore).toHaveBeenCalledOnce(); + act(() => root.unmount()); + }); + it("starts a truncated title reveal on link focus and keeps actions independent", async () => { const bounds = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 16)); const createRange = document.createRange.bind(document); diff --git a/ui/src/components/IssueRow.tsx b/ui/src/components/IssueRow.tsx index bb0d1748755..407f3c84154 100644 --- a/ui/src/components/IssueRow.tsx +++ b/ui/src/components/IssueRow.tsx @@ -2,7 +2,7 @@ import { requiresExecutionReconciliation } from "@paperclipai/shared"; import { useState, type CSSProperties, type ReactNode } from "react"; import type { ExternalObjectSummary, Issue, IssueRecoveryAction } from "@paperclipai/shared"; import { Link } from "@/lib/router"; -import { Archive, Flag, CircleAlert } from "lucide-react"; +import { Archive, ArchiveRestore, Flag, CircleAlert } from "lucide-react"; import { createIssueDetailPath, rememberIssueDetailLocationState, @@ -81,6 +81,7 @@ export interface IssueRowProps { onMarkRead?: () => void; onArchive?: () => void; archiveDisabled?: boolean; + archiveAction?: IssueRowArchiveAction; className?: string; /** Pointer entered the row (used by list keyboard nav to track hover). */ onMouseEnter?: () => void; @@ -95,15 +96,27 @@ export interface IssueRowProps { showDivider?: boolean; } +export type IssueRowArchiveAction = { + archived: boolean; + disabled?: boolean; + onClick: () => void; +}; + export function InboxArchiveButton({ onArchive, disabled, compact = false, + archived = false, + iconOnly = false, }: { onArchive: () => void; disabled?: boolean; compact?: boolean; + archived?: boolean; + iconOnly?: boolean; }) { + const label = archived ? "Restore from archive" : "Archive"; + const Icon = archived ? ArchiveRestore : Archive; return ( ); } @@ -166,6 +180,7 @@ export function IssueRow({ onMarkRead, onArchive, archiveDisabled, + archiveAction, className, onMouseEnter, treeGuides = 0, @@ -239,6 +254,15 @@ export function IssueRow({ ) : null; + const personalArchiveControl = archiveAction ? ( + + ) : null; + if (presentation === "task") { const refreshed = appearance === "refreshed"; const statusLabel = getStatusIconLabel(issue.status, issue.externalConversationState, issue.blockerAttention, issue.displayStatus); @@ -445,6 +469,14 @@ export function IssueRow({ )} + {personalArchiveControl ? ( + + {personalArchiveControl} + + ) : null} ); @@ -595,6 +627,7 @@ export function IssueRow({ ) : null} ) : null} + {personalArchiveControl ? {personalArchiveControl} : null} {showUnreadDot ? ( // Inbox rows reserve a mobile gutter on both read and unread rows. The // full control stays inside overflow-clipping row containers while its diff --git a/ui/src/components/IssuesList.tsx b/ui/src/components/IssuesList.tsx index 4629dbfe073..1f2ee7e3945 100644 --- a/ui/src/components/IssuesList.tsx +++ b/ui/src/components/IssuesList.tsx @@ -1,3 +1,4 @@ +import { PERSONAL_ARCHIVE_QUERY_KEY } from "@/lib/inboxArchiveCache"; import { QueryErrorState } from "./QueryView"; import { ISSUE_SORT_FIELDS, sortIssues, type IssueSort, type IssueSortField } from "../lib/issue-sort"; import { useIssueRowDetails } from "../hooks/useIssueRowDetails"; @@ -73,7 +74,7 @@ import { EmptyState } from "./EmptyState"; import { Identity } from "./Identity"; import { IssueGroupHeader } from "./IssueGroupHeader"; import { IssueFiltersPopover } from "./IssueFiltersPopover"; -import { IssueRow, type IssueRowPresentation } from "./IssueRow"; +import { IssueRow, type IssueRowPresentation, type IssueRowArchiveAction } from "./IssueRow"; import { CollectionToolbar, type CollectionToolbarProps } from "./CollectionToolbar"; import { IssuesList as LegacyIssuesList } from "./LegacyIssuesList"; import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled"; @@ -454,6 +455,7 @@ type IssueListRequestFilters = NonNullable[1]> interface IssuesListProps { issues: Issue[]; + getArchiveAction?: (issue: Issue) => IssueRowArchiveAction | undefined; /** Preload the chat of the top visible rows. Only the top-level tasks page sets this. */ preloadTaskChats?: boolean; isLoading?: boolean; @@ -714,6 +716,7 @@ export function IssuesList(props: IssuesListProps) { function StreamlinedIssuesList({ issues, + getArchiveAction, preloadTaskChats = false, isLoading, error, @@ -940,6 +943,7 @@ function StreamlinedIssuesList({ queryKey: [ ...queryKeys.issues.search(selectedCompanyId!, normalizedIssueSearch, projectId), searchFilters ?? {}, + ...(searchFilters?.inboxArchive ? [PERSONAL_ARCHIVE_QUERY_KEY] : []), creationRequestFilters, enableAgentCreatedVisibilityFilter && viewState.viewMode === "list" ? "index" : "compact", ISSUE_SEARCH_RESULT_LIMIT, @@ -2299,6 +2303,7 @@ function StreamlinedIssuesList({ > void; /** Preload the chat of the top rows for this company. Only a page's main task list sets this. */ preloadCompanyId?: string | null; + getArchiveAction?: (issue: Issue) => IssueRowArchiveAction | undefined; }) { const localKey = useId(); const { columns, order: columnOrder, setColumns, setOrder: setColumnOrder } = useTaskListColumnPreferences(preferenceLocation, initialColumns); @@ -131,6 +132,7 @@ export function TaskList({ items, allItems = items, initialColumns = defaultTask 0 && children.length > 0} leadingControl={children.length ? ( diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsx index 9f99597a4da..cb3c51b3168 100644 --- a/ui/src/context/ToastContext.tsx +++ b/ui/src/context/ToastContext.tsx @@ -30,6 +30,7 @@ export type ToastActor = { export interface ToastInput { id?: string; + dedupe?: boolean; dedupeKey?: string; title: string; body?: string; @@ -135,11 +136,11 @@ export function ToastProvider({ children }: { children: ReactNode }) { const lastSeen = dedupeRef.current.get(key); return lastSeen !== undefined && now - lastSeen < DEDUPE_WINDOW_MS; }); - if (recentlyShown) { - return null; + if (input.dedupe !== false) { + if (recentlyShown) return null; + dedupeRef.current.set(dedupeKey, now); + dedupeRef.current.set(contentKey, now); } - dedupeRef.current.set(dedupeKey, now); - dedupeRef.current.set(contentKey, now); const id = input.id ?? generateToastId(); clearTimer(id); diff --git a/ui/src/hooks/useTaskArchiveAction.ts b/ui/src/hooks/useTaskArchiveAction.ts new file mode 100644 index 00000000000..4446aa2c6be --- /dev/null +++ b/ui/src/hooks/useTaskArchiveAction.ts @@ -0,0 +1,95 @@ +import { useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import type { Issue } from "@paperclipai/shared"; +import { describeError } from "@/api/errors"; +import { issuesApi } from "@/api/issues"; +import type { IssueRowArchiveAction } from "@/components/IssueRow"; +import { useOptionalToastActions } from "@/context/ToastContext"; +import { useAccountBoundMutation } from "@/hooks/useAccountBoundMutation"; +import { bindAccount } from "@/lib/account-scope"; +import { + beginLocalInboxArchive, + clearLocalInboxArchive, + confirmLocalInboxArchive, + invalidateTaskArchiveQueries, +} from "@/lib/inboxArchiveCache"; + +type ArchiveChange = { companyId: string; issueId: string; reference: string; archive: boolean; owner: string }; + +function changeKey({ companyId, issueId, owner }: ArchiveChange) { + return JSON.stringify([companyId, issueId, owner]); +} + +export function useTaskArchiveAction(companyId: string | null, userId: string | null) { + const client = useQueryClient(); + const toast = useOptionalToastActions(); + const inFlight = useRef(new Set()); + const [pending, setPending] = useState>(inFlight.current); + + const change = useAccountBoundMutation({ + mutationFn: ({ issueId, archive }: ArchiveChange) => archive + ? issuesApi.archiveFromInbox(issueId) + : issuesApi.unarchiveFromInbox(issueId), + onMutate: ({ companyId, issueId, archive }) => archive + ? { release: beginLocalInboxArchive(companyId, issueId), account: bindAccount(client) } + : undefined, + onSuccess: (_result, { companyId, issueId, archive }) => { + if (archive) confirmLocalInboxArchive(companyId, issueId); + else clearLocalInboxArchive(companyId, issueId); + }, + onError: (error, { archive }, context) => { + context?.release(); + toast?.pushToast({ + title: archive ? "Archive failed" : "Restore failed", + body: describeError(error).body, + tone: "error", + }); + }, + onFinished: (_input, context) => { + if (context && !context.account.isCurrentScope()) context.release(); + }, + onSettled: (_result, _error, { companyId }) => invalidateTaskArchiveQueries(client, companyId), + }); + + async function submit(input: ArchiveChange) { + const key = changeKey(input); + if (inFlight.current.has(key)) return; + const account = bindAccount(client); + inFlight.current.add(key); + setPending(new Set(inFlight.current)); + try { + await change.mutateAsync(input); + if (input.archive && account.isCurrentAccount()) { + toast?.pushToast({ + id: `archive:${input.companyId}:${input.issueId}`, + dedupe: false, + title: "Task archived", + body: input.reference, + tone: "success", + ttlMs: 8000, + action: { + label: "Undo", + onClick: () => { + if (account.isCurrentAccount()) void submit({ ...input, archive: false }); + }, + }, + }); + } + } catch { + return; + } finally { + inFlight.current.delete(key); + setPending(new Set(inFlight.current)); + } + } + + return (issue: Issue): IssueRowArchiveAction | undefined => { + if (!companyId || !userId || issue.companyId !== companyId || issue.isArchivedForMe === undefined) return; + const input = { companyId, issueId: issue.id, reference: issue.identifier ?? issue.id, archive: !issue.isArchivedForMe, owner: userId }; + return { + archived: issue.isArchivedForMe, + disabled: pending.has(changeKey(input)), + onClick: () => void submit(input), + }; + }; +} diff --git a/ui/src/lib/inboxArchiveCache.ts b/ui/src/lib/inboxArchiveCache.ts index b2842ddb888..221d8e2c1ce 100644 --- a/ui/src/lib/inboxArchiveCache.ts +++ b/ui/src/lib/inboxArchiveCache.ts @@ -3,6 +3,8 @@ 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; export const INBOX_ARCHIVE_CONFIRMATION_GRACE_MS = 5_000; @@ -245,6 +247,16 @@ export function invalidateInboxIssueQueries(queryClient: QueryClient, 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, diff --git a/ui/src/lib/task-views.test.ts b/ui/src/lib/task-views.test.ts index 3c27c86d796..4eaa8900861 100644 --- a/ui/src/lib/task-views.test.ts +++ b/ui/src/lib/task-views.test.ts @@ -18,15 +18,15 @@ describe("task views registry (PAP-670)", () => { expect(new Set(keys).size).toBe(keys.length); }); - it("routes My-work views to the inbox surface with a tab, and organization views to the task list with statuses", () => { + it("renders the archived collection and organization views in the task list", () => { const [myWork, organization] = TASK_VIEW_GROUPS; - expect(myWork.views.map((view) => view.inboxTab)).toEqual(["mine", "unread", "blocked", "recent", "all"]); - for (const view of myWork.views) { - expect(view.surface).toBe("inbox"); - expect(view.statuses).toBeUndefined(); - } + const inboxViews = myWork.views.filter(view => view.surface === "inbox"); + expect(inboxViews.map(view => view.inboxTab)).toEqual(["mine", "unread", "blocked", "recent", "all"]); + for (const view of inboxViews) expect(view.statuses).toBeUndefined(); + expect(myWork.views.find(view => view.key === "archived")).toMatchObject({ surface: "issues", statuses: [] }); + expect(taskViewPath("archived")).toBe("/issues?view=archived"); for (const view of organization.views) { expect(view.surface).toBe("issues"); expect(view.inboxTab).toBeUndefined(); diff --git a/ui/src/lib/task-views.ts b/ui/src/lib/task-views.ts index c0396b2be5d..798d49f1e5d 100644 --- a/ui/src/lib/task-views.ts +++ b/ui/src/lib/task-views.ts @@ -21,6 +21,7 @@ export const TASK_VIEW_KEYS = [ "blocked", "recent", "everything", + "archived", "needs_attention", "all", "active", @@ -58,6 +59,7 @@ export const TASK_VIEW_GROUPS: TaskViewGroup[] = [ { key: "blocked", label: "Blocked", surface: "inbox", inboxTab: "blocked", hint: "Blocked tasks, grouped by blocker" }, { key: "recent", label: "Recent", surface: "inbox", inboxTab: "recent", hint: "Everything you touched lately" }, { key: "everything", label: "Everything", surface: "inbox", inboxTab: "all", hint: "Tasks, approvals, failed runs and join requests" }, + { key: "archived", label: "Archived", surface: "issues", statuses: [], hint: "Tasks archived for you" }, ], }, { diff --git a/ui/src/pages/CoordinatorTasks.test.tsx b/ui/src/pages/CoordinatorTasks.test.tsx index b4e52278e82..540394feea7 100644 --- a/ui/src/pages/CoordinatorTasks.test.tsx +++ b/ui/src/pages/CoordinatorTasks.test.tsx @@ -10,14 +10,17 @@ import { Route, Routes, useLocation, useNavigate } from "react-router-dom"; import { CoordinatorTasks } from "./CoordinatorTasks"; import { Issues } from "./Issues"; import { queryKeys } from "@/lib/queryKeys"; +import { ToastProvider, useToastState } from "@/context/ToastContext"; import { IssueFilterPanel } from "@/components/IssueFilterPanel"; import type { ComponentProps } from "react"; +import type { Issue } from "@paperclipai/shared"; +import type { IssueRowArchiveAction } from "@/components/IssueRow"; import type { TaskListSort } from "@/lib/task-list"; import { taskListViews, taskListViewStorageKey, type TaskListView } from "@/lib/task-list-views"; -const mocks = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn(), attention: vi.fn(), breadcrumbs: vi.fn(), liveRuns: vi.fn(), localTrusted: false, realFilters: false, labels: [] as { id: string; name: string; color: string }[], identity: { userId: "person" as string | null, settled: true } })); +const mocks = vi.hoisted(() => ({ list: vi.fn(), archive: vi.fn(), restore: vi.fn(), get: vi.fn(), attention: vi.fn(), breadcrumbs: vi.fn(), liveRuns: vi.fn(), localTrusted: false, realFilters: false, labels: [] as { id: string; name: string; color: string }[], identity: { userId: "person" as string | null, settled: true } })); vi.mock("@/api/heartbeats", () => ({ heartbeatsApi: { liveRunsForCompany: mocks.liveRuns } })); -vi.mock("@/api/issues", () => ({ issuesApi: { list: mocks.list, listCompact: mocks.list, get: mocks.get, listLabels: async () => mocks.labels, update: vi.fn() } })); +vi.mock("@/api/issues", () => ({ issuesApi: { list: mocks.list, listCompact: mocks.list, get: mocks.get, archiveFromInbox: mocks.archive, unarchiveFromInbox: mocks.restore, listLabels: async () => mocks.labels, update: vi.fn() } })); vi.mock("@/api/attention", () => ({ attentionApi: { taskIndex: mocks.attention } })); vi.mock("@/api/agents", () => ({ agentsApi: { list: async () => [] } })); vi.mock("@/api/projects", () => ({ projectsApi: { list: async () => [] } })); @@ -45,8 +48,21 @@ vi.mock("@/components/TaskListToolbar", () => ({ TaskListToolbar: ({ filters, vi })); vi.mock("@/components/TaskList", async importOriginal => ({ ...await importOriginal(), - TaskList: ({ items, emptyState, onSortChange }: { onSortChange?: (sort: TaskListSort) => void; items: { issue: { id: string; title: string }; assignee?: string | null }[]; emptyState: React.ReactNode }) => -
{useLocation().search}{items.length ? items.map(item =>

{item.issue.title}

) : emptyState}
, + TaskList: ({ items, emptyState, onSortChange, getArchiveAction }: { + onSortChange?: (sort: TaskListSort) => void; + items: { issue: Issue; assignee?: string | null }[]; + emptyState: React.ReactNode; + getArchiveAction?: (issue: Issue) => IssueRowArchiveAction | undefined; + }) =>
+ + {useLocation().search} + {items.length ? items.map(item => { + const action = getArchiveAction?.(item.issue); + return

+ {item.issue.title}{action ? : null} +

; + }) : emptyState} +
, })); describe("Coordinator tasks using the proposed table", () => { @@ -69,6 +85,86 @@ describe("Coordinator tasks using the proposed table", () => { flushSync(() => root.render()); await vi.waitFor(() => expect(host.textContent).not.toContain("Loading tasks")); } + it("archives from All tasks, supports Undo, and restores from Archived", async () => { + let archived = false; + const task = createIssue({ id: "task", companyId: "company", parentId: null, title: "Send report" }); + mocks.list.mockImplementation(async (_company, filters) => filters.inboxArchive === "archived" && !archived + ? [] + : [{ ...task, isArchivedForMe: archived }]); + mocks.archive.mockImplementation(async () => { archived = true; }); + mocks.restore.mockImplementation(async () => { archived = false; }); + client.setQueryData(queryKeys.auth.session, { user: { id: "person" } }); + + function Controls() { + const navigate = useNavigate(); + const undo = useToastState().find(toast => toast.action?.label === "Undo"); + return <> + + {undo ? : null} + ; + } + flushSync(() => root.render( + + + , + )); + const button = (label: string) => [...host.querySelectorAll("button")].find(element => element.textContent === label); + const click = (label: string) => flushSync(() => button(label)!.click()); + + await vi.waitFor(() => expect(button("Archive")).toBeDefined()); + click("Archive"); + await vi.waitFor(() => { + expect(button("Undo")).toBeDefined(); + expect(button("Restore")).toBeDefined(); + expect(host.querySelector('[data-task-id="task"]')).not.toBeNull(); + }); + click("Undo"); + await vi.waitFor(() => expect(button("Archive")).toBeDefined()); + click("Archive"); + await vi.waitFor(() => expect(button("Restore")?.disabled).toBe(false)); + click("Open Archived"); + await vi.waitFor(() => { + expect(mocks.list).toHaveBeenCalledWith("company", expect.objectContaining({ inboxArchive: "archived" }), expect.anything()); + expect(button("Restore")).toBeDefined(); + }); + click("Restore"); + await vi.waitFor(() => expect(host.textContent).toContain("No archived tasks")); + expect(mocks.archive).toHaveBeenCalledTimes(2); + expect(mocks.restore).toHaveBeenCalledTimes(2); + }); + + it("keeps separate Undo actions for consecutive task archives", async () => { + const tasks = [ + createIssue({ id: "first-archive", identifier: "TASK-1", companyId: "company", parentId: null }), + createIssue({ id: "second-archive", identifier: "TASK-2", companyId: "company", parentId: null }), + ]; + const archived = new Set(); + mocks.list.mockImplementation(async () => tasks.map(task => ({ ...task, isArchivedForMe: archived.has(task.id) }))); + mocks.archive.mockImplementation(async (id: string) => { archived.add(id); }); + mocks.restore.mockImplementation(async (id: string) => { archived.delete(id); }); + client.setQueryData(queryKeys.auth.session, { user: { id: "person" } }); + + function UndoActions() { + return useToastState().filter(toast => toast.action?.label === "Undo").map(toast => + , + ); + } + flushSync(() => root.render( + + + , + )); + const archiveButton = (id: string) => host.querySelector(`[data-task-id="${id}"] button`); + await vi.waitFor(() => expect(archiveButton(tasks[0]!.id)?.textContent).toBe("Archive")); + flushSync(() => archiveButton(tasks[0]!.id)!.click()); + await vi.waitFor(() => expect(host.querySelectorAll("[data-undo-task]")).toHaveLength(1)); + flushSync(() => archiveButton(tasks[1]!.id)!.click()); + await vi.waitFor(() => expect(host.querySelectorAll("[data-undo-task]")).toHaveLength(2)); + flushSync(() => host.querySelector('[data-undo-task="TASK-2"]')!.click()); + await vi.waitFor(() => expect(mocks.restore).toHaveBeenCalledExactlyOnceWith(tasks[1]!.id)); + expect(archived.has(tasks[0]!.id)).toBe(true); + }); + it.each([ { url: "/issues", view: "all", ids: ["parent", "mine", "assigned", "unrelated"] }, { url: "/issues?view=inbox", view: "inbox", ids: ["parent", "mine", "assigned"] }, diff --git a/ui/src/pages/CoordinatorTasks.tsx b/ui/src/pages/CoordinatorTasks.tsx index 49c73964a0a..6a02c266f4f 100644 --- a/ui/src/pages/CoordinatorTasks.tsx +++ b/ui/src/pages/CoordinatorTasks.tsx @@ -1,3 +1,4 @@ +import { PERSONAL_ARCHIVE_QUERY_KEY } from "@/lib/inboxArchiveCache"; import { companyProjectsQuery } from "@/lib/company-projects-query"; import { readTaskListSortParams, taskListOrderToIssueSort, type TaskListSort } from "@/lib/task-list"; import { useDeferredValue, useEffect, useRef, useState, type ReactNode } from "react"; @@ -21,6 +22,7 @@ import { useBreadcrumbs } from "@/context/BreadcrumbContext"; import { useCompany } from "@/context/CompanyContext"; import { useDialogActions } from "@/context/DialogContext"; import { useTaskListCollection } from "@/hooks/useTaskListCollection"; +import { useTaskArchiveAction } from "@/hooks/useTaskArchiveAction"; import { useIssueRowDetails } from "@/hooks/useIssueRowDetails"; import { useCoordinatorWorkspaceEnabled } from "@/hooks/useCoordinatorWorkspaceEnabled"; import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling"; @@ -95,6 +97,10 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = const initialStatuses: string[] = params.has("status") ? params.getAll("status") : presetStatuses; const previousUrlFilters = useRef({ assignee: urlAssignee, statuses: urlStatuses, labels: urlLabels, view: urlView, routineTasksOnly }); const needsAttention = view === "blocked"; + const archivedView = urlView === "archived"; + const hideArchived = view === "inbox" || view === "unread"; + const inboxArchive = userId && !needsAttention ? (archivedView ? "archived" : "include") : undefined; + const getArchiveAction = useTaskArchiveAction(companyId, userId); const query = params.get("q") ?? ""; const deferredQuery = useDeferredValue(query.trim()); const useListSort = layout === "list" && !deferredQuery; @@ -116,19 +122,21 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = useEffect(() => { setBreadcrumbs([{ label: "Tasks" }]); }, [setBreadcrumbs]); const tasks = useInfiniteQuery({ - queryKey: [...queryKeys.issues.list(companyId!), "coordinator-table", "index", userId, deferredQuery, participantAgentId, workspaceIds, originKind, serverSortField, serverSortDir, includeBlockedBy, view === "unread"], + queryKey: [...queryKeys.issues.list(companyId!), "coordinator-table", "index", userId, deferredQuery, participantAgentId, workspaceIds, originKind, serverSortField, serverSortDir, includeBlockedBy, view === "unread", hideArchived, PERSONAL_ARCHIVE_QUERY_KEY, inboxArchive], queryFn: async ({ pageParam, signal }) => { const pages = await Promise.all((workspaceIds.length ? workspaceIds : [undefined]).map(workspaceId => issuesApi.listCompact(companyId!, { projection: "index", limit: pageSize, offset: pageParam, includeAgentCreatedTasks: true, includeRoutineExecutions: true, sortField: serverSortField, sortDir: serverSortDir, includeBlockedBy: includeBlockedBy || undefined, q: deferredQuery || undefined, participantAgentId, workspaceId, originKind, unreadForUserId: view === "unread" ? "me" : undefined, + inboxArchivedByUserId: hideArchived && userId ? "me" : undefined, + inboxArchive, }, { signal }))); return { items: pages.flat(), hasNextPage: pages.some(page => page.length === pageSize) }; }, initialPageParam: 0, getNextPageParam: (last, _pages, offset) => last.hasNextPage ? offset + pageSize : undefined, - enabled: !!companyId && !needsAttention, + enabled: !!companyId && !needsAttention && (!archivedView || !!userId), }); const attention = useQuery({ queryKey: coordinatorAttentionTasksQueryKey(companyId!, userId), queryFn: () => attentionApi.taskIndex(companyId!), enabled: !!companyId && !!userId && needsAttention }); @@ -235,7 +243,7 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = next.delete("status"); for (const status of patch.statuses) next.append("status", status); const preset = normalizeTaskViewKey(next.get("view")); - if (preset && taskView(preset).surface === "issues") next.set("view", "all"); + if (preset && !archivedView && taskView(preset).surface === "issues") next.set("view", "all"); } navigate({ search: next.toString(), hash: location.hash }, { replace: true }); }; @@ -243,7 +251,7 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = collection.updateFilters(defaultIssueFilterState); const next = new URLSearchParams(params); for (const key of ["q", "assignee", "status", "label", "originKind"]) next.delete(key); - if (next.get("view") !== "needs_attention") next.set("view", "all"); + if (!needsAttention && !archivedView) next.set("view", "all"); navigate({ search: next.toString(), hash: location.hash }, { replace: true }); }; const cancelTask = useTaskCancellation(); @@ -267,8 +275,8 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = const enrichItem = (item: TaskListItem): TaskListItem => ({ ...item, issue: enrichIssueRow(item.issue) }); const narrowed = query || collection.activeFilterCount || view === "inbox" || view === "unread"; const empty = openNewIssue()} />; const issueLinkState = createIssueDetailLocationState("Tasks", `${location.pathname}${location.search}`, "issues"); const retry = () => { @@ -281,6 +289,7 @@ export function CoordinatorTasks({ viewControl }: { viewControl?: ReactNode } = }; if (!companyId) return ; + if (archivedView && identitySettled && !userId) return ; return