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): change or delete an action from its row menu (#1144)
Cihana52a5efc8f5c
diff --git a/server/src/routes/action-center-delete.test.js b/server/src/routes/action-center-delete.test.jsnew file mode 100644index 000000000..745b9bbad--- /dev/null+++ b/server/src/routes/action-center-delete.test.js@@ -0,0 +1,123 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Deleting an action from its row menu: hidden, not removed (00168). It+ * becomes dismissed with deleted_at, checked against the caller's+ * organization and role first, and the trail records it.+ */++let action;+let role;+let writes;++vi.mock('../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const op = { table, filters: [] };+ const chain = {+ select: () => chain,+ eq: (col, val) => {+ op.filters.push(['eq', col, val]);+ return chain;+ },+ is: (col, val) => {+ op.filters.push(['is', col, val]);+ return chain;+ },+ update: (row) => {+ op.update = row;+ return chain;+ },+ insert: (row) => {+ op.insert = row;+ return chain;+ },+ maybeSingle: async () => ({+ data: table === 'actions' ? action : table === 'profiles' ? { role } : null,+ error: null,+ }),+ then: (resolve) => {+ writes.push(op);+ return resolve({ data: null, error: null });+ },+ };+ return chain;+ },+ },+}));++const assertBrandAccess = vi.fn();+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));+vi.mock('../lib/action-center/priority-data.js', () => ({ rescoreActionsForSignal: vi.fn() }));+vi.mock('../lib/plan-guard.js', () => ({ PlanLimitError: class extends Error {} }));+vi.mock('../lib/action-center/task-writer/index.js', () => ({+ TaskWriterError: class extends Error {},+ isTaskWriterEnabled: () => false,+ writeTasksForAction: vi.fn(),+}));+vi.mock('../lib/action-center/task-send.js', () => ({+ TaskSendError: class extends Error {},+ loadTask: vi.fn(),+ sendTaskToContent: vi.fn(),+ sendTaskToWebhook: vi.fn(),+}));++const { deleteAction } = await import('./action-center.js');++beforeEach(() => {+ action = { id: 'a1', brand_id: 'b1', status: 'in_progress', deleted_at: null };+ role = 'manager';+ writes = [];+ assertBrandAccess.mockReset();+});++describe('deleteAction', () => {+ it('dismisses the action, stamps deleted_at and records who did it', async () => {+ await expect(deleteAction('a1', 'u1')).resolves.toEqual({ deleted: true });+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');++ const [update, event] = writes;+ expect(update).toMatchObject({+ table: 'actions',+ update: {+ status: 'dismissed',+ deleted_at: expect.any(String),+ completed_at: null,+ updated_at: expect.any(String),+ },+ });+ // Only an action not deleted yet.+ expect(update.filters).toEqual([+ ['eq', 'id', 'a1'],+ ['is', 'deleted_at', null],+ ]);+ expect(event).toMatchObject({+ table: 'action_events',+ insert: { action_id: 'a1', event: 'deleted', data: { from: 'in_progress' }, actor_id: 'u1' },+ });+ });++ it("checks the caller's organization before anything", async () => {+ assertBrandAccess.mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }));+ await expect(deleteAction('a1', 'u1')).rejects.toThrow('Forbidden');+ expect(writes).toEqual([]);+ });++ it('lets only admins and managers delete', async () => {+ role = 'member';+ await expect(deleteAction('a1', 'u1')).rejects.toMatchObject({+ status: 403,+ message: 'Only admins and managers can delete actions.',+ });+ role = 'admin';+ await expect(deleteAction('a1', 'u1')).resolves.toEqual({ deleted: true });+ });++ it('is not found when the action is gone or already deleted', async () => {+ action = null;+ await expect(deleteAction('a1', 'u1')).rejects.toMatchObject({ status: 404 });+ action = { id: 'a1', brand_id: 'b1', status: 'dismissed', deleted_at: '2026-10-18T00:00:00Z' };+ await expect(deleteAction('a1', 'u1')).rejects.toMatchObject({ status: 404 });+ expect(writes).toEqual([]);+ });+});diff --git a/server/src/routes/action-center.js b/server/src/routes/action-center.jsindex 2779ac024..0a92fb455 100644--- a/server/src/routes/action-center.js+++ b/server/src/routes/action-center.js@@ -112,6 +112,75 @@ router.post('/actions/:id/tasks/regenerate', async (req, res) => {}});+/** Roles that may delete an action, as for other destructive changes. */+const DELETE_ROLES = ['admin', 'manager'];++/**+ * Deletes an action from its row menu: hidden, not removed. It becomes+ * dismissed and gets deleted_at (00168), so the lists, the API and the+ * exports leave it out, while the nightly generator still reads a dismissed+ * action and keeps its rest window: a condition that is still firing+ * doesn't bring it back the next night. Admins and managers only.+ *+ * @returns {Promise<{ deleted: true }>}+ */+export async function deleteAction(actionId, userId) {+ const { data: action } = await supabaseAdmin+ .from('actions')+ .select('id, brand_id, status, deleted_at')+ .eq('id', actionId)+ .maybeSingle();+ if (!action || action.deleted_at) {+ const err = new Error('Action not found');+ err.status = 404;+ throw err;+ }+ await assertBrandAccess(action.brand_id, userId);++ const { data: profile } = await supabaseAdmin+ .from('profiles')+ .select('role')+ .eq('id', userId)+ .maybeSingle();+ if (!DELETE_ROLES.includes(profile?.role)) {+ const err = new Error('Only admins and managers can delete actions.');+ err.status = 403;+ throw err;+ }++ const now = new Date().toISOString();+ const { error } = await supabaseAdmin+ .from('actions')+ .update({ status: 'dismissed', deleted_at: now, completed_at: null, updated_at: now })+ .eq('id', actionId)+ .is('deleted_at', null);+ if (error) throw new Error(error.message);++ // The trail keeps who deleted it and from where, though nobody reads it now.+ const { error: eventErr } = await supabaseAdmin.from('action_events').insert({+ action_id: actionId,+ event: 'deleted',+ data: { from: action.status },+ actor_id: userId,+ });+ if (eventErr) throw new Error(eventErr.message);+ return { deleted: true };+}++/** DELETE /api/action-center/actions/:id */+router.delete('/actions/:id', async (req, res) => {+ const id = signalIdSchema.safeParse(req.params.id);+ if (!id.success) return res.status(400).json({ error: 'Invalid action id' });+ try {+ return res.json(await deleteAction(id.data, req.user.id));+ } catch (error) {+ if (!error.status) req.log.error({ err: error }, 'delete action error');+ return res.status(error.status || 500).json({+ error: error.status ? error.message : 'Failed to delete the action.',+ });+ }+});+/*** Sends a task onward (AC-004): to Content as an opportunity, or to the* brand's webhook. `title` is the task's text as the dashboard shows it, fordiff --git a/supabase/migrations/00168_actions_soft_delete.sql b/supabase/migrations/00168_actions_soft_delete.sqlnew file mode 100644index 000000000..a466d4422--- /dev/null+++ b/supabase/migrations/00168_actions_soft_delete.sql@@ -0,0 +1,89 @@+-- Deleting an Action Center action from its row menu.+--+-- A delete hides the action rather than removing the row: it is set to+-- 'dismissed' and stamped deleted_at. Kept as a dismissed row, it still+-- gives the nightly generator its rest window (generate.js reads completed+-- and dismissed actions to see when a definition last closed), so a+-- condition that is still firing doesn't come back as a fresh action the+-- next night. Removed outright, it would.+--+-- Everyone else stops seeing it:+-- * members read actions through "actions: member select", which now+-- leaves deleted rows out. The task, event and signal-link policies look+-- actions up through it, so a deleted action's tasks and trail go too.+-- * the server's admin reads (MCP, API, exports) filter deleted_at+-- themselves.+-- * sync_opportunity_status, a security-definer trigger, counts an+-- opportunity's actions to set its status; a deleted one no longer+-- counts, as if it had never been sent.++alter table public.actions add column if not exists deleted_at timestamptz;++drop policy if exists "actions: member select" on public.actions;++create policy "actions: member select" on public.actions+ for select using (+ deleted_at is null+ and brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++create or replace function public.sync_opportunity_status()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;+ since timestamptz;+ next_status text;+begin+ if opp is null then+ return new;+ end if;++ select nullif(source_data->'reopened'->>'at', '')::timestamptz+ into since+ from content_opportunities+ where id = opp;++ select case+ when count(*) = 0 then null+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0+ then 'in_progress'+ else 'sent'+ end+ into next_status+ from actions a+ where a.kind = 'content_opportunity'+ and a.brand_id = new.brand_id+ and a.payload->>'opportunityId' = opp::text+ and a.deleted_at is null+ and (since is null or a.created_at >= since);++ -- Only earlier work changed, or the only action was deleted: the+ -- opportunity stays as it is.+ if next_status is null then+ return new;+ end if;++ update content_opportunities+ set status = next_status, updated_at = now()+ where id = opp+ and brand_id = new.brand_id+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')+ and status <> next_status;++ return new;+end;+$$;++revoke all on function public.sync_opportunity_status() from public, anon, authenticated;++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex a7afdcb8f..f676eaf34 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -22455,3 +22455,96 @@ grant execute on function public.audit_competitor_cited_prompts(uuid, timestamptnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00168_actions_soft_delete.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Deleting an Action Center action from its row menu.+--+-- A delete hides the action rather than removing the row: it is set to+-- 'dismissed' and stamped deleted_at. Kept as a dismissed row, it still+-- gives the nightly generator its rest window (generate.js reads completed+-- and dismissed actions to see when a definition last closed), so a+-- condition that is still firing doesn't come back as a fresh action the+-- next night. Removed outright, it would.+--+-- Everyone else stops seeing it:+-- * members read actions through "actions: member select", which now+-- leaves deleted rows out. The task, event and signal-link policies look+-- actions up through it, so a deleted action's tasks and trail go too.+-- * the server's admin reads (MCP, API, exports) filter deleted_at+-- themselves.+-- * sync_opportunity_status, a security-definer trigger, counts an+-- opportunity's actions to set its status; a deleted one no longer+-- counts, as if it had never been sent.++alter table public.actions add column if not exists deleted_at timestamptz;++drop policy if exists "actions: member select" on public.actions;++create policy "actions: member select" on public.actions+ for select using (+ deleted_at is null+ and brand_id in (+ select b.id from public.brands b+ join public.profiles p on p.organization_id = b.organization_id+ where p.id = auth.uid()+ )+ );++create or replace function public.sync_opportunity_status()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ opp uuid := nullif(new.payload->>'opportunityId', '')::uuid;+ since timestamptz;+ next_status text;+begin+ if opp is null then+ return new;+ end if;++ select nullif(source_data->'reopened'->>'at', '')::timestamptz+ into since+ from content_opportunities+ where id = opp;++ select case+ when count(*) = 0 then null+ when count(*) filter (where a.status <> 'dismissed') = 0 then 'reviewed'+ when count(*) filter (where a.status not in ('completed', 'dismissed')) = 0 then 'done'+ when count(*) filter (where a.status in ('in_progress', 'on_hold', 'completed')) > 0+ then 'in_progress'+ else 'sent'+ end+ into next_status+ from actions a+ where a.kind = 'content_opportunity'+ and a.brand_id = new.brand_id+ and a.payload->>'opportunityId' = opp::text+ and a.deleted_at is null+ and (since is null or a.created_at >= since);++ -- Only earlier work changed, or the only action was deleted: the+ -- opportunity stays as it is.+ if next_status is null then+ return new;+ end if;++ update content_opportunities+ set status = next_status, updated_at = now()+ where id = opp+ and brand_id = new.brand_id+ and status in ('new', 'reviewed', 'sent', 'in_progress', 'done')+ and status <> next_status;++ return new;+end;+$$;++revoke all on function public.sync_opportunity_status() from public, anon, authenticated;++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 904cfdd20..89c701c02 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -853,6 +853,19 @@"menu": {"label": "Actions for this item"},+ "rowMenu": {+ "label": "Actions for {title}",+ "in_progress": "In Progress",+ "completed": "Completed",+ "dismissed": "Dismiss",+ "delete": "Delete",+ "deleteNotAllowed": "Only admins and managers can delete actions",+ "deleteTitle": "Delete this action?",+ "deleteConfirm": "It leaves the Action Center for everyone and won't come back on its own tomorrow.",+ "cancel": "Cancel",+ "statusChanged": "Moved to {status}",+ "deleted": "Action deleted"+ },"empty": {"title": "No actions yet","description": "Actions are generated from your signals after daily tracking runs. When meaningful work emerges, it will appear here — quality over quantity."diff --git a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsxindex fb6df952c..875fb41a7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/action-center/actions/page.tsx@@ -17,8 +17,15 @@ import {X,} from 'lucide-react';import { useBrandStore } from '@/stores/use-brand-store';+import { useUserRole } from '@/hooks/use-user-role';import type { Brand } from '@/types';-import { getActions, getActionsAffected, type ActionItem } from '@/lib/actions/action-center';+import {+ deleteAction,+ getActions,+ getActionsAffected,+ updateActionStatus,+ type ActionItem,+} from '@/lib/actions/action-center';import { listMembers, type TeamMember } from '@/lib/actions/team';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import {@@ -118,6 +125,9 @@ function ActionsContent({ brand }: { brand: Brand }) {const [sort, setSort] = useState<ActionSort>('priority');const [search, setSearch] = useState('');const [isExporting, setIsExporting] = useState(false);+ const { canManage } = useUserRole();+ // Rows with a menu change in flight.+ const [busyIds, setBusyIds] = useState<Set<string>>(() => new Set());// False once this brand's view is gone, so an export still reading doesn't// download the previous brand's file after a switch.const mounted = useRef(true);@@ -205,6 +215,35 @@ function ActionsContent({ brand }: { brand: Brand }) {if (id && actions.some((action) => action.id === id)) setSelectedId(id);}, [actions]);+ // The row menu: set a status or delete, without the drawer, then read the+ // list again.+ const runRowChange = async (action: ActionItem, change: () => Promise<void>, done: string) => {+ setBusyIds((prev) => new Set(prev).add(action.id));+ try {+ await change();+ toast.success(done);+ } catch {+ toast.error(t('updateFailed'));+ } finally {+ await load();+ setBusyIds((prev) => {+ const next = new Set(prev);+ next.delete(action.id);+ return next;+ });+ }+ };+ const changeStatus = (action: ActionItem, next: ActionStatus) =>+ void runRowChange(+ action,+ () => updateActionStatus(brand.id, action.id, next),+ t('rowMenu.statusChanged', { status: t(`status.${next}`) }),+ );+ const removeAction = (action: ActionItem) => {+ if (selectedId === action.id) selectAction(null);+ void runRowChange(action, () => deleteAction(action.id), t('rowMenu.deleted'));+ };+const selected = useMemo(() => (actions ?? []).find((action) => action.id === selectedId) ?? null,[actions, selectedId],@@ -518,7 +557,14 @@ function ActionsContent({ brand }: { brand: Brand }) {</div>{visible.length > 0 ? (- <ActionTable actions={visible} onSelect={(action) => selectAction(action.id)} />+ <ActionTable+ actions={visible}+ onSelect={(action) => selectAction(action.id)}+ onStatusChange={changeStatus}+ onDelete={removeAction}+ canDelete={canManage}+ busyIds={busyIds}+ />) : (<div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16 text-center"><p className="text-sm text-muted-foreground">{t('noResults')}</p>diff --git a/web/src/components/action-center/action-table.test.tsx b/web/src/components/action-center/action-table.test.tsxnew file mode 100644index 000000000..cab1d3075--- /dev/null+++ b/web/src/components/action-center/action-table.test.tsx@@ -0,0 +1,130 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { ActionItem } from '@/lib/actions/action-center';+import { ActionTable } from './action-table';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const action: ActionItem = {+ id: 'a1',+ actionNo: 7,+ category: 'recover',+ kind: 'recover_lost_citations',+ impact: 'high',+ priorityScore: 72,+ priorityLevel: 'high',+ priorityReason: null,+ status: 'in_progress',+ payload: {},+ kpiKeys: [],+ assignee: null,+ dueDate: null,+ createdAt: '2026-10-15T00:00:00.000Z',+ updatedAt: '2026-10-15T00:00:00.000Z',+ taskTotal: 0,+ taskCompleted: 0,+ signalCount: 1,+};++let container: HTMLDivElement;+let root: Root;+const onSelect = vi.fn();+const onStatusChange = vi.fn();+const onDelete = vi.fn();++function render(props: Partial<React.ComponentProps<typeof ActionTable>> = {}) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <ActionTable+ actions={[action]}+ onSelect={onSelect}+ onStatusChange={onStatusChange}+ onDelete={onDelete}+ canDelete+ {...props}+ />+ </NextIntlClientProvider>,+ );+ });+}++async function openMenu() {+ const trigger = container.querySelector<HTMLButtonElement>('button[aria-label^="Actions for"]')!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}++const disabled = (item: HTMLElement) =>+ item.hasAttribute('data-disabled') || item.getAttribute('aria-disabled') === 'true';++beforeEach(() => {+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('ActionTable row menu', () => {+ it('offers In Progress, Completed, Dismiss and Delete, the current status off', async () => {+ render();+ const items = await openMenu();+ expect(items.map((item) => item.textContent)).toEqual([+ 'In Progress',+ 'Completed',+ 'Dismiss',+ 'Delete',+ ]);+ expect(items.map(disabled)).toEqual([true, false, false, false]);+ });++ it('changes the status from the list, without opening the drawer', async () => {+ render();+ const items = await openMenu();+ await act(async () => items[1].click());+ expect(onStatusChange).toHaveBeenCalledWith(action, 'completed');+ expect(onSelect).not.toHaveBeenCalled();+ });++ it('asks before deleting, and deletes on Delete', async () => {+ render();+ const items = await openMenu();+ await act(async () => items[3].click());+ expect(onDelete).not.toHaveBeenCalled();+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(dialog.textContent).toContain('Delete this action?');+ const confirm = [...dialog.querySelectorAll('button')].find(+ (b) => b.textContent?.trim() === 'Delete',+ )!;+ await act(async () => confirm.click());+ expect(onDelete).toHaveBeenCalledWith(action);+ expect(onSelect).not.toHaveBeenCalled();+ });++ it("keeps Delete off for members who can't delete", async () => {+ render({ canDelete: false });+ const items = await openMenu();+ expect(disabled(items[3])).toBe(true);+ });++ it('waits while a change to the row is in flight, and has no menu without handlers', () => {+ render({ busyIds: new Set(['a1']) });+ expect(+ container.querySelector<HTMLButtonElement>('button[aria-label^="Actions for"]')!.disabled,+ ).toBe(true);+ render({ onStatusChange: undefined, onDelete: undefined });+ expect(container.querySelector('button[aria-label^="Actions for"]')).toBeNull();+ });+});diff --git a/web/src/components/action-center/action-table.tsx b/web/src/components/action-center/action-table.tsxindex 2e6618be6..862b2b869 100644--- a/web/src/components/action-center/action-table.tsx+++ b/web/src/components/action-center/action-table.tsx@@ -1,20 +1,43 @@'use client';+import { useState } from 'react';import { useTranslations } from 'next-intl';import {BarChart3,+ Check,+ CirclePlay,MessageSquare,+ MoreHorizontal,MousePointerClick,Swords,+ Trash2,Wrench,ShieldCheck,Layers,Quote,Sparkles,Target,+ X,} from 'lucide-react';import { Badge } from '@/components/ui/badge';import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import {Table,TableBody,@@ -145,14 +168,113 @@ export function AssigneeAvatar({ assignee }: { assignee: ActionItem['assignee']);}+/**+ * The menu column stays at the table's right edge: the table scrolls+ * sideways below about 1,100px, and the menu is what a row is reached for.+ * Opaque, with the row's hover tint, so it covers what scrolls under it.+ */+const MENU_CELL =+ 'sticky right-0 z-[5] w-10 bg-background [tr:hover>&]:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]';++/** The statuses the row menu sets, in its order. */+const MENU_STATUSES = [+ { status: 'in_progress', icon: CirclePlay },+ { status: 'completed', icon: Check },+ { status: 'dismissed', icon: X },+] as const;++/**+ * An action's row menu: set it In Progress, Completed or Dismissed, or+ * delete it, without opening the drawer. The status it already has is off;+ * Delete asks first, and is off for members who can't delete.+ */+function ActionMenu({+ action,+ title,+ canDelete,+ disabled,+ onStatusChange,+ onDelete,+}: {+ action: ActionItem;+ title: string;+ canDelete: boolean;+ disabled: boolean;+ onStatusChange: (action: ActionItem, status: ActionStatus) => void;+ onDelete: (action: ActionItem) => void;+}) {+ const t = useTranslations('actionCenter.actionsPage');+ const [confirming, setConfirming] = useState(false);+ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ className="rounded p-1 text-muted-foreground hover:bg-muted disabled:pointer-events-none disabled:opacity-50"+ disabled={disabled}+ aria-label={t('rowMenu.label', { title })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ {MENU_STATUSES.map(({ status, icon: Icon }) => (+ <DropdownMenuItem+ key={status}+ disabled={action.status === status}+ onClick={() => onStatusChange(action, status)}+ >+ <Icon className="h-4 w-4" />+ {t(`rowMenu.${status}`)}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ disabled={!canDelete}+ title={canDelete ? undefined : t('rowMenu.deleteNotAllowed')}+ onClick={() => setConfirming(true)}+ >+ <Trash2 className="h-4 w-4" />+ {t('rowMenu.delete')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <Dialog open={confirming} onOpenChange={setConfirming}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('rowMenu.deleteTitle')}</DialogTitle>+ <DialogDescription>{t('rowMenu.deleteConfirm')}</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>{t('rowMenu.cancel')}</DialogClose>+ <DialogClose render={<Button variant="destructive" onClick={() => onDelete(action)} />}>+ {t('rowMenu.delete')}+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}+export function ActionTable({actions,onSelect,+ onStatusChange,+ onDelete,+ canDelete = false,+ busyIds,}: {actions: ActionItem[];onSelect: (action: ActionItem) => void;+ /** With these, each row gets its menu (status changes and Delete). */+ onStatusChange?: (action: ActionItem, status: ActionStatus) => void;+ onDelete?: (action: ActionItem) => void;+ canDelete?: boolean;+ /** Actions with a change in flight: their menu waits. */+ busyIds?: Set<string>;}) {const t = useTranslations('actionCenter.actionsPage');+ const withMenu = Boolean(onStatusChange && onDelete);const tTexts = useTranslations('actionCenter.actionTexts');const tCategories = useTranslations('actionCenter.actionCategories');const tCommon = useTranslations('common');@@ -168,6 +290,11 @@ export function ActionTable({<TableHead className="text-xs">{t('table.assignee')}</TableHead><TableHead className="text-xs">{t('table.dueDate')}</TableHead><TableHead className="text-xs">{t('table.updated')}</TableHead>+ {withMenu && (+ <TableHead className={MENU_CELL}>+ <span className="sr-only">{t('table.actions')}</span>+ </TableHead>+ )}</TableRow></TableHeader><TableBody>@@ -241,6 +368,19 @@ export function ActionTable({<TableCell className="text-xs text-muted-foreground">{formatRelative(action.updatedAt, tCommon)}</TableCell>+ {withMenu && onStatusChange && onDelete && (+ // The menu works on the row without opening the drawer.+ <TableCell className={MENU_CELL} onClick={(e) => e.stopPropagation()}>+ <ActionMenu+ action={action}+ title={texts.title}+ canDelete={canDelete}+ disabled={busyIds?.has(action.id) ?? false}+ onStatusChange={onStatusChange}+ onDelete={onDelete}+ />+ </TableCell>+ )}</TableRow>);})}diff --git a/web/src/lib/actions/action-center.ts b/web/src/lib/actions/action-center.tsindex 37d429bdc..ae49f3056 100644--- a/web/src/lib/actions/action-center.ts+++ b/web/src/lib/actions/action-center.ts@@ -11,6 +11,7 @@*/import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';import {type ActionCategory,type ActionImpact,@@ -309,6 +310,29 @@ export async function updateActionStatus(await logEvent(supabase, actionId, 'status_changed', { to: status });}+/**+ * Delete an action from its row menu (admins and managers). The server hides+ * it rather than removing it: dismissed, with deleted_at (00168), so it+ * leaves every list while the nightly generator keeps its rest window.+ */+export async function deleteAction(actionId: string): Promise<void> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) throw new Error('Not authenticated');++ const res = await fetch(`${API_BASE_URL}/api/action-center/actions/${actionId}`, {+ method: 'DELETE',+ headers: { Authorization: `Bearer ${session.access_token}` },+ cache: 'no-store',+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || `Server error: ${res.status}`);+ }+}+export async function assignAction(brandId: string,actionId: string,diff --git a/web/src/lib/mcp/action-center.test.ts b/web/src/lib/mcp/action-center.test.tsindex 28ae43317..3b28b4ddc 100644--- a/web/src/lib/mcp/action-center.test.ts+++ b/web/src/lib/mcp/action-center.test.ts@@ -12,6 +12,7 @@ type Op = { table: string; op: 'select' | 'update' | 'insert'; payload?: unknownlet ops: Op[] = [];let taskOwned = true;+let isFilters: [string, unknown][] = [];function builder(table: string) {let current: Op = { table, op: 'select' };@@ -30,6 +31,10 @@ function builder(table: string) {return { error: null };},eq: () => chain,+ is: (column: string, value: unknown) => {+ isFilters.push([column, value]);+ return chain;+ },maybeSingle: async () => ({data: taskOwned ? { id: 'task-1', action_id: 'action-1' } : null,error: null,@@ -68,6 +73,12 @@ describe('updateTaskStatusFor', () => {beforeEach(() => {ops = [];taskOwned = true;+ isFilters = [];+ });++ it("checks the task's action isn't deleted (00168)", async () => {+ await updateTaskStatusFor(auth, 'task-1', 'completed');+ expect(isFilters).toContainEqual(['actions.deleted_at', null]);});it('returns null and writes nothing for a task outside the caller org', async () => {diff --git a/web/src/lib/mcp/action-export.test.ts b/web/src/lib/mcp/action-export.test.tsindex 4aa930dad..75195da15 100644--- a/web/src/lib/mcp/action-export.test.ts+++ b/web/src/lib/mcp/action-export.test.ts@@ -45,6 +45,7 @@ function table(name: string) {return chain;},order: () => chain,+ is: () => chain,range: (from: number, to: number) => {range = [from, to];return chain;diff --git a/web/src/lib/mcp/action-export.ts b/web/src/lib/mcp/action-export.tsindex b01d39c51..0aa250373 100644--- a/web/src/lib/mcp/action-export.ts+++ b/web/src/lib/mcp/action-export.ts@@ -181,6 +181,8 @@ export async function exportActionFor(.select(`${ACTION_COLUMNS}, brand_id, brands!inner(organization_id)`).eq('id', actionId).eq('brands.organization_id', auth.organizationId)+ // A deleted action (00168) has nothing left to export.+ .is('deleted_at', null).maybeSingle();if (error) throw new Error(error.message);if (!row) return null;diff --git a/web/src/lib/mcp/action-priority.test.ts b/web/src/lib/mcp/action-priority.test.tsindex 8163f46c1..496fc710c 100644--- a/web/src/lib/mcp/action-priority.test.ts+++ b/web/src/lib/mcp/action-priority.test.ts@@ -47,6 +47,7 @@ function builder(table: string) {const chain = {select: () => chain,eq: () => chain,+ is: () => chain,in: () => chain,order: (column: string, options?: Record<string, unknown>) => {if (table === 'actions') orders.push([column, options]);diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex c6acdcfdc..c835ad781 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2580,7 +2580,9 @@ export async function listActionsFor(.select('id, action_no, category, kind, impact, status, outcome, assignee_id, due_date, created_at, updated_at, priority_score, priority_level, priority_reason',)- .eq('brand_id', params.brandId);+ .eq('brand_id', params.brandId)+ // A deleted action (00168) is gone for everyone but the nightly generator.+ .is('deleted_at', null);query =params.sort === 'updated'? query.order('updated_at', { ascending: false })@@ -2705,6 +2707,7 @@ export async function getActionFor().eq('id', actionId).eq('brands.organization_id', auth.organizationId)+ .is('deleted_at', null).maybeSingle();if (error) throw new Error(error.message);if (!action) return null;@@ -2814,6 +2817,7 @@ async function signalActionRefs(.select('signal_id, actions!inner(id, action_no, kind, status)').in('signal_id', ids).eq('actions.brand_id', brandId)+ .is('actions.deleted_at', null).order('linked_at', { ascending: false }),),);@@ -2920,6 +2924,7 @@ export async function listActionHistoryFor().eq('brand_id', params.brandId).in('status', ['completed', 'dismissed'])+ .is('deleted_at', null).order('completed_at', { ascending: false, nullsFirst: false }).limit(limit);if (error) throw new Error(error.message);@@ -2981,6 +2986,7 @@ export async function updateTaskStatusFor(.select('id, action_id, actions!inner(brand_id, brands!inner(organization_id))').eq('id', taskId).eq('actions.brands.organization_id', auth.organizationId)+ .is('actions.deleted_at', null).maybeSingle();if (!owned) return null;diff --git a/web/src/lib/mcp/signals.test.ts b/web/src/lib/mcp/signals.test.tsindex c303e9b48..ded09fd6e 100644--- a/web/src/lib/mcp/signals.test.ts+++ b/web/src/lib/mcp/signals.test.ts@@ -18,6 +18,7 @@ function builder(table: string) {const chain = {select: () => chain,eq: () => chain,+ is: () => chain,order: () => chain,limit: () => chain,in: (_column: string, values: string[]) => {