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): give tasks where, why, how and done-when fields (#1080)

Cihan59323ef7dcdb
diff --git a/web/messages/en.json b/web/messages/en.json
index 6dd4f5c26..a72a830f2 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -963,6 +963,11 @@
"link": "Link",
"task": "Task",
"details": "Details",
+ "taskWhere": "Where",
+ "taskWhy": "Why",
+ "taskHow": "How",
+ "taskDoneWhen": "Done when",
+ "taskEffort": "Effort",
"item": "Item",
"volume": "Volume",
"lostPage": "Lost page",
@@ -1139,14 +1144,13 @@
"task_added": "Task added: “{title}”",
"task_renamed": "Task renamed to “{title}”",
"task_deleted": "Task deleted",
+ "task_edited": "Task edited",
"task_ran": "{task} — carried out automatically ({tool})",
"task_run_failed": "{task} — the automatic attempt failed; it needs doing by hand",
"task_awaiting_approval": "{task} — waiting for your approval before it reaches outside Ansvisor",
"position_outcome_recorded": "{measurable, plural, =0 {30-day result: not enough data to compare positions} other {30-day result: position improved on {improved} of # platforms}}",
"outcome_measured": "{outcome, select, improved {Result: metrics improved after this action closed} declined {Result: metrics declined after this action closed} no_meaningful_change {Result: no meaningful change in metrics after this action closed} not_measurable {Result: could not be measured} other {Result measured}}"
},
- "taskText": "Task text",
- "renameTask": "Rename task",
"deleteTask": "Delete task",
"addTask": "Add task",
"addTaskPlaceholder": "What needs doing?",
@@ -1156,6 +1160,27 @@
"skipReasonPlaceholder": "e.g. handled elsewhere, no longer relevant",
"skipConfirm": "Skip task",
"skipCancel": "Cancel",
+ "task": {
+ "showDetails": "Show details",
+ "hideDetails": "Hide details",
+ "what": "What",
+ "where": "Where",
+ "why": "Why",
+ "how": "How",
+ "howHint": "One step per line, up to {max}",
+ "doneWhen": "Done when",
+ "type": "Type",
+ "noType": "No type",
+ "effort": "Effort",
+ "effortPlaceholder": "e.g. ~2h",
+ "role": "Role",
+ "rolePlaceholder": "e.g. Content writer",
+ "edit": "Edit",
+ "save": "Save",
+ "cancel": "Cancel",
+ "empty": "No details yet: add where to do it, how, and when it counts as done.",
+ "answerSource": "AI answer"
+ },
"noSignalsOpportunity": "This action was sent from Content Optimization. Its evidence is the opportunity on the Overview tab, not detection signals.",
"opportunity": {
"title": "Content opportunity",
@@ -1810,6 +1835,14 @@
"competitors": "{count, plural, one {# competitor} other {# competitors}}"
}
},
+ "taskTypes": {
+ "content": "Content",
+ "on_page": "On-page",
+ "technical": "Technical",
+ "outreach": "Outreach",
+ "pr": "PR",
+ "product": "Product"
+ },
"taskStatus": {
"todo": "To Do",
"in_progress": "In Progress",
diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsx
index 2818a87d6..c16e44a6c 100644
--- a/web/src/components/action-center/action-drawer.tsx
+++ b/web/src/components/action-center/action-drawer.tsx
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useFormatter, useTranslations } from 'next-intl';
import { useRouter } from '@/i18n/navigation';
import { toast } from 'sonner';
-import { Plus, Trash2 } from 'lucide-react';
+import { ChevronRight, Plus, Trash2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -33,8 +33,8 @@ import {
getPromptDemand,
setActionDueDate,
updateActionStatus,
+ updateTaskDetails,
updateTaskStatus,
- updateTaskTitle,
type ActionDetail,
type ActionItem,
type ActionTask,
@@ -74,6 +74,8 @@ import { actionStory } from '@/lib/action-center/story';
import { ImproveContext } from './improve-context';
import { TopicGapContext } from './topic-gap-context';
import { TopicOpportunityContext } from './topic-opportunity-context';
+import { TaskDetailForm, TaskDetailView, TaskTypeBadge } from './task-detail';
+import { hasTaskSpec, type TaskDetailsEdit } from '@/lib/action-center/task-details';
import { ImproveOutcomeCard } from './improve-outcome-card';
import { improvePlatformLabels } from '@/lib/improve-outcome';
import { cn } from '@/lib/utils';
@@ -117,7 +119,6 @@ export function ActionDrawer({
const router = useRouter();
const [tab, setTab] = useState<DrawerTab>('overview');
const [detail, setDetail] = useState<ActionDetail | null>(null);
- const [isLoading, setIsLoading] = useState(false);
const [isBusy, setIsBusy] = useState(false);
// Traceability: a signal card jumps to the Signals page with that signal's
@@ -126,15 +127,14 @@ export function ActionDrawer({
router.push(`/dashboard/action-center/signals?signal=${signalId}`);
};
+ // A reload after a change keeps the detail on screen until the new one is
+ // in, so an opened task stays open; only a first load shows placeholders.
const load = useCallback(async () => {
if (!action) return;
- setIsLoading(true);
try {
setDetail(await getActionDetail(brandId, action.id));
} catch {
toast.error(t('error.title'));
- } finally {
- setIsLoading(false);
}
}, [brandId, action, t]);
@@ -235,17 +235,23 @@ export function ActionDrawer({
? (action.payload.pages as unknown[]).filter((u): u is string => typeof u === 'string')
: [];
- const mutate = async (fn: () => Promise<void>) => {
+ /** Runs a change, then reloads; false when the change failed (and said so). */
+ const mutate = async (fn: () => Promise<void>): Promise<boolean> => {
setIsBusy(true);
try {
await fn();
- await load();
- onChanged();
} catch {
toast.error(t('updateFailed'));
+ setIsBusy(false);
+ return false;
+ }
+ try {
+ await load();
+ onChanged();
} finally {
setIsBusy(false);
}
+ return true;
};
return (
@@ -407,7 +413,7 @@ export function ActionDrawer({
</nav>
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4 text-sm">
- {isLoading || !detail || !ready ? (
+ {!detail || !ready ? (
<div className="space-y-3">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-16 w-full" />
@@ -527,8 +533,8 @@ export function ActionDrawer({
updateTaskStatus(brandId, action.id, task.id, status, skipReason),
)
}
- onRename={(title) =>
- void mutate(() => updateTaskTitle(brandId, action.id, task.id, title))
+ onEdit={(edit) =>
+ mutate(() => updateTaskDetails(brandId, action.id, task.id, edit))
}
onDelete={() => void mutate(() => deleteTask(brandId, action.id, task.id))}
/>
@@ -602,12 +608,10 @@ export function ActionDrawer({
type TaskTranslator = (key: string, values?: Record<string, string | number>) => string;
/**
- * One task: its text, its status, and the two edits a person can make to it.
+ * One task: its text, type and status, opening onto its details (AC-004).
*
- * Renaming happens in place rather than in a dialog — the text is one line and
- * a dialog for one line is a detour. Escape abandons the edit, Enter or blur
- * commits it, and an empty value is treated as abandonment rather than as a
- * request to blank the task out, which the database would refuse anyway.
+ * The text opens the task rather than renaming it: a task is read before it
+ * is edited, and its text is one of the fields the details' Edit changes.
*/
function TaskRow({
task,
@@ -616,7 +620,7 @@ function TaskRow({
statusLabel,
t,
onStatusChange,
- onRename,
+ onEdit,
onDelete,
}: {
task: ActionTask;
@@ -625,63 +629,55 @@ function TaskRow({
statusLabel: TaskTranslator;
t: TaskTranslator;
onStatusChange: (status: TaskStatus, skipReason?: string) => void;
- onRename: (title: string) => void;
+ /** Resolves true once saved; false when the save failed. */
+ onEdit: (edit: TaskDetailsEdit & { title: string | null }) => Promise<boolean>;
onDelete: () => void;
}) {
- const [draft, setDraft] = useState<string | null>(null);
- const isEditing = draft !== null;
+ // A task sent from the Improve tab opens on its suggestion, as it always
+ // showed it; the rest open on a click.
+ const [open, setOpen] = useState(
+ () => !!task.details && !hasTaskSpec(task.details) && !!task.details.body,
+ );
+ const [editing, setEditing] = useState(false);
// Choosing Skipped opens a reason field rather than committing: a skip
// without a reason cannot be told apart from an abandoned task later.
const [skipDraft, setSkipDraft] = useState<string | null>(null);
-
- const commit = () => {
- const next = (draft ?? '').trim();
- if (next && next !== text) onRename(next);
- setDraft(null);
- };
+ const locked = disabled || editing || skipDraft !== null;
return (
<div className="rounded-md border">
{/* Top-aligned so a task that wraps keeps its controls beside its first
line. */}
<div className="flex items-start justify-between gap-2 px-3 py-2">
- {isEditing ? (
- <Input
- autoFocus
- value={draft}
- maxLength={200}
- disabled={disabled}
- aria-label={t('drawer.taskText')}
- className="h-7 min-w-0 flex-1 text-sm"
- onChange={(e) => setDraft(e.target.value)}
- onBlur={commit}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- commit();
- } else if (e.key === 'Escape') {
- e.preventDefault();
- setDraft(null);
- }
- }}
+ <button
+ type="button"
+ // Not while editing: closing would drop what was typed.
+ onClick={() => !editing && setOpen((current) => !current)}
+ aria-expanded={open}
+ title={open ? t('drawer.task.hideDetails') : t('drawer.task.showDetails')}
+ className="flex min-w-0 flex-1 items-start gap-1 rounded px-1 py-1 text-left text-sm leading-snug hover:bg-muted/60"
+ >
+ <ChevronRight
+ className={cn(
+ 'mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform',
+ open && 'rotate-90',
+ )}
/>
- ) : (
- <button
- type="button"
- disabled={disabled}
- onClick={() => setDraft(text)}
- title={t('drawer.renameTask')}
+ {/* Wraps rather than truncates: a task is read, not scanned, and
+ "Create a content brief for 23 prom…" says nothing. */}
+ <span
className={cn(
- // Wraps rather than truncates: a task is read, not scanned,
- // and "Create a content brief for 23 prom…" says nothing.
- 'min-w-0 flex-1 rounded px-1 py-1 text-left text-sm leading-snug break-words hover:bg-muted/60',
+ 'min-w-0 break-words',
(task.status === 'completed' || UNCOUNTED_TASK_STATUSES.includes(task.status)) &&
'text-muted-foreground line-through',
)}
>
{task.position}. {text}
- </button>
- )}
+ </span>
+ </button>
+ <div className="mt-1.5 shrink-0">
+ <TaskTypeBadge type={task.details?.type ?? null} />
+ </div>
<Select
value={task.status}
onValueChange={(value) => {
@@ -689,7 +685,7 @@ function TaskRow({
if (next === 'skipped') setSkipDraft('');
else onStatusChange(next);
}}
- disabled={disabled || isEditing || skipDraft !== null}
+ disabled={locked}
items={TASK_STATUSES.map((status) => ({ value: status, label: statusLabel(status) }))}
>
<SelectTrigger className="h-7 w-32 shrink-0 text-xs">
@@ -707,7 +703,7 @@ function TaskRow({
type="button"
variant="ghost"
size="icon"
- disabled={disabled || isEditing || skipDraft !== null}
+ disabled={locked}
onClick={onDelete}
aria-label={t('drawer.deleteTask')}
className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"
@@ -716,7 +712,25 @@ function TaskRow({
</Button>
</div>
- {task.details && <TaskDetails details={task.details} />}
+ {open &&
+ (editing ? (
+ <TaskDetailForm
+ text={text}
+ details={task.details}
+ disabled={disabled}
+ onSave={async (edit) => {
+ // The form stays until the save lands, so a failure keeps what was typed.
+ if (await onEdit(edit)) setEditing(false);
+ }}
+ onCancel={() => setEditing(false)}
+ />
+ ) : (
+ <TaskDetailView
+ details={task.details}
+ disabled={disabled || skipDraft !== null}
+ onEdit={() => setEditing(true)}
+ />
+ ))}
{skipDraft !== null && (
<div className="flex items-center gap-2 border-t bg-muted/30 px-3 py-2">
@@ -851,29 +865,3 @@ function AddTaskForm({
</div>
);
}
-
-/** A task sent from the Improve tab: its platform, body and evidence (PROMPT-004). */
-function TaskDetails({ details }: { details: NonNullable<ActionTask['details']> }) {
- return (
- <div className="space-y-1.5 px-4 pb-3">
- {details.body && (
- <p className="text-xs leading-relaxed text-muted-foreground">{details.body}</p>
- )}
- <div className="flex flex-wrap gap-1">
- <Badge variant="secondary" className="text-[10px]">
- {details.platformLabel}
- </Badge>
- {details.sources.map((source) => (
- <Badge
- key={`${source.type}:${source.ref}`}
- variant="outline"
- title={source.ref}
- className="max-w-full truncate text-[10px] font-normal text-muted-foreground"
- >
- {source.type === 'answer' ? 'AI answer' : source.ref}
- </Badge>
- ))}
- </div>
- </div>
- );
-}
diff --git a/web/src/components/action-center/action-export-buttons.tsx b/web/src/components/action-center/action-export-buttons.tsx
index f05f9d18d..eb932af1e 100644
--- a/web/src/components/action-center/action-export-buttons.tsx
+++ b/web/src/components/action-center/action-export-buttons.tsx
@@ -85,6 +85,7 @@ export function ActionExportButtons({
const tRegistry = useTranslations('actionCenter.registry');
const tTasks = useTranslations('actionCenter.actionTasks');
const tTaskStatus = useTranslations('actionCenter.taskStatus');
+ const tTaskTypes = useTranslations('actionCenter.taskTypes');
const tSignals = useTranslations('actionCenter.signalsPage');
const tSignalTexts = useTranslations('actionCenter.signalTexts');
const tSignalCategories = useTranslations('actionCenter.signalCategories');
@@ -235,6 +236,7 @@ export function ActionExportButtons({
},
event: (event) => actionEventText(event, t, tTasks),
skipped: (reason) => tExport('skipped', { reason }),
+ taskType: (type) => tTaskTypes(type),
answerSource: tExport('answerSource'),
},
{ origin, timeZone: viewerTimeZone() },
diff --git a/web/src/components/action-center/task-detail.test.tsx b/web/src/components/action-center/task-detail.test.tsx
new file mode 100644
index 000000000..6f2a3d44e
--- /dev/null
+++ b/web/src/components/action-center/task-detail.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 { parseTaskDetails } from '@/lib/action-center/task-details';
+import { TaskDetailForm, TaskDetailView, TaskTypeBadge } from './task-detail';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+/** Types into a field the way a person does, so React's onChange runs. */
+function type(field: HTMLInputElement | HTMLTextAreaElement, value: string) {
+ const proto = Object.getPrototypeOf(field) as HTMLInputElement;
+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(field, value);
+ act(() => {
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+const field = (label: string) => {
+ const target = [...container.querySelectorAll('label')].find((l) =>
+ l.textContent?.startsWith(label),
+ );
+ return container.querySelector<HTMLInputElement | HTMLTextAreaElement>(
+ `[id="${target?.getAttribute('for')}"]`,
+ )!;
+};
+
+const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+
+const details = parseTaskDetails({
+ where: 'acme.example/blog/best-tools · 3 prompts on ChatGPT',
+ why: 'Cited #2 until Oct 8.',
+ how: ['Add a feature table.', 'Put "2026" in the title.'],
+ doneWhen: 'Cited again on 2 of 3 platforms within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+});
+
+describe('TaskDetailView', () => {
+ it('shows where, why, the steps in order, done-when and the effort', () => {
+ render(<TaskDetailView details={details} disabled={false} onEdit={() => {}} />);
+ const terms = [...container.querySelectorAll('dt')].map((dt) => dt.textContent);
+ expect(terms).toEqual(['Where', 'Why', 'How', 'Done when', 'Effort']);
+ expect([...container.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Add a feature table.',
+ 'Put "2026" in the title.',
+ ]);
+ expect(container.textContent).toContain('~2h · Content writer');
+ });
+
+ it('asks for details when a task has none, and opens the editor', () => {
+ const onEdit = vi.fn();
+ render(<TaskDetailView details={null} disabled={false} onEdit={onEdit} />);
+ expect(container.textContent).toContain('No details yet');
+ act(() => button('Edit').click());
+ expect(onEdit).toHaveBeenCalled();
+ });
+
+ it("keeps an Improve task's body and evidence", () => {
+ render(
+ <TaskDetailView
+ details={parseTaskDetails({
+ body: 'Lead with the table.',
+ platformLabel: 'ChatGPT',
+ sources: [{ type: 'answer', ref: '9c1e' }],
+ })}
+ disabled={false}
+ onEdit={() => {}}
+ />,
+ );
+ expect(container.textContent).toContain('Lead with the table.');
+ expect(container.textContent).toContain('AI answer');
+ expect(container.textContent).not.toContain('No details yet');
+ });
+});
+
+describe('TaskDetailView without a body', () => {
+ it("shows an Improve task's evidence without asking for details", () => {
+ render(
+ <TaskDetailView
+ details={parseTaskDetails({
+ platformLabel: 'Gemini',
+ sources: [{ type: 'domain', ref: 'g2.com' }],
+ })}
+ disabled={false}
+ onEdit={() => {}}
+ />,
+ );
+ expect(container.textContent).toContain('g2.com');
+ expect(container.textContent).not.toContain('No details yet');
+ });
+});
+
+describe('TaskDetailForm', () => {
+ it('saves every field, one step per line, and leaves an unchanged text alone', () => {
+ const onSave = vi.fn();
+ render(
+ <TaskDetailForm
+ text="Refresh /pricing"
+ details={details}
+ disabled={false}
+ onSave={onSave}
+ onCancel={() => {}}
+ />,
+ );
+ type(field('How'), 'Add a table.\n\nUpdate the title.');
+ type(field('Role'), 'Editor');
+ act(() => button('Save').click());
+ expect(onSave).toHaveBeenCalledWith({
+ title: null,
+ where: 'acme.example/blog/best-tools · 3 prompts on ChatGPT',
+ why: 'Cited #2 until Oct 8.',
+ how: ['Add a table.', '', 'Update the title.'],
+ doneWhen: 'Cited again on 2 of 3 platforms within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Editor',
+ });
+ });
+
+ it('saves a new text, and refuses an empty one', () => {
+ const onSave = vi.fn();
+ render(
+ <TaskDetailForm
+ text="Refresh /pricing"
+ details={null}
+ disabled={false}
+ onSave={onSave}
+ onCancel={() => {}}
+ />,
+ );
+ type(field('What'), ' ');
+ expect(button('Save').disabled).toBe(true);
+ type(field('What'), 'Add a 2026 table to /pricing');
+ act(() => button('Save').click());
+ expect(onSave).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'Add a 2026 table to /pricing', type: null }),
+ );
+ });
+});
+
+describe('TaskTypeBadge', () => {
+ it('names the type, and shows nothing without one', () => {
+ render(<TaskTypeBadge type="on_page" />);
+ expect(container.textContent).toBe('On-page');
+ render(<TaskTypeBadge type={null} />);
+ expect(container.textContent).toBe('');
+ });
+});
diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsx
new file mode 100644
index 000000000..503dafd25
--- /dev/null
+++ b/web/src/components/action-center/task-detail.tsx
@@ -0,0 +1,329 @@
+'use client';
+
+import { useId, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ TASK_DETAIL_LIMITS,
+ TASK_TYPES,
+ hasTaskSpec,
+ isTaskType,
+ type ActionTaskDetails,
+ type TaskDetailsEdit,
+} from '@/lib/action-center/task-details';
+
+/** The type of work, beside the task's text (AC-004). */
+export function TaskTypeBadge({ type }: { type: ActionTaskDetails['type'] }) {
+ const tTypes = useTranslations('actionCenter.taskTypes');
+ if (!type) return null;
+ return (
+ <Badge variant="outline" className="shrink-0 text-[10px]">
+ {tTypes(type)}
+ </Badge>
+ );
+}
+
+/**
+ * An opened task (AC-004): where to do it, why, how, when it counts as done
+ * and what it takes, and for a task sent from the Improve tab its body,
+ * platform and evidence (PROMPT-004).
+ */
+export function TaskDetailView({
+ details,
+ disabled,
+ onEdit,
+}: {
+ details: ActionTaskDetails | null;
+ disabled: boolean;
+ onEdit: () => void;
+}) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.task');
+ const effort = [details?.effort, details?.role].filter(Boolean).join(' · ');
+
+ return (
+ <div className="space-y-2 border-t px-4 py-3">
+ {details?.body && (
+ <p className="text-xs leading-relaxed whitespace-pre-line text-muted-foreground">
+ {details.body}
+ </p>
+ )}
+ {details && (details.platformLabel || details.sources.length > 0) && (
+ <div className="flex flex-wrap gap-1">
+ {details.platformLabel && (
+ <Badge variant="secondary" className="text-[10px]">
+ {details.platformLabel}
+ </Badge>
+ )}
+ {details.sources.map((source) => (
+ <Badge
+ key={`${source.type}:${source.ref}`}
+ variant="outline"
+ title={source.ref}
+ className="max-w-full truncate text-[10px] font-normal text-muted-foreground"
+ >
+ {source.type === 'answer' ? t('answerSource') : source.ref}
+ </Badge>
+ ))}
+ </div>
+ )}
+ {details && hasTaskSpec(details) ? (
+ <dl className="grid grid-cols-[5.5rem_1fr] gap-x-3 gap-y-1.5 text-xs">
+ {details.where && <Field label={t('where')}>{details.where}</Field>}
+ {details.why && <Field label={t('why')}>{details.why}</Field>}
+ {details.how.length > 0 && (
+ <Field label={t('how')}>
+ <ol className="list-decimal space-y-0.5 pl-4">
+ {details.how.map((step, i) => (
+ <li key={i}>{step}</li>
+ ))}
+ </ol>
+ </Field>
+ )}
+ {details.doneWhen && <Field label={t('doneWhen')}>{details.doneWhen}</Field>}
+ {effort && <Field label={t('effort')}>{effort}</Field>}
+ </dl>
+ ) : (
+ !details && <p className="text-xs text-muted-foreground">{t('empty')}</p>
+ )}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={disabled}
+ onClick={onEdit}
+ className="h-7 text-xs"
+ >
+ {t('edit')}
+ </Button>
+ </div>
+ );
+}
+
+function Field({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <>
+ <dt className="text-muted-foreground">{label}</dt>
+ <dd className="min-w-0 break-words whitespace-pre-line">{children}</dd>
+ </>
+ );
+}
+
+const NO_TYPE = 'none';
+
+/**
+ * Every field of a task, editable (AC-004). The text is saved only when it
+ * changed, so a library task keeps rendering from its template in the
+ * reader's language.
+ */
+export function TaskDetailForm({
+ text,
+ details,
+ disabled,
+ onSave,
+ onCancel,
+}: {
+ /** The task's text as the drawer shows it. */
+ text: string;
+ details: ActionTaskDetails | null;
+ disabled: boolean;
+ onSave: (edit: TaskDetailsEdit & { title: string | null }) => void | Promise<void>;
+ onCancel: () => void;
+}) {
+ const t = useTranslations('actionCenter.actionsPage.drawer.task');
+ const tTypes = useTranslations('actionCenter.taskTypes');
+ const [draft, setDraft] = useState({
+ title: text,
+ where: details?.where ?? '',
+ why: details?.why ?? '',
+ how: (details?.how ?? []).join('\n'),
+ doneWhen: details?.doneWhen ?? '',
+ type: details?.type ?? null,
+ effort: details?.effort ?? '',
+ role: details?.role ?? '',
+ });
+ const id = useId();
+ const set = (field: keyof typeof draft) => (value: string) =>
+ setDraft((current) => ({ ...current, [field]: value }));
+ const title = draft.title.trim();
+
+ return (
+ <form
+ className="space-y-2.5 border-t px-4 py-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!title) return;
+ void onSave({
+ title: title === text ? null : title,
+ where: draft.where,
+ why: draft.why,
+ how: draft.how.split('\n'),
+ doneWhen: draft.doneWhen,
+ type: draft.type,
+ effort: draft.effort,
+ role: draft.role,
+ });
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ >
+ <FormField id={`${id}-what`} label={t('what')}>
+ <Input
+ id={`${id}-what`}
+ autoFocus
+ value={draft.title}
+ maxLength={200}
+ disabled={disabled}
+ className="h-8 text-sm"
+ onChange={(e) => set('title')(e.target.value)}
+ />
+ </FormField>
+ <FormField id={`${id}-where`} label={t('where')}>
+ <Input
+ id={`${id}-where`}
+ value={draft.where}
+ maxLength={TASK_DETAIL_LIMITS.where}
+ disabled={disabled}
+ className="h-8 text-xs"
+ onChange={(e) => set('where')(e.target.value)}
+ />
+ </FormField>
+ <FormField id={`${id}-why`} label={t('why')}>
+ <Textarea
+ id={`${id}-why`}
+ value={draft.why}
+ rows={2}
+ maxLength={TASK_DETAIL_LIMITS.why}
+ disabled={disabled}
+ className="min-h-0 text-xs"
+ onChange={(e) => set('why')(e.target.value)}
+ />
+ </FormField>
+ <FormField
+ id={`${id}-how`}
+ label={t('how')}
+ hint={t('howHint', { max: TASK_DETAIL_LIMITS.steps })}
+ >
+ <Textarea
+ id={`${id}-how`}
+ value={draft.how}
+ rows={4}
+ maxLength={TASK_DETAIL_LIMITS.step * TASK_DETAIL_LIMITS.steps}
+ disabled={disabled}
+ className="min-h-0 text-xs"
+ onChange={(e) => set('how')(e.target.value)}
+ />
+ </FormField>
+ <FormField id={`${id}-done`} label={t('doneWhen')}>
+ <Input
+ id={`${id}-done`}
+ value={draft.doneWhen}
+ maxLength={TASK_DETAIL_LIMITS.doneWhen}
+ disabled={disabled}
+ className="h-8 text-xs"
+ onChange={(e) => set('doneWhen')(e.target.value)}
+ />
+ </FormField>
+ <div className="grid grid-cols-3 gap-2">
+ <FormField id={`${id}-type`} label={t('type')}>
+ <Select
+ value={draft.type ?? NO_TYPE}
+ onValueChange={(value) =>
+ setDraft((current) => ({ ...current, type: isTaskType(value) ? value : null }))
+ }
+ disabled={disabled}
+ items={[
+ { value: NO_TYPE, label: t('noType') },
+ ...TASK_TYPES.map((type) => ({ value: type, label: tTypes(type) })),
+ ]}
+ >
+ <SelectTrigger id={`${id}-type`} className="h-8 w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NO_TYPE}>{t('noType')}</SelectItem>
+ {TASK_TYPES.map((type) => (
+ <SelectItem key={type} value={type}>
+ {tTypes(type)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormField>
+ <FormField id={`${id}-effort`} label={t('effort')}>
+ <Input
+ id={`${id}-effort`}
+ value={draft.effort}
+ maxLength={TASK_DETAIL_LIMITS.effort}
+ placeholder={t('effortPlaceholder')}
+ disabled={disabled}
+ className="h-8 text-xs"
+ onChange={(e) => set('effort')(e.target.value)}
+ />
+ </FormField>
+ <FormField id={`${id}-role`} label={t('role')}>
+ <Input
+ id={`${id}-role`}
+ value={draft.role}
+ maxLength={TASK_DETAIL_LIMITS.role}
+ placeholder={t('rolePlaceholder')}
+ disabled={disabled}
+ className="h-8 text-xs"
+ onChange={(e) => set('role')(e.target.value)}
+ />
+ </FormField>
+ </div>
+ <div className="flex gap-2">
+ <Button type="submit" size="sm" disabled={disabled || !title} className="h-7 text-xs">
+ {t('save')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={disabled}
+ onClick={onCancel}
+ className="h-7 text-xs"
+ >
+ {t('cancel')}
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+function FormField({
+ id,
+ label,
+ hint,
+ children,
+}: {
+ id: string;
+ label: string;
+ hint?: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-1">
+ <Label htmlFor={id} className="text-xs text-muted-foreground">
+ {label}
+ {hint && <span className="ml-1 font-normal">· {hint}</span>}
+ </Label>
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.ts
index f15e77a9a..3124344d6 100644
--- a/web/src/lib/action-center/display.test.ts
+++ b/web/src/lib/action-center/display.test.ts
@@ -309,7 +309,7 @@ describe('History events', () => {
* checking nothing. */
it('reads the events the server actions log', () => {
expect(logged).toEqual(
- expect.arrayContaining(['status_changed', 'task_added', 'task_renamed', 'task_deleted']),
+ expect.arrayContaining(['status_changed', 'task_added', 'task_edited', 'task_deleted']),
);
});
diff --git a/web/src/lib/action-center/export.test.ts b/web/src/lib/action-center/export.test.ts
index 5a9ff3014..9a3fd273c 100644
--- a/web/src/lib/action-center/export.test.ts
+++ b/web/src/lib/action-center/export.test.ts
@@ -131,6 +131,7 @@ const texts: ExportTexts = {
}),
event: () => 'Action created',
skipped: (reason) => `Skipped: ${reason}`,
+ taskType: (type) => ({ content: 'Content', outreach: 'Outreach' })[type] ?? type,
answerSource: 'AI answer',
};
@@ -306,7 +307,85 @@ describe('the Excel file', () => {
'sheets.signals',
'sheets.history',
]);
- expect(sheets[2].data[2]).toEqual([2, '=HYPERLINK("x")', 'Skipped', 'Skipped: Done by hand']);
+ expect(sheets[2].data[2]).toEqual([
+ 2,
+ '=HYPERLINK("x")',
+ null,
+ 'Skipped',
+ null,
+ null,
+ null,
+ null,
+ null,
+ 'Skipped: Done by hand',
+ ]);
expect(sheets[3].data[1][6]).toBe('ChatGPT, Gemini');
});
});
+
+describe('a task with AC-004 fields', () => {
+ const concrete = buildActionExport(
+ action,
+ {
+ ...detail,
+ tasks: [
+ {
+ ...detail.tasks[0],
+ status: 'todo',
+ details: {
+ body: null,
+ platform: null,
+ platformLabel: null,
+ sources: [],
+ where: 'acme.example/blog/best-tools · 3 prompts on ChatGPT',
+ why: 'Cited #2 until Oct 8.\nThe pages cited now have a dated table.',
+ how: ['Add a feature table.', 'Put "2026" in the title.'],
+ doneWhen: 'Cited again on 2 of 3 platforms within 14 days.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ },
+ },
+ ],
+ },
+ texts,
+ { origin: 'https://app.example', timeZone: 'Europe/Istanbul' },
+ );
+
+ it('writes each field on its own line in Copy Data', () => {
+ expect(actionMarkdown(concrete, label)).toContain(
+ [
+ '1. Add a 2026 comparison table to /blog/best-tools (todo) · Content',
+ ' taskWhere: acme.example/blog/best-tools · 3 prompts on ChatGPT',
+ ' taskWhy: Cited #2 until Oct 8. The pages cited now have a dated table.',
+ ' taskHow: 1) Add a feature table. 2) Put "2026" in the title.',
+ ' taskDoneWhen: Cited again on 2 of 3 platforms within 14 days.',
+ ' taskEffort: ~2h · Content writer',
+ ].join('\n'),
+ );
+ });
+
+ it('gives each field its own column in the CSV and the workbook', () => {
+ const [head, , task] = actionCsv(concrete).split('\n');
+ const cells = Object.fromEntries(
+ head.split(',').map((name, i) => [name, task.match(/("([^"]|"")*"|[^,]*)(,|$)/g)?.[i]]),
+ );
+ expect(cells.type).toBe('Content,');
+ expect(cells.how).toBe('"1) Add a feature table. 2) Put ""2026"" in the title.",');
+ expect(cells.done_when).toBe('Cited again on 2 of 3 platforms within 14 days.,');
+
+ const sheet = actionWorkbook(concrete, label)[2];
+ expect(sheet.data[1]).toEqual([
+ 1,
+ 'Add a 2026 comparison table to /blog/best-tools',
+ 'Content',
+ 'todo',
+ 'acme.example/blog/best-tools · 3 prompts on ChatGPT',
+ 'Cited #2 until Oct 8. The pages cited now have a dated table.',
+ '1) Add a feature table. 2) Put "2026" in the title.',
+ 'Cited again on 2 of 3 platforms within 14 days.',
+ '~2h · Content writer',
+ '',
+ ]);
+ });
+});
diff --git a/web/src/lib/action-center/export.ts b/web/src/lib/action-center/export.ts
index 4587d0456..b3466e076 100644
--- a/web/src/lib/action-center/export.ts
+++ b/web/src/lib/action-center/export.ts
@@ -77,7 +77,15 @@ export interface ExportTask {
number: number;
title: string;
status: string;
- /** What the task carries beyond its title, and why it was skipped. */
+ /** "Content", "Outreach"…; empty when the task has none (AC-004). */
+ type: string;
+ where: string;
+ why: string;
+ how: string[];
+ doneWhen: string;
+ /** "~2h · Content writer". */
+ effort: string;
+ /** What else the task carries (an Improve task's body and evidence), and why it was skipped. */
details: string;
}
@@ -127,6 +135,8 @@ export interface ExportTexts {
event: (event: ActionDetail['events'][number]) => string;
/** "Skipped: {reason}". */
skipped: (reason: string) => string;
+ /** "Content", "On-page"…, for a task's type (AC-004). */
+ taskType: (type: string) => string;
/** What an AI answer a task rests on is called; its id means nothing outside. */
answerSource: string;
}
@@ -140,6 +150,13 @@ function dayOf(iso: string | null | undefined, timeZone: string): string {
return /^\d{4}-\d{2}-\d{2}$/.test(iso) ? iso : dayIn(iso, timeZone);
}
+/** A field on one line: an export row or a Markdown list item holds no line breaks. */
+const oneLine = (value: string | null | undefined): string =>
+ (value ?? '').replace(/\s*\n+\s*/g, ' ').trim();
+
+/** "1) Add a table. 2) Update the title." */
+const steps = (how: string[]): string => how.map((step, i) => `${i + 1}) ${step}`).join(' ');
+
/** The action and its detail, labelled, in the order the drawer shows them. */
export function buildActionExport(
action: ActionItem,
@@ -166,11 +183,12 @@ export function buildActionExport(
link: `${origin}/dashboard/action-center/actions?action=${action.id}`,
affected: texts.affected,
tasks: detail.tasks.map((task, i) => {
- const details = task.details
+ const d = task.details;
+ const details: (string | null)[] = d
? [
- task.details.body,
- task.details.platformLabel,
- ...task.details.sources.map((source) =>
+ d.body,
+ d.platformLabel,
+ ...d.sources.map((source) =>
source.type === 'answer' ? texts.answerSource : source.ref,
),
]
@@ -180,9 +198,15 @@ export function buildActionExport(
number: i + 1,
title: texts.taskTitle(task),
status: texts.taskStatus(task.status),
+ type: d?.type ? texts.taskType(d.type) : '',
+ where: oneLine(d?.where),
+ why: oneLine(d?.why),
+ how: (d?.how ?? []).map(oneLine),
+ doneWhen: oneLine(d?.doneWhen),
+ effort: [d?.effort, d?.role].filter(Boolean).join(' · '),
details: details
- .filter(Boolean)
- .map((part) => part.replace(/\s*\n+\s*/g, ' '))
+ .filter((part): part is string => !!part)
+ .map(oneLine)
.join(' · '),
};
}),
@@ -275,7 +299,14 @@ export function actionMarkdown(a: ActionExport, label: Labels): string {
lines.push('', `## ${label('tasksHeading', { count: a.tasks.length })}`);
for (const task of a.tasks) {
- lines.push(`${task.number}. ${task.title} (${task.status})`);
+ lines.push(
+ `${task.number}. ${task.title} (${task.status})${task.type ? ` · ${task.type}` : ''}`,
+ );
+ if (task.where) lines.push(` ${label('taskWhere')}: ${task.where}`);
+ if (task.why) lines.push(` ${label('taskWhy')}: ${task.why}`);
+ if (task.how.length) lines.push(` ${label('taskHow')}: ${steps(task.how)}`);
+ if (task.doneWhen) lines.push(` ${label('taskDoneWhen')}: ${task.doneWhen}`);
+ if (task.effort) lines.push(` ${label('taskEffort')}: ${task.effort}`);
if (task.details) lines.push(` ${task.details}`);
}
@@ -303,6 +334,11 @@ export const ACTION_CSV_HEADERS = [
'type',
'entity',
'details',
+ 'where',
+ 'why',
+ 'how',
+ 'done_when',
+ 'effort',
'status',
'category',
'impact',
@@ -337,7 +373,13 @@ export function actionCsv(a: ActionExport): string {
action: a.ref,
ref: task.number,
title: task.title,
+ type: task.type,
details: task.details,
+ where: task.where,
+ why: task.why,
+ how: steps(task.how),
+ done_when: task.doneWhen,
+ effort: task.effort,
status: task.status,
link: a.link,
})),
@@ -433,10 +475,43 @@ export function actionWorkbook(a: ActionExport, label: Labels): Sheet<Blob>[] {
{
sheet: label('sheets.tasks'),
stickyRowsCount: 1,
- columns: [{ width: 5 }, { width: 60 }, { width: 14 }, { width: 70 }],
+ columns: [
+ { width: 5 },
+ { width: 60 },
+ { width: 12 },
+ { width: 14 },
+ { width: 40 },
+ { width: 50 },
+ { width: 60 },
+ { width: 40 },
+ { width: 20 },
+ { width: 50 },
+ ],
data: [
- ['#', label('task'), label('status'), label('details')].map(bold),
- ...a.tasks.map((task) => [task.number, task.title, task.status, task.details]),
+ [
+ '#',
+ label('task'),
+ label('type'),
+ label('status'),
+ label('taskWhere'),
+ label('taskWhy'),
+ label('taskHow'),
+ label('taskDoneWhen'),
+ label('taskEffort'),
+ label('details'),
+ ].map(bold),
+ ...a.tasks.map((task) => [
+ task.number,
+ task.title,
+ task.type,
+ task.status,
+ task.where,
+ task.why,
+ steps(task.how),
+ task.doneWhen,
+ task.effort,
+ task.details,
+ ]),
],
},
{
diff --git a/web/src/lib/action-center/task-details.test.ts b/web/src/lib/action-center/task-details.test.ts
new file mode 100644
index 000000000..ff243ee74
--- /dev/null
+++ b/web/src/lib/action-center/task-details.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from 'vitest';
+import {
+ TASK_DETAIL_LIMITS,
+ cleanTaskDetailsEdit,
+ isTaskDetailsEdit,
+ parseTaskDetails,
+} from './task-details';
+
+const empty = {
+ body: null,
+ platform: null,
+ platformLabel: null,
+ sources: [],
+ where: null,
+ why: null,
+ how: [],
+ doneWhen: null,
+ type: null,
+ effort: null,
+ role: null,
+};
+
+describe('parseTaskDetails', () => {
+ it('reads a task sent from the Improve tab, which has none of the AC-004 fields', () => {
+ expect(
+ parseTaskDetails({
+ body: 'Lead with the table.',
+ platform: 'chatgpt-web',
+ platformLabel: 'ChatGPT',
+ sources: [{ type: 'domain', ref: 'profound.com' }],
+ }),
+ ).toEqual({
+ ...empty,
+ body: 'Lead with the table.',
+ platform: 'chatgpt-web',
+ platformLabel: 'ChatGPT',
+ sources: [{ type: 'domain', ref: 'profound.com' }],
+ });
+ });
+
+ it('reads where, why, how, done-when, type, effort and role', () => {
+ expect(
+ parseTaskDetails({
+ where: 'acme.example/blog/best-tools',
+ why: 'Cited #2 until Oct 8.',
+ how: ['Add a table.', ' ', 'Update the title.'],
+ doneWhen: 'Cited again on 2 of 3 platforms.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ }),
+ ).toEqual({
+ ...empty,
+ where: 'acme.example/blog/best-tools',
+ why: 'Cited #2 until Oct 8.',
+ how: ['Add a table.', 'Update the title.'],
+ doneWhen: 'Cited again on 2 of 3 platforms.',
+ type: 'content',
+ effort: '~2h',
+ role: 'Content writer',
+ });
+ });
+
+ it('ignores what is malformed rather than failing on it', () => {
+ expect(
+ parseTaskDetails({
+ where: 'x.example',
+ how: 'not a list',
+ type: 'marketing',
+ sources: [{ type: 'domain' }, null, 'x'],
+ }),
+ ).toEqual({ ...empty, where: 'x.example' });
+ });
+
+ it('is null when there is nothing to show', () => {
+ expect(parseTaskDetails(null)).toBeNull();
+ expect(parseTaskDetails([])).toBeNull();
+ expect(parseTaskDetails('text')).toBeNull();
+ expect(parseTaskDetails({ where: ' ', how: [] })).toBeNull();
+ });
+});
+
+describe('cleanTaskDetailsEdit', () => {
+ const edit = {
+ where: '',
+ why: '',
+ how: [],
+ doneWhen: '',
+ type: null,
+ effort: '',
+ role: '',
+ };
+
+ it('trims, and stores a cleared field as null', () => {
+ expect(
+ cleanTaskDetailsEdit({ ...edit, where: ' /pricing ', why: ' ', effort: ' ~1h ' }),
+ ).toEqual({
+ where: '/pricing',
+ why: null,
+ how: [],
+ doneWhen: null,
+ type: null,
+ effort: '~1h',
+ role: null,
+ });
+ });
+
+ it('drops blank steps and keeps at most the limit', () => {
+ const how = ['One', '', ' ', ...Array.from({ length: 12 }, (_, i) => `Step ${i}`)];
+ const cleaned = cleanTaskDetailsEdit({ ...edit, how });
+ expect(cleaned.how[0]).toBe('One');
+ expect(cleaned.how).toHaveLength(TASK_DETAIL_LIMITS.steps);
+ });
+
+ it('cuts each field to its length and refuses an unknown type', () => {
+ const cleaned = cleanTaskDetailsEdit({
+ ...edit,
+ why: 'x'.repeat(1000),
+ type: 'marketing' as never,
+ });
+ expect(cleaned.why).toHaveLength(TASK_DETAIL_LIMITS.why);
+ expect(cleaned.type).toBeNull();
+ });
+});
+
+describe('isTaskDetailsEdit', () => {
+ const edit = {
+ where: '/pricing',
+ why: '',
+ how: ['Add a table.'],
+ doneWhen: '',
+ type: 'content',
+ effort: '',
+ role: '',
+ };
+
+ it('accepts what the form sends', () => {
+ expect(isTaskDetailsEdit(edit)).toBe(true);
+ expect(isTaskDetailsEdit({ ...edit, type: null })).toBe(true);
+ });
+
+ it('refuses a malformed edit before anything reads it', () => {
+ expect(isTaskDetailsEdit(null)).toBe(false);
+ expect(isTaskDetailsEdit({ ...edit, how: 'Add a table.' })).toBe(false);
+ expect(isTaskDetailsEdit({ ...edit, how: [1] })).toBe(false);
+ expect(isTaskDetailsEdit({ ...edit, where: null })).toBe(false);
+ expect(isTaskDetailsEdit({ ...edit, type: 'marketing' })).toBe(false);
+ });
+});
diff --git a/web/src/lib/action-center/task-details.ts b/web/src/lib/action-center/task-details.ts
new file mode 100644
index 000000000..2f3c02a34
--- /dev/null
+++ b/web/src/lib/action-center/task-details.ts
@@ -0,0 +1,159 @@
+/**
+ * What a task carries beyond its title (AC-004): where to do it, why, how,
+ * when it counts as done, what kind of work it is and what it takes.
+ *
+ * A task sent from the Improve tab (PROMPT-004) also carries its body,
+ * platform and evidence; both shapes live in `action_tasks.details` and are
+ * read through `parseTaskDetails`, so a row written by either, or by neither,
+ * never breaks the drawer or the exports.
+ */
+
+/** The kinds of work a task can be (AC-004). */
+export const TASK_TYPES = ['content', 'on_page', 'technical', 'outreach', 'pr', 'product'] as const;
+export type TaskType = (typeof TASK_TYPES)[number];
+
+export interface ActionTaskDetails {
+ /** Improve (PROMPT-004): the suggestion as the user edited it. */
+ body: string | null;
+ platform: string | null;
+ platformLabel: string | null;
+ sources: { type: string; ref: string }[];
+ /** The exact page, prompt, platform, domain or competitor. */
+ where: string | null;
+ /** The evidence from the action's signals. */
+ why: string | null;
+ /** The steps, in order. */
+ how: string[];
+ /** A measurable check. */
+ doneWhen: string | null;
+ type: TaskType | null;
+ /** An estimate, e.g. "~2h". */
+ effort: string | null;
+ /** Who would do it, e.g. "Content writer". */
+ role: string | null;
+}
+
+/** The fields a person edits in the drawer. */
+export interface TaskDetailsEdit {
+ where: string;
+ why: string;
+ how: string[];
+ doneWhen: string;
+ type: TaskType | null;
+ effort: string;
+ role: string;
+}
+
+/** How long each field may be. Steps are lines of one list. */
+export const TASK_DETAIL_LIMITS = {
+ where: 300,
+ why: 600,
+ step: 300,
+ steps: 8,
+ doneWhen: 300,
+ effort: 40,
+ role: 60,
+} as const;
+
+const text = (value: unknown): string | null =>
+ typeof value === 'string' && value.trim() ? value.trim() : null;
+
+export function isTaskType(value: unknown): value is TaskType {
+ return typeof value === 'string' && (TASK_TYPES as readonly string[]).includes(value);
+}
+
+/**
+ * A task's details as stored, read defensively: any field may be missing or
+ * of the wrong type. Null when there is nothing to show.
+ */
+export function parseTaskDetails(raw: unknown): ActionTaskDetails | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const details: ActionTaskDetails = {
+ body: text(r.body),
+ platform: text(r.platform),
+ platformLabel: text(r.platformLabel),
+ sources: (Array.isArray(r.sources) ? r.sources : [])
+ .map((source) => {
+ const s = (source ?? {}) as Record<string, unknown>;
+ return { type: text(s.type) ?? '', ref: text(s.ref) ?? '' };
+ })
+ .filter((source) => source.type && source.ref),
+ where: text(r.where),
+ why: text(r.why),
+ how: (Array.isArray(r.how) ? r.how : [])
+ .map(text)
+ .filter((step): step is string => step !== null),
+ doneWhen: text(r.doneWhen),
+ type: isTaskType(r.type) ? r.type : null,
+ effort: text(r.effort),
+ role: text(r.role),
+ };
+ return hasTaskDetails(details) ? details : null;
+}
+
+/** Whether any field says something. */
+export function hasTaskDetails(details: ActionTaskDetails): boolean {
+ return (
+ details.body !== null ||
+ details.platformLabel !== null ||
+ details.sources.length > 0 ||
+ hasTaskSpec(details)
+ );
+}
+
+/** Whether the AC-004 fields say something; the Improve ones aside. */
+export function hasTaskSpec(details: ActionTaskDetails): boolean {
+ return (
+ details.where !== null ||
+ details.why !== null ||
+ details.how.length > 0 ||
+ details.doneWhen !== null ||
+ details.type !== null ||
+ details.effort !== null ||
+ details.role !== null
+ );
+}
+
+const clip = (value: string, max: number): string | null => {
+ const trimmed = value.trim().slice(0, max).trim();
+ return trimmed || null;
+};
+
+/**
+ * Whether a value has an edit's shape. A server action takes whatever the
+ * client sends, so the shape is checked before anything is read or written.
+ */
+export function isTaskDetailsEdit(value: unknown): value is TaskDetailsEdit {
+ if (!value || typeof value !== 'object') return false;
+ const v = value as Record<string, unknown>;
+ const strings = ['where', 'why', 'doneWhen', 'effort', 'role'] as const;
+ return (
+ strings.every((key) => typeof v[key] === 'string') &&
+ Array.isArray(v.how) &&
+ v.how.every((step) => typeof step === 'string') &&
+ (v.type === null || isTaskType(v.type))
+ );
+}
+
+/**
+ * An edit as it is stored: trimmed, cut to length, blank steps dropped and
+ * the list capped. Empty fields are stored as null, so clearing a field
+ * clears it.
+ */
+export function cleanTaskDetailsEdit(
+ edit: TaskDetailsEdit,
+): Pick<ActionTaskDetails, 'where' | 'why' | 'how' | 'doneWhen' | 'type' | 'effort' | 'role'> {
+ return {
+ where: clip(edit.where, TASK_DETAIL_LIMITS.where),
+ why: clip(edit.why, TASK_DETAIL_LIMITS.why),
+ how: edit.how
+ .map((step) => clip(step, TASK_DETAIL_LIMITS.step))
+ .filter((step): step is string => step !== null)
+ .slice(0, TASK_DETAIL_LIMITS.steps),
+ doneWhen: clip(edit.doneWhen, TASK_DETAIL_LIMITS.doneWhen),
+ type: isTaskType(edit.type) ? edit.type : null,
+ effort: clip(edit.effort, TASK_DETAIL_LIMITS.effort),
+ role: clip(edit.role, TASK_DETAIL_LIMITS.role),
+ };
+}
diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.ts
index fefa339a5..bae2700c2 100644
--- a/web/src/lib/actions/action-center.ts
+++ b/web/src/lib/actions/action-center.ts
@@ -24,6 +24,13 @@ import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { supabaseAdmin } from '@/lib/supabase/admin';
import type { KpiTimeframe } from '@/lib/kpis/registry';
import { parseImproveOutcome, type ImproveOutcome } from '@/lib/improve-outcome';
+import {
+ cleanTaskDetailsEdit,
+ isTaskDetailsEdit,
+ parseTaskDetails,
+ type ActionTaskDetails,
+ type TaskDetailsEdit,
+} from '@/lib/action-center/task-details';
import {
parsePriorityReason,
storedPriorityLevel,
@@ -189,19 +196,13 @@ export interface ActionTask {
/** Why the task was skipped; null for every other status. */
skipReason: string | null;
/**
- * What a task sent from the Improve tab carries beyond its title (PROMPT-004):
- * its body, platform and evidence. Null for library and hand-added tasks.
+ * What the task carries beyond its title: where, why, how, done-when, type
+ * and effort (AC-004), and for a task sent from the Improve tab its body,
+ * platform and evidence (PROMPT-004). Null when it carries nothing.
*/
details: ActionTaskDetails | null;
}
-export interface ActionTaskDetails {
- body: string;
- platform: string;
- platformLabel: string;
- sources: { type: string; ref: string }[];
-}
-
export interface ActionEvent {
id: string;
event: string;
@@ -281,7 +282,7 @@ export async function getActionDetail(brandId: string, actionId: string): Promis
titleParams: (task.title_params ?? {}) as Record<string, string | number>,
dependsOn: (task.depends_on ?? []) as string[],
skipReason: task.skip_reason,
- details: (task.details ?? null) as ActionTaskDetails | null,
+ details: parseTaskDetails(task.details),
})),
signals: mapSignalRows((signalsRes.data ?? []) as SignalRow[], places),
events: (eventsRes.data ?? []).map((event) => ({
@@ -451,27 +452,51 @@ export async function addTask(brandId: string, actionId: string, title: string):
}
/**
- * Rename a task. A generated task keeps its `task_key` for provenance — which
- * template it grew from stays answerable — and the title simply wins at render
- * time.
+ * Edit a task's text and its details (AC-004): where, why, how, done-when,
+ * type, effort and role. `title` is null to leave the text as it is, so a
+ * library task keeps rendering from its template in the reader's language.
+ *
+ * The fields are merged into what the task already carries, so a task sent
+ * from the Improve tab keeps its body, platform and evidence.
*/
-export async function updateTaskTitle(
+export async function updateTaskDetails(
brandId: string,
actionId: string,
taskId: string,
- title: string,
+ edit: TaskDetailsEdit & { title: string | null },
): Promise<void> {
+ if (!isTaskDetailsEdit(edit) || (edit.title !== null && typeof edit.title !== 'string')) {
+ throw new Error('Invalid task details');
+ }
const supabase = await createClient();
- const text = cleanTaskTitle(title);
+ const { data: row, error: readError } = await supabase
+ .from('action_tasks')
+ .select('details')
+ .eq('action_id', actionId)
+ .eq('id', taskId)
+ .maybeSingle();
+ if (readError) throw new Error(readError.message);
+ if (!row) throw new Error('Task not found');
+
+ const stored =
+ row.details && typeof row.details === 'object' && !Array.isArray(row.details)
+ ? (row.details as Record<string, unknown>)
+ : {};
+ const details = { ...stored, ...cleanTaskDetailsEdit(edit) };
+ const title = edit.title === null ? null : cleanTaskTitle(edit.title);
const { error } = await supabase
.from('action_tasks')
- .update({ title: text, updated_at: new Date().toISOString() })
+ .update({
+ details,
+ ...(title === null ? {} : { title }),
+ updated_at: new Date().toISOString(),
+ })
.eq('action_id', actionId)
.eq('id', taskId);
if (error) throw new Error(error.message);
- await logEvent(supabase, actionId, 'task_renamed', { taskId, title: text });
+ await logEvent(supabase, actionId, 'task_edited', { taskId, title });
await touchAction(supabase, brandId, actionId);
}
diff --git a/web/src/lib/actions/task-details-edit.test.ts b/web/src/lib/actions/task-details-edit.test.ts
new file mode 100644
index 000000000..1f72e055d
--- /dev/null
+++ b/web/src/lib/actions/task-details-edit.test.ts
@@ -0,0 +1,95 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Editing a task's details (AC-004): the fields merge into what the task
+ * already carries, and the text is written only when it changed.
+ */
+
+let stored: Record<string, unknown> | null;
+let updates: Record<string, unknown>[];
+let events: Record<string, unknown>[];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ from: (table: string) => {
+ const chain: Record<string, unknown> = {};
+ for (const method of ['select', 'eq']) chain[method] = () => chain;
+ chain.maybeSingle = async () => ({
+ data: stored === undefined ? null : { details: stored },
+ error: null,
+ });
+ chain.update = (values: Record<string, unknown>) => {
+ if (table === 'action_tasks') updates.push(values);
+ return chain;
+ };
+ chain.insert = async (values: Record<string, unknown>) => {
+ if (table === 'action_events') events.push(values);
+ return { error: null };
+ };
+ chain.then = (resolve: (value: unknown) => unknown) => resolve({ error: null });
+ return chain;
+ },
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+
+const { updateTaskDetails } = await import('./action-center');
+
+const edit = {
+ title: null,
+ where: ' acme.example/pricing ',
+ why: '',
+ how: ['Add a table.', ''],
+ doneWhen: 'Cited again within 14 days.',
+ type: 'content' as const,
+ effort: '~1h',
+ role: '',
+};
+
+beforeEach(() => {
+ stored = null;
+ updates = [];
+ events = [];
+});
+
+describe('updateTaskDetails', () => {
+ it("keeps an Improve task's body, platform and evidence", async () => {
+ stored = {
+ body: 'Lead with the table.',
+ platform: 'chatgpt-web',
+ platformLabel: 'ChatGPT',
+ sources: [{ type: 'domain', ref: 'profound.com' }],
+ };
+ await updateTaskDetails('b1', 'a1', 't1', edit);
+
+ expect(updates[0].details).toEqual({
+ body: 'Lead with the table.',
+ platform: 'chatgpt-web',
+ platformLabel: 'ChatGPT',
+ sources: [{ type: 'domain', ref: 'profound.com' }],
+ where: 'acme.example/pricing',
+ why: null,
+ how: ['Add a table.'],
+ doneWhen: 'Cited again within 14 days.',
+ type: 'content',
+ effort: '~1h',
+ role: null,
+ });
+ // The text was not changed, so a library task keeps rendering from its template.
+ expect(updates[0]).not.toHaveProperty('title');
+ expect(events[0]).toMatchObject({ event: 'task_edited', data: { taskId: 't1', title: null } });
+ });
+
+ it('writes a changed text', async () => {
+ await updateTaskDetails('b1', 'a1', 't1', { ...edit, title: ' Add a table to /pricing ' });
+ expect(updates[0].title).toBe('Add a table to /pricing');
+ });
+
+ it('refuses a malformed edit without touching the task', async () => {
+ await expect(
+ updateTaskDetails('b1', 'a1', 't1', { ...edit, how: 'Add a table.' as never }),
+ ).rejects.toThrow('Invalid task details');
+ expect(updates).toEqual([]);
+ });
+});
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index ff1a1ac65..d90d27b45 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -21,6 +21,7 @@ import {
import { mapSignalRows, type SignalRow } from '@/lib/signals/map';
import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';
+import { parseTaskDetails } from '@/lib/action-center/task-details';
/**
* Pure data-fetch functions shared by the MCP route and the parallel REST
@@ -2661,11 +2662,31 @@ export interface ActionDetailForMcp {
mode: string | null;
permission: string | null;
depends_on: string[];
+ details: ReturnType<typeof mcpTaskDetails>;
}>;
signals: Record<string, unknown>[];
events: Array<{ event: string; data: Record<string, unknown>; created_at: string }>;
}
+/** A task's details in the snake_case the rest of the MCP output uses. */
+function mcpTaskDetails(raw: unknown) {
+ const d = parseTaskDetails(raw);
+ if (!d) return null;
+ return {
+ where: d.where,
+ why: d.why,
+ how: d.how,
+ done_when: d.doneWhen,
+ type: d.type,
+ effort: d.effort,
+ role: d.role,
+ body: d.body,
+ platform: d.platform,
+ platform_label: d.platformLabel,
+ sources: d.sources,
+ };
+}
+
export async function getActionFor(
auth: McpAuthContext,
actionId: string,
@@ -2687,7 +2708,7 @@ export async function getActionFor(
supabaseAdmin
.from('action_tasks')
.select(
- 'id, position, task_key, title, title_params, status, skip_reason, mode, permission, depends_on',
+ 'id, position, task_key, title, title_params, status, skip_reason, mode, permission, depends_on, details',
)
.eq('action_id', actionId)
.order('position'),
@@ -2740,6 +2761,8 @@ export async function getActionFor(
mode: t.mode ?? null,
permission: t.permission ?? null,
depends_on: (t.depends_on ?? []) as string[],
+ // Where, why, how and done-when (AC-004); an Improve task's body and evidence.
+ details: mcpTaskDetails(t.details),
})),
// The join that found them is not part of a signal.
signals: ((signalsRes.data ?? []) as Record<string, unknown>[]).map((row) =>
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index eebdfc427..225e3e003 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -938,7 +938,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'get_action',
{
description:
- 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`.',
+ 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`. `details` says what the task carries beyond that, or null: `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `how` (the steps), `done_when` (the check that closes it), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`.',
inputSchema: {
action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),
},