Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(action-center): copy or export everything an action shows (#1070)

Cihane0204e99e70b
diff --git a/web/messages/en.json b/web/messages/en.json
index 7403de96e..c4c9cf8a0 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -688,6 +688,57 @@
"description": "Select a brand to view its actions."
},
"updateFailed": "Couldn't update the action.",
+ "export": {
+ "copyAll": "Copy Data",
+ "csv": "Export CSV",
+ "excel": "Export Excel",
+ "copied": "Action {ref} copied: {tasks, plural, one {# task} other {# tasks}}, {signals, plural, one {# signal} other {# signals}}",
+ "exportFailed": "Couldn't create the export.",
+ "preview": {
+ "copy": "Copy all",
+ "copied": "Copied",
+ "failed": "Couldn't copy. The text is selected: press ⌘C or Ctrl+C."
+ },
+ "skipped": "Skipped: {reason}",
+ "answerSource": "AI answer",
+ "tasksHeading": "Tasks ({count})",
+ "signalsHeading": "Signals ({count})",
+ "historyHeading": "History ({count})",
+ "sheets": {
+ "action": "Action",
+ "tasks": "Tasks",
+ "signals": "Signals",
+ "history": "History"
+ },
+ "action": "Action",
+ "title": "Title",
+ "category": "Category",
+ "impact": "Impact",
+ "status": "Status",
+ "assignee": "Assignee",
+ "dueDate": "Due",
+ "tags": "Tags",
+ "why": "Why",
+ "goal": "Goal",
+ "kpis": "KPIs",
+ "decision": "Decision",
+ "pages": "Pages",
+ "created": "Created",
+ "updated": "Updated",
+ "link": "Link",
+ "task": "Task",
+ "details": "Details",
+ "type": "Type",
+ "entity": "Affected",
+ "signal": "Signal",
+ "description": "Description",
+ "platforms": "Platforms",
+ "locations": "Locations",
+ "firstDetected": "First detected",
+ "lastDetected": "Last detected",
+ "date": "Date",
+ "event": "Event"
+ },
"drawer": {
"actionId": "Action ID",
"tabs": {
diff --git a/web/package.json b/web/package.json
index 3ffa38856..ae5dd7927 100644
--- a/web/package.json
+++ b/web/package.json
@@ -54,6 +54,7 @@
"stripe": "^22.0.0",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0",
+ "write-excel-file": "4.1.1",
"zod": "^4.4.3",
"zustand": "^5.0.11"
},
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index e897c442c..dc72fc84b 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -48,9 +48,9 @@ import {
} from '@/lib/action-center/registry';
import {
actionContextTags,
+ actionEventText,
actionGoal,
actionTexts,
- eventTaskText,
memberLabel,
taskText,
} from '@/lib/action-center/display';
@@ -59,6 +59,7 @@ import { isKpiKey } from '@/lib/kpis/registry';
import { ImpactDots, isSuperseded, SignalStatusBadge } from './signal-table';
import { ActionIcon } from './action-table';
import { OpportunityContext } from './opportunity-context';
+import { ActionExportButtons } from './action-export-buttons';
import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
@@ -191,6 +192,7 @@ export function ActionDrawer({
</Badge>
))}
</div>
+ <ActionExportButtons action={action} detail={detail} />
</SheetHeader>
{/* Who has it, where it stands and by when: ahead of the tabs, so they
@@ -459,26 +461,7 @@ export function ActionDrawer({
<div key={event.id} className="flex gap-3">
<div className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-foreground/50" />
<div>
- <p className="text-xs font-medium">
- {t(`drawer.events.${event.event}`, {
- to: String(event.data.to ?? ''),
- count: Number(event.data.count ?? 0),
- // Work the product did itself names the task in the
- // reader's language and the tool as it is recorded —
- // the tool id is the audit fact, so it is not
- // translated.
- task: eventTaskText(event.data.task, tTasks),
- tool: String(event.data.tool ?? ''),
- improved: Number(event.data.improved ?? 0),
- measurable: Number(event.data.measurable ?? 0),
- // A task someone added or renamed is named in their
- // own words, as they typed it.
- title: String(event.data.title ?? ''),
- // The validation sweep's verdict once the action
- // closed: improved, declined, and so on.
- outcome: String(event.data.outcome ?? ''),
- })}
- </p>
+ <p className="text-xs font-medium">{actionEventText(event, t, tTasks)}</p>
<p className="text-xs text-muted-foreground">
{new Date(event.createdAt).toLocaleDateString('en-US', {
month: 'short',
diff --git a/web/src/components/action-center/action-export-buttons.test.tsx b/web/src/components/action-center/action-export-buttons.test.tsx
new file mode 100644
index 000000000..64d3fbd1b
--- /dev/null
+++ b/web/src/components/action-center/action-export-buttons.test.tsx
@@ -0,0 +1,250 @@
+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 { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+
+const { toast, written } = vi.hoisted(() => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+ written: [] as { sheets: { sheet?: string }[]; file: string }[],
+}));
+vi.mock('sonner', () => ({ toast }));
+vi.mock('write-excel-file/browser', () => ({
+ default: (sheets: { sheet?: string }[]) => ({
+ toFile: async (file: string) => {
+ written.push({ sheets, file });
+ },
+ }),
+}));
+vi.mock('@/lib/actions/content', () => ({
+ getOpportunity: async () => ({
+ id: 'o1',
+ title: 'Coffee subscription guide',
+ decision: null,
+ brief: null,
+ sourceData: { targetPages: [{ url: 'https://acme.example/subscriptions', title: '' }] },
+ }),
+ getOpportunityBasket: async () => ({
+ clusters: [{ prompts: [{ text: 'Best coffee subscription?' }] }],
+ queries: [{ query: 'coffee subscription', included: true }],
+ }),
+}));
+
+const { ActionExportButtons } = await import('./action-export-buttons');
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+let clipboard: string[];
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+
+const action = {
+ id: 'a1',
+ actionNo: 52,
+ category: 'recover',
+ kind: 'recover_visibility',
+ impact: 'high',
+ status: 'new',
+ payload: {},
+ kpiKeys: [],
+ assignee: null,
+ dueDate: null,
+ createdAt: '2026-10-08T09:00:00Z',
+ updatedAt: '2026-10-15T12:30:00Z',
+ taskTotal: 1,
+ taskCompleted: 0,
+ signalCount: 1,
+} as ActionItem;
+
+const detail = {
+ tasks: [
+ {
+ id: 't1',
+ position: 0,
+ taskKey: null,
+ title: 'Refresh /pricing',
+ status: 'todo',
+ titleParams: {},
+ dependsOn: [],
+ skipReason: null,
+ details: null,
+ },
+ ],
+ signals: [
+ {
+ id: 's1',
+ category: 'visibility',
+ kind: 'sharp_drop',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ detectedAt: '2026-10-08T05:00:00Z',
+ lastDetectedAt: '2026-10-15T05:00:00Z',
+ resolvedAt: null,
+ previousValue: 40,
+ currentValue: 20,
+ changeValue: -20,
+ payload: {},
+ kpiKeys: [],
+ actionId: 'a1',
+ where: { platforms: ['gemini-web'], regions: [] },
+ },
+ ],
+ events: [
+ { id: 'e1', event: 'created', data: {}, actorId: null, createdAt: '2026-10-08T09:00:00Z' },
+ ],
+ kpis: [],
+} as unknown as ActionDetail;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ clipboard = [];
+ written.length = 0;
+ toast.success.mockReset();
+ toast.error.mockReset();
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async (text: string) => void clipboard.push(text) },
+ });
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('ActionExportButtons', () => {
+ it('waits for the action to load', () => {
+ render(<ActionExportButtons action={action} detail={null} />);
+ expect(
+ ['Copy Data', 'Export CSV', 'Export Excel'].map((name) => button(name).disabled),
+ ).toEqual([true, true, true]);
+ });
+
+ const copyButton = () =>
+ document.querySelector<HTMLButtonElement>('button[aria-label="Copy all"]')!;
+
+ it('opens every tab of the action as Markdown, and copies it all in one click', async () => {
+ render(<ActionExportButtons action={action} detail={detail} />);
+ await act(async () => button('Copy Data').click());
+ const shown = document.querySelector('textarea')?.value ?? '';
+ expect(shown).toMatch(/^# Recover lost visibility \(AC-52\)\n/);
+ expect(shown).toContain('## Tasks (1)\n1. Refresh /pricing (To Do)');
+ expect(shown).toContain('## Signals (1)\n- Visibility · ');
+ expect(shown).toContain('## History (1)\n- 2026-10-08 · ');
+ expect(shown).toContain(
+ 'Link: http://localhost:3000/dashboard/action-center/actions?action=a1',
+ );
+ expect(clipboard).toEqual([]);
+
+ await act(async () => copyButton().click());
+ expect(clipboard).toEqual([shown]);
+ expect(toast.success).toHaveBeenCalledWith('Action AC-52 copied: 1 task, 1 signal');
+ // The icon says it copied.
+ expect(copyButton()).toBeNull();
+ expect(document.querySelector('button[aria-label="Copied"]')).not.toBeNull();
+ });
+
+ it("copies with the browser's command where the clipboard is blocked", async () => {
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async () => Promise.reject(new Error('denied')) },
+ });
+ const execCommand = vi.fn(() => true);
+ document.execCommand = execCommand;
+ render(<ActionExportButtons action={action} detail={detail} />);
+ await act(async () => button('Copy Data').click());
+ await act(async () => copyButton().click());
+ expect(execCommand).toHaveBeenCalledWith('copy');
+ expect(toast.success).toHaveBeenCalledWith('Action AC-52 copied: 1 task, 1 signal');
+ });
+
+ it('says so when neither way can copy', async () => {
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async () => Promise.reject(new Error('denied')) },
+ });
+ document.execCommand = vi.fn(() => false);
+ render(<ActionExportButtons action={action} detail={detail} />);
+ await act(async () => button('Copy Data').click());
+ await act(async () => copyButton().click());
+ expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't copy. The text is selected: press ⌘C or Ctrl+C.",
+ );
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('adds what a content opportunity action was sent from', async () => {
+ render(
+ <ActionExportButtons
+ action={{ ...action, kind: 'content_opportunity', payload: { opportunityId: 'o1' } }}
+ detail={detail}
+ />,
+ );
+ await act(async () => button('Copy Data').click());
+ const shown = document.querySelector('textarea')?.value ?? '';
+ expect(shown).toContain('Content opportunity: Coffee subscription guide');
+ expect(shown).toContain('Pages:\n- https://acme.example/subscriptions');
+ expect(shown).toContain('1 prompt to answer:\n- Best coffee subscription?');
+ });
+
+ it('downloads a CSV Excel reads as UTF-8, named after the action', async () => {
+ const saved: { blob: Blob; name: string }[] = [];
+ URL.createObjectURL = (blob: Blob) => {
+ saved.push({ blob, name: '' });
+ return 'blob:csv';
+ };
+ URL.revokeObjectURL = () => {};
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
+ this: HTMLAnchorElement,
+ ) {
+ saved[saved.length - 1].name = this.download;
+ });
+ render(<ActionExportButtons action={action} detail={detail} />);
+ await act(async () => button('Export CSV').click());
+ click.mockRestore();
+ expect(saved[0].name).toBe('action-AC-52.csv');
+ const bytes = await new Promise<Uint8Array>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
+ reader.readAsArrayBuffer(saved[0].blob);
+ });
+ // UTF-8's byte order mark, then the header row.
+ expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);
+ const text = new TextDecoder().decode(bytes);
+ expect(text.split('\n')[0]).toMatch(/^section,action,ref,/);
+ });
+
+ it('writes an Excel workbook with a sheet per tab', async () => {
+ render(<ActionExportButtons action={action} detail={detail} />);
+ await act(async () => button('Export Excel').click());
+ expect(written).toHaveLength(1);
+ expect(written[0].sheets.map((s) => s.sheet)).toEqual([
+ 'Action',
+ 'Tasks',
+ 'Signals',
+ 'History',
+ ]);
+ expect(written[0].file).toBe('action-AC-52.xlsx');
+ });
+});
diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsx
new file mode 100644
index 000000000..6249aad88
--- /dev/null
+++ b/web/src/components/action-center/action-export-buttons.tsx
@@ -0,0 +1,337 @@
+'use client';
+
+import { useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Check, Copy, FileDown, FileSpreadsheet } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+import { getOpportunity, getOpportunityBasket } from '@/lib/actions/content';
+import {
+ actionContextTags,
+ actionEventText,
+ actionGoal,
+ actionTexts,
+ taskText,
+} from '@/lib/action-center/display';
+import {
+ actionCsv,
+ actionExportFileName,
+ actionMarkdown,
+ actionWorkbook,
+ buildActionExport,
+ type ActionExport,
+ type ExportFact,
+} from '@/lib/action-center/export';
+import { opportunityLists } from '@/lib/content/opportunity-lists';
+import { isKpiKey } from '@/lib/kpis/registry';
+import { signalAffected, signalTexts } from '@/lib/signals/display';
+import { SIGNAL_KINDS } from '@/lib/signals/registry';
+import { viewerTimeZone } from '@/lib/time-zone';
+import { isSuperseded } from './signal-table';
+
+// Written out so Excel reads the CSV as UTF-8 and keeps Turkish characters.
+const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+
+const IMPROVE_STATES = ['not_mentioned', 'mentioned_late', 'not_cited', 'doing_well', 'no_runs'];
+
+/** Saves a file the browser built, as the actions list's export does. */
+function save(blob: Blob, fileName: string) {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileName;
+ link.click();
+ // Revoked once the download has started; at once, some browsers drop it.
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+/**
+ * Copy all, Export CSV and Export Excel for one action (AC-005): what every
+ * tab of the drawer shows, to take into a doc, a ticket or a spreadsheet.
+ * Disabled until the drawer has loaded the action's detail. Copy Data opens the
+ * whole action as Markdown: select any part to copy it, or copy it all with
+ * the icon.
+ */
+export function ActionExportButtons({
+ action,
+ detail,
+}: {
+ action: ActionItem;
+ detail: ActionDetail | null;
+}) {
+ const t = useTranslations('actionCenter.actionsPage');
+ const tExport = useTranslations('actionCenter.actionsPage.export');
+ const tImprove = useTranslations('actionCenter.actionsPage.drawer.improve');
+ const tOpportunity = useTranslations('actionCenter.actionsPage.drawer.opportunity');
+ const tContent = useTranslations('content');
+ const tTexts = useTranslations('actionCenter.actionTexts');
+ const tCategories = useTranslations('actionCenter.actionCategories');
+ const tRegistry = useTranslations('actionCenter.registry');
+ const tTasks = useTranslations('actionCenter.actionTasks');
+ const tTaskStatus = useTranslations('actionCenter.taskStatus');
+ const tSignals = useTranslations('actionCenter.signalsPage');
+ const tSignalTexts = useTranslations('actionCenter.signalTexts');
+ const tSignalCategories = useTranslations('actionCenter.signalCategories');
+ const [isBusy, setIsBusy] = useState(false);
+ // The Markdown Copy Data shows, and what to say once it is copied.
+ const [preview, setPreview] = useState<{ text: string; copied: string } | null>(null);
+ const [justCopied, setJustCopied] = useState(false);
+ const previewRef = useRef<HTMLTextAreaElement>(null);
+
+ /** What the Overview tab shows of where a person sent the action from. */
+ const sentFrom = async (origin: string): Promise<ExportFact[]> => {
+ const p = action.payload ?? {};
+ if (action.kind === 'prompt_improve') {
+ const platforms = Array.isArray(p.platforms)
+ ? (p.platforms as { label?: unknown; state?: unknown }[]).filter(
+ (x): x is { label: string; state: string } =>
+ typeof x.label === 'string' &&
+ typeof x.state === 'string' &&
+ IMPROVE_STATES.includes(x.state),
+ )
+ : [];
+ const facts: ExportFact[] = [{ label: tImprove('source'), value: tImprove('sourceValue') }];
+ if (typeof p.promptText === 'string') {
+ facts.push({ label: tImprove('prompt'), value: p.promptText });
+ }
+ if (platforms.length) {
+ facts.push({
+ label: tImprove('platforms'),
+ value: platforms.map((x) => `${x.label} · ${tImprove(`states.${x.state}`)}`),
+ });
+ }
+ if (typeof p.panelLink === 'string') {
+ facts.push({ label: tImprove('openPanel'), value: `${origin}${p.panelLink}` });
+ }
+ return facts;
+ }
+ if (action.kind !== 'content_opportunity' || typeof p.opportunityId !== 'string') return [];
+
+ const pageUrls = Array.isArray(p.pages)
+ ? (p.pages as unknown[]).filter((u): u is string => typeof u === 'string')
+ : [];
+ try {
+ const [opportunity, basket] = await Promise.all([
+ getOpportunity(p.opportunityId),
+ getOpportunityBasket(p.opportunityId),
+ ]);
+ const { pages, prompts, queries } = opportunityLists(
+ opportunity,
+ basket,
+ p.assetKey ? pageUrls : undefined,
+ );
+ const brief = opportunity.brief;
+ const facts: ExportFact[] = [
+ { label: tOpportunity('title'), value: opportunity.title },
+ { label: tOpportunity('open'), value: `${origin}/dashboard/content/${opportunity.id}` },
+ ];
+ if (opportunity.decision) {
+ facts.push({
+ label: tExport('decision'),
+ value: tContent(`decision.${opportunity.decision}`),
+ });
+ }
+ if (pages.length) {
+ facts.push({ label: tExport('pages'), value: pages.map((page) => page.url) });
+ }
+ if (brief) {
+ facts.push({
+ label: tOpportunity('brief'),
+ value: [
+ `${brief.suggestedTitle} · ${brief.contentType.replace(/-/g, ' ')} · ${tOpportunity('words', { count: brief.targetWordCount })}`,
+ ...brief.outline.map(
+ (section, i) =>
+ `${i + 1}. ${section.heading}${section.keyPoints.length ? `: ${section.keyPoints.join('; ')}` : ''}`,
+ ),
+ ],
+ });
+ }
+ if (prompts.length) {
+ facts.push({
+ label: tOpportunity('prompts', { count: prompts.length }),
+ value: prompts.map((prompt) => prompt.text),
+ });
+ }
+ if (queries.length) {
+ facts.push({
+ label: tOpportunity('queries', { count: queries.length }),
+ value: queries.map((query) => query.query),
+ });
+ }
+ return facts;
+ } catch {
+ return [{ label: tOpportunity('title'), value: tOpportunity('unavailable') }];
+ }
+ };
+
+ const build = async (): Promise<ActionExport | null> => {
+ if (!detail) return null;
+ const origin = window.location.origin;
+ const texts = actionTexts(action, tTexts);
+ const related: string[] = action.kpiKeys.filter(isKpiKey);
+ return buildActionExport(
+ action,
+ detail,
+ {
+ title: texts.title,
+ why: texts.description,
+ goal: actionGoal(action.kind, tTexts, action.payload),
+ category: tCategories(action.category),
+ impact: t(`impact.${action.impact}`),
+ status: t(`status.${action.status}`),
+ tags: actionContextTags(action, t),
+ kpis: detail.kpis
+ .filter((kpi) => related.includes(kpi.kpiKey) && isKpiKey(kpi.kpiKey))
+ .map(
+ (kpi) =>
+ `${tRegistry(`${kpi.kpiKey}.name`)} (${t('drawer.kpiTarget', { target: kpi.target })})`,
+ ),
+ context: await sentFrom(origin),
+ taskTitle: (task) => taskText(task, tTasks),
+ taskStatus: (status) => tTaskStatus(status),
+ signal: (signal) => {
+ const affected = signalAffected(signal, tSignals);
+ return {
+ ...signalTexts(signal, tSignalTexts),
+ type: `${tSignalCategories(signal.category)} · ${tSignals(`states.${SIGNAL_KINDS[signal.kind].stateKey}`)}`,
+ entity: affected.detail ?? affected.label,
+ category: tSignalCategories(signal.category),
+ status: isSuperseded(signal)
+ ? tSignals('superseded')
+ : tSignals(`status.${signal.status}`),
+ impact: tSignals(`impact.${signal.impact}`),
+ };
+ },
+ event: (event) => actionEventText(event, t, tTasks),
+ skipped: (reason) => tExport('skipped', { reason }),
+ answerSource: tExport('answerSource'),
+ },
+ { origin, timeZone: viewerTimeZone() },
+ );
+ };
+
+ /** Builds the export once, holding the buttons while it runs. */
+ const run = async (fn: (data: ActionExport) => Promise<void> | void) => {
+ setIsBusy(true);
+ try {
+ const data = await build();
+ if (data) await fn(data);
+ } catch {
+ toast.error(tExport('exportFailed'));
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ /** Copy Data: the whole action, every tab, shown to copy in one click. */
+ const showData = (data: ActionExport) => {
+ setJustCopied(false);
+ setPreview({
+ text: actionMarkdown(data, tExport),
+ copied: tExport('copied', {
+ ref: data.ref,
+ tasks: data.tasks.length,
+ signals: data.signals.length,
+ }),
+ });
+ };
+
+ /**
+ * The dialog's Copy: the clipboard, or the browser's copy command on the
+ * selected text where the clipboard API is not allowed (an insecure page,
+ * an embedded browser).
+ */
+ const copyAll = async () => {
+ if (!preview) return;
+ previewRef.current?.select();
+ let done = false;
+ try {
+ await navigator.clipboard.writeText(preview.text);
+ done = true;
+ } catch {
+ try {
+ done = document.execCommand('copy');
+ } catch {
+ done = false;
+ }
+ }
+ if (!done) {
+ toast.error(tExport('preview.failed'));
+ return;
+ }
+ toast.success(preview.copied);
+ setJustCopied(true);
+ setTimeout(() => setJustCopied(false), 2000);
+ };
+
+ const downloadCsv = (data: ActionExport) =>
+ save(
+ new Blob([BYTE_ORDER_MARK, actionCsv(data)], { type: 'text/csv;charset=utf-8;' }),
+ actionExportFileName(data, 'csv'),
+ );
+
+ const downloadExcel = async (data: ActionExport) => {
+ // Loaded on demand: the writer is only needed when someone asks for a file.
+ const { default: writeXlsxFile } = await import('write-excel-file/browser');
+ await writeXlsxFile(actionWorkbook(data, tExport)).toFile(actionExportFileName(data, 'xlsx'));
+ };
+
+ const disabled = !detail || isBusy;
+ return (
+ <>
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" size="sm" disabled={disabled} onClick={() => void run(showData)}>
+ <Copy className="h-4 w-4" />
+ {tExport('copyAll')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => void run(downloadCsv)}
+ >
+ <FileDown className="h-4 w-4" />
+ {tExport('csv')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={() => void run(downloadExcel)}
+ >
+ <FileSpreadsheet className="h-4 w-4" />
+ {tExport('excel')}
+ </Button>
+ </div>
+ <Dialog open={preview !== null} onOpenChange={(open) => !open && setPreview(null)}>
+ <DialogContent className="sm:max-w-2xl" initialFocus={previewRef}>
+ <DialogHeader>
+ <DialogTitle>{tExport('copyAll')}</DialogTitle>
+ </DialogHeader>
+ {/* Select any part to copy it, or copy it all with the icon. */}
+ <div className="relative">
+ <textarea
+ ref={previewRef}
+ readOnly
+ aria-label={tExport('copyAll')}
+ value={preview?.text ?? ''}
+ className="h-80 w-full resize-none rounded-md border bg-muted/40 p-3 pr-12 font-mono text-xs"
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={justCopied ? tExport('preview.copied') : tExport('preview.copy')}
+ title={justCopied ? tExport('preview.copied') : tExport('preview.copy')}
+ onClick={() => void copyAll()}
+ className="absolute top-2 right-2 h-8 w-8 bg-background/80"
+ >
+ {justCopied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/web/src/components/action-center/opportunity-context.tsx b/web/src/components/action-center/opportunity-context.tsx
index f2f82f322..f5742c2d8 100644
--- a/web/src/components/action-center/opportunity-context.tsx
+++ b/web/src/components/action-center/opportunity-context.tsx
@@ -8,6 +8,7 @@ import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Link } from '@/i18n/navigation';
import { getOpportunity, getOpportunityBasket } from '@/lib/actions/content';
+import { opportunityLists } from '@/lib/content/opportunity-lists';
import type { ContentOpportunity, OpportunityBasket } from '@/types';
/** Fan-out queries listed before the rest fold away. */
@@ -60,13 +61,7 @@ export function OpportunityContext({
);
}
- const sd = opportunity.sourceData;
- const allPages = [...(sd.targetPages ?? []), ...(sd.assets ?? []).flatMap((a) => a.pages)].filter(
- (p, i, list) => list.findIndex((q) => q.url === p.url) === i,
- );
- const pages = pageUrls?.length ? allPages.filter((p) => pageUrls.includes(p.url)) : allPages;
- const prompts = basket.clusters.flatMap((c) => c.prompts);
- const queries = basket.queries.filter((q) => q.included);
+ const { pages, prompts, queries } = opportunityLists(opportunity, basket, pageUrls);
const brief = opportunity.brief;
return (
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index 5fab50f71..f15e77a9a 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -4,6 +4,7 @@ import { createTranslator } from 'next-intl';
import { describe, expect, it } from 'vitest';
import {
actionContextTags,
+ actionEventText,
actionGoal,
actionTexts,
eventTaskText,
@@ -226,6 +227,37 @@ describe('eventTaskText', () => {
});
});
+describe('actionEventText', () => {
+ const page = createTranslator({ locale: 'en', messages, namespace: 'actionCenter.actionsPage' });
+ const tPage = (key: string, values?: Record<string, string | number>) =>
+ page(key as Parameters<typeof page>[0], values);
+ const event = (name: string, data: Record<string, unknown>) => ({
+ id: 'e1',
+ event: name,
+ data,
+ actorId: null,
+ createdAt: '2026-10-16T00:00:00Z',
+ });
+
+ it('reads the 30-day position result with its counts', () => {
+ expect(
+ actionEventText(event('position_outcome_recorded', { improved: 2, measurable: 3 }), tPage, t),
+ ).toBe('30-day result: position improved on 2 of 3 platforms');
+ expect(
+ actionEventText(event('position_outcome_recorded', { improved: 0, measurable: 0 }), tPage, t),
+ ).toBe('30-day result: not enough data to compare positions');
+ });
+
+ it("passes a task's own title and the measured verdict", () => {
+ expect(actionEventText(event('task_added', { title: 'Ask the agency' }), tPage, t)).toBe(
+ 'Task added: “Ask the agency”',
+ );
+ expect(actionEventText(event('outcome_measured', { outcome: 'improved' }), tPage, t)).toBe(
+ 'Result: metrics improved after this action closed',
+ );
+ });
+});
+
/**
* Every event written to an action's trail is a line in the drawer's History
* tab, and an event with no message there shows next-intl's missing-message
diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.ts
index 4209125cd..d1d908569 100644
--- a/web/src/lib/action-center/display.ts
+++ b/web/src/lib/action-center/display.ts
@@ -1,4 +1,4 @@
-import type { ActionItem } from '@/lib/actions/action-center';
+import type { ActionEvent, ActionItem } from '@/lib/actions/action-center';
import { isActionKind } from '@/lib/action-center/registry';
import { formatCompactNumber } from '@/lib/format';
@@ -135,6 +135,31 @@ export function eventTaskText(
return t(key);
}
+/** A History entry as a sentence: what happened, to what, by which tool. */
+export function actionEventText(
+ event: ActionEvent,
+ t: Translator,
+ tTasks: Translator & { has?: (key: string) => boolean },
+): string {
+ return t(`drawer.events.${event.event}`, {
+ to: String(event.data.to ?? ''),
+ count: Number(event.data.count ?? 0),
+ // Work the product did itself names the task in the reader's language
+ // and the tool as it is recorded — the tool id is the audit fact, so it
+ // is not translated.
+ task: eventTaskText(event.data.task, tTasks),
+ tool: String(event.data.tool ?? ''),
+ improved: Number(event.data.improved ?? 0),
+ measurable: Number(event.data.measurable ?? 0),
+ // A task someone added or renamed is named in their own words, as they
+ // typed it.
+ title: String(event.data.title ?? ''),
+ // The validation sweep's verdict once the action closed: improved,
+ // declined, and so on.
+ outcome: String(event.data.outcome ?? ''),
+ });
+}
+
/**
* What the drawer shows under "Goal".
*
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
new file mode 100644
index 000000000..1b9addc8e
--- /dev/null
+++ b/web/src/lib/action-center/export.test.ts
@@ -0,0 +1,272 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+import type { Signal } from '@/lib/signals/map';
+import {
+ ACTION_CSV_HEADERS,
+ actionCsv,
+ actionExportFileName,
+ actionMarkdown,
+ actionWorkbook,
+ buildActionExport,
+ type ExportTexts,
+} from './export';
+
+const action = {
+ id: 'a1',
+ actionNo: 52,
+ category: 'recover',
+ kind: 'recover_visibility',
+ impact: 'high',
+ status: 'in_progress',
+ payload: {},
+ kpiKeys: ['ai_visibility'],
+ assignee: { id: 'u1', fullName: 'Ada Lovelace', avatarUrl: null },
+ dueDate: '2026-11-09',
+ createdAt: '2026-10-08T09:00:00Z',
+ updatedAt: '2026-10-15T12:30:00Z',
+ taskTotal: 2,
+ taskCompleted: 1,
+ signalCount: 1,
+} as ActionItem;
+
+const signal: Signal = {
+ id: 's1',
+ category: 'citation',
+ kind: 'lost_citations',
+ impact: 'high',
+ status: 'new',
+ source: ['ai_results'],
+ // Late on Oct 8 in UTC is Oct 9 in Istanbul.
+ detectedAt: '2026-10-08T22:30:00Z',
+ lastDetectedAt: '2026-10-15T05:00:00Z',
+ resolvedAt: null,
+ previousValue: null,
+ currentValue: null,
+ changeValue: null,
+ payload: {},
+ kpiKeys: [],
+ actionId: 'a1',
+ where: { platforms: ['chatgpt-web', 'gemini-web'], regions: ['US'] },
+};
+
+const detail = {
+ tasks: [
+ {
+ id: 't1',
+ position: 0,
+ taskKey: null,
+ title: 'Add a 2026 comparison table to /blog/best-tools',
+ status: 'completed',
+ titleParams: {},
+ dependsOn: [],
+ skipReason: null,
+ details: {
+ body: 'Lead with the table.\nThen the FAQ.',
+ platform: 'chatgpt-web',
+ platformLabel: 'ChatGPT',
+ sources: [
+ { type: 'url', ref: 'https://acme.example/blog/best-tools' },
+ { type: 'answer', ref: '9c1e0d2a-0000-4b2f-8000-000000000000' },
+ ],
+ },
+ },
+ {
+ id: 't2',
+ position: 1,
+ taskKey: null,
+ title: '=HYPERLINK("x")',
+ status: 'skipped',
+ titleParams: {},
+ dependsOn: [],
+ skipReason: 'Done by hand',
+ details: null,
+ },
+ ],
+ signals: [signal],
+ events: [
+ { id: 'e1', event: 'created', data: {}, actorId: null, createdAt: '2026-10-08T09:00:00Z' },
+ ],
+ kpis: [],
+} as unknown as ActionDetail;
+
+const texts: ExportTexts = {
+ title: 'Recover lost citations on 7 prompts',
+ why: '7 prompts lost their citations.',
+ goal: 'Citations back on 5 of 7 prompts',
+ category: 'Recover',
+ impact: 'High',
+ status: 'In progress',
+ tags: ['Recover', '1 platform'],
+ kpis: ['AI Visibility (target 40)'],
+ context: [
+ { label: 'Prompt', value: 'Which tools track AI search?' },
+ { label: 'Platforms at send time', value: ['Gemini · No runs', 'ChatGPT · Not cited'] },
+ ],
+ taskTitle: (task) => task.title ?? '',
+ taskStatus: (status) => ({ completed: 'Completed', skipped: 'Skipped' })[status] ?? status,
+ signal: () => ({
+ type: 'Citation · Lost',
+ entity: 'Which tools track AI search?',
+ title: 'Citations lost for "Which tools track AI search?"',
+ description: 'Your pages are no longer cited.',
+ category: 'Citation',
+ status: 'New',
+ impact: 'High',
+ }),
+ event: () => 'Action created',
+ skipped: (reason) => `Skipped: ${reason}`,
+ answerSource: 'AI answer',
+};
+
+// Labels as their keys, with the counts the headings take.
+const label = (key: string, values?: Record<string, string | number>) =>
+ values ? `${key}(${Object.values(values).join(',')})` : key;
+
+const exported = buildActionExport(action, detail, texts, {
+ origin: 'https://app.example',
+ timeZone: 'Europe/Istanbul',
+});
+
+describe('buildActionExport', () => {
+ it("labels the action, its tasks, signals and history, dated in the reader's zone", () => {
+ expect(exported).toMatchObject({
+ ref: 'AC-52',
+ assignee: 'Ada Lovelace',
+ dueDate: '2026-11-09',
+ created: '2026-10-08',
+ link: 'https://app.example/dashboard/action-center/actions?action=a1',
+ tasks: [
+ {
+ number: 1,
+ status: 'Completed',
+ // An AI answer is named, not given by its id; lines are joined.
+ details:
+ 'Lead with the table. Then the FAQ. · ChatGPT · https://acme.example/blog/best-tools · AI answer',
+ },
+ { number: 2, status: 'Skipped', details: 'Skipped: Done by hand' },
+ ],
+ signals: [
+ {
+ type: 'Citation · Lost',
+ platforms: ['ChatGPT', 'Gemini'],
+ locations: ['United States'],
+ detected: '2026-10-09',
+ link: 'https://app.example/dashboard/action-center/signals?signal=s1',
+ },
+ ],
+ events: [{ date: '2026-10-08', text: 'Action created' }],
+ });
+ });
+});
+
+describe('actionMarkdown', () => {
+ it('writes what every tab shows as headed Markdown', () => {
+ expect(actionMarkdown(exported, label)).toBe(
+ [
+ '# Recover lost citations on 7 prompts (AC-52)',
+ 'category: Recover · impact: High · status: In progress',
+ 'assignee: Ada Lovelace · dueDate: 2026-11-09',
+ 'tags: Recover, 1 platform',
+ 'why: 7 prompts lost their citations.',
+ 'goal: Citations back on 5 of 7 prompts',
+ 'kpis: AI Visibility (target 40)',
+ 'Prompt: Which tools track AI search?',
+ 'Platforms at send time:',
+ '- Gemini · No runs',
+ '- ChatGPT · Not cited',
+ 'link: https://app.example/dashboard/action-center/actions?action=a1',
+ '',
+ '## tasksHeading(2)',
+ '1. Add a 2026 comparison table to /blog/best-tools (Completed)',
+ ' Lead with the table. Then the FAQ. · ChatGPT · https://acme.example/blog/best-tools · AI answer',
+ '2. =HYPERLINK("x") (Skipped)',
+ ' Skipped: Done by hand',
+ '',
+ '## signalsHeading(1)',
+ '- Citation · Lost · ChatGPT, Gemini · United States · 2026-10-09 · Which tools track AI search? · New',
+ '',
+ '## historyHeading(1)',
+ '- 2026-10-08 · Action created',
+ ].join('\n'),
+ );
+ });
+
+ it('leaves out what an action has none of', () => {
+ const bare = {
+ ...exported,
+ assignee: '',
+ dueDate: '',
+ tags: [],
+ kpis: [],
+ context: [],
+ tasks: [],
+ signals: [],
+ events: [],
+ };
+ const md = actionMarkdown(bare, label);
+ expect(md).not.toMatch(/assignee|tags|kpis|historyHeading/);
+ expect(md).toContain('## tasksHeading(0)');
+ });
+});
+
+describe('actionCsv', () => {
+ it('gives each task and signal a row, marked by section and the action', () => {
+ const [head, ...rows] = actionCsv(exported).split('\n');
+ expect(head).toBe(ACTION_CSV_HEADERS.join(','));
+ expect(rows.map((row) => row.split(',').slice(0, 2).join(','))).toEqual([
+ 'task,AC-52',
+ 'task,AC-52',
+ 'signal,AC-52',
+ ]);
+ // A cell a spreadsheet would run as a formula is kept as text.
+ expect(rows[1]).toContain(`"'=HYPERLINK(""x"")"`);
+ expect(rows[2]).toContain('Citation · Lost,Which tools track AI search?');
+ expect(rows[2]).toContain('ChatGPT; Gemini,United States,2026-10-09');
+ });
+});
+
+describe('actionWorkbook', () => {
+ it('gives the action, its tasks, signals and history a sheet each', () => {
+ const sheets = actionWorkbook(exported, label);
+ expect(sheets.map((s) => s.sheet)).toEqual([
+ 'sheets.action',
+ 'sheets.tasks',
+ 'sheets.signals',
+ 'sheets.history',
+ ]);
+ expect(sheets[0].data).toContainEqual([
+ { value: 'Platforms at send time', fontWeight: 'bold' },
+ 'Gemini · No runs; ChatGPT · Not cited',
+ ]);
+ expect(sheets[1].data[0][1]).toEqual({ value: 'task', fontWeight: 'bold' });
+ expect(sheets[2].data[1].slice(0, 2)).toEqual([
+ 'Citation · Lost',
+ 'Which tools track AI search?',
+ ]);
+ expect(sheets[3].data[1]).toEqual(['2026-10-08', 'Action created']);
+ });
+});
+
+describe('actionExportFileName', () => {
+ it('names the file after the action, as the spec does', () => {
+ expect(actionExportFileName(exported, 'csv')).toBe('action-AC-52.csv');
+ });
+});
+
+describe('the Excel file', () => {
+ it('is a workbook a spreadsheet reader opens, with every sheet and cell', async () => {
+ const { default: writeXlsxFile } = await import('write-excel-file/browser');
+ const { default: readXlsxFile } = await import('read-excel-file/browser');
+ const blob = await writeXlsxFile(actionWorkbook(exported, label)).toBlob();
+ const sheets = await readXlsxFile(blob);
+ expect(sheets.map((s) => s.sheet)).toEqual([
+ 'sheets.action',
+ 'sheets.tasks',
+ 'sheets.signals',
+ 'sheets.history',
+ ]);
+ expect(sheets[1].data[2]).toEqual([2, '=HYPERLINK("x")', 'Skipped', 'Skipped: Done by hand']);
+ expect(sheets[2].data[1][6]).toBe('ChatGPT, Gemini');
+ });
+});
diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.ts
new file mode 100644
index 000000000..218a40d69
--- /dev/null
+++ b/web/src/lib/action-center/export.ts
@@ -0,0 +1,401 @@
+import type { ActionDetail, ActionItem } from '@/lib/actions/action-center';
+import { toCsv } from '@/lib/csv';
+import { locationName, platformName } from '@/lib/signals/names';
+import { dayIn } from '@/lib/time-zone';
+import type { Sheet } from 'write-excel-file/browser';
+
+/**
+ * One action, whole, to take out of the app (AC-005): Markdown for the
+ * clipboard ("Copy all"), a CSV with a `section` column, and an Excel
+ * workbook with a sheet per section.
+ *
+ * The drawer first resolves every label in the reader's language into an
+ * `ActionExport`, with what each of its tabs shows; the formats below only lay
+ * it out, so the three always say the same thing.
+ */
+
+/** A labelled fact; a list is shown as one, a single value inline. */
+export interface ExportFact {
+ label: string;
+ value: string | string[];
+}
+
+export interface ActionExport {
+ /** "AC-52". */
+ ref: string;
+ title: string;
+ category: string;
+ impact: string;
+ status: string;
+ /** Empty when no one is assigned. */
+ assignee: string;
+ /** `YYYY-MM-DD`, or empty. */
+ dueDate: string;
+ /** The chips under the title ("Compete", "1 platform"). */
+ tags: string[];
+ why: string;
+ goal: string;
+ /** "AI Visibility (target 40)". */
+ kpis: string[];
+ /**
+ * What the action was sent from, when a person sent it: the Improve tab's
+ * prompt and platforms, a content opportunity's pages, brief and prompts.
+ */
+ context: ExportFact[];
+ created: string;
+ updated: string;
+ /** The action's drawer in the app. */
+ link: string;
+ tasks: ExportTask[];
+ signals: ExportSignal[];
+ /** The History tab, in its order. */
+ events: { date: string; text: string }[];
+}
+
+export interface ExportTask {
+ number: number;
+ title: string;
+ status: string;
+ /** What the task carries beyond its title, and why it was skipped. */
+ details: string;
+}
+
+export interface ExportSignal {
+ /** "Citation · Lost", as the signals list's Type column. */
+ type: string;
+ /** What it is about, as the Affected column: a prompt, a page, "3 prompts". */
+ entity: string;
+ title: string;
+ description: string;
+ category: string;
+ status: string;
+ impact: string;
+ /** Display names, most common first. */
+ platforms: string[];
+ locations: string[];
+ /** `YYYY-MM-DD`. */
+ detected: string;
+ lastDetected: string;
+ /** The signal's drawer in the app. */
+ link: string;
+}
+
+/** The labels an `ActionExport` is built from, each already in the reader's language. */
+export interface ExportTexts {
+ title: string;
+ why: string;
+ goal: string;
+ category: string;
+ impact: string;
+ status: string;
+ tags: string[];
+ kpis: string[];
+ context: ExportFact[];
+ taskTitle: (task: ActionDetail['tasks'][number]) => string;
+ taskStatus: (status: string) => string;
+ signal: (signal: ActionDetail['signals'][number]) => {
+ type: string;
+ entity: string;
+ title: string;
+ description: string;
+ category: string;
+ status: string;
+ impact: string;
+ };
+ event: (event: ActionDetail['events'][number]) => string;
+ /** "Skipped: {reason}". */
+ skipped: (reason: string) => string;
+ /** What an AI answer a task rests on is called; its id means nothing outside. */
+ answerSource: string;
+}
+
+/**
+ * `YYYY-MM-DD` in the reader's time zone, as the app shows dates. A date
+ * without a time (a due date) is already the day.
+ */
+function dayOf(iso: string | null | undefined, timeZone: string): string {
+ if (!iso) return '';
+ return /^\d{4}-\d{2}-\d{2}$/.test(iso) ? iso : dayIn(iso, timeZone);
+}
+
+/** The action and its detail, labelled, in the order the drawer shows them. */
+export function buildActionExport(
+ action: ActionItem,
+ detail: ActionDetail,
+ texts: ExportTexts,
+ { origin, timeZone }: { origin: string; timeZone: string },
+): ActionExport {
+ const day = (iso: string | null | undefined) => dayOf(iso, timeZone);
+ return {
+ ref: `AC-${action.actionNo}`,
+ title: texts.title,
+ category: texts.category,
+ impact: texts.impact,
+ status: texts.status,
+ assignee: action.assignee?.fullName?.trim() ?? '',
+ dueDate: day(action.dueDate),
+ tags: texts.tags,
+ why: texts.why,
+ goal: texts.goal,
+ kpis: texts.kpis,
+ context: texts.context,
+ created: day(action.createdAt),
+ updated: day(action.updatedAt),
+ link: `${origin}/dashboard/action-center/actions?action=${action.id}`,
+ tasks: detail.tasks.map((task, i) => {
+ const details = task.details
+ ? [
+ task.details.body,
+ task.details.platformLabel,
+ ...task.details.sources.map((source) =>
+ source.type === 'answer' ? texts.answerSource : source.ref,
+ ),
+ ]
+ : [];
+ if (task.skipReason) details.push(texts.skipped(task.skipReason));
+ return {
+ number: i + 1,
+ title: texts.taskTitle(task),
+ status: texts.taskStatus(task.status),
+ details: details
+ .filter(Boolean)
+ .map((part) => part.replace(/\s*\n+\s*/g, ' '))
+ .join(' · '),
+ };
+ }),
+ signals: detail.signals.map((signal) => ({
+ ...texts.signal(signal),
+ platforms: signal.where.platforms.map(platformName),
+ locations: signal.where.regions.map(locationName),
+ detected: day(signal.detectedAt),
+ lastDetected: day(signal.lastDetectedAt),
+ link: `${origin}/dashboard/action-center/signals?signal=${signal.id}`,
+ })),
+ events: detail.events.map((event) => ({
+ date: day(event.createdAt),
+ text: texts.event(event),
+ })),
+ };
+}
+
+/** Headings and field names, in the reader's language (actionsPage.export). */
+type Labels = (key: string, values?: Record<string, string | number>) => string;
+
+const listed = (value: string | string[]) => (Array.isArray(value) ? value.join('; ') : value);
+
+/** One line per signal: what, where, when, about what. */
+function signalLine(signal: ExportSignal): string {
+ return [
+ signal.type,
+ signal.platforms.join(', '),
+ signal.locations.join(', '),
+ signal.detected,
+ signal.entity,
+ signal.status,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+}
+
+/**
+ * "Copy all": the action as Markdown, everything its drawer's tabs show, to
+ * paste into Docs, Notion, Jira or an AI agent.
+ */
+export function actionMarkdown(a: ActionExport, label: Labels): string {
+ const facts = (pairs: [string, string][]) =>
+ pairs
+ .filter(([, value]) => value)
+ .map(([key, value]) => `${label(key)}: ${value}`)
+ .join(' · ');
+ const lines = [
+ `# ${a.title} (${a.ref})`,
+ facts([
+ ['category', a.category],
+ ['impact', a.impact],
+ ['status', a.status],
+ ]),
+ facts([
+ ['assignee', a.assignee],
+ ['dueDate', a.dueDate],
+ ]),
+ a.tags.length ? `${label('tags')}: ${a.tags.join(', ')}` : '',
+ `${label('why')}: ${a.why}`,
+ `${label('goal')}: ${a.goal}`,
+ a.kpis.length ? `${label('kpis')}: ${a.kpis.join(', ')}` : '',
+ ...a.context.flatMap(({ label: name, value }) =>
+ Array.isArray(value)
+ ? [`${name}:`, ...value.map((item) => `- ${item}`)]
+ : [`${name}: ${value}`],
+ ),
+ `${label('link')}: ${a.link}`,
+ ].filter(Boolean);
+
+ lines.push('', `## ${label('tasksHeading', { count: a.tasks.length })}`);
+ for (const task of a.tasks) {
+ lines.push(`${task.number}. ${task.title} (${task.status})`);
+ if (task.details) lines.push(` ${task.details}`);
+ }
+
+ lines.push('', `## ${label('signalsHeading', { count: a.signals.length })}`);
+ for (const signal of a.signals) lines.push(`- ${signalLine(signal)}`);
+
+ if (a.events.length) {
+ lines.push('', `## ${label('historyHeading', { count: a.events.length })}`);
+ for (const event of a.events) lines.push(`- ${event.date} · ${event.text}`);
+ }
+
+ return lines.join('\n');
+}
+
+/**
+ * The CSV columns: a row per task and per signal, marked by `section`, with
+ * the columns they share. Machine names, as in the actions list's export.
+ */
+export const ACTION_CSV_HEADERS = [
+ 'section',
+ 'action',
+ 'ref',
+ 'title',
+ 'type',
+ 'entity',
+ 'details',
+ 'status',
+ 'category',
+ 'impact',
+ 'platforms',
+ 'locations',
+ 'first_detected',
+ 'last_detected',
+ 'link',
+];
+
+/** "Export CSV": the action's tasks and signals, one row each. */
+export function actionCsv(a: ActionExport): string {
+ const rows: Record<string, unknown>[] = [
+ ...a.tasks.map((task) => ({
+ section: 'task',
+ action: a.ref,
+ ref: task.number,
+ title: task.title,
+ details: task.details,
+ status: task.status,
+ link: a.link,
+ })),
+ ...a.signals.map((signal, i) => ({
+ section: 'signal',
+ action: a.ref,
+ ref: i + 1,
+ title: signal.title,
+ type: signal.type,
+ entity: signal.entity,
+ details: signal.description,
+ status: signal.status,
+ category: signal.category,
+ impact: signal.impact,
+ platforms: signal.platforms.join('; '),
+ locations: signal.locations.join('; '),
+ first_detected: signal.detected,
+ last_detected: signal.lastDetected,
+ link: signal.link,
+ })),
+ ];
+ return toCsv(rows, ACTION_CSV_HEADERS);
+}
+
+const bold = (value: string) => ({ value, fontWeight: 'bold' as const });
+
+/** "Export Excel": a sheet each for the action, its tasks, its signals and its history. */
+export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {
+ const summary: [string, string][] = [
+ [label('action'), a.ref],
+ [label('title'), a.title],
+ [label('category'), a.category],
+ [label('impact'), a.impact],
+ [label('status'), a.status],
+ [label('assignee'), a.assignee],
+ [label('dueDate'), a.dueDate],
+ [label('tags'), a.tags.join(', ')],
+ [label('why'), a.why],
+ [label('goal'), a.goal],
+ [label('kpis'), a.kpis.join(', ')],
+ ...a.context.map(({ label: name, value }): [string, string] => [name, listed(value)]),
+ [label('created'), a.created],
+ [label('updated'), a.updated],
+ [label('link'), a.link],
+ ];
+ return [
+ {
+ sheet: label('sheets.action'),
+ columns: [{ width: 22 }, { width: 90 }],
+ data: summary.map(([name, value]) => [bold(name), value]),
+ },
+ {
+ sheet: label('sheets.tasks'),
+ stickyRowsCount: 1,
+ columns: [{ width: 5 }, { width: 60 }, { width: 14 }, { width: 70 }],
+ data: [
+ ['#', label('task'), label('status'), label('details')].map(bold),
+ ...a.tasks.map((task) => [task.number, task.title, task.status, task.details]),
+ ],
+ },
+ {
+ sheet: label('sheets.signals'),
+ stickyRowsCount: 1,
+ columns: [
+ { width: 22 },
+ { width: 40 },
+ { width: 50 },
+ { width: 60 },
+ { width: 12 },
+ { width: 10 },
+ { width: 24 },
+ { width: 16 },
+ { width: 14 },
+ { width: 14 },
+ { width: 40 },
+ ],
+ data: [
+ [
+ label('type'),
+ label('entity'),
+ label('signal'),
+ label('description'),
+ label('status'),
+ label('impact'),
+ label('platforms'),
+ label('locations'),
+ label('firstDetected'),
+ label('lastDetected'),
+ label('link'),
+ ].map(bold),
+ ...a.signals.map((signal) => [
+ signal.type,
+ signal.entity,
+ signal.title,
+ signal.description,
+ signal.status,
+ signal.impact,
+ signal.platforms.join(', '),
+ signal.locations.join(', '),
+ signal.detected,
+ signal.lastDetected,
+ signal.link,
+ ]),
+ ],
+ },
+ {
+ sheet: label('sheets.history'),
+ stickyRowsCount: 1,
+ columns: [{ width: 14 }, { width: 90 }],
+ data: [
+ [label('date'), label('event')].map(bold),
+ ...a.events.map((event) => [event.date, event.text]),
+ ],
+ },
+ ];
+}
+
+/** `action-AC-52.csv`, as the spec names it. */
+export function actionExportFileName(a: ActionExport, extension: 'csv' | 'xlsx') {
+ return `action-${a.ref}.${extension}`;
+}
diff --git a/web/src/lib/content/opportunity-lists.ts b/web/src/lib/content/opportunity-lists.ts
new file mode 100644
index 000000000..451ff27ee
--- /dev/null
+++ b/web/src/lib/content/opportunity-lists.ts
@@ -0,0 +1,22 @@
+import type { ContentOpportunity, OpportunityBasket } from '@/types';
+
+/**
+ * What the drawer lists of an opportunity: the pages sent (all of its pages
+ * when it was sent whole), the prompts to answer and the fan-out queries kept.
+ * The action's export lists the same.
+ */
+export function opportunityLists(
+ opportunity: ContentOpportunity,
+ basket: OpportunityBasket,
+ pageUrls?: string[],
+) {
+ const sd = opportunity.sourceData;
+ const allPages = [...(sd.targetPages ?? []), ...(sd.assets ?? []).flatMap((a) => a.pages)].filter(
+ (p, i, list) => list.findIndex((q) => q.url === p.url) === i,
+ );
+ return {
+ pages: pageUrls?.length ? allPages.filter((p) => pageUrls.includes(p.url)) : allPages,
+ prompts: basket.clusters.flatMap((c) => c.prompts),
+ queries: basket.queries.filter((q) => q.included),
+ };
+}
diff --git a/web/yarn.lock b/web/yarn.lock
index 24db909e8..a4fbf87ff 100644
--- a/web/yarn.lock
+++ b/web/yarn.lock
@@ -8203,6 +8203,13 @@ wrappy@1:
resolved "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz"
integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==
+ version "4.1.1"
+ resolved "https://registry.yarnpkg.com/write-excel-file/-/write-excel-file-4.1.1.tgz#b2c7065605d87b8d43601f63c4a726b7fba1be3c"
+ integrity sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==
+ dependencies:
+ fflate "^0.8.2"
+
ws@^8.18.0:
version "8.21.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.21.0.tgz#012e413fc07429945121b0c153158c4343086951"