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 (
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 (
{text}
); })()} {/* When to decide — the importance signal that drives desk ordering. */}
When to decide
{DECIDE_BY_OPTIONS.map(([value, label]) => ( setDecideBy.mutate(decideBy === value ? null : value)} > {label} ))} {isDatePreset ? decideByLabel(decideBy) : "Pick date"} { if (event.target.value) setDecideBy.mutate(event.target.value); }} />
{/* 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. */}
{/* Queues — current membership as removable chips + add/create. */}
Queues {item.queues.map((queue) => ( {queue.title} ))} queue.key))} disabled={pending} onAdd={(key) => addToQueue.mutate(key)} />
{/* Snooze + route-to-agent. */}
{item.snoozedUntil ? ( Snoozed until {new Date(item.snoozedUntil).toLocaleString()} ) : ( {SNOOZE_PRESETS.map((preset) => ( setSnooze.mutate(preset.resolve())}> {preset.label} ))} )} routeToAgent.mutate(agent)} /> {pending && }
); } function SegmentButton({ active, disabled, onClick, children, }: { active: boolean; disabled?: boolean; onClick?: () => void; children: React.ReactNode; }) { return ( ); } function QueuePicker({ companyId, existingKeys, disabled, onAdd, }: { companyId: string; existingKeys: Set; 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 ( {creating ? (
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" />
) : (
{available.length === 0 && (

No other queues yet.

)} {available.map((queue) => ( ))}
)}
); } function DropdownMenuSeparatorLike() { return
; } /** * "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 ( {active.map((agent) => ( onRoute(agent)}> {agent.name} ))} ); }