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): show a prompt's real demand on its page (PROMPT-014, part 2) (#1651)
Cihancb25868bf89a
diff --git a/server/src/lib/prompt-demand.js b/server/src/lib/prompt-demand.jsindex cc23c0b5f..76fd8405f 100644--- a/server/src/lib/prompt-demand.js+++ b/server/src/lib/prompt-demand.js@@ -287,6 +287,17 @@ export function trendsSignal(result, at) {return { ...base, trend, change };}+/** A link the provider gave, kept only when it's an http(s) URL; null otherwise. */+export function webUrl(value) {+ if (typeof value !== 'string') return null;+ try {+ const { protocol } = new URL(value);+ return protocol === 'https:' || protocol === 'http:' ? value : null;+ } catch {+ return null;+ }+}+/*** People Also Ask on Google's first page (SERP organic, advanced): each* question (people_also_ask_element's title) and the page Google answers it@@ -311,7 +322,7 @@ export function paaSignal(result, at) {: element.expanded_element;questions.push({question,- url: typeof expanded?.url === 'string' ? expanded.url : null,+ url: webUrl(expanded?.url),domain: typeof expanded?.domain === 'string' ? expanded.domain : null,});}@@ -334,7 +345,7 @@ export function youtubeSignal(result, at) {if (!top || count > top.views) {top = {title: String(video.title ?? '').slice(0, 300),- url: typeof video.url === 'string' ? video.url : null,+ url: webUrl(video.url),channel: typeof video.channel_name === 'string' ? video.channel_name : null,views: count,published: typeof video.timestamp === 'string' ? video.timestamp : null,@@ -931,14 +942,56 @@ export function scheduleDemandCollect(delayMs = COLLECT_DELAY_MS) {// ─── What the card reads ────────────────────────────────────────────────────+/**+ * A prompt's text as compared for "already tracked": case, accents,+ * punctuation and spacing don't count ("How do I track my brand in+ * ChatGPT?" is "how do i track my brand in chatgpt"). The web's +Track+ * makes the same check before it adds a question (web/src/lib/prompt-demand.ts).+ */+export function questionKey(text) {+ return String(text ?? '')+ .normalize('NFKD')+ .replace(/\p{M}/gu, '')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, ' ')+ .trim();+}++/** The brand's prompts' texts, active or paused, as questionKey reads them. */+export async function brandPromptKeys(brandId) {+ const rows = await selectAll(() =>+ supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .order('id', { ascending: true }),+ );+ return new Set(rows.map((r) => questionKey(r.text)).filter(Boolean));+}+/*** What GET /api/prompts/:id/demand answers: the signals read, the level,* which tasks are still waiting, and what the card needs to say about a* missing signal: whether the prompt has a volume analysis and a keyword to* read the paid signals for, and whether they're read at all on this server.+ * Each People Also Ask question says whether the brand already tracks it+ * (`trackedKeys`, from brandPromptKeys), so its +Track isn't offered twice.*/-export function demandResponse(row, volume, { paid = paidSignalsEnabled() } = {}) {+export function demandResponse(+ row,+ volume,+ { paid = paidSignalsEnabled(), trackedKeys = new Set() } = {},+) {const keyword = topKeyword(volume);+ const paa = row?.paa+ ? {+ ...row.paa,+ questions: (row.paa.questions ?? []).map((q) => ({+ ...q,+ tracked: trackedKeys.has(questionKey(q.question)),+ })),+ }+ : null;return {level: row?.level ?? null,signals: row?.signals ?? 0,@@ -948,7 +1001,7 @@ export function demandResponse(row, volume, { paid = paidSignalsEnabled() } = {}languageCode: row?.keyword ? (row.language_code ?? null) : (keyword?.languageCode ?? null),gsc: row?.gsc ?? null,trends: row?.trends ?? null,- paa: row?.paa ?? null,+ paa,youtube: row?.youtube ?? null,pending: Object.fromEntries(PAID_SIGNALS.map((name) => [name, Boolean(row?.tasks?.[name])])),hasVolume: Boolean(volume),diff --git a/server/src/lib/prompt-demand.test.js b/server/src/lib/prompt-demand.test.jsindex fe745b720..a20c24e03 100644--- a/server/src/lib/prompt-demand.test.js+++ b/server/src/lib/prompt-demand.test.js@@ -172,6 +172,7 @@ const {paaSignal,pickDue,postDemandTasks,+ questionKey,sweepOrder,sweepPromptDemand,topKeyword,@@ -596,6 +597,26 @@ describe('paaSignal', () => {expect(paaSignal({ items: [SERP_RESULT.items[0]] }, AT)).toEqual({ questions: [], at: AT });expect(paaSignal(null, AT)).toEqual({ questions: [], at: AT });});++ it('keeps no link that is not an http(s) URL', () => {+ const element = (url) => ({+ type: 'people_also_ask_element',+ title: `Question ${url}`,+ expanded_element: [{ url, domain: 'example.org' }],+ });+ const result = {+ items: [+ {+ type: 'people_also_ask',+ items: [element('javascript:alert(1)'), element('https://example.org/a')],+ },+ ],+ };+ expect(paaSignal(result, AT).questions.map((q) => q.url)).toEqual([+ null,+ 'https://example.org/a',+ ]);+ });});describe('youtubeSignal', () => {@@ -614,6 +635,16 @@ describe('youtubeSignal', () => {at: AT,});});++ it('keeps no link that is not an http(s) URL', () => {+ const video = { type: 'youtube_video', title: 'A video', views_count: 10 };+ for (const url of ['javascript:alert(1)', 'data:text/html,hi', '/watch?v=x', 42]) {+ expect(youtubeSignal({ items: [{ ...video, url }] }, AT).top.url).toBeNull();+ }+ expect(youtubeSignal({ items: [{ ...video, url: 'http://youtu.be/x' }] }, AT).top.url).toBe(+ 'http://youtu.be/x',+ );+ });});describe('the tasks asked', () => {@@ -1252,6 +1283,18 @@ describe('collecting the tasks whose ids were lost', () => {});});+describe('questionKey', () => {+ it('reads the same question written differently as one', () => {+ expect(questionKey('How do I track my brand in ChatGPT?')).toBe(+ questionKey(' how do I track my brand in chatgpt'),+ );+ expect(questionKey('Café-crème: what is it?')).toBe('cafe creme what is it');+ expect(questionKey('What is AI search monitoring?')).not.toBe(+ questionKey('What is AI search?'),+ );+ });+});+describe('demandResponse', () => {it("says what the card needs about the signals that aren't there", () => {expect(demandResponse(null, null, { paid: false })).toEqual({@@ -1286,4 +1329,19 @@ describe('demandResponse', () => {paidSignals: true,});});++ it('marks the People Also Ask questions the brand already tracks', () => {+ const row = {+ level: 'medium',+ signals: 1,+ paa: { questions: paaSignal(SERP_RESULT, AT).questions, at: AT },+ };+ const keys = new Set([questionKey('how do i track my brand in chatgpt')]);+ const { paa } = demandResponse(row, null, { paid: true, trackedKeys: keys });+ expect(paa.questions.map((q) => [q.question, q.tracked])).toEqual([+ ['How do I track my brand in ChatGPT?', true],+ ['What is AI search monitoring?', false],+ ['Is there a tool to monitor AI answers?', false],+ ]);+ });});diff --git a/server/src/routes/prompts-demand.test.js b/server/src/routes/prompts-demand.test.jsindex 975574494..5649a48a5 100644--- a/server/src/routes/prompts-demand.test.js+++ b/server/src/routes/prompts-demand.test.js@@ -9,10 +9,13 @@ import express from 'express';let demand;let profileOrg;+/** The brand's prompts, as a list read gets them. */+let brandPrompts;function table(name) {- const result = () => {+ const result = (list = false) => {if (name === 'prompts') {+ if (list) return { data: brandPrompts, error: null };return { data: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } }, error: null };}if (name === 'brands') return { data: { id: 'b1', organization_id: 'o1' }, error: null };@@ -36,7 +39,7 @@ function table(name) {{get: (_t, prop) => {if (prop === 'then') {- return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);+ return (resolve, reject) => Promise.resolve(result(true)).then(resolve, reject);}if (prop === 'single' || prop === 'maybeSingle') return async () => result();return () => chain;@@ -69,6 +72,7 @@ let baseUrl;beforeEach(async () => {demand = null;profileOrg = 'o1';+ brandPrompts = [{ id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } }];vi.stubEnv('DEMAND_SIGNALS', 'false');const app = express();app.use((req, _res, next) => {@@ -121,6 +125,34 @@ describe('GET /api/prompts/:promptId/demand', () => {});});+ it('says which People Also Ask questions the brand already tracks, however they are written', async () => {+ brandPrompts.push({+ id: 'p2',+ text: ' what is the BEST crm for startups ',+ prompt_sets: { brand_id: 'b1' },+ });+ demand = {+ prompt_id: 'p1',+ brand_id: 'b1',+ keyword: 'best crm',+ paa: {+ questions: [+ { question: 'What is the best CRM for startups?', url: null, domain: null },+ { question: 'Is HubSpot CRM free?', url: null, domain: null },+ ],+ at: '2026-10-27T07:00:00Z',+ },+ level: 'medium',+ signals: 1,+ };+ const res = await fetch(`${baseUrl}/p1/demand`);+ expect(res.status).toBe(200);+ expect((await res.json()).demand.paa.questions).toEqual([+ { question: 'What is the best CRM for startups?', url: null, domain: null, tracked: true },+ { question: 'Is HubSpot CRM free?', url: null, domain: null, tracked: false },+ ]);+ });+it('answers an empty card for a prompt nothing was read for', async () => {const res = await fetch(`${baseUrl}/p1/demand`);expect(res.status).toBe(200);diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex 5c2b40251..cfe7a3ea3 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -38,7 +38,7 @@ import {loadImproveRounds,sendImproveToActionCenter,} from '../lib/action-center/from-prompt-improve.js';-import { demandResponse } from '../lib/prompt-demand.js';+import { brandPromptKeys, demandResponse } from '../lib/prompt-demand.js';const router = Router();@@ -1087,12 +1087,13 @@ router.get('/:promptId/improve', readImprove, async (req, res) => {});// The prompt's real demand (PROMPT-014): the signals the nightly sweep read-// and their level, for the Demand card. A read: a workspace whose plan has+// and their level, for the Demand card, each People Also Ask question with+// whether the brand already tracks it. A read: a workspace whose plan has// ended still sees what was read.router.get('/:promptId/demand', async (req, res) => {try {const promptId = req.params.promptId;- await loadImprovePrompt(promptId, req.user.id);+ const { brandId } = await loadImprovePrompt(promptId, req.user.id);const [demand, volume] = await Promise.all([supabaseAdmin.from('prompt_demand').select('*').eq('prompt_id', promptId).maybeSingle(),supabaseAdmin@@ -1105,7 +1106,10 @@ router.get('/:promptId/demand', async (req, res) => {]);if (demand.error) throw demand.error;if (volume.error) throw volume.error;- return res.json({ demand: demandResponse(demand.data, volume.data) });+ const trackedKeys = demand.data?.paa?.questions?.length+ ? await brandPromptKeys(brandId)+ : undefined;+ return res.json({ demand: demandResponse(demand.data, volume.data, { trackedKeys }) });} catch (error) {req.log.error({ err: error }, 'prompt demand read error');return resdiff --git a/web/messages/en.json b/web/messages/en.jsonindex f5b0978c9..f85318263 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7254,6 +7254,88 @@"label": "{range} a month, estimated, {level} confidence","perMonth": "/mo"},+ "promptDemand": {+ "title": "Demand · is this asked for real?",+ "keyword": "Read for “{keyword}”",+ "loadFailed": "Couldn't load this prompt's demand.",+ "measured": "Measured",+ "measuredTitle": "Measured from real searches, not estimated.",+ "kpiTitle": "Demand · {signals} of {total} signals",+ "level": {+ "high": "High",+ "medium": "Medium",+ "low": "Low"+ },+ "note": {+ "high": "Demand level <b>High</b> raises the Priority Score of Action Center actions about this prompt.",+ "medium": "Demand level <b>Medium</b> raises the Priority Score of Action Center actions about this prompt a little.",+ "low": "Demand level <b>Low</b> leaves the Priority Score of Action Center actions about this prompt as it is.",+ "none": "Once a signal is read, the demand level feeds the Priority Score of Action Center actions about this prompt."+ },+ "readOn": "{source} · read {date}",+ "gsc": {+ "title": "Search Console",+ "window": "Measured · last 28 days",+ "source": "Your Search Console",+ "totals": "<b>{impressions}</b> impressions · <b>{clicks}</b> clicks",+ "queries": "{count, plural, one {# matching query} other {# matching queries}}, e.g. “{query}”",+ "noQueries": "None of your Search Console queries in the last 28 days matches this prompt.",+ "notConnected": "Connect Search Console to see real clicks.",+ "notConnectedBody": "The searches that brought people to your site are matched to this prompt every night.",+ "connect": "Connect Search Console",+ "connectNotAllowed": "Ask an admin or a manager to connect Search Console.",+ "unmapped": "Pick this brand's Search Console property to see real clicks.",+ "manage": "Manage in Settings",+ "syncing": "Search Console is syncing. Its queries are matched to this prompt the night after the first sync.",+ "notConfigured": "Search Console isn't set up on this server.",+ "notRead": "Not read yet. Matching queries are read every night."+ },+ "trends": {+ "title": "Google Trends",+ "window": "12 months",+ "source": "Google Trends via DataForSEO",+ "rising": "Rising",+ "steady": "Steady",+ "falling": "Falling",+ "change": "<b>{trend}</b> · {change} vs a year ago",+ "risingFromNone": "<b>Rising</b> · from no search interest a year ago",+ "label": "<b>{trend}</b>",+ "noData": "Too little search interest to draw a line."+ },+ "paa": {+ "title": "People Also Ask",+ "window": "Google",+ "source": "Google results via DataForSEO",+ "track": "+ Track",+ "trackLabel": "Track “{question}”",+ "tracked": "Tracked",+ "trackedLabel": "“{question}” is tracked",+ "tracking": "Adding…",+ "trackNotAllowed": "Only admins and managers can add prompts.",+ "trackedToast": "“{question}” is now a tracked prompt.",+ "alreadyTrackedToast": "“{question}” is already a tracked prompt.",+ "planLimit": "Your plan's prompt limit is reached. Upgrade to track more prompts.",+ "trackFailed": "Couldn't track this question.",+ "none": "Google shows no People Also Ask questions for this keyword."+ },+ "youtube": {+ "title": "YouTube",+ "window": "Top results",+ "source": "YouTube results via DataForSEO",+ "totals": "<b>{views}</b> views across the top <b>{videos}</b> videos",+ "top": "Top: “{title}” · {views} views",+ "results": "YouTube lists about {count} results.",+ "none": "YouTube shows no videos for this keyword."+ },+ "paid": {+ "pending": "Being read. Ready within a day.",+ "noVolume": "Analyze volume first. Trends, People Also Ask and YouTube are read for the keyword the volume analysis finds.",+ "noVolumeLink": "Open Prompts Insights",+ "noKeyword": "Nothing to read: Google shows no searches for this prompt's keywords.",+ "off": "Not read yet. Weekly reads aren't turned on yet.",+ "notRead": "Not read yet. It's read about once a week."+ }+ },"mentions": {"title": "Mentions & Sentiment","description": "Where AI mentions your brand, how it describes you, why, and what to do about it.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex e0d68a9f1..c49395006 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -26,6 +26,7 @@ import {import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { Input } from '@/components/ui/input';import {+ Activity,ArrowLeft,AlertCircle,ChevronDown,@@ -42,6 +43,11 @@ import {import { getPromptVolume, type PromptVolumeEstimateRow } from '@/lib/actions/prompt-volume';import { promptVolumeEstimate } from '@/lib/volume-estimate';import { EstimateBadge, EstimateRange } from '@/components/prompts/volume-estimate';+import { DemandLevelValue, DemandSection } from '@/components/prompts/demand-card';+import { getPromptDemandSignals } from '@/lib/actions/prompt-demand-signals';+import { getSuggestionSourceStates } from '@/lib/actions/integrations';+import { DEMAND_SIGNALS, type PromptDemand } from '@/lib/prompt-demand';+import { googleSourceStatus, type GoogleSourceStatus } from '@/lib/traffic-sources';import { cn } from '@/lib/utils';import { formatRegionDisplay } from '@/lib/region';import { toast } from 'sonner';@@ -234,6 +240,13 @@ function VisibilityBar({ score }: { score: number }) {);}+/** The KPI row's columns for its number of cards: three, four, or five with Demand. */+function kpiGridColumns(count: number): string {+ if (count >= 5) return 'sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5';+ if (count === 4) return 'sm:grid-cols-2 lg:grid-cols-4';+ return 'sm:grid-cols-3';+}+function KpiCard({title,value,@@ -672,6 +685,15 @@ export default function PromptDetailPage() {// The prompt's estimated AI searches (PROMPT-013); no card without one.const [volume, setVolume] = useState<PromptVolumeEstimateRow | null>(null);const tVolumes = useTranslations('prompts.volumeInsights');+ // Its real demand (PROMPT-014): read by the server every night.+ const [demand, setDemand] = useState<PromptDemand | null>(null);+ const [demandFailed, setDemandFailed] = useState(false);+ // An API without the demand route yet: the page shows no Demand section.+ const [demandUnavailable, setDemandUnavailable] = useState(false);+ // The brand's Search Console, for the Demand card's state; bumped on connect.+ const [gscStatus, setGscStatus] = useState<GoogleSourceStatus | null>(null);+ const [sourcesRead, setSourcesRead] = useState(0);+ const tDemand = useTranslations('promptDemand');// Workflow data is independent of the date window — load it once per// prompt, outside the main load cycle, so date changes don't refetch it.@@ -703,6 +725,42 @@ export default function PromptDetailPage() {};}, [promptId]);+ // Like the volume, the demand doesn't depend on the date window.+ useEffect(() => {+ let cancelled = false;+ setDemand(null);+ setDemandFailed(false);+ setDemandUnavailable(false);+ getPromptDemandSignals(promptId)+ .then((res) => {+ if (cancelled) return;+ if ('demand' in res) setDemand(res.demand);+ else if ('unavailable' in res) setDemandUnavailable(true);+ else setDemandFailed(true);+ })+ .catch(() => {+ if (!cancelled) setDemandFailed(true);+ });+ return () => {+ cancelled = true;+ };+ }, [promptId]);++ useEffect(() => {+ let cancelled = false;+ if (!promptBrandId) return;+ getSuggestionSourceStates(promptBrandId)+ .then((states) => {+ if (!cancelled) setGscStatus(googleSourceStatus(states.gsc));+ })+ .catch(() => {+ if (!cancelled) setGscStatus(null);+ });+ return () => {+ cancelled = true;+ };+ }, [promptBrandId, sourcesRead]);+useEffect(() => {let cancelled = false;if (!promptBrandId) return;@@ -941,7 +999,7 @@ export default function PromptDetailPage() {<divclassName={cn('grid gap-4',- volume ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3',+ kpiGridColumns(3 + (volume ? 1 : 0) + (demand?.level ? 1 : 0)),)}><KpiCard@@ -971,8 +1029,30 @@ export default function PromptDetailPage() {icon={TrendingUp}/>)}+ {demand?.level && (+ <KpiCard+ title={tDemand('kpiTitle', {+ signals: demand.signals,+ total: DEMAND_SIGNALS.length,+ })}+ value={<DemandLevelValue demand={demand} />}+ icon={Activity}+ />+ )}</div>+ {!demandUnavailable && (+ <DemandSection+ demand={demand}+ failed={demandFailed}+ gscStatus={gscStatus}+ brandId={data.prompt.brandId}+ topic={data.prompt.topicName ?? ''}+ canManage={canManage}+ onGscConnected={() => setSourcesRead((n) => n + 1)}+ />+ )}+<Card><CardHeader className="pb-3"><CardTitle className="text-sm font-medium">Platform Results</CardTitle>diff --git a/web/src/components/prompts/demand-card.test.tsx b/web/src/components/prompts/demand-card.test.tsxnew file mode 100644index 000000000..6efb18fa0--- /dev/null+++ b/web/src/components/prompts/demand-card.test.tsx@@ -0,0 +1,347 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { PromptDemand } from '@/lib/prompt-demand';+import type { GoogleSourceStatus } from '@/lib/traffic-sources';++/**+ * The prompt's Demand card (PROMPT-014, mockup screen 2): four measured+ * signals with their sources and dates, a clear state for each one that+ * isn't there, the level (never an Estimate), and People Also Ask+ * questions tracked in one click.+ */++const hook = vi.hoisted(() => ({ connect: vi.fn() }));+vi.mock('@/hooks/use-integration-connect', () => ({+ useIntegrationConnect: () => ({ connecting: false, connect: hook.connect }),+}));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,+}));+const trackDemandQuestion = vi.fn();+vi.mock('@/lib/actions/prompt-demand-signals', () => ({+ trackDemandQuestion: (...args: unknown[]) => trackDemandQuestion(...args),+}));+const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const { DemandLevelValue, DemandSection } = await import('./demand-card');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const READ = '2026-10-27T12:00:00.000Z';++const full = (over: Partial<PromptDemand> = {}): PromptDemand => ({+ level: 'high',+ signals: 4,+ updatedAt: READ,+ keyword: 'ai search monitoring',+ locationCode: 2840,+ languageCode: 'en',+ gsc: {+ impressions: 4120,+ clicks: 96,+ queries: 7,+ top: { query: 'ai search monitoring tool', impressions: 2400, clicks: 60 },+ at: READ,+ },+ trends: {+ points: [25, 26, 30, 28, 33, 35, 41],+ trend: 'rising',+ change: 64,+ from: '2025-10-26',+ to: '2026-10-24',+ at: READ,+ },+ paa: {+ questions: [+ { question: 'How do I track my brand in ChatGPT?', url: null, domain: null },+ { question: 'What is AI search monitoring?', url: null, domain: null },+ ],+ at: READ,+ },+ youtube: {+ videos: 20,+ views: 1_800_000,+ results: 214,+ top: {+ title: 'How to track your brand in ChatGPT',+ url: 'https://www.youtube.com/watch?v=abc123',+ channel: 'Search Lab',+ views: 310_000,+ published: null,+ },+ at: READ,+ },+ pending: { trends: false, paa: false, youtube: false },+ hasVolume: true,+ hasKeyword: true,+ paidSignals: true,+ ...over,+});++const empty = (over: Partial<PromptDemand> = {}): PromptDemand =>+ full({+ level: null,+ signals: 0,+ gsc: null,+ trends: null,+ paa: null,+ youtube: null,+ ...over,+ });++let container: HTMLDivElement;+let root: Root;+const onGscConnected = vi.fn();++beforeEach(() => {+ vi.clearAllMocks();+ trackDemandQuestion.mockResolvedValue({ promptIds: ['n1'] });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(+ demand: PromptDemand | null,+ {+ gscStatus = 'connected',+ canManage = true,+ failed = false,+ }: { gscStatus?: GoogleSourceStatus | null; canManage?: boolean; failed?: boolean } = {},+) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <DemandSection+ demand={demand}+ failed={failed}+ gscStatus={gscStatus}+ brandId="b1"+ topic="Monitoring"+ canManage={canManage}+ onGscConnected={onGscConnected}+ />+ </NextIntlClientProvider>,+ );+ });+}++const text = () => (container.textContent ?? '').replace(/\s+/g, ' ');+const buttons = (label: string) =>+ [...container.querySelectorAll('button')].filter((b) => b.textContent === label);++describe('DemandSection with every signal read', () => {+ it('shows the four signals, each with its source and the day it was read', () => {+ render(full());+ const t = text();+ expect(t).toContain('Demand · is this asked for real?');+ expect(t).toContain('Read for “ai search monitoring”');+ // Search Console.+ expect(t).toContain('4,120 impressions · 96 clicks');+ expect(t).toContain('7 matching queries, e.g. “ai search monitoring tool”');+ expect(t).toContain('Measured · last 28 days');+ expect(t).toContain('Your Search Console · read Oct 27, 2026');+ // Google Trends.+ expect(t).toContain('Rising · +64% vs a year ago');+ expect(t).toContain('Google Trends via DataForSEO · read Oct 27, 2026');+ expect(container.querySelector('svg')).not.toBeNull();+ // People Also Ask.+ expect(t).toContain('How do I track my brand in ChatGPT?');+ expect(buttons('+ Track')).toHaveLength(2);+ expect(t).toContain('Google results via DataForSEO · read Oct 27, 2026');+ // YouTube.+ expect(t).toContain('1.8M views across the top 20 videos');+ expect(t).toContain('Top: “How to track your brand in ChatGPT” · 310k views');+ expect(t).toContain('YouTube lists about 214 results.');+ // The level's effect.+ expect(t).toContain(+ 'Demand level High raises the Priority Score of Action Center actions about this prompt.',+ );+ });++ it("links the top video only when it's a web page", () => {+ render(full());+ expect(container.querySelector('a[target="_blank"]')?.getAttribute('href')).toBe(+ 'https://www.youtube.com/watch?v=abc123',+ );+ const top = full().youtube!.top!;+ render(full({ youtube: { ...full().youtube!, top: { ...top, url: 'javascript:alert(1)' } } }));+ expect(container.querySelector('a[target="_blank"]')).toBeNull();+ expect(text()).toContain('Top: “How to track your brand in ChatGPT” · 310k views');+ });++ it('says so when a read found nothing', () => {+ render(+ full({+ gsc: { impressions: 0, clicks: 0, queries: 0, top: null, at: READ },+ trends: { points: [0, 0], trend: null, change: null, from: null, to: null, at: READ },+ paa: { questions: [], at: READ },+ youtube: { videos: 0, views: 0, results: null, top: null, at: READ },+ level: 'low',+ }),+ );+ const t = text();+ expect(t).toContain('None of your Search Console queries in the last 28 days matches');+ expect(t).toContain('Too little search interest to draw a line.');+ expect(t).toContain('Google shows no People Also Ask questions for this keyword.');+ expect(t).toContain('YouTube shows no videos for this keyword.');+ expect(t).toContain(+ 'Demand level Low leaves the Priority Score of Action Center actions about this prompt as it is.',+ );+ });++ it('says "from no search interest" only for a rising line without a change to give', () => {+ const trends = (trend: 'rising' | 'steady', change: number | null) =>+ full({ trends: { ...full().trends!, trend, change } });++ render(trends('rising', null));+ expect(text()).toContain('Rising · from no search interest a year ago');++ // Interest in between, none at either end: steady, and no percent to give.+ render(trends('steady', null));+ expect(text()).toContain('Steady');+ expect(text()).not.toContain('from no search interest');+ expect(text()).not.toContain('vs a year ago');++ render(trends('steady', 4));+ expect(text()).toContain('Steady · +4% vs a year ago');+ });+});++describe('DemandSection without a source', () => {+ it('asks to connect Search Console, and connects it in place', () => {+ render(empty(), { gscStatus: 'not_connected' });+ expect(text()).toContain('Connect Search Console to see real clicks.');+ const [connect] = buttons('Connect Search Console');+ act(() => connect.click());+ expect(hook.connect).toHaveBeenCalled();+ });++ it("tells a person who can't connect to ask an admin", () => {+ render(empty(), { gscStatus: 'not_connected', canManage: false });+ expect(buttons('Connect Search Console')).toHaveLength(0);+ expect(text()).toContain('Ask an admin or a manager to connect Search Console.');+ });++ it('says what each Search Console state needs', () => {+ render(empty(), { gscStatus: 'unmapped' });+ expect(text()).toContain("Pick this brand's Search Console property to see real clicks.");+ expect(+ container.querySelector('a[href="/dashboard/settings?tab=integrations"]'),+ ).not.toBeNull();+ render(empty(), { gscStatus: 'syncing' });+ expect(text()).toContain('Search Console is syncing.');+ render(empty(), { gscStatus: 'connected' });+ expect(text()).toContain('Not read yet. Matching queries are read every night.');+ });++ it('asks for a volume analysis first, with the way there', () => {+ render(empty({ hasVolume: false, hasKeyword: false, keyword: null }));+ expect(text()).toContain('Analyze volume first.');+ expect(container.querySelectorAll('a[href="/dashboard/prompts/insights"]')).toHaveLength(3);+ expect(text()).not.toContain('Read for');+ });++ it('says when there is no keyword with searches, when reads are off, and when one is being read', () => {+ render(empty({ hasKeyword: false }));+ expect(text()).toContain(+ "Nothing to read: Google shows no searches for this prompt's keywords.",+ );+ render(empty({ paidSignals: false }));+ expect(text()).toContain("Not read yet. Weekly reads aren't turned on yet.");+ render(empty({ pending: { trends: true, paa: false, youtube: false } }));+ expect(text()).toContain('Being read. Ready within a day.');+ expect(text()).toContain("Not read yet. It's read about once a week.");+ expect(text()).toContain('Once a signal is read, the demand level feeds');+ });++ it("says it couldn't load", () => {+ render(null, { failed: true });+ expect(text()).toContain("Couldn't load this prompt's demand.");+ });+});++describe('+ Track on a People Also Ask question', () => {+ it('tracks the question in its topic in one click', async () => {+ render(full());+ const [first] = buttons('+ Track');+ await act(async () => first.click());+ expect(trackDemandQuestion).toHaveBeenCalledWith(+ 'b1',+ 'How do I track my brand in ChatGPT?',+ 'Monitoring',+ );+ expect(toast.success).toHaveBeenCalledWith(+ '“How do I track my brand in ChatGPT?” is now a tracked prompt.',+ );+ expect(buttons('Tracked')).toHaveLength(1);+ expect(buttons('+ Track')).toHaveLength(1);+ });++ it('names the question it tracks for a screen reader', () => {+ render(full({ paa: { ...full().paa!, questions: [full().paa!.questions[0]] } }));+ const [button] = buttons('+ Track');+ expect(button.getAttribute('aria-label')).toBe('Track “How do I track my brand in ChatGPT?”');+ });++ it('shows a question the brand already tracks as tracked when the page loads again', () => {+ const [first, second] = full().paa!.questions;+ render(full({ paa: { questions: [{ ...first, tracked: true }, second], at: READ } }));+ const [done] = buttons('Tracked');+ expect(done.disabled).toBe(true);+ expect(done.getAttribute('aria-label')).toBe(+ '“How do I track my brand in ChatGPT?” is tracked',+ );+ expect(buttons('+ Track')).toHaveLength(1);+ });++ it('adds nothing for a question tracked meanwhile, and shows it as tracked', async () => {+ trackDemandQuestion.mockResolvedValue({ promptIds: [], alreadyTracked: true });+ render(full());+ await act(async () => buttons('+ Track')[0].click());+ expect(toast.success).toHaveBeenCalledWith(+ '“How do I track my brand in ChatGPT?” is already a tracked prompt.',+ );+ expect(toast.error).not.toHaveBeenCalled();+ expect(buttons('Tracked')).toHaveLength(1);+ });++ it("says the plan's limit is reached", async () => {+ trackDemandQuestion.mockResolvedValue({ promptIds: [], error: 'limit', code: 'plan_limit' });+ render(full());+ await act(async () => buttons('+ Track')[0].click());+ expect(toast.error).toHaveBeenCalledWith(+ "Your plan's prompt limit is reached. Upgrade to track more prompts.",+ );+ expect(buttons('+ Track')).toHaveLength(2);+ });++ it("is off for a person who can't add prompts", () => {+ render(full(), { canManage: false });+ expect(buttons('+ Track').every((b) => b.disabled)).toBe(true);+ });+});++describe('DemandLevelValue', () => {+ it('reads the level, measured: never an Estimate', () => {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <DemandLevelValue demand={full({ level: 'medium', signals: 3 })} />+ </NextIntlClientProvider>,+ );+ });+ expect(text()).toBe('MediumMeasured');+ expect(text()).not.toContain('Estimate');+ });+});diff --git a/web/src/components/prompts/demand-card.tsx b/web/src/components/prompts/demand-card.tsxnew file mode 100644index 000000000..98df61b41--- /dev/null+++ b/web/src/components/prompts/demand-card.tsx@@ -0,0 +1,475 @@+'use client';++import { useState, type ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2, Plug } from 'lucide-react';+import { toast } from 'sonner';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { Card, CardContent } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import KpiSparkline from '@/components/action-center/kpi-sparkline';+import { useIntegrationConnect } from '@/hooks/use-integration-connect';+import { trackDemandQuestion } from '@/lib/actions/prompt-demand-signals';+import { formatCompactNumber, formatDate, formatNumber } from '@/lib/format';+import {+ DEMAND_SIGNALS,+ formatChange,+ gscSignalState,+ paidSignalState,+ type PaidDemandSignal,+ type PromptDemand,+} from '@/lib/prompt-demand';+import { INTEGRATIONS_SETTINGS_PATH, type GoogleSourceStatus } from '@/lib/traffic-sources';+import { cn } from '@/lib/utils';++const bold = (chunks: ReactNode) => <strong className="font-semibold">{chunks}</strong>;++/**+ * "Measured": the demand level and its signals are read from real searches,+ * so they never carry the Estimate badge (PROMPT-013's rule).+ */+export function MeasuredBadge({ className }: { className?: string }) {+ const t = useTranslations('promptDemand');+ return (+ <span+ title={t('measuredTitle')}+ className={cn(+ 'inline-flex items-center rounded-md border px-1.5 text-[11px] font-medium leading-5 text-muted-foreground',+ className,+ )}+ >+ {t('measured')}+ </span>+ );+}++/** The KPI row's value: "High", measured. */+export function DemandLevelValue({ demand }: { demand: PromptDemand }) {+ const t = useTranslations('promptDemand');+ if (!demand.level) return null;+ return (+ <span className="flex flex-col items-start gap-1">+ <span>{t(`level.${demand.level}`)}</span>+ <MeasuredBadge />+ </span>+ );+}++/** One of the four cards: title, what it covers, the data or its state, and its source and date. */+function SignalCard({+ title,+ window,+ footer,+ children,+}: {+ title: string;+ window: string;+ footer?: string | null;+ children: ReactNode;+}) {+ return (+ <Card className="min-w-0">+ <CardContent className="flex h-full flex-col gap-2 p-4">+ <div className="flex flex-wrap items-baseline justify-between gap-x-2">+ <h3 className="text-sm font-medium">{title}</h3>+ <span className="text-xs text-muted-foreground">{window}</span>+ </div>+ <div className="flex flex-1 flex-col gap-1.5 text-sm">{children}</div>+ {footer && <p className="text-[11px] text-muted-foreground">{footer}</p>}+ </CardContent>+ </Card>+ );+}++function StateText({ children }: { children: ReactNode }) {+ return <p className="text-xs text-muted-foreground">{children}</p>;+}++/** Why a Trends, People Also Ask or YouTube card has no data. */+function PaidState({ demand, signal }: { demand: PromptDemand; signal: PaidDemandSignal }) {+ const t = useTranslations('promptDemand.paid');+ const state = paidSignalState(demand, signal);+ if (state === 'data') return null;+ if (state === 'noVolume') {+ return (+ <>+ <StateText>{t('noVolume')}</StateText>+ <Link+ href="/dashboard/prompts/insights"+ className="text-xs font-medium text-foreground underline underline-offset-2"+ >+ {t('noVolumeLink')}+ </Link>+ </>+ );+ }+ return (+ <StateText>+ {state === 'pending' && <Loader2 className="mr-1 inline h-3 w-3 animate-spin" />}+ {t(state)}+ </StateText>+ );+}++function GscCard({+ demand,+ gscStatus,+ canManage,+ onConnected,+}: {+ demand: PromptDemand;+ gscStatus: GoogleSourceStatus | null;+ canManage: boolean;+ onConnected: () => void;+}) {+ const t = useTranslations('promptDemand');+ const { connecting, connect } = useIntegrationConnect('google-search-console', {+ label: t('gsc.title'),+ callbackUrl: () => window.location.href,+ onStatus: (status) => {+ if (status === 'connected') onConnected();+ },+ });+ const state = gscSignalState(demand, gscStatus);+ const gsc = demand.gsc;++ let body: ReactNode;+ if (state === 'data' && gsc) {+ body = (+ <>+ <p>+ {t.rich('gsc.totals', {+ impressions: formatNumber(gsc.impressions),+ clicks: formatNumber(gsc.clicks),+ b: bold,+ })}+ </p>+ <p className="text-xs text-muted-foreground">+ {gsc.queries > 0 && gsc.top+ ? t('gsc.queries', { count: gsc.queries, query: gsc.top.query })+ : t('gsc.noQueries')}+ </p>+ </>+ );+ } else if (state === 'not_connected') {+ body = (+ <>+ <p className="flex items-center gap-2 text-sm font-medium">+ <Plug className="h-3.5 w-3.5 text-muted-foreground" />+ {t('gsc.notConnected')}+ </p>+ <StateText>{t('gsc.notConnectedBody')}</StateText>+ {canManage ? (+ <Button+ size="sm"+ variant="outline"+ className="h-7 w-fit gap-1.5 text-xs"+ onClick={() => void connect()}+ disabled={connecting}+ >+ {connecting && <Loader2 className="h-3 w-3 animate-spin" />}+ {t('gsc.connect')}+ </Button>+ ) : (+ <StateText>{t('gsc.connectNotAllowed')}</StateText>+ )}+ </>+ );+ } else if (state === 'unmapped') {+ body = (+ <>+ <p className="text-sm font-medium">{t('gsc.unmapped')}</p>+ <Link+ href={INTEGRATIONS_SETTINGS_PATH}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 w-fit text-xs')}+ >+ {t('gsc.manage')}+ </Link>+ </>+ );+ } else {+ body = (+ <StateText>+ {state === 'syncing'+ ? t('gsc.syncing')+ : state === 'not_configured'+ ? t('gsc.notConfigured')+ : t('gsc.notRead')}+ </StateText>+ );+ }++ return (+ <SignalCard+ title={t('gsc.title')}+ window={t('gsc.window')}+ footer={gsc ? t('readOn', { source: t('gsc.source'), date: formatDate(gsc.at) }) : null}+ >+ {body}+ </SignalCard>+ );+}++const TREND_TONE = {+ rising: 'text-emerald-600 dark:text-emerald-400',+ steady: 'text-foreground',+ falling: 'text-red-600 dark:text-red-400',+} as const;++function TrendsCard({ demand }: { demand: PromptDemand }) {+ const t = useTranslations('promptDemand');+ const trends = demand.trends;+ return (+ <SignalCard+ title={t('trends.title')}+ window={t('trends.window')}+ footer={+ trends ? t('readOn', { source: t('trends.source'), date: formatDate(trends.at) }) : null+ }+ >+ {trends ? (+ trends.trend ? (+ <>+ <div className={cn('w-fit', TREND_TONE[trends.trend])}>+ <KpiSparkline+ points={trends.points.map((value, i) => ({ date: String(i), value }))}+ />+ </div>+ <p>+ {trends.change !== null+ ? t.rich('trends.change', {+ trend: t(`trends.${trends.trend}`),+ change: formatChange(trends.change),+ b: bold,+ })+ : trends.trend === 'rising'+ ? t.rich('trends.risingFromNone', { b: bold })+ : // No change to give (no interest at either end): the direction alone.+ t.rich('trends.label', { trend: t(`trends.${trends.trend}`), b: bold })}+ </p>+ </>+ ) : (+ <StateText>{t('trends.noData')}</StateText>+ )+ ) : (+ <PaidState demand={demand} signal="trends" />+ )}+ </SignalCard>+ );+}++function PaaCard({+ demand,+ brandId,+ topic,+ canManage,+}: {+ demand: PromptDemand;+ brandId: string;+ topic: string;+ canManage: boolean;+}) {+ const t = useTranslations('promptDemand');+ const [tracking, setTracking] = useState<string | null>(null);+ const [tracked, setTracked] = useState<Set<string>>(new Set());+ const paa = demand.paa;++ const track = async (question: string) => {+ setTracking(question);+ const outcome = await trackDemandQuestion(brandId, question, topic).catch((err: Error) => ({+ promptIds: [] as string[],+ error: err.message,+ code: undefined,+ alreadyTracked: false,+ }));+ setTracking(null);+ if (outcome.promptIds.length > 0 || outcome.alreadyTracked) {+ setTracked((prev) => new Set(prev).add(question));+ toast.success(+ t(outcome.alreadyTracked ? 'paa.alreadyTrackedToast' : 'paa.trackedToast', { question }),+ );+ return;+ }+ toast.error(+ outcome.code === 'plan_limit' ? t('paa.planLimit') : outcome.error || t('paa.trackFailed'),+ );+ };++ return (+ <SignalCard+ title={t('paa.title')}+ window={t('paa.window')}+ footer={paa ? t('readOn', { source: t('paa.source'), date: formatDate(paa.at) }) : null}+ >+ {paa ? (+ paa.questions.length > 0 ? (+ <ul className="flex flex-col gap-1.5">+ {paa.questions.map(({ question, tracked: trackedBefore }) => {+ const done = trackedBefore === true || tracked.has(question);+ return (+ <li key={question} className="flex items-start justify-between gap-2">+ <span className="min-w-0 break-words text-sm">{question}</span>+ <Button+ size="sm"+ variant="outline"+ className="h-6 shrink-0 px-2 text-xs"+ disabled={!canManage || done || tracking !== null}+ title={canManage ? undefined : t('paa.trackNotAllowed')}+ aria-label={+ done ? t('paa.trackedLabel', { question }) : t('paa.trackLabel', { question })+ }+ onClick={() => void track(question)}+ >+ {tracking === question+ ? t('paa.tracking')+ : done+ ? t('paa.tracked')+ : t('paa.track')}+ </Button>+ </li>+ );+ })}+ </ul>+ ) : (+ <StateText>{t('paa.none')}</StateText>+ )+ ) : (+ <PaidState demand={demand} signal="paa" />+ )}+ </SignalCard>+ );+}++function YoutubeCard({ demand }: { demand: PromptDemand }) {+ const t = useTranslations('promptDemand');+ const youtube = demand.youtube;+ // The provider's link, only when it's a web page (the server keeps no other).+ const topUrl =+ youtube?.top?.url && /^https?:\/\//i.test(youtube.top.url) ? youtube.top.url : null;+ return (+ <SignalCard+ title={t('youtube.title')}+ window={t('youtube.window')}+ footer={+ youtube ? t('readOn', { source: t('youtube.source'), date: formatDate(youtube.at) }) : null+ }+ >+ {youtube ? (+ youtube.videos > 0 ? (+ <>+ <p>+ {t.rich('youtube.totals', {+ views: formatCompactNumber(youtube.views),+ videos: youtube.videos,+ b: bold,+ })}+ </p>+ {youtube.top && (+ <p className="break-words text-xs text-muted-foreground">+ {topUrl ? (+ <a+ href={topUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="hover:text-foreground hover:underline"+ >+ {t('youtube.top', {+ title: youtube.top.title,+ views: formatCompactNumber(youtube.top.views),+ })}+ </a>+ ) : (+ t('youtube.top', {+ title: youtube.top.title,+ views: formatCompactNumber(youtube.top.views),+ })+ )}+ </p>+ )}+ {youtube.results !== null && (+ <p className="text-xs text-muted-foreground">+ {t('youtube.results', { count: formatNumber(youtube.results) })}+ </p>+ )}+ </>+ ) : (+ <StateText>{t('youtube.none')}</StateText>+ )+ ) : (+ <PaidState demand={demand} signal="youtube" />+ )}+ </SignalCard>+ );+}++/**+ * "Demand · is this asked for real?" (PROMPT-014, mockup screen 2): the+ * prompt's four demand signals in a 2×2 grid, each with its source and the+ * day it was read, or what to do to get it, and what the level does to the+ * prompt's Priority Score. A People Also Ask question is tracked in one click.+ */+export function DemandSection({+ demand,+ failed,+ gscStatus,+ brandId,+ topic,+ canManage,+ onGscConnected,+}: {+ /** Null while it loads. */+ demand: PromptDemand | null;+ failed: boolean;+ /** The brand's Search Console state; null while it loads or when it couldn't be read. */+ gscStatus: GoogleSourceStatus | null;+ brandId: string;+ /** The prompt's topic: a tracked question joins it. */+ topic: string;+ /** Admins and managers: connect Search Console, track a question. */+ canManage: boolean;+ onGscConnected: () => void;+}) {+ const t = useTranslations('promptDemand');+ return (+ <section className="space-y-3" aria-label={t('title')}>+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <h2 className="text-sm font-medium">{t('title')}</h2>+ {demand?.keyword && (+ <span className="min-w-0 break-words text-xs text-muted-foreground">+ {t('keyword', { keyword: demand.keyword })}+ </span>+ )}+ </div>+ {failed ? (+ <Card>+ <CardContent className="p-4 text-sm text-muted-foreground">{t('loadFailed')}</CardContent>+ </Card>+ ) : !demand ? (+ <div className="grid gap-4 md:grid-cols-2">+ {DEMAND_SIGNALS.map((signal) => (+ <Skeleton key={signal} className="h-32" />+ ))}+ </div>+ ) : (+ <>+ <div className="grid gap-4 md:grid-cols-2">+ <GscCard+ demand={demand}+ gscStatus={gscStatus}+ canManage={canManage}+ onConnected={onGscConnected}+ />+ <TrendsCard demand={demand} />+ <PaaCard demand={demand} brandId={brandId} topic={topic} canManage={canManage} />+ <YoutubeCard demand={demand} />+ </div>+ <p className="text-xs text-muted-foreground">+ {demand.level ? t.rich(`note.${demand.level}`, { b: bold }) : t('note.none')}+ </p>+ </>+ )}+ </section>+ );+}diff --git a/web/src/lib/actions/prompt-demand-signals.test.ts b/web/src/lib/actions/prompt-demand-signals.test.tsnew file mode 100644index 000000000..9f7c7ad8a--- /dev/null+++ b/web/src/lib/actions/prompt-demand-signals.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * "+ Track" on a People Also Ask question (PROMPT-014): the question is+ * tracked once. A brand that already tracks the same text (case, accents,+ * punctuation and spacing aside) gets nothing added.+ */++let brandPrompts: { text: string }[] = [];+let pages: [number, number][] = [];++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: {+ getSession: async () => ({ data: { session: { access_token: 'token' } } }),+ },+ from: (table: string) => {+ expect(table).toBe('prompts');+ const chain = {+ select: () => chain,+ eq: () => chain,+ order: () => chain,+ range: async (from: number, to: number) => {+ pages.push([from, to]);+ return { data: brandPrompts.slice(from, to + 1), error: null };+ },+ };+ return chain;+ },+ })),+}));++const trackPagePrompts = vi.fn();+vi.mock('@/lib/actions/prompt-suggestions', () => ({+ trackPagePrompts: (...args: unknown[]) => trackPagePrompts(...args),+}));++const { getPromptDemandSignals, trackDemandQuestion } = await import('./prompt-demand-signals');++beforeEach(() => {+ brandPrompts = [{ text: 'What is the best AI search monitoring tool?' }];+ pages = [];+ trackPagePrompts.mockReset().mockResolvedValue({ promptIds: ['n1'] });+});++describe('trackDemandQuestion', () => {+ it('tracks a question the brand has no prompt for, in its topic', async () => {+ expect(+ await trackDemandQuestion('b1', ' How do I track my brand in ChatGPT? ', 'Monitoring'),+ ).toEqual({+ promptIds: ['n1'],+ });+ expect(trackPagePrompts).toHaveBeenCalledWith('b1', null, [+ { text: 'How do I track my brand in ChatGPT?', topic: 'Monitoring' },+ ]);+ });++ it('adds nothing a second time for the same text, however it is written', async () => {+ brandPrompts.push({ text: 'how do i track my brand in chatgpt' });+ expect(+ await trackDemandQuestion('b1', 'How do I track my brand in ChatGPT?', 'Monitoring'),+ ).toEqual({+ promptIds: [],+ alreadyTracked: true,+ });+ expect(trackPagePrompts).not.toHaveBeenCalled();+ });++ it("reads every page of the brand's prompts", async () => {+ brandPrompts = Array.from({ length: 1000 }, (_, i) => ({ text: `prompt ${i}` }));+ brandPrompts.push({ text: 'How do I track my brand in ChatGPT' });+ expect(await trackDemandQuestion('b1', 'How do I track my brand in ChatGPT?', 'x')).toEqual({+ promptIds: [],+ alreadyTracked: true,+ });+ expect(pages).toEqual([+ [0, 999],+ [1000, 1999],+ ]);+ });++ it('asks for a question', async () => {+ expect(await trackDemandQuestion('b1', ' ', 'x')).toEqual({+ promptIds: [],+ error: 'Pick a question.',+ });+ expect(trackPagePrompts).not.toHaveBeenCalled();+ });+});++describe('getPromptDemandSignals', () => {+ const answer = (status: number, body: string) =>+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response(body, { status })),+ );++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('reads the demand', async () => {+ answer(200, JSON.stringify({ demand: { level: 'high' } }));+ expect(await getPromptDemandSignals('p1')).toEqual({ demand: { level: 'high' } });+ });++ it('is unavailable on an API without the route yet', async () => {+ answer(404, '<pre>Cannot GET /api/prompts/p1/demand</pre>');+ expect(await getPromptDemandSignals('p1')).toEqual({ unavailable: true });+ });++ it("keeps the route's own 404 and other failures as errors", async () => {+ answer(404, JSON.stringify({ error: 'Prompt not found' }));+ expect(await getPromptDemandSignals('p1')).toEqual({ error: 'Prompt not found' });+ answer(500, JSON.stringify({ error: 'Failed to load demand' }));+ expect(await getPromptDemandSignals('p1')).toEqual({ error: 'Failed to load demand' });+ answer(502, 'Bad gateway');+ expect(await getPromptDemandSignals('p1')).toEqual({ error: 'Server error: 502' });+ });+});diff --git a/web/src/lib/actions/prompt-demand-signals.ts b/web/src/lib/actions/prompt-demand-signals.tsnew file mode 100644index 000000000..8e5a07f28--- /dev/null+++ b/web/src/lib/actions/prompt-demand-signals.ts@@ -0,0 +1,77 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';+import { trackPagePrompts, type TrackPagePromptsResult } from '@/lib/actions/prompt-suggestions';+import { questionKey, type PromptDemand } from '@/lib/prompt-demand';++/**+ * A prompt's real demand (PROMPT-014) for its Demand card: what the+ * server's nightly sweep read. A failure comes back as a value, so the card+ * can say it couldn't load instead of the page failing. A 404 without our+ * error body is an API that doesn't have the route yet: `unavailable`, and+ * the page leaves the section out.+ */+export async function getPromptDemandSignals(+ promptId: string,+): Promise<{ demand: PromptDemand } | { error: string } | { unavailable: true }> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ try {+ const res = await fetch(`${API_BASE_URL}/api/prompts/${encodeURIComponent(promptId)}/demand`, {+ headers: { Authorization: `Bearer ${session.access_token}` },+ cache: 'no-store',+ signal: AbortSignal.timeout(15_000),+ });+ const data = await res.json().catch(() => ({}));+ if (res.status === 404 && !data.error && !data.message) return { unavailable: true };+ if (!res.ok || !data.demand) {+ return { error: data.message || data.error || `Server error: ${res.status}` };+ }+ return { demand: data.demand as PromptDemand };+ } catch {+ return { error: 'Could not reach the server. Please try again.' };+ }+}++/** Prompts read per page: PostgREST's own cap. */+const PAGE = 1000;++/**+ * "+ Track" on a People Also Ask question: tracks it in the prompt's topic+ * (trackPagePrompts), unless the brand already tracks a prompt with the same+ * text (questionKey: case, accents, punctuation and spacing don't count).+ * Then nothing is added and `alreadyTracked` says so. The card already shows+ * those as tracked (the server's `tracked`); this holds for a question+ * tracked since the card loaded.+ */+export async function trackDemandQuestion(+ brandId: string,+ question: string,+ topic: string,+): Promise<TrackPagePromptsResult & { alreadyTracked?: boolean }> {+ const text = typeof question === 'string' ? question.trim() : '';+ if (!text) return { promptIds: [], error: 'Pick a question.' };++ const supabase = await createClient();+ const key = questionKey(text);+ for (let from = 0; ; from += PAGE) {+ const { data, error } = await supabase+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .order('id', { ascending: true })+ .range(from, from + PAGE - 1);+ if (error) return { promptIds: [], error: error.message };+ const rows = (data ?? []) as { text: string | null }[];+ if (rows.some((row) => questionKey(row.text ?? '') === key)) {+ return { promptIds: [], alreadyTracked: true };+ }+ if (rows.length < PAGE) break;+ }+ return trackPagePrompts(brandId, null, [{ text, topic }]);+}diff --git a/web/src/lib/prompt-demand.test.ts b/web/src/lib/prompt-demand.test.tsnew file mode 100644index 000000000..baed8fd04--- /dev/null+++ b/web/src/lib/prompt-demand.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';+import {+ formatChange,+ gscSignalState,+ paidSignalState,+ questionKey,+ type PromptDemand,+} from './prompt-demand';++/** What each Demand card shows when its signal isn't there (PROMPT-014). */++const demand = (over: Partial<PromptDemand> = {}): PromptDemand => ({+ level: null,+ signals: 0,+ updatedAt: null,+ keyword: null,+ locationCode: null,+ languageCode: null,+ gsc: null,+ trends: null,+ paa: null,+ youtube: null,+ pending: { trends: false, paa: false, youtube: false },+ hasVolume: true,+ hasKeyword: true,+ paidSignals: true,+ ...over,+});++describe('paidSignalState', () => {+ it('shows data first, then a task being read, then what is missing', () => {+ const paa = { questions: [], at: '2026-10-27T12:00:00Z' };+ expect(paidSignalState(demand({ paa, hasVolume: false }), 'paa')).toBe('data');+ expect(+ paidSignalState(demand({ pending: { trends: false, paa: true, youtube: false } }), 'paa'),+ ).toBe('pending');+ expect(paidSignalState(demand({ hasVolume: false, hasKeyword: false }), 'paa')).toBe(+ 'noVolume',+ );+ expect(paidSignalState(demand({ hasKeyword: false }), 'trends')).toBe('noKeyword');+ expect(paidSignalState(demand({ paidSignals: false }), 'youtube')).toBe('off');+ expect(paidSignalState(demand(), 'youtube')).toBe('notRead');+ });+});++describe('gscSignalState', () => {+ it("shows what was read whatever the source's state, else the state", () => {+ const gsc = { impressions: 1, clicks: 0, queries: 1, top: null, at: '2026-10-27T12:00:00Z' };+ expect(gscSignalState(demand({ gsc }), 'not_connected')).toBe('data');+ expect(gscSignalState(demand(), 'not_connected')).toBe('not_connected');+ expect(gscSignalState(demand(), 'unmapped')).toBe('unmapped');+ expect(gscSignalState(demand(), 'connected')).toBe('notRead');+ expect(gscSignalState(demand(), null)).toBe('notRead');+ });+});++describe('formatChange', () => {+ it('signs the change', () => {+ expect(formatChange(64)).toBe('+64%');+ expect(formatChange(-12)).toBe('−12%');+ expect(formatChange(0)).toBe('0%');+ });+});++describe('questionKey', () => {+ it('reads the same question written differently as one, as the server does', () => {+ expect(questionKey('How do I track my brand in ChatGPT?')).toBe(+ 'how do i track my brand in chatgpt',+ );+ expect(questionKey(' how do I track my brand in CHATGPT ')).toBe(+ 'how do i track my brand in chatgpt',+ );+ expect(questionKey('Café-crème: what is it?')).toBe('cafe creme what is it');+ expect(questionKey('What is AI search?')).not.toBe(+ questionKey('What is AI search monitoring?'),+ );+ });+});diff --git a/web/src/lib/prompt-demand.ts b/web/src/lib/prompt-demand.tsnew file mode 100644index 000000000..bdf69890d--- /dev/null+++ b/web/src/lib/prompt-demand.ts@@ -0,0 +1,141 @@+/**+ * A prompt's real demand (PROMPT-014) as the Demand card reads it: what the+ * server's nightly sweep read (server/src/lib/prompt-demand.js) and what+ * each card says when a signal isn't there. Measured numbers: they never+ * carry the Estimate badge (PROMPT-013).+ */++import type { GoogleSourceStatus } from '@/lib/traffic-sources';++export type DemandLevel = 'high' | 'medium' | 'low';++/** The four signals; the level counts how many were read. */+export const DEMAND_SIGNALS = ['gsc', 'trends', 'paa', 'youtube'] as const;+export type DemandSignal = (typeof DEMAND_SIGNALS)[number];+export type PaidDemandSignal = Exclude<DemandSignal, 'gsc'>;++/** Search Console over the last 28 days: the brand's queries that match the prompt. */+export interface GscDemand {+ impressions: number;+ clicks: number;+ queries: number;+ top: { query: string; impressions: number; clicks: number } | null;+ at: string;+}++/** Google Trends, 12 months: weekly interest (0–100, relative to its own peak). */+export interface TrendsDemand {+ points: number[];+ trend: 'rising' | 'steady' | 'falling' | null;+ /** Percent between the first and the last four weeks; null without a base. */+ change: number | null;+ from: string | null;+ to: string | null;+ at: string;+}++export interface PaaDemand {+ questions: {+ question: string;+ url: string | null;+ domain: string | null;+ /** The brand already tracks a prompt with this text (questionKey). */+ tracked?: boolean;+ }[];+ at: string;+}++export interface YoutubeDemand {+ /** Videos read: YouTube's first results. */+ videos: number;+ /** Their views, summed. */+ views: number;+ /** How many results YouTube says it has. */+ results: number | null;+ top: {+ title: string;+ url: string | null;+ channel: string | null;+ views: number;+ published: string | null;+ } | null;+ at: string;+}++/** GET /api/prompts/:id/demand. */+export interface PromptDemand {+ level: DemandLevel | null;+ signals: number;+ updatedAt: string | null;+ /** The keyword the paid signals are read for: the volume analysis's top one. */+ keyword: string | null;+ locationCode: number | null;+ languageCode: string | null;+ gsc: GscDemand | null;+ trends: TrendsDemand | null;+ paa: PaaDemand | null;+ youtube: YoutubeDemand | null;+ /** Tasks set and not read yet. */+ pending: Record<PaidDemandSignal, boolean>;+ /** The prompt has a volume analysis. */+ hasVolume: boolean;+ /** …with a keyword Google has searches for. */+ hasKeyword: boolean;+ /** Trends, PAA and YouTube are read on this server (DEMAND_SIGNALS). */+ paidSignals: boolean;+}++/**+ * What a Trends, People Also Ask or YouTube card shows: its data, or why+ * there is none — being read, no volume analysis yet, no keyword with+ * searches, not read on this server, or not read yet.+ */+export type PaidSignalState = 'data' | 'pending' | 'noVolume' | 'noKeyword' | 'off' | 'notRead';++export function paidSignalState(demand: PromptDemand, signal: PaidDemandSignal): PaidSignalState {+ if (demand[signal]) return 'data';+ if (demand.pending[signal]) return 'pending';+ if (!demand.hasVolume) return 'noVolume';+ if (!demand.hasKeyword) return 'noKeyword';+ if (!demand.paidSignals) return 'off';+ return 'notRead';+}++/**+ * What the Search Console card shows: its data, or the source's state+ * (AI Traffic's, googleSourceStatus) — not connected, no property for this+ * brand, the first sync running, a server without Search Console — or not+ * read yet when it's connected. Unknown state (still loading, or unread):+ * not read yet.+ */+export type GscSignalState = 'data' | Exclude<GoogleSourceStatus, 'connected'> | 'notRead';++export function gscSignalState(+ demand: PromptDemand,+ status: GoogleSourceStatus | null,+): GscSignalState {+ if (demand.gsc) return 'data';+ if (!status || status === 'connected') return 'notRead';+ return status;+}++/**+ * A prompt's text as compared for "already tracked": case, accents,+ * punctuation and spacing don't count. The server marks the People Also Ask+ * questions the brand tracks the same way (server/src/lib/prompt-demand.js).+ */+export function questionKey(text: string): string {+ return text+ .normalize('NFKD')+ .replace(/\p{M}/gu, '')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, ' ')+ .trim();+}++/** "+64%", "−12%", "0%": a year's change as the Trends card says it. */+export function formatChange(change: number): string {+ if (change > 0) return `+${change}%`;+ if (change < 0) return `−${Math.abs(change)}%`;+ return '0%';+}