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(prompts): Add prompt dialog on the All Prompts tab (#483)
Gökhan Geyikd95142e00098
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 027c15a97..25e806362 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -27,6 +27,21 @@ import {TableRow,} from '@/components/ui/table';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';import { CompetitionBars } from '@/components/ui/competition-bars';import {TrendingUp,@@ -39,18 +54,25 @@ import {Loader2,RefreshCw,Pencil,+ Plus,Settings2,Download,ChevronUp,ChevronDown,+ X,} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';import { analyzePromptVolumesBatch, refreshVolumes, type VolumeQuota } from '@/lib/actions/volumes';-import { getPromptsPageData } from '@/lib/actions/prompt';+import { addPromptToBrand, getPromptsPageData } from '@/lib/actions/prompt';+import { useUserRole } from '@/hooks/use-user-role';+import { usePlanContext } from '@/components/providers/plan-provider';+import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';+import { PLANS } from '@/config/plans';+import { getTopics } from '@/lib/actions/topic';import { type PromptVisibilitySummary } from '@/lib/actions/tracking';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';-import type { PromptVolume, Prompt } from '@/types';+import type { PromptVolume, Prompt, Topic } from '@/types';import { toast } from 'sonner';import { toCsv } from '@/lib/csv';import { compareNullsLast, type SortDir } from './prompt-sort';@@ -224,6 +246,296 @@ function visibilityBarClass(score: number): string {// ─── Sub-components ───────────────────────────────────────────────────────────+/**+ * Quick-add dialog for the active brand (#460). Same mechanism as the Add+ * Prompt card on brands/[id]/prompts: topic select + the grouped+ * Platform & Models picker (plan-filtered, shopping hidden unless the brand+ * opted in), all allowed engines selected by default. Plan-limit and other+ * user-facing failures come back as a value and render inside the dialog+ * instead of the masked production digest (#427).+ */+function AddPromptDialog({+ brandId,+ shoppingEnabled,+ open,+ onClose,+ onAdded,+}: {+ brandId: string;+ shoppingEnabled: boolean;+ open: boolean;+ onClose: () => void;+ onAdded: () => void;+}) {+ const { planId, allowedModelIds: planAllowedModelIds } = usePlanContext();++ const allowedScraperIds = useMemo(() => {+ const allowed = PLANS[planId].limits.allowedScrapers;+ const ids = allowed ? [...allowed] : ALL_SCRAPERS.map((s) => s.id);+ // Shopping tracking is opt-in per brand (#155): hide the engine entirely+ // when the pref is off. The write actions strip it server-side too.+ return shoppingEnabled ? ids : ids.filter((id) => id !== 'chatgpt-shopping');+ }, [planId, shoppingEnabled]);+ const allowedModelIds = useMemo(+ () => planAllowedModelIds ?? ALL_MODELS.map((m) => m.id),+ [planAllowedModelIds],+ );+ const visibleScrapers = useMemo(+ () => ALL_SCRAPERS.filter((s) => allowedScraperIds.includes(s.id)),+ [allowedScraperIds],+ );+ const visibleModels = useMemo(+ () => ALL_MODELS.filter((m) => allowedModelIds.includes(m.id)),+ [allowedModelIds],+ );++ const [text, setText] = useState('');+ const [category, setCategory] = useState('');+ const [scrapers, setScrapers] = useState<string[]>([]);+ const [models, setModels] = useState<string[]>([]);+ const [topics, setTopics] = useState<Topic[]>([]);+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);++ // Reset to a fresh form on every open: all allowed engines pre-selected+ // (matching the brand page's defaults) and topics fetched lazily — the+ // dialog must cost zero requests until it is actually opened.+ useEffect(() => {+ if (!open) return;+ setText('');+ setError(null);+ setScrapers(allowedScraperIds);+ setModels(allowedModelIds);+ let cancelled = false;+ getTopics(brandId)+ .then((t) => {+ if (cancelled) return;+ setTopics(t);+ setCategory((prev) => prev || (t[0]?.name ?? ''));+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, brandId]);++ const handleClose = () => {+ if (saving) return;+ onClose();+ };++ const handleAdd = async () => {+ if (!text.trim() || (scrapers.length === 0 && models.length === 0) || saving) return;+ setSaving(true);+ setError(null);+ try {+ const result = await addPromptToBrand(brandId, {+ text,+ category: category || undefined,+ platforms: scrapers,+ models,+ });+ if ('error' in result) {+ setError(result.error);+ return;+ }+ onClose();+ toast.success('Prompt added — it will be picked up by the next tracking run.');+ onAdded();+ } catch {+ setError('Failed to add prompt. Please try again.');+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>+ <DialogContent className="sm:max-w-md max-h-[85vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-base">+ <Plus className="h-4 w-4" />+ Add Prompt+ </DialogTitle>+ <DialogDescription>+ Track a new prompt for this brand across the selected platforms.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-3">+ <Input+ autoFocus+ placeholder="e.g. Best project management tools for startups"+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ if (error) setError(null);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleAdd();+ }}+ disabled={saving}+ />++ {/* Topic */}+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">Topic</label>+ {topics.length > 0 ? (+ <Select value={category || null} onValueChange={(v) => v && setCategory(String(v))}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a topic" />+ </SelectTrigger>+ <SelectContent>+ {topics.map((topic) => (+ <SelectItem key={topic.id} value={topic.name}>+ {topic.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <p className="text-xs text-muted-foreground py-2">+ No topics defined yet. Add topics in brand settings.+ </p>+ )}+ </div>++ {/* Platform & Models — combined select, same as brands/[id]/prompts */}+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">+ Platform & Models+ </label>+ <Select+ value="__placeholder__"+ onValueChange={(v) => {+ if (!v || v === '__placeholder__') return;+ const id = String(v);+ if (visibleModels.some((m) => m.id === id) && !models.includes(id)) {+ setModels((prev) => [...prev, id]);+ } else if (visibleScrapers.some((s) => s.id === id) && !scrapers.includes(id)) {+ setScrapers((prev) => [...prev, id]);+ }+ }}+ >+ <SelectTrigger className="w-full">+ <span className="truncate text-muted-foreground">+ {models.length + scrapers.length > 0+ ? `${models.length + scrapers.length} selected`+ : 'Select platform & models'}+ </span>+ </SelectTrigger>+ <SelectContent>+ {SCRAPER_GROUPS.map((group) => {+ const groupScrapers = group.scrapers.filter((s) =>+ visibleScrapers.some((vs) => vs.id === s.id),+ );+ if (groupScrapers.length === 0) return null;+ return (+ <div key={group.provider}>+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">+ {group.provider} (Scraper)+ </div>+ {groupScrapers.map((s) => (+ <SelectItem key={s.id} value={s.id} disabled={scrapers.includes(s.id)}>+ <div>+ <div>{s.label}</div>+ <div className="text-[10px] text-muted-foreground font-mono">+ {s.id}+ </div>+ </div>+ </SelectItem>+ ))}+ </div>+ );+ })}+ {MODEL_GROUPS.map((group) => {+ const groupModels = group.models.filter((m) =>+ visibleModels.some((vm) => vm.id === m.id),+ );+ if (groupModels.length === 0) return null;+ return (+ <div key={group.provider}>+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">+ {group.provider} (API)+ </div>+ {groupModels.map((m) => (+ <SelectItem key={m.id} value={m.id} disabled={models.includes(m.id)}>+ <div>+ <div>{m.label}</div>+ <div className="text-[10px] text-muted-foreground font-mono">+ {m.id}+ </div>+ </div>+ </SelectItem>+ ))}+ </div>+ );+ })}+ </SelectContent>+ </Select>+ {(models.length > 0 || scrapers.length > 0) && (+ <div className="mt-1.5 flex flex-wrap gap-1">+ {scrapers.map((id) => {+ const s = ALL_SCRAPERS.find((as_) => as_.id === id);+ return (+ <Badge key={id} variant="outline" className="gap-1 text-xs">+ {s?.label ?? id}+ <button+ type="button"+ onClick={() => setScrapers((p) => p.filter((i) => i !== id))}+ >+ <X className="h-3 w-3" />+ </button>+ </Badge>+ );+ })}+ {models.map((id) => {+ const m = ALL_MODELS.find((am) => am.id === id);+ return (+ <Badge key={id} variant="secondary" className="gap-1 text-xs">+ {m?.label ?? id}+ <button+ type="button"+ onClick={() => setModels((p) => p.filter((i) => i !== id))}+ >+ <X className="h-3 w-3" />+ </button>+ </Badge>+ );+ })}+ </div>+ )}+ </div>++ {error && <p className="text-xs text-red-500">{error}</p>}+ </div>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={handleClose} disabled={saving}>+ Cancel+ </Button>+ <Button+ type="button"+ onClick={handleAdd}+ disabled={saving || !text.trim() || (scrapers.length === 0 && models.length === 0)}+ >+ {saving ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ Adding…+ </>+ ) : (+ <>+ <Plus className="mr-2 h-4 w-4" />+ Add Prompt+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}+function KpiCard({title,icon: Icon,@@ -275,6 +587,8 @@ export default function PromptsPage() {const [analyzing, setAnalyzing] = useState(false);const [refreshing, setRefreshing] = useState(false);const [quota, setQuota] = useState<VolumeQuota | null>(null);+ const [addPromptOpen, setAddPromptOpen] = useState(false);+ const { canManage } = useUserRole();const activeBrandId = useBrandStore((s) => s.activeBrandId);const activeBrand = useBrandStore(@@ -565,6 +879,17 @@ export default function PromptsPage() {<TabsTrigger value="insights">Insights</TabsTrigger></TabsList><div className="flex items-center gap-2">+ {tab === 'all' && canManage && (+ <Button+ type="button"+ size="sm"+ className="gap-2"+ onClick={() => setAddPromptOpen(true)}+ >+ <Plus className="h-4 w-4" />+ Add prompt+ </Button>+ )}{tab === 'all' && (<span title={!canExport ? PROMPT_EXPORT_HINT : undefined}><Button@@ -637,6 +962,7 @@ export default function PromptsPage() {activeBrandId={activeBrandId}volumeByPromptId={volumeByPromptId}visibility={visibility}+ onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}/></TabsContent>@@ -988,6 +1314,16 @@ export default function PromptsPage() {)}</TabsContent></Tabs>++ {activeBrandId && (+ <AddPromptDialog+ brandId={activeBrandId}+ shoppingEnabled={!!activeBrand?.shoppingModeEnabled}+ open={addPromptOpen}+ onClose={() => setAddPromptOpen(false)}+ onAdded={loadData}+ />+ )}</div>);}@@ -1000,12 +1336,15 @@ function AllPromptsTab({activeBrandId,volumeByPromptId,visibility,+ onAddPrompt,}: {loading: boolean;prompts: Prompt[];activeBrandId: string;volumeByPromptId: Map<string, PromptVolume>;visibility: Record<string, PromptVisibilitySummary>;+ /** Opens the Add Prompt dialog; undefined when the user can't write (member role). */+ onAddPrompt?: () => void;}) {const [search, setSearch] = useState('');const searchParams = useSearchParams();@@ -1082,12 +1421,20 @@ function AllPromptsTab({Add prompts to your brand to start tracking their AI visibility.</p></div>- <Link href={`/dashboard/brands/${activeBrandId}/prompts`}>- <Button size="sm" className="gap-2">- <Pencil className="h-4 w-4" />- Manage prompts- </Button>- </Link>+ <div className="flex items-center gap-2">+ {onAddPrompt && (+ <Button size="sm" className="gap-2" onClick={onAddPrompt}>+ <Plus className="h-4 w-4" />+ Add prompt+ </Button>+ )}+ <Link href={`/dashboard/brands/${activeBrandId}/prompts`}>+ <Button size="sm" variant={onAddPrompt ? 'outline' : 'default'} className="gap-2">+ <Pencil className="h-4 w-4" />+ Manage prompts+ </Button>+ </Link>+ </div></CardContent></Card>);diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 105202ce2..63ae50021 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -3,7 +3,7 @@import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';-import { enforceLimit, getOrgPlan } from '@/lib/guards/plan-guard';+import { enforceLimit, getOrgPlan, PlanLimitError } from '@/lib/guards/plan-guard';import { ALL_MODELS, ALL_SCRAPERS } from '@/config/prompt-options';import type { Plan } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';@@ -386,6 +386,69 @@ export async function addPromptToSet(input: AddPromptInput): Promise<Prompt> {return mapPromptRow(data as Record<string, unknown>);}+export type AddPromptToBrandResult = { prompt: Prompt } | { error: string };++/**+ * Add a single prompt to a brand from the main Prompts page (#460). Same+ * write path as the brand page's Add Prompt card (addPromptToSet with the+ * caller's topic/platform/model choices); the brand's earliest prompt set is+ * the target, created on the fly when the brand has none yet.+ *+ * User-facing failures (plan limit, empty selection) come back as a VALUE:+ * production masks every error thrown from a server action, so a thrown+ * PlanLimitError would reach users as the meaningless digest message (#427).+ */+export async function addPromptToBrand(+ brandId: string,+ input: { text: string; category?: string; platforms: string[]; models?: string[] },+): Promise<AddPromptToBrandResult> {+ const supabase = await createClient();+ const trimmed = input.text.trim();+ if (!trimmed) return { error: 'Prompt text is required.' };+ if (input.platforms.length === 0 && (input.models ?? []).length === 0) {+ return { error: 'Select at least one platform or model.' };+ }++ const { data: ps, error: psErr } = await supabase+ .from('prompt_sets')+ .select('id')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: true })+ .limit(1)+ .maybeSingle();+ if (psErr) return { error: psErr.message };++ let promptSetId = ps?.id as string | undefined;+ if (!promptSetId) {+ const { data: createdSet, error: setErr } = await supabase+ .from('prompt_sets')+ .insert({ brand_id: brandId, name: 'Prompts' })+ .select('id')+ .single();+ if (setErr || !createdSet) {+ return { error: setErr?.message ?? 'Failed to create a prompt set for this brand.' };+ }+ promptSetId = createdSet.id as string;+ }++ let created: Prompt;+ try {+ created = await addPromptToSet({+ promptSetId,+ text: trimmed,+ category: input.category,+ platforms: input.platforms,+ models: input.models ?? [],+ });+ } catch (err) {+ if (err instanceof PlanLimitError) return { error: err.message };+ throw err;+ }++ revalidatePath('/dashboard/prompts');+ return { prompt: created };+}+export async function deletePrompt(id: string): Promise<void> {const supabase = await createClient();