@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
@@ -2,17 +2,16 @@
2
2
 
3
3
  import {
4
4
  ArchiveIcon,
5
- CheckIcon,
6
5
  ChevronLeftIcon,
7
6
  ChevronRightIcon,
8
- CircleCheckIcon,
9
- CircleXIcon,
10
7
  ExternalLinkIcon,
11
8
  } from "lucide-react";
12
9
  import { useEffect, useRef, useState, type ReactNode, type PointerEvent as ReactPointerEvent } from "react";
13
10
  import { Button } from "./ui/button";
14
11
  import { cn } from "../lib/utils";
15
- import { REFERENCE_REJECTION_REASON_CODES, type ReferenceRejectionReasonCode } from "../lib/reference-policy";
12
+ import { DecisionControl } from "./decision-control";
13
+ import { useRatingStore, type RatingController } from "./use-reference-ratings";
14
+ import type { ReferenceRejectionReasonCode } from "../lib/reference-policy";
16
15
 
17
16
  export type ReviewChoice = "accept" | "reject";
18
17
 
@@ -28,20 +27,8 @@ export type ReviewCardDecision = {
28
27
  reasonCode: ReferenceRejectionReasonCode | null;
29
28
  };
30
29
 
31
- const REASON_LABELS: Record<ReferenceRejectionReasonCode, string> = {
32
- out_of_scope: "Out of scope",
33
- policy_exclusion: "Policy exclusion",
34
- duplicate: "Duplicate",
35
- low_quality: "Low quality",
36
- unavailable: "Unavailable",
37
- provenance: "Provenance",
38
- other: "Other",
39
- };
40
-
41
- const CHOICE_LABEL: Record<ReviewChoice, string> = { accept: "Accept", reject: "Reject" };
42
-
43
- function percent(confidence: number | null): string | null {
44
- return confidence === null ? null : `${Math.round(confidence * 100)}%`;
30
+ export function predictionFromDecision(decision: { label: string; positiveLabel: string | null; confidence: number | null }): CardPrediction {
31
+ return { state: "ready", choice: decision.label === (decision.positiveLabel ?? "include") ? "accept" : "reject", confidence: decision.confidence };
45
32
  }
46
33
 
47
34
  /**
@@ -52,96 +39,57 @@ function percent(confidence: number | null): string | null {
52
39
  export function ReviewCard({
53
40
  children,
54
41
  decided,
42
+ dek,
55
43
  disabledReason,
56
44
  initialNote = "",
57
45
  initialReason = null,
58
46
  itemId,
47
+ meta,
59
48
  onArchive,
49
+ sourcePreview,
60
50
  onDecide,
61
51
  prediction,
62
52
  summary,
63
53
  title,
64
54
  titleHref,
55
+ ratings,
65
56
  }: {
66
57
  children?: ReactNode;
58
+ /** A shared rating store, so the grid card and this card stay in step. Optional: the card works alone without it. */
59
+ ratings?: RatingController;
67
60
  /** The saved human answer, or null while the item is undecided. */
68
61
  decided: ReviewChoice | null;
62
+ /** The source's own subtitle or blurb, shown under the title. */
63
+ dek?: string | null;
69
64
  /** When set, the controls explain in words why they cannot change anything. */
70
65
  disabledReason?: string | null;
71
66
  initialNote?: string;
72
67
  initialReason?: ReferenceRejectionReasonCode | null;
73
68
  itemId: string;
69
+ /** Badges (type, status) shown under the title and link. */
70
+ meta?: ReactNode;
74
71
  onArchive?: () => Promise<void> | void;
75
72
  onDecide: (choice: ReviewChoice, decision: ReviewCardDecision) => Promise<void> | void;
76
73
  prediction: CardPrediction;
74
+ /** The live preview of the source, shown under its link. It renders nothing when there is none. */
75
+ sourcePreview?: ReactNode;
77
76
  summary?: string | null;
78
77
  title: string;
79
78
  titleHref?: string | null;
80
79
  }) {
81
- const [draft, setDraft] = useState<ReviewChoice | null>(null);
82
- const [note, setNote] = useState(initialNote);
83
- const [reason, setReason] = useState<ReferenceRejectionReasonCode | null>(initialReason);
84
- const [saving, setSaving] = useState(false);
85
- const [saved, setSaved] = useState(false);
86
- const [error, setError] = useState<string | null>(null);
87
- const inFlight = useRef(false);
88
- const noteTouched = useRef(false);
89
- const reasonTouched = useRef(false);
90
- const savedNote = useRef(initialNote);
91
-
92
- // Saved values from outside (another editor, a reload) refresh whatever the human has not touched.
93
- useEffect(() => {
94
- savedNote.current = initialNote;
95
- if (!noteTouched.current) setNote(initialNote);
96
- }, [initialNote]);
97
- useEffect(() => {
98
- if (!reasonTouched.current) setReason(initialReason);
99
- }, [initialReason]);
100
-
101
- const chosen = draft ?? decided;
102
-
103
- async function save(choice: ReviewChoice, nextReason: ReferenceRejectionReasonCode | null, nextNote: string) {
104
- if (disabledReason || inFlight.current) return;
105
- if (choice === "reject" && !nextReason) return;
106
- inFlight.current = true;
107
- setSaving(true);
108
- setSaved(false);
109
- setError(null);
110
- try {
111
- await onDecide(choice, { note: nextNote.trim(), reasonCode: choice === "reject" ? nextReason : null });
112
- savedNote.current = nextNote.trim();
113
- noteTouched.current = false;
114
- reasonTouched.current = false;
115
- setDraft(null);
116
- setSaved(true);
117
- } catch (failure) {
118
- setDraft(null);
119
- setError(failure instanceof Error ? failure.message : "Your answer could not be saved. Tap it again to retry.");
120
- } finally {
121
- inFlight.current = false;
122
- setSaving(false);
123
- }
124
- }
125
-
126
- function choose(choice: ReviewChoice) {
127
- if (disabledReason) return;
128
- if (chosen === choice && draft === null) return; // the selected answer never unselects itself
129
- setError(null);
130
- setDraft(choice);
131
- void save(choice, reason, note);
132
- }
133
-
134
- function chooseReason(code: ReferenceRejectionReasonCode) {
135
- if (disabledReason) return;
136
- setReason(code);
137
- reasonTouched.current = true;
138
- if (chosen === "reject") void save("reject", code, note);
139
- }
140
-
141
- function commitNote() {
142
- if (!decided || disabledReason || note.trim() === savedNote.current.trim()) return;
143
- void save(decided, reason, note);
144
- }
80
+ // The rating state lives in a store. Given one (`ratings`), the grid card and this card share it, so a vote or a reason typed in
81
+ // either shows in both at once; without one the card keeps a private store, exactly as before.
82
+ const local = useRatingStore({
83
+ save: (_id, choice, detail) => onDecide(choice, detail),
84
+ saved: () => decided,
85
+ seed: () => ({ note: initialNote, reasonCode: initialReason }),
86
+ });
87
+ const store = ratings ?? local;
88
+ const item = store.get(itemId);
89
+ const note = item.note ?? initialNote;
90
+ const chosen = item.pending ?? decided;
91
+ const choose = (choice: ReviewChoice) => { if (!disabledReason) store.choose(itemId, choice); };
92
+ const commitNote = () => { if (!disabledReason) store.commitNote(itemId); };
145
93
 
146
94
  // Desktop shortcuts: A accepts, R rejects. Never while typing.
147
95
  useEffect(() => {
@@ -156,131 +104,44 @@ export function ReviewCard({
156
104
  return () => window.removeEventListener("keydown", onKey);
157
105
  });
158
106
 
159
- const predictedMarker = (choice: ReviewChoice) => {
160
- if (prediction.state !== "ready" || prediction.choice !== choice) return null;
161
- return prediction.choice;
162
- };
163
- const matched = decided && prediction.state === "ready" ? prediction.choice === decided : null;
164
-
165
107
  return (
166
108
  <section aria-label="Review" className="space-y-4" data-review-card={itemId}>
167
- <header className="space-y-1">
109
+ {/* Title, blurb, link, badges, summary: what the item is, read top to bottom before the rating. */}
110
+ <header className="space-y-2">
168
111
  <h2 className="text-lg font-semibold leading-snug text-foreground">{title}</h2>
112
+ {dek && dek.trim() !== title.trim() ? <p className="text-base text-muted-foreground" data-review-dek>{dek}</p> : null}
169
113
  {titleHref ? (
170
114
  <a className="inline-flex max-w-full items-center gap-1 truncate text-sm text-primary underline-offset-4 hover:underline" href={titleHref} rel="noreferrer" target="_blank">
171
115
  <span className="truncate">{titleHref}</span>
172
116
  <ExternalLinkIcon aria-hidden="true" className="size-3.5 shrink-0" />
173
117
  </a>
174
118
  ) : null}
175
- {summary ? <p className="text-sm text-muted-foreground">{summary}</p> : null}
176
- </header>
177
-
178
- <div className="space-y-2" data-review-row="cyclotron">
179
- <div className="flex items-center gap-3">
180
- <span className="w-20 shrink-0 text-sm font-semibold">Cyclotron</span>
181
- {prediction.state === "ready" ? (
182
- <div className="flex flex-1 gap-2">
183
- {(["accept", "reject"] as const).map((choice) => {
184
- const predicted = predictedMarker(choice) !== null;
185
- const verdict = predicted && matched !== null ? (matched ? "match" : "miss") : null;
186
- return (
187
- <span
188
- className={cn(
189
- "inline-flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md border px-3 text-sm",
190
- predicted ? "border-foreground bg-muted font-semibold" : "border-dashed text-muted-foreground",
191
- verdict === "match" && "border-green-700 bg-green-100 text-green-950",
192
- verdict === "miss" && "border-red-700 bg-red-100 text-red-950",
193
- )}
194
- data-cyclotron-choice={choice}
195
- data-predicted={predicted || undefined}
196
- data-verdict={verdict ?? undefined}
197
- key={choice}
198
- >
199
- {verdict === "match" ? <CircleCheckIcon aria-hidden="true" className="size-4" /> : null}
200
- {verdict === "miss" ? <CircleXIcon aria-hidden="true" className="size-4" /> : null}
201
- {CHOICE_LABEL[choice]}
202
- {predicted && percent(prediction.confidence) ? <small className="text-xs font-normal">{percent(prediction.confidence)}</small> : null}
203
- {verdict ? <span className="sr-only">{verdict === "match" ? ", matches your answer" : ", differs from your answer"}</span> : null}
204
- </span>
205
- );
206
- })}
207
- </div>
208
- ) : (
209
- <p className="text-sm text-muted-foreground" data-cyclotron-state={prediction.state}>
210
- {prediction.state === "loading" ? "Loading…" : prediction.state === "error" ? "Prediction unavailable" : "No prediction"}
211
- </p>
212
- )}
213
- </div>
214
- </div>
215
-
216
- <div className="space-y-2" data-review-row="you">
217
- <div className="flex items-center gap-3">
218
- <span className="w-20 shrink-0 text-sm font-semibold">You</span>
219
- <div className="flex flex-1 gap-2">
220
- {(["accept", "reject"] as const).map((choice) => {
221
- const on = chosen === choice;
222
- return (
223
- <Button
224
- aria-disabled={disabledReason ? true : undefined}
225
- aria-pressed={on}
226
- className="min-h-14 flex-1 text-base"
227
- data-review-choice={choice}
228
- key={choice}
229
- onClick={() => choose(choice)}
230
- type="button"
231
- variant={on ? (choice === "accept" ? "default" : "destructive") : "outline"}
232
- >
233
- {on ? <CheckIcon aria-hidden="true" className="size-5" /> : null}
234
- {CHOICE_LABEL[choice]}
235
- </Button>
236
- );
237
- })}
119
+ {sourcePreview}
120
+ {meta}
121
+ {summary ? (
122
+ <div className="space-y-1 pt-1" data-review-summary>
123
+ <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Summary</h3>
124
+ <p className="text-sm leading-relaxed text-foreground">{summary}</p>
238
125
  </div>
239
- </div>
240
- <div className="min-h-5 pl-[5.75rem] text-sm" role="status">
241
- {saving ? "Saving…" : saved ? (
242
- <span className="inline-flex items-center gap-1" data-review-saved><CheckIcon aria-hidden="true" className="size-4" />Saved</span>
243
- ) : null}
244
- </div>
245
- {disabledReason ? <p className="text-sm text-muted-foreground" data-review-disabled-reason>{disabledReason}</p> : null}
246
- {error ? <p className="text-sm text-destructive" role="alert">{error}</p> : null}
247
- </div>
248
-
249
- <label className="block text-sm font-medium">
250
- Why? (optional)
251
- <textarea
252
- aria-label="Why? (optional)"
253
- className="mt-1 block min-h-24 w-full rounded-md border bg-background p-3 text-base font-normal"
254
- onBlur={commitNote}
255
- onChange={(event) => { setNote(event.target.value); noteTouched.current = true; setSaved(false); }}
256
- placeholder="Say what made this an easy yes or a clear no. Your note teaches the Cyclotron."
257
- value={note}
258
- />
259
- </label>
126
+ ) : null}
127
+ </header>
260
128
 
261
- {chosen === "reject" ? (
262
- <div className="space-y-2" data-review-reasons>
263
- <p className="text-sm font-medium">Reason for rejecting</p>
264
- <div className="flex flex-wrap gap-2">
265
- {REFERENCE_REJECTION_REASON_CODES.map((code) => (
266
- <Button
267
- aria-disabled={disabledReason ? true : undefined}
268
- aria-pressed={reason === code}
269
- className="min-h-10"
270
- data-review-reason={code}
271
- key={code}
272
- onClick={() => chooseReason(code)}
273
- type="button"
274
- variant={reason === code ? "default" : "outline"}
275
- >
276
- {reason === code ? <CheckIcon aria-hidden="true" className="size-4" /> : null}
277
- {REASON_LABELS[code]}
278
- </Button>
279
- ))}
280
- </div>
281
- {!reason ? <p className="text-sm text-muted-foreground">Choose a reason to save your Reject.</p> : null}
282
- </div>
283
- ) : null}
129
+ <DecisionControl
130
+ answer={chosen}
131
+ decided={decided}
132
+ disabled={Boolean(disabledReason)}
133
+ disabledReason={disabledReason}
134
+ feedback={item.feedback}
135
+ needsReason={item.askReason}
136
+ onChoose={choose}
137
+ onReasonChange={(text) => store.setNote(itemId, text)}
138
+ onReasonCommit={commitNote}
139
+ prediction={prediction}
140
+ reason={note}
141
+ reasonRequiredFor="reject"
142
+ size="large"
143
+ surface="card"
144
+ />
284
145
 
285
146
  {children}
286
147
 
@@ -301,7 +162,10 @@ export function ReviewQueueBar({
301
162
  onPrevious,
302
163
  position,
303
164
  total,
165
+ anchored = false,
304
166
  }: {
167
+ /** On a wide screen, pin the bar to the bottom-right corner of the viewport (the detail column's width), whatever scrolls. A sheet's own bar is not anchored. */
168
+ anchored?: boolean;
305
169
  caughtUp?: boolean;
306
170
  onNext: () => void;
307
171
  onPrevious: () => void;
@@ -313,7 +177,8 @@ export function ReviewQueueBar({
313
177
  return (
314
178
  <nav
315
179
  aria-label="Review queue"
316
- className="sticky bottom-0 z-10 flex shrink-0 items-center gap-2 border-t border-border bg-card px-3 py-2"
180
+ className={cn("sticky bottom-0 z-10 flex shrink-0 items-center gap-2 bg-[var(--feed-card)] px-3 py-2", anchored && "md:fixed md:bottom-0 md:right-0 md:w-[calc(24rem+1rem)] md:pr-7 lg:w-[calc(28rem+1rem)]")}
181
+ data-review-queue-anchored={anchored || undefined}
317
182
  data-review-queue-bar
318
183
  >
319
184
  <Button
@@ -87,6 +87,31 @@ function PdfSourcePreview({ preview }: { preview: Extract<ReferenceSourcePreview
87
87
  );
88
88
  }
89
89
 
90
+ /** Session memory of the server's answers, so reopening an item does not ask again. */
91
+ const frameableAnswers = new Map<string, boolean>();
92
+
93
+ /** Whether the page allows being shown in a frame: null while asking. A refused frame would be an empty box, so it is not shown. */
94
+ function useFrameable(href: string | null): boolean | null {
95
+ const [answer, setAnswer] = useState<boolean | null>(() => (href ? frameableAnswers.get(href) ?? null : null));
96
+ useEffect(() => {
97
+ if (!href) return undefined;
98
+ const known = frameableAnswers.get(href);
99
+ if (known !== undefined) { setAnswer(known); return undefined; }
100
+ setAnswer(null);
101
+ let active = true;
102
+ fetch(`/api/newsroom/source-frameable?url=${encodeURIComponent(href)}`)
103
+ .then((response) => (response.ok ? response.json() : { frameable: false }))
104
+ .then((body: { frameable?: unknown }) => { frameableAnswers.set(href, body.frameable === true); if (active) setAnswer(body.frameable === true); })
105
+ .catch(() => { if (active) setAnswer(false); });
106
+ return () => { active = false; };
107
+ }, [href]);
108
+ return answer;
109
+ }
110
+
111
+ /**
112
+ * The live preview of the source, or nothing at all: a YouTube video or a PDF always has one; a web page only when the page allows
113
+ * being framed (asked of the server first). It sits under the link to the original, with no heading of its own.
114
+ */
90
115
  export function ReferenceSourcePreview({
91
116
  attachments = [],
92
117
  sourceUri,
@@ -95,6 +120,7 @@ export function ReferenceSourcePreview({
95
120
  sourceUri?: string | null;
96
121
  }) {
97
122
  const preview = resolveReferenceSourcePreview(sourceUri, attachments);
123
+ const frameable = useFrameable(preview?.kind === "html" ? preview.href : null);
98
124
  const pendingPdfPreview = !preview && attachments.some(
99
125
  (attachment) => isPdfAttachment(attachment) && Boolean(attachment.storagePath),
100
126
  );
@@ -139,6 +165,7 @@ export function ReferenceSourcePreview({
139
165
  return <PdfSourcePreview preview={preview} />;
140
166
  }
141
167
 
168
+ if (frameable !== true) return null;
142
169
  return (
143
170
  <div
144
171
  className="news-desk-reference-source-preview news-desk-reference-source-preview--html"
@@ -153,11 +180,6 @@ export function ReferenceSourcePreview({
153
180
  title={preview.label}
154
181
  />
155
182
  </div>
156
- <p className="news-desk-reference-source-preview__actions">
157
- <a href={preview.href} rel="noopener noreferrer" target="_blank">
158
- {preview.label}
159
- </a>
160
- </p>
161
183
  </div>
162
184
  );
163
185
  }
@@ -0,0 +1,34 @@
1
+ "use client";
2
+
3
+ import { FileTextIcon, LinkIcon } from "lucide-react";
4
+ import Link from "next/link";
5
+ import { useEffect, useState } from "react";
6
+ import { getNewsroomNavHref } from "../lib/newsroom-nav";
7
+ import { referenceRoleLabel, type ReferenceStory } from "../lib/story-reporting-trail";
8
+ import { loadStoriesBasedOnReference } from "./story-reporting-trail-client";
9
+
10
+ /**
11
+ * The stories made from one Reference: each links to the story's own page. The stories' text is their own; this list is the other end
12
+ * of the link the story view shows under References.
13
+ */
14
+ export function ReferenceStories({ demo = false, referenceLineageId }: { demo?: boolean; referenceLineageId: string }) {
15
+ const [stories, setStories] = useState<ReferenceStory[] | null>(null);
16
+ useEffect(() => {
17
+ let active = true;
18
+ setStories(null);
19
+ loadStoriesBasedOnReference(referenceLineageId, demo).then(rows => { if (active) setStories(rows); }).catch(() => { if (active) setStories([]); });
20
+ return () => { active = false; };
21
+ }, [demo, referenceLineageId]);
22
+ if (!stories?.length) return null;
23
+ return <section aria-label="Stories based on this Reference" className="reference-stories" data-reference-stories={referenceLineageId}>
24
+ <h3>Stories based on this Reference</h3>
25
+ <ul>
26
+ {stories.map(story => <li data-reference-story={story.lineageId} key={story.relationId}>
27
+ <FileTextIcon aria-hidden="true" size={16} />
28
+ <Link href={getNewsroomNavHref(`/newsroom/articles/${encodeURIComponent(story.itemId)}`, demo)}>{story.title ?? story.lineageId}</Link>
29
+ <span className="story-trail-role">{story.role === "based_on" ? <LinkIcon aria-hidden="true" size={13} /> : null}{referenceRoleLabel(story.role)}</span>
30
+ {story.stage && <span className="story-trail-meta">{story.stage}</span>}
31
+ </li>)}
32
+ </ul>
33
+ </section>;
34
+ }
@@ -0,0 +1,61 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useState } from "react";
4
+ import { LoaderIcon } from "lucide-react";
5
+ import { SITE_BRAND } from "../lib/site-brand";
6
+ import { loadFeedSnapshot, type FeedSnapshot } from "../lib/reference-feed-cache";
7
+ import { partitionReferenceFeed, type ReferenceFeedTabKey } from "../lib/reference-feed-ranking";
8
+ import { selectCanonicalReferenceRecords } from "../lib/newsroom-references";
9
+ import { ReferenceFeed, ReferenceFeedSkeleton } from "./reference-feed";
10
+
11
+ /**
12
+ * What the References page shows while the session and the first reads are still resolving: the real page header at once,
13
+ * then this browser's last saved view (read only, answering switches on when the session is confirmed), or card skeletons
14
+ * when there is none. Never a full-screen "checking" screen.
15
+ */
16
+ export function ReferencesPageLoading() {
17
+ const [snapshot, setSnapshot] = useState<FeedSnapshot | null>(null);
18
+ const [checked, setChecked] = useState(false);
19
+ const [tab, setTab] = useState<ReferenceFeedTabKey>("feed");
20
+ const [note, setNote] = useState<string | null>(null);
21
+ const [now] = useState(() => Date.now());
22
+ useEffect(() => {
23
+ setSnapshot(loadFeedSnapshot(SITE_BRAND.id));
24
+ setChecked(true);
25
+ }, []);
26
+ const references = useMemo(() => selectCanonicalReferenceRecords(snapshot?.references ?? []), [snapshot]);
27
+ const decisions = useMemo(() => new Map(snapshot?.decisions ?? []), [snapshot]);
28
+ const previews = useMemo(() => new Map(snapshot?.previews ?? []), [snapshot]);
29
+ const partition = useMemo(() => partitionReferenceFeed(references, decisions, { now }), [references, decisions, now]);
30
+ const noVisitRated = useMemo(() => new Set<string>(), []);
31
+
32
+ return (
33
+ <div className="space-y-4" data-references-page-loading>
34
+ <div className="space-y-1">
35
+ <h2 className="text-2xl font-bold tracking-tight">References</h2>
36
+ <p className="text-sm text-muted-foreground">A feed ranked by what you are most likely to accept.</p>
37
+ </div>
38
+ {note ? <p className="text-sm text-muted-foreground" role="status">{note}</p> : null}
39
+ {checked && references.length ? (
40
+ <ReferenceFeed
41
+ disabledReason="Confirming your sign-in. You can answer in a moment."
42
+ now={now}
43
+ onOpen={() => setNote("Opening a reference is available in a moment, once your sign-in is confirmed.")}
44
+ onRate={() => undefined}
45
+ onTabChange={setTab}
46
+ onVisitRated={() => undefined}
47
+ partition={partition}
48
+ previews={previews}
49
+ stale
50
+ tab={tab}
51
+ visitRated={noVisitRated}
52
+ />
53
+ ) : (
54
+ <>
55
+ <p className="inline-flex items-center gap-1.5 text-xs text-muted-foreground" role="status"><LoaderIcon aria-hidden="true" className="size-3.5 animate-spin" />Loading your references</p>
56
+ <ReferenceFeedSkeleton />
57
+ </>
58
+ )}
59
+ </div>
60
+ );
61
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Starts the References reads as soon as the editor session is confirmed, in parallel with the summary dashboard, instead of after it.
3
+ * The page that needs them takes the in-flight request once; anything later, or a retry, makes a fresh read. This is a head start
4
+ * on the same reads, not a cache: the backend authorizes each call exactly as before.
5
+ */
6
+ import {
7
+ loadEditorMessagesData,
8
+ loadEditorReferencesData,
9
+ loadEditorSemanticRelationsData,
10
+ } from "./news-desk-taxonomy-client";
11
+
12
+ const HEAD_START_MS = 60_000;
13
+ type Started = { startedAt: number; promise: Promise<unknown> };
14
+ const started = new Map<string, Started>();
15
+
16
+ const LOADERS = {
17
+ references: loadEditorReferencesData,
18
+ relations: loadEditorSemanticRelationsData,
19
+ messages: loadEditorMessagesData,
20
+ } as const;
21
+ type Key = keyof typeof LOADERS;
22
+
23
+ /** Begin all three reads. Safe to call twice; a failure is reported to whoever takes the read, never as an unhandled rejection. */
24
+ export function prefetchReferencesFeed(now = Date.now()) {
25
+ for (const key of Object.keys(LOADERS) as Key[]) {
26
+ if (started.has(key)) continue;
27
+ const promise = LOADERS[key]();
28
+ promise.catch(() => undefined);
29
+ started.set(key, { startedAt: now, promise });
30
+ }
31
+ }
32
+
33
+ function take<Key2 extends Key>(key: Key2, now = Date.now()): ReturnType<(typeof LOADERS)[Key2]> {
34
+ const head = started.get(key);
35
+ started.delete(key);
36
+ if (head && now - head.startedAt <= HEAD_START_MS) return head.promise as ReturnType<(typeof LOADERS)[Key2]>;
37
+ return LOADERS[key]() as ReturnType<(typeof LOADERS)[Key2]>;
38
+ }
39
+
40
+ export const loadReferencesWithHeadStart = () => take("references");
41
+ export const loadRelationsWithHeadStart = () => take("relations");
42
+ export const loadMessagesWithHeadStart = () => take("messages");
43
+
44
+ /** Forget any unclaimed head start (sign-out). */
45
+ export function discardReferencesHeadStart() {
46
+ started.clear();
47
+ }
48
+
49
+ /** The pages that need the References straight away: the feed itself and the home page, whose Notification Center shows References cards. */
50
+ export function wantsReferencesHeadStart(pathname: string): boolean {
51
+ return /\/newsroom\/references(\/|$)/.test(pathname) || /\/newsroom\/?$/.test(pathname);
52
+ }
@@ -3,8 +3,8 @@
3
3
  import { generateClient } from "aws-amplify/data";
4
4
  import type { Schema } from "../amplify/data/resource";
5
5
  import { isLocalPreviewEnabled } from "../lib/local-preview";
6
- import { createLocalPreviewReportingTrail } from "../lib/local-preview-seed";
7
- import { EMPTY_STORY_REPORTING_TRAIL, type StoryReportingTrail, type TrailAssignment, type TrailAttachment, type TrailReference, type TrailThread, type TrailVersion } from "../lib/story-reporting-trail";
6
+ import { createLocalPreviewReportingTrail, createLocalPreviewStoriesForReference } from "../lib/local-preview-seed";
7
+ import { EMPTY_STORY_REPORTING_TRAIL, referencesByRole, siteNameOf, type ReferenceStory, type StoryReportingTrail, type TrailAssignment, type TrailAttachment, type TrailReference, type TrailThread, type TrailVersion } from "../lib/story-reporting-trail";
8
8
  import { configureAmplifyClient } from "./amplify-client-provider";
9
9
 
10
10
  type GraphqlResponse = { data?: Record<string, { items?: Record<string, unknown>[] | null; nextToken?: string | null } | null> | null; errors?: { message?: string }[] | null };
@@ -48,9 +48,44 @@ async function getReference(client: GraphqlClient, referenceId: string): Promise
48
48
  }
49
49
  }
50
50
 
51
+ function relationRole(value: unknown): TrailReference["role"] {
52
+ return value === "based_on" ? "based_on" : value === "cited" ? "cited" : "consulted";
53
+ }
54
+
55
+ /** The Reference's preview image address and site name, from its `preview` attachment (nothing is downloaded). */
56
+ async function getPreview(client: GraphqlClient, referenceLineageId: string): Promise<{ imageUrl: string | null; siteName: string | null }> {
57
+ try {
58
+ const rows = await listAll(client, "listReferenceAttachmentsByReferenceLineageAndSortKey", "id role sourceUri filename metadata", ", $referenceLineageId: ID!", ", referenceLineageId: $referenceLineageId", { referenceLineageId });
59
+ const preview = rows.find(row => row.role === "preview");
60
+ const address = text(preview?.sourceUri);
61
+ return { imageUrl: address && /^https?:\/\//i.test(address) ? address : null, siteName: text(parseMetadata(preview?.metadata).siteName) ?? text(preview?.filename) };
62
+ } catch {
63
+ return { imageUrl: null, siteName: null };
64
+ }
65
+ }
66
+
67
+ /** The stories whose `uses_evidence` link names this Reference, each with its working title and stage. */
68
+ export async function loadStoriesBasedOnReference(referenceLineageId: string, demo = false): Promise<ReferenceStory[]> {
69
+ if (demo || isLocalPreviewEnabled()) return createLocalPreviewStoriesForReference(referenceLineageId);
70
+ configureAmplifyClient();
71
+ const client = generateClient<Schema>() as unknown as GraphqlClient;
72
+ const relations = await listAll(client, "listSemanticRelationsByObjectState", "id predicate subjectKind subjectId subjectLineageId metadata", ", $objectStateKey: String!", ", objectStateKey: $objectStateKey", { objectStateKey: `reference#${referenceLineageId}#current` });
73
+ const stories = relations.filter(relation => relation.predicate === "uses_evidence" && relation.subjectKind === "item");
74
+ const rows = await Promise.all(stories.map(async relation => {
75
+ const lineageId = String(relation.subjectLineageId ?? relation.subjectId);
76
+ const versions = await listAll(client, "listItemsByLineageAndVersion", "id versionNumber versionState stage headline title", ", $lineageId: ID!", ", lineageId: $lineageId", { lineageId }).catch(() => []);
77
+ const current = versions.find(version => version.versionState === "current") ?? versions.sort((left, right) => Number(right.versionNumber ?? 0) - Number(left.versionNumber ?? 0))[0];
78
+ return {
79
+ relationId: String(relation.id), itemId: String(current?.id ?? relation.subjectId), lineageId, title: text(current?.headline) ?? text(current?.title), stage: text(current?.stage),
80
+ role: relationRole(parseMetadata(relation.metadata).role),
81
+ } satisfies ReferenceStory;
82
+ }));
83
+ return rows;
84
+ }
85
+
51
86
  /** Reads the whole reporting trail of one story from the backend; the local preview serves a snapshot instead. */
52
- export async function loadStoryReportingTrail(lineageId: string, itemId: string): Promise<StoryReportingTrail> {
53
- if (isLocalPreviewEnabled()) return createLocalPreviewReportingTrail(lineageId);
87
+ export async function loadStoryReportingTrail(lineageId: string, itemId: string, demo = false): Promise<StoryReportingTrail> {
88
+ if (demo || isLocalPreviewEnabled()) return createLocalPreviewReportingTrail(lineageId);
54
89
  configureAmplifyClient();
55
90
  const client = generateClient<Schema>() as unknown as GraphqlClient;
56
91
  const [versionRows, assignmentRows, attachmentRows, relationRows] = await Promise.all([
@@ -77,15 +112,17 @@ export async function loadStoryReportingTrail(lineageId: string, itemId: string)
77
112
  return { id: String(row.id), title: text(row.title), threadKind: text(row.threadKind), summary: text(row.summary), messages: messageRows.map(message => ({ id: String(message.id), sequenceNumber: typeof message.sequenceNumber === "number" ? message.sequenceNumber : null, messageKind: text(message.messageKind), authorLabel: text(message.authorLabel), summary: text(message.summary), content: text(message.content), createdAt: String(message.createdAt ?? "") })) };
78
113
  }));
79
114
  const referenceRelations = relationRows.filter(relation => relation.predicate === "uses_evidence" && relation.subjectLineageId === lineageId && relation.objectKind === "reference");
80
- const references: TrailReference[] = await Promise.all(referenceRelations.map(async relation => {
115
+ const references: TrailReference[] = referencesByRole(await Promise.all(referenceRelations.map(async relation => {
81
116
  const metadata = parseMetadata(relation.metadata);
82
117
  const referenceRow = await getReference(client, String(relation.objectId));
118
+ const preview = await getPreview(client, text(relation.objectLineageId) ?? String(relation.objectId));
119
+ const sourceUri = text(referenceRow?.sourceUri);
83
120
  return {
84
121
  relationId: String(relation.id), predicate: String(relation.predicate ?? ""), referenceId: String(relation.objectId), referenceLineageId: text(relation.objectLineageId),
85
- title: text(referenceRow?.title), sourceUri: text(referenceRow?.sourceUri),
86
- role: metadata.role === "cited" ? "cited" as const : "consulted" as const, note: text(metadata.note), citationKey: text(metadata.citationKey), addedBy: text(metadata.addedBy), addedAt: text(metadata.addedAt),
122
+ title: text(referenceRow?.title), sourceUri, siteName: siteNameOf(sourceUri, preview.siteName), previewImageUrl: preview.imageUrl,
123
+ role: relationRole(metadata.role), note: text(metadata.note), citationKey: text(metadata.citationKey), addedBy: text(metadata.addedBy), addedAt: text(metadata.addedAt),
87
124
  };
88
- }));
125
+ })));
89
126
  const attachments: TrailAttachment[] = attachmentRows.map(row => ({ id: String(row.id), role: text(row.role), filename: text(row.filename), mediaType: text(row.mediaType), byteSize: typeof row.byteSize === "number" ? row.byteSize : null }));
90
127
  return { ...EMPTY_STORY_REPORTING_TRAIL, versions, assignments, threads, references, attachments };
91
128
  }