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): write the History drawer's goal and what happened from the action's data (#1086)

Cihanba062d303238
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx
index 4692768b0..957b9630c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/history/page.tsx
@@ -388,7 +388,11 @@ export default function ActionCenterHistoryPage() {
</>
)}
- <HistoryDrawer item={selected} onOpenChange={(open) => !open && setSelected(null)} />
+ <HistoryDrawer
+ brandId={brandId}
+ item={selected}
+ onOpenChange={(open) => !open && setSelected(null)}
+ />
</div>
);
}
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 81be9de48..2362122b0 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -1,7 +1,7 @@
'use client';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useFormatter, useTranslations } from 'next-intl';
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { toast } from 'sonner';
import { ChevronRight, Plus, Trash2 } from 'lucide-react';
@@ -30,7 +30,6 @@ import {
assignAction,
deleteTask,
getActionDetail,
- getPromptDemand,
setActionDueDate,
updateActionStatus,
updateTaskDetails,
@@ -64,13 +63,8 @@ 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 { actionStory } from '@/lib/action-center/story';
+import { affectedChips, affectedTotal } from '@/lib/action-center/affected';
+import { useActionStory } from './use-action-story';
import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
@@ -115,8 +109,6 @@ export function ActionDrawer({
const tTasks = useTranslations('actionCenter.actionTasks');
const tTaskStatus = useTranslations('actionCenter.taskStatus');
const tPriority = useTranslations('actionCenter.actionsPage.priority');
- const tStory = useTranslations('actionCenter.actionsPage.drawer.story');
- const format = useFormatter();
const router = useRouter();
const [tab, setTab] = useState<DrawerTab>('overview');
@@ -164,70 +156,12 @@ export function ActionDrawer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [action?.id]);
- // The signals the action rests on, and what they affect, item by item (AC-003).
- const evidence = useMemo(
- () => (action && detail ? affectedSignals(detail.signals, action.id) : null),
- [action, detail],
- );
- const affected = useMemo(
- () => (action && evidence ? affectedOf(evidence, action.payload ?? {}) : null),
- [action, evidence],
- );
-
- // Each affected prompt's demand. Best effort: without it the column is left
- // out. Kept with the prompts it was read for, so a read still under way is
- // told apart from one that failed.
- const promptIdsKey = (affected?.prompts ?? [])
- .map((row) => row.id)
- .filter(Boolean)
- .join(',');
- const demandKey = `${brandId}:${promptIdsKey}`;
- const [demand, setDemand] = useState<{
- key: string;
- volumes: Map<string, number> | null;
- } | null>(null);
- useEffect(() => {
- if (!promptIdsKey) return;
- let cancelled = false;
- const key = `${brandId}:${promptIdsKey}`;
- getPromptDemand(brandId, promptIdsKey.split(',')).then(
- (read) => {
- if (!cancelled) setDemand({ key, volumes: new Map(Object.entries(read)) });
- },
- () => {
- if (!cancelled) setDemand({ key, volumes: null });
- },
- );
- return () => {
- cancelled = true;
- };
- }, [brandId, promptIdsKey]);
- const demandRead = !promptIdsKey || demand?.key === demandKey;
- const volumes = promptIdsKey && demand?.key === demandKey ? demand.volumes : null;
- // The detail and its demand are both in: the Why names the prompts' demand,
- // so it waits for it rather than reading one way and then another.
- const ready = detail !== null && demandRead;
-
- // Why and Goal in the action's own terms (AC-003); null for an action a
- // person sent, which carries its own.
- const story = useMemo(
- () =>
- action && evidence
- ? actionStory(
- {
- signals: evidence,
- volumes,
- createdAt: action.createdAt,
- dueDate: action.dueDate,
- },
- tStory,
- {
- day: (date) => format.dateTime(date, { month: 'short', day: 'numeric' }),
- list: (items) => format.list(items, { type: 'conjunction' }),
- },
- )
- : null,
- [action, evidence, volumes, tStory, format],
+ // The signals the action rests on, what they affect, their prompts' demand
+ // and the Why and Goal they tell (AC-003), as the History drawer reads them.
+ const { affected, volumes, story, ready } = useActionStory(
+ brandId,
+ action,
+ detail?.signals ?? null,
);
if (!action) return null;
diff --git a/web/src/components/action-center/history-drawer.test.tsx b/web/src/components/action-center/history-drawer.test.tsx
index 9d219dd32..37636d435 100644
--- a/web/src/components/action-center/history-drawer.test.tsx
+++ b/web/src/components/action-center/history-drawer.test.tsx
@@ -1,9 +1,28 @@
import { act } from 'react';
-import { createRoot } from 'react-dom/client';
+import { createRoot, type Root } from 'react-dom/client';
import { NextIntlClientProvider } from 'next-intl';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { ActionHistoryItem } from '@/lib/action-center/history';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../messages/en.json';
+import type { ActionHistoryItem } from '@/lib/action-center/history';
+import type { Signal } from '@/lib/signals/map';
+
+/**
+ * The History drawer's goal and what happened, told from the action's own
+ * signals as the Actions drawer tells them (AC-003), with the general
+ * sentences while nothing can be read.
+ */
+
+const { getActionSignals, getPromptDemand } = vi.hoisted(() => ({
+ getActionSignals: vi.fn(),
+ getPromptDemand: vi.fn(),
+}));
+vi.mock('@/lib/actions/action-center', () => ({ getActionSignals, getPromptDemand }));
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));
+
+const { HistoryDrawer } = await import('./history-drawer');
+
+// Days are read where the reader is; pin it so the fixtures' days hold anywhere.
+process.env.TZ = 'UTC';
(
globalThis as typeof globalThis & {
@@ -11,67 +30,134 @@ import messages from '../../../messages/en.json';
}
).IS_REACT_ACT_ENVIRONMENT = true;
-vi.mock('@/i18n/navigation', () => ({
- useRouter: () => ({ push: vi.fn() }),
-}));
-
-import { HistoryDrawer } from './history-drawer';
+let container: HTMLDivElement;
+let root: Root;
-const item = (signalCount: number): ActionHistoryItem => ({
- id: 'action-id',
- actionNo: 1,
- kind: 'recover_visibility',
+const item = {
+ id: 'a1',
+ actionNo: 12,
+ kind: 'recover_lost_citations',
type: 'recover',
- priorityScore: 72,
+ priorityScore: 84,
priorityLevel: 'high',
status: 'completed',
- outcome: 'pending_measurement',
+ outcome: 'improved',
payload: {},
kpiKeys: [],
- sources: [],
- triggerSignals: Array.from({ length: signalCount }, (_, i) => ({
- signalId: `signal-${i}`,
- kind: 'visibility_drop',
- detectedAt: '2026-01-01T00:00:00.000Z',
- })),
+ sources: ['ai_results'],
+ triggerSignals: [{ signalId: 's1', kind: 'lost_citations', detectedAt: '2026-10-09T00:00:00Z' }],
affected: [],
results: [],
positionOutcome: null,
tasks: [],
assignee: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- completedAt: '2026-01-05T00:00:00.000Z',
- timeToCloseDays: 4,
-});
+ dueDate: '2026-11-09',
+ createdAt: '2026-10-10T00:00:00Z',
+ completedAt: '2026-10-20T00:00:00Z',
+ timeToCloseDays: 10,
+} as ActionHistoryItem;
-async function renderDrawer(signalCount: number) {
- const container = document.createElement('div');
- document.body.append(container);
- const root = createRoot(container);
- await act(async () => {
+const signal = {
+ id: 's1',
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'resolved',
+ source: ['ai_results'],
+ detectedAt: '2026-10-09T00:00:00Z',
+ lastDetectedAt: '2026-10-09T00:00:00Z',
+ resolvedAt: '2026-10-20T00:00:00Z',
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: {
+ promptId: 'p1',
+ promptText: 'Best coffee subscription?',
+ lostUrls: [{ url: 'https://acme.example/pricing', position: 2 }],
+ },
+ kpiKeys: [],
+ actionId: 'a1',
+ where: { platforms: ['chatgpt-web'], regions: [], topics: [] },
+} as unknown as Signal;
+
+function render(node: React.ReactNode) {
+ act(() => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <HistoryDrawer item={item(signalCount)} onOpenChange={() => {}} />
+ {node}
</NextIntlClientProvider>,
);
});
- return root;
}
+/** The text under a section's label. */
+const under = (label: string) =>
+ [...document.querySelectorAll('section')].find((s) => s.textContent?.startsWith(label))
+ ?.textContent ?? '';
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ getActionSignals.mockReset();
+ getPromptDemand.mockReset();
+});
+
afterEach(() => {
- document.body.replaceChildren();
+ act(() => root.unmount());
+ container.remove();
});
describe('HistoryDrawer', () => {
+ it("tells the goal and what happened from the action's signals once they are read", async () => {
+ let answer: (value: unknown) => void = () => {};
+ getActionSignals.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ getPromptDemand.mockResolvedValue({ p1: 5500 });
+ render(<HistoryDrawer brandId="b1" item={item} onOpenChange={() => {}} />);
+
+ // Placeholders while reading, not the general sentences.
+ expect(under('What was the goal?')).toBe('What was the goal?');
+ expect(getActionSignals).toHaveBeenCalledWith('b1', 'a1');
+
+ await act(async () => answer([signal]));
+ const happened = under('What happened?');
+ expect(happened).toContain('Best coffee subscription?');
+ expect(happened).toContain('~5.5k');
+ expect(happened).toContain('Oct 9');
+ // The goal is dated by the action's due date.
+ expect(under('What was the goal?')).toContain('Nov 9');
+ });
+
+ it('keeps the general sentences when the signals cannot be read', async () => {
+ getActionSignals.mockRejectedValue(new Error('offline'));
+ render(<HistoryDrawer brandId="b1" item={item} onOpenChange={() => {}} />);
+ await act(async () => {});
+
+ expect(under('What happened?')).toContain(
+ `What happened?${messages.actionCenter.actionTexts.recover_lost_citations.description}`,
+ );
+ expect(under('What was the goal?')).not.toBe('What was the goal?');
+ expect(getPromptDemand).not.toHaveBeenCalled();
+ });
+
it.each([
[1, 'Consolidated from 1 signal'],
[3, 'Consolidated from 3 signals'],
])('counts %i trigger signal(s) in the right grammatical number', async (count, text) => {
- const root = await renderDrawer(count);
- const line = Array.from(document.body.querySelectorAll('p')).find((p) =>
+ getActionSignals.mockResolvedValue([]);
+ const triggerSignals = Array.from({ length: count }, (_, i) => ({
+ signalId: `s${i}`,
+ kind: 'lost_citations',
+ detectedAt: '2026-10-09T00:00:00Z',
+ }));
+ render(
+ <HistoryDrawer brandId="b1" item={{ ...item, triggerSignals }} onOpenChange={() => {}} />,
+ );
+ await act(async () => {});
+
+ const line = [...document.querySelectorAll('p')].find((p) =>
p.textContent?.startsWith('Consolidated from'),
);
expect(line?.textContent).toBe(text);
- await act(async () => root.unmount());
});
});
diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsx
index 6dd426418..671accdce 100644
--- a/web/src/components/action-center/history-drawer.tsx
+++ b/web/src/components/action-center/history-drawer.tsx
@@ -1,5 +1,6 @@
'use client';
+import { useEffect, useMemo, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { Badge } from '@/components/ui/badge';
@@ -18,6 +19,10 @@ import { UNCOUNTED_TASK_STATUSES } from '@/lib/action-center/registry';
import { ActionIcon, PriorityBadge } from './action-table';
import { HistoryStatusBadge } from './history-table';
import { ImproveOutcomeCard } from './improve-outcome-card';
+import { useActionStory } from './use-action-story';
+import { Skeleton } from '@/components/ui/skeleton';
+import { getActionSignals } from '@/lib/actions/action-center';
+import type { Signal } from '@/lib/signals/map';
import { improvePlatformLabels } from '@/lib/improve-outcome';
import { cn } from '@/lib/utils';
@@ -71,9 +76,11 @@ function ResultMetricCard({
* for and the rest is the evidence behind it.
*/
export function HistoryDrawer({
+ brandId,
item,
onOpenChange,
}: {
+ brandId: string;
item: ActionHistoryItem | null;
onOpenChange: (open: boolean) => void;
}) {
@@ -87,6 +94,39 @@ export function HistoryDrawer({
const tAffected = useTranslations('actionCenter.historyPage.affected');
const router = useRouter();
+ // The signals the action took as evidence, read once it opens as the Actions
+ // drawer reads them, so its goal and what happened are told from its own
+ // data (AC-003). A failed read leaves the general sentences.
+ const itemId = item?.id ?? null;
+ const [read, setRead] = useState<{ id: string; signals: Signal[] } | null>(null);
+ useEffect(() => {
+ if (!itemId) return;
+ let cancelled = false;
+ getActionSignals(brandId, itemId).then(
+ (signals) => {
+ if (!cancelled) setRead({ id: itemId, signals });
+ },
+ () => {
+ if (!cancelled) setRead({ id: itemId, signals: [] });
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, itemId]);
+ const storyAction = useMemo(
+ () =>
+ item
+ ? { id: item.id, payload: item.payload, createdAt: item.createdAt, dueDate: item.dueDate }
+ : null,
+ [item],
+ );
+ const { story, ready } = useActionStory(
+ brandId,
+ storyAction,
+ read && read.id === itemId ? read.signals : null,
+ );
+
if (!item) return null;
const texts = actionTexts(
@@ -139,16 +179,24 @@ export function HistoryDrawer({
</SheetHeader>
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">
- <section>
+ <section aria-busy={!ready}>
<p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>
- <p className="mt-1">{actionGoal(item.kind, tTexts, item.payload)}</p>
+ {ready ? (
+ <p className="mt-1">{story?.goal ?? actionGoal(item.kind, tTexts, item.payload)}</p>
+ ) : (
+ <Skeleton className="mt-1.5 h-4 w-3/4" />
+ )}
</section>
<Separator />
- <section>
+ <section aria-busy={!ready}>
<p className="text-xs font-medium text-muted-foreground">{t('drawer.whatHappened')}</p>
- <p className="mt-1">{texts.description}</p>
+ {ready ? (
+ <p className="mt-1">{story?.why ?? texts.description}</p>
+ ) : (
+ <Skeleton className="mt-1.5 h-4 w-full" />
+ )}
{item.triggerSignals.length > 0 && (
<p className="mt-1.5 text-xs text-muted-foreground">
{t('drawer.triggeredBy', { count: item.triggerSignals.length })}
diff --git a/web/src/components/action-center/history-table.test.tsx b/web/src/components/action-center/history-table.test.tsx
index 51dc212e1..2e4166a6c 100644
--- a/web/src/components/action-center/history-table.test.tsx
+++ b/web/src/components/action-center/history-table.test.tsx
@@ -15,6 +15,12 @@ vi.mock('@/i18n/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
}));
+// The drawer reads the action's signals for its goal (AC-003); none here.
+vi.mock('@/lib/actions/action-center', () => ({
+ getActionSignals: vi.fn(async () => []),
+ getPromptDemand: vi.fn(async () => ({})),
+}));
+
import { HistoryTable } from './history-table';
import { HistoryDrawer } from './history-drawer';
@@ -36,6 +42,7 @@ const item = (overrides: Partial<ActionHistoryItem> = {}): ActionHistoryItem =>
positionOutcome: null,
tasks: [],
assignee: null,
+ dueDate: null,
createdAt: '2026-01-01T00:00:00.000Z',
completedAt: '2026-01-05T00:00:00.000Z',
timeToCloseDays: 4,
@@ -111,6 +118,7 @@ describe('HistoryDrawer', () => {
])('shows %i affected signal(s) as "%s"', async (count, text) => {
const root = await render(
<HistoryDrawer
+ brandId="b1"
item={item({ affected: [counted('citation', count)] })}
onOpenChange={() => {}}
/>,
@@ -124,7 +132,7 @@ describe('HistoryDrawer', () => {
[4, '4 days'],
])('shows a time to close of %i as "%s"', async (days, text) => {
const root = await render(
- <HistoryDrawer item={item({ timeToCloseDays: days })} onOpenChange={() => {}} />,
+ <HistoryDrawer brandId="b1" item={item({ timeToCloseDays: days })} onOpenChange={() => {}} />,
);
expect(textAfterLabel('Time to Close')).toBe(text);
await act(async () => root.unmount());
diff --git a/web/src/components/action-center/use-action-story.ts b/web/src/components/action-center/use-action-story.ts
new file mode 100644
index 000000000..cee114346
--- /dev/null
+++ b/web/src/components/action-center/use-action-story.ts
@@ -0,0 +1,106 @@
+'use client';
+
+import { useEffect, useMemo, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { getPromptDemand } from '@/lib/actions/action-center';
+import type { Signal } from '@/lib/signals/map';
+import { affectedOf, affectedSignals, type Affected } from '@/lib/action-center/affected';
+import { actionStory, type ActionStory } from '@/lib/action-center/story';
+
+/** What the story reads of an action. */
+export interface StoryAction {
+ id: string;
+ payload: Record<string, unknown>;
+ createdAt: string;
+ dueDate: string | null;
+}
+
+/**
+ * What a drawer works out from an action's signals (AC-003): what the ones it
+ * rests on affect item by item, each affected prompt's demand, and
+ * the Why and Goal in the action's own terms. Shared by the Actions and the
+ * History drawers, so an action reads the same in both. `signals` is null
+ * until the caller has read them; `ready` once they and their demand are in,
+ * so the Why is written once rather than one way and then another.
+ */
+export function useActionStory(
+ brandId: string,
+ action: StoryAction | null,
+ signals: Signal[] | null,
+): {
+ affected: Affected | null;
+ volumes: Map<string, number> | null;
+ story: ActionStory | null;
+ ready: boolean;
+} {
+ const tStory = useTranslations('actionCenter.actionsPage.drawer.story');
+ const format = useFormatter();
+
+ const evidence = useMemo(
+ () => (action && signals ? affectedSignals(signals, action.id) : null),
+ [action, signals],
+ );
+ const affected = useMemo(
+ () => (action && evidence ? affectedOf(evidence, action.payload ?? {}) : null),
+ [action, evidence],
+ );
+
+ // Each affected prompt's demand. Best effort: without it the column is left
+ // out. Kept with the prompts it was read for, so a read still under way is
+ // told apart from one that failed.
+ const promptIdsKey = (affected?.prompts ?? [])
+ .map((row) => row.id)
+ .filter(Boolean)
+ .join(',');
+ const demandKey = `${brandId}:${promptIdsKey}`;
+ const [demand, setDemand] = useState<{
+ key: string;
+ volumes: Map<string, number> | null;
+ } | null>(null);
+ useEffect(() => {
+ if (!promptIdsKey) return;
+ let cancelled = false;
+ const key = `${brandId}:${promptIdsKey}`;
+ getPromptDemand(brandId, promptIdsKey.split(',')).then(
+ (read) => {
+ if (!cancelled) setDemand({ key, volumes: new Map(Object.entries(read)) });
+ },
+ () => {
+ if (!cancelled) setDemand({ key, volumes: null });
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId, promptIdsKey]);
+ const demandRead = !promptIdsKey || demand?.key === demandKey;
+ const volumes = promptIdsKey && demand?.key === demandKey ? demand.volumes : null;
+
+ // The signals and their demand are both in: the Why names the prompts'
+ // demand, so it waits for it rather than reading one way and then another.
+ const ready = signals !== null && demandRead;
+
+ // Why and Goal in the action's own terms; null for an action a person sent,
+ // which carries its own.
+ const story = useMemo(
+ () =>
+ action && evidence
+ ? actionStory(
+ {
+ signals: evidence,
+ volumes,
+ createdAt: action.createdAt,
+ dueDate: action.dueDate,
+ },
+ tStory,
+ {
+ day: (date) => format.dateTime(date, { month: 'short', day: 'numeric' }),
+ list: (items) => format.list(items, { type: 'conjunction' }),
+ },
+ )
+ : null,
+ [action, evidence, volumes, tStory, format],
+ );
+
+ return { affected, volumes, story, ready };
+}
diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.ts
index 892e7981b..f1e8d7126 100644
--- a/web/src/lib/action-center/history.ts
+++ b/web/src/lib/action-center/history.ts
@@ -106,6 +106,8 @@ export interface ActionHistoryItem {
positionOutcome: ImproveOutcome | null;
tasks: ActionHistoryTask[];
assignee: { id: string; fullName: string | null; avatarUrl: string | null } | null;
+ /** `YYYY-MM-DD`; the Goal's date when set (AC-003). */
+ dueDate: string | null;
createdAt: string;
completedAt: string | null;
/** Calendar days from creation to close. Real — both stamps are recorded. */
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index 253bc834f..37d429bdc 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -192,21 +192,47 @@ export interface ActionDetail {
positionOutcome: ImproveOutcome | null;
}
-/** Everything the drawer's tabs need beyond the list row, in one round trip
- * per source. `kpis` are the brand's configured definitions among the
- * 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, places] = await Promise.all([
- supabase.from('action_tasks').select(TASK_COLUMNS).eq('action_id', actionId).order('position'),
- // Every signal the action has taken as evidence (AC-007), kept after a
- // signal moves on to a later cycle: a closed action still shows its own.
+/**
+ * Every signal the action has taken as evidence (AC-007), kept after a signal
+ * moves on to a later cycle: a closed action still shows its own. With where
+ * each prompt is tracked and its topic, as the Signals page reads them: the
+ * Affected tab's platforms and topics (AC-003).
+ */
+async function readActionSignals(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ brandId: string,
+ actionId: string,
+): Promise<Signal[]> {
+ const [signalsRes, places] = await Promise.all([
supabase
.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 }),
+ readPromptPlaces(supabase, brandId),
+ ]);
+ if (signalsRes.error) throw new Error(signalsRes.error.message);
+ return mapSignalRows((signalsRes.data ?? []) as SignalRow[], places);
+}
+
+/**
+ * An action's evidence alone, for a drawer that already has the rest: the
+ * History drawer's goal and what happened (AC-003).
+ */
+export async function getActionSignals(brandId: string, actionId: string): Promise<Signal[]> {
+ const supabase = await createClient();
+ return readActionSignals(supabase, brandId, actionId);
+}
+
+/** Everything the drawer's tabs need beyond the list row, in one round trip
+ * per source. `kpis` are the brand's configured definitions among the
+ * 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([
+ supabase.from('action_tasks').select(TASK_COLUMNS).eq('action_id', actionId).order('position'),
+ readActionSignals(supabase, brandId, actionId),
supabase
.from('action_events')
.select(EVENT_COLUMNS)
@@ -223,18 +249,14 @@ 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);
if (eventsRes.error) throw new Error(eventsRes.error.message);
if (kpisRes.error) throw new Error(kpisRes.error.message);
return {
tasks: (tasksRes.data ?? []).map(taskFromRow),
- signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[], places),
+ signals,
events: (eventsRes.data ?? []).map(eventFromRow),
kpis: (kpisRes.data ?? []).map(kpiFromRow),
positionOutcome: parseImproveOutcome(outcomeRes.data?.position_outcome ?? null),
diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.ts
index c78649262..220fccbd6 100644
--- a/web/src/lib/actions/action-history.ts
+++ b/web/src/lib/actions/action-history.ts
@@ -42,6 +42,7 @@ interface HistoryRow {
payload: Record<string, unknown>;
kpi_keys: string[];
assignee_id: string | null;
+ due_date: string | null;
created_at: string;
completed_at: string | null;
updated_at: string;
@@ -50,7 +51,7 @@ interface HistoryRow {
}
const HISTORY_COLUMNS =
- 'id, action_no, category, kind, status, outcome, validation, position_outcome, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at, priority_score, priority_level';
+ 'id, action_no, category, kind, status, outcome, validation, position_outcome, payload, kpi_keys, assignee_id, due_date, created_at, completed_at, updated_at, priority_score, priority_level';
/** What the validation sweep stores on an action. */
interface ValidationSnapshot {
@@ -260,6 +261,7 @@ export async function getActionHistory(
results,
tasks: tasksByAction.get(row.id) ?? [],
assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,
+ dueDate: row.due_date ?? null,
createdAt: row.created_at,
completedAt: row.completed_at,
timeToCloseDays: row.completed_at ? daysBetween(row.created_at, row.completed_at) : null,