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

+111
View File
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import type { AttentionItem } from "@paperclipai/shared";
import {
attentionAlreadyClosedText,
attentionCanTransfer,
attentionCanWithdraw,
attentionHiddenState,
attentionHiddenText,
attentionOtherAudienceUserId,
attentionTransferTargets,
planStaleWithdraw,
readAttentionAlreadyClosed,
splitArchivedAttentionItems,
splitStaleAttentionItems,
} from "./attention-close";
const labels = new Map([["scott", "Scott"], ["dotta", "Dotta"], ["riley", "Riley"]]);
function item(id: string, overrides: Partial<AttentionItem> = {}) {
return {
id,
sourceKind: "issue_thread_interaction",
subject: { id: `${id}-subject` },
audience: { kind: "user", userId: "scott", reason: "addressee" },
stale: null,
closeModes: ["withdraw", "archive", "snooze"], obligationKey: null, obligationLeadId: null,
...overrides,
} as unknown as AttentionItem;
}
describe("attention close helpers (PAP-749 task 2c)", () => {
it("offers withdraw only where the server lists it, and transfer only for interactions", () => {
expect(attentionCanWithdraw(item("a"))).toBe(true);
expect(attentionCanWithdraw(item("b", { sourceKind: "failed_run", closeModes: ["archive", "snooze"] }))).toBe(false);
expect(attentionCanTransfer(item("a"))).toBe(true);
expect(attentionCanTransfer(item("c", { sourceKind: "approval" }))).toBe(false);
});
it("names the other person only for a card addressed to someone else", () => {
expect(attentionOtherAudienceUserId(item("a"), "scott")).toBeNull();
expect(attentionOtherAudienceUserId(item("a"), "dotta")).toBe("scott");
expect(attentionOtherAudienceUserId(item("p", { audience: { kind: "pool", userId: null, reason: "none" } }), "scott")).toBeNull();
expect(attentionOtherAudienceUserId(item("c", { audience: { kind: "company", userId: null, reason: "none" } }), "scott")).toBeNull();
});
it("transfers to everyone but the viewer and the current owner", () => {
const forDotta = item("d", { audience: { kind: "user", userId: "dotta", reason: "addressee" } });
expect(attentionTransferTargets(forDotta, "scott", labels).map((target) => target.label)).toEqual(["Riley"]);
expect(attentionTransferTargets(item("x", { sourceKind: "decision" }), "scott", labels)).toEqual([]);
});
it("splits stale cards from current ones, keeping order", () => {
const items = [item("1"), item("2", { stale: { reason: "aged" } }), item("3"), item("4", { stale: { reason: "issue_closed" } })];
const { current, stale } = splitStaleAttentionItems(items);
expect(current.map((entry) => entry.id)).toEqual(["1", "3"]);
expect(stale.map((entry) => entry.id)).toEqual(["2", "4"]);
});
it("withdraws in bulk only cards with a real withdraw that are not required gates", () => {
const { withdrawable, required, kept } = planStaleWithdraw([
item("q"),
item("budget", { sourceKind: "budget_alert", closeModes: ["archive", "snooze"] }),
item("hire", { sourceKind: "approval", closeModes: ["archive", "snooze"], required: true }),
item("approval", { sourceKind: "approval", required: true }),
item("governed", { required: true }),
]);
expect(withdrawable.map((entry) => entry.id)).toEqual(["q"]);
// Rule 10: a stale required card goes to a person; it never leaves in bulk.
expect(required.map((entry) => entry.id)).toEqual(["approval", "governed"]);
expect(kept.map((entry) => entry.id)).toEqual(["budget", "hire"]);
});
it('reads the 409 and says "Already answered by @x"', () => {
const error = Object.assign(new Error("Already answered"), {
status: 409,
body: { error: "Already answered", details: { code: "attention_already_closed", resolvedByUserId: "dotta", resolvedByAgentId: null } },
});
const details = readAttentionAlreadyClosed(error)!;
expect(attentionAlreadyClosedText(details, labels)).toBe("Already answered by @Dotta");
expect(readAttentionAlreadyClosed(new Error("boom"))).toBeNull();
expect(attentionAlreadyClosedText({ ...details, resolvedByUserId: null, resolvedByAgentId: "agent-1" }, labels)).toBe("Already answered by an agent");
});
});
describe("Archived view helpers (PAP-749 task 2e)", () => {
const hidden = (id: string, kind: "dismiss" | "snooze", snoozedUntil: string | null = null, isActive = true) =>
item(id, { dismissal: { kind, dismissedAt: "2026-10-29T12:00:00.000Z", snoozedUntil, isActive } });
it("reads how a card is hidden for you, and nothing for a card you did not hide", () => {
expect(attentionHiddenState(hidden("a", "dismiss"))).toEqual({ kind: "archived", since: "2026-10-29T12:00:00.000Z" });
expect(attentionHiddenState(hidden("s", "snooze", "2026-10-31T09:00:00.000Z")))
.toEqual({ kind: "snoozed", since: "2026-10-29T12:00:00.000Z", until: "2026-10-31T09:00:00.000Z" });
// A card that changed (inactive dismissal) is back in its view, not hidden.
expect(attentionHiddenState(hidden("back", "dismiss", null, false))).toBeNull();
expect(attentionHiddenState(item("plain"))).toBeNull();
});
it('says "Archived <date>" and "Back <time>"', () => {
expect(attentionHiddenText({ kind: "archived", since: "2026-10-29T12:00:00.000Z" })).toMatch(/^Archived /);
expect(attentionHiddenText({ kind: "snoozed", since: "2026-10-29T12:00:00.000Z", until: "2026-10-31T09:00:00.000Z" })).toMatch(/^Back /);
});
it("puts archived cards first and the Snoozed group soonest first", () => {
const later = hidden("later", "snooze", "2026-11-05T09:00:00.000Z");
const sooner = hidden("sooner", "snooze", "2026-10-31T09:00:00.000Z");
const archived = hidden("archived", "dismiss");
const { archived: archivedItems, snoozed } = splitArchivedAttentionItems([later, archived, sooner]);
expect(archivedItems.map((entry) => entry.id)).toEqual(["archived"]);
expect(snoozed.map((entry) => entry.id)).toEqual(["sooner", "later"]);
});
});
+176
View File
@@ -0,0 +1,176 @@
import {
ATTENTION_CLAIMABLE_SOURCE_KINDS,
attentionStaleReasonText,
type AttentionAlreadyClosedDetails,
type AttentionCloseMode,
type AttentionItem,
} from "@paperclipai/shared";
/**
* The Close… menu (PAP-749 plan §2, Rule 6) and the Stale group (§3). Pure
* helpers so both Decisions pages make the same choices. The server still
* checks every close, claim and transfer; nothing here grants authority.
*/
/**
* The Close… verbs the server listed for this card. A feed from a server
* without `closeModes` (an older cached response) offers none.
*/
export function attentionCloseModes(item: AttentionItem): readonly AttentionCloseMode[] {
return item.closeModes ?? [];
}
/** Withdraw closes the request for everyone; only some sources have one. */
export function attentionCanWithdraw(item: AttentionItem): boolean {
return attentionCloseModes(item).includes("withdraw");
}
/** Transfer stores a new addressee, so it needs a source with that field. */
export function attentionCanTransfer(item: AttentionItem): boolean {
return (ATTENTION_CLAIMABLE_SOURCE_KINDS as readonly string[]).includes(item.sourceKind);
}
/**
* The person a card is for, when that is not the viewer. Acting on such a card
* asks "This is for @x. Continue?" first (PAP-749 plan §2 and §6).
*/
export function attentionOtherAudienceUserId(
item: AttentionItem,
currentUserId: string | null | undefined,
): string | null {
const audience = item.audience;
if (!audience || audience.kind !== "user" || !audience.userId) return null;
return audience.userId === currentUserId ? null : audience.userId;
}
export function attentionUserLabel(
userId: string,
userLabelMap: ReadonlyMap<string, string> | null | undefined,
): string {
return userLabelMap?.get(userId) ?? "another person";
}
/** People the card can go to: everyone in the directory but the viewer and the current owner. */
export function attentionTransferTargets(
item: AttentionItem,
currentUserId: string | null | undefined,
userLabelMap: ReadonlyMap<string, string> | null | undefined,
): Array<{ userId: string; label: string }> {
if (!attentionCanTransfer(item) || !userLabelMap) return [];
const owner = item.audience?.kind === "user" ? item.audience.userId : null;
return [...userLabelMap]
.filter(([userId]) => userId !== currentUserId && userId !== owner)
.map(([userId, label]) => ({ userId, label }))
.sort((a, b) => a.label.localeCompare(b.label));
}
/**
* How a card in the Archived view is hidden for you (PAP-749 plan §3):
* archived until it changes, or snoozed until a time. `null` for a card you
* did not hide.
*/
export type AttentionHiddenState =
| { kind: "archived"; since: string }
| { kind: "snoozed"; since: string; until: string };
export function attentionHiddenState(item: AttentionItem): AttentionHiddenState | null {
const dismissal = item.dismissal;
if (!dismissal?.isActive) return null;
if (dismissal.kind === "snooze" && dismissal.snoozedUntil) {
return { kind: "snoozed", since: dismissal.dismissedAt, until: dismissal.snoozedUntil };
}
return { kind: "archived", since: dismissal.dismissedAt };
}
/** "Archived Oct 29" or "Back Fri, Oct 31, 9:00 AM" (local time). */
export function attentionHiddenText(hidden: AttentionHiddenState): string {
if (hidden.kind === "snoozed") {
return `Back ${new Date(hidden.until).toLocaleString(undefined, {
weekday: "short",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
})}`;
}
return `Archived ${new Date(hidden.since).toLocaleDateString(undefined, { month: "short", day: "numeric" })}`;
}
/**
* The Archived view's two parts: archived cards first, then the Snoozed group,
* which comes back soonest first.
*/
export function splitArchivedAttentionItems(items: AttentionItem[]): {
archived: AttentionItem[];
snoozed: AttentionItem[];
} {
const archived: AttentionItem[] = [];
const snoozed: AttentionItem[] = [];
for (const item of items) (attentionHiddenState(item)?.kind === "snoozed" ? snoozed : archived).push(item);
snoozed.sort((a, b) => Date.parse(a.dismissal!.snoozedUntil!) - Date.parse(b.dismissal!.snoozedUntil!));
return { archived, snoozed };
}
/** Current cards first; stale cards go to the collapsed Stale (N) group (Rule 10). */
export function splitStaleAttentionItems(items: AttentionItem[]): {
current: AttentionItem[];
stale: AttentionItem[];
} {
const current: AttentionItem[] = [];
const stale: AttentionItem[] = [];
for (const item of items) (item.stale ? stale : current).push(item);
return { current, stale };
}
/**
* What "Withdraw all stale" does (PAP-749 plan §2, Rule 10). It withdraws only
* cards with a real withdraw that are not required gates. Required approvals
* and governed requests go to a person and never leave in bulk; a person can
* still withdraw one from its own Close… menu. Cards with no request to
* withdraw (failed runs, reviews, budget) also stay. The confirmation lists
* all three, so nothing closes without the person seeing it.
*/
export function planStaleWithdraw(items: AttentionItem[]): {
withdrawable: AttentionItem[];
required: AttentionItem[];
kept: AttentionItem[];
} {
const withdrawable: AttentionItem[] = [];
const required: AttentionItem[] = [];
const kept: AttentionItem[] = [];
for (const item of items) {
if (!attentionCanWithdraw(item)) kept.push(item);
else if (item.required) required.push(item);
else withdrawable.push(item);
}
return { withdrawable, required, kept };
}
export function attentionStaleChipText(item: AttentionItem): string | null {
return item.stale ? attentionStaleReasonText(item.stale.reason) : null;
}
/** The 409 the close, claim and transfer endpoints send when someone else was first. */
export function readAttentionAlreadyClosed(error: unknown): AttentionAlreadyClosedDetails | null {
if (!error || typeof error !== "object") return null;
const body = (error as { body?: unknown }).body;
if (!body || typeof body !== "object") return null;
const details = (body as { details?: unknown }).details;
if (!details || typeof details !== "object") return null;
return (details as { code?: unknown }).code === "attention_already_closed"
? details as AttentionAlreadyClosedDetails
: null;
}
/** "Already answered by @x" (PAP-749 plan §2, "Two persons answer at the same time"). */
export function attentionAlreadyClosedText(
details: AttentionAlreadyClosedDetails,
userLabelMap: ReadonlyMap<string, string> | null | undefined,
): string {
if (details.resolvedByUserId) return `Already answered by @${attentionUserLabel(details.resolvedByUserId, userLabelMap)}`;
return details.resolvedByAgentId ? "Already answered by an agent" : "Already answered";
}
export function attentionForOtherText(name: string, verb: "withdraw" | "continue"): string {
return verb === "withdraw" ? `This is for @${name}. Withdraw anyway?` : `This is for @${name}. Continue?`;
}
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import type { AttentionItem } from "@paperclipai/shared";
import {
attentionEvidenceLabel,
attentionEvidenceText,
attentionObligationEvidence,
foldAttentionObligations,
isAttentionObligationEvidence,
} from "./attention-obligations";
function item(id: string, overrides: Partial<AttentionItem> = {}): AttentionItem {
return {
id,
sourceKind: "approval",
subject: { kind: "approval", id, companyId: "c1", title: `Card ${id}`, identifier: null, status: null, href: `/PAP/x/${id}` },
whyNow: `Why ${id}`,
detail: null,
obligationKey: null,
obligationLeadId: null,
...overrides,
} as AttentionItem;
}
describe("one card for each obligation (PAP-749 task 2d)", () => {
const approval = item("approval:a1", { obligationKey: "approval:a1", obligationLeadId: "approval:a1" });
const review = item("review:t1", {
sourceKind: "review",
subject: { kind: "issue", id: "t1", companyId: "c1", title: "Ship the page", identifier: "PAP-7", status: "in_review", href: "/PAP/issues/PAP-7" },
whyNow: "Issue is in review with a linked pending approval.",
obligationKey: "approval:a1",
obligationLeadId: "approval:a1",
});
const solo = item("decision:d1", { sourceKind: "decision" });
it("folds evidence into its lead and keeps every other card", () => {
const folded = foldAttentionObligations([review, solo, approval]);
expect(folded.cards.map((card) => card.id)).toEqual(["decision:d1", "approval:a1"]);
expect(attentionObligationEvidence(folded, approval)).toEqual([review]);
expect(attentionObligationEvidence(folded, solo)).toEqual([]);
expect(isAttentionObligationEvidence(review)).toBe(true);
expect(isAttentionObligationEvidence(approval)).toBe(false);
expect(isAttentionObligationEvidence(solo)).toBe(false);
});
it("keeps evidence as its own card when its lead is not in the list", () => {
const folded = foldAttentionObligations([review, solo]);
expect(folded.cards.map((card) => card.id)).toEqual(["review:t1", "decision:d1"]);
expect(folded.evidenceByLeadId.size).toBe(0);
});
it("names what each evidence card is to its lead", () => {
const run = item("failed_run:run:r1", { sourceKind: "failed_run" });
const blocked = item("blocker_attention:blocker:t2", { sourceKind: "blocker_attention" });
const blockedOwner = item("blocker_attention:blocked-owner:t2", { sourceKind: "blocker_attention" });
expect(attentionEvidenceLabel(approval, review)).toBe("Task waiting on this approval");
expect(attentionEvidenceLabel(run, blocked)).toBe("Blocked by this run");
expect(attentionEvidenceLabel(blockedOwner, blocked)).toBe("Blocked work");
expect(attentionEvidenceLabel(run, item("failed_run:run:r2", { sourceKind: "failed_run" }))).toBe("Also failed");
// PAP-768: a hard stop's Raise limit / Keep paused answer its override approval.
const stop = item("budget_alert:budget:p1", { sourceKind: "budget_alert" });
expect(attentionEvidenceLabel(stop, item("approval:approval:b1"))).toBe("Approval this answers");
expect(attentionEvidenceText(review)).toEqual({
title: "PAP-7 Ship the page",
detail: "Issue is in review with a linked pending approval.",
});
});
});
+67
View File
@@ -0,0 +1,67 @@
import type { AttentionItem } from "@paperclipai/shared";
import { attentionDetailLine, sourceMeta } from "./attention";
/**
* One card for each obligation (PAP-749 plan §2, Rule 11). The server keeps
* every card and marks the ones that are one obligation with a shared
* `obligationKey` and the id of the lead card; the page shows the lead and
* folds the others into it as evidence.
*/
export interface FoldedAttentionObligations {
/** The cards to show: each lead, each card that is its own obligation, and evidence whose lead is not in the list. */
cards: AttentionItem[];
/** The evidence cards folded into each shown lead, keyed by the lead's `id`. */
evidenceByLeadId: ReadonlyMap<string, AttentionItem[]>;
}
const NO_EVIDENCE: readonly AttentionItem[] = [];
export function isAttentionObligationEvidence(item: AttentionItem): boolean {
return item.obligationLeadId != null && item.obligationLeadId !== item.id;
}
/**
* Fold evidence into its lead. An evidence card whose lead is not in `items`
* stays a card of its own, so nothing of the obligation disappears.
*/
export function foldAttentionObligations(items: readonly AttentionItem[]): FoldedAttentionObligations {
const ids = new Set(items.map((item) => item.id));
const cards: AttentionItem[] = [];
const evidenceByLeadId = new Map<string, AttentionItem[]>();
for (const item of items) {
if (isAttentionObligationEvidence(item) && ids.has(item.obligationLeadId!)) {
evidenceByLeadId.set(item.obligationLeadId!, [...(evidenceByLeadId.get(item.obligationLeadId!) ?? []), item]);
} else {
cards.push(item);
}
}
return { cards, evidenceByLeadId };
}
export function attentionObligationEvidence(
folded: FoldedAttentionObligations,
item: AttentionItem,
): readonly AttentionItem[] {
return folded.evidenceByLeadId.get(item.id) ?? NO_EVIDENCE;
}
/**
* What an evidence card is to its lead: the task that waits on the approval,
* the work a failed run blocks, or another cause.
*/
export function attentionEvidenceLabel(lead: AttentionItem, evidence: AttentionItem): string {
if (evidence.sourceKind === "review") return lead.sourceKind === "approval" ? "Task waiting on this approval" : "Task in review";
if (evidence.sourceKind === "blocker_attention") return lead.sourceKind === "failed_run" ? "Blocked by this run" : "Blocked work";
if (evidence.sourceKind === "failed_run") return "Also failed";
// Raise limit approves the override approval and Keep paused rejects it (PAP-768).
if (evidence.sourceKind === "approval" && lead.sourceKind === "budget_alert") return "Approval this answers";
return sourceMeta(evidence.sourceKind).label;
}
/** The one line an evidence card adds: what it is about and what it says. */
export function attentionEvidenceText(evidence: AttentionItem): { title: string; detail: string | null } {
const subject = evidence.subject;
const title = [subject.identifier, subject.title].filter(Boolean).join(" ") || sourceMeta(evidence.sourceKind).label;
const detail = attentionDetailLine(evidence) ?? evidence.whyNow;
return { title, detail: detail && detail !== subject.title ? detail : null };
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import type { AttentionItem } from "@paperclipai/shared";
import { attentionRecordQueryKeys } from "./attention-record-views";
import { queryKeys } from "./queryKeys";
function item(sourceKind: AttentionItem["sourceKind"], subject: Partial<AttentionItem["subject"]>, overrides: Partial<AttentionItem> = {}) {
return {
id: `${sourceKind}-card`,
sourceKind,
subject: { id: "source-1", metadata: {}, ...subject },
relatedIssue: null,
...overrides,
} as unknown as AttentionItem;
}
describe("attentionRecordQueryKeys (PAP-771: one record, many views)", () => {
it("refreshes the task's interactions under both its UUID and identifier, plus chat", () => {
const keys = attentionRecordQueryKeys("company-1", item(
"issue_thread_interaction",
{ metadata: { issueId: "issue-1" } },
{ relatedIssue: { id: "issue-1", identifier: "NEE-39" } as AttentionItem["relatedIssue"] },
));
expect(keys).toEqual([
queryKeys.attention("company-1"),
queryKeys.issues.interactions("issue-1"),
queryKeys.issues.interactions("NEE-39"),
["issues", "pending-questions"],
["issues", "decision-receipts"],
]);
});
it("refreshes an open approval page and every approval list", () => {
expect(attentionRecordQueryKeys("company-1", item("approval", { id: "approval-1" }))).toEqual([
queryKeys.attention("company-1"),
["approvals", "company-1"],
queryKeys.approvals.detail("approval-1"),
]);
});
it("refreshes an open decision, whose detail key sits outside the company prefix", () => {
expect(attentionRecordQueryKeys("company-1", item("decision", { id: "decision-1" }))).toContainEqual(
queryKeys.decisions.detail("decision-1"),
);
});
it("refreshes the budget page and the hard stop's folded override approval", () => {
expect(attentionRecordQueryKeys("company-1", item("budget_alert", { id: "incident-1", metadata: { approvalId: "approval-9" } }))).toEqual([
queryKeys.attention("company-1"),
queryKeys.budgets.overview("company-1"),
["approvals", "company-1"],
queryKeys.approvals.detail("approval-9"),
]);
});
it("keeps join requests on their own list", () => {
expect(attentionRecordQueryKeys("company-1", item("join_request", { id: "join-1" }))).toEqual([
queryKeys.attention("company-1"),
queryKeys.access.joinRequests("company-1"),
]);
});
});
+66
View File
@@ -0,0 +1,66 @@
import type { QueryClient } from "@tanstack/react-query";
import type { AttentionItem } from "@paperclipai/shared";
import { queryKeys } from "./queryKeys";
/**
* One record, many views (PAP-749 design review, Part 2). A card's source
* record also shows in task detail, chat, and the approval, decision and
* budget pages. After a person acts on a card, each of those reads refetches,
* not only the Needs You feed. Other people's open pages get the same change
* from LiveUpdatesProvider.
*/
export function attentionRecordQueryKeys(companyId: string, item: AttentionItem): ReadonlyArray<readonly unknown[]> {
const keys: Array<readonly unknown[]> = [queryKeys.attention(companyId)];
const metadata = item.subject.metadata;
switch (item.sourceKind) {
case "issue_thread_interaction": {
// Task detail caches interactions under the route's identifier, while
// the card resolver uses the task UUID.
const refs = new Set(
[metadata?.issueId, item.relatedIssue?.id, item.relatedIssue?.identifier]
.filter((ref): ref is string => typeof ref === "string" && ref.length > 0),
);
for (const ref of refs) keys.push(queryKeys.issues.interactions(ref));
keys.push(["issues", "pending-questions"], ["issues", "decision-receipts"]);
break;
}
case "approval":
keys.push(["approvals", companyId], queryKeys.approvals.detail(item.subject.id));
break;
case "decision":
keys.push(["decisions", companyId], queryKeys.decisions.detail(item.subject.id), ["issues", "decision-receipts"]);
break;
case "join_request":
keys.push(queryKeys.access.joinRequests(companyId));
break;
case "budget_alert": {
// A hard stop answers its override approval in the same write (PAP-768).
keys.push(queryKeys.budgets.overview(companyId), ["approvals", companyId]);
const approvalId = metadata?.approvalId;
if (typeof approvalId === "string" && approvalId) keys.push(queryKeys.approvals.detail(approvalId));
break;
}
}
return keys;
}
export function invalidateAttentionRecordViews(queryClient: QueryClient, companyId: string, item: AttentionItem) {
for (const queryKey of attentionRecordQueryKeys(companyId, item)) {
void queryClient.invalidateQueries({ queryKey });
}
}
/**
* One record, many views, in every direction (PAP-775, UX2). After a person
* answers, accepts, rejects or withdraws an interaction in Needs You, the
* agent's chat or task detail, every open view of it refetches in this tab:
* the Needs You feed and badge, the chat's pending question and receipts, and
* the task's interaction list under both its UUID and its identifier key.
* Other people's tabs get the same change from LiveUpdatesProvider.
*/
export function invalidateInteractionRecordViews(queryClient: QueryClient, companyId: string) {
void queryClient.invalidateQueries({ queryKey: ["issues", "interactions"] });
void queryClient.invalidateQueries({ queryKey: queryKeys.attention(companyId) });
void queryClient.invalidateQueries({ queryKey: ["issues", "pending-questions"] });
void queryClient.invalidateQueries({ queryKey: ["issues", "decision-receipts"] });
}
+167
View File
@@ -0,0 +1,167 @@
import { describe, expect, it } from "vitest";
import type { AttentionAudience, AttentionItem, AttentionReceipt, AttentionSourceKind } from "@paperclipai/shared";
import {
ATTENTION_COMPANY_AUDIENCE_TEXT,
ATTENTION_POOL_AUDIENCE_TEXT,
attentionAudienceLineNamesResponders,
attentionClaimAlternative,
attentionEveryoneViewAllowed,
attentionItemClaimable,
attentionReceiptLine,
attentionResponderText,
attentionUnownedAudienceText,
attentionViewsFor,
describeAttentionAudience,
parseAttentionView,
unassignedBannerText,
} from "./attention-views";
import { coordinatorAttentionQueryKey } from "./coordinator-attention";
function item(audience: AttentionAudience, sourceKind: AttentionSourceKind = "issue_thread_interaction") {
return { id: "card", sourceKind, audience, subject: { id: "card" } } as unknown as AttentionItem;
}
describe("attention views (PAP-749 task 1b)", () => {
it("defaults to For you and keeps only the three known views", () => {
expect(parseAttentionView(null)).toBe("mine");
expect(parseAttentionView("all")).toBe("mine");
expect(parseAttentionView("bogus")).toBe("mine");
expect(parseAttentionView("unassigned")).toBe("unassigned");
expect(parseAttentionView("company")).toBe("company");
});
it("opens Everyone only for a board member (PAP-768)", () => {
expect(parseAttentionView("all", { everyone: true })).toBe("all");
expect(parseAttentionView("all", { everyone: false })).toBe("mine");
expect(attentionViewsFor(false)).toEqual(["mine", "unassigned", "company", "archived"]);
expect(attentionViewsFor(true)).toEqual(["mine", "unassigned", "company", "archived", "all"]);
});
it("treats owners, admins, operators and legacy members as board members, not viewers (PAP-768)", () => {
const member = (membershipRole: "owner" | "admin" | "operator" | "viewer" | "member" | null, status: "active" | "suspended" = "active") =>
({ source: "session", isInstanceAdmin: false, memberships: [{ companyId: "c1", membershipRole, status }] });
for (const role of ["owner", "admin", "operator", "member"] as const) {
expect(attentionEveryoneViewAllowed("c1", member(role))).toBe(true);
}
expect(attentionEveryoneViewAllowed("c1", member("viewer"))).toBe(false);
expect(attentionEveryoneViewAllowed("c1", member(null))).toBe(false);
expect(attentionEveryoneViewAllowed("c1", member("owner", "suspended"))).toBe(false);
expect(attentionEveryoneViewAllowed("c2", member("owner"))).toBe(false);
expect(attentionEveryoneViewAllowed("c1", { source: "local_implicit", isInstanceAdmin: false, memberships: [] })).toBe(true);
expect(attentionEveryoneViewAllowed("c1", { source: "session", isInstanceAdmin: true, memberships: [] })).toBe(true);
expect(attentionEveryoneViewAllowed("c1", undefined)).toBe(false);
expect(attentionEveryoneViewAllowed(null, member("owner"))).toBe(false);
});
it("keys each list by company, person and view", () => {
expect(coordinatorAttentionQueryKey("c1", "scott", "mine")).not.toEqual(coordinatorAttentionQueryKey("c1", "dotta", "mine"));
expect(coordinatorAttentionQueryKey("c1", "scott", "mine")).not.toEqual(coordinatorAttentionQueryKey("c1", "scott", "unassigned"));
expect(coordinatorAttentionQueryKey("c1", "scott", "mine").slice(0, 4)).toEqual(["attention", "c1", "scott", "mine"]);
});
it("answers Why me? for your own card from the audience reason", () => {
expect(describeAttentionAudience(item({ kind: "user", userId: "scott", reason: "addressee" }), "scott"))
.toEqual({ kind: "mine", text: "Sent to you" });
expect(describeAttentionAudience(item({ kind: "user", userId: "scott", reason: "reviewer" }), "scott"))
.toEqual({ kind: "mine", text: "You are the reviewer" });
expect(describeAttentionAudience(item({ kind: "user", userId: "scott", reason: "instigator" }), "scott"))
.toEqual({ kind: "mine", text: "You created the original task" });
expect(describeAttentionAudience(item({ kind: "user", userId: "scott", reason: "escalation_owner" }), "scott"))
.toEqual({ kind: "mine", text: "You are the default decision owner" });
});
it("names the project and budget escalation owners (PAP-749 task 1d)", () => {
expect(describeAttentionAudience(item({ kind: "user", userId: "riley", reason: "project_owner" }), "riley"))
.toEqual({ kind: "mine", text: "You own this project's decisions" });
const budgetStop = item({ kind: "user", userId: "scott", reason: "budget_owner", alsoInCompany: true }, "budget_alert");
expect(describeAttentionAudience(budgetStop, "scott")).toEqual({ kind: "mine", text: "You own budget escalation" });
// Company still shows the hard stop to everyone else, as "For @scott".
expect(describeAttentionAudience(budgetStop, "dotta")).toEqual({ kind: "other", userId: "scott" });
expect(attentionItemClaimable(budgetStop)).toBe(false);
});
it("names the other person on a card that is not yours", () => {
expect(describeAttentionAudience(item({ kind: "user", userId: "dotta", reason: "addressee" }), "scott"))
.toEqual({ kind: "other", userId: "dotta" });
});
it("says why an ownerless card is answerable and offers Claim only where an addressee can be stored", () => {
expect(describeAttentionAudience(item({ kind: "pool", userId: null, reason: "none" }), "scott"))
.toEqual({ kind: "pool", text: ATTENTION_POOL_AUDIENCE_TEXT, claimable: true });
expect(describeAttentionAudience(item({ kind: "pool", userId: null, reason: "none" }, "decision"), "scott"))
.toEqual({ kind: "pool", text: ATTENTION_POOL_AUDIENCE_TEXT, claimable: false });
// An ownerless interaction that moved to Company after 7 days can still be claimed.
expect(describeAttentionAudience(item({ kind: "company", userId: null, reason: "none" }), "scott"))
.toEqual({ kind: "company", text: ATTENTION_COMPANY_AUDIENCE_TEXT, claimable: true });
expect(attentionItemClaimable(item({ kind: "company", userId: null, reason: "none" }, "failed_run"))).toBe(false);
expect(attentionItemClaimable(item({ kind: "user", userId: "dotta", reason: "addressee" }))).toBe(false);
});
it("says \"Transferred by\" on a card routed to you (PAP-749 plan §6)", () => {
expect(describeAttentionAudience(item({ kind: "user", userId: "riley", reason: "addressee", transferredByUserId: "scott" }), "riley"))
.toEqual({ kind: "mine", text: "Transferred by", transferredByUserId: "scott" });
});
it("phrases receipts with display names, never IDs", () => {
const labels = new Map([["scott", "Scott"], ["riley", "Riley"]]);
const receipt = (outcome: AttentionReceipt["outcome"], transferredToUserId: string | null = null) =>
({ outcome, actorUserId: "scott", transferredToUserId }) as AttentionReceipt;
expect(attentionReceiptLine(receipt("answered"), labels)).toBe("Answered by @Scott");
expect(attentionReceiptLine(receipt("withdrawn"), labels)).toBe("Withdrawn by @Scott");
expect(attentionReceiptLine(receipt("transferred", "riley"), labels)).toBe("Transferred to @Riley by @Scott");
expect(attentionReceiptLine(receipt("approved"), null)).toBe("Approved by @someone");
});
it("says who may answer in the same statement as why the card is here (PAP-767)", () => {
const resolver = (overrides: Partial<NonNullable<AttentionItem["resolverAudience"]>> = {}) => ({
requestedResolverPolicy: "anyone", effectiveResolverPolicy: "anyone", effectiveResolverPolicySource: "requested",
resolverPolicyProvenance: "inherited", addresseeAgentId: null, addresseeUserId: null, addresseeName: null,
createdByAgentId: "agent-1", createdByAgentName: "Watchdog", ...overrides,
}) as NonNullable<AttentionItem["resolverAudience"]>;
const card = (audience: AttentionAudience, resolverAudience: AttentionItem["resolverAudience"]) =>
({ ...item(audience), resolverAudience }) as AttentionItem;
const describe_ = (entry: AttentionItem, viewer: string) => describeAttentionAudience(entry, viewer)!;
// NEE-15: the project owner's card is open to anyone, so others may answer it too.
const owned = card({ kind: "user", userId: "dotta", reason: "project_owner" }, resolver());
expect(attentionResponderText(owned, describe_(owned, "dotta"))).toBe("Anyone else can answer it too.");
const sent = card({ kind: "user", userId: "dotta", reason: "addressee" }, resolver({ addresseeUserId: "dotta" }));
expect(attentionResponderText(sent, describe_(sent, "dotta"))).toBe("Only you can answer it.");
expect(attentionResponderText(sent, describe_(sent, "scott"), new Map([["dotta", "Dotta"]]))).toBe("Only @Dotta can answer it.");
// An ownerless card addressed to a napping agent names the agent and the board, once.
const napping = card({ kind: "pool", userId: null, reason: "none" }, resolver({ addresseeAgentId: "agent-2", addresseeName: "Napping Agent" }));
const pool = describe_(napping, "scott") as Extract<ReturnType<typeof describeAttentionAudience>, { kind: "pool" }>;
expect(attentionUnownedAudienceText(napping, pool)).toBe("No owner yet. Napping Agent or any board member can answer it.");
const boardOnly = card({ kind: "pool", userId: null, reason: "none" }, resolver({ effectiveResolverPolicy: "human_only" }));
expect(attentionUnownedAudienceText(boardOnly, pool)).toBe("No owner yet. Any board member can answer it.");
const notCreator = card({ kind: "pool", userId: null, reason: "none" }, resolver({ effectiveResolverPolicy: "not_creator" }));
expect(attentionUnownedAudienceText(notCreator, pool)).toBe("No owner yet. Anyone except Watchdog can answer it.");
// A card with no resolver facts (an approval, a recovery) keeps the plain line.
const approval = { ...item({ kind: "pool", userId: null, reason: "none" }, "approval"), resolverAudience: null } as AttentionItem;
expect(attentionUnownedAudienceText(approval, pool)).toBe(ATTENTION_POOL_AUDIENCE_TEXT);
expect(attentionAudienceLineNamesResponders(napping, "scott")).toBe(true);
expect(attentionAudienceLineNamesResponders(napping, null)).toBe(false);
expect(attentionAudienceLineNamesResponders(approval, "scott")).toBe(false);
});
it("offers the task instead of Claim on an ownerless card with no owner field (PAP-767)", () => {
const pool: AttentionAudience = { kind: "pool", userId: null, reason: "none" };
const withTask = { ...item(pool, "blocker_attention"), subject: { id: "i", kind: "issue", href: "/NEE/issues/NEE-16" } } as unknown as AttentionItem;
expect(attentionClaimAlternative(withTask)).toEqual({ kind: "assign", href: "/NEE/issues/NEE-16" });
const noTask = { ...item(pool, "approval"), relatedIssue: null } as AttentionItem;
expect(attentionClaimAlternative(noTask)).toEqual({ kind: "none" });
// Claim itself, a card for a person and a company alert need no alternative.
expect(attentionClaimAlternative(item(pool))).toBeNull();
expect(attentionClaimAlternative(item({ kind: "user", userId: "scott", reason: "addressee" }, "approval"))).toBeNull();
expect(attentionClaimAlternative({ ...item({ kind: "company", userId: null, reason: "none" }, "failed_run"), stale: null } as AttentionItem)).toBeNull();
const unowned = { ...item({ kind: "company", userId: null, reason: "none" }, "blocker_attention"), stale: { reason: "unowned" },
subject: { id: "i", kind: "issue", href: "/NEE/issues/NEE-9" } } as unknown as AttentionItem;
expect(attentionClaimAlternative(unowned)).toEqual({ kind: "assign", href: "/NEE/issues/NEE-9" });
});
it("phrases the Unassigned banner", () => {
expect(unassignedBannerText(1)).toBe("1 card needs an owner");
expect(unassignedBannerText(3)).toBe("3 cards need an owner");
});
});
+202
View File
@@ -0,0 +1,202 @@
import {
ATTENTION_CLAIMABLE_SOURCE_KINDS,
ATTENTION_PERSONAL_VIEWS,
attentionAudienceReasonText,
attentionReceiptText,
type AttentionItem,
type AttentionPersonalView,
type AttentionReceipt,
type AttentionViewCounts,
} from "@paperclipai/shared";
import type { CurrentBoardAccess } from "@/api/access";
/**
* The view switch on the classic Decisions page and Coordinator Needs You
* (PAP-749 plan §1, Rule 3; §3). "For you" is the default; the URL keeps the
* others so a link (and the Unassigned banner) can open them directly.
* Archived holds the cards you archived or snoozed for yourself. Everyone
* holds every person's cards, for board members only (PAP-768).
*/
export const ATTENTION_VIEW_LABELS: Record<AttentionPersonalView, string> = {
mine: "For you",
unassigned: "Unassigned",
company: "Company",
archived: "Archived",
all: "Everyone",
};
export const ATTENTION_VIEW_PARAM = "view";
/** The views a person can switch to: Everyone only for a board member. */
export function attentionViewsFor(everyone: boolean): readonly AttentionPersonalView[] {
return everyone ? ATTENTION_PERSONAL_VIEWS : ATTENTION_PERSONAL_VIEWS.filter((view) => view !== "all");
}
/** The view a URL asks for; "For you" when it names a view this person cannot open. */
export function parseAttentionView(value: string | null | undefined, options: { everyone?: boolean } = {}): AttentionPersonalView {
return (attentionViewsFor(options.everyone === true) as readonly string[]).includes(value ?? "")
? value as AttentionPersonalView
: "mine";
}
export const EMPTY_ATTENTION_VIEW_COUNTS: AttentionViewCounts = { mine: 0, unassigned: 0, company: 0, archived: 0, all: 0 };
/**
* Whether the signed-in person is a board member of `companyId`, who may see
* Everyone (PAP-768): a local board, an instance admin, or an active member
* who can act (owner, admin, operator, or a legacy member). A viewer cannot
* act on another person's card, so the tab stays hidden. False while the
* access snapshot is unknown. The server still checks every action.
*/
export function attentionEveryoneViewAllowed(
companyId: string | null | undefined,
boardAccess: Pick<CurrentBoardAccess, "source" | "isInstanceAdmin" | "memberships"> | null | undefined,
): boolean {
if (!boardAccess || !companyId) return false;
if (boardAccess.source === "local_implicit" || boardAccess.isInstanceAdmin) return true;
const membership = boardAccess.memberships?.find((entry) => entry.companyId === companyId && entry.status === "active");
return Boolean(membership?.membershipRole && membership.membershipRole !== "viewer");
}
/** "N cards need an owner" (recommendation e). Never part of the badge. */
export function unassignedBannerText(count: number) {
return count === 1 ? "1 card needs an owner" : `${count} cards need an owner`;
}
/**
* What a card says about its audience (PAP-749 plan §1, Rule 4). A card for
* you says why ("Sent to you"); a card for a different person shows "For
* @name"; an ownerless card says why you can still answer it and whether you
* can claim it; a company alert says it is for operators. Placement only: the
* resolver policy, not this line, decides who may act.
*/
export type AttentionAudienceDescription =
| { kind: "mine"; text: string; transferredByUserId?: string }
| { kind: "other"; userId: string }
| { kind: "pool"; text: string; claimable: boolean }
| { kind: "company"; text: string; claimable: boolean };
export const ATTENTION_POOL_AUDIENCE_TEXT = "No owner yet. Any board member can answer it.";
export const ATTENTION_COMPANY_AUDIENCE_TEXT = "Company alert for operators";
/**
* Whether Claim can store an owner for this card. Only sources with an
* addressee field qualify, and only while nobody owns the card: in the pool,
* or moved to Company after a week without an owner.
*/
export function attentionItemClaimable(item: AttentionItem): boolean {
const audience = item.audience;
if (!audience || audience.userId) return false;
if (audience.kind !== "pool" && audience.kind !== "company") return false;
return (ATTENTION_CLAIMABLE_SOURCE_KINDS as readonly string[]).includes(item.sourceKind);
}
/**
* What an ownerless card offers when Claim cannot store an owner on it
* (PAP-767): its task, where a person can be assigned, which gives the card
* that owner. A card with no task (an approval no task waits on) says it
* cannot be claimed instead of showing nothing. `null` for a claimable card
* and for a company alert, which nobody owns by design.
*/
export type AttentionClaimAlternative = { kind: "assign"; href: string } | { kind: "none" };
export function attentionClaimAlternative(item: AttentionItem): AttentionClaimAlternative | null {
const audience = item.audience;
if (!audience || audience.userId || attentionItemClaimable(item)) return null;
const unowned = audience.kind === "pool" || (audience.kind === "company" && item.stale?.reason === "unowned");
if (!unowned) return null;
const task = item.relatedIssue ?? (item.subject.kind === "issue" ? item.subject : null);
return task?.href ? { kind: "assign", href: task.href } : { kind: "none" };
}
export const ATTENTION_NO_CLAIM_TEXT = "It has no task to assign, so it can't be claimed.";
export function describeAttentionAudience(
item: AttentionItem,
currentUserId: string | null | undefined,
): AttentionAudienceDescription | null {
const audience = item.audience;
if (!audience) return null;
if (audience.kind === "user" && audience.userId) {
if (audience.userId !== currentUserId) return { kind: "other", userId: audience.userId };
// "Transferred by @x" replaces "Sent to you" (PAP-749 plan §6, Rule 12).
if (audience.transferredByUserId) {
return { kind: "mine", text: "Transferred by", transferredByUserId: audience.transferredByUserId };
}
const text = attentionAudienceReasonText(audience.reason);
return text ? { kind: "mine", text } : null;
}
if (audience.kind === "pool") {
return { kind: "pool", text: ATTENTION_POOL_AUDIENCE_TEXT, claimable: attentionItemClaimable(item) };
}
return { kind: "company", text: ATTENTION_COMPANY_AUDIENCE_TEXT, claimable: attentionItemClaimable(item) };
}
/**
* Who may answer an interaction card, worded to agree with its audience line
* so the two read as one statement (PAP-767): "Why me? You own this project's
* decisions. Anyone else can answer it too." and "No owner yet. Napping Agent
* or any board member can answer it." It reads the server-evaluated resolver
* facts, in the precedence of `describeResolverAudience`. `null` when the
* card carries no resolver facts: then the plain audience line stands alone.
*/
export function attentionResponderText(
item: Pick<AttentionItem, "sourceKind" | "resolverAudience">,
description: AttentionAudienceDescription,
userLabelMap?: ReadonlyMap<string, string> | null,
): string | null {
const facts = item.sourceKind === "issue_thread_interaction" ? item.resolverAudience : null;
if (!facts) return null;
const mine = description.kind === "mine";
const too = mine ? " too" : "";
if (facts.addresseeUserId) {
if (mine) return "Only you can answer it.";
return `Only @${userLabelMap?.get(facts.addresseeUserId) ?? "the addressed person"} can answer it.`;
}
if (facts.effectiveResolverPolicy === "human_only") return `Any board member can answer it${too}.`;
if (facts.addresseeAgentId) return `${facts.addresseeName?.trim() || "The addressed agent"} or any board member can answer it${too}.`;
if (facts.effectiveResolverPolicy === "not_creator") {
return `Anyone except ${facts.createdByAgentName?.trim() || "the agent that asked"} can answer it${too}.`;
}
return mine ? "Anyone else can answer it too." : "Anyone can answer it.";
}
/**
* The text of an ownerless or company card's audience line, with who may
* answer it when the card says (PAP-767).
*/
export function attentionUnownedAudienceText(
item: Pick<AttentionItem, "sourceKind" | "resolverAudience">,
description: Extract<AttentionAudienceDescription, { kind: "pool" | "company" }>,
userLabelMap?: ReadonlyMap<string, string> | null,
) {
const responders = attentionResponderText(item, description, userLabelMap);
if (!responders) return description.text;
return description.kind === "pool" ? `No owner yet. ${responders}` : `${description.text}. ${responders}`;
}
/**
* Whether the card's audience line already says who may answer it, so a row
* leaves out the separate "Anyone can respond" clause (PAP-767).
*/
export function attentionAudienceLineNamesResponders(item: AttentionItem, currentUserId: string | null | undefined) {
const description = currentUserId ? describeAttentionAudience(item, currentUserId) : null;
return Boolean(description && attentionResponderText(item, description));
}
/** Display name for a person on a receipt; never an ID. */
function receiptUserLabel(userId: string | null | undefined, userLabelMap?: ReadonlyMap<string, string> | null) {
return (userId ? userLabelMap?.get(userId) : null) ?? "someone";
}
/**
* The first line of a receipt (PAP-749 plan §6, Rule 12): "Answered by
* @scott", "Withdrawn by @scott", "Transferred to @riley by @scott".
*/
export function attentionReceiptLine(receipt: AttentionReceipt, userLabelMap?: ReadonlyMap<string, string> | null) {
return attentionReceiptText({
outcome: receipt.outcome,
actorLabel: receiptUserLabel(receipt.actorUserId, userLabelMap),
transferredToLabel: receipt.transferredToUserId ? receiptUserLabel(receipt.transferredToUserId, userLabelMap) : null,
});
}
+19 -2
View File
@@ -108,11 +108,18 @@ describe("isInlineResolvable", () => {
expect(isInlineResolvable(buildItem({ sourceKind: "review", inlineResolvable: false }))).toBe(false);
});
it("deep-links recovery/failure/budget rows rather than inlining", () => {
for (const kind of ["recovery_action", "failed_run", "budget_alert", "blocker_attention"] as AttentionSourceKind[]) {
it("deep-links recovery/blocker/agent-error rows rather than inlining", () => {
for (const kind of ["recovery_action", "blocker_attention", "agent_error_alert"] as AttentionSourceKind[]) {
expect(isInlineResolvable(buildItem({ sourceKind: kind, inlineResolvable: true }))).toBe(false);
}
});
it("inlines failed-run Retry and budget verbs only when the server flags them (PAP-749 Rule 7)", () => {
for (const kind of ["failed_run", "budget_alert"] as AttentionSourceKind[]) {
expect(isInlineResolvable(buildItem({ sourceKind: kind, inlineResolvable: true }))).toBe(true);
expect(isInlineResolvable(buildItem({ sourceKind: kind, inlineResolvable: false }))).toBe(false);
}
});
});
describe("attentionBadgeCount", () => {
@@ -407,6 +414,16 @@ describe("attentionDetailLine (§7)", () => {
expect(line).toContain("exit code 1");
});
it("shows budget amounts as dollars, not cents (PAP-767)", () => {
const line = attentionDetailLine(
buildItem({
sourceKind: "budget_alert",
detail: { kind: "budget", observedPercent: 100, amountObserved: 10000, amountLimit: 10000, images: [] },
}),
);
expect(line).toBe("100% of budget used ($100.00 / $100.00)");
});
it("returns null when there is no detail block", () => {
expect(attentionDetailLine(buildItem({ detail: null }))).toBeNull();
});
+18 -13
View File
@@ -9,14 +9,14 @@ import type {
AttentionSourceKind,
AttentionWorkspaceRef,
} from "@paperclipai/shared";
import { formatCents } from "./utils";
export type AttentionListOptions = AttentionFeedQuery;
/**
* Source kinds the queue can fully resolve in-row. Everything else deep-links
* to its native surface — the state-derived sources (recovery, failures,
* budget) expose verbs too rich to safely inline here, so they open their
* surface.
* to its native surface — recovery, blockers and agent errors keep their
* verbs on their own pages, so they open that surface.
*
* `review` is inline *only when stalled* (PAP-16080 §4.4): a stalled review has
* no interaction/approval/monitor to open, so the three review verbs
@@ -24,6 +24,10 @@ export type AttentionListOptions = AttentionFeedQuery;
* `inlineResolvable` on for exactly those rows (`isInlineResolvable` still ANDs
* that flag). A *covered* review keeps deep-linking, since its real action
* lives on the issue (the pending card, a monitor, a live run).
*
* `failed_run` (Retry, when the run has a task) and `budget_alert` (Raise
* budget, Keep paused) are inline since PAP-749 Rule 7: the server offers only
* verbs that work, and the server flag still decides each row.
*/
export const INLINE_RESOLVABLE_SOURCE_KINDS: ReadonlySet<AttentionSourceKind> = new Set<AttentionSourceKind>([
"approval",
@@ -31,6 +35,8 @@ export const INLINE_RESOLVABLE_SOURCE_KINDS: ReadonlySet<AttentionSourceKind> =
"issue_thread_interaction",
"join_request",
"review",
"failed_run",
"budget_alert",
]);
export function isInlineResolvable(item: AttentionItem): boolean {
@@ -240,7 +246,8 @@ export function attentionDetailLine(item: AttentionItem): string | null {
return b.title ? `Blocked by ${id}${b.title}` : b.identifier ? `Blocked by ${b.identifier}` : null;
}
case "budget":
return `${Math.round(detail.observedPercent)}% of budget used ($${detail.amountObserved} / $${detail.amountLimit})`;
// Budget amounts are cents, like the Spend line of the budget card.
return `${Math.round(detail.observedPercent)}% of budget used (${formatCents(detail.amountObserved)} / ${formatCents(detail.amountLimit)})`;
case "generic":
return quote(detail.summaryExcerpt);
default:
@@ -264,10 +271,9 @@ export function attentionImageUrl(assetId: string): string {
}
/**
* The sidebar badge: distinct items that either surfaced today or carry an
* explicit decide-by deadline that is due today/past. The server computes this
* before pagination (`deskBadgeCount`), so badge polling can fetch a small
* first page without losing the company-wide signal.
* The shared badge: current "For you" cards (PAP-749 plan §1, Rule 5). The
* server counts it before pagination (`deskBadgeCount`), so a small first page
* still carries the full count. It has no day boundary.
*/
export function attentionBadgeCount(feed: AttentionFeed | null | undefined): number {
return feed?.deskBadgeCount ?? 0;
@@ -282,11 +288,10 @@ export function attentionBadgeCount(feed: AttentionFeed | null | undefined): num
// is due today/past. No deadline set anywhere → no shelf, no claim.
// • "New today" — decisions that surfaced today (arrival grouping).
// • "Earlier" — everything else, older arrivals.
// The server owns the authoritative decide-by ranking (`sort=decide`) and the
// badge (`deskBadgeCount`); these client helpers mirror that logic *exactly*
// (same UTC day boundaries) so the on-page split and the badge never disagree.
// Keep in lockstep with `server/src/services/attention.ts`
// (`decideOrder`/`isDecideNow`/`isNewToday`).
// The server owns the authoritative decide-by ranking (`sort=decide`); these
// client helpers mirror its UTC day boundaries exactly. Keep in lockstep with
// `decideOrder` in `server/src/services/attention.ts`. The shelves only group
// the desk; the badge counts "For you" cards and ignores the day (PAP-749).
// ---------------------------------------------------------------------------
const MS_PER_DAY_DECIDE = 24 * 60 * 60 * 1_000;
+103 -2
View File
@@ -1,6 +1,18 @@
import { describe, expect, it } from "vitest";
import type { AttentionItem, DecisionHistoryItem } from "@paperclipai/shared";
import { COORDINATOR_RECENT_DECISION_MS, pendingDecisionTaskIds, recentDecisionReceipts } from "./coordinator-attention";
import { attentionReceiptText, type AttentionItem, type DecisionHistoryItem } from "@paperclipai/shared";
import {
COORDINATOR_RECENT_DECISION_MS,
DECISION_HISTORY_OUTCOME_OPTIONS,
coordinatorAudienceKey,
coordinatorAssignee,
coordinatorAssigneeTarget,
coordinatorCardDetail,
coordinatorCardTitle,
decisionHistoryContext,
decisionHistoryHeadline,
pendingDecisionTaskIds,
recentDecisionReceipts,
} from "./coordinator-attention";
describe("Coordinator attention projections", () => {
it("lists one task for two pending decisions and removes it only after the last decision leaves", () => {
@@ -23,3 +35,92 @@ describe("Coordinator attention projections", () => {
expect([...pendingDecisionTaskIds([])]).toEqual([]);
});
});
describe("Decision history presentation (PAP-749 task 2e)", () => {
const entry = (overrides: Partial<DecisionHistoryItem>) => ({
id: "issue_thread_interaction:a", sourceKind: "issue_thread_interaction", sourceId: "a", issueId: "task-1", issueIdentifier: "PAP-1",
issueTitle: "Launch copy", title: "Copy review", label: "Withdrawn by user", outcome: "cancelled", resultOutcome: "withdrawn",
resolvedAt: "2026-10-30T12:00:00.000Z", resolvedByUserId: "scott", resolvedByAgentId: null, agentId: null, agentName: null,
projectId: null, projectName: null, href: "/PAP/issues/PAP-1#interaction-a", target: null, ...overrides,
}) as DecisionHistoryItem;
it("offers Withdrawn, Expired and Closed with task as separate outcome filters", () => {
expect(DECISION_HISTORY_OUTCOME_OPTIONS.map((option) => option.label)).toEqual(expect.arrayContaining(["Withdrawn", "Expired", "Closed with task"]));
expect(DECISION_HISTORY_OUTCOME_OPTIONS.find((option) => option.label === "Closed with task")?.value).toBe("issue_closed");
});
it("names who withdrew a card and keeps every other label", () => {
const labels = new Map([["scott", "Scott"]]);
expect(decisionHistoryHeadline(entry({}), labels)).toBe("Withdrawn by @Scott");
expect(decisionHistoryHeadline(entry({ resolvedByUserId: null, label: "Withdrawn" }), labels)).toBe("Withdrawn");
expect(decisionHistoryHeadline(entry({ resultOutcome: null, label: "Approved", outcome: "accepted" }), labels)).toBe("Approved");
});
it("names who acted with the receipt's verb for the same action (PAP-767)", () => {
const labels = new Map([["scott", "Scott"], ["dotta", "Dotta"]]);
const approved = entry({ resultOutcome: null, label: "Approved", outcome: "accepted", action: { outcome: "approved", detail: null } });
expect(decisionHistoryHeadline(approved, labels)).toBe("Approved by @Scott");
expect(decisionHistoryHeadline(approved, labels)).toBe(attentionReceiptText({ outcome: "approved", actorLabel: "Scott" }));
const keptPaused = entry({ sourceKind: "approval", resultOutcome: null, label: "Kept paused", outcome: "rejected",
resolvedByUserId: "dotta", action: { outcome: "kept_paused", detail: null } });
expect(decisionHistoryHeadline(keptPaused, labels)).toBe("Kept paused by @Dotta");
const decided = entry({ sourceKind: "decision", resultOutcome: null, label: "Ship it", outcome: "decided", action: { outcome: "decided", detail: "Ship it" } });
expect(decisionHistoryHeadline(decided, labels)).toBe("Decided by @Scott: Ship it");
// An expired card has no actor: the label stays.
expect(decisionHistoryHeadline(entry({ resultOutcome: null, label: "Expired", outcome: "expired", resolvedByUserId: null, action: null }), labels)).toBe("Expired");
});
it("titles a card the way Needs You shows it, for the Withdraw all stale list (PAP-767)", () => {
const base = {
id: "c", sourceKind: "issue_thread_interaction", inlineResolvable: true,
subject: { id: "i", kind: "interaction", title: "Lingering on a done task", metadata: {} },
relatedIssue: { id: "t", identifier: "PAP-19", title: "Confirmation on a done task" }, whyNow: "Why",
} as unknown as AttentionItem;
// An inline interaction card is named by its task link.
expect(coordinatorCardTitle(base)).toBe("Confirmation on a done task");
// Every other card leads with its heading.
expect(coordinatorCardTitle({ ...base, sourceKind: "approval", subject: { ...base.subject, kind: "approval", title: "Approve the plan" } } as AttentionItem))
.toBe("Approve the plan");
expect(coordinatorCardTitle({ ...base, inlineResolvable: false } as AttentionItem)).toBe("Lingering on a done task");
});
it("gives a card titled with its bare task or agent name an ask, and explains a stuck task (PAP-770)", () => {
const blocker = {
id: "b", sourceKind: "blocker_attention", inlineResolvable: false, whyNow: "Blocks 0 tasks and needs human attention.",
subject: { id: "t", kind: "issue", title: "Today's weather forecast", metadata: {} }, relatedIssue: null,
detail: { kind: "blocker", blockingIssue: null, blockedTaskCount: 0, images: [] },
} as unknown as AttentionItem;
expect(coordinatorCardTitle(blocker)).toBe("Get “Today's weather forecast” moving again");
expect(coordinatorCardDetail(blocker, null)).toBe("No one is working on it. Unblock it, reassign it, or nudge its owner.");
const holding = { ...blocker, detail: { kind: "blocker", blockingIssue: null, blockedTaskCount: 2, images: [] } } as unknown as AttentionItem;
expect(coordinatorCardDetail(holding, null)).toBe("It's holding up 2 tasks, and no one is working on it. Unblock it, reassign it, or nudge its owner.");
const agentError = { ...blocker, sourceKind: "agent_error_alert", subject: { id: "a", kind: "agent", title: "Chief of Staff" },
detail: { kind: "agent_error", agentName: "Chief of Staff", failureReasonExcerpt: null, images: [] } } as unknown as AttentionItem;
expect(coordinatorCardTitle(agentError)).toBe("Chief of Staff hit an error and needs help");
});
it("shows the task, or names an approval that has no task", () => {
expect(decisionHistoryContext(entry({}))).toBe("PAP-1 · Launch copy");
expect(decisionHistoryContext(entry({ sourceKind: "approval", issueId: null, issueIdentifier: null, issueTitle: null, title: "Hire a designer" })))
.toBe("Approval · Hire a designer");
});
});
describe("who a card is for (PAP-775)", () => {
const card = (audience: unknown) => ({ audience }) as Pick<AttentionItem, "audience">;
it("keys a card by its person, No owner yet or Company", () => {
expect(coordinatorAudienceKey(card({ kind: "user", userId: "dotta", reason: "addressee" }))).toBe("user:dotta");
expect(coordinatorAudienceKey(card({ kind: "pool", userId: null, reason: "none" }))).toBe("unassigned");
expect(coordinatorAudienceKey(card({ kind: "company", userId: null, reason: "none" }))).toBe("company");
});
it("maps the assignee filter to a view and back", () => {
expect(coordinatorAssignee("mine", null)).toBe("me");
expect(coordinatorAssignee("all", null)).toBe("all");
expect(coordinatorAssignee("all", "dotta")).toBe("user:dotta");
expect(coordinatorAssignee("archived", null)).toBeNull();
expect(coordinatorAssigneeTarget("user:dotta", "scott")).toEqual({ view: "all", forUserId: "dotta" });
expect(coordinatorAssigneeTarget("user:scott", "scott")).toEqual({ view: "mine", forUserId: null });
expect(coordinatorAssigneeTarget("unassigned", "scott")).toEqual({ view: "unassigned", forUserId: null });
});
});
+139 -2
View File
@@ -1,7 +1,61 @@
import type { AttentionItem, DecisionHistoryItem } from "@paperclipai/shared";
import { attentionReceiptText, type AttentionItem, type AttentionPersonalView, type DecisionHistoryItem, type DecisionHistoryOutcomeFilter, type DecisionHistoryScope } from "@paperclipai/shared";
import { queryKeys } from "./queryKeys";
import { isInlineResolvable } from "./attention";
export const coordinatorAttentionQueryKey = (companyId: string) => [...queryKeys.attention(companyId), "coordinator", "pending"] as const;
/**
* The pending feed for one person and one view (PAP-749 plan §1). The key
* holds the user, so switching accounts never shows the previous person's
* cached list. The "For you" key is shared by the page, the sidebar, the mobile
* navigation and the Tasks filter, so the badge always agrees with the list.
*/
export const coordinatorAttentionQueryKey = (companyId: string, userId?: string | null, view?: AttentionPersonalView) =>
userId === undefined && view === undefined
? [...queryKeys.attention(companyId), "coordinator", "pending"] as const
: [...queryKeys.attention(companyId), userId, view, "coordinator", "pending"] as const;
/**
* The title a Needs You card leads with, so a list of cards (the Withdraw all
* stale confirmation) names each one the way the card does (PAP-767). An
* inline interaction or stalled review card renders its own resolver, and its
* task link names it; every other card has a heading.
*/
export function coordinatorCardTitle(item: AttentionItem) {
const task = item.relatedIssue ?? (item.subject.kind === "issue" ? item.subject : null);
const inline = isInlineResolvable(item)
&& (item.sourceKind === "issue_thread_interaction"
|| (item.sourceKind === "review" && item.subject.kind === "issue" && item.subject.metadata?.reviewAttentionState === "stalled"));
if (inline && task?.title) return task.title;
return coordinatorCardAsk(item, task?.title ?? null) ?? item.subject.title ?? item.whyNow;
}
/**
* Focus (PAP-770): a card's heading says what to do. Some sources are titled
* with the bare task or agent name ("Today's weather forecast", "Chief of
* Staff"), which repeats the task link and asks nothing; those get an ask.
*/
function coordinatorCardAsk(item: AttentionItem, taskTitle: string | null): string | null {
const title = item.subject.title?.trim() || null;
if (item.sourceKind === "blocker_attention" && title) return `Get “${title}” moving again`;
if (item.sourceKind === "agent_error_alert") {
const agent = item.detail?.kind === "agent_error" ? item.detail.agentName ?? title : title;
return agent ? `${agent} hit an error and needs help` : null;
}
if (item.sourceKind === "review" && title && title === taskTitle) return `Review “${title}”`;
// PAP-775 (UI1): approvals and join requests are answered on the card now.
if (item.sourceKind === "approval" && title && !/^approve\b/i.test(title)) return `Approve “${title}”?`;
if (item.sourceKind === "join_request" && title) return `Let ${title} join the company?`;
return null;
}
/** The context under a card's heading: what happened and what you can do about it. */
export function coordinatorCardDetail(item: AttentionItem, detailLine: string | null): string | null {
if (item.sourceKind === "blocker_attention" && item.detail?.kind === "blocker" && !item.detail.blockingIssue) {
const count = item.detail.blockedTaskCount ?? 0;
const holding = count > 0 ? `It's holding up ${count} ${count === 1 ? "task" : "tasks"}, and no` : "No";
return `${holding} one is working on it. Unblock it, reassign it, or nudge its owner.`;
}
return detailLine ?? item.whyNow;
}
export const coordinatorAttentionSummaryQueryKey = (companyId: string) => [...queryKeys.attention(companyId), "coordinator", "summary"] as const;
export const coordinatorAttentionTasksQueryKey = (companyId: string) => [...queryKeys.attention(companyId), "coordinator", "tasks"] as const;
@@ -15,3 +69,86 @@ export function recentDecisionReceipts(items: DecisionHistoryItem[], now: number
export function pendingDecisionTaskIds(items: AttentionItem[]) {
return new Set(items.flatMap((item) => item.relatedIssue ? [item.relatedIssue.id] : item.subject.kind === "issue" ? [item.subject.id] : []));
}
/**
* The Decision history outcome filter (PAP-749 plan §3). Withdrawn, Expired and
* Closed with task are separate: a card that closed with its task is not in
* Expired. "Handled for me" is a different filter (who the card was for), so
* it is not an outcome here.
*/
export const DECISION_HISTORY_OUTCOME_OPTIONS: ReadonlyArray<{ value: DecisionHistoryOutcomeFilter; label: string }> = [
{ value: "accepted", label: "Approved" },
{ value: "answered", label: "Answered" },
{ value: "rejected", label: "Changes requested" },
{ value: "decided", label: "Decided" },
{ value: "withdrawn", label: "Withdrawn" },
{ value: "expired", label: "Expired" },
{ value: "issue_closed", label: "Closed with task" },
{ value: "cancelled", label: "Cancelled" },
];
/**
* Whose decisions Decision history and Recent Decisions list (PAP-768). Your
* own is the default: what you answered, withdrew or transferred, what a
* different person handled for you, and the cards that were for you.
*/
export const DECISION_HISTORY_SCOPE_OPTIONS: ReadonlyArray<{ value: DecisionHistoryScope; label: string }> = [
{ value: "mine", label: "Handled by me or for me" },
{ value: "all", label: "Everyone" },
];
export const DEFAULT_DECISION_HISTORY_SCOPE: DecisionHistoryScope = "mine";
/**
* A history entry's headline. When a person acted, it names them with the
* receipt's verb for the same action ("Approved by @scott", "Kept paused by
* @dotta"; PAP-749 plan §3, PAP-767). A decision adds the option chosen and an
* item review its verdict counts. Everything else keeps the server's label.
*/
export function decisionHistoryHeadline(item: DecisionHistoryItem, userLabelMap?: ReadonlyMap<string, string> | null) {
const actorLabel = item.resolvedByUserId ? userLabelMap?.get(item.resolvedByUserId) ?? "someone" : null;
if (item.action && actorLabel) {
const line = attentionReceiptText({ outcome: item.action.outcome, actorLabel });
return item.action.detail ? `${line}: ${item.action.detail}` : line;
}
if (item.resultOutcome === "withdrawn" && actorLabel) return `Withdrawn by @${actorLabel}`;
return item.label;
}
/** The task line of a history entry; an approval with no task names itself instead. */
export function decisionHistoryContext(item: DecisionHistoryItem) {
if (!item.issueId) return item.sourceKind === "approval" ? `Approval · ${item.title}` : item.title;
return [item.issueIdentifier, item.issueTitle].filter(Boolean).join(" · ");
}
/**
* The toolbar's assignee filter (PAP-775): "Assigned to you" by default, every
* card the viewer may see ("all", a board member's Everyone), one person, the
* cards with no owner yet, or company alerts. Each value is one personal view
* of the feed, plus a person for "user:<id>"; the server routes every card and
* re-checks every action, so this only picks which cards to list.
*/
export type CoordinatorAssignee = "me" | "all" | "unassigned" | "company" | `user:${string}`;
/** The URL parameter that names the person in a `user:<id>` filter. */
export const COORDINATOR_ASSIGNEE_PARAM = "for";
export function coordinatorAudienceKey(item: Pick<AttentionItem, "audience">): Exclude<CoordinatorAssignee, "me" | "all"> {
const audience = item.audience;
if (audience?.kind === "user" && audience.userId) return `user:${audience.userId}`;
if (audience?.kind === "pool") return "unassigned";
return "company";
}
/** The filter a URL shows: its view, narrowed to one person in Everyone. */
export function coordinatorAssignee(view: AttentionPersonalView, forUserId: string | null | undefined): CoordinatorAssignee | null {
if (view === "archived") return null;
if (view === "all") return forUserId ? `user:${forUserId}` : "all";
return view === "mine" ? "me" : view;
}
/** The view (and person) to load for a filter value; your own name is "Assigned to you". */
export function coordinatorAssigneeTarget(assignee: CoordinatorAssignee, currentUserId: string | null | undefined): { view: AttentionPersonalView; forUserId: string | null } {
if (assignee === "me" || assignee === `user:${currentUserId}`) return { view: "mine", forUserId: null };
if (assignee.startsWith("user:")) return { view: "all", forUserId: assignee.slice(5) };
return { view: assignee as "all" | "unassigned" | "company", forUserId: null };
}
+55
View File
@@ -0,0 +1,55 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import {
claimReviseDraftWork,
clearReviseDraft,
getReviseDraft,
releaseReviseDraftWork,
resetReviseDraftsForTests,
reviseDraftKey,
updateReviseDraft,
} from "./revise-draft-store";
afterEach(() => {
sessionStorage.clear();
resetReviseDraftsForTests();
});
describe("revise draft store", () => {
it("keys a draft by interaction and plan revision", () => {
expect(reviseDraftKey("i1", "r1")).toBe("i1:r1");
expect(reviseDraftKey("i1", null)).toBe("i1");
updateReviseDraft(reviseDraftKey("i1", "r1"), { revising: true, reason: "abc" });
expect(getReviseDraft("i1:r1")).toMatchObject({ revising: true, reason: "abc" });
// A newer revision of the same plan starts clean.
expect(getReviseDraft("i1:r2")).toMatchObject({ revising: false, reason: "" });
});
it("clears a draft", () => {
updateReviseDraft("k", { revising: true, reason: "abc" });
clearReviseDraft("k");
expect(getReviseDraft("k")).toMatchObject({ revising: false, reason: "" });
expect(sessionStorage.getItem("paperclip:revise-drafts")).toBeNull();
});
it("lets only one view send at a time", () => {
expect(claimReviseDraftWork("k", "reject")).toBe(true);
expect(claimReviseDraftWork("k", "reject")).toBe(false);
expect(claimReviseDraftWork("k", "accept")).toBe(false);
releaseReviseDraftWork("k");
expect(claimReviseDraftWork("k", "accept")).toBe(true);
});
it("survives a reload through sessionStorage, without the in-flight send", () => {
updateReviseDraft("k", { revising: true, reason: "keep me", working: "reject" });
resetReviseDraftsForTests();
expect(getReviseDraft("k")).toEqual({ revising: true, reason: "keep me", working: null });
});
it("ignores a corrupt stored value", () => {
sessionStorage.setItem("paperclip:revise-drafts", "{not json");
resetReviseDraftsForTests();
expect(getReviseDraft("k")).toMatchObject({ revising: false, reason: "" });
});
});
+131
View File
@@ -0,0 +1,131 @@
import { useCallback, useSyncExternalStore } from "react";
/**
* One "Revise…" draft per decision (PAP-773). On Needs You a plan card and its
* Review side panel are two views of the same decision; both read and write
* this store so opening Revise…, typing, cancelling and sending mirror live.
* The side panel renders through the layout's panel slot, outside the page's
* React tree, so this is a module store rather than a context.
*
* Key by interaction id + target revision id: a newer plan revision gets a
* fresh, empty draft. Drafts survive closing the panel or switching cards for
* the session (sessionStorage), and are cleared when the decision resolves.
*/
export type ReviseDraftWork = "accept" | "reject" | "revise";
export interface ReviseDraft {
revising: boolean;
reason: string;
/** Which action one of the views is sending right now; blocks a second send. */
working: ReviseDraftWork | null;
}
const STORAGE_KEY = "paperclip:revise-drafts";
const EMPTY_DRAFT: ReviseDraft = Object.freeze({ revising: false, reason: "", working: null }) as ReviseDraft;
const drafts = new Map<string, ReviseDraft>();
const listeners = new Set<() => void>();
let hydrated = false;
function hydrate() {
if (hydrated) return;
hydrated = true;
try {
const raw = globalThis.sessionStorage?.getItem(STORAGE_KEY);
if (!raw) return;
const parsed = JSON.parse(raw) as Record<string, { revising?: unknown; reason?: unknown }>;
for (const [key, value] of Object.entries(parsed)) {
if (!value || typeof value !== "object") continue;
const reason = typeof value.reason === "string" ? value.reason : "";
const revising = value.revising === true;
if (revising || reason) drafts.set(key, { revising, reason, working: null });
}
} catch {
// A corrupt or unavailable store only costs the reload persistence.
}
}
function persist() {
try {
const out: Record<string, { revising: boolean; reason: string }> = {};
for (const [key, draft] of drafts) {
if (draft.revising || draft.reason) out[key] = { revising: draft.revising, reason: draft.reason };
}
if (Object.keys(out).length === 0) globalThis.sessionStorage?.removeItem(STORAGE_KEY);
else globalThis.sessionStorage?.setItem(STORAGE_KEY, JSON.stringify(out));
} catch {
// Storage full or blocked: the in-memory draft still syncs both views.
}
}
function emit() {
for (const listener of listeners) listener();
}
export function reviseDraftKey(interactionId: string, revisionId?: string | null) {
return revisionId ? `${interactionId}:${revisionId}` : interactionId;
}
export function getReviseDraft(key: string): ReviseDraft {
hydrate();
return drafts.get(key) ?? EMPTY_DRAFT;
}
export function updateReviseDraft(key: string, patch: Partial<ReviseDraft>) {
hydrate();
const current = drafts.get(key) ?? EMPTY_DRAFT;
const next = { ...current, ...patch };
if (next.revising === current.revising && next.reason === current.reason && next.working === current.working) return;
if (!next.revising && !next.reason && !next.working) drafts.delete(key);
else drafts.set(key, next);
persist();
emit();
}
export function clearReviseDraft(key: string) {
hydrate();
if (!drafts.has(key)) return;
drafts.delete(key);
persist();
emit();
}
/** Start sending from one view. Returns false when another view already is,
* so one decision can't be resolved twice by two buttons. */
export function claimReviseDraftWork(key: string, working: ReviseDraftWork): boolean {
if (getReviseDraft(key).working) return false;
updateReviseDraft(key, { working });
return true;
}
export function releaseReviseDraftWork(key: string) {
updateReviseDraft(key, { working: null });
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** Read and write the shared draft for `key`. A null key means "not shared";
* callers keep their own local state then. */
export function useReviseDraft(key: string | null) {
const draft = useSyncExternalStore(
subscribe,
() => (key ? getReviseDraft(key) : EMPTY_DRAFT),
() => EMPTY_DRAFT,
);
const update = useCallback((patch: Partial<ReviseDraft>) => {
if (key) updateReviseDraft(key, patch);
}, [key]);
return [draft, update] as const;
}
/** Test-only: forget every draft and the hydration flag. */
export function resetReviseDraftsForTests() {
drafts.clear();
hydrated = false;
emit();
}