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 an Improve tab with platform-specific position suggestions (#1011)
Cihanf78b4b6940a2
diff --git a/server/.env.example b/server/.env.exampleindex 9f4f07b06..b4ce348ee 100644--- a/server/.env.example+++ b/server/.env.example@@ -44,6 +44,11 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview# Groups prompts into clusters and judges their fan-out queries (#857).# Falls back to DEFAULT_SUGGESTION_MODEL when unset.# PROMPT_CLUSTER_MODEL=openai/gpt-6-luna+# Positions panel → Improve tab suggestions (provider/model). One call per+# generation, charged at its token cost against the plan's monthly budget+# (improveMonthlyBudgetUsd). Falls back to+# DEFAULT_SUGGESTION_MODEL, then google/gemini-3-flash-preview.+# IMPROVE_SUGGESTION_MODEL=google/gemini-3-flash-preview# Model used for the Site Audit LLM-judged signals (provider/model). Cheap by# default; point it at anthropic/claude-... or openai/... if you prefer.AUDIT_LLM_MODEL=google/gemini-3-flash-previewdiff --git a/server/src/config/plans.js b/server/src/config/plans.jsindex 5fa8b9f24..eaa9d07f2 100644--- a/server/src/config/plans.js+++ b/server/src/config/plans.js@@ -15,6 +15,7 @@ export const PLANS = {maxDomainsPerBrand: -1,maxVolumeAnalyses: -1,maxBriefGenerations: -1,+ improveMonthlyBudgetUsd: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -31,6 +32,7 @@ export const PLANS = {'api_access','ai_agent','shopping_analytics',+ 'prompt_improve',],},},@@ -45,6 +47,7 @@ export const PLANS = {maxDomainsPerBrand: 3,maxVolumeAnalyses: 4,maxBriefGenerations: 10,+ improveMonthlyBudgetUsd: 0,maxSiteAudits: 100,maxDailyOnDemand: 3,onDemandCooldownMinutes: 15,@@ -76,6 +79,8 @@ export const PLANS = {maxDomainsPerBrand: 10,maxVolumeAnalyses: 10,maxBriefGenerations: 50,+ // 1% of the $249 price, spent on Improve model calls (PROMPT-003).+ improveMonthlyBudgetUsd: 2.49,maxSiteAudits: 500,maxDailyOnDemand: 10,onDemandCooldownMinutes: 5,@@ -95,6 +100,7 @@ export const PLANS = {'api_access','ai_agent','shopping_analytics',+ 'prompt_improve',],},},@@ -110,6 +116,9 @@ export const PLANS = {maxVolumeAnalyses: -1,// Per-customer: override via organizations.plan_overrides in the DB.maxBriefGenerations: -1,+ // 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%+ // of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.+ improveMonthlyBudgetUsd: 4.99,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -132,6 +141,7 @@ export const PLANS = {'sso_saml','ai_agent','shopping_analytics',+ 'prompt_improve',],},},diff --git a/server/src/lib/improve-cost.js b/server/src/lib/improve-cost.jsnew file mode 100644index 000000000..4c3a991d7--- /dev/null+++ b/server/src/lib/improve-cost.js@@ -0,0 +1,74 @@+/**+ * What an Improve generation (PROMPT-003) actually cost, so the monthly+ * quota can be a dollar budget — a share of what the customer pays — and stay+ * there whichever model IMPROVE_SUGGESTION_MODEL points at.+ *+ * List prices in USD per million tokens. Update this table when a provider+ * changes its prices or a new model is configured; a model missing here is+ * charged at FALLBACK_PRICE, deliberately expensive, so an unknown model can+ * only use the budget up faster, never overspend it.+ */++export const MODEL_PRICES = {+ 'google/gemini-3-flash-preview': { input: 0.5, output: 3 },+ 'google/gemini-3-flash': { input: 0.5, output: 3 },+ 'openai/gpt-5-mini': { input: 0.25, output: 2 },+ 'anthropic/claude-haiku-4-5': { input: 1, output: 5 },+};++export const FALLBACK_PRICE = { input: 5, output: 25 };++/** Share of the plan price the Improve feature may spend on model calls. */+export const IMPROVE_BUDGET_SHARE = 0.01;++/**+ * A typical generation, used to estimate "generations left" before an org+ * has any history: ~7k input and ~2k output tokens on the configured model.+ */+const TYPICAL_TOKENS = { input: 7000, output: 2000 };++/**+ * OpenRouter ids carry the provider id after an `openrouter/` prefix+ * (`openrouter/google/gemini-3-flash-preview`); they're priced as that model.+ */+export function priceFor(modelId) {+ const id = String(modelId ?? '').replace(/^openrouter\//, '');+ return MODEL_PRICES[id] ?? FALLBACK_PRICE;+}++/** USD cost of one call from the AI SDK's `usage`. */+export function generationCostUsd(modelId, usage) {+ const price = priceFor(modelId);+ const input = Number(usage?.inputTokens) || 0;+ const output = Number(usage?.outputTokens) || 0;+ return (input * price.input + output * price.output) / 1_000_000;+}++export function typicalCostUsd(modelId) {+ return generationCostUsd(modelId, {+ inputTokens: TYPICAL_TOKENS.input,+ outputTokens: TYPICAL_TOKENS.output,+ });+}++/**+ * The org's typical generation cost: the median of its recent ones, so one+ * unusually long answer doesn't swing the estimate. Null with no history.+ */+export function medianCost(costs) {+ const sorted = costs.filter((c) => c > 0).sort((a, b) => a - b);+ if (sorted.length === 0) return null;+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++/**+ * The counter users see: about how many generations the remaining budget+ * buys, at the org's typical cost (or the model's before it has any).+ * Dollars stay internal.+ */+export function estimateGenerationsLeft(remainingUsd, avgCostUsd) {+ if (remainingUsd <= 0) return 0;+ if (!(avgCostUsd > 0)) return 0;+ return Math.floor(remainingUsd / avgCostUsd);+}diff --git a/server/src/lib/improve-cost.test.js b/server/src/lib/improve-cost.test.jsnew file mode 100644index 000000000..a63240c34--- /dev/null+++ b/server/src/lib/improve-cost.test.js@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';+import {+ FALLBACK_PRICE,+ MODEL_PRICES,+ estimateGenerationsLeft,+ generationCostUsd,+ medianCost,+ priceFor,+ typicalCostUsd,+} from './improve-cost.js';++describe('generationCostUsd', () => {+ it('prices input and output tokens per million at the model rate', () => {+ // Gemini 3 Flash: $0.50 in / $3 out per 1M.+ expect(+ generationCostUsd('google/gemini-3-flash-preview', { inputTokens: 7000, outputTokens: 2000 }),+ ).toBeCloseTo(0.0095, 6);+ // GPT-5 mini: $0.25 / $2.+ expect(+ generationCostUsd('openai/gpt-5-mini', { inputTokens: 1_000_000, outputTokens: 0 }),+ ).toBe(0.25);+ });++ it('charges an unknown model at the expensive fallback, never at zero', () => {+ expect(priceFor('someone/new-model')).toBe(FALLBACK_PRICE);+ expect(priceFor('openrouter/someone/new-model')).toBe(FALLBACK_PRICE);+ expect(generationCostUsd('someone/new-model', { inputTokens: 1000, outputTokens: 1000 })).toBe(+ 0.03,+ );+ });++ it('prices an OpenRouter id as the model it routes to', () => {+ expect(priceFor('openrouter/google/gemini-3-flash-preview')).toBe(+ MODEL_PRICES['google/gemini-3-flash-preview'],+ );+ });++ it('treats missing usage as zero tokens', () => {+ expect(generationCostUsd('openai/gpt-5-mini', undefined)).toBe(0);+ });+});++describe('the same 1% budget buys more on a cheaper model', () => {+ it('Growth ($2.49) on Flash vs GPT-5 mini vs Haiku', () => {+ const left = (model) => estimateGenerationsLeft(2.49, typicalCostUsd(model));+ expect(left('google/gemini-3-flash-preview')).toBe(262);+ expect(left('openai/gpt-5-mini')).toBe(433);+ expect(left('anthropic/claude-haiku-4-5')).toBe(146);+ });+});++describe('estimateGenerationsLeft', () => {+ it('is zero once the budget is spent or the cost is unknown', () => {+ expect(estimateGenerationsLeft(0, 0.01)).toBe(0);+ expect(estimateGenerationsLeft(1, 0)).toBe(0);+ });++ it('rounds down', () => {+ expect(estimateGenerationsLeft(0.1, 0.03)).toBe(3);+ });+});++describe('medianCost', () => {+ it('ignores one outlier', () => {+ expect(medianCost([0.0095, 0.0095, 1.6, 0.0095])).toBe(0.0095);+ });++ it('averages the two middle values of an even list, and is null when empty', () => {+ expect(medianCost([0.01, 0.03])).toBe(0.02);+ expect(medianCost([])).toBeNull();+ });+});diff --git a/server/src/lib/plan-guard.js b/server/src/lib/plan-guard.jsindex e911b1d2b..c6c246925 100644--- a/server/src/lib/plan-guard.js+++ b/server/src/lib/plan-guard.js@@ -7,6 +7,12 @@ import {isSubscriptionActive,} from '../config/plans.js';import { anchoredPeriodStart } from './quota-period.js';+import {+ IMPROVE_BUDGET_SHARE,+ estimateGenerationsLeft,+ medianCost,+ typicalCostUsd,+} from './improve-cost.js';export class PlanLimitError extends Error {constructor(message, statusCode = 403) {@@ -19,6 +25,11 @@ export class PlanLimitError extends Error {/*** Enterprise orgs can have per-customer limit overrides stored in* organizations.plan_overrides (jsonb) — mirrors web getOrgPlan().+ *+ * `contractMonthlyUsd` is the contract's monthly value, entered when the deal+ * is signed. It sets the Improve budget to the same 1% share of the contract+ * the other plans get of their price (never below the plan default), unless+ * `improveMonthlyBudgetUsd` is set explicitly, which wins.*/export function applyPlanOverrides(plan, org) {if (@@ -27,7 +38,16 @@ export function applyPlanOverrides(plan, org) {typeof org.plan_overrides === 'object' &&!Array.isArray(org.plan_overrides)) {- return { ...plan, limits: { ...plan.limits, ...org.plan_overrides } };+ const overrides = org.plan_overrides;+ const limits = { ...plan.limits, ...overrides };+ const usd = Number(overrides.contractMonthlyUsd);+ if (overrides.improveMonthlyBudgetUsd === undefined && Number.isFinite(usd) && usd > 0) {+ limits.improveMonthlyBudgetUsd = Math.max(+ plan.limits.improveMonthlyBudgetUsd ?? 0,+ Math.round(usd * IMPROVE_BUDGET_SHARE * 100) / 100,+ );+ }+ return { ...plan, limits };}return plan;}@@ -267,6 +287,55 @@ export async function getBriefQuotaStatus(orgId) {return { used, limit: max, remaining: Math.max(0, max - used) };}+async function improveSpendThisPeriod(orgId) {+ const periodStart = await quotaPeriodStart(orgId);+ const { data } = await supabaseAdmin+ .from('prompt_improve_usage')+ .select('cost_usd')+ .eq('organization_id', orgId)+ .gte('used_at', periodStart.toISOString())+ .order('used_at', { ascending: false })+ .limit(5000);+ const costs = (data ?? []).map((r) => Number(r.cost_usd) || 0);+ const spent = costs.reduce((a, b) => a + b, 0);+ return { spent, typical: medianCost(costs.slice(0, 20)) };+}++/**+ * Improve-tab budget (PROMPT-003): a monthly USD budget per organization,+ * 1% of the plan price (plan.limits.improveMonthlyBudgetUsd), charged with+ * each generation's real token cost so the share holds for any model. Users+ * see an estimate of generations left, not dollars. -1 is unlimited.+ */+export async function getImproveQuotaStatus(orgId, modelId) {+ const plan = await resolveOrgPlanByOrgId(orgId);+ const budget = plan.limits.improveMonthlyBudgetUsd ?? -1;+ if (budget === -1) return { unlimited: true, planName: plan.name };+ const { spent, typical } = await improveSpendThisPeriod(orgId);+ const remaining = Math.max(0, budget - spent);+ return {+ unlimited: false,+ planName: plan.name,+ budgetUsd: budget,+ spentUsd: spent,+ remainingUsd: remaining,+ generationsLeft: estimateGenerationsLeft(remaining, typical ?? typicalCostUsd(modelId)),+ percentLeft: budget > 0 ? Math.round((remaining / budget) * 100) : 0,+ };+}++/** Throws PlanLimitError (429) once the period's Improve budget is spent. */+export async function enforceImproveQuota(orgId, modelId) {+ const quota = await getImproveQuotaStatus(orgId, modelId);+ if (!quota.unlimited && quota.remainingUsd <= 0) {+ throw new PlanLimitError(+ `This month's suggestion budget on the ${quota.planName} plan is used up. It resets when your subscription renews.`,+ 429,+ );+ }+ return quota;+}+async function countSiteAuditUsageThisMonth(orgId) {const periodStart = await quotaPeriodStart(orgId);const { count } = await supabaseAdmindiff --git a/server/src/lib/plan-guard.test.js b/server/src/lib/plan-guard.test.jsindex ce2912e04..4065b84a6 100644--- a/server/src/lib/plan-guard.test.js+++ b/server/src/lib/plan-guard.test.js@@ -46,3 +46,33 @@ describe('applyPlanOverrides', () => {expect(applyPlanOverrides(plan, { plan: 'enterprise', plan_overrides: [] })).toEqual(plan);});});++describe('applyPlanOverrides — Improve budget from the contract value', () => {+ const enterprise = {+ id: 'enterprise',+ name: 'Enterprise',+ limits: { maxPrompts: -1, improveMonthlyBudgetUsd: 4.99 },+ };+ const budget = (plan_overrides) =>+ applyPlanOverrides(enterprise, { plan: 'enterprise', plan_overrides }).limits+ .improveMonthlyBudgetUsd;++ it('is 1% of the monthly contract', () => {+ expect(budget({ contractMonthlyUsd: 1000 })).toBe(10);+ expect(budget({ contractMonthlyUsd: 2000 })).toBe(20);+ expect(budget({ contractMonthlyUsd: 1234 })).toBe(12.34);+ });++ it('never drops below the plan default', () => {+ expect(budget({ contractMonthlyUsd: 300 })).toBe(4.99);+ });++ it('an explicit improveMonthlyBudgetUsd wins over the contract value', () => {+ expect(budget({ contractMonthlyUsd: 2000, improveMonthlyBudgetUsd: 7 })).toBe(7);+ });++ it('keeps the default without a usable contract value', () => {+ expect(budget({ maxPrompts: 900 })).toBe(4.99);+ expect(budget({ contractMonthlyUsd: 'n/a' })).toBe(4.99);+ });+});diff --git a/server/src/lib/prompt-improve.js b/server/src/lib/prompt-improve.jsnew file mode 100644index 000000000..53e52522d--- /dev/null+++ b/server/src/lib/prompt-improve.js@@ -0,0 +1,439 @@+/**+ * Positions panel → Improve tab (PROMPT-003): platform-specific suggestions to+ * improve one prompt's position.+ *+ * Pure on purpose. The route loads the answers; this module decides each+ * platform's state, gathers the evidence the model may cite, builds the+ * prompt, and checks what comes back against that evidence. The checks are+ * the point of the feature: a suggestion has to name a real sub-query, URL or+ * competitor, and a source the model invented is dropped rather than shown.+ */++import { z } from 'zod';+import { extractHostname } from './response-parser.js';++/** Labels for the engines the Positions panel lists (web/src/lib/prompt-positions.ts). */+export const IMPROVE_PLATFORM_LABELS = {+ 'chatgpt-web': 'ChatGPT',+ 'perplexity-web': 'Perplexity',+ 'google-aio': 'Google AI Overviews',+ 'google-aimode': 'Google AI Mode',+ 'gemini-web': 'Gemini',+ 'copilot-web': 'Microsoft Copilot',+ 'grok-web': 'Grok',+ claude: 'Claude',+};++/**+ * - no_runs — nothing tracked on this platform in the window+ * - not_mentioned — tracked, the brand appears in fewer than half the runs+ * - mentioned_late — appears, but not first (or with no stored position)+ * - not_cited — appears first, but its pages aren't cited, or cited late+ * - doing_well — first, and cited early: nothing to suggest+ */+export const IMPROVE_STATES = [+ 'no_runs',+ 'not_mentioned',+ 'mentioned_late',+ 'not_cited',+ 'doing_well',+];++/** States that get suggestions. */+export const ACTIONABLE_STATES = ['not_mentioned', 'mentioned_late', 'not_cited'];++export const SOURCE_TYPES = ['fanout', 'domain', 'answer', 'competitor_url', 'brand_page'];++const MAX_FANOUTS = 12;+const MAX_DOMAINS = 10;+const MAX_COMPETITOR_URLS = 8;+const MAX_COMPETITORS = 6;+const MAX_BRAND_PAGES = 6;+const EXCERPT_CHARS = 1200;++/**+ * Below this share of runs mentioning the brand, the platform counts as not+ * mentioned: a brand in 8 of 120 answers is mostly missing there, and needs+ * coverage advice, not positioning advice, however high those 8 ranked.+ */+export const MIN_MENTION_RATE = 0.5;++/** Same split as web/src/lib/position-tone.ts: first third Early, last third Late. */+export function positionTone(rank, total) {+ const ratio = total > 1 ? (rank - 1) / (total - 1) : 0;+ return ratio <= 1 / 3 ? 'Early' : ratio >= 2 / 3 ? 'Late' : 'Mid';+}++function normalizeDomains(domains) {+ return (domains || [])+ .map(+ (d) =>+ extractHostname(d) ??+ String(d ?? '')+ .trim()+ .toLowerCase(),+ )+ .filter(Boolean);+}++function hostMatches(host, domains) {+ return !!host && domains.some((d) => host === d || host.endsWith(`.${d}`));+}++/** The brand's first source in an answer, 1-based among sources with a URL. */+export function brandCitationRank(citations, brandDomains) {+ if (!Array.isArray(citations)) return null;+ const domains = normalizeDomains(brandDomains);+ if (domains.length === 0) return null;+ let total = 0;+ let rank = null;+ for (const cite of citations) {+ const url = typeof cite?.url === 'string' ? cite.url.trim() : '';+ if (!url) continue;+ total += 1;+ if (rank === null && hostMatches(extractHostname(url), domains)) rank = total;+ }+ return rank === null ? null : { rank, total };+}++const avg = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null);+const round1 = (n) => (n === null ? null : Math.round(n * 10) / 10);++/**+ * One platform's state over the window. A platform where the brand appears in+ * fewer than MIN_MENTION_RATE of the runs is not mentioned. Otherwise+ * positions are averaged over the runs that mention the brand, so one lucky+ * #1 among many #4s still reads "late". Rows: prompt_results with+ * mention_count, mention_position, mentioned_entity_count and citations.+ */+export function classifyPlatform(rows, brandDomains) {+ const runs = rows.length;+ if (runs === 0) {+ return {+ state: 'no_runs',+ runs,+ mentionedRuns: 0,+ citedRuns: 0,+ mentionPosition: null,+ citationRank: null,+ };+ }++ const mentioned = rows.filter((r) => (r.mention_count ?? 0) > 0);+ const positions = mentioned+ .map((r) => r.mention_position)+ .filter((p) => typeof p === 'number' && p > 0);+ const totals = mentioned+ .map((r) => r.mentioned_entity_count)+ .filter((t) => typeof t === 'number' && t > 0);+ const citations = rows.map((r) => brandCitationRank(r.citations, brandDomains)).filter(Boolean);++ const mentionPosition = round1(avg(positions));+ const mentionTotal = round1(avg(totals));+ const citationRank = citations.length+ ? {+ rank: round1(avg(citations.map((c) => c.rank))),+ total: round1(avg(citations.map((c) => c.total))),+ }+ : null;++ let state;+ if (mentioned.length < runs * MIN_MENTION_RATE) state = 'not_mentioned';+ else if (mentionPosition === null || Math.round(mentionPosition) > 1) state = 'mentioned_late';+ else if (!citationRank || positionTone(citationRank.rank, citationRank.total) !== 'Early') {+ state = 'not_cited';+ } else state = 'doing_well';++ return {+ state,+ runs,+ mentionedRuns: mentioned.length,+ citedRuns: citations.length,+ mentionPosition,+ mentionTotal,+ citationRank,+ };+}++function topCounts(map, n) {+ return [...map.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n);+}++function bump(map, key, by = 1) {+ map.set(key, (map.get(key) ?? 0) + by);+}++/**+ * Around the brand's first mention when the answer has one, so the model sees+ * which attributes earned the slots above it; otherwise the opening.+ */+export function answerExcerpt(response, brandName) {+ const text = typeof response === 'string' ? response.replace(/\s+/g, ' ').trim() : '';+ if (!text) return '';+ if (text.length <= EXCERPT_CHARS) return text;+ const at = brandName ? text.toLowerCase().indexOf(brandName.toLowerCase()) : -1;+ if (at < 0) return `${text.slice(0, EXCERPT_CHARS)}…`;+ const start = Math.max(0, at - EXCERPT_CHARS * 0.6);+ const end = Math.min(text.length, start + EXCERPT_CHARS);+ return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;+}++/**+ * The evidence one platform's answers offer: the sub-queries it ran, the+ * domains it cited, the competitors it named and their cited URLs, and the+ * brand's own cited pages. Rows are newest first; `latestResponse` is the+ * newest answer's text.+ */+export function collectEvidence(rows, { brandName, brandDomains, competitors, latestResponse }) {+ const own = normalizeDomains(brandDomains);+ const competitorDomains = (competitors || [])+ .map((c) => ({ name: c.name, domain: extractHostname(c.domain) ?? c.domain?.toLowerCase() }))+ .filter((c) => c.domain);++ const fanouts = new Map();+ const domains = new Map();+ const competitorUrls = new Map();+ const brandPages = new Map();+ const competitorStats = new Map();++ for (const row of rows) {+ const seen = new Set();+ for (const q of Array.isArray(row.search_queries) ? row.search_queries : []) {+ const query = typeof q?.query === 'string' ? q.query.trim() : '';+ if (!query || seen.has(query.toLowerCase())) continue;+ seen.add(query.toLowerCase());+ bump(fanouts, query);+ }+ for (const cite of Array.isArray(row.citations) ? row.citations : []) {+ const url = typeof cite?.url === 'string' ? cite.url.trim() : '';+ const host = extractHostname(url);+ if (!host) continue;+ bump(domains, host);+ if (hostMatches(host, own)) bump(brandPages, url);+ else if (competitorDomains.some((c) => hostMatches(host, [c.domain])))+ bump(competitorUrls, url);+ }+ for (const m of Array.isArray(row.competitor_mentions) ? row.competitor_mentions : []) {+ if (!m?.name || !((m.mention_count ?? 0) > 0)) continue;+ const s = competitorStats.get(m.name) ?? { runs: 0, positions: [] };+ s.runs += 1;+ if (typeof m.mention_position === 'number') s.positions.push(m.mention_position);+ competitorStats.set(m.name, s);+ }+ }++ return {+ fanouts: topCounts(fanouts, MAX_FANOUTS).map(([query, count]) => ({ query, count })),+ citedDomains: topCounts(domains, MAX_DOMAINS).map(([domain, count]) => ({+ domain,+ count,+ own: hostMatches(domain, own),+ })),+ competitorUrls: topCounts(competitorUrls, MAX_COMPETITOR_URLS).map(([url, count]) => ({+ url,+ count,+ })),+ brandPages: topCounts(brandPages, MAX_BRAND_PAGES).map(([url, count]) => ({ url, count })),+ competitors: [...competitorStats.entries()]+ .sort((a, b) => b[1].runs - a[1].runs || a[0].localeCompare(b[0]))+ .slice(0, MAX_COMPETITORS)+ .map(([name, s]) => ({ name, runs: s.runs, avgPosition: round1(avg(s.positions)) })),+ excerpt: answerExcerpt(latestResponse, brandName),+ };+}++const STATE_LABELS = {+ not_mentioned: 'NOT MENTIONED',+ mentioned_late: 'MENTIONED LATE',+ not_cited: 'MENTIONED EARLY BUT NOT CITED / CITED LATE',+};++const STATE_GUIDANCE = {+ not_mentioned:+ 'Coverage gaps: pages to create or extend so they answer the sub-queries, and third-party sites (from the cited domains) to get listed on.',+ mentioned_late:+ 'Positioning: which attributes or claims earn the top slots in the answer, what the competitors ranked above do on their cited pages, and on-page structure changes.',+ not_cited:+ 'Citations: what the cited pages offer that the brand pages do not, and which brand page to strengthen so it becomes a source.',+};++/** The per-item schema the model fills; bounds keep cards short and lists sane. */+export const improveSchema = z.object({+ suggestions: z+ .array(+ z.object({+ platform: z.string().describe('The platform id this suggestion is for, exactly as given'),+ title: z.string().min(5).max(90).describe('Short imperative title'),+ body: z+ .string()+ .min(20)+ .max(420)+ .describe('1-3 sentences: what to do and why, naming the specific evidence'),+ sources: z+ .array(+ z.object({+ type: z.enum(SOURCE_TYPES),+ ref: z+ .string()+ .min(1)+ .max(300)+ .describe(+ 'Copied verbatim from the evidence: a sub-query, a domain, a competitor URL, a brand page URL, or a short quote from the AI answer',+ ),+ }),+ )+ .min(1)+ .max(4),+ confidence: z.enum(['high', 'medium', 'low']),+ }),+ )+ .max(24),+});++function evidenceBlock(evidence) {+ const lines = [];+ if (evidence.fanouts.length) {+ lines.push(+ `Sub-queries it ran (fanout): ${evidence.fanouts.map((f) => `"${f.query}" ×${f.count}`).join('; ')}`,+ );+ } else {+ lines.push(+ 'Sub-queries it ran (fanout): none recorded — use the cited sources and the answer.',+ );+ }+ if (evidence.citedDomains.length) {+ lines.push(+ `Cited domains: ${evidence.citedDomains+ .map((d) => `${d.domain} ×${d.count}${d.own ? ' (brand)' : ''}`)+ .join('; ')}`,+ );+ }+ if (evidence.competitors.length) {+ lines.push(+ `Competitors named: ${evidence.competitors+ .map((c) => `${c.name} (${c.runs} runs${c.avgPosition ? `, avg #${c.avgPosition}` : ''})`)+ .join('; ')}`,+ );+ }+ if (evidence.competitorUrls.length) {+ lines.push(`Competitor URLs cited: ${evidence.competitorUrls.map((u) => u.url).join(' ; ')}`);+ }+ if (evidence.brandPages.length) {+ lines.push(`Brand pages cited: ${evidence.brandPages.map((u) => u.url).join(' ; ')}`);+ }+ if (evidence.excerpt) lines.push(`Latest AI answer (excerpt): """${evidence.excerpt}"""`);+ return lines.map((l) => ` ${l}`).join('\n');+}++/**+ * System and user prompt for one generation. `platforms` are the actionable+ * ones: [{ id, state, mentionPosition, mentionTotal, citationRank, evidence }].+ */+export function buildImprovePrompt({ promptText, brand, platforms }) {+ const system = `You are an AI search (answer engine) optimization strategist. For one tracked prompt, you tell a brand what to do on each AI platform where it is missing or ranked late.++Rules:+- Every suggestion must be specific to the evidence given for ITS platform: name the sub-query, URL, domain, competitor or answer attribute it is based on. No generic SEO advice ("improve your content", "add schema markup", "build backlinks") unless tied to a named page, query or domain.+- Each source's "ref" must be copied verbatim from that platform's evidence. Source types: fanout = a listed sub-query; domain = a listed cited domain; competitor_url = a listed competitor URL; brand_page = a listed brand page; answer = a short quote (under 20 words) from the answer excerpt.+- When a platform has no sub-queries, base it on the cited sources and the answer text instead.+- Never output placeholders such as "prompt [0]", "[1]" or "<brand>". Use real names.+- 1-3 suggestions per platform, most impactful first. Write in English.`;++ const blocks = platforms+ .map((p) => {+ const where =+ p.state === 'not_mentioned' && p.mentionedRuns > 0+ ? ` — mentioned in only ${p.mentionedRuns} of ${p.runs} runs`+ : p.state === 'mentioned_late' && p.mentionPosition+ ? ` — mentioned at avg #${p.mentionPosition}${p.mentionTotal ? ` of ${p.mentionTotal} brands` : ''}`+ : p.state === 'not_cited' && p.citationRank+ ? ` — cited at avg #${p.citationRank.rank} of ${p.citationRank.total} sources`+ : '';+ return `Platform "${p.id}" (${IMPROVE_PLATFORM_LABELS[p.id] ?? p.id}): ${STATE_LABELS[p.state]}${where}+ Kind of suggestion: ${STATE_GUIDANCE[p.state]}+${evidenceBlock(p.evidence)}`;+ })+ .join('\n\n');++ const prompt = `Brand: ${brand.name}${brand.domains?.length ? ` (${brand.domains.join(', ')})` : ''}+${brand.description ? `About the brand: ${brand.description}\n` : ''}Tracked prompt: "${promptText}"++${blocks}++Write the suggestions. Use each platform id exactly as given.`;++ return { system, prompt };+}++const PLACEHOLDER_RE = /\bprompt\s*\[\d+\]|\[\d+\]|<brand>/i;+const norm = (s) =>+ String(s ?? '')+ .trim()+ .toLowerCase()+ .replace(/\/+$/, '');++/** Whether a source points at something that platform's evidence really contains. */+export function isKnownSource(source, evidence) {+ const ref = norm(source.ref);+ if (!ref) return false;+ switch (source.type) {+ case 'fanout':+ return evidence.fanouts.some((f) => norm(f.query) === ref);+ case 'domain': {+ const host = extractHostname(source.ref) ?? ref;+ return (+ evidence.citedDomains.some((d) => d.domain === host) ||+ evidence.competitorUrls.some((u) => extractHostname(u.url) === host)+ );+ }+ case 'competitor_url':+ return evidence.competitorUrls.some((u) => norm(u.url) === ref);+ case 'brand_page':+ return evidence.brandPages.some((u) => norm(u.url) === ref);+ case 'answer':+ // A quote has to appear in the excerpt the model was shown.+ return ref.length >= 3 && norm(evidence.excerpt).includes(ref.replace(/^["'“]|["'”]$/g, ''));+ default:+ return false;+ }+}++/**+ * Keeps what the model returned only where it holds up: a known actionable+ * platform, no placeholder text, and at least one source found in that+ * platform's evidence (invented sources are dropped). Ids are stable within a+ * set so the panel can track edits.+ */+export function sanitizeSuggestions(raw, platforms) {+ const byId = new Map(platforms.map((p) => [p.id, p]));+ const perPlatform = new Map();+ const out = [];+ for (const s of raw ?? []) {+ const platform = byId.get(s?.platform);+ if (!platform || !ACTIONABLE_STATES.includes(platform.state)) continue;+ if (PLACEHOLDER_RE.test(`${s.title} ${s.body}`)) continue;+ const sources = (s.sources ?? [])+ .filter((src) => isKnownSource(src, platform.evidence))+ .map((src) => ({ type: src.type, ref: String(src.ref).trim() }));+ if (sources.length === 0) continue;+ const n = perPlatform.get(platform.id) ?? 0;+ if (n >= 3) continue;+ perPlatform.set(platform.id, n + 1);+ out.push({+ id: `${platform.id}:${n}`,+ platform: platform.id,+ state: platform.state,+ title: s.title.trim(),+ body: s.body.trim(),+ sources,+ confidence: s.confidence,+ });+ }+ return out;+}++/** The cache key for a panel range: a preset, or the custom bounds. */+export function improveRangeKey({ preset, from, to }) {+ if (preset !== 'custom') return preset;+ return `custom:${from ?? ''}:${to ?? ''}`;+}diff --git a/server/src/lib/prompt-improve.test.js b/server/src/lib/prompt-improve.test.jsnew file mode 100644index 000000000..369b2503e--- /dev/null+++ b/server/src/lib/prompt-improve.test.js@@ -0,0 +1,325 @@+import { describe, expect, it } from 'vitest';+import {+ answerExcerpt,+ buildImprovePrompt,+ classifyPlatform,+ collectEvidence,+ improveRangeKey,+ isKnownSource,+ sanitizeSuggestions,+} from './prompt-improve.js';++const BRAND_DOMAINS = ['acme.com'];++const row = (over = {}) => ({+ mention_count: 0,+ mention_position: null,+ mentioned_entity_count: null,+ citations: [],+ search_queries: [],+ competitor_mentions: [],+ ...over,+});++describe('classifyPlatform', () => {+ it('no rows is no_runs', () => {+ expect(classifyPlatform([], BRAND_DOMAINS).state).toBe('no_runs');+ });++ it('tracked but never mentioned is not_mentioned', () => {+ const r = classifyPlatform([row(), row()], BRAND_DOMAINS);+ expect(r).toMatchObject({ state: 'not_mentioned', runs: 2, mentionedRuns: 0 });+ });++ it('mentioned in fewer than half the runs is not_mentioned, however high it ranked', () => {+ const first = row({ mention_count: 1, mention_position: 1, mentioned_entity_count: 5 });+ const rare = classifyPlatform(+ [...Array(8).fill(first), ...Array.from({ length: 112 }, () => row())],+ BRAND_DOMAINS,+ );+ expect(rare).toMatchObject({ state: 'not_mentioned', runs: 120, mentionedRuns: 8 });+ // Exactly half is enough to be judged on position.+ expect(classifyPlatform([first, row()], BRAND_DOMAINS).state).not.toBe('not_mentioned');+ });++ it('mentioned at an average below #1 is mentioned_late', () => {+ const r = classifyPlatform(+ [+ row({ mention_count: 1, mention_position: 1, mentioned_entity_count: 5 }),+ row({ mention_count: 1, mention_position: 4, mentioned_entity_count: 5 }),+ ],+ BRAND_DOMAINS,+ );+ expect(r).toMatchObject({ state: 'mentioned_late', mentionPosition: 2.5, mentionTotal: 5 });+ });++ it('mentioned with no stored position counts as late, not as doing well', () => {+ expect(classifyPlatform([row({ mention_count: 2 })], BRAND_DOMAINS).state).toBe(+ 'mentioned_late',+ );+ });++ it('#1 but not cited is not_cited', () => {+ const r = classifyPlatform(+ [row({ mention_count: 1, mention_position: 1, citations: [{ url: 'https://other.com/a' }] })],+ BRAND_DOMAINS,+ );+ expect(r.state).toBe('not_cited');+ });++ it('#1 but cited late is not_cited', () => {+ const citations = [+ { url: 'https://a.com' },+ { url: 'https://b.com' },+ { url: 'https://c.com' },+ { url: 'https://www.acme.com/page' },+ ];+ const r = classifyPlatform(+ [row({ mention_count: 1, mention_position: 1, citations })],+ BRAND_DOMAINS,+ );+ expect(r).toMatchObject({ state: 'not_cited', citationRank: { rank: 4, total: 4 } });+ });++ it('#1 and cited early is doing_well', () => {+ const citations = [{ url: 'https://shop.acme.com/x' }, { url: 'https://b.com' }];+ const r = classifyPlatform(+ [row({ mention_count: 1, mention_position: 1, citations })],+ BRAND_DOMAINS,+ );+ expect(r.state).toBe('doing_well');+ });+});++describe('collectEvidence', () => {+ const rows = [+ row({+ search_queries: [+ { query: 'best coffee subscription' },+ { query: 'Best Coffee Subscription' },+ ],+ citations: [+ { url: 'https://www.rival.com/plans' },+ { url: 'https://acme.com/subscribe' },+ { url: 'https://reddit.com/r/coffee' },+ ],+ competitor_mentions: [+ { name: 'Rival', mention_count: 2, mention_position: 1 },+ { name: 'Quiet', mention_count: 0 },+ ],+ }),+ row({+ search_queries: [{ query: 'best coffee subscription' }, { query: 'coffee gift box' }],+ citations: [{ url: 'https://rival.com/plans' }],+ competitor_mentions: [{ name: 'Rival', mention_count: 1, mention_position: 3 }],+ }),+ ];+ const ev = collectEvidence(rows, {+ brandName: 'Acme',+ brandDomains: BRAND_DOMAINS,+ competitors: [{ name: 'Rival', domain: 'rival.com' }],+ latestResponse: 'Rival is the top pick. Acme is also good.',+ });++ it('counts each sub-query once per answer, most frequent first', () => {+ expect(ev.fanouts).toEqual([+ { query: 'best coffee subscription', count: 2 },+ { query: 'coffee gift box', count: 1 },+ ]);+ });++ it('splits cited URLs into domains, competitor URLs and brand pages', () => {+ expect(ev.citedDomains[0]).toEqual({ domain: 'rival.com', count: 2, own: false });+ expect(ev.citedDomains.find((d) => d.domain === 'acme.com')?.own).toBe(true);+ expect(ev.competitorUrls.map((u) => u.url)).toContain('https://www.rival.com/plans');+ expect(ev.brandPages).toEqual([{ url: 'https://acme.com/subscribe', count: 1 }]);+ });++ it('keeps only competitors actually named, with their average position', () => {+ expect(ev.competitors).toEqual([{ name: 'Rival', runs: 2, avgPosition: 2 }]);+ });++ it('carries the answer excerpt', () => {+ expect(ev.excerpt).toBe('Rival is the top pick. Acme is also good.');+ });+});++describe('answerExcerpt', () => {+ it('centres a long answer on the brand mention', () => {+ const long = `${'x '.repeat(2000)}Acme wins here ${'y '.repeat(2000)}`;+ const out = answerExcerpt(long, 'Acme');+ expect(out).toContain('Acme wins here');+ expect(out.startsWith('…')).toBe(true);+ expect(out.length).toBeLessThanOrEqual(1203);+ });+});++describe('sanitizeSuggestions', () => {+ const evidence = {+ fanouts: [{ query: 'best coffee subscription', count: 2 }],+ citedDomains: [{ domain: 'reddit.com', count: 1, own: false }],+ competitorUrls: [{ url: 'https://rival.com/plans', count: 1 }],+ brandPages: [],+ competitors: [],+ excerpt: 'Rival is the top pick for freshness.',+ };+ const platforms = [+ { id: 'perplexity-web', state: 'not_mentioned', evidence },+ { id: 'chatgpt-web', state: 'doing_well', evidence },+ ];+ const base = {+ platform: 'perplexity-web',+ title: 'Answer the sub-query',+ body: 'Publish a comparison page that answers the sub-query directly.',+ confidence: 'high',+ };++ it('keeps real sources and drops invented ones', () => {+ const out = sanitizeSuggestions(+ [+ {+ ...base,+ sources: [+ { type: 'fanout', ref: 'Best coffee subscription' },+ { type: 'fanout', ref: 'invented query' },+ { type: 'competitor_url', ref: 'https://rival.com/plans/' },+ { type: 'answer', ref: '"top pick for freshness"' },+ ],+ },+ ],+ platforms,+ );+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({ id: 'perplexity-web:0', state: 'not_mentioned' });+ expect(out[0].sources.map((s) => s.type)).toEqual(['fanout', 'competitor_url', 'answer']);+ });++ it('drops a suggestion with no real source left', () => {+ const out = sanitizeSuggestions(+ [{ ...base, sources: [{ type: 'domain', ref: 'made-up.com' }] }],+ platforms,+ );+ expect(out).toEqual([]);+ });++ it('drops placeholder text, doing-well and unknown platforms', () => {+ const src = [{ type: 'domain', ref: 'reddit.com' }];+ const out = sanitizeSuggestions(+ [+ { ...base, body: 'Target prompt [0] with a new page about it.', sources: src },+ { ...base, platform: 'chatgpt-web', sources: src },+ { ...base, platform: 'nope', sources: src },+ ],+ platforms,+ );+ expect(out).toEqual([]);+ });++ it('caps a platform at three suggestions', () => {+ const src = [{ type: 'domain', ref: 'reddit.com' }];+ const out = sanitizeSuggestions(+ Array.from({ length: 5 }, () => ({ ...base, sources: src })),+ platforms,+ );+ expect(out.map((s) => s.id)).toEqual([+ 'perplexity-web:0',+ 'perplexity-web:1',+ 'perplexity-web:2',+ ]);+ });+});++describe('isKnownSource', () => {+ it('accepts a domain given as a URL', () => {+ expect(+ isKnownSource(+ { type: 'domain', ref: 'https://www.reddit.com' },+ {+ fanouts: [],+ citedDomains: [{ domain: 'reddit.com' }],+ competitorUrls: [],+ brandPages: [],+ excerpt: '',+ },+ ),+ ).toBe(true);+ });+});++describe('buildImprovePrompt', () => {+ it('lists each actionable platform with its state and evidence', () => {+ const { system, prompt } = buildImprovePrompt({+ promptText: 'best coffee subscription',+ brand: { name: 'Acme', domains: ['acme.com'] },+ platforms: [+ {+ id: 'perplexity-web',+ state: 'mentioned_late',+ mentionPosition: 3,+ mentionTotal: 5,+ citationRank: null,+ evidence: {+ fanouts: [{ query: 'q1', count: 2 }],+ citedDomains: [],+ competitors: [],+ competitorUrls: [],+ brandPages: [],+ excerpt: 'text',+ },+ },+ ],+ });+ expect(system).toContain('Never output placeholders');+ expect(prompt).toContain(+ 'Platform "perplexity-web" (Perplexity): MENTIONED LATE — mentioned at avg #3 of 5 brands',+ );+ expect(prompt).toContain('"q1" ×2');+ });++ it('says how rarely a not-mentioned platform names the brand', () => {+ const { prompt } = buildImprovePrompt({+ promptText: 'best coffee subscription',+ brand: { name: 'Acme', domains: [] },+ platforms: [+ {+ id: 'gemini-web',+ state: 'not_mentioned',+ runs: 120,+ mentionedRuns: 8,+ evidence: {+ fanouts: [],+ citedDomains: [],+ competitors: [],+ competitorUrls: [],+ brandPages: [],+ excerpt: '',+ },+ },+ ],+ });+ expect(prompt).toContain('NOT MENTIONED — mentioned in only 8 of 120 runs');+ });+});++describe('improveRangeKey', () => {+ it('keys presets by name and custom ranges by their bounds', () => {+ expect(improveRangeKey({ preset: '30d' })).toBe('30d');+ expect(improveRangeKey({ preset: 'custom', from: '2026-10-01', to: '2026-10-05' })).toBe(+ 'custom:2026-10-01:2026-10-05',+ );+ });+});++describe('Improve plan limits', () => {+ it('is a Growth+ feature with a budget of 1% of the plan price', async () => {+ const { PLANS } = await import('../config/plans.js');+ expect(PLANS.starter.limits.features).not.toContain('prompt_improve');+ expect(PLANS.starter.limits.improveMonthlyBudgetUsd).toBe(0);+ for (const id of ['growth', 'enterprise', 'self_hosted']) {+ expect(PLANS[id].limits.features).toContain('prompt_improve');+ }+ expect(PLANS.growth.limits.improveMonthlyBudgetUsd).toBe(2.49);+ expect(PLANS.enterprise.limits.improveMonthlyBudgetUsd).toBe(4.99);+ expect(PLANS.self_hosted.limits.improveMonthlyBudgetUsd).toBe(-1);+ });+});diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.jsindex a72bce0ef..8cd98ffdc 100644--- a/server/src/routes/prompts.js+++ b/server/src/routes/prompts.js@@ -1,14 +1,30 @@import { Router } from 'express';-import { generateObject } from 'ai';+import { NoObjectGeneratedError, generateObject } from 'ai';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { resolveModel } from '../lib/ai-provider.js';import { classifyPromptIntent } from '../lib/intent-extraction.js';import { getLanguageName } from '../lib/languages.js';-import { requireFeature } from '../lib/plan-guard.js';+import {+ PlanLimitError,+ enforceImproveQuota,+ getImproveQuotaStatus,+ requireFeature,+} from '../lib/plan-guard.js';import { withRetry } from '../lib/retry.js';import { getGscSuggestionCandidates } from '../lib/gsc-suggestions.js';import { getGaSuggestionCandidates } from '../lib/ga-suggestions.js';+import {+ ACTIONABLE_STATES,+ IMPROVE_PLATFORM_LABELS,+ buildImprovePrompt,+ classifyPlatform,+ collectEvidence,+ improveRangeKey,+ improveSchema,+ sanitizeSuggestions,+} from '../lib/prompt-improve.js';+import { generationCostUsd } from '../lib/improve-cost.js';const router = Router();@@ -743,4 +759,334 @@ router.post('/fanout-intents', async (req, res) => {}});+// ─── Positions panel → Improve tab (PROMPT-003) ───────────────────────────────++const IMPROVE_PLATFORM_ORDER = Object.keys(IMPROVE_PLATFORM_LABELS);+const IMPROVE_PRESETS = ['24h', '7d', '30d', '90d', 'custom'];++/**+ * The panel's range as the request states it. `from` / `to` are the resolved+ * ISO bounds the web read the Positions numbers over; the key is what the set+ * is cached under.+ */+function parseImproveRange(input) {+ const preset = IMPROVE_PRESETS.includes(input?.preset) ? input.preset : null;+ const from =+ typeof input?.from === 'string' && !Number.isNaN(Date.parse(input.from)) ? input.from : null;+ const to = typeof input?.to === 'string' && !Number.isNaN(Date.parse(input.to)) ? input.to : null;+ if (!preset || !from) {+ const err = new Error('A valid range (preset and from) is required');+ err.status = 400;+ throw err;+ }+ const region = typeof input?.region === 'string' ? input.region.trim() : '';+ const key = improveRangeKey({+ preset,+ from: input.customFrom ?? from.slice(0, 10),+ to: input.customTo ?? to?.slice(0, 10),+ });+ return { preset, from, to, region, key };+}++async function loadImprovePrompt(promptId, userId) {+ const { data: prompt } = await supabaseAdmin+ .from('prompts')+ .select('id, text, platforms, prompt_sets!inner(brand_id)')+ .eq('id', promptId)+ .maybeSingle();+ if (!prompt) {+ const err = new Error('Prompt not found');+ err.status = 404;+ throw err;+ }+ const brandId = prompt.prompt_sets.brand_id;+ const { brand } = await assertBrandAccess(brandId, userId);+ return { prompt, brand, brandId };+}++// States read every answer in the window, as the Positions tab does; the+// heavy evidence columns come from the newest IMPROVE_EVIDENCE_ROWS only.+const IMPROVE_MAX_ROWS = 5000;+const IMPROVE_PAGE_SIZE = 1000;+const IMPROVE_EVIDENCE_ROWS = 600;+const IMPROVE_ID_CHUNK = 100;++/**+ * The light columns of every answer in the window, newest first, plus the+ * source lists of the cited ones: what classifyPlatform needs.+ */+async function loadImproveStateRows({ promptId, brandId, range }) {+ const rows = [];+ for (let offset = 0; offset < IMPROVE_MAX_ROWS; offset += IMPROVE_PAGE_SIZE) {+ const { data, error } = await improveResultsQuery(+ 'id, platform, created_at, mention_count, mention_position, mentioned_entity_count, citation_count',+ { promptId, brandId, range },+ ).range(offset, offset + IMPROVE_PAGE_SIZE - 1);+ if (error) throw error;+ rows.push(...(data ?? []));+ if ((data ?? []).length < IMPROVE_PAGE_SIZE) break;+ }+ const citedIds = rows.filter((r) => Number(r.citation_count ?? 0) > 0).map((r) => r.id);+ const citationsById = new Map();+ for (let i = 0; i < citedIds.length; i += IMPROVE_ID_CHUNK) {+ const { data, error } = await supabaseAdmin+ .from('prompt_results')+ .select('id, citations')+ .in('id', citedIds.slice(i, i + IMPROVE_ID_CHUNK));+ if (error) throw error;+ for (const r of data ?? []) citationsById.set(r.id, r.citations);+ }+ return rows.map((r) => ({ ...r, citations: citationsById.get(r.id) ?? [] }));+}++/**+ * Charges one model attempt to the org's Improve budget. A failed insert is+ * logged, not thrown: the suggestions the user paid for still go out.+ */+async function recordImproveUsage(log, { organizationId, promptId, modelId, usage }) {+ const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({+ organization_id: organizationId,+ prompt_id: promptId,+ model: modelId,+ input_tokens: usage?.inputTokens ?? null,+ output_tokens: usage?.outputTokens ?? null,+ cost_usd: generationCostUsd(modelId, usage),+ });+ if (error) log.error({ err: error, promptId }, 'prompt improve usage insert error');+}++function improveResultsQuery(columns, { promptId, brandId, range }) {+ let q = supabaseAdmin+ .from('prompt_results')+ .select(columns)+ .eq('prompt_id', promptId)+ .eq('brand_id', brandId)+ .gte('created_at', range.from);+ if (range.to) q = q.lte('created_at', range.to);+ if (range.region) q = q.eq('region', range.region);+ return q.order('created_at', { ascending: false });+}++function improveResponse(row, newestAt) {+ if (!row) return null;+ return {+ rangeKey: row.range_key,+ region: row.region,+ platforms: row.platform_states,+ suggestions: row.suggestions,+ latestResultAt: row.latest_result_at,+ generatedAt: row.generated_at,+ // Newer answers than the set was built from: the panel rebuilds it.+ stale: !!newestAt && (!row.latest_result_at || newestAt > row.latest_result_at),+ };+}++// What the panel shows: an estimate of generations left, never dollars.+function publicQuota(q) {+ if (q.unlimited) {+ return { unlimited: true, exhausted: false, generationsLeft: null, percentLeft: null };+ }+ return {+ unlimited: false,+ exhausted: q.remainingUsd <= 0,+ generationsLeft: q.generationsLeft,+ percentLeft: q.percentLeft,+ };+}++function improveModelId() {+ return (+ process.env.IMPROVE_SUGGESTION_MODEL ||+ process.env.DEFAULT_SUGGESTION_MODEL ||+ 'google/gemini-3-flash-preview'+ );+}++// Read the cached set; never generates.+router.get('/:promptId/improve', requireFeature('prompt_improve'), async (req, res) => {+ try {+ const range = parseImproveRange(req.query);+ const { brand, brandId } = await loadImprovePrompt(req.params.promptId, req.user.id);+ const [{ data: cached }, { data: newest }, quota] = await Promise.all([+ supabaseAdmin+ .from('prompt_improve_suggestions')+ .select('*')+ .eq('prompt_id', req.params.promptId)+ .eq('range_key', range.key)+ .eq('region', range.region)+ .maybeSingle(),+ improveResultsQuery('created_at', { promptId: req.params.promptId, brandId, range }).limit(1),+ getImproveQuotaStatus(brand.organization_id, improveModelId()),+ ]);+ return res.json({+ improve: improveResponse(cached, newest?.[0]?.created_at ?? null),+ quota: publicQuota(quota),+ });+ } catch (error) {+ req.log.error({ err: error }, 'prompt improve read error');+ return res+ .status(error.status || 500)+ .json({ error: error.message || 'Failed to load suggestions' });+ }+});++// Build (or rebuild) the set for the range and cache it.+router.post('/:promptId/improve', requireFeature('prompt_improve'), async (req, res) => {+ try {+ const range = parseImproveRange(req.body);+ const promptId = req.params.promptId;+ const { prompt, brand, brandId } = await loadImprovePrompt(promptId, req.user.id);++ const [+ rows,+ { data: evidenceRows, error: evidenceError },+ { data: domainRows },+ { data: competitors },+ ] = await Promise.all([+ loadImproveStateRows({ promptId, brandId, range }),+ improveResultsQuery(+ 'id, platform, created_at, citations, search_queries, competitor_mentions',+ { promptId, brandId, range },+ ).limit(IMPROVE_EVIDENCE_ROWS),+ supabaseAdmin.from('brand_domains').select('domain').eq('brand_id', brandId),+ supabaseAdmin.from('competitors').select('name, domain').eq('brand_id', brandId),+ ]);+ if (evidenceError) throw evidenceError;+ const brandDomains = (domainRows ?? []).map((r) => r.domain);++ const groupByPlatform = (list) => {+ const map = new Map();+ for (const r of list ?? []) {+ if (!map.has(r.platform)) map.set(r.platform, []);+ map.get(r.platform).push(r);+ }+ return map;+ };+ const byPlatform = groupByPlatform(rows);+ const evidenceByPlatform = groupByPlatform(evidenceRows);+ const platformIds = IMPROVE_PLATFORM_ORDER.filter(+ (id) => byPlatform.has(id) || (prompt.platforms ?? []).includes(id),+ );++ const states = platformIds.map((id) => ({+ id,+ label: IMPROVE_PLATFORM_LABELS[id],+ ...classifyPlatform(byPlatform.get(id) ?? [], brandDomains),+ }));+ const actionable = states.filter((p) => ACTIONABLE_STATES.includes(p.state));++ // The newest answer's text, per actionable platform, for the excerpt.+ const latestIds = actionable.map((p) => byPlatform.get(p.id)[0].id);+ const { data: responses } = latestIds.length+ ? await supabaseAdmin.from('prompt_results').select('id, response').in('id', latestIds)+ : { data: [] };+ const responseById = new Map((responses ?? []).map((r) => [r.id, r.response]));++ const withEvidence = actionable.map((p) => ({+ ...p,+ evidence: collectEvidence(evidenceByPlatform.get(p.id) ?? [], {+ brandName: brand.name,+ brandDomains,+ competitors: competitors ?? [],+ latestResponse: responseById.get(byPlatform.get(p.id)[0].id),+ }),+ }));++ const modelId = improveModelId();+ let suggestions = [];+ // Only a model call is metered; a range with nothing to improve is free.+ if (withEvidence.length > 0) await enforceImproveQuota(brand.organization_id, modelId);+ if (withEvidence.length > 0) {+ const { system, prompt: userPrompt } = buildImprovePrompt({+ promptText: prompt.text,+ brand: { name: brand.name, description: brand.description, domains: brandDomains },+ platforms: withEvidence,+ });+ // Every attempt is charged at its real token cost, so the budget holds+ // for any model, including attempts withRetry repeats after a schema miss.+ const charge = (usage) =>+ recordImproveUsage(req.log, {+ organizationId: brand.organization_id,+ promptId,+ modelId,+ usage,+ });+ const { object } = await withRetry(+ async () => {+ try {+ const result = await generateObject({+ model: resolveModel(modelId),+ schema: improveSchema,+ system,+ prompt: userPrompt,+ });+ await charge(result.usage);+ return result;+ } catch (err) {+ if (NoObjectGeneratedError.isInstance(err) && err.usage) await charge(err.usage);+ throw err;+ }+ },+ { attempts: 3, baseDelayMs: 500, label: 'prompt-improve' },+ );+ suggestions = sanitizeSuggestions(object.suggestions, withEvidence);+ }++ // What each platform's group header shows: why it's there and which+ // inputs the suggestions could draw on.+ const evidenceById = new Map(withEvidence.map((p) => [p.id, p.evidence]));+ const platformStates = states.map((p) => {+ const ev = evidenceById.get(p.id);+ return {+ ...p,+ inputs: ev+ ? {+ fanouts: ev.fanouts.length,+ citedDomains: ev.citedDomains.length,+ competitorUrls: ev.competitorUrls.length,+ answer: !!ev.excerpt,+ }+ : null,+ };+ });++ const { data: saved, error: saveError } = await supabaseAdmin+ .from('prompt_improve_suggestions')+ .upsert(+ {+ prompt_id: promptId,+ brand_id: brandId,+ range_key: range.key,+ region: range.region,+ platform_states: platformStates,+ suggestions,+ latest_result_at: rows?.[0]?.created_at ?? null,+ model: withEvidence.length > 0 ? modelId : null,+ generated_at: new Date().toISOString(),+ },+ { onConflict: 'prompt_id,range_key,region' },+ )+ .select('*')+ .single();+ if (saveError) throw saveError;++ const quota = await getImproveQuotaStatus(brand.organization_id, modelId);+ return res.json({+ improve: improveResponse(saved, rows?.[0]?.created_at ?? null),+ quota: publicQuota(quota),+ });+ } catch (error) {+ if (error instanceof PlanLimitError) {+ return res.status(error.statusCode).json({+ error: error.statusCode === 429 ? 'quota_exceeded' : 'plan_limit',+ message: error.message,+ });+ }+ req.log.error({ err: error }, 'prompt improve generate error');+ return res+ .status(error.status || 500)+ .json({ error: error.message || 'Failed to generate suggestions' });+ }+});+export default router;diff --git a/supabase/migrations/00120_prompt_improve_suggestions.sql b/supabase/migrations/00120_prompt_improve_suggestions.sqlnew file mode 100644index 000000000..085c5317e--- /dev/null+++ b/supabase/migrations/00120_prompt_improve_suggestions.sql@@ -0,0 +1,74 @@+-- Positions panel → Improve tab (PROMPT-003): AI-generated, platform-specific+-- suggestions to improve one prompt's position.+--+-- One row per (prompt, range, location): the whole generated set for every+-- platform the prompt was tracked on in that window. Generating costs a model+-- call, so the panel reads this row first and only regenerates when the user+-- asks or when newer answers have arrived since it was built+-- (latest_result_at).+--+-- range_key is the panel's range as the user picked it: a preset ('24h', '7d',+-- '30d', '90d') or 'custom:<from>:<to>'. Presets slide with the clock; keying+-- on the preset rather than the resolved bounds is what lets "30d" be reused+-- across a day instead of missing the cache every minute.+--+-- Edits, removals and the user's own suggestions are not stored here: they+-- live in the panel until sent to Action Center (PROMPT-004).++create table if not exists public.prompt_improve_suggestions (+ id uuid primary key default gen_random_uuid(),+ prompt_id uuid not null references public.prompts(id) on delete cascade,+ brand_id uuid not null references public.brands(id) on delete cascade,+ range_key text not null,+ -- '' = every location, matching the Prompts table's location filter.+ region text not null default '',++ -- Per platform: { platform, state, runs, mentionPosition, citationRank, inputs }.+ platform_states jsonb not null default '[]'::jsonb,+ -- [{ id, platform, state, title, body, sources: [{ type, ref }], confidence }].+ suggestions jsonb not null default '[]'::jsonb,++ -- Newest answer the set was built from. A newer answer in the window marks+ -- the set stale, so it is rebuilt on the next open.+ latest_result_at timestamptz,+ model text,+ generated_at timestamptz not null default now()+);++create unique index if not exists prompt_improve_suggestions_key_idx+ on public.prompt_improve_suggestions (prompt_id, range_key, region);++create index if not exists prompt_improve_suggestions_brand_idx+ on public.prompt_improve_suggestions (brand_id);++-- Service-role only, like action_candidates (00089): the server reads and+-- writes it after checking the caller's brand access. No policy on purpose.+alter table public.prompt_improve_suggestions enable row level security;++comment on table public.prompt_improve_suggestions is+ 'Cached Improve-tab suggestions per (prompt, range, location). Rebuilt on Regenerate or when an answer newer than latest_result_at arrives.';++-- Monthly Improve budget: one row per model call with its real token cost,+-- summed per organization over the subscription period against+-- plan.limits.improveMonthlyBudgetUsd, 1% of the plan price (Starter 0,+-- Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd).+-- Charging the real cost keeps the share fixed whichever model is+-- configured. Same posture as brief_usage (00015): reading a cached set+-- costs nothing. Self-hosted bypasses the budget.++create table if not exists public.prompt_improve_usage (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ prompt_id uuid references public.prompts(id) on delete set null,+ model text,+ input_tokens integer,+ output_tokens integer,+ cost_usd numeric(12, 6) not null default 0,+ used_at timestamptz not null default now()+);++create index if not exists prompt_improve_usage_org_used_idx+ on public.prompt_improve_usage (organization_id, used_at);++-- Service-role only, no policy (as brief_usage).+alter table public.prompt_improve_usage enable row level security;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex eba2b6880..9b01f7563 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -14230,3 +14230,81 @@ revoke execute on function public.citations_urls_daily(uuid, date, date, text[],grant execute on function public.citations_urls_daily(uuid, date, date, text[], text[], uuid[], integer, text[], text[])to authenticated, service_role;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00120_prompt_improve_suggestions.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Positions panel → Improve tab (PROMPT-003): AI-generated, platform-specific+-- suggestions to improve one prompt's position.+--+-- One row per (prompt, range, location): the whole generated set for every+-- platform the prompt was tracked on in that window. Generating costs a model+-- call, so the panel reads this row first and only regenerates when the user+-- asks or when newer answers have arrived since it was built+-- (latest_result_at).+--+-- range_key is the panel's range as the user picked it: a preset ('24h', '7d',+-- '30d', '90d') or 'custom:<from>:<to>'. Presets slide with the clock; keying+-- on the preset rather than the resolved bounds is what lets "30d" be reused+-- across a day instead of missing the cache every minute.+--+-- Edits, removals and the user's own suggestions are not stored here: they+-- live in the panel until sent to Action Center (PROMPT-004).++create table if not exists public.prompt_improve_suggestions (+ id uuid primary key default gen_random_uuid(),+ prompt_id uuid not null references public.prompts(id) on delete cascade,+ brand_id uuid not null references public.brands(id) on delete cascade,+ range_key text not null,+ -- '' = every location, matching the Prompts table's location filter.+ region text not null default '',++ -- Per platform: { platform, state, runs, mentionPosition, citationRank, inputs }.+ platform_states jsonb not null default '[]'::jsonb,+ -- [{ id, platform, state, title, body, sources: [{ type, ref }], confidence }].+ suggestions jsonb not null default '[]'::jsonb,++ -- Newest answer the set was built from. A newer answer in the window marks+ -- the set stale, so it is rebuilt on the next open.+ latest_result_at timestamptz,+ model text,+ generated_at timestamptz not null default now()+);++create unique index if not exists prompt_improve_suggestions_key_idx+ on public.prompt_improve_suggestions (prompt_id, range_key, region);++create index if not exists prompt_improve_suggestions_brand_idx+ on public.prompt_improve_suggestions (brand_id);++-- Service-role only, like action_candidates (00089): the server reads and+-- writes it after checking the caller's brand access. No policy on purpose.+alter table public.prompt_improve_suggestions enable row level security;++comment on table public.prompt_improve_suggestions is+ 'Cached Improve-tab suggestions per (prompt, range, location). Rebuilt on Regenerate or when an answer newer than latest_result_at arrives.';++-- Monthly Improve budget: one row per model call with its real token cost,+-- summed per organization over the subscription period against+-- plan.limits.improveMonthlyBudgetUsd, 1% of the plan price (Starter 0,+-- Growth $2.49, Enterprise $4.99 or 1% of plan_overrides.contractMonthlyUsd).+-- Charging the real cost keeps the share fixed whichever model is+-- configured. Same posture as brief_usage (00015): reading a cached set+-- costs nothing. Self-hosted bypasses the budget.++create table if not exists public.prompt_improve_usage (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ prompt_id uuid references public.prompts(id) on delete set null,+ model text,+ input_tokens integer,+ output_tokens integer,+ cost_usd numeric(12, 6) not null default 0,+ used_at timestamptz not null default now()+);++create index if not exists prompt_improve_usage_org_used_idx+ on public.prompt_improve_usage (organization_id, used_at);++-- Service-role only, no policy (as brief_usage).+alter table public.prompt_improve_usage enable row level security;+diff --git a/web/src/components/prompts/prompt-improve-tab.tsx b/web/src/components/prompts/prompt-improve-tab.tsxnew file mode 100644index 000000000..01d0402fd--- /dev/null+++ b/web/src/components/prompts/prompt-improve-tab.tsx@@ -0,0 +1,630 @@+'use client';++/**+ * Positions panel → Improve tab (PROMPT-003): what to do on each platform+ * where the brand is missing or ranked late, for one prompt and range.+ *+ * The set is generated on the server (one model call, cached per prompt,+ * range and location) and checked there against the evidence, so every card+ * names a real sub-query, URL or answer. Here it becomes an editable draft:+ * check, edit, remove (undoable) or add your own. The draft lives only while+ * the panel is open; sending it to Action Center is PROMPT-004.+ */++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Check, Loader2, Lock, Pencil, Plus, RefreshCw, Sparkles, X } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { Checkbox } from '@/components/ui/checkbox';+import { Input } from '@/components/ui/input';+import { Skeleton } from '@/components/ui/skeleton';+import { Textarea } from '@/components/ui/textarea';+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { cn } from '@/lib/utils';+import { PLANS, hasFeature, type PlanId } from '@/config/plans';+import { generateImproveSuggestions, getImproveSuggestions } from '@/lib/actions/prompt-improve';+import {+ STATE_LABEL,+ STATE_ORDER,+ hasUnsentEdits,+ mentionRateLabel,+ selectionSummary,+ sourceChipLabel,+ toDrafts,+ type DraftSuggestion,+ type ImprovePlatform,+ type ImproveQuota,+ type ImproveRangeInput,+ type ImproveSet,+} from '@/lib/prompt-improve';++type Status = 'idle' | 'loading' | 'generating' | 'ready' | 'error' | 'locked';++export interface ImproveController {+ status: Status;+ set: ImproveSet | null;+ /** Generations left this period; null while unknown. */+ quota: ImproveQuota | null;+ drafts: DraftSuggestion[];+ setDrafts: React.Dispatch<React.SetStateAction<DraftSuggestion[]>>;+ error: string | null;+ /** Unsent edits, removals, unchecks or own suggestions. */+ dirty: boolean;+ /** Count for the tab badge: suggestions still in the draft. */+ count: number | null;+ /** Builds (or rebuilds) the set; one metered model call. */+ generate: () => void;+ /** Reads the cached set again; never generates. */+ reload: () => void;+}++/**+ * The Improve state for the open prompt and range. Lives in the panel, not+ * the tab, so the tab badge can show a count before the tab is opened and the+ * range control can ask before discarding unsent edits. Opening the panel+ * only reads the cache. Generating is always the user's click: each one is a+ * metered model call against the plan's monthly quota.+ */+export function useImprove({+ promptId,+ range,+ planId,+}: {+ promptId: string | null;+ range: ImproveRangeInput;+ planId: PlanId | null;+}): ImproveController {+ const locked = planId !== null && !hasFeature(PLANS[planId], 'prompt_improve');+ const key = promptId ? `${promptId}|${JSON.stringify(range)}` : '';+ const [state, setState] = useState<{+ key: string;+ status: Status;+ set: ImproveSet | null;+ error: string | null;+ }>({ key: '', status: 'idle', set: null, error: null });+ const [quota, setQuota] = useState<ImproveQuota | null>(null);+ const [drafts, setDrafts] = useState<DraftSuggestion[]>([]);+ // The latest key, so a response for a range the user already left is dropped.+ const keyRef = useRef(key);+ keyRef.current = key;++ const apply = useCallback(+ (+ forKey: string,+ op: 'read' | 'generate',+ result: Awaited<ReturnType<typeof getImproveSuggestions>>,+ ) => {+ if (keyRef.current !== forKey) return;+ if ('error' in result) {+ // A failed generate keeps the set (and edits) the user already has on+ // screen, and shows the error next to Generate / Regenerate. Only a+ // failed read lands on the error state, whose Retry reads again: a+ // retry should never be a paid call the user didn't ask for.+ if (op === 'generate' && result.code !== 'plan_limit') {+ setState((s) => ({ ...s, key: forKey, status: 'ready', error: result.error }));+ if (result.code === 'quota_exceeded') {+ setQuota((q) =>+ q ? { ...q, exhausted: true, generationsLeft: 0, percentLeft: 0 } : q,+ );+ }+ return;+ }+ setState({+ key: forKey,+ status: result.code === 'plan_limit' ? 'locked' : 'error',+ set: null,+ error: result.error,+ });+ return;+ }+ setState({ key: forKey, status: 'ready', set: result.improve, error: null });+ setDrafts(toDrafts(result.improve?.suggestions ?? []));+ if (result.quota) setQuota(result.quota);+ },+ [],+ );++ const reload = useCallback(() => {+ if (!promptId) return;+ const forKey = keyRef.current;+ setState({ key: forKey, status: 'loading', set: null, error: null });+ setDrafts([]);+ getImproveSuggestions(promptId, range).then((r) => apply(forKey, 'read', r));+ }, [promptId, range, apply]);++ useEffect(() => {+ if (!promptId || locked) return;+ reload();+ // `key` covers the prompt and the range.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key, locked]);++ const generate = useCallback(() => {+ if (!promptId) return;+ const forKey = keyRef.current;+ setState((s) => ({ ...s, key: forKey, status: 'generating', error: null }));+ generateImproveSuggestions(promptId, range).then((r) => apply(forKey, 'generate', r));+ }, [promptId, range, apply]);++ const current = state.key === key ? state : null;+ const status: Status = locked ? 'locked' : (current?.status ?? 'idle');+ const set = current?.set ?? null;++ const dirty = useMemo(() => !!set && hasUnsentEdits(drafts, set.suggestions), [drafts, set]);++ return {+ status,+ set,+ quota,+ drafts,+ setDrafts,+ error: current?.error ?? null,+ dirty,+ // A locked plan shows no count, even when a set was read before the plan was known.+ count: set && !locked ? drafts.filter((d) => !d.removed).length : null,+ generate,+ reload,+ };+}++// ─── Tab ──────────────────────────────────────────────────────────────────────++export function ImproveTab({ improve }: { improve: ImproveController }) {+ const { status, set, quota, drafts, setDrafts, error, dirty, generate, reload } = improve;+ const [confirmRegenerate, setConfirmRegenerate] = useState(false);+ const outOfQuota = !!quota?.exhausted;++ if (status === 'locked') return <LockedImprove />;+ if (status === 'error') {+ return (+ <div className="flex flex-col items-start gap-3 rounded-lg border border-red-200 bg-red-50 p-4 text-sm dark:border-red-900/50 dark:bg-red-950/30">+ <p className="text-red-900 dark:text-red-200">+ {friendlyError(error, 'Failed to load suggestions.')}+ </p>+ <Button size="sm" variant="outline" onClick={reload}>+ <RefreshCw />+ Retry+ </Button>+ </div>+ );+ }+ if (status === 'generating') return <Generating />;+ if (status !== 'ready') return <ImproveSkeleton />;+ if (!set) {+ return (+ <div className="flex flex-col items-start gap-3 rounded-lg border p-4">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Sparkles className="h-4 w-4" />+ Get platform-specific suggestions+ </p>+ <p className="text-xs text-muted-foreground">+ Analyzes this period's answers on every platform (the sub-queries they ran, the+ sources they cited and the competitors ranked above you) and suggests what to do where the+ brand is missing or ranked late.+ </p>+ {error && <p className="text-xs text-red-600 dark:text-red-400">{friendlyError(error)}</p>}+ <div className="flex flex-wrap items-center gap-3">+ <Button size="sm" onClick={generate} disabled={outOfQuota}>+ <Sparkles />+ Generate suggestions+ </Button>+ <QuotaNote quota={quota} />+ </div>+ </div>+ );+ }++ const groups = [...set.platforms].sort(+ (a, b) => STATE_ORDER.indexOf(a.state) - STATE_ORDER.indexOf(b.state),+ );+ const tracked = set.platforms.filter((p) => p.state !== 'no_runs');+ const actionable = tracked.filter((p) => p.state !== 'doing_well');+ const summary = selectionSummary(drafts);++ const update = (id: string, patch: Partial<DraftSuggestion>) =>+ setDrafts((ds) => ds.map((d) => (d.id === id ? { ...d, ...patch } : d)));+ const addOwn = (platform: ImprovePlatform) =>+ setDrafts((ds) => [+ ...ds,+ {+ id: `own:${platform.id}:${Date.now()}`,+ platform: platform.id,+ state: platform.state,+ title: '',+ body: '',+ sources: [],+ confidence: 'medium',+ checked: true,+ removed: false,+ own: true,+ },+ ]);++ return (+ <div className="space-y-3">+ {set.stale && (+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-sky-200 bg-sky-50 px-3 py-2 text-xs dark:border-sky-900/50 dark:bg-sky-950/30">+ <span className="text-sky-900 dark:text-sky-200">+ New runs have arrived since these suggestions were generated.+ </span>+ <Button+ size="xs"+ variant="outline"+ disabled={outOfQuota}+ onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}+ >+ <RefreshCw />+ Regenerate+ </Button>+ </div>+ )}+ {error && <p className="text-xs text-red-600 dark:text-red-400">{friendlyError(error)}</p>}+ {tracked.length === 0 ? (+ <EmptyNote>No runs in this period, so there is nothing to improve yet.</EmptyNote>+ ) : actionable.length === 0 ? (+ <EmptyNote>+ No improvements needed: the brand is mentioned first and cited early on every platform in+ this period.+ </EmptyNote>+ ) : null}++ <div className="divide-y rounded-lg border">+ {groups.map((p) => (+ <PlatformGroup+ key={p.id}+ platform={p}+ drafts={drafts.filter((d) => d.platform === p.id)}+ onUpdate={update}+ onAddOwn={() => addOwn(p)}+ />+ ))}+ </div>++ <div className="sticky bottom-0 -mx-5 flex flex-wrap items-center justify-between gap-2 border-t bg-background px-5 py-3">+ <span className="text-xs text-muted-foreground">+ {summary.selected} of {summary.total} selected · {summary.platforms} platform+ {summary.platforms === 1 ? '' : 's'}+ <span className="ml-2 text-muted-foreground/70">+ Generated {new Date(set.generatedAt).toLocaleString()}+ </span>+ <QuotaNote quota={quota} className="ml-2" />+ </span>+ {confirmRegenerate ? (+ <span className="flex items-center gap-2 text-xs">+ Discard your edits?+ <Button size="xs" variant="outline" onClick={() => setConfirmRegenerate(false)}>+ Keep editing+ </Button>+ <Button+ size="xs"+ onClick={() => {+ setConfirmRegenerate(false);+ generate();+ }}+ >+ Discard & regenerate+ </Button>+ </span>+ ) : (+ <Button+ size="sm"+ variant="outline"+ disabled={outOfQuota}+ onClick={() => (dirty ? setConfirmRegenerate(true) : generate())}+ >+ <RefreshCw />+ Regenerate+ </Button>+ )}+ </div>+ </div>+ );+}++function friendlyError(error: string | null, fallback = 'Failed to generate suggestions.'): string {+ if (error && /not configured|api key/i.test(error)) {+ return 'AI suggestions are not set up on this server yet: an AI provider key is missing.';+ }+ return error || fallback;+}++/** "About 185 generations left this month"; nothing on unlimited plans. */+function QuotaNote({ quota, className }: { quota: ImproveQuota | null; className?: string }) {+ if (!quota || quota.unlimited) return null;+ const n = quota.generationsLeft ?? 0;+ return (+ <span+ className={cn(+ 'text-xs',+ quota.exhausted ? 'text-red-600 dark:text-red-400' : 'text-muted-foreground',+ className,+ )}+ title={+ quota.percentLeft !== null ? `${quota.percentLeft}% of this month's budget left` : undefined+ }+ >+ {quota.exhausted+ ? "This month's suggestion budget is used up. It resets when your subscription renews."+ : `About ${n} generation${n === 1 ? '' : 's'} left this month`}+ </span>+ );+}++function EmptyNote({ children }: { children: React.ReactNode }) {+ return (+ <p className="rounded-lg border border-dashed px-3 py-3 text-sm text-muted-foreground">+ {children}+ </p>+ );+}++const STATE_TONE: Record<ImprovePlatform['state'], string> = {+ not_mentioned: 'border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-300',+ mentioned_late: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300',+ not_cited: 'border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300',+ doing_well: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',+ no_runs: '',+};++/**+ * Why the platform is in the list: how often the brand is mentioned (a+ * platform mentioned in under half its runs counts as not mentioned), and+ * where it ranks.+ */+function stateDetail(p: ImprovePlatform): string | null {+ if (p.state === 'no_runs') return null;+ const rate = mentionRateLabel(p);+ if (p.state === 'mentioned_late' && p.mentionPosition) {+ return `avg #${p.mentionPosition}${p.mentionTotal ? ` of ${p.mentionTotal}` : ''} · ${rate}`;+ }+ if (p.state === 'not_cited') {+ return p.citationRank+ ? `cited at avg #${p.citationRank.rank} of ${p.citationRank.total} sources · ${rate}`+ : `not cited · ${rate}`;+ }+ return rate;+}++const countLabel = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;++function inputsNote(p: ImprovePlatform): string | null {+ if (!p.inputs) return null;+ const parts: string[] = [];+ if (p.inputs.fanouts) parts.push(countLabel(p.inputs.fanouts, 'fan-out', 'fan-outs'));+ if (p.inputs.citedDomains) {+ parts.push(countLabel(p.inputs.citedDomains, 'cited domain', 'cited domains'));+ }+ if (p.inputs.competitorUrls) {+ parts.push(countLabel(p.inputs.competitorUrls, 'competitor URL', 'competitor URLs'));+ }+ if (p.inputs.answer) parts.push('AI answer');+ const based = parts.length ? `Based on ${parts.join(' · ')}` : 'Based on the AI answer';+ return p.inputs.fanouts ? based : `No fan-outs recorded. ${based}`;+}++function PlatformGroup({+ platform: p,+ drafts,+ onUpdate,+ onAddOwn,+}: {+ platform: ImprovePlatform;+ drafts: DraftSuggestion[];+ onUpdate: (id: string, patch: Partial<DraftSuggestion>) => void;+ onAddOwn: () => void;+}) {+ const detail = stateDetail(p);+ const inputs = inputsNote(p);+ const canSuggest = p.state !== 'no_runs';+ return (+ <div className="space-y-2 px-3 py-3">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className="flex min-w-0 items-center gap-2">+ <AIProviderAvatar plain provider={resolveAIProvider('', p.id)} className="h-6 w-6" />+ <span className="truncate text-sm font-medium">{p.label}</span>+ </span>+ <Badge variant="outline" className={cn('text-[11px]', STATE_TONE[p.state])}>+ {STATE_LABEL[p.state]}+ </Badge>+ {detail && <span className="text-xs text-muted-foreground">{detail}</span>}+ </div>+ {inputs && <p className="text-[11px] text-muted-foreground">{inputs}</p>}++ {p.state === 'doing_well' && drafts.length === 0 && (+ <p className="text-xs text-muted-foreground">Doing well: no suggestions.</p>+ )}+ {(p.state === 'not_mentioned' || p.state === 'mentioned_late' || p.state === 'not_cited') &&+ drafts.length === 0 && (+ <p className="text-xs text-muted-foreground">+ No suggestion held up against this platform's evidence. Add your own, or+ regenerate.+ </p>+ )}++ {drafts.map((d) => (+ <SuggestionCard key={d.id} draft={d} onUpdate={(patch) => onUpdate(d.id, patch)} />+ ))}++ {canSuggest && (+ <button+ type="button"+ onClick={onAddOwn}+ className="inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground"+ >+ <Plus className="h-3.5 w-3.5" />+ Add your own suggestion+ </button>+ )}+ </div>+ );+}++function SuggestionCard({+ draft: d,+ onUpdate,+}: {+ draft: DraftSuggestion;+ onUpdate: (patch: Partial<DraftSuggestion>) => void;+}) {+ // A new own suggestion opens straight into editing.+ const [editing, setEditing] = useState(!!d.own && !d.title);+ const [title, setTitle] = useState(d.title);+ const [body, setBody] = useState(d.body);++ if (d.removed) {+ return (+ <div className="flex items-center justify-between gap-2 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">+ <span className="truncate">Removed: {d.title || 'your suggestion'}</span>+ <Button size="xs" variant="ghost" onClick={() => onUpdate({ removed: false })}>+ Undo+ </Button>+ </div>+ );+ }++ if (editing) {+ const save = () => {+ if (!title.trim()) return;+ onUpdate({ title: title.trim(), body: body.trim() });+ setEditing(false);+ };+ return (+ <div className="space-y-2 rounded-md border bg-muted/30 p-3">+ <Input+ autoFocus+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ placeholder="Title"+ className="h-8 text-sm"+ maxLength={120}+ />+ <Textarea+ value={body}+ onChange={(e) => setBody(e.target.value)}+ placeholder="What to do and why"+ className="min-h-20 text-sm"+ maxLength={600}+ />+ <div className="flex justify-end gap-2">+ <Button+ size="xs"+ variant="outline"+ onClick={() => {+ if (d.own && !d.title) onUpdate({ removed: true });+ setTitle(d.title);+ setBody(d.body);+ setEditing(false);+ }}+ >+ Cancel+ </Button>+ <Button size="xs" onClick={save} disabled={!title.trim()}>+ <Check />+ Save+ </Button>+ </div>+ </div>+ );+ }++ return (+ <div className={cn('flex gap-3 rounded-md border p-3', !d.checked && 'opacity-60')}>+ <Checkbox+ checked={d.checked}+ onCheckedChange={(v) => onUpdate({ checked: v === true })}+ aria-label={`Select "${d.title}"`}+ className="mt-0.5"+ />+ <div className="min-w-0 flex-1 space-y-1.5">+ <div className="flex items-start justify-between gap-2">+ <p className="text-sm font-medium leading-snug">{d.title}</p>+ <span className="flex shrink-0 items-center">+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Edit suggestion"+ onClick={() => {+ setTitle(d.title);+ setBody(d.body);+ setEditing(true);+ }}+ >+ <Pencil />+ </Button>+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Remove suggestion"+ onClick={() => onUpdate({ removed: true })}+ >+ <X />+ </Button>+ </span>+ </div>+ {d.body && <p className="text-xs leading-relaxed text-muted-foreground">{d.body}</p>}+ {(d.sources.length > 0 || d.own) && (+ <div className="flex flex-wrap gap-1">+ {d.own && (+ <Badge variant="secondary" className="text-[10px]">+ Your suggestion+ </Badge>+ )}+ {d.sources.map((s) => (+ <Badge+ key={`${s.type}:${s.ref}`}+ variant="outline"+ title={s.ref}+ className="max-w-full truncate text-[10px] font-normal text-muted-foreground"+ >+ {sourceChipLabel(s)}+ </Badge>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++function Generating() {+ return (+ <div className="space-y-3">+ <p className="flex items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ Generating suggestions from this period's answers… this can take up to 15 seconds.+ </p>+ <ImproveSkeleton />+ </div>+ );+}++function ImproveSkeleton() {+ return (+ <div className="space-y-2">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-20 w-full" />+ ))}+ </div>+ );+}++function LockedImprove() {+ return (+ <div className="flex flex-col items-start gap-3 rounded-lg border p-4">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Lock className="h-4 w-4" />+ Improve is available on Growth+ </p>+ <p className="text-xs text-muted-foreground">+ Get platform-specific suggestions to improve this prompt's position, based on the+ sub-queries, sources and competitors in each AI answer.+ </p>+ <Link href="/dashboard/settings?tab=billing" className={buttonVariants({ size: 'sm' })}>+ <Sparkles />+ Upgrade plan+ </Link>+ </div>+ );+}diff --git a/web/src/components/prompts/prompt-positions-sheet.tsx b/web/src/components/prompts/prompt-positions-sheet.tsxindex 1b796f8b1..a9b14e46f 100644--- a/web/src/components/prompts/prompt-positions-sheet.tsx+++ b/web/src/components/prompts/prompt-positions-sheet.tsx@@ -43,6 +43,7 @@ import { CONTACT_SALES_URL, type PlanId } from '@/config/plans';import { PROMPT_RANGE_PRESETS, type PromptRangePreset } from '@/config/prompt-options';import type { PositionsRange } from '@/lib/positions-range';import { DateRangeFilter } from '@/components/filters/date-range-filter';+import { ImproveTab, useImprove, type ImproveController } from './prompt-improve-tab';import { getPromptPositions, type PromptPositionsData } from '@/lib/actions/prompt-positions';import type {AnswerView,@@ -115,6 +116,9 @@ export function PromptPositionsSheet({onClose,}: Props) {const preset = range.preset;+ // A range change asked for while the Improve tab has unsent edits waits here+ // until the user confirms discarding them.+ const [pendingRange, setPendingRange] = useState<PositionsRange | null>(null);// Everything the data depends on. A response is shown only while its key// still matches, so another prompt's (or window's) numbers never linger.const key = prompt ? `${prompt.id}|${window.from}|${window.to ?? ''}|${region}` : '';@@ -152,6 +156,23 @@ export function PromptPositionsSheet({const data = current?.data ?? null;const latestMode = preset === '24h';+ const improve = useImprove({+ promptId: prompt?.id ?? null,+ range: {+ preset,+ from: window.from,+ to: window.to,+ customFrom: preset === 'custom' ? range.from : undefined,+ customTo: preset === 'custom' ? range.to : undefined,+ region,+ },+ planId: data?.planId ?? null,+ });+ const changeRange = (next: PositionsRange) => {+ if (improve.dirty) setPendingRange(next);+ else onRangeChange(next);+ };+const retry = () => {setLoaded(null);setAttempt((n) => n + 1);@@ -201,19 +222,43 @@ export function PromptPositionsSheet({label="Period"value={preset}presets={PROMPT_RANGE_PRESETS}- onChange={(next) => onRangeChange({ ...range, preset: next })}+ onChange={(next) => changeRange({ ...range, preset: next })}from={range.from}to={range.to}- onFromChange={(from) => onRangeChange({ ...range, from })}- onToChange={(to) => onRangeChange({ ...range, to })}+ onFromChange={(from) => changeRange({ ...range, from })}+ onToChange={(to) => changeRange({ ...range, to })}/></div>+ {pendingRange && (+ <div className="flex flex-wrap items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs dark:border-amber-900/50 dark:bg-amber-950/30">+ <span className="text-amber-900 dark:text-amber-200">+ Changing the period discards your unsent Improve edits.+ </span>+ <Button size="xs" variant="outline" onClick={() => setPendingRange(null)}>+ Keep editing+ </Button>+ <Button+ size="xs"+ onClick={() => {+ onRangeChange(pendingRange);+ setPendingRange(null);+ }}+ >+ Discard & change+ </Button>+ </div>+ )}</SheetHeader><div className="flex-1 overflow-y-auto px-5 py-4">{prompt && !current && <PositionsSkeleton />}{current?.error && <LoadError message={current.error} onRetry={retry} />}- {data && (latestMode ? <LatestView data={data} /> : <PeriodView data={data} />)}+ {data &&+ (latestMode ? (+ <LatestView data={data} improve={improve} />+ ) : (+ <PeriodView data={data} improve={improve} />+ ))}</div><div className="flex items-center justify-between gap-2 border-t px-5 py-3">@@ -405,7 +450,20 @@ function avgLabel(stats: PositionStats | null): string {// ─── 24h: each platform's latest answer ───────────────────────────────────────-function LatestView({ data }: { data: PromptPositionsData }) {+function ImproveTrigger({ improve }: { improve: ImproveController }) {+ return (+ <TabsTrigger value="improve">+ Improve+ {improve.count !== null && improve.count > 0 && (+ <Badge variant="secondary" className="ml-1 h-4 px-1.5 text-[10px]">+ {improve.count}+ </Badge>+ )}+ </TabsTrigger>+ );+}++function LatestView({ data, improve }: { data: PromptPositionsData; improve: ImproveController }) {const included = data.platforms.filter((p) => p.access.state === 'included');const answered = included.filter((p) => p.latest);const mentioned = answered.filter((p) => p.latest!.mentioned).length;@@ -431,15 +489,26 @@ function LatestView({ data }: { data: PromptPositionsData }) {<Stat label="Avg. position" value={avg} sub="when mentioned" /></div>- <div className="divide-y rounded-lg border">- {data.platforms.map((p) =>- p.access.state === 'locked' ? (- <LockedRow key={p.id} platform={p} planId={data.planId} />- ) : (- <LatestRow key={p.id} platform={p} />- ),- )}- </div>+ <Tabs defaultValue="platforms">+ <TabsList>+ <TabsTrigger value="platforms">Platform results</TabsTrigger>+ <ImproveTrigger improve={improve} />+ </TabsList>+ <TabsContent value="platforms" className="mt-3">+ <div className="divide-y rounded-lg border">+ {data.platforms.map((p) =>+ p.access.state === 'locked' ? (+ <LockedRow key={p.id} platform={p} planId={data.planId} />+ ) : (+ <LatestRow key={p.id} platform={p} />+ ),+ )}+ </div>+ </TabsContent>+ <TabsContent value="improve" className="mt-3">+ <ImproveTab improve={improve} />+ </TabsContent>+ </Tabs></div>);}@@ -491,7 +560,7 @@ function LatestRow({ platform: p }: { platform: PlatformPositions }) {// ─── 7d / 30d / 90d / custom: days ────────────────────────────────────────────-function PeriodView({ data }: { data: PromptPositionsData }) {+function PeriodView({ data, improve }: { data: PromptPositionsData; improve: ImproveController }) {const s = data.summary;return (<div className="space-y-4">@@ -532,6 +601,7 @@ function PeriodView({ data }: { data: PromptPositionsData }) {<TabsList><TabsTrigger value="platforms">Platform results</TabsTrigger><TabsTrigger value="history">Daily history ({s.trackedDays})</TabsTrigger>+ <ImproveTrigger improve={improve} /></TabsList><TabsContent value="platforms" className="mt-3 space-y-3"><HeatmapLegend />@@ -552,6 +622,9 @@ function PeriodView({ data }: { data: PromptPositionsData }) {<TabsContent value="history" className="mt-3"><DailyHistory platforms={data.platforms} /></TabsContent>+ <TabsContent value="improve" className="mt-3">+ <ImproveTab improve={improve} />+ </TabsContent></Tabs></div>);diff --git a/web/src/config/plans.ts b/web/src/config/plans.tsindex d68ab9869..ad07dc756 100644--- a/web/src/config/plans.ts+++ b/web/src/config/plans.ts@@ -21,6 +21,9 @@ export const FEATURES = [// merchant breakdown). Free / Starter get the headline KPI only;// Growth+ and self-host get the full set of tabs.'shopping_analytics',+ // Positions panel → Improve tab: AI-generated, platform-specific+ // suggestions to improve a prompt's position (PROMPT-003). Growth+.+ 'prompt_improve',] as const;export type Feature = (typeof FEATURES)[number];@@ -40,6 +43,13 @@ export interface PlanLimits {* organizations.plan_overrides.maxBriefGenerations in the DB.*/maxBriefGenerations: number;+ /**+ * Monthly USD budget for Improve-tab model calls (Positions panel,+ * PROMPT-003): 1% of the plan price, enforced on the server from each+ * call's real token cost so it holds whichever model is configured.+ * -1 = unlimited (self-host).+ */+ improveMonthlyBudgetUsd: number;/*** Monthly Site Audit runs. -1 = unlimited (self-hosted / enterprise).* Starter 100, Growth 500.@@ -81,6 +91,7 @@ export const PLANS: Record<PlanId, Plan> = {maxDomainsPerBrand: -1,maxVolumeAnalyses: -1,maxBriefGenerations: -1,+ improveMonthlyBudgetUsd: -1,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -97,6 +108,7 @@ export const PLANS: Record<PlanId, Plan> = {'api_access','ai_agent','shopping_analytics',+ 'prompt_improve',],// Self-host runs against the operator's own infrastructure / API// keys — no platform quota to enforce.@@ -115,6 +127,7 @@ export const PLANS: Record<PlanId, Plan> = {maxDomainsPerBrand: 3,maxVolumeAnalyses: 4,maxBriefGenerations: 10,+ improveMonthlyBudgetUsd: 0,maxSiteAudits: 100,maxDailyOnDemand: 3,onDemandCooldownMinutes: 15,@@ -153,6 +166,8 @@ export const PLANS: Record<PlanId, Plan> = {maxDomainsPerBrand: 10,maxVolumeAnalyses: 10,maxBriefGenerations: 50,+ // 1% of the $249 price, spent on Improve model calls (PROMPT-003).+ improveMonthlyBudgetUsd: 2.49,maxSiteAudits: 500,maxDailyOnDemand: 10,onDemandCooldownMinutes: 5,@@ -172,6 +187,7 @@ export const PLANS: Record<PlanId, Plan> = {'api_access','ai_agent','shopping_analytics',+ 'prompt_improve',],},},@@ -189,6 +205,9 @@ export const PLANS: Record<PlanId, Plan> = {maxVolumeAnalyses: -1,// Per-customer: override via organizations.plan_overrides in the DB.maxBriefGenerations: -1,+ // 1% of the $499 floor. plan_overrides.contractMonthlyUsd raises it to 1%+ // of the contract; an explicit plan_overrides.improveMonthlyBudgetUsd wins.+ improveMonthlyBudgetUsd: 4.99,maxSiteAudits: -1,maxDailyOnDemand: -1,onDemandCooldownMinutes: 0,@@ -213,6 +232,7 @@ export const PLANS: Record<PlanId, Plan> = {'sso_saml','ai_agent','shopping_analytics',+ 'prompt_improve',],// Enterprise — no platform quota; usage governed by contract.},diff --git a/web/src/lib/actions/prompt-improve.ts b/web/src/lib/actions/prompt-improve.tsnew file mode 100644index 000000000..b742a5f8c--- /dev/null+++ b/web/src/lib/actions/prompt-improve.ts@@ -0,0 +1,81 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';+// Types only — the helpers that go with them live in a plain module.+import type { ImproveQuota, ImproveRangeInput, ImproveSet } from '@/lib/prompt-improve';++/**+ * Failures come back as a value, not a throw, so the panel can show the real+ * message (plan limit, missing AI key) instead of the masked production+ * digest (#427).+ */+type ImproveResult =+ | { improve: ImproveSet | null; quota: ImproveQuota | null }+ | { error: string; code?: 'plan_limit' | 'quota_exceeded' };++async function call(+ promptId: string,+ range: ImproveRangeInput,+ method: 'GET' | 'POST',+): Promise<ImproveResult> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'Not authenticated' };++ const url = new URL(`${API_BASE_URL}/api/prompts/${promptId}/improve`);+ const body: Record<string, string> = {};+ for (const [k, v] of Object.entries(range)) if (typeof v === 'string' && v) body[k] = v;+ if (method === 'GET') for (const [k, v] of Object.entries(body)) url.searchParams.set(k, v);++ try {+ const res = await fetch(url, {+ method,+ headers: {+ Authorization: `Bearer ${session.access_token}`,+ ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}),+ },+ body: method === 'POST' ? JSON.stringify(body) : undefined,+ cache: 'no-store',+ // Reading the cache is quick; generating is one model call (target p95 < 15 s).+ signal: AbortSignal.timeout(method === 'GET' ? 15_000 : 60_000),+ });+ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ return {+ error: data.message || data.error || `Server error: ${res.status}`,+ code:+ data.error === 'plan_limit' || data.error === 'quota_exceeded' ? data.error : undefined,+ };+ }+ return {+ improve: (data.improve ?? null) as ImproveSet | null,+ quota: (data.quota ?? null) as ImproveQuota | null,+ };+ } catch (err) {+ return {+ error:+ err instanceof Error && err.name === 'TimeoutError'+ ? 'Generating suggestions took too long. Please try again.'+ : 'Could not reach the server. Please try again.',+ };+ }+}++/** The cached set for this prompt and range, or null when none was built yet. */+export async function getImproveSuggestions(+ promptId: string,+ range: ImproveRangeInput,+): Promise<ImproveResult> {+ return call(promptId, range, 'GET');+}++/** Build (or rebuild) the set for this prompt and range. */+export async function generateImproveSuggestions(+ promptId: string,+ range: ImproveRangeInput,+): Promise<ImproveResult> {+ return call(promptId, range, 'POST');+}diff --git a/web/src/lib/prompt-improve.test.ts b/web/src/lib/prompt-improve.test.tsnew file mode 100644index 000000000..906483927--- /dev/null+++ b/web/src/lib/prompt-improve.test.ts@@ -0,0 +1,82 @@+/**+ * prompt-improve.test.ts (PROMPT-003)+ *+ * Tests the Improve tab's draft helpers: the footer summary, the unsent-edits+ * check that guards range changes and Regenerate, and the source chip labels.+ */++import { describe, expect, test } from 'vitest';+import {+ hasUnsentEdits,+ mentionRateLabel,+ selectionSummary,+ sourceChipLabel,+ toDrafts,+ type ImproveSuggestion,+} from './prompt-improve';++const s = (id: string, platform: string): ImproveSuggestion => ({+ id,+ platform,+ state: 'not_mentioned',+ title: `Title ${id}`,+ body: 'Body',+ sources: [{ type: 'domain', ref: 'reddit.com' }],+ confidence: 'high',+});++const original = [s('a', 'chatgpt-web'), s('b', 'chatgpt-web'), s('c', 'perplexity-web')];++describe('selectionSummary', () => {+ test('counts selected over live suggestions and distinct selected platforms', () => {+ const drafts = toDrafts(original);+ expect(selectionSummary(drafts)).toEqual({ selected: 3, total: 3, platforms: 2 });+ drafts[2] = { ...drafts[2], checked: false };+ drafts[1] = { ...drafts[1], removed: true };+ expect(selectionSummary(drafts)).toEqual({ selected: 1, total: 2, platforms: 1 });+ });+});++describe('hasUnsentEdits', () => {+ test('a fresh draft has none', () => {+ expect(hasUnsentEdits(toDrafts(original), original)).toBe(false);+ });++ test('an edit, an uncheck or a removal counts', () => {+ const edited = toDrafts(original).map((d) => (d.id === 'a' ? { ...d, body: 'Changed' } : d));+ expect(hasUnsentEdits(edited, original)).toBe(true);+ const unchecked = toDrafts(original).map((d) => (d.id === 'b' ? { ...d, checked: false } : d));+ expect(hasUnsentEdits(unchecked, original)).toBe(true);+ const removed = toDrafts(original).map((d) => (d.id === 'c' ? { ...d, removed: true } : d));+ expect(hasUnsentEdits(removed, original)).toBe(true);+ });++ test('an own suggestion counts until it is removed', () => {+ const own = { ...s('own:1', 'chatgpt-web'), checked: true, removed: false, own: true };+ expect(hasUnsentEdits([...toDrafts(original), own], original)).toBe(true);+ expect(hasUnsentEdits([...toDrafts(original), { ...own, removed: true }], original)).toBe(+ false,+ );+ });+});++describe('sourceChipLabel', () => {+ test('labels each source type', () => {+ expect(sourceChipLabel({ type: 'fanout', ref: 'best coffee' })).toBe('Fan-out: best coffee');+ expect(sourceChipLabel({ type: 'answer', ref: 'a quote' })).toBe('AI answer');+ expect(sourceChipLabel({ type: 'competitor_url', ref: 'https://www.rival.com/plans' })).toBe(+ 'rival.com/plans',+ );+ expect(sourceChipLabel({ type: 'brand_page', ref: 'https://acme.com/' })).toBe(+ 'Your page: acme.com',+ );+ expect(sourceChipLabel({ type: 'domain', ref: 'reddit.com' })).toBe('reddit.com');+ });+});++describe('mentionRateLabel', () => {+ test('says how many runs mention the brand', () => {+ expect(mentionRateLabel({ runs: 120, mentionedRuns: 8 })).toBe('mentioned in 8 of 120 runs');+ expect(mentionRateLabel({ runs: 1, mentionedRuns: 0 })).toBe('mentioned in 0 of 1 run');+ });+});diff --git a/web/src/lib/prompt-improve.ts b/web/src/lib/prompt-improve.tsnew file mode 100644index 000000000..989ed0b9f--- /dev/null+++ b/web/src/lib/prompt-improve.ts@@ -0,0 +1,162 @@+/**+ * Positions panel → Improve tab (PROMPT-003): the shapes the server returns+ * (server/src/lib/prompt-improve.js) and the panel's editable copy of them.+ * Kept out of the 'use server' actions file, whose every runtime export must+ * be a server action.+ */++export type ImproveState =+ | 'no_runs'+ | 'not_mentioned'+ | 'mentioned_late'+ | 'not_cited'+ | 'doing_well';++export type ImproveSourceType = 'fanout' | 'domain' | 'answer' | 'competitor_url' | 'brand_page';++export interface ImproveSource {+ type: ImproveSourceType;+ ref: string;+}++export interface ImproveSuggestion {+ id: string;+ platform: string;+ state: ImproveState;+ title: string;+ body: string;+ sources: ImproveSource[];+ confidence: 'high' | 'medium' | 'low';+}++export interface ImprovePlatform {+ id: string;+ label: string;+ state: ImproveState;+ runs: number;+ mentionedRuns: number;+ citedRuns: number;+ mentionPosition: number | null;+ mentionTotal?: number | null;+ citationRank: { rank: number; total: number } | null;+ /** What the suggestions could draw on; null when the platform got none. */+ inputs: { fanouts: number; citedDomains: number; competitorUrls: number; answer: boolean } | null;+}++export interface ImproveSet {+ rangeKey: string;+ region: string;+ platforms: ImprovePlatform[];+ suggestions: ImproveSuggestion[];+ latestResultAt: string | null;+ generatedAt: string;+ /** Answers newer than the set exist: the panel rebuilds it. */+ stale: boolean;+}++/**+ * The monthly Improve budget as the panel shows it. The budget itself is in+ * dollars (1% of the plan price) and stays on the server; the panel gets an+ * estimate of the generations it still buys.+ */+export interface ImproveQuota {+ unlimited: boolean;+ exhausted: boolean;+ generationsLeft: number | null;+ percentLeft: number | null;+}++/** The panel's range as sent to the server: the resolved bounds plus the picked preset. */+export interface ImproveRangeInput {+ preset: string;+ from: string;+ to?: string;+ customFrom?: string;+ customTo?: string;+ region?: string;+}++/** A suggestion as the panel holds it: edited in place, checked, removable. */+export interface DraftSuggestion extends ImproveSuggestion {+ checked: boolean;+ removed: boolean;+ /** Written by the user with "Add your own suggestion". */+ own?: boolean;+}++export const STATE_LABEL: Record<ImproveState, string> = {+ no_runs: 'No runs in this period',+ not_mentioned: 'Not mentioned',+ mentioned_late: 'Mentioned · Late',+ not_cited: 'Mentioned early · not cited',+ doing_well: 'Doing well',+};++/** Order of the groups: the biggest gaps first. */+export const STATE_ORDER: ImproveState[] = [+ 'not_mentioned',+ 'mentioned_late',+ 'not_cited',+ 'doing_well',+ 'no_runs',+];++/** "mentioned in 8 of 120 runs": why a platform's state is what it is. */+export function mentionRateLabel(p: Pick<ImprovePlatform, 'runs' | 'mentionedRuns'>): string {+ return `mentioned in ${p.mentionedRuns} of ${p.runs} run${p.runs === 1 ? '' : 's'}`;+}++export function toDrafts(suggestions: ImproveSuggestion[]): DraftSuggestion[] {+ return suggestions.map((s) => ({ ...s, checked: true, removed: false }));+}++/** "x of y selected · n platforms" — removed suggestions don't count. */+export function selectionSummary(drafts: DraftSuggestion[]): {+ selected: number;+ total: number;+ platforms: number;+} {+ const live = drafts.filter((d) => !d.removed);+ const selected = live.filter((d) => d.checked);+ return {+ selected: selected.length,+ total: live.length,+ platforms: new Set(selected.map((d) => d.platform)).size,+ };+}++/** Whether the user changed anything the server didn't generate. */+export function hasUnsentEdits(drafts: DraftSuggestion[], original: ImproveSuggestion[]): boolean {+ const byId = new Map(original.map((s) => [s.id, s]));+ return drafts.some((d) => {+ if (d.own) return !d.removed;+ const o = byId.get(d.id);+ return !o || d.removed || !d.checked || d.title !== o.title || d.body !== o.body;+ });+}++/** Short label for a source chip. */+export function sourceChipLabel(source: ImproveSource): string {+ switch (source.type) {+ case 'fanout':+ return `Fan-out: ${source.ref}`;+ case 'answer':+ return 'AI answer';+ case 'brand_page':+ return `Your page: ${shortUrl(source.ref)}`;+ case 'competitor_url':+ return shortUrl(source.ref);+ default:+ return source.ref;+ }+}++function shortUrl(url: string): string {+ try {+ const u = new URL(url);+ const path = u.pathname.length > 24 ? `${u.pathname.slice(0, 24)}…` : u.pathname;+ return `${u.hostname.replace(/^www\./, '')}${path === '/' ? '' : path}`;+ } catch {+ return url;+ }+}