Files
PaperClipAI/ui/src/pages/DecisionQueuePage.tsx
T
cf1def0ca6 feat(inbox): rebuild compact cards and share task review controls (#20961)
## Thinking Path

> - Paperclip helps people manage AI agents and their work.
> - The inbox collects decisions, requests, and updates for the people
in a company.
> - People need a clear personal queue and a consistent way to answer
each request.
> - Repeated headings, inconsistent card actions, and separate review
flows make that work harder.
> - This pull request connects the inbox UI to the routing foundation in
#20959.
> - Compact cards use shared task controls and open supporting work in a
side panel.
> - People can answer, claim, transfer, archive, and inspect outcomes
from one place.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The inbox cards, personal views, shared task controls, and decision
history.

**Subsystem affected**

UI. This PR targets master and uses the routing foundation merged in
#20959.

**Current behavior**

The inbox repeats headings and counts. Cards have different layouts and
action placement. The requester can repeat the signed-in person's name.
Review and question controls differ between the inbox and task thread.

**Proposed behavior**

Open Assigned to you by default. Show one count line above the cards.
Use a compact card layout with consistent actions and supporting
details. Show the requester's avatar and name only when they differ from
the signed-in person. Share question controls, including a radio option
for Other that reveals a text field when selected.

**Reason and benefit**

People can scan their queue and complete requests without losing the
surrounding task or creating separate drafts for the same review.

**Breaking changes**

The default inbox view becomes personal. The all-assignee and shared
views remain available. Card close menus distinguish personal archive
and snooze from shared withdrawal.

**Additional context**

Refs #20959, #19363, and #19520. Refs #20268 for related
actionable-request work. This stack adds personal routing and shared
controls. ROADMAP.md includes Multiple Human Users and Agent Reviews and
Approvals.

## What Changed

- Add personal, unassigned, company, all-assignee, and archived inbox
views. Add claim, transfer, personal close actions, receipts, and
history controls.
- Use compact decision cards with a single count line, one-pixel
borders, and equal space above, below, and to the right of each primary
action.
- Open artifacts and synchronized confirmation/approval controls in a
shared side panel. Share their revision drafts and action state with the
task thread. Other requests keep one editable form on the inbox card
while reviewing an artifact.
- Make Other match the question options and reveal its field only when
selected. Apply this to inbox and task question cards.
- Hide self-requester labels, space agent avatars, and use the standard
canceled status icon for withdrawn requests.
- Use connector logos in connector cards. Keep the connector promotion
background and sidebar border continuous.
- Add company and project decision-owner controls and document the
updated inbox behavior.

## Verification

- The complete [GitHub Actions CI
matrix](https://github.com/paperclipai/paperclip/actions/runs/43141559641)
passes on `8d81a75e49b518fff6b6ff4c23dd67979b0b97ee` (Linux/Node 24:
typecheck, build, general and serialized tests, Runner support, browser
shards, and aggregate gates). Greptile is 5/5 on that exact head with
zero open findings, and the security scan passes.
- Local UI typechecking passes. Eight focused suites pass 382 tests: 236
inbox/review/question/connector tests plus all 146 composer tests.
Regressions passed red to green for attachment links, prompt rendering,
single-form artifact review, connector scope copy, accessible headings,
and the composer test harness's missing theme provider. The final commit
changes only that test harness; production code is unchanged from
`59d015833f`.
- Browser acceptance on the production implementation confirms preserved
selected answers with one editable question form, accessible Markdown
prompts, inert image references, accurate connector scope copy, native
PDF downloads, image sidebar previews, and Open file requesting the
attachment endpoint while preserving the inbox URL. Request reads and
file responses were intercepted; no question answers were written. The
preview is healthy on the final head.
- Visual and interaction checks cover Other radio behavior in both
themes and on mobile, the loaded Google Calendar logo, and 20px above,
below, and to the right of the primary action across all 23 visible
cards. The affected desktop/mobile navigation and sidebar specs pass
locally and in the final CI browser matrix.
- Real-editor browser checks confirm Ctrl/Cmd+Enter cannot bypass
another person's confirmation. Cancel preserves the draft and unlocks
silently; Continue submits once. Approval write failures remain visible.
- `pnpm verify` returns exit 2 because DESIGN.md requires broader
coverage; the final full CI matrix supplies every requested gate. Maps
and Storybook catalog structural checks pass. The routing foundation
#20959 merged after passing 249 database tests, server typechecking,
full CI, Greptile 5/5, and security scanning. Its backend and SDK
registry are preserved.
- Demo data is retained for testing; database suites and browser specs
use separate disposable databases.

## Risks

- The inbox uses the routing contracts merged in #20959. Personal
filters and history affect shared task entry points; the affected
controls are included in local regression coverage and full CI.
- Personal defaults and close-menu wording change inbox behavior.
Existing resolver permissions still control shared actions.
- Shared revision state and live invalidation affect two surfaces.
Focused tests cover draft synchronization, action locks, and incoming
updates.
- Visual changes use the existing design tokens and component
primitives.

## Model Used

OpenAI GPT-6 through Codex. Used repository tools, code execution, and
browser checks. This session does not expose a more specific runtime
model ID or its context-window size.

## 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 described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
Paperclip ticket id
- [x] I have run focused 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 <scott@scottsmbpm5max.lan>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-11 21:05:00 -08:00

533 lines
20 KiB
TypeScript

import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Loader2, Settings2, X } from "lucide-react";
import type { Agent, AttentionItem } from "@paperclipai/shared";
import { useParams } from "@/lib/router";
import { attentionApi } from "../api/attention";
import { agentsApi } from "../api/agents";
import { authApi } from "../api/auth";
import { decisionQueuesApi } from "../api/decisionQueues";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useToastActions } from "../context/ToastContext";
import { useInboxDismissals } from "../hooks/useInboxBadge";
import { queryKeys } from "../lib/queryKeys";
import { attentionObligationEvidence, foldAttentionObligations } from "../lib/attention-obligations";
import {
ATTENTION_AGING_DAYS,
attentionIsAging,
buildAttentionFilterOptions,
buildDeskShelves,
defaultAttentionFilterState,
filterAttentionItems,
groupAttentionItems,
loadAttentionFilters,
loadAttentionGroupBy,
loadAttentionSortOrder,
loadCollapsedAttentionGroupKeys,
resolveAttentionDateRange,
saveAttentionFilters,
saveAttentionGroupBy,
saveAttentionSortOrder,
saveCollapsedAttentionGroupKeys,
sortAttentionItems,
type AttentionDateRangeId,
type AttentionFilterState,
type AttentionGroup,
type AttentionGroupBy,
type AttentionSortOrder,
} from "../lib/attention";
import { cn } from "../lib/utils";
import { PageSkeleton } from "../components/PageSkeleton";
import { QueryErrorState, useQueryView } from "../components/QueryView";
import { describeError } from "../api/errors";
import { AttentionQueueRow } from "../components/AttentionQueueRow";
import { DecisionsToolbar } from "../components/DecisionsToolbar";
import { Curtain, AgingItemRow } from "../components/DecisionShelf";
import { DecisionQueueRail } from "../components/DecisionQueueRail";
import { DecisionDateChips, type AttentionCustomRange } from "../components/DecisionDateChips";
import { IssueGroupHeader } from "../components/IssueGroupHeader";
import { Button } from "../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../components/ui/popover";
/**
* Queue page. A single queue's pending
* decisions with per-item resolution, exclusion (with an optional reason), and
* the queue's seed-rules card with an enable/disable toggle.
*
* The queue exposes the same toolbar the desk does — filter,
* group-by, sort, the arrival timeline groupings, the date-range chips, and the
* aging shelf — sharing the desk's `DecisionsToolbar`, grouping helpers, and
* shelf components so a decision looks, groups, and resolves the same wherever it
* is surfaced.
*/
export function DecisionQueuePage() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToastActions();
const queryClient = useQueryClient();
const params = useParams<{ key: string }>();
const queueKey = params.key ?? "";
const [expandedId, setExpandedId] = useState<string | null>(null);
const { dismiss, snooze } = useInboxDismissals(selectedCompanyId);
const [searchQuery, setSearchQuery] = useState("");
// Toolbar preferences (persisted to localStorage, shared with the desk).
const [groupBy, setGroupBy] = useState<AttentionGroupBy>(() => loadAttentionGroupBy());
const [sortOrder, setSortOrder] = useState<AttentionSortOrder>(() => loadAttentionSortOrder());
const [filters, setFilters] = useState<AttentionFilterState>(() => defaultAttentionFilterState);
const [collapsedGroupKeys, setCollapsedGroupKeys] = useState<Set<string>>(() => new Set());
const [agingOpen, setAgingOpen] = useState(false);
// Date-range chips (§4.2) — resolve to server-side activity bounds.
const [dateRange, setDateRange] = useState<AttentionDateRangeId>("all");
const [customRange, setCustomRange] = useState<AttentionCustomRange>({ from: null, to: null });
const activityBounds = useMemo(
() => resolveAttentionDateRange(dateRange, Date.now(), customRange),
[dateRange, customRange],
);
const { data: queues } = useQuery({
queryKey: queryKeys.decisionQueues.list(selectedCompanyId!),
queryFn: () => decisionQueuesApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const queue = useMemo(() => queues?.find((q) => q.key === queueKey) ?? null, [queues, queueKey]);
const feedQuery = useQuery({
queryKey: [
...queryKeys.attention(selectedCompanyId!),
"queue",
queueKey,
activityBounds.activitySince ?? null,
activityBounds.activityUntil ?? null,
],
queryFn: () => attentionApi.list(selectedCompanyId!, { queue: queueKey, all: true, ...activityBounds }),
enabled: !!selectedCompanyId && !!queueKey,
refetchOnWindowFocus: true,
});
const { data: feed, isLoading } = feedQuery;
const feedView = useQueryView(feedQuery);
const { data: agents } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
const agentMap = useMemo(() => {
const map = new Map<string, Agent>();
for (const agent of agents ?? []) map.set(agent.id, agent);
return map;
}, [agents]);
useEffect(() => {
setBreadcrumbs([{ label: "Decisions", href: "/decisions" }, { label: queue?.title ?? queueKey }]);
}, [setBreadcrumbs, queue?.title, queueKey]);
// Re-hydrate per-company preferences when the company changes.
useEffect(() => {
setFilters(loadAttentionFilters(selectedCompanyId));
setCollapsedGroupKeys(loadCollapsedAttentionGroupKeys(selectedCompanyId));
}, [selectedCompanyId]);
// The server's clock at feed time — used for the arrival/decide-by shelves and
// the aging idle labels so they match the desk exactly.
const now = useMemo(
() => (feed?.generatedAt ? new Date(feed.generatedAt).getTime() : Date.now()),
[feed?.generatedAt],
);
// One card for each obligation (PAP-749 Rule 11): evidence folds into its lead.
const obligations = useMemo(() => foldAttentionObligations(feed?.items ?? []), [feed]);
const activeItems = useMemo(
() => obligations.cards.filter((item) => !(item.dismissal?.isActive ?? false)),
[obligations],
);
// Aging shelf (§4.4): items the server flags as idle past retention leave the
// live list for their own curtain, mirroring the desk.
const agingItems = useMemo(() => activeItems.filter(attentionIsAging), [activeItems]);
const listItems = useMemo(() => activeItems.filter((item) => !attentionIsAging(item)), [activeItems]);
const filterOptions = useMemo(() => buildAttentionFilterOptions(listItems), [listItems]);
// Filter → sort → group, matching the desk. In the default (ungrouped) view the
// list groups by arrival ("New today" / "Earlier", plus a "Decide now" shelf
// when something carries an explicit due decide-by); any explicit group-by keeps
// the Inbox-style activity grouping.
const groups = useMemo<AttentionGroup[]>(() => {
const filtered = filterAttentionItems(listItems, filters, searchQuery);
if (groupBy === "none") {
return buildDeskShelves(filtered, now);
}
const sorted = sortAttentionItems(filtered, sortOrder);
return groupAttentionItems(sorted, groupBy);
}, [listItems, filters, searchQuery, sortOrder, groupBy, now]);
const visibleCount = useMemo(() => groups.reduce((sum, group) => sum + group.items.length, 0), [groups]);
const updateGroupBy = (next: AttentionGroupBy) => {
setGroupBy(next);
saveAttentionGroupBy(next);
};
const updateSortOrder = (next: AttentionSortOrder) => {
setSortOrder(next);
saveAttentionSortOrder(next);
};
const updateFilters = (next: AttentionFilterState) => {
setFilters(next);
saveAttentionFilters(selectedCompanyId, next);
};
const toggleGroupCollapse = (key: string) => {
setCollapsedGroupKeys((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
saveCollapsedAttentionGroupKeys(selectedCompanyId, next);
return next;
});
};
const handleToggleExpand = useCallback((item: AttentionItem) => {
setExpandedId((prev) => (prev === item.id ? null : item.id));
}, []);
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: queryKeys.attention(selectedCompanyId!) });
queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(selectedCompanyId!) });
};
const toggleSeedRules = useMutation({
mutationFn: (enabled: boolean) =>
decisionQueuesApi.update(selectedCompanyId!, queueKey, { seedRulesEnabled: enabled }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(selectedCompanyId!) }),
onError: (err) =>
pushToast({
title: "Could not update seeding",
body: describeError(err).body,
tone: "error",
}),
});
if (!selectedCompanyId) {
return <p className="text-sm text-muted-foreground">Select an organization first.</p>;
}
// Keep a loaded queue on screen through a failed refetch; only a real
// failure, or an outage before the first load, replaces the page.
if (isLoading || feedView.kind === "reconnecting") {
return <PageSkeleton variant="approvals" />;
}
if (feedView.kind === "error") {
return (
<QueryErrorState
size="page"
error={feedView.error}
action="load this queue"
onRetry={feedView.retry}
retrying={feedView.isFetching}
/>
);
}
const isEmpty = activeItems.length === 0;
return (
<div className="max-w-3xl space-y-4">
<div className="space-y-4">
<div className="min-w-0">
<h1 className="text-xl font-bold">{queue?.title ?? queueKey}</h1>
{queue?.description && <p className="mt-0.5 text-sm text-muted-foreground">{queue.description}</p>}
</div>
<DecisionsToolbar
query={searchQuery}
onQueryChange={setSearchQuery}
visibleCount={visibleCount}
filterOptions={filterOptions}
filters={filters}
onFiltersChange={updateFilters}
groupBy={groupBy}
onGroupByChange={updateGroupBy}
sortOrder={sortOrder}
onSortOrderChange={updateSortOrder}
/>
</div>
<div className="space-y-2">
<DecisionQueueRail companyId={selectedCompanyId} activeQueueKey={queueKey} />
<DecisionDateChips
value={dateRange}
custom={customRange}
onChange={(value, custom) => {
setDateRange(value);
setCustomRange(custom);
}}
/>
</div>
{queue && queue.seedRules.length > 0 && (
<SeedRulesCard
enabled={queue.seedRulesEnabled}
rules={queue.seedRules.map((rule) => rule.description)}
pending={toggleSeedRules.isPending}
onToggle={() => toggleSeedRules.mutate(!queue.seedRulesEnabled)}
/>
)}
{isEmpty ? (
<div className="rounded-xl border border-dashed border-border py-14 text-center">
<p className="text-sm font-medium text-foreground">This queue is empty.</p>
<p className="mt-1 text-xs text-muted-foreground">
Decisions land here when they match the queue's rules or an agent adds them.
</p>
</div>
) : (
<div className="space-y-4">
{visibleCount === 0 ? (
<div className="rounded-xl border border-dashed border-border py-10 text-center">
<p className="text-sm font-medium text-foreground">No decisions match your search or filters.</p>
<p className="mt-1 text-xs text-muted-foreground">Adjust or clear your search and filters to see the rest.</p>
</div>
) : (
groups.map((group) => {
const groupLabel = group.label;
const collapsed = groupLabel !== null && collapsedGroupKeys.has(group.key);
return (
<section key={group.key} className="space-y-2">
{groupLabel !== null && (
<IssueGroupHeader
label={groupLabel}
collapsible
collapsed={collapsed}
onToggle={() => toggleGroupCollapse(group.key)}
trailing={
<span className="text-xs tabular-nums text-muted-foreground">{group.items.length}</span>
}
/>
)}
{!collapsed && (
<div className="space-y-4">
{group.items.map((item) => (
<QueueItemRow
key={item.id}
item={item}
companyId={selectedCompanyId}
queueKey={queueKey}
agentMap={agentMap}
agents={agents}
currentUserId={currentUserId}
expanded={expandedId === item.id}
onToggleExpand={handleToggleExpand}
onDismiss={(next) => dismiss(next.dismissalKey, next.changeFingerprint)}
onSnooze={(next, until) => snooze(next.dismissalKey, until, next.changeFingerprint)}
onExcluded={invalidate}
evidence={attentionObligationEvidence(obligations, item)}
/>
))}
</div>
)}
</section>
);
})
)}
{agingItems.length > 0 && (
<Curtain
label="Aging"
count={agingItems.length}
open={agingOpen}
onToggle={() => setAgingOpen((prev) => !prev)}
>
<p className="text-xs text-muted-foreground">
Idle past {ATTENTION_AGING_DAYS} days — kept off the queue. Keep any you still want surfaced.
</p>
{agingItems.map((item) => (
<AgingItemRow
key={item.id}
item={item}
companyId={selectedCompanyId}
now={now}
agentMap={agentMap}
agents={agents}
currentUserId={currentUserId}
expanded={expandedId === item.id}
onToggleExpand={handleToggleExpand}
onDismiss={(next) => dismiss(next.dismissalKey, next.changeFingerprint)}
onSnooze={(next, until) => snooze(next.dismissalKey, until, next.changeFingerprint)}
evidence={attentionObligationEvidence(obligations, item)}
/>
))}
</Curtain>
)}
</div>
)}
</div>
);
}
/**
* Auto-seed card: explains in place what seeding does — the queue's seed rules
* (from `DECISION_QUEUE_SEEDS`) that pull matching decisions in automatically —
* and what the toggle changes. Disabling stops only the automatic adds; anything
* already here stays, and manual adds keep working.
*/
function SeedRulesCard({
enabled,
rules,
pending,
onToggle,
}: {
enabled: boolean;
rules: string[];
pending: boolean;
onToggle: () => void;
}) {
return (
<div className="rounded-xl border border-border bg-muted/20 p-3">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-2">
<Settings2 className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 space-y-1">
<p className="text-sm font-medium text-foreground">Auto-seeding is {enabled ? "on" : "off"}</p>
<p className="text-xs text-muted-foreground">
{enabled
? "This queue fills itself automatically. Decisions are added the moment they match any of its rules:"
: "Automatic adds are paused. These rules would add decisions to the queue when on:"}
</p>
<ul className="mt-0.5 space-y-0.5">
{rules.map((rule) => (
<li key={rule} className="flex items-start gap-1.5 text-xs text-muted-foreground">
<Check className="mt-0.5 h-3 w-3 shrink-0" />
{rule}
</li>
))}
</ul>
<p className="text-(length:--text-nano) text-muted-foreground">
{enabled
? "Turning it off stops new automatic adds only — decisions already here stay, and you can still add or remove decisions by hand."
: "Adding or removing decisions by hand still works while automatic seeding is off."}
</p>
</div>
</div>
<Button type="button" variant="outline" size="xs" className="h-7 shrink-0" disabled={pending} onClick={onToggle}>
{pending && <Loader2 className="h-3 w-3 animate-spin" />}
{enabled ? "Disable" : "Enable"}
</Button>
</div>
</div>
);
}
function QueueItemRow({
item,
companyId,
queueKey,
agentMap,
agents,
currentUserId,
expanded,
onToggleExpand,
onDismiss,
onSnooze,
onExcluded,
evidence,
}: {
item: AttentionItem;
companyId: string;
queueKey: string;
agentMap: Map<string, Agent>;
agents: Agent[] | undefined;
currentUserId: string | null;
expanded: boolean;
onToggleExpand: (item: AttentionItem) => void;
onDismiss: (item: AttentionItem) => void;
onSnooze: (item: AttentionItem, snoozedUntil: string) => void;
onExcluded: () => void;
evidence: readonly AttentionItem[];
}) {
const { pushToast } = useToastActions();
const [open, setOpen] = useState(false);
const [reason, setReason] = useState("");
const exclude = useMutation({
mutationFn: async () => {
await decisionQueuesApi.removeItem(
companyId,
queueKey,
item.sourceKind,
item.subject.id,
reason.trim() || undefined,
);
},
onSuccess: () => {
setOpen(false);
setReason("");
pushToast({ title: "Removed from queue", body: item.subject.title ?? undefined, tone: "info" });
onExcluded();
},
onError: (err) =>
pushToast({
title: "Could not exclude",
body: describeError(err).body,
tone: "error",
}),
});
return (
<div className="space-y-1.5">
<div className="flex items-center justify-end px-1">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button type="button" variant="ghost" size="xs" className="h-7 gap-1 text-muted-foreground">
<X className="h-3.5 w-3.5" />
Exclude
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-64 space-y-2 p-3">
<p className="text-xs font-medium text-foreground">Remove from this queue</p>
<textarea
value={reason}
onChange={(event) => setReason(event.target.value)}
placeholder="Reason (optional)…"
className="min-h-16 w-full rounded-sm border border-border bg-background px-2 py-1 text-xs"
/>
<div className="flex justify-end gap-1">
<Button type="button" variant="ghost" size="xs" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
type="button"
size="xs"
className={cn(exclude.isPending && "opacity-80")}
disabled={exclude.isPending}
onClick={() => exclude.mutate()}
>
{exclude.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
Exclude
</Button>
</div>
</PopoverContent>
</Popover>
</div>
<AttentionQueueRow
item={item}
companyId={companyId}
expanded={expanded}
onToggleExpand={onToggleExpand}
onDismiss={onDismiss}
onSnooze={onSnooze}
agentMap={agentMap}
agents={agents}
showTriage
currentUserId={currentUserId}
evidence={evidence}
/>
</div>
);
}