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(chat): add the Activity log page, with Undo and CSV (#1791)

Cihan24ec2ce5d1e1
diff --git a/web/messages/en.json b/web/messages/en.json
index 209a1f650..59643f0c0 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3815,6 +3815,68 @@
"removed": "Removed: it asks again"
}
},
+ "activity": {
+ "title": "Activity log",
+ "lead": "Every change Chat made, every Undo and everything it wasn't allowed to do. You see your own; Admins see the workspace's.",
+ "loadError": "Couldn't load the Activity log. Try again in a moment.",
+ "retry": "Retry",
+ "empty": "Nothing here yet: Chat's changes show up here as they happen.",
+ "emptyFiltered": "Nothing matches these filters.",
+ "loadMore": "Load more",
+ "export": "Export CSV",
+ "exported": "Exported the Activity log",
+ "exportFailed": "Couldn't export it. Try again.",
+ "clear": "Clear",
+ "autoOnly": "Auto changes only",
+ "you": "You",
+ "seeLog": "See the Activity log",
+ "filters": {
+ "person": "Person",
+ "everyone": "Everyone",
+ "area": "Area",
+ "allAreas": "All areas",
+ "kind": "Class",
+ "allKinds": "All",
+ "kinds": { "write": "WRITE", "execute": "EXECUTE", "denied": "Not allowed" }
+ },
+ "columns": {
+ "when": "When",
+ "who": "Who",
+ "event": "Event",
+ "class": "Class",
+ "approval": "Approval",
+ "undo": "Undo"
+ },
+ "surfaces": {
+ "chat": "chat",
+ "agent": "agent",
+ "mcp": "MCP",
+ "schedule": "schedule",
+ "watch_rule": "watch rule"
+ },
+ "approval": {
+ "denied": "Not allowed",
+ "card": "Approved on its card",
+ "click": "Your click",
+ "always": "Auto · policy Always",
+ "full_auto": "Auto · Full auto",
+ "dont_ask_again": "Auto · “Don't ask again”",
+ "run": "Ran"
+ },
+ "denials": {
+ "brand_scope": "Brand not shared",
+ "subscription_inactive": "Read-only workspace",
+ "demo_brand": "Demo brand",
+ "policy_never": "Turned off by an Admin",
+ "plan_locked": "Needs another plan",
+ "forbidden_role": "Role doesn't allow it",
+ "execute_off": "Off for Managers",
+ "no_access": "No access"
+ },
+ "status": { "done": "Done", "undone": "Undone", "undo_conflict": "Changed since" },
+ "undo": "Undo",
+ "openToUndo": "Open it"
+ },
"yourAccess": {
"title": "Your access",
"brands": "Brands",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/activity/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/chat/activity/page.tsx
new file mode 100644
index 000000000..c11b0e9b3
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/activity/page.tsx
@@ -0,0 +1,29 @@
+import { notFound } from 'next/navigation';
+import { createClient } from '@/lib/supabase/server';
+import { chatAgenticEnabled } from '@/lib/chat/flag';
+import { CHAT_TOOLS } from '@/lib/chat/registry/tools';
+import { ActivityLogView } from '@/components/chat-access/activity-log-view';
+
+/**
+ * The Activity log (CHAT-20 §10a; mockup #g-activity): every change Chat
+ * made, every Undo and every denial, with Undo while it is open, and CSV
+ * for Admins. Only with the new Chat on for the workspace.
+ */
+export default async function ChatActivityPage() {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) notFound();
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', user.id)
+ .single();
+ if (!chatAgenticEnabled(profile?.organization_id)) notFound();
+ // The areas the registry's changes belong to, in its order, for the Area filter.
+ const areas = [
+ ...new Set(CHAT_TOOLS.filter((tool) => tool.class !== 'read').map((tool) => tool.area)),
+ ];
+ return <ActivityLogView areas={areas} />;
+}
diff --git a/web/src/components/chat-access/activity-log-view.test.tsx b/web/src/components/chat-access/activity-log-view.test.tsx
new file mode 100644
index 000000000..935d5457d
--- /dev/null
+++ b/web/src/components/chat-access/activity-log-view.test.tsx
@@ -0,0 +1,180 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import type { ActivityRow } from '@/lib/chat/activity-view';
+
+/** The Activity log page (CHAT-20 §10a, mockup #g-activity). */
+
+const actions = vi.hoisted(() => ({
+ listActivity: vi.fn(),
+ undoActivity: vi.fn(),
+ exportActivityCsv: vi.fn(),
+}));
+vi.mock('@/lib/actions/chat-activity', () => actions);
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (
+ <a href={href} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { ActivityLogView } = await import('./activity-log-view');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ for (const fn of [...Object.values(actions), ...Object.values(toast)]) fn.mockReset();
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+const row = (over: Partial<ActivityRow> = {}): ActivityRow => ({
+ id: 'a1',
+ at: '2026-10-29T10:41:00Z',
+ userId: 'u1',
+ person: 'Alex Kim',
+ isYou: false,
+ surface: 'chat',
+ kind: 'change',
+ toolKey: 'saveDraft',
+ area: 'content',
+ class: 'write',
+ mode: 'full_auto',
+ approvalKind: 'auto',
+ autoVia: 'full_auto',
+ denialCode: null,
+ summaryKey: 'saveDraft',
+ summaryParams: { title: 'Pricing FAQ' },
+ status: 'done',
+ canUndo: true,
+ undoneAt: null,
+ ...over,
+});
+const page = (over = {}) => ({
+ ok: true,
+ isAdmin: false,
+ rows: [row()],
+ hasMore: false,
+ people: [],
+ ...over,
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <ActivityLogView areas={['content', 'prompts']} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const text = () => container.textContent ?? '';
+const button = (label: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === label);
+
+describe('ActivityLogView', () => {
+ it('says what happened in words, how it ran, and offers Undo', async () => {
+ actions.listActivity.mockResolvedValue(
+ page({
+ rows: [
+ row(),
+ row({
+ id: 'a2',
+ kind: 'access.denied',
+ summaryKey: 'accessDenied',
+ summaryParams: { tool: 'Dismiss prompt suggestions' },
+ denialCode: 'forbidden_role',
+ approvalKind: null,
+ canUndo: false,
+ }),
+ ],
+ }),
+ );
+ await render();
+ expect(text()).toContain('Saved the draft “Pricing FAQ”');
+ expect(text()).toContain('Auto · Full auto');
+ expect(text()).toContain('Not allowed: Dismiss prompt suggestions');
+ expect(text()).toContain("Role doesn't allow it");
+ expect(text()).not.toContain('create_draft');
+ expect(button('Export CSV')).toBeUndefined();
+ actions.undoActivity.mockResolvedValue({
+ ok: true,
+ code: 'ok',
+ message: 'Undone.',
+ href: null,
+ });
+ await act(async () => button('Undo')!.click());
+ expect(actions.undoActivity).toHaveBeenCalledWith('a1');
+ expect(toast.success).toHaveBeenCalledWith('Undone.');
+ expect(actions.listActivity).toHaveBeenCalledTimes(2);
+ });
+
+ it('links a change that changed since, to undo by hand', async () => {
+ actions.listActivity.mockResolvedValueOnce(page());
+ actions.undoActivity.mockResolvedValue({
+ ok: true,
+ code: 'conflict',
+ message: 'This changed since. Open it to undo by hand.',
+ href: '/dashboard/content/d1',
+ });
+ actions.listActivity.mockResolvedValue(
+ page({ rows: [row({ status: 'undo_conflict', canUndo: false })] }),
+ );
+ await render();
+ await act(async () => button('Undo')!.click());
+ expect(toast.info).toHaveBeenCalledWith('This changed since. Open it to undo by hand.');
+ expect(container.querySelector('a[href="/dashboard/content/d1"]')?.textContent).toBe('Open it');
+ expect(text()).toContain('Changed since');
+ });
+
+ it('reads again on a filter, and gives an Admin the person filter and CSV', async () => {
+ actions.listActivity.mockResolvedValue(
+ page({ isAdmin: true, people: [{ id: 'u2', name: 'Taylor Brooks' }] }),
+ );
+ await render();
+ expect(text()).toContain('Taylor Brooks');
+ const kind = [...container.querySelectorAll('select')].find((s) =>
+ [...s.options].some((o) => o.value === 'denied'),
+ )!;
+ await act(async () => {
+ kind.value = 'denied';
+ kind.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ expect(actions.listActivity).toHaveBeenLastCalledWith({ kind: 'denied' });
+ actions.exportActivityCsv.mockResolvedValue({ ok: false, failure: 'failed' });
+ await act(async () => button('Export CSV')!.click());
+ expect(actions.exportActivityCsv).toHaveBeenCalledWith({ kind: 'denied', before: undefined });
+ expect(toast.error).toHaveBeenCalledWith("Couldn't export it. Try again.");
+ });
+
+ it('pages on with Load more, and says so in plain words when it can’t be read', async () => {
+ actions.listActivity.mockResolvedValueOnce(page({ hasMore: true }));
+ actions.listActivity.mockResolvedValueOnce(
+ page({ rows: [row({ id: 'a9', summaryParams: { title: 'Older' } })] }),
+ );
+ await render();
+ await act(async () => button('Load more')!.click());
+ expect(actions.listActivity).toHaveBeenLastCalledWith({ before: '2026-10-29T10:41:00Z' });
+ expect(text()).toContain('Saved the draft “Older”');
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ actions.listActivity.mockResolvedValue({ ok: false, failure: 'failed' });
+ await render();
+ expect(text()).toContain("Couldn't load the Activity log.");
+ expect(button('Retry')).toBeDefined();
+ });
+});
diff --git a/web/src/components/chat-access/activity-log-view.tsx b/web/src/components/chat-access/activity-log-view.tsx
new file mode 100644
index 000000000..0aef2665e
--- /dev/null
+++ b/web/src/components/chat-access/activity-log-view.tsx
@@ -0,0 +1,344 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { ArrowUpRight, Download, Loader2 } from 'lucide-react';
+import { toast } from 'sonner';
+import { Link } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { exportActivityCsv, listActivity, undoActivity } from '@/lib/actions/chat-activity';
+import { approvalLabel, type ActivityFilters, type ActivityRow } from '@/lib/chat/activity-view';
+import type { ToolArea } from '@/lib/chat/registry/define-tool';
+import { cn } from '@/lib/utils';
+import { ClassBadge } from './class-badge';
+
+const SELECT =
+ 'h-8 rounded-md border bg-background px-2 text-xs text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50';
+
+interface Page {
+ isAdmin: boolean;
+ rows: ActivityRow[];
+ hasMore: boolean;
+ people: { id: string; name: string }[];
+}
+
+/**
+ * The Activity log (CHAT-20 §10a): newest first, filtered by person (an
+ * Admin's), area, class and "Auto changes only", with Undo on a change while
+ * its window is open and CSV for Admins. Each row says what happened in
+ * words (chatActivity.summary), never a tool's name.
+ */
+export function ActivityLogView({ areas }: { areas: ToolArea[] }) {
+ const t = useTranslations('chatAccess.activity');
+ const tAreas = useTranslations('chatAccess.capabilities.areaNames');
+ const tSummary = useTranslations('chatActivity.summary');
+ const tTools = useTranslations('chatTools');
+ const format = useFormatter();
+ const [filters, setFilters] = useState<ActivityFilters>({});
+ const [page, setPage] = useState<Page | 'failed' | null>(null);
+ const [version, setVersion] = useState(0);
+ const [more, setMore] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [exporting, setExporting] = useState(false);
+ // Where to undo by hand a change that changed since, by row.
+ const [conflicts, setConflicts] = useState<Record<string, string | null>>({});
+
+ useEffect(() => {
+ let live = true;
+ listActivity(filters)
+ .then((read) => {
+ if (!live) return;
+ setPage(read.ok ? read : 'failed');
+ })
+ .catch(() => {
+ if (live) setPage('failed');
+ });
+ return () => {
+ live = false;
+ };
+ }, [filters, version]);
+
+ if (page === null) return <Skeleton className="h-96 w-full" />;
+ if (page === 'failed') {
+ return (
+ <div role="status" className="space-y-2 text-sm text-muted-foreground">
+ <h1 className="text-2xl font-bold tracking-tight text-foreground">{t('title')}</h1>
+ <p>{t('loadError')}</p>
+ <Button size="sm" variant="outline" onClick={() => setVersion((n) => n + 1)}>
+ {t('retry')}
+ </Button>
+ </div>
+ );
+ }
+
+ const filtered = !!(filters.userId || filters.area || filters.kind || filters.autoOnly);
+ const set = (next: Partial<ActivityFilters>) => setFilters((f) => ({ ...f, ...next }));
+
+ async function loadMore(current: Page) {
+ const last = current.rows.at(-1);
+ if (!last) return;
+ setMore(true);
+ try {
+ const read = await listActivity({ ...filters, before: last.at });
+ if (read.ok) {
+ setPage({ ...current, rows: [...current.rows, ...read.rows], hasMore: read.hasMore });
+ } else {
+ toast.error(t('loadError'));
+ }
+ } finally {
+ setMore(false);
+ }
+ }
+
+ async function undo(row: ActivityRow) {
+ setBusy(row.id);
+ try {
+ const result = await undoActivity(row.id);
+ if (!result.ok) {
+ toast.error(t('loadError'));
+ return;
+ }
+ if (result.code === 'ok') toast.success(result.message);
+ else toast.info(result.message);
+ if (result.code === 'conflict') setConflicts((c) => ({ ...c, [row.id]: result.href }));
+ setVersion((n) => n + 1);
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ async function exportCsv() {
+ setExporting(true);
+ try {
+ const result = await exportActivityCsv({ ...filters, before: undefined });
+ if (!result.ok) {
+ toast.error(t('exportFailed'));
+ return;
+ }
+ const url = URL.createObjectURL(new Blob([result.csv], { type: 'text/csv;charset=utf-8' }));
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `chat-activity-${new Date().toISOString().slice(0, 10)}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ toast.success(t('exported'));
+ } finally {
+ setExporting(false);
+ }
+ }
+
+ const event = (row: ActivityRow) => {
+ const name =
+ row.toolKey && tTools.has(`${row.toolKey}.name`) ? tTools(`${row.toolKey}.name`) : '';
+ if (row.summaryKey && tSummary.has(row.summaryKey)) {
+ return tSummary(row.summaryKey, row.summaryParams);
+ }
+ return name;
+ };
+
+ return (
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-start gap-3">
+ <div className="min-w-0 flex-1 space-y-1">
+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
+ <p className="text-muted-foreground">{t('lead')}</p>
+ </div>
+ {page.isAdmin && (
+ <Button size="sm" variant="outline" disabled={exporting} onClick={() => void exportCsv()}>
+ {exporting ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Download className="h-4 w-4" />
+ )}
+ {t('export')}
+ </Button>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ {page.isAdmin && (
+ <label className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{t('filters.person')}</span>
+ <select
+ className={SELECT}
+ value={filters.userId ?? ''}
+ onChange={(e) => set({ userId: e.target.value || null })}
+ >
+ <option value="">{t('filters.everyone')}</option>
+ {page.people.map((person) => (
+ <option key={person.id} value={person.id}>
+ {person.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <label className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{t('filters.area')}</span>
+ <select
+ className={SELECT}
+ value={filters.area ?? ''}
+ onChange={(e) => set({ area: (e.target.value || null) as ToolArea | null })}
+ >
+ <option value="">{t('filters.allAreas')}</option>
+ {areas.map((area) => (
+ <option key={area} value={area}>
+ {tAreas(area)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">{t('filters.kind')}</span>
+ <select
+ className={SELECT}
+ value={filters.kind ?? ''}
+ onChange={(e) => set({ kind: (e.target.value || null) as ActivityFilters['kind'] })}
+ >
+ <option value="">{t('filters.allKinds')}</option>
+ {(['write', 'execute', 'denied'] as const).map((kind) => (
+ <option key={kind} value={kind}>
+ {t(`filters.kinds.${kind}`)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1.5">
+ <input
+ type="checkbox"
+ checked={!!filters.autoOnly}
+ onChange={(e) => set({ autoOnly: e.target.checked })}
+ />
+ {t('autoOnly')}
+ </label>
+ {filtered && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 px-2 text-xs"
+ onClick={() => setFilters({})}
+ >
+ {t('clear')}
+ </Button>
+ )}
+ </div>
+
+ {page.rows.length === 0 ? (
+ <p className="rounded-xl border px-3.5 py-6 text-center text-sm text-muted-foreground">
+ {filtered ? t('emptyFiltered') : t('empty')}
+ </p>
+ ) : (
+ <div className="overflow-x-auto rounded-xl border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('columns.when')}</TableHead>
+ <TableHead>{t('columns.who')}</TableHead>
+ <TableHead>{t('columns.event')}</TableHead>
+ <TableHead>{t('columns.class')}</TableHead>
+ <TableHead>{t('columns.approval')}</TableHead>
+ <TableHead>{t('columns.undo')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {page.rows.map((row) => {
+ const conflictHref = conflicts[row.id];
+ return (
+ <TableRow key={row.id} className="align-top">
+ <TableCell className="text-xs whitespace-nowrap text-muted-foreground tabular-nums">
+ {format.dateTime(new Date(row.at), {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ })}
+ </TableCell>
+ <TableCell className="text-xs">
+ <span className="font-medium">{row.isYou ? t('you') : row.person}</span>
+ <span className="block text-muted-foreground">
+ {t.has(`surfaces.${row.surface}`)
+ ? t(`surfaces.${row.surface}`)
+ : row.surface}
+ </span>
+ </TableCell>
+ <TableCell className="whitespace-normal">
+ <span className={cn(row.status === 'undone' && 'line-through')}>
+ {event(row)}
+ </span>
+ {(row.area || row.denialCode) && (
+ <span className="block text-xs text-muted-foreground">
+ {[
+ row.area && tAreas(row.area),
+ row.denialCode &&
+ t.has(`denials.${row.denialCode}`) &&
+ t(`denials.${row.denialCode}`),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ )}
+ </TableCell>
+ <TableCell>
+ <ClassBadge cls={row.kind === 'access.denied' ? 'never' : row.class} />
+ </TableCell>
+ <TableCell className="text-xs text-muted-foreground">
+ {t(`approval.${approvalLabel(row)}`)}
+ </TableCell>
+ <TableCell className="text-xs">
+ {row.canUndo ? (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={busy === row.id}
+ onClick={() => void undo(row)}
+ >
+ {t('undo')}
+ </Button>
+ ) : row.kind === 'change' && row.status !== 'done' ? (
+ <span className="text-muted-foreground">
+ {t(`status.${row.status}`)}
+ {row.status === 'undo_conflict' && conflictHref && (
+ <Link
+ href={conflictHref}
+ className="ml-1 inline-flex items-center gap-0.5 font-medium text-foreground underline-offset-2 hover:underline"
+ >
+ {t('openToUndo')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
+ )}
+ </span>
+ ) : (
+ <span aria-hidden className="text-muted-foreground">
+ –
+ </span>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+
+ {page.hasMore && (
+ <div className="flex justify-center">
+ <Button size="sm" variant="outline" disabled={more} onClick={() => void loadMore(page)}>
+ {more && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t('loadMore')}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/chat-access/chat-settings-section.tsx b/web/src/components/chat-access/chat-settings-section.tsx
index 7f957f10f..9d9e85f76 100644
--- a/web/src/components/chat-access/chat-settings-section.tsx
+++ b/web/src/components/chat-access/chat-settings-section.tsx
@@ -2,7 +2,8 @@
import { Fragment, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
-import { Info, Lock } from 'lucide-react';
+import { ArrowUpRight, Info, Lock } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
@@ -145,6 +146,13 @@ export function ChatSettingsSection() {
<div className="space-y-1">
<h2 className="text-lg font-semibold">{t('title')}</h2>
<p className="text-sm text-muted-foreground">{t('lead')}</p>
+ <Link
+ href="/dashboard/chat/activity"
+ className="inline-flex items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"
+ >
+ {tAccess('activity.seeLog')}
+ <ArrowUpRight className="h-3 w-3" />
+ </Link>
</div>
{!isAdmin && (
diff --git a/web/src/lib/actions/chat-activity.test.ts b/web/src/lib/actions/chat-activity.test.ts
new file mode 100644
index 000000000..83f968e36
--- /dev/null
+++ b/web/src/lib/actions/chat-activity.test.ts
@@ -0,0 +1,232 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** The Activity log page's reads, Undo and CSV (CHAT-20 §10a). */
+
+const ME = '11111111-1111-4111-8111-111111111111';
+const OTHER = '33333333-3333-4333-8333-333333333333';
+const ORG = '22222222-2222-4222-8222-222222222222';
+
+interface Call {
+ table: string;
+ filters: unknown[][];
+}
+let calls: Call[] = [];
+let role = 'manager';
+let logRows: Record<string, unknown>[] = [];
+let logError: { message: string } | null = null;
+
+function from(table: string) {
+ const call: Call = { table, filters: [] };
+ calls.push(call);
+ const answer = () => {
+ if (table === 'chat_activity_log') return { data: logError ? null : logRows, error: logError };
+ if (table === 'profiles') {
+ return call.filters.some((f) => f[0] === 'in' || f[1] === 'organization_id')
+ ? {
+ data: [
+ { id: ME, full_name: 'Alex Kim' },
+ { id: OTHER, full_name: 'Taylor Brooks' },
+ ],
+ error: null,
+ }
+ : { data: { organization_id: ORG, role }, error: null };
+ }
+ return { data: null, error: null };
+ };
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ ...Object.fromEntries(
+ ['eq', 'neq', 'in', 'lt', 'order', 'limit'].map((name) => [
+ name,
+ (...args: unknown[]) => {
+ call.filters.push([name, ...args]);
+ return chain;
+ },
+ ]),
+ ),
+ maybeSingle: async () => answer(),
+ then: (resolve: (value: unknown) => unknown) => Promise.resolve(answer()).then(resolve),
+ };
+ return chain;
+}
+
+const undoChange = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ auth: { getUser: async () => ({ data: { user: { id: ME } } }) } }),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: { from: (t: string) => from(t) } }));
+vi.mock('@/lib/member-emails', () => ({ readMemberAuth: async () => new Map() }));
+vi.mock('@/lib/chat/undo', () => ({ undoChange }));
+
+const { exportActivityCsv, listActivity, undoActivity } = await import('./chat-activity');
+
+const HOUR = 3_600_000;
+const row = (over: Record<string, unknown> = {}) => ({
+ id: 'a1',
+ created_at: '2026-10-29T10:00:00Z',
+ user_id: ME,
+ surface: 'chat',
+ kind: 'change',
+ tool_key: 'saveDraft',
+ class: 'write',
+ mode: 'full_auto',
+ approval_kind: 'auto',
+ auto_via: 'full_auto',
+ denial_code: null,
+ summary_key: 'saveDraft',
+ summary_params: { title: 'Pricing FAQ' },
+ status: 'done',
+ undo_until: new Date(Date.now() + HOUR).toISOString(),
+ undone_at: null,
+ ...over,
+});
+const logRead = () => calls.find((c) => c.table === 'chat_activity_log')!;
+
+beforeEach(() => {
+ vi.stubEnv('CHAT_AGENTIC', 'true');
+ calls = [];
+ role = 'manager';
+ logRows = [row()];
+ logError = null;
+ undoChange.mockReset();
+});
+afterEach(() => vi.unstubAllEnvs());
+
+describe('listActivity', () => {
+ it("gives a member their own rows, in words, with Undo while it's open", async () => {
+ logRows = [
+ row(),
+ row({ id: 'a2', undo_until: new Date(Date.now() - HOUR).toISOString() }),
+ row({
+ id: 'a3',
+ kind: 'access.denied',
+ tool_key: 'saveDraft',
+ denial_code: 'forbidden_role',
+ }),
+ ];
+ const read = await listActivity();
+ expect(read.ok).toBe(true);
+ if (!read.ok) return;
+ expect(read.isAdmin).toBe(false);
+ expect(read.people).toEqual([]);
+ expect(logRead().filters).toContainEqual(['eq', 'user_id', ME]);
+ expect(read.rows.map((r) => [r.id, r.canUndo])).toEqual([
+ ['a1', true],
+ ['a2', false],
+ ['a3', false],
+ ]);
+ expect(read.rows[0]).toMatchObject({
+ person: 'Alex Kim',
+ isYou: true,
+ area: 'content',
+ summaryKey: 'saveDraft',
+ summaryParams: { title: 'Pricing FAQ' },
+ });
+ // What Undo restores stays on the server; a tool goes by its label key.
+ expect(JSON.stringify(read)).not.toMatch(/undo_json|create_draft/);
+ });
+
+ it("gives an Admin everyone's rows, one person's, the people, and Undo on others'", async () => {
+ role = 'admin';
+ logRows = [row({ user_id: OTHER })];
+ const read = await listActivity();
+ if (!read.ok) throw new Error('expected rows');
+ expect(logRead().filters.some((f) => f[1] === 'user_id')).toBe(false);
+ expect(read.rows[0]).toMatchObject({ person: 'Taylor Brooks', isYou: false, canUndo: true });
+ expect(read.people.map((p) => p.name)).toEqual(['Alex Kim', 'Taylor Brooks']);
+ calls = [];
+ await listActivity({ userId: OTHER });
+ expect(logRead().filters).toContainEqual(['eq', 'user_id', OTHER]);
+ });
+
+ it('filters by area, class or denials, auto changes, and pages on', async () => {
+ await listActivity({
+ area: 'prompts',
+ kind: 'write',
+ autoOnly: true,
+ before: '2026-10-29T09:00:00Z',
+ });
+ const filters = logRead().filters;
+ expect(filters).toContainEqual([
+ 'in',
+ 'tool_key',
+ expect.arrayContaining(['dismissSuggestion']),
+ ]);
+ expect(filters).toContainEqual(['eq', 'class', 'write']);
+ expect(filters).toContainEqual(['neq', 'kind', 'access.denied']);
+ expect(filters).toContainEqual(['eq', 'approval_kind', 'auto']);
+ expect(filters).toContainEqual(['lt', 'created_at', '2026-10-29T09:00:00Z']);
+ calls = [];
+ await listActivity({ kind: 'denied' });
+ expect(logRead().filters).toContainEqual(['eq', 'kind', 'access.denied']);
+ });
+
+ it('says there is more past a page', async () => {
+ logRows = Array.from({ length: 51 }, (_, i) => row({ id: `a${i}` }));
+ const read = await listActivity();
+ if (!read.ok) throw new Error('expected rows');
+ expect(read.rows).toHaveLength(50);
+ expect(read.hasMore).toBe(true);
+ });
+
+ it('answers a failed read or Chat off in its result, never by throwing', async () => {
+ logError = { message: 'db down' };
+ expect(await listActivity()).toEqual({ ok: false, failure: 'failed' });
+ vi.stubEnv('CHAT_AGENTIC', 'false');
+ expect(await listActivity()).toEqual({ ok: false, failure: 'chat_off' });
+ });
+});
+
+describe('undoActivity', () => {
+ it('undoes as the signed-in person and passes on what Undo says, and where to fix a conflict', async () => {
+ undoChange.mockResolvedValue({
+ code: 'conflict',
+ reason: 'changed',
+ href: '/dashboard/content/d1',
+ message: 'This changed since. Open it to undo by hand.',
+ });
+ expect(await undoActivity('a1')).toEqual({
+ ok: true,
+ code: 'conflict',
+ message: 'This changed since. Open it to undo by hand.',
+ href: '/dashboard/content/d1',
+ });
+ expect(undoChange).toHaveBeenCalledWith({
+ activityId: 'a1',
+ userId: ME,
+ organizationId: ORG,
+ surface: 'chat',
+ });
+ });
+
+ it('keeps a denial’s internals off the page', async () => {
+ undoChange.mockResolvedValue({
+ code: 'denied',
+ denial: { code: 'forbidden_role', asked: 'x' },
+ message: 'Your role is Analyst.',
+ });
+ expect(await undoActivity('a1')).toEqual({
+ ok: true,
+ code: 'denied',
+ message: 'Your role is Analyst.',
+ href: null,
+ });
+ });
+});
+
+describe('exportActivityCsv', () => {
+ it("is an Admin's, in words and the tools' labels", async () => {
+ expect(await exportActivityCsv()).toEqual({ ok: false, failure: 'forbidden' });
+ role = 'admin';
+ logRows = [row({ summary_params: { title: '=HYPERLINK("x")' } })];
+ const result = await exportActivityCsv();
+ if (!result.ok) throw new Error('expected a CSV');
+ const [header, line] = result.csv.split('\n');
+ expect(header).toBe('time,person,surface,event,tool,class,mode,approval,status');
+ expect(line).toContain('Alex Kim');
+ expect(line).toContain('Save drafts in Content');
+ expect(line).toContain('Auto · Full auto');
+ expect(line).not.toContain('create_draft');
+ expect(logRead().filters).toContainEqual(['limit', 5000]);
+ });
+});
diff --git a/web/src/lib/actions/chat-activity.ts b/web/src/lib/actions/chat-activity.ts
new file mode 100644
index 000000000..3b4d40e7a
--- /dev/null
+++ b/web/src/lib/actions/chat-activity.ts
@@ -0,0 +1,241 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { readMemberAuth } from '@/lib/member-emails';
+import type { TeamRole } from '@/components/providers/role-provider';
+import { chatAgenticEnabled } from '@/lib/chat/flag';
+import { parseTeamRole } from '@/lib/chat/precedence';
+import { activitySummary } from '@/lib/chat/activity';
+import { undoChange } from '@/lib/chat/undo';
+import { CHAT_TOOLS, chatToolByKey } from '@/lib/chat/registry/tools';
+import type { ToolArea } from '@/lib/chat/registry/define-tool';
+import {
+ ACTIVITY_PAGE_SIZE,
+ ACTIVITY_EXPORT_MAX,
+ activityCsv,
+ type ActivityFilters,
+ type ActivityRow,
+} from '@/lib/chat/activity-view';
+
+/**
+ * The Activity log page (CHAT-20 §10a; mockup #g-activity), behind
+ * CHAT_AGENTIC: every change Chat made, every Undo and every denial
+ * (chat_activity_log, 00402). The person sees their own rows; an Admin sees
+ * the workspace's and exports them as CSV. A row goes by its label key and
+ * its summary in words: a tool's name never reaches the page, nor does
+ * what Undo restores (undo_json stays on the server).
+ *
+ * Every action answers { ok } with a typed failure and never throws (#1777).
+ */
+
+export type ActivityFailure = 'chat_off' | 'forbidden' | 'failed';
+
+interface Viewer {
+ userId: string;
+ organizationId: string;
+ role: TeamRole;
+}
+
+async function viewer(): Promise<Viewer | null> {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) return null;
+ const { data: profile } = await supabaseAdmin
+ .from('profiles')
+ .select('organization_id, role')
+ .eq('id', user.id)
+ .maybeSingle();
+ const role = parseTeamRole(profile?.role);
+ const organizationId = profile?.organization_id;
+ if (!organizationId || !role || !chatAgenticEnabled(organizationId)) return null;
+ return { userId: user.id, organizationId, role };
+}
+
+const COLUMNS =
+ 'id, created_at, user_id, surface, kind, tool_key, class, mode, approval_kind, auto_via, denial_code, summary_key, summary_params, status, undo_until, undone_at';
+
+/** The label keys of an area's tools, for the Area filter. */
+const keysOf = (area: ToolArea) =>
+ CHAT_TOOLS.filter((tool) => tool.area === area).map((tool) => tool.labelKey);
+
+/** The rows a viewer may read, with the filters, newest first, from before `before`. */
+async function readRows(who: Viewer, filters: ActivityFilters, limit: number) {
+ let query = supabaseAdmin
+ .from('chat_activity_log')
+ .select(COLUMNS)
+ .eq('organization_id', who.organizationId)
+ .order('created_at', { ascending: false })
+ .limit(limit);
+ // The person's own rows; an Admin's: everyone's, or one person's.
+ if (who.role !== 'admin') query = query.eq('user_id', who.userId);
+ else if (filters.userId) query = query.eq('user_id', filters.userId);
+ if (filters.area) query = query.in('tool_key', keysOf(filters.area));
+ if (filters.kind === 'denied') query = query.eq('kind', 'access.denied');
+ else if (filters.kind === 'write' || filters.kind === 'execute') {
+ query = query.eq('class', filters.kind).neq('kind', 'access.denied');
+ }
+ if (filters.autoOnly) query = query.eq('approval_kind', 'auto');
+ if (filters.before) query = query.lt('created_at', filters.before);
+ const { data, error } = await query;
+ if (error) throw new Error(error.message);
+ return data ?? [];
+}
+
+/** People's names, by id: their profile's, else their e-mail's part before the @. */
+async function namesOf(organizationId: string, ids: string[]): Promise<Map<string, string>> {
+ const names = new Map<string, string>();
+ if (ids.length === 0) return names;
+ const [{ data, error }, auth] = await Promise.all([
+ supabaseAdmin
+ .from('profiles')
+ .select('id, full_name')
+ .eq('organization_id', organizationId)
+ .in('id', ids),
+ readMemberAuth(ids),
+ ]);
+ if (error) throw new Error(error.message);
+ for (const id of ids) {
+ const profile = (data ?? []).find((row) => row.id === id);
+ names.set(id, profile?.full_name?.trim() || auth.get(id)?.email?.split('@')[0] || '');
+ }
+ return names;
+}
+
+function toRow(
+ row: Awaited<ReturnType<typeof readRows>>[number],
+ who: Viewer,
+ names: Map<string, string>,
+ now: number,
+): ActivityRow {
+ const tool = row.tool_key ? chatToolByKey(row.tool_key) : undefined;
+ const mine = row.user_id === who.userId;
+ return {
+ id: row.id,
+ at: row.created_at,
+ userId: row.user_id,
+ person: row.user_id ? (names.get(row.user_id) ?? '') : '',
+ isYou: mine,
+ surface: row.surface,
+ kind: row.kind as ActivityRow['kind'],
+ toolKey: row.tool_key,
+ area: tool?.area ?? null,
+ class: row.class as ActivityRow['class'],
+ mode: row.mode,
+ approvalKind: row.approval_kind,
+ autoVia: row.auto_via,
+ denialCode: row.denial_code,
+ summaryKey: row.summary_key,
+ summaryParams: (row.summary_params ?? {}) as Record<string, string>,
+ status: row.status as ActivityRow['status'],
+ // Undo is the person's, or an Admin's, while its window is open (§10b).
+ canUndo:
+ row.kind === 'change' &&
+ row.status === 'done' &&
+ !!row.undo_until &&
+ Date.parse(row.undo_until) > now &&
+ (mine || who.role === 'admin'),
+ undoneAt: row.undone_at,
+ };
+}
+
+/** A page of the log, newest first; `before` reads the next one. */
+export async function listActivity(filters: ActivityFilters = {}): Promise<
+ | {
+ ok: true;
+ isAdmin: boolean;
+ rows: ActivityRow[];
+ hasMore: boolean;
+ /** For an Admin's person filter: the workspace's members. */
+ people: { id: string; name: string }[];
+ }
+ | { ok: false; failure: ActivityFailure }
+> {
+ try {
+ const who = await viewer();
+ if (!who) return { ok: false, failure: 'chat_off' };
+ const isAdmin = who.role === 'admin';
+ const read = await readRows(who, filters, ACTIVITY_PAGE_SIZE + 1);
+ const page = read.slice(0, ACTIVITY_PAGE_SIZE);
+
+ let people: { id: string; name: string }[] = [];
+ let ids = [...new Set(page.map((row) => row.user_id).filter((id): id is string => !!id))];
+ if (isAdmin) {
+ const { data, error } = await supabaseAdmin
+ .from('profiles')
+ .select('id')
+ .eq('organization_id', who.organizationId);
+ if (error) throw new Error(error.message);
+ ids = [...new Set([...ids, ...(data ?? []).map((row) => row.id)])];
+ }
+ const names = await namesOf(who.organizationId, ids);
+ if (isAdmin) {
+ people = [...names]
+ .map(([id, name]) => ({ id, name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ }
+ const now = Date.now();
+ return {
+ ok: true,
+ isAdmin,
+ rows: page.map((row) => toRow(row, who, names, now)),
+ hasMore: read.length > ACTIVITY_PAGE_SIZE,
+ people,
+ };
+ } catch {
+ return { ok: false, failure: 'failed' };
+ }
+}
+
+/** Undoes a change from the log: the person's own, or any for an Admin. */
+export async function undoActivity(
+ activityId: string,
+): Promise<
+ | { ok: true; code: string; message: string; href: string | null }
+ | { ok: false; failure: ActivityFailure }
+> {
+ try {
+ const who = await viewer();
+ if (!who) return { ok: false, failure: 'chat_off' };
+ const result = await undoChange({
+ activityId,
+ userId: who.userId,
+ organizationId: who.organizationId,
+ surface: 'chat',
+ });
+ return {
+ ok: true,
+ code: result.code,
+ message: result.message,
+ href: result.code === 'conflict' ? result.href : null,
+ };
+ } catch {
+ return { ok: false, failure: 'failed' };
+ }
+}
+
+/** The log as CSV, for an Admin: the filtered rows, up to ACTIVITY_EXPORT_MAX. */
+export async function exportActivityCsv(
+ filters: ActivityFilters = {},
+): Promise<{ ok: true; csv: string } | { ok: false; failure: ActivityFailure }> {
+ try {
+ const who = await viewer();
+ if (!who) return { ok: false, failure: 'chat_off' };
+ if (who.role !== 'admin') return { ok: false, failure: 'forbidden' };
+ const rows = await readRows(who, { ...filters, before: undefined }, ACTIVITY_EXPORT_MAX);
+ const ids = [...new Set(rows.map((row) => row.user_id).filter((id): id is string => !!id))];
+ const names = await namesOf(who.organizationId, ids);
+ const now = Date.now();
+ return {
+ ok: true,
+ csv: activityCsv(
+ rows.map((row) => toRow(row, who, names, now)),
+ (key, params) => activitySummary(key, params),
+ ),
+ };
+ } catch {
+ return { ok: false, failure: 'failed' };
+ }
+}
diff --git a/web/src/lib/chat/access-log.test.ts b/web/src/lib/chat/access-log.test.ts
index 67270aa07..bff2d0104 100644
--- a/web/src/lib/chat/access-log.test.ts
+++ b/web/src/lib/chat/access-log.test.ts
@@ -1,6 +1,12 @@
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { accessDeniedEvent, recordAccessDenied, type AccessDeniedContext } from './access-log';
+
+const recordActivity = vi.hoisted(() => vi.fn());
+vi.mock('./activity', () => ({ recordActivity }));
+
+const { accessDeniedEvent, recordAccessDenied } = await import('./access-log');
+type AccessDeniedContext = import('./access-log').AccessDeniedContext;
+type ToolDenial = import('./precedence').ToolDenial;
/** Every denial is an `access.denied` event (CHAT-20 §4c). */
@@ -39,19 +45,17 @@ describe('accessDeniedEvent', () => {
});
describe('recordAccessDenied', () => {
- it('writes the event to the server log', async () => {
- const info = vi.spyOn(console, 'info').mockImplementation(() => {});
- await recordAccessDenied(ctx, { code: 'forbidden_role', role: 'analyst', roles: ['admin'] });
- expect(info).toHaveBeenCalledWith(
- '[chat] access.denied',
- expect.stringContaining('"forbidden_role"'),
- );
+ it("writes the denial's row in the Activity log", async () => {
+ recordActivity.mockResolvedValue('row-1');
+ const denial: ToolDenial = { code: 'forbidden_role', role: 'analyst', roles: ['admin'] };
+ await recordAccessDenied(ctx, denial);
+ expect(recordActivity).toHaveBeenCalledWith(accessDeniedEvent(ctx, denial));
});
it('never fails the run', async () => {
- vi.spyOn(console, 'info').mockImplementation(() => {
- throw new Error('log down');
- });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ recordActivity.mockRejectedValue(new Error('log down'));
await expect(recordAccessDenied(ctx, { code: 'policy_never' })).resolves.toBeUndefined();
+ expect(console.error).toHaveBeenCalled();
});
});
diff --git a/web/src/lib/chat/access-log.ts b/web/src/lib/chat/access-log.ts
index ada90a9bf..fab658806 100644
--- a/web/src/lib/chat/access-log.ts
+++ b/web/src/lib/chat/access-log.ts
@@ -1,3 +1,4 @@
+import { recordActivity } from './activity';
import type { ChatSurface, ToolDenial } from './precedence';
import type { ToolClass } from './registry/define-tool';
@@ -9,9 +10,9 @@ import type { ToolClass } from './registry/define-tool';
*
* One way in for every place that refuses a call: the run's tool-call step
* when the precedence denies (decideOrDeny, then buildDenial for the
- * answer), and MCP's. Until the Activity log lands (A4, 00402) the event
- * goes to the server's log only; then this writes its row, and no caller
- * changes. Server only.
+ * answer), and MCP's. It writes the denial's row in the Activity log
+ * (chat_activity_log, 00402), which the person sees among their own rows and
+ * Admins among all. Server only.
*/
export interface AccessDeniedContext {
@@ -52,8 +53,9 @@ export async function recordAccessDenied(
denial: ToolDenial,
): Promise<void> {
try {
- console.info('[chat] access.denied', JSON.stringify(accessDeniedEvent(ctx, denial)));
- } catch {
+ await recordActivity(accessDeniedEvent(ctx, denial));
+ } catch (err) {
// Logging must not fail the run.
+ console.error('[chat] access.denied not logged:', err instanceof Error ? err.message : err);
}
}
diff --git a/web/src/lib/chat/activity-view.test.ts b/web/src/lib/chat/activity-view.test.ts
new file mode 100644
index 000000000..55583bd73
--- /dev/null
+++ b/web/src/lib/chat/activity-view.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+import { activityCsv, approvalLabel, type ActivityRow } from './activity-view';
+
+/** What the Activity log and its CSV say about a row (CHAT-20 §10a). */
+
+describe('approvalLabel', () => {
+ it('says how a row ran', () => {
+ const label = (
+ kind: ActivityRow['kind'],
+ approvalKind: string | null,
+ autoVia: string | null = null,
+ ) => approvalLabel({ kind, approvalKind, autoVia });
+ expect(label('access.denied', null)).toBe('denied');
+ expect(label('change', 'ask')).toBe('card');
+ expect(label('change', 'click')).toBe('click');
+ expect(label('change', 'auto', 'always')).toBe('always');
+ expect(label('change', 'auto', 'dont_ask_again')).toBe('dont_ask_again');
+ expect(label('change', 'auto', 'full_auto')).toBe('full_auto');
+ expect(label('undo', 'run')).toBe('run');
+ });
+});
+
+describe('activityCsv', () => {
+ it('writes a line per row in words, a formula kept as text', () => {
+ const row: ActivityRow = {
+ id: 'a1',
+ at: '2026-10-29T10:00:00Z',
+ userId: 'u1',
+ person: 'Alex Kim',
+ isYou: true,
+ surface: 'chat',
+ kind: 'access.denied',
+ toolKey: 'saveDraft',
+ area: 'content',
+ class: 'write',
+ mode: null,
+ approvalKind: null,
+ autoVia: null,
+ denialCode: 'forbidden_role',
+ summaryKey: 'accessDenied',
+ summaryParams: { tool: '=cmd' },
+ status: 'done',
+ canUndo: false,
+ undoneAt: null,
+ };
+ const csv = activityCsv([row], (key, params) => `${key}:${params.tool}`);
+ expect(csv.split('\n')[1]).toBe(
+ '2026-10-29T10:00:00Z,Alex Kim,chat,accessDenied:=cmd,Save drafts in Content,denied,,Not allowed,Done',
+ );
+ expect(activityCsv([{ ...row, person: '=evil' }], () => '').split('\n')[1]).toMatch(
+ /^[^,]+,'=evil,/,
+ );
+ });
+});
diff --git a/web/src/lib/chat/activity-view.ts b/web/src/lib/chat/activity-view.ts
new file mode 100644
index 000000000..d7c571536
--- /dev/null
+++ b/web/src/lib/chat/activity-view.ts
@@ -0,0 +1,114 @@
+import { createTranslator } from 'next-intl';
+import messages from '../../../messages/en.json';
+import { toCsv } from '@/lib/csv';
+import type { ToolArea, ToolClass } from './registry/define-tool';
+
+/**
+ * The Activity log page's rows (CHAT-20 §10a; lib/actions/chat-activity.ts
+ * reads them), and what the page and its CSV say about each.
+ */
+
+/** Rows a page of the log shows before "Load more". */
+export const ACTIVITY_PAGE_SIZE = 50;
+/** Rows an Admin's CSV holds at most. */
+export const ACTIVITY_EXPORT_MAX = 5000;
+
+export interface ActivityFilters {
+ /** An Admin's: one person's rows. */
+ userId?: string | null;
+ area?: ToolArea | null;
+ /** Changes of a class, or the denials. */
+ kind?: 'write' | 'execute' | 'denied' | null;
+ /** Only what ran without a card. */
+ autoOnly?: boolean;
+ /** Rows older than this (ISO): the next page. */
+ before?: string;
+}
+
+export interface ActivityRow {
+ id: string;
+ at: string;
+ userId: string | null;
+ person: string;
+ isYou: boolean;
+ surface: string;
+ kind: 'change' | 'undo' | 'access.denied';
+ /** The row's label key (chatTools.{key}); never a tool's name. */
+ toolKey: string | null;
+ area: ToolArea | null;
+ class: ToolClass;
+ mode: string | null;
+ approvalKind: string | null;
+ autoVia: string | null;
+ denialCode: string | null;
+ summaryKey: string | null;
+ summaryParams: Record<string, string>;
+ status: 'done' | 'undone' | 'undo_conflict';
+ canUndo: boolean;
+ undoneAt: string | null;
+}
+
+/** How a row ran, as the Approval column says it. */
+export type ApprovalLabel =
+ | 'denied'
+ | 'card'
+ | 'click'
+ | 'always'
+ | 'full_auto'
+ | 'dont_ask_again'
+ | 'run';
+
+export function approvalLabel(
+ row: Pick<ActivityRow, 'kind' | 'approvalKind' | 'autoVia'>,
+): ApprovalLabel {
+ if (row.kind === 'access.denied') return 'denied';
+ if (row.approvalKind === 'ask') return 'card';
+ if (row.approvalKind === 'click') return 'click';
+ if (row.approvalKind === 'auto') {
+ return row.autoVia === 'always' || row.autoVia === 'dont_ask_again' ? row.autoVia : 'full_auto';
+ }
+ return 'run';
+}
+
+const t = createTranslator({ locale: 'en', messages, namespace: 'chatAccess.activity' });
+const toolT = createTranslator({ locale: 'en', messages, namespace: 'chatTools' });
+
+const toolName = (key: string | null) =>
+ key && Object.hasOwn(messages.chatTools, key)
+ ? toolT(`${key as keyof (typeof messages)['chatTools']}.name`)
+ : '';
+
+/**
+ * An Admin's export: one line per row, in words, as the page shows it. The
+ * cells are escaped by lib/csv (formulas included).
+ */
+export function activityCsv(
+ rows: ActivityRow[],
+ summaryOf: (key: string, params: Record<string, string>) => string,
+): string {
+ const headers = [
+ 'time',
+ 'person',
+ 'surface',
+ 'event',
+ 'tool',
+ 'class',
+ 'mode',
+ 'approval',
+ 'status',
+ ];
+ return toCsv(
+ rows.map((row) => ({
+ time: row.at,
+ person: row.person,
+ surface: row.surface,
+ event: row.summaryKey ? summaryOf(row.summaryKey, row.summaryParams) : '',
+ tool: toolName(row.toolKey),
+ class: row.kind === 'access.denied' ? 'denied' : row.class,
+ mode: row.mode ?? '',
+ approval: t(`approval.${approvalLabel(row)}`),
+ status: t(`status.${row.status}`),
+ })),
+ headers,
+ );
+}