Files
PaperClipAI/ui/src/components/DecisionTriageStrip.tsx
T
DottaandPaperclip 8e7f1c03eb feat(decisions): improve desk triage and queue parity (#10785)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The decisions desk and queue help operators find work that needs a
human decision.
> - The current views use different grouping, sorting, and labels.
> - Repeated confirmation requests can also leave stale pending actions
in the queue.
> - Blocked-work attention can point at an intermediate issue instead of
the terminal blocker.
> - This pull request aligns the server contract and both user
interfaces.
> - The benefit is a smaller, clearer queue that ranks the decisions
with the largest impact.

## Linked Issues or Issue Description

Related PR: #10774

**What existing behavior does this improve?**

The decisions desk and queue currently use different triage rules. They
can show stale repeated confirmations and can rank blocked work by an
intermediate issue.

**Subsystem affected**

This change affects attention aggregation, issue thread interactions,
shared attention contracts, and the decisions user interface.

**Current behavior**

The desk uses a can-wait group that has no clear arrival meaning. The
queue has fewer controls than the desk. Repeated pending confirmations
remain actionable. Blocked-work rows do not always identify the terminal
actionable blocker.

**Proposed behavior**

Group desk items by arrival date, and reserve Decide now for explicit
due dates. Use one toolbar and shelf model on both pages. Supersede
older repeated pending confirmations. Aggregate blocked work under the
terminal actionable blocker and rank it by impact.

**Reason and benefit**

Operators get one consistent triage model. The badge reflects new and
overdue work. High-impact blockers move to the top. Duplicate
confirmation work no longer consumes attention.

**Breaking changes**

The attention summary field `decideNowCount` changes to
`deskBadgeCount`. Consumers must use the new field. Older repeated
confirmation interactions can now finish with the
`superseded_by_newer_request` outcome.

## What Changed

- Supersede older pending confirmation requests for the same issue and
record the mutation in activity history.
- Resolve blocked-work attention to actionable terminal blockers,
suppress live blocker trees, and rank rows by blocked-work impact.
- Group the decisions desk into New today and Earlier, and count new
plus overdue work in the desk badge.
- Share the decision toolbar and shelf components across the desk and
queue.
- Add queue grouping, sorting, filtering, aging, visible training
controls, and clearer recommendation copy.
- Add server, shared-contract, and user-interface tests for the new
behavior.

## Verification

- `pnpm check:token-gates`
- `pnpm -r typecheck`
- `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY pnpm test:run` (all
server, UI, CLI, shared, and catalog tests passed; one fixed five-second
DB timeout flaked under full-suite load)
- `NODE_ENV=test pnpm --filter @paperclipai/db exec vitest run
src/status-card-migrations.test.ts` (passed in isolation)
- `pnpm build`

## Risks

- The attention summary field rename requires synchronized consumers.
- Terminal-blocker traversal uses cycle and depth guards. A malformed
dependency graph can stop at the last safe node.
- The new arrival grouping changes which items contribute to the
decisions badge.
- Superseding repeated confirmations changes the terminal state of older
pending interactions.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex with GPT-5. The runtime did not expose a dated model
snapshot or context-window size. The model used reasoning, repository
tools, code execution, and test execution.

## 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: Paperclip <noreply@paperclip.ing>
2026-08-03 21:31:45 -05:00

465 lines
17 KiB
TypeScript

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlarmClock, CalendarClock, ChevronDown, Loader2, Plus, UserPlus, X } from "lucide-react";
import { buildAgentMentionHref, type Agent, type AttentionItem, type AttentionSourceKind } from "@paperclipai/shared";
import { decisionQueuesApi } from "../api/decisionQueues";
import { issuesApi } from "../api/issues";
import { useToastActions } from "../context/ToastContext";
import { queryKeys } from "../lib/queryKeys";
import {
attentionTaskRef,
DECIDE_BY_OPTIONS,
decideByLabel,
type DecideByPreset,
} from "../lib/attention";
import { cn } from "../lib/utils";
import { Button } from "./ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "./ui/dropdown-menu";
const HOUR_MS = 60 * 60 * 1000;
const DAY_MS = 24 * HOUR_MS;
/** Snooze presets shared with the row menu, resolved at click time. */
const SNOOZE_PRESETS: ReadonlyArray<{ label: string; resolve: () => string }> = [
{ label: "1 hour", resolve: () => new Date(Date.now() + HOUR_MS).toISOString() },
{ label: "4 hours", resolve: () => new Date(Date.now() + 4 * HOUR_MS).toISOString() },
{ label: "Tomorrow", resolve: () => {
const d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(9, 0, 0, 0);
return d.toISOString();
} },
{ label: "Next week", resolve: () => new Date(Date.now() + 7 * DAY_MS).toISOString() },
];
/** Slugify a queue title into a URL-safe kebab key the API will accept. */
function toQueueKey(title: string): string {
return title
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 80);
}
/** Compact countdown/overdue label for an expiry timestamp. */
function expiryLabel(expiresAt: string): { text: string; overdue: boolean } {
const diff = new Date(expiresAt).getTime() - Date.now();
if (!Number.isFinite(diff)) return { text: "", overdue: false };
if (diff <= 0) return { text: "Expired", overdue: true };
const mins = Math.round(diff / 60000);
if (mins < 60) return { text: `Expires in ${mins}m`, overdue: false };
const hrs = Math.round(mins / 60);
if (hrs < 24) return { text: `Expires in ${hrs}h`, overdue: false };
const days = Math.round(hrs / 24);
return { text: `Expires in ${days}d`, overdue: false };
}
interface DecisionTriageStripProps {
item: AttentionItem;
companyId: string;
/** Company agents, for the route-to-agent picker (optional). */
agents?: Agent[];
}
/**
* Per-card triage strip (PAP-16032 §4.5 / wireframe screen 3). Exposes the
* write path the "agents alongside" also use: decide-by urgency (drives the
* desk's Decide-now / Can-wait split), queue membership, snooze, and
* route-to-agent. Every write is attributed and rendered as a setting, never a
* silent mutation. Queue/decide-by/snooze go through the P1 triage APIs; the
* expiry chip surfaces the underlying decision's TTL read-only.
*/
export function DecisionTriageStrip({ item, companyId, agents }: DecisionTriageStripProps) {
const queryClient = useQueryClient();
const { pushToast } = useToastActions();
const sourceKind = item.sourceKind;
const sourceId = item.subject.id;
const taskRef = attentionTaskRef(item);
const relatedIssueId = item.relatedIssue?.id
?? (typeof item.subject.metadata?.issueId === "string" ? item.subject.metadata.issueId : null)
?? (item.subject.kind === "issue" ? item.subject.id : null);
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) });
queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(companyId) });
queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.triage(companyId, sourceKind, sourceId) });
};
const onError = (verb: string) => (error: unknown) =>
pushToast({
title: `Could not ${verb}`,
body: error instanceof Error ? error.message : "Please try again.",
tone: "error",
});
const setDecideBy = useMutation({
mutationFn: (decideBy: string | null) =>
decisionQueuesApi.updateTriage(companyId, sourceKind, sourceId, { decideBy }),
onSuccess: invalidate,
onError: onError("set when to decide"),
});
const setSnooze = useMutation({
mutationFn: (snoozedUntil: string | null) =>
decisionQueuesApi.updateTriage(companyId, sourceKind, sourceId, { snoozedUntil }),
onSuccess: invalidate,
onError: onError("snooze"),
});
const addToQueue = useMutation({
mutationFn: (key: string) => decisionQueuesApi.addItem(companyId, key, sourceKind, sourceId),
onSuccess: invalidate,
onError: onError("add to queue"),
});
const removeFromQueue = useMutation({
mutationFn: (key: string) => decisionQueuesApi.removeItem(companyId, key, sourceKind, sourceId),
onSuccess: invalidate,
onError: onError("remove from queue"),
});
const routeToAgent = useMutation({
mutationFn: (agent: Agent) => {
if (!relatedIssueId) throw new Error("This decision has no linked task to route from.");
const mention = `[@${agent.name}](${buildAgentMentionHref(agent.id)})`;
const body =
`${mention} — could you look at this decision${taskRef ? ` on ${taskRef.identifier}` : ""}, `
+ `prepare a recommendation, and re-surface it on the decisions desk? (routed from the desk)`;
return issuesApi.addComment(relatedIssueId, body);
},
onSuccess: (_result, agent) => {
invalidate();
pushToast({ title: `Asked ${agent.name} for a recommendation`, tone: "success" });
},
onError: onError("ask that agent for a recommendation"),
});
const pending = setDecideBy.isPending || setSnooze.isPending || addToQueue.isPending || removeFromQueue.isPending;
const decideBy = item.decideBy;
const isDatePreset = decideBy != null && /^\d{4}-\d{2}-\d{2}$/.test(decideBy);
return (
<div
className="flex flex-col gap-2 rounded-lg border border-border bg-muted/30 p-3"
data-decision-triage-strip
// Contained inside the expandable panel; stop the card's expand toggle
// from firing when the operator interacts with a control.
onClick={(event) => event.stopPropagation()}
>
{/* Expiry — read-only countdown so a dying confirmation is visible. */}
{item.expiresAt && (() => {
const { text, overdue } = expiryLabel(item.expiresAt);
if (!text) return null;
return (
<div className="flex items-center gap-1.5 text-xs">
<AlarmClock className={cn("h-3.5 w-3.5", overdue ? "text-destructive" : "text-muted-foreground")} />
<span className={overdue ? "font-medium text-destructive" : "text-muted-foreground"}>{text}</span>
</div>
);
})()}
{/* When to decide — the importance signal that drives desk ordering. */}
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-muted-foreground">When to decide</span>
<div className="flex flex-wrap items-center gap-1" role="group" aria-label="When to decide">
{DECIDE_BY_OPTIONS.map(([value, label]) => (
<SegmentButton
key={value}
active={decideBy === (value satisfies DecideByPreset)}
disabled={pending}
onClick={() => setDecideBy.mutate(decideBy === value ? null : value)}
>
{label}
</SegmentButton>
))}
<Popover>
<PopoverTrigger asChild>
<SegmentButton active={isDatePreset} disabled={pending}>
<CalendarClock className="h-3.5 w-3.5" />
{isDatePreset ? decideByLabel(decideBy) : "Pick date"}
</SegmentButton>
</PopoverTrigger>
<PopoverContent align="start" className="w-auto p-2">
<input
type="date"
defaultValue={isDatePreset ? decideBy ?? "" : ""}
className="rounded-sm border border-border bg-background px-2 py-1 text-xs"
onChange={(event) => {
if (event.target.value) setDecideBy.mutate(event.target.value);
}}
/>
</PopoverContent>
</Popover>
</div>
{/* Provenance ("· set by …") is rendered once, in the card meta row
(AttentionQueueRow), which shows in both collapsed and expanded
states — repeating it here duplicated it on the expanded card. */}
</div>
{/* Queues — current membership as removable chips + add/create. */}
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-muted-foreground">Queues</span>
{item.queues.map((queue) => (
<span
key={queue.key}
className="inline-flex items-center gap-1 rounded-sm border border-border bg-background px-1.5 py-0.5 text-xs"
>
{queue.title}
<button
type="button"
className="text-muted-foreground hover:text-destructive disabled:opacity-50"
aria-label={`Remove from ${queue.title}`}
disabled={pending}
onClick={() => removeFromQueue.mutate(queue.key)}
>
<X className="h-3 w-3" />
</button>
</span>
))}
<QueuePicker
companyId={companyId}
existingKeys={new Set(item.queues.map((queue) => queue.key))}
disabled={pending}
onAdd={(key) => addToQueue.mutate(key)}
/>
</div>
{/* Snooze + route-to-agent. */}
<div className="flex flex-wrap items-center gap-2">
{item.snoozedUntil ? (
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<AlarmClock className="h-3.5 w-3.5" />
Snoozed until {new Date(item.snoozedUntil).toLocaleString()}
<button
type="button"
className="text-muted-foreground hover:text-foreground"
disabled={pending}
onClick={() => setSnooze.mutate(null)}
>
Clear
</button>
</span>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="outline" size="xs" className="h-7 gap-1" disabled={pending}>
<AlarmClock className="h-3.5 w-3.5" />
Snooze
<ChevronDown className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{SNOOZE_PRESETS.map((preset) => (
<DropdownMenuItem key={preset.label} onClick={() => setSnooze.mutate(preset.resolve())}>
{preset.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
<AskAgentPicker
agents={agents ?? []}
disabled={routeToAgent.isPending || !relatedIssueId}
disabledReason={!relatedIssueId ? "No linked task to ask about" : undefined}
onRoute={(agent) => routeToAgent.mutate(agent)}
/>
{pending && <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />}
</div>
</div>
);
}
function SegmentButton({
active,
disabled,
onClick,
children,
}: {
active: boolean;
disabled?: boolean;
onClick?: () => void;
children: React.ReactNode;
}) {
return (
<button
type="button"
disabled={disabled}
onClick={onClick}
aria-pressed={active}
className={cn(
"inline-flex items-center gap-1 rounded-sm border px-2 py-1 text-xs transition-colors disabled:opacity-50",
active
? "border-primary bg-primary/10 font-medium text-primary"
: "border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
{children}
</button>
);
}
function QueuePicker({
companyId,
existingKeys,
disabled,
onAdd,
}: {
companyId: string;
existingKeys: Set<string>;
disabled?: boolean;
onAdd: (key: string) => void;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToastActions();
const [open, setOpen] = useState(false);
const [creating, setCreating] = useState(false);
const [title, setTitle] = useState("");
const { data: queues } = useQuery({
queryKey: queryKeys.decisionQueues.list(companyId),
queryFn: () => decisionQueuesApi.list(companyId),
enabled: open,
});
const create = useMutation({
mutationFn: (name: string) =>
decisionQueuesApi.create(companyId, { key: toQueueKey(name), title: name.trim() }),
onSuccess: (queue) => {
queryClient.invalidateQueries({ queryKey: queryKeys.decisionQueues.list(companyId) });
onAdd(queue.key);
setTitle("");
setCreating(false);
setOpen(false);
},
onError: (error) =>
pushToast({
title: "Could not create queue",
body: error instanceof Error ? error.message : "Please try again.",
tone: "error",
}),
});
const available = (queues ?? []).filter((queue) => !existingKeys.has(queue.key));
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button type="button" variant="outline" size="xs" className="h-7 gap-1" disabled={disabled}>
<Plus className="h-3.5 w-3.5" />
Queue
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-56 p-1">
{creating ? (
<div className="flex flex-col gap-1.5 p-1">
<input
autoFocus
value={title}
onChange={(event) => setTitle(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && title.trim()) create.mutate(title);
if (event.key === "Escape") setCreating(false);
}}
placeholder="New queue name…"
className="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={() => setCreating(false)}>
Cancel
</Button>
<Button type="button" size="xs" disabled={!title.trim() || create.isPending} onClick={() => create.mutate(title)}>
{create.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
Create
</Button>
</div>
</div>
) : (
<div className="max-h-64 space-y-0.5 overflow-y-auto">
{available.length === 0 && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">No other queues yet.</p>
)}
{available.map((queue) => (
<button
key={queue.key}
type="button"
className="flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground"
onClick={() => {
onAdd(queue.key);
setOpen(false);
}}
>
<span className="truncate">{queue.title}</span>
{queue.itemCount > 0 && (
<span className="ml-2 shrink-0 text-(length:--text-nano) tabular-nums text-muted-foreground">
{queue.itemCount}
</span>
)}
</button>
))}
<DropdownMenuSeparatorLike />
<button
type="button"
className="flex w-full items-center gap-1.5 rounded-sm px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground"
onClick={() => setCreating(true)}
>
<Plus className="h-3.5 w-3.5" />
New queue…
</button>
</div>
)}
</PopoverContent>
</Popover>
);
}
function DropdownMenuSeparatorLike() {
return <div className="my-1 h-px bg-border" />;
}
/**
* "Ask agent for recommendation" — posts a mention-comment on the linked task
* asking the agent to prepare a recommendation and re-surface the decision. It
* does not reassign the task, so the label says exactly what it does
* (Previously labeled "Route to agent".)
*/
function AskAgentPicker({
agents,
disabled,
disabledReason,
onRoute,
}: {
agents: Agent[];
disabled?: boolean;
disabledReason?: string;
onRoute: (agent: Agent) => void;
}) {
const active = agents.filter((agent) => agent.status !== "terminated");
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="xs"
className="h-7 gap-1"
disabled={disabled || active.length === 0}
title={disabledReason}
>
<UserPlus className="h-3.5 w-3.5" />
Ask agent for recommendation
<ChevronDown className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-h-72 overflow-y-auto">
{active.map((agent) => (
<DropdownMenuItem key={agent.id} onClick={() => onRoute(agent)}>
{agent.name}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}