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 the data the Content Agent writes from (CE-032, CE-034) (#1397)

Cihan8db6bac1d9e9
diff --git a/web/messages/en.json b/web/messages/en.json
index c2f73402e..f982572f7 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3606,6 +3606,15 @@
"run": {
"about": "What Run Agent does"
},
+ "data": {
+ "uses": "Uses your data: {parts} · <edit>Edit sources</edit>",
+ "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.",
+ "close": "Close"
+ }
+ },
"agentCard": {
"waiting": "{count, plural, one {Content Agent has # suggestion for you} other {Content Agent has # suggestions for you}}",
"gain": "Rules {met, number} → {after, number} of {total, number}",
@@ -3799,6 +3808,7 @@
"hide": "Hide side panel",
"openTab": "Open {tab} in the side panel",
"openRules": "{count, plural, one {# rule open} other {# rules open}}",
+ "sourcesInUse": "{count, plural, one {# source in use} other {# sources in use}}",
"tabs": {
"instructions": "Instructions",
"sources": "Sources",
@@ -3880,7 +3890,12 @@
"sources": {
"loadError": "Couldn't load the sources.",
"retry": "Retry",
- "summary": "{count, plural, one {Built from # source} other {Built from # sources}}",
+ "summary": "{count, plural, one {# source in use} other {# sources in use}}",
+ "lastUsed": {
+ "when": "Last used by Content Agent · {when}",
+ "justNow": "Last used by Content Agent · just now",
+ "never": "Not used by Content Agent yet"
+ },
"summaryParts": "{prompts, plural, one {# prompt} other {# prompts}} · {fanouts, plural, one {# fan-out} other {# fan-outs}} · {pages, plural, one {# cited page} other {# cited pages}} · {queries, plural, one {# Search Console query} other {# Search Console queries}}",
"hint": "Each source shows where the draft uses it. Uncheck one to leave it out, then rebuild the brief.",
"empty": "No sources yet. Add a prompt, a page or a Search Console query.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
index c0a8914f1..67525e0f8 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
@@ -57,6 +57,7 @@ export function BriefTab({
onRetry,
onSaved,
rewrite,
+ dataLine,
}: {
draftId: string;
state: BriefState;
@@ -71,6 +72,8 @@ export function BriefTab({
onSaved: (brief: DraftBrief) => void;
/** Absent once the page is ready or published. */
rewrite?: AgentRewrite;
+ /** "Uses your data", under Run Agent's card (v1.1 CE-032). */
+ dataLine?: React.ReactNode;
}) {
const t = useTranslations('contentEditor.editor.brief');
const tTypes = useTranslations('contentEditor.pageTypes');
@@ -136,9 +139,10 @@ export function BriefTab({
</Button>
}
info={t('info')}
+ data={dataLine}
>
<p className="text-[11px] text-muted-foreground">{t('usage')}</p>
- {/* Right under the button that asked, not past the outline. */}
+ {/* Under the card that asked, not past the outline. */}
{confirming && (
<div role="alert" className="space-y-2 rounded-md border px-3 py-2 text-xs">
<p>{t('rebuildEdited')}</p>
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
new file mode 100644
index 000000000..c5a079752
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.test.tsx
@@ -0,0 +1,120 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import type { User } from '@supabase/supabase-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import { useAuthStore } from '@/stores/use-auth-store';
+import { DATA_NOTE_KEY, DataNote, UsesYourData } from './_data-note';
+
+const updateUser = vi.fn();
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({ auth: { updateUser: (...args: unknown[]) => updateUser(...args) } }),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const person = (metadata: Record<string, unknown> = {}) =>
+ ({ id: 'u1', email: '[email protected]', user_metadata: metadata }) as unknown as User;
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(node: React.ReactNode) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ updateUser.mockReset();
+ useAuthStore.setState({ user: null });
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('Uses your data', () => {
+ it('counts the sources kept, and Edit sources opens them', async () => {
+ const onEdit = vi.fn();
+ await render(
+ <UsesYourData
+ counts={{ prompt: 1, fanout: 21, cited_page: 20, gsc_query: 10 }}
+ onEdit={onEdit}
+ />,
+ );
+ expect(container.textContent).toBe(
+ 'Uses your data: 1 prompt · 21 fan-outs · 20 cited pages · 10 Search Console queries · Edit sources',
+ );
+ await act(async () => container.querySelector('button')!.click());
+ expect(onEdit).toHaveBeenCalled();
+ });
+
+ it('says when none are kept', async () => {
+ await render(
+ <UsesYourData
+ counts={{ prompt: 0, fanout: 0, cited_page: 0, gsc_query: 0 }}
+ onEdit={vi.fn()}
+ />,
+ );
+ expect(container.textContent).toBe('No sources kept yet · Edit sources');
+ });
+});
+
+describe('the data note', () => {
+ it('waits until the person is known, and never shows once they closed it', async () => {
+ await render(<DataNote />);
+ expect(container.textContent).toBe('');
+
+ await act(async () => useAuthStore.setState({ user: person({ [DATA_NOTE_KEY]: true }) }));
+ expect(container.textContent).toBe('');
+ });
+
+ it('shows on a first visit, and closing it is kept in the person’s own metadata', async () => {
+ const closed = person({ full_name: 'Demo', [DATA_NOTE_KEY]: true });
+ updateUser.mockResolvedValue({ data: { user: closed }, error: null });
+ 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.',
+ );
+
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Close"]')!.click(),
+ );
+ expect(container.textContent).toBe('');
+ expect(updateUser).toHaveBeenCalledWith({ data: { [DATA_NOTE_KEY]: true } });
+ expect(useAuthStore.getState().user).toBe(closed);
+ });
+
+ it('goes away even when keeping it closed fails, and shows again next time', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ updateUser.mockResolvedValue({ data: { user: null }, error: new Error('offline') });
+ useAuthStore.setState({ user: person() });
+ await render(<DataNote />);
+ await act(async () =>
+ container.querySelector<HTMLButtonElement>('[aria-label="Close"]')!.click(),
+ );
+ expect(container.textContent).toBe('');
+ expect(error).toHaveBeenCalled();
+ error.mockRestore();
+ // Nothing was kept: the next visit shows it again.
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render(<DataNote />);
+ expect(container.textContent).toContain('Content Agent writes from your data');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.tsx
new file mode 100644
index 000000000..c443fc287
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_data-note.tsx
@@ -0,0 +1,104 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Database, X } from 'lucide-react';
+import type { DraftSourceKind } from '@/lib/content/sources';
+import { createClient } from '@/lib/supabase/client';
+import { useAuthStore } from '@/stores/use-auth-store';
+
+/**
+ * Where a person's dismissal of the data note is kept: in their own user
+ * metadata, so it holds on every device and never shows them again.
+ */
+export const DATA_NOTE_KEY = 'content_agent_data_note_dismissed';
+
+/**
+ * "Uses your data" (Content Editor v1.1 §3b, CE-032): under each Run Agent
+ * card, the sources the agent writes from, counted as the Sources tab keeps
+ * them, so turning one off there lowers the count at once. Edit sources
+ * opens that tab.
+ */
+export function UsesYourData({
+ counts,
+ onEdit,
+}: {
+ counts: Record<DraftSourceKind, number>;
+ onEdit: () => void;
+}) {
+ const t = useTranslations('contentEditor.editor.data');
+ const tSources = useTranslations('contentEditor.editor.sources');
+ const total = Object.values(counts).reduce((a, b) => a + b, 0);
+ const edit = (chunks: React.ReactNode) => (
+ <button
+ type="button"
+ onClick={onEdit}
+ className="font-medium text-foreground underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ >
+ {chunks}
+ </button>
+ );
+ return (
+ <p className="text-xs text-muted-foreground">
+ {total > 0
+ ? t.rich('uses', {
+ parts: tSources('summaryParts', {
+ prompts: counts.prompt,
+ fanouts: counts.fanout,
+ pages: counts.cited_page,
+ queries: counts.gsc_query,
+ }),
+ edit,
+ })
+ : t.rich('none', { edit })}
+ </p>
+ );
+}
+
+/**
+ * The first visit's note at the top of Instructions (CE-032): the Content
+ * Agent writes from the person's own data. Shown until they close it.
+ */
+export function DataNote() {
+ const t = useTranslations('contentEditor.editor.data.note');
+ const user = useAuthStore((state) => state.user);
+ const setUser = useAuthStore((state) => state.setUser);
+ const [closed, setClosed] = useState(false);
+ // Until the person is known, nothing: never a note that flashes and goes.
+ if (!user || closed || user.user_metadata?.[DATA_NOTE_KEY]) return null;
+
+ const close = async () => {
+ setClosed(true);
+ try {
+ const { data, error } = await createClient().auth.updateUser({
+ data: { [DATA_NOTE_KEY]: true },
+ });
+ if (error) throw error;
+ if (data.user) setUser(data.user);
+ } catch (err) {
+ // It shows again on the next visit; nothing else is lost.
+ console.error('Failed to keep the data note closed:', err);
+ }
+ };
+
+ return (
+ <section
+ aria-label={t('title')}
+ className="relative flex gap-2.5 rounded-xl border bg-muted/50 px-3 py-2.5 text-xs"
+ >
+ <Database aria-hidden className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1 space-y-0.5 pr-5">
+ <p className="text-[13px] font-semibold">{t('title')}</p>
+ <p className="text-muted-foreground">{t('body')}</p>
+ </div>
+ <button
+ type="button"
+ aria-label={t('close')}
+ onClick={() => void close()}
+ className="absolute top-2 right-2 rounded-md p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </section>
+ );
+}
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 6ee73e285..0c31bc575 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
@@ -1347,6 +1347,8 @@ export function DraftEditor({
agentFix={agentFix}
pageRewrite={pageRewrite}
agentRewrite={agentRewrite}
+ // One batch, one run: its first suggestion's time is the run's.
+ lastSuggestionAt={suggestions[0]?.createdAt ?? null}
/>
) : (
<EditorPanelRail onOpen={openPanelTab} />
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
index 96950916d..5379090f2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
@@ -205,6 +205,7 @@ export function RulesTab({
draftPageType,
agentFix,
pageRewrite,
+ dataLine,
onOpenSources,
}: {
state: DraftRulesState;
@@ -212,6 +213,8 @@ export function RulesTab({
draftPageType: PageType | null;
agentFix?: AgentFix;
pageRewrite?: PageRewrite;
+ /** "Uses your data", under Run Agent's card (v1.1 CE-032). */
+ dataLine?: React.ReactNode;
/**
* Opens the Sources tab, where a draft with no prompts (so no fan-outs)
* gets them; none while the sources are read, or when the draft has prompts.
@@ -306,6 +309,7 @@ export function RulesTab({
info={t.rich(pageRewrite ? 'run.info' : 'run.infoFix', {
b: (chunks) => <b>{chunks}</b>,
})}
+ data={dataLine}
blocked={open.length > 0 ? blocked : null}
>
{advice && (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx
index 95167c33f..55a736556 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_run-card.tsx
@@ -16,6 +16,7 @@ export function RunCard({
detail,
action,
info,
+ data,
blocked,
children,
}: {
@@ -25,9 +26,11 @@ export function RunCard({
action?: React.ReactNode;
/** What the button does, in the ⓘ's tip. */
info: React.ReactNode;
+ /** The data the agent writes from, right under the card (CE-032). */
+ data?: React.ReactNode;
/** Why the agent can't run now, or null. */
blocked?: string | null;
- /** Under the card: the advice line, the data it uses. */
+ /** Last, under the reason: the advice line, the usage, a question the button asked. */
children?: React.ReactNode;
}) {
const t = useTranslations('contentEditor.editor.run');
@@ -59,6 +62,7 @@ export function RunCard({
</TooltipContent>
</Tooltip>
</div>
+ {data}
{/* Always there, so a screen reader hears the reason when it comes. */}
<p
role="status"
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 f54c7c115..121bab48c 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
@@ -1,11 +1,14 @@
'use client';
-import { useEffect, useRef, useState } from 'react';
+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 { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { BriefTab, type AgentRewrite } from './_brief-tab';
+import { DataNote, UsesYourData } from './_data-note';
import { ImpactTab } from './_impact-tab';
import { RulesTab, type AgentFix, type PageRewrite } from './_rules-tab';
import { SourcesTab } from './_sources-tab';
@@ -106,6 +109,7 @@ export function EditorSidePanel({
agentFix,
pageRewrite,
agentRewrite,
+ lastSuggestionAt,
}: {
draft: ContentDraft;
/** The draft's title, page and type as written now: Sources and Brief read them. */
@@ -124,6 +128,8 @@ export function EditorSidePanel({
pageRewrite?: PageRewrite;
/** Rewrite from brief, for Brief; absent once the page is ready or published. */
agentRewrite?: AgentRewrite;
+ /** When the agent's latest suggestions came, or null: the last time it wrote from the sources. */
+ lastSuggestionAt: string | null;
}) {
const t = useTranslations('contentEditor.editor.panel');
const [tab, setTab] = useState<PanelTab>('instructions');
@@ -146,6 +152,36 @@ export function EditorSidePanel({
};
const rulesOpen = Math.max(0, rules.total - rules.met);
+ // The sources the agent writes from, as the Sources tab keeps them (v1.1
+ // CE-032/034): counted under each Run Agent and on the tab, so turning one
+ // off there lowers both at once.
+ const sourceCounts = useMemo(
+ () =>
+ reads.sources?.data
+ ? includedCounts(
+ buildSourceGroups(reads.sources.data, reads.sources.choices, {
+ title,
+ sourceUrl: draft.sourceUrl,
+ }),
+ )
+ : null,
+ [reads.sources, title, draft.sourceUrl],
+ );
+ const sourcesInUse = sourceCounts ? Object.values(sourceCounts).reduce((a, b) => a + b, 0) : null;
+ const dataLine = sourceCounts && (
+ <UsesYourData counts={sourceCounts} onEdit={() => open('sources')} />
+ );
+ // The last time the agent wrote from them: its latest run's suggestions,
+ // the brief it built, or its writing the page (Start, Rewrite from brief),
+ // unless that run failed.
+ const builtAt = reads.brief.status === 'ready' ? (reads.brief.brief?.builtAt ?? null) : null;
+ const wroteAt = draft.agentState === 'failed' ? null : draft.agentSince;
+ const agentUsedAt =
+ [lastSuggestionAt, builtAt, wroteAt]
+ .filter((at): at is string => !!at && Number.isFinite(Date.parse(at)))
+ .sort((a, b) => Date.parse(a) - Date.parse(b))
+ .at(-1) ?? null;
+
const requested = tabRequest?.n;
useEffect(() => {
if (tabRequest) open(tabRequest.tab);
@@ -189,12 +225,26 @@ export function EditorSidePanel({
<span className="sr-only">{t('openRules', { count: rulesOpen })}</span>
</>
)}
+ {/* The sources in use (CE-034), the number in full on hover. */}
+ {value === 'sources' && !!sourcesInUse && (
+ <>
+ <span
+ aria-hidden
+ title={t('sourcesInUse', { count: sourcesInUse })}
+ className="rounded-md bg-muted px-1.5 text-[10.5px] font-medium text-muted-foreground"
+ >
+ {formatNumber(sourcesInUse)}
+ </span>
+ <span className="sr-only">{t('sourcesInUse', { count: sourcesInUse })}</span>
+ </>
+ )}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
<div hidden={tab !== 'instructions'} className="space-y-4">
+ <DataNote />
<div
role="radiogroup"
aria-label={t('segmentsLabel')}
@@ -245,6 +295,7 @@ export function EditorSidePanel({
onRetry={reads.reloadBrief}
onSaved={(saved) => reads.setBrief(saved)}
rewrite={agentRewrite}
+ dataLine={dataLine}
/>
</div>
)}
@@ -253,6 +304,7 @@ export function EditorSidePanel({
<RulesTab
agentFix={agentFix}
pageRewrite={pageRewrite}
+ dataLine={dataLine}
// Only a draft with no prompts gets no fan-outs for want of them.
onOpenSources={
reads.sources && !reads.sources.failed && reads.sources.data.prompts.length === 0
@@ -279,6 +331,7 @@ export function EditorSidePanel({
bodyHtml={bodyHtml}
rebuilding={rebuilding}
onRebuild={(sources) => void rebuild({ sources })}
+ agentUsedAt={agentUsedAt}
/>
</div>
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
index ebb212271..388c84a04 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
@@ -66,15 +66,16 @@ let root: Root;
async function render(
bodyHtml = '<h1>The home espresso guide</h1>',
choices: DraftSourceChoice[] = [],
+ agentUsedAt: string | null = null,
) {
getDraftSources.mockResolvedValue({ data: data(), choices });
await act(async () => {
- root.render(<Tab bodyHtml={bodyHtml} />);
+ root.render(<Tab bodyHtml={bodyHtml} agentUsedAt={agentUsedAt} />);
});
}
/** The tab as the editor gives it its sources: one read, shared (useDraftReads). */
-function Tab({ bodyHtml }: { bodyHtml: string }) {
+function Tab({ bodyHtml, agentUsedAt = null }: { bodyHtml: string; agentUsedAt?: string | null }) {
const reads = useDraftReads('d1');
return (
<NextIntlClientProvider locale="en" messages={messages}>
@@ -89,6 +90,7 @@ function Tab({ bodyHtml }: { bodyHtml: string }) {
bodyHtml={bodyHtml}
rebuilding={false}
onRebuild={onRebuild}
+ agentUsedAt={agentUsedAt}
/>
</NextIntlClientProvider>
);
@@ -124,6 +126,21 @@ afterEach(() => {
});
describe('the Sources tab', () => {
+ it('says when the Content Agent last wrote from them (v1.1 CE-034)', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-23T10:00:00Z'));
+ try {
+ await render(undefined, [], null);
+ expect(container.textContent).toContain('Not used by Content Agent yet');
+ await render(undefined, [], '2026-10-23T09:58:00Z');
+ expect(container.textContent).toContain('Last used by Content Agent · 2 minutes ago');
+ await render(undefined, [], '2026-10-23T09:59:40Z');
+ expect(container.textContent).toContain('Last used by Content Agent · just now');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('names every source with its numbers and where the draft uses it', async () => {
await render(
'<h1>The home espresso guide</h1><h2>Best espresso machines under $500</h2>' +
@@ -131,7 +148,7 @@ describe('the Sources tab', () => {
);
expect(getDraftSources).toHaveBeenCalledWith('d1');
- expect(container.textContent).toContain('Built from 4 sources');
+ expect(container.textContent).toContain('4 sources in use');
expect(container.textContent).toContain(
'1 prompt · 1 fan-out · 1 cited page · 1 Search Console query',
);
@@ -170,7 +187,7 @@ describe('the Sources tab', () => {
included: false,
});
expect(rows()[1].checked).toBe('false');
- expect(container.textContent).toContain('Built from 3 sources');
+ expect(container.textContent).toContain('3 sources in use');
vi.spyOn(console, 'error').mockImplementation(() => {});
setDraftSourceIncluded.mockRejectedValueOnce(new Error('boom'));
@@ -216,7 +233,7 @@ describe('the Sources tab', () => {
it('lists a source left out unchecked', async () => {
await render(undefined, [{ kind: 'prompt', ref: 'p1', included: false, added: false }]);
expect(rows()[0].checked).toBe('false');
- expect(container.textContent).toContain('Built from 3 sources');
+ expect(container.textContent).toContain('3 sources in use');
});
it('adds a page by its address and reads the sources again', async () => {
@@ -260,7 +277,7 @@ describe('the Sources tab', () => {
getDraftSources.mockResolvedValue({ data: data(), choices: [] });
const retry = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Retry')!;
await act(async () => retry.click());
- expect(container.textContent).toContain('Built from 4 sources');
+ expect(container.textContent).toContain('4 sources in use');
});
it('says when there is nothing to list', async () => {
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 6be3a0e64..bd10a8da8 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,7 +1,7 @@
'use client';
import { useDeferredValue, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
-import { useTranslations } from 'next-intl';
+import { useFormatter, useNow, useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { Loader2, Plus, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -43,6 +43,7 @@ export function SourcesTab({
bodyHtml,
rebuilding,
onRebuild,
+ agentUsedAt,
}: {
/** The sources as the editor read them; null while reading. */
read: SourcesRead | null;
@@ -57,8 +58,12 @@ export function SourcesTab({
/** Rebuild with selection: the brief from the sources as checked here. */
rebuilding: boolean;
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;
}) {
const t = useTranslations('contentEditor.editor.sources');
+ const format = useFormatter();
+ const now = useNow({ updateInterval: 60_000 });
const [adding, setAdding] = useState(false);
// Where each source is used follows the page as it is written, a beat behind typing.
@@ -127,6 +132,13 @@ export function SourcesTab({
queries: counts.gsc_query,
})}
</p>
+ <p className="text-xs text-muted-foreground">
+ {agentUsedAt === null
+ ? t('lastUsed.never')
+ : now.getTime() - new Date(agentUsedAt).getTime() < 60_000
+ ? t('lastUsed.justNow')
+ : t('lastUsed.when', { when: format.relativeTime(new Date(agentUsedAt), now) })}
+ </p>
<p className="text-xs text-muted-foreground">{t('hint')}</p>
</div>
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 a4847fcdc..d98a6f9d5 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
@@ -18,6 +18,7 @@ const setContentDraftPageType = vi.fn();
const getContentImpact = vi.fn();
const getContentResults = vi.fn();
const getDraftSources = vi.fn();
+const setDraftSourceIncluded = vi.fn();
const getDraftBrief = vi.fn();
const rebuildDraftBrief = vi.fn();
const saveDraftRules = vi.fn();
@@ -46,6 +47,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({
saveMyRuleSet: (...args: unknown[]) => saveMyRuleSet(...args),
saveDraftRules: (...args: unknown[]) => saveDraftRules(...args),
getDraftSources: (...args: unknown[]) => getDraftSources(...args),
+ setDraftSourceIncluded: (...args: unknown[]) => setDraftSourceIncluded(...args),
getDraftBrief: (...args: unknown[]) => getDraftBrief(...args),
rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),
getContentImpact: (...args: unknown[]) => getContentImpact(...args),
@@ -1684,13 +1686,13 @@ describe('the side panel', () => {
expect(getDraftSources).toHaveBeenCalledTimes(1);
expect(panel()!.textContent).not.toContain('pipeline forecasting');
+ // The tab counts the sources in use, from the editor's one read.
const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(
- (el) => el.textContent === 'Sources',
+ (el) => tabName(el) === 'Sources',
)!;
- await act(async () => {
- tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
- tab.click();
- });
+ expect(tab.querySelector('[aria-hidden]')!.textContent).toBe('1');
+ expect(tab.querySelector('.sr-only')!.textContent).toBe('1 source in use');
+ await pickTab('Sources');
// The tab shows the editor's one read: nothing is read again.
expect(getDraftSources).toHaveBeenCalledTimes(1);
// The draft's H1 carries the fan-out's words.
@@ -1805,6 +1807,92 @@ describe('the side panel', () => {
).toContain('forecast accuracy, pipeline');
});
+ it('says under Run Agent which sources the agent writes from, live as Sources changes them', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [
+ { query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 },
+ { query: 'forecast accuracy tips', platforms: ['chatgpt'], searched: 1 },
+ ],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ setDraftSourceIncluded.mockResolvedValue(undefined);
+ getContentDraft.mockResolvedValue(draft());
+ window.innerWidth = 1440;
+ await renderPage();
+
+ const line = () =>
+ [...panel()!.querySelectorAll('p')].find((p) => p.textContent?.startsWith('Uses your data'));
+ expect(line()!.textContent).toBe(
+ 'Uses your data: 0 prompts · 2 fan-outs · 0 cited pages · 0 Search Console queries · Edit sources',
+ );
+ // Edit sources opens them.
+ await act(async () => button('Edit sources')!.click());
+ expect(selectedTab()).toBe('Sources');
+ // Turning one off lowers the count under Run Agent at once.
+ const box = panel()!.querySelector<HTMLElement>(
+ '[role="checkbox"][aria-label="Use pipeline forecasting"]',
+ )!;
+ await act(async () => box.click());
+ expect(setDraftSourceIncluded).toHaveBeenCalledWith('d1', {
+ kind: 'fanout',
+ ref: 'pipeline forecasting',
+ included: false,
+ });
+ await pickTab('Rules');
+ expect(line()!.textContent).toContain('· 1 fan-out ·');
+ // Brief says the same under its card.
+ await pickTab('Brief');
+ expect(
+ [...panel()!.querySelectorAll('p')].filter((p) =>
+ p.textContent?.startsWith('Uses your data'),
+ ),
+ ).toHaveLength(2);
+ });
+
+ it('says nothing of the data while the sources can’t be read', async () => {
+ // The default read fails (null): no line, no count on the tab.
+ getContentDraft.mockResolvedValue(draft());
+ window.innerWidth = 1440;
+ await renderPage();
+ expect(panel()!.textContent).not.toContain('Uses your data');
+ expect(panel()!.textContent).not.toContain('No sources kept yet');
+ expect(panel()!.querySelector('[role="tab"] [title]')).toBeNull();
+ });
+
+ it('says when the agent last wrote from the sources: a page it wrote, not a run that failed', async () => {
+ getDraftSources.mockResolvedValue({
+ data: {
+ prompts: [],
+ fanouts: [],
+ citedPages: [],
+ gscQueries: [],
+ brandDomains: [],
+ competitorDomains: [],
+ },
+ choices: [],
+ });
+ const wrote = new Date(Date.now() - 2 * 60_000).toISOString();
+ getContentDraft.mockResolvedValue(draft({ agentState: null, agentSince: wrote }));
+ window.innerWidth = 1440;
+ await renderPage();
+ await pickTab('Sources');
+ expect(panel()!.textContent).toContain('Last used by Content Agent · 2 minutes ago');
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ getContentDraft.mockResolvedValue(draft({ agentState: 'failed', agentSince: wrote }));
+ await renderPage();
+ await pickTab('Sources');
+ expect(panel()!.textContent).toContain('Not used by Content Agent yet');
+ });
+
it('shows how many rules the page meets, and opens them from the header', async () => {
getContentDraft.mockResolvedValue(
draft({
diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.ts
index 5c1c11256..4ec3e9903 100644
--- a/web/src/lib/actions/content-drafts.test.ts
+++ b/web/src/lib/actions/content-drafts.test.ts
@@ -587,6 +587,8 @@ describe('agent suggestions', () => {
reason: 'answer a fan-out',
ruleKeys: ['dated'],
status: 'open',
+ // When the run left it, for "Last used by Content Agent".
+ createdAt: '2026-10-21T10:00:00Z',
});
expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);
// The latest batch is found first; only its rows are read whole.
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index f0859288f..28afaadd0 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -1419,6 +1419,7 @@ export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]
reason: row.reason,
ruleKeys: row.rule_keys ?? [],
status: row.status as SuggestionStatus,
+ createdAt: row.created_at,
};
});
}
diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.ts
index 8a227c215..5baccc092 100644
--- a/web/src/lib/content/suggestions.ts
+++ b/web/src/lib/content/suggestions.ts
@@ -37,6 +37,8 @@ export interface DraftSuggestion {
/** The rules it is meant to fix. */
ruleKeys: string[];
status: SuggestionStatus;
+ /** When the agent left it: the run's time, for "Last used by Content Agent". */
+ createdAt?: string;
}
/**