Skip to content

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

feat(prompts): delete a topic from its row menu on the Topics tab (#1779)

Cihan0da45a359bbd
diff --git a/docs/guides/prompts.mdx b/docs/guides/prompts.mdx
index b5b9943a5..5738f7a85 100644
--- a/docs/guides/prompts.mdx
+++ b/docs/guides/prompts.mdx
@@ -18,6 +18,8 @@ The date range (24h, 7d, 30d, 90d or custom) applies to Prompts, Topics and Quer
Topics is a tab of the Prompts page. The old `/dashboard/topics` address, and a topic's old `/dashboard/topics/<id>` page, redirect to `/dashboard/prompts/topics`. The tab uses the page's date range and opens on the last 24 hours. It has no Location selector, because topics aren't split by location.
+To delete a topic, admins and managers open the **…** menu at the end of its row and choose **Delete topic**: its prompts aren't deleted but keep their tracking and results as prompts without a topic, and the delete can be undone for 10 seconds.
+
What each column means, and how to use topics for planning, is in the [Topics](/guides/topics) guide.
## Adding prompts
diff --git a/web/messages/en.json b/web/messages/en.json
index 510eed9d6..4a8c54b51 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3957,7 +3957,23 @@
"lastRun": "Last run"
},
"appearedIn": "Appeared in {visible} of {active, plural, one {# prompt} other {# prompts}}",
- "openDetails": "Open topic details"
+ "openDetails": "Open topic details",
+ "rowMenu": {
+ "label": "Actions for {name}",
+ "delete": "Delete topic"
+ },
+ "delete": {
+ "title": "Delete the topic \"{name}\"?",
+ "counting": "Counting the prompts in this topic…",
+ "prompts": "{count, plural, =0 {No prompts are in this topic.} one {# prompt is in this topic. It isn't deleted: it keeps its tracking and results, and moves to prompts without a topic.} other {# prompts are in this topic. They aren't deleted: they keep their tracking and results, and move to prompts without a topic.}}",
+ "promptsKept": "Its prompts aren't deleted: they keep their tracking and results, and move to prompts without a topic.",
+ "undoHint": "You can undo for 10 seconds.",
+ "keep": "Keep it",
+ "confirm": "Delete topic",
+ "deleted": "Topic deleted",
+ "undo": "Undo",
+ "failed": "Couldn't delete \"{name}\", so it's back in the list."
+ }
},
"contentEditor": {
"publish": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
index 8613a3bef..995dcd30a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.test.tsx
@@ -22,10 +22,19 @@ vi.mock('@/stores/use-brand-store', () => ({
vi.mock('@/i18n/navigation', () => ({
Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
}));
+// The leaderboard's rows: none unless a test gives some.
+let topicRows: Record<string, unknown>[] = [];
+const getTopicsOverview = vi.fn(async () => ({ topics: topicRows, unassignedPromptCount: 0 }));
+const getPromptCountByTopic = vi.fn(async () => 3);
+const deleteTopic = vi.fn(async () => undefined);
vi.mock('@/lib/actions/topic', () => ({
- getTopicsOverview: vi.fn(async () => ({ topics: [], unassignedPromptCount: 0 })),
+ getTopicsOverview,
+ getPromptCountByTopic,
+ deleteTopic,
createTopic: vi.fn(),
}));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
vi.mock('./_topic-suggestions-card', () => ({ TopicSuggestionsCard: () => null }));
const { TopicsTab } = await import('./_topics-tab');
@@ -40,7 +49,12 @@ let root: Root;
beforeEach(() => {
canManage = true;
isLocked = false;
+ topicRows = [];
openUpgrade.mockClear();
+ getTopicsOverview.mockClear();
+ getPromptCountByTopic.mockClear();
+ deleteTopic.mockClear();
+ toast.mockClear();
container = document.createElement('div');
slot = document.createElement('div');
document.body.append(slot, container);
@@ -49,6 +63,7 @@ beforeEach(() => {
afterEach(() => {
act(() => root.unmount());
+ vi.useRealTimers();
container.remove();
slot.remove();
});
@@ -114,3 +129,124 @@ describe('Add Topic on a read-only workspace (plan not active)', () => {
expect(dialog()?.textContent).toContain('Add Topic');
});
});
+
+describe('Delete topic in a row\'s "…" menu', () => {
+ // Two active prompts; with a paused one, the topic holds three.
+ const ESPRESSO = {
+ id: 't1',
+ name: 'Espresso',
+ promptCount: 2,
+ visibilityRate: 50,
+ visiblePrompts: 1,
+ activePrompts: 2,
+ visibilityChange: null,
+ totalMentions: 3,
+ totalCitations: 1,
+ shareOfVoice: 20,
+ topCompetitor: null,
+ lastRunAt: null,
+ trendSparkline: [],
+ };
+ const trigger = () => container.querySelector<HTMLElement>('[aria-label="Actions for Espresso"]');
+ const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');
+ const button = (root: Element | null, text: string) =>
+ [...(root?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find(
+ (b) => b.textContent?.trim() === text,
+ )!;
+
+ /** Opens the row's menu and picks Delete topic. */
+ async function pickDelete() {
+ await act(async () => trigger()!.click());
+ const item = [...document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
+ (el) => el.textContent === 'Delete topic',
+ )!;
+ await act(async () => item.click());
+ }
+
+ /** Confirms in the dialog, with the Undo window's timer faked. */
+ async function confirm() {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ await act(async () => button(dialog(), 'Delete topic').click());
+ }
+
+ beforeEach(() => {
+ topicRows = [ESPRESSO];
+ });
+
+ it("isn't shown to members who can't manage topics", async () => {
+ canManage = false;
+ await render();
+ expect(container.textContent).toContain('Espresso');
+ expect(trigger()).toBeNull();
+ });
+
+ it('asks first, with every prompt in the topic counted, paused ones too', async () => {
+ await render();
+ await pickDelete();
+ expect(getPromptCountByTopic).toHaveBeenCalledExactlyOnceWith('b1', 't1');
+ expect(dialog()?.textContent).toContain('Delete the topic "Espresso"?');
+ expect(dialog()?.textContent).toContain(
+ "3 prompts are in this topic. They aren't deleted: they keep their tracking and results, and move to prompts without a topic. You can undo for 10 seconds.",
+ );
+ expect(deleteTopic).not.toHaveBeenCalled();
+ });
+
+ it('hides the topic at once and deletes it after the 10-second Undo window', async () => {
+ await render();
+ await pickDelete();
+ await confirm();
+ expect(trigger()).toBeNull();
+ expect(toast).toHaveBeenCalledExactlyOnceWith('Topic deleted', {
+ description: 'Espresso',
+ duration: 10_000,
+ action: { label: 'Undo', onClick: expect.any(Function) },
+ });
+ expect(deleteTopic).not.toHaveBeenCalled();
+
+ await act(async () => vi.advanceTimersByTime(10_000));
+ expect(deleteTopic).toHaveBeenCalledExactlyOnceWith('t1');
+ // Read again: its prompts now count as prompts without a topic.
+ expect(getTopicsOverview).toHaveBeenCalledTimes(2);
+ });
+
+ it('puts the topic back on Undo and deletes nothing', async () => {
+ await render();
+ await pickDelete();
+ await confirm();
+ await act(async () => toast.mock.calls[0][1].action.onClick());
+ expect(trigger()).not.toBeNull();
+ await act(async () => vi.advanceTimersByTime(10_000));
+ expect(deleteTopic).not.toHaveBeenCalled();
+ });
+
+ it('still deletes the topic when the tab closes inside the window', async () => {
+ await render();
+ await pickDelete();
+ await confirm();
+ act(() => root.unmount());
+ expect(deleteTopic).toHaveBeenCalledExactlyOnceWith('t1');
+ });
+
+ it('brings the topic back with an error when the delete fails', async () => {
+ deleteTopic.mockRejectedValueOnce(new Error('Only an admin or a manager can delete topics.'));
+ const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await render();
+ await pickDelete();
+ await confirm();
+ await act(async () => vi.advanceTimersByTime(10_000));
+ expect(trigger()).not.toBeNull();
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Couldn\'t delete "Espresso", so it\'s back in the list.',
+ );
+ quiet.mockRestore();
+ });
+
+ it('opens the upgrade dialog instead on a read-only workspace (plan not active)', async () => {
+ isLocked = true;
+ await render();
+ await pickDelete();
+ expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Deleting topics needs a plan');
+ expect(dialog()).toBeNull();
+ expect(getPromptCountByTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
index f07c94e31..134431392 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_topics-tab.tsx
@@ -7,7 +7,12 @@ import { Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
import { useUserRole } from '@/hooks/use-user-role';
import { useUpgradeGate } from '@/components/providers/upgrade-gate';
-import { getTopicsOverview, type TopicOverviewRow } from '@/lib/actions/topic';
+import {
+ deleteTopic,
+ getPromptCountByTopic,
+ getTopicsOverview,
+ type TopicOverviewRow,
+} from '@/lib/actions/topic';
import { TOPIC_NAME_CHARS } from '@/lib/topic-names';
import { customUtcWindow } from '@/lib/topic-trend';
import type { PromptRange, PromptRangePreset } from '@/config/prompt-options';
@@ -34,6 +39,12 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Button, buttonVariants } from '@/components/ui/button';
@@ -46,9 +57,11 @@ import {
Flame,
Layers,
Minus,
+ MoreHorizontal,
RotateCw,
Settings2,
Tag,
+ Trash2,
TrendingDown,
TrendingUp,
Trophy,
@@ -210,6 +223,32 @@ function SortableHead({
);
}
+// ─── Row menu ────────────────────────────────────────────────────────────
+
+/** How long a deleted topic can be put back; it is deleted for real after. */
+const DELETE_UNDO_MS = 10_000;
+
+/** A leaderboard row's "…" menu, for admins and managers. */
+function TopicRowMenu({ name, onDelete }: { name: string; onDelete: () => void }) {
+ const t = useTranslations('topics.rowMenu');
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ aria-label={t('label', { name })}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 className="h-3.5 w-3.5" />
+ {t('delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
// ─── Tab ─────────────────────────────────────────────────────────────────
/**
@@ -249,7 +288,7 @@ export function TopicsTab({
// A read-only workspace (plan not active): Add Topic opens the upgrade dialog instead.
const { guard } = useUpgradeGate();
const tActions = useTranslations('readOnly.actions');
- const [topics, setTopics] = useState<TopicOverviewRow[]>([]);
+ const [loadedTopics, setTopics] = useState<TopicOverviewRow[]>([]);
const [unassignedPromptCount, setUnassignedPromptCount] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -257,6 +296,25 @@ export function TopicsTab({
const [newName, setNewName] = useState('');
const [open, setOpen] = useState(false);
const openAddTopic = guard(() => setOpen(true), { action: tActions('addTopics') });
+ const tDelete = useTranslations('topics.delete');
+ // The topic whose delete is being confirmed, and the prompts each topic
+ // holds, paused ones too, read as its dialog opens ('failed' if they
+ // couldn't be). Deleting moves all of them to no topic, not only the active
+ // ones the Prompts column counts.
+ const [confirmDelete, setConfirmDelete] = useState<TopicOverviewRow | null>(null);
+ // Kept apart from the topic, so the dialog's text stays while it closes.
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [deleteCounts, setDeleteCounts] = useState<Record<string, number | 'failed'>>({});
+ // Topics deleted from the row menu, hidden at once and deleted for real
+ // after the Undo window, as the Prompts tab deletes prompts (PROMPT-006):
+ // an Undo inside it changes nothing in the database. A deleted topic stays
+ // in the set, so a read that started before the delete can't show it again.
+ const [pendingDeletes, setPendingDeletes] = useState<Set<string>>(() => new Set());
+ const deleteTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
+ const topics = useMemo(
+ () => loadedTopics.filter((topic) => !pendingDeletes.has(topic.id)),
+ [loadedTopics, pendingDeletes],
+ );
// Default matches the previous hard-coded order (#597): visibility descending.
const [sortKey, setSortKey] = useState<TopicSortKey>('visibility');
const [sortDir, setSortDir] = useState<SortDir>('desc');
@@ -310,6 +368,26 @@ export function TopicsTab({
loadData();
}, [loadData]);
+ // A delete lands after its Undo window, and reads the tab again with the
+ // range picked by then.
+ const loadDataRef = useRef(loadData);
+ useEffect(() => {
+ loadDataRef.current = loadData;
+ }, [loadData]);
+
+ // A pending delete still lands if the tab unmounts inside the window
+ // (switching tabs); only an Undo or closing the page stops it.
+ useEffect(() => {
+ const timers = deleteTimers.current;
+ return () => {
+ for (const [id, timer] of timers) {
+ clearTimeout(timer);
+ deleteTopic(id).catch((err) => console.error('Failed to delete the topic', err));
+ }
+ timers.clear();
+ };
+ }, []);
+
const sortedTopics = useMemo(() => {
const valueOf = (row: TopicOverviewRow): number | null => {
switch (sortKey) {
@@ -408,7 +486,8 @@ export function TopicsTab({
if (isAdding) return;
const name = newName.trim();
if (!name) return;
- if (topics.some((t) => t.name.toLowerCase() === name.toLowerCase())) {
+ // A topic waiting out its Undo window still exists.
+ if (loadedTopics.some((t) => t.name.toLowerCase() === name.toLowerCase())) {
toast.error(t('topicAlreadyExists'));
return;
}
@@ -426,6 +505,64 @@ export function TopicsTab({
}
};
+ const askDelete = (topic: TopicOverviewRow) => {
+ setConfirmDelete(topic);
+ setConfirmOpen(true);
+ setDeleteCounts((counts) => {
+ const next = { ...counts };
+ delete next[topic.id];
+ return next;
+ });
+ getPromptCountByTopic(activeBrandId, topic.id).then(
+ (count) => setDeleteCounts((counts) => ({ ...counts, [topic.id]: count })),
+ () => setDeleteCounts((counts) => ({ ...counts, [topic.id]: 'failed' })),
+ );
+ };
+
+ const restoreTopic = (id: string) =>
+ setPendingDeletes((set) => {
+ const next = new Set(set);
+ next.delete(id);
+ return next;
+ });
+
+ const runDelete = async (topic: TopicOverviewRow) => {
+ try {
+ await deleteTopic(topic.id);
+ } catch (err) {
+ console.error('Failed to delete the topic', err);
+ restoreTopic(topic.id);
+ toast.error(tDelete('failed', { name: topic.name }));
+ return;
+ }
+ // Its prompts now count as prompts without a topic.
+ await loadDataRef.current();
+ };
+
+ const undoDelete = (id: string) => {
+ const timer = deleteTimers.current.get(id);
+ if (timer === undefined) return;
+ clearTimeout(timer);
+ deleteTimers.current.delete(id);
+ restoreTopic(id);
+ };
+
+ const deleteWithUndo = (topic: TopicOverviewRow) => {
+ setPendingDeletes((set) => new Set(set).add(topic.id));
+ const timer = setTimeout(() => {
+ deleteTimers.current.delete(topic.id);
+ void runDelete(topic);
+ }, DELETE_UNDO_MS);
+ deleteTimers.current.set(topic.id, timer);
+ toast(tDelete('deleted'), {
+ description: topic.name,
+ duration: DELETE_UNDO_MS,
+ action: { label: tDelete('undo'), onClick: () => undoDelete(topic.id) },
+ });
+ };
+
+ const deleteCount = confirmDelete ? deleteCounts[confirmDelete.id] : undefined;
+
return (
<div className="space-y-6">
{actionsSlot &&
@@ -504,6 +641,39 @@ export function TopicsTab({
</DialogContent>
</Dialog>
)}
+ {canManage && (
+ <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="break-words text-base">
+ {tDelete('title', { name: confirmDelete?.name ?? '' })}
+ </DialogTitle>
+ <DialogDescription className="break-words">
+ {deleteCount === undefined
+ ? tDelete('counting')
+ : deleteCount === 'failed'
+ ? tDelete('promptsKept')
+ : tDelete('prompts', { count: deleteCount })}{' '}
+ {tDelete('undoHint')}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>{tDelete('keep')}</DialogClose>
+ <Button
+ variant="destructive"
+ disabled={deleteCount === undefined}
+ onClick={() => {
+ if (confirmDelete) deleteWithUndo(confirmDelete);
+ setConfirmOpen(false);
+ }}
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ {tDelete('confirm')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )}
{/* KPIs */}
{loading ? (
@@ -767,14 +937,26 @@ export function TopicsTab({
<TableCell className="text-right text-xs text-muted-foreground">
{formatRelative(topic.lastRunAt, common)}
</TableCell>
- <TableCell className="pr-6 text-right">
- <Link
- href={`/dashboard/prompts/topics/${topic.id}`}
- className="inline-flex opacity-0 group-hover:opacity-100 transition-opacity"
- aria-label={t('openDetails')}
- >
- <ArrowRight className="h-4 w-4 text-muted-foreground" />
- </Link>
+ {/* The menu's own padding stands in for the cell's, so the
+ table still fits at 1024px. */}
+ <TableCell className={cn('text-right', canManage ? 'pr-3' : 'pr-6')}>
+ <div className="flex items-center justify-end">
+ <Link
+ href={`/dashboard/prompts/topics/${topic.id}`}
+ className="inline-flex opacity-0 group-hover:opacity-100 transition-opacity"
+ aria-label={t('openDetails')}
+ >
+ <ArrowRight className="h-4 w-4 text-muted-foreground" />
+ </Link>
+ {canManage && (
+ <TopicRowMenu
+ name={topic.name}
+ onDelete={guard(() => askDelete(topic), {
+ action: tActions('deleteTopics'),
+ })}
+ />
+ )}
+ </div>
</TableCell>
</TableRow>
))}
diff --git a/web/src/lib/actions/topic.test.ts b/web/src/lib/actions/topic.test.ts
index eb1310468..c2c4e9a68 100644
--- a/web/src/lib/actions/topic.test.ts
+++ b/web/src/lib/actions/topic.test.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
/**
@@ -12,23 +14,42 @@ let calls: { fn: string; args: Record<string, unknown> }[] = [];
let windowRows: Record<string, unknown>[] | 'missing' = [];
let fixedRows: Record<string, unknown>[] = [];
+// The signed-in member's role, for deleteTopic.
+let role: string | null = 'admin';
const tables: Record<string, unknown[]> = {
- topics: [{ id: 't1', name: 'Espresso', created_at: '2026-01-01T00:00:00Z' }],
+ topics: [{ id: 't1', name: 'Espresso', brand_id: 'b1', created_at: '2026-01-01T00:00:00Z' }],
prompt_sets: [{ id: 's1' }],
prompts: [
{ id: 'p1', topic_id: 't1' },
{ id: 'p2', topic_id: 't1' },
],
};
+/** Every delete and update asked for, by table. */
+let writes: { table: string; op: string }[] = [];
-/** A query builder whose every call chains, resolving to the table's rows. */
+/**
+ * A query builder whose every call chains, resolving to the table's rows
+ * (single and maybeSingle to the first one).
+ */
function query(table: string): unknown {
- const result = { data: tables[table] ?? [], error: null };
+ const rows = table === 'profiles' ? [{ role }] : (tables[table] ?? []);
+ const resolveTo = (data: unknown) => ({
+ then: (resolve: (value: unknown) => void) => resolve({ data, error: null }),
+ });
const builder: unknown = new Proxy(
{},
{
- get: (_, prop) =>
- prop === 'then' ? (resolve: (value: unknown) => void) => resolve(result) : () => builder,
+ get: (_, prop) => {
+ if (prop === 'then') return resolveTo(rows).then;
+ if (prop === 'single' || prop === 'maybeSingle') return () => resolveTo(rows[0] ?? null);
+ if (prop === 'delete' || prop === 'update') {
+ return () => {
+ writes.push({ table, op: prop });
+ return builder;
+ };
+ }
+ return () => builder;
+ },
},
);
return builder;
@@ -36,6 +57,7 @@ function query(table: string): unknown {
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
from: (table: string) => query(table),
rpc: async (fn: string, args: Record<string, unknown>) => {
calls.push({ fn, args });
@@ -72,6 +94,8 @@ const shared = {
beforeEach(() => {
calls = [];
+ writes = [];
+ role = 'admin';
const today = new Date().toISOString().slice(0, 10);
windowRows = [
{
@@ -153,3 +177,35 @@ describe('topic names', () => {
await expect(createTopic('b1', ` ${'x'.repeat(100)} `)).resolves.toBeDefined();
});
});
+
+describe('deleteTopic', () => {
+ it('lets an admin or a manager delete a topic, and never deletes its prompts', async () => {
+ const { deleteTopic } = await import('./topic');
+ for (const r of ['admin', 'manager']) {
+ role = r;
+ writes = [];
+ await expect(deleteTopic('t1')).resolves.toBeUndefined();
+ expect(writes).toContainEqual({ table: 'topics', op: 'delete' });
+ expect(writes).not.toContainEqual({ table: 'prompts', op: 'delete' });
+ }
+ });
+
+ it('refuses an analyst or an agency partner before anything is written', async () => {
+ const { deleteTopic } = await import('./topic');
+ for (const r of ['analyst', 'agency_partner', null]) {
+ role = r;
+ await expect(deleteTopic('t1')).rejects.toThrow(
+ 'Only an admin or a manager can delete topics.',
+ );
+ }
+ expect(writes).toEqual([]);
+ });
+
+ it("keeps the topic's prompts in the database: their topic is set to none", () => {
+ // The delete leans on this rule to keep the prompts and their results.
+ const schema = readFileSync(join(__dirname, '../../../../supabase/schema.sql'), 'utf8');
+ expect(schema).toMatch(
+ /"prompts_topic_id_fkey" FOREIGN KEY \("topic_id"\) REFERENCES "public"\."topics"\("id"\) ON DELETE SET NULL/,
+ );
+ });
+});
diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.ts
index c7202a0ab..ae64570e4 100644
--- a/web/src/lib/actions/topic.ts
+++ b/web/src/lib/actions/topic.ts
@@ -6,6 +6,7 @@ import { API_BASE_URL } from '@/config/api';
import type { Topic } from '@/types';
import { DAY_MS, topicTrendDays, type TopicsWindow } from '@/lib/topic-trend';
import { assertWritable } from '@/lib/subscription-guard';
+import { MANAGER_ROLES } from '@/lib/mcp/role-gate';
import { TOPIC_NAME_CHARS, topicNameFits } from '@/lib/topic-names';
export type { TopicsWindow } from '@/lib/topic-trend';
@@ -441,10 +442,30 @@ export async function getTopicsOverview(
return { topics: rows, unassignedPromptCount, trendDays };
}
+/**
+ * Deletes a topic for an admin or a manager. Its prompts stay, with their
+ * results: prompts.topic_id is ON DELETE SET NULL, so they become prompts
+ * without a topic. The topics table's row rules let every member write, so
+ * the role is checked here.
+ */
export async function deleteTopic(topicId: string): Promise<void> {
await assertWritable();
const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ if (!user) throw new Error('Unauthorized');
+ const { data: profile, error: profileErr } = await supabase
+ .from('profiles')
+ .select('role')
+ .eq('id', user.id)
+ .maybeSingle();
+ if (profileErr) throw new Error(profileErr.message);
+ if (!MANAGER_ROLES.some((role) => role === profile?.role)) {
+ throw new Error('Only an admin or a manager can delete topics.');
+ }
+
// Fetch topic to get name and brand_id
const { data: topic, error: fetchErr } = await supabase
.from('topics')