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(action-center): list the prompts, pages and platforms behind an action's counts (#1076)

Cihan1061b1ed8e6f
diff --git a/web/messages/en.json b/web/messages/en.json
index d81a7220d..67e66634a 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -931,11 +931,13 @@
},
"skipped": "Skipped: {reason}",
"answerSource": "AI answer",
+ "affectedHeading": "Affected ({count})",
"tasksHeading": "Tasks ({count})",
"signalsHeading": "Signals ({count})",
"historyHeading": "History ({count})",
"sheets": {
"action": "Action",
+ "affected": "Affected",
"tasks": "Tasks",
"signals": "Signals",
"history": "History"
@@ -961,6 +963,14 @@
"link": "Link",
"task": "Task",
"details": "Details",
+ "item": "Item",
+ "volume": "Volume",
+ "lostPage": "Lost page",
+ "citedInstead": "Cited instead",
+ "affectedPrompt": "Prompt",
+ "affectedPage": "Page",
+ "affectedCompetitor": "Competitor",
+ "affectedTopic": "Topic",
"type": "Type",
"entity": "Affected",
"signal": "Signal",
@@ -976,6 +986,7 @@
"actionId": "Action ID",
"tabs": {
"overview": "Overview",
+ "affected": "Affected",
"tasks": "Tasks",
"signals": "Signals",
"history": "History"
@@ -987,6 +998,30 @@
"noKpis": "No configured KPIs are linked to this action.",
"support": "{count, plural, =0 {No open signal supports this action any more.} one {# signal supports this action} other {# signals support this action}}",
"supportAll": "All signals ({count})",
+ "affected": {
+ "prompts": "{count, plural, one {# prompt} other {# prompts}}",
+ "pages": "{count, plural, one {# page} other {# pages}}",
+ "prompt": "Prompt",
+ "volume": "Volume",
+ "lostOn": "Lost on",
+ "platforms": "Platforms",
+ "lostPage": "Your lost page",
+ "citedInstead": "Cited instead",
+ "ahead": "Ahead of you",
+ "aheadValue": "{competitor} {them} vs you {you} on {platform}",
+ "aheadNotNamed": "{competitor} {them} on {platform}; you're not named",
+ "positions": "See positions for {prompt}",
+ "positionsShort": "See positions",
+ "page": "Page",
+ "visits": "AI visits",
+ "visitsValue": "{before} → {now}",
+ "from": "From",
+ "issues": "Issues",
+ "competitors": "Competitors",
+ "topics": "Topics",
+ "more": "Showing {shown} of {total}",
+ "empty": "Nothing recorded to list for this action."
+ },
"tasksProgress": "{completed} / {total} tasks completed",
"noSignals": "No linked signals.",
"assignee": "Assignee",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 43ae6f434..15b31dd4f 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { toast } from 'sonner';
@@ -30,6 +30,7 @@ import {
assignAction,
deleteTask,
getActionDetail,
+ getPromptDemand,
setActionDueDate,
updateActionStatus,
updateTaskStatus,
@@ -62,6 +63,13 @@ import { priorityReasonText } from '@/lib/action-center/priority';
import { OpportunityContext } from './opportunity-context';
import { ActionExportButtons } from './action-export-buttons';
import { SupportingSignals } from './supporting-signals';
+import { AffectedTab } from './affected-tab';
+import {
+ affectedChips,
+ affectedOf,
+ affectedSignals,
+ affectedTotal,
+} from '@/lib/action-center/affected';
import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
@@ -69,8 +77,10 @@ import { ImproveOutcomeCard } from './improve-outcome-card';
import { improvePlatformLabels } from '@/lib/improve-outcome';
import { cn } from '@/lib/utils';
-type DrawerTab = 'overview' | 'tasks' | 'signals' | 'history';
+type DrawerTab = 'overview' | 'affected' | 'tasks' | 'signals' | 'history';
const TABS: DrawerTab[] = ['overview', 'tasks', 'signals', 'history'];
+/** With something to list, Affected follows Overview (AC-003). */
+const TABS_WITH_AFFECTED: DrawerTab[] = ['overview', 'affected', 'tasks', 'signals', 'history'];
/**
* Action detail: evidence, execution, trail. Tabs are local state, not
@@ -132,9 +142,49 @@ export function ActionDrawer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [action?.id]);
+ // What the action is about, item by item (AC-003), from the signals it rests on.
+ const affected = useMemo(
+ () =>
+ action && detail
+ ? affectedOf(affectedSignals(detail.signals, action.id), action.payload ?? {})
+ : null,
+ [action, detail],
+ );
+
+ // Each affected prompt's demand. Best effort: without it the column is left out.
+ const [volumes, setVolumes] = useState<Map<string, number> | null>(null);
+ const promptIdsKey = (affected?.prompts ?? [])
+ .map((row) => row.id)
+ .filter(Boolean)
+ .join(',');
+ useEffect(() => {
+ setVolumes(null);
+ if (!promptIdsKey) return;
+ let cancelled = false;
+ getPromptDemand(brandId, promptIdsKey.split(',')).then(
+ (demand) => {
+ if (!cancelled) setVolumes(new Map(Object.entries(demand)));
+ },
+ () => undefined,
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, promptIdsKey]);
+
if (!action) return null;
const texts = actionTexts(action, tTexts);
const tags = actionContextTags(action, t);
+ const tabs = affected && affectedTotal(affected) > 0 ? TABS_WITH_AFFECTED : TABS;
+ // Once the detail is in, each count opens the list behind it (AC-003).
+ const chips =
+ detail && affected
+ ? affectedChips(detail.signals, affected, action.id).map((chip) => ({
+ key: chip.entity,
+ label: t(`tags.${chip.entity}`, { count: chip.count }),
+ tab: chip.tab as DrawerTab,
+ }))
+ : [];
const relatedKpis: string[] = action.kpiKeys.filter(isKpiKey);
// Sent by a person from Content Optimization (#857): its evidence is the
// opportunity, not detection signals.
@@ -188,13 +238,29 @@ export function ActionDrawer({
</div>
</div>
<div className="flex flex-wrap gap-1">
- {tags.map((tag) => (
- <Badge key={tag} variant="outline" className="text-[10px]">
- {tag}
- </Badge>
- ))}
+ {chips.length > 0
+ ? chips.map((chip) => (
+ <Badge
+ key={chip.key}
+ variant="outline"
+ className="cursor-pointer text-[10px] hover:bg-muted"
+ render={<button type="button" onClick={() => setTab(chip.tab)} />}
+ >
+ {chip.label}
+ </Badge>
+ ))
+ : tags.map((tag) => (
+ <Badge key={tag} variant="outline" className="text-[10px]">
+ {tag}
+ </Badge>
+ ))}
</div>
- <ActionExportButtons action={action} detail={detail} />
+ <ActionExportButtons
+ action={action}
+ detail={detail}
+ affected={affected}
+ volumes={volumes}
+ />
</SheetHeader>
{/* Who has it, where it stands and by when: ahead of the tabs, so they
@@ -278,7 +344,7 @@ export function ActionDrawer({
</div>
<nav className="flex gap-4 border-b px-6" aria-label={t('table.action')}>
- {TABS.map((key) => (
+ {tabs.map((key) => (
<button
key={key}
type="button"
@@ -293,6 +359,7 @@ export function ActionDrawer({
>
{t(`drawer.tabs.${key}`)}
{key === 'tasks' && detail ? ` (${detail.tasks.length})` : ''}
+ {key === 'affected' && affected ? ` (${affectedTotal(affected)})` : ''}
</button>
))}
</nav>
@@ -388,6 +455,8 @@ export function ActionDrawer({
</>
) : null}
</>
+ ) : tab === 'affected' && affected ? (
+ <AffectedTab affected={affected} volumes={volumes} />
) : tab === 'tasks' ? (
<section>
{/* Canceled tasks leave the denominator — the work was called
diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsx
index 301c63e4f..1253ca18a 100644
--- a/web/src/components/action-center/action-export-buttons.tsx
+++ b/web/src/components/action-center/action-export-buttons.tsx
@@ -23,6 +23,7 @@ import {
buildActionExport,
type ActionExport,
type ExportFact,
+ type ExportAffected,
} from '@/lib/action-center/export';
import { opportunityLists } from '@/lib/content/opportunity-lists';
import { priorityReasonText } from '@/lib/action-center/priority';
@@ -30,6 +31,10 @@ import { isKpiKey } from '@/lib/kpis/registry';
import { signalAffected, signalTexts, signalTypeLabel } from '@/lib/signals/display';
import { viewerTimeZone } from '@/lib/time-zone';
import { isSuperseded } from './signal-table';
+import { leaderText, type Affected } from '@/lib/action-center/affected';
+import { platformName } from '@/lib/signals/names';
+import { getPlatformName } from '@/lib/traffic-platforms';
+import { formatCompactNumber } from '@/lib/format';
// Written out so Excel reads the CSV as UTF-8 and keeps Turkish characters.
const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
@@ -57,9 +62,14 @@ function save(blob: Blob, fileName: string) {
export function ActionExportButtons({
action,
detail,
+ affected = null,
+ volumes = null,
}: {
action: ActionItem;
detail: ActionDetail | null;
+ /** The Affected tab's list and its prompts' demand, as the drawer shows them (AC-003). */
+ affected?: Affected | null;
+ volumes?: Map<string, number> | null;
}) {
const t = useTranslations('actionCenter.actionsPage');
const tExport = useTranslations('actionCenter.actionsPage.export');
@@ -75,6 +85,7 @@ export function ActionExportButtons({
const tSignalTexts = useTranslations('actionCenter.signalTexts');
const tSignalCategories = useTranslations('actionCenter.signalCategories');
const tPriority = useTranslations('actionCenter.actionsPage.priority');
+ const tAffected = useTranslations('actionCenter.actionsPage.drawer.affected');
const [isBusy, setIsBusy] = useState(false);
// The Markdown Copy Data shows, and what to say once it is copied.
const [preview, setPreview] = useState<{ text: string; copied: string } | null>(null);
@@ -202,6 +213,7 @@ export function ActionExportButtons({
`${tRegistry(`${kpi.kpiKey}.name`)} (${t('drawer.kpiTarget', { target: kpi.target })})`,
),
context: await sentFrom(origin),
+ affected: exportAffected(origin),
taskTitle: (task) => taskText(task, tTasks),
taskStatus: (status) => tTaskStatus(status),
signal: (signal) => {
@@ -225,6 +237,60 @@ export function ActionExportButtons({
);
};
+ /** The Affected tab's rows, labelled for the exports (AC-003). */
+ const exportAffected = (origin: string): ExportAffected[] => {
+ if (!affected) return [];
+ const row = (over: Partial<ExportAffected>): ExportAffected => ({
+ entity: '',
+ label: '',
+ volume: '',
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ details: '',
+ link: '',
+ ...over,
+ });
+ const leadersShown = affected.prompts.some((p) => p.leaders.length > 0);
+ return [
+ ...affected.prompts.map((prompt) => {
+ const volume = prompt.id ? volumes?.get(prompt.id) : undefined;
+ return row({
+ entity: tExport('affectedPrompt'),
+ label: prompt.text,
+ volume: volume ? `~${formatCompactNumber(volume)}` : '',
+ platforms: prompt.platforms.map(platformName),
+ lostPages: prompt.lostPages,
+ citedInstead: prompt.citedInstead,
+ details: prompt.leaders.map((leader) => leaderText(leader, tAffected)).join('; '),
+ link: prompt.id ? `${origin}/dashboard/prompts/${prompt.id}` : '',
+ });
+ }),
+ ...affected.pages.map((page) =>
+ row({
+ entity: tExport('affectedPage'),
+ label: page.url,
+ platforms: page.platforms.map(getPlatformName),
+ details: [
+ page.sessions !== null && page.before !== null
+ ? `${tAffected('visits')}: ${tAffected('visitsValue', { before: page.before, now: page.sessions })}`
+ : '',
+ page.issues.join(', '),
+ ]
+ .filter(Boolean)
+ .join('; '),
+ link: /^https?:\/\//.test(page.url) ? page.url : '',
+ }),
+ ),
+ ...(leadersShown
+ ? []
+ : affected.competitors.map((name) =>
+ row({ entity: tExport('affectedCompetitor'), label: name }),
+ )),
+ ...affected.topics.map((name) => row({ entity: tExport('affectedTopic'), label: name })),
+ ];
+ };
+
/** Builds the export once, holding the buttons while it runs. */
const run = async (fn: (data: ActionExport) => Promise<void> | void) => {
setIsBusy(true);
diff --git a/web/src/components/action-center/affected-tab.test.tsx b/web/src/components/action-center/affected-tab.test.tsx
new file mode 100644
index 000000000..00f81f18f
--- /dev/null
+++ b/web/src/components/action-center/affected-tab.test.tsx
@@ -0,0 +1,141 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import type { Affected } from '@/lib/action-center/affected';
+import { AffectedTab } from './affected-tab';
+
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+const base: Affected = {
+ prompts: [],
+ pages: [],
+ promptTotal: 0,
+ pageTotal: 0,
+ platforms: [],
+ lostPages: [],
+ competitors: [],
+ topics: [],
+};
+
+const headers = () => [...container.querySelectorAll('th')].map((th) => th.textContent);
+
+describe('AffectedTab', () => {
+ it('shows a lost citation row with its demand, page and what is cited instead', () => {
+ render(
+ <AffectedTab
+ affected={{
+ ...base,
+ promptTotal: 1,
+ prompts: [
+ {
+ id: 'p1',
+ text: 'Which tools track AI search?',
+ platforms: ['chatgpt-web'],
+ lostPages: ['https://acme.example/blog/best-tools'],
+ citedInstead: ['https://www.profound.com/features'],
+ leaders: [],
+ topics: [],
+ },
+ ],
+ }}
+ volumes={new Map([['p1', 25100]])}
+ />,
+ );
+ expect(headers()).toEqual(['Prompt', 'Volume', 'Lost on', 'Your lost page', 'Cited instead']);
+ const cells = [...container.querySelectorAll('td')].map((td) => td.textContent);
+ expect(cells[1]).toBe('~25.1k');
+ expect(cells[3]).toContain('/blog/best-tools');
+ expect(cells[4]).toContain('profound.com');
+ // The prompt opens its page; its chart icon, the Positions panel.
+ const links = [...container.querySelectorAll('a')].map((a) => a.getAttribute('href'));
+ expect(links).toContain('/dashboard/prompts/p1');
+ expect(links).toContain('/dashboard/prompts?tab=all&positions=p1');
+ });
+
+ it('leaves out columns nothing fills', () => {
+ render(
+ <AffectedTab
+ affected={{
+ ...base,
+ promptTotal: 1,
+ prompts: [
+ {
+ id: null,
+ text: 'A prompt',
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ },
+ ],
+ }}
+ volumes={null}
+ />,
+ );
+ expect(headers()).toEqual(['Prompt']);
+ });
+
+ it('says how many there are when it lists only the first ones', () => {
+ render(
+ <AffectedTab
+ affected={{
+ ...base,
+ promptTotal: 60,
+ prompts: [
+ {
+ id: 'p1',
+ text: 'One',
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ },
+ ],
+ }}
+ volumes={null}
+ />,
+ );
+ expect(container.textContent).toContain('60 prompts');
+ expect(container.textContent).toContain('Showing 1 of 60');
+ });
+});
diff --git a/web/src/components/action-center/affected-tab.tsx b/web/src/components/action-center/affected-tab.tsx
new file mode 100644
index 000000000..d2f5cbe4f
--- /dev/null
+++ b/web/src/components/action-center/affected-tab.tsx
@@ -0,0 +1,323 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { ArrowUpRight, BarChart3 } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Badge } from '@/components/ui/badge';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import {
+ leaderText,
+ type Affected,
+ type AffectedPage,
+ type AffectedPrompt,
+} from '@/lib/action-center/affected';
+import { getPlatformName } from '@/lib/traffic-platforms';
+import { formatCompactNumber } from '@/lib/format';
+import { SignalWhereLine } from './signal-table';
+
+/**
+ * The Affected tab (AC-003): the prompts and pages behind an action's counts.
+ * Columns follow what the action's signals record, so a citation recovery
+ * shows where each prompt was lost, the page that lost it and what is cited
+ * instead, and a traffic action its pages' AI visits. A column nothing fills
+ * is left out.
+ */
+export function AffectedTab({
+ affected,
+ volumes,
+}: {
+ affected: Affected;
+ /** Estimated monthly AI searches per prompt id; null until read, or when they can't be. */
+ volumes: Map<string, number> | null;
+}) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.affected');
+ const hasRows = affected.prompts.length > 0 || affected.pages.length > 0;
+
+ return (
+ <div className="space-y-6">
+ {affected.prompts.length > 0 && (
+ <PromptsTable rows={affected.prompts} total={affected.promptTotal} volumes={volumes} />
+ )}
+ {affected.pages.length > 0 && <PagesTable rows={affected.pages} total={affected.pageTotal} />}
+ {affected.competitors.length > 0 &&
+ !affected.prompts.some((row) => row.leaders.length > 0) && (
+ <NameList label={t('competitors')} names={affected.competitors} />
+ )}
+ {affected.topics.length > 0 && <NameList label={t('topics')} names={affected.topics} />}
+ {!hasRows && affected.competitors.length === 0 && affected.topics.length === 0 && (
+ <p className="text-xs text-muted-foreground">{t('empty')}</p>
+ )}
+ </div>
+ );
+}
+
+function PromptsTable({
+ rows,
+ total,
+ volumes,
+}: {
+ rows: AffectedPrompt[];
+ total: number;
+ volumes: Map<string, number> | null;
+}) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.affected');
+ const volumeOf = (row: AffectedPrompt) => (row.id ? (volumes?.get(row.id) ?? null) : null);
+ const show = {
+ volume: rows.some((row) => volumeOf(row) !== null),
+ platforms: rows.some((row) => row.platforms.length > 0),
+ lost: rows.some((row) => row.lostPages.length > 0),
+ citedInstead: rows.some((row) => row.citedInstead.length > 0),
+ ahead: rows.some((row) => row.leaders.length > 0),
+ };
+
+ return (
+ <section>
+ <Heading title={t('prompts', { count: total })} shown={rows.length} total={total} />
+ <div className="mt-2 overflow-x-auto rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">{t('prompt')}</TableHead>
+ {show.volume && <TableHead className="text-right text-xs">{t('volume')}</TableHead>}
+ {show.platforms && (
+ <TableHead className="text-xs">
+ {show.lost ? t('lostOn') : t('platforms')}
+ </TableHead>
+ )}
+ {show.lost && <TableHead className="text-xs">{t('lostPage')}</TableHead>}
+ {show.citedInstead && <TableHead className="text-xs">{t('citedInstead')}</TableHead>}
+ {show.ahead && <TableHead className="text-xs">{t('ahead')}</TableHead>}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => {
+ const volume = volumeOf(row);
+ return (
+ <TableRow key={row.id ?? row.text}>
+ <TableCell className="min-w-[10rem] whitespace-normal align-top text-xs">
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0">
+ {row.id ? (
+ <Link
+ href={`/dashboard/prompts/${row.id}`}
+ className="font-medium underline-offset-2 hover:underline"
+ >
+ {row.text}
+ </Link>
+ ) : (
+ <span className="font-medium">{row.text}</span>
+ )}
+ {row.topics.length > 0 && (
+ <p className="text-[11px] text-muted-foreground">
+ {row.topics.join(', ')}
+ </p>
+ )}
+ </div>
+ {row.id && (
+ <Link
+ href={`/dashboard/prompts?tab=all&positions=${row.id}`}
+ aria-label={t('positions', { prompt: row.text })}
+ title={t('positionsShort')}
+ className="mt-0.5 shrink-0 text-muted-foreground hover:text-foreground"
+ >
+ <BarChart3 className="h-3.5 w-3.5" />
+ </Link>
+ )}
+ </div>
+ </TableCell>
+ {show.volume && (
+ <TableCell className="text-right align-top text-xs tabular-nums">
+ {volume !== null ? `~${formatCompactNumber(volume)}` : '—'}
+ </TableCell>
+ )}
+ {show.platforms && (
+ <TableCell className="whitespace-normal align-top text-xs">
+ {row.platforms.length > 0 ? (
+ <SignalWhereLine
+ where={{ platforms: row.platforms, regions: [], topics: [] }}
+ />
+ ) : (
+ '—'
+ )}
+ </TableCell>
+ )}
+ {show.lost && (
+ <TableCell className="min-w-[8rem] whitespace-normal align-top text-xs">
+ <Urls urls={row.lostPages} path />
+ </TableCell>
+ )}
+ {show.citedInstead && (
+ <TableCell className="min-w-[7rem] whitespace-normal align-top text-xs">
+ <Urls urls={row.citedInstead} short />
+ </TableCell>
+ )}
+ {show.ahead && (
+ <TableCell className="min-w-[9rem] whitespace-normal align-top text-xs">
+ {row.leaders.length > 0
+ ? row.leaders.map((leader) => (
+ <p key={`${leader.competitor}:${leader.platform}`}>
+ {leaderText(leader, t)}
+ </p>
+ ))
+ : '—'}
+ </TableCell>
+ )}
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+ );
+}
+
+function PagesTable({ rows, total }: { rows: AffectedPage[]; total: number }) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.affected');
+ const show = {
+ visits: rows.some((row) => row.sessions !== null),
+ from: rows.some((row) => row.platforms.length > 0),
+ issues: rows.some((row) => row.issues.length > 0),
+ };
+
+ return (
+ <section>
+ <Heading title={t('pages', { count: total })} shown={rows.length} total={total} />
+ <div className="mt-2 overflow-x-auto rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-xs">{t('page')}</TableHead>
+ {show.visits && <TableHead className="text-right text-xs">{t('visits')}</TableHead>}
+ {show.from && <TableHead className="text-xs">{t('from')}</TableHead>}
+ {show.issues && <TableHead className="text-xs">{t('issues')}</TableHead>}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {rows.map((row) => (
+ <TableRow key={row.url}>
+ <TableCell className="min-w-[10rem] whitespace-normal align-top text-xs">
+ <Urls urls={[row.url]} />
+ </TableCell>
+ {show.visits && (
+ <TableCell className="whitespace-nowrap text-right align-top text-xs tabular-nums">
+ {row.sessions === null
+ ? '—'
+ : row.before === null
+ ? row.sessions
+ : t('visitsValue', { before: row.before, now: row.sessions })}
+ </TableCell>
+ )}
+ {show.from && (
+ <TableCell className="whitespace-normal align-top text-xs">
+ {row.platforms.map(getPlatformName).join(', ') || '—'}
+ </TableCell>
+ )}
+ {show.issues && (
+ <TableCell className="whitespace-normal align-top text-xs">
+ {row.issues.join(', ') || '—'}
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+ );
+}
+
+function Heading({ title, shown, total }: { title: string; shown: number; total: number }) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.affected');
+ return (
+ <div className="flex items-baseline justify-between gap-2">
+ <p className="text-xs font-medium text-muted-foreground">{title}</p>
+ {total > shown && (
+ <p className="text-[11px] text-muted-foreground">{t('more', { shown, total })}</p>
+ )}
+ </div>
+ );
+}
+
+function NameList({ label, names }: { label: string; names: string[] }) {
+ return (
+ <section>
+ <p className="text-xs font-medium text-muted-foreground">{label}</p>
+ <div className="mt-2 flex flex-wrap gap-1">
+ {names.map((name) => (
+ <Badge key={name} variant="outline" className="text-[10px]">
+ {name}
+ </Badge>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+/**
+ * URLs, linked when they are absolute. `short` shows another site's domain,
+ * `path` the brand's own page by its path: the domain is the brand's.
+ */
+function Urls({
+ urls,
+ short = false,
+ path = false,
+}: {
+ urls: string[];
+ short?: boolean;
+ path?: boolean;
+}) {
+ if (urls.length === 0) return <>—</>;
+ return (
+ <div className="space-y-0.5">
+ {urls.map((url) => {
+ const text = short
+ ? domainOf(url)
+ : path
+ ? pathOf(url)
+ : url.replace(/^https?:\/\/(www\.)?/, '');
+ return /^https?:\/\//.test(url) ? (
+ <a
+ key={url}
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={url}
+ className="flex items-center gap-0.5 break-words underline-offset-2 hover:underline"
+ >
+ {text}
+ <ArrowUpRight className="h-3 w-3 shrink-0" />
+ </a>
+ ) : (
+ <p key={url} title={url} className="break-words">
+ {text}
+ </p>
+ );
+ })}
+ </div>
+ );
+}
+
+function pathOf(url: string): string {
+ try {
+ const { pathname, search } = new URL(url);
+ return `${pathname}${search}`;
+ } catch {
+ return url;
+ }
+}
+
+function domainOf(url: string): string {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return url;
+ }
+}
diff --git a/web/src/components/action-center/supporting-signals.tsx b/web/src/components/action-center/supporting-signals.tsx
index 1f198d8cd..a8315e6dd 100644
--- a/web/src/components/action-center/supporting-signals.tsx
+++ b/web/src/components/action-center/supporting-signals.tsx
@@ -4,7 +4,7 @@ import { useTranslations } from 'next-intl';
import type { Signal } from '@/lib/actions/signals';
import { signalAffected, signalTypeLabel } from '@/lib/signals/display';
import { platformName } from '@/lib/signals/names';
-import { OPEN_SIGNAL_STATUSES } from '@/lib/signals/registry';
+import { supportingOf } from '@/lib/action-center/affected';
/** How many supporting signals "Why this action?" lists before "All signals". */
export const SUPPORT_SHOWN = 5;
@@ -33,9 +33,7 @@ export function SupportingSignals({
const tCategories = useTranslations('actionCenter.signalCategories');
// As the list counts them: open, and this action's now.
- const supporting = signals.filter(
- (signal) => OPEN_SIGNAL_STATUSES.includes(signal.status) && signal.actionId === actionId,
- );
+ const supporting = supportingOf(signals, actionId);
return (
<div className="mt-3">
diff --git a/web/src/lib/action-center/affected.test.ts b/web/src/lib/action-center/affected.test.ts
new file mode 100644
index 000000000..2bcdb9229
--- /dev/null
+++ b/web/src/lib/action-center/affected.test.ts
@@ -0,0 +1,328 @@
+import { describe, expect, it } from 'vitest';
+import type { Signal } from '@/lib/signals/map';
+import { affectedChips, affectedCounts, affectedOf, affectedTotal, leaderText } from './affected';
+
+const signal = (over: Partial<Signal> = {}): Signal =>
+ ({
+ id: 's1',
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detectedAt: '2026-10-09T00:00:00Z',
+ lastDetectedAt: '2026-10-09T00:00:00Z',
+ resolvedAt: null,
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: {},
+ kpiKeys: [],
+ actionId: 'a1',
+ where: { platforms: [], regions: [], topics: [] },
+ ...over,
+ }) as Signal;
+
+describe('affectedOf', () => {
+ it('lists each lost prompt with where it was lost, the page lost and what is cited instead', () => {
+ const affected = affectedOf([
+ signal({
+ payload: {
+ promptId: 'p1',
+ promptText: 'Which tools track AI search?',
+ lostUrls: [{ url: 'https://acme.example/blog/best-tools', position: 2 }],
+ citedNow: [{ url: 'https://profound.com/features', position: 1 }],
+ },
+ where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'], topics: [] },
+ }),
+ // A second finding on the same prompt, on another platform: one row.
+ signal({
+ id: 's2',
+ payload: { promptId: 'p1', promptText: 'Which tools track AI search?' },
+ where: { platforms: ['google-aio'], regions: ['US'], topics: [] },
+ }),
+ signal({
+ id: 's3',
+ payload: { promptId: 'p2', promptText: 'Best AI rank tracker?' },
+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },
+ }),
+ ]);
+
+ expect(affected.prompts).toEqual([
+ {
+ id: 'p1',
+ text: 'Which tools track AI search?',
+ platforms: ['chatgpt-web', 'gemini-web', 'google-aio'],
+ lostPages: ['https://acme.example/blog/best-tools'],
+ citedInstead: ['https://profound.com/features'],
+ leaders: [],
+ topics: [],
+ },
+ {
+ id: 'p2',
+ text: 'Best AI rank tracker?',
+ platforms: ['chatgpt-web'],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ },
+ ]);
+ expect(affected.promptTotal).toBe(2);
+ expect(affected.platforms).toEqual(['chatgpt-web', 'gemini-web', 'google-aio']);
+ expect(affected.lostPages).toEqual(['https://acme.example/blog/best-tools']);
+ });
+
+ it('names the prompts a competitor is ahead on, platform by platform', () => {
+ const affected = affectedOf([
+ signal({
+ category: 'competitor',
+ kind: 'competitor_leads',
+ payload: {
+ competitorName: 'Profound',
+ positions: [
+ {
+ promptId: 'p1',
+ promptText: 'Best AI rank tracker?',
+ platform: 'chatgpt-web',
+ competitor: { now: 1, before: 2 },
+ you: { now: 4, before: 3 },
+ },
+ ],
+ },
+ }),
+ ]);
+
+ expect(affected.prompts[0]).toMatchObject({
+ id: 'p1',
+ platforms: ['chatgpt-web'],
+ leaders: [{ competitor: 'Profound', platform: 'chatgpt-web', them: 1, you: 4 }],
+ });
+ expect(affected.competitors).toEqual(['Profound']);
+ });
+
+ it('counts the prompts a grouped finding names beyond its first ones', () => {
+ const affected = affectedOf([
+ signal({
+ category: 'visibility',
+ kind: 'prompt_visibility_gap',
+ currentValue: 60,
+ payload: {
+ entity: 'prompts',
+ targets: [
+ { id: 'p1', label: 'One' },
+ { id: 'p2', label: 'Two' },
+ ],
+ },
+ }),
+ ]);
+ expect(affected.prompts.map((p) => p.text)).toEqual(['One', 'Two']);
+ expect(affected.promptTotal).toBe(60);
+ });
+
+ it('lists AI-traffic pages with their visits and where they came from', () => {
+ const affected = affectedOf([
+ signal({
+ category: 'traffic',
+ kind: 'ai_traffic_drop',
+ payload: {
+ entity: 'pages',
+ targets: [{ id: '/subscriptions', label: '/subscriptions', before: 40, now: 32 }],
+ referrals: [
+ {
+ page: '/subscriptions',
+ source: 'analytics',
+ sessions: 32,
+ before: 40,
+ platforms: [{ platform: 'chatgpt.com', sessions: 22, before: 31 }],
+ },
+ ],
+ },
+ }),
+ ]);
+ expect(affected.pages).toEqual([
+ {
+ url: '/subscriptions',
+ sessions: 32,
+ before: 40,
+ platforms: ['chatgpt.com'],
+ issues: [],
+ },
+ ]);
+ expect(affected.pageTotal).toBe(1);
+ });
+
+ it('takes an Improve action’s prompt and platforms from what was sent', () => {
+ const affected = affectedOf([], {
+ promptId: 'p9',
+ promptText: 'What are the best coffee subscriptions?',
+ platforms: [
+ { id: 'gemini-web', label: 'Gemini', state: 'no_runs' },
+ { id: 'perplexity-web', label: 'Perplexity', state: 'not_mentioned' },
+ ],
+ });
+ expect(affected.prompts).toEqual([
+ expect.objectContaining({
+ id: 'p9',
+ platforms: ['gemini-web', 'perplexity-web'],
+ }),
+ ]);
+ });
+
+ it('is empty for an action with nothing to list', () => {
+ expect(affectedOf([], {})).toMatchObject({ prompts: [], pages: [], promptTotal: 0 });
+ });
+});
+
+describe('affectedCounts', () => {
+ it('counts the pages that lost a citation with the listed ones, once each', () => {
+ const affected = affectedOf([
+ signal({
+ payload: {
+ promptId: 'p1',
+ promptText: 'One',
+ lostUrls: [{ url: 'https://acme.example/a' }, { url: 'https://acme.example/b' }],
+ },
+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },
+ }),
+ signal({
+ id: 's2',
+ payload: {
+ promptId: 'p2',
+ promptText: 'Two',
+ lostUrls: [{ url: 'https://acme.example/a' }],
+ },
+ }),
+ ]);
+ expect(affectedCounts(affected)).toEqual({
+ prompts: 2,
+ pages: 2,
+ platforms: 1,
+ competitors: 0,
+ topics: 0,
+ });
+ expect(affectedTotal(affected)).toBe(2);
+ });
+});
+
+describe('leaderText', () => {
+ const t = (key: string, values?: Record<string, string | number>) =>
+ `${key}(${Object.values(values ?? {}).join(',')})`;
+
+ it('names the competitor, both positions and the platform', () => {
+ expect(
+ leaderText({ competitor: 'Trade Coffee', platform: 'chatgpt-web', them: 1, you: 4 }, t),
+ ).toBe('aheadValue(Trade Coffee,#1,ChatGPT,#4)');
+ });
+
+ it('says so when the brand is not named', () => {
+ expect(
+ leaderText({ competitor: 'Trade Coffee', platform: 'gemini-web', them: 2, you: null }, t),
+ ).toBe('aheadNotNamed(Trade Coffee,#2,Gemini)');
+ });
+});
+
+describe('what the review found', () => {
+ it('does not count a bare prompt count on top of the rows it lists', () => {
+ const affected = affectedOf([
+ signal({
+ category: 'mention',
+ kind: 'uncited_mentions',
+ payload: {
+ promptIds: ['p1', 'p2'],
+ mentions: [
+ { promptId: 'p1', promptText: 'One', platforms: ['chatgpt-web'], answers: 3 },
+ { promptId: 'p2', promptText: 'Two', platforms: ['gemini-web'], answers: 1 },
+ ],
+ },
+ currentValue: 2,
+ }),
+ ]);
+ expect(affected.prompts).toHaveLength(2);
+ expect(affected.promptTotal).toBe(2);
+ });
+
+ it('counts a platform once whether it is an engine or the site visits came from', () => {
+ const affected = affectedOf([
+ signal({
+ payload: { promptId: 'p1', promptText: 'One' },
+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },
+ }),
+ signal({
+ id: 's2',
+ category: 'traffic',
+ kind: 'ai_traffic_drop',
+ payload: {
+ entity: 'pages',
+ targets: [{ id: '/a', label: '/a', before: 10, now: 5 }],
+ referrals: [
+ {
+ page: '/a',
+ sessions: 5,
+ before: 10,
+ platforms: [{ platform: 'chatgpt.com', sessions: 5, before: 10 }],
+ },
+ ],
+ },
+ }),
+ ]);
+ expect(affectedCounts(affected).platforms).toBe(1);
+ });
+
+ it('keeps visits one signal recorded when another names the page without them', () => {
+ const affected = affectedOf([
+ signal({
+ category: 'traffic',
+ kind: 'ai_traffic_drop',
+ payload: { entity: 'pages', targets: [{ id: '/a', label: '/a', before: 40, now: 32 }] },
+ }),
+ signal({
+ id: 's2',
+ category: 'traffic',
+ kind: 'ai_traffic_slipping',
+ payload: { entity: 'pages', targets: [{ id: '/a', label: '/a' }] },
+ }),
+ ]);
+ expect(affected.pages[0]).toMatchObject({ sessions: 32, before: 40 });
+ });
+
+ it("names a single-prompt signal's topic, which tells copies of one prompt apart", () => {
+ const affected = affectedOf([
+ signal({
+ payload: { promptId: 'p1', promptText: 'Same text' },
+ where: { platforms: [], regions: [], topics: ['Coffee subscriptions'] },
+ }),
+ signal({
+ id: 's2',
+ payload: { promptId: 'p2', promptText: 'Same text' },
+ where: { platforms: [], regions: [], topics: ['Office coffee'] },
+ }),
+ ]);
+ expect(affected.prompts.map((p) => p.topics)).toEqual([
+ ['Coffee subscriptions'],
+ ['Office coffee'],
+ ]);
+ });
+});
+
+describe('affectedChips', () => {
+ const lost = signal({
+ payload: { promptId: 'p1', promptText: 'One' },
+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },
+ });
+
+ it('opens the Signals tab for signals and Affected for the rest', () => {
+ const chips = affectedChips([lost], affectedOf([lost]), 'a1');
+ expect(chips).toEqual([
+ { entity: 'signals', count: 1, tab: 'signals' },
+ { entity: 'prompts', count: 1, tab: 'affected' },
+ { entity: 'platforms', count: 1, tab: 'affected' },
+ ]);
+ });
+
+ it("counts all the action's signals once none supports it any more", () => {
+ const resolved = { ...lost, status: 'resolved' } as Signal;
+ const chips = affectedChips([resolved], affectedOf([resolved]), 'a1');
+ expect(chips[0]).toEqual({ entity: 'signals', count: 1, tab: 'signals' });
+ });
+});
diff --git a/web/src/lib/action-center/affected.ts b/web/src/lib/action-center/affected.ts
new file mode 100644
index 000000000..719fc2e7b
--- /dev/null
+++ b/web/src/lib/action-center/affected.ts
@@ -0,0 +1,384 @@
+import type { Signal } from '@/lib/signals/map';
+import { signalWhereValue, type CitedPage, type WhereValue } from '@/lib/signals/detail';
+import { OPEN_SIGNAL_STATUSES } from '@/lib/signals/registry';
+import { platformName } from '@/lib/signals/names';
+import { getPlatformName } from '@/lib/traffic-platforms';
+
+/**
+ * What an action is about, item by item (AC-003): the prompts, pages,
+ * competitors and topics behind its counts, read from the signals it rests
+ * on so the list matches them. A count with nothing to see behind it ("7
+ * prompts") is what this replaces.
+ *
+ * Each signal says what it can: its prompt or prompts, the platforms it
+ * happened on, the brand's pages that lost a citation and those cited
+ * instead, the competitors ahead per prompt, AI-traffic pages and their
+ * visits, a technical finding's checks. Signals about the same prompt or page
+ * merge into one row.
+ */
+
+export interface AffectedPrompt {
+ /** Null for a prompt named by text only. */
+ id: string | null;
+ text: string;
+ /** Where it happened: the platforms it was lost, missed or mentioned uncited on. */
+ platforms: string[];
+ /** The brand's pages that stopped being cited for it. */
+ lostPages: string[];
+ /** Pages cited in their place. */
+ citedInstead: string[];
+ /** Competitors named ahead of the brand on it, per platform (1 = first). */
+ leaders: { competitor: string; platform: string; them: number | null; you: number | null }[];
+ /** Its topic: what tells copies of one prompt text apart. */
+ topics: string[];
+}
+
+export interface AffectedPage {
+ url: string;
+ /** AI sessions now and in the window before; null when not recorded. */
+ sessions: number | null;
+ before: number | null;
+ /** The platforms its AI visits came from. */
+ platforms: string[];
+ /** Failed checks, for a technical finding. */
+ issues: string[];
+}
+
+export interface Affected {
+ prompts: AffectedPrompt[];
+ pages: AffectedPage[];
+ /** How many in all: a grouped finding names its first 50 and counts the rest. */
+ promptTotal: number;
+ pageTotal: number;
+ /** The AI engines involved (slugs), and the brand's pages that lost a citation, for the chips. */
+ platforms: string[];
+ lostPages: string[];
+ competitors: string[];
+ topics: string[];
+}
+
+/** A new, empty list: each call fills its own arrays. */
+const empty = (): Affected => ({
+ prompts: [],
+ pages: [],
+ promptTotal: 0,
+ pageTotal: 0,
+ platforms: [],
+ lostPages: [],
+ competitors: [],
+ topics: [],
+});
+
+const add = (list: string[], ...items: string[]) => {
+ for (const item of items) if (item && !list.includes(item)) list.push(item);
+};
+
+const urlsOf = (value: WhereValue | null): string[] =>
+ value?.type === 'citations'
+ ? value.items.map((page: CitedPage) => page.url)
+ : value?.type === 'list'
+ ? [...value.items]
+ : [];
+
+/**
+ * The action's affected items, from the signals that support it. With none
+ * (an action a person sent), from what it was sent about.
+ */
+export function affectedOf(signals: Signal[], payload: Record<string, unknown> = {}): Affected {
+ if (signals.length === 0) return affectedFromPayload(payload);
+
+ const prompts = new Map<string, AffectedPrompt>();
+ const pages = new Map<string, AffectedPage>();
+ const out: Affected = empty();
+ let promptExtra = 0;
+ let pageExtra = 0;
+
+ const promptRow = (id: string | null, text: string): AffectedPrompt | null => {
+ if (!text && !id) return null;
+ const key = id ?? `text:${text}`;
+ let row = prompts.get(key);
+ if (!row) {
+ row = { id, text, platforms: [], lostPages: [], citedInstead: [], leaders: [], topics: [] };
+ prompts.set(key, row);
+ } else if (!row.text && text) {
+ row.text = text;
+ }
+ return row;
+ };
+ const pageRow = (url: string): AffectedPage | null => {
+ if (!url) return null;
+ let row = pages.get(url);
+ if (!row) {
+ row = { url, sessions: null, before: null, platforms: [], issues: [] };
+ pages.set(url, row);
+ }
+ return row;
+ };
+
+ for (const signal of signals) {
+ const value = (key: Parameters<typeof signalWhereValue>[1]) => signalWhereValue(signal, key);
+ const mine: AffectedPrompt[] = [];
+
+ const single = value('prompt');
+ if (single?.type === 'prompt') {
+ const row = promptRow(single.id, single.text);
+ if (row) mine.push(row);
+ }
+ const many = value('prompts');
+ if (many?.type === 'prompts') {
+ for (const item of many.items) {
+ const row = promptRow(item.id, item.text);
+ if (row) mine.push(row);
+ }
+ // A list cut at its first 50 counts the rest. A bare count with no
+ // names (a topic's prompts, ids only) is left to what lists them, so a
+ // count is never shown with nothing behind it.
+ if (many.items.length > 0) promptExtra += Math.max(0, many.total - many.items.length);
+ }
+
+ // Per prompt, where a competitor is ahead.
+ const positions = value('competitorPositions');
+ if (positions?.type === 'positions') {
+ add(out.competitors, positions.competitor);
+ for (const item of positions.items) {
+ const row = promptRow(item.promptId, item.promptText);
+ if (!row) continue;
+ add(row.platforms, item.platform);
+ row.leaders.push({
+ competitor: positions.competitor,
+ platform: item.platform,
+ them: item.competitor.now,
+ you: item.you.now,
+ });
+ }
+ }
+ // Per prompt, where the brand is named without a citation.
+ const mentions = value('mentionDetails');
+ if (mentions?.type === 'mentions') {
+ for (const item of mentions.items) {
+ const row = promptRow(item.promptId, item.promptText);
+ if (row) add(row.platforms, ...item.platforms);
+ }
+ }
+
+ // What the signal says about all its prompts at once.
+ const platforms = value('platforms');
+ const slugs = platforms?.type === 'platforms' ? [...platforms.slugs] : [];
+ add(out.platforms, ...slugs);
+ const lost = urlsOf(value('lostUrl'));
+ const citedNow = urlsOf(value('citedNow'));
+ add(out.lostPages, ...lost);
+ for (const row of mine) {
+ if (row.leaders.length === 0) add(row.platforms, ...slugs);
+ add(row.lostPages, ...lost);
+ add(row.citedInstead, ...citedNow);
+ }
+ // A signal about one prompt names its topic; one about many, theirs together.
+ if (mine.length === 1) add(mine[0].topics, ...signal.where.topics);
+
+ // Pages: AI-traffic pages with their visits, others by URL.
+ const mineP: AffectedPage[] = [];
+ const pageValue = value('pages');
+ if (pageValue?.type === 'trafficPages') {
+ for (const item of pageValue.items) {
+ const row = pageRow(item.page);
+ if (!row) continue;
+ // Another signal may have recorded them where this one didn't.
+ if (item.sessions !== null) row.sessions = item.sessions;
+ if (item.before !== null) row.before = item.before;
+ mineP.push(row);
+ }
+ pageExtra += Math.max(0, pageValue.total - pageValue.items.length);
+ } else if (pageValue?.type === 'list') {
+ for (const url of pageValue.items) {
+ const row = pageRow(url);
+ if (row) mineP.push(row);
+ }
+ pageExtra += Math.max(0, pageValue.total - pageValue.items.length);
+ }
+ const url = value('url');
+ if (url?.type === 'text') {
+ const row = pageRow(url.text);
+ if (row) mineP.push(row);
+ }
+ const referrals = value('aiReferrals');
+ if (referrals?.type === 'referrals') {
+ for (const item of referrals.items) {
+ if (!item.page) continue;
+ const row = pageRow(item.page);
+ if (!row) continue;
+ add(row.platforms, ...item.platforms.map((p) => p.platform));
+ row.sessions ??= item.sessions;
+ row.before ??= item.before;
+ }
+ }
+ const issues = value('issue');
+ if (issues?.type === 'list') {
+ for (const row of mineP) add(row.issues, ...issues.items);
+ }
+
+ const competitor = value('competitor');
+ if (competitor?.type === 'text') add(out.competitors, competitor.text);
+ if (competitor?.type === 'list') add(out.competitors, ...competitor.items);
+ const topic = value('topic');
+ if (topic?.type === 'text') add(out.topics, topic.text);
+ if (topic?.type === 'list') add(out.topics, ...topic.items);
+ }
+
+ out.prompts = [...prompts.values()];
+ out.pages = [...pages.values()];
+ out.promptTotal = out.prompts.length + promptExtra;
+ out.pageTotal = out.pages.length + pageExtra;
+ for (const row of out.prompts) add(out.platforms, ...row.platforms);
+ return out;
+}
+
+const str = (value: unknown) => (typeof value === 'string' ? value : '');
+
+/** An action a person sent: what it was sent about, from its payload. */
+function affectedFromPayload(payload: Record<string, unknown>): Affected {
+ const out: Affected = empty();
+ const platforms = (Array.isArray(payload.platforms) ? payload.platforms : [])
+ .map((p) => (typeof p === 'string' ? p : str((p as Record<string, unknown>)?.id)))
+ .filter(Boolean);
+
+ if (str(payload.promptText)) {
+ out.prompts.push({
+ id: str(payload.promptId) || null,
+ text: str(payload.promptText),
+ platforms,
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ });
+ }
+ const targets = (Array.isArray(payload.targets) ? payload.targets : []) as Record<
+ string,
+ unknown
+ >[];
+ const entity = str(payload.targetEntity);
+ for (const target of targets) {
+ const label = str(target.label) || str(target.id);
+ if (!label) continue;
+ if (entity === 'prompts') {
+ out.prompts.push({
+ id: str(target.id) || null,
+ text: label,
+ platforms: [],
+ lostPages: [],
+ citedInstead: [],
+ leaders: [],
+ topics: [],
+ });
+ } else if (entity === 'pages') {
+ out.pages.push({ url: label, sessions: null, before: null, platforms: [], issues: [] });
+ } else if (entity === 'competitors') {
+ add(out.competitors, label);
+ } else if (entity === 'topics') {
+ add(out.topics, label);
+ }
+ }
+ out.promptTotal = out.prompts.length;
+ out.pageTotal = out.pages.length;
+ add(out.platforms, ...platforms);
+ return out;
+}
+
+/**
+ * The signals that support an action now (AC-007): open, and the action's.
+ * With none left (all resolved, or moved on), the list falls back to every
+ * signal it took, so a finished action still shows what it was about.
+ */
+export function supportingOf(signals: Signal[], actionId: string): Signal[] {
+ return signals.filter(
+ (signal) => OPEN_SIGNAL_STATUSES.includes(signal.status) && signal.actionId === actionId,
+ );
+}
+
+export function affectedSignals(signals: Signal[], actionId: string): Signal[] {
+ const supporting = supportingOf(signals, actionId);
+ return supporting.length > 0 ? supporting : signals;
+}
+
+/** The header's counts, each opening the list behind it. Zero ones are left out. */
+export function affectedCounts(affected: Affected): {
+ prompts: number;
+ pages: number;
+ platforms: number;
+ competitors: number;
+ topics: number;
+} {
+ const pages = new Set([...affected.pages.map((p) => p.url), ...affected.lostPages]);
+ // Engines (chatgpt-web) and the sites AI visits come from (chatgpt.com) by
+ // name, so one platform counts once.
+ const platforms = new Set([
+ ...affected.platforms.map(platformName),
+ ...affected.pages.flatMap((p) => p.platforms.map(getPlatformName)),
+ ]);
+ return {
+ prompts: affected.promptTotal,
+ pages: pages.size + (affected.pageTotal - affected.pages.length),
+ platforms: platforms.size,
+ competitors: affected.competitors.length,
+ topics: affected.topics.length,
+ };
+}
+
+/** What the Affected tab's label counts: its rows, or the names it lists. */
+export function affectedTotal(affected: Affected): number {
+ const rows = affected.promptTotal + affected.pageTotal;
+ return rows > 0 ? rows : affected.competitors.length + affected.topics.length;
+}
+
+type Translator = (key: string, values?: Record<string, string | number>) => string;
+
+/** "#1", or "—" when not named. */
+function rankLabel(position: number | null): string {
+ return position === null ? '—' : `#${Math.round(position * 10) / 10}`;
+}
+
+/**
+ * "Trade Coffee #1 vs you #4 on ChatGPT", or "…; you're not named", in the
+ * reader's language (actionsPage.drawer.affected).
+ */
+export function leaderText(leader: AffectedPrompt['leaders'][number], t: Translator): string {
+ const values = {
+ competitor: leader.competitor,
+ them: rankLabel(leader.them),
+ platform: platformName(leader.platform),
+ };
+ return leader.you === null
+ ? t('aheadNotNamed', values)
+ : t('aheadValue', { ...values, you: rankLabel(leader.you) });
+}
+
+export type AffectedChipEntity =
+ | 'signals'
+ | 'prompts'
+ | 'pages'
+ | 'platforms'
+ | 'competitors'
+ | 'topics';
+
+/**
+ * The drawer header's chips: each count and the tab that lists what it
+ * counts (AC-003). Signals count those that support the action, or all it
+ * took once none do, as the Affected list falls back to them.
+ */
+export function affectedChips(
+ signals: Signal[],
+ affected: Affected,
+ actionId: string,
+): { entity: AffectedChipEntity; count: number; tab: 'signals' | 'affected' }[] {
+ const counts = affectedCounts(affected);
+ const supporting = supportingOf(signals, actionId).length;
+ const chips: { entity: AffectedChipEntity; count: number; tab: 'signals' | 'affected' }[] = [];
+ if (signals.length > 0) {
+ chips.push({ entity: 'signals', count: supporting || signals.length, tab: 'signals' });
+ }
+ for (const entity of ['prompts', 'pages', 'platforms', 'competitors', 'topics'] as const) {
+ if (counts[entity] > 0) chips.push({ entity, count: counts[entity], tab: 'affected' });
+ }
+ return chips;
+}
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index 68437a2a4..5a9ff3014 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -106,6 +106,18 @@ const texts: ExportTexts = {
{ label: 'Prompt', value: 'Which tools track AI search?' },
{ label: 'Platforms at send time', value: ['Gemini · No runs', 'ChatGPT · Not cited'] },
],
+ affected: [
+ {
+ entity: 'Prompt',
+ label: 'Which tools track AI search?',
+ volume: '~25.1k',
+ platforms: ['ChatGPT', 'Gemini'],
+ lostPages: ['https://acme.example/blog/best-tools'],
+ citedInstead: ['https://profound.com/features'],
+ details: '',
+ link: 'https://app.example/dashboard/prompts/p1',
+ },
+ ],
taskTitle: (task) => task.title ?? '',
taskStatus: (status) => ({ completed: 'Completed', skipped: 'Skipped' })[status] ?? status,
signal: () => ({
@@ -181,6 +193,9 @@ describe('actionMarkdown', () => {
'- ChatGPT · Not cited',
'link: https://app.example/dashboard/action-center/actions?action=a1',
'',
+ '## affectedHeading(1)',
+ '- Which tools track AI search? · ~25.1k · ChatGPT, Gemini · lostPage: https://acme.example/blog/best-tools · citedInstead: https://profound.com/features',
+ '',
'## tasksHeading(2)',
'1. Add a 2026 comparison table to /blog/best-tools (Completed)',
' Lead with the table. Then the FAQ. · ChatGPT · https://acme.example/blog/best-tools · AI answer',
@@ -205,37 +220,43 @@ describe('actionMarkdown', () => {
tags: [],
kpis: [],
context: [],
+ affected: [],
tasks: [],
signals: [],
events: [],
};
const md = actionMarkdown(bare, label);
- expect(md).not.toMatch(/priority|assignee|tags|kpis|historyHeading/);
+ expect(md).not.toMatch(/priority|assignee|tags|kpis|affectedHeading|historyHeading/);
expect(md).toContain('## tasksHeading(0)');
});
});
describe('actionCsv', () => {
- it('gives each task and signal a row, marked by section and the action', () => {
+ it('gives each affected item, task and signal a row, marked by section and the action', () => {
const [head, ...rows] = actionCsv(exported).split('\n');
expect(head).toBe(ACTION_CSV_HEADERS.join(','));
expect(rows.map((row) => row.split(',').slice(0, 2).join(','))).toEqual([
+ 'affected,AC-52',
'task,AC-52',
'task,AC-52',
'signal,AC-52',
]);
+ expect(rows[0]).toContain(
+ '~25.1k,https://acme.example/blog/best-tools,https://profound.com/features,ChatGPT; Gemini',
+ );
// A cell a spreadsheet would run as a formula is kept as text.
- expect(rows[1]).toContain(`"'=HYPERLINK(""x"")"`);
- expect(rows[2]).toContain('Citation · Lost,Which tools track AI search?');
- expect(rows[2]).toContain('ChatGPT; Gemini,United States,2026-10-09');
+ expect(rows[2]).toContain(`"'=HYPERLINK(""x"")"`);
+ expect(rows[3]).toContain('Citation · Lost,Which tools track AI search?');
+ expect(rows[3]).toContain('ChatGPT; Gemini,United States,2026-10-09');
});
});
describe('actionWorkbook', () => {
- it('gives the action, its tasks, signals and history a sheet each', () => {
+ it('gives the action, its affected items, tasks, signals and history a sheet each', () => {
const sheets = actionWorkbook(exported, label);
expect(sheets.map((s) => s.sheet)).toEqual([
'sheets.action',
+ 'sheets.affected',
'sheets.tasks',
'sheets.signals',
'sheets.history',
@@ -251,12 +272,18 @@ describe('actionWorkbook', () => {
{ value: 'Platforms at send time', fontWeight: 'bold' },
'Gemini · No runs; ChatGPT · Not cited',
]);
- expect(sheets[1].data[0][1]).toEqual({ value: 'task', fontWeight: 'bold' });
- expect(sheets[2].data[1].slice(0, 2)).toEqual([
+ expect(sheets[1].data[1].slice(0, 4)).toEqual([
+ 'Prompt',
+ 'Which tools track AI search?',
+ '~25.1k',
+ 'ChatGPT, Gemini',
+ ]);
+ expect(sheets[2].data[0][1]).toEqual({ value: 'task', fontWeight: 'bold' });
+ expect(sheets[3].data[1].slice(0, 2)).toEqual([
'Citation · Lost',
'Which tools track AI search?',
]);
- expect(sheets[3].data[1]).toEqual(['2026-10-08', 'Action created']);
+ expect(sheets[4].data[1]).toEqual(['2026-10-08', 'Action created']);
});
});
@@ -274,11 +301,12 @@ describe('the Excel file', () => {
const sheets = await readXlsxFile(blob);
expect(sheets.map((s) => s.sheet)).toEqual([
'sheets.action',
+ 'sheets.affected',
'sheets.tasks',
'sheets.signals',
'sheets.history',
]);
- expect(sheets[1].data[2]).toEqual([2, '=HYPERLINK("x")', 'Skipped', 'Skipped: Done by hand']);
- expect(sheets[2].data[1][6]).toBe('ChatGPT, Gemini');
+ expect(sheets[2].data[2]).toEqual([2, '=HYPERLINK("x")', 'Skipped', 'Skipped: Done by hand']);
+ expect(sheets[3].data[1][6]).toBe('ChatGPT, Gemini');
});
});
diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.ts
index 4b1b1d18c..4587d0456 100644
--- a/web/src/lib/action-center/export.ts
+++ b/web/src/lib/action-center/export.ts
@@ -47,12 +47,32 @@ export interface ActionExport {
updated: string;
/** The action's drawer in the app. */
link: string;
+ /** The Affected tab's rows (AC-003). */
+ affected: ExportAffected[];
tasks: ExportTask[];
signals: ExportSignal[];
/** The History tab, in its order. */
events: { date: string; text: string }[];
}
+/** One affected item as the exports list it (AC-003). */
+export interface ExportAffected {
+ /** "Prompt", "Page", "Competitor", "Topic". */
+ entity: string;
+ label: string;
+ /** "~5.5k", or empty when unknown. */
+ volume: string;
+ /** Display names. */
+ platforms: string[];
+ /** The brand's pages that lost a citation, and those cited instead. */
+ lostPages: string[];
+ citedInstead: string[];
+ /** What else its row says: competitors ahead, a page's visits or issues. */
+ details: string;
+ /** Where it opens in the app, or the page itself. */
+ link: string;
+}
+
export interface ExportTask {
number: number;
title: string;
@@ -92,6 +112,7 @@ export interface ExportTexts {
tags: string[];
kpis: string[];
context: ExportFact[];
+ affected: ExportAffected[];
taskTitle: (task: ActionDetail['tasks'][number]) => string;
taskStatus: (status: string) => string;
signal: (signal: ActionDetail['signals'][number]) => {
@@ -143,6 +164,7 @@ export function buildActionExport(
created: day(action.createdAt),
updated: day(action.updatedAt),
link: `${origin}/dashboard/action-center/actions?action=${action.id}`,
+ affected: texts.affected,
tasks: detail.tasks.map((task, i) => {
const details = task.details
? [
@@ -198,6 +220,20 @@ function signalLine(signal: ExportSignal): string {
.join(' · ');
}
+/** One affected item on a line: what it is, its demand, where, and what else it says. */
+function affectedLine(item: ExportAffected, label: Labels): string {
+ return [
+ item.label,
+ item.volume,
+ item.platforms.join(', '),
+ item.lostPages.length ? `${label('lostPage')}: ${item.lostPages.join(', ')}` : '',
+ item.citedInstead.length ? `${label('citedInstead')}: ${item.citedInstead.join(', ')}` : '',
+ item.details,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+}
+
/**
* "Copy all": the action as Markdown, everything its drawer's tabs show, to
* paste into Docs, Notion, Jira or an AI agent.
@@ -232,6 +268,11 @@ export function actionMarkdown(a: ActionExport, label: Labels): string {
`${label('link')}: ${a.link}`,
].filter(Boolean);
+ if (a.affected.length) {
+ lines.push('', `## ${label('affectedHeading', { count: a.affected.length })}`);
+ for (const item of a.affected) lines.push(`- ${affectedLine(item, label)}`);
+ }
+
lines.push('', `## ${label('tasksHeading', { count: a.tasks.length })}`);
for (const task of a.tasks) {
lines.push(`${task.number}. ${task.title} (${task.status})`);
@@ -250,8 +291,9 @@ export function actionMarkdown(a: ActionExport, label: Labels): string {
}
/**
- * The CSV columns: a row per task and per signal, marked by `section`, with
- * the columns they share. Machine names, as in the actions list's export.
+ * The CSV columns: a row per affected item, task and signal, marked by
+ * `section`, with the columns they share. Machine names, as in the actions
+ * list's export.
*/
export const ACTION_CSV_HEADERS = [
'section',
@@ -264,6 +306,9 @@ export const ACTION_CSV_HEADERS = [
'status',
'category',
'impact',
+ 'volume',
+ 'lost_pages',
+ 'cited_instead',
'platforms',
'locations',
'first_detected',
@@ -271,9 +316,22 @@ export const ACTION_CSV_HEADERS = [
'link',
];
-/** "Export CSV": the action's tasks and signals, one row each. */
+/** "Export CSV": the action's affected items, tasks and signals, one row each. */
export function actionCsv(a: ActionExport): string {
const rows: Record<string, unknown>[] = [
+ ...a.affected.map((item, i) => ({
+ section: 'affected',
+ action: a.ref,
+ ref: i + 1,
+ title: item.label,
+ type: item.entity,
+ details: item.details,
+ volume: item.volume,
+ lost_pages: item.lostPages.join('; '),
+ cited_instead: item.citedInstead.join('; '),
+ platforms: item.platforms.join('; '),
+ link: item.link,
+ })),
...a.tasks.map((task) => ({
section: 'task',
action: a.ref,
@@ -332,6 +390,46 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {
columns: [{ width: 22 }, { width: 90 }],
data: summary.map(([name, value]) => [bold(name), value]),
},
+ ...(a.affected.length
+ ? [
+ {
+ sheet: label('sheets.affected'),
+ stickyRowsCount: 1,
+ columns: [
+ { width: 10 },
+ { width: 60 },
+ { width: 10 },
+ { width: 24 },
+ { width: 40 },
+ { width: 40 },
+ { width: 40 },
+ { width: 40 },
+ ],
+ data: [
+ [
+ label('type'),
+ label('item'),
+ label('volume'),
+ label('platforms'),
+ label('lostPage'),
+ label('citedInstead'),
+ label('details'),
+ label('link'),
+ ].map(bold),
+ ...a.affected.map((item) => [
+ item.entity,
+ item.label,
+ item.volume,
+ item.platforms.join(', '),
+ item.lostPages.join(', '),
+ item.citedInstead.join(', '),
+ item.details,
+ item.link,
+ ]),
+ ],
+ },
+ ]
+ : []),
{
sheet: label('sheets.tasks'),
stickyRowsCount: 1,
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index e6542f73a..fefa339a5 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -20,6 +20,8 @@ import {
} from '@/lib/action-center/registry';
import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';
import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';
+import { readPromptPlaces } from '@/lib/signals/prompt-places';
+import { supabaseAdmin } from '@/lib/supabase/admin';
import type { KpiTimeframe } from '@/lib/kpis/registry';
import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';
import {
@@ -228,7 +230,7 @@ export interface ActionDetail {
* action's kpi_keys — evidence of which goals this work serves. */
export async function getActionDetail(brandId: string, actionId: string): Promise<ActionDetail> {
const supabase = await createClient();
- const [tasksRes, signalsRes, eventsRes, kpisRes, outcomeRes] = await Promise.all([
+ const [tasksRes, signalsRes, eventsRes, kpisRes, outcomeRes, places] = await Promise.all([
supabase
.from('action_tasks')
.select(
@@ -260,6 +262,9 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
.eq('brand_id', brandId)
.eq('id', actionId)
.maybeSingle(),
+ // Where each prompt is tracked and its topic, as the Signals page reads
+ // them: the Affected tab's platforms and topics (AC-003).
+ readPromptPlaces(supabase, brandId),
]);
if (tasksRes.error) throw new Error(tasksRes.error.message);
if (signalsRes.error) throw new Error(signalsRes.error.message);
@@ -278,7 +283,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
skipReason: task.skip_reason,
details: (task.details ?? null) as ActionTaskDetails | null,
})),
- signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[]),
+ signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[], places),
events: (eventsRes.data ?? []).map((event) => ({
id: event.id,
event: event.event,
@@ -507,3 +512,43 @@ export async function deleteTask(brandId: string, actionId: string, taskId: stri
await logEvent(supabase, actionId, 'task_deleted', { taskId });
await touchAction(supabase, brandId, actionId);
}
+
+/** Prompt ids per request, so the filter stays well inside a URL's length. */
+const DEMAND_CHUNK = 150;
+
+/**
+ * The estimated monthly AI searches of these prompts, for the Affected tab's
+ * Volume column (AC-003). prompt_volumes is a server-only table, so the
+ * prompts are first checked to be the brand's and visible to the caller
+ * (RLS), and only theirs are read with the admin client.
+ */
+export async function getPromptDemand(
+ brandId: string,
+ promptIds: string[],
+): Promise<Record<string, number>> {
+ const ids = [...new Set(promptIds)];
+ if (ids.length === 0) return {};
+ const supabase = await createClient();
+ const demand: Record<string, number> = {};
+ for (let i = 0; i < ids.length; i += DEMAND_CHUNK) {
+ const chunk = ids.slice(i, i + DEMAND_CHUNK);
+ const { data: visible, error } = await supabase
+ .from('prompts')
+ .select('id, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .in('id', chunk);
+ if (error) throw new Error(error.message);
+ const allowed = (visible ?? []).map((row) => row.id as string);
+ if (allowed.length === 0) continue;
+ const { data: rows, error: volumeError } = await supabaseAdmin
+ .from('prompt_volumes')
+ .select('prompt_id, est_ai_volume')
+ .in('prompt_id', allowed);
+ if (volumeError) throw new Error(volumeError.message);
+ for (const row of rows ?? []) {
+ const volume = Number(row.est_ai_volume ?? 0);
+ if (volume > 0) demand[row.prompt_id as string] = volume;
+ }
+ }
+ return demand;
+}
diff --git a/web/src/lib/actions/action-signals.test.ts b/web/src/lib/actions/action-signals.test.ts
index 29a201edb..d3d1e4aa9 100644
--- a/web/src/lib/actions/action-signals.test.ts
+++ b/web/src/lib/actions/action-signals.test.ts
@@ -16,7 +16,7 @@ vi.mock('@/lib/supabase/server', () => ({
const query = { table, calls: [] as Call[] };
queries.push(query);
const chain: Record<string, unknown> = {};
- for (const method of ['select', 'eq', 'in', 'not', 'order', 'limit']) {
+ for (const method of ['select', 'eq', 'in', 'not', 'order', 'limit', 'range']) {
chain[method] = (...args: unknown[]) => {
query.calls.push([method, ...args]);
return chain;
@@ -30,6 +30,9 @@ vi.mock('@/lib/supabase/server', () => ({
})),
}));
+// The admin client reads prompt_volumes; nothing here reaches it.
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+
const { getActionDetail, getActions } = await import('./action-center');
const signalsQuery = () => queries.find((q) => q.table === 'signals')!;
diff --git a/web/src/lib/actions/prompt-demand.test.ts b/web/src/lib/actions/prompt-demand.test.ts
new file mode 100644
index 000000000..0e0e86e02
--- /dev/null
+++ b/web/src/lib/actions/prompt-demand.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * AC-003: the Affected tab's volumes come from prompt_volumes, a server-only
+ * table. Only prompts of the brand the caller can see are read.
+ */
+
+let visible: { id: string }[];
+let volumeReads: string[][];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ in: () => chain,
+ then: (resolve: (value: unknown) => unknown) => resolve({ data: visible, error: null }),
+ };
+ return chain;
+ },
+ })),
+}));
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: () => {
+ let ids: string[] = [];
+ const chain = {
+ select: () => chain,
+ in: (_column: string, values: string[]) => {
+ ids = values;
+ volumeReads.push(values);
+ return chain;
+ },
+ then: (resolve: (value: unknown) => unknown) =>
+ resolve({
+ data: ids.map((id) => ({ prompt_id: id, est_ai_volume: id === 'p2' ? 0 : 1200 })),
+ error: null,
+ }),
+ };
+ return chain;
+ },
+ },
+}));
+
+const { getPromptDemand } = await import('./action-center');
+
+beforeEach(() => {
+ visible = [{ id: 'p1' }, { id: 'p2' }];
+ volumeReads = [];
+});
+
+describe('getPromptDemand', () => {
+ it("reads the volumes of the brand's prompts the caller can see, and only those", async () => {
+ visible = [{ id: 'p1' }];
+ const demand = await getPromptDemand('b1', ['p1', 'other-brand']);
+ expect(volumeReads).toEqual([['p1']]);
+ expect(demand).toEqual({ p1: 1200 });
+ });
+
+ it('leaves out a prompt without demand', async () => {
+ await expect(getPromptDemand('b1', ['p1', 'p2'])).resolves.toEqual({ p1: 1200 });
+ });
+
+ it('reads nothing for no prompts', async () => {
+ await expect(getPromptDemand('b1', [])).resolves.toEqual({});
+ expect(volumeReads).toEqual([]);
+ });
+});
diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.ts
index d63146bfe..1a771884a 100644
--- a/web/src/lib/signals/detail.ts
+++ b/web/src/lib/signals/detail.ts
@@ -1023,6 +1023,11 @@ function isSiteWide(signal: Signal): boolean {
}
/** The Where block: the spec's fields for this signal, each with its value or none. */
+/** One of a signal's where fields, whatever its category's panel shows (AC-003). */
+export function signalWhereValue(signal: Signal, key: WhereFieldKey): WhereValue | null {
+ return fieldValue(signal, key);
+}
+
export function signalWhereFields(signal: Signal): WhereField[] {
const layout =
signal.kind === 'first_citation'