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): History — what was done, and what has been measured (#815)
Gökhan Geyik4b8b792b6194
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 892b07d64..1edf62dff 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -75,10 +75,6 @@"signals": "What changed across your AI visibility data.","history": "What was done, and what it moved."},- "comingSoon": {- "title": "Coming soon",- "description": "This part of the Action Center is on its way. KPIs, Actions and Signals are live in the meantime."- },"categories": {"visibility": "Visibility","citations": "Citations",@@ -537,6 +533,132 @@"in_progress": "In Progress","completed": "Completed","canceled": "Canceled"+ },+ "historyPage": {+ "title": "History",+ "subtitle": "Browse past actions, what they were meant to do, and what has been measured since.",+ "table": {+ "action": "Action",+ "type": "Type",+ "impact": "Impact",+ "affected": "Affected",+ "result": "Result",+ "status": "Status",+ "date": "Date"+ },+ "status": {+ "new": "New",+ "in_progress": "In Progress",+ "completed": "Completed",+ "on_hold": "On Hold",+ "no_improvement": "No Improvement",+ "dismissed": "Dismissed"+ },+ "affected": {+ "prompt": "{count} prompts",+ "url": "{count} pages",+ "citation": "{count} signals",+ "keyword": "{count} keywords",+ "topic": "{count} topics",+ "competitor": "Competitor",+ "platform": "{count} platforms"+ },+ "validation": {+ "pending": "Not measured",+ "running": "Measuring",+ "improved": "Improved",+ "no_improvement": "No improvement",+ "declined": "Declined",+ "not_required": "Not applicable"+ },+ "validationHint": {+ "pending": "no result recorded",+ "running": "in progress",+ "improved": "vs before",+ "no_improvement": "vs before",+ "declined": "vs before",+ "not_required": "action was dismissed"+ },+ "validationExplain": {+ "pending": "This action's effect has not been measured. The metrics below fill in once validation runs.",+ "running": "Validation is running. Results appear when it finishes.",+ "improved": "Measured after this action closed.",+ "no_improvement": "Measured after this action closed; the metrics did not move.",+ "declined": "Measured after this action closed; the metrics moved the wrong way.",+ "not_required": "This action was dismissed, so nothing was measured."+ },+ "range": {+ "7d": "7d",+ "30d": "30d",+ "90d": "90d",+ "all": "All"+ },+ "sort": {+ "newest": "Newest",+ "oldest": "Oldest",+ "impact": "Impact"+ },+ "filters": {+ "status": "Status",+ "type": "Type",+ "impact": "Impact",+ "source": "Source",+ "sort": "Sort",+ "all": "All",+ "search": "Search actions…",+ "clear": "Clear filters"+ },+ "cards": {+ "total": "Total Actions",+ "totalSub": "in this window",+ "completed": "Completed",+ "inProgress": "In Progress",+ "noImprovement": "No Improvement",+ "dismissed": "Dismissed",+ "ofTotal": "{percent}% of total"+ },+ "pagination": {+ "showing": "Showing {from}–{to} of {total} actions",+ "page": "{page} / {pageCount}",+ "previous": "Previous",+ "next": "Next"+ },+ "drawer": {+ "goal": "What was the goal?",+ "whatHappened": "What happened?",+ "triggeredBy": "Consolidated from {count} signals",+ "result": "Result",+ "visibilityChange": "Visibility Change",+ "citationsChange": "Citations Change",+ "promptsImproved": "Prompts Improved",+ "timeToClose": "Time to Close",+ "vsBefore": "vs before",+ "netChange": "net change",+ "ofAffected": "of affected",+ "fromStart": "from start",+ "days": "{n} days",+ "affected": "Affected",+ "noAffected": "Nothing recorded.",+ "tasks": "Tasks ({completed}/{total})",+ "noTasks": "No tasks were created.",+ "viewAction": "View action →"+ },+ "empty": {+ "title": "No action history yet",+ "description": "Actions appear here once they are underway or closed. Nothing has reached that point for this brand."+ },+ "noMatch": {+ "title": "No actions match these filters",+ "clear": "Clear filters"+ },+ "error": {+ "title": "We couldn't load action history.",+ "retry": "Try again"+ },+ "noBrand": {+ "title": "No brand selected",+ "description": "Select a brand to view its action history."+ }}},"agent": {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.tsxindex 4e191c260..4f8368156 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@@ -1,5 +1,409 @@-import { ComingSoonPage } from '@/components/action-center/coming-soon-page';+'use client';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { AlertCircle, History as HistoryIcon, Search, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card, CardContent } from '@/components/ui/card';+import { Input } from '@/components/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { Skeleton } from '@/components/ui/skeleton';+import { useBrandStore } from '@/stores/use-brand-store';+import { getActionHistory } from '@/lib/actions/action-history';+import { actionTexts } from '@/lib/action-center/display';+import {+ HISTORY_PAGE_SIZE,+ HISTORY_SORTS,+ HISTORY_STATUSES,+ summarize,+ type ActionHistoryItem,+ type HistorySort,+} from '@/lib/action-center/history';+import {+ ACTION_CATEGORIES,+ ACTION_IMPACTS,+ type ActionCategory,+ type ActionImpact,+ type ActionStatus,+} from '@/lib/action-center/registry';+import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';+import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';+import { HistoryTable } from '@/components/action-center/history-table';+import { HistoryDrawer } from '@/components/action-center/history-drawer';+import { cn } from '@/lib/utils';++const RANGE_DAYS = { '7d': 7, '30d': 30, '90d': 90, all: null } as const;+type RangePreset = keyof typeof RANGE_DAYS;+const RANGE_PRESETS = Object.keys(RANGE_DAYS) as RangePreset[];++/**+ * History: what was done, and what it moved.+ *+ * Reads the same actions the Actions tab triages, but from the far end — an+ * action appears here once it has run its course. Every column except Result+ * comes from a recorded row; Result says what has been measured, which is+ * nothing yet, because no pass re-reads an action's metrics after it closes.+ * See lib/action-center/history.+ */export default function ActionCenterHistoryPage() {- return <ComingSoonPage tab="history" />;+ const brand = useBrandStore((s) => s.getActiveBrand());+ const brandId = brand?.id ?? null;+ const t = useTranslations('actionCenter.historyPage');+ const tTexts = useTranslations('actionCenter.actionTexts');+ const tTypes = useTranslations('actionCenter.actionCategories');+ const tActions = useTranslations('actionCenter.actionsPage');+ const tSources = useTranslations('actionCenter.signalsPage.sources');++ const [items, setItems] = useState<ActionHistoryItem[] | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [loadFailed, setLoadFailed] = useState(false);++ const [range, setRange] = useState<RangePreset>('30d');+ const [status, setStatus] = useState<ActionStatus | 'all'>('all');+ const [type, setType] = useState<ActionCategory | 'all'>('all');+ const [impact, setImpact] = useState<ActionImpact | 'all'>('all');+ const [source, setSource] = useState<SignalSource | 'all'>('all');+ const [search, setSearch] = useState('');+ const [sort, setSort] = useState<HistorySort>('newest');+ const [page, setPage] = useState(1);+ const [selected, setSelected] = useState<ActionHistoryItem | null>(null);++ const load = useCallback(async () => {+ if (!brandId) {+ setItems([]);+ setIsLoading(false);+ return;+ }+ setIsLoading(true);+ setLoadFailed(false);+ try {+ const days = RANGE_DAYS[range];+ const from = days ? new Date(Date.now() - days * 86_400_000).toISOString() : undefined;+ setItems(await getActionHistory(brandId, { from }));+ } catch {+ setLoadFailed(true);+ } finally {+ setIsLoading(false);+ }+ }, [brandId, range]);++ useEffect(() => {+ void load();+ }, [load]);++ // Any narrowing puts the reader back on page 1; staying on page 4 of a list+ // that now has one page shows nothing and looks like a failure.+ useEffect(() => {+ setPage(1);+ }, [status, type, impact, source, search, sort, range]);++ const filtered = useMemo(() => {+ const needle = search.trim().toLowerCase();+ const rows = (items ?? []).filter((item) => {+ if (status !== 'all' && item.status !== status) return false;+ if (type !== 'all' && item.type !== type) return false;+ if (impact !== 'all' && item.impact !== impact) return false;+ if (source !== 'all' && !item.sources.includes(source)) return false;+ if (needle) {+ // Titles are composed from i18n templates rather than stored, so the+ // search has to run against what the row actually renders.+ const texts = actionTexts(+ { kind: item.kind, payload: item.payload } as Parameters<typeof actionTexts>[0],+ tTexts,+ );+ const haystack = `${texts.title} ${texts.description} AC-${item.actionNo}`.toLowerCase();+ if (!haystack.includes(needle)) return false;+ }+ return true;+ });++ const impactRank = { high: 0, medium: 1, low: 2 };+ return rows.sort((a, b) => {+ const aDate = a.completedAt ?? a.createdAt;+ const bDate = b.completedAt ?? b.createdAt;+ switch (sort) {+ case 'oldest':+ return aDate.localeCompare(bDate);+ case 'impact':+ return impactRank[a.impact] - impactRank[b.impact] || bDate.localeCompare(aDate);+ default:+ return bDate.localeCompare(aDate);+ }+ });+ }, [items, status, type, impact, source, search, sort, tTexts]);++ const summary = useMemo(() => summarize(filtered), [filtered]);++ const pageCount = Math.max(1, Math.ceil(filtered.length / HISTORY_PAGE_SIZE));+ const visible = filtered.slice((page - 1) * HISTORY_PAGE_SIZE, page * HISTORY_PAGE_SIZE);++ const hasActiveFilters =+ status !== 'all' || type !== 'all' || impact !== 'all' || source !== 'all' || search !== '';++ const clearFilters = () => {+ setStatus('all');+ setType('all');+ setImpact('all');+ setSource('all');+ setSearch('');+ };++ const header = (+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ );++ if (!brandId) {+ return (+ <div className="space-y-6">+ {header}+ <ActionCenterTabs />+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">+ <h2 className="font-semibold">{t('noBrand.title')}</h2>+ <p className="mt-1 text-sm text-muted-foreground">{t('noBrand.description')}</p>+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-6">+ {header}+ <ActionCenterTabs />++ {isLoading ? (+ <div className="space-y-4">+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">+ {[0, 1, 2, 3, 4].map((i) => (+ <Skeleton key={i} className="h-24 w-full" />+ ))}+ </div>+ <div className="space-y-2">+ {[0, 1, 2, 3, 4, 5].map((i) => (+ <Skeleton key={i} className="h-14 w-full" />+ ))}+ </div>+ </div>+ ) : loadFailed ? (+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">+ <AlertCircle className="h-8 w-8 text-muted-foreground" />+ <h2 className="mt-4 font-semibold">{t('error.title')}</h2>+ <Button variant="outline" className="mt-4" onClick={() => void load()}>+ {t('error.retry')}+ </Button>+ </div>+ ) : !items?.length ? (+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">+ <HistoryIcon className="h-8 w-8 text-muted-foreground" />+ <h2 className="mt-4 font-semibold">{t('empty.title')}</h2>+ <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('empty.description')}</p>+ </div>+ ) : (+ <>+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">+ <SummaryCard+ label={t('cards.total')}+ value={summary.totalActions}+ sub={t('cards.totalSub')}+ />+ <SummaryCard+ label={t('cards.completed')}+ value={summary.completed}+ sub={t('cards.ofTotal', { percent: summary.completedPercent })}+ />+ <SummaryCard+ label={t('cards.inProgress')}+ value={summary.inProgress}+ sub={t('cards.ofTotal', { percent: summary.inProgressPercent })}+ />+ <SummaryCard+ label={t('cards.noImprovement')}+ value={summary.noImprovement}+ sub={t('cards.ofTotal', { percent: summary.noImprovementPercent })}+ />+ <SummaryCard+ label={t('cards.dismissed')}+ value={summary.dismissed}+ sub={t('cards.ofTotal', { percent: summary.dismissedPercent })}+ />+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <div className="inline-flex overflow-hidden rounded-md border">+ {RANGE_PRESETS.map((preset) => (+ <button+ key={preset}+ type="button"+ onClick={() => setRange(preset)}+ className={cn(+ 'px-3 py-1.5 text-xs font-medium transition-colors',+ range === preset+ ? 'bg-primary text-primary-foreground'+ : 'bg-card text-foreground hover:bg-muted',+ )}+ >+ {t(`range.${preset}`)}+ </button>+ ))}+ </div>+ <FilterSelect+ label={t('filters.status')}+ value={status}+ onChange={(v) => setStatus(v as ActionStatus | 'all')}+ options={HISTORY_STATUSES.map((v) => ({ value: v, label: t(`status.${v}`) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.type')}+ value={type}+ onChange={(v) => setType(v as ActionCategory | 'all')}+ options={ACTION_CATEGORIES.map((v) => ({ value: v, label: tTypes(v) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.impact')}+ value={impact}+ onChange={(v) => setImpact(v as ActionImpact | 'all')}+ options={ACTION_IMPACTS.map((v) => ({ value: v, label: tActions(`impact.${v}`) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.source')}+ value={source}+ onChange={(v) => setSource(v as SignalSource | 'all')}+ options={SIGNAL_SOURCES.map((v) => ({ value: v, label: tSources(v) }))}+ allLabel={t('filters.all')}+ />+ <FilterSelect+ label={t('filters.sort')}+ value={sort}+ onChange={(v) => setSort((v === 'all' ? 'newest' : v) as HistorySort)}+ options={HISTORY_SORTS.map((v) => ({ value: v, label: t(`sort.${v}`) }))}+ allLabel={t('sort.newest')}+ />+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t('filters.search')}+ className="h-8 w-56 pl-8 text-xs"+ />+ </div>+ {hasActiveFilters && (+ <Button variant="ghost" size="sm" className="text-xs" onClick={clearFilters}>+ <X className="h-3.5 w-3.5" />+ {t('filters.clear')}+ </Button>+ )}+ </div>++ {visible.length > 0 ? (+ <>+ <HistoryTable+ items={visible}+ selectedId={selected?.id ?? null}+ onSelect={setSelected}+ />+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">+ <span>+ {t('pagination.showing', {+ from: (page - 1) * HISTORY_PAGE_SIZE + 1,+ to: Math.min(page * HISTORY_PAGE_SIZE, filtered.length),+ total: filtered.length,+ })}+ </span>+ {pageCount > 1 && (+ <div className="flex items-center gap-1">+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs"+ disabled={page === 1}+ onClick={() => setPage((p) => Math.max(1, p - 1))}+ >+ {t('pagination.previous')}+ </Button>+ <span className="px-2 tabular-nums">+ {t('pagination.page', { page, pageCount })}+ </span>+ <Button+ variant="outline"+ size="sm"+ className="h-7 text-xs"+ disabled={page === pageCount}+ onClick={() => setPage((p) => Math.min(pageCount, p + 1))}+ >+ {t('pagination.next')}+ </Button>+ </div>+ )}+ </div>+ </>+ ) : (+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center">+ <h2 className="font-semibold">{t('noMatch.title')}</h2>+ <Button variant="outline" size="sm" className="mt-4 text-xs" onClick={clearFilters}>+ {t('noMatch.clear')}+ </Button>+ </div>+ )}+ </>+ )}++ <HistoryDrawer item={selected} onOpenChange={(open) => !open && setSelected(null)} />+ </div>+ );+}++function SummaryCard({ label, value, sub }: { label: string; value: number; sub: string }) {+ return (+ <Card>+ <CardContent className="p-4">+ <p className="text-xs font-medium text-muted-foreground">{label}</p>+ <p className="mt-1 text-2xl font-bold tabular-nums">{value}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">{sub}</p>+ </CardContent>+ </Card>+ );+}++function FilterSelect({+ label,+ value,+ onChange,+ options,+ allLabel,+}: {+ label: string;+ value: string;+ onChange: (value: string) => void;+ options: { value: string; label: string }[];+ allLabel: string;+}) {+ const items = [{ value: 'all', label: allLabel }, ...options];+ return (+ <Select value={value} onValueChange={(v) => onChange(v ?? 'all')} items={items}>+ <SelectTrigger className="h-8 w-36 text-xs">+ <span className="text-muted-foreground">{label}:</span>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">{allLabel}</SelectItem>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );}diff --git a/web/src/components/action-center/action-center-tabs.tsx b/web/src/components/action-center/action-center-tabs.tsxindex d28104729..88a1206a6 100644--- a/web/src/components/action-center/action-center-tabs.tsx+++ b/web/src/components/action-center/action-center-tabs.tsx@@ -7,18 +7,15 @@ import { useBrandStore } from '@/stores/use-brand-store';import { getNewSignalCount } from '@/lib/actions/signals';import { cn } from '@/lib/utils';-// History is deliberately absent: the route still answers, but a top-level-// tab that only ever says "coming soon" is a dead end for anyone who clicks-// it. It returns here when the page renders the action_events trail the-// action drawer already shows per action.const TABS = [{ key: 'kpis', href: '/dashboard/action-center/kpis' },{ key: 'actions', href: '/dashboard/action-center/actions' },{ key: 'signals', href: '/dashboard/action-center/signals' },+ { key: 'history', href: '/dashboard/action-center/history' },] as const;/**- * The Action Center's section nav: KPIs | Actions | Signals.+ * The Action Center's section nav: KPIs | Actions | Signals | History.* Route-backed rather than state-backed tabs so each section is linkable* and the browser back button works across them.*/diff --git a/web/src/components/action-center/coming-soon-page.tsx b/web/src/components/action-center/coming-soon-page.tsxdeleted file mode 100644index d70fac043..000000000--- a/web/src/components/action-center/coming-soon-page.tsx+++ /dev/null@@ -1,30 +0,0 @@-'use client';--import { useTranslations } from 'next-intl';-import { Hourglass } from 'lucide-react';-import { ActionCenterTabs } from './action-center-tabs';--/**- * Shell for an Action Center section whose route exists but whose page does- * not yet. Only History uses it now that Actions and Signals are real, and- * History is no longer in the tab bar — so this answers a deep link or a- * bookmark rather than a click, and says plainly where things stand.- */-export function ComingSoonPage({ tab }: { tab: 'history' }) {- const t = useTranslations('actionCenter');-- return (- <div className="space-y-6">- <div>- <h1 className="text-2xl font-bold tracking-tight">{t(`tabs.${tab}`)}</h1>- <p className="mt-1 text-sm text-muted-foreground">{t(`pages.${tab}`)}</p>- </div>- <ActionCenterTabs />- <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-20 text-center">- <Hourglass className="h-8 w-8 text-muted-foreground" />- <h2 className="mt-4 font-semibold">{t('comingSoon.title')}</h2>- <p className="mt-1 max-w-md text-sm text-muted-foreground">{t('comingSoon.description')}</p>- </div>- </div>- );-}diff --git a/web/src/components/action-center/history-drawer.tsx b/web/src/components/action-center/history-drawer.tsxnew file mode 100644index 000000000..750608aed--- /dev/null+++ b/web/src/components/action-center/history-drawer.tsx@@ -0,0 +1,242 @@+'use client';++import { useTranslations } from 'next-intl';+import { useRouter } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Separator } from '@/components/ui/separator';+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from '@/components/ui/sheet';+import { actionTexts } from '@/lib/action-center/display';+import type { ActionHistoryItem } from '@/lib/action-center/history';+import { ImpactDots } from './signal-table';+import { KIND_ICONS } from './action-table';+import { HistoryStatusBadge } from './history-table';+import { cn } from '@/lib/utils';++/**+ * One metric an action moved.+ *+ * Renders a dash rather than a zero when nothing has measured it: zero is a+ * measurement, and claiming one that was never taken is the failure this whole+ * tab exists to avoid.+ */+function ResultMetricCard({ label, value, sub }: { label: string; value: string; sub: string }) {+ return (+ <div className="rounded-md border p-3">+ <p className="text-[11px] text-muted-foreground">{label}</p>+ <p className="mt-1 text-lg font-semibold tabular-nums">{value}</p>+ <p className="text-[11px] text-muted-foreground">{sub}</p>+ </div>+ );+}++/**+ * What an action was, what opened it, what was carried out, and what it+ * achieved — in that order, because the last one is the question the tab is+ * for and the rest is the evidence behind it.+ */+export function HistoryDrawer({+ item,+ onOpenChange,+}: {+ item: ActionHistoryItem | null;+ onOpenChange: (open: boolean) => void;+}) {+ const t = useTranslations('actionCenter.historyPage');+ const tActions = useTranslations('actionCenter.actionsPage');+ const tTexts = useTranslations('actionCenter.actionTexts');+ const tTypes = useTranslations('actionCenter.actionCategories');+ const tTasks = useTranslations('actionCenter.actionTasks');+ const tTaskStatus = useTranslations('actionCenter.taskStatus');+ const tSources = useTranslations('actionCenter.signalsPage.sources');+ const tAffected = useTranslations('actionCenter.historyPage.affected');+ const router = useRouter();++ if (!item) return null;++ const Icon = KIND_ICONS[item.kind as keyof typeof KIND_ICONS];+ const texts = actionTexts(+ { kind: item.kind, payload: item.payload } as Parameters<typeof actionTexts>[0],+ tTexts,+ );+ const date = item.completedAt ?? item.createdAt;+ const measured = item.results.length > 0;+ const completedTasks = item.tasks.filter((task) => task.status === 'completed').length;+ const countedTasks = item.tasks.filter((task) => task.status !== 'canceled').length;++ const metricValue = (metric: string) => {+ const found = item.results.find((r) => r.metric === metric);+ if (!found) return '—';+ const delta = found.delta ?? 0;+ return `${delta > 0 ? '↑' : delta < 0 ? '↓' : ''}${Math.abs(delta)}${found.unit === 'percent' ? '%' : ''}`;+ };++ return (+ <Sheet open={Boolean(item)} onOpenChange={onOpenChange}>+ <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-lg">+ <SheetHeader className="border-b px-6 py-4">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <Badge variant="outline" className="text-[10px]">+ {tTypes(item.type)}+ </Badge>+ <span className="flex items-center gap-1.5 text-muted-foreground">+ <ImpactDots impact={item.impact} />+ {tActions(`impact.${item.impact}`)}+ </span>+ <HistoryStatusBadge status={item.status} />+ <span className="ml-auto text-muted-foreground">AC-{item.actionNo}</span>+ </div>+ <div className="flex items-start gap-3">+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">+ {Icon && <Icon className="h-4 w-4 text-muted-foreground" />}+ </div>+ <div className="min-w-0">+ <SheetTitle>{texts.title}</SheetTitle>+ <SheetDescription>+ {new Date(date).toLocaleDateString('en-US', {+ month: 'long',+ day: 'numeric',+ year: 'numeric',+ })}+ {item.sources.length > 0 && (+ <> · {item.sources.map((source) => tSources(source)).join(' · ')}</>+ )}+ </SheetDescription>+ </div>+ </div>+ </SheetHeader>++ <div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">+ <section>+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.goal')}</p>+ <p className="mt-1">{tTexts(`${item.kind}.goal`)}</p>+ </section>++ <Separator />++ <section>+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.whatHappened')}</p>+ <p className="mt-1">{texts.description}</p>+ {item.triggerSignals.length > 0 && (+ <p className="mt-1.5 text-xs text-muted-foreground">+ {t('drawer.triggeredBy', { count: item.triggerSignals.length })}+ </p>+ )}+ </section>++ <Separator />++ <section>+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.result')}</p>+ {!measured && (+ // The honest state, and the reason for it. Everything above this+ // line is recorded; the effect is not, because nothing re-reads+ // these metrics after an action closes.+ <p className="mt-1 text-xs text-muted-foreground">+ {t(`validationExplain.${item.validationStatus}`)}+ </p>+ )}+ <div className="mt-2 grid grid-cols-2 gap-2">+ <ResultMetricCard+ label={t('drawer.visibilityChange')}+ value={metricValue('visibility')}+ sub={t('drawer.vsBefore')}+ />+ <ResultMetricCard+ label={t('drawer.citationsChange')}+ value={metricValue('citations')}+ sub={t('drawer.netChange')}+ />+ <ResultMetricCard+ label={t('drawer.promptsImproved')}+ value={metricValue('prompts_improved')}+ sub={t('drawer.ofAffected')}+ />+ <ResultMetricCard+ label={t('drawer.timeToClose')}+ value={+ item.timeToCloseDays != null ? t('drawer.days', { n: item.timeToCloseDays }) : '—'+ }+ sub={t('drawer.fromStart')}+ />+ </div>+ </section>++ <Separator />++ <section>+ <p className="text-xs font-medium text-muted-foreground">{t('drawer.affected')}</p>+ {item.affected.length > 0 ? (+ <div className="mt-2 flex flex-wrap gap-1.5">+ {item.affected.map((entity) => (+ <Badge key={entity.id} variant="outline" className="text-[10px]">+ {entity.count != null+ ? tAffected(entity.type, { count: entity.count })+ : entity.name}+ </Badge>+ ))}+ </div>+ ) : (+ <p className="mt-1 text-xs text-muted-foreground">{t('drawer.noAffected')}</p>+ )}+ </section>++ <Separator />++ <section>+ <p className="text-xs font-medium text-muted-foreground">+ {t('drawer.tasks', { completed: completedTasks, total: countedTasks })}+ </p>+ {item.tasks.length > 0 ? (+ <ul className="mt-2 space-y-1.5">+ {item.tasks.map((task) => (+ <li key={task.id} className="flex items-start gap-2 text-sm">+ <span+ className={cn(+ 'mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full',+ task.status === 'completed' ? 'bg-emerald-500' : 'bg-muted-foreground/40',+ )}+ />+ <span+ className={cn(+ 'min-w-0 flex-1',+ (task.status === 'completed' || task.status === 'canceled') &&+ 'text-muted-foreground line-through',+ )}+ >+ {/* A user-written title arrives verbatim; a generated task+ arrives as its template key and is resolved here. */}+ {tTasks.has(task.title) ? tTasks(task.title) : task.title}+ </span>+ <span className="shrink-0 text-[11px] text-muted-foreground">+ {tTaskStatus(task.status)}+ </span>+ </li>+ ))}+ </ul>+ ) : (+ <p className="mt-1 text-xs text-muted-foreground">{t('drawer.noTasks')}</p>+ )}+ </section>+ </div>++ <div className="border-t px-6 py-3">+ <Button+ variant="outline"+ size="sm"+ className="w-full text-xs"+ onClick={() => router.push(`/dashboard/action-center/actions?action=${item.id}`)}+ >+ {t('drawer.viewAction')}+ </Button>+ </div>+ </SheetContent>+ </Sheet>+ );+}diff --git a/web/src/components/action-center/history-table.tsx b/web/src/components/action-center/history-table.tsxnew file mode 100644index 000000000..c3032cd66--- /dev/null+++ b/web/src/components/action-center/history-table.tsx@@ -0,0 +1,183 @@+'use client';++import { useTranslations } from 'next-intl';+import { Badge } from '@/components/ui/badge';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { actionTexts } from '@/lib/action-center/display';+import type { ActionHistoryItem } from '@/lib/action-center/history';+import type { ActionStatus } from '@/lib/action-center/registry';+import { ImpactDots } from './signal-table';+import { KIND_ICONS } from './action-table';+import { cn } from '@/lib/utils';++/** Low-saturation per type, the way the Signals table tints its categories —+ * enough to group at a glance, not enough to colour the row. */+const TYPE_TONES: Record<string, string> = {+ growth: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400',+ recover: 'border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-400',+ protect: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400',+ fix: 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-400',+ compete: 'border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-400',+};++const STATUS_TONES: Record<string, string> = {+ completed: 'text-emerald-600 dark:text-emerald-400',+ in_progress: 'text-blue-600 dark:text-blue-400',+ on_hold: 'text-muted-foreground',+ no_improvement: 'text-amber-600 dark:text-amber-400',+ dismissed: 'text-muted-foreground',+};++export function HistoryStatusBadge({ status }: { status: ActionStatus }) {+ const t = useTranslations('actionCenter.historyPage');+ return (+ <span className={cn('flex items-center gap-1.5 text-xs', STATUS_TONES[status])}>+ <span className="h-1.5 w-1.5 rounded-full bg-current" />+ {t(`status.${status}`)}+ </span>+ );+}++/**+ * The Result column.+ *+ * Nothing measures an action's effect yet, so every row says so rather than+ * showing a number that was never taken. When a validation pass starts filling+ * `results`, this is where its metrics land — the empty case stays for actions+ * closed before it ran.+ */+function ResultCell({ item }: { item: ActionHistoryItem }) {+ const t = useTranslations('actionCenter.historyPage');++ if (item.results.length > 0) {+ return (+ <div className="space-y-0.5">+ {item.results.slice(0, 2).map((metric) => (+ <p key={metric.id} className="text-xs tabular-nums">+ {(metric.delta ?? 0) > 0 ? '↑' : '↓'} {Math.abs(metric.delta ?? 0)} {metric.label}+ </p>+ ))}+ </div>+ );+ }++ return (+ <div className="space-y-0.5">+ <p className="text-xs text-muted-foreground">{t(`validation.${item.validationStatus}`)}</p>+ <p className="text-[11px] text-muted-foreground/70">+ {t(`validationHint.${item.validationStatus}`)}+ </p>+ </div>+ );+}++export function HistoryTable({+ items,+ selectedId,+ onSelect,+}: {+ items: ActionHistoryItem[];+ selectedId: string | null;+ onSelect: (item: ActionHistoryItem) => void;+}) {+ const t = useTranslations('actionCenter.historyPage');+ const tActions = useTranslations('actionCenter.actionsPage');+ const tTexts = useTranslations('actionCenter.actionTexts');+ const tTypes = useTranslations('actionCenter.actionCategories');+ const tAffected = useTranslations('actionCenter.historyPage.affected');++ return (+ <div className="overflow-x-auto rounded-lg border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="text-xs">{t('table.action')}</TableHead>+ <TableHead className="text-xs">{t('table.type')}</TableHead>+ <TableHead className="text-xs">{t('table.impact')}</TableHead>+ <TableHead className="text-xs">{t('table.affected')}</TableHead>+ <TableHead className="text-xs">{t('table.result')}</TableHead>+ <TableHead className="text-xs">{t('table.status')}</TableHead>+ <TableHead className="text-xs">{t('table.date')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {items.map((item) => {+ const Icon = KIND_ICONS[item.kind as keyof typeof KIND_ICONS];+ const texts = actionTexts(+ { kind: item.kind, payload: item.payload } as Parameters<typeof actionTexts>[0],+ tTexts,+ );+ const date = item.completedAt ?? item.createdAt;+ return (+ <TableRow+ key={item.id}+ className={cn('cursor-pointer', selectedId === item.id && 'bg-muted/50')}+ onClick={() => onSelect(item)}+ >+ <TableCell className="max-w-[360px]">+ <div className="flex items-start gap-3">+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-muted/40">+ {Icon && <Icon className="h-4 w-4 text-muted-foreground" />}+ </div>+ <div className="min-w-0">+ <p className="truncate text-sm font-medium">{texts.title}</p>+ <p className="truncate text-xs text-muted-foreground">{texts.description}</p>+ <p className="mt-0.5 text-[11px] text-muted-foreground/70">+ AC-{item.actionNo}+ </p>+ </div>+ </div>+ </TableCell>+ <TableCell>+ <Badge variant="outline" className={cn('text-[10px]', TYPE_TONES[item.type])}>+ {tTypes(item.type)}+ </Badge>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ <span className="text-xs">{tActions(`impact.${item.impact}`)}</span>+ <ImpactDots impact={item.impact} />+ </div>+ </TableCell>+ <TableCell>+ <div className="space-y-0.5">+ {item.affected.slice(0, 2).map((entity) => (+ <p key={entity.id} className="text-xs text-muted-foreground">+ {entity.count != null+ ? tAffected(entity.type, { count: entity.count })+ : entity.name}+ </p>+ ))}+ {item.affected.length === 0 && (+ <p className="text-xs text-muted-foreground">—</p>+ )}+ </div>+ </TableCell>+ <TableCell>+ <ResultCell item={item} />+ </TableCell>+ <TableCell>+ <HistoryStatusBadge status={item.status} />+ </TableCell>+ <TableCell className="text-xs tabular-nums text-muted-foreground">+ {new Date(date).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ })}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ );+}diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsnew file mode 100644index 000000000..2b324e41a--- /dev/null+++ b/web/src/lib/action-center/history.ts@@ -0,0 +1,209 @@+/**+ * The shapes the History tab reads, and the honest state of each one.+ *+ * History answers a narrower question than the Actions tab: not "what should+ * we do", but "what did we do, and did it work". The second half of that has+ * two parts, and only one of them exists yet.+ *+ * What the product already knows, and this tab shows from real rows: which+ * action ran, what kind it was, what it touched, which signals opened it,+ * what its goal was, which tasks were carried out, who it was assigned to,+ * when it closed and how long that took.+ *+ * What nothing yet measures: the result. An action's `baseline` captures the+ * triggering signals' values at the moment it was created, so the "before"+ * half is recorded — but no pass re-reads those metrics afterwards, so there+ * is no "after" to compare it to. Visibility change, citations change, prompts+ * improved: none of them have a source.+ *+ * So `results` comes back empty and `validationStatus` says `pending` rather+ * than a number, and the UI says so plainly instead of implying a measurement+ * that did not happen. The types below are the full shape a validation pass+ * would fill in; adding it is a matter of populating these, not reshaping+ * them.+ */++import type { ActionCategory, ActionImpact, ActionStatus } from './registry';+import type { SignalSource } from '@/lib/signals/registry';++/**+ * Whether an action's effect has been measured.+ *+ * Distinct from ActionStatus on purpose: an action can be `completed` while+ * its validation is still `pending`, which is exactly the state every closed+ * action is in today. `not_required` is for actions that were dismissed —+ * nothing ran, so there is nothing to measure.+ */+export type ValidationStatus =+ | 'pending'+ | 'running'+ | 'improved'+ | 'no_improvement'+ | 'declined'+ | 'not_required';++/** A metric an action moved, read before and after it ran. */+export interface ActionResultMetric {+ id: string;+ label: string;+ metric:+ | 'visibility'+ | 'citations'+ | 'mentions'+ | 'traffic'+ | 'share_of_voice'+ | 'prompts_improved'+ | 'custom';+ before?: number;+ after?: number;+ delta?: number;+ deltaPercent?: number;+ unit: 'percent' | 'number' | 'sessions' | 'citations' | 'mentions' | 'prompts';+ direction: 'higher_is_better' | 'lower_is_better';+}++/** Something an action touched. Deliberately generic — an action's subject is+ * prompts for one kind and pages for another, and the column shows whichever+ * the payload actually carries. */+export interface AffectedEntity {+ id: string;+ type: 'prompt' | 'url' | 'keyword' | 'topic' | 'citation' | 'competitor' | 'platform';+ /** Either a named entity, or a bare count when the payload holds only a number. */+ name: string;+ count?: number;+ url?: string;+ platform?: string;+ beforeValue?: string | number;+ afterValue?: string | number;+}++/** A task as it stood when the action closed. */+export interface ActionHistoryTask {+ id: string;+ /** Resolved text: the user's title when they wrote one, else the template. */+ title: string;+ status: 'completed' | 'skipped' | 'failed' | 'todo' | 'in_progress' | 'canceled';+ completedAt?: string;+}++/** A signal that opened the action. Several signals consolidate into one+ * action, so this is a list rather than a field. */+export interface TriggerSignal {+ signalId: string;+ kind: string;+ detectedAt: string;+}++export interface ActionHistoryItem {+ id: string;+ actionNo: number;+ kind: string;+ /** Grow / Recover / Protect / Fix / Compete — the module's one classification. */+ type: ActionCategory;+ impact: ActionImpact;+ status: ActionStatus;+ validationStatus: ValidationStatus;+ payload: Record<string, unknown>;+ kpiKeys: string[];+ sources: SignalSource[];+ triggerSignals: TriggerSignal[];+ affected: AffectedEntity[];+ /** Empty until something measures an action's effect. */+ results: ActionResultMetric[];+ tasks: ActionHistoryTask[];+ assignee: { id: string; fullName: string | null; avatarUrl: string | null } | null;+ createdAt: string;+ completedAt: string | null;+ /** Calendar days from creation to close. Real — both stamps are recorded. */+ timeToCloseDays: number | null;+}++export interface HistorySummary {+ totalActions: number;+ completed: number;+ completedPercent: number;+ inProgress: number;+ inProgressPercent: number;+ noImprovement: number;+ noImprovementPercent: number;+ dismissed: number;+ dismissedPercent: number;+ /** Highest impact among the actions in range — a readout of what was worked+ * on, not a claim about what it achieved. That claim needs validation. */+ topImpact: ActionImpact | null;+}++/** Statuses History covers: an action that has run its course, plus the ones+ * still running so the tab shows the whole arc rather than only its end. */+export const HISTORY_STATUSES: readonly ActionStatus[] = [+ 'in_progress',+ 'completed',+ 'no_improvement',+ 'dismissed',+ 'on_hold',+];++export const HISTORY_SORTS = ['newest', 'oldest', 'impact'] as const;+export type HistorySort = (typeof HISTORY_SORTS)[number];++export const HISTORY_PAGE_SIZE = 10;++const pct = (part: number, total: number) => (total === 0 ? 0 : Math.round((part / total) * 100));++export function summarize(items: ActionHistoryItem[]): HistorySummary {+ const total = items.length;+ const count = (status: ActionStatus) => items.filter((i) => i.status === status).length;+ const completed = count('completed');+ const inProgress = count('in_progress');+ const noImprovement = count('no_improvement');+ const dismissed = count('dismissed');++ const impacts = items.map((i) => i.impact);+ const topImpact: ActionImpact | null = impacts.includes('high')+ ? 'high'+ : impacts.includes('medium')+ ? 'medium'+ : impacts.includes('low')+ ? 'low'+ : null;++ return {+ totalActions: total,+ completed,+ completedPercent: pct(completed, total),+ inProgress,+ inProgressPercent: pct(inProgress, total),+ noImprovement,+ noImprovementPercent: pct(noImprovement, total),+ dismissed,+ dismissedPercent: pct(dismissed, total),+ topImpact,+ };+}++/**+ * Whether an action's effect has been measured.+ *+ * Every closed action answers `pending` today, and a dismissed one answers+ * `not_required` — nothing ran, so there is nothing to measure. The other+ * values exist for the validation pass to return; nothing produces them yet,+ * and inferring one from the action's own status would be inventing the+ * measurement rather than reporting it.+ */+export function validationStatusFor(+ status: ActionStatus,+ results: ActionResultMetric[],+): ValidationStatus {+ if (status === 'dismissed') return 'not_required';+ if (results.length === 0) return 'pending';+ const improved = results.some((r) =>+ r.direction === 'higher_is_better' ? (r.delta ?? 0) > 0 : (r.delta ?? 0) < 0,+ );+ return improved ? 'improved' : 'no_improvement';+}++/** Whole days between two stamps, floored — "4 days" means four elapsed. */+export function daysBetween(fromIso: string, toIso: string): number {+ const ms = new Date(toIso).getTime() - new Date(fromIso).getTime();+ return Math.max(0, Math.floor(ms / 86_400_000));+}diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsnew file mode 100644index 000000000..17ee8489b--- /dev/null+++ b/web/src/lib/actions/action-history.ts@@ -0,0 +1,213 @@+'use server';++/**+ * The History tab's reads.+ *+ * One query per source, assembled here rather than in the component, so the+ * tab makes a single round trip for a page of rows and the shapes it renders+ * are settled before they reach React.+ *+ * Everything returned is read from rows the product already writes. The one+ * field that is deliberately empty is `results` — see lib/action-center/history+ * for why, and for the shape a validation pass would fill.+ */++import { createClient } from '@/lib/supabase/server';+import { isActionKind, type ActionCategory, type ActionImpact } from '@/lib/action-center/registry';+import type { ActionStatus, TaskStatus } from '@/lib/action-center/registry';+import { SIGNAL_SOURCES, type SignalSource } from '@/lib/signals/registry';+import {+ HISTORY_STATUSES,+ daysBetween,+ validationStatusFor,+ type ActionHistoryItem,+ type ActionHistoryTask,+ type ActionResultMetric,+ type AffectedEntity,+ type TriggerSignal,+} from '@/lib/action-center/history';++interface HistoryRow {+ id: string;+ action_no: number;+ category: string;+ kind: string;+ impact: string;+ status: string;+ payload: Record<string, unknown>;+ kpi_keys: string[];+ assignee_id: string | null;+ created_at: string;+ completed_at: string | null;+ updated_at: string;+}++const HISTORY_COLUMNS =+ 'id, action_no, category, kind, impact, status, payload, kpi_keys, assignee_id, created_at, completed_at, updated_at';++function num(payload: Record<string, unknown>, key: string): number {+ const value = payload[key];+ return typeof value === 'number' ? value : 0;+}++/**+ * What an action touched, from its payload.+ *+ * Generic by design: the subject is prompts for one kind and pages for+ * another, so this reports whichever counts the payload actually carries+ * rather than forcing every action into the same two columns.+ */+function affectedFrom(+ kind: string,+ payload: Record<string, unknown>,+ signalCount: number,+): AffectedEntity[] {+ const entities: AffectedEntity[] = [];+ const add = (type: AffectedEntity['type'], count: number) => {+ if (count > 0) entities.push({ id: `${type}-${count}`, type, name: type, count });+ };++ add('prompt', num(payload, 'promptCount'));+ add('url', num(payload, 'pageCount'));+ add('citation', num(payload, 'citationCount'));++ const competitors = Array.isArray(payload.competitorNames)+ ? (payload.competitorNames as string[])+ : [];+ for (const name of competitors.slice(0, 5)) {+ entities.push({ id: `competitor-${name}`, type: 'competitor', name });+ }++ // Every action has at least its signals to show, so a row is never blank.+ if (entities.length === 0 && signalCount > 0) {+ entities.push({+ id: `citation-${signalCount}`,+ type: 'citation',+ name: 'citation',+ count: signalCount,+ });+ }+ return entities;+}++/**+ * A page of history for one brand.+ *+ * Filtering and sorting happen in Postgres so pagination counts what the user+ * is actually looking at; search runs client-side, because an action's title+ * is composed from i18n templates and never stored as text.+ */+export async function getActionHistory(+ brandId: string,+ opts?: { from?: string; to?: string },+): Promise<ActionHistoryItem[]> {+ const supabase = await createClient();++ let query = supabase+ .from('actions')+ .select(HISTORY_COLUMNS)+ .eq('brand_id', brandId)+ .in('status', HISTORY_STATUSES as string[])+ .order('created_at', { ascending: false })+ .limit(500);++ // The window covers when an action closed, falling back to when it was+ // raised for one still running — which is the date the row shows.+ if (opts?.from) query = query.gte('created_at', opts.from);+ if (opts?.to) query = query.lte('created_at', opts.to);++ const { data, error } = await query;+ if (error) throw new Error(error.message);++ const rows = ((data ?? []) as HistoryRow[]).filter((row) => isActionKind(row.kind));+ if (rows.length === 0) return [];++ 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([+ supabase+ .from('action_tasks')+ .select('id, action_id, position, task_key, title, status')+ .in('action_id', actionIds)+ .order('position'),+ supabase+ .from('signals')+ .select('id, action_id, kind, source, detected_at')+ .eq('brand_id', brandId)+ .in('action_id', actionIds),+ assigneeIds.length > 0+ ? supabase.from('profiles').select('id, full_name, avatar_url').in('id', assigneeIds)+ : Promise.resolve({ data: [], error: null }),+ ]);+ if (tasksRes.error) throw new Error(tasksRes.error.message);+ if (signalsRes.error) throw new Error(signalsRes.error.message);+ if (profilesRes.error) throw new Error(profilesRes.error.message);++ const tasksByAction = new Map<string, ActionHistoryTask[]>();+ for (const task of tasksRes.data ?? []) {+ const list = tasksByAction.get(task.action_id) ?? [];+ list.push({+ id: task.id,+ // Resolved by the caller through i18n when there is no user title; the+ // key travels in `title` so the component can tell the two apart.+ title: task.title ?? task.task_key ?? '',+ status: task.status as TaskStatus,+ });+ tasksByAction.set(task.action_id, list);+ }++ const signalsByAction = new Map<string, TriggerSignal[]>();+ const sourcesByAction = new Map<string, Set<SignalSource>>();+ for (const signal of signalsRes.data ?? []) {+ if (!signal.action_id) continue;+ const list = signalsByAction.get(signal.action_id) ?? [];+ list.push({ signalId: signal.id, kind: signal.kind, detectedAt: signal.detected_at });+ signalsByAction.set(signal.action_id, list);++ // `source` is an array — one signal can be corroborated by several feeds.+ const set = sourcesByAction.get(signal.action_id) ?? new Set<SignalSource>();+ for (const source of (signal.source ?? []) as string[]) {+ if ((SIGNAL_SOURCES as readonly string[]).includes(source)) set.add(source as SignalSource);+ }+ if (set.size > 0) sourcesByAction.set(signal.action_id, set);+ }++ const profiles = new Map(+ (profilesRes.data ?? []).map((p) => [+ p.id as string,+ {+ id: p.id as string,+ fullName: (p.full_name as string | null) ?? null,+ avatarUrl: (p.avatar_url as string | null) ?? null,+ },+ ]),+ );++ return rows.map((row) => {+ const triggerSignals = signalsByAction.get(row.id) ?? [];+ // Empty until something measures an action's effect — see+ // lib/action-center/history for why, and for the shape it would fill.+ const results: ActionResultMetric[] = [];+ return {+ id: row.id,+ actionNo: Number(row.action_no),+ kind: row.kind,+ type: row.category as ActionCategory,+ impact: row.impact as ActionImpact,+ status: row.status as ActionStatus,+ validationStatus: validationStatusFor(row.status as ActionStatus, results),+ payload: row.payload ?? {},+ kpiKeys: row.kpi_keys ?? [],+ sources: [...(sourcesByAction.get(row.id) ?? [])],+ triggerSignals,+ affected: affectedFrom(row.kind, row.payload ?? {}, triggerSignals.length),+ results,+ tasks: tasksByAction.get(row.id) ?? [],+ assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,+ createdAt: row.created_at,+ completedAt: row.completed_at,+ timeToCloseDays: row.completed_at ? daysBetween(row.created_at, row.completed_at) : null,+ };+ });+}