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>
This commit is contained in:
authored and GitHub committed 2026-11-11 21:05:00 -08:00
1 parent 156453fe7c
commit cf1def0ca6
85 files changed
+9492 -1043

No files matched your search

@@ -1,10 +1,9 @@
import { useQueryView } from "@/components/QueryView";
import { useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpRight } from "lucide-react";
import { attentionApi } from "@/api/attention";
import { useCompany } from "@/context/CompanyContext";
import { coordinatorAttentionQueryKey, pendingDecisionTaskIds } from "@/lib/coordinator-attention";
import { pendingDecisionTaskIds } from "@/lib/coordinator-attention";
import { useAttentionViewFeed } from "@/hooks/useAttentionViews";
import { useNavigate } from "@/lib/router";
import { Button } from "@/components/ui/button";
import { StatusIcon } from "@/components/StatusIcon";
@@ -15,8 +14,7 @@ export function CoordinatorAttentionTasks({ toolbar }: { toolbar: ReactNode }) {
const { selectedCompanyId } = useCompany();
const navigate = useNavigate();
const [search, setSearch] = useState("");
const feed = useQuery({ queryKey: coordinatorAttentionQueryKey(selectedCompanyId!),
queryFn: () => attentionApi.list(selectedCompanyId!, { all: true }), enabled: !!selectedCompanyId, refetchOnWindowFocus: true });
const feed = useAttentionViewFeed(selectedCompanyId, "mine");
const feedView = useQueryView(feed);
const waiting = ["loading", "reconnecting"].includes(feedView.kind);
const items = feed.data?.items ?? [];
@@ -1,13 +1,22 @@
import { ArrowUpRight, Check } from "lucide-react";
import type { DecisionHistoryItem } from "@paperclipai/shared";
import { decisionHistoryContext, decisionHistoryHeadline } from "@/lib/coordinator-attention";
/** A recorded decision links to its context; it is not a second approval form. */
export function CoordinatorDecisionReceipt({ item, onOpen }: { item: DecisionHistoryItem; onOpen: (href: string) => void }) {
return <button type="button" onClick={() => onOpen(item.href)} className="coordinator-decision-receipt flex w-full items-center gap-3 rounded-xl border border-border bg-card p-4 text-left hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: {
item: DecisionHistoryItem;
onOpen: (href: string) => void;
/** Names the person a different person answered for ("for @dotta"; PAP-749 plan §6). */
userLabelMap?: ReadonlyMap<string, string> | null;
}) {
const handledFor = item.handledForUserId ? userLabelMap?.get(item.handledForUserId) ?? "someone else" : null;
return <button type="button" onClick={() => onOpen(item.href)} data-decision-history-item={item.id} className="coordinator-decision-receipt flex w-full items-center gap-3 rounded-xl border border-border bg-card p-4 text-left hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Check className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="min-w-0 flex-1 space-y-1">
<span className="block text-sm font-medium">{item.label}</span>
<span className="block truncate text-sm text-muted-foreground">{item.issueIdentifier} · {item.issueTitle}</span>
<span className="block text-sm font-medium">{decisionHistoryHeadline(item, userLabelMap)}{handledFor ? <span className="font-normal text-muted-foreground"> · for @{handledFor}</span> : null}</span>
<span className="block truncate text-sm text-muted-foreground">{decisionHistoryContext(item)}</span>
{/* Who withdrew it is in the headline; the reason they gave is here (PAP-749 plan §3). */}
{item.reason ? <span className="block text-sm text-muted-foreground" data-decision-history-reason>Reason: {item.reason}</span> : null}
</span>
<ArrowUpRight className="size-4 shrink-0 text-muted-foreground" aria-hidden />
</button>;
@@ -4,22 +4,43 @@ import { MemoryRouter, useLocation } from "react-router-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AttentionItem, DecisionHistoryItem } from "@paperclipai/shared";
import type { Agent, AttentionItem, AttentionReceipt, DecisionHistoryItem } from "@paperclipai/shared";
import { CoordinatorNeedsYou } from "./CoordinatorNeedsYou";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const fixture = vi.hoisted(() => ({ pending: [] as AttentionItem[], history: [] as DecisionHistoryItem[], url: "/decisions", mobile: false, partial: false, historyFail: false, feedFail: false, openPanel: vi.fn(), closePanel: vi.fn(), setPanelVisible: vi.fn(), navigate: vi.fn(), breadcrumbs: vi.fn() }));
const fixture = vi.hoisted(() => ({ pending: [] as AttentionItem[], byView: {} as Record<string, AttentionItem[]>, viewCounts: undefined as undefined | Record<string, number>, receipts: [] as AttentionReceipt[], listCalls: [] as unknown[], claim: vi.fn(async () => ({})), close: vi.fn(async (..._args: unknown[]) => ({ until: null })), retryTask: vi.fn(async (..._args: unknown[]) => ({ accepted: true, requestId: "r", stale: false, presentation: null })), history: [] as DecisionHistoryItem[], url: "/decisions", mobile: false, partial: false, historyFail: false, feedFail: false, openPanel: vi.fn(), closePanel: vi.fn(), setPanelVisible: vi.fn(), navigate: vi.fn(), breadcrumbs: vi.fn(), boardAccess: null as null | Record<string, unknown>, historyByScope: {} as Record<string, DecisionHistoryItem[]>, historyCalls: [] as Array<Record<string, unknown>>, resolveIncident: vi.fn(async (..._args: unknown[]) => ({})) }));
const dismissals = vi.hoisted(() => ({ restore: vi.fn(async (..._args: unknown[]) => ({})), dismiss: vi.fn(async (..._args: unknown[]) => ({})) }));
vi.mock("@/api/inboxDismissals", () => ({ inboxDismissalsApi: { restore: dismissals.restore, dismiss: dismissals.dismiss } }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "company" }) }));
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }) }));
vi.mock("@/context/PanelContext", () => ({ usePanel: () => ({ openPanel: fixture.openPanel, closePanel: fixture.closePanel, setPanelVisible: fixture.setPanelVisible }) }));
vi.mock("@/context/PanelContext", () => ({ usePanel: () => ({ openPanel: fixture.openPanel, closePanel: fixture.closePanel, setPanelVisible: fixture.setPanelVisible, panelVisible: true }) }));
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: fixture.mobile }) }));
vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ userId: "reviewer" }) }));
vi.mock("@/lib/router", async importOriginal => ({ ...await importOriginal<typeof import("@/lib/router")>(), useNavigate: () => fixture.navigate }));
vi.mock("@/api/agents", () => ({ agentsApi: { list: async () => [] } }));
const agentFixture = vi.hoisted(() => ({ rows: [] as Agent[] }));
vi.mock("@/api/agents", () => ({ agentsApi: { list: async () => agentFixture.rows } }));
vi.mock("@/api/projects", () => ({ projectsApi: { list: async () => [] } }));
vi.mock("@/api/access", () => ({ accessApi: {
listUserDirectory: async () => ({ users: [{ principalId: "dotta", status: "active", user: { name: "Dotta" } }] }),
getCurrentBoardAccess: async () => { if (!fixture.boardAccess) throw new Error("No board access"); return fixture.boardAccess; },
} }));
vi.mock("@/api/issues", () => ({ issuesApi: { retryTask: fixture.retryTask } }));
vi.mock("@/api/budgets", () => ({ budgetsApi: { resolveIncident: fixture.resolveIncident } }));
const approvals = vi.hoisted(() => ({ get: vi.fn(async (..._args: unknown[]) => ({ payload: {} })), approve: vi.fn(async (..._args: unknown[]) => ({})), reject: vi.fn(async () => ({})), requestRevision: vi.fn(async () => ({})) }));
vi.mock("@/api/approvals", () => ({ approvalsApi: approvals }));
vi.mock("@/api/attention", () => ({ attentionApi: {
list: async () => { if (fixture.feedFail) throw new Error("Feed unavailable"); return { items: [...fixture.pending] }; },
history: async () => { if (fixture.historyFail) throw new Error("History unavailable"); return { items: [...fixture.history], nextCursor: null }; },
claim: fixture.claim,
close: fixture.close,
list: async (_companyId: string, options: { view?: string }) => {
fixture.listCalls.push(options);
if (fixture.feedFail) throw new Error("Feed unavailable");
return { items: [...(fixture.byView[options.view ?? ""] ?? fixture.pending)], viewCounts: fixture.viewCounts, receipts: options.view === "mine" ? [...fixture.receipts] : [] };
},
history: async (_companyId: string, options: Record<string, unknown> = {}) => {
fixture.historyCalls.push(options);
if (fixture.historyFail) throw new Error("History unavailable");
return { items: [...(fixture.historyByScope[String(options.scope)] ?? fixture.history)], nextCursor: null };
},
} }));
vi.mock("motion/react", () => ({
LayoutGroup: ({ children }: { children: ReactNode }) => children,
@@ -32,7 +53,7 @@ vi.mock("@/components/StalledReviewActions", () => ({ StalledReviewActions: ({ i
fixture.pending = fixture.pending.filter((item) => item.subject.id !== issueId);
onResolved();
}}>{approveLabel}</button> }));
vi.mock("@/components/AttentionInteractionResolver", () => ({ AttentionInteractionResolver: ({ issueId, interactionId, footerSlot, onResolved }: { issueId: string; interactionId: string; footerSlot?: ReactNode; onResolved: (interaction: { status: string }) => void }) => <>{footerSlot}<button data-issue-id={issueId} onClick={() => {
vi.mock("@/components/AttentionInteractionResolver", () => ({ AttentionInteractionResolver: ({ issueId, interactionId, footerSlot, artifactRow, onResolved }: { issueId: string; interactionId: string; footerSlot?: ReactNode; artifactRow?: ReactNode; onResolved: (interaction: { status: string }) => void }) => <>{artifactRow}{footerSlot}<button data-issue-id={issueId} onClick={() => {
if (fixture.partial) { onResolved({ status: "pending" }); return; }
fixture.pending = fixture.pending.filter((item) => item.subject.id !== interactionId);
fixture.history.push({ id: `issue_thread_interaction:${interactionId}`, sourceKind: "issue_thread_interaction", sourceId: interactionId,
@@ -46,7 +67,9 @@ let root: Root;
let container: HTMLDivElement;
beforeEach(() => {
fixture.pending = ["1", "2", "3"].map((id) => ({ id, sourceKind: "issue_thread_interaction", inlineResolvable: true, subject: { id, kind: "interaction", title: `Review ${id}`, metadata: { issueId: `task-${id}` } }, relatedIssue: { id: `task-${id}`, identifier: `PAP-${id}`, title: `Task ${id}`, href: `/PAP/issues/PAP-${id}` }, activityAt: new Date().toISOString() } as unknown as AttentionItem));
agentFixture.rows = [{ id: "agent-cos", name: "Chief of Staff" }] as Agent[];
fixture.history = []; fixture.url = "/decisions"; vi.clearAllMocks();
fixture.byView = {}; fixture.viewCounts = undefined; fixture.receipts = []; fixture.listCalls = []; fixture.boardAccess = null; fixture.historyByScope = {}; fixture.historyCalls = [];
fixture.historyFail = false; fixture.feedFail = false; fixture.partial = false; fixture.mobile = false;
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
});
@@ -57,6 +80,157 @@ async function click(text: string) {
expect(button, text).toBeTruthy();
await act(async () => button!.click()); await flush();
}
/** History has one home, the View menu (PAP-775, IA2–IA4). */
async function openHistory() {
const trigger = container.querySelector<HTMLElement>("[data-attention-view-menu]");
expect(trigger, "View menu").toBeTruthy();
await act(async () => {
trigger!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
const item = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((entry) => entry.textContent === "Decision history");
expect(item, "Decision history menu item").toBeTruthy();
await act(async () => item!.click()); await flush();
}
async function renderPage(url = fixture.url) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[url]}><CoordinatorNeedsYou /><Location /></MemoryRouter></QueryClientProvider>));
await flush(); await flush();
return client;
}
describe("Coordinator Needs You — Archived view and history filters (PAP-749 task 2e)", () => {
const hidden = (id: string, kind: "dismiss" | "snooze", snoozedUntil: string | null = null) => ({
id, sourceKind: "issue_thread_interaction", inlineResolvable: false, dismissalKey: `attention:${id}`, changeFingerprint: `${id}.me`,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: null, obligationLeadId: null, audience: { kind: "user", userId: "reviewer", reason: "addressee" },
dismissal: { kind, dismissedAt: "2026-10-29T12:00:00.000Z", snoozedUntil, isActive: true },
subject: { id: `${id}-interaction`, kind: "interaction", title: `Hidden ${id}`, href: `/PAP/issues/PAP-9#${id}`, metadata: {} },
relatedIssue: null, activityAt: new Date().toISOString(),
}) as unknown as AttentionItem;
it("lists your archived cards with their date and a Snoozed group, and restores one", async () => {
fixture.byView = { archived: [hidden("arch", "dismiss"), hidden("snz", "snooze", "2026-10-31T09:00:00.000Z")] };
fixture.viewCounts = { mine: 2, unassigned: 0, company: 0, archived: 2 };
const client = await renderPage("/decisions?view=archived");
expect(fixture.listCalls).toContainEqual(expect.objectContaining({ view: "archived", all: true }));
// Focus (PAP-770): Archived opens from the View menu, not a persistent tab;
// its heading names the view, with a back control to Needs You (PAP-775).
expect(container.querySelector("[data-attention-view-menu]")).not.toBeNull();
expect(container.querySelector("h1")?.textContent).toBe("Archived");
expect(container.querySelector('[aria-label="Back to Needs You"]')).not.toBeNull();
expect(container.querySelector('select[aria-label="Filter decisions by assignee"]')).toBeNull();
const archivedCard = container.querySelector<HTMLElement>('[data-attention-card="arch"]')!;
expect(archivedCard.querySelector('[data-attention-hidden="archived"]')?.textContent).toMatch(/^Archived /);
const group = container.querySelector<HTMLElement>("[data-attention-snoozed-group]")!;
expect(group.textContent).toContain("Snoozed (1)");
expect(group.querySelector('[data-attention-card="snz"] [data-attention-hidden="snoozed"]')).not.toBeNull();
expect(group.querySelector('[data-attention-card="arch"]')).toBeNull();
dismissals.restore.mockImplementationOnce(async () => { fixture.byView.archived = fixture.byView.archived!.filter(item => item.id !== "arch"); return {}; });
const trigger = archivedCard.querySelector<HTMLElement>("[data-attention-close-menu]")!;
await act(async () => {
trigger.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(document.body.querySelector('[data-attention-close-mode="archive"]')).toBeNull();
await act(async () => document.body.querySelector<HTMLElement>('[data-attention-close-mode="restore"]')!.click());
await flush();
expect(dismissals.restore).toHaveBeenCalledWith("company", "attention:arch");
expect(container.querySelector('[data-attention-card="arch"]')).toBeNull();
await act(async () => container.querySelector<HTMLElement>('[aria-label="Back to Needs You"]')!.click()); await flush();
expect(container.querySelector("[data-location]")?.textContent).toBe("");
expect(container.querySelector("h1")).toBeNull();
client.clear();
// The file's first test also pays for the cold module graph.
}, 15_000);
it("shows the Archived empty state", async () => {
fixture.byView = { archived: [] };
const client = await renderPage("/decisions?view=archived");
expect(container.textContent).toContain("Nothing archived. Cards you archive or snooze for yourself show here.");
client.clear();
});
it("filters history by Withdrawn, Expired and Closed with task, and names who withdrew and why", async () => {
fixture.mobile = true;
fixture.pending = [];
fixture.history = [{ id: "approval:appr", sourceKind: "approval", sourceId: "appr", issueId: null, issueIdentifier: null, issueTitle: null,
title: "Hire a designer", label: "Withdrawn by user", outcome: "cancelled", resultOutcome: "withdrawn", reason: "Budget moved to Q1",
resolvedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(), resolvedByUserId: "dotta", resolvedByAgentId: null,
agentId: null, agentName: null, projectId: null, projectName: null, href: "/PAP/approvals/appr", target: null }];
const historySpy = vi.spyOn(await import("@/api/attention").then((module) => module.attentionApi), "history");
const client = await renderPage();
await openHistory();
const dialog = container.querySelector<HTMLElement>("[data-coordinator-decision-history]")!;
const outcome = dialog.querySelector<HTMLSelectElement>('[aria-label="Filter decision outcomes"]')!;
const labels = [...outcome.options].map((option) => option.textContent);
expect(labels).toEqual(expect.arrayContaining(["Withdrawn", "Expired", "Closed with task", "Handled for me"]));
expect(dialog.textContent).toContain("Withdrawn by @Dotta");
expect(dialog.textContent).toContain("Reason: Budget moved to Q1");
expect(dialog.textContent).toContain("Approval · Hire a designer");
await act(async () => {
outcome.value = "issue_closed";
outcome.dispatchEvent(new Event("change", { bubbles: true }));
});
await flush();
expect(historySpy).toHaveBeenCalledWith("company", expect.objectContaining({ outcome: "issue_closed" }));
client.clear();
});
const historyEntry = (id: string, issueTitle: string, resolvedByUserId: string) => ({ id: `issue_thread_interaction:${id}`, sourceKind: "issue_thread_interaction",
sourceId: id, issueId: `task-${id}`, issueIdentifier: `NEE-${id}`, issueTitle, title: "Confirm", label: "Approved", outcome: "accepted",
action: { outcome: "approved", detail: null }, resolvedAt: new Date(Date.now() - 60_000).toISOString(), resolvedByUserId, resolvedByAgentId: null,
agentId: null, agentName: null, projectId: null, projectName: null, href: `/NEE/issues/NEE-${id}`, target: null }) as DecisionHistoryItem;
const choose = async (root: ParentNode, label: string, value: string) => {
const select = root.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`);
expect(select, label).not.toBeNull();
await act(async () => { select!.value = value; select!.dispatchEvent(new Event("change", { bubbles: true })); });
await flush();
return select!;
};
it("opens Decision history on Handled by me or for me, with Everyone one choice away, and keeps history off the page (PAP-768, PAP-775)", async () => {
fixture.mobile = true;
fixture.pending = [];
const mineEntry = historyEntry("1", "Dotta's launch checklist", "reviewer");
const othersEntry = historyEntry("2", "Scott: task you created", "scott");
fixture.historyByScope = { mine: [mineEntry], all: [mineEntry, othersEntry] };
const client = await renderPage();
// IA3/IA4: history has one home, the main-pane view; no Recent Decisions list or header button.
expect(container.querySelector('[aria-label="Recent Decisions"]')).toBeNull();
expect(container.textContent).not.toContain("Dotta's launch checklist");
expect([...container.querySelectorAll("button")].some((button) => button.textContent?.includes("Decision history"))).toBe(false);
await openHistory();
const dialog = container.querySelector<HTMLElement>("[data-coordinator-decision-history]")!;
const scope = dialog.querySelector<HTMLSelectElement>('select[aria-label="Whose decision history"]')!;
expect(scope.value).toBe("mine");
expect([...scope.options].map((option) => option.textContent)).toEqual(["Handled by me or for me", "Everyone"]);
expect(dialog.textContent).not.toContain("Scott: task you created");
await choose(dialog, "Whose decision history", "all");
expect(dialog.textContent).toContain("Scott: task you created");
// An outcome filter applies within the chosen scope.
await choose(dialog, "Filter decision outcomes", "accepted");
expect(fixture.historyCalls).toContainEqual(expect.objectContaining({ scope: "all", outcome: "accepted", limit: 40 }));
client.clear();
});
it("offers everyone's decisions when nothing was handled by or for you (PAP-768)", async () => {
fixture.mobile = true;
fixture.pending = [];
fixture.historyByScope = { mine: [], all: [historyEntry("2", "Scott: task you created", "scott")] };
const client = await renderPage();
// Nothing of yours in the last day: Recent Decisions stays out of the way.
expect(container.querySelector('[aria-label="Recent Decisions"]')).toBeNull();
await openHistory();
const dialog = container.querySelector<HTMLElement>("[data-coordinator-decision-history]")!;
expect(dialog.textContent).toContain("No decisions handled by you or for you yet.");
await act(async () => [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Show everyone's decisions")!.click());
await flush();
expect(dialog.querySelector<HTMLSelectElement>('select[aria-label="Whose decision history"]')!.value).toBe("all");
expect(dialog.textContent).toContain("Scott: task you created");
client.clear();
});
});
describe("Coordinator Needs You", () => {
it("reveals and focuses a linked decision beyond the first rendering window, then consumes only its URL parameter", async () => {
fixture.url = "/decisions?decisionId=target&q=kept";
@@ -80,25 +254,38 @@ describe("Coordinator Needs You", () => {
expect(scroll).not.toHaveBeenCalled();
client.clear();
});
it("opens searchable history from both phone buttons without the hidden desktop panel", async () => {
it("opens a decision link outside the personal feed before focusing it", async () => {
fixture.url = "/decisions?decisionId=target";
fixture.boardAccess = { userId: "reviewer", source: "session", memberships: [{ companyId: "company", status: "active", membershipRole: "admin" }] };
fixture.byView = { mine: [], all: [{ ...fixture.pending[0], id: "linked-decision", sourceKind: "decision", subject: { id: "target", kind: "decision", title: "Linked decision" } } as AttentionItem] };
const scroll = vi.fn();
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, writable: true, value: scroll });
const client = await renderPage(fixture.url);
for (let tick = 0; tick < 5; tick++) await flush();
expect(fixture.listCalls).toContainEqual(expect.objectContaining({ view: "all" }));
expect(container.querySelector("#coordinator-decision-target")).not.toBeNull();
expect(container.querySelector("[data-location]")?.textContent).not.toContain("decisionId");
expect(scroll).toHaveBeenCalled();
client.clear();
});
it("opens searchable history in the main pane from the View menu, never in the side panel (PAP-770, PAP-775)", async () => {
fixture.mobile = true;
fixture.pending = [];
fixture.history = [{ id: "old-decision", sourceKind: "issue_thread_interaction", sourceId: "old", issueId: "task-1", issueIdentifier: "PAP-1", issueTitle: "Earlier launch", title: "Review", label: "Approved", outcome: "accepted", resolvedAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), resolvedByUserId: "reviewer", resolvedByAgentId: null, agentId: null, agentName: null, projectId: null, projectName: null, href: "/PAP/issues/PAP-1#interaction-old", target: null }];
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[fixture.url]}><CoordinatorNeedsYou /><Location /></MemoryRouter></QueryClientProvider>));
await flush();
for (const label of ["Decision history", "Open decision history"]) {
const trigger = [...container.querySelectorAll("button")].find(button => button.textContent?.trim() === label);
expect(trigger).toBeTruthy();
await act(async () => trigger!.click()); await flush();
const dialog = document.querySelector('[role="dialog"]');
expect(dialog).not.toBeNull();
expect(dialog!.querySelector('[aria-label="Search decision history"]')).not.toBeNull();
expect(dialog!.textContent).toContain("Earlier launch");
for (let round = 0; round < 2; round += 1) {
await openHistory();
const history = container.querySelector("[data-coordinator-decision-history]");
expect(history).not.toBeNull();
expect(history!.querySelector('[aria-label="Search decision history"]')).not.toBeNull();
expect(history!.textContent).toContain("Earlier launch");
expect(fixture.openPanel).not.toHaveBeenCalled();
const close = [...dialog!.querySelectorAll("button")].find(button => button.textContent === "Close");
await act(async () => close!.click()); await flush();
expect(document.querySelector('[role="dialog"]')).toBeNull();
const back = [...history!.querySelectorAll("button")].find(button => button.textContent === "Needs You");
await act(async () => back!.click()); await flush();
expect(container.querySelector("[data-coordinator-decision-history]")).toBeNull();
}
client.clear();
});
@@ -122,41 +309,40 @@ describe("Coordinator Needs You", () => {
fixture.historyFail = true; fixture.feedFail = staleFeed;
await click("Resolve 1"); await flush();
expect([...container.querySelectorAll("button")].some(button => button.textContent === "Resolve 1")).toBe(false);
expect(container.textContent).toContain("Recent decisions could not be loaded");
expect(container.textContent).toContain("Resolve 2");
client.clear();
});
it("sorts, groups, and filters the recent decisions shown beneath the toolbar", async () => {
fixture.pending = [];
const now = Date.now();
fixture.history = [
{ id: "recent-old", sourceId: "old", issueIdentifier: "PAP-1", issueTitle: "First task", projectId: "launch", projectName: "Launch", resolvedAt: new Date(now - 180_000).toISOString() },
{ id: "recent-middle", sourceId: "middle", issueIdentifier: "PAP-2", issueTitle: "Second task", projectId: "other", projectName: "Other", resolvedAt: new Date(now - 120_000).toISOString() },
{ id: "recent-new", sourceId: "new", issueIdentifier: "PAP-3", issueTitle: "Third task", projectId: "launch", projectName: "Launch", resolvedAt: new Date(now - 60_000).toISOString() },
].map((item) => ({ sourceKind: "issue_thread_interaction", issueId: item.sourceId, agentId: null, agentName: null,
title: "Review", outcome: "accepted", label: "Approved", resolvedByUserId: "reviewer", resolvedByAgentId: null,
href: `/PAP/issues/${item.issueIdentifier}`, target: null, ...item })) as DecisionHistoryItem[];
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[fixture.url]}><CoordinatorNeedsYou /><Location /></MemoryRouter></QueryClientProvider>));
await flush();
const visibleIds = () => [...container.querySelectorAll('[aria-label="Recent Decisions"] .coordinator-decision-receipt')]
.map((item) => item.textContent?.match(/PAP-\d+/)?.[0]);
const changeSelect = async (label: string, value: string) => {
const select = container.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`);
expect(select).not.toBeNull();
await act(async () => { select!.value = value; select!.dispatchEvent(new Event("change", { bubbles: true })); });
};
expect(visibleIds()).toEqual(["PAP-3", "PAP-2", "PAP-1"]);
await changeSelect("Sort decisions", "oldest");
expect(visibleIds()).toEqual(["PAP-1", "PAP-2", "PAP-3"]);
await changeSelect("Group decisions", "task");
expect([...container.querySelectorAll('[aria-label="Recent Decisions"] h3')].map((item) => item.textContent)).toEqual(["PAP-1", "PAP-2", "PAP-3"]);
await changeSelect("Filter decisions by project", "launch");
expect(visibleIds()).toEqual(["PAP-1", "PAP-3"]);
it("keeps search, filters and grouping in one visible toolbar and applies them to cards (UX6, PAP-775)", async () => {
const client = await renderPage();
const toolbar = container.querySelector<HTMLElement>('[role="toolbar"][aria-label="Decisions controls"]')!;
expect(toolbar).not.toBeNull();
// No filter icon toggle and no sort select: the controls are always there.
expect(container.querySelector('[aria-label="Filter and search"]')).toBeNull();
expect(container.querySelector('select[aria-label="Sort decisions"]')).toBeNull();
const summary = container.querySelector("[data-needs-you-summary]")!;
expect(summary.textContent).toBe("3 decisions");
expect(toolbar.compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(container.querySelector("h1")).toBeNull();
expect(container.textContent).not.toContain("Someone needs you to choose");
// Grouped by type by default.
const group = toolbar.querySelector<HTMLSelectElement>('select[aria-label="Group decisions"]')!;
expect(group.value).toBe("type");
expect([...group.options].map((option) => option.textContent)).toEqual(["By type", "By task", "By agent", "By project", "No grouping"]);
expect(container.querySelector('[data-needs-you-section="decisions"]')).toBeNull();
await act(async () => { group.value = "none"; group.dispatchEvent(new Event("change", { bubbles: true })); });
expect(container.querySelector("[data-needs-you-section]")).toBeNull();
expect(container.querySelectorAll("article")).toHaveLength(3);
// Search narrows the cards.
const search = toolbar.querySelector<HTMLInputElement>('input[placeholder="Search…"]')!;
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(search, "Task 2");
search.dispatchEvent(new Event("input", { bubbles: true }));
});
expect([...container.querySelectorAll("[data-attention-card]")].map((card) => card.getAttribute("data-attention-card"))).toEqual(["2"]);
client.clear();
});
it("resizes and gathers light in place before moving the saved receipt into Recent Decisions", async () => {
it("resizes and gathers light in place, then the receipt leaves for Decision history", async () => {
window.matchMedia = vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() });
const animate = vi.fn().mockReturnValue({ cancel: vi.fn() });
HTMLElement.prototype.animate = animate;
@@ -179,8 +365,9 @@ describe("Coordinator Needs You", () => {
expect(animate.mock.calls[0]?.[1]).toMatchObject({ duration: 480 });
await act(async () => { await vi.advanceTimersByTimeAsync(1400); });
expect(container.querySelector("[data-motion]")).toBeNull();
expect(container.querySelector('[aria-label="Recent Decisions"]')?.textContent).toContain("PAP-1");
expect(container.querySelectorAll(".coordinator-decision-receipt")).toHaveLength(1);
// IA3: the record now lives in Decision history only.
expect(container.querySelector('[aria-label="Recent Decisions"]')).toBeNull();
expect(container.querySelectorAll(".coordinator-decision-receipt")).toHaveLength(0);
client.clear();
});
it("renders a pending canonical question from persistent chat with its original resolver and context", async () => {
@@ -210,14 +397,18 @@ describe("Coordinator Needs You", () => {
expect(container.textContent).toContain("Choose how this task continues");
expect(container.textContent).not.toContain("Open to review");
expect(container.querySelectorAll("article")).toHaveLength(1);
expect(container.querySelectorAll(".coordinator-decision-receipt")).toHaveLength(1);
// IA7: a stuck task is a problem card, listed under Problems (PAP-775).
expect(container.querySelector("article")?.getAttribute("data-card-kind")).toBe("problem");
expect(container.querySelector("article")?.getAttribute("data-card-type")).toBe("blocked_task");
expect(container.querySelector("[data-attention-type-label]")?.textContent).toBe("Unblock a task");
expect(container.querySelector("[data-needs-you-summary]")?.textContent).toBe("1 problem");
expect(container.querySelector('[data-needs-you-section="decisions"]')).toBeNull();
expect(container.querySelector("[data-review-policy]")?.getAttribute("data-review-policy")).toBe("human_only");
await click("Mark task done");
expect(container.querySelectorAll("article")).toHaveLength(0);
expect(container.textContent).toContain("You're caught up.");
expect(container.querySelectorAll(".coordinator-decision-receipt")).toHaveLength(1);
});
it("retains all three decisions as receipts, including an answered question, and opens history only on demand", async () => {
it("turns all three answers into receipts, then keeps them in Decision history, opened only on demand", async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[fixture.url]}><CoordinatorNeedsYou /><Location /></MemoryRouter></QueryClientProvider>));
await flush();
@@ -226,19 +417,532 @@ describe("Coordinator Needs You", () => {
await click("Resolve 1"); await click("Resolve 2"); await click("Resolve 3");
await flush();
expect(container.querySelectorAll("article")).toHaveLength(0);
expect(container.textContent).toContain("Recent Decisions");
expect(container.querySelectorAll(".coordinator-decision-receipt")).toHaveLength(3);
expect(container.textContent).toContain("Answers recorded");
await click("PAP-3");
expect(fixture.navigate).toHaveBeenCalledWith("/PAP/issues/PAP-3#interaction-3");
await click("Decision history");
expect(fixture.openPanel).toHaveBeenCalled();
expect(fixture.setPanelVisible).toHaveBeenCalledWith(true);
// The shared desktop hide control changes visibility without closing
// this tab. Clicking history again must reveal the already-open tab.
fixture.setPanelVisible(false);
fixture.setPanelVisible.mockClear();
await click("Decision history");
expect(fixture.setPanelVisible).toHaveBeenCalledWith(true);
expect(container.textContent).not.toContain("Recent Decisions");
// Decision history opens in the main pane, not the side panel (PAP-770).
await openHistory();
const history = container.querySelector<HTMLElement>("[data-coordinator-decision-history]");
expect(history).not.toBeNull();
expect(history!.textContent).toContain("Answers recorded");
expect(fixture.openPanel).not.toHaveBeenCalled();
});
});
describe("Coordinator Needs You views (PAP-749 task 1b)", () => {
const mine = (id: string, reason: string) => ({ ...fixture.pending[0], id, subject: { id, kind: "interaction", title: `Mine ${id}`, metadata: { issueId: `task-${id}` } },
audience: { kind: "user", userId: "reviewer", reason } }) as unknown as AttentionItem;
const pool = { id: "pool", sourceKind: "issue_thread_interaction", inlineResolvable: true, subject: { id: "pool-interaction", kind: "interaction", title: "Pool", metadata: { issueId: "task-pool" } },
relatedIssue: { id: "task-pool", identifier: "PAP-9", title: "Pool task", href: "/PAP/issues/PAP-9" }, activityAt: new Date().toISOString(),
audience: { kind: "pool", userId: null, reason: "none" } } as unknown as AttentionItem;
const company = { id: "alert", sourceKind: "failed_run", inlineResolvable: false, subject: { id: "run-1", kind: "run", title: "Nightly sync failed", href: "/PAP/runs/1" }, relatedIssue: null,
activityAt: new Date().toISOString(), audience: { kind: "user", userId: "dotta", reason: "escalation_owner" } } as unknown as AttentionItem;
async function render(client: QueryClient) {
await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[fixture.url]}><CoordinatorNeedsYou /><Location /></MemoryRouter></QueryClientProvider>));
await flush(); await flush();
}
const tab = (view: string) => container.querySelector<HTMLElement>(`[data-attention-view="${view}"]`)!;
it("defaults to Assigned to you with Why me?, no banner and per-person keys, then claims from No owner yet", async () => {
fixture.byView = { mine: [mine("m1", "addressee"), mine("m2", "reviewer")], unassigned: [pool], company: [company] };
fixture.viewCounts = { mine: 2, unassigned: 1, company: 1 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
expect(fixture.listCalls).toContainEqual({ all: true, view: "mine" });
expect(fixture.listCalls.some((call) => (call as { view?: string }).view !== "mine")).toBe(false);
// PAP-775: For you is the page (no tab, no chips); the toolbar's assignee
// filter says "Assigned to you" and widens to the other views.
expect(tab("mine")).toBeNull();
expect(tab("unassigned")).toBeNull();
const assignee = () => container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
expect(assignee().value).toBe("me");
expect(assignee().selectedOptions[0]?.textContent).toBe("Assigned to you");
// Why me? is the type label's tooltip, not text on the card; your own card doesn't name you.
expect([...container.querySelectorAll<HTMLElement>("[data-attention-type-label]")].map((label) => [label.textContent, label.title]))
.toEqual([["Confirm or decline", "Why me? Sent to you"], ["Confirm or decline", "Why me? You are the reviewer"]]);
expect(container.textContent).not.toContain("Why me?");
expect(container.querySelector("[data-attention-for-user]")).toBeNull();
expect(container.querySelector("[data-attention-unassigned-banner]")).toBeNull();
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "reviewer", "mine"], exact: false })).toBeTruthy();
await act(async () => { assignee().value = "unassigned"; assignee().dispatchEvent(new Event("change", { bubbles: true })); }); await flush();
expect(container.querySelector("[data-location]")?.textContent).toBe("?view=unassigned");
expect(assignee().value).toBe("unassigned");
expect(fixture.listCalls).toContainEqual({ all: true, view: "unassigned" });
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "reviewer", "unassigned"], exact: false })).toBeTruthy();
expect(container.querySelector("[data-attention-unassigned-banner]")).toBeNull();
await vi.waitFor(() => expect(container.querySelector('[data-attention-audience="pool"]')).not.toBeNull());
await click("Claim");
expect(fixture.claim).toHaveBeenCalledWith("company", "issue_thread_interaction", "pool-interaction");
client.clear();
});
it("opens Company alerts from the URL and names another person's card with @name before its type", async () => {
fixture.url = "/decisions?view=company";
fixture.byView = { company: [company] };
fixture.viewCounts = { mine: 0, unassigned: 0, company: 1 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const assignee = container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
expect(assignee.value).toBe("company");
expect(assignee.selectedOptions[0]?.textContent).toBe("Company alerts");
expect(fixture.listCalls).toContainEqual({ all: true, view: "company" });
await flush();
// A1 (PAP-775): the type label starts with the person the card is for.
const label = container.querySelector<HTMLElement>("[data-attention-type-label]")!;
expect(label.textContent).toBe("@Dotta Fix a failed run");
expect(label.querySelector("[data-attention-for-user]")?.getAttribute("data-attention-for-user")).toBe("dotta");
expect(container.querySelector("article")?.textContent).not.toContain("Company alert");
expect(container.querySelector('[data-attention-view-count="mine"]')).toBeNull();
client.clear();
});
it("puts stale cards in a collapsed Stale (N) group at the bottom and withdraws them after a confirmation (PAP-749 task 2c)", async () => {
const stale = (id: string, reason: string, extra: Record<string, unknown> = {}) => ({ ...mine(id, "addressee"), stale: { reason }, closeModes: ["withdraw", "archive", "snooze"], ...extra }) as unknown as AttentionItem;
fixture.byView = { mine: [mine("fresh", "addressee"), stale("old", "aged"), stale("done", "issue_closed"),
stale("run", "aged", { sourceKind: "failed_run", inlineResolvable: false, closeModes: ["archive", "snooze"], subject: { id: "run-9", kind: "run", title: "Old run", href: "/PAP/runs/9" } })] };
fixture.viewCounts = { mine: 4, unassigned: 0, company: 0 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const group = container.querySelector<HTMLElement>("[data-attention-stale-group]")!;
expect(group.textContent).toContain("Stale (3)");
// Collapsed: only the current card is mounted, and the group sits after it.
expect(container.querySelectorAll("article")).toHaveLength(1);
expect(container.querySelector("article")!.compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
await act(async () => group.querySelector<HTMLElement>("[aria-expanded]")!.click()); await flush();
expect(container.querySelectorAll("article")).toHaveLength(4);
expect(group.querySelector('[data-attention-stale="aged"]')?.textContent).toBe("Stale · Waiting 30+ days");
expect(group.querySelector('[data-attention-stale="issue_closed"]')?.textContent).toBe("Stale · Task closed");
await click("Withdraw all stale");
const dialog = document.querySelector<HTMLElement>("[data-attention-stale-withdraw-dialog]")!;
expect(dialog.textContent).toContain("Withdraw 2 stale requests?");
expect(fixture.close).not.toHaveBeenCalled();
await act(async () => [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Withdraw 2 requests")!.click());
await flush(); await flush();
expect(fixture.close.mock.calls.map((call) => [call[2], (call[3] as { mode: string }).mode])).toEqual([["old", "withdraw"], ["done", "withdraw"]]);
// Withdrawn cards leave at once; the failed run has nothing to withdraw and stays.
expect(group.textContent).toContain("Stale (1)");
client.clear();
});
it("indexes company agents once when many task cards need assignee names", async () => {
let reads = 0;
agentFixture.rows = Array.from({ length: 1000 }, (_, index) => ({
get id() { if (++reads > 15_000) throw new Error("Repeated company roster scan"); return `agent-${index}`; },
name: `Agent ${index}`,
})) as Agent[];
fixture.byView = { mine: Array.from({ length: 80 }, (_, index) => ({
...mine(`review-${index}`, "assignee"), sourceKind: "review", inlineResolvable: false,
subject: { id: `task-${index}`, companyId: "company", identifier: `PAP-${index}`, kind: "issue", title: `Review ${index}`, status: "in_review", href: `/PAP/issues/PAP-${index}`,
metadata: { assigneeAgentId: "agent-999" } }, relatedIssue: null,
}) as AttentionItem) };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
expect(container.querySelectorAll('[data-attention-card]')).toHaveLength(40);
expect(container.textContent?.match(/Assigned to Agent 999/g)).toHaveLength(40);
expect(reads).toBeLessThan(15_000);
client.clear();
});
it("archives a card for me from its Close… menu with the version I saw", async () => {
fixture.byView = { mine: [{ ...mine("m1", "addressee"), closeModes: ["withdraw", "archive", "snooze"], changeFingerprint: "fp-1.me" } as unknown as AttentionItem, mine("m2", "addressee")] };
fixture.close.mockImplementationOnce(async () => { fixture.byView.mine = [mine("m2", "addressee")]; return { until: null }; });
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const menu = container.querySelector<HTMLElement>("[data-attention-close-menu]")!;
await act(async () => {
menu.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
menu.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await act(async () => document.querySelector<HTMLElement>('[data-attention-close-mode="archive"]')!.click()); await flush(); await flush();
expect(fixture.close).toHaveBeenCalledWith("company", "issue_thread_interaction", "m1", { mode: "archive", reason: undefined, until: undefined, fingerprint: "fp-1.me" });
expect(container.querySelector('[data-attention-card="m1"]')).toBeNull();
expect(container.querySelector('[data-attention-card="m2"]')).not.toBeNull();
// The server can return the same request after a snooze or content change.
fixture.byView.mine = [{ ...mine("m1", "addressee"), changeFingerprint: "fp-2.me" } as AttentionItem, mine("m2", "addressee")];
await act(async () => { await client.invalidateQueries({ queryKey: ["attention", "company"] }); });
await flush();
expect(container.querySelector('[data-attention-card="m1"]')).not.toBeNull();
client.clear();
});
it("retries a failed run inline instead of only linking to it (Rule 7)", async () => {
fixture.url = "/decisions?view=company";
fixture.byView = { company: [{ id: "failed", sourceKind: "failed_run", inlineResolvable: true, decisionVerbs: [{ id: "retry", label: "Retry" }, { id: "inspect", label: "Open run" }],
subject: { id: "run-7", kind: "run", title: "Nightly sync failed", href: "/PAP/agents/a/runs/run-7", metadata: { issueId: "task-7" } },
relatedIssue: { id: "task-7", identifier: "PAP-7", title: "Nightly sync", href: "/PAP/issues/PAP-7" }, closeModes: ["archive", "snooze"],
activityAt: new Date().toISOString(), audience: { kind: "company", userId: null, reason: "none" } } as unknown as AttentionItem] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
expect(container.textContent).not.toContain("Open to review");
// PAP-775: View run, then the primary Retry run last.
const card = container.querySelector<HTMLElement>('[data-attention-card="failed"]')!;
expect([...card.querySelectorAll("a, button")].map((entry) => entry.textContent).slice(-2)).toEqual(["View run", "Retry run"]);
await click("Retry run");
expect(fixture.retryTask).toHaveBeenCalledWith("task-7", { idempotencyKey: expect.any(String), observedRunId: "run-7" });
client.clear();
});
it("explains when retry does not start new work", async () => {
fixture.url = "/decisions?view=company";
fixture.retryTask.mockResolvedValueOnce({ accepted: false, requestId: "stale", stale: true, presentation: null });
fixture.byView = { company: [{ id: "stale-run", sourceKind: "failed_run", inlineResolvable: true,
subject: { id: "run-old", kind: "run", title: "Previous attempt", metadata: { issueId: "task-old" } },
relatedIssue: { id: "task-old", identifier: "PAP-7", href: "/PAP/issues/PAP-7" }, activityAt: new Date().toISOString(),
audience: { kind: "company", userId: null, reason: "none" } } as unknown as AttentionItem] };
const client = await renderPage(fixture.url);
await click("Retry run");
expect(container.textContent).toContain("Retry did not start new work");
expect(container.textContent).not.toContain("A retry is already running");
client.clear();
});
it("shows what others did with your requests as Updates cards you can dismiss (PAP-749 plan §6, PAP-775)", async () => {
fixture.byView = { mine: [mine("m1", "addressee")] };
fixture.receipts = [{ id: "receipt-1", dismissalKey: "receipt:1", outcome: "approved", sourceKind: "approval", sourceId: "appr-9", title: "Hire a designer",
reason: null, actorUserId: "dotta", transferredToUserId: null, issue: null, href: "/PAP/approvals/appr-9",
createdAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() }];
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
await vi.waitFor(() => expect(container.querySelector('[data-attention-receipt="approved"]')).not.toBeNull());
expect(container.querySelector("[data-needs-you-summary]")?.textContent).toBe("1 decision · 1 update");
expect(container.querySelector('[data-needs-you-section="updates"]')?.textContent).toBe("Updates");
// No collapsed "N updates on your requests" line any more.
expect(container.textContent).not.toContain("updates on your requests");
const update = container.querySelector<HTMLElement>('[data-attention-receipt="approved"]')!;
expect(update.textContent).toContain("View a request update");
expect(update.querySelector("h2")?.textContent).toBe("Hire a designer");
expect(update.querySelector("[data-needs-you-panel]")?.textContent).toBe("Approved by Dotta");
// Updates are not in the badge and have no ⋯ menu.
expect(update.querySelector("[data-attention-close-menu]")).toBeNull();
expect([...update.querySelectorAll("button")].map((button) => button.textContent)).toEqual(["Dismiss", "View request"]);
await act(async () => [...update.querySelectorAll("button")].find((button) => button.textContent === "View request")!.click());
expect(fixture.navigate).toHaveBeenCalledWith("/PAP/approvals/appr-9");
await act(async () => [...update.querySelectorAll("button")].find((button) => button.textContent === "Dismiss")!.click()); await flush();
expect(dismissals.dismiss).toHaveBeenCalledWith("company", "receipt:1");
client.clear();
});
it("shows one card for each obligation, with the rest folded in as evidence (PAP-749 task 2d)", async () => {
const now = new Date().toISOString();
const forMe = { kind: "user", userId: "reviewer", reason: "instigator" };
const run = { id: "failed", sourceKind: "failed_run", inlineResolvable: true, decisionVerbs: [{ id: "retry", label: "Retry" }, { id: "inspect", label: "Open run" }],
subject: { id: "run-7", kind: "run", title: "Flaky Runner run failed", href: "/PAP/agents/a/runs/run-7", metadata: { issueId: "task-7" } },
relatedIssue: { id: "task-7", identifier: "PAP-7", title: "Nightly sync", href: "/PAP/issues/PAP-7" }, closeModes: ["archive", "snooze"],
obligationKey: "blocked:task-7", obligationLeadId: "failed", activityAt: now, audience: forMe } as unknown as AttentionItem;
const blocked = { id: "blocked", sourceKind: "blocker_attention", inlineResolvable: false, whyNow: "Automatic retries exhausted. Retry or reassign the task.",
subject: { id: "task-7", kind: "issue", identifier: "PAP-7", title: "Nightly sync", href: "/PAP/issues/PAP-7" }, relatedIssue: null, closeModes: ["archive", "snooze"],
obligationKey: "blocked:task-7", obligationLeadId: "failed", activityAt: now, audience: forMe } as unknown as AttentionItem;
const approval = { id: "approval", sourceKind: "approval", inlineResolvable: false, whyNow: "Approval is pending a board decision.",
subject: { id: "appr-1", kind: "approval", title: "Approve the launch", href: "/PAP/approvals/appr-1", metadata: { issueId: "task-8" } }, relatedIssue: null,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: "approval:appr-1", obligationLeadId: "approval", activityAt: now, audience: forMe } as unknown as AttentionItem;
const review = { id: "review", sourceKind: "review", inlineResolvable: false, whyNow: "Issue is in review with a linked pending approval.",
subject: { id: "task-8", kind: "issue", identifier: "PAP-8", title: "Launch page", href: "/PAP/issues/PAP-8" }, relatedIssue: null, closeModes: ["archive", "snooze"],
obligationKey: "approval:appr-1", obligationLeadId: "approval", activityAt: now, audience: forMe } as unknown as AttentionItem;
fixture.byView = { mine: [run, blocked, approval, review] };
fixture.viewCounts = { mine: 2, unassigned: 0, company: 0 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
// Two obligations, two cards; the evidence cards are never cards of their own.
// By type, the approval's decision comes before the run's problem (PAP-775).
expect([...container.querySelectorAll("[data-attention-card]")].map((card) => card.getAttribute("data-attention-card"))).toEqual(["approval", "failed"]);
expect([...container.querySelectorAll("[data-needs-you-section]")].map((section) => section.getAttribute("data-needs-you-section"))).toEqual(["problems"]);
const runCard = container.querySelector<HTMLElement>('[data-attention-card="failed"]')!;
expect(runCard.querySelector('[data-attention-evidence="blocked"]')?.textContent)
.toBe("Blocked by this run: PAP-7 Nightly sync — Automatic retries exhausted. Retry or reassign the task.");
const approvalCard = container.querySelector<HTMLElement>('[data-attention-card="approval"]')!;
expect(approvalCard.querySelector('[data-attention-evidence="review"]')?.textContent)
.toBe("Task waiting on this approval: PAP-8 Launch page — Issue is in review with a linked pending approval.");
expect(approvalCard.querySelector('[data-attention-evidence="review"] a')?.getAttribute("href")).toBe("/PAP/issues/PAP-8");
for (const card of [runCard, approvalCard]) {
const evidence = card.querySelector("[data-attention-evidence]")!;
const footer = card.querySelector("[data-decision-footer]")!;
expect(evidence.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
}
// The run keeps the one action for the blocked work.
await click("Retry");
expect(fixture.retryTask).toHaveBeenCalledWith("task-7", { idempotencyKey: expect.any(String), observedRunId: "run-7" });
client.clear();
});
const boardMember = (membershipRole: string) => ({ userId: "reviewer", source: "session", isInstanceAdmin: false, companyIds: ["company"],
memberships: [{ companyId: "company", membershipRole, status: "active" }] });
it("opens Everyone for a board member, names another person's card and asks before withdrawing it (PAP-768)", async () => {
fixture.boardAccess = boardMember("admin");
fixture.url = "/decisions?view=all";
const dottas = { ...mine("d1", "instigator"), audience: { kind: "user", userId: "dotta", reason: "instigator" }, closeModes: ["withdraw", "archive", "snooze"],
subject: { id: "d1", kind: "interaction", title: "Dotta's confirmation", metadata: { issueId: "task-d1" } } } as unknown as AttentionItem;
fixture.byView = { all: [mine("m1", "addressee"), dottas] };
fixture.viewCounts = { mine: 1, unassigned: 0, company: 0, archived: 0, all: 2 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
// PAP-775: Everyone is "All assignees" in the toolbar's assignee filter, and
// "Assigned to you" returns to the page.
const assignee = () => container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
await vi.waitFor(() => expect(assignee().value).toBe("all"));
expect(assignee().selectedOptions[0]?.textContent).toBe("All assignees");
expect(container.querySelector("[data-needs-you-summary]")?.textContent).toBe("2 decisions");
expect(fixture.listCalls).toContainEqual({ all: true, view: "all" });
expect(client.getQueryCache().find({ queryKey: ["attention", "company", "reviewer", "all"], exact: false })).toBeTruthy();
const card = container.querySelector<HTMLElement>('[data-attention-card="d1"]')!;
expect(card.querySelector("[data-attention-type-label]")?.textContent).toBe("@Dotta Confirm or decline");
expect(card.querySelector("[data-attention-for-user]")?.textContent).toBe("@Dotta ");
expect(container.querySelector('[data-attention-card="m1"] [data-attention-for-user]')).toBeNull();
const menu = card.querySelector<HTMLElement>("[data-attention-close-menu]")!;
await act(async () => {
menu.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
menu.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await act(async () => document.querySelector<HTMLElement>('[data-attention-close-mode="withdraw"]')!.click()); await flush();
const dialog = document.querySelector<HTMLElement>("[data-attention-withdraw-dialog]")!;
expect(dialog.textContent).toContain("This is for @Dotta. Withdraw anyway?");
expect(fixture.close).not.toHaveBeenCalled();
await act(async () => [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Withdraw request")!.click());
await flush(); await flush();
expect(fixture.close).toHaveBeenCalledWith("company", "issue_thread_interaction", "d1", expect.objectContaining({ mode: "withdraw" }));
expect(container.querySelector('[data-attention-card="d1"]')).toBeNull();
client.clear();
});
it("keeps Everyone from a viewer: no tab, and ?view=all opens For you (PAP-768)", async () => {
fixture.boardAccess = boardMember("viewer");
fixture.url = "/decisions?view=all";
fixture.byView = { mine: [mine("m1", "addressee")], all: [mine("m1", "addressee"), mine("m2", "addressee")] };
fixture.viewCounts = { mine: 1, unassigned: 0, company: 0, archived: 0, all: 2 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client); await flush();
// A viewer has no Everyone — ?view=all falls back to For you (the page), and
// the assignee filter offers no "All assignees" and no other people (PAP-775).
const assignee = container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
expect(assignee.value).toBe("me");
expect([...assignee.options].map((option) => option.textContent)).toEqual(["Assigned to you", "No owner yet", "Company alerts"]);
expect(container.querySelector('[data-attention-view="all"]')).toBeNull();
expect(fixture.listCalls.some((call) => (call as { view?: string }).view === "all")).toBe(false);
client.clear();
});
it("shows a budget hard stop and its override approval as one card with Increase limit and Keep paused (PAP-768)", async () => {
const now = new Date().toISOString();
const owner = { kind: "user", userId: "reviewer", reason: "budget_owner", alsoInCompany: true };
const stop = { id: "stop", sourceKind: "budget_alert", inlineResolvable: true, whyNow: "Budget hard stop was reached.",
decisionVerbs: [{ id: "raise_budget_and_resume", label: "Raise limit" }, { id: "keep_paused", label: "Keep paused" }],
subject: { id: "incident-1", kind: "budget_incident", title: "Spendy Agent budget hard stop", href: "/PAP/costs", metadata: { thresholdType: "hard", amountObserved: 10_000, amountLimit: 10_000, approvalId: "appr-b" } },
detail: { kind: "budget", observedPercent: 100, amountObserved: 10_000, amountLimit: 10_000, images: [] },
relatedIssue: null, closeModes: ["archive", "snooze"], obligationKey: "approval:appr-b", obligationLeadId: "stop", activityAt: now, audience: owner } as unknown as AttentionItem;
const approval = { id: "approval-b", sourceKind: "approval", inlineResolvable: true, whyNow: "Approval is pending a board decision.",
decisionVerbs: [{ id: "approve", label: "Approve" }, { id: "reject", label: "Reject" }],
subject: { id: "appr-b", kind: "approval", title: "budget override required", href: "/PAP/approvals/appr-b", metadata: { type: "budget_override_required" } }, relatedIssue: null,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: "approval:appr-b", obligationLeadId: "stop", activityAt: now, audience: owner } as unknown as AttentionItem;
fixture.byView = { mine: [stop, approval] };
fixture.viewCounts = { mine: 1, unassigned: 0, company: 1, archived: 0, all: 1 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
expect([...container.querySelectorAll("[data-attention-card]")].map((card) => card.getAttribute("data-attention-card"))).toEqual(["stop"]);
const card = container.querySelector<HTMLElement>('[data-attention-card="stop"]')!;
expect(card.querySelector('[data-attention-evidence="approval-b"]')?.textContent).toBe("Approval this answers: budget override required — Approval is pending a board decision.");
expect(card.querySelector("[data-attention-type-label]")?.textContent).toBe("Resolve a budget stop");
const buttons = () => [...card.querySelectorAll("button")].map((button) => button.textContent);
// PAP-775: the new limit is asked for only once you choose to increase it; the primary action is last.
expect(buttons().slice(-2)).toEqual(["Keep paused", "Increase limit…"]);
expect(card.querySelector('input[inputmode="decimal"]')).toBeNull();
await click("Increase limit…");
expect(card.querySelector('input[inputmode="decimal"]')).not.toBeNull();
expect(buttons().slice(-3)).toEqual(["Keep paused", "Cancel", "Raise limit & resume"]);
// The approval's own Approve / Reject would skip the budget; they are not offered.
expect(buttons()).not.toContain("Approve");
expect(buttons()).not.toContain("Reject");
// Keep paused answers the stop, which rejects its approval on the server.
await click("Keep paused");
expect(fixture.resolveIncident).toHaveBeenCalledWith("company", "incident-1", { action: "keep_paused" });
client.clear();
});
it("shows a view-specific empty state", async () => {
fixture.url = "/decisions?view=unassigned";
fixture.byView = { unassigned: [] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
expect(container.textContent).toContain("No cards need an owner.");
client.clear();
});
it("opens a plan card's plan as a side-panel tab and closes the tab again (PAP-770)", async () => {
fixture.pending = [{ ...fixture.pending[0], subject: { ...fixture.pending[0].subject, metadata: { issueId: "task-1", targetDocumentKey: "plan" } } }, fixture.pending[1]];
const client = await renderPage();
// PAP-775 (IA5): the plan opens from a row in the card's panel, not a footer button.
const row = (verb: "Open" | "Close") => container.querySelector<HTMLElement>(`button[aria-label="${verb} Plan in the sidebar"]`);
expect(container.querySelectorAll('button[aria-label$="in the sidebar"]')).toHaveLength(1);
expect(row("Open")?.textContent).toBe("PlanOpen in sidebar");
await act(async () => row("Open")!.click()); await flush();
expect(fixture.setPanelVisible).toHaveBeenLastCalledWith(true);
expect(row("Close")?.textContent).toBe("PlanOpen in sidebar · Showing");
const panel = fixture.openPanel.mock.calls.at(-1)?.[0] as { props: { tabs: Array<{ id: string; label: string }>; activeTabId: string; reviewable: AttentionItem[] } };
expect(panel.props.tabs).toEqual([expect.objectContaining({ id: `review:${fixture.pending[0].id}` })]);
expect(panel.props.activeTabId).toBe(`review:${fixture.pending[0].id}`);
// The + launcher offers every card with a document to review.
expect(panel.props.reviewable.map(item => item.id)).toEqual([fixture.pending[0].id]);
expect(container.querySelector("[data-reviewing]")).toBeTruthy();
await act(async () => row("Close")!.click()); await flush();
expect(row("Open")).not.toBeNull();
const after = fixture.openPanel.mock.calls.at(-1)?.[0] as { props: { tabs: unknown[] } };
expect(after.props.tabs).toEqual([]);
expect(container.querySelector("[data-reviewing]")).toBeNull();
client.clear();
});
it("shows who is asking, why it is yours, and the task's status before its ID (UI2, UI3, UI5, A3)", async () => {
fixture.byView = { mine: [{ ...mine("m1", "addressee"), requester: { kind: "agent", id: "agent-cos", name: "Chief of Staff" },
relatedIssue: { id: "task-m1", identifier: "PAP-21", title: "Launch", status: "in_progress", href: "/PAP/issues/PAP-21" } } as unknown as AttentionItem,
{ ...mine("m2", "assignee"), requester: { kind: "user", id: "dotta", name: null } } as unknown as AttentionItem] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const agentCard = container.querySelector<HTMLElement>('[data-attention-card="m1"]')!;
expect(agentCard.querySelector('[data-attention-requester="agent"]')?.textContent).toBe("from Chief of Staff");
// Your own card says why in the type label's tooltip, never your own name (PAP-775).
const label = agentCard.querySelector<HTMLElement>("[data-attention-type-label]")!;
expect(label.textContent).toBe("Confirm or decline");
expect(label.title).toBe("Why me? Sent to you");
expect(agentCard.querySelector('[data-attention-audience]')).toBeNull();
expect(agentCard.querySelector("[data-attention-for-user]")).toBeNull();
// The footer's task link: status icon, then "ID · title", then ↗.
const link = agentCard.querySelector<HTMLElement>("[data-attention-task-link]")!;
expect(link.querySelector('[title="In Progress"], [aria-label="In Progress"]')).not.toBeNull();
expect(link.textContent).toMatch(/^In Progress.*PAP-21 · Launch$/);
const personCard = container.querySelector<HTMLElement>('[data-attention-card="m2"]')!;
expect(personCard.querySelector('[data-attention-requester="user"]')?.textContent).toContain("from Dotta");
client.clear();
});
it("omits the requester avatar and line when the viewer made the request", async () => {
fixture.byView = { mine: [{ ...mine("own", "addressee"), requester: { kind: "user", id: "reviewer", name: "Dotta" } } as unknown as AttentionItem] };
const client = await renderPage();
expect(container.querySelector('[data-attention-requester="user"]')).toBeNull();
client.clear();
});
it("says No owner yet with Claim on an ownerless card (A2)", async () => {
fixture.url = "/decisions?view=unassigned";
fixture.byView = { unassigned: [pool] };
fixture.viewCounts = { mine: 0, unassigned: 1, company: 0 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const corner = container.querySelector<HTMLElement>('[data-attention-audience="pool"]')!;
expect(corner.textContent).toBe("No owner yetClaim");
client.clear();
});
it("puts problems under a Problems heading apart from decisions, in words and not colour alone (IA7, UI6)", async () => {
fixture.byView = { mine: [{ ...company, id: "run", inlineResolvable: false, audience: { kind: "user", userId: "reviewer", reason: "assignee" } } as unknown as AttentionItem, mine("decision", "addressee")] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const kinds = Object.fromEntries([...container.querySelectorAll("[data-attention-card]")].map((card) => [card.getAttribute("data-attention-card"), [card.getAttribute("data-card-kind"), card.getAttribute("data-card-type")]]));
expect(kinds).toEqual({ decision: ["decision", "confirm"], run: ["problem", "failed_run"] });
// Counts live in one line; the later Problems group keeps its own label.
const sections = [...container.querySelectorAll<HTMLElement>("[data-needs-you-section]")];
expect(sections.map((section) => section.textContent)).toEqual(["Problems"]);
expect(container.querySelector("[data-needs-you-summary]")?.textContent).toBe("1 decision · 1 problem");
// In document order, each card sits under its section's heading.
expect([...container.querySelectorAll("[data-needs-you-section], [data-attention-card]")].map((node) => node.getAttribute("data-needs-you-section") ?? node.getAttribute("data-attention-card")))
.toEqual(["decision", "problems", "run"]);
// The heading is the signal; the card carries no "Problem" label of its own.
expect(container.querySelector("[data-attention-problem]")).toBeNull();
expect(container.querySelector('[data-attention-card="run"] [data-attention-type-label]')?.textContent).toBe("Fix a failed run");
client.clear();
});
it("filters cards by who they are for from the toolbar (PAP-775)", async () => {
fixture.boardAccess = boardMember("admin");
fixture.url = "/decisions?view=all";
const dottas = { ...mine("d1", "instigator"), audience: { kind: "user", userId: "dotta", reason: "instigator" },
subject: { id: "d1", kind: "interaction", title: "Dotta's confirmation", metadata: { issueId: "task-d1" } } } as unknown as AttentionItem;
fixture.byView = { all: [mine("m1", "addressee"), dottas, pool] };
fixture.viewCounts = { mine: 1, unassigned: 1, company: 0, archived: 0, all: 3 };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const assignee = () => container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
const choose = async (value: string) => { await act(async () => { assignee().value = value; assignee().dispatchEvent(new Event("change", { bubbles: true })); }); await flush(); };
const cards = () => [...container.querySelectorAll("[data-attention-card]")].map(card => card.getAttribute("data-attention-card"));
await vi.waitFor(() => expect(assignee().value).toBe("all"));
// The viewer is "Assigned to you", never a person option of their own.
expect([...assignee().options].map(option => [option.value, option.textContent])).toEqual([
["me", "Assigned to you"], ["all", "All assignees"], ["user:dotta", "Dotta"], ["unassigned", "No owner yet"], ["company", "Company alerts"]]);
expect(cards()).toEqual(["m1", "d1", "pool"]);
// One person narrows Everyone, and the person lives in the URL.
await choose("user:dotta");
expect(container.querySelector("[data-location]")?.textContent).toBe("?view=all&for=dotta");
expect(assignee().value).toBe("user:dotta");
expect(cards()).toEqual(["d1"]);
// Back to everyone drops the person.
await choose("all");
expect(container.querySelector("[data-location]")?.textContent).toBe("?view=all");
expect(cards()).toEqual(["m1", "d1", "pool"]);
// "Assigned to you" is the page itself.
await choose("me");
expect(container.querySelector("[data-location]")?.textContent).toBe("");
client.clear();
});
it("defaults the assignee filter to Assigned to you in For you, where every card is yours (PAP-775)", async () => {
fixture.byView = { mine: [mine("m1", "addressee"), mine("m2", "assignee")] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
await vi.waitFor(() => expect(container.querySelector('[data-attention-card="m2"]')).toBeTruthy());
const assignee = container.querySelector<HTMLSelectElement>('select[aria-label="Filter decisions by assignee"]')!;
expect(assignee.value).toBe("me");
expect(assignee.getAttribute("data-attention-assignee")).toBe("me");
// The old "For anyone" filter is gone.
expect(container.querySelector("[data-attention-audience-filter]")).toBeNull();
expect(container.querySelector("[data-needs-you-summary]")?.textContent).toBe("2 decisions");
client.clear();
});
it("opens a document a card links to as its own side-panel tab, tied to the card (PAP-775, IA5)", async () => {
const approval = { id: "approval", sourceKind: "approval", inlineResolvable: true, whyNow: "Approval is pending a board decision.",
subject: { id: "appr-1", kind: "approval", title: "Hire a designer", href: "/PAP/approvals/appr-1", metadata: {} }, relatedIssue: null,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: null, obligationLeadId: null, activityAt: new Date().toISOString(),
audience: { kind: "user", userId: "reviewer", reason: "requester" } } as unknown as AttentionItem;
fixture.byView = { mine: [approval] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const card = container.querySelector<HTMLElement>('[data-attention-card="approval"]')!;
const link = document.createElement("a");
link.href = "/PAP/issues/PAP-12#document-design";
link.textContent = "design notes";
card.querySelector("h2")!.after(link);
await act(async () => link.click()); await flush();
const panel = fixture.openPanel.mock.calls.at(-1)?.[0] as { props: { tabs: Array<{ id: string; type: string; payload: { itemId: string; artifact?: unknown } }>; activeTabId: string } };
expect(panel.props.tabs).toEqual([expect.objectContaining({ id: "review:approval:document:PAP-12:design", type: "design notes",
payload: { kind: "review", itemId: "approval", artifact: { kind: "document", issueId: "PAP-12", key: "design", title: "design notes" } } })]);
expect(panel.props.activeTabId).toBe("review:approval:document:PAP-12:design");
// The card is highlighted while something it mentions is open (UI9).
expect(card.getAttribute("data-reviewing")).toBe("true");
client.clear();
});
it("approves an approval on the card and opens it in the side panel (UX1, IA5)", async () => {
const approval = { id: "approval", sourceKind: "approval", inlineResolvable: true, whyNow: "Approval is pending a board decision.",
decisionVerbs: [{ id: "approve", label: "Approve" }, { id: "reject", label: "Reject" }],
subject: { id: "appr-1", kind: "approval", title: "Hire a designer", href: "/PAP/approvals/appr-1", metadata: {} }, relatedIssue: null,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: null, obligationLeadId: null, activityAt: new Date().toISOString(),
audience: { kind: "user", userId: "reviewer", reason: "requester" } } as unknown as AttentionItem;
fixture.byView = { mine: [approval] };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await render(client);
const card = container.querySelector<HTMLElement>('[data-attention-card="approval"]')!;
expect(card.querySelector("h2")?.textContent).toBe("Approve “Hire a designer”?");
expect(card.textContent).not.toContain("Open to review");
expect(card.querySelector("[data-attention-type-label]")?.textContent).toBe("Approve a request");
// PAP-775: View details · Reject · Approve, primary last; the note and Request
// revision stay in the side panel.
const footer = [...card.querySelectorAll("button")].map((button) => button.textContent).filter((text) => ["View details", "Reject", "Approve"].includes(text ?? ""));
expect(footer).toEqual(["View details", "Reject", "Approve"]);
expect(card.querySelector("textarea")).toBeNull();
expect(card.textContent).not.toContain("Request revision");
await act(async () => [...card.querySelectorAll("button")].find((button) => button.textContent === "View details")!.click()); await flush();
const panel = fixture.openPanel.mock.calls.at(-1)?.[0] as { props: { tabs: Array<{ id: string; type: string }> } };
expect(panel.props.tabs).toEqual([expect.objectContaining({ id: "review:approval", type: "Approval" })]);
await act(async () => [...card.querySelectorAll("button")].find((button) => button.textContent === "Approve")!.click()); await flush();
expect(approvals.approve).toHaveBeenCalledWith("appr-1", undefined);
client.clear();
});
});
@@ -1,10 +1,10 @@
import { useQueryView } from "@/components/QueryView";
import { useCallback, useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { ArrowUpRight, History, Loader2 } from "lucide-react";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { useCallback, useEffect, useMemo, useState, type MouseEvent as ReactMouseEvent } from "react";
import { useQuery } from "@tanstack/react-query";
import { ArrowLeft, ArrowUpRight, ChevronDown, FileText, Image as ImageIcon, Loader2 } from "lucide-react";
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
import type { Agent, AttentionItem, DecisionHistoryItem } from "@paperclipai/shared";
import { attentionCardType, type AttentionCloseMode, type AttentionItem, type AttentionPersonalView } from "@paperclipai/shared";
import { accessApi } from "@/api/access";
import { attentionApi } from "@/api/attention";
import { agentsApi } from "@/api/agents";
import { useCompany } from "@/context/CompanyContext";
@@ -12,175 +12,253 @@ import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { usePanel } from "@/context/PanelContext";
import { useSidebar } from "@/context/SidebarContext";
import { useCoordinatorWorkspaceEnabled } from "@/hooks/useCoordinatorWorkspaceEnabled";
import { useAttentionBadge, useAttentionCloseActions, useAttentionEveryoneView, useAttentionViewFeed, useClaimAttentionItem, useDismissAttentionReceipt } from "@/hooks/useAttentionViews";
import { useNavigate, useSearchParams } from "@/lib/router";
import { queryKeys } from "@/lib/queryKeys";
import { coordinatorAttentionQueryKey, COORDINATOR_RECENT_DECISION_MS, recentDecisionReceipts } from "@/lib/coordinator-attention";
import { COORDINATOR_ASSIGNEE_PARAM, COORDINATOR_RECENT_DECISION_MS, DEFAULT_DECISION_HISTORY_SCOPE, coordinatorAssignee, coordinatorAssigneeTarget, coordinatorAudienceKey, coordinatorCardDetail, coordinatorCardTitle, recentDecisionReceipts, type CoordinatorAssignee } from "@/lib/coordinator-attention";
import { attentionDetailLine, isInlineResolvable } from "@/lib/attention";
import { ATTENTION_VIEW_PARAM, attentionAudienceLineNamesResponders, parseAttentionView } from "@/lib/attention-views";
import { splitArchivedAttentionItems, splitStaleAttentionItems } from "@/lib/attention-close";
import { attentionObligationEvidence, foldAttentionObligations } from "@/lib/attention-obligations";
import { buildCompanyUserLabelMap } from "@/lib/company-members";
import { AttentionCloseMenu, AttentionForOtherGate, AttentionHiddenChip, AttentionSnoozedGroup, AttentionStaleChip, AttentionStaleGroup } from "@/components/AttentionCloseMenu";
import { BudgetAlertActions, FailedRunActions } from "@/components/AttentionInlineVerbs";
import { AttentionInteractionResolver } from "@/components/AttentionInteractionResolver";
import { StalledReviewActions } from "@/components/StalledReviewActions";
import { ApprovalResolver, JoinRequestResolver } from "@/components/AttentionQueueRow";
import { AttentionObligationEvidence } from "@/components/AttentionObligationEvidence";
import { DecisionHistoryPanel } from "@/components/DecisionHistoryPanel";
import { DecisionResolver } from "@/components/DecisionResolver";
import { PROPERTIES_PANE_HEADER_SLOT_ID } from "@/components/PropertiesPanel";
import { SidePanelTab } from "@/components/side-panel";
import { DecisionCardFooter } from "@/components/DecisionCardFooter";
import { useSidePanelTabs } from "@/components/side-panel";
import { ToolbarSearch } from "@/components/ToolbarSearch";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { NativeSelect } from "@/components/ui/select";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { parseCssTimeMs } from "@/components/task-chat/motion-tokens";
import { readIssueReviewPolicyMetadata } from "@/lib/review-policy";
import { timeAgo } from "@/lib/timeAgo";
import { CoordinatorDecisionReceipt as Receipt } from "./CoordinatorDecisionReceipt";
import { CoordinatorTaskMotion } from "./CoordinatorTaskCommitment";
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { CoordinatorReviewPanel, needsYouArtifact, needsYouArtifactLabel, needsYouMentionedArtifact, type NeedsYouArtifact } from "./CoordinatorReviewPanel";
import { BlockedTaskCardBody, RecoveryCardBody, ReviewTaskCardBody } from "./NeedsYouCardBodies";
import { NEEDS_YOU_SECTIONS, NeedsYouPanelRow, needsYouSection, type NeedsYouSection } from "./NeedsYouCardKit";
import { NeedsYouAudience, NeedsYouReceiptCard, NeedsYouRequester, NeedsYouTaskLink, NeedsYouTypeLabel, needsYouTaskRef } from "./NeedsYouCardParts";
import { CoordinatorNeedsYouSidePanel, needsYouReviewTab, needsYouReviewTabId, needsYouTabArtifact, type NeedsYouReviewPayload } from "./CoordinatorNeedsYouSidePanel";
type Group = "none" | "task" | "agent" | "project";
type Group = "type" | "none" | "task" | "agent" | "project";
function HistoryPanel({ companyId, agents, onClose, mobile = false }: { companyId: string; agents: Agent[]; onClose: () => void; mobile?: boolean }) {
const navigate = useNavigate();
const [search, setSearch] = useState("");
const [outcome, setOutcome] = useState("");
const [agentId, setAgentId] = useState("");
const [projectId, setProjectId] = useState("");
const [groupBy, setGroupBy] = useState<Group>("none");
const [sort, setSort] = useState<"newest" | "oldest">("newest");
const projects = useQuery({ ...companyProjectsQuery(companyId) });
const history = useInfiniteQuery({
queryKey: [...queryKeys.attention(companyId), "history", { search, outcome, agentId, projectId, sort }],
queryFn: ({ pageParam }) => attentionApi.history(companyId, { search, outcome, agentId, projectId, sort, cursor: pageParam, limit: 40 }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (page) => page.nextCursor ?? undefined,
});
const historyView = useQueryView(history);
const historyWaiting = ["loading", "reconnecting"].includes(historyView.kind);
const items = history.data?.pages.flatMap((page) => page.items) ?? [];
const groups = new Map<string, typeof items>();
for (const item of items) {
const label = groupBy === "task" ? item.issueIdentifier ?? item.issueTitle ?? "Other tasks" : groupBy === "agent" ? item.agentName ?? "Other agents" : groupBy === "project" ? item.projectName ?? "No project" : "";
groups.set(label, [...(groups.get(label) ?? []), item]);
}
const slot = typeof document !== "undefined" ? document.getElementById(PROPERTIES_PANE_HEADER_SLOT_ID) : null;
const tab = <SidePanelTab id="decision-history" label="Decision history" active onSelect={() => {}} onClose={onClose} />;
return <div className="space-y-5" data-coordinator-decision-history>
{!mobile ? <>{slot ? createPortal(tab, slot) : tab}<h2 className="text-lg font-medium">Decision history</h2></> : null}
<ToolbarSearch query={search} onQueryChange={setSearch} label="Search decision history" placeholder="Search decisions or task IDs…" />
<div className="grid grid-cols-2 gap-2">
<NativeSelect aria-label="Filter decision outcomes" value={outcome} onChange={(event) => setOutcome(event.target.value)}>
<option value="">All outcomes</option><option value="accepted">Approved</option><option value="answered">Answered</option><option value="rejected">Changes requested</option><option value="decided">Decided</option><option value="cancelled">Cancelled</option><option value="expired">Expired</option>
</NativeSelect>
<NativeSelect aria-label="Sort decision history" value={sort} onChange={(event) => setSort(event.target.value as typeof sort)}><option value="newest">Newest first</option><option value="oldest">Oldest first</option></NativeSelect>
<NativeSelect aria-label="Filter decision history by agent" value={agentId} onChange={(event) => setAgentId(event.target.value)} className="col-span-2"><option value="">All agents</option>{agents.map((agent) => <option key={agent.id} value={agent.id}>{agent.name}</option>)}</NativeSelect>
<NativeSelect aria-label="Filter decision history by project" value={projectId} onChange={(event) => setProjectId(event.target.value)} className="col-span-2"><option value="">All projects</option>{(projects.data ?? []).map((project) => <option key={project.id} value={project.id}>{project.name}</option>)}</NativeSelect>
<NativeSelect aria-label="Group decision history" value={groupBy} onChange={(event) => setGroupBy(event.target.value as Group)} className="col-span-2"><option value="none">No grouping</option><option value="task">By task</option><option value="agent">By agent</option><option value="project">By project</option></NativeSelect>
</div>
{historyWaiting ? <p role="status" className="text-sm text-muted-foreground">Loading decisions…</p> : null}
{(historyView.kind === "error") ? <div role="alert" className="space-y-2 text-sm"><p>Decision history could not be loaded.</p><Button variant="outline" onClick={() => void history.refetch()}>Retry</Button></div> : null}
{!historyWaiting && !(historyView.kind === "error") && !items.length ? <p className="text-sm text-muted-foreground">No decisions match these filters.</p> : null}
<div className="space-y-4">{[...groups].map(([label, entries]) => <section key={label} className="space-y-3">{label ? <h3 className="text-sm font-medium text-muted-foreground">{label}</h3> : null}{entries.map((item) => <div key={item.id} className="space-y-1"><Receipt item={item} onOpen={navigate} /><p className="px-1 text-xs text-muted-foreground"><time dateTime={item.resolvedAt}>{new Date(item.resolvedAt).toLocaleString()}</time></p></div>)}</section>)}</div>
{history.hasNextPage ? <Button variant="outline" disabled={history.isFetchingNextPage} onClick={() => void history.fetchNextPage()}>{history.isFetchingNextPage ? "Loading…" : "Load more decisions"}</Button> : null}
</div>;
/** Rule 7: a card that cannot answer inline links to the exact control, named by its verb. */
function openLabel(item: AttentionItem) {
return (item.decisionVerbs ?? []).find((verb) => verb.id === "open_recovery" || verb.id === "inspect")?.label ?? "Open to review";
}
/** Say each thing once (IA4): a quoted excerpt of the title is not a second line. */
function sameText(left: string, right: string) {
const plain = (text: string) => text.trim().replace(/^[“"']+|[”"']+$/g, "").replace(/[.\s]+$/, "").trim().toLocaleLowerCase();
const a = plain(left);
const b = plain(right);
return a === b || b.includes(`“${a}”`.toLocaleLowerCase()) || b.endsWith(a);
}
/** A document key as a name ("email-draft" → "Email draft") until its title loads. */
function documentKeyLabel(key: string) {
const words = key.replace(/[-_]+/g, " ").trim();
return words.charAt(0).toLocaleUpperCase() + words.slice(1);
}
const EMPTY_VIEW_TEXT: Record<AttentionPersonalView, string> = {
mine: "You're caught up.",
unassigned: "No cards need an owner.",
company: "No company alerts right now.",
archived: "Nothing archived. Cards you archive or snooze for yourself show here.",
all: "No open cards for anyone.",
};
export function CoordinatorNeedsYou() {
const { selectedCompanyId } = useCompany();
const { userId } = useCoordinatorWorkspaceEnabled();
const { setBreadcrumbs } = useBreadcrumbs();
const { openPanel, closePanel, setPanelVisible } = usePanel();
const { openPanel, closePanel, panelVisible, setPanelVisible } = usePanel();
const { isMobile } = useSidebar();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const deepLinkDecisionId = searchParams.get("decisionId");
// For you is the default; the other views live in the URL (PAP-749 Rule 3).
// Everyone opens for a board member only (PAP-768).
const everyone = useAttentionEveryoneView(selectedCompanyId);
const view = parseAttentionView(searchParams.get(ATTENTION_VIEW_PARAM), { everyone });
// Everyone can be narrowed to one person (PAP-775); the person lives in the URL too.
const forUserId = view === "all" ? searchParams.get(COORDINATOR_ASSIGNEE_PARAM) : null;
const setView = useCallback((next: typeof view, person: string | null = null) => setSearchParams(current => {
const params = new URLSearchParams(current);
if (next === "mine") params.delete(ATTENTION_VIEW_PARAM); else params.set(ATTENTION_VIEW_PARAM, next);
if (person) params.set(COORDINATOR_ASSIGNEE_PARAM, person); else params.delete(COORDINATOR_ASSIGNEE_PARAM);
return params;
}, { replace: true }), [setSearchParams]);
const assignee = coordinatorAssignee(view, forUserId);
const reducedMotion = useReducedMotion();
const [query, setQuery] = useState("");
const [agentFilter, setAgentFilter] = useState("");
const [projectFilter, setProjectFilter] = useState("");
const [groupBy, setGroupBy] = useState<Group>("none");
const [sort, setSort] = useState<"newest" | "oldest">("newest");
const [groupBy, setGroupBy] = useState<Group>("type");
const [historyOpen, setHistoryOpen] = useState(false);
// Focus (PAP-770): documents a card asks about open as side-panel tabs, the
// same chrome as task detail. Decision history is a main-pane view instead.
const reviewTabs = useSidePanelTabs<NeedsYouReviewPayload>({ initialState: { tabs: [], activeTabId: null } });
const [reviewPanelOpen, setReviewPanelOpen] = useState(false);
const [now, setNow] = useState(Date.now);
const [settling, setSettling] = useState<AttentionItem[]>([]);
const [savedIds, setSavedIds] = useState<Set<string>>(() => new Set());
useEffect(() => { setSettling([]); setSavedIds(new Set()); }, [selectedCompanyId, userId]);
const [savedIds, setSavedIds] = useState<Map<string, { version: number; fingerprint: string; closed: boolean }>>(() => new Map());
// The Stale (N) group starts collapsed in each view; the Archived view's
// Snoozed group starts open (PAP-749 plan §3).
const [staleOpen, setStaleOpen] = useState(false);
const [snoozedOpen, setSnoozedOpen] = useState(true);
useEffect(() => { setSettling([]); setSavedIds(new Map()); setStaleOpen(false); setSnoozedOpen(true); }, [selectedCompanyId, userId, view]);
const archivedView = view === "archived";
const [renderLimit, setRenderLimit] = useState(40);
const feed = useQuery({ queryKey: coordinatorAttentionQueryKey(selectedCompanyId!),
queryFn: () => attentionApi.list(selectedCompanyId!, { all: true }), enabled: !!selectedCompanyId, refetchOnWindowFocus: true });
// Keyed by person and view; the For you key is the one the badge reads.
const feed = useAttentionViewFeed(selectedCompanyId, view);
useEffect(() => {
setSavedIds(current => {
const pending = new Map([...current].filter(([, hidden]) => hidden.closed || hidden.version === feed.dataUpdatedAt));
return pending.size === current.size ? current : pending;
});
}, [feed.dataUpdatedAt]);
const feedView = useQueryView(feed);
const feedWaiting = ["loading", "reconnecting"].includes(feedView.kind);
const feedWaiting = feedView.kind === "loading" || feedView.kind === "reconnecting";
const { viewCounts } = useAttentionBadge(selectedCompanyId);
const claim = useClaimAttentionItem(selectedCompanyId);
const receiptActions = useDismissAttentionReceipt(selectedCompanyId);
const directory = useQuery({ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!), queryFn: () => accessApi.listUserDirectory(selectedCompanyId!), enabled: !!selectedCompanyId });
const userLabelMap = useMemo(() => buildCompanyUserLabelMap(directory.data?.users), [directory.data?.users]);
// A closed card leaves the list at once; a withdrawn one comes back as a
// receipt in Recent Decisions after the history refetch. In the Archived
// view a new snooze time keeps the card (it only changes group), and a
// restored card leaves it; elsewhere an Undo brings the card straight back.
const hideCard = useCallback((item: AttentionItem, closed = false) => {
setSavedIds(current => new Map(current).set(`${item.sourceKind}:${item.subject.id}`, { version: feed.dataUpdatedAt, fingerprint: item.changeFingerprint, closed }));
}, [feed.dataUpdatedAt]);
const showCard = useCallback((item: AttentionItem) => {
setSavedIds(current => { const next = new Map(current); next.delete(`${item.sourceKind}:${item.subject.id}`); return next; });
}, []);
const onCardClosed = useCallback((item: AttentionItem, mode: AttentionCloseMode) => {
if (archivedView && mode !== "withdraw") return;
hideCard(item, mode === "withdraw");
}, [archivedView, hideCard]);
const onCardRestored = useCallback((item: AttentionItem) => (archivedView ? hideCard : showCard)(item), [archivedView, hideCard, showCard]);
const closeActions = useAttentionCloseActions(selectedCompanyId, { userLabelMap, onClosed: onCardClosed, onRestored: onCardRestored });
const agentQuery = useQuery({ queryKey: queryKeys.agents.list(selectedCompanyId!), queryFn: () => agentsApi.list(selectedCompanyId!), enabled: !!selectedCompanyId });
// Full history lives in its own paginated tab. Only the newest bounded page
// is fetched here; its window expires visually without deleting any record.
const recent = useQuery({ queryKey: [...queryKeys.attention(selectedCompanyId!), "history", "recent"],
queryFn: () => attentionApi.history(selectedCompanyId!, { limit: 100, since: new Date(Date.now() - COORDINATOR_RECENT_DECISION_MS).toISOString() }), enabled: !!selectedCompanyId, refetchOnWindowFocus: true });
const recentView = useQueryView(recent);
// History has one home, the main-pane Decision history view (PAP-775, IA3/IA4).
// The newest page is read here only so an answered card can turn into its
// receipt in place before it leaves, and so a card already answered elsewhere
// never shows twice.
const recent = useQuery({ queryKey: [...queryKeys.attention(selectedCompanyId!), "history", "recent", DEFAULT_DECISION_HISTORY_SCOPE],
queryFn: () => attentionApi.history(selectedCompanyId!, { limit: 100, scope: DEFAULT_DECISION_HISTORY_SCOPE, since: new Date(Date.now() - COORDINATOR_RECENT_DECISION_MS).toISOString() }), enabled: !!selectedCompanyId, refetchOnWindowFocus: true });
const agentMap = useMemo(() => new Map((agentQuery.data ?? []).map((agent) => [agent.id, agent])), [agentQuery.data]);
const recentItems = useMemo(() => recentDecisionReceipts(recent.data?.items ?? [], now), [recent.data, now]);
const settlingIds = useMemo(() => new Set(settling.map(item => `${item.sourceKind}:${item.subject.id}`)), [settling]);
const visibleRecentItems = useMemo(() => recentItems.filter((item) => {
if (settlingIds.has(item.id)) return false;
if (agentFilter && item.agentId !== agentFilter) return false;
if (projectFilter && item.projectId !== projectFilter) return false;
return [item.title, item.issueTitle, item.issueIdentifier, item.agentName, item.projectName, item.label]
.join(" ").toLocaleLowerCase().includes(query.trim().toLocaleLowerCase());
}).sort((a, b) => (sort === "oldest" ? 1 : -1) * (Date.parse(a.resolvedAt) - Date.parse(b.resolvedAt))),
[recentItems, settlingIds, agentFilter, projectFilter, query, sort]);
const recentGroups = useMemo(() => {
const result = new Map<string, DecisionHistoryItem[]>();
for (const item of visibleRecentItems) {
const label = groupBy === "task" ? item.issueIdentifier ?? item.issueTitle ?? "Other tasks"
: groupBy === "agent" ? item.agentName ?? "Other agents"
: groupBy === "project" ? item.projectName ?? "No project" : "";
result.set(label, [...(result.get(label) ?? []), item]);
}
return [...result];
}, [visibleRecentItems, groupBy]);
// One card for each obligation (PAP-749 Rule 11): evidence folds into its
// lead before the page hides, splits or groups anything.
const obligations = useMemo(() => foldAttentionObligations(feed.data?.items ?? []), [feed.data]);
const pendingItems = useMemo(() => {
const receipts = new Set(recentItems.map((item) => item.id));
const items = new Map((feed.data?.items ?? []).map((item) => [`${item.sourceKind}:${item.subject.id}`, item]));
const items = new Map(obligations.cards.map((item) => [`${item.sourceKind}:${item.subject.id}`, item]));
for (const item of settling) if (!items.has(`${item.sourceKind}:${item.subject.id}`)) items.set(`${item.sourceKind}:${item.subject.id}`, item);
return [...items].filter(([key]) => settlingIds.has(key) || (!receipts.has(key) && !savedIds.has(key))).map(([, item]) => item);
}, [feed.data, settling, settlingIds, recentItems, savedIds]);
return [...items].filter(([key, item]) => {
const hidden = savedIds.get(key);
const locallyHidden = hidden && (hidden.closed ? hidden.fingerprint === item.changeFingerprint : hidden.version === feed.dataUpdatedAt);
return settlingIds.has(key) || (!receipts.has(key) && !locallyHidden);
}).map(([, item]) => item);
}, [obligations, settling, settlingIds, recentItems, savedIds, feed.dataUpdatedAt]);
const filtered = useMemo(() => pendingItems.filter((item) => {
const agentId = String(item.subject.metadata?.createdByAgentId ?? item.subject.metadata?.originAgentId ?? "");
if (agentFilter && agentId !== agentFilter && item.originAgentName !== agentMap.get(agentFilter)?.name) return false;
if (projectFilter && item.project?.id !== projectFilter) return false;
if (forUserId && coordinatorAudienceKey(item) !== `user:${forUserId}`) return false;
return [item.subject.title, item.relatedIssue?.title, item.relatedIssue?.identifier, item.originAgentName, item.project?.name, attentionDetailLine(item)].join(" ").toLocaleLowerCase().includes(query.trim().toLocaleLowerCase());
}).sort((a, b) => (sort === "oldest" ? 1 : -1) * (Date.parse(a.activityAt) - Date.parse(b.activityAt))), [pendingItems, agentFilter, projectFilter, query, sort, agentMap]);
}).sort((a, b) => Date.parse(b.activityAt) - Date.parse(a.activityAt)), [pendingItems, agentFilter, projectFilter, forUserId, query, agentMap]);
// Stale cards go to the collapsed group at the bottom of each view (Rule 10).
// The Archived view keeps stale cards in place with their chip, and puts
// snoozed cards in their own group (plan §3).
const { current: currentItems, stale: staleItems, snoozed: snoozedItems } = useMemo(() => {
if (archivedView) {
const { archived, snoozed } = splitArchivedAttentionItems(filtered);
return { current: archived, stale: [] as AttentionItem[], snoozed };
}
return { ...splitStaleAttentionItems(filtered), snoozed: [] as AttentionItem[] };
}, [archivedView, filtered]);
const groups = useMemo(() => {
const result = new Map<string, AttentionItem[]>();
for (const item of filtered.slice(0, renderLimit)) {
const label = groupBy === "task" ? item.relatedIssue?.identifier ?? item.relatedIssue?.title ?? "Other decisions"
for (const item of currentItems.slice(0, renderLimit)) {
const label = groupBy === "type" ? needsYouSection(item) : groupBy === "task" ? item.relatedIssue?.identifier ?? item.relatedIssue?.title ?? "Other decisions"
: groupBy === "agent" ? item.originAgentName ?? "Other agents" : groupBy === "project" ? item.project?.name ?? "No project" : "";
result.set(label, [...(result.get(label) ?? []), item]);
}
return [...result];
}, [filtered, groupBy, renderLimit]);
// By type, decisions come before problems (Paper "A · Compact cards").
return groupBy === "type" ? [...result].sort(([a], [b]) => (a === "decisions" ? 0 : 1) - (b === "decisions" ? 0 : 1)) : [...result];
}, [currentItems, groupBy, renderLimit]);
useEffect(() => {
if (!deepLinkDecisionId || !selectedCompanyId || !pendingItems.some(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId)) return;
if (!deepLinkDecisionId || !selectedCompanyId) return;
if (!pendingItems.some(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId)) {
if (!feedWaiting && everyone && view !== "all") setView("all");
return;
}
// A saved decision link takes precedence over local toolbar filters and the
// rendering window. Consume it only after its actual card has mounted.
if (query || agentFilter || projectFilter) { setQuery(""); setAgentFilter(""); setProjectFilter(""); return; }
const index = filtered.findIndex(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId);
if (forUserId) { setView("all"); return; }
if (staleItems.some(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId)) setStaleOpen(true);
const index = currentItems.findIndex(item => item.sourceKind === "decision" && item.subject.id === deepLinkDecisionId);
if (index >= renderLimit) { setRenderLimit(Math.ceil((index + 1) / 40) * 40); return; }
const card = document.getElementById(`coordinator-decision-${deepLinkDecisionId}`);
if (!card) return;
card.focus({ preventScroll: true });
card.scrollIntoView({ block: "center", behavior: reducedMotion ? "auto" : "smooth" });
setSearchParams(current => { const next = new URLSearchParams(current); next.delete("decisionId"); return next; }, { replace: true });
}, [deepLinkDecisionId, selectedCompanyId, pendingItems, filtered, query, agentFilter, projectFilter, renderLimit, reducedMotion, setSearchParams]);
}, [deepLinkDecisionId, selectedCompanyId, pendingItems, currentItems, staleItems, feedWaiting, everyone, view, query, agentFilter, projectFilter, forUserId, setView, renderLimit, reducedMotion, setSearchParams]);
const projects = useMemo(() => [...new Map([
...pendingItems.flatMap((item) => item.project ? [[item.project.id, item.project.name] as const] : []),
...recentItems.flatMap((item) => item.projectId ? [[item.projectId, item.projectName ?? "Unnamed project"] as const] : []),
]).entries()], [pendingItems, recentItems]);
const filtersActive = Boolean(query.trim() || agentFilter || projectFilter);
const closeHistory = useCallback(() => { setHistoryOpen(false); closePanel(); }, [closePanel]);
const showHistory = () => { setHistoryOpen(true); if (!isMobile) setPanelVisible(true); };
useEffect(() => { setBreadcrumbs([{ label: "Inbox" }]); }, [setBreadcrumbs]);
useEffect(() => {
setSettling([]); setHistoryOpen(false); setNow(Date.now()); closePanel();
return closePanel;
}, [selectedCompanyId, closePanel]);
useEffect(() => {
if (!historyOpen || !selectedCompanyId || isMobile) { closePanel(); return; }
// Assigned to you, everyone the viewer may see, one person, no owner yet, or company alerts.
const assigneeOptions = useMemo(() => {
const people = [...userLabelMap].filter(([id]) => id !== userId).sort(([, a], [, b]) => a.localeCompare(b));
return [
{ value: "me" as CoordinatorAssignee, label: "Assigned to you" },
...(everyone ? [{ value: "all" as CoordinatorAssignee, label: "All assignees" }, ...people.map(([id, name]) => ({ value: `user:${id}` as CoordinatorAssignee, label: name }))] : []),
{ value: "unassigned" as CoordinatorAssignee, label: "No owner yet" },
{ value: "company" as CoordinatorAssignee, label: "Company alerts" },
];
}, [userLabelMap, userId, everyone]);
const chooseAssignee = (value: CoordinatorAssignee) => { const target = coordinatorAssigneeTarget(value, userId); setView(target.view, target.forUserId); };
const closeHistory = useCallback(() => setHistoryOpen(false), []);
const showHistory = () => setHistoryOpen(true);
// Cards whose artifact can open beside them: the + launcher lists these.
const reviewable = useMemo(() => pendingItems.filter(item => !!needsYouArtifact(item)), [pendingItems]);
const { openTab: openReviewTab, closeTab: closeReviewTab, selectTab: selectReviewTab, reorderTabs: reorderReviewTabs, resetTabs: resetReviewTabs } = reviewTabs;
const showReview = useCallback((item: AttentionItem, artifact?: NeedsYouArtifact | null) => {
openReviewTab(needsYouReviewTab(item, artifact));
setReviewPanelOpen(true);
setPanelVisible(true);
openPanel(<HistoryPanel companyId={selectedCompanyId} agents={agentQuery.data ?? []} onClose={closeHistory} />);
}, [historyOpen, selectedCompanyId, isMobile, agentQuery.data, openPanel, closePanel, closeHistory, setPanelVisible]);
}, [openReviewTab, setPanelVisible]);
// The frame's close control hides the panel; its tabs come back with the next Review.
useEffect(() => { if (!panelVisible) setReviewPanelOpen(false); }, [panelVisible]);
// A resolved or closed card's tabs close with it.
useEffect(() => {
const open = new Set(pendingItems.map(item => item.id));
for (const tab of reviewTabs.tabs) if (!open.has(tab.payload.itemId)) closeReviewTab(tab.id);
}, [pendingItems, reviewTabs.tabs, closeReviewTab]);
useEffect(() => { setBreadcrumbs([{ label: "Needs You" }]); }, [setBreadcrumbs]);
useEffect(() => {
setSettling([]); setHistoryOpen(false); setReviewPanelOpen(false); resetReviewTabs({ tabs: [], activeTabId: null }); setNow(Date.now()); closePanel();
return closePanel;
}, [selectedCompanyId, closePanel, resetReviewTabs]);
useEffect(() => {
if (!selectedCompanyId || isMobile || !reviewPanelOpen) { closePanel(); return; }
openPanel(<CoordinatorNeedsYouSidePanel tabs={reviewTabs.tabs} activeTabId={reviewTabs.activeTabId} items={pendingItems} reviewable={reviewable}
onSelectTab={selectReviewTab} onCloseTab={closeReviewTab} onReorderTabs={reorderReviewTabs} onOpenItem={item => showReview(item)}
renderReview={(item, tab) => { const artifact = needsYouTabArtifact(item, tab.payload); return artifact ? <CoordinatorReviewPanel key={tab.id} companyId={selectedCompanyId} item={item} artifact={artifact}
agentMap={agentMap} currentUserId={userId} userLabelMap={userLabelMap} onOpenTask={navigate} onResolved={() => closeReviewTab(tab.id)} /> : null; }} />);
}, [reviewPanelOpen, reviewTabs.tabs, reviewTabs.activeTabId, pendingItems, reviewable, selectedCompanyId, isMobile, agentMap, userId, userLabelMap, navigate, openPanel, closePanel, selectReviewTab, closeReviewTab, reorderReviewTabs, showReview]);
useEffect(() => {
const next = recentItems.reduce((earliest, item) => Math.min(earliest, Date.parse(item.resolvedAt) + COORDINATOR_RECENT_DECISION_MS), Infinity);
if (!Number.isFinite(next)) return;
@@ -189,7 +267,7 @@ export function CoordinatorNeedsYou() {
}, [recentItems]);
const onResolved = (item: AttentionItem) => {
const id = `${item.sourceKind}:${item.subject.id}`;
setSavedIds(current => new Set([...current, id]));
hideCard(item, true);
setSettling(current => current.some(entry => entry.id === item.id) ? current : [...current, item]);
void recent.refetch().then(result => {
if (result.isError) setSettling(current => current.filter(entry => `${entry.sourceKind}:${entry.subject.id}` !== id));
@@ -197,53 +275,164 @@ export function CoordinatorNeedsYou() {
void feed.refetch();
};
const duration = typeof document === "undefined" ? 0 : parseCssTimeMs(getComputedStyle(document.documentElement).getPropertyValue("--motion-duration-base")) / 1_000;
const renderCard = (item: AttentionItem) => {
const issueId = item.relatedIssue?.id ?? String(item.subject.metadata?.issueId ?? "");
const interaction = item.sourceKind === "issue_thread_interaction" && isInlineResolvable(item) && issueId;
const decision = item.sourceKind === "decision" && isInlineResolvable(item);
const stalledReview = item.sourceKind === "review" && item.subject.kind === "issue" && isInlineResolvable(item) && item.subject.metadata?.reviewAttentionState === "stalled";
const failedRun = item.sourceKind === "failed_run" && isInlineResolvable(item);
const budget = item.sourceKind === "budget_alert" && isInlineResolvable(item);
// PAP-775 (UX1): approvals and join requests are answered on the card.
const approval = item.sourceKind === "approval" && isInlineResolvable(item);
const joinRequest = item.sourceKind === "join_request" && isInlineResolvable(item);
const taskRef = needsYouTaskRef(item);
// null when there is no task, so the footer keeps its actions on the right (UI4).
const taskLink = taskRef?.href ? <NeedsYouTaskLink task={taskRef} onOpen={navigate} /> : null;
const id = `${item.sourceKind}:${item.subject.id}`;
const receipt = settlingIds.has(id) ? recentItems.find(entry => entry.id === id) : undefined;
const phase = !receipt ? "pending" : ["cancelled", "expired"].includes(receipt.outcome) ? "closed" : "resolved";
const refetchAll = () => { void feed.refetch(); void recent.refetch(); };
// Focus (PAP-770, PAP-775 IA5): a card about an artifact opens it beside the card.
const artifact = isMobile ? null : needsYouArtifact(item);
// The card stays highlighted while any of its artifacts is open beside it (UI9).
const panelOpen = !isMobile && reviewPanelOpen && panelVisible;
const activeTab = panelOpen ? reviewTabs.tabs.find(tab => tab.id === reviewTabs.activeTabId) : undefined;
const reviewing = !!activeTab && activeTab.payload.itemId === item.id;
const reviewingOwn = !!artifact && panelOpen && reviewTabs.activeTabId === needsYouReviewTabId(item);
// The artifact opens beside the card from the first row of its context panel (IA5).
const artifactRow = artifact && artifact.kind !== "approval" ? <NeedsYouPanelRow
icon={artifact.kind === "images" ? <ImageIcon /> : <FileText />}
title={artifact.kind === "document" && !artifact.title ? (artifact.key === "plan" ? "Plan" : documentKeyLabel(artifact.key)) : needsYouArtifactLabel(artifact)}
meta={reviewingOwn ? "Open in sidebar · Showing" : "Open in sidebar"}
label={`${reviewingOwn ? "Close" : "Open"} ${needsYouArtifactLabel(artifact)} in the sidebar`}
onOpen={() => reviewingOwn ? closeReviewTab(needsYouReviewTabId(item)) : showReview(item)} /> : null;
// A plan, document, approval or attachment the card links to opens as a
// side-panel tab beside the card, not a page change (PAP-775, IA5).
// A modified click still opens the link itself.
const openMentionedDocument = (event: ReactMouseEvent) => {
if (isMobile || event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
const link = (event.target as HTMLElement).closest<HTMLAnchorElement>("a[href]");
const mentioned = link ? needsYouMentionedArtifact(link.getAttribute("href")!, link.textContent) : null;
if (!mentioned) return;
event.preventDefault();
showReview(item, mentioned);
};
const title = coordinatorCardTitle(item);
const detail = coordinatorCardDetail(item, attentionDetailLine(item));
// The ask, with one plain line under it (UI1).
const heading = <div className="space-y-1.5"><h2>{title}</h2>{detail && !sameText(detail, title) ? <p className="text-sm text-muted-foreground">{detail}</p> : null}</div>;
const footerContext = <AttentionObligationEvidence item={item} evidence={attentionObligationEvidence(obligations, item)} />;
const type = attentionCardType(item);
return <motion.div id={item.sourceKind === "decision" ? `coordinator-decision-${item.subject.id}` : undefined} tabIndex={item.sourceKind === "decision" ? -1 : undefined} layout={reducedMotion ? false : "position"} layoutId={reducedMotion ? undefined : id} transition={{ duration }} key={id}>
<CoordinatorTaskMotion eventId={`decision:${selectedCompanyId}:${userId}:${id}`} phase={phase} createdAt={item.activityAt} className="coordinator-decision-motion"
onSettled={() => setSettling(current => current.filter(entry => `${entry.sourceKind}:${entry.subject.id}` !== id))}>
{receipt ? <Receipt item={receipt} onOpen={navigate} userLabelMap={userLabelMap} /> : <article onClickCapture={openMentionedDocument}
className="coordinator-decision-card space-y-3"
data-attention-card={item.id} data-card-type={type} data-card-kind={needsYouSection(item) === "problems" ? "problem" : "decision"} data-reviewing={reviewing || undefined}>
{/* What to do (with whose card it is) on the left; who asked, when, and ⋯ on the right (Paper "A · Compact cards"). */}
<div className="flex items-center justify-between gap-4">
<div className="flex min-w-0 items-center gap-2">
<NeedsYouTypeLabel item={item} currentUserId={userId} userLabelMap={userLabelMap} />
<AttentionHiddenChip item={item} />
<AttentionStaleChip item={item} />
</div>
<div className="flex shrink-0 items-center gap-3" data-attention-context>
<NeedsYouAudience item={item} currentUserId={userId} userLabelMap={userLabelMap} onClaim={entry => claim.mutate(entry)} claiming={claim.isPending && claim.variables?.id === item.id} />
<NeedsYouRequester item={item} agentMap={agentMap} userLabelMap={userLabelMap} currentUserId={userId} />
<time dateTime={item.activityAt} title={new Date(item.activityAt).toLocaleString()} className="shrink-0 text-xs leading-4.5 text-muted-foreground">{timeAgo(item.activityAt)}</time>
<AttentionCloseMenu item={item} currentUserId={userId} userLabelMap={userLabelMap}
busy={closeActions.closingItemId === item.id || closeActions.transferringItemId === item.id}
onWithdraw={(entry, reason) => closeActions.close({ item: entry, mode: "withdraw", reason })}
onArchive={entry => closeActions.close({ item: entry, mode: "archive" })}
onSnooze={(entry, until) => closeActions.close({ item: entry, mode: "snooze", until })}
onTransfer={(entry, target) => closeActions.transfer({ item: entry, userId: target })}
onRestore={archivedView ? entry => void closeActions.restore(entry) : undefined} />
</div>
</div>
<AttentionForOtherGate item={item} currentUserId={userId} userLabelMap={userLabelMap}>
{interaction ? <AttentionInteractionResolver footerSlot={taskLink} artifactRow={artifactRow} presentation="coordinator-decision" audienceStated={attentionAudienceLineNamesResponders(item, userId)} companyId={selectedCompanyId!} issueId={issueId} interactionId={item.subject.id} shareReviseDraft agentMap={agentMap} currentUserId={userId} onResolved={resolved => {
if (!resolved || resolved.status === "pending") { refetchAll(); return; }
onResolved(item);
}} />
: decision ? <DecisionResolver companyId={selectedCompanyId!} decisionId={item.subject.id} originIssue={item.relatedIssue} agentMap={agentMap} leading={taskLink} onResolved={() => onResolved(item)} />
: stalledReview ? <><div className="space-y-1.5"><h2>Choose how this task continues</h2><p className="text-sm text-muted-foreground">This task is still in review with no active reviewer or continuation. Return it to work, request changes, or mark the task done.</p></div><BlockedTaskCardBody item={item} companyId={selectedCompanyId!} agentMap={agentMap} userLabelMap={userLabelMap} leading={taskLink} footerContext={footerContext} onOpen={navigate} onResolved={refetchAll} /></>
: failedRun ? <>{heading}<FailedRunActions item={item} companyId={selectedCompanyId!} leading={taskLink} footerContext={footerContext} presentation="card" onResolved={refetchAll} /></>
: budget ? <>{heading}<BudgetAlertActions item={item} companyId={selectedCompanyId!} leading={taskLink} footerContext={footerContext} presentation="card" onResolved={refetchAll} /></>
: approval ? <>{heading}<ApprovalResolver item={item} companyId={selectedCompanyId!} toggle={taskLink} footerContext={footerContext} presentation="card" onViewDetails={isMobile ? undefined : () => showReview(item)} shareDraft onResolved={() => onResolved(item)} /></>
: joinRequest ? <>{heading}<JoinRequestResolver item={item} companyId={selectedCompanyId!} toggle={taskLink} presentation="card" onResolved={() => onResolved(item)} /></>
: type === "review_task" ? <>{heading}<ReviewTaskCardBody item={item} companyId={selectedCompanyId!} agentMap={agentMap} userLabelMap={userLabelMap} leading={taskLink} footerContext={footerContext} onOpen={navigate} onResolved={refetchAll} /></>
: type === "blocked_task" ? <>{heading}<BlockedTaskCardBody item={item} companyId={selectedCompanyId!} agentMap={agentMap} userLabelMap={userLabelMap} leading={taskLink} footerContext={footerContext} onOpen={navigate} onResolved={refetchAll} /></>
: type === "recovery" ? <>{heading}<RecoveryCardBody item={item} companyId={selectedCompanyId!} leading={taskLink} footerContext={footerContext} onOpen={navigate} onResolved={refetchAll} /></>
: <>{heading}{footerContext}<DecisionCardFooter leading={taskLink}><Button disabled={!item.subject.href} onClick={() => { if (item.subject.href) navigate(item.subject.href); }}>{openLabel(item)}<ArrowUpRight className="size-4" /></Button></DecisionCardFooter></>}
</AttentionForOtherGate>
</article>}
</CoordinatorTaskMotion>
</motion.div>;
};
if (!selectedCompanyId) return <p className="text-sm text-muted-foreground">Choose a company to see its decisions.</p>;
return <LayoutGroup id="coordinator-decisions"><section className="coordinator-needs-you mx-auto w-full max-w-4xl space-y-6" aria-label="Inbox">
{isMobile ? <Sheet open={historyOpen} onOpenChange={open => { if (!open) closeHistory(); }}>
<SheetContent side="bottom" aria-describedby={undefined} className="mobile-task-side-panel inset-0 h-dvh max-h-dvh w-full max-w-none gap-0 border-0 p-0 pt-(--sz-safe-top) pb-(--sz-safe-bottom)">
<SheetHeader><SheetTitle>Decision history</SheetTitle></SheetHeader>
<div className="min-h-0 flex-1 overflow-y-auto p-4"><HistoryPanel companyId={selectedCompanyId} agents={agentQuery.data ?? []} onClose={closeHistory} mobile /></div>
</SheetContent>
</Sheet> : null}
<header className="flex items-center justify-between gap-3"><h1 className="text-2xl font-medium">Inbox</h1><Button variant="ghost" onClick={showHistory}><History className="size-4" />Decision history</Button></header>
<div data-canonical-toolbar="coordinator-decisions" role="toolbar" aria-label="Decisions controls" className="flex flex-wrap items-center gap-2">
<ToolbarSearch query={query} onQueryChange={setQuery} label="Search decisions" placeholder="Search decisions or task IDs…" />
// Decision history is a view of the main pane (PAP-770), not a side panel
// that repeats Recent Decisions beside them.
if (historyOpen) return <section className="coordinator-needs-you mx-auto w-full max-w-4xl space-y-6" aria-label="Decision history" data-coordinator-decision-history>
<Button variant="ghost" size="sm" onClick={closeHistory}><ArrowLeft className="size-4" />Needs You</Button>
<DecisionHistoryPanel companyId={selectedCompanyId} agents={agentQuery.data ?? []} userLabelMap={userLabelMap} header={<h1 className="text-2xl font-medium">Decision history</h1>} />
</section>;
const receipts = view === "mine" ? feed.data?.receipts ?? [] : [];
const counts = { decisions: 0, problems: 0, updates: receipts.length };
for (const item of currentItems) counts[needsYouSection(item)]++;
const summarySections = (Object.keys(counts) as NeedsYouSection[]).filter(section => counts[section] > 0);
if (!summarySections.length) summarySections.push("decisions");
const sectionHeading = (section: NeedsYouSection) => <h2 className="text-base font-medium" data-needs-you-section={section}>
{NEEDS_YOU_SECTIONS[section].title}
</h2>;
return <LayoutGroup id="coordinator-decisions"><section className="coordinator-needs-you mx-auto w-full max-w-4xl space-y-6" aria-label="Needs You">
{archivedView ? <div className="flex items-center gap-2"><Button variant="ghost" size="icon-sm" aria-label="Back to Needs You" onClick={() => setView("mine")}><ArrowLeft className="size-4" /></Button><h1 className="text-2xl font-medium">Archived</h1></div> : null}
{/* Assigned to you by default (PAP-775); the assignee filter widens to all
assignees, one person, no owner yet or company alerts. Archived and
Decision history sit in View. */}
<div role="toolbar" aria-label="Decisions controls" className="flex flex-wrap items-center gap-2">
<div className="min-w-44 flex-1"><ToolbarSearch query={query} onQueryChange={setQuery} label="Search decisions" placeholder="Search…" /></div>
<NativeSelect aria-label="Filter decisions by agent" value={agentFilter} onChange={(event) => setAgentFilter(event.target.value)} className="w-auto"><option value="">All agents</option>{(agentQuery.data ?? []).map((agent) => <option key={agent.id} value={agent.id}>{agent.name}</option>)}</NativeSelect>
<NativeSelect aria-label="Filter decisions by project" value={projectFilter} onChange={(event) => setProjectFilter(event.target.value)} className="w-auto"><option value="">All projects</option>{projects.map(([id, name]) => <option key={id} value={id}>{name}</option>)}</NativeSelect>
<NativeSelect aria-label="Group decisions" value={groupBy} onChange={(event) => setGroupBy(event.target.value as Group)} className="w-auto"><option value="none">No grouping</option><option value="task">By task</option><option value="agent">By agent</option><option value="project">By project</option></NativeSelect>
<NativeSelect aria-label="Sort decisions" value={sort} onChange={(event) => setSort(event.target.value as typeof sort)} className="w-auto"><option value="newest">Newest first</option><option value="oldest">Oldest first</option></NativeSelect>
{assignee ? <NativeSelect aria-label="Filter decisions by assignee" data-attention-assignee={assignee} value={assignee} onChange={(event) => chooseAssignee(event.target.value as CoordinatorAssignee)} className="w-auto">
{assigneeOptions.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
{assignee.startsWith("user:") && !assigneeOptions.some(option => option.value === assignee) ? <option value={assignee}>Someone else</option> : null}
</NativeSelect> : null}
<NativeSelect aria-label="Group decisions" value={groupBy} onChange={(event) => setGroupBy(event.target.value as Group)} className="w-auto"><option value="type">By type</option><option value="task">By task</option><option value="agent">By agent</option><option value="project">By project</option><option value="none">No grouping</option></NativeSelect>
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" data-attention-view-menu>View<ChevronDown className="size-4" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => setView("archived")}>Archived{viewCounts.archived ? ` · ${viewCounts.archived}` : ""}</DropdownMenuItem>
<DropdownMenuItem onSelect={showHistory}>Decision history</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{feed.data ? <p className="text-sm text-muted-foreground" data-needs-you-summary>
{summarySections.map((section, index) => {
const label = NEEDS_YOU_SECTIONS[section].title.toLocaleLowerCase();
return <span key={section}>{index ? " · " : ""}{counts[section]} {counts[section] === 1 ? label.slice(0, -1) : label}</span>;
})}
</p> : null}
{feedWaiting ? <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Loading decisions…</p> : null}
{(feedView.kind === "error") ? <div role="alert" className="space-y-2"><p className="text-sm">Decisions could not be loaded.</p><Button variant="outline" onClick={() => void feed.refetch()}>Retry</Button></div> : null}
{!feedWaiting && !(feedView.kind === "error") && filtered.length === 0 ? <div className="space-y-3 py-8 text-center"><p className="text-sm text-muted-foreground">{filtersActive && !visibleRecentItems.length ? "No decisions match these filters." : pendingItems.length ? "No open decisions match these filters." : "You're caught up."}</p><Button variant="ghost" onClick={showHistory}>Open decision history<ArrowUpRight className="size-4" /></Button></div> : null}
{groups.map(([label, items]) => <div key={label} className="space-y-4">{label ? <h2 className="text-sm font-medium text-muted-foreground">{label}</h2> : null}{items.map((item) => {
const issueId = item.relatedIssue?.id ?? String(item.subject.metadata?.issueId ?? "");
const interaction = item.sourceKind === "issue_thread_interaction" && isInlineResolvable(item) && issueId;
const decision = item.sourceKind === "decision" && isInlineResolvable(item);
const stalledReview = item.sourceKind === "review" && item.subject.kind === "issue" && isInlineResolvable(item) && item.subject.metadata?.reviewAttentionState === "stalled";
const taskRef = item.relatedIssue ?? (item.subject.kind === "issue" ? item.subject : null);
const taskLink = taskRef?.href ? <button type="button" onClick={() => { if (taskRef.href) navigate(taskRef.href); }} className="flex max-w-full items-center gap-2 text-left text-sm text-muted-foreground hover:text-foreground"><span className="shrink-0">{taskRef.identifier ?? "Open task"}</span><span className="truncate">{taskRef.title}</span><ArrowUpRight className="size-4 shrink-0" /></button> : null;
const id = `${item.sourceKind}:${item.subject.id}`;
const receipt = settlingIds.has(id) ? recentItems.find(entry => entry.id === id) : undefined;
const phase = !receipt ? "pending" : ["cancelled", "expired"].includes(receipt.outcome) ? "closed" : "resolved";
return <motion.div id={item.sourceKind === "decision" ? `coordinator-decision-${item.subject.id}` : undefined} tabIndex={item.sourceKind === "decision" ? -1 : undefined} layout={reducedMotion ? false : "position"} layoutId={reducedMotion ? undefined : id} transition={{ duration }} key={id}>
<CoordinatorTaskMotion eventId={`decision:${selectedCompanyId}:${userId}:${id}`} phase={phase} createdAt={item.activityAt} className="coordinator-decision-motion"
onSettled={() => setSettling(current => current.filter(entry => `${entry.sourceKind}:${entry.subject.id}` !== id))}>
{receipt ? <Receipt item={receipt} onOpen={navigate} /> : <article className="coordinator-decision-card space-y-4 rounded-xl border border-border bg-card p-6">
{interaction ? <AttentionInteractionResolver footerSlot={taskLink} presentation="coordinator-decision" companyId={selectedCompanyId} issueId={issueId} interactionId={item.subject.id} agentMap={agentMap} currentUserId={userId} onResolved={resolved => {
if (!resolved || resolved.status === "pending") { void feed.refetch(); void recent.refetch(); return; }
onResolved(item);
}} />
: decision ? <DecisionResolver companyId={selectedCompanyId} decisionId={item.subject.id} originIssue={item.relatedIssue} agentMap={agentMap} onResolved={() => onResolved(item)} />
: stalledReview ? <><h2 className="text-lg font-medium">Choose how this task continues</h2><p className="text-sm">This task is still in review with no active reviewer or continuation. Return it to work, request changes, or mark the task done.</p><StalledReviewActions footerSlot={taskLink} issueId={item.subject.id} companyId={selectedCompanyId} reviewPolicy={readIssueReviewPolicyMetadata(item.subject.metadata)} approveLabel="Mark task done" onResolved={() => { void feed.refetch(); void recent.refetch(); }} /></>
: <><h2 className="text-lg font-medium">{item.subject.title ?? item.whyNow}</h2><p className="text-sm">{attentionDetailLine(item) ?? item.whyNow}</p><Button disabled={!item.subject.href} onClick={() => { if (item.subject.href) navigate(item.subject.href); }}>Open to review<ArrowUpRight className="size-4" /></Button></>}
{!interaction && !stalledReview ? taskLink : null}
</article>}
</CoordinatorTaskMotion>
</motion.div>;
})}</div>)}
{filtered.length > renderLimit ? <Button variant="outline" onClick={() => setRenderLimit((value) => value + 40)}>Show more decisions</Button> : null}
{visibleRecentItems.length ? <section className="space-y-3" aria-label="Recent Decisions"><h2 className="text-sm font-medium text-muted-foreground">Recent Decisions</h2>{recentGroups.map(([label, items]) => <div key={label} className="space-y-3">{label ? <h3 className="text-sm font-medium text-muted-foreground">{label}</h3> : null}{items.map((item) => <motion.div layout={!reducedMotion} layoutId={reducedMotion ? undefined : item.id} transition={{ duration }} key={item.id}><Receipt item={item} onOpen={navigate} /></motion.div>)}</div>)}</section> : null}
{(recentView.kind === "error") ? <p role="alert" className="text-sm text-muted-foreground">Recent decisions could not be loaded. <button className="underline" onClick={() => void recent.refetch()}>Retry</button></p> : null}
{feedView.kind === "error" ? <QueryErrorState error={feedView.error} onRetry={feedView.retry} /> : null}
{!feedWaiting && feedView.kind !== "error" && currentItems.length === 0 && !receipts.length ? <div className="space-y-3 py-8 text-center"><p className="text-sm text-muted-foreground">{staleItems.length ? "No current cards. Stale cards are below." : snoozedItems.length ? "No archived cards. Snoozed cards are below." : pendingItems.length ? "No open decisions match these filters." : EMPTY_VIEW_TEXT[view]}</p></div> : null}
{groups.map(([label, items], index) => <div key={label} className="space-y-3" role={groupBy === "type" ? "group" : undefined} aria-label={groupBy === "type" ? NEEDS_YOU_SECTIONS[label as NeedsYouSection].title : undefined}>
{groupBy === "type" ? index > 0 ? sectionHeading(label as NeedsYouSection) : null : label ? <h2 className="text-sm font-medium text-muted-foreground">{label}</h2> : null}
{items.map(renderCard)}
</div>)}
{currentItems.length > renderLimit ? <Button variant="outline" onClick={() => setRenderLimit((value) => value + 40)}>Show more decisions</Button> : null}
<AttentionStaleGroup items={staleItems} open={staleOpen} onToggle={() => setStaleOpen(open => !open)} onWithdrawAll={closeActions.withdrawAll}
busy={closeActions.bulkPending} currentUserId={userId} userLabelMap={userLabelMap} titleOf={coordinatorCardTitle}>
{staleItems.map(renderCard)}
</AttentionStaleGroup>
{/* Snoozed by you: each card says when it comes back (PAP-749 plan §3). */}
<AttentionSnoozedGroup count={snoozedItems.length} open={snoozedOpen} onToggle={() => setSnoozedOpen(open => !open)}>
{snoozedItems.map(renderCard)}
</AttentionSnoozedGroup>
{/* What other people did with your requests (PAP-749 plan §6): not in the badge. */}
{receipts.length ? <div className="space-y-3" aria-label="Updates">
{currentItems.length || staleItems.length || snoozedItems.length ? sectionHeading("updates") : null}
{receipts.map(entry => <NeedsYouReceiptCard key={entry.id} receipt={entry} userLabelMap={userLabelMap} onOpen={navigate}
onDismiss={receiptActions.dismiss} dismissing={receiptActions.dismissingId === entry.id} />)}
</div> : null}
</section></LayoutGroup>;
}
@@ -0,0 +1,109 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { FileText, Plus } from "lucide-react";
import type { AttentionItem } from "@paperclipai/shared";
import { PROPERTIES_PANE_HEADER_SLOT_ID } from "@/components/PropertiesPanel";
import { SidePanelLauncher, SidePanelTabs, type SidePanelLauncherItem, type SidePanelLauncherSection, type SidePanelTabItem, type SidePanelTabRecord } from "@/components/side-panel";
import { Button } from "@/components/ui/button";
import { needsYouArtifact, needsYouArtifactId, needsYouArtifactLabel, type NeedsYouArtifact } from "./CoordinatorReviewPanel";
/**
* A Needs You side-panel tab: what one pending card is deciding on (a plan,
* an approval, attachments), or an artifact the card mentions (PAP-775).
* Every tab belongs to its card, so it shows the card's own actions and
* closes when the card leaves.
*/
export interface NeedsYouReviewPayload {
kind: "review";
itemId: string;
/** A mentioned artifact; absent for the card's own artifact. */
artifact?: NeedsYouArtifact;
}
/** The card's own artifact keeps `review:<card>`; a mentioned one adds its own id. */
export function needsYouReviewTabId(item: AttentionItem, artifact?: NeedsYouArtifact | null) {
const own = needsYouArtifact(item);
if (!artifact || (own && needsYouArtifactId(own, item) === needsYouArtifactId(artifact, item))) return `review:${item.id}`;
return `review:${item.id}:${needsYouArtifactId(artifact, item)}`;
}
/** The artifact a tab shows: the mentioned one, else the card's own. */
export function needsYouTabArtifact(item: AttentionItem, payload: NeedsYouReviewPayload) {
return payload.artifact ?? needsYouArtifact(item);
}
function documentLabel(item: AttentionItem, artifact?: NeedsYouArtifact | null) {
const shown = artifact ?? needsYouArtifact(item);
return shown ? needsYouArtifactLabel(shown) : "Document";
}
/** "NEE-39 plan": the artifact and its task, where several are listed or open. */
export function needsYouReviewTabLabel(item: AttentionItem, artifact?: NeedsYouArtifact | null) {
const task = item.relatedIssue?.identifier;
const label = documentLabel(item, artifact);
return task ? `${task} ${label.toLocaleLowerCase()}` : item.subject.title ? `${label}: ${item.subject.title}` : label;
}
export function needsYouReviewTab(item: AttentionItem, artifact?: NeedsYouArtifact | null): SidePanelTabRecord<NeedsYouReviewPayload> {
const id = needsYouReviewTabId(item, artifact);
const mentioned = id !== needsYouReviewTabId(item) ? artifact ?? undefined : undefined;
return { id, type: documentLabel(item, artifact), label: needsYouReviewTabLabel(item, artifact), ariaLabel: needsYouReviewTabLabel(item, artifact), closable: true, payload: { kind: "review", itemId: item.id, artifact: mentioned } };
}
/**
* Focus (PAP-770): the Needs You side panel uses the task-detail panel's
* chrome: a tab per opened document, a + launcher listing the other
* documents waiting on you, and the frame's own expand and close controls.
* The page owns the tab state, so a card and its tab stay in step.
*/
export function CoordinatorNeedsYouSidePanel({ tabs, activeTabId, items, reviewable, onSelectTab, onCloseTab, onReorderTabs, onOpenItem, renderReview }: {
tabs: SidePanelTabRecord<NeedsYouReviewPayload>[];
activeTabId: string | null;
/** Every pending card, so a tab for a mentioned artifact finds its card. */
items: AttentionItem[];
reviewable: AttentionItem[];
onSelectTab: (tabId: string) => void;
onCloseTab: (tabId: string) => void;
onReorderTabs: (ordered: string[]) => void;
onOpenItem: (item: AttentionItem) => void;
renderReview: (item: AttentionItem, tab: SidePanelTabRecord<NeedsYouReviewPayload>) => ReactNode;
}) {
const [launcherOpen, setLauncherOpen] = useState(false);
const [slot, setSlot] = useState<HTMLElement | null>(null);
useEffect(() => { setSlot(document.getElementById(PROPERTIES_PANE_HEADER_SLOT_ID)); }, []);
const byId = useMemo(() => new Map(items.map(item => [item.id, item])), [items]);
// A tab says "Plan" until a second plan opens; then each names its task.
const visualTabs = useMemo<SidePanelTabItem[]>(() => tabs.map(tab => ({
id: tab.id, type: tab.type, ariaLabel: tab.ariaLabel, closable: true, icon: <FileText />,
label: tabs.filter(other => other.type === tab.type).length > 1 ? tab.label : tab.type,
})), [tabs]);
const sections = useMemo<SidePanelLauncherSection[]>(() => [{
id: "waiting",
label: "Waiting on you",
items: reviewable.map((item): SidePanelLauncherItem => ({
id: item.id,
label: needsYouReviewTabLabel(item),
description: item.relatedIssue?.title ?? undefined,
searchText: [item.relatedIssue?.identifier, item.relatedIssue?.title, item.subject.title].filter(Boolean).join(" "),
icon: <FileText />,
alreadyOpen: tabs.some(tab => tab.id === needsYouReviewTabId(item)),
})),
}], [reviewable, tabs]);
const select = (entry: SidePanelLauncherItem) => {
const item = byId.get(entry.id);
if (item) onOpenItem(item);
};
const launcher = <SidePanelLauncher sections={sections} onSelect={select} presentation="popover" open={launcherOpen} onOpenChange={setLauncherOpen}
emptyMessage="Nothing else is waiting on you."
trigger={<Button type="button" variant="ghost" size="icon-sm" className="h-(--side-panel-tab-height) w-(--side-panel-tab-height) shrink-0 rounded-md text-muted-foreground hover:text-foreground focus-visible:text-foreground" aria-label="Open a new tab"><Plus aria-hidden /></Button>} />;
const header = <SidePanelTabs tabs={visualTabs} activeTabId={activeTabId} onActiveTabChange={onSelectTab} onCloseTab={onCloseTab}
onReorderTabs={onReorderTabs} addControl={launcher} appearance="streamlined-task" />;
const active = tabs.find(tab => tab.id === activeTabId) ?? null;
const item = active ? byId.get(active.payload.itemId) ?? null : null;
return <div className="flex min-h-full flex-col" data-coordinator-side-panel>
{slot ? createPortal(header, slot) : header}
{!active ? <SidePanelLauncher sections={sections} onSelect={select} emptyMessage="Nothing else is waiting on you." />
: item ? renderReview(item, active)
: <p className="text-sm text-muted-foreground">This is no longer waiting on you.</p>}
</div>;
}
@@ -0,0 +1,193 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AttentionItem } from "@paperclipai/shared";
import { pendingRequestConfirmationInteraction } from "@/fixtures/issueThreadInteractionFixtures";
import { issuesApi } from "@/api/issues";
import { ThemeProvider } from "@/context/ThemeContext";
import { approvalsApi } from "@/api/approvals";
import { ApprovalResolver } from "@/components/AttentionQueueRow";
import { CoordinatorReviewPanel, needsYouArtifact, needsYouMentionedArtifact } from "./CoordinatorReviewPanel";
vi.mock("@/api/issues", () => ({ issuesApi: { getDocument: vi.fn(), getDocumentRevision: vi.fn(), listInteractions: vi.fn() } }));
vi.mock("@/components/AttentionInteractionResolver", () => ({ AttentionInteractionResolver: () => <div data-testid="panel-interaction-resolver" /> }));
vi.mock("@/api/agents", () => ({ agentsApi: { list: vi.fn(async () => [{ id: "mgr", name: "Dottabot" }]) } }));
vi.mock("@/api/approvals", () => ({ approvalsApi: { approve: vi.fn(), reject: vi.fn(), requestRevision: vi.fn(), get: vi.fn() } }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
describe("needsYouMentionedArtifact (PAP-775)", () => {
it("reads a task document, an approval and an attachment from a card's links", () => {
expect(needsYouMentionedArtifact("/NEE/issues/NEE-12#document-design", "design notes"))
.toMatchObject({ kind: "document", issueId: "NEE-12", key: "design", title: "design notes" });
expect(needsYouMentionedArtifact("/NEE/approvals/appr-1")).toEqual({ kind: "approval", approvalId: "appr-1" });
expect(needsYouMentionedArtifact("/api/attachments/att-1/content", "screenshot.png"))
.toEqual({ kind: "attachment", assetId: "att-1", name: "screenshot.png" });
});
it("preserves pinned document revisions, annotations, and the document owner", () => {
expect(needsYouMentionedArtifact("/NEE/issues/NEE-12#document-launch%20plan&revision=rev-1&interaction=req-1&documentIssue=NEE-9&thread=thread-2"))
.toMatchObject({ kind: "document", issueId: "NEE-9", key: "launch plan", documentTarget: { revisionId: "rev-1", interactionId: "req-1", threadId: "thread-2", documentIssueId: "NEE-9" } });
expect(needsYouMentionedArtifact("/NEE/issues/NEE-12#document-%invalid")).toBeNull();
});
it.each(["notes.pdf", "notes.txt", "clip.mp4", "Download file", undefined])("keeps unsupported attachment %s as a normal browser link", name => {
expect(needsYouMentionedArtifact("/api/attachments/att-1/content", name)).toBeNull();
});
it("leaves every other link alone", () => {
expect(needsYouMentionedArtifact("/NEE/issues/NEE-12")).toBeNull();
expect(needsYouMentionedArtifact("https://example.com/issues/X-1#document-plan")).toBeNull();
});
});
describe("ApprovalResolver shared between a card and its side panel (PAP-775)", () => {
let container: HTMLDivElement;
let root: Root;
const item = { id: "approval", sourceKind: "approval", updatedAt: "2026-11-04T00:00:00.000Z",
subject: { id: "appr-1", kind: "approval", title: "Ship it", metadata: {} } } as unknown as AttentionItem;
beforeEach(() => {
sessionStorage.clear();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("mirrors the decision note and sends the approval once", async () => {
let resolveApprove!: (value: unknown) => void;
vi.mocked(approvalsApi.approve).mockImplementation(() => new Promise(resolve => { resolveApprove = resolve; }) as never);
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<div data-view="card"><ApprovalResolver item={item} companyId="company" toggle={null} shareDraft /></div>
<div data-view="panel"><ApprovalResolver item={item} companyId="company" toggle={null} shareDraft /></div>
</QueryClientProvider>));
const note = (view: string) => container.querySelector<HTMLTextAreaElement>(`[data-view="${view}"] textarea`)!;
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;
await act(async () => {
setter.call(note("card"), "Looks right");
note("card").dispatchEvent(new Event("input", { bubbles: true }));
});
expect(note("panel").value).toBe("Looks right");
const approve = (view: string) => [...container.querySelectorAll<HTMLButtonElement>(`[data-view="${view}"] button`)].find(button => button.textContent === "Approve")!;
await act(async () => approve("card").click());
// Sending from one view disables the other, so nothing is sent twice.
expect(approve("panel").disabled).toBe(true);
await act(async () => approve("panel").click());
expect(approvalsApi.approve).toHaveBeenCalledTimes(1);
expect(approvalsApi.approve).toHaveBeenCalledWith("appr-1", "Looks right");
await act(async () => resolveApprove({}));
client.clear();
});
it.each([["ask_user_questions", false, null], ["request_checkbox_confirmation", false, null], ["request_item_verdicts", false, null], ["suggest_tasks", false, null], ["request_confirmation", true, null], ["request_confirmation", true, "deliverable"], ["request_confirmation", false, "tool_action"], ["request_confirmation", false, "secret"], ["request_confirmation", false, "connection"]] as const)("shares only synchronized %s actions in the artifact panel", async (kind, shared, requestKind) => {
const question = { ...item, sourceKind: "issue_thread_interaction", subject: { ...item.subject, metadata: { issueId: "task", kind, requestKind } } } as AttentionItem;
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<CoordinatorReviewPanel companyId="company" item={question} artifact={{ kind: "images" }} agentMap={new Map()} currentUserId="scott"
onOpenTask={vi.fn()} onResolved={vi.fn()} />
</QueryClientProvider>));
expect(Boolean(container.querySelector('[data-testid="panel-interaction-resolver"]'))).toBe(shared);
expect(container.textContent?.includes("Answer on the inbox card")).toBe(!shared);
client.clear();
});
it("opens the original attachment through a browser link instead of task navigation", async () => {
const onOpen = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<CoordinatorReviewPanel companyId="company" item={item} artifact={{ kind: "attachment", assetId: "image with spaces", name: "screenshot.png" }}
agentMap={new Map()} currentUserId="scott" onOpenTask={onOpen} onResolved={vi.fn()} />
</QueryClientProvider>));
await act(async () => container.querySelector("img")!.dispatchEvent(new Event("error")));
expect(container.querySelector("img")).toBeNull();
expect(container.textContent).toContain("This file cannot be previewed.");
const link = [...container.querySelectorAll<HTMLAnchorElement>("a")].find(entry => entry.textContent === "Open file");
expect(link?.getAttribute("href")).toBe("/api/attachments/image%20with%20spaces/content");
expect(link?.target).toBe("_blank");
expect(onOpen).not.toHaveBeenCalled();
client.clear();
});
it("loads the pinned revision and retains the full document link", async () => {
vi.mocked(issuesApi.getDocumentRevision).mockResolvedValue({ title: "Pinned plan", body: "Revision under review" } as never);
const artifact = needsYouMentionedArtifact("/NEE/issues/NEE-12#document-plan&revision=rev-1&interaction=req-1&documentIssue=NEE-9&thread=thread-2")!;
const onOpen = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<ThemeProvider><CoordinatorReviewPanel companyId="company" item={item} artifact={artifact} agentMap={new Map()} currentUserId="scott" onOpenTask={onOpen} onResolved={vi.fn()} /></ThemeProvider>
</QueryClientProvider>));
for (let tick = 0; tick < 3; tick++) await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
expect(issuesApi.getDocumentRevision).toHaveBeenCalledExactlyOnceWith("NEE-9", "plan", "rev-1");
expect(issuesApi.getDocument).not.toHaveBeenCalled();
expect(container.textContent).toContain("Revision under review");
await act(async () => [...container.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.includes("Open in"))!.click());
expect(onOpen.mock.calls[0]?.[0]).toContain("#document-plan&thread=thread-2&revision=rev-1&interaction=req-1&documentIssue=NEE-9");
client.clear();
});
it("reviews the exact target of a plan request owned by another task", async () => {
const request = { ...pendingRequestConfirmationInteraction, id: "request-1", issueId: "request-task", payload: {
...pendingRequestConfirmationInteraction.payload, target: { type: "issue_document" as const, issueId: "document-owner", key: "plan", revisionId: "pinned-revision" },
} };
vi.mocked(issuesApi.listInteractions).mockResolvedValue([request]);
vi.mocked(issuesApi.getDocumentRevision).mockClear().mockResolvedValue({ title: "Correct plan", body: "The plan being approved" } as never);
vi.mocked(issuesApi.getDocument).mockClear().mockResolvedValue({ title: "Wrong plan", body: "The request task's current plan" } as never);
const plan = { ...item, id: "plan-request", sourceKind: "issue_thread_interaction", subject: { ...item.subject, id: request.id, metadata: { issueId: "request-task", targetDocumentKey: "plan" } },
relatedIssue: { id: "request-task", kind: "issue", companyId: "company", title: "Request task", identifier: "NEE-12", status: "in_progress", href: "/NEE/issues/NEE-12", metadata: {} } } as AttentionItem;
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}><ThemeProvider>
<CoordinatorReviewPanel companyId="company" item={plan} artifact={needsYouArtifact(plan)!} agentMap={new Map()} currentUserId="scott" onOpenTask={vi.fn()} onResolved={vi.fn()} />
</ThemeProvider></QueryClientProvider>));
for (let tick = 0; tick < 5; tick++) await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
expect(issuesApi.getDocumentRevision).toHaveBeenCalledExactlyOnceWith("document-owner", "plan", "pinned-revision");
expect(issuesApi.getDocument).not.toHaveBeenCalled();
expect(container.textContent).toContain("The plan being approved");
client.clear();
});
it("confirms before the panel answers another person's request", async () => {
vi.mocked(approvalsApi.approve).mockClear().mockResolvedValue({} as never);
const other = { ...item, inlineResolvable: true, audience: { kind: "user", userId: "dotta", reason: "requester" } } as AttentionItem;
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<CoordinatorReviewPanel companyId="company" item={other} artifact={{ kind: "images" }} agentMap={new Map()} currentUserId="scott"
userLabelMap={new Map([["dotta", "Dotta"]])} onOpenTask={vi.fn()} onResolved={vi.fn()} />
</QueryClientProvider>));
const button = (label: string) => [...container.querySelectorAll<HTMLButtonElement>("button")].find(entry => entry.textContent === label)!;
await act(async () => button("Approve").click());
expect(approvalsApi.approve).not.toHaveBeenCalled();
expect(container.textContent).toContain("This is for @Dotta");
await act(async () => button("Continue").click());
expect(approvalsApi.approve).toHaveBeenCalledTimes(1);
client.clear();
});
it("shows the hire on a card with View configuration, Reject and Approve hire, and no note", async () => {
vi.mocked(approvalsApi.get).mockResolvedValue({ payload: { name: "Researcher", role: "researcher", reportsTo: "mgr", budgetMonthlyCents: 5000 } } as never);
const hire = { ...item, subject: { ...item.subject, metadata: { type: "hire_agent" } } } as AttentionItem;
const onViewDetails = vi.fn();
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
await act(async () => root.render(<QueryClientProvider client={client}>
<ApprovalResolver item={hire} companyId="company" toggle={null} presentation="card" onViewDetails={onViewDetails} shareDraft />
</QueryClientProvider>));
for (let tick = 0; tick < 3; tick++) await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
expect(container.querySelector("textarea")).toBeNull();
const panel = container.querySelector("[data-needs-you-panel]")!;
expect(panel.textContent).toContain("Researcher · $50 / month");
expect(panel.textContent).toContain("Reports to Dottabot");
const labels = [...container.querySelectorAll("[data-decision-actions] button")].map(button => button.textContent);
expect(labels).toEqual(["View configuration", "Reject", "Approve hire"]);
await act(async () => [...container.querySelectorAll<HTMLButtonElement>("[data-decision-actions] button")][0]!.click());
expect(onViewDetails).toHaveBeenCalledTimes(1);
client.clear();
});
});
@@ -0,0 +1,215 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpRight, Loader2 } from "lucide-react";
import type { Agent, AttentionItem } from "@paperclipai/shared";
import { approvalsApi } from "@/api/approvals";
import { issuesApi } from "@/api/issues";
import { buildDocumentAnnotationHash, parseDocumentAnnotationHash, type DocumentAnnotationHashTarget } from "@/lib/document-annotation-hash";
import { AttentionForOtherGate } from "@/components/AttentionCloseMenu";
import { queryKeys } from "@/lib/queryKeys";
import { attentionDetailImages, attentionImageUrl, isInlineResolvable } from "@/lib/attention";
import { AttentionInteractionResolver } from "@/components/AttentionInteractionResolver";
import { ApprovalPayloadRenderer } from "@/components/ApprovalPayload";
import { ApprovalResolver } from "@/components/AttentionQueueRow";
import { Button } from "@/components/ui/button";
import { useQueryView } from "@/components/QueryView";
import { MarkdownBody } from "@/components/MarkdownBody";
import { isImageFilename } from "@/components/task-chat/task-chat-attachments";
/** The document a card asks you to review, when it has one (a plan approval today). */
export function attentionReviewDocumentKey(item: AttentionItem): string | null {
if (item.sourceKind !== "issue_thread_interaction") return null;
const key = item.subject.metadata?.targetDocumentKey;
return typeof key === "string" && key ? key : null;
}
/**
* What a card is deciding on, when it can open beside the card (PAP-775,
* IA5/IA6): a document such as a plan, an approval's request, or the
* screenshots attached to the task.
*/
export type NeedsYouArtifact =
| { kind: "document"; key: string; issueId: string; title?: string; documentTarget?: DocumentAnnotationHashTarget; requestIssueId?: string }
| { kind: "approval"; approvalId?: string }
| { kind: "images" }
| { kind: "attachment"; assetId: string; name?: string };
export function needsYouArtifact(item: AttentionItem): NeedsYouArtifact | null {
const issueId = item.relatedIssue?.id ?? (typeof item.subject.metadata?.issueId === "string" ? item.subject.metadata.issueId : null);
const key = attentionReviewDocumentKey(item);
if (key && issueId) return { kind: "document", key, issueId, requestIssueId: issueId };
if (item.sourceKind === "approval") return { kind: "approval" };
if (attentionDetailImages(item).length > 0) return { kind: "images" };
return null;
}
/**
* An artifact a card's text links to (PAP-775): another document of a task
* (`/NEE/issues/NEE-12#document-design`), an approval, or an attachment. It
* opens beside the card like the card's own artifact. `null` for any other
* link, which keeps its normal behaviour.
*/
export function needsYouMentionedArtifact(href: string, name?: string | null): NeedsYouArtifact | null {
let url: URL;
try { url = new URL(href, "http://paperclip.local"); } catch { return null; }
if (url.origin !== "http://paperclip.local" && typeof window !== "undefined" && url.origin !== window.location.origin) return null;
const doc = parseDocumentAnnotationHash(url.hash);
const issue = url.pathname.match(/\/issues\/([^/]+)\/?$/);
if (doc && issue) {
try { return { kind: "document", issueId: doc.documentIssueId ?? decodeURIComponent(issue[1]), key: doc.documentKey, title: name?.trim() || undefined, ...(url.hash.includes("&") ? { documentTarget: doc } : {}) }; }
catch { return null; }
}
const approval = url.pathname.match(/\/approvals\/([^/]+)\/?$/);
if (approval) return { kind: "approval", approvalId: decodeURIComponent(approval[1]) };
const attachment = url.pathname.match(/^\/api\/attachments\/([^/]+)\/content\/?$/);
if (attachment && name && isImageFilename(name.trim())) return { kind: "attachment", assetId: decodeURIComponent(attachment[1]), name: name.trim() };
return null;
}
/** One id per artifact, so the same plan or approval never opens twice. */
export function needsYouArtifactId(artifact: NeedsYouArtifact, item: AttentionItem) {
if (artifact.kind === "document" && artifact.requestIssueId) return `document:interaction:${item.subject.id}`;
if (artifact.kind === "document") return `document:${artifact.issueId}:${artifact.key}${artifact.documentTarget?.revisionId ? `:${artifact.documentTarget.revisionId}` : ""}`;
if (artifact.kind === "approval") return `approval:${artifact.approvalId ?? item.subject.id}`;
if (artifact.kind === "attachment") return `attachment:${artifact.assetId}`;
return `images:${item.id}`;
}
/** "Plan", "Approval" or "Attachments": the artifact's name on its tab and button. */
export function needsYouArtifactLabel(artifact: NeedsYouArtifact) {
if (artifact.kind === "approval") return "Approval";
if (artifact.kind === "images") return "Attachments";
if (artifact.kind === "attachment") return artifact.name ?? "Attachment";
return artifact.key === "plan" ? "Plan" : artifact.title ?? artifact.key;
}
export interface CoordinatorReviewPanelProps {
companyId: string;
item: AttentionItem;
artifact: NeedsYouArtifact;
agentMap: Map<string, Agent>;
currentUserId: string | null | undefined;
userLabelMap?: ReadonlyMap<string, string>;
onOpenTask: (href: string) => void;
onResolved: () => void;
}
/**
* Focus review panel (PAP-770, PAP-775): the artifact a card asks about,
* opened beside the card. It links to the exact spot in the task and pins the
* card's own actions to the bottom. Both read the same record, so answering
* here or on the card resolves both (one record, many views).
*/
export function CoordinatorReviewPanel(props: CoordinatorReviewPanelProps) {
const { artifact, item } = props;
const requestIssueId = artifact.kind === "document" ? artifact.requestIssueId : undefined;
const request = useQuery({
queryKey: queryKeys.issues.interactions(requestIssueId ?? ""),
queryFn: () => issuesApi.listInteractions(requestIssueId!),
enabled: Boolean(requestIssueId),
});
const requestView = useQueryView(request);
if (!requestIssueId) return <CoordinatorReviewPanelContent {...props} />;
if (requestView.kind === "loading" || requestView.kind === "reconnecting") {
return <p role="status" className="text-sm text-muted-foreground">Loading the requested document…</p>;
}
const interaction = request.data?.find(entry => entry.id === item.subject.id);
const target = interaction?.kind === "request_confirmation" ? interaction.payload.target : null;
if (requestView.kind === "error" || !target || target.type !== "issue_document") {
return <div role="alert" className="space-y-2 text-sm"><p>The requested document could not be loaded.</p><Button variant="outline" onClick={() => void request.refetch()}>Retry</Button></div>;
}
const resolved: NeedsYouArtifact = { kind: "document", key: target.key, issueId: target.issueId ?? requestIssueId, requestIssueId,
documentTarget: { documentKey: target.key, revisionId: target.revisionId, interactionId: interaction!.id,
documentIssueId: target.issueId ?? requestIssueId, threadId: null, commentId: null, viewer: null } };
return <CoordinatorReviewPanelContent {...props} artifact={resolved} />;
}
function CoordinatorReviewPanelContent({ companyId, item, artifact, agentMap, currentUserId, userLabelMap, onOpenTask, onResolved }: CoordinatorReviewPanelProps) {
const task = item.relatedIssue;
const label = needsYouArtifactLabel(artifact);
const ownDocument = artifact.kind === "document" && (artifact.issueId === task?.id || artifact.requestIssueId === task?.id);
const approvalId = artifact.kind === "approval" ? artifact.approvalId ?? item.subject.id : null;
// "/NEE": the company prefix of the card's own links, for a mentioned artifact's link.
const prefix = (task?.href ?? item.subject.href ?? "").match(/^\/[^/]+/)?.[0] ?? "";
const exactHref = artifact.kind === "document" ? `${ownDocument && task?.href ? task.href : `${prefix}/issues/${artifact.requestIssueId ?? artifact.issueId}`}${buildDocumentAnnotationHash(artifact.documentTarget ?? { documentKey: artifact.key, threadId: null, commentId: null })}`
: artifact.kind === "approval" ? (approvalId === item.subject.id ? item.subject.href : `${prefix}/approvals/${approvalId}`)
: artifact.kind === "attachment" ? attachmentUrl(artifact.assetId)
: task?.href ?? item.subject.href;
const interactionIssueId = item.sourceKind === "issue_thread_interaction"
? item.relatedIssue?.id ?? (typeof item.subject.metadata?.issueId === "string" ? item.subject.metadata.issueId : null)
: null;
// Confirmation drafts/actions synchronize across views. Other interaction
// kinds keep one editable form on the card while their artifact is open.
const requestKind = item.subject.metadata?.requestKind;
const sharedInteractionActions = interactionIssueId && item.subject.metadata?.kind === "request_confirmation"
&& (requestKind == null || requestKind === "deliverable");
return <div className="flex min-h-full flex-col gap-4" data-coordinator-review-panel={item.id} data-artifact={artifact.kind}>
<div className="min-h-0 flex-1">
{artifact.kind === "document" ? <DocumentArtifact issueId={artifact.issueId} documentKey={artifact.key} label={label} revisionId={artifact.documentTarget?.revisionId} />
: artifact.kind === "approval" ? <ApprovalArtifact approvalId={approvalId!} title={approvalId === item.subject.id ? item.subject.title : null} />
: artifact.kind === "attachment" ? <AttachmentArtifact key={artifact.assetId} assetId={artifact.assetId} name={label} />
: <ImagesArtifact item={item} />}
</div>
{exactHref ? artifact.kind === "attachment" ? <a href={exactHref} target="_blank" rel="noreferrer" className="flex max-w-full items-center gap-2 text-left text-sm text-muted-foreground hover:text-foreground">
<span className="shrink-0">Open file</span><ArrowUpRight className="size-4 shrink-0" />
</a> : <button type="button" onClick={() => onOpenTask(exactHref)} className="flex max-w-full items-center gap-2 text-left text-sm text-muted-foreground hover:text-foreground">
<span className="shrink-0">{`Open in ${artifact.kind === "approval" && !task ? "approvals" : artifact.kind === "document" && !ownDocument ? artifact.issueId : task?.identifier ?? "task"}`}</span><ArrowUpRight className="size-4 shrink-0" />
</button> : null}
{/* The card's own actions, pinned to the bottom of the artifact. */}
{/* Only the buttons the card itself offers (UX1). */}
{sharedInteractionActions || (item.sourceKind === "approval" && isInlineResolvable(item)) ? <div className="coordinator-review-actions sticky bottom-0 -mx-4 border-t border-border bg-card px-4 py-3">
<AttentionForOtherGate key={`${item.id}:${item.audience?.userId}`} item={item} currentUserId={currentUserId} userLabelMap={userLabelMap}>
{sharedInteractionActions ? <AttentionInteractionResolver presentation="coordinator-decision" companyId={companyId} issueId={interactionIssueId!} interactionId={item.subject.id} shareReviseDraft
agentMap={agentMap} currentUserId={currentUserId} userLabelMap={userLabelMap}
onResolved={resolved => { if (resolved && resolved.status !== "pending") onResolved(); }} />
: <ApprovalResolver item={item} companyId={companyId} toggle={null} presentation="panel" shareDraft onResolved={onResolved} />}
</AttentionForOtherGate>
</div> : interactionIssueId ? <p className="text-sm text-muted-foreground">Answer on the inbox card while reviewing this artifact.</p> : null}
</div>;
}
function DocumentArtifact({ issueId, documentKey, label, revisionId }: { issueId: string; documentKey: string; label: string; revisionId?: string }) {
const doc = useQuery<{ title: string | null; body: string }>({
queryKey: revisionId ? [...queryKeys.issues.document(issueId, documentKey), "revision", revisionId] : queryKeys.issues.document(issueId, documentKey),
queryFn: () => revisionId ? issuesApi.getDocumentRevision(issueId, documentKey, revisionId) : issuesApi.getDocument(issueId, documentKey),
});
return <>
{/* Say the title once (IA4): a body that opens with it already shows it. */}
{doc.data?.body.trimStart().toLocaleLowerCase().startsWith(`# ${(doc.data.title ?? label).toLocaleLowerCase()}`) ? null : <h2 className="mb-4 text-lg font-medium">{doc.data?.title ?? label}</h2>}
{doc.isPending ? <p className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Loading {label.toLocaleLowerCase()}…</p>
: doc.isError || !doc.data ? <p className="text-sm text-muted-foreground">This document couldn't be loaded. Open it in the task instead.</p>
: <MarkdownBody>{doc.data.body}</MarkdownBody>}
</>;
}
function ApprovalArtifact({ approvalId, title }: { approvalId: string; title: string | null }) {
const approval = useQuery({ queryKey: queryKeys.approvals.detail(approvalId), queryFn: () => approvalsApi.get(approvalId) });
return <>
<h2 className="mb-4 text-lg font-medium">{title ?? "Approval"}</h2>
{approval.isPending ? <p className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Loading approval…</p>
: approval.isError || !approval.data ? <p className="text-sm text-muted-foreground">This approval couldn't be loaded. Open it instead.</p>
: <ApprovalPayloadRenderer type={approval.data.type} payload={approval.data.payload} hidePrimaryTitle />}
</>;
}
const attachmentUrl = (assetId: string) => `/api/attachments/${encodeURIComponent(assetId)}/content`;
function AttachmentArtifact({ assetId, name }: { assetId: string; name: string }) {
const [previewFailed, setPreviewFailed] = useState(false);
return <>
<h2 className="mb-4 text-lg font-medium">{name}</h2>
{previewFailed ? <p className="text-sm text-muted-foreground">This file cannot be previewed. Open the original file below.</p>
: <img src={attachmentUrl(assetId)} alt={name} onError={() => setPreviewFailed(true)} className="w-full rounded-md border border-border bg-muted object-contain" />}
</>;
}
function ImagesArtifact({ item }: { item: AttentionItem }) {
const images = attentionDetailImages(item);
return <>
<h2 className="mb-4 text-lg font-medium">Attachments</h2>
<div className="space-y-3">
{images.map((image, index) => <img key={`${image.assetId}-${index}`} src={attentionImageUrl(image.assetId)} alt={image.alt ?? ""} loading="lazy"
className="w-full rounded-md border border-border bg-muted object-contain" />)}
</div>
</>;
}
@@ -5,7 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CoordinatorTaskMotion } from "./CoordinatorTaskCommitment";
import { TaskChatCompactInteractionCard } from "../task-chat/TaskChatCompactInteractionCard";
import { pendingSuggestedTasksInteraction } from "@/fixtures/issueThreadInteractionFixtures";
import { pendingRequestConfirmationInteraction, pendingSuggestedTasksInteraction } from "@/fixtures/issueThreadInteractionFixtures";
import { claimReviseDraftWork, getReviseDraft, resetReviseDraftsForTests, reviseDraftKey, updateReviseDraft } from "@/lib/revise-draft-store";
import { ThemeProvider } from "@/context/ThemeContext";
import { TooltipProvider } from "../ui/tooltip";
vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: true, loaded: true, userId: "viewer" }) }));
@@ -13,11 +15,14 @@ vi.mock("@/lib/router", () => ({ Link: ({ to, children, ...props }: any) => <a h
const summaries = vi.hoisted(() => ({ rows: null as null | Array<Record<string, unknown>> }));
vi.mock("@/api/issues", () => ({ issuesApi: { summaries: vi.fn(async () => summaries.rows ?? [{ id: "task-created", identifier: "PAPER-108", title: "Write the launch post", status: "todo" }]) } }));
vi.mock("../task-chat/TaskChatRichInput", () => ({ TaskChatRichInput: ({ value, onChange, disabled }: { value: string; onChange: (value: string) => void; disabled: boolean }) => <textarea value={value} onChange={event => onChange(event.target.value)} disabled={disabled} /> }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root;
let host: HTMLDivElement;
let client: QueryClient;
beforeEach(() => {
sessionStorage.clear(); resetReviseDraftsForTests();
host = document.createElement("div"); document.body.append(host); root = createRoot(host);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
window.matchMedia = vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() });
@@ -31,6 +36,33 @@ function render(interaction: typeof pendingSuggestedTasksInteraction, onAcceptIn
}
describe("Coordinator task commitment", () => {
it("shares a pending confirmation's revision draft and in-flight action with the inbox", async () => {
const interaction = pendingRequestConfirmationInteraction;
const target = interaction.payload.target;
const key = reviseDraftKey(interaction.id, target?.type === "issue_document" ? target.revisionId : null);
updateReviseDraft(key, { revising: true, reason: "Start with a smaller change" });
let finish!: () => void;
const reject = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
await act(() => root.render(<QueryClientProvider client={client}><TooltipProvider>
<ThemeProvider><TaskChatCompactInteractionCard interaction={interaction} onAcceptInteraction={vi.fn()} onRejectInteraction={reject} showPlanPreview={false} /></ThemeProvider>
</TooltipProvider></QueryClientProvider>));
expect(host.querySelector<HTMLTextAreaElement>("textarea")?.value).toBe("Start with a smaller change");
const field = host.querySelector<HTMLTextAreaElement>("textarea")!;
await act(() => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(field, "Use the revised scope");
field.dispatchEvent(new Event("input", { bubbles: true }));
});
expect(getReviseDraft(key).reason).toBe("Use the revised scope");
const send = [...host.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent === "Request revisions")!;
await act(() => send.click());
expect(getReviseDraft(key).working).toBe("reject");
expect(claimReviseDraftWork(key, "accept")).toBe(false);
expect(send.disabled).toBe(true);
await act(() => finish());
expect(reject).toHaveBeenCalledExactlyOnceWith(interaction, "Use the revised scope");
expect(getReviseDraft(key)).toMatchObject({ revising: false, reason: "", working: null });
});
it("does not claim creation when acceptance is still pending or failed", async () => {
let fail!: (reason: Error) => void;
const accept = vi.fn(() => new Promise<void>((_, reject) => { fail = reject; }));
@@ -0,0 +1,155 @@
import type { ReactNode } from "react";
import { FileText, TriangleAlert } from "lucide-react";
import type { Agent, AttentionItem } from "@paperclipai/shared";
import { Link } from "@/lib/router";
import { readIssueReviewPolicyMetadata } from "@/lib/review-policy";
import { DecisionCardFooter } from "@/components/DecisionCardFooter";
import { StalledReviewActions } from "@/components/StalledReviewActions";
import { Button } from "@/components/ui/button";
import { NeedsYouPanel, NeedsYouPanelNote, NeedsYouPanelRow } from "./NeedsYouCardKit";
/**
* Bodies of the Needs You cards whose real action lives on the task (PAP-775,
* Paper "10", "13", "14"): the inset panel and the footer. There is no inline
* review verdict for a covered review, no inline reassign, and resolving a
* recovery also sets the task's next status, so their primary action opens the
* task. A stalled review keeps its three inline review verbs.
*/
export interface NeedsYouCardBodyProps {
item: AttentionItem;
companyId: string;
agentMap?: ReadonlyMap<string, Agent>;
userLabelMap?: ReadonlyMap<string, string>;
/** The task link at the left of the footer. */
leading?: ReactNode;
footerContext?: ReactNode;
onResolved?: () => void;
/** In-app navigation (react-router `navigate`); a plain link without it. */
onOpen?: (href: string) => void;
}
const metadataString = (item: AttentionItem, key: string) => {
const value = item.subject.metadata?.[key];
return typeof value === "string" && value ? value : null;
};
/** "NEE-19 · Review pilot consent copy". */
const taskLine = (task: { identifier?: string | null; title?: string | null }) =>
[task.identifier, task.title].filter(Boolean).join(" · ") || "Task";
/** The assignee's name, from the same agent and people lists the page reads. */
function assigneeName(item: AttentionItem, agentMap?: ReadonlyMap<string, Agent>, userLabelMap?: ReadonlyMap<string, string>): string | null {
const agentId = metadataString(item, "assigneeAgentId");
const userId = metadataString(item, "assigneeUserId");
if (agentId) return agentMap?.get(agentId)?.name ?? null;
return userId ? userLabelMap?.get(userId) ?? null : null;
}
/** The primary "Open …" action: in-app navigation when given, else a link. */
function OpenButton({ href, onOpen, variant = "default", children }: { href: string; onOpen?: (href: string) => void; variant?: "default" | "outline"; children: ReactNode }) {
if (onOpen) return <Button type="button" size="sm" variant={variant} onClick={() => onOpen(href)}>{children}</Button>;
return <Button asChild size="sm" variant={variant}><Link to={href}>{children}</Link></Button>;
}
/**
* 10 "Review a task": a task in review assigned to you. The verdict is given on
* the task, where the review stage, its policy and the comment live, so the
* card opens it.
*/
export function ReviewTaskCardBody({ item, companyId, agentMap, userLabelMap, leading, footerContext, onOpen }: NeedsYouCardBodyProps) {
const assignee = assigneeName(item, agentMap, userLabelMap);
const href = item.subject.href;
// The feed carries no acceptance checklist yet, so the panel is the state line.
return <>
<NeedsYouPanel>
<NeedsYouPanelNote>{["In review", assignee ? `Assigned to ${assignee}` : null].filter(Boolean).join(" · ")}</NeedsYouPanelNote>
</NeedsYouPanel>
{footerContext}
<DecisionCardFooter leading={leading}>
{href ? <OpenButton href={href} onOpen={onOpen}>Open task</OpenButton> : null}
</DecisionCardFooter>
</>;
}
/**
* 13 "Unblock a task": the task that is in the way (the blocker, or the
* stalled review itself) and what it blocks. A stalled review is answered here
* with its review verbs; any other blocker opens the task that is in the way.
*/
export function BlockedTaskCardBody({ item, companyId, agentMap, userLabelMap, leading, footerContext, onResolved, onOpen }: NeedsYouCardBodyProps) {
const assignee = assigneeName(item, agentMap, userLabelMap);
const stalledReview = item.sourceKind === "review";
const blocking = item.detail?.kind === "blocker" ? item.detail.blockingIssue : null;
// "/NEE": the company prefix of the card's own links.
const prefix = (item.subject.href ?? "").match(/^\/[^/]+/)?.[0] ?? "";
const blockingHref = blocking?.id || blocking?.identifier ? `${prefix}/issues/${blocking.identifier ?? blocking.id}` : null;
const href = blockingHref ?? item.subject.href;
// A human-owned unblock names the blocker and blocks the subject; a stalled
// blocker chain is the subject itself and blocks its related task.
const blocked = blocking ? item.subject : item.relatedIssue?.id !== item.subject.id ? item.relatedIssue : null;
const blockedCount = item.detail?.kind === "blocker" ? item.detail.blockedTaskCount ?? 0 : 0;
const status = item.subject.status ? `${item.subject.status[0]!.toUpperCase()}${item.subject.status.slice(1).replaceAll("_", " ")}` : null;
const meta = stalledReview ? ["Review stalled", assignee].filter(Boolean).join(" · ")
: blocking ? item.whyNow
: [status, assignee].filter(Boolean).join(" · ") || undefined;
const note = stalledReview ? "No reviewer, approval or run is moving this review."
: blocked ? `Blocks ${taskLine(blocked)}${blockedCount > 1 ? ` and ${blockedCount - 1} more` : ""}`
: blockedCount > 0 ? `Blocks ${blockedCount} ${blockedCount === 1 ? "task" : "tasks"}`
: null;
const panel = <NeedsYouPanel>
{/* Without a separate blocker the task is the footer's, so the row only says its state (IA4). */}
{blocking ? <NeedsYouPanelRow icon={<FileText />} title={taskLine(blocking)} meta={meta}
onOpen={href && onOpen ? () => onOpen(href) : undefined} /> : <NeedsYouPanelRow icon={<FileText />} title={meta ?? "Blocked"} />}
{note ? <NeedsYouPanelNote>{note}</NeedsYouPanelNote> : null}
</NeedsYouPanel>;
if (stalledReview) {
return <>
{panel}
<StalledReviewActions presentation="card" footerSlot={leading} issueId={item.subject.id} companyId={companyId}
reviewPolicy={readIssueReviewPolicyMetadata(item.subject.metadata)} approveLabel="Mark task done" onResolved={() => onResolved?.()} />
</>;
}
return <>
{panel}
{footerContext}
<DecisionCardFooter leading={leading}>
{href ? <OpenButton href={href} onOpen={onOpen}>{blockingHref ? "Open blocking task" : "Open task"}</OpenButton> : null}
</DecisionCardFooter>
</>;
}
const RECOVERY_KIND_LABELS: Record<string, string> = {
missing_disposition: "No next step chosen",
deliberate_wait_without_target: "Waiting on nothing",
stranded_assigned_issue: "Task stranded",
workspace_validation: "Workspace unavailable",
configuration_validation: "Configuration missing",
active_run_watchdog: "Run gone quiet",
issue_graph_liveness: "Task needs a next step",
};
/**
* 14 "Recover a run": what stopped and the next step. Resolving a recovery
* also sets the task's next status, so it is done in the recovery control on
* the task (PAP-749 Rule 7), which the card opens.
*/
export function RecoveryCardBody({ item, leading, footerContext, onOpen }: NeedsYouCardBodyProps) {
const kind = metadataString(item, "kind");
const title = [
kind ? RECOVERY_KIND_LABELS[kind] ?? `${kind[0]!.toUpperCase()}${kind.slice(1).replaceAll("_", " ")}` : "Recovery",
item.subject.status === "escalated" ? "Recovery escalated" : "Recovery paused",
].join(" · ");
const href = item.subject.href;
return <>
<NeedsYouPanel>
<NeedsYouPanelRow icon={<TriangleAlert className="text-amber-600 dark:text-amber-300" />} title={title} />
{/* The ask above is the recovery's next action; this says where it is done. */}
<NeedsYouPanelNote>Resolve, reassign or cancel it in the recovery control on the task.</NeedsYouPanelNote>
</NeedsYouPanel>
{footerContext}
<DecisionCardFooter leading={leading}>
{href ? <OpenButton href={href} onOpen={onOpen}>Open recovery</OpenButton> : null}
</DecisionCardFooter>
</>;
}
@@ -0,0 +1,94 @@
import type { ReactNode } from "react";
import { ArrowUpRight } from "lucide-react";
import { attentionCardKind, attentionCardType, type AttentionCardType, type AttentionItem } from "@paperclipai/shared";
import { cn } from "@/lib/utils";
/**
* The parts every Needs You card is built from (PAP-775, Paper "A · Compact
* cards"): a type label that says what to do, an inset context panel, and a
* footer with the task link on the left and the actions on the right. Each
* card type fills the panel and the actions with its own content.
*/
const CARD_TYPE_LABELS: Record<AttentionCardType, string> = {
answer_questions: "Answer questions",
make_choice: "Make a choice",
review_plan: "Review a plan",
confirm: "Confirm or decline",
suggested_tasks: "Accept suggested tasks",
review_deliverable: "Review a deliverable",
review_items: "Review items",
board_approval: "Approve a request",
join_request: "Review a join request",
tool_access: "Approve tool or secret access",
connect_service: "Connect a service",
review_task: "Review a task",
failed_run: "Fix a failed run",
budget_stop: "Resolve a budget stop",
blocked_task: "Unblock a task",
recovery: "Recover a run",
};
const APPROVAL_LABELS: Record<string, string> = {
hire_agent: "Approve an agent hire",
approve_ceo_strategy: "Approve a strategy",
budget_override_required: "Approve a budget override",
};
/** The card's type, said as what to do ("Review a plan"). */
export function needsYouCardLabel(item: AttentionItem): string {
const type = attentionCardType(item);
if (type === "board_approval") return APPROVAL_LABELS[String(item.subject.metadata?.type ?? "")] ?? CARD_TYPE_LABELS.board_approval;
if (type === "failed_run" && item.sourceKind === "agent_error_alert") return "Fix an agent error";
if (type === "budget_stop" && item.subject.metadata?.thresholdType === "soft") return "Review a budget warning";
return CARD_TYPE_LABELS[type];
}
export type NeedsYouSection = "decisions" | "problems" | "updates";
export const NEEDS_YOU_SECTIONS: Record<NeedsYouSection, { title: string }> = {
decisions: { title: "Decisions" },
problems: { title: "Problems" },
updates: { title: "Updates" },
};
export function needsYouSection(item: AttentionItem): NeedsYouSection {
return attentionCardKind(item) === "problem" ? "problems" : "decisions";
}
/** The inset panel under the ask: what the decision is about. */
export function NeedsYouPanel({ children, className }: { children: ReactNode; className?: string }) {
return <div data-needs-you-panel className={cn("flex min-w-0 flex-col gap-2 rounded-md bg-background p-3", className)}>{children}</div>;
}
/**
* One line in the panel: an icon, a title and a meta line, with ↗ when it opens
* something (a document in the side panel, a run, a person).
*/
export function NeedsYouPanelRow({ icon, title, meta, onOpen, href, label }: {
icon?: ReactNode;
title: ReactNode;
meta?: ReactNode;
onOpen?: () => void;
href?: string;
/** Accessible name for the open control; defaults to the title text. */
label?: string;
}) {
const body = <>
{icon ? <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4">{icon}</span> : null}
<span className="flex min-w-0 grow basis-0 flex-col gap-0.5">
<span className="truncate text-(length:--text-compact) font-medium leading-5 text-foreground">{title}</span>
{meta ? <span className="truncate text-xs leading-4.5 text-muted-foreground">{meta}</span> : null}
</span>
{onOpen || href ? <ArrowUpRight className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}
</>;
const className = "flex w-full min-w-0 items-center gap-2.5 text-left";
if (href) return <a href={href} aria-label={label} className={cn(className, "hover:[&_span]:text-foreground")}>{body}</a>;
if (onOpen) return <button type="button" aria-label={label} onClick={onOpen} className={cn(className, "rounded-sm hover:[&_span]:text-foreground")}>{body}</button>;
return <div className={className}>{body}</div>;
}
/** The small grey line at the bottom of a panel. */
export function NeedsYouPanelNote({ children }: { children: ReactNode }) {
return <p data-needs-you-note className="text-xs leading-4.5 text-muted-foreground">{children}</p>;
}
@@ -0,0 +1,158 @@
import { ArrowUpRight, Check, Hand, UserRound } from "lucide-react";
import { type Agent, type AttentionItem, type AttentionReceipt, type AttentionSubject } from "@paperclipai/shared";
import { AgentAvatar } from "@/components/AgentAvatar";
import { deriveInitials } from "@/components/Identity";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { StatusIcon } from "@/components/StatusIcon";
import { Button } from "@/components/ui/button";
import {
ATTENTION_NO_CLAIM_TEXT,
attentionClaimAlternative,
attentionReceiptLine,
attentionResponderText,
describeAttentionAudience,
} from "@/lib/attention-views";
import { Link } from "@/lib/router";
import { cn } from "@/lib/utils";
import { timeAgo } from "@/lib/timeAgo";
import { DecisionCardFooter } from "@/components/DecisionCardFooter";
import { NeedsYouPanel, NeedsYouPanelRow, needsYouCardLabel } from "./NeedsYouCardKit";
/**
* Who is asking (PAP-775, UI2): the requester's avatar and name, agent or
* person. A system alert nobody asked for shows nothing.
*/
export function NeedsYouRequester({ item, agentMap, userLabelMap, currentUserId }: {
item: AttentionItem;
agentMap: ReadonlyMap<string, Agent>;
userLabelMap?: ReadonlyMap<string, string> | null;
currentUserId?: string | null;
}) {
const requester = item.requester;
const base = "inline-flex min-w-0 items-center gap-2 text-xs leading-4.5 text-muted-foreground";
if (requester?.kind === "user") {
if (requester.id === currentUserId) return null;
const name = userLabelMap?.get(requester.id) ?? requester.name ?? "A teammate";
return <span data-attention-requester="user" className={base} title={name}>
<Avatar size="xs" aria-hidden="true"><AvatarFallback>{deriveInitials(name)}</AvatarFallback></Avatar><span className="truncate">from {name}</span>
</span>;
}
const agent = requester?.kind === "agent" ? agentMap.get(requester.id) : undefined;
const name = requester?.name ?? agent?.name ?? item.originAgentName;
if (!name) return null;
return <span data-attention-requester="agent" className={base} title={name}>
<AgentAvatar agent={agent ?? { id: requester?.id, name }} name={name} size={20} />
<span className="truncate">from {name}</span>
</span>;
}
/**
* The card's type, said as what to do (PAP-775, Paper "A · Compact cards").
* A card for someone else puts their name first ("@Dotta Confirm or decline");
* your own card doesn't name you. Why the card is yours stays in the tooltip.
*/
export function NeedsYouTypeLabel({ item, currentUserId, userLabelMap }: {
item: AttentionItem;
currentUserId: string | null | undefined;
userLabelMap?: ReadonlyMap<string, string> | null;
}) {
const description = currentUserId ? describeAttentionAudience(item, currentUserId) : null;
const forUserId = description?.kind === "other" ? description.userId : null;
const why = description?.kind === "mine" ? `Why me? ${description.text}${description.transferredByUserId ? ` @${userLabelMap?.get(description.transferredByUserId) ?? "someone"}` : ""}` : undefined;
return <span data-attention-type-label className="min-w-0 truncate text-xs leading-4.5 text-muted-foreground" title={why}>
{forUserId ? <span data-attention-for-user={forUserId} className="text-foreground">@{userLabelMap?.get(forUserId) ?? "someone"} </span> : null}
{needsYouCardLabel(item)}
</span>;
}
/**
* An ownerless card's corner (PAP-775, A2): "No owner yet" with Claim, or a
* link to assign it on its task. Your own and other people's cards say whose
* they are in the type label instead. The server re-checks every action.
*/
export function NeedsYouAudience({ item, currentUserId, userLabelMap, onClaim, claiming = false }: {
item: AttentionItem;
currentUserId: string | null | undefined;
userLabelMap?: ReadonlyMap<string, string> | null;
onClaim?: (item: AttentionItem) => void;
claiming?: boolean;
}) {
const description = currentUserId ? describeAttentionAudience(item, currentUserId) : null;
if (!description || description.kind === "mine" || description.kind === "other") return null;
if (description.kind === "company" && !description.claimable) return null;
const responders = attentionResponderText(item, description, userLabelMap);
const alternative = onClaim ? attentionClaimAlternative(item) : null;
return <div className="flex shrink-0 items-center gap-2 text-xs leading-4.5 text-muted-foreground" data-attention-audience={description.kind} title={responders ?? undefined}>
{description.kind === "pool" ? <span className="inline-flex items-center gap-1"><UserRound className="size-3.5" aria-hidden="true" />No owner yet</span> : null}
{description.claimable && onClaim ? <Button type="button" variant="outline" size="xs" disabled={claiming} onClick={(event) => { event.stopPropagation(); onClaim(item); }}>
<Hand className="h-3 w-3" />{claiming ? "Claiming…" : "Claim"}
</Button> : null}
{alternative?.kind === "assign" ? <Button asChild variant="outline" size="xs">
<Link to={alternative.href} disableIssueQuicklook data-attention-open-to-assign onClick={(event) => event.stopPropagation()}>Open to assign</Link>
</Button> : null}
{alternative?.kind === "none" ? <span data-attention-no-claim className="sr-only">{ATTENTION_NO_CLAIM_TEXT}</span> : null}
</div>;
}
/** The task a card belongs to, whichever field the feed put it in. */
export function needsYouTaskRef(item: AttentionItem): AttentionSubject | null {
return item.relatedIssue ?? (item.subject.kind === "issue" ? item.subject : null);
}
/**
* The footer's task link (PAP-775, UI4, UI5): the task's standard status icon,
* then its ID, then (when there is room) its title. Opens the exact spot in
* the task (IA5).
*/
export function NeedsYouTaskLink({ task, short = false, onOpen }: {
task: AttentionSubject | null;
short?: boolean;
onOpen: (href: string) => void;
}) {
if (!task?.href) return null;
const href = task.href;
return <button type="button" data-attention-task-link title={task.title ?? undefined} onClick={() => onOpen(href)}
className={cn("flex min-w-0 items-center gap-1.5 text-left text-(length:--text-compact) leading-5 text-muted-foreground hover:text-foreground", short ? "shrink-0" : "max-w-full")}>
{task.status ? <StatusIcon status={task.status} size="sm" /> : null}
<span className="min-w-0 truncate">{task.identifier ?? "Open task"}{short || !task.title ? null : ` · ${task.title}`}</span>
<ArrowUpRight className="size-4 shrink-0" />
</button>;
}
/**
* What someone else did with your request (PAP-775, Paper card 15; PAP-749
* plan §6): an Updates card. It isn't in the badge and has no ⋯ menu; Dismiss
* hides it for you, and it leaves on its own after 7 days.
*/
export function NeedsYouReceiptCard({ receipt, userLabelMap, onDismiss, onOpen, dismissing = false }: {
receipt: AttentionReceipt;
userLabelMap?: ReadonlyMap<string, string> | null;
onDismiss: (receipt: AttentionReceipt) => void;
onOpen: (href: string) => void;
dismissing?: boolean;
}) {
const actor = userLabelMap?.get(receipt.actorUserId) ?? "Someone";
const href = receipt.href ?? receipt.issue?.href ?? null;
const negative = receipt.outcome === "rejected" || receipt.outcome === "withdrawn";
return <article className="coordinator-decision-card space-y-3" data-attention-receipt={receipt.outcome} aria-label={attentionReceiptLine(receipt, userLabelMap)}>
<div className="flex items-center justify-between gap-4">
<span className="text-xs leading-4.5 text-muted-foreground">View a request update</span>
<div className="flex shrink-0 items-center gap-3 text-xs leading-4.5 text-muted-foreground">
<span className="inline-flex items-center gap-1"><Avatar size="xs" aria-hidden="true"><AvatarFallback>{deriveInitials(actor)}</AvatarFallback></Avatar>from {actor}</span>
<time dateTime={receipt.createdAt} title={new Date(receipt.createdAt).toLocaleString()}>{timeAgo(receipt.createdAt)}</time>
</div>
</div>
<div className="space-y-1.5">
<h2>{receipt.title ?? "Your request"}</h2>
{receipt.reason ? <p className="text-sm text-muted-foreground">{receipt.reason}</p> : null}
</div>
<NeedsYouPanel>
<NeedsYouPanelRow icon={negative ? <StatusIcon status="cancelled" /> : <Check className="text-(--status-task-icon-done)" />}
title={attentionReceiptLine(receipt, userLabelMap).replace(/@/g, "")} />
</NeedsYouPanel>
<DecisionCardFooter leading={receipt.issue?.href ? <NeedsYouTaskLink task={{ kind: "issue", id: receipt.issue.id, companyId: "", title: receipt.issue.title, identifier: receipt.issue.identifier, status: null, href: receipt.issue.href, metadata: {} }} onOpen={onOpen} /> : null}>
<Button type="button" variant="ghost" disabled={dismissing} onClick={() => onDismiss(receipt)}>Dismiss</Button>
{href ? <Button type="button" variant="outline" onClick={() => onOpen(href)}>View request</Button> : null}
</DecisionCardFooter>
</article>;
}