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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): list every action a signal was used by (#1093)
Cihan3d3934632212
diff --git a/web/src/components/action-center/signal-detail-blocks.test.tsx b/web/src/components/action-center/signal-detail-blocks.test.tsxindex fb21f2bb5..b89ad9995 100644--- a/web/src/components/action-center/signal-detail-blocks.test.tsx+++ b/web/src/components/action-center/signal-detail-blocks.test.tsx@@ -561,26 +561,79 @@ describe("an AI-traffic finding's pages", () => {});describe('SignalEvidenceBlock', () => {- it('links the answers and the action the signal is used by', async () => {+ it('links the answers and every action the signal is used by, with its status', async () => {+ // The latest link first: the current action, then the closed one before it.getSignalActions.mockResolvedValue([- { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'new', payload: {} },+ { id: 'a2', actionNo: 61, kind: 'unknown_kind_for_test', status: 'new', payload: {} },+ { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'completed', payload: {} },]);await act(async () => {render(<SignalEvidenceBlockbrandId="b1"- signal={signal({ payload: { promptId: 'p1', promptText: 'x' }, actionId: 'a1' })}+ signal={signal({ payload: { promptId: 'p1', promptText: 'x' }, actionId: 'a2' })}/>,);});- expect(getSignalActions).toHaveBeenCalledWith('b1', ['a1']);+ // By the signal, so its earlier actions come too, not by its action_id.+ expect(getSignalActions).toHaveBeenCalledWith('b1', 's1');const links = [...container.querySelectorAll('a')].map((a) => `${a.textContent} → ${a.getAttribute('href')}`,);expect(links).toEqual(['View AI answers → /dashboard/prompts/p1',- 'AC-52 · Unknown kind for test → /dashboard/action-center/actions?action=a1',+ 'AC-61 · Unknown kind for testNew → /dashboard/action-center/actions?action=a2',+ 'AC-52 · Unknown kind for testCompleted → /dashboard/action-center/actions?action=a1',+ ]);+ });++ it("puts the signal's current action first when its link is older", async () => {+ getSignalActions.mockResolvedValue([+ { id: 'a2', actionNo: 61, kind: 'unknown_kind_for_test', status: 'completed', payload: {} },+ { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'in_progress', payload: {} },+ ]);+ await act(async () => {+ render(<SignalEvidenceBlock brandId="b1" signal={signal({ actionId: 'a1' })} />);+ });+ const labels = [...container.querySelectorAll('li a')].map((a) => a.textContent);+ expect(labels).toEqual([+ 'AC-52 · Unknown kind for testIn Progress',+ 'AC-61 · Unknown kind for testCompleted',+ ]);+ });++ it('loads again when the signal moves to another action, without the old list', async () => {+ getSignalActions.mockResolvedValueOnce([+ { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'new', payload: {} },]);+ await act(async () => {+ render(<SignalEvidenceBlock brandId="b1" signal={signal({ actionId: 'a1' })} />);+ });+ expect(container.textContent).toContain('AC-52');++ let resolve: (rows: unknown[]) => void = () => {};+ getSignalActions.mockReturnValueOnce(new Promise((r) => (resolve = r)));+ render(<SignalEvidenceBlock brandId="b1" signal={signal({ actionId: 'a2' })} />);+ expect(getSignalActions).toHaveBeenCalledTimes(2);+ expect(container.textContent).toContain('Loading…');+ expect(container.textContent).not.toContain('AC-52');++ await act(async () => {+ resolve([+ { id: 'a2', actionNo: 61, kind: 'unknown_kind_for_test', status: 'new', payload: {} },+ { id: 'a1', actionNo: 52, kind: 'unknown_kind_for_test', status: 'completed', payload: {} },+ ]);+ });+ expect(container.textContent).toContain('AC-61');+ expect(container.textContent).toContain('AC-52');+ });++ it('says when the actions could not be loaded', async () => {+ getSignalActions.mockRejectedValue(new Error('timeout'));+ await act(async () => {+ render(<SignalEvidenceBlock brandId="b1" signal={signal({ actionId: 'a1' })} />);+ });+ expect(container.textContent).toContain('Couldn’t load the actions.');});it('says when no action uses the signal, without asking', () => {diff --git a/web/src/components/action-center/signal-detail-blocks.tsx b/web/src/components/action-center/signal-detail-blocks.tsxindex 05ea0fffd..b68b202a1 100644--- a/web/src/components/action-center/signal-detail-blocks.tsx+++ b/web/src/components/action-center/signal-detail-blocks.tsx@@ -10,6 +10,7 @@ import { actionTexts } from '@/lib/action-center/display';import { crawlerName, locationName, platformFamily, platformName } from '@/lib/signals/names';import { getPlatformName } from '@/lib/traffic-platforms';import {+ currentActionFirst,METRIC_UNITS,PERIOD_DAYS,signalChange,@@ -20,6 +21,7 @@ import {type WhereValue,} from '@/lib/signals/detail';import { cn } from '@/lib/utils';+import { ActionStatusBadge } from './action-table';/*** The signal drawer's three blocks (AC-001): Where, What changed, and@@ -644,34 +646,40 @@ function FigureBox({ label, value }: { label: string; value: string }) {export function SignalEvidenceBlock({ signal, brandId }: { signal: Signal; brandId: string }) {const t = useTranslations('actionCenter.signalsPage.drawer');const tActions = useTranslations('actionCenter.actionTexts');- // Loaded per action id; until the answer for this id arrives it is loading.+ // Loaded per signal and current action; until the answer for them arrives+ // it is loading. A signal is linked to an action only by becoming its+ // current one, and deleting an action drops both, so a signal without one+ // is used by none and isn't asked about.const [loaded, setLoaded] = useState<{- id: string;+ key: string;actions: SignalAction[] | null;} | null>(null);- const actionId = signal.actionId;+ const signalId = signal.id;+ const key = signal.actionId ? `${signalId}|${signal.actionId}` : null;useEffect(() => {- if (!actionId) return;+ if (!key) return;let cancelled = false;- getSignalActions(brandId, [actionId])+ getSignalActions(brandId, signalId).then((rows) => {- if (!cancelled) setLoaded({ id: actionId, actions: rows });+ if (!cancelled) setLoaded({ key, actions: rows });}).catch(() => {- if (!cancelled) setLoaded({ id: actionId, actions: null });+ if (!cancelled) setLoaded({ key, actions: null });});return () => {cancelled = true;};- }, [brandId, actionId]);+ }, [brandId, signalId, key]);- const current = actionId && loaded?.id === actionId ? loaded : null;- const actions: SignalAction[] | 'loading' | 'failed' = !actionId+ const current = key && loaded?.key === key ? loaded : null;+ const actions: SignalAction[] | 'loading' | 'failed' = !key? []: !current? 'loading'- : (current.actions ?? 'failed');+ : current.actions+ ? currentActionFirst(current.actions, signal.actionId)+ : 'failed';const stamp = (iso: string) =>new Date(iso).toLocaleDateString('en-US', {@@ -721,13 +729,16 @@ export function SignalEvidenceBlock({ signal, brandId }: { signal: Signal; brand<li key={action.id}><Linkhref={`/dashboard/action-center/actions?action=${action.id}`}- className="inline-flex items-start gap-1 rounded-md border px-2.5 py-1 font-medium hover:bg-muted"+ className="flex items-center justify-between gap-2 rounded-md border px-2.5 py-1.5 hover:bg-muted">- {t('actionLabel', {- no: action.actionNo,- title: actionTexts(action, tActions).title,- })}- <ArrowUpRight className="h-3 w-3" />+ <span className="inline-flex min-w-0 items-start gap-1 font-medium">+ {t('actionLabel', {+ no: action.actionNo,+ title: actionTexts(action, tActions).title,+ })}+ <ArrowUpRight className="mt-px h-3 w-3 shrink-0" />+ </span>+ <ActionStatusBadge status={action.status} /></Link></li>))}diff --git a/web/src/lib/actions/action-signals.test.ts b/web/src/lib/actions/action-signals.test.tsindex d3d1e4aa9..bcb04443d 100644--- a/web/src/lib/actions/action-signals.test.ts+++ b/web/src/lib/actions/action-signals.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';* AC-007 reads. The list counts the signals that support an action now (open* ones it holds); the drawer lists every signal the action took as evidence,* through action_signals, so a closed action keeps the ones that moved on.+ * The other way, a signal's drawer lists every action that took it.*/type Call = [string, ...unknown[]];@@ -34,6 +35,7 @@ vi.mock('@/lib/supabase/server', () => ({vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));const { getActionDetail, getActions } = await import('./action-center');+const { getSignalActions } = await import('./signals');const signalsQuery = () => queries.find((q) => q.table === 'signals')!;@@ -85,3 +87,41 @@ describe('getActionDetail', () => {expect(calls).not.toContainEqual(['eq', 'action_id', 'a1']);});});++describe('getSignalActions', () => {+ it('lists every action that took the signal, through action_signals, the latest first', async () => {+ rows.action_signals = [+ {+ actions: {+ id: 'a2',+ action_no: 12,+ kind: 'recover_lost_citations',+ status: 'new',+ payload: null,+ },+ },+ {+ actions: {+ id: 'a1',+ action_no: 9,+ kind: 'recover_lost_citations',+ status: 'completed',+ payload: {},+ },+ },+ ];+ const actions = await getSignalActions('b1', 's1');++ expect(actions).toEqual([+ { id: 'a2', actionNo: 12, kind: 'recover_lost_citations', status: 'new', payload: {} },+ { id: 'a1', actionNo: 9, kind: 'recover_lost_citations', status: 'completed', payload: {} },+ ]);+ const calls = queries.find((q) => q.table === 'action_signals')!.calls;+ expect(calls[0][1]).toContain('actions!inner(');+ expect(calls).toContainEqual(['eq', 'signal_id', 's1']);+ expect(calls).toContainEqual(['eq', 'actions.brand_id', 'b1']);+ expect(calls).toContainEqual(['order', 'linked_at', { ascending: false }]);+ // Not the actions by the signal's action_id, which names only the current one.+ expect(queries.map((q) => q.table)).toEqual(['action_signals']);+ });+});diff --git a/web/src/lib/actions/signal-status-rescore.test.ts b/web/src/lib/actions/signal-status-rescore.test.tsindex 8549b88e4..e3553f683 100644--- a/web/src/lib/actions/signal-status-rescore.test.ts+++ b/web/src/lib/actions/signal-status-rescore.test.ts@@ -3,11 +3,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';/*** AC-007: when a signal starts or stops supporting its action, the server is* asked to score the action again, after the response has gone. Moves that- * leave the signal open, and signals no action holds, ask for nothing.+ * leave the signal open, and signals no action holds, ask for nothing; copies+ * of one finding that share an action ask once.*/-let previousStatus: string | null;-let actionId: string | null;+let rows: { id: string; status: string; action_id: string | null }[];let writes: Record<string, unknown>[];const fetchMock = vi.fn();@@ -18,25 +18,27 @@ vi.mock('@/lib/supabase/server', () => ({auth: { getSession: async () => ({ data: { session: { access_token: 'token-1' } } }) },from: () => {let patch: Record<string, unknown> | null = null;+ let ids: string[] = [];const chain = {select: () => chain,eq: () => chain,- in: () => chain,+ in: (_column: string, values: string[]) => {+ ids = values;+ return chain;+ },update: (values: Record<string, unknown>) => {patch = values;writes.push(values);return chain;},- // The read before the change, then the updated rows.- then: (resolve: (value: unknown) => unknown) =>- resolve(+ then: (resolve: (value: unknown) => unknown) => {+ const matched = rows.filter((row) => ids.includes(row.id));+ return resolve(patch- ? { data: [{ id: 's1', action_id: actionId }], error: null }- : {- data: previousStatus ? [{ id: 's1', status: previousStatus }] : [],- error: null,- },- ),+ ? { data: matched.map(({ id, action_id }) => ({ id, action_id })), error: null }+ : { data: matched.map(({ id, status }) => ({ id, status })), error: null },+ );+ },};return chain;},@@ -46,8 +48,7 @@ vi.mock('@/lib/supabase/server', () => ({const { updateSignalStatus } = await import('./signals');beforeEach(() => {- previousStatus = 'new';- actionId = 'a1';+ rows = [{ id: 's1', status: 'new', action_id: 'a1' }];writes = [];fetchMock.mockReset();fetchMock.mockResolvedValue({ ok: true, status: 200 });@@ -69,11 +70,21 @@ describe('updateSignalStatus', () => {});it('asks again when a dismissed signal is reopened', async () => {- previousStatus = 'dismissed';+ rows[0].status = 'dismissed';await updateSignalStatus('b1', ['s1'], 'new');expect(fetchMock).toHaveBeenCalledTimes(1);});+ it('asks once for copies of one finding that share an action', async () => {+ rows = [+ { id: 's1', status: 'new', action_id: 'a1' },+ { id: 's2', status: 'new', action_id: 'a1' },+ { id: 's3', status: 'new', action_id: 'a2' },+ ];+ await updateSignalStatus('b1', ['s1', 's2', 's3'], 'dismissed');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+it('asks nothing when the signal stays open', async () => {await updateSignalStatus('b1', ['s1'], 'acknowledged');expect(writes).toHaveLength(1);@@ -81,7 +92,7 @@ describe('updateSignalStatus', () => {});it('asks nothing for a signal no action holds', async () => {- actionId = null;+ rows[0].action_id = null;await updateSignalStatus('b1', ['s1'], 'resolved');expect(fetchMock).not.toHaveBeenCalled();});diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.tsindex d0c672057..2e04a2b7d 100644--- a/web/src/lib/actions/signals.ts+++ b/web/src/lib/actions/signals.ts@@ -22,6 +22,7 @@ import {} from '@/lib/signals/registry';import { SIGNAL_ROW_COLUMNS, mapSignalRows, type Signal, type SignalRow } from '@/lib/signals/map';import { readPromptPlaces } from '@/lib/signals/prompt-places';+import type { ActionStatus } from '@/lib/action-center/registry';export type { Signal } from '@/lib/signals/map';@@ -75,32 +76,31 @@ export interface SignalAction {id: string;actionNo: number;kind: string;- status: string;+ status: ActionStatus;payload: Record<string, unknown>;}/**- * The actions behind a signal's `action_id` (spec §10: signal → action- * traceability). Read when a drawer opens rather than with the list, so the- * list stays one query of signals.+ * Every action a signal has been used by (spec §10: signal → action+ * traceability), through action_signals (AC-007): not only its current+ * `action_id` but the earlier ones it supported, closed ones included, the+ * latest link first. Read when a drawer opens rather than with the list, so+ * the list stays one query of signals.*/-export async function getSignalActions(- brandId: string,- actionIds: string[],-): Promise<SignalAction[]> {- if (actionIds.length === 0) return [];+export async function getSignalActions(brandId: string, signalId: string): Promise<SignalAction[]> {const supabase = await createClient();const { data, error } = await supabase- .from('actions')- .select('id, action_no, kind, status, payload')- .eq('brand_id', brandId)- .in('id', actionIds);+ .from('action_signals')+ .select('actions!inner(id, action_no, kind, status, payload)')+ .eq('signal_id', signalId)+ .eq('actions.brand_id', brandId)+ .order('linked_at', { ascending: false });if (error) throw new Error(error.message);- return (data ?? []).map((row) => ({+ return (data ?? []).map(({ actions: row }) => ({id: row.id,actionNo: Number(row.action_no),kind: row.kind,- status: row.status,+ status: row.status as ActionStatus,payload: (row.payload ?? {}) as Record<string, unknown>,}));}@@ -215,19 +215,23 @@ export async function updateSignalStatus(.select('id, action_id');if (error) throw new Error(error.message);- // When one starts or stops supporting its action, the action's support and- // confidence follow at once, not the next night (AC-007). Acknowledging- // leaves it open, so nothing changes for the action.+ // When a signal starts or stops supporting its action, the action's support+ // and confidence follow at once, not the next night (AC-007). Acknowledging+ // leaves it open, so nothing changes for the action. Copies of one finding+ // move together and usually share their action: it is scored once.const isOpen = (value: unknown) => OPEN_SIGNAL_STATUSES.includes(value as SignalStatus);- const wasOpen = new Map((before ?? []).map((row) => [row.id as string, isOpen(row.status)]));- const moved = (data ?? []).filter(- (row) => row.action_id && wasOpen.get(row.id as string) !== isOpen(status),- );- if (moved.length === 0) return;+ const wasOpen = new Map((before ?? []).map((row) => [row.id, isOpen(row.status)]));+ const byAction = new Map<string, string>();+ for (const row of data ?? []) {+ if (!row.action_id || wasOpen.get(row.id) === isOpen(status)) continue;+ if (!byAction.has(row.action_id)) byAction.set(row.action_id, row.id);+ }+ if (byAction.size === 0) return;const {data: { session },} = await supabase.auth.getSession();- if (session) for (const row of moved) scheduleRescore(row.id as string, session.access_token);+ if (!session) return;+ for (const signalId of byAction.values()) scheduleRescore(signalId, session.access_token);}/**diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 87aaf53ae..c6acdcfdc 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -20,7 +20,7 @@ import {} from '@/lib/prompt-usage-summary';import { mapSignalRows, type SignalRow } from '@/lib/signals/map';import { readPromptPlaces } from '@/lib/signals/prompt-places';-import { signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';+import { currentActionFirst, signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';import { parseTaskDetails } from '@/lib/action-center/task-details';/**@@ -2788,6 +2788,60 @@ export interface ListSignalsParams {limit?: number;}+/** Signal ids per action_signals read: 100 UUIDs keep the request line well under 8KB. */+const SIGNAL_LINK_CHUNK = 100;++type LinkedAction = { id: string; action_no: number; kind: string; status: string };++/**+ * The actions each signal has been used by, through action_signals (AC-007):+ * its current action and the earlier ones, closed ones included, the latest+ * link first. They only add used_by_actions, so a failed read is logged and+ * leaves every signal's list empty rather than taking the signals down.+ */+async function signalActionRefs(+ brandId: string,+ signalIds: string[],+): Promise<Map<string, SignalActionRef[]>> {+ const chunks: string[][] = [];+ for (let i = 0; i < signalIds.length; i += SIGNAL_LINK_CHUNK) {+ chunks.push(signalIds.slice(i, i + SIGNAL_LINK_CHUNK));+ }+ const results = await Promise.all(+ chunks.map((ids) =>+ supabaseAdmin+ .from('action_signals')+ .select('signal_id, actions!inner(id, action_no, kind, status)')+ .in('signal_id', ids)+ .eq('actions.brand_id', brandId)+ .order('linked_at', { ascending: false }),+ ),+ );+ const bySignal = new Map<string, SignalActionRef[]>();+ for (const { data, error } of results) {+ if (error) {+ console.error('[mcp] signal actions read failed:', error.message);+ return new Map();+ }+ // The untyped admin client models the action_signals→actions FK as an+ // array; it is a single action, so peel it off.+ const links =+ (data as unknown as Array<{+ signal_id: string;+ actions: LinkedAction[] | LinkedAction | null;+ }> | null) ?? [];+ for (const link of links) {+ const a = Array.isArray(link.actions) ? (link.actions[0] ?? null) : link.actions;+ if (!a) continue;+ bySignal.set(link.signal_id, [+ ...(bySignal.get(link.signal_id) ?? []),+ { id: a.id, action_no: Number(a.action_no), kind: a.kind, status: a.status },+ ]);+ }+ }+ return bySignal;+}+export async function listSignalsFor(auth: McpAuthContext,params: ListSignalsParams,@@ -2810,32 +2864,19 @@ export async function listSignalsFor(// Each signal also says where it happened, what changed with units and// period, what it rests on, and which actions use it (AC-001), the same- // way the dashboard's signal drawer does.- const actionIds = [...new Set(rows.map((row) => row.action_id).filter(Boolean))] as string[];- const [prompts, actionsRes] = await Promise.all([+ // way the dashboard's signal drawer does. A signal is linked to an action+ // only by becoming its current one, so those without one have no links.+ const [prompts, actions] = await Promise.all([readPromptPlaces(supabaseAdmin, params.brandId),- actionIds.length- ? supabaseAdmin- .from('actions')- .select('id, action_no, kind, status')- .eq('brand_id', params.brandId)- .in('id', actionIds)- : Promise.resolve({ data: [], error: null }),+ signalActionRefs(+ params.brandId,+ rows.filter((row) => row.action_id).map((row) => row.id),+ ),]);- // The actions only add used_by_actions; a failed read leaves it empty- // rather than taking the signals down with it.- if (actionsRes.error)- console.error('[mcp] signal actions read failed:', actionsRes.error.message);- const actions = new Map<string, SignalActionRef>(- (actionsRes.error ? [] : (actionsRes.data ?? [])).map((a) => [- a.id,- { id: a.id, action_no: Number(a.action_no), kind: a.kind, status: a.status },- ]),- );const known = new Map(mapSignalRows(rows, prompts).map((signal) => [signal.id, signal]));return rows.map((row) => {- const used = row.action_id && actions.has(row.action_id) ? [actions.get(row.action_id)!] : [];+ const used = currentActionFirst(actions.get(row.id) ?? [], row.action_id);const signal = known.get(row.id);// A kind this build has no detail for still comes back, as it always did.return signaldiff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 86345e9bd..fc5789305 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -976,7 +976,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'list_signals',{description:- "List the signals the Action Center detected for a brand: measured changes such as a visibility drop, a competitor gaining citations or a page losing AI traffic. Newest first. Each signal carries its raw row (previous_value, current_value, change_value, payload, action_id) and, read from it: `where` (the prompt, topic, platforms with names, locations, domain, competitor or pages it is about; a field is null when no detector records it yet), `change` (labelled figures: metric, role such as before/after or you/competitor, value, unit and the period it covers, e.g. 'week_over_week', given per figure since one finding can mix windows; null when the signal records no figures), `evidence` (first and last detection, and app paths that show the underlying answers) and `used_by_actions` (the actions built on it). Prefer `change` over the raw value columns: their meaning differs per signal kind. Use this to explain why an action exists or what has changed recently.",+ "List the signals the Action Center detected for a brand: measured changes such as a visibility drop, a competitor gaining citations or a page losing AI traffic. Newest first. Each signal carries its raw row (previous_value, current_value, change_value, payload, action_id) and, read from it: `where` (the prompt, topic, platforms with names, locations, domain, competitor or pages it is about; a field is null when no detector records it yet), `change` (labelled figures: metric, role such as before/after or you/competitor, value, unit and the period it covers, e.g. 'week_over_week', given per figure since one finding can mix windows; null when the signal records no figures), `evidence` (first and last detection, and app paths that show the underlying answers) and `used_by_actions` (every action built on it, closed ones too, the latest first). Prefer `change` over the raw value columns: their meaning differs per signal kind. Use this to explain why an action exists or what has changed recently.",inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),status: zdiff --git a/web/src/lib/mcp/signals.test.ts b/web/src/lib/mcp/signals.test.tsindex da5e478e4..c303e9b48 100644--- a/web/src/lib/mcp/signals.test.ts+++ b/web/src/lib/mcp/signals.test.ts@@ -3,25 +3,37 @@ import type { McpAuthContext } from '@/lib/mcp-auth';/*** list_signals returns each signal's raw row plus the detail the dashboard's- * drawer shows (AC-001): where, change, evidence and used_by_actions. These- * pin that a kind this build doesn't know still comes back as it always did,- * and that a failed actions read costs used_by_actions, not the signals.+ * drawer shows (AC-001): where, change, evidence and used_by_actions, every+ * action a signal was linked to (AC-007). These pin that a kind this build+ * doesn't know still comes back as it always did, and that a failed actions+ * read costs used_by_actions, not the signals.*/let rows: Record<string, unknown[]> = {};let errors: Record<string, { message: string } | null> = {};+let linkReads: string[][] = [];function builder(table: string) {+ let ids: string[] | null = null;const chain = {select: () => chain,eq: () => chain,order: () => chain,limit: () => chain,- in: () => chain,+ in: (_column: string, values: string[]) => {+ ids = values;+ if (table === 'action_signals') linkReads.push(values);+ return chain;+ },range: () => chain,maybeSingle: async () => ({ data: table === 'brands' ? { id: 'b1' } : null, error: null }),- then: (resolve: (v: { data: unknown[]; error: { message: string } | null }) => void) =>- resolve({ data: rows[table] ?? [], error: errors[table] ?? null }),+ then: (resolve: (v: { data: unknown[]; error: { message: string } | null }) => void) => {+ const data = (rows[table] ?? []).filter(+ (row) =>+ table !== 'action_signals' || ids!.includes((row as { signal_id: string }).signal_id),+ );+ resolve({ data, error: errors[table] ?? null });+ },};return chain;}@@ -60,6 +72,7 @@ const row = (over: Record<string, unknown>) => ({beforeEach(() => {errors = {};+ linkReads = [];rows = {signals: [row({}), row({ id: 's2', kind: 'retired_kind', action_id: null, payload: {} })],prompts: [@@ -72,7 +85,17 @@ beforeEach(() => {topics: { name: 'Coffee' },},],- actions: [{ id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' }],+ // The latest link first: the current action, then a closed one before it.+ action_signals: [+ {+ signal_id: 's1',+ actions: { id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' },+ },+ {+ signal_id: 's1',+ actions: { id: 'a0', action_no: 31, kind: 'recover_lost_citations', status: 'completed' },+ },+ ],};});@@ -92,15 +115,42 @@ describe('listSignalsFor', () => {},change: null,evidence: { links: [{ kind: 'prompt_answers', path: '/dashboard/prompts/p1' }] },- used_by_actions: [{ id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' }],+ used_by_actions: [+ { id: 'a1', action_no: 52, kind: 'recover_lost_citations', status: 'new' },+ { id: 'a0', action_no: 31, kind: 'recover_lost_citations', status: 'completed' },+ ],});// A kind this build has no copy for keeps its raw row.expect(unknown).toMatchObject({ id: 's2', kind: 'retired_kind', used_by_actions: [] });expect(unknown).not.toHaveProperty('where');+ // Only signals with an action are looked up: s2 has none.+ expect(linkReads).toEqual([['s1']]);+ });++ it("puts the signal's current action first when its link is older", async () => {+ rows.signals = [row({ action_id: 'a0' })];+ const [known] = (await listSignalsFor(auth, { brandId: 'b1' }))!;+ expect((known.used_by_actions as { id: string }[]).map((a) => a.id)).toEqual(['a0', 'a1']);+ });++ it('reads the links of a full page in chunks of 100 signals', async () => {+ rows.signals = Array.from({ length: 150 }, (_, i) => row({ id: `s${i + 1}` }));+ rows.action_signals.push({+ signal_id: 's150',+ actions: { id: 'a9', action_no: 77, kind: 'recover_lost_citations', status: 'new' },+ });+ const signals = (await listSignalsFor(auth, { brandId: 'b1', limit: 150 }))!;++ expect(linkReads.map((ids) => ids.length)).toEqual([100, 50]);+ expect(signals[0].used_by_actions).toHaveLength(2);+ expect(signals[149].used_by_actions).toEqual([+ { id: 'a9', action_no: 77, kind: 'recover_lost_citations', status: 'new' },+ ]);+ expect(signals[1].used_by_actions).toEqual([]);});it('still returns the signals when the actions read fails', async () => {- errors.actions = { message: 'timeout' };+ errors.action_signals = { message: 'timeout' };vi.spyOn(console, 'error').mockImplementation(() => {});const [known] = (await listSignalsFor(auth, { brandId: 'b1' }))!;expect(known).toMatchObject({ id: 's1', used_by_actions: [] });diff --git a/web/src/lib/signals/detail.test.ts b/web/src/lib/signals/detail.test.tsindex baf195550..c09ec20e1 100644--- a/web/src/lib/signals/detail.test.ts+++ b/web/src/lib/signals/detail.test.ts@@ -1,7 +1,13 @@import { describe, expect, it } from 'vitest';import type { Signal } from './map';import { NO_WHERE } from './where';-import { signalChange, signalDetailForApi, signalLinks, signalWhereFields } from './detail';+import {+ currentActionFirst,+ signalChange,+ signalDetailForApi,+ signalLinks,+ signalWhereFields,+} from './detail';const signal = (over: Partial<Signal>): Signal => ({id: 's1',@@ -249,6 +255,21 @@ describe('signalLinks', () => {});});+describe('currentActionFirst', () => {+ const byLink = [{ id: 'b' }, { id: 'a' }, { id: 'c' }];++ it("puts the signal's current action first and keeps the others by latest link", () => {+ // A signal that rejoined a reopened action keeps that link's first date.+ expect(currentActionFirst(byLink, 'a').map((a) => a.id)).toEqual(['a', 'b', 'c']);+ expect(currentActionFirst(byLink, 'b').map((a) => a.id)).toEqual(['b', 'a', 'c']);+ });++ it('leaves the order when the current action is not among them', () => {+ expect(currentActionFirst(byLink, null).map((a) => a.id)).toEqual(['b', 'a', 'c']);+ expect(currentActionFirst(byLink, 'z').map((a) => a.id)).toEqual(['b', 'a', 'c']);+ });+});+describe('signalDetailForApi', () => {it('returns the same detail with snake_case keys, units and named platforms', () => {const detail = signalDetailForApi({ ...lostCitation, actionId: 'a1' }, [diff --git a/web/src/lib/signals/detail.ts b/web/src/lib/signals/detail.tsindex 1a771884a..46776ab5e 100644--- a/web/src/lib/signals/detail.ts+++ b/web/src/lib/signals/detail.ts@@ -1222,6 +1222,22 @@ export interface SignalActionRef {status: string;}+/**+ * A signal's actions as "Used by actions" lists them: its current action+ * (`signals.action_id`) first, then the others by their latest link. The+ * link date alone can put an older action first: a signal that rejoins a+ * reopened action keeps that link's first date.+ */+export function currentActionFirst<T extends { id: string }>(+ actions: T[],+ currentId: string | null,+): T[] {+ return [+ ...actions.filter((action) => action.id === currentId),+ ...actions.filter((action) => action.id !== currentId),+ ];+}+/*** A signal's detail in the shape the MCP tools return (AC-001: "the signal* API/MCP returns the same structured fields"): snake_case keys, a null for