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.

fix(action-center): show an action's count, less what was removed since, everywhere (AC-009, 2/3) (#1389)

Cihan2baaddb5d100
diff --git a/web/messages/en.json b/web/messages/en.json
index 89d9ed0ac..fa154f63d 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -895,6 +895,11 @@
"regions": "{count, plural, one {# region} other {# regions}}",
"competitors": "{count, plural, one {# competitor} other {# competitors}}"
},
+ "removed": {
+ "note": "({items} removed since this action was created)",
+ "hover": "No longer tracked since this action was created: {names}",
+ "hoverMore": "No longer tracked since this action was created: {names} and {more} more"
+ },
"menu": {
"label": "Actions for this item"
},
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index d133589a8..bf4b84cf1 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { toast } from 'sonner';
import { ChevronRight, Plus, Trash2 } from 'lucide-react';
+import { RemovedNote } from '@/components/action-center/removed-note';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -416,6 +417,7 @@ export function ActionDrawer({
{tag}
</Badge>
))}
+ <RemovedNote payload={action.payload ?? {}} />
</div>
</SheetHeader>
diff --git a/web/src/components/action-center/action-table.test.tsx b/web/src/components/action-center/action-table.test.tsx
index 106acf648..f49db384b 100644
--- a/web/src/components/action-center/action-table.test.tsx
+++ b/web/src/components/action-center/action-table.test.tsx
@@ -133,6 +133,33 @@ describe('ActionTable row menu', () => {
describe('ActionTable assignee', () => {
const assigneeCell = () => container.querySelectorAll('tbody tr td')[3];
+ it('counts what is left, and says what was removed since (AC-009)', () => {
+ render({
+ actions: [
+ {
+ ...action,
+ // As getActions reads it: 13 prompts when created, one deleted since.
+ payload: {
+ targetEntity: 'prompts',
+ targetCount: 12,
+ createdTargetCount: 13,
+ removedCount: 1,
+ removedLabels: ['best crm for agents'],
+ },
+ },
+ ],
+ });
+ const row = container.querySelector('tbody tr')!;
+ expect(row.textContent).toContain('12 prompts');
+ // A button, so focus shows the names as hover does; a click stays on it.
+ const note = [...row.querySelectorAll<HTMLButtonElement>('button')].find((el) =>
+ el.textContent?.includes('removed since'),
+ )!;
+ expect(note.textContent).toBe('(1 prompt removed since this action was created)');
+ act(() => note.click());
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
it('shows an action with no one on it as Everyone', () => {
render();
expect(assigneeCell().textContent).toBe('Everyone');
diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsx
index cb60bb8ae..86eaa9209 100644
--- a/web/src/components/action-center/action-table.tsx
+++ b/web/src/components/action-center/action-table.tsx
@@ -19,6 +19,7 @@ import {
Target,
X,
} from 'lucide-react';
+import { RemovedNote } from '@/components/action-center/removed-note';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
@@ -338,6 +339,7 @@ export function ActionTable({
{tag}
</Badge>
))}
+ <RemovedNote payload={action.payload ?? {}} />
</div>
</div>
</div>
diff --git a/web/src/components/action-center/removed-note.tsx b/web/src/components/action-center/removed-note.tsx
new file mode 100644
index 000000000..f3051f8b4
--- /dev/null
+++ b/web/src/components/action-center/removed-note.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { removedTargets } from '@/lib/action-center/entity-counts';
+
+/**
+ * "(1 prompt removed since this action was created)" beside an action's
+ * count (AC-009): prompts deleted or paused, or competitors deleted, since
+ * the action kept its list. Hover or focus names them. Nothing when none
+ * were. A click on it stays on it: in a table row, it doesn't open the drawer.
+ */
+export function RemovedNote({ payload }: { payload: Record<string, unknown> }) {
+ const t = useTranslations('actionCenter.actionsPage');
+ const removed = removedTargets(payload);
+ if (!removed) return null;
+ const entity = typeof payload.targetEntity === 'string' ? payload.targetEntity : null;
+ const note = t('removed.note', {
+ items: entity ? t(`tags.${entity}`, { count: removed.count }) : String(removed.count),
+ });
+ if (removed.labels.length === 0) {
+ return <span className="self-center text-[10px] text-muted-foreground">{note}</span>;
+ }
+ const names = removed.labels.join(', ');
+ const more = removed.count - removed.labels.length;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={300}
+ closeDelay={0}
+ render={
+ <button
+ type="button"
+ onClick={(event) => event.stopPropagation()}
+ className="cursor-help self-center rounded-sm text-[10px] text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ />
+ }
+ >
+ {note}
+ </TooltipTrigger>
+ <TooltipContent className="max-w-80 text-left">
+ {more > 0 ? t('removed.hoverMore', { names, more }) : t('removed.hover', { names })}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/web/src/components/action-center/use-action-story.ts b/web/src/components/action-center/use-action-story.ts
index 199e6c842..c7524196f 100644
--- a/web/src/components/action-center/use-action-story.ts
+++ b/web/src/components/action-center/use-action-story.ts
@@ -92,6 +92,7 @@ export function useActionStory(
volumes,
createdAt: action.createdAt,
dueDate: action.dueDate,
+ payload: action.payload ?? {},
},
tStory,
{
diff --git a/web/src/lib/action-center/affected.test.ts b/web/src/lib/action-center/affected.test.ts
index 9003ba15b..ebdefddbf 100644
--- a/web/src/lib/action-center/affected.test.ts
+++ b/web/src/lib/action-center/affected.test.ts
@@ -177,6 +177,31 @@ describe('affectedOf', () => {
]);
});
+ it('lists a mention review’s first prompt once, though it is its first target too', () => {
+ const payload = {
+ promptText: 'Best coffee subscriptions?',
+ promptIds: ['p1', 'p2'],
+ targetEntity: 'prompts',
+ targetCount: 2,
+ targets: ['Best coffee subscriptions?', 'Cheapest beans online?'],
+ };
+ const affected = affectedOf([], payload);
+ expect(affected.prompts.map((p) => p.text)).toEqual([
+ 'Best coffee subscriptions?',
+ 'Cheapest beans online?',
+ ]);
+ expect(affected.promptTotal).toBe(2);
+ // Removed since (AC-009): gone by its text, the label the action kept for it.
+ const left = affectedOf([], {
+ ...payload,
+ targetCount: 1,
+ removedKeys: ['p1'],
+ removedLabels: ['Best coffee subscriptions?'],
+ });
+ expect(left.prompts.map((p) => p.text)).toEqual(['Cheapest beans online?']);
+ expect(left.promptTotal).toBe(1);
+ });
+
it('is empty for an action with nothing to list', () => {
expect(affectedOf([], {})).toMatchObject({ prompts: [], pages: [], promptTotal: 0 });
});
diff --git a/web/src/lib/action-center/affected.ts b/web/src/lib/action-center/affected.ts
index fc383aae4..73ed0a8d1 100644
--- a/web/src/lib/action-center/affected.ts
+++ b/web/src/lib/action-center/affected.ts
@@ -82,11 +82,47 @@ const urlsOf = (value: WhereValue | null): string[] =>
/**
* The action's affected items, from the signals that support it. With none
- * (an action a person sent), from what it was sent about.
+ * (an action a person sent), from what it was sent about. Its prompts or
+ * pages count as the action counts them (AC-009): the list it kept when it
+ * was created, less what was removed since, not the signals the nightly
+ * pass rewrites; the rows still show what the signals say about each.
*/
export function affectedOf(signals: Signal[], payload: Record<string, unknown> = {}): Affected {
- if (signals.length === 0) return affectedFromPayload(payload);
+ const out = signals.length === 0 ? affectedFromPayload(payload) : affectedOfSignals(signals);
+ // What was removed since (withEntityCounts) isn't listed: by its key (a
+ // prompt's id, or its text where it has none), a competitor by its name.
+ const strings = (value: unknown) =>
+ new Set(Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []);
+ const keys = strings(payload.removedKeys);
+ const labels = strings(payload.removedLabels);
+ const count = typeof payload.targetCount === 'number' ? payload.targetCount : 0;
+ if (payload.targetEntity === 'prompts') {
+ const listed = out.prompts.length;
+ // A prompt listed by its text alone (a topic's, a mention review's: kept
+ // by their ids, listed as texts) is matched by the text 00244 keeps as its
+ // label. The RPC names only the first 20 removed, so past those such a
+ // row can stay listed.
+ const removed = (row: AffectedPrompt) =>
+ keys.has(row.id ?? row.text) || (row.id === null && labels.has(row.text));
+ if (keys.size > 0 || labels.size > 0) out.prompts = out.prompts.filter((row) => !removed(row));
+ out.promptTotal = Math.max(0, out.promptTotal - (listed - out.prompts.length));
+ // A count is never shown with nothing behind it.
+ if (count > 0 && out.prompts.length > 0) out.promptTotal = count;
+ }
+ if (payload.targetEntity === 'pages') {
+ const listed = out.pages.length;
+ if (keys.size > 0) out.pages = out.pages.filter((row) => !keys.has(row.url));
+ out.pageTotal = Math.max(0, out.pageTotal - (listed - out.pages.length));
+ if (count > 0 && out.pages.length > 0) out.pageTotal = count;
+ }
+ if (payload.targetEntity === 'competitors') {
+ const names = strings(payload.removedLabels);
+ if (names.size > 0) out.competitors = out.competitors.filter((name) => !names.has(name));
+ }
+ return out;
+}
+function affectedOfSignals(signals: Signal[]): Affected {
const prompts = new Map<string, AffectedPrompt>();
const pages = new Map<string, AffectedPage>();
const out: Affected = empty();
@@ -277,15 +313,22 @@ function affectedFromPayload(payload: Record<string, unknown>): Affected {
topics: [],
});
}
- const targets = (Array.isArray(payload.targets) ? payload.targets : []) as Record<
- string,
- unknown
- >[];
+ const targets: unknown[] = Array.isArray(payload.targets) ? payload.targets : [];
const entity = str(payload.targetEntity);
- for (const target of targets) {
+ // A prompt once: a mention review's promptText is its first target too.
+ const listed = new Set(out.prompts.map((row) => row.id ?? row.text));
+ for (const raw of targets) {
+ // A target is { id, label }, or (topics, mentions) its text alone.
+ const target = (typeof raw === 'string' ? { label: raw } : (raw ?? {})) as Record<
+ string,
+ unknown
+ >;
const label = str(target.label) || str(target.id);
if (!label) continue;
if (entity === 'prompts') {
+ const key = str(target.id) || label;
+ if (listed.has(key)) continue;
+ listed.add(key);
out.prompts.push({
id: str(target.id) || null,
text: label,
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index c047cf054..d4b609399 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -116,6 +116,27 @@ describe('actionTexts', () => {
(key: string) => key,
);
expect(tags).not.toContain('tags.signals');
+ // Every prompt removed since (AC-009): its plain title, never "0 prompts".
+ const none = { mentionCount: 2, negativeCount: 0, promptCount: 0 };
+ expect(actionTexts(action({ kind: 'mention_review', payload: none }), t).title).toBe(
+ t('mention_review.titleGeneric'),
+ );
+ // Its first prompt removed, the one left isn't the one promptText names.
+ const left = {
+ mentionCount: 3,
+ negativeCount: 0,
+ promptCount: 1,
+ promptText: 'Best beans?',
+ promptIds: ['p1', 'p2'],
+ removedKeys: ['p1'],
+ };
+ expect(actionTexts(action({ kind: 'mention_review', payload: left }), t).title).toBe(
+ t('mention_review.titleMany', { count: 1 }),
+ );
+ const otherRemoved = { ...left, removedKeys: ['p2'] };
+ expect(actionTexts(action({ kind: 'mention_review', payload: otherRemoved }), t).title).toBe(
+ 'Improve how AI describes you for "Best beans?"',
+ );
});
it('names a topic opportunity after its topic and demand (VIS-011)', () => {
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index f5300c2f2..f02904638 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -131,11 +131,20 @@ export function actionTexts(
typeof p.promptCount === 'number'
) {
const negative = typeof p.negativeCount === 'number' ? p.negativeCount : 0;
+ // promptText is the first prompt's: once it is removed (AC-009), the one
+ // left is another, so the title counts instead of naming it.
+ const firstRemoved =
+ Array.isArray(p.promptIds) &&
+ Array.isArray(p.removedKeys) &&
+ p.removedKeys.includes(p.promptIds[0]);
return {
title:
- p.promptCount === 1 && typeof p.promptText === 'string' && p.promptText
+ p.promptCount === 1 && typeof p.promptText === 'string' && p.promptText && !firstRemoved
? t(`${action.kind}.title`, { prompt: p.promptText })
- : t(`${action.kind}.titleMany`, { count: p.promptCount }),
+ : p.promptCount > 0
+ ? t(`${action.kind}.titleMany`, { count: p.promptCount })
+ : // Every prompt removed since (AC-009): no "0 prompts".
+ t(`${action.kind}.titleGeneric`),
description:
negative > 0
? t(`${action.kind}.descriptionNegative`, { count: p.mentionCount, negative })
diff --git a/web/src/lib/action-center/entity-counts.test.ts b/web/src/lib/action-center/entity-counts.test.ts
new file mode 100644
index 000000000..fe46a7602
--- /dev/null
+++ b/web/src/lib/action-center/entity-counts.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { SupabaseClient } from '@supabase/supabase-js';
+import {
+ currentPriorityReason,
+ currentTaskParams,
+ readEntityCounts,
+ removedTargets,
+ withEntityCounts,
+ withoutTargetIds,
+ type EntityCountRow,
+} from './entity-counts';
+import { affectedOf } from './affected';
+
+const row = (over: Partial<EntityCountRow> = {}): EntityCountRow => ({
+ action_id: 'a1',
+ entity_type: 'prompts',
+ total: 13,
+ removed: 1,
+ removed_labels: ['best crm for agents'],
+ removed_keys: ['p1'],
+ ...over,
+});
+
+describe('withEntityCounts (AC-009)', () => {
+ it('reads the count left, and says what was removed', () => {
+ const payload = { targetEntity: 'prompts', targetCount: 13, promptCount: 13 };
+ const now = withEntityCounts(payload, [row()]);
+ expect(now).toMatchObject({
+ targetCount: 12,
+ promptCount: 12,
+ createdTargetCount: 13,
+ removedCount: 1,
+ removedLabels: ['best crm for agents'],
+ });
+ expect(removedTargets(now)).toEqual({ count: 1, labels: ['best crm for agents'] });
+ });
+
+ it('leaves an action with nothing removed, or another list, as it was', () => {
+ const payload = { targetEntity: 'prompts', targetCount: 13 };
+ expect(withEntityCounts(payload, [row({ removed: 0 })])).toBe(payload);
+ expect(withEntityCounts(payload, [row({ entity_type: 'pages' })])).toBe(payload);
+ expect(withEntityCounts(payload, undefined)).toBe(payload);
+ expect(removedTargets(payload)).toBeNull();
+ });
+
+ it('never counts below none', () => {
+ const now = withEntityCounts({ targetEntity: 'prompts', targetCount: 2 }, [
+ row({ removed: 5 }),
+ ]);
+ expect(now).toMatchObject({ targetCount: 0, removedCount: 2 });
+ });
+});
+
+describe('currentTaskParams', () => {
+ const payload = withEntityCounts({ targetEntity: 'prompts', targetCount: 13 }, [row()]);
+
+ it('names the count left in a task that named the action’s', () => {
+ expect(currentTaskParams({ count: 13, entity: 'prompts' }, payload)).toEqual({
+ count: 12,
+ entity: 'prompts',
+ });
+ });
+
+ it('names no count once none is left, so the plain title reads', () => {
+ const none = withEntityCounts({ targetEntity: 'prompts', targetCount: 1 }, [row({ total: 1 })]);
+ expect(currentTaskParams({ count: 1, entity: 'prompts', page: '/x' }, none)).toEqual({
+ page: '/x',
+ });
+ });
+
+ it('keeps any other count as written', () => {
+ const params = { count: 4, entity: 'pages' };
+ expect(currentTaskParams(params, payload)).toBe(params);
+ expect(currentTaskParams(undefined, payload)).toBeUndefined();
+ });
+});
+
+describe('the affected list’s count', () => {
+ it('counts as the action does, not as the signals now say', () => {
+ const payload = withEntityCounts(
+ {
+ targetEntity: 'prompts',
+ targetCount: 13,
+ targets: [{ id: 'p2', label: 'one' }],
+ },
+ [row()],
+ );
+ expect(affectedOf([], payload).promptTotal).toBe(12);
+ });
+
+ it('lists none of what was removed, by its id', () => {
+ const payload = withEntityCounts(
+ {
+ targetEntity: 'prompts',
+ targetCount: 3,
+ targets: [
+ { id: 'p1', label: 'best crm for agents' },
+ // Another prompt with the same text stays.
+ { id: 'p3', label: 'best crm for agents' },
+ { id: 'p2', label: 'crm pricing' },
+ ],
+ },
+ [row({ total: 3 })],
+ );
+ const affected = affectedOf([], payload);
+ expect(affected.prompts.map((p) => p.id)).toEqual(['p3', 'p2']);
+ expect(affected.promptTotal).toBe(2);
+ });
+
+ it('lists none of what was removed where it lists prompts by text, by its label', () => {
+ // A topic gap keeps its prompts by id and lists them as texts: 00244
+ // keeps a removed one's text as its label.
+ const payload = withEntityCounts(
+ {
+ targetEntity: 'prompts',
+ targetCount: 2,
+ promptIds: ['p1', 'p2'],
+ targets: ['best crm for agents', 'crm pricing'],
+ },
+ [row({ total: 2 })],
+ );
+ expect(payload).toMatchObject({ removedKeys: ['p1'], removedLabels: ['best crm for agents'] });
+ const affected = affectedOf([], payload);
+ expect(affected.prompts.map((p) => p.text)).toEqual(['crm pricing']);
+ expect(affected.promptTotal).toBe(1);
+ });
+
+ it('lists targets given as text, and shows no count with nothing behind it', () => {
+ const named = affectedOf([], {
+ targetEntity: 'prompts',
+ targetCount: 2,
+ targets: ['crm pricing', 'crm for agents'],
+ });
+ expect(named.prompts.map((p) => p.text)).toEqual(['crm pricing', 'crm for agents']);
+ expect(named.promptTotal).toBe(2);
+ const bare = affectedOf([], { targetEntity: 'prompts', targetCount: 9 });
+ expect(bare.promptTotal).toBe(0);
+ });
+});
+
+describe('readEntityCounts', () => {
+ it('reads the counts in calls of 500, by action', async () => {
+ const rpc = vi.fn(async (_fn: string, args: { p_action_ids: string[] }) => ({
+ data: args.p_action_ids.slice(0, 1).map((id) => row({ action_id: id })),
+ error: null,
+ }));
+ const ids = Array.from({ length: 501 }, (_, i) => `a${i}`);
+ const counts = await readEntityCounts({ rpc } as unknown as SupabaseClient, ids);
+ expect(rpc).toHaveBeenCalledTimes(2);
+ expect(rpc.mock.calls[0][1].p_action_ids).toHaveLength(500);
+ expect([...counts.keys()]).toEqual(['a0', 'a500']);
+ });
+
+ it('leaves the actions as created when the counts can’t be read', async () => {
+ const rpc = vi.fn(async () => ({
+ data: null,
+ error: { code: 'PGRST202', message: 'missing' },
+ }));
+ const counts = await readEntityCounts({ rpc } as unknown as SupabaseClient, ['a1']);
+ expect(counts.size).toBe(0);
+ });
+});
+
+describe('currentPriorityReason', () => {
+ it('names the count left where the reason named the action’s', () => {
+ const payload = withEntityCounts({ targetEntity: 'prompts', targetCount: 13 }, [row()]);
+ const reason = { subject: { entity: 'prompts', count: 13 }, days: 2 };
+ expect(currentPriorityReason(reason, payload)).toEqual({
+ subject: { entity: 'prompts', count: 12 },
+ days: 2,
+ });
+ const other = { subject: { entity: 'pages', count: 13 } };
+ expect(currentPriorityReason(other, payload)).toBe(other);
+ expect(currentPriorityReason(null, payload)).toBeNull();
+ });
+});
+
+describe('withoutTargetIds', () => {
+ it('drops a big group’s ids from a signal, and leaves the rest', () => {
+ const row = { id: 's1', payload: { targets: [1], targetIds: ['a', 'b'] } };
+ expect(withoutTargetIds(row)).toEqual({ id: 's1', payload: { targets: [1] } });
+ const plain = { id: 's2', payload: { targets: [1] } };
+ expect(withoutTargetIds(plain)).toBe(plain);
+ });
+});
diff --git a/web/src/lib/action-center/entity-counts.ts b/web/src/lib/action-center/entity-counts.ts
new file mode 100644
index 000000000..7ae9c193f
--- /dev/null
+++ b/web/src/lib/action-center/entity-counts.ts
@@ -0,0 +1,181 @@
+import type { SupabaseClient } from '@supabase/supabase-js';
+
+/**
+ * AC-009: one count for an action, everywhere.
+ *
+ * An action keeps the list of what it is about (its prompts, pages,
+ * competitors…) once, when it is created (action_entities, 00244). Its
+ * payload's `targetCount` is that list's size then; a prompt deleted or
+ * paused since, or a competitor deleted, is marked removed. Every place reads
+ * the action as `withEntityCounts` leaves it: the count less the removed,
+ * and which were removed, so the title, the chips, the tasks, the detail,
+ * Copy all and the exports all say "12 prompts (1 removed since this action
+ * was created)".
+ */
+
+/** One row of action_entity_counts (00244). */
+export interface EntityCountRow {
+ action_id: string;
+ entity_type: string;
+ /** How many the action was made with, removed ones included. */
+ total: number;
+ removed: number;
+ removed_labels: string[] | null;
+ /** The removed ones' keys (a prompt's id…), to leave them out of a list. */
+ removed_keys?: string[] | null;
+}
+
+/** What was removed from an action's list since it was created. */
+export interface RemovedTargets {
+ count: number;
+ /** Their names, up to 20, for the hover. */
+ labels: string[];
+}
+
+/** Payload counts that name the same list as targetCount, in the kinds that have them. */
+const SAME_LIST_COUNTS = ['promptCount', 'pageCount'] as const;
+
+const numberOf = (value: unknown) => (typeof value === 'number' ? value : Number(value ?? 0));
+
+/**
+ * The payload as the action reads now: `targetCount` (and a promptCount or
+ * pageCount that counted the same list) less what was removed, with
+ * `createdTargetCount`, `removedCount` and `removedLabels` to say so. An
+ * action with nothing removed, or whose list is of another kind than its
+ * count, reads as it was.
+ */
+export function withEntityCounts(
+ payload: Record<string, unknown>,
+ rows: EntityCountRow[] | undefined,
+): Record<string, unknown> {
+ const entity = typeof payload.targetEntity === 'string' ? payload.targetEntity : null;
+ const created = numberOf(payload.targetCount);
+ const row = entity ? rows?.find((r) => r.entity_type === entity) : undefined;
+ if (!row || row.removed <= 0 || !(created > 0)) return payload;
+
+ const removed = Math.min(row.removed, created);
+ const next: Record<string, unknown> = {
+ ...payload,
+ targetCount: created - removed,
+ createdTargetCount: created,
+ removedCount: removed,
+ removedLabels: (row.removed_labels ?? []).filter(Boolean).slice(0, Math.min(20, removed)),
+ removedKeys: (row.removed_keys ?? []).filter(Boolean),
+ };
+ for (const key of SAME_LIST_COUNTS) {
+ if (numberOf(payload[key]) === created) next[key] = created - removed;
+ }
+ return next;
+}
+
+/** What an action lost since it was created, as withEntityCounts noted it; null when nothing. */
+export function removedTargets(payload: Record<string, unknown>): RemovedTargets | null {
+ const count = numberOf(payload.removedCount);
+ if (!(count > 0)) return null;
+ const labels = Array.isArray(payload.removedLabels)
+ ? payload.removedLabels.filter((l): l is string => typeof l === 'string')
+ : [];
+ return { count, labels };
+}
+
+/**
+ * A planned task's title parameters as the action reads now: a task that
+ * named the action's own count ("across 13 prompts") names the count left.
+ * With none left it names no count, and reads as its plain title.
+ */
+export function currentTaskParams(
+ params: Record<string, string | number> | undefined,
+ payload: Record<string, unknown>,
+): Record<string, string | number> | undefined {
+ if (!params) return params;
+ const created = numberOf(payload.createdTargetCount);
+ if (
+ !(created > 0) ||
+ params.entity !== payload.targetEntity ||
+ numberOf(params.count) !== created
+ ) {
+ return params;
+ }
+ const left = numberOf(payload.targetCount);
+ if (left > 0) return { ...params, count: left };
+ return Object.fromEntries(
+ Object.entries(params).filter(([key]) => key !== 'count' && key !== 'entity'),
+ );
+}
+
+/**
+ * A priority reason ("Lost ground on 13 prompts") that named the action's
+ * count names the count left, as the title does.
+ */
+export function currentPriorityReason<T>(reason: T, payload: Record<string, unknown>): T {
+ const subject = (reason as { subject?: { entity?: unknown; count?: unknown } } | null)?.subject;
+ const created = numberOf(payload.createdTargetCount);
+ if (
+ !subject ||
+ !(created > 0) ||
+ subject.entity !== payload.targetEntity ||
+ numberOf(subject.count) !== created
+ ) {
+ return reason;
+ }
+ return {
+ ...(reason as object),
+ subject: { ...subject, count: numberOf(payload.targetCount) },
+ } as T;
+}
+
+/**
+ * Only what tells which targets were removed: for a list told from part of
+ * an action's signals (its Why), which leaves them out but keeps its own count.
+ */
+export function removedOnly(payload: Record<string, unknown>): Record<string, unknown> {
+ return {
+ targetEntity: payload.targetEntity,
+ removedKeys: payload.removedKeys,
+ removedLabels: payload.removedLabels,
+ };
+}
+
+/**
+ * A signal without the ids a big group lists past the 50 it names (AC-009):
+ * up to a thousand keys the action keeps for its count, which no reader of
+ * the signal needs.
+ */
+export function withoutTargetIds<T extends { payload?: unknown }>(row: T): T {
+ const payload = row.payload as Record<string, unknown> | null | undefined;
+ if (!payload || typeof payload !== 'object' || !('targetIds' in payload)) return row;
+ const rest = { ...payload };
+ delete rest.targetIds;
+ return { ...row, payload: rest };
+}
+
+/** The RPC takes up to this many actions a call (00244). */
+export const ENTITY_COUNTS_PER_CALL = 500;
+
+/**
+ * Each action's list counts (action_entity_counts), by action. Read through
+ * the caller's client: the member's own, under their policy, or the admin
+ * one for the MCP. A database without 00244 has none, and a failed read
+ * leaves the actions as created: the count saved then.
+ */
+export async function readEntityCounts(
+ client: SupabaseClient,
+ actionIds: string[],
+): Promise<Map<string, EntityCountRow[]>> {
+ const byAction = new Map<string, EntityCountRow[]>();
+ for (let i = 0; i < actionIds.length; i += ENTITY_COUNTS_PER_CALL) {
+ const { data, error } = await client.rpc('action_entity_counts', {
+ p_action_ids: actionIds.slice(i, i + ENTITY_COUNTS_PER_CALL),
+ });
+ if (error) {
+ if (error.code !== 'PGRST202') console.error('Failed to read action counts:', error.message);
+ return byAction;
+ }
+ for (const row of (data ?? []) as EntityCountRow[]) {
+ const rows = byAction.get(row.action_id) ?? [];
+ rows.push(row);
+ byAction.set(row.action_id, rows);
+ }
+ }
+ return byAction;
+}
diff --git a/web/src/lib/action-center/export-labels.ts b/web/src/lib/action-center/export-labels.ts
index 3ea65d1c5..cd0a14ad7 100644
--- a/web/src/lib/action-center/export-labels.ts
+++ b/web/src/lib/action-center/export-labels.ts
@@ -1,4 +1,5 @@
import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+import { removedTargets } from '@/lib/action-center/entity-counts';
import type { ContentOpportunity, OpportunityBasket } from '@/types';
import {
actionContextTags,
@@ -273,7 +274,8 @@ export function labelActionExport(input: ActionExportInput, t: ExportTranslators
goal: input.story?.goal ?? actionGoal(action.kind, t.texts, action.payload),
category: t.categories(action.category),
status: t.page(`status.${action.status}`),
- tags: actionContextTags(action, t.page),
+ // With what was removed since (AC-009), as the page says it.
+ tags: [...actionContextTags(action, t.page), ...removedTag(action.payload ?? {}, t.page)],
kpis: detail.kpis
.filter((kpi) => related.includes(kpi.kpiKey) && isKpiKey(kpi.kpiKey))
.map(
@@ -306,3 +308,15 @@ export function labelActionExport(input: ActionExportInput, t: ExportTranslators
{ origin, timeZone: input.timeZone },
);
}
+
+/** "(1 prompt removed since this action was created)", as a tag; none when nothing was. */
+function removedTag(payload: Record<string, unknown>, t: ExportTranslators['page']): string[] {
+ const removed = removedTargets(payload);
+ if (!removed) return [];
+ const entity = typeof payload.targetEntity === 'string' ? payload.targetEntity : null;
+ return [
+ t('removed.note', {
+ items: entity ? t(`tags.${entity}`, { count: removed.count }) : String(removed.count),
+ }),
+ ];
+}
diff --git a/web/src/lib/action-center/rows.ts b/web/src/lib/action-center/rows.ts
index 54f8a4e1a..0ae01c9b3 100644
--- a/web/src/lib/action-center/rows.ts
+++ b/web/src/lib/action-center/rows.ts
@@ -14,6 +14,11 @@ import type {
import type { KpiTimeframe } from '@/lib/kpis/registry';
import { parsePriorityReason, storedPriorityLevel } from '@/lib/action-center/priority';
import { parseTaskDetails } from '@/lib/action-center/task-details';
+import {
+ currentPriorityReason,
+ withEntityCounts,
+ type EntityCountRow,
+} from '@/lib/action-center/entity-counts';
/**
* Action Center rows → the shapes the dashboard reads, shared by its server
@@ -56,9 +61,12 @@ export function actionItemFromRow(
taskTotal: number;
taskCompleted: number;
signalCount: number;
+ /** Its list's counts (AC-009): the payload then reads the count left. */
+ entityCounts?: EntityCountRow[];
},
): ActionItem {
const score = row.priority_score === null ? null : Number(row.priority_score);
+ const payload = withEntityCounts(row.payload ?? {}, extra.entityCounts);
return {
id: row.id,
actionNo: Number(row.action_no),
@@ -66,7 +74,7 @@ export function actionItemFromRow(
kind: row.kind,
impact: row.impact as ActionImpact,
status: row.status as ActionStatus,
- payload: row.payload ?? {},
+ payload,
kpiKeys: row.kpi_keys ?? [],
assignee: extra.assignee,
dueDate: row.due_date,
@@ -77,9 +85,11 @@ export function actionItemFromRow(
signalCount: extra.signalCount,
priorityScore: score,
priorityLevel: storedPriorityLevel(row.priority_level, score),
- priorityReason: parsePriorityReason(row.priority_reason, {
- scoredAt: row.priority_updated_at,
- }),
+ // "Lost ground on 12 prompts", as the title counts them (AC-009).
+ priorityReason: currentPriorityReason(
+ parsePriorityReason(row.priority_reason, { scoredAt: row.priority_updated_at }),
+ payload,
+ ),
};
}
diff --git a/web/src/lib/action-center/story.ts b/web/src/lib/action-center/story.ts
index 8a6ba5952..e8394a326 100644
--- a/web/src/lib/action-center/story.ts
+++ b/web/src/lib/action-center/story.ts
@@ -4,6 +4,7 @@ import { SIGNAL_KINDS, isSignalKind } from '@/lib/signals/registry';
import { platformName } from '@/lib/signals/names';
import { formatEstimateRange, sumEstimates, type VolumeEstimate } from '@/lib/volume-estimate';
import { affectedOf, bareUrl, hostOf, type Affected } from './affected';
+import { removedOnly } from './entity-counts';
/**
* "Why this action?" and "Goal" written from the action's own data (AC-003):
@@ -212,6 +213,7 @@ export function actionStory(
volumes,
createdAt,
dueDate,
+ payload = {},
}: {
/** The signals the Affected list was built from. */
signals: Signal[];
@@ -219,6 +221,8 @@ export function actionStory(
volumes: Map<string, VolumeEstimate> | null;
createdAt: string;
dueDate: string | null;
+ /** The action as it reads now (AC-009): what was removed since isn't told. */
+ payload?: Record<string, unknown>;
},
t: Translator,
format: StoryFormat,
@@ -228,7 +232,7 @@ export function actionStory(
// Told from the lead family's signals alone, so the counts match the verb:
// a competitor's prompts are not "lost citations".
const mine = signals.filter((signal) => storyFamily(signal) === family);
- const affected = affectedOf(mine);
+ const affected = affectedOf(mine, removedOnly(payload));
const subject = subjectOf(affected, family, mine);
// The subject: "7 prompts in AI Rank Tracker (28–42k AI searches a month, estimated)".
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index e1adce031..5ec693f9b 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -26,6 +26,12 @@ import { affectedOf, affectedSignals, affectedSummary } from '@/lib/action-cente
import { readPromptDemand } from '@/lib/action-center/prompt-demand';
import type { VolumeEstimate } from '@/lib/volume-estimate';
import { readAssignees } from '@/lib/action-center/assignees';
+import {
+ currentTaskParams,
+ readEntityCounts,
+ withEntityCounts,
+ withoutTargetIds,
+} from '@/lib/action-center/entity-counts';
import {
ACTION_COLUMNS,
EVENT_COLUMNS,
@@ -95,7 +101,7 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
const actionIds = rows.map((row) => row.id);
const assigneeIds = [...new Set(rows.map((row) => row.assignee_id).filter(Boolean))] as string[];
- const [tasksRes, signalsRes, profiles] = await Promise.all([
+ const [tasksRes, signalsRes, profiles, entityCounts] = await Promise.all([
supabase.from('action_tasks').select('action_id, status').in('action_id', actionIds),
// The signals that support each action now (AC-007): its open ones.
supabase
@@ -106,6 +112,8 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
.not('action_id', 'is', null),
// Other members' profiles are hidden from the user (RLS): read as the team list reads them.
readAssignees(supabase, brandId, assigneeIds),
+ // Each action's list (AC-009): its count less what was removed since.
+ readEntityCounts(supabase, actionIds),
]);
if (tasksRes.error) throw new Error(tasksRes.error.message);
if (signalsRes.error) throw new Error(signalsRes.error.message);
@@ -128,6 +136,7 @@ export async function getActions(brandId: string): Promise<ActionItem[]> {
taskTotal: progress.total,
taskCompleted: progress.completed,
signalCount: signalCounts.get(row.id) ?? 0,
+ entityCounts: entityCounts.get(row.id),
});
});
}
@@ -202,7 +211,11 @@ async function readActionSignals(
readPromptPlaces(supabase, brandId),
]);
if (signalsRes.error) throw new Error(signalsRes.error.message);
- return mapSignalRows((signalsRes.data ?? []) as SignalRow[], places);
+ // Without a big group's thousand target ids (AC-009): the drawer names 50.
+ return mapSignalRows(
+ ((signalsRes.data ?? []) as SignalRow[]).map((row) => withoutTargetIds(row)),
+ places,
+ );
}
/**
@@ -219,7 +232,7 @@ export async function getActionSignals(brandId: string, actionId: string): Promi
* 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, signals, eventsRes, kpisRes, outcomeRes] = await Promise.all([
+ const [tasksRes, signals, eventsRes, kpisRes, outcomeRes, entityCounts] = await Promise.all([
supabase.from('action_tasks').select(TASK_COLUMNS).eq('action_id', actionId).order('position'),
readActionSignals(supabase, brandId, actionId),
supabase
@@ -234,17 +247,26 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
.eq('is_active', true),
supabase
.from('actions')
- .select('position_outcome')
+ .select('position_outcome, payload')
.eq('brand_id', brandId)
.eq('id', actionId)
.maybeSingle(),
+ readEntityCounts(supabase, [actionId]),
]);
if (tasksRes.error) throw new Error(tasksRes.error.message);
if (eventsRes.error) throw new Error(eventsRes.error.message);
if (kpisRes.error) throw new Error(kpisRes.error.message);
+ // A planned task that named the action's count names the count left (AC-009).
+ const payload = withEntityCounts(
+ (outcomeRes.data?.payload ?? {}) as Record<string, unknown>,
+ entityCounts.get(actionId),
+ );
return {
- tasks: (tasksRes.data ?? []).map(taskFromRow),
+ tasks: (tasksRes.data ?? []).map(taskFromRow).map((task) => ({
+ ...task,
+ titleParams: currentTaskParams(task.titleParams, payload) ?? task.titleParams,
+ })),
signals,
events: (eventsRes.data ?? []).map(eventFromRow),
kpis: (kpisRes.data ?? []).map(kpiFromRow),
@@ -575,10 +597,12 @@ export async function getActionsAffected(
return (data ?? []) as { id: string; payload: Record<string, unknown> | null }[];
};
- const [signalChunks, payloadChunks, places] = await Promise.all([
+ const [signalChunks, payloadChunks, places, entityCounts] = await Promise.all([
Promise.all(chunks.map(readSignals)),
Promise.all(chunks.map(readPayloads)),
readPromptPlaces(supabase, brandId),
+ // The count each action shows (AC-009), so the CSV's agrees with its title.
+ readEntityCounts(supabase, ids),
]);
const rowsByAction = new Map<string, SignalRow[]>();
@@ -593,7 +617,10 @@ export async function getActionsAffected(
for (const action of payloadChunks.flat()) {
const signals = mapSignalRows(rowsByAction.get(action.id) ?? [], places);
summaries[action.id] = affectedSummary(
- affectedOf(affectedSignals(signals, action.id), action.payload ?? {}),
+ affectedOf(
+ affectedSignals(signals, action.id),
+ withEntityCounts(action.payload ?? {}, entityCounts.get(action.id)),
+ ),
);
}
return summaries;
diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.ts
index 220fccbd6..875f8c51f 100644
--- a/web/src/lib/actions/action-history.ts
+++ b/web/src/lib/actions/action-history.ts
@@ -20,6 +20,7 @@ import type { ActionOutcome, ActionStatus, TaskStatus } from '@/lib/action-cente
import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';
import { parseImproveOutcome } from '@/lib/improve-outcome';
import { storedPriorityLevel } from '@/lib/action-center/priority';
+import { readEntityCounts, withEntityCounts } from '@/lib/action-center/entity-counts';
import {
HISTORY_STATUSES,
daysBetween,
@@ -179,7 +180,7 @@ export async function getActionHistory(
const actionIds = rows.map((row) => row.id);
const assigneeIds = [...new Set(rows.map((row) => row.assignee_id).filter(Boolean))] as string[];
- const [tasksRes, signalsRes, profilesRes] = await Promise.all([
+ const [tasksRes, signalsRes, profilesRes, entityCounts] = await Promise.all([
supabase
.from('action_tasks')
.select('id, action_id, position, task_key, title, status')
@@ -194,6 +195,8 @@ export async function getActionHistory(
assigneeIds.length > 0
? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)
: Promise.resolve({ data: [], error: null }),
+ // The count each action shows on Actions too (AC-009).
+ readEntityCounts(supabase, actionIds),
]);
if (tasksRes.error) throw new Error(tasksRes.error.message);
if (signalsRes.error) throw new Error(signalsRes.error.message);
@@ -253,7 +256,7 @@ export async function getActionHistory(
status: row.status as ActionStatus,
outcome: row.outcome as ActionOutcome,
positionOutcome: parseImproveOutcome(row.position_outcome ?? null),
- payload: row.payload ?? {},
+ payload: withEntityCounts(row.payload ?? {}, entityCounts.get(row.id)),
kpiKeys: row.kpi_keys ?? [],
sources: [...(sourcesByAction.get(row.id) ?? [])],
triggerSignals,
diff --git a/web/src/lib/actions/action-signals.test.ts b/web/src/lib/actions/action-signals.test.ts
index 91239dac0..69ec18943 100644
--- a/web/src/lib/actions/action-signals.test.ts
+++ b/web/src/lib/actions/action-signals.test.ts
@@ -28,6 +28,8 @@ vi.mock('@/lib/supabase/server', () => ({
chain.maybeSingle = async () => ({ data: rows[table]?.[0] ?? null, error: null });
return chain;
},
+ // The actions' list counts (AC-009): nothing removed here.
+ rpc: async () => ({ data: [], error: null }),
})),
}));
diff --git a/web/src/lib/actions/actions-affected.test.ts b/web/src/lib/actions/actions-affected.test.ts
index 3e760f9b4..1457ac199 100644
--- a/web/src/lib/actions/actions-affected.test.ts
+++ b/web/src/lib/actions/actions-affected.test.ts
@@ -34,6 +34,7 @@ function answer(table: string, calls: Call[]): Row[] {
return range ? out.slice(range[1] as number, (range[2] as number) + 1) : out;
}
+let entityCounts: unknown[] = [];
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
from: (table: string) => {
@@ -50,6 +51,8 @@ vi.mock('@/lib/supabase/server', () => ({
resolve({ data: answer(table, query.calls), error: null });
return chain;
},
+ // The actions' list counts (AC-009): nothing removed here.
+ rpc: async () => ({ data: entityCounts, error: null }),
})),
}));
vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
@@ -77,6 +80,7 @@ const lost = (id: string, promptId: string, promptText: string, actions: string[
beforeEach(() => {
queries = [];
+ entityCounts = [];
rows = {
actions: [
{ id: 'a1', payload: {} },
@@ -103,6 +107,16 @@ describe('getActionsAffected', () => {
});
});
+ it('counts an action as its title does, with what was removed since (AC-009)', async () => {
+ rows.actions[0].payload = { targetEntity: 'prompts', targetCount: 13 };
+ entityCounts = [
+ { action_id: 'a1', entity_type: 'prompts', total: 13, removed: 1, removed_labels: ['x'] },
+ ];
+ const result = await getActionsAffected('b1', ['a1']);
+ // 13 prompts when it was created, one deleted since: 12, not the 2 the signals name now.
+ expect(result.a1.count).toBe(12);
+ });
+
it("reads past one response's rows, a page at a time", async () => {
rows.signals = Array.from({ length: 1001 }, (_, i) =>
lost(`s${i}`, `p${i}`, `Prompt ${i}`, ['a1']),
diff --git a/web/src/lib/actions/signals.ts b/web/src/lib/actions/signals.ts
index 2e04a2b7d..74cd45073 100644
--- a/web/src/lib/actions/signals.ts
+++ b/web/src/lib/actions/signals.ts
@@ -10,6 +10,7 @@
* client-side: there is no stored text to search.
*/
+import { readEntityCounts, withEntityCounts } from '@/lib/action-center/entity-counts';
import { createClient } from '@/lib/supabase/server';
import { after } from 'next/server';
import { API_BASE_URL } from '@/config/api';
@@ -96,12 +97,18 @@ export async function getSignalActions(brandId: string, signalId: string): Promi
.eq('actions.brand_id', brandId)
.order('linked_at', { ascending: false });
if (error) throw new Error(error.message);
- return (data ?? []).map(({ actions: row }) => ({
+ const rows = (data ?? []).map(({ actions: row }) => row);
+ // Named as on Actions (AC-009): the count left.
+ const counts = await readEntityCounts(
+ supabase,
+ rows.map((row) => row.id),
+ );
+ return rows.map((row) => ({
id: row.id,
actionNo: Number(row.action_no),
kind: row.kind,
status: row.status as ActionStatus,
- payload: (row.payload ?? {}) as Record<string, unknown>,
+ payload: withEntityCounts((row.payload ?? {}) as Record<string, unknown>, counts.get(row.id)),
}));
}
diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.ts
index c57421d0a..818fd1d6d 100644
--- a/web/src/lib/mcp/action-export.test.ts
+++ b/web/src/lib/mcp/action-export.test.ts
@@ -63,7 +63,13 @@ function table(name: string) {
return chain;
}
-vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: table } }));
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: table,
+ // The action's list counts (AC-009): nothing removed here.
+ rpc: async () => ({ data: [], error: null }),
+ },
+}));
const { exportActionFor } = await import('./action-export');
diff --git a/web/src/lib/mcp/action-export.ts b/web/src/lib/mcp/action-export.ts
index 0aa250373..6ff5db643 100644
--- a/web/src/lib/mcp/action-export.ts
+++ b/web/src/lib/mcp/action-export.ts
@@ -9,6 +9,11 @@ import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { OPEN_SIGNAL_STATUSES, type SignalStatus } from '@/lib/signals/registry';
import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';
import { affectedOf, affectedSignals } from '@/lib/action-center/affected';
+import {
+ currentTaskParams,
+ readEntityCounts,
+ withEntityCounts,
+} from '@/lib/action-center/entity-counts';
import { actionStory } from '@/lib/action-center/story';
import { readPromptDemand } from '@/lib/action-center/prompt-demand';
import { actionCsv, actionExportFileName, actionMarkdown } from '@/lib/action-center/export';
@@ -192,47 +197,58 @@ export async function exportActionFor(
payload: (row.payload ?? {}) as Record<string, unknown>,
});
- const [tasksRes, signalsRes, eventsRes, kpisRes, places, assigneeRes, openRes, sentFrom] =
- await Promise.all([
- supabaseAdmin
- .from('action_tasks')
- .select(TASK_COLUMNS)
- .eq('action_id', actionId)
- .order('position'),
- // Every signal the action has taken as evidence (AC-007), as the drawer reads them.
- supabaseAdmin
- .from('signals')
- .select(`${SIGNAL_ROW_COLUMNS}, action_signals!inner(action_id)`)
- .eq('brand_id', brandId)
- .eq('action_signals.action_id', actionId)
- .order('detected_at', { ascending: false }),
- supabaseAdmin
- .from('action_events')
- .select(EVENT_COLUMNS)
- .eq('action_id', actionId)
- .order('created_at'),
- supabaseAdmin
- .from('kpi_definitions')
- .select('kpi_key, target, timeframe')
- .eq('brand_id', brandId)
- .eq('is_active', true),
- readPromptPlaces(supabaseAdmin, brandId),
- row.assignee_id
- ? supabaseAdmin
- .from('profiles')
- .select('id, full_name, avatar_url')
- .eq('id', row.assignee_id)
- .maybeSingle()
- : Promise.resolve({ data: null, error: null }),
- // The signals that support it now, as the list counts them (AC-007): its "n signals" tag.
- supabaseAdmin
- .from('signals')
- .select('id', { count: 'exact', head: true })
- .eq('brand_id', brandId)
- .eq('action_id', actionId)
- .in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]),
- opportunityId ? sentFromOpportunity(brandId, opportunityId) : Promise.resolve(null),
- ]);
+ const [
+ tasksRes,
+ signalsRes,
+ eventsRes,
+ kpisRes,
+ places,
+ assigneeRes,
+ openRes,
+ sentFrom,
+ entityCounts,
+ ] = await Promise.all([
+ supabaseAdmin
+ .from('action_tasks')
+ .select(TASK_COLUMNS)
+ .eq('action_id', actionId)
+ .order('position'),
+ // Every signal the action has taken as evidence (AC-007), as the drawer reads them.
+ supabaseAdmin
+ .from('signals')
+ .select(`${SIGNAL_ROW_COLUMNS}, action_signals!inner(action_id)`)
+ .eq('brand_id', brandId)
+ .eq('action_signals.action_id', actionId)
+ .order('detected_at', { ascending: false }),
+ supabaseAdmin
+ .from('action_events')
+ .select(EVENT_COLUMNS)
+ .eq('action_id', actionId)
+ .order('created_at'),
+ supabaseAdmin
+ .from('kpi_definitions')
+ .select('kpi_key, target, timeframe')
+ .eq('brand_id', brandId)
+ .eq('is_active', true),
+ readPromptPlaces(supabaseAdmin, brandId),
+ row.assignee_id
+ ? supabaseAdmin
+ .from('profiles')
+ .select('id, full_name, avatar_url')
+ .eq('id', row.assignee_id)
+ .maybeSingle()
+ : Promise.resolve({ data: null, error: null }),
+ // The signals that support it now, as the list counts them (AC-007): its "n signals" tag.
+ supabaseAdmin
+ .from('signals')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId)
+ .eq('action_id', actionId)
+ .in('status', OPEN_SIGNAL_STATUSES as SignalStatus[]),
+ opportunityId ? sentFromOpportunity(brandId, opportunityId) : Promise.resolve(null),
+ // Its list (AC-009): the count it shows, as on the page.
+ readEntityCounts(supabaseAdmin, [actionId]),
+ ]);
for (const res of [tasksRes, signalsRes, eventsRes, kpisRes, assigneeRes, openRes]) {
if (res.error) throw new Error(res.error.message);
}
@@ -242,7 +258,12 @@ export async function exportActionFor(
full_name: string | null;
avatar_url: string | null;
} | null;
- const tasks = (tasksRes.data ?? []).map(taskFromRow);
+ const counts = entityCounts.get(actionId);
+ const current = withEntityCounts((row.payload ?? {}) as Record<string, unknown>, counts);
+ const tasks = (tasksRes.data ?? []).map(taskFromRow).map((task) => ({
+ ...task,
+ titleParams: currentTaskParams(task.titleParams, current) ?? task.titleParams,
+ }));
// Skipped and failed tasks leave the count, as on the list.
const counted = tasks.filter(
(task) => !(UNCOUNTED_TASK_STATUSES as readonly string[]).includes(task.status),
@@ -254,6 +275,7 @@ export async function exportActionFor(
taskTotal: counted.length,
taskCompleted: counted.filter((task) => task.status === 'completed').length,
signalCount: openRes.count ?? 0,
+ entityCounts: counts,
});
const detail: ActionDetail = {
tasks,
@@ -276,7 +298,13 @@ export async function exportActionFor(
const t = translators();
const format_ = createFormatter({ locale: 'en', timeZone: 'UTC' });
const story = actionStory(
- { signals: evidence, volumes, createdAt: action.createdAt, dueDate: action.dueDate },
+ {
+ signals: evidence,
+ volumes,
+ createdAt: action.createdAt,
+ dueDate: action.dueDate,
+ payload: action.payload ?? {},
+ },
t.story,
{
day: (date) => format_.dateTime(date, { month: 'short', day: 'numeric' }),
diff --git a/web/src/lib/mcp/action-priority.test.ts b/web/src/lib/mcp/action-priority.test.ts
index 496fc710c..ec2255f52 100644
--- a/web/src/lib/mcp/action-priority.test.ts
+++ b/web/src/lib/mcp/action-priority.test.ts
@@ -7,6 +7,7 @@ import type { McpAuthContext } from '@/lib/mcp-auth';
*/
let orders: [string, Record<string, unknown> | undefined][] = [];
+let entityCounts: unknown[] = [];
const ACTIONS = [
{
@@ -43,6 +44,8 @@ const ACTIONS = [
},
];
+let actionRows: Record<string, unknown>[] = ACTIONS;
+
function builder(table: string) {
const chain = {
select: () => chain,
@@ -62,13 +65,17 @@ function builder(table: string) {
error: null,
}),
then: (resolve: (v: { data: unknown; error: null }) => void) =>
- resolve({ data: table === 'actions' ? ACTIONS : [], error: null }),
+ resolve({ data: table === 'actions' ? actionRows : [], error: null }),
};
return chain;
}
vi.mock('@/lib/supabase/admin', () => ({
- supabaseAdmin: { from: (table: string) => builder(table) },
+ supabaseAdmin: {
+ from: (table: string) => builder(table),
+ // The actions' list counts (AC-009): nothing removed unless a test says so.
+ rpc: async () => ({ data: entityCounts, error: null }),
+ },
}));
const { getActionFor, listActionsFor } = await import('./data');
@@ -83,6 +90,8 @@ const auth: McpAuthContext = {
describe('listActionsFor', () => {
beforeEach(() => {
orders = [];
+ entityCounts = [];
+ actionRows = ACTIONS;
});
it('gives each action its priority, or null before it is scored', async () => {
@@ -98,6 +107,25 @@ describe('listActionsFor', () => {
]);
});
+ it('names the count left in a reason that named the action’s, as get_action does (AC-009)', async () => {
+ actionRows = [
+ {
+ ...ACTIONS[0],
+ priority_reason: { subject: { entity: 'prompts', count: 13 }, days: 2 },
+ target_entity: 'prompts',
+ target_count: 13,
+ },
+ ];
+ entityCounts = [
+ { action_id: 'a1', entity_type: 'prompts', total: 13, removed: 1, removed_labels: ['x'] },
+ ];
+ const rows = await listActionsFor(auth, { brandId: 'brand-1' });
+ expect(rows?.[0].priority?.reason).toEqual({
+ subject: { entity: 'prompts', count: 12 },
+ days: 2,
+ });
+ });
+
it('lists the most recently updated first when asked', async () => {
await listActionsFor(auth, { brandId: 'brand-1', sort: 'updated' });
expect(orders).toEqual([['updated_at', { ascending: false }]]);
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 52162a365..265e20ea0 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -22,6 +22,13 @@ import {
import { mapSignalRows, type SignalRow } from '@/lib/signals/map';
import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { currentActionFirst, signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';
+import {
+ currentPriorityReason,
+ currentTaskParams,
+ readEntityCounts,
+ withEntityCounts,
+ withoutTargetIds,
+} from '@/lib/action-center/entity-counts';
import { parseTaskDetails } from '@/lib/action-center/task-details';
import { locationCode, isValidLocation } from '@/lib/region';
import { promptVolumeEstimate, type EstimateConfidence } from '@/lib/volume-estimate';
@@ -2872,7 +2879,7 @@ export async function listActionsFor(
let query = supabaseAdmin
.from('actions')
.select(
- 'id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at, priority_score, priority_level, priority_reason',
+ 'id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at, priority_score, priority_level, priority_reason, target_entity:payload->>targetEntity, target_count:payload->targetCount',
)
.eq('brand_id', params.brandId)
// A deleted action (00168) is gone for everyone but the nightly generator.
@@ -2909,7 +2916,14 @@ export async function listActionsFor(
if (task.status === 'completed') acc.completed += 1;
progress.set(task.action_id, acc);
}
- const names = await assigneeNames(rows.map((r) => r.assignee_id));
+ const [names, entityCounts] = await Promise.all([
+ assigneeNames(rows.map((r) => r.assignee_id)),
+ // Each action's list (AC-009): its reason names the count left, as get_action's does.
+ readEntityCounts(
+ supabaseAdmin,
+ rows.map((r) => r.id),
+ ),
+ ]);
return rows.map((r) => ({
id: r.id,
@@ -2924,7 +2938,16 @@ export async function listActionsFor(
: null,
due_date: r.due_date ?? null,
task_progress: progress.get(r.id) ?? { completed: 0, total: 0 },
- priority: priorityFor(r),
+ priority: priorityFor({
+ ...r,
+ priority_reason: currentPriorityReason(
+ r.priority_reason,
+ withEntityCounts(
+ { targetEntity: r.target_entity, targetCount: r.target_count },
+ entityCounts.get(r.id),
+ ),
+ ),
+ }),
created_at: r.created_at,
updated_at: r.updated_at,
}));
@@ -3006,7 +3029,7 @@ export async function getActionFor(
if (error) throw new Error(error.message);
if (!action) return null;
- const [tasksRes, signalsRes, eventsRes, names] = await Promise.all([
+ const [tasksRes, signalsRes, eventsRes, names, entityCounts] = await Promise.all([
supabaseAdmin
.from('action_tasks')
.select(
@@ -3028,10 +3051,16 @@ export async function getActionFor(
.eq('action_id', actionId)
.order('created_at'),
assigneeNames([action.assignee_id]),
+ // Its list (AC-009): the count left, and what was removed since.
+ readEntityCounts(supabaseAdmin, [actionId]),
]);
if (tasksRes.error) throw new Error(tasksRes.error.message);
if (signalsRes.error) throw new Error(signalsRes.error.message);
if (eventsRes.error) throw new Error(eventsRes.error.message);
+ const payload = withEntityCounts(
+ (action.payload ?? {}) as Record<string, unknown>,
+ entityCounts.get(actionId),
+ );
return {
id: action.id,
@@ -3042,13 +3071,16 @@ export async function getActionFor(
impact: action.impact,
status: action.status,
outcome: action.outcome ?? null,
- payload: (action.payload ?? {}) as Record<string, unknown>,
+ payload,
kpi_keys: action.kpi_keys ?? [],
assignee: action.assignee_id
? { id: action.assignee_id, full_name: names.get(action.assignee_id) ?? null }
: null,
due_date: action.due_date ?? null,
- priority: priorityFor(action),
+ priority: priorityFor({
+ ...action,
+ priority_reason: currentPriorityReason(action.priority_reason, payload),
+ }),
created_at: action.created_at,
updated_at: action.updated_at,
completed_at: action.completed_at ?? null,
@@ -3057,7 +3089,10 @@ export async function getActionFor(
position: t.position,
task_key: t.task_key ?? null,
title: t.title ?? null,
- title_params: (t.title_params ?? {}) as Record<string, unknown>,
+ title_params: (currentTaskParams(
+ (t.title_params ?? {}) as Record<string, string | number>,
+ payload,
+ ) ?? {}) as Record<string, unknown>,
status: t.status,
skip_reason: t.skip_reason ?? null,
mode: t.mode ?? null,
@@ -3068,7 +3103,9 @@ export async function getActionFor(
})),
// The join that found them is not part of a signal.
signals: ((signalsRes.data ?? []) as Record<string, unknown>[]).map((row) =>
- Object.fromEntries(Object.entries(row).filter(([key]) => key !== 'action_signals')),
+ withoutTargetIds(
+ Object.fromEntries(Object.entries(row).filter(([key]) => key !== 'action_signals')),
+ ),
),
events: (eventsRes.data ?? []).map((e) => ({
event: e.event,
@@ -3176,10 +3213,11 @@ export async function listSignalsFor(
return rows.map((row) => {
const used = currentActionFirst(actions.get(row.id) ?? [], row.action_id);
const signal = known.get(row.id);
+ const lean = withoutTargetIds(row as unknown as Record<string, unknown>);
// A kind this build has no detail for still comes back, as it always did.
return signal
- ? { ...row, ...signalDetailForApi(signal, used) }
- : { ...row, used_by_actions: used };
+ ? { ...lean, ...signalDetailForApi(signal, used) }
+ : { ...lean, used_by_actions: used };
});
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index f13d8f1cb..81fc16598 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -14,6 +14,44 @@ export type Database = {
}
public: {
Tables: {
+ action_entities: {
+ Row: {
+ action_id: string
+ entity_key: string
+ entity_type: string
+ kept_at: string
+ label: string | null
+ removed_at: string | null
+ removed_reason: string | null
+ }
+ Insert: {
+ action_id: string
+ entity_key: string
+ entity_type: string
+ kept_at?: string
+ label?: string | null
+ removed_at?: string | null
+ removed_reason?: string | null
+ }
+ Update: {
+ action_id?: string
+ entity_key?: string
+ entity_type?: string
+ kept_at?: string
+ label?: string | null
+ removed_at?: string | null
+ removed_reason?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "action_entities_action_id_fkey"
+ columns: ["action_id"]
+ isOneToOne: false
+ referencedRelation: "actions"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
action_events: {
Row: {
action_id: string
@@ -3541,6 +3579,17 @@ export type Database = {
[_ in never]: never
}
Functions: {
+ action_entity_counts: {
+ Args: { p_action_ids: string[] }
+ Returns: {
+ action_id: string
+ entity_type: string
+ removed: number
+ removed_keys: string[]
+ removed_labels: string[]
+ total: number
+ }[]
+ }
ai_traffic_merged: {
Args: {
p_analytics?: boolean