@anthusai/papyrus 5.43.0-next.4 → 5.43.0-next.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/amplify/data/resource.js +6 -0
  2. package/amplify/data/resource.ts +7 -0
  3. package/amplify/data/schema.js +6 -0
  4. package/amplify/data/schema.ts +7 -0
  5. package/amplify/functions/category-action/handler.ts +2 -1
  6. package/amplify/functions/content-actions/handler.py +8 -0
  7. package/amplify/functions/content-actions/requirements.txt +2 -0
  8. package/amplify/functions/content-actions/resource.js +1 -1
  9. package/amplify/functions/content-actions/resource.ts +1 -1
  10. package/amplify/functions/model-attachment-upload/handler.ts +1 -0
  11. package/amplify/functions/monitoring-view/schema.js +16 -0
  12. package/amplify/functions/monitoring-view/schema.ts +16 -0
  13. package/amplify/functions/procedure-action/handler.ts +2 -10
  14. package/amplify/functions/proposal-actions/proposals.py +20 -3
  15. package/amplify/plugins/reader-steering/function/handler.py +1 -3
  16. package/amplify/plugins/reader-steering/function/moderation.py +19 -0
  17. package/app/api/newsroom/source-frameable/route.ts +12 -0
  18. package/app/api/newsroom/source-icon/route.ts +20 -0
  19. package/app/newsroom/[section]/[...selection]/page.tsx +2 -0
  20. package/app/newsroom/[section]/page.tsx +1 -0
  21. package/bin/papyrus-app.mjs +12 -1
  22. package/bin/papyrus-infra.mjs +21 -1
  23. package/components/auto-accepted-badge.tsx +21 -0
  24. package/components/conversation-context.tsx +52 -0
  25. package/components/conversation-provider.tsx +20 -0
  26. package/components/conversation-thread.tsx +174 -0
  27. package/components/decision-control.tsx +306 -0
  28. package/components/dev-sandbox-editor-sign-in.tsx +2 -2
  29. package/components/markdown-context.tsx +412 -0
  30. package/components/monitoring-overview-view.tsx +143 -21
  31. package/components/monitoring-panel.tsx +64 -4
  32. package/components/needs-me-bodies.tsx +302 -0
  33. package/components/needs-me-detail.tsx +24 -0
  34. package/components/needs-me-feed.tsx +594 -0
  35. package/components/needs-me-reference-detail.tsx +79 -0
  36. package/components/needs-me-shared.tsx +48 -0
  37. package/components/news-desk-client-provider.tsx +24 -3
  38. package/components/news-desk-page.tsx +2 -1
  39. package/components/news-desk-taxonomy-client.ts +253 -31
  40. package/components/newsroom-access-gate.tsx +13 -20
  41. package/components/newsroom-board-skeleton.tsx +20 -0
  42. package/components/newsroom-board-view.tsx +2 -6
  43. package/components/newsroom-client-shell.tsx +2 -1
  44. package/components/newsroom-ops-overview.tsx +88 -73
  45. package/components/newsroom-ops-shell.tsx +8 -28
  46. package/components/newsroom-organizer.css +127 -3
  47. package/components/newsroom-references-view.tsx +334 -158
  48. package/components/notification-cards.tsx +370 -0
  49. package/components/notification-center.tsx +376 -213
  50. package/components/papyrus-console-shell.tsx +2 -1
  51. package/components/proposals-panel.tsx +21 -24
  52. package/components/proposals-view.tsx +4 -2
  53. package/components/reader-auth-control.tsx +3 -1
  54. package/components/reference-capture-client.ts +138 -0
  55. package/components/reference-capture-panel.tsx +268 -0
  56. package/components/reference-conversation.tsx +43 -0
  57. package/components/reference-feed.tsx +514 -0
  58. package/components/reference-review-card.tsx +62 -197
  59. package/components/reference-source-preview.tsx +27 -5
  60. package/components/reference-stories.tsx +34 -0
  61. package/components/references-page-loading.tsx +61 -0
  62. package/components/references-prefetch.ts +52 -0
  63. package/components/story-reporting-trail-client.ts +45 -8
  64. package/components/story-reporting-trail.tsx +24 -13
  65. package/components/topic-steering-workspace.tsx +50 -439
  66. package/components/ui/auto-grow-textarea.tsx +18 -0
  67. package/components/use-conversation.ts +84 -0
  68. package/components/use-media-query.ts +16 -0
  69. package/components/use-reference-preview-attachments.ts +101 -0
  70. package/components/use-reference-ratings.ts +188 -0
  71. package/infra/amplify-app-shell.js +18 -2
  72. package/infra/amplify-app-shell.ts +18 -2
  73. package/infra/chat-stack.js +222 -0
  74. package/infra/chat-stack.ts +250 -0
  75. package/infra/chat.test.js +142 -0
  76. package/infra/chat.test.ts +151 -0
  77. package/infra/index.js +1 -0
  78. package/infra/site-config.js +58 -1
  79. package/infra/site-config.ts +78 -1
  80. package/lib/category-repository.ts +6 -1
  81. package/lib/content-actions-client.ts +20 -0
  82. package/lib/conversation.ts +154 -0
  83. package/lib/local-preview-feed-fixture.ts +63 -0
  84. package/lib/local-preview-seed.ts +24 -2
  85. package/lib/local-preview-synthetic-rejects.ts +41 -0
  86. package/lib/monitoring-client.ts +29 -2
  87. package/lib/monitoring-overview.ts +52 -1
  88. package/lib/monitoring-paging.ts +58 -0
  89. package/lib/needs-me-items.ts +289 -0
  90. package/lib/needs-me-ranking.ts +315 -0
  91. package/lib/newsroom-all-pages.ts +21 -0
  92. package/lib/newsroom-chat-identity.ts +2 -1
  93. package/lib/newsroom-index-filters.ts +18 -0
  94. package/lib/newsroom-nav.ts +1 -1
  95. package/lib/newsroom-organizer-nav.ts +2 -1
  96. package/lib/newsroom-references.ts +25 -1
  97. package/lib/notification-feed.ts +212 -0
  98. package/lib/proposals-client.ts +29 -0
  99. package/lib/reader-subject.ts +3 -2
  100. package/lib/reference-capture.ts +294 -0
  101. package/lib/reference-feed-cache.ts +170 -0
  102. package/lib/reference-feed-ranking.ts +236 -0
  103. package/lib/reference-policy.ts +12 -0
  104. package/lib/reference-preview.ts +112 -0
  105. package/lib/review-client.ts +71 -5
  106. package/lib/review-drafts.ts +277 -0
  107. package/lib/review-fixture.ts +56 -2
  108. package/lib/review-requests.ts +89 -24
  109. package/lib/site-brand.ts +2 -0
  110. package/lib/source-frameable.ts +77 -0
  111. package/lib/source-icon.ts +104 -0
  112. package/lib/staff-groups.ts +23 -0
  113. package/lib/staging-gate.ts +2 -2
  114. package/lib/story-reporting-trail.ts +33 -2
  115. package/package.json +45 -2
  116. package/routes.manifest.json +23 -1
  117. package/components/newsroom-overview-skeleton.tsx +0 -25
@@ -1,240 +1,261 @@
1
1
  "use client";
2
2
 
3
- import Link from "next/link";
4
- import { useCallback, useEffect, useMemo, useState } from "react";
5
- import { Badge } from "./ui/badge";
6
- import { Button } from "./ui/button";
7
- import { getNewsroomNavHref } from "../lib/newsroom-nav";
8
- import {
9
- cyclotronAutoDecided, cyclotronHeldForReview, formatWhen, isUnread, modeLabel, modeMark, nextText, sectionReviews,
10
- steeringText, subjectHref, subjectLabel, summarize, summaryText,
11
- type AnswerInput, type CyclotronEntry, type ReviewRequest,
12
- } from "../lib/review-requests";
13
- import type { ReferenceRecord } from "../lib/category-repository";
3
+ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
4
+ import type { ReferenceAttachmentRecord, ReferenceRecord } from "../lib/category-repository";
5
+ import type { EmailDecisionResult, MonitoringEmailDetails, MonitoringEmailSummary } from "../lib/monitoring-overview";
6
+ import { proposalReceiptMessage, stateLabel, type ProposalReceipt } from "../lib/proposals-admin";
7
+ import type { DraftLoad, ReviewLoad } from "../lib/review-client";
8
+ import { acceptPath, batchAnswer, draftDecisionOf, draftReasonUpdate, draftView, rejectPath, undecidedDraftIds, withDecision, draftDecisionUpdate, type DraftChoice, type DraftView } from "../lib/review-drafts";
9
+ import { previewsBySourceAddress, recentDecisions } from "../lib/notification-feed";
10
+ import { answerReasonUpdate, answerUpdate, applyReviewUpdate, cyclotronAutoDecided, draftIdsOf, isDraftReview, sectionReviews, type AnswerInput, type DraftDecision, type ReviewRequest } from "../lib/review-requests";
14
11
  import type { RelevanceDecisionView } from "../lib/relevance-decisions";
15
- import { FIXTURE_REVIEW_REQUESTS } from "../lib/review-fixture";
12
+ import { learnFreshness } from "../lib/reference-feed-ranking";
13
+ import { learnConfidenceThreshold, shapingThisWeek } from "../lib/needs-me-ranking";
14
+ import { buildNeedsMeItems } from "../lib/needs-me-items";
15
+ import { captureStatusesByLineage } from "../lib/reference-capture";
16
+ import { normalizeReferenceCurationStatus, type ReferenceRejectionReasonCode } from "../lib/reference-policy";
17
+ import type { ReferencePreview } from "../lib/reference-preview";
18
+ import { referenceLineageId } from "../lib/newsroom-references";
19
+ import { loadNotificationSnapshot, saveNotificationSnapshot } from "../lib/reference-feed-cache";
20
+ import { isLocalPreviewEnabled } from "../lib/local-preview";
21
+ import { SITE_BRAND } from "../lib/site-brand";
22
+ import { FIXTURE_DRAFTS, FIXTURE_EMAIL_DETAILS, FIXTURE_HELD_EMAILS, FIXTURE_REVIEW_REQUESTS } from "../lib/review-fixture";
23
+ import { NeedsMeView, type NeedsMeDecision } from "./needs-me-feed";
24
+ import type { NeedsMeEntry } from "../lib/needs-me-items";
25
+ import type { CorrectCaptureAction } from "./reference-capture-client";
26
+ import type { ReviewChoice } from "./reference-review-card";
16
27
 
17
28
  export type NotificationLoadState = "loading" | "ready" | "forbidden" | "unavailable";
29
+ export type DraftsLoadState = "loading" | "ready" | "failed";
18
30
 
19
- type ViewProps = {
20
- loadState: NotificationLoadState;
21
- requests: ReviewRequest[];
22
- readIds: ReadonlySet<string>;
23
- held: CyclotronEntry[];
24
- autoDecided: CyclotronEntry[];
25
- storyTitles?: Readonly<Record<string, string>>;
26
- deletedStories?: ReadonlySet<string>;
27
- demo?: boolean;
28
- busyId?: string | null;
29
- error?: string | null;
30
- onAnswer?: (request: ReviewRequest, input: AnswerInput) => void;
31
- onMarkRead?: (requestId: string) => void;
32
- onMarkAllRead?: () => void;
33
- };
34
-
35
- function Entry({ request, unread, demo, busy, titles, deleted, onAnswer, onMarkRead }: {
36
- request: ReviewRequest; unread: boolean; demo: boolean; busy: boolean; titles: Readonly<Record<string, string>>; deleted: ReadonlySet<string>;
37
- onAnswer?: ViewProps["onAnswer"]; onMarkRead?: ViewProps["onMarkRead"];
38
- }) {
39
- const [note, setNote] = useState("");
40
- const href = subjectHref(request.subject, demo);
41
- const open = request.state === "open";
42
- const steering = steeringText(request);
43
- const act = (input: AnswerInput) => onAnswer?.(request, { ...input, feedback: input.feedback ?? (note.trim() || null) });
44
- return (
45
- <li className="rounded-lg border p-3 space-y-2" data-review-request={request.id} data-review-mode={request.mode} data-review-state={request.state} data-review-unread={unread || undefined}>
46
- <div className="flex flex-wrap items-center gap-2">
47
- <Badge variant="outline"><span aria-hidden="true">{modeMark(request.mode)} </span>{modeLabel(request.mode)}</Badge>
48
- {unread ? <Badge variant="default"><span aria-hidden="true">● </span>New</Badge> : <span className="text-xs text-muted-foreground">Read</span>}
49
- <strong className="text-sm">{request.reason}</strong>
50
- </div>
51
- <p className="text-xs text-muted-foreground">
52
- Raised by {request.raisedBy} on {formatWhen(request.raisedAt)}
53
- {" · "}About: {href ? <Link href={href} onClick={() => onMarkRead?.(request.id)}>{subjectLabel(request.subject, titles, deleted)}</Link> : <span>{subjectLabel(request.subject, titles, deleted)}</span>}
54
- </p>
55
- {request.ask ? <p className="text-sm">{request.ask}</p> : null}
56
- {request.links.length ? (
57
- <ul className="text-xs space-y-0.5" aria-label="Items in this request">
58
- {request.links.slice(0, 10).map((link, index) => {
59
- const target = link.url ?? (link.type ? subjectHref({ type: link.type, id: link.id ?? "" }, demo) : null);
60
- return <li key={`${link.id ?? link.url}-${index}`}>{target ? <Link href={target}>{link.label ?? link.id ?? link.url}</Link> : (link.label ?? link.id)}</li>;
61
- })}
62
- {request.links.length > 10 ? <li>and {request.links.length - 10} more</li> : null}
63
- </ul>
64
- ) : null}
65
- <p className="text-sm" data-review-next>{nextText(request)}</p>
66
- {steering ? <p className="text-sm" data-review-steering>{steering}</p> : null}
67
- {open ? (
68
- <div className="space-y-2" data-review-controls>
69
- <label className="block text-xs text-muted-foreground">
70
- Steering note (optional)
71
- <textarea
72
- className="mt-1 block w-full rounded-md border bg-background p-2 text-sm"
73
- disabled={busy}
74
- onChange={(event) => setNote(event.target.value)}
75
- placeholder={request.mode === "flag" ? "Tell the step what to do differently" : "What should change, or what did you want instead?"}
76
- rows={2}
77
- value={note}
78
- />
79
- </label>
80
- <div className="flex flex-wrap gap-2">
81
- {request.mode === "flag" ? (
82
- <Button disabled={busy} onClick={() => act({ decision: "acknowledge" })} size="sm" variant="outline">Acknowledge</Button>
83
- ) : (
84
- <>
85
- <Button disabled={busy} onClick={() => act({ decision: "approve" })} size="sm" variant="outline">Approve</Button>
86
- <Button disabled={busy} onClick={() => act({ decision: "reject" })} size="sm" variant="outline">Reject</Button>
87
- </>
88
- )}
89
- <Button disabled={busy || !note.trim()} onClick={() => act({ decision: "feedback", steer: "adjust" })} size="sm" variant="outline">Steer with this note</Button>
90
- <Button disabled={busy} onClick={() => act({ decision: "feedback", steer: "not_this_kind" })} size="sm" variant="outline">Not this kind of thing</Button>
91
- {unread ? <Button disabled={busy} onClick={() => onMarkRead?.(request.id)} size="sm" variant="ghost">Mark read</Button> : null}
92
- </div>
93
- </div>
94
- ) : unread ? (
95
- <Button disabled={busy} onClick={() => onMarkRead?.(request.id)} size="sm" variant="ghost">Mark read</Button>
96
- ) : null}
97
- </li>
98
- );
99
- }
31
+ /** What a real-data preview shows instead of the invented sample (scripts/export-notification-center-fixture.py). */
32
+ export type NotificationFixture = { requests: ReviewRequest[]; drafts: Parameters<typeof draftView>[0][]; emails?: MonitoringEmailSummary[] };
100
33
 
101
- function CyclotronLine({ entry, held }: { entry: CyclotronEntry; held: boolean }) {
102
- const confidence = entry.confidence === null ? "confidence not recorded" : `confidence ${Math.round(entry.confidence * 100)}%`;
103
- return (
104
- <li className="rounded-lg border p-3 space-y-1" data-cyclotron-entry={entry.lineageId} data-cyclotron-held={held || undefined}>
105
- <div className="flex flex-wrap items-center gap-2">
106
- <Badge variant="outline"><span aria-hidden="true">{held ? "◔" : "✓"} </span>{held ? "Held for review" : "Decided by the system"}</Badge>
107
- <strong className="text-sm">{entry.title}</strong>
108
- </div>
109
- <p className="text-xs text-muted-foreground">
110
- Classified as {entry.label} · {confidence}{entry.decidedAt ? ` · ${formatWhen(entry.decidedAt)}` : ""}
111
- {entry.reviewedByPerson ? " · reviewed by a person" : ""}
112
- </p>
113
- {held ? <p className="text-sm">{entry.reviewDetail ? `${entry.reviewDetail}. ` : ""}Held for review: it stays pending until someone decides.</p> : null}
114
- <Link className="text-sm" href={entry.href}>{held ? "Review it in References" : "Open it in References to correct it"}</Link>
115
- </li>
116
- );
117
- }
34
+ const NO_VISIT: ReadonlySet<string> = new Set();
35
+ const NO_PREVIEWS: ReadonlyMap<string, ReferencePreview> = new Map();
36
+ const NO_ATTACHMENTS: ReferenceAttachmentRecord[] = [];
118
37
 
119
- function Section({ id, title, count, children, empty }: { id: string; title: string; count: number; children: React.ReactNode; empty: string }) {
120
- return (
121
- <section aria-labelledby={`notification-${id}`} className="space-y-2" data-notification-section={id}>
122
- <h2 className="text-sm font-medium" id={`notification-${id}`}>{title} ({count})</h2>
123
- {count ? children : <p className="text-sm text-muted-foreground">{empty}</p>}
124
- </section>
125
- );
126
- }
38
+ /** Everything the container reads and writes. The live one talks to the site's data API; tests pass a fake. */
39
+ export type NotificationApi = {
40
+ loadReviews: () => Promise<ReviewLoad>;
41
+ loadDrafts: (ids: string[]) => Promise<DraftLoad>;
42
+ loadStoryTitles: (ids: string[]) => Promise<{ titles: Record<string, string>; deleted: string[]; excerpts?: Record<string, string> }>;
43
+ answerReviewRequest: (request: ReviewRequest, input: AnswerInput, by: string) => Promise<ReviewRequest>;
44
+ saveDraftDecision: (request: ReviewRequest, draftId: string, decision: DraftDecision) => Promise<ReviewRequest>;
45
+ /** Changes only the Why of a draft or request that is already decided (`draftReasonUpdate`, `answerReasonUpdate`). Returns the saved request. */
46
+ saveReviewReason: (request: ReviewRequest, update: Record<string, unknown>) => Promise<ReviewRequest>;
47
+ markReviewRead: (userKey: string, requestId: string) => Promise<void>;
48
+ transitionProposalPath: (proposalId: string, path: readonly string[]) => Promise<ProposalReceipt>;
49
+ /** Email submissions held for review (Monitoring's own read). Optional: a site without monitoring has none. */
50
+ loadHeldEmails?: () => Promise<MonitoringEmailSummary[]>;
51
+ loadEmail?: (receiptId: string) => Promise<MonitoringEmailDetails>;
52
+ decideEmail?: (receiptId: string, decision: "accept" | "reject", reason: string) => Promise<EmailDecisionResult>;
53
+ };
127
54
 
128
- /** The CMS console home: what needs a person, what will proceed on its own, and what the system decided. Ignore-safe by design. */
129
- export function NotificationCenterView({ loadState, requests, readIds, held, autoDecided, demo = false, storyTitles = {}, deletedStories = new Set<string>(), busyId = null, error = null, onAnswer, onMarkRead, onMarkAllRead }: ViewProps) {
130
- const sections = useMemo(() => sectionReviews(requests), [requests]);
131
- const unreadCount = requests.filter((request) => isUnread(request, readIds)).length;
132
- const summary = summarize(sections, held, autoDecided, unreadCount);
133
- const entry = (request: ReviewRequest) => (
134
- <Entry busy={busyId === request.id} demo={demo} key={request.id} titles={storyTitles} deleted={deletedStories} onAnswer={onAnswer} onMarkRead={onMarkRead} request={request} unread={isUnread(request, readIds)} />
135
- );
136
- if (loadState === "loading") return (
137
- <section aria-label="Loading Notification Center" className="space-y-4" data-notification-state="loading" role="status">
138
- <div className="h-6 w-48 rounded bg-muted" />
139
- <div className="h-4 w-3/4 max-w-xl rounded bg-muted" />
140
- <div className="h-4 w-2/3 max-w-lg rounded bg-muted" />
141
- <div className="grid gap-3 sm:grid-cols-2">
142
- {Array.from({ length: 4 }, (_, index) => <div className="h-28 rounded-xl border bg-card p-4" key={index}>
143
- <div className="h-4 w-2/3 rounded bg-muted" /><div className="mt-4 h-3 w-1/2 rounded bg-muted" />
144
- </div>)}
145
- </div>
146
- </section>
147
- );
148
- if (loadState === "forbidden") return <div role="alert" data-notification-state="forbidden"><strong>The Notification Center is for editors and admins</strong></div>;
149
- if (loadState === "unavailable") return <div role="alert" data-notification-state="unavailable"><strong>Review requests could not be read right now</strong><p>Try again in a minute. The current request state is unknown.</p></div>;
150
- return (
151
- <div className="space-y-6" data-notification-center>
152
- <header className="space-y-1">
153
- <h1 className="text-lg font-semibold">Notification Center</h1>
154
- <p className="text-sm" data-notification-summary>{summaryText(summary)}</p>
155
- <p className="text-xs text-muted-foreground">
156
- Look, or steer. Anything you ignore keeps going: a soft review with a deadline proceeds at it, one without stays open until handled, and flags never wait. Only a hard gate waits for you.
157
- </p>
158
- <p className="text-xs text-muted-foreground" data-notification-unread>
159
- {unreadCount ? `${unreadCount} unread` : "Nothing unread"}
160
- {unreadCount ? <Button className="ml-2" onClick={onMarkAllRead} size="sm" variant="ghost">Mark all read</Button> : null}
161
- </p>
162
- {error ? <p role="alert" className="text-sm" data-notification-error>{error}</p> : null}
163
- </header>
55
+ const liveApi: NotificationApi = {
56
+ loadReviews: async () => (await import("../lib/review-client")).loadReviews(),
57
+ loadDrafts: async (ids) => (await import("../lib/review-client")).loadDrafts(ids),
58
+ loadStoryTitles: async (ids) => (await import("../lib/review-client")).loadStoryTitles(ids),
59
+ answerReviewRequest: async (request, input, by) => (await import("../lib/review-client")).answerReviewRequest(request, input, by),
60
+ saveDraftDecision: async (request, draftId, decision) => (await import("../lib/review-client")).saveDraftDecision(request, draftId, decision),
61
+ saveReviewReason: async (request, update) => (await import("../lib/review-client")).saveReviewReason(request, update),
62
+ markReviewRead: async (userKey, requestId) => (await import("../lib/review-client")).markReviewRead(userKey, requestId),
63
+ transitionProposalPath: async (proposalId, path) => (await import("../lib/proposals-client")).transitionProposalPath(proposalId, path),
64
+ loadHeldEmails: async () => {
65
+ const { loadMonitoringPage } = await import("../lib/monitoring-client");
66
+ const rows: MonitoringEmailSummary[] = [];
67
+ let cursor: string | null = null;
68
+ do {
69
+ const page = await loadMonitoringPage("emailSubmissions", cursor, "publication", true);
70
+ if (!("rows" in page)) return rows;
71
+ rows.push(...(page.rows as MonitoringEmailSummary[]));
72
+ cursor = page.cursor;
73
+ } while (cursor);
74
+ return rows;
75
+ },
76
+ loadEmail: async (receiptId) => (await import("../lib/monitoring-client")).loadMonitoringEmailSubmission(receiptId),
77
+ decideEmail: async (receiptId, decision, reason) => (await import("../lib/monitoring-client")).decideMonitoringEmailSubmission(receiptId, decision, reason),
78
+ };
164
79
 
165
- <Section count={sections.hardGates.length} empty="No hard gates. Nothing is blocked on you." id="hard-gates" title="Waiting for you: hard gates">
166
- <ul className="space-y-2">{sections.hardGates.map(entry)}</ul>
167
- </Section>
168
- <Section count={sections.softReviews.length} empty="No soft reviews are running." id="soft-reviews" title="Proceeding soon: soft reviews, soonest deadline first">
169
- <ul className="space-y-2">{sections.softReviews.map(entry)}</ul>
170
- </Section>
171
- <Section count={held.length} empty="No Cyclotron items are held for review." id="cyclotron" title="Cyclotron items routed to a person (low confidence)">
172
- <ul className="space-y-2">{held.slice(0, 10).map((item) => <CyclotronLine entry={item} held key={item.lineageId} />)}</ul>
173
- {held.length > 10 ? <p className="text-sm">and {held.length - 10} more. <Link href={getNewsroomNavHref("/newsroom/references", demo)}>See all in References</Link></p> : null}
174
- </Section>
175
- <Section count={sections.flags.length} empty="No flags." id="flags" title="Flags: for your information">
176
- <ul className="space-y-2">{sections.flags.map(entry)}</ul>
177
- </Section>
178
- <Section count={sections.decided.length} empty="Nothing answered or proceeded yet." id="decided" title="Answered, and what became of it">
179
- <ul className="space-y-2">{sections.decided.slice(0, 20).map(entry)}</ul>
180
- </Section>
181
- <details data-notification-section="auto-decided">
182
- <summary className="cursor-pointer text-sm font-medium">Recently decided by the system ({autoDecided.length})</summary>
183
- <div className="mt-2 space-y-2">
184
- <p className="text-xs text-muted-foreground">Read only. The Cyclotron was confident enough to decide these without you. To correct one, open it in References.</p>
185
- {autoDecided.length ? <ul className="space-y-2">{autoDecided.map((item) => <CyclotronLine entry={item} held={false} key={item.lineageId} />)}</ul> : <p className="text-sm text-muted-foreground">No automatic decisions yet.</p>}
186
- </div>
187
- </details>
188
- </div>
189
- );
190
- }
80
+ /** The demo and the real-data preview answer in memory with the same rules as the live data API; nothing leaves the page. */
81
+ const demoApi: NotificationApi = {
82
+ loadReviews: async () => ({ state: "unavailable" }),
83
+ loadDrafts: async () => ({ drafts: {}, missing: [], failed: [] }),
84
+ loadStoryTitles: async () => ({ titles: {}, deleted: [] }),
85
+ answerReviewRequest: async (request, input, by) => {
86
+ const update = answerUpdate(request, input, by, new Date());
87
+ return { ...request, state: "answered", answer: JSON.parse(String(update.answer)), links: update.links ? JSON.parse(String(update.links)) : request.links, history: JSON.parse(String(update.history)), updatedAt: String(update.updatedAt) };
88
+ },
89
+ saveDraftDecision: async (request, draftId, decision) => {
90
+ const update = draftDecisionUpdate(request, draftId, decision);
91
+ return { ...request, links: JSON.parse(String(update.links)), history: JSON.parse(String(update.history)), updatedAt: String(update.updatedAt) };
92
+ },
93
+ saveReviewReason: async (request, update) => applyReviewUpdate(request, update),
94
+ markReviewRead: async () => undefined,
95
+ transitionProposalPath: async () => ({ status: "ok" }),
96
+ loadHeldEmails: async () => FIXTURE_HELD_EMAILS,
97
+ loadEmail: async (receiptId) => FIXTURE_EMAIL_DETAILS[receiptId] ?? { state: "unavailable" },
98
+ decideEmail: async (_receiptId, decision) => ({ ok: true, already: false, quarantine: { state: decision === "accept" ? "released" : "discarded", decision: null, failure: null } }),
99
+ };
191
100
 
192
101
  type ContainerProps = {
193
102
  references: ReferenceRecord[];
194
103
  decisions: ReadonlyMap<string, RelevanceDecisionView>;
195
- humanCuratedReferenceLineageIds: ReadonlySet<string>;
104
+ humanCuratedReferenceLineageIds?: ReadonlySet<string>;
105
+ previews?: ReadonlyMap<string, ReferencePreview>;
106
+ referencesLoading?: boolean;
107
+ predictionLoading?: boolean;
108
+ referenceDisabledReason?: string | null;
109
+ onRateReference?: (reference: ReferenceRecord, choice: ReviewChoice, reasonCode: ReferenceRejectionReasonCode | null, note?: string) => Promise<void> | void;
110
+ /** The Reference attachments (previews, captured text), for the cards' pictures and the capture checks. */
111
+ referenceAttachments?: ReferenceAttachmentRecord[];
112
+ /** Saves a pasted or corrected capture. Without it the capture panel has no edit action. */
113
+ onCorrectCapture?: CorrectCaptureAction;
196
114
  actorLabel: string;
197
115
  demo: boolean;
116
+ /** A real-data preview (see scripts/export-notification-center-fixture.py); the invented sample otherwise. */
117
+ fixture?: NotificationFixture | null;
118
+ api?: NotificationApi;
119
+ /** Other page sections, shown at the end of the feed's own scroll. */
120
+ below?: ReactNode;
198
121
  };
199
122
 
200
123
  const REFRESH_MILLISECONDS = 60_000;
201
124
 
202
- export function NotificationCenter({ references, decisions, humanCuratedReferenceLineageIds, actorLabel, demo }: ContainerProps) {
125
+ /** Preview only: ?ncState=loading holds the skeleton, caught-up shows the empty state, sample swaps in the invented hard gate, flags, batches and held email, mixed adds the invented hard gate, flag and held email to the real data. */
126
+ function previewState(): "loading" | "caught-up" | "sample" | "mixed" | null {
127
+ if (typeof window === "undefined" || !isLocalPreviewEnabled()) return null;
128
+ const requested = new URLSearchParams(window.location.search).get("ncState");
129
+ return requested === "loading" || requested === "caught-up" || requested === "sample" || requested === "mixed" ? requested : null;
130
+ }
131
+
132
+ const EMAIL_REFUSALS: Record<string, string> = {
133
+ forbidden: "Your session cannot decide held email.",
134
+ bad_request: "That email could not be decided from here.",
135
+ already_applied: "This email was already queued, so its reason can no longer be changed here.",
136
+ already_decided: "Someone already decided this email. Refresh to see what they chose.",
137
+ not_quarantined: "This email is no longer held.",
138
+ expired: "This email expired and can no longer be accepted.",
139
+ };
140
+
141
+ export function NotificationCenter({
142
+ references, decisions, humanCuratedReferenceLineageIds = NO_VISIT, previews = NO_PREVIEWS, referencesLoading = false, predictionLoading = false, referenceDisabledReason = null,
143
+ onRateReference, referenceAttachments = NO_ATTACHMENTS, onCorrectCapture, actorLabel, demo, fixture = null, api: liveOverride = liveApi, below,
144
+ }: ContainerProps) {
145
+ const api = demo ? demoApi : liveOverride;
203
146
  const [loadState, setLoadState] = useState<NotificationLoadState>("loading");
147
+ const [stale, setStale] = useState(false);
204
148
  const [requests, setRequests] = useState<ReviewRequest[]>([]);
205
- const [readIds, setReadIds] = useState<Set<string>>(new Set());
206
149
  const [userKey, setUserKey] = useState<string | null>(null);
207
- const [busyId, setBusyId] = useState<string | null>(null);
208
150
  const [error, setError] = useState<string | null>(null);
209
151
  const [storyTitles, setStoryTitles] = useState<Record<string, string>>({});
152
+ const [storyExcerpts, setStoryExcerpts] = useState<Record<string, string>>({});
210
153
  const [deletedStories, setDeletedStories] = useState<ReadonlySet<string>>(new Set());
154
+ const [drafts, setDrafts] = useState<Record<string, DraftView>>({});
155
+ const [missingDrafts, setMissingDrafts] = useState<ReadonlySet<string>>(new Set());
156
+ const [draftsState, setDraftsState] = useState<DraftsLoadState>("loading");
157
+ const [emails, setEmails] = useState<MonitoringEmailSummary[]>([]);
158
+ const [emailsState, setEmailsState] = useState<"loading" | "ready">("loading");
159
+ const [emailsDecided, setEmailsDecided] = useState<ReadonlyMap<string, "accept" | "reject">>(new Map());
160
+ const [stay, setStay] = useState<ReadonlySet<string>>(new Set());
161
+ const [visitRated, setVisitRated] = useState<ReadonlySet<string>>(new Set());
162
+ const [now] = useState(() => Date.now());
163
+ const resolving = useRef(new Set<string>());
164
+ const demoStarted = useRef(false);
165
+ const preview = useMemo(() => previewState(), []);
166
+ const sample = useMemo(() => {
167
+ if (preview === "sample" || !fixture) return { requests: FIXTURE_REVIEW_REQUESTS, drafts: FIXTURE_DRAFTS };
168
+ if (preview === "mixed") {
169
+ const invented = FIXTURE_REVIEW_REQUESTS.filter((request) => request.id === "rr-hard-1" || request.id === "rr-flag-1");
170
+ return { requests: [...invented, ...fixture.requests], drafts: fixture.drafts };
171
+ }
172
+ return { requests: preview === "caught-up" ? [] : fixture.requests, drafts: fixture.drafts };
173
+ }, [fixture, preview]);
174
+
175
+ const keep = useCallback((key: string) => setStay((current) => (current.has(key) ? current : new Set(current).add(key))), []);
176
+
177
+ const loadDraftsFor = useCallback(async (list: ReviewRequest[]) => {
178
+ const ids = list.filter((request) => request.state === "open" && isDraftReview(request)).flatMap(draftIdsOf);
179
+ if (!ids.length) {
180
+ setDraftsState("ready");
181
+ return;
182
+ }
183
+ if (demo) {
184
+ const known = sample.drafts.filter((row) => ids.includes(row.id));
185
+ setDrafts((current) => ({ ...current, ...Object.fromEntries(known.map((row) => [row.id, draftView(row, true)])) }));
186
+ setMissingDrafts(new Set(ids.filter((id) => !known.some((row) => row.id === id))));
187
+ setDraftsState("ready");
188
+ return;
189
+ }
190
+ try {
191
+ const loaded = await api.loadDrafts(ids);
192
+ setDrafts((current) => ({ ...current, ...loaded.drafts }));
193
+ setMissingDrafts(new Set(loaded.missing));
194
+ setDraftsState(loaded.failed.length ? "failed" : "ready");
195
+ } catch {
196
+ setDraftsState("failed");
197
+ }
198
+ }, [api, demo, sample]);
199
+
200
+ // Email held for review is read on its own: a site without monitoring, or an editor who may not read it, simply has none.
201
+ const loadEmailsNow = useCallback(async () => {
202
+ if (preview === "caught-up") { setEmails([]); setEmailsState("ready"); return; }
203
+ // The real-data preview has no held email of its own; only the sample and mixed previews show the invented one.
204
+ if (demo && fixture && preview !== "sample" && preview !== "mixed") { setEmails(fixture.emails ?? []); setEmailsState("ready"); return; }
205
+ try {
206
+ setEmails((await api.loadHeldEmails?.()) ?? []);
207
+ } catch {
208
+ // Held email is one source among several; the others still show.
209
+ }
210
+ setEmailsState("ready");
211
+ }, [api, demo, fixture, preview]);
212
+
213
+ // A return visit paints the last view at once, marked as such, while the real reads run.
214
+ useEffect(() => {
215
+ if (demo) return;
216
+ const snapshot = loadNotificationSnapshot(SITE_BRAND.id);
217
+ if (!snapshot) return;
218
+ setRequests(snapshot.requests);
219
+ setDrafts(snapshot.drafts);
220
+ setMissingDrafts(new Set(snapshot.missing));
221
+ setDraftsState("ready");
222
+ setStale(true);
223
+ setLoadState((current) => (current === "loading" ? "ready" : current));
224
+ }, [demo]);
211
225
 
212
226
  const refresh = useCallback(async () => {
213
227
  if (demo) {
214
- setRequests(FIXTURE_REVIEW_REQUESTS);
215
- setReadIds(new Set(["rr-flag-1"]));
228
+ // The sample is read once: answering in the preview must not be undone by the next refresh.
229
+ if (demoStarted.current) return;
230
+ demoStarted.current = true;
231
+ setRequests(sample.requests);
216
232
  setLoadState("ready");
233
+ void loadDraftsFor(sample.requests);
234
+ void loadEmailsNow();
217
235
  return;
218
236
  }
219
237
  try {
220
- const { loadReviews } = await import("../lib/review-client");
221
- const loaded = await loadReviews();
238
+ const loaded = await api.loadReviews();
222
239
  if (loaded.state !== "ready") {
240
+ setStale(false);
223
241
  setLoadState(loaded.state);
224
242
  return;
225
243
  }
226
244
  setRequests(loaded.requests);
227
- setReadIds(new Set(loaded.readIds));
228
245
  setUserKey(loaded.userKey);
246
+ setStale(false);
229
247
  setLoadState("ready");
230
- const { loadStoryTitles } = await import("../lib/review-client");
231
- const stories = await loadStoryTitles(loaded.requests.filter((request) => request.subject.type === "story").map((request) => request.subject.id)).catch(() => ({ titles: {}, deleted: [] as string[] }));
248
+ void loadDraftsFor(loaded.requests);
249
+ void loadEmailsNow();
250
+ const stories = await api.loadStoryTitles(loaded.requests.filter((request) => request.subject.type === "story").map((request) => request.subject.id)).catch(() => ({ titles: {}, deleted: [] as string[], excerpts: {} }));
232
251
  setStoryTitles(stories.titles);
252
+ setStoryExcerpts(stories.excerpts ?? {});
233
253
  setDeletedStories(new Set(stories.deleted));
234
254
  } catch {
255
+ setStale(false);
235
256
  setLoadState("unavailable");
236
257
  }
237
- }, [demo]);
258
+ }, [api, demo, loadDraftsFor, loadEmailsNow, sample]);
238
259
 
239
260
  useEffect(() => {
240
261
  void refresh();
@@ -242,40 +263,182 @@ export function NotificationCenter({ references, decisions, humanCuratedReferenc
242
263
  return () => window.clearInterval(timer);
243
264
  }, [refresh]);
244
265
 
245
- const held = useMemo(() => cyclotronHeldForReview(references, decisions, demo), [references, decisions, demo]);
246
- const autoDecided = useMemo(() => cyclotronAutoDecided(references, decisions, humanCuratedReferenceLineageIds, demo), [references, decisions, humanCuratedReferenceLineageIds, demo]);
266
+ // Keep a display copy for the next visit once the live read and its drafts have arrived.
267
+ useEffect(() => {
268
+ if (demo || stale || loadState !== "ready" || draftsState !== "ready") return;
269
+ const timer = window.setTimeout(() => saveNotificationSnapshot(SITE_BRAND.id, { requests, drafts, missing: missingDrafts }), 800);
270
+ return () => window.clearTimeout(timer);
271
+ }, [demo, draftsState, drafts, loadState, missingDrafts, requests, stale]);
247
272
 
248
273
  const markRead = useCallback(async (requestId: string) => {
249
- setReadIds((current) => new Set(current).add(requestId));
250
274
  if (demo || !userKey) return;
251
- const { markReviewRead } = await import("../lib/review-client");
252
- await markReviewRead(userKey, requestId).catch(() => undefined);
253
- }, [demo, userKey]);
275
+ await api.markReviewRead(userKey, requestId).catch(() => undefined);
276
+ }, [api, demo, userKey]);
254
277
 
278
+ /** Answers a whole request. Throws a sentence for the card when it cannot be saved. */
255
279
  const answer = useCallback(async (request: ReviewRequest, input: AnswerInput) => {
256
280
  setError(null);
257
- setBusyId(request.id);
281
+ const saved = await api.answerReviewRequest(request, input, actorLabel);
282
+ keep(request.id);
283
+ setRequests((current) => current.map((entry) => (entry.id === saved.id ? saved : entry)));
284
+ await markRead(request.id);
285
+ }, [actorLabel, api, keep, markRead]);
286
+
287
+ /** Accept or Reject one draft: the Proposal moves to approved or declined, the decision is recorded on the request, and the request closes once every draft is decided. */
288
+ const decideDraft = useCallback(async (request: ReviewRequest, draftId: string, choice: DraftChoice, extras: { why: string; notThisKind: boolean }) => {
289
+ setError(null);
290
+ resolving.current.add(request.id);
258
291
  try {
259
- if (demo) throw new Error("This is a demo: answers are not saved.");
260
- const { answerReviewRequest } = await import("../lib/review-client");
261
- const saved = await answerReviewRequest(request, input, actorLabel);
262
- setRequests((current) => current.map((entry) => (entry.id === saved.id ? saved : entry)));
263
- await markRead(request.id);
292
+ const view = drafts[draftId];
293
+ if (!view) throw new Error("This draft has not loaded yet.");
294
+ const path = choice === "accept" ? acceptPath(view.state) : rejectPath(view.state);
295
+ if (!path) throw new Error(`This draft is ${stateLabel(view.state, false).toLowerCase()} and cannot be ${choice === "accept" ? "accepted" : "rejected"} from here. Open it in Proposals.`);
296
+ const receipt = await api.transitionProposalPath(draftId, path);
297
+ if (receipt.status !== "ok") throw new Error(proposalReceiptMessage(receipt));
298
+ const decided: DraftView = { ...view, state: choice === "accept" ? "approved" : "declined", decided: choice };
299
+ const nextDrafts = { ...drafts, [draftId]: decided };
300
+ setDrafts(nextDrafts);
301
+ keep(`${request.id}#${draftId}`);
302
+ const decision: DraftDecision = { choice, title: view.headline, why: extras.why || null, notThisKind: choice === "reject" && extras.notThisKind, by: actorLabel, at: new Date().toISOString() };
303
+ const withDecisionRequest = { ...request, links: withDecision(request, draftId, decision) };
304
+ const closing = batchAnswer(withDecisionRequest, nextDrafts, { by: actorLabel, at: decision.at });
305
+ try {
306
+ const saved = closing ? await api.answerReviewRequest(request, closing, actorLabel) : await api.saveDraftDecision(request, draftId, decision);
307
+ setRequests((current) => current.map((entry) => (entry.id === saved.id ? saved : entry)));
308
+ if (closing) await markRead(request.id);
309
+ } catch (failure) {
310
+ throw new Error(`The draft was ${choice === "accept" ? "accepted" : "rejected"} in Proposals, but this request could not record it. ${failure instanceof Error ? failure.message : ""}`.trim());
311
+ }
264
312
  } catch (failure) {
265
- setError(failure instanceof Error ? failure.message : "Could not save the answer.");
313
+ if (!demo) void loadDraftsFor([request]);
314
+ throw failure;
266
315
  } finally {
267
- setBusyId(null);
316
+ resolving.current.delete(request.id);
317
+ }
318
+ }, [actorLabel, api, demo, drafts, keep, loadDraftsFor, markRead]);
319
+
320
+ // Drafts decided in Proposals (not here) still close their request.
321
+ useEffect(() => {
322
+ if (demo || draftsState !== "ready" || stale) return;
323
+ for (const request of requests) {
324
+ if (request.state !== "open" || !isDraftReview(request) || resolving.current.has(request.id)) continue;
325
+ if (undecidedDraftIds(request, drafts).length) continue;
326
+ const closing = batchAnswer(request, drafts, { by: "an editor in Proposals", at: new Date().toISOString() });
327
+ if (!closing) continue;
328
+ resolving.current.add(request.id);
329
+ void (async () => {
330
+ try {
331
+ const saved = await api.answerReviewRequest(request, closing, "an editor in Proposals");
332
+ setRequests((current) => current.map((entry) => (entry.id === saved.id ? saved : entry)));
333
+ } catch {
334
+ // The next refresh shows what became of it.
335
+ } finally {
336
+ resolving.current.delete(request.id);
337
+ }
338
+ })();
268
339
  }
269
- }, [actorLabel, demo, markRead]);
340
+ }, [api, demo, drafts, draftsState, requests, stale]);
341
+
342
+ /** Accept or Reject a held email, or (the same choice again) correct the reason it was given. The reason shown is what the server recorded. */
343
+ const sendEmailDecision = useCallback(async (summary: MonitoringEmailSummary, choice: "accept" | "reject", why: string, editing = false) => {
344
+ const result = await api.decideEmail?.(summary.receiptId, choice, why);
345
+ if (!result) throw new Error("Held email cannot be decided from here.");
346
+ if (!("ok" in result)) throw new Error("error" in result ? EMAIL_REFUSALS[result.error] ?? "The decision could not be saved." : "The decision could not be saved right now. Try again in a minute.");
347
+ const plain = (text: string) => text.replace(/\s+/g, " ").trim().slice(0, 500);
348
+ const recorded = result.quarantine?.decision;
349
+ // The server keeps the first reason once it has queued the email; say so in words rather than showing a reason that was not kept.
350
+ if (editing && recorded && plain(recorded.reason) !== plain(why)) throw new Error(EMAIL_REFUSALS.already_applied);
351
+ const kept = recorded?.reason ?? plain(why);
352
+ setEmailsDecided((current) => new Map(current).set(summary.receiptId, choice));
353
+ setEmails((current) => current.map((entry) => (entry.receiptId === summary.receiptId
354
+ ? { ...entry, quarantine: { state: entry.quarantine?.state ?? "quarantined", failure: entry.quarantine?.failure ?? null, decision: { action: choice, by: recorded?.by || actorLabel, at: recorded?.at ?? new Date().toISOString(), reason: kept, viaGroup: recorded?.viaGroup } } }
355
+ : entry)));
356
+ }, [actorLabel, api]);
270
357
 
271
- const markAllRead = useCallback(() => {
272
- for (const request of requests) if (isUnread(request, readIds)) void markRead(request.id);
273
- }, [markRead, readIds, requests]);
358
+ /**
359
+ * Changes only the Why of an item that is already decided, onto the decision that exists:
360
+ * AI draft the request's link for the draft (and, once the request has closed, its answer's drafts and feedback)
361
+ * review request the request's answer note (a hard gate, a stage review, an acknowledged flag)
362
+ * held email the same decision again with the new reason, so the Monitoring view updates the recorded reason
363
+ * A Proposal's own transitions carry only public reasons, so a private note is never written there.
364
+ */
365
+ const latest = useRef({ requests, drafts, emails, emailsDecided });
366
+ latest.current = { requests, drafts, emails, emailsDecided };
367
+ const editReason = useCallback(async (item: NeedsMeEntry, why: string) => {
368
+ const { payload } = item;
369
+ const now = new Date();
370
+ const store = (saved: ReviewRequest) => {
371
+ latest.current.requests = latest.current.requests.map((entry) => (entry.id === saved.id ? saved : entry));
372
+ setRequests((current) => current.map((entry) => (entry.id === saved.id ? saved : entry)));
373
+ };
374
+ if (payload.kind === "draft") {
375
+ const request = latest.current.requests.find((entry) => entry.id === payload.item.request.id) ?? payload.item.request;
376
+ const view = latest.current.drafts[payload.item.draftId];
377
+ const decision = draftDecisionOf(request.links.find((link) => link.id === payload.item.draftId), view, { by: actorLabel, at: now.toISOString() });
378
+ if (!decision) throw new Error("This draft has not been decided yet.");
379
+ store(await api.saveReviewReason(request, draftReasonUpdate(request, payload.item.draftId, { ...decision, title: decision.title ?? view?.headline, why }, actorLabel, now)));
380
+ } else if (payload.kind === "request") {
381
+ const request = latest.current.requests.find((entry) => entry.id === payload.request.id) ?? payload.request;
382
+ store(await api.saveReviewReason(request, answerReasonUpdate(request, why, actorLabel, now)));
383
+ } else if (payload.kind === "email") {
384
+ const choice = latest.current.emailsDecided.get(payload.summary.receiptId) ?? payload.summary.quarantine?.decision?.action;
385
+ if (!choice) throw new Error("This email has not been decided yet.");
386
+ await sendEmailDecision(payload.summary, choice, why, true);
387
+ }
388
+ }, [actorLabel, api, sendEmailDecision]);
389
+
390
+ /** One decision, whatever the type: it goes to the action that already owns that kind of thing. */
391
+ const decide = useCallback(async (item: NeedsMeEntry, decision: NeedsMeDecision) => {
392
+ const { payload } = item;
393
+ if (payload.kind === "reference") {
394
+ setVisitRated((current) => (current.has(payload.lineageId) ? current : new Set(current).add(payload.lineageId)));
395
+ await onRateReference?.(payload.reference, decision.choice, decision.choice === "reject" ? decision.reasonCode : null, decision.why || undefined);
396
+ } else if (payload.kind === "draft") {
397
+ await decideDraft(payload.item.request, payload.item.draftId, decision.choice, { why: decision.why, notThisKind: decision.notThisKind });
398
+ } else if (payload.kind === "request") {
399
+ const { request } = payload;
400
+ if (request.mode === "flag") await answer(request, { decision: "acknowledge", feedback: decision.why || null });
401
+ else if (decision.choice === "accept") await answer(request, { decision: "approve", feedback: decision.why || null });
402
+ else await answer(request, { decision: "reject", feedback: decision.why || null, steer: decision.notThisKind ? "not_this_kind" : null });
403
+ } else if (payload.kind === "email") {
404
+ await sendEmailDecision(payload.summary, decision.choice, decision.why);
405
+ }
406
+ }, [answer, decideDraft, onRateReference, sendEmailDecision]);
407
+
408
+ const shownReferences = preview === "caught-up" ? references.filter((reference) => normalizeReferenceCurationStatus(reference.curationStatus) !== "pending") : references;
409
+ const bySource = useMemo(() => previewsBySourceAddress(shownReferences, previews), [shownReferences, previews]);
410
+ const lineageIds = useMemo(() => shownReferences.map(referenceLineageId), [shownReferences]);
411
+ const { statuses: captures, teaserLine } = useMemo(() => captureStatusesByLineage(referenceAttachments, lineageIds), [lineageIds, referenceAttachments]);
412
+
413
+ const entries = useMemo(
414
+ () => buildNeedsMeItems({
415
+ references: shownReferences, decisions, previews, captures, visitRated, requests, drafts, missingDrafts, draftsState, stay, bySource,
416
+ storyTitles, storyExcerpts, deletedStories, emails, emailsDecided,
417
+ }),
418
+ [shownReferences, decisions, previews, captures, visitRated, requests, drafts, missingDrafts, draftsState, stay, bySource, storyTitles, storyExcerpts, deletedStories, emails, emailsDecided],
419
+ );
420
+ const freshness = useMemo(() => learnFreshness(shownReferences, visitRated), [shownReferences, visitRated]);
421
+ const threshold = useMemo(() => learnConfidenceThreshold(shownReferences, decisions, visitRated), [shownReferences, decisions, visitRated]);
422
+ const recent = useMemo(() => recentDecisions(requests, references, demo), [requests, references, demo]);
423
+ const shaping = useMemo(
424
+ () => shapingThisWeek({ decidedAt: recentDecisions(requests, references, demo, Number.MAX_SAFE_INTEGER).map((entry) => entry.at), references, decisions, now }),
425
+ [requests, references, demo, decisions, now],
426
+ );
427
+ const shownIds = useMemo(() => new Set(entries.map((item) => item.id)), [entries]);
428
+ const legacyAuto = useMemo(
429
+ () => cyclotronAutoDecided(shownReferences, decisions, humanCuratedReferenceLineageIds, demo).filter((entry) => !shownIds.has(entry.lineageId)),
430
+ [shownReferences, decisions, humanCuratedReferenceLineageIds, demo, shownIds],
431
+ );
432
+ const openDraftRequests = useMemo(() => sectionReviews(requests).draftBatches, [requests]);
433
+ const missingCount = openDraftRequests.reduce((total, request) => total + draftIdsOf(request).filter((id) => missingDrafts.has(id)).length, 0);
434
+ const settled = !stale && loadState === "ready" && draftsState !== "loading" && emailsState === "ready" && !referencesLoading && !predictionLoading;
274
435
 
275
436
  return (
276
- <NotificationCenterView
277
- autoDecided={autoDecided} busyId={busyId} storyTitles={storyTitles} deletedStories={deletedStories} demo={demo} error={error} held={held} loadState={loadState}
278
- onAnswer={answer} onMarkAllRead={markAllRead} onMarkRead={markRead} readIds={readIds} requests={requests}
437
+ <NeedsMeView
438
+ below={below} captureTeaserLine={teaserLine} demo={demo} draftsFailed={draftsState === "failed"} entries={entries} error={error} freshness={freshness} legacyAuto={legacyAuto}
439
+ loadEmail={api.loadEmail} loadState={preview === "loading" ? "loading" : loadState} missingDraftCount={missingCount} now={now} onCorrectCapture={onCorrectCapture} onDecide={decide} onEditReason={editReason}
440
+ onRetryDrafts={() => void loadDraftsFor(requests)} predictionLoading={predictionLoading} recent={recent} referenceAttachments={referenceAttachments}
441
+ referenceDisabledReason={referenceDisabledReason} referencesLoading={referencesLoading} settled={settled} shaping={shaping} stale={stale} threshold={threshold}
279
442
  />
280
443
  );
281
444
  }