Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): show what each agent suggestion was written from (CE-033, CE-034) (#1399)

Cihan8cde68c22d28
diff --git a/web/messages/en.json b/web/messages/en.json
index f982572f7..908a12208 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3611,7 +3611,7 @@
"none": "No sources kept yet · <edit>Edit sources</edit>",
"note": {
"title": "Content Agent writes from your data",
- "body": "Your prompts, fan-outs, cited pages and Search Console queries.",
+ "body": "Your prompts, fan-outs, cited pages and Search Console queries. Every change shows the sources it used.",
"close": "Close"
}
},
@@ -3623,7 +3623,9 @@
"reviewedLine": "{accepted, number} accepted · Rules {met, number} of {total, number}{open, plural, =0 {} other { · # still open}}",
"more": "+{count, number} more",
"run": "Run Agent",
- "working": "Content Agent is working"
+ "working": "Content Agent is working",
+ "builtFrom": "built from {count, number} of your sources",
+ "seeSources": "See sources"
},
"rewrite": {
"bar": "Rewritten page",
@@ -3666,6 +3668,14 @@
"stale": "The page changed here since the agent read it.",
"heading": "This would put more than a heading into the heading. Reject it, and add the text below the heading yourself.",
"links": "Links",
+ "basedOn": "Based on",
+ "sourceKinds": {
+ "prompt": "Prompt",
+ "fanout": "Fan-out",
+ "cited_page": "Cited page",
+ "gsc_query": "Search Console"
+ },
+ "sourceMark": "Source {n}: {label}",
"acceptedToast": "{count, plural, one {Accepted} other {# changes accepted}} · undo any time",
"rejectedToast": "{count, plural, one {Rejected} other {# changes rejected}} · restore any time",
"undoneToast": "{count, plural, one {Undone · back to the suggestion} other {# undone · the suggestions are back}}",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
index 7954aa355..d81b0a646 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
@@ -154,6 +154,44 @@ describe('AgentCard', () => {
expect(handlers.onDecidePage).toHaveBeenCalledWith('accepted');
});
+ it('says how many of the person’s sources a batch or a rewrite was built from (CE-034)', async () => {
+ const onSeeSources = vi.fn();
+ const show = async (list: DraftSuggestion[]) =>
+ act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <AgentCard
+ suggestions={list}
+ rules={rules}
+ busy={false}
+ working={false}
+ sourceCount={3}
+ onSeeSources={onSeeSources}
+ {...handlers}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ await show([suggestion({})]);
+ expect(container.textContent).toContain('built from 3 of your sources · See sources');
+ await click('See sources');
+ expect(onSeeSources).toHaveBeenCalledTimes(1);
+ await show([
+ suggestion({
+ kind: 'page',
+ beforeHtml: '<h1>Old</h1><p>Longer than this.</p>',
+ afterText: '<h1>New</h1><p>Short.</p>',
+ reason: 'cut to the Length',
+ }),
+ ]);
+ expect(container.textContent).toContain(
+ 'cut to the Length · built from 3 of your sources · See sources',
+ );
+ // None named: nothing said.
+ await render([suggestion({})]);
+ expect(container.textContent).not.toContain('built from');
+ });
+
it('stops all of its motion with reduced motion, in every state', async () => {
for (const [list, working] of [
[[suggestion()], false],
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
index a83a0fa1c..d79fe2f6b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
@@ -168,6 +168,8 @@ export function AgentCard({
onClose,
onDecidePage,
runBlocked = null,
+ sourceCount = 0,
+ onSeeSources,
}: {
suggestions: DraftSuggestion[];
rules: CardRules;
@@ -187,6 +189,10 @@ export function AgentCard({
onDecidePage: (status: SuggestionStatus) => void;
/** Why Run Agent can't run now (another agent run, locked passages loading), or null. */
runBlocked?: string | null;
+ /** How many of the person's sources the batch was written from (CE-033/034). */
+ sourceCount?: number;
+ /** Opens the Sources tab. */
+ onSeeSources?: () => void;
}) {
const t = useTranslations('contentEditor.editor.agentCard');
const locale = useLocale();
@@ -205,6 +211,25 @@ export function AgentCard({
const reasonId = useId();
const reason = runShown ? runBlocked : null;
const tone = working ? 'working' : open > 0 ? 'waiting' : 'done';
+ // "built from 3 of your sources · See sources" (v1.1 §3b).
+ const builtFrom = sourceCount > 0 && (
+ <>
+ {' · '}
+ {t('builtFrom', { count: sourceCount })}
+ {onSeeSources && (
+ <>
+ {' · '}
+ <button
+ type="button"
+ onClick={onSeeSources}
+ className="font-medium text-foreground underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ >
+ {t('seeSources')}
+ </button>
+ </>
+ )}
+ </>
+ );
let title: React.ReactNode;
let line: React.ReactNode;
@@ -236,6 +261,7 @@ export function AgentCard({
page.status === 'open' ? (
<>
{tRewrite('characters', { before, after: afterChars })} · {page.reason}
+ {builtFrom}
</>
) : page.status === 'accepted' && stillOpen > 0 ? (
tRewrite('rulesOpen', { count: stillOpen })
@@ -254,6 +280,7 @@ export function AgentCard({
</span>
</>
)}
+ {builtFrom}
{action && (
<>
{' · '}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.test.tsx
index c5a079752..421f5f3dd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.test.tsx
@@ -89,7 +89,7 @@ describe('the data note', () => {
useAuthStore.setState({ user: person({ full_name: 'Demo' }) });
await render(<DataNote />);
expect(container.textContent).toBe(
- 'Content Agent writes from your dataYour prompts, fan-outs, cited pages and Search Console queries.',
+ 'Content Agent writes from your dataYour prompts, fan-outs, cited pages and Search Console queries. Every change shows the sources it used.',
);
await act(async () =>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index 0c31bc575..81f0d0290 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
@@ -52,9 +52,13 @@ import {
import type { DraftVersion } from '@/lib/content/history';
import {
AGENT_RUN_MAX,
+ batchSources,
type DraftSuggestion,
+ type SuggestionSource,
type SuggestionStatus,
} from '@/lib/content/suggestions';
+import { rebuildSources } from '@/lib/content/brief';
+import { buildSourceGroups } from '@/lib/content/sources';
import {
cleanHtml,
formatHtmlSource,
@@ -78,6 +82,7 @@ import {
type HeldEdit,
} from './_cited-passages';
import { ExportMenu } from './_export-menu';
+import { sourceDetail } from './_sources-tab';
import { HistoryMenu } from './_history-menu';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { OwnCopies, ownCopyHtml } from './_own-copies';
@@ -242,11 +247,21 @@ export function DraftEditor({
const [panelOpen, togglePanel] = useSidePanelOpen();
// The header's rules chip opens the panel on Rules, and the closed panel's
// strip on the tab picked there.
- const [tabRequest, setTabRequest] = useState<{ tab: PanelTarget; n: number } | null>(null);
- const openPanelTab = (tab: PanelTarget) => {
+ const [tabRequest, setTabRequest] = useState<{
+ tab: PanelTarget;
+ n: number;
+ /** A source to show in Sources: a "Based on" chip or mark clicked (CE-033). */
+ source?: Pick<SuggestionSource, 'kind' | 'ref'>;
+ } | null>(null);
+ const openPanelTab = (tab: PanelTarget, source?: SuggestionSource) => {
if (!panelOpen) togglePanel();
- setTabRequest((prev) => ({ tab, n: (prev?.n ?? 0) + 1 }));
+ setTabRequest((prev) => ({
+ tab,
+ n: (prev?.n ?? 0) + 1,
+ ...(source ? { source: { kind: source.kind, ref: source.ref } } : {}),
+ }));
};
+ const onSource = useRef<(source: SuggestionSource) => void>(() => {});
const editor = useEditor({
extensions: [
@@ -277,7 +292,10 @@ export function DraftEditor({
// person can't type while the question is open.
onHeld: (edit) => setHeld((current) => current ?? edit),
}),
- AgentSuggestions.configure({ onDecide: (id, decision) => onDecide.current(id, decision) }),
+ AgentSuggestions.configure({
+ onDecide: (id, decision) => onDecide.current(id, decision),
+ onSource: (source) => onSource.current(source),
+ }),
OneH1,
],
content: draft.bodyHtml,
@@ -354,6 +372,7 @@ export function DraftEditor({
useEffect(() => {
attachRef.current = (files) => void attachments.attach(files);
onDecide.current = (id, decision) => void decide([id], decision);
+ onSource.current = (source) => openPanelTab('sources', source);
});
/** "ChatGPT 14× and Perplexity 6×": the platforms quoting a passage, the most first. */
@@ -440,6 +459,17 @@ export function DraftEditor({
editor.commands.focus();
};
+ // The rows of the Sources tab by kind and ref, for a "Based on" chip's hover (CE-033).
+ const tDetail = useTranslations('contentEditor.editor.sources.detail');
+ const sourceRows = useMemo(() => {
+ const read = reads.sources;
+ if (!read?.data) return null;
+ const groups = buildSourceGroups(read.data, read.choices, {
+ title: draft.title,
+ sourceUrl: draft.sourceUrl,
+ });
+ return new Map(groups.flatMap((g) => g.rows.map((row) => [`${row.kind}:${row.ref}`, row])));
+ }, [reads.sources, draft.title, draft.sourceUrl]);
const suggestionLabels = useMemo<SuggestionLabels>(
() => ({
agent: t('suggestions.agent'),
@@ -453,8 +483,24 @@ export function DraftEditor({
stale: t('suggestions.stale'),
heading: t('suggestions.heading'),
links: t('suggestions.links'),
+ basedOn: t('suggestions.basedOn'),
+ sourceKinds: {
+ prompt: t('suggestions.sourceKinds.prompt'),
+ fanout: t('suggestions.sourceKinds.fanout'),
+ cited_page: t('suggestions.sourceKinds.cited_page'),
+ gsc_query: t('suggestions.sourceKinds.gsc_query'),
+ },
+ sourceMark: (n, label) => t('suggestions.sourceMark', { n, label }),
+ sourceTip: sourceRows
+ ? (source) => {
+ const row = sourceRows.get(`${source.kind}:${source.ref}`);
+ if (!row) return null;
+ const detail = sourceDetail(row, tDetail);
+ return detail ? `${row.name} · ${detail}` : row.name;
+ }
+ : undefined,
}),
- [t],
+ [t, tDetail, sourceRows],
);
// The latest batch, read when the editor opens.
@@ -718,6 +764,17 @@ export function DraftEditor({
const locks = citedLocks(editor.state);
return [...locks.labels.keys()].filter((key) => !locks.unlocked.has(key));
})(),
+ // The data it writes from: the sources the Sources tab keeps (CE-033).
+ ...(reads.sources?.data
+ ? {
+ sources: rebuildSources(reads.sources.data, reads.sources.choices, {
+ title,
+ sourceUrl: draft.sourceUrl,
+ html: editor.getHTML(),
+ length: rules.length,
+ }),
+ }
+ : {}),
};
setFixing(true);
const asked = Date.now();
@@ -1255,6 +1312,8 @@ export function DraftEditor({
<AgentCard
suggestions={suggestions}
rules={cardRules}
+ sourceCount={batchSources(suggestions).length}
+ onSeeSources={() => openPanelTab('sources')}
// Not while the HTML view holds the page: it would write over it.
busy={deciding || htmlSource !== null}
working={fixing}
@@ -1349,6 +1408,9 @@ export function DraftEditor({
agentRewrite={agentRewrite}
// One batch, one run: its first suggestion's time is the run's.
lastSuggestionAt={suggestions[0]?.createdAt ?? null}
+ onSourceShown={() =>
+ setTabRequest((prev) => (prev?.source ? { tab: prev.tab, n: prev.n } : prev))
+ }
/>
) : (
<EditorPanelRail onOpen={openPanelTab} />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
index 121bab48c..f22239880 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { isPageType, type ContentDraft } from '@/lib/content/drafts';
-import { buildSourceGroups, includedCounts } from '@/lib/content/sources';
+import { buildSourceGroups, includedCounts, type DraftSourceKind } from '@/lib/content/sources';
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { BriefTab, type AgentRewrite } from './_brief-tab';
@@ -110,6 +110,7 @@ export function EditorSidePanel({
pageRewrite,
agentRewrite,
lastSuggestionAt,
+ onSourceShown,
}: {
draft: ContentDraft;
/** The draft's title, page and type as written now: Sources and Brief read them. */
@@ -120,8 +121,15 @@ export function EditorSidePanel({
rules: DraftRulesState;
/** The draft's brief and sources, read once for the editor. */
reads: DraftReads;
- /** A tab to open, from outside the panel (the header's rules chip). */
- tabRequest: { tab: PanelTarget; n: number } | null;
+ /**
+ * A tab to open, from outside the panel (the header's rules chip), and a
+ * source to show in Sources (a "Based on" chip or mark, CE-033).
+ */
+ tabRequest: {
+ tab: PanelTarget;
+ n: number;
+ source?: { kind: DraftSourceKind; ref: string };
+ } | null;
/** Run Agent's Fix open rules, for Rules (CE-018, v1.1 CE-029). */
agentFix?: AgentFix;
/** Run Agent ▾'s Rewrite the whole page, for Rules; absent once the page is ready or published. */
@@ -130,6 +138,8 @@ export function EditorSidePanel({
agentRewrite?: AgentRewrite;
/** When the agent's latest suggestions came, or null: the last time it wrote from the sources. */
lastSuggestionAt: string | null;
+ /** The source asked for was shown (or isn't listed): it isn't shown again. */
+ onSourceShown?: () => void;
}) {
const t = useTranslations('contentEditor.editor.panel');
const [tab, setTab] = useState<PanelTab>('instructions');
@@ -332,6 +342,13 @@ export function EditorSidePanel({
rebuilding={rebuilding}
onRebuild={(sources) => void rebuild({ sources })}
agentUsedAt={agentUsedAt}
+ // Only while Sources shows: a hidden row can't be scrolled to.
+ highlight={
+ tab === 'sources' && tabRequest?.source
+ ? { ...tabRequest.source, n: tabRequest.n }
+ : null
+ }
+ onHighlighted={onSourceShown}
/>
</div>
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
index bd10a8da8..94888b0b4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
@@ -1,6 +1,14 @@
'use client';
-import { useDeferredValue, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
+import {
+ useDeferredValue,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type Dispatch,
+ type SetStateAction,
+} from 'react';
import { useFormatter, useNow, useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { Loader2, Plus, RefreshCw } from 'lucide-react';
@@ -14,6 +22,7 @@ import {
readDraftDoc,
usedIn,
type DraftSourceChoice,
+ type DraftSourceKind,
type DraftSourceRow,
type DraftSourcesData,
type UsedIn,
@@ -44,6 +53,8 @@ export function SourcesTab({
rebuilding,
onRebuild,
agentUsedAt,
+ highlight = null,
+ onHighlighted,
}: {
/** The sources as the editor read them; null while reading. */
read: SourcesRead | null;
@@ -60,6 +71,10 @@ export function SourcesTab({
onRebuild: (sources: { data: DraftSourcesData; choices: DraftSourceChoice[] }) => void;
/** When the Content Agent last wrote from them (a run's suggestions, a brief), or null. */
agentUsedAt: string | null;
+ /** A source to show: scrolled to and marked for a moment ("Based on", CE-033); n tells asks apart. */
+ highlight?: { kind: DraftSourceKind; ref: string; n: number } | null;
+ /** The source asked for was shown, or isn't listed now. */
+ onHighlighted?: () => void;
}) {
const t = useTranslations('contentEditor.editor.sources');
const format = useFormatter();
@@ -74,6 +89,28 @@ export function SourcesTab({
[read, title, sourceUrl],
);
+ // A source asked for from a suggestion: scrolled to and marked for a
+ // moment, once its row is listed (the sources may still be read).
+ const list = useRef<HTMLDivElement>(null);
+ const shown = useRef(0);
+ useEffect(() => {
+ if (!highlight || highlight.n === shown.current || !list.current) return;
+ const key = `${highlight.kind}:${highlight.ref}`;
+ const row = [...list.current.querySelectorAll<HTMLElement>('[data-source]')].find(
+ (node) => node.dataset.source === key,
+ );
+ shown.current = highlight.n;
+ // Asked once: shown now, or not listed (left out of the related queries,
+ // a prompt deleted), never later when a row turns up.
+ onHighlighted?.();
+ if (!row) return;
+ row.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ const mark = ['ring-2', 'ring-sky-300', 'dark:ring-sky-700'];
+ row.classList.add(...mark);
+ // Not cleared with the effect: a later render mustn't leave the mark on.
+ setTimeout(() => row.classList.remove(...mark), 1200);
+ }, [highlight, groups, onHighlighted]);
+
if (!read) {
return (
<div className="flex justify-center py-8" aria-busy="true">
@@ -121,7 +158,7 @@ export function SourcesTab({
};
return (
- <div className="space-y-4 text-sm">
+ <div ref={list} className="space-y-4 text-sm">
<div className="space-y-1 rounded-lg bg-muted/50 px-3 py-2">
<p className="font-medium">{t('summary', { count: total })}</p>
<p className="text-xs text-muted-foreground">
@@ -209,7 +246,10 @@ function SourceRow({
}) {
const t = useTranslations('contentEditor.editor.sources');
return (
- <li className={cn('flex items-start gap-2.5 px-3 py-2', !row.included && 'opacity-60')}>
+ <li
+ data-source={`${row.kind}:${row.ref}`}
+ className={cn('flex items-start gap-2.5 px-3 py-2', !row.included && 'opacity-60')}
+ >
<Checkbox
className="mt-0.5"
checked={row.included}
@@ -245,6 +285,17 @@ function SourceRow({
function SourceDetail({ row }: { row: DraftSourceRow }) {
const t = useTranslations('contentEditor.editor.sources.detail');
+ return <>{sourceDetail(row, t)}</>;
+}
+
+/**
+ * What a source's row says of it ("825 answers · you're named in 28"): the
+ * Sources tab's detail line, and a "Based on" chip's hover (CE-033).
+ */
+export function sourceDetail(
+ row: DraftSourceRow,
+ t: ReturnType<typeof useTranslations<'contentEditor.editor.sources.detail'>>,
+): string {
const parts: string[] = [];
switch (row.kind) {
case 'prompt':
@@ -268,7 +319,7 @@ function SourceDetail({ row }: { row: DraftSourceRow }) {
break;
}
if (row.added) parts.push(t('added'));
- return <>{parts.filter(Boolean).join(' · ')}</>;
+ return parts.filter(Boolean).join(' · ');
}
function UsedInLabel({ used }: { used: UsedIn | null }) {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
index 69c7f94a2..e9aaa3dff 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
@@ -9,7 +9,14 @@ import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/p
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { cleanHtml } from '@/lib/content/clean-html';
import { passageKey } from '@/lib/content/cited-passages';
-import { growsPastLimit, type DraftSuggestion } from '@/lib/content/suggestions';
+import { normalizeDomain } from '@/lib/citations/classify';
+import type { DraftSourceKind } from '@/lib/content/sources';
+import {
+ growsPastLimit,
+ type DraftSuggestion,
+ type SourceMark,
+ type SuggestionSource,
+} from '@/lib/content/suggestions';
import { blockKey, citedLocks, citedPassagesKey, type CitedLocks } from './_cited-passages';
/**
@@ -19,6 +26,9 @@ import { blockKey, citedLocks, citedPassagesKey, type CitedLocks } from './_cite
* Undo; a rejected one a dashed card and Restore. A suggestion finds its
* passage by the text the agent read, so one the page changed since can only
* be rejected, and one on a locked passage (AI quotes it) is never applied.
+ * Under its words, "Based on" names the person's data it was written from,
+ * and a small number marks the words each source supports (v1.1 CE-033); a
+ * click on either opens that source in the Sources tab.
*/
export type SuggestionDecision = 'accept' | 'reject' | 'undo' | 'restore';
@@ -37,6 +47,14 @@ export interface SuggestionLabels {
heading: string;
/** "Links": before the addresses a suggestion links to. */
links: string;
+ /** "Based on": before the sources a suggestion was written from. */
+ basedOn: string;
+ /** Each kind of source, as a chip names it: "Fan-out", "Cited page"… */
+ sourceKinds: Record<DraftSourceKind, string>;
+ /** "Source 2: …": a mark's label for a screen reader. */
+ sourceMark: (n: number, label: string) => string;
+ /** What the Sources tab knows of a source, on hover ("Cited 12× in AI answers"), or null. */
+ sourceTip?: (source: SuggestionSource) => string | null;
}
interface SuggestionView {
@@ -338,24 +356,151 @@ function el<K extends keyof HTMLElementTagNameMap>(
/** Linked words on a card: underlined, the address on hover. */
const LINKED = 'underline decoration-dotted underline-offset-2';
-/** A replace's new words, its links underlined. */
-function linkedWords(s: DraftSuggestion): HTMLElement {
+/** What opens a source in the Sources tab, from a chip or a mark. */
+type OpenSource = (source: SuggestionSource) => void;
+
+/** A source as a chip names it: a cited page by its site, the others by their words. */
+function sourceName(source: SuggestionSource): string {
+ return source.kind === 'cited_page'
+ ? normalizeDomain(source.label) || source.label
+ : source.label.trim();
+}
+
+/** A source's number after the words it supports: ¹ ². */
+function markButton(
+ n: number,
+ source: SuggestionSource,
+ labels: SuggestionLabels,
+ open: OpenSource,
+): HTMLElement {
+ const sup = el('sup', 'ml-0.5');
+ const mark = button(
+ 'rounded-sm px-0.5 text-[10px] font-semibold text-sky-700 hover:bg-sky-50 dark:text-sky-300 dark:hover:bg-sky-950/40',
+ String(n),
+ () => open(source),
+ );
+ mark.setAttribute('aria-label', labels.sourceMark(n, sourceName(source)));
+ mark.title = labels.sourceTip?.(source) ?? source.label;
+ sup.append(mark);
+ return sup;
+}
+
+/** A replace's new words, its links underlined and each source's words marked. */
+function linkedWords(s: DraftSuggestion, labels: SuggestionLabels, open: OpenSource): HTMLElement {
const ins = el(
'ins',
'rounded-sm bg-emerald-50 text-emerald-800 no-underline dark:bg-emerald-950/40 dark:text-emerald-300',
);
- let at = 0;
- for (const { start, end, href } of s.afterLinks ?? []) {
- ins.append(document.createTextNode(s.afterText.slice(at, start)));
- const linked = el('span', LINKED, s.afterText.slice(start, end));
- linked.title = href;
- ins.append(linked);
- at = end;
+ const text = s.afterText;
+ const links = s.afterLinks ?? [];
+ const marks = s.sourceMarks ?? [];
+ // Cut where a link starts or ends, and where a mark ends: its number goes there.
+ const cuts = [
+ ...new Set([
+ 0,
+ text.length,
+ ...links.flatMap((l) => [l.start, l.end]),
+ ...marks.map((m) => m.end),
+ ]),
+ ].sort((a, b) => a - b);
+ for (let i = 0; i < cuts.length - 1; i++) {
+ const [from, to] = [cuts[i], cuts[i + 1]];
+ const link = links.find((l) => l.start <= from && to <= l.end);
+ const piece = text.slice(from, to);
+ if (link) {
+ const linked = el('span', LINKED, piece);
+ linked.title = link.href;
+ ins.append(linked);
+ } else {
+ ins.append(document.createTextNode(piece));
+ }
+ for (const mark of marks.filter((m) => m.end === to)) {
+ const source = s.sources?.[mark.source];
+ if (source) ins.append(markButton(mark.source + 1, source, labels, open));
+ }
}
- ins.append(document.createTextNode(s.afterText.slice(at)));
return ins;
}
+/**
+ * An insert's numbers after the words each source supports. Its marks are
+ * offsets into its HTML read as text, as the server read it (a fragment's
+ * text nodes, joined): the words are taken from there and found again in the
+ * card as drawn — where they were, or else the first after the last mark
+ * from as far back as the card's cleaning took out.
+ */
+function markInsert(
+ added: HTMLElement,
+ marks: SourceMark[],
+ s: DraftSuggestion,
+ labels: SuggestionLabels,
+ open: OpenSource,
+) {
+ // Read as a fragment, as the server's parser does.
+ const fragment = document.createElement('template');
+ fragment.innerHTML = s.afterText;
+ const raw = fragment.content.textContent ?? '';
+ const walker = document.createTreeWalker(added, NodeFilter.SHOW_TEXT);
+ const nodes: { node: Text; start: number }[] = [];
+ let drawn = '';
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ nodes.push({ node: node as Text, start: drawn.length });
+ drawn += (node as Text).data;
+ }
+ const places: { at: number; mark: SourceMark }[] = [];
+ let from = 0;
+ // Cleaning only takes characters out: a mark is never further on than it was.
+ const takenOut = Math.max(0, raw.length - drawn.length);
+ for (const mark of marks) {
+ const words = raw.slice(mark.start, mark.end);
+ if (!words) continue;
+ const at =
+ mark.start >= from && drawn.startsWith(words, mark.start)
+ ? mark.start
+ : drawn.indexOf(words, Math.max(from, mark.start - takenOut));
+ if (at === -1) continue;
+ places.push({ at: at + words.length, mark });
+ from = at + words.length;
+ }
+ // From the last place back, so the nodes' offsets still hold.
+ for (const { at, mark } of places.reverse()) {
+ const source = s.sources?.[mark.source];
+ const holder = nodes.findLast(
+ ({ node, start }) => start < at && at <= start + node.data.length,
+ );
+ if (!source || !holder) continue;
+ const sup = markButton(mark.source + 1, source, labels, open);
+ const offset = at - holder.start;
+ if (offset === holder.node.data.length) holder.node.after(sup);
+ else holder.node.splitText(offset).before(sup);
+ }
+}
+
+/** "Based on" and a chip per source, each opening it in the Sources tab. */
+function basedOn(
+ sources: SuggestionSource[],
+ labels: SuggestionLabels,
+ open: OpenSource,
+): HTMLElement {
+ const line = el('div', 'mt-1.5 flex flex-wrap items-center gap-1 text-xs');
+ line.append(el('span', 'mr-0.5 text-muted-foreground', labels.basedOn));
+ sources.forEach((source, i) => {
+ const chip = button(
+ 'inline-flex max-w-full min-w-0 items-center gap-1 rounded-md border bg-muted/50 px-1.5 py-0.5 text-[11px] text-foreground hover:bg-muted',
+ '',
+ () => open(source),
+ );
+ chip.append(
+ el('span', 'shrink-0 font-semibold text-sky-700 dark:text-sky-300', String(i + 1)),
+ el('span', 'shrink-0 text-muted-foreground', `${labels.sourceKinds[source.kind]} ·`),
+ el('span', 'min-w-0 truncate', sourceName(source)),
+ );
+ chip.title = labels.sourceTip?.(source) ?? source.label;
+ line.append(chip);
+ });
+ return line;
+}
+
function button(
className: string,
text: string,
@@ -396,6 +541,7 @@ function card(
labels: SuggestionLabels,
blocked: 'stale' | 'locked' | 'heading' | null,
decide: (id: string, decision: SuggestionDecision) => void,
+ open: OpenSource,
): HTMLElement {
if (s.status === 'rejected') {
const box = el('div', 'not-prose my-3 rounded-xl border border-dashed px-3 py-1.5');
@@ -438,7 +584,7 @@ function card(
s.beforeText,
),
document.createTextNode(' '),
- linkedWords(s),
+ linkedWords(s, labels, open),
);
} else {
const added = el(
@@ -452,9 +598,11 @@ function card(
span.title = a.getAttribute('href') ?? '';
a.replaceWith(span);
}
+ if (s.sourceMarks?.length) markInsert(added, s.sourceMarks, s, labels, open);
change.append(added);
}
box.append(change);
+ if (s.sources?.length) box.append(basedOn(s.sources, labels, open));
const hrefs = [
...new Set(
s.kind === 'replace'
@@ -480,16 +628,19 @@ function card(
export const AgentSuggestions = Extension.create<{
onDecide: (id: string, decision: SuggestionDecision) => void;
+ /** Opens a source in the Sources tab, from a "Based on" chip or a mark. */
+ onSource: OpenSource;
}>({
name: 'agentSuggestions',
addOptions() {
- return { onDecide: () => {} };
+ return { onDecide: () => {}, onSource: () => {} };
},
addProseMirrorPlugins() {
const decide = (id: string, decision: SuggestionDecision) =>
this.options.onDecide(id, decision);
+ const open: OpenSource = (source) => this.options.onSource(source);
/** The cards and marks for the suggestions where the page has them now. */
const placeMarks = (
state: EditorState,
@@ -506,8 +657,9 @@ export const AgentSuggestions = Extension.create<{
const blocked =
s.status === 'open' ? blockedReason(state, s, suggestions, state.doc, locks) : null;
const widget = (pos: number) =>
- Decoration.widget(pos, () => card(s, labels, blocked, decide), {
- key: `${s.id}:${s.status}:${blocked ?? ''}:${s.reason}`,
+ Decoration.widget(pos, () => card(s, labels, blocked, decide, open), {
+ // Drawn again once the sources are read, for their hover details.
+ key: `${s.id}:${s.status}:${blocked ?? ''}:${s.reason}:${labels.sourceTip ? 1 : 0}`,
side: -1,
ignoreSelection: true,
stopEvent: () => true,
@@ -548,8 +700,8 @@ export const AgentSuggestions = Extension.create<{
for (const s of unplaced) {
const blocked = s.status === 'open' ? 'stale' : null;
marks.push(
- Decoration.widget(0, () => card(s, labels, blocked, decide), {
- key: `${s.id}:${s.status}:unplaced`,
+ Decoration.widget(0, () => card(s, labels, blocked, decide, open), {
+ key: `${s.id}:${s.status}:unplaced:${labels.sourceTip ? 1 : 0}`,
side: -1,
ignoreSelection: true,
stopEvent: () => true,
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index d98a6f9d5..0187ce882 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
@@ -2129,6 +2129,174 @@ describe('the side panel', () => {
);
});
+ it('sends the sources the Sources tab keeps, numbered by the server (CE-033)', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([]);
+ fixDraftRules.mockResolvedValue({ count: 0 });
+ await openRules();
+ await act(async () => panelButton('Run Agent').click());
+ await act(async () => {});
+ expect(fixDraftRules.mock.calls[0][2].sources).toMatchObject({
+ promptIds: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'] }],
+ pages: [],
+ queries: [],
+ });
+ });
+
+ it('shows what a suggestion was written from, and opens it in Sources', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ ...agentSuggestion,
+ afterText: 'look at pipeline forecasting',
+ sources: [{ kind: 'fanout', ref: 'pipeline forecasting', label: 'pipeline forecasting' }],
+ sourceMarks: [{ start: 8, end: 28, source: 0 }],
+ },
+ ]);
+ await openRules();
+
+ const card = container.querySelector<HTMLElement>('[data-suggestion="n1"]')!;
+ // Its words, the source's number after the ones it supports, then "Based on".
+ expect(card.querySelector('ins')!.textContent).toBe('look at pipeline forecasting1');
+ const mark = card.querySelector<HTMLButtonElement>('ins sup button')!;
+ expect(mark.getAttribute('aria-label')).toBe('Source 1: pipeline forecasting');
+ expect(card.textContent).toContain('Based on1Fan-out ·pipeline forecasting');
+ const chip = [...card.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
+ b.textContent?.includes('Fan-out'),
+ )!;
+ // The Sources tab's details, on hover.
+ expect(chip.title).toBe('pipeline forecasting · Microsoft Copilot · searched 2×');
+ // The card says how many of the person's sources it was built from.
+ expect(
+ container.querySelector('[role="region"][aria-label="Agent suggestions"]')!.textContent,
+ ).toContain('built from 1 of your sources · See sources');
+
+ const scrolled = vi.fn();
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = scrolled;
+ try {
+ await act(async () => chip.click());
+ expect(selectedTab()).toBe('Sources');
+ const row = panel()!.querySelector<HTMLElement>(
+ '[data-source="fanout:pipeline forecasting"]',
+ )!;
+ // Scrolled to, and marked for a moment.
+ expect(scrolled).toHaveBeenCalled();
+ expect(row.className).toContain('ring-2');
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ }
+ });
+
+ it('marks an insert’s words by its text, found again in the card as drawn', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ ...agentSuggestion,
+ kind: 'insert' as const,
+ beforeText: '',
+ afterText: '<h3>FAQ</h3>\n<p>Use pipeline forecasting weekly.</p>',
+ // Offsets into "FAQ\nUse pipeline forecasting weekly." (the server's text).
+ sources: [{ kind: 'fanout', ref: 'pipeline forecasting', label: 'pipeline forecasting' }],
+ sourceMarks: [{ start: 8, end: 28, source: 0 }],
+ },
+ ]);
+ await openRules();
+ const card = container.querySelector<HTMLElement>('[data-suggestion="n1"]')!;
+ expect(card.querySelector('p')!.textContent).toBe('Use pipeline forecasting1 weekly.');
+ });
+
+ it('scrolls to a source in a Sources tab opened before, now hidden behind Rules', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ ...agentSuggestion,
+ afterText: 'look at pipeline forecasting',
+ sources: [{ kind: 'fanout', ref: 'pipeline forecasting', label: 'pipeline forecasting' }],
+ // Its mark ends inside the link on its words: both stay.
+ afterLinks: [{ start: 8, end: 28, href: 'https://acme.example/forecasting' }],
+ sourceMarks: [{ start: 8, end: 16, source: 0 }],
+ },
+ ]);
+ await openRules();
+ const ins = container.querySelector<HTMLElement>('[data-suggestion="n1"] ins')!;
+ expect(ins.textContent).toBe('look at pipeline1 forecasting');
+ expect(
+ [...ins.querySelectorAll<HTMLElement>('span[title]')].map((span) => span.textContent),
+ ).toEqual(['pipeline', ' forecasting']);
+
+ await pickTab('Sources');
+ await pickTab('Rules');
+ const scrolled = vi.fn();
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = scrolled;
+ try {
+ const mark = container.querySelector<HTMLButtonElement>(
+ '[data-suggestion="n1"] sup button',
+ )!;
+ await act(async () => mark.click());
+ expect(selectedTab()).toBe('Sources');
+ expect(scrolled).toHaveBeenCalledTimes(1);
+ // Asked once: switching tabs again doesn't scroll again.
+ await pickTab('Rules');
+ await pickTab('Sources');
+ expect(scrolled).toHaveBeenCalledTimes(1);
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ }
+ });
+
+ it('puts an insert’s number after the words it marks, not the same words before them', async () => {
+ getContentDraft.mockResolvedValue(traced);
+ getDraftSuggestions.mockResolvedValue([
+ {
+ ...agentSuggestion,
+ kind: 'insert' as const,
+ beforeText: '',
+ afterText: '<p>In 2026 teams plan; by 2026, most do.</p>',
+ sources: [{ kind: 'fanout', ref: 'plans 2026', label: 'plans 2026' }],
+ sourceMarks: [{ start: 23, end: 27, source: 0 }],
+ },
+ ]);
+ await openRules();
+ const card = container.querySelector<HTMLElement>('[data-suggestion="n1"]')!;
+ expect(card.querySelector('p')!.textContent).toBe('In 2026 teams plan; by 20261, most do.');
+ });
+
it('says a full batch is the most one run makes, to run it again (C)', async () => {
getContentDraft.mockResolvedValue(traced);
const full = Array.from({ length: 8 }, (_, i) => ({
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index 4ec3e9903..c787b0456 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -589,6 +589,8 @@ describe('agent suggestions', () => {
status: 'open',
// When the run left it, for "Last used by Content Agent".
createdAt: '2026-10-21T10:00:00Z',
+ sources: null,
+ sourceMarks: null,
});
expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);
// The latest batch is found first; only its rows are read whole.
@@ -601,6 +603,31 @@ describe('agent suggestions', () => {
expect(calls).toHaveLength(1);
});
+ it('reads what a suggestion was written from, and only marks it can show (00248)', async () => {
+ list = [
+ row({
+ after_text: 'shown per team in 2026',
+ sources: [
+ { kind: 'fanout', ref: 'forecast per team', label: 'Forecast per team' },
+ { kind: 'made-up', ref: 'x', label: 'x' },
+ { kind: 'gsc_query', ref: '', label: 'empty' },
+ ],
+ source_marks: [
+ { start: 0, end: 5, source: 0 },
+ { start: 3, end: 8, source: 0 },
+ { start: 18, end: 22, source: 4 },
+ { start: 18, end: 99, source: 0 },
+ ],
+ }),
+ ];
+ const [read] = await getDraftSuggestions(DRAFT);
+ expect(read.sources).toEqual([
+ { kind: 'fanout', ref: 'forecast per team', label: 'Forecast per team' },
+ ]);
+ // Overlapping, out of range or to a source it doesn't have: left out.
+ expect(read.sourceMarks).toEqual([{ start: 0, end: 5, source: 0 }]);
+ });
+
it('reads a whole page rewritten, with the page the agent read (00247)', async () => {
list = [
row({
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 28afaadd0..868d369ca 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -65,6 +65,7 @@ import {
MAX_DECIDE,
SUGGESTION_STATUSES,
suggestionLinks,
+ suggestionSources,
type DraftSuggestion,
type SuggestionStatus,
} from '@/lib/content/suggestions';
@@ -1390,7 +1391,7 @@ export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]
const { data, error } = await supabase
.from('content_draft_suggestions')
.select(
- 'id, batch_id, action_id, kind, block_text, before_text, before_html, after_text, after_links, reason, rule_keys, position, status, created_at, actions(action_no)',
+ 'id, batch_id, action_id, kind, block_text, before_text, before_html, after_text, after_links, reason, rule_keys, position, status, created_at, sources, source_marks, actions(action_no)',
)
.eq('draft_id', id)
.eq('batch_id', latest.batch_id)
@@ -1404,6 +1405,13 @@ export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]
const action = (Array.isArray(row.actions) ? row.actions[0] : row.actions) as {
action_no: number;
} | null;
+ // What it was written from (00248); an insert's marks are by its text,
+ // within its HTML's length. A page names its sources, with no marks.
+ const { sources, marks } = suggestionSources(
+ row.sources,
+ row.kind === 'page' ? null : row.source_marks,
+ row.after_text,
+ );
return {
id: row.id,
batchId: row.batch_id,
@@ -1420,6 +1428,8 @@ export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]
ruleKeys: row.rule_keys ?? [],
status: row.status as SuggestionStatus,
createdAt: row.created_at,
+ sources,
+ sourceMarks: marks,
};
});
}
@@ -1727,6 +1737,8 @@ export interface AgentFixRequest {
textRules: string[];
/** The locked passages, by passageKey. */
locked: string[];
+ /** The sources the Sources tab keeps, which the agent writes from (v1.1 CE-033). */
+ sources?: RebuildSources;
}
/**
@@ -1764,6 +1776,8 @@ export async function fixDraftRules(
})),
textRules: request.textRules.slice(0, 50).map((text) => text.slice(0, 300)),
locked: request.locked.slice(0, 500).map((key) => key.slice(0, 5000)),
+ // Already within the server's limits (rebuildSources).
+ ...(request.sources ? { sources: request.sources } : {}),
}),
});
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
diff --git a/web/src/lib/content/suggestions.test.ts b/web/src/lib/content/suggestions.test.ts
index 1b253181b..06f0904ad 100644
--- a/web/src/lib/content/suggestions.test.ts
+++ b/web/src/lib/content/suggestions.test.ts
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { asksMoreThanOne, growsPastLimit, headingLimit, suggestionLinks } from './suggestions';
+import {
+ asksMoreThanOne,
+ batchSources,
+ growsPastLimit,
+ headingLimit,
+ suggestionLinks,
+ suggestionSources,
+ type DraftSuggestion,
+} from './suggestions';
/**
* How long an agent's change may make a heading: an H1 up to 70 characters,
@@ -61,3 +69,46 @@ describe('suggestionLinks', () => {
expect(suggestionLinks([{ start: 0, end: 1 }], 'x')).toBeNull();
});
});
+
+describe('a suggestion’s sources (00248, CE-033)', () => {
+ const fanout = { kind: 'fanout' as const, ref: 'best tracker', label: 'Best tracker' };
+ const page = {
+ kind: 'cited_page' as const,
+ ref: 'https://a.example/x',
+ label: 'https://a.example/x',
+ };
+
+ it('keeps the sources it can show, and marks within its words, renumbered', () => {
+ const odd = { kind: 'other', ref: 'x', label: 'x' };
+ // The unknown kind before them is left out: marks to 1 and 2 now point to 0 and 1.
+ expect(
+ suggestionSources(
+ [odd, fanout, { ...page, ref: '' }, page],
+ [
+ { start: 0, end: 4, source: 1 },
+ { start: 2, end: 6, source: 1 },
+ { start: 5, end: 12, source: 3 },
+ { start: 6, end: 99, source: 1 },
+ { start: 13, end: 14, source: 2 },
+ ],
+ 'Best tracker here',
+ ),
+ ).toEqual({
+ sources: [fanout, page],
+ marks: [
+ { start: 0, end: 4, source: 0 },
+ { start: 5, end: 12, source: 1 },
+ ],
+ });
+ expect(suggestionSources(null, [{ start: 0, end: 1, source: 0 }], 'x')).toEqual({
+ sources: null,
+ marks: null,
+ });
+ expect(suggestionSources([], null, 'x')).toEqual({ sources: null, marks: null });
+ });
+
+ it('counts a batch’s sources once: "built from N of your sources"', () => {
+ const s = (sources: DraftSuggestion['sources']) => ({ sources }) as DraftSuggestion;
+ expect(batchSources([s([fanout, page]), s([fanout]), s(null)])).toEqual([fanout, page]);
+ });
+});
diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.ts
index 5baccc092..23e6203cc 100644
--- a/web/src/lib/content/suggestions.ts
+++ b/web/src/lib/content/suggestions.ts
@@ -11,6 +11,7 @@
*/
import { safeLinkHref } from './editor';
+import { DRAFT_SOURCE_KINDS, type DraftSourceKind } from './sources';
export const SUGGESTION_STATUSES = ['open', 'accepted', 'rejected'] as const;
export type SuggestionStatus = (typeof SUGGESTION_STATUSES)[number];
@@ -39,6 +40,28 @@ export interface DraftSuggestion {
status: SuggestionStatus;
/** When the agent left it: the run's time, for "Last used by Content Agent". */
createdAt?: string;
+ /** The person's data it was written from (00248, v1.1 CE-033), or null. */
+ sources?: SuggestionSource[] | null;
+ /** The words each of its sources supports, the ¹ ² marks, or null. */
+ sourceMarks?: SourceMark[] | null;
+}
+
+/** A source a suggestion was written from, keyed as the Sources tab keys its row. */
+export interface SuggestionSource {
+ kind: DraftSourceKind;
+ ref: string;
+ label: string;
+}
+
+/**
+ * Where a source supports a suggestion's words: from start to end, offsets
+ * into a replace's afterText or an insert's HTML read as text; source is an
+ * index into its sources.
+ */
+export interface SourceMark {
+ start: number;
+ end: number;
+ source: number;
}
/**
@@ -103,6 +126,58 @@ export function suggestionLinks(raw: unknown, afterText: string): SuggestionLink
return links.length ? links : null;
}
+/**
+ * A suggestion's sources and marks as stored (00248), the ones the editor can
+ * show: sources of a kind it knows, with a ref and a name; marks in order,
+ * within `text`, each to one of those sources — renumbered when a source
+ * before it is left out. Null for either with none.
+ */
+export function suggestionSources(
+ rawSources: unknown,
+ rawMarks: unknown,
+ text: string,
+): { sources: SuggestionSource[] | null; marks: SourceMark[] | null } {
+ if (!Array.isArray(rawSources)) return { sources: null, marks: null };
+ const kinds: readonly string[] = DRAFT_SOURCE_KINDS;
+ const sources: SuggestionSource[] = [];
+ // Where each stored source is now, or -1 when it is left out.
+ const at = (rawSources as Partial<SuggestionSource>[]).map((item) => {
+ if (
+ !kinds.includes(item?.kind as string) ||
+ typeof item?.ref !== 'string' ||
+ typeof item?.label !== 'string' ||
+ !item.ref ||
+ !item.label
+ ) {
+ return -1;
+ }
+ sources.push({ kind: item.kind as DraftSourceKind, ref: item.ref, label: item.label });
+ return sources.length - 1;
+ });
+ const marks: SourceMark[] = [];
+ for (const item of Array.isArray(rawMarks) ? (rawMarks as Partial<SourceMark>[]) : []) {
+ const { start, end, source } = item ?? {};
+ if (!Number.isInteger(start) || !Number.isInteger(end) || !Number.isInteger(source)) continue;
+ if (start! < (marks.at(-1)?.end ?? 0) || end! <= start! || end! > text.length) continue;
+ const kept = at[source!] ?? -1;
+ if (kept === -1) continue;
+ marks.push({ start: start!, end: end!, source: kept });
+ }
+ return {
+ sources: sources.length ? sources : null,
+ marks: sources.length && marks.length ? marks : null,
+ };
+}
+
+/** The sources a batch was written from, each once: "built from N of your sources". */
+export function batchSources(suggestions: DraftSuggestion[]): SuggestionSource[] {
+ const seen = new Map<string, SuggestionSource>();
+ for (const s of suggestions) {
+ for (const source of s.sources ?? []) seen.set(`${source.kind}:${source.ref}`, source);
+ }
+ return [...seen.values()];
+}
+
/** The most suggestions decided at once (00217). */
export const MAX_DECIDE = 200;
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 480ac32cc..9a3b50c80 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1140,6 +1140,8 @@ export type Database = {
position: number
reason: string
rule_keys: string[]
+ source_marks: Json | null
+ sources: Json | null
status: string
}
Insert: {
@@ -1160,6 +1162,8 @@ export type Database = {
position?: number
reason: string
rule_keys?: string[]
+ source_marks?: Json | null
+ sources?: Json | null
status?: string
}
Update: {
@@ -1180,6 +1184,8 @@ export type Database = {
position?: number
reason?: string
rule_keys?: string[]
+ source_marks?: Json | null
+ sources?: Json | null
status?: string
}
Relationships: [