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): analyze a prompt the moment it is added (#754)

Gökhan Geyik316e13dc6d18
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 5439829c3..56608d09e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -100,7 +100,7 @@ import { DateRangeFilter } from '@/components/filters/date-range-filter';
import { DataSourcesPanel } from './_data-sources-panel';
import { PLANS } from '@/config/plans';
import { getTopics } from '@/lib/actions/topic';
-import { type PromptVisibilitySummary } from '@/lib/actions/tracking';
+import { analyzeNewPrompt, type PromptVisibilitySummary } from '@/lib/actions/tracking';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import type { PromptVolume, Prompt, Topic } from '@/types';
import { toast } from 'sonner';
@@ -578,8 +578,17 @@ function AddPromptDialog({
setError(result.error);
return;
}
+ // Send the prompt off to be analyzed straight away instead of leaving it
+ // idle until tomorrow's scheduled run. Only this prompt is submitted, and
+ // a refusal (daily cap, cooldown, paused brand) is not an error — the
+ // prompt is saved either way, so the message just says which happened.
+ const { started } = await analyzeNewPrompt(brandId, result.prompt.id);
onClose();
- toast.success('Prompt added — it will be picked up by the next tracking run.');
+ toast.success(
+ started
+ ? 'Prompt added — analyzing it now.'
+ : 'Prompt added — it will be picked up by the next tracking run.',
+ );
onAdded();
} catch {
setError('Failed to add prompt. Please try again.');
diff --git a/web/src/lib/actions/tracking.test.ts b/web/src/lib/actions/tracking.test.ts
index 934d41786..ddd39b9f4 100644
--- a/web/src/lib/actions/tracking.test.ts
+++ b/web/src/lib/actions/tracking.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
const promptResultRow = {
id: 'result-id',
@@ -64,10 +64,13 @@ const insightsAggregatesRow = {
let rpcMock = vi.fn(async () => ({ data: insightsAggregatesRow, error: null }));
+let sessionMock: { access_token: string } | null = { access_token: 'access-token' };
+
vi.mock('@/lib/supabase/server', () => ({
createClient: async () => ({
from: (table: string) => fakeQueryBuilder(table),
rpc: () => rpcMock(),
+ auth: { getSession: async () => ({ data: { session: sessionMock } }) },
}),
}));
@@ -109,3 +112,61 @@ describe('getInsightsSummary', () => {
expect(summary.positiveSentimentPct).toBe(0);
});
});
+
+describe('analyzeNewPrompt', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ sessionMock = { access_token: 'access-token' };
+ });
+
+ it('submits the prompt that was just created and nothing else', async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ jobId: 'job-1' })));
+ vi.stubGlobal('fetch', fetchMock);
+ const { analyzeNewPrompt } = await import('./tracking');
+
+ await expect(analyzeNewPrompt('brand-id', 'new-prompt')).resolves.toEqual({ started: true });
+
+ // The whole point of naming the id: the brand's other unanalyzed prompts —
+ // including any still waiting on Cloro's webhook — must not be swept in and
+ // paid for twice.
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(JSON.parse(init.body as string)).toEqual({
+ brandId: 'brand-id',
+ promptIds: ['new-prompt'],
+ });
+ });
+
+ it('reports not-started rather than throwing when the run is refused', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify({ message: 'limit' }), { status: 429 })),
+ );
+ const { analyzeNewPrompt } = await import('./tracking');
+
+ // The prompt is already saved by this point, so a refusal must stay quiet
+ // and leave it for the daily scheduled run.
+ await expect(analyzeNewPrompt('brand-id', 'new-prompt')).resolves.toEqual({ started: false });
+ });
+
+ it('reports not-started when the server is unreachable', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new Error('ECONNREFUSED');
+ }),
+ );
+ const { analyzeNewPrompt } = await import('./tracking');
+
+ await expect(analyzeNewPrompt('brand-id', 'new-prompt')).resolves.toEqual({ started: false });
+ });
+
+ it('makes no request at all when there is no session', async () => {
+ sessionMock = null;
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const { analyzeNewPrompt } = await import('./tracking');
+
+ await expect(analyzeNewPrompt('brand-id', 'new-prompt')).resolves.toEqual({ started: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 13a18a394..410b0525c 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -1324,6 +1324,60 @@ export async function triggerTrackingCheck(
return { jobId: data.jobId };
}
+/**
+ * Submit a single freshly created prompt to the tracking pipeline.
+ *
+ * Deliberately scoped to ONE prompt id rather than the brand's whole
+ * unanalyzed set. Cloro delivers results asynchronously, so a prompt that is
+ * still in flight has no `prompt_results` rows yet and would be picked up —
+ * and paid for — a second time by the very next add. Passing only the id we
+ * just created keeps each prompt to exactly one submission.
+ *
+ * Never throws, and never surfaces a failure as an error: a prompt that can't
+ * be submitted right now (daily cap, cooldown, paused brand, no active
+ * subscription, server unreachable) is still saved, and the daily scheduled
+ * run picks it up. The boolean only decides which "prompt added" message the
+ * user sees.
+ */
+export async function analyzeNewPrompt(
+ brandId: string,
+ promptId: string,
+): Promise<{ started: boolean }> {
+ const supabase = await createClient();
+
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { started: false };
+
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/tracking/analyze-new`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ brandId, promptIds: [promptId] }),
+ });
+
+ if (!res.ok) {
+ // 402 (no subscription), 409 (paused brand) and 429 (daily cap or
+ // cooldown) are expected states rather than faults — stay quiet about
+ // them. Anything else is worth a server-side log.
+ if (res.status !== 402 && res.status !== 409 && res.status !== 429) {
+ console.error('Failed to submit new prompt for analysis', res.status);
+ }
+ return { started: false };
+ }
+
+ const body: { jobId?: string } = await res.json().catch(() => ({}));
+ return { started: Boolean(body.jobId) };
+ } catch (err) {
+ console.error('Failed to submit new prompt for analysis', err);
+ return { started: false };
+ }
+}
+
export interface TrackingJobStatus {
status: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'not_found';
progress: {