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): add a bulk action bar for selected prompts (#1029)

Cihanefe332e58aa4
diff --git a/web/messages/en.json b/web/messages/en.json
index 170b6058f..2d77bc387 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2088,6 +2088,13 @@
"platformsAndModels": "Platform & Models",
"selectPlatformsAndModels": "Select platform & models",
"selectedCount": "{count} selected"
+ },
+ "bulkDelete": {
+ "progress": "Deleting {done} of {total} prompts…",
+ "failed": "{count, plural, one {Failed to delete the prompt.} other {Failed to delete the prompts.}}",
+ "stopped": "{deleted} of {total} prompts deleted",
+ "stoppedDescription": "Deleting stopped at an error. {kept, plural, one {The other prompt is} other {The other # prompts are}} back in the list, so you can try again.",
+ "notDeleted": "{kept} of {total} {total, plural, one {prompt} other {prompts}} couldn't be deleted."
}
},
"competitors": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx
new file mode 100644
index 000000000..354f61016
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_bulk-action-bar.tsx
@@ -0,0 +1,127 @@
+'use client';
+
+import { Lightbulb, Loader2, Pause, Play, Trash2, X } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+
+/**
+ * The prompts table's bulk action bar (PROMPT-006): shown while rows are
+ * selected, with the row menu's own actions for all of them at once. Pause
+ * and Resume each show only when some selected prompt can take them. While a
+ * bulk delete runs, a few prompts per call, it shows how far it has got, even
+ * with nothing selected.
+ */
+export function BulkActionBar({
+ count,
+ activeCount,
+ busy,
+ suggesting,
+ suggestBlockedReason,
+ deleting,
+ onPause,
+ onResume,
+ onSuggestContent,
+ onDelete,
+ onClear,
+}: {
+ count: number;
+ /** How many of the selected prompts are being tracked now. */
+ activeCount: number;
+ /** A pause, resume or suggestion run is going; the actions wait for it. */
+ busy: boolean;
+ suggesting: boolean;
+ /** Why Suggest content can't take this selection now; null when it can. */
+ suggestBlockedReason: string | null;
+ /** How far the delete that is running has got; null when none is. */
+ deleting: { done: number; total: number } | null;
+ onPause: () => void;
+ onResume: () => void;
+ onSuggestContent: () => void;
+ onDelete: () => void;
+ onClear: () => void;
+}) {
+ const t = useTranslations('prompts.bulkDelete');
+ const pausedCount = count - activeCount;
+ const progress = deleting && (
+ <span role="status" className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t('progress', deleting)}
+ </span>
+ );
+ // Nothing selected: only the delete's progress, at the bar's usual height.
+ if (count === 0) {
+ return <div className="flex h-11 items-center border-b bg-muted/50 px-4">{progress}</div>;
+ }
+ return (
+ <div
+ role="toolbar"
+ aria-label="Actions for the selected prompts"
+ className="flex flex-wrap items-center gap-2 border-b bg-muted/50 px-4 py-2"
+ >
+ <span className="text-xs font-medium">{count} selected</span>
+ {progress}
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-1">
+ {activeCount > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={onPause}
+ disabled={busy}
+ >
+ <Pause className="h-3 w-3" />
+ Pause{pausedCount > 0 ? ` ${activeCount}` : ''}
+ </Button>
+ )}
+ {pausedCount > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={onResume}
+ disabled={busy}
+ >
+ <Play className="h-3 w-3" />
+ Resume{activeCount > 0 ? ` ${pausedCount}` : ''}
+ </Button>
+ )}
+ {suggestBlockedReason && !suggesting && (
+ <span className="px-1 text-[11px] text-muted-foreground">{suggestBlockedReason}</span>
+ )}
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={onSuggestContent}
+ disabled={busy || suggestBlockedReason !== null}
+ >
+ {suggesting ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Lightbulb className="h-3 w-3" />
+ )}
+ Suggest content
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1.5 text-xs text-red-600 hover:text-red-600 dark:text-red-400 dark:hover:text-red-400"
+ onClick={onDelete}
+ disabled={busy}
+ >
+ <Trash2 className="h-3 w-3" />
+ Delete
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 w-7 p-0"
+ onClick={onClear}
+ aria-label="Clear selection"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 036cf3fd9..c138072a2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -100,9 +100,11 @@ import {
} from '@/lib/actions/volumes';
import {
deletePrompt,
+ deletePrompts,
getPromptsPageData,
importPrompts,
setPromptActive,
+ setPromptsActive,
updatePrompt,
type LocationQuota,
} from '@/lib/actions/prompt';
@@ -139,10 +141,20 @@ import {
suggestContentForPrompt,
} from '@/lib/actions/content';
import { hasContentQuota, type ContentUsage } from '@/lib/content-usage';
-import { waitForContentJob } from '@/lib/content-job';
+import { suggestForPrompt } from '@/lib/content-job';
+import {
+ allSelected,
+ bulkSuggestBlock,
+ bulkSuggestSummary,
+ deleteInBatches,
+ PROMPT_DELETE_BATCH,
+ runInTurn,
+ toggleAll,
+} from '@/lib/prompt-bulk-actions';
import { toCsv } from '@/lib/csv';
import { formatRelative } from '@/lib/format-relative';
import { compareNullsLast, type SortDir } from './prompt-sort';
+import { BulkActionBar } from './_bulk-action-bar';
import { formatCompactNumber } from '@/lib/format';
import { usePagination, TablePager } from '@/components/table-pager';
import { PromptPositionsSheet } from '@/components/prompts/prompt-positions-sheet';
@@ -2423,6 +2435,9 @@ function dotDetail(d: PlatformDot): string {
/** How long a row deleted from its menu can be restored (PROMPT-006). */
const DELETE_UNDO_MS = 10_000;
+/** The server calls behind "Suggest content" (PROMPT-006). */
+const SUGGEST_CALLS = { start: suggestContentForPrompt, getStatus: getGenerationJobStatus };
+
/**
* The row's ⋯ menu (PROMPT-006): Edit, pause or resume tracking, open the
* Positions panel on Improve, suggest content, and Delete behind a
@@ -2450,7 +2465,7 @@ function RowActionsMenu({
onOpenSuggestion: (opportunityId: string) => void;
/** A suggestion for this prompt is being written. */
suggesting: boolean;
- /** Why Suggest content can't run now (the month's quota is used up). */
+ /** Why Suggest content can't run now (the month's quota is used up, or a bulk run is going). */
suggestDisabledReason: string | null;
onDelete: () => void;
}) {
@@ -2572,61 +2587,125 @@ function AllPromptsTab({
onChanged: () => void;
}) {
const tCommon = useTranslations('common');
- // Rows deleted from the row menu, hidden at once and deleted for real after
- // the Undo window (PROMPT-006). There is no soft delete for prompts — a
- // delete drops their history — so the delay is the undo: closing the page
- // inside the window simply leaves the prompt in place.
+ const tDelete = useTranslations('prompts.bulkDelete');
+ // Rows deleted from the row menu or the bulk bar, hidden at once and
+ // deleted for real after the Undo window (PROMPT-006). There is no soft
+ // delete for prompts — a delete drops their history — so the delay is the
+ // undo: closing the page inside the window simply leaves the prompts in place.
const [pendingDeletes, setPendingDeletes] = useState<Set<string>>(() => new Set());
- const deleteTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
- const [confirmDelete, setConfirmDelete] = useState<Prompt | null>(null);
+ // One entry per delete, keyed by its first prompt, with every prompt it hides.
+ const deleteTimers = useRef(
+ new Map<string, { ids: string[]; timer: ReturnType<typeof setTimeout> }>(),
+ );
+ const [confirmDelete, setConfirmDelete] = useState<Prompt[] | null>(null);
const [positionsTab, setPositionsTab] = useState<'platforms' | 'improve'>('platforms');
const prompts = useMemo(
() => allRows.filter((p) => !pendingDeletes.has(p.id)),
[allRows, pendingDeletes],
);
- const undoDelete = useCallback((id: string) => {
- const timer = deleteTimers.current.get(id);
- if (timer) clearTimeout(timer);
- deleteTimers.current.delete(id);
+ const restoreRows = useCallback((ids: string[]) => {
setPendingDeletes((set) => {
const next = new Set(set);
- next.delete(id);
+ for (const id of ids) next.delete(id);
return next;
});
}, []);
+ // Past its Undo window a delete runs a few prompts per call
+ // (deleteInBatches), so no statement outlives the timeout on big brands.
+ // Deletes queue behind each other, one call at a time, and the bulk bar
+ // shows how far the running one has got.
+ const deleteQueue = useRef<Promise<void>>(Promise.resolve());
+ const [deleteProgress, setDeleteProgress] = useState<{ done: number; total: number } | null>(
+ null,
+ );
+
+ const runDelete = useCallback(
+ async (ids: string[]) => {
+ setDeleteProgress({ done: 0, total: ids.length });
+ const result = await deleteInBatches(ids, deletePrompts, (done) =>
+ setDeleteProgress({ done, total: ids.length }),
+ );
+ // Prompts still there (a call failed, or RLS left them out) come back
+ // into view; the ones deleted before a failure stay deleted.
+ const kept = result.keptIds.length;
+ if (kept > 0) restoreRows(result.keptIds);
+ if (result.failed && result.deletedIds.length === 0) {
+ toast.error(tDelete('failed', { count: ids.length }));
+ return;
+ }
+ if (result.failed) {
+ toast.error(tDelete('stopped', { deleted: result.deletedIds.length, total: ids.length }), {
+ description: tDelete('stoppedDescription', { kept }),
+ });
+ } else if (kept > 0) {
+ toast.error(tDelete('notDeleted', { kept, total: ids.length }));
+ }
+ onChanged();
+ },
+ [onChanged, restoreRows, tDelete],
+ );
+
+ const queueDelete = useCallback(
+ (ids: string[]) => {
+ const run: Promise<void> = deleteQueue.current
+ .then(() => runDelete(ids))
+ .catch(() => undefined)
+ .then(() => {
+ if (deleteQueue.current === run) setDeleteProgress(null);
+ });
+ deleteQueue.current = run;
+ },
+ [runDelete],
+ );
+
+ const undoDelete = useCallback(
+ (key: string) => {
+ const pending = deleteTimers.current.get(key);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ deleteTimers.current.delete(key);
+ restoreRows(pending.ids);
+ },
+ [restoreRows],
+ );
+
const deleteWithUndo = useCallback(
- (prompt: Prompt) => {
- setPendingDeletes((set) => new Set(set).add(prompt.id));
- const timer = setTimeout(async () => {
- deleteTimers.current.delete(prompt.id);
- try {
- await deletePrompt(prompt.id);
- onChanged();
- } catch {
- toast.error('Failed to delete the prompt.');
- undoDelete(prompt.id);
- }
+ (list: Prompt[]) => {
+ if (list.length === 0) return;
+ const ids = list.map((p) => p.id);
+ const key = ids[0];
+ setPendingDeletes((set) => new Set([...set, ...ids]));
+ const timer = setTimeout(() => {
+ deleteTimers.current.delete(key);
+ queueDelete(ids);
}, DELETE_UNDO_MS);
- deleteTimers.current.set(prompt.id, timer);
- toast('Prompt deleted', {
- description: prompt.text,
+ deleteTimers.current.set(key, { ids, timer });
+ toast(ids.length === 1 ? 'Prompt deleted' : `${ids.length} prompts deleted`, {
+ description: ids.length === 1 ? list[0].text : undefined,
duration: DELETE_UNDO_MS,
- action: { label: 'Undo', onClick: () => undoDelete(prompt.id) },
+ action: { label: 'Undo', onClick: () => undoDelete(key) },
});
},
- [onChanged, undoDelete],
+ [queueDelete, undoDelete],
);
// A pending delete still lands if the table unmounts inside the window
- // (switching tabs, changing brand); only an Undo or closing the page stops it.
+ // (switching tabs, changing brand), in the same batches, after any delete
+ // already running; only an Undo or closing the page stops it.
useEffect(() => {
const timers = deleteTimers.current;
+ const queue = deleteQueue;
return () => {
- for (const [id, timer] of timers) {
+ for (const { ids, timer } of timers.values()) {
clearTimeout(timer);
- void deletePrompt(id);
+ queue.current = queue.current
+ .then(() => deleteInBatches(ids, deletePrompts))
+ .then(
+ () => undefined,
+ () => undefined,
+ );
}
timers.clear();
};
@@ -2657,18 +2736,65 @@ function AllPromptsTab({
[onChanged],
);
+ // Bulk Pause / Resume: one write for the selected prompts that change.
+ const [bulkBusy, setBulkBusy] = useState(false);
+ const setActiveFor = useCallback(
+ async (list: Prompt[], isActive: boolean) => {
+ const ids = list.filter((p) => p.isActive !== isActive).map((p) => p.id);
+ if (ids.length === 0) return;
+ setBulkBusy(true);
+ const verb = isActive ? 'resume' : 'pause';
+ try {
+ const result = await setPromptsActive(ids, isActive).catch(() => ({
+ error: 'unreachable',
+ }));
+ if ('error' in result) {
+ // Resuming needs free slots on the plan; the message says how many.
+ const planLimit = 'code' in result && result.code === 'plan_limit';
+ toast.error(
+ planLimit ? 'Not enough room to resume' : `Failed to ${verb} the prompts.`,
+ planLimit ? { description: result.error } : undefined,
+ );
+ return;
+ }
+ if (result.updated > 0) {
+ toast.success(
+ `Tracking ${isActive ? 'resumed' : 'paused'} for ${result.updated} prompt${result.updated === 1 ? '' : 's'}`,
+ );
+ }
+ if (result.updated < ids.length) {
+ toast.error(`${ids.length - result.updated} of ${ids.length} couldn't be ${verb}d.`);
+ }
+ onChanged();
+ } finally {
+ setBulkBusy(false);
+ }
+ },
+ [onChanged],
+ );
+
// "Suggest content" (PROMPT-006): one content opportunity for a prompt,
// against the month's content quota. The quota is read up front so the
// menu can say when nothing is left; the server enforces it either way.
const router = useRouter();
const [contentUsage, setContentUsage] = useState<ContentUsage | null>(null);
+ // The quota couldn't be read; the bulk bar falls back to the smallest cap.
+ const [contentUsageFailed, setContentUsageFailed] = useState(false);
const [usageVersion, setUsageVersion] = useState(0);
const [suggestingIds, setSuggestingIds] = useState<Set<string>>(new Set());
useEffect(() => {
let cancelled = false;
getContentUsage().then(
- (usage) => !cancelled && setContentUsage(usage),
- () => !cancelled && setContentUsage(null),
+ (usage) => {
+ if (cancelled) return;
+ setContentUsage(usage);
+ setContentUsageFailed(false);
+ },
+ () => {
+ if (cancelled) return;
+ setContentUsage(null);
+ setContentUsageFailed(true);
+ },
);
return () => {
cancelled = true;
@@ -2691,94 +2817,134 @@ function AllPromptsTab({
(id: string) => router.push(`/dashboard/content?opportunity=${id}`),
[router],
);
+ const markSuggesting = useCallback((ids: string[], on: boolean) => {
+ setSuggestingIds((set) => {
+ const next = new Set(set);
+ for (const id of ids) {
+ if (on) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ });
+ }, []);
+
const suggestContent = useCallback(
async (prompt: Prompt) => {
// Only a plan with a monthly limit has a quota to say was left alone.
const quotaUntouched = hasOpportunityLimit
? 'Nothing was used from your monthly content quota.'
: undefined;
- setSuggestingIds((set) => new Set(set).add(prompt.id));
+ markSuggesting([prompt.id], true);
const toastId = toast.loading('Writing a content suggestion…', {
description: prompt.text,
});
- // CONTENT-004: an open suggestion already answers this prompt.
- const showExisting = (id: string) =>
- toast.info('This prompt already has a content suggestion', {
- id: toastId,
- description: prompt.text,
- duration: 10_000,
- action: { label: 'Open existing', onClick: () => openOpportunity(id) },
- });
- try {
- const started = await suggestContentForPrompt(prompt.id, crypto.randomUUID());
- if (!started.ok) {
- toast.error(started.quotaExhausted ? 'Monthly content limit reached.' : started.error, {
+ const outcome = await suggestForPrompt(prompt.id, SUGGEST_CALLS);
+ markSuggesting([prompt.id], false);
+ setUsageVersion((v) => v + 1);
+ switch (outcome.kind) {
+ case 'created':
+ toast.success('Content suggestion created', {
id: toastId,
description: prompt.text,
+ duration: 10_000,
+ action: { label: 'Open', onClick: () => openOpportunity(outcome.opportunityId) },
});
- return;
- }
- if ('existingId' in started) {
- showExisting(started.existingId);
- return;
- }
-
- const outcome = await waitForContentJob(started.jobId, {
- getStatus: getGenerationJobStatus,
- });
- if (outcome.kind === 'completed') {
- const createdId = outcome.result.opportunityIds?.[0];
- if (createdId) {
- toast.success('Content suggestion created', {
- id: toastId,
- description: prompt.text,
- duration: 10_000,
- action: { label: 'Open', onClick: () => openOpportunity(createdId) },
- });
- } else if (outcome.result.existingId) {
- // Covered while the job ran, e.g. once the prompt was regrouped.
- showExisting(outcome.result.existingId);
- } else if (outcome.result.limited) {
- toast.error('Monthly content limit reached.', { id: toastId });
- } else {
- toast.info("Couldn't write a suggestion for this prompt yet", {
- id: toastId,
- // Not grouped with other prompts yet, or no answers to go on.
- description: [
- 'It needs tracked answers and a prompt group first; both come with its next tracking run.',
- quotaUntouched,
- ]
- .filter(Boolean)
- .join(' '),
- });
- }
- } else if (outcome.kind === 'failed') {
+ break;
+ case 'existing':
+ // CONTENT-004: an open suggestion already answers this prompt.
+ toast.info('This prompt already has a content suggestion', {
+ id: toastId,
+ description: prompt.text,
+ duration: 10_000,
+ action: {
+ label: 'Open existing',
+ onClick: () => openOpportunity(outcome.opportunityId),
+ },
+ });
+ break;
+ case 'limited':
+ toast.error('Monthly content limit reached.', { id: toastId, description: prompt.text });
+ break;
+ case 'nothing':
+ toast.info("Couldn't write a suggestion for this prompt yet", {
+ id: toastId,
+ // Not grouped with other prompts yet, or no answers to go on.
+ description: [
+ 'It needs tracked answers and a prompt group first; both come with its next tracking run.',
+ quotaUntouched,
+ ]
+ .filter(Boolean)
+ .join(' '),
+ });
+ break;
+ case 'failed':
toast.error("Couldn't write a content suggestion", {
id: toastId,
- description: quotaUntouched,
+ description: [outcome.message, quotaUntouched].filter(Boolean).join(' ') || undefined,
});
- } else {
+ break;
+ case 'timeout':
toast.info('Still writing the content suggestion', {
id: toastId,
description: 'It will appear in Content when it is done.',
});
- }
- } catch (err) {
- // Nothing may be left spinning, whatever went wrong on the way.
- toast.error("Couldn't write a content suggestion", {
- id: toastId,
- description: err instanceof Error ? err.message : quotaUntouched,
- });
- } finally {
- setSuggestingIds((set) => {
- const next = new Set(set);
- next.delete(prompt.id);
- return next;
- });
- setUsageVersion((v) => v + 1);
+ break;
}
},
- [openOpportunity, hasOpportunityLimit],
+ [hasOpportunityLimit, markSuggesting, openOpportunity],
+ );
+
+ // Bulk "Suggest content": one prompt after another (runInTurn), so a
+ // prompt whose group got a suggestion a moment ago is answered by that one,
+ // at no cost.
+ const [bulkSuggesting, setBulkSuggesting] = useState(false);
+ const suggestFor = useCallback(
+ async (list: Prompt[]) => {
+ if (list.length === 0) return;
+ setBulkSuggesting(true);
+ markSuggesting(
+ list.map((p) => p.id),
+ true,
+ );
+ const toastId = toast.loading(`Writing content suggestions… 1 of ${list.length}`, {
+ description: list[0].text,
+ });
+ const tally = await runInTurn(list, async (prompt, i) => {
+ if (i > 0) {
+ toast.loading(`Writing content suggestions… ${i + 1} of ${list.length}`, {
+ id: toastId,
+ description: prompt.text,
+ });
+ }
+ const outcome = await suggestForPrompt(prompt.id, SUGGEST_CALLS);
+ markSuggesting([prompt.id], false);
+ return outcome;
+ });
+ markSuggesting(
+ list.map((p) => p.id),
+ false,
+ );
+ setBulkSuggesting(false);
+ setUsageVersion((v) => v + 1);
+
+ const summary = bulkSuggestSummary(tally);
+ const opened = tally.created.length > 0 ? tally.created : tally.existing;
+ toast[summary.tone](summary.title, {
+ id: toastId,
+ description: summary.description,
+ duration: 10_000,
+ action:
+ opened.length === 1
+ ? {
+ label: tally.created.length > 0 ? 'Open' : 'Open existing',
+ onClick: () => openOpportunity(opened[0]),
+ }
+ : opened.length > 1
+ ? { label: 'Open Content', onClick: () => router.push('/dashboard/content') }
+ : undefined,
+ });
+ },
+ [markSuggesting, openOpportunity, router],
);
const [search, setSearch] = useState('');
const [workFilter, setWorkFilter] = useState<'all' | 'none' | PromptWorkStatus>('all');
@@ -2947,6 +3113,31 @@ function AllPromptsTab({
const promptsResetKey = `${search}::${workFilter}::${lateOnly}::${activeSort}::${dir}`;
const promptsPager = usePagination(filtered.length, promptsResetKey);
+ // Rows ticked for the bulk action bar. Only rows on screen can be ticked,
+ // so the selection starts over whenever the rows on screen change.
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());
+ const selectionKey = [
+ activeBrandId,
+ promptsResetKey,
+ promptsPager.page,
+ regionFilter,
+ positionsWindow.from,
+ positionsWindow.to ?? '',
+ ].join('::');
+ const [prevSelectionKey, setPrevSelectionKey] = useState(selectionKey);
+ if (prevSelectionKey !== selectionKey) {
+ setPrevSelectionKey(selectionKey);
+ setSelectedIds(new Set());
+ }
+ const toggleRow = useCallback((id: string, on: boolean) => {
+ setSelectedIds((set) => {
+ const next = new Set(set);
+ if (on) next.add(id);
+ else next.delete(id);
+ return next;
+ });
+ }, []);
+
if (loading) {
return (
<div className="flex items-center justify-center py-10">
@@ -2985,6 +3176,12 @@ function AllPromptsTab({
);
}
+ const pageRows = filtered.slice(promptsPager.start, promptsPager.end);
+ const pageIds = pageRows.map((p) => p.id);
+ const selectedPrompts = pageRows.filter((p) => selectedIds.has(p.id));
+ // A delete that fits in one call is over before the bar could say so.
+ const showDeleteProgress = deleteProgress !== null && deleteProgress.total > PROMPT_DELETE_BATCH;
+
return (
<Card>
<CardHeader className="pb-3">
@@ -3044,10 +3241,45 @@ function AllPromptsTab({
</div>
</CardHeader>
<CardContent className="p-0">
+ {onEditPrompt && (selectedPrompts.length > 0 || showDeleteProgress) && (
+ <BulkActionBar
+ count={selectedPrompts.length}
+ activeCount={selectedPrompts.filter((p) => p.isActive).length}
+ busy={bulkBusy || bulkSuggesting}
+ suggesting={bulkSuggesting}
+ suggestBlockedReason={
+ suggestDisabledReason ??
+ (!bulkSuggesting && suggestingIds.size > 0
+ ? 'Wait for the suggestion being written'
+ : bulkSuggestBlock(selectedPrompts.length, contentUsage, {
+ unavailable: contentUsageFailed,
+ }))
+ }
+ deleting={showDeleteProgress ? deleteProgress : null}
+ onPause={() => void setActiveFor(selectedPrompts, false)}
+ onResume={() => void setActiveFor(selectedPrompts, true)}
+ onSuggestContent={() => void suggestFor(selectedPrompts)}
+ onDelete={() => setConfirmDelete(selectedPrompts)}
+ onClear={() => setSelectedIds(new Set())}
+ />
+ )}
<Table stickyHeader stickyFirstColumn>
<TableHeader>
<TableRow>
- <TableHead className="pl-6">Prompt</TableHead>
+ <TableHead className="pl-6">
+ {onEditPrompt ? (
+ <div className="flex items-center gap-3">
+ <Checkbox
+ checked={allSelected(pageIds, selectedIds)}
+ onCheckedChange={() => setSelectedIds(toggleAll(pageIds, selectedIds))}
+ aria-label="Select every prompt on this page"
+ />
+ Prompt
+ </div>
+ ) : (
+ 'Prompt'
+ )}
+ </TableHead>
<TableHead>Topic</TableHead>
<TableHead className="text-center">Status</TableHead>
<ColHead
@@ -3140,18 +3372,28 @@ function AllPromptsTab({
</TableRow>
</TableHeader>
<TableBody>
- {filtered.slice(promptsPager.start, promptsPager.end).map((p) => {
+ {pageRows.map((p) => {
const vol = volumeByPromptId.get(p.id);
const vis = visibility[p.id];
return (
<TableRow key={p.id} className="hover:bg-muted/50">
<TableCell className="pl-6 font-medium text-sm max-w-[320px]">
- <Link
- href={`/dashboard/prompts/${p.id}`}
- className="line-clamp-2 transition-colors hover:text-primary hover:underline"
- >
- {p.text}
- </Link>
+ <div className="flex items-start gap-3">
+ {onEditPrompt && (
+ <Checkbox
+ className="mt-0.5"
+ checked={selectedIds.has(p.id)}
+ onCheckedChange={(v) => toggleRow(p.id, v === true)}
+ aria-label={`Select ${p.text}`}
+ />
+ )}
+ <Link
+ href={`/dashboard/prompts/${p.id}`}
+ className="line-clamp-2 transition-colors hover:text-primary hover:underline"
+ >
+ {p.text}
+ </Link>
+ </div>
</TableCell>
<TableCell>
<span className="text-xs text-muted-foreground truncate inline-block max-w-[140px] align-middle">
@@ -3297,8 +3539,11 @@ function AllPromptsTab({
onSuggestContent={() => void suggestContent(p)}
onOpenSuggestion={openOpportunity}
suggesting={suggestingIds.has(p.id)}
- suggestDisabledReason={suggestDisabledReason}
- onDelete={() => setConfirmDelete(p)}
+ suggestDisabledReason={
+ suggestDisabledReason ??
+ (bulkSuggesting ? 'Wait for the selected prompts' : null)
+ }
+ onDelete={() => setConfirmDelete([p])}
/>
</TableCell>
)}
@@ -3333,21 +3578,38 @@ function AllPromptsTab({
<Dialog open={confirmDelete !== null} onOpenChange={(v) => !v && setConfirmDelete(null)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle className="text-base">Delete prompt and its history?</DialogTitle>
+ <DialogTitle className="text-base">
+ {confirmDelete && confirmDelete.length > 1
+ ? `Delete ${confirmDelete.length} prompts and their history?`
+ : 'Delete prompt and its history?'}
+ </DialogTitle>
<DialogDescription className="break-words">
- &ldquo;{confirmDelete?.text}&rdquo; and its tracking results will be removed. You can
- undo for 10 seconds.
+ {confirmDelete && confirmDelete.length > 1 ? (
+ <>These prompts and their tracking results will be removed.</>
+ ) : (
+ <>
+ &ldquo;{confirmDelete?.[0]?.text}&rdquo; and its tracking results will be removed.
+ </>
+ )}{' '}
+ You can undo for 10 seconds.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setConfirmDelete(null)}>
- Keep it
+ {confirmDelete && confirmDelete.length > 1 ? 'Keep them' : 'Keep it'}
</Button>
<Button
type="button"
variant="destructive"
onClick={() => {
- if (confirmDelete) deleteWithUndo(confirmDelete);
+ if (confirmDelete) {
+ deleteWithUndo(confirmDelete);
+ setSelectedIds((set) => {
+ const next = new Set(set);
+ for (const p of confirmDelete) next.delete(p.id);
+ return next;
+ });
+ }
setConfirmDelete(null);
}}
>
diff --git a/web/src/lib/actions/prompt-bulk-delete.test.ts b/web/src/lib/actions/prompt-bulk-delete.test.ts
new file mode 100644
index 000000000..d07f50feb
--- /dev/null
+++ b/web/src/lib/actions/prompt-bulk-delete.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * deletePrompts takes a few prompts per call (PROMPT-006): each prompt's
+ * answers and citations go with it, and a whole page in one statement outran
+ * the 8-second timeout on big brands. The page calls it in turn.
+ */
+
+let deleted: string[][] = [];
+let visible: Set<string>;
+let failWith: string | null = null;
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: vi.fn() }));
+vi.mock('@/lib/actions/tracking', () => ({ getPromptVisibilitySummaries: vi.fn() }));
+vi.mock('@/lib/guards/plan-guard', () => ({ getOrgPlan: vi.fn() }));
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: () => ({
+ delete: () => ({
+ in: (_column: string, ids: string[]) => ({
+ select: async () => {
+ if (failWith) return { data: null, error: { message: failWith } };
+ deleted.push(ids);
+ // RLS leaves out the prompts the caller can't see.
+ return { data: ids.filter((id) => visible.has(id)).map((id) => ({ id })), error: null };
+ },
+ }),
+ }),
+ }),
+ })),
+}));
+
+const { deletePrompts } = await import('./prompt');
+const { PROMPT_DELETE_BATCH } = await import('@/lib/prompt-bulk-actions');
+
+describe('deletePrompts', () => {
+ beforeEach(() => {
+ deleted = [];
+ visible = new Set(['p1', 'p2', 'p3', 'p4']);
+ failWith = null;
+ });
+
+ it('deletes one batch and returns the ids RLS let through', async () => {
+ visible.delete('p2');
+ const result = await deletePrompts(['p1', 'p2', 'p3']);
+ expect(result).toEqual({ deletedIds: ['p1', 'p3'] });
+ expect(deleted).toEqual([['p1', 'p2', 'p3']]);
+ });
+
+ it('refuses more than a batch in one call, and deletes nothing', async () => {
+ const ids = Array.from({ length: PROMPT_DELETE_BATCH + 1 }, (_, i) => `p${i + 1}`);
+ const result = await deletePrompts(ids);
+ expect(result).toEqual({ error: `At most ${PROMPT_DELETE_BATCH} prompts per call.` });
+ expect(deleted).toEqual([]);
+ });
+
+ it('returns a database error as a value', async () => {
+ failWith = 'canceling statement due to statement timeout';
+ const result = await deletePrompts(['p1']);
+ expect(result).toEqual({ error: 'canceling statement due to statement timeout' });
+ });
+
+ it('makes no call for an empty list', async () => {
+ expect(await deletePrompts([])).toEqual({ deletedIds: [] });
+ expect(deleted).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/prompt-bulk-resume.test.ts b/web/src/lib/actions/prompt-bulk-resume.test.ts
new file mode 100644
index 000000000..e60b797ae
--- /dev/null
+++ b/web/src/lib/actions/prompt-bulk-resume.test.ts
@@ -0,0 +1,100 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { PLANS, type Plan } from '@/config/plans';
+
+/**
+ * setPromptsActive meters a bulk resume as setPromptActive meters one (00128):
+ * the paused prompts among the selection bring all their locations back, and
+ * when the plan has no room for them nothing is written. Pausing is never
+ * metered.
+ */
+
+let rows: { id: string; regions: string[]; is_active: boolean }[] = [];
+let usedLocations = 0;
+let plan: Plan;
+let writes: unknown[] = [];
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+vi.mock('@/lib/actions/volumes', () => ({ getPromptVolumes: vi.fn() }));
+vi.mock('@/lib/actions/tracking', () => ({ getPromptVisibilitySummaries: vi.fn() }));
+
+vi.mock('@/lib/guards/plan-guard', () => ({
+ getOrgPlan: vi.fn(async () => plan),
+}));
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ rpc: async () => ({ data: [{ brand_id: 'b1', locations: usedLocations }], error: null }),
+ from: () => ({
+ select: () => ({
+ in: async () => ({
+ data: rows.map((r) => ({ ...r, prompt_sets: { brands: { organization_id: 'org-1' } } })),
+ error: null,
+ }),
+ }),
+ update: (payload: Record<string, unknown>) => {
+ writes.push(payload);
+ return {
+ in: (_column: string, ids: string[]) => ({
+ select: async () => ({ data: ids.map((id) => ({ id })), error: null }),
+ }),
+ };
+ },
+ }),
+ })),
+}));
+
+const { setPromptsActive } = await import('./prompt');
+
+const capped = (maxPrompts: number): Plan => ({
+ ...PLANS.starter,
+ limits: { ...PLANS.starter.limits, maxPrompts },
+});
+
+describe('setPromptsActive', () => {
+ beforeEach(() => {
+ writes = [];
+ plan = capped(50);
+ });
+
+ it('refuses a bulk resume whose paused locations no longer fit, and writes nothing', async () => {
+ // Two paused prompts with 2 + 3 locations; only 4 slots are left.
+ rows = [
+ { id: 'p1', regions: ['US', 'DE'], is_active: false },
+ { id: 'p2', regions: ['US', 'DE', 'TR'], is_active: false },
+ ];
+ usedLocations = 46;
+
+ const result = await setPromptsActive(['p1', 'p2'], true);
+ expect(result).toMatchObject({ code: 'plan_limit' });
+ expect('error' in result && result.error).toMatch(/Remove or pause 1 location/);
+ expect(writes).toEqual([]);
+ });
+
+ it('resumes them when the plan has room, counting only the paused ones', async () => {
+ rows = [
+ { id: 'p1', regions: ['US', 'DE'], is_active: false },
+ // Already active: resuming it adds nothing.
+ { id: 'p2', regions: ['US', 'DE', 'TR'], is_active: true },
+ ];
+ usedLocations = 48;
+
+ await expect(setPromptsActive(['p1', 'p2'], true)).resolves.toEqual({ updated: 2 });
+ expect(writes).toEqual([{ is_active: true }]);
+ });
+
+ it('always lets prompts be paused, even over the limit', async () => {
+ rows = [{ id: 'p1', regions: ['US'], is_active: true }];
+ usedLocations = 60;
+
+ await expect(setPromptsActive(['p1'], false)).resolves.toEqual({ updated: 1 });
+ expect(writes).toEqual([{ is_active: false }]);
+ });
+
+ it('never limits unlimited plans', async () => {
+ plan = capped(-1);
+ rows = [{ id: 'p1', regions: ['US', 'DE'], is_active: false }];
+ usedLocations = 10_000;
+
+ await expect(setPromptsActive(['p1'], true)).resolves.toEqual({ updated: 1 });
+ });
+});
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index 473070a48..76baf0afc 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -12,6 +12,7 @@ import {
promptLocationCount,
} from '@/lib/prompt-locations';
import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';
+import { PROMPT_DELETE_BATCH } from '@/lib/prompt-bulk-actions';
import { isValidLocation, locationCode } from '@/lib/region';
import type { Plan, PlanId } from '@/config/plans';
import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';
@@ -731,6 +732,51 @@ export async function addPromptToBrand(
export type SetPromptActiveResult = { prompt: Prompt } | { error: string; code?: 'plan_limit' };
+type ResumeRow = {
+ regions: unknown;
+ is_active: boolean | null;
+ prompt_sets: unknown;
+};
+
+/**
+ * Whether the plan has room for these prompts to be active: the paused ones
+ * among them bring all their locations back (activationDelta), so resuming is
+ * measured like adding them. Null to allow, or the refusal as a value.
+ */
+async function resumeLimitError(
+ supabase: Awaited<ReturnType<typeof createClient>>,
+ rows: ResumeRow[],
+): Promise<{ error: string; code?: 'plan_limit' } | null> {
+ const adding = activationDelta(
+ rows.map((row) => ({
+ isActive: row.is_active !== false,
+ regions: row.regions as string[] | null,
+ })),
+ );
+ if (adding <= 0) return null;
+ const orgIds = new Set(
+ rows.map(
+ (row) =>
+ (row.prompt_sets as { brands: { organization_id: string } } | null)?.brands
+ ?.organization_id,
+ ),
+ );
+ // One brand's prompts, so one organization's plan.
+ const [orgId] = orgIds;
+ if (orgIds.size !== 1 || !orgId) return { error: 'Prompt not found' };
+ let limitError: string | null;
+ try {
+ const [plan, usage] = await Promise.all([
+ getOrgPlan(orgId),
+ getOrgLocationUsage(supabase, orgId),
+ ]);
+ limitError = locationLimitMessage(plan, usage.total, adding);
+ } catch {
+ return { error: "Couldn't check your plan's prompt limit. Please try again." };
+ }
+ return limitError ? { code: 'plan_limit', error: limitError } : null;
+}
+
/**
* Pause or resume one prompt — the only way a prompt's active state changes
* after it is created. Pausing frees its locations on the plan (00128).
@@ -752,25 +798,8 @@ export async function setPromptActive(
.eq('id', id)
.single();
if (error || !row) return { error: 'Prompt not found' };
- const adding = activationDelta([
- { isActive: row.is_active !== false, regions: row.regions as string[] | null },
- ]);
- const orgId = (row.prompt_sets as unknown as { brands: { organization_id: string } } | null)
- ?.brands?.organization_id;
- if (adding > 0) {
- if (!orgId) return { error: 'Prompt not found' };
- let limitError: string | null;
- try {
- const [plan, usage] = await Promise.all([
- getOrgPlan(orgId),
- getOrgLocationUsage(supabase, orgId),
- ]);
- limitError = locationLimitMessage(plan, usage.total, adding);
- } catch {
- return { error: "Couldn't check your plan's prompt limit. Please try again." };
- }
- if (limitError) return { code: 'plan_limit', error: limitError };
- }
+ const refused = await resumeLimitError(supabase, [row as ResumeRow]);
+ if (refused) return refused;
}
const { data, error } = await supabase
@@ -915,6 +944,63 @@ export async function deletePrompt(id: string): Promise<void> {
if (error) throw new Error(error.message);
}
+export type SetPromptsActiveResult = { updated: number } | { error: string; code?: 'plan_limit' };
+
+/**
+ * Pause or resume several prompts in one write, from the prompts table's
+ * bulk action bar (PROMPT-006). At most a page of rows; RLS keeps it to the
+ * caller's prompts, so `updated` can be fewer than asked. Resuming is metered
+ * as setPromptActive meters one: when the plan has no room for every paused
+ * prompt's locations, nothing is written. Errors come back as values.
+ */
+export async function setPromptsActive(
+ ids: string[],
+ isActive: boolean,
+): Promise<SetPromptsActiveResult> {
+ if (ids.length === 0) return { updated: 0 };
+ const supabase = await createClient();
+
+ if (isActive) {
+ const { data: rows, error } = await supabase
+ .from('prompts')
+ .select('regions, is_active, prompt_sets!inner(brands!inner(organization_id))')
+ .in('id', ids);
+ if (error) return { error: error.message };
+ const refused = await resumeLimitError(supabase, (rows ?? []) as ResumeRow[]);
+ if (refused) return refused;
+ }
+
+ const { data, error } = await supabase
+ .from('prompts')
+ .update({ is_active: isActive })
+ .in('id', ids)
+ .select('id');
+ if (error) return { error: error.message };
+ return { updated: data?.length ?? 0 };
+}
+
+/**
+ * Delete a few prompts and their history in one write, once the undo window
+ * has passed (PROMPT-006). Each prompt's answers and citations go with it, so
+ * a call takes at most PROMPT_DELETE_BATCH prompts and the page calls it in
+ * turn (deleteInBatches); a whole page at once outran the statement timeout
+ * on big brands. Returns the ids actually deleted: RLS quietly leaves out any
+ * the caller can't delete. Errors come back as values.
+ */
+export async function deletePrompts(
+ ids: string[],
+): Promise<{ deletedIds: string[] } | { error: string }> {
+ if (ids.length === 0) return { deletedIds: [] };
+ if (ids.length > PROMPT_DELETE_BATCH) {
+ return { error: `At most ${PROMPT_DELETE_BATCH} prompts per call.` };
+ }
+ const supabase = await createClient();
+
+ const { data, error } = await supabase.from('prompts').delete().in('id', ids).select('id');
+ if (error) return { error: error.message };
+ return { deletedIds: (data ?? []).map((row) => row.id as string) };
+}
+
export async function deletePromptSet(id: string): Promise<void> {
const supabase = await createClient();
diff --git a/web/src/lib/content-job.test.ts b/web/src/lib/content-job.test.ts
index 86a5b85ae..2b1d9b212 100644
--- a/web/src/lib/content-job.test.ts
+++ b/web/src/lib/content-job.test.ts
@@ -6,7 +6,7 @@
import { describe, expect, test } from 'vitest';
import type { GenerationJobStatus } from '@/lib/actions/content';
-import { waitForContentJob } from './content-job';
+import { suggestForPrompt, waitForContentJob } from './content-job';
const status = (s: Partial<GenerationJobStatus>): GenerationJobStatus => ({
status: 'active',
@@ -73,3 +73,68 @@ describe('waitForContentJob', () => {
expect(outcome).toEqual({ kind: 'timeout' });
});
});
+
+describe('suggestForPrompt', () => {
+ const run = (
+ start: Parameters<typeof suggestForPrompt>[1]['start'],
+ getStatus: Parameters<typeof suggestForPrompt>[1]['getStatus'] = async () =>
+ status({ status: 'active' }),
+ ) => suggestForPrompt('p1', { start, getStatus, newKey: () => 'key-1', ...fakeClock() });
+
+ test('follows the job to the opportunity it created', async () => {
+ const outcome = await run(
+ async () => ({ ok: true, jobId: 'j1' }),
+ async () => status({ status: 'completed', result: { generated: 1, opportunityIds: ['o1'] } }),
+ );
+ expect(outcome).toEqual({ kind: 'created', opportunityId: 'o1' });
+ });
+
+ test('offers the open opportunity, whether known up front or found by the job', async () => {
+ expect(await run(async () => ({ ok: true, existingId: 'o2' }))).toEqual({
+ kind: 'existing',
+ opportunityId: 'o2',
+ });
+ expect(
+ await run(
+ async () => ({ ok: true, jobId: 'j1' }),
+ async () => status({ status: 'completed', result: { generated: 0, existingId: 'o3' } }),
+ ),
+ ).toEqual({ kind: 'existing', opportunityId: 'o3' });
+ });
+
+ test('tells a used-up quota from nothing to write yet', async () => {
+ expect(
+ await run(async () => ({ ok: false, error: 'Monthly limit', quotaExhausted: true })),
+ ).toEqual({ kind: 'limited' });
+ expect(
+ await run(
+ async () => ({ ok: true, jobId: 'j1' }),
+ async () => status({ status: 'completed', result: { generated: 0, limited: true } }),
+ ),
+ ).toEqual({ kind: 'limited' });
+ expect(
+ await run(
+ async () => ({ ok: true, jobId: 'j1' }),
+ async () => status({ status: 'completed', result: { generated: 0 } }),
+ ),
+ ).toEqual({ kind: 'nothing' });
+ });
+
+ test('turns a refusal, a failed job or a throw into failed', async () => {
+ expect(await run(async () => ({ ok: false, error: 'Prompt not found' }))).toEqual({
+ kind: 'failed',
+ message: 'Prompt not found',
+ });
+ expect(
+ await run(
+ async () => ({ ok: true, jobId: 'j1' }),
+ async () => status({ status: 'failed', failedReason: 'No AI key' }),
+ ),
+ ).toEqual({ kind: 'failed', message: 'No AI key' });
+ expect(
+ await run(async () => {
+ throw new Error('crypto.randomUUID is not a function');
+ }),
+ ).toEqual({ kind: 'failed', message: 'crypto.randomUUID is not a function' });
+ });
+});
diff --git a/web/src/lib/content-job.ts b/web/src/lib/content-job.ts
index 1889a09de..c121f916a 100644
--- a/web/src/lib/content-job.ts
+++ b/web/src/lib/content-job.ts
@@ -1,11 +1,11 @@
/**
* Following a content generation job to its end, for callers that started
* one and want its outcome ("Suggest content" in the prompts table). The
- * status reader is passed in, so the waiting rules are tested without a
+ * server calls are passed in, so the waiting rules are tested without a
* server.
*/
-import type { GenerationJobStatus } from '@/lib/actions/content';
+import type { GenerationJobStatus, PromptSuggestionResult } from '@/lib/actions/content';
export type ContentJobOutcome =
| { kind: 'completed'; result: NonNullable<GenerationJobStatus['result']> }
@@ -43,3 +43,59 @@ export async function waitForContentJob(
}
return { kind: 'timeout' };
}
+
+/** How one prompt's "Suggest content" ended (PROMPT-006). */
+export type PromptSuggestionOutcome =
+ | { kind: 'created'; opportunityId: string }
+ /** An open opportunity already answers the prompt; nothing was written. */
+ | { kind: 'existing'; opportunityId: string }
+ /** The month's quota is used up. */
+ | { kind: 'limited' }
+ /** Nothing to write from yet: the prompt isn't grouped or has no answers. */
+ | { kind: 'nothing' }
+ | { kind: 'failed'; message: string | null }
+ /** Still being written when we stopped waiting. */
+ | { kind: 'timeout' };
+
+/**
+ * Asks for one prompt's content suggestion and follows it to its end. Never
+ * throws: whatever goes wrong on the way comes back as `failed`.
+ */
+export async function suggestForPrompt(
+ promptId: string,
+ {
+ start,
+ getStatus,
+ newKey = () => crypto.randomUUID(),
+ ...waiting
+ }: {
+ start: (promptId: string, idempotencyKey: string) => Promise<PromptSuggestionResult>;
+ getStatus: (jobId: string) => Promise<GenerationJobStatus>;
+ newKey?: () => string;
+ intervalMs?: number;
+ timeoutMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+ },
+): Promise<PromptSuggestionOutcome> {
+ try {
+ const started = await start(promptId, newKey());
+ if (!started.ok) {
+ return started.quotaExhausted
+ ? { kind: 'limited' }
+ : { kind: 'failed', message: started.error };
+ }
+ if ('existingId' in started) return { kind: 'existing', opportunityId: started.existingId };
+
+ const outcome = await waitForContentJob(started.jobId, { getStatus, ...waiting });
+ if (outcome.kind === 'failed') return { kind: 'failed', message: outcome.reason };
+ if (outcome.kind === 'timeout') return { kind: 'timeout' };
+ const { opportunityIds, existingId, limited } = outcome.result;
+ if (opportunityIds?.[0]) return { kind: 'created', opportunityId: opportunityIds[0] };
+ // Covered while the job ran, e.g. once the prompt was regrouped.
+ if (existingId) return { kind: 'existing', opportunityId: existingId };
+ return limited ? { kind: 'limited' } : { kind: 'nothing' };
+ } catch (err) {
+ return { kind: 'failed', message: err instanceof Error ? err.message : null };
+ }
+}
diff --git a/web/src/lib/prompt-bulk-actions.test.ts b/web/src/lib/prompt-bulk-actions.test.ts
new file mode 100644
index 000000000..7870833a2
--- /dev/null
+++ b/web/src/lib/prompt-bulk-actions.test.ts
@@ -0,0 +1,261 @@
+/**
+ * prompt-bulk-actions.test.ts (PROMPT-006)
+ *
+ * The prompts table's bulk action bar: selecting the page, capping a bulk
+ * "Suggest content", summing up how it went, and deleting in small batches.
+ */
+
+import { describe, expect, test } from 'vitest';
+import type { ContentUsage } from '@/lib/content-usage';
+import {
+ allSelected,
+ bulkSuggestBlock,
+ bulkSuggestSummary,
+ deleteInBatches,
+ emptyTally,
+ PROMPT_DELETE_BATCH,
+ runInTurn,
+ tallyOutcome,
+ toggleAll,
+} from './prompt-bulk-actions';
+import type { PromptSuggestionOutcome } from '@/lib/content-job';
+
+const usage = (remaining: number, perRequest = 3, limit = 10): ContentUsage => ({
+ plan: 'starter',
+ planName: 'Starter',
+ periodStart: null,
+ periodEnd: null,
+ opportunities: { used: limit - remaining, limit, remaining, perRequest },
+ briefs: { used: 0, limit: 10, remaining: 10 },
+});
+
+describe('selecting the page', () => {
+ test('the header selects every row on the page, then clears them', () => {
+ const page = ['a', 'b', 'c'];
+ const some = new Set(['a']);
+ expect(allSelected(page, some)).toBe(false);
+ const all = toggleAll(page, some);
+ expect([...all]).toEqual(page);
+ expect(allSelected(page, all)).toBe(true);
+ expect(toggleAll(page, all).size).toBe(0);
+ });
+
+ test('an empty page is never "all selected"', () => {
+ expect(allSelected([], new Set())).toBe(false);
+ });
+});
+
+describe('bulkSuggestBlock', () => {
+ test('allows up to what one "+ New" request may ask for', () => {
+ expect(bulkSuggestBlock(3, usage(10))).toBeNull();
+ expect(bulkSuggestBlock(4, usage(10))).toBe('Select up to 3 to suggest content');
+ });
+
+ test('never more than is left of the month', () => {
+ expect(bulkSuggestBlock(2, usage(1))).toBe('Select up to 1 to suggest content');
+ expect(bulkSuggestBlock(1, usage(0))).toBe('Monthly limit reached');
+ });
+
+ test('an unlimited plan still takes the per-request cap', () => {
+ expect(bulkSuggestBlock(5, usage(-1, 5, -1))).toBeNull();
+ expect(bulkSuggestBlock(6, usage(-1, 5, -1))).toBe('Select up to 5 to suggest content');
+ });
+
+ test('waits for the quota before asking for anything', () => {
+ expect(bulkSuggestBlock(1, null)).toBe('Checking your content quota…');
+ });
+
+ test("falls back to the smallest cap when the quota can't be read", () => {
+ expect(bulkSuggestBlock(3, null, { unavailable: true })).toBeNull();
+ expect(bulkSuggestBlock(4, null, { unavailable: true })).toBe(
+ 'Select up to 3 to suggest content',
+ );
+ });
+});
+
+describe('bulkSuggestSummary', () => {
+ const run = (...outcomes: Parameters<typeof tallyOutcome>[1][]) => {
+ const tally = emptyTally(outcomes.length);
+ for (const o of outcomes) tallyOutcome(tally, o);
+ return tally;
+ };
+
+ test('leads with what was written and lists the rest', () => {
+ expect(
+ bulkSuggestSummary(
+ run(
+ { kind: 'created', opportunityId: 'o1' },
+ { kind: 'created', opportunityId: 'o2' },
+ { kind: 'existing', opportunityId: 'o3' },
+ { kind: 'nothing' },
+ ),
+ ),
+ ).toEqual({
+ tone: 'success',
+ title: '2 content suggestions created',
+ description: '1 already had one · 1 needs tracked answers and a prompt group first',
+ });
+ });
+
+ test('says when every prompt already had one', () => {
+ expect(
+ bulkSuggestSummary(
+ run({ kind: 'existing', opportunityId: 'o1' }, { kind: 'existing', opportunityId: 'o2' }),
+ ),
+ ).toMatchObject({ tone: 'info', title: 'These prompts already have content suggestions' });
+ });
+
+ test('counts the prompts the monthly limit stopped', () => {
+ const tally = emptyTally(3);
+ tallyOutcome(tally, { kind: 'created', opportunityId: 'o1' });
+ tallyOutcome(tally, { kind: 'limited' });
+ expect(bulkSuggestSummary(tally)).toEqual({
+ tone: 'success',
+ title: '1 content suggestion created',
+ description: 'Monthly limit reached · 2 not started',
+ });
+ });
+
+ test('reports a limit hit before anything as an error', () => {
+ const tally = emptyTally(2);
+ tallyOutcome(tally, { kind: 'limited' });
+ expect(bulkSuggestSummary(tally)).toMatchObject({
+ tone: 'error',
+ title: 'Monthly content limit reached.',
+ });
+ });
+
+ test('reports a run where everything failed as an error', () => {
+ expect(
+ bulkSuggestSummary(run({ kind: 'failed', message: 'x' }, { kind: 'failed', message: null })),
+ ).toEqual({
+ tone: 'error',
+ title: "Couldn't write content suggestions",
+ description: '2 failed',
+ });
+ });
+
+ test('keeps jobs still being written apart from failures', () => {
+ expect(bulkSuggestSummary(run({ kind: 'timeout' }, { kind: 'nothing' }))).toEqual({
+ tone: 'info',
+ title: 'No new content suggestions',
+ description: '1 needs tracked answers and a prompt group first · 1 still being written',
+ });
+ });
+});
+
+describe('runInTurn', () => {
+ test('asks for one prompt at a time, in order', async () => {
+ const log: string[] = [];
+ const tally = await runInTurn(['a', 'b'], async (item) => {
+ log.push(`start ${item}`);
+ await Promise.resolve();
+ log.push(`end ${item}`);
+ return { kind: 'created', opportunityId: `o-${item}` };
+ });
+ expect(log).toEqual(['start a', 'end a', 'start b', 'end b']);
+ expect(tally.created).toEqual(['o-a', 'o-b']);
+ });
+
+ test.each<[string, PromptSuggestionOutcome, string]>([
+ ['the monthly limit', { kind: 'limited' }, 'Monthly content limit reached.'],
+ ['a job that outlives the wait', { kind: 'timeout' }, 'No new content suggestions'],
+ ])('stops at %s', async (_name, stop, title) => {
+ const seen: number[] = [];
+ const tally = await runInTurn([1, 2, 3], async (item) => {
+ seen.push(item);
+ return item === 1 ? { kind: 'created', opportunityId: 'o1' } : stop;
+ });
+ expect(seen).toEqual([1, 2]);
+ expect(bulkSuggestSummary(tally).description).toBe(
+ stop.kind === 'limited'
+ ? 'Monthly limit reached · 2 not started'
+ : '1 still being written · 1 not started',
+ );
+ expect(bulkSuggestSummary({ ...tally, created: [] }).title).toBe(title);
+ });
+});
+
+describe('deleteInBatches', () => {
+ const ids = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7'];
+
+ test('deletes a few prompts per call, one call after another', async () => {
+ const log: string[] = [];
+ const progress: number[] = [];
+ const result = await deleteInBatches(
+ ids,
+ async (batch) => {
+ log.push(`start ${batch.join(',')}`);
+ await Promise.resolve();
+ log.push(`end ${batch.join(',')}`);
+ return { deletedIds: batch };
+ },
+ (done) => progress.push(done),
+ );
+ expect(PROMPT_DELETE_BATCH).toBe(3);
+ expect(log).toEqual([
+ 'start p1,p2,p3',
+ 'end p1,p2,p3',
+ 'start p4,p5,p6',
+ 'end p4,p5,p6',
+ 'start p7',
+ 'end p7',
+ ]);
+ expect(progress).toEqual([3, 6, 7]);
+ expect(result).toEqual({ deletedIds: ids, keptIds: [], failed: false });
+ });
+
+ test('stops at a failed call: earlier batches stay deleted, the rest is kept', async () => {
+ const asked: string[][] = [];
+ const progress: number[] = [];
+ const result = await deleteInBatches(
+ ids,
+ async (batch) => {
+ asked.push(batch);
+ return asked.length === 2
+ ? { error: 'canceling statement due to statement timeout' }
+ : { deletedIds: batch };
+ },
+ (done) => progress.push(done),
+ );
+ // The third batch is never asked for.
+ expect(asked).toEqual([
+ ['p1', 'p2', 'p3'],
+ ['p4', 'p5', 'p6'],
+ ]);
+ expect(progress).toEqual([3]);
+ expect(result).toEqual({
+ deletedIds: ['p1', 'p2', 'p3'],
+ keptIds: ['p4', 'p5', 'p6', 'p7'],
+ failed: true,
+ });
+ });
+
+ test('a call that throws counts as a failed call', async () => {
+ const result = await deleteInBatches(ids, async () => {
+ throw new Error('network');
+ });
+ expect(result).toEqual({ deletedIds: [], keptIds: ids, failed: true });
+ });
+
+ test('keeps prompts RLS left out and carries on', async () => {
+ const result = await deleteInBatches(ids, async (batch) => ({
+ deletedIds: batch.filter((id) => id !== 'p2'),
+ }));
+ expect(result).toEqual({
+ deletedIds: ['p1', 'p3', 'p4', 'p5', 'p6', 'p7'],
+ keptIds: ['p2'],
+ failed: false,
+ });
+ });
+
+ test('makes no call for an empty list', async () => {
+ let calls = 0;
+ const result = await deleteInBatches([], async () => {
+ calls += 1;
+ return { deletedIds: [] };
+ });
+ expect(calls).toBe(0);
+ expect(result).toEqual({ deletedIds: [], keptIds: [], failed: false });
+ });
+});
diff --git a/web/src/lib/prompt-bulk-actions.ts b/web/src/lib/prompt-bulk-actions.ts
new file mode 100644
index 000000000..8bbd7b784
--- /dev/null
+++ b/web/src/lib/prompt-bulk-actions.ts
@@ -0,0 +1,218 @@
+/**
+ * The prompts table's bulk action bar (PROMPT-006): selecting the rows on
+ * screen, how many content suggestions one click may ask for, how a run of
+ * suggestions is summed up, and deleting a few prompts per call. The page
+ * passes the calls in; this only decides.
+ */
+
+import { onDemandMax, type ContentUsage } from '@/lib/content-usage';
+import type { PromptSuggestionOutcome } from '@/lib/content-job';
+
+/** Every row on the page is selected (and there is at least one). */
+export function allSelected(pageIds: string[], selected: ReadonlySet<string>): boolean {
+ return pageIds.length > 0 && pageIds.every((id) => selected.has(id));
+}
+
+/**
+ * The header checkbox: selects the page's rows, or clears them when they are
+ * all selected already. Only the page on screen, so nothing out of sight is
+ * ever acted on.
+ */
+export function toggleAll(pageIds: string[], selected: ReadonlySet<string>): Set<string> {
+ return allSelected(pageIds, selected) ? new Set() : new Set(pageIds);
+}
+
+/** The smallest plan's per-request cap, for when the quota can't be read. */
+export const FALLBACK_PER_REQUEST = 3;
+
+/**
+ * Why one bulk "Suggest content" click can't take this many prompts, or null
+ * when it can. It may ask for what one "+ New" request may (CONTENT-003):
+ * Starter 3, Growth 5, never more than is left of the month. Nothing is asked
+ * for while the quota is loading; if it can't be read, the smallest cap holds
+ * and the server still keeps the month's limit.
+ */
+export function bulkSuggestBlock(
+ count: number,
+ usage: ContentUsage | null,
+ { unavailable = false }: { unavailable?: boolean } = {},
+): string | null {
+ if (!usage && !unavailable) return 'Checking your content quota…';
+ const max = usage ? onDemandMax(usage) : FALLBACK_PER_REQUEST;
+ if (max === 0) return 'Monthly limit reached';
+ return count > max ? `Select up to ${max} to suggest content` : null;
+}
+
+/** How a run of suggestions went, prompt by prompt. */
+export interface BulkSuggestTally {
+ asked: number;
+ /** Prompts the run started; the rest weren't asked for or were turned away. */
+ attempted: number;
+ created: string[];
+ existing: string[];
+ nothing: number;
+ failed: number;
+ stillWriting: number;
+ /** The month's quota ran out. */
+ limited: boolean;
+}
+
+export function emptyTally(asked: number): BulkSuggestTally {
+ return {
+ asked,
+ attempted: 0,
+ created: [],
+ existing: [],
+ nothing: 0,
+ failed: 0,
+ stillWriting: 0,
+ limited: false,
+ };
+}
+
+/** Adds one prompt's outcome to the run. */
+export function tallyOutcome(tally: BulkSuggestTally, outcome: PromptSuggestionOutcome) {
+ // A prompt the month's limit turned away was never started.
+ if (outcome.kind !== 'limited') tally.attempted += 1;
+ switch (outcome.kind) {
+ case 'created':
+ tally.created.push(outcome.opportunityId);
+ break;
+ case 'existing':
+ tally.existing.push(outcome.opportunityId);
+ break;
+ case 'nothing':
+ tally.nothing += 1;
+ break;
+ case 'failed':
+ tally.failed += 1;
+ break;
+ case 'timeout':
+ tally.stillWriting += 1;
+ break;
+ case 'limited':
+ tally.limited = true;
+ break;
+ }
+}
+
+/**
+ * Prompts deleted per call. Each takes its answers and their citations with
+ * it, and on the heaviest brands one prompt carries about 700 answers and
+ * 7,000 citations. Three stay near the 2,000 answers a brand delete takes per
+ * statement (#991), well inside the signed-in user's 8-second statement
+ * timeout; a whole page in one call outran it and rolled back.
+ */
+export const PROMPT_DELETE_BATCH = 3;
+
+/** How a delete run went. */
+export interface BatchDeleteResult {
+ deletedIds: string[];
+ /** Still there: left out by RLS, in the call that failed, or never asked for after it. */
+ keptIds: string[];
+ /** A call failed, so the run stopped there. */
+ failed: boolean;
+}
+
+/**
+ * Deletes prompts a few per call, one call after another, so each statement
+ * stays short. It stops at the first call that fails, as a brand delete
+ * stops at a failed batch: what came before stays deleted, the rest is kept.
+ * `onProgress` hears how many prompts are done after each call.
+ */
+export async function deleteInBatches(
+ ids: string[],
+ deleteBatch: (ids: string[]) => Promise<{ deletedIds: string[] } | { error: string }>,
+ onProgress?: (done: number) => void,
+): Promise<BatchDeleteResult> {
+ const deleted = new Set<string>();
+ let failed = false;
+ for (let start = 0; start < ids.length; start += PROMPT_DELETE_BATCH) {
+ const batch = ids.slice(start, start + PROMPT_DELETE_BATCH);
+ const result = await deleteBatch(batch).catch(() => ({ error: 'unreachable' }));
+ if ('error' in result) {
+ failed = true;
+ break;
+ }
+ for (const id of result.deletedIds) deleted.add(id);
+ onProgress?.(start + batch.length);
+ }
+ return {
+ deletedIds: ids.filter((id) => deleted.has(id)),
+ keptIds: ids.filter((id) => !deleted.has(id)),
+ failed,
+ };
+}
+
+/**
+ * A run of suggestions, one prompt after another: each content job regroups
+ * the brand's prompts first, and two at once would regroup over each other.
+ * It stops at the month's limit, and when a job outlives the wait, since the
+ * next one would then run beside it.
+ */
+export async function runInTurn<T>(
+ items: T[],
+ suggest: (item: T, index: number) => Promise<PromptSuggestionOutcome>,
+): Promise<BulkSuggestTally> {
+ const tally = emptyTally(items.length);
+ for (const [i, item] of items.entries()) {
+ const outcome = await suggest(item, i);
+ tallyOutcome(tally, outcome);
+ if (outcome.kind === 'limited' || outcome.kind === 'timeout') break;
+ }
+ return tally;
+}
+
+const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+
+/**
+ * The toast at the end of a run: what was written as the title, the rest as
+ * one line. The tone follows what the user got out of it.
+ */
+export function bulkSuggestSummary(t: BulkSuggestTally): {
+ tone: 'success' | 'info' | 'error';
+ title: string;
+ description: string | undefined;
+} {
+ const handled = t.created.length + t.existing.length + t.nothing + t.failed + t.stillWriting;
+ const notStarted = t.asked - t.attempted;
+ const details = [
+ t.existing.length > 0 && `${t.existing.length} already had one`,
+ t.nothing > 0 &&
+ `${plural(t.nothing, 'needs', 'need')} tracked answers and a prompt group first`,
+ t.stillWriting > 0 && `${t.stillWriting} still being written`,
+ t.failed > 0 && `${t.failed} failed`,
+ t.limited && 'monthly limit reached',
+ notStarted > 0 && `${notStarted} not started`,
+ ].filter((d): d is string => Boolean(d));
+ const description = details.length ? capitalize(details.join(' · ')) : undefined;
+
+ if (t.created.length > 0) {
+ return {
+ tone: 'success',
+ title: `${plural(t.created.length, 'content suggestion', 'content suggestions')} created`,
+ description,
+ };
+ }
+ if (t.limited && handled === 0) {
+ return { tone: 'error', title: 'Monthly content limit reached.', description: undefined };
+ }
+ if (t.existing.length > 0 && handled === t.existing.length && !t.limited) {
+ return {
+ tone: 'info',
+ title:
+ t.existing.length === 1
+ ? 'This prompt already has a content suggestion'
+ : 'These prompts already have content suggestions',
+ description: undefined,
+ };
+ }
+ if (t.failed > 0 && t.failed === handled) {
+ return { tone: 'error', title: "Couldn't write content suggestions", description };
+ }
+ return { tone: 'info', title: 'No new content suggestions', description };
+}
+
+function capitalize(text: string): string {
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}