Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): hold tasks an agent writes without the page, the change, Done when or the check for review (AC-010, part 2) (#1562)
Cihanf913673adcf3
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex 0310dcdd0..c07a62c20 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -93,6 +93,8 @@ From a task you can also:Where AI task writing is on for your workspace, **Regenerate tasks** writes the action's tasks again from its evidence. Done, under-way and hand-added tasks stay. It uses your plan's monthly AI allowance.+A task the AI writes without its **URL**, its **Change**, **Done when** or **How we check** doesn't reach your list. It waits on the **Needs review** tab, which admins and managers see, with what it misses. Click **Edit**, fill the missing fields and click **Approve** to add it after the action's other tasks, or **Dismiss** it.+Some tasks that only read data, such as checking a page's traffic in your connected Analytics, can be carried out by Ansvisor itself overnight. The action's History says so. Nothing that would change something outside Ansvisor runs without your approval: such a task waits as **Waiting Approval**.### Assigning workdiff --git a/server/src/lib/action-center/task-writer/index.js b/server/src/lib/action-center/task-writer/index.jsindex 60a017ef4..72c25c328 100644--- a/server/src/lib/action-center/task-writer/index.js+++ b/server/src/lib/action-center/task-writer/index.js@@ -27,7 +27,15 @@ import { getTask } from '../tasks/registry.js';import { IMPROVE_ACTION_KIND } from '../from-prompt-improve.js';import { OPPORTUNITY_ACTION_KIND } from '../from-opportunity.js';import { buildEvidence, evidenceForPrompt, hasTargets } from './evidence.js';-import { MAX_TASKS, pageAddress, sameTask, taskProblems } from './quality.js';+import {+ MAX_TASKS,+ TASK_CHECKS,+ onlyGaps,+ pageAddress,+ sameTask,+ taskGaps,+ taskProblems,+} from './quality.js';import { buildRetryPrompt, buildTaskWriterPrompt, taskWriterSchema } from './prompt.js';/** Whether this deployment writes tasks at all. */@@ -294,6 +302,8 @@ async function compose({ action, brand, domains, signals, name, trigger, userId,const first = sift(await callModel({ modelId, ...base, charge }), evidence, []);let tasks = first.accepted;let refused = first.refused;+ // The refusals of the last round asked: the first round's were asked for again.+ let lastRefused = first.refused;// Refused tasks come back once, with their reasons.const missing = Math.min(refused.length, MAX_TASKS - tasks.length);@@ -303,29 +313,89 @@ async function compose({ action, brand, domains, signals, name, trigger, userId,tasks = [...tasks, ...second.accepted];// Both rounds' refusals, so a review sees how often the first answer misses.refused = [...refused, ...second.refused];+ lastRefused = second.refused;}- if (dryRun) return { status: 'preview', tasks, refused, costUsd, evidence: shown };- if (tasks.length === 0) {+ // AC-010: a task the last round refused only for the fields it misses+ // (the exact page, the change, Done when, how it's checked) waits for an+ // admin or a manager to fill them, up to the action's MAX_TASKS.+ const reviews = [];+ for (const { task, problems } of lastRefused) {+ if (tasks.length + reviews.length >= MAX_TASKS) break;+ if (!onlyGaps(problems) || [...tasks, ...reviews].some((t) => sameTask(t, task))) continue;+ reviews.push(task);+ }++ if (dryRun) return { status: 'preview', tasks, reviews, refused, costUsd, evidence: shown };+ if (tasks.length === 0 && reviews.length === 0) {await markWritten(actionId, now);return { status: 'skipped', reason: 'no_valid_tasks', refused, costUsd };}- const kept = await replaceTasks(actionId, tasks, { now });- await markWritten(actionId, now, { changed: true });+ // The reviews first: a failure there leaves the tasks as they were. None+ // to show yet: the template tasks stay, and the reviews wait.+ await replaceReviews(actionId, reviews);+ const kept = tasks.length > 0 ? await replaceTasks(actionId, tasks, { now }) : null;+ await markWritten(actionId, now, { changed: tasks.length > 0 });await supabaseAdmin.from('action_events').insert({action_id: actionId,event: 'tasks_generated',- data: { count: tasks.length, kept, trigger },+ data: { count: tasks.length, kept, trigger, reviews: reviews.length },actor_id: userId,});- return { status: 'written', tasks, refused, kept, costUsd };+ return { status: 'written', tasks, reviews, refused, kept, costUsd };} finally {// Nothing charged (the first call failed): the hold goes.await budget?.release();}}+const text = (value) => (typeof value === 'string' ? value.trim() : '');++/** A written task's details as stored (AC-004, AC-010); a field it misses is null. */+function detailsOf(task) {+ const after = text(task.change?.after);+ const check = text(task.check).toLowerCase();+ return {+ url: pageAddress(task.url),+ where: text(task.where),+ why: text(task.why),+ change: after ? { before: text(task.change.before) || null, after } : null,+ how: (task.how ?? []).map(text).filter(Boolean),+ doneWhen: text(task.doneWhen) || null,+ check: TASK_CHECKS.includes(check) ? check : null,+ type: task.type,+ effort: text(task.effort),+ role: text(task.role),+ source: 'ai',+ refs: task.refs,+ };+}++/**+ * The action's tasks waiting for review (AC-010, 00293) in place of the ones+ * an earlier writing left: a new writing is the one to review.+ */+async function replaceReviews(actionId, reviews) {+ const { error: deleteError } = await supabaseAdmin+ .from('action_task_reviews')+ .delete()+ .eq('action_id', actionId)+ .eq('source', 'ai');+ if (deleteError) throw new Error(deleteError.message);+ if (reviews.length === 0) return;+ const { error } = await supabaseAdmin.from('action_task_reviews').insert(+ reviews.map((task) => ({+ action_id: actionId,+ title: task.title.trim(),+ details: detailsOf(task),+ missing: taskGaps(task),+ source: 'ai',+ })),+ );+ if (error) throw new Error(error.message);+}+/** Record the writing; the action counts as updated only when its tasks changed. */async function markWritten(actionId, now, { changed = false } = {}) {const { error } = await supabaseAdmin@@ -368,20 +438,7 @@ export async function replaceTasks(actionId, tasks, { now = new Date() } = {}) {title: task.title.trim(),mode: 'human',permission: 'read',- details: {- url: pageAddress(task.url),- where: task.where.trim(),- why: task.why.trim(),- change: { before: task.change.before.trim() || null, after: task.change.after.trim() },- how: task.how.map((step) => step.trim()).filter(Boolean),- doneWhen: task.doneWhen.trim(),- check: task.check.trim().toLowerCase(),- type: task.type,- effort: task.effort.trim(),- role: task.role.trim(),- source: 'ai',- refs: task.refs,- },+ details: detailsOf(task),})),).select('id, position');diff --git a/server/src/lib/action-center/task-writer/index.test.js b/server/src/lib/action-center/task-writer/index.test.jsindex 15d6f2cdd..e391eb9cf 100644--- a/server/src/lib/action-center/task-writer/index.test.js+++ b/server/src/lib/action-center/task-writer/index.test.js@@ -45,7 +45,7 @@ function table(name) {}if (q.op === 'delete') {const ids = q.filters.find(([col]) => col === 'id')?.[1] ?? [];- db[name] = db[name].filter((row) => !ids.includes(row.id));+ db[name] = (db[name] ?? []).filter((row) => !ids.includes(row.id));}if (q.op === 'update') {const matched = rows();@@ -194,6 +194,10 @@ describe('keepsTask', () => {expect(keepsTask({ task_key: 'refresh_content', status: 'todo' })).toBe(false);expect(keepsTask({ task_key: null, status: 'todo', details: null })).toBe(true);expect(keepsTask({ task_key: null, status: 'todo', details: { source: 'ai' } })).toBe(false);+ // One a manager filled and approved from Needs review (AC-010, 00293) is theirs.+ expect(keepsTask({ task_key: null, status: 'todo', details: { source: 'reviewed' } })).toBe(+ true,+ );expect(keepsTask({ task_key: 'analyze_citations', status: 'completed' })).toBe(false);expect(keepsTask({ task_key: 'validate_citations', status: 'in_progress' })).toBe(false);// Sent to Content or a webhook: kept, whatever its status.@@ -293,6 +297,74 @@ describe('writeTasksForAction', () => {expect(db.actions[0].tasks_generated_at).toEqual(expect.any(String));});+ it('puts a task the last round gave without its page, change or check in review (AC-010)', async () => {+ generateObject+ .mockResolvedValueOnce(+ answer([task(), task({ title: 'Add an FAQ to /blog/shipping', url: '', check: 'later' })]),+ )+ .mockResolvedValueOnce(+ answer([+ task({+ title: 'Add a map to /blog/shipping',+ url: 'the shipping page',+ change: { before: '', after: ' ' },+ }),+ ]),+ );++ const result = await writeTasksForAction('a1', { trigger: 'regenerate', userId: 'u1' });++ expect(result.status).toBe('written');+ expect(result.tasks.map((t) => t.title)).toEqual([+ 'Add a 2026 shipping table to /blog/shipping',+ ]);+ // The first round's was asked for again: only the last round's waits.+ expect(result.reviews.map((t) => t.title)).toEqual(['Add a map to /blog/shipping']);+ const reviews = ops.filter((op) => op.table === 'action_task_reviews');+ expect(reviews.map((op) => [op.op, op.filters])).toEqual([+ // The earlier writing's go first.+ [+ 'delete',+ [+ ['action_id', 'a1'],+ ['source', 'ai'],+ ],+ ],+ ['insert', []],+ ]);+ // The reviews go in before the tasks: a failure there leaves the tasks as they were.+ const at = (table, op) => ops.findIndex((o) => o.table === table && o.op === op);+ expect(at('action_task_reviews', 'insert')).toBeLessThan(at('action_tasks', 'insert'));+ expect(reviews[1].payload).toEqual([+ {+ action_id: 'a1',+ title: 'Add a map to /blog/shipping',+ details: expect.objectContaining({ url: null, change: null, check: 'rerun', source: 'ai' }),+ missing: ['url', 'change'],+ source: 'ai',+ },+ ]);+ expect(ops.find((op) => op.table === 'action_events').payload.data).toMatchObject({+ count: 1,+ reviews: 1,+ });+ });++ it('keeps the template tasks when every written task waits for review', async () => {+ generateObject+ .mockResolvedValueOnce(answer([task({ url: '' })]))+ .mockResolvedValueOnce(answer([task({ check: 'weekly' })]));++ const result = await writeTasksForAction('a1', { trigger: 'regenerate', userId: 'u1' });++ expect(result).toMatchObject({ status: 'written', kept: null, tasks: [] });+ expect(result.reviews).toHaveLength(1);+ expect(ops.some((op) => op.table === 'action_tasks' && op.op === 'insert')).toBe(false);+ expect(+ ops.find((op) => op.table === 'action_task_reviews' && op.op === 'insert').payload[0].missing,+ ).toEqual(['check']);+ });+it('writes and charges nothing on a dry run', async () => {generateObject.mockResolvedValueOnce(answer([task()]));const result = await writeTasksForAction('a1', { dryRun: true });diff --git a/server/src/lib/action-center/task-writer/quality.js b/server/src/lib/action-center/task-writer/quality.jsindex ace9b8465..e6c0f2cf5 100644--- a/server/src/lib/action-center/task-writer/quality.js+++ b/server/src/lib/action-center/task-writer/quality.js@@ -37,12 +37,41 @@ const COUNT_IN_TITLE =*/const PAGE_ADDRESS = /^(?:https?:\/\/\S+|\/\S*|(?:[a-z0-9-]+\.)+[a-z]{2,}(?:[/?#]\S*)?)$/i;-/** A task's URL as stored: a host and path gets its https://. */+/** A task's URL as stored: a host and path gets its https://; null when it's no page address. */export function pageAddress(url) {const value = text(url);+ if (!PAGE_ADDRESS.test(value)) return null;return /^(?:https?:\/\/|\/)/i.test(value) ? value : `https://${value}`;}+/**+ * What a task missing one of AC-010's fields is refused for. A task refused+ * for these alone waits for review (00293) rather than going.+ */+const GAP = Object.freeze({+ urlEmpty: 'URL is empty',+ urlNotPage: 'URL is not a page address (https://… or /…)',+ change: 'the change has no after text',+ doneWhen: 'Done when is empty',+ check: 'check is not auto, rerun or manual',+});++/** Whether a task's problems are only AC-010 fields it misses. */+export function onlyGaps(problems) {+ const gaps = new Set(Object.values(GAP));+ return problems.length > 0 && problems.every((problem) => gaps.has(problem));+}++/** The AC-010 fields a task misses, as action_task_reviews.missing names them. */+export function taskGaps(task) {+ const gaps = [];+ if (!pageAddress(task?.url)) gaps.push('url');+ if (!text(task?.change?.after)) gaps.push('change');+ if (!text(task?.doneWhen)) gaps.push('doneWhen');+ if (!TASK_CHECKS.includes(text(task?.check).toLowerCase())) gaps.push('check');+ return gaps;+}+/** Analysis the product does itself and shows in the Affected tab. */const ANALYSIS_VERB =/^(?:analy[sz]e|identify|validate|measure|monitor|review|investigate|assess|audit|evaluate|research|track|determine|look into)\b/i;@@ -65,15 +94,13 @@ export function taskProblems(task, evidence) {if (!title) problems.push('it has no title');// AC-010: the exact page, the change, Done when and how it's checked.- if (!url) problems.push('URL is empty');- else if (!PAGE_ADDRESS.test(url)) problems.push('URL is not a page address (https://… or /…)');+ if (!url) problems.push(GAP.urlEmpty);+ else if (!PAGE_ADDRESS.test(url)) problems.push(GAP.urlNotPage);if (!where) problems.push('Where is empty');- if (!text(task?.change?.after)) problems.push('the change has no after text');+ if (!text(task?.change?.after)) problems.push(GAP.change);if (steps.length < 2 || steps.length > 5) problems.push('How needs 2 to 5 steps');- if (!text(task?.doneWhen)) problems.push('Done when is empty');- if (!TASK_CHECKS.includes(text(task?.check).toLowerCase())) {- problems.push('check is not auto, rerun or manual');- }+ if (!text(task?.doneWhen)) problems.push(GAP.doneWhen);+ if (!TASK_CHECKS.includes(text(task?.check).toLowerCase())) problems.push(GAP.check);if (!TASK_TYPES.includes(task?.type)) problems.push('its type is not one of the six');if (COUNT_IN_TITLE.test(title)) {problems.push('the title counts prompts or pages instead of naming one');diff --git a/server/src/lib/action-center/task-writer/quality.test.js b/server/src/lib/action-center/task-writer/quality.test.jsindex 59927cb87..4bdc44e81 100644--- a/server/src/lib/action-center/task-writer/quality.test.js+++ b/server/src/lib/action-center/task-writer/quality.test.js@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';import { buildEvidence } from './evidence.js';-import { pageAddress, sameTask, taskProblems } from './quality.js';+import { onlyGaps, pageAddress, sameTask, taskGaps, taskProblems } from './quality.js';const evidence = buildEvidence([{@@ -89,10 +89,24 @@ describe('taskProblems', () => {expect(taskProblems({ ...good, check: 'Auto' }, evidence)).toEqual([]);});- it('stores a host and path with its https://', () => {+ it('stores a host and path with its https://, and no address as none', () => {expect(pageAddress(' acme.example/blog/shipping ')).toBe('https://acme.example/blog/shipping');expect(pageAddress('/pricing')).toBe('/pricing');expect(pageAddress('http://acme.example/x')).toBe('http://acme.example/x');+ expect(pageAddress('the shipping guide')).toBeNull();+ expect(pageAddress(undefined)).toBeNull();+ });++ it('names the fields a task misses, and tells them from its other problems (AC-010)', () => {+ expect(taskGaps(good)).toEqual([]);+ expect(+ taskGaps({ ...good, url: 'the guide', change: { before: 'x', after: '' }, doneWhen: ' ' }),+ ).toEqual(['url', 'change', 'doneWhen']);+ expect(taskGaps({ ...good, check: undefined })).toEqual(['check']);+ expect(onlyGaps(taskProblems({ ...good, url: '', check: 'later' }, evidence))).toBe(true);+ // Another problem with them, or none at all: not a gap to review.+ expect(onlyGaps(taskProblems({ ...good, url: '', where: '' }, evidence))).toBe(false);+ expect(onlyGaps([])).toBe(false);});it('needs refs the evidence has, and its target named', () => {diff --git a/server/src/routes/action-center-tasks.test.js b/server/src/routes/action-center-tasks.test.jsindex ad13fa517..ad500b05a 100644--- a/server/src/routes/action-center-tasks.test.js+++ b/server/src/routes/action-center-tasks.test.js@@ -78,8 +78,14 @@ describe('regenerateTasks', () => {});it('writes as the caller and says how many were written and kept', async () => {- writeTasksForAction.mockResolvedValueOnce({ status: 'written', tasks: [{}, {}, {}], kept: 2 });- expect(await regenerateTasks('a1', 'u1')).toEqual({ written: 3, kept: 2 });+ writeTasksForAction.mockResolvedValueOnce({+ status: 'written',+ tasks: [{}, {}, {}],+ reviews: [{}],+ kept: 2,+ });+ // With how many wait in Needs review (AC-010).+ expect(await regenerateTasks('a1', 'u1')).toEqual({ written: 3, kept: 2, reviews: 1 });expect(writeTasksForAction).toHaveBeenCalledWith('a1', { trigger: 'regenerate', userId: 'u1' });});diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsindex 52ea45942..968b95c8f 100644--- a/server/src/routes/action-center.js+++ b/server/src/routes/action-center.js@@ -99,7 +99,8 @@ export async function regenerateTasks(actionId, userId) {if (result.status !== 'written') {throw new TaskWriterError(result.reason, NOTHING_WRITTEN[result.reason]);}- return { written: result.tasks.length, kept: result.kept };+ // Tasks missing an AC-010 field wait in Needs review (00293).+ return { written: result.tasks.length, kept: result.kept ?? 0, reviews: result.reviews.length };}/** POST /api/action-center/actions/:id/tasks/regenerate */diff --git a/server/src/scripts/review-action-tasks.js b/server/src/scripts/review-action-tasks.jsindex c30c36bd8..d4fad3131 100644--- a/server/src/scripts/review-action-tasks.js+++ b/server/src/scripts/review-action-tasks.js@@ -54,7 +54,9 @@ for (const action of actions) {console.log(result.reason);continue;}- console.log(`${result.tasks.length} tasks, ${result.refused.length} refused`);+ console.log(+ `${result.tasks.length} tasks, ${result.reviews.length} for review, ${result.refused.length} refused`,+ );const e = result.evidence;lines.push(`Evidence: ${e.pages.length} pages, ${e.prompts.length} prompts, ${e.domains.length} domains, ${e.competitors.length} competitors · $${result.costUsd.toFixed(4)}`,@@ -63,14 +65,20 @@ for (const action of actions) {result.tasks.forEach((task, i) => {lines.push(`${i + 1}. **${task.title}** · ${task.type}`,+ ` - URL: ${task.url}`,` - Where: ${task.where}`,` - Why: ${task.why}`,+ ` - Change: ${task.change.before ? `${task.change.before} → ` : ''}${task.change.after}`,` - How: ${task.how.map((step, n) => `${n + 1}) ${step}`).join(' ')}`,- ` - Done when: ${task.doneWhen}`,+ ` - Done when: ${task.doneWhen} (check: ${task.check})`,` - Effort: ${[task.effort, task.role].filter(Boolean).join(' · ')}`,` - Refs: ${task.refs.join(', ')}`,);});+ if (result.reviews.length) {+ lines.push('', 'Waiting for review (AC-010):');+ for (const task of result.reviews) lines.push(`- ${task.title}`);+ }if (result.refused.length) {lines.push('', 'Refused:');for (const { task, problems } of result.refused) {diff --git a/supabase/migrations/00293_action_task_reviews.sql b/supabase/migrations/00293_action_task_reviews.sqlnew file mode 100644index 000000000..4196e09a0--- /dev/null+++ b/supabase/migrations/00293_action_task_reviews.sql@@ -0,0 +1,163 @@+-- ============================================================================+-- 00293: tasks waiting for review (AC-010)+-- ============================================================================+-- Every task an agent writes says the exact page, the change, when it is+-- done and how that is checked (AC-010; the fields live in+-- action_tasks.details). A task the AI task writer gives without one of+-- them doesn't reach the people doing the work: it waits here, for an+-- admin or a manager of the brand's organization to fill what it misses.+--+-- * action_task_reviews: one row per task waiting, with the task as it was+-- written (title and details) and the fields it misses ('url', 'change',+-- 'doneWhen', 'check'). Not a task yet, so nothing that reads+-- action_tasks (the lists, counts, exports, the runner) sees it.+-- * approve_action_task_review: the reviewed task, its four fields filled,+-- goes onto the action's task list, after its last task, and the review+-- row goes, in one transaction. The trail says a task was added. It is+-- the reviewer's task now (source 'reviewed'): Regenerate tasks keeps+-- it, as it keeps a task someone added. Not on an action that is+-- deleted or closed.+-- * Admins and managers read and dismiss (delete) the rows; the server+-- writes them (service role). Edits go into the task on approval.++create table if not exists public.action_task_reviews (+ id uuid primary key default gen_random_uuid(),+ action_id uuid not null references public.actions(id) on delete cascade,+ title text not null check (char_length(title) between 1 and 200),+ details jsonb not null default '{}'::jsonb,+ missing text[] not null default '{}'+ check (missing <@ array['url', 'change', 'doneWhen', 'check']::text[]),+ source text not null default 'ai' check (source in ('ai', 'agent')),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists action_task_reviews_action_idx+ on public.action_task_reviews (action_id);++-- Read and dismissed by admins and managers (the policies below); written by the server.+alter table public.action_task_reviews enable row level security;+revoke all on table public.action_task_reviews from anon, authenticated;+grant select, delete on table public.action_task_reviews to authenticated;+grant all on table public.action_task_reviews to service_role;++drop policy if exists "action_task_reviews: manager select" on public.action_task_reviews;+create policy "action_task_reviews: manager select"+ on public.action_task_reviews+ for select+ using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++drop policy if exists "action_task_reviews: manager delete" on public.action_task_reviews;+create policy "action_task_reviews: manager delete"+ on public.action_task_reviews+ for delete+ using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++comment on table public.action_task_reviews is+ 'Action Center (AC-010): tasks an agent wrote without the exact page, the change, Done when or how it is checked (missing), waiting for an admin or a manager. Not tasks yet: approve_action_task_review puts one on its action''s list. The server writes them.';++-- The reviewed task onto its action's list, its four fields filled, and the+-- review row gone. Null when the row isn't there (approved or dismissed+-- meanwhile, or another organization's); an error when the caller isn't an+-- admin or a manager, the action is deleted or closed, or a field is still+-- missing.+create or replace function public.approve_action_task_review(+ p_review_id uuid,+ p_title text,+ p_details jsonb+)+returns uuid+language plpgsql+security definer+set search_path = public+as $$+declare+ v_review public.action_task_reviews%rowtype;+ v_title text := btrim(coalesce(p_title, ''));+ v_task_id uuid;+begin+ -- The caller's role first, before any row is read or locked.+ if not exists (+ select 1 from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ ) then+ raise exception 'not allowed' using errcode = '42501';+ end if;++ -- Only a row of the caller's own organization: another's reads as not there.+ select r.* into v_review+ from public.action_task_reviews r+ join public.actions a on a.id = r.action_id+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where r.id = p_review_id+ and p.id = auth.uid()+ for update of r;+ if not found then+ return null;+ end if;++ if exists (+ select 1 from public.actions a+ where a.id = v_review.action_id+ and (a.deleted_at is not null or a.status in ('completed', 'dismissed'))+ ) then+ raise exception 'action closed' using errcode = '55000';+ end if;++ if char_length(v_title) not between 1 and 200+ or jsonb_typeof(p_details) is distinct from 'object'+ or nullif(btrim(coalesce(p_details->>'url', '')), '') is null+ or nullif(btrim(coalesce(p_details->'change'->>'after', '')), '') is null+ or nullif(btrim(coalesce(p_details->>'doneWhen', '')), '') is null+ or coalesce(p_details->>'check', '') not in ('auto', 'rerun', 'manual')+ then+ raise exception 'incomplete task' using errcode = '22023';+ end if;++ insert into public.action_tasks (action_id, position, title, status, mode, permission, details)+ select+ v_review.action_id,+ coalesce(max(t.position), 0) + 1,+ v_title,+ 'todo',+ 'human',+ 'read',+ -- The reviewer's task now: Regenerate keeps it (task-writer keepsTask).+ p_details || jsonb_build_object('source', 'reviewed')+ from public.action_tasks t+ where t.action_id = v_review.action_id+ returning id into v_task_id;++ delete from public.action_task_reviews where id = v_review.id;++ insert into public.action_events (action_id, event, data, actor_id)+ values (v_review.action_id, 'task_added', jsonb_build_object('title', v_title), auth.uid());++ update public.actions set updated_at = now() where id = v_review.action_id;++ return v_task_id;+end;+$$;++revoke all on function public.approve_action_task_review(uuid, text, jsonb) from public, anon;+grant execute on function public.approve_action_task_review(uuid, text, jsonb) to authenticated;++comment on function public.approve_action_task_review(uuid, text, jsonb) is+ 'Action Center (AC-010): a task waiting for review (action_task_reviews) onto its action''s task list, after its last task, with the exact page, the change, Done when and how it is checked filled, as the reviewer''s (source reviewed); the review row goes and the trail says a task was added. Admins and managers of the brand''s organization only, on an action neither deleted nor closed. Null when the row is gone or another organization''s.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 8ac90b4ae..5fd1b51f4 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -41431,3 +41431,170 @@ $$;comment on function public.content_plan_pages(uuid, integer) is'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7, 30 or 90) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and, with conversions on (00291), the conversions from AI journeys that landed on, went through or converted on each page, of the latest 2,000 (null with conversions off); with the earlier window''s first day and the brand''s first tracked day. Security definer with an organization check.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00293_action_task_reviews.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00293: tasks waiting for review (AC-010)+-- ============================================================================+-- Every task an agent writes says the exact page, the change, when it is+-- done and how that is checked (AC-010; the fields live in+-- action_tasks.details). A task the AI task writer gives without one of+-- them doesn't reach the people doing the work: it waits here, for an+-- admin or a manager of the brand's organization to fill what it misses.+--+-- * action_task_reviews: one row per task waiting, with the task as it was+-- written (title and details) and the fields it misses ('url', 'change',+-- 'doneWhen', 'check'). Not a task yet, so nothing that reads+-- action_tasks (the lists, counts, exports, the runner) sees it.+-- * approve_action_task_review: the reviewed task, its four fields filled,+-- goes onto the action's task list, after its last task, and the review+-- row goes, in one transaction. The trail says a task was added. It is+-- the reviewer's task now (source 'reviewed'): Regenerate tasks keeps+-- it, as it keeps a task someone added. Not on an action that is+-- deleted or closed.+-- * Admins and managers read and dismiss (delete) the rows; the server+-- writes them (service role). Edits go into the task on approval.++create table if not exists public.action_task_reviews (+ id uuid primary key default gen_random_uuid(),+ action_id uuid not null references public.actions(id) on delete cascade,+ title text not null check (char_length(title) between 1 and 200),+ details jsonb not null default '{}'::jsonb,+ missing text[] not null default '{}'+ check (missing <@ array['url', 'change', 'doneWhen', 'check']::text[]),+ source text not null default 'ai' check (source in ('ai', 'agent')),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists action_task_reviews_action_idx+ on public.action_task_reviews (action_id);++-- Read and dismissed by admins and managers (the policies below); written by the server.+alter table public.action_task_reviews enable row level security;+revoke all on table public.action_task_reviews from anon, authenticated;+grant select, delete on table public.action_task_reviews to authenticated;+grant all on table public.action_task_reviews to service_role;++drop policy if exists "action_task_reviews: manager select" on public.action_task_reviews;+create policy "action_task_reviews: manager select"+ on public.action_task_reviews+ for select+ using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++drop policy if exists "action_task_reviews: manager delete" on public.action_task_reviews;+create policy "action_task_reviews: manager delete"+ on public.action_task_reviews+ for delete+ using (+ action_id in (+ select a.id from public.actions a+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ );++comment on table public.action_task_reviews is+ 'Action Center (AC-010): tasks an agent wrote without the exact page, the change, Done when or how it is checked (missing), waiting for an admin or a manager. Not tasks yet: approve_action_task_review puts one on its action''s list. The server writes them.';++-- The reviewed task onto its action's list, its four fields filled, and the+-- review row gone. Null when the row isn't there (approved or dismissed+-- meanwhile, or another organization's); an error when the caller isn't an+-- admin or a manager, the action is deleted or closed, or a field is still+-- missing.+create or replace function public.approve_action_task_review(+ p_review_id uuid,+ p_title text,+ p_details jsonb+)+returns uuid+language plpgsql+security definer+set search_path = public+as $$+declare+ v_review public.action_task_reviews%rowtype;+ v_title text := btrim(coalesce(p_title, ''));+ v_task_id uuid;+begin+ -- The caller's role first, before any row is read or locked.+ if not exists (+ select 1 from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ ) then+ raise exception 'not allowed' using errcode = '42501';+ end if;++ -- Only a row of the caller's own organization: another's reads as not there.+ select r.* into v_review+ from public.action_task_reviews r+ join public.actions a on a.id = r.action_id+ join public.brands b on b.id = a.brand_id+ join public.profiles p on p.organization_id = b.organization_id+ where r.id = p_review_id+ and p.id = auth.uid()+ for update of r;+ if not found then+ return null;+ end if;++ if exists (+ select 1 from public.actions a+ where a.id = v_review.action_id+ and (a.deleted_at is not null or a.status in ('completed', 'dismissed'))+ ) then+ raise exception 'action closed' using errcode = '55000';+ end if;++ if char_length(v_title) not between 1 and 200+ or jsonb_typeof(p_details) is distinct from 'object'+ or nullif(btrim(coalesce(p_details->>'url', '')), '') is null+ or nullif(btrim(coalesce(p_details->'change'->>'after', '')), '') is null+ or nullif(btrim(coalesce(p_details->>'doneWhen', '')), '') is null+ or coalesce(p_details->>'check', '') not in ('auto', 'rerun', 'manual')+ then+ raise exception 'incomplete task' using errcode = '22023';+ end if;++ insert into public.action_tasks (action_id, position, title, status, mode, permission, details)+ select+ v_review.action_id,+ coalesce(max(t.position), 0) + 1,+ v_title,+ 'todo',+ 'human',+ 'read',+ -- The reviewer's task now: Regenerate keeps it (task-writer keepsTask).+ p_details || jsonb_build_object('source', 'reviewed')+ from public.action_tasks t+ where t.action_id = v_review.action_id+ returning id into v_task_id;++ delete from public.action_task_reviews where id = v_review.id;++ insert into public.action_events (action_id, event, data, actor_id)+ values (v_review.action_id, 'task_added', jsonb_build_object('title', v_title), auth.uid());++ update public.actions set updated_at = now() where id = v_review.action_id;++ return v_task_id;+end;+$$;++revoke all on function public.approve_action_task_review(uuid, text, jsonb) from public, anon;+grant execute on function public.approve_action_task_review(uuid, text, jsonb) to authenticated;++comment on function public.approve_action_task_review(uuid, text, jsonb) is+ 'Action Center (AC-010): a task waiting for review (action_task_reviews) onto its action''s task list, after its last task, with the exact page, the change, Done when and how it is checked filled, as the reviewer''s (source reviewed); the review row goes and the trail says a task was added. Admins and managers of the brand''s organization only, on an action neither deleted nor closed. Null when the row is gone or another organization''s.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex c9e789bbb..3a0cc4716 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -134,6 +134,7 @@"actionCenter": {"tabs": {"label": "Action Center sections",+ "review": "Needs review","kpis": "KPIs","actions": "Actions","signals": "Signals",@@ -1277,7 +1278,7 @@"task_renamed": "Task renamed to “{title}”","task_deleted": "Task deleted","task_edited": "Task edited",- "tasks_generated": "{count, plural, one {# task} other {# tasks}} written from the action's evidence",+ "tasks_generated": "{count, plural, one {# task} other {# tasks}} written from the action's evidence{reviews, plural, =0 {} one {; # waits for review} other {; # wait for review}}","task_sent": "{to, select, content {Sent to Content} webhook {Sent to the webhook} other {Sent}}: {title}","task_ran": "{task} — carried out automatically ({tool})","task_run_failed": "{task} — the automatic attempt failed; it needs doing by hand",@@ -1317,6 +1318,8 @@"cancel": "Cancel","busy": "Writing tasks…","done": "{count, plural, one {# task written} other {# tasks written}}",+ "doneWithReviews": "{count, plural, one {# task written} other {# tasks written}}; {reviews, plural, one {# waits} other {# wait}} in Needs review for the page, the change or the check",+ "doneWithReviewsMember": "{count, plural, one {# task written} other {# tasks written}}; {reviews, plural, one {# waits} other {# wait}} for an admin or a manager to review","timeout": "Writing the tasks took too long. Please try again.","unreachable": "Couldn't reach the server. Please try again.","unauthenticated": "Your session has ended. Please sign in again.",@@ -2377,6 +2380,34 @@"competitors": "{count, plural, one {# competitor} other {# competitors}}"}},+ "reviewPage": {+ "title": "Needs review",+ "subtitle": "Tasks an agent wrote without the exact page, the change, Done when or how we check it. Fill what's missing and approve them onto their action, or dismiss them.",+ "noBrand": "Pick a brand to see its tasks waiting for review.",+ "managersOnly": "Only admins and managers review tasks.",+ "empty": "Nothing waits for review. Tasks an agent writes without the page, the change, Done when or how we check it show up here.",+ "loadFailed": "Couldn't load the tasks waiting for review.",+ "missing": "Missing",+ "fields": {+ "url": "URL",+ "change": "Change",+ "doneWhen": "Done when",+ "check": "How we check"+ },+ "openAction": "Open {ref}",+ "approve": "Approve",+ "dismiss": "Dismiss",+ "confirmDismiss": "Dismiss this task? It won't reach the action.",+ "confirmDismissButton": "Dismiss",+ "cancel": "Cancel",+ "approved": "Task added to {ref}",+ "dismissed": "Task dismissed",+ "incomplete": "Fill the URL, the change, Done when and How we check first.",+ "closed": "This task's action is closed or deleted, so it can't take the task.",+ "gone": "This task was already approved or dismissed.",+ "notAllowed": "Only admins and managers review tasks.",+ "failed": "Couldn't save. Try again."+ },"taskChecks": {"auto": "Automatic: we fetch the page again","rerun": "Re-run: the prompts run again",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.test.tsxnew file mode 100644index 000000000..39e563438--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.test.tsx@@ -0,0 +1,213 @@+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 type { TaskReview } from '@/lib/actions/action-task-reviews';++/**+ * Needs review (AC-010): an admin or a manager fills what an agent's task+ * misses and approves it onto its action, or dismisses it.+ */++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: { getActiveBrand: () => { id: string } }) => unknown) =>+ selector({ getActiveBrand: () => ({ id: 'b1' }) }),+}));+let canManage = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canManage ? 'manager' : 'analyst', canManage, canAdmin: false }),+}));+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock('@/components/action-center/action-center-tabs', () => ({+ ActionCenterTabs: () => null,+}));+const { getTaskReviews, approveTaskReview, dismissTaskReview } = vi.hoisted(() => ({+ getTaskReviews: vi.fn(),+ approveTaskReview: vi.fn(),+ dismissTaskReview: vi.fn(),+}));+vi.mock('@/lib/actions/action-task-reviews', () => ({+ getTaskReviews,+ approveTaskReview,+ dismissTaskReview,+}));+const { toast } = vi.hoisted(() => ({+ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+vi.mock('sonner', () => ({ toast }));++import ActionCenterReviewPage from './page';++const review: TaskReview = {+ id: 'r1',+ actionId: 'a1',+ actionNo: 12,+ title: 'Add a pricing FAQ to /pricing',+ details: parseTaskDetails({ where: '/pricing', doneWhen: 'FAQ present', check: 'rerun' }),+ missing: ['url', 'change'],+ createdAt: '2026-10-26T10:00:00Z',+};++let container: HTMLDivElement;+let root: Root;++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ActionCenterReviewPage />+ </NextIntlClientProvider>,+ );+ });+}++const button = (name: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === name);+const field = (label: string) => {+ const target = [...container.querySelectorAll('label')].find((l) =>+ l.textContent?.startsWith(label),+ );+ return container.querySelector<HTMLInputElement | HTMLTextAreaElement>(+ `[id="${target?.getAttribute('for')}"]`,+ )!;+};+function type(input: HTMLInputElement | HTMLTextAreaElement, value: string) {+ const proto = Object.getPrototypeOf(input) as HTMLInputElement;+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(input, value);+ act(() => {+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ getTaskReviews.mockResolvedValue([review]);+ approveTaskReview.mockResolvedValue({ taskId: 't9' });+ dismissTaskReview.mockResolvedValue(undefined);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.clearAllMocks();+ canManage = true;+});++describe('Needs review', () => {+ it('lists a task with what it misses and its action', async () => {+ await render();+ expect(getTaskReviews).toHaveBeenCalledWith('b1');+ expect(container.textContent).toContain('Add a pricing FAQ to /pricing');+ expect(container.textContent).toContain('Missing:URLChange');+ expect(container.querySelector('a')!.getAttribute('href')).toBe(+ '/dashboard/action-center/actions?action=a1',+ );+ expect(container.querySelector('a')!.textContent).toBe('Open AC-12');+ });++ it('approves only with the four fields filled, then the task leaves the list', async () => {+ await render();+ act(() => button('Edit')!.click());+ expect(button('Approve')!.disabled).toBe(true);+ type(field('URL'), '/pricing');+ expect(button('Approve')!.disabled).toBe(true);+ type(field('Change · After'), 'FAQ: Do plans ship free?');+ expect(button('Approve')!.disabled).toBe(false);+ await act(async () => button('Approve')!.click());+ expect(approveTaskReview).toHaveBeenCalledWith(+ 'b1',+ 'r1',+ expect.objectContaining({+ // Its text unchanged: the review's own.+ title: 'Add a pricing FAQ to /pricing',+ url: '/pricing',+ after: 'FAQ: Do plans ship free?',+ doneWhen: 'FAQ present',+ check: 'rerun',+ }),+ );+ expect(toast.success).toHaveBeenCalledWith('Task added to AC-12');+ expect(container.textContent).toContain('Nothing waits for review');+ });++ it('tells the tab to count again once a task leaves the list', async () => {+ const changed = vi.fn();+ window.addEventListener('action-task-reviews-changed', changed);+ try {+ await render();+ act(() => button('Edit')!.click());+ type(field('URL'), '/pricing');+ type(field('Change · After'), 'FAQ');+ await act(async () => button('Approve')!.click());+ expect(changed).toHaveBeenCalledTimes(1);+ } finally {+ window.removeEventListener('action-task-reviews-changed', changed);+ }+ });++ it("says when the task's action is closed", async () => {+ approveTaskReview.mockResolvedValue({ error: 'closed' });+ await render();+ act(() => button('Edit')!.click());+ type(field('URL'), '/pricing');+ type(field('Change · After'), 'FAQ');+ await act(async () => button('Approve')!.click());+ expect(toast.error).toHaveBeenCalledWith(+ "This task's action is closed or deleted, so it can't take the task.",+ );+ });++ it('says what is still missing when the database refuses it', async () => {+ approveTaskReview.mockResolvedValue({ error: 'incomplete' });+ await render();+ act(() => button('Edit')!.click());+ type(field('URL'), '/pricing');+ type(field('Change · After'), 'FAQ');+ await act(async () => button('Approve')!.click());+ expect(toast.error).toHaveBeenCalledWith(+ 'Fill the URL, the change, Done when and How we check first.',+ );+ expect(container.textContent).toContain('Add a pricing FAQ to /pricing');+ });++ it('dismisses after asking', async () => {+ await render();+ act(() => button('Dismiss')!.click());+ expect(container.textContent).toContain("Dismiss this task? It won't reach the action.");+ expect(dismissTaskReview).not.toHaveBeenCalled();+ await act(async () =>+ [...container.querySelectorAll('button')]+ .filter((b) => b.textContent === 'Dismiss')+ .at(-1)!+ .click(),+ );+ expect(dismissTaskReview).toHaveBeenCalledWith('b1', 'r1');+ expect(container.textContent).toContain('Nothing waits for review');+ });++ it('reads nothing for someone who is not an admin or a manager', async () => {+ canManage = false;+ await render();+ expect(getTaskReviews).not.toHaveBeenCalled();+ expect(container.textContent).toContain('Only admins and managers review tasks.');+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.tsxnew file mode 100644index 000000000..f994701be--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/review/page.tsx@@ -0,0 +1,238 @@+'use client';++import { useCallback, useEffect, useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { ArrowUpRight } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { useUserRole } from '@/hooks/use-user-role';+import { useBrandStore } from '@/stores/use-brand-store';+import {+ approveTaskReview,+ dismissTaskReview,+ getTaskReviews,+ type TaskReview,+} from '@/lib/actions/action-task-reviews';+import type { TaskDetailsEdit } from '@/lib/action-center/task-details';+import { TASK_REVIEWS_CHANGED } from '@/lib/action-center/tabs';+import { ActionCenterTabs } from '@/components/action-center/action-center-tabs';+import { TaskDetailForm, TaskDetailView } from '@/components/action-center/task-detail';+import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';++/**+ * Needs review (AC-010): tasks an agent wrote without the exact page, the+ * change, Done when or how we check it. An admin or a manager fills what+ * each misses and approves it onto its action's list, or dismisses it.+ */+export default function ActionCenterReviewPage() {+ const brand = useBrandStore((s) => s.getActiveBrand());+ const t = useTranslations('actionCenter.reviewPage');++ return (+ <div className="space-y-6">+ <HeaderWithAiUsage>+ <div>+ <h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>+ <p className="mt-1 text-sm text-muted-foreground">{t('subtitle')}</p>+ </div>+ </HeaderWithAiUsage>+ <ActionCenterTabs />+ {brand ? (+ <ReviewContent key={brand.id} brandId={brand.id} />+ ) : (+ <p className="py-20 text-center text-sm text-muted-foreground">{t('noBrand')}</p>+ )}+ </div>+ );+}++function ReviewContent({ brandId }: { brandId: string }) {+ const t = useTranslations('actionCenter.reviewPage');+ const { canManage } = useUserRole();+ const [reviews, setReviews] = useState<TaskReview[] | null>(null);+ const [editing, setEditing] = useState<string | null>(null);+ const [dismissing, setDismissing] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);++ const load = useCallback(async () => {+ try {+ setReviews(await getTaskReviews(brandId));+ } catch (err) {+ console.error('Failed to load the tasks waiting for review:', err);+ setReviews([]);+ toast.error(t('loadFailed'));+ }+ }, [brandId, t]);++ useEffect(() => {+ if (canManage) void load();+ }, [canManage, load]);++ if (!canManage) {+ return <p className="py-20 text-center text-sm text-muted-foreground">{t('managersOnly')}</p>;+ }+ if (reviews === null) {+ return (+ <div className="space-y-3">+ {[0, 1].map((i) => (+ <Skeleton key={i} className="h-28 w-full" />+ ))}+ </div>+ );+ }+ if (reviews.length === 0) {+ return <p className="py-20 text-center text-sm text-muted-foreground">{t('empty')}</p>;+ }++ const ref = (review: TaskReview) => (review.actionNo !== null ? `AC-${review.actionNo}` : '');+ const gone = (id: string) => {+ setReviews((list) => (list ?? []).filter((r) => r.id !== id));+ // The tab's count, on this same page.+ window.dispatchEvent(new Event(TASK_REVIEWS_CHANGED));+ };++ const approve = async (review: TaskReview, edit: TaskDetailsEdit & { title: string | null }) => {+ setBusy(review.id);+ try {+ const result = await approveTaskReview(brandId, review.id, {+ ...edit,+ title: edit.title ?? review.title,+ });+ if ('taskId' in result) {+ toast.success(t('approved', { ref: ref(review) }));+ setEditing(null);+ gone(review.id);+ } else if (result.error === 'gone') {+ toast(t('gone'));+ gone(review.id);+ } else {+ toast.error(+ t(+ result.error === 'incomplete'+ ? 'incomplete'+ : result.error === 'not_allowed'+ ? 'notAllowed'+ : result.error === 'closed'+ ? 'closed'+ : 'failed',+ ),+ );+ }+ } catch (err) {+ console.error('Failed to approve the task:', err);+ toast.error(t('failed'));+ } finally {+ setBusy(null);+ }+ };++ const dismiss = async (review: TaskReview) => {+ setBusy(review.id);+ try {+ await dismissTaskReview(brandId, review.id);+ toast(t('dismissed'));+ setDismissing(null);+ gone(review.id);+ } catch (err) {+ console.error('Failed to dismiss the task:', err);+ toast.error(t('failed'));+ } finally {+ setBusy(null);+ }+ };++ return (+ <ul className="space-y-3">+ {reviews.map((review) => (+ <li key={review.id} className="rounded-lg border bg-card">+ <div className="flex flex-wrap items-start justify-between gap-2 px-4 pt-3">+ <div className="min-w-0 space-y-1">+ <p className="text-sm font-medium break-words">{review.title}</p>+ <div className="flex flex-wrap items-center gap-1 text-xs text-muted-foreground">+ {t('missing')}:+ {review.missing.map((field) => (+ <Badge+ key={field}+ variant="outline"+ className="border-amber-500/40 text-[10px] text-amber-700 dark:text-amber-400"+ >+ {t(`fields.${field}`)}+ </Badge>+ ))}+ </div>+ </div>+ {review.actionNo !== null && (+ <Link+ href={`/dashboard/action-center/actions?action=${review.actionId}`}+ className="inline-flex shrink-0 items-center gap-0.5 text-xs font-medium underline-offset-2 hover:underline"+ >+ {t('openAction', { ref: ref(review) })}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ )}+ </div>+ {editing === review.id ? (+ <TaskDetailForm+ text={review.title}+ details={review.details}+ disabled={busy === review.id}+ requireSpec+ submitLabel={t('approve')}+ onSave={(edit) => approve(review, edit)}+ onCancel={() => setEditing(null)}+ />+ ) : (+ <TaskDetailView+ details={review.details}+ disabled={busy !== null}+ onEdit={() => setEditing(review.id)}+ />+ )}+ {editing !== review.id && (+ <div className="flex flex-wrap items-center gap-2 border-t px-4 py-2 text-xs">+ {dismissing === review.id ? (+ <>+ <span className="text-muted-foreground">{t('confirmDismiss')}</span>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={busy === review.id}+ onClick={() => void dismiss(review)}+ className="h-7 text-xs"+ >+ {t('confirmDismissButton')}+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={busy === review.id}+ onClick={() => setDismissing(null)}+ className="h-7 text-xs"+ >+ {t('cancel')}+ </Button>+ </>+ ) : (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={busy !== null}+ onClick={() => setDismissing(review.id)}+ className="h-7 text-xs text-muted-foreground"+ >+ {t('dismiss')}+ </Button>+ )}+ </div>+ )}+ </li>+ ))}+ </ul>+ );+}diff --git a/web/src/components/action-center/action-center-tabs.test.tsx b/web/src/components/action-center/action-center-tabs.test.tsxnew file mode 100644index 000000000..616ad6300--- /dev/null+++ b/web/src/components/action-center/action-center-tabs.test.tsx@@ -0,0 +1,95 @@+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';++/** The Action Center's tabs: Needs review (AC-010) for admins and managers, with its count. */++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++vi.mock('@/i18n/navigation', () => ({+ usePathname: () => '/dashboard/action-center/actions',+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));+vi.mock('@/stores/use-brand-store', () => ({+ useBrandStore: (selector: (state: { activeBrandId: string }) => unknown) =>+ selector({ activeBrandId: 'b1' }),+}));+let canManage = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),+}));+vi.mock('@/lib/actions/signals', () => ({ getNewSignalCount: vi.fn(async () => 0) }));+const { getTaskReviewCount } = vi.hoisted(() => ({ getTaskReviewCount: vi.fn() }));+vi.mock('@/lib/actions/action-task-reviews', () => ({ getTaskReviewCount }));+vi.mock('./first-run-note', () => ({ FirstRunNote: () => null }));++import { ActionCenterTabs } from './action-center-tabs';++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ getTaskReviewCount.mockResolvedValue(3);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.clearAllMocks();+ canManage = true;+});++async function render() {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ActionCenterTabs />+ </NextIntlClientProvider>,+ );+ });+}++const tabs = () => [...container.querySelectorAll('nav a')].map((a) => a.textContent);++describe('ActionCenterTabs', () => {+ it('shows Needs review last, with how many wait, to an admin or a manager', async () => {+ await render();+ expect(getTaskReviewCount).toHaveBeenCalledWith('b1');+ expect(tabs()).toEqual(['Actions', 'Signals', 'KPIs', 'History', 'Needs review3']);+ });++ it('counts again when a review is approved or dismissed on its page', async () => {+ await render();+ getTaskReviewCount.mockResolvedValue(2);+ await act(async () => {+ window.dispatchEvent(new Event('action-task-reviews-changed'));+ });+ expect(tabs().at(-1)).toBe('Needs review2');+ });++ it('shows no count when nothing waits', async () => {+ getTaskReviewCount.mockResolvedValue(0);+ await render();+ expect(tabs().at(-1)).toBe('Needs review');+ });++ it('leaves it out for anyone else, and reads no count', async () => {+ canManage = false;+ await render();+ expect(tabs()).toEqual(['Actions', 'Signals', 'KPIs', 'History']);+ expect(getTaskReviewCount).not.toHaveBeenCalled();+ });+});diff --git a/web/src/components/action-center/action-center-tabs.tsx b/web/src/components/action-center/action-center-tabs.tsxindex bd3ac1b65..2a5a3666e 100644--- a/web/src/components/action-center/action-center-tabs.tsx+++ b/web/src/components/action-center/action-center-tabs.tsx@@ -4,16 +4,19 @@ import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';import { Link, usePathname } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';+import { useUserRole } from '@/hooks/use-user-role';import { getNewSignalCount } from '@/lib/actions/signals';+import { getTaskReviewCount } from '@/lib/actions/action-task-reviews';import { cn } from '@/lib/utils';-import { ACTION_CENTER_TABS } from '@/lib/action-center/tabs';+import { ACTION_CENTER_TABS, REVIEW_TAB, TASK_REVIEWS_CHANGED } from '@/lib/action-center/tabs';import { FirstRunNote } from './first-run-note';/**- * The Action Center's section nav: Actions | Signals | KPIs | History.- * Route-backed rather than state-backed tabs so each section is linkable- * and the browser back button works across them. The first run's note sits- * under it while a new brand's first analysis goes on.+ * The Action Center's section nav: Actions | Signals | KPIs | History, and+ * Needs review for admins and managers (AC-010). Route-backed rather than+ * state-backed tabs so each section is linkable and the browser back button+ * works across them. The first run's note sits under it while a new brand's+ * first analysis goes on.*/export function ActionCenterTabs() {const pathname = usePathname();@@ -36,10 +39,35 @@ export function ActionCenterTabs() {};}, [brandId, pathname]);+ // Tasks waiting for review, on their own tab: admins and managers fill and approve them.+ const { canManage } = useUserRole();+ // Kept with its brand: another brand's count isn't shown while this one's loads.+ const [reviewCount, setReviewCount] = useState<{ brandId: string; count: number } | null>(null);+ const reviews = reviewCount && reviewCount.brandId === brandId ? reviewCount.count : 0;+ useEffect(() => {+ if (!brandId || !canManage) return;+ let cancelled = false;+ const load = () => {+ getTaskReviewCount(brandId)+ .then((count) => {+ if (!cancelled) setReviewCount({ brandId, count });+ })+ .catch(() => {});+ };+ load();+ // Approved or dismissed on the review page itself.+ window.addEventListener(TASK_REVIEWS_CHANGED, load);+ return () => {+ cancelled = true;+ window.removeEventListener(TASK_REVIEWS_CHANGED, load);+ };+ }, [brandId, canManage, pathname]);+ const tabs = canManage ? [...ACTION_CENTER_TABS, REVIEW_TAB] : ACTION_CENTER_TABS;+return (<><nav className="flex gap-6 border-b" aria-label={t('label')}>- {ACTION_CENTER_TABS.map((tab) => {+ {tabs.map((tab) => {const isActive = pathname.startsWith(tab.href);return (<Link@@ -59,6 +87,11 @@ export function ActionCenterTabs() {{newSignals}</span>)}+ {tab.key === 'review' && reviews > 0 && (+ <span className="ml-1.5 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-400">+ {reviews}+ </span>+ )}</Link>);})}diff --git a/web/src/components/action-center/regenerate-tasks.test.tsx b/web/src/components/action-center/regenerate-tasks.test.tsxindex d8057a49c..19bbb857d 100644--- a/web/src/components/action-center/regenerate-tasks.test.tsx+++ b/web/src/components/action-center/regenerate-tasks.test.tsx@@ -10,6 +10,10 @@ const { toast, regenerate } = vi.hoisted(() => ({}));vi.mock('sonner', () => ({ toast }));vi.mock('@/lib/actions/action-task-writer', () => ({ regenerateActionTasks: regenerate }));+let canManage = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),+}));const { RegenerateTasks } = await import('./regenerate-tasks');@@ -36,6 +40,7 @@ const button = (name: string) =>[...container.querySelectorAll('button')].find((b) => b.textContent === name)!;beforeEach(() => {+ canManage = true;container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -51,7 +56,7 @@ afterEach(() => {describe('RegenerateTasks', () => {it('asks first, saying what stays, then writes and reloads', async () => {- regenerate.mockResolvedValueOnce({ written: 4, kept: 1 });+ regenerate.mockResolvedValueOnce({ written: 4, kept: 1, reviews: 0 });const onDone = vi.fn();const onBusyChange = vi.fn();render(@@ -75,6 +80,31 @@ describe('RegenerateTasks', () => {expect(onBusyChange.mock.calls).toEqual([[true], [false]]);});+ it('says how many wait in Needs review (AC-010)', async () => {+ regenerate.mockResolvedValueOnce({ written: 1, kept: 0, reviews: 2 });+ render(+ <RegenerateTasks actionId="a1" disabled={false} onBusyChange={() => {}} onDone={() => {}} />,+ );+ act(() => button('Regenerate tasks').click());+ await act(async () => button('Regenerate').click());+ expect(toast.success).toHaveBeenCalledWith(+ '1 task written; 2 wait in Needs review for the page, the change or the check',+ );+ });++ it('tells someone without the Needs review tab who reviews', async () => {+ canManage = false;+ regenerate.mockResolvedValueOnce({ written: 0, kept: 0, reviews: 1 });+ render(+ <RegenerateTasks actionId="a1" disabled={false} onBusyChange={() => {}} onDone={() => {}} />,+ );+ act(() => button('Regenerate tasks').click());+ await act(async () => button('Regenerate').click());+ expect(toast.success).toHaveBeenCalledWith(+ '0 tasks written; 1 waits for an admin or a manager to review',+ );+ });+it("words the server's reason, and a timeout", async () => {render(<RegenerateTasks actionId="a1" disabled={false} onBusyChange={() => {}} onDone={() => {}} />,diff --git a/web/src/components/action-center/regenerate-tasks.tsx b/web/src/components/action-center/regenerate-tasks.tsxindex d69a12afb..d33314865 100644--- a/web/src/components/action-center/regenerate-tasks.tsx+++ b/web/src/components/action-center/regenerate-tasks.tsx@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { Loader2, RefreshCw } from 'lucide-react';import { Button } from '@/components/ui/button';+import { useUserRole } from '@/hooks/use-user-role';import { regenerateActionTasks } from '@/lib/actions/action-task-writer';/** Whether this deployment writes tasks (AC-004); the server has its own switch. */@@ -43,6 +44,8 @@ export function RegenerateTasks({onDone: () => void | Promise<void>;}) {const t = useTranslations('actionCenter.actionsPage.drawer.regenerate');+ // Needs review is an admin's or a manager's tab: anyone else is told who reviews.+ const { canManage } = useUserRole();const [confirming, setConfirming] = useState(false);const [busy, setBusy] = useState(false);@@ -52,7 +55,14 @@ export function RegenerateTasks({try {const result = await regenerateActionTasks(actionId);if ('written' in result) {- toast.success(t('done', { count: result.written }));+ toast.success(+ result.reviews > 0+ ? t(canManage ? 'doneWithReviews' : 'doneWithReviewsMember', {+ count: result.written,+ reviews: result.reviews,+ })+ : t('done', { count: result.written }),+ );await onDone();} else {toast.error(diff --git a/web/src/components/action-center/task-detail.tsx b/web/src/components/action-center/task-detail.tsxindex 6c0a2e876..af6cbe4e1 100644--- a/web/src/components/action-center/task-detail.tsx+++ b/web/src/components/action-center/task-detail.tsx@@ -314,6 +314,8 @@ export function TaskDetailForm({disabled,onSave,onCancel,+ submitLabel,+ requireSpec = false,}: {/** The task's text as the drawer shows it. */text: string;@@ -321,6 +323,10 @@ export function TaskDetailForm({disabled: boolean;onSave: (edit: TaskDetailsEdit & { title: string | null }) => void | Promise<void>;onCancel: () => void;+ /** The submit button's label; Save by default. */+ submitLabel?: string;+ /** Submit only with the URL, the change, Done when and How we check filled (AC-010's review). */+ requireSpec?: boolean;}) {const t = useTranslations('actionCenter.actionsPage.drawer.task');const tTypes = useTranslations('actionCenter.taskTypes');@@ -343,13 +349,16 @@ export function TaskDetailForm({const set = (field: keyof typeof draft) => (value: string) =>setDraft((current) => ({ ...current, [field]: value }));const title = draft.title.trim();+ const specFilled =+ !!draft.url.trim() && !!draft.after.trim() && !!draft.doneWhen.trim() && !!draft.check;+ const canSubmit = !!title && (!requireSpec || specFilled);return (<formclassName="space-y-2.5 border-t px-4 py-3"onSubmit={(e) => {e.preventDefault();- if (!title) return;+ if (!canSubmit) return;void onSave({title: title === text ? null : title,url: draft.url,@@ -386,6 +395,7 @@ export function TaskDetailForm({<FormField id={`${id}-url`} label={t('url')}><Inputid={`${id}-url`}+ aria-required={requireSpec || undefined}value={draft.url}maxLength={TASK_DETAIL_LIMITS.url}placeholder={t('urlPlaceholder')}@@ -433,6 +443,7 @@ export function TaskDetailForm({<FormField id={`${id}-after`} label={`${t('change')} · ${t('changeAfter')}`}><Textareaid={`${id}-after`}+ aria-required={requireSpec || undefined}value={draft.after}rows={2}maxLength={TASK_DETAIL_LIMITS.change}@@ -459,6 +470,7 @@ export function TaskDetailForm({<FormField id={`${id}-done`} label={t('doneWhen')}><Inputid={`${id}-done`}+ aria-required={requireSpec || undefined}value={draft.doneWhen}maxLength={TASK_DETAIL_LIMITS.doneWhen}disabled={disabled}@@ -478,7 +490,11 @@ export function TaskDetailForm({...TASK_CHECKS.map((check) => ({ value: check, label: tChecks(check) })),]}>- <SelectTrigger id={`${id}-check`} className="h-8 w-full text-xs">+ <SelectTrigger+ id={`${id}-check`}+ aria-required={requireSpec || undefined}+ className="h-8 w-full text-xs"+ ><SelectValue /></SelectTrigger><SelectContent>@@ -541,8 +557,8 @@ export function TaskDetailForm({</FormField></div><div className="flex gap-2">- <Button type="submit" size="sm" disabled={disabled || !title} className="h-7 text-xs">- {t('save')}+ <Button type="submit" size="sm" disabled={disabled || !canSubmit} className="h-7 text-xs">+ {submitLabel ?? t('save')}</Button><Buttontype="button"diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex d4b609399..76fbbd05c 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -422,6 +422,7 @@ describe('History events', () => {measurable: 2,title: 'Ask the agency',outcome: 'improved',+ reviews: 0,};const eventText = (event: string, data: Partial<typeof values> = {}) =>tPage(`drawer.events.${event}` as Parameters<typeof tPage>[0], { ...values, ...data });@@ -452,6 +453,16 @@ describe('History events', () => {expect(() => eventText(event)).not.toThrow();});+ /** Tasks the writer left for review are said after the ones it wrote (AC-010). */+ it('says how many tasks wait for review, when any do', () => {+ expect(eventText('tasks_generated', { count: 3 })).toBe(+ "3 tasks written from the action's evidence",+ );+ expect(eventText('tasks_generated', { count: 0, reviews: 2 })).toBe(+ "0 tasks written from the action's evidence; 2 wait for review",+ );+ });+/** The validation sweep records one of four verdicts, and each reads in* words — "after this action closed", never "because of it". */it.each([diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex f02904638..6ae25bd4f 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -204,6 +204,8 @@ export function actionEventText(return t(`drawer.events.${event.event}`, {to: String(event.data.to ?? ''),count: Number(event.data.count ?? 0),+ // Tasks the writer left for review (AC-010).+ reviews: Number(event.data.reviews ?? 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.diff --git a/web/src/lib/action-center/tabs.ts b/web/src/lib/action-center/tabs.tsindex c62ae16c1..4e6d03ab4 100644--- a/web/src/lib/action-center/tabs.ts+++ b/web/src/lib/action-center/tabs.ts@@ -8,3 +8,13 @@ export const ACTION_CENTER_TABS = [{ key: 'kpis', href: '/dashboard/action-center/kpis' },{ key: 'history', href: '/dashboard/action-center/history' },] as const;++/**+ * Needs review (AC-010): tasks an agent wrote without the exact page, the+ * change, Done when or how it is checked. After the others, for admins and+ * managers only.+ */+export const REVIEW_TAB = { key: 'review', href: '/dashboard/action-center/review' } as const;++/** The review page tells the tab when a task is approved or dismissed, so its count reads again. */+export const TASK_REVIEWS_CHANGED = 'action-task-reviews-changed';diff --git a/web/src/lib/actions/action-task-reviews.test.ts b/web/src/lib/actions/action-task-reviews.test.tsnew file mode 100644index 000000000..f8af7b754--- /dev/null+++ b/web/src/lib/actions/action-task-reviews.test.ts@@ -0,0 +1,159 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Tasks waiting for review (AC-010, 00293): read for the brand, approved+ * onto their action through the RPC with what the writer stored kept, and+ * dismissed.+ */++let rows: Record<string, unknown>[];+let filters: [string, string, unknown][];+let rpcCalls: [string, Record<string, unknown>][];+let rpcResult: { data: unknown; error: { code: string; message: string } | null };+let deletes: [string, unknown][];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) => {+ let deleting = false;+ const chain: Record<string, unknown> = {};+ chain.select = () => chain;+ chain.order = () => chain;+ chain.eq = (column: string, value: unknown) => {+ if (deleting) deletes.push([column, value]);+ else filters.push([table, column, value]);+ return chain;+ };+ chain.is = (column: string, value: unknown) => (filters.push([table, column, value]), chain);+ chain.not = (column: string, op: string, value: unknown) => (+ filters.push([table, `${column} not ${op}`, value]),+ chain+ );+ chain.delete = () => ((deleting = true), chain);+ chain.maybeSingle = async () => ({ data: rows[0] ?? null, error: null });+ chain.then = (resolve: (value: unknown) => unknown) =>+ resolve({ data: rows, error: null, count: rows.length });+ return chain;+ },+ rpc: async (name: string, args: Record<string, unknown>) => {+ rpcCalls.push([name, args]);+ return rpcResult;+ },+ })),+}));++const { approveTaskReview, dismissTaskReview, getTaskReviews } =+ await import('./action-task-reviews');++const edit = {+ title: ' Add a pricing FAQ to /pricing ',+ url: ' /pricing ',+ where: '/pricing',+ why: '',+ before: '',+ after: 'FAQ: Do plans ship free?',+ how: ['Add the FAQ.'],+ doneWhen: 'FAQ present · page re-fetched',+ check: 'auto' as const,+ type: 'content' as const,+ effort: '',+ role: '',+};++beforeEach(() => {+ rows = [];+ filters = [];+ rpcCalls = [];+ rpcResult = { data: 'task-1', error: null };+ deletes = [];+});++describe('getTaskReviews', () => {+ it("reads the brand's tasks waiting for review, with their action and what they miss", async () => {+ rows = [+ {+ id: 'r1',+ action_id: 'a1',+ title: 'Add a pricing FAQ to /pricing',+ details: { where: '/pricing', doneWhen: 'FAQ present', source: 'ai' },+ missing: ['url', 'change', 'nonsense'],+ created_at: '2026-10-26T10:00:00Z',+ actions: { action_no: 12, brand_id: 'b1' },+ },+ ];+ expect(await getTaskReviews('b1')).toEqual([+ {+ id: 'r1',+ actionId: 'a1',+ actionNo: 12,+ title: 'Add a pricing FAQ to /pricing',+ details: expect.objectContaining({ where: '/pricing', doneWhen: 'FAQ present' }),+ missing: ['url', 'change'],+ createdAt: '2026-10-26T10:00:00Z',+ },+ ]);+ expect(filters).toContainEqual(['action_task_reviews', 'actions.brand_id', 'b1']);+ // None of an action that is deleted or closed: it can't take them.+ expect(filters).toContainEqual(['action_task_reviews', 'actions.deleted_at', null]);+ expect(filters).toContainEqual([+ 'action_task_reviews',+ 'actions.status not in',+ '(completed,dismissed)',+ ]);+ });+});++describe('approveTaskReview', () => {+ it('puts the task on its action as edited, keeping what the writer stored', async () => {+ rows = [{ details: { source: 'ai', refs: ['page:1'], url: null } }];+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ taskId: 'task-1' });+ expect(rpcCalls).toEqual([+ [+ 'approve_action_task_review',+ {+ p_review_id: 'r1',+ p_title: 'Add a pricing FAQ to /pricing',+ p_details: expect.objectContaining({+ source: 'ai',+ refs: ['page:1'],+ url: '/pricing',+ change: { before: null, after: 'FAQ: Do plans ship free?' },+ doneWhen: 'FAQ present · page re-fetched',+ check: 'auto',+ }),+ },+ ],+ ]);+ // Only a row of this brand's actions.+ expect(filters).toContainEqual(['action_task_reviews', 'actions.brand_id', 'b1']);+ });++ it('says why it was not approved', async () => {+ expect(await approveTaskReview('b1', 'r1', { ...edit, how: 'x' as never })).toEqual({+ error: 'invalid',+ });+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ error: 'gone' });+ rows = [{ details: {} }];+ rpcResult = { data: null, error: { code: '22023', message: 'incomplete task' } };+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ error: 'incomplete' });+ rpcResult = { data: null, error: { code: '42501', message: 'not allowed' } };+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ error: 'not_allowed' });+ rpcResult = { data: null, error: { code: '55000', message: 'action closed' } };+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ error: 'closed' });+ // Approved or dismissed meanwhile: the RPC finds no row.+ rpcResult = { data: null, error: null };+ expect(await approveTaskReview('b1', 'r1', edit)).toEqual({ error: 'gone' });+ });+});++describe('dismissTaskReview', () => {+ it("deletes a row of the brand's, and nothing when it's gone", async () => {+ rows = [{ id: 'r1' }];+ await dismissTaskReview('b1', 'r1');+ expect(deletes).toEqual([['id', 'r1']]);+ rows = [];+ deletes = [];+ await dismissTaskReview('b1', 'r1');+ expect(deletes).toEqual([]);+ });+});diff --git a/web/src/lib/actions/action-task-reviews.ts b/web/src/lib/actions/action-task-reviews.tsnew file mode 100644index 000000000..0dafda9f3--- /dev/null+++ b/web/src/lib/actions/action-task-reviews.ts@@ -0,0 +1,137 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import {+ cleanTaskDetailsEdit,+ isTaskDetailsEdit,+ parseTaskDetails,+ type ActionTaskDetails,+ type TaskDetailsEdit,+} from '@/lib/action-center/task-details';++/**+ * Tasks waiting for review (AC-010, 00293): ones an agent wrote without the+ * exact page, the change, Done when or how it is checked. They aren't tasks+ * yet; an admin or a manager fills what they miss and approves them onto+ * their action's list, or dismisses them. Read through the caller's RLS, so+ * anyone else reads none.+ */++export type TaskReviewField = 'url' | 'change' | 'doneWhen' | 'check';++export interface TaskReview {+ id: string;+ actionId: string;+ actionNo: number | null;+ title: string;+ details: ActionTaskDetails | null;+ /** What it was written without. */+ missing: TaskReviewField[];+ createdAt: string;+}++const FIELDS: readonly TaskReviewField[] = ['url', 'change', 'doneWhen', 'check'];++/**+ * The brand's tasks waiting for review, the oldest first; none of an action+ * that is deleted or closed, which can't take them.+ */+export async function getTaskReviews(brandId: string): Promise<TaskReview[]> {+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('action_task_reviews')+ .select(+ 'id, action_id, title, details, missing, created_at, actions!inner(action_no, brand_id, status, deleted_at)',+ )+ .eq('actions.brand_id', brandId)+ .is('actions.deleted_at', null)+ .not('actions.status', 'in', '(completed,dismissed)')+ .order('created_at', { ascending: true });+ if (error) throw new Error(error.message);+ return (data ?? []).map((row) => {+ const action = (Array.isArray(row.actions) ? row.actions[0] : row.actions) as {+ action_no: number | null;+ } | null;+ return {+ id: row.id,+ actionId: row.action_id,+ actionNo: action?.action_no ?? null,+ title: row.title,+ details: parseTaskDetails(row.details),+ missing: (row.missing ?? []).filter((field: string): field is TaskReviewField =>+ (FIELDS as readonly string[]).includes(field),+ ),+ createdAt: row.created_at,+ };+ });+}++/** How many of the brand's tasks wait for review, for the tab; 0 when the read fails. */+export async function getTaskReviewCount(brandId: string): Promise<number> {+ const supabase = await createClient();+ const { count, error } = await supabase+ .from('action_task_reviews')+ .select('id, actions!inner(brand_id, status, deleted_at)', { count: 'exact', head: true })+ .eq('actions.brand_id', brandId)+ .is('actions.deleted_at', null)+ .not('actions.status', 'in', '(completed,dismissed)');+ return error ? 0 : (count ?? 0);+}++export type ApproveTaskReviewResult =+ | { taskId: string }+ | { error: 'invalid' | 'incomplete' | 'gone' | 'not_allowed' | 'closed' };++/**+ * A reviewed task onto its action's list, as edited, its four fields+ * filled. What the writer stored beside them (its evidence refs) stays.+ */+export async function approveTaskReview(+ brandId: string,+ reviewId: string,+ edit: TaskDetailsEdit & { title: string },+): Promise<ApproveTaskReviewResult> {+ if (!isTaskDetailsEdit(edit) || typeof edit.title !== 'string') return { error: 'invalid' };+ const supabase = await createClient();+ const { data: row, error: readError } = await supabase+ .from('action_task_reviews')+ .select('details, actions!inner(brand_id)')+ .eq('id', reviewId)+ .eq('actions.brand_id', brandId)+ .maybeSingle();+ if (readError) throw new Error(readError.message);+ if (!row) return { error: 'gone' };++ const stored =+ row.details && typeof row.details === 'object' && !Array.isArray(row.details)+ ? (row.details as Record<string, unknown>)+ : {};+ const details = { ...stored, ...cleanTaskDetailsEdit(edit) };+ const { data, error } = await supabase.rpc('approve_action_task_review', {+ p_review_id: reviewId,+ p_title: edit.title.trim().slice(0, 200),+ p_details: details,+ });+ if (error) {+ if (error.code === '22023') return { error: 'incomplete' };+ if (error.code === '42501') return { error: 'not_allowed' };+ if (error.code === '55000') return { error: 'closed' };+ throw new Error(error.message);+ }+ return data ? { taskId: data } : { error: 'gone' };+}++/** A task waiting for review dropped: it never reaches the action. */+export async function dismissTaskReview(brandId: string, reviewId: string): Promise<void> {+ const supabase = await createClient();+ const { data: row, error: readError } = await supabase+ .from('action_task_reviews')+ .select('id, actions!inner(brand_id)')+ .eq('id', reviewId)+ .eq('actions.brand_id', brandId)+ .maybeSingle();+ if (readError) throw new Error(readError.message);+ if (!row) return;+ const { error } = await supabase.from('action_task_reviews').delete().eq('id', reviewId);+ if (error) throw new Error(error.message);+}diff --git a/web/src/lib/actions/action-task-writer.test.ts b/web/src/lib/actions/action-task-writer.test.tsindex 56342ec5e..aacb97f89 100644--- a/web/src/lib/actions/action-task-writer.test.ts+++ b/web/src/lib/actions/action-task-writer.test.ts@@ -18,9 +18,10 @@ afterEach(() => {describe('regenerateActionTasks', () => {it('posts as the user and returns what was written and kept', async () => {- const fetch = respond(200, { written: 5, kept: 2 });+ const fetch = respond(200, { written: 5, kept: 2, reviews: 1 });vi.stubGlobal('fetch', fetch);- expect(await regenerateActionTasks('a1')).toEqual({ written: 5, kept: 2 });+ // With how many wait in Needs review (AC-010).+ expect(await regenerateActionTasks('a1')).toEqual({ written: 5, kept: 2, reviews: 1 });const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];expect(url).toBe('https://api.example/api/action-center/actions/a1/tasks/regenerate');expect(init.headers).toEqual({ Authorization: 'Bearer token' });diff --git a/web/src/lib/actions/action-task-writer.ts b/web/src/lib/actions/action-task-writer.tsindex aae942c7e..fb80bebba 100644--- a/web/src/lib/actions/action-task-writer.ts+++ b/web/src/lib/actions/action-task-writer.ts@@ -11,7 +11,8 @@ import { API_BASE_URL } from '@/config/api';* is its English text, for a reason this build has no words for.*/export type RegenerateTasksResult =- | { written: number; kept: number }+ /** `reviews`: tasks missing an AC-010 field, waiting in Needs review. */+ | { written: number; kept: number; reviews: number }| { error: 'server'; code: string | null; message: string }| { error: 'timeout' | 'unreachable' | 'unauthenticated' };@@ -43,7 +44,11 @@ export async function regenerateActionTasks(actionId: string): Promise<Regeneratmessage: data.error || `Server error: ${res.status}`,};}- return { written: Number(data.written ?? 0), kept: Number(data.kept ?? 0) };+ return {+ written: Number(data.written ?? 0),+ kept: Number(data.kept ?? 0),+ reviews: Number(data.reviews ?? 0),+ };} catch (err) {return {error: err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable',diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex e4771804e..152aa3c30 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -127,6 +127,47 @@ export type Database = {},]}+ action_task_reviews: {+ Row: {+ action_id: string+ created_at: string+ details: Json+ id: string+ missing: string[]+ source: string+ title: string+ updated_at: string+ }+ Insert: {+ action_id: string+ created_at?: string+ details?: Json+ id?: string+ missing?: string[]+ source?: string+ title: string+ updated_at?: string+ }+ Update: {+ action_id?: string+ created_at?: string+ details?: Json+ id?: string+ missing?: string[]+ source?: string+ title?: string+ updated_at?: string+ }+ Relationships: [+ {+ foreignKeyName: "action_task_reviews_action_id_fkey"+ columns: ["action_id"]+ isOneToOne: false+ referencedRelation: "actions"+ referencedColumns: ["id"]+ },+ ]+ }action_tasks: {Row: {action_id: string@@ -4415,6 +4456,10 @@ export type Database = {Returns: Json}apply_prompt_locations: { Args: { p_updates: Json }; Returns: number }+ approve_action_task_review: {+ Args: { p_details: Json; p_review_id: string; p_title: string }+ Returns: string+ }brand_ai_conversions: {Args: { p_brand_id: string; p_days?: number }Returns: Json