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(insights): replace the share of voice charts with the by AI platform table
Cihan99fcc3148ace
diff --git a/supabase/migrations/00133_insights_platform_table.sql b/supabase/migrations/00133_insights_platform_table.sqlnew file mode 100644index 000000000..e0e6e0abb--- /dev/null+++ b/supabase/migrations/00133_insights_platform_table.sql@@ -0,0 +1,188 @@+-- Insights "By AI platform" table (VIS-008).+--+-- The v2 mockup replaces the Share of Voice donut and trend with one table:+-- per platform, Visibility, its change, Coverage, Share of voice and Avg.+-- position, with "Low sample" / "No runs this period" in place of numbers+-- a platform can't support.+--+-- insights_platform_compare[_daily] (00132) already return each platform's+-- Visibility components in both windows; this adds what Coverage and Avg.+-- position need: the position sum (00131) and, for the current window, the+-- prompts answered on each engine and the ones where the brand appeared.+-- They are prompt ids, not counts, because the app folds engines into+-- platforms (ChatGPT is several models and a scraper): a prompt answered+-- by two of them must still count once.+--+-- The window bounds now default to null, read as open, and a missing+-- previous window reads the current one alone: the table also shows on All+-- time, which has nothing to compare with. Same argument order, so the+-- summary line keeps reading them unchanged. `complete` now also waits for+-- the 00131 backfill, which the position sum depends on.++create or replace function public.insights_platform_compare_daily(+ p_brand_id uuid,+ p_cur_from date default null,+ p_cur_to date default null,+ p_prev_from date default null,+ p_prev_to date default null,+ p_models text[] default null,+ p_region text default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between coalesce(p_cur_from, '-infinity'::date)+ and coalesce(p_cur_to, 'infinity'::date)+ then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between coalesce(p_cur_from, '-infinity'::date)+ and coalesce(p_cur_to, 'infinity'::date)+ or d.day between p_prev_from and p_prev_to)+ ),+ shared as (+ select prompt_id+ from prompt_rows+ group by prompt_id+ having bool_or(win = 'cur') and bool_or(win = 'prev')+ ),+ scoped as (+ select * from prompt_rows+ where not p_same_prompts or prompt_id in (select prompt_id from shared)+ ),+ platforms as (+ select model_used, platform, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count,+ sum(sum_position) as sum_position,+ case when win = 'cur' then+ coalesce(array_agg(distinct prompt_id) filter (where has_mention or has_citation),+ '{}')+ end as visible_prompt_ids,+ case when win = 'cur' then array_agg(distinct prompt_id) end+ as active_prompt_ids+ from scoped+ group by model_used, platform, win+ )+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null),+ 'platforms', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', p.model_used,+ 'platform', p.platform,+ 'win', p.win,+ 'answers', p.answers,+ 'mention_answers', p.mention_answers,+ 'citation_answers', p.citation_answers,+ 'sum_inv_position', p.sum_inv_position,+ 'position_count', p.position_count,+ 'sum_position', p.sum_position,+ 'visible_prompt_ids', p.visible_prompt_ids,+ 'active_prompt_ids', p.active_prompt_ids))+ from platforms p),+ '[]'::jsonb)+ );+$$;++create or replace function public.insights_platform_compare(+ p_brand_id uuid,+ p_cur_from timestamptz default null,+ p_cur_to timestamptz default null,+ p_prev_from timestamptz default null,+ p_prev_to timestamptz default null,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,+ pr.mention_count, pr.citation_count, pr.mention_position+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= coalesce(p_prev_from, p_cur_from, '-infinity'::timestamptz)+ and pr.created_at <= coalesce(p_cur_to, 'infinity'::timestamptz)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))+ ),+ -- Each window selected on its own, inclusive at both ends like the card.+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= coalesce(p_cur_from, '-infinity'::timestamptz)+ and f.created_at <= coalesce(p_cur_to, 'infinity'::timestamptz)+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ shared as (+ select prompt_id+ from windowed+ group by prompt_id+ having bool_or(win = 'cur') and bool_or(win = 'prev')+ ),+ scoped as (+ select * from windowed+ where not p_same_prompts or prompt_id in (select prompt_id from shared)+ ),+ platforms as (+ select model_used, platform, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ case when win = 'cur' then+ coalesce(array_agg(distinct prompt_id)+ filter (where mention_count > 0 or citation_count > 0),+ '{}')+ end as visible_prompt_ids,+ case when win = 'cur' then array_agg(distinct prompt_id) end+ as active_prompt_ids+ from scoped+ group by model_used, platform, win+ )+ select jsonb_build_object(+ 'complete', true,+ 'platforms', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', p.model_used,+ 'platform', p.platform,+ 'win', p.win,+ 'answers', p.answers,+ 'mention_answers', p.mention_answers,+ 'citation_answers', p.citation_answers,+ 'sum_inv_position', p.sum_inv_position,+ 'position_count', p.position_count,+ 'sum_position', p.sum_position,+ 'visible_prompt_ids', p.visible_prompt_ids,+ 'active_prompt_ids', p.active_prompt_ids))+ from platforms p),+ '[]'::jsonb)+ );+$$;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex da6f297a1..561f57fc3 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -16064,3 +16064,195 @@ comment on function public.insights_platform_compare() is'Insights summary line (VIS-006, 00132) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_platform_compare_daily.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00133_insights_platform_table.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Insights "By AI platform" table (VIS-008).+--+-- The v2 mockup replaces the Share of Voice donut and trend with one table:+-- per platform, Visibility, its change, Coverage, Share of voice and Avg.+-- position, with "Low sample" / "No runs this period" in place of numbers+-- a platform can't support.+--+-- insights_platform_compare[_daily] (00132) already return each platform's+-- Visibility components in both windows; this adds what Coverage and Avg.+-- position need: the position sum (00131) and, for the current window, the+-- prompts answered on each engine and the ones where the brand appeared.+-- They are prompt ids, not counts, because the app folds engines into+-- platforms (ChatGPT is several models and a scraper): a prompt answered+-- by two of them must still count once.+--+-- The window bounds now default to null, read as open, and a missing+-- previous window reads the current one alone: the table also shows on All+-- time, which has nothing to compare with. Same argument order, so the+-- summary line keeps reading them unchanged. `complete` now also waits for+-- the 00131 backfill, which the position sum depends on.++create or replace function public.insights_platform_compare_daily(+ p_brand_id uuid,+ p_cur_from date default null,+ p_cur_to date default null,+ p_prev_from date default null,+ p_prev_to date default null,+ p_models text[] default null,+ p_region text default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between coalesce(p_cur_from, '-infinity'::date)+ and coalesce(p_cur_to, 'infinity'::date)+ then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between coalesce(p_cur_from, '-infinity'::date)+ and coalesce(p_cur_to, 'infinity'::date)+ or d.day between p_prev_from and p_prev_to)+ ),+ shared as (+ select prompt_id+ from prompt_rows+ group by prompt_id+ having bool_or(win = 'cur') and bool_or(win = 'prev')+ ),+ scoped as (+ select * from prompt_rows+ where not p_same_prompts or prompt_id in (select prompt_id from shared)+ ),+ platforms as (+ select model_used, platform, win,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count,+ sum(sum_position) as sum_position,+ case when win = 'cur' then+ coalesce(array_agg(distinct prompt_id) filter (where has_mention or has_citation),+ '{}')+ end as visible_prompt_ids,+ case when win = 'cur' then array_agg(distinct prompt_id) end+ as active_prompt_ids+ from scoped+ group by model_used, platform, win+ )+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null),+ 'platforms', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', p.model_used,+ 'platform', p.platform,+ 'win', p.win,+ 'answers', p.answers,+ 'mention_answers', p.mention_answers,+ 'citation_answers', p.citation_answers,+ 'sum_inv_position', p.sum_inv_position,+ 'position_count', p.position_count,+ 'sum_position', p.sum_position,+ 'visible_prompt_ids', p.visible_prompt_ids,+ 'active_prompt_ids', p.active_prompt_ids))+ from platforms p),+ '[]'::jsonb)+ );+$$;++create or replace function public.insights_platform_compare(+ p_brand_id uuid,+ p_cur_from timestamptz default null,+ p_cur_to timestamptz default null,+ p_prev_from timestamptz default null,+ p_prev_to timestamptz default null,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_same_prompts boolean default true+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,+ pr.mention_count, pr.citation_count, pr.mention_position+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= coalesce(p_prev_from, p_cur_from, '-infinity'::timestamptz)+ and pr.created_at <= coalesce(p_cur_to, 'infinity'::timestamptz)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))+ ),+ -- Each window selected on its own, inclusive at both ends like the card.+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= coalesce(p_cur_from, '-infinity'::timestamptz)+ and f.created_at <= coalesce(p_cur_to, 'infinity'::timestamptz)+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ shared as (+ select prompt_id+ from windowed+ group by prompt_id+ having bool_or(win = 'cur') and bool_or(win = 'prev')+ ),+ scoped as (+ select * from windowed+ where not p_same_prompts or prompt_id in (select prompt_id from shared)+ ),+ platforms as (+ select model_used, platform, win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ sum(1.0 / mention_position) filter (where mention_position is not null)+ as sum_inv_position,+ count(*) filter (where mention_position is not null) as position_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ case when win = 'cur' then+ coalesce(array_agg(distinct prompt_id)+ filter (where mention_count > 0 or citation_count > 0),+ '{}')+ end as visible_prompt_ids,+ case when win = 'cur' then array_agg(distinct prompt_id) end+ as active_prompt_ids+ from scoped+ group by model_used, platform, win+ )+ select jsonb_build_object(+ 'complete', true,+ 'platforms', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', p.model_used,+ 'platform', p.platform,+ 'win', p.win,+ 'answers', p.answers,+ 'mention_answers', p.mention_answers,+ 'citation_answers', p.citation_answers,+ 'sum_inv_position', p.sum_inv_position,+ 'position_count', p.position_count,+ 'sum_position', p.sum_position,+ 'visible_prompt_ids', p.visible_prompt_ids,+ 'active_prompt_ids', p.active_prompt_ids))+ from platforms p),+ '[]'::jsonb)+ );+$$;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 596c21d63..9326b3c6b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1643,7 +1643,6 @@"positiveSentiment": "Positive Sentiment","neutral": "Neutral","negative": "Negative",- "sovByPlatform": "Share of Voice by Platform","resultDetail": {"notFoundTitle": "Result not found","notFoundDescription": "This result may have been deleted or does not exist.",@@ -1715,6 +1714,19 @@"copy": "Copy summary","copied": "Summary copied","copyFailed": "Couldn't copy the summary. Select the text and copy it instead."+ },+ "platforms": {+ "title": "By AI platform",+ "tableLabel": "Visibility by AI platform",+ "platform": "Platform",+ "visibility": "Visibility",+ "change": "Change",+ "coverage": "Coverage",+ "shareOfVoice": "Share of voice",+ "avgPosition": "Avg. pos",+ "lowSample": "Low sample · {count, plural, one {# run} other {# runs}}",+ "noRuns": "No runs this period",+ "biggestDrop": "biggest drop"}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsxindex e0ec5dd54..3233b1477 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx@@ -24,7 +24,6 @@ import type {VisibilityTrendPoint,VisibilityRateTrendData,SoVByPlatform,- SoVTrendPoint,} from '@/lib/actions/tracking';import { getFaviconUrl } from '@/lib/favicon';import { formatCompactNumber } from '@/lib/format';@@ -635,107 +634,3 @@ export function ShareOfVoicePlatformChart({</div>);}--function SoVTrendTooltip({- active,- payload,- label,-}: {- active?: boolean;- payload?: { name: string; value: number; color: string }[];- label?: string;-}) {- if (!active || !payload?.length) return null;- return (- <div className="rounded-lg border bg-background px-3 py-2 shadow-md text-xs">- <p className="font-medium text-foreground mb-1">{label}</p>- {payload.map((entry) => (- <div key={entry.name} className="flex items-center gap-2">- <span- className="inline-block h-2 w-2 rounded-full shrink-0"- style={{ backgroundColor: entry.color }}- />- <span className="text-muted-foreground">{entry.name}:</span>- <span className="font-medium text-foreground">{entry.value}%</span>- </div>- ))}- </div>- );-}--export function ShareOfVoiceTrendChart({ data }: { data: SoVTrendPoint[] }) {- if (data.length === 0) {- return (- <div className="flex items-center justify-center h-[280px] text-sm text-muted-foreground">- No trend data available yet- </div>- );- }-- const hasCompetitors = data.some((d) => d.competitorSov > 0);-- return (- <ChartContainer height={280}>- {(width) => (- <AreaChart- width={width}- height={280}- data={data}- margin={{ top: 4, right: 4, left: -24, bottom: 0 }}- >- <defs>- <linearGradient id="gradSovBrand" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#6366f1" stopOpacity={0.2} />- <stop offset="95%" stopColor="#6366f1" stopOpacity={0} />- </linearGradient>- <linearGradient id="gradSovComp" x1="0" y1="0" x2="0" y2="1">- <stop offset="5%" stopColor="#94a3b8" stopOpacity={0.15} />- <stop offset="95%" stopColor="#94a3b8" stopOpacity={0} />- </linearGradient>- </defs>- <CartesianGrid strokeDasharray="3 3" className="stroke-border" vertical={false} />- <XAxis- dataKey="date"- tick={{ fontSize: 11 }}- tickLine={false}- axisLine={false}- className="fill-muted-foreground"- />- <YAxis- tick={{ fontSize: 11 }}- tickLine={false}- axisLine={false}- className="fill-muted-foreground"- domain={[0, 100]}- tickFormatter={(v: number) => `${v}%`}- />- <Tooltip content={<SoVTrendTooltip />} />- <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 11, paddingTop: 8 }} />- <Area- type="monotone"- dataKey="brandSov"- name="Your Brand"- stroke="#6366f1"- strokeWidth={2}- fill="url(#gradSovBrand)"- dot={false}- activeDot={{ r: 4 }}- />- {hasCompetitors && (- <Area- type="monotone"- dataKey="competitorSov"- name="Competitors"- stroke="#94a3b8"- strokeWidth={2}- fill="url(#gradSovComp)"- dot={false}- activeDot={{ r: 4 }}- strokeDasharray="4 4"- />- )}- </AreaChart>- )}- </ChartContainer>- );-}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsxnew file mode 100644index 000000000..2439b4889--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_platform-table.tsx@@ -0,0 +1,108 @@+'use client';++import { useTranslations } from 'next-intl';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import type { PlatformTableRow } from '@/lib/insights-summary';+import { TONE_TEXT, upIsGood } from './kpi-format';++/**+ * "By AI platform" (VIS-008), as in the v2 mockup: per platform, Visibility,+ * its change, Coverage, Share of voice and Avg. position. A platform without+ * enough answers shows why instead of numbers; the row with the biggest drop+ * is tinted. Replaces the Share of Voice donut and trend charts.+ */+export function PlatformTable({ rows }: { rows: PlatformTableRow[] }) {+ const t = useTranslations('insights.platforms');+ // Share-of-voice bars are scaled to the largest share in the table.+ const maxSov = Math.max(0, ...rows.map((r) => r.shareOfVoice ?? 0));++ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ </CardHeader>+ <CardContent className="overflow-x-auto">+ <table className="w-full min-w-[560px] text-sm" aria-label={t('tableLabel')}>+ <thead>+ <tr className="border-b text-[11px] uppercase tracking-wide text-muted-foreground">+ <th className="py-2 pr-3 text-left font-medium">{t('platform')}</th>+ <th className="w-20 px-2 py-2 text-right font-medium">{t('visibility')}</th>+ <th className="w-16 px-2 py-2 text-right font-medium">{t('change')}</th>+ <th className="w-20 px-2 py-2 text-right font-medium">{t('coverage')}</th>+ <th className="w-[34%] px-2 py-2 text-left font-medium">{t('shareOfVoice')}</th>+ <th className="w-16 py-2 pl-2 text-right font-medium">{t('avgPosition')}</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => {+ const change = upIsGood(row.change);+ return (+ <tr+ key={row.name}+ className={cn(+ 'border-b last:border-b-0',+ row.worst && 'bg-red-50 dark:bg-red-950/30',+ )}+ >+ <td className="py-2.5 pr-3 font-medium">+ {row.name}+ {row.worst && <span className="sr-only"> ({t('biggestDrop')})</span>}+ </td>+ {row.status === 'ok' ? (+ <>+ <td className="px-2 py-2.5 text-right font-semibold tabular-nums">+ {row.visibility}+ </td>+ <td+ className={cn(+ 'px-2 py-2.5 text-right font-medium tabular-nums',+ change && TONE_TEXT[change.tone],+ )}+ >+ {change?.text ?? '—'}+ </td>+ <td className="px-2 py-2.5 text-right tabular-nums">+ {row.coverage === null ? '—' : `${row.coverage}%`}+ </td>+ <td className="px-2 py-2.5">+ {row.shareOfVoice === null ? (+ <span className="text-muted-foreground">—</span>+ ) : (+ <span className="flex items-center gap-2">+ <span className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">+ <span+ className="block h-full rounded-full bg-foreground/60"+ style={{+ width: `${maxSov > 0 ? (row.shareOfVoice / maxSov) * 100 : 0}%`,+ }}+ />+ </span>+ <span className="min-w-10 text-right tabular-nums">+ {row.shareOfVoice}%+ </span>+ </span>+ )}+ </td>+ <td className="py-2.5 pl-2 text-right tabular-nums">+ {row.avgPosition === null ? '—' : `#${row.avgPosition}`}+ </td>+ </>+ ) : (+ <td colSpan={5} className="px-2 py-2.5">+ <span className="inline-flex rounded-full bg-muted px-2 py-px text-[11.5px] text-muted-foreground">+ {row.status === 'noRuns'+ ? t('noRuns')+ : t('lowSample', { count: row.runs })}+ </span>+ </td>+ )}+ </tr>+ );+ })}+ </tbody>+ </table>+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex ec25d630c..4f7bef6ca 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -22,21 +22,6 @@ const CompetitorLeaderboard = dynamic(},);-const ShareOfVoicePlatformChart = dynamic(- () => import('./_charts').then((m) => m.ShareOfVoicePlatformChart),- {- ssr: false,- loading: () => <Skeleton className="h-64 w-full" />,- },-);--const ShareOfVoiceTrendChart = dynamic(- () => import('./_charts').then((m) => m.ShareOfVoiceTrendChart),- {- ssr: false,- loading: () => <Skeleton className="h-64 w-full" />,- },-);import { MetricBreakdownSheet } from './_metric-breakdown-sheet';import { FormulaDialog } from './_formula-dialog';import { useBrandStore } from '@/stores/use-brand-store';@@ -82,7 +67,6 @@ import {TrendingDown,Loader2,FlaskConical,- PieChart,Users,StopCircle,ArrowRight,@@ -107,9 +91,10 @@ import { toast } from 'sonner';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import type { PromptComparison } from '@/lib/insights-same-prompts';import type { KpiSeriesDay } from '@/lib/insights-kpis';-import type { PlatformChange } from '@/lib/insights-summary';+import type { PlatformChange, PlatformTableRow } from '@/lib/insights-summary';import { KpiRows } from './_kpi-cards';import { SummaryLine } from './_summary-line';+import { PlatformTable } from './_platform-table';// ─── Filter Types ─────────────────────────────────────────────────────────────@@ -233,27 +218,6 @@ function getDateRange(// ─── Sub-components ───────────────────────────────────────────────────────────-// ─── Delta Badge ──────────────────────────────────────────────────────────────--function DeltaBadge({ delta, suffix = '%' }: { delta: number | null; suffix?: string }) {- if (delta === null) return null;- if (delta === 0) return <span className="text-xs text-muted-foreground">— 0{suffix}</span>;- const pos = delta > 0;- return (- <span- className={cn(- 'flex items-center gap-0.5 text-xs font-medium',- pos ? 'text-green-600 dark:text-green-400' : 'text-red-500',- )}- >- {pos ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}- {pos ? '+' : ''}- {delta}- {suffix}- </span>- );-}-// ─── Run Single Prompt Dialog ─────────────────────────────────────────────────function RunSinglePromptDialog({@@ -900,6 +864,7 @@ export default function InsightsPage() {const [coverage, setCoverage] = useState<CoverageKpi | null>(null);const [kpiSeries, setKpiSeries] = useState<KpiSeriesDay[] | null>(null);const [platformChanges, setPlatformChanges] = useState<PlatformChange[] | null>(null);+ const [platforms, setPlatforms] = useState<PlatformTableRow[] | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);// The window and filters the cards were last loaded with (the 24h view// anchored to its tracking run): the breakdown panel explains those exact@@ -989,6 +954,7 @@ export default function InsightsPage() {setCoverage(insights.coverage);setKpiSeries(insights.kpiSeries);setPlatformChanges(insights.platformChanges);+ setPlatforms(insights.platforms);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1528,40 +1494,8 @@ export default function InsightsPage() {<NoCompetitorsTeaser />)}- {/* Share of Voice */}- {sovData && (- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <Card>- <CardHeader className="pb-2">- <CardTitle className="flex items-center gap-2 text-sm font-medium">- <PieChart className="h-4 w-4" />- {t('sovByPlatform')}- </CardTitle>- {sovData.overallSovChange !== null && sovData.overallSovChange !== 0 && (- <DeltaBadge delta={sovData.overallSovChange} suffix=" pts" />- )}- </CardHeader>- <CardContent>- <ShareOfVoicePlatformChart- data={sovData.byPlatform}- overallSov={sovData.overallSov}- />- </CardContent>- </Card>-- <Card>- <CardHeader className="pb-2">- <CardTitle className="flex items-center gap-2 text-sm font-medium">- <TrendingUp className="h-4 w-4" />- Share of Voice Trend- </CardTitle>- </CardHeader>- <CardContent>- <ShareOfVoiceTrendChart data={sovData.trend} />- </CardContent>- </Card>- </div>- )}+ {/* By AI platform (VIS-008): replaces the Share of Voice charts. */}+ {platforms && platforms.length > 0 && <PlatformTable rows={platforms} />}{/* Recommendations (#459) — stored data, not period-scoped */}{recommendations && <RecommendationsSection data={recommendations} />}diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 6a5075fb3..86356385c 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -45,7 +45,14 @@ import { getPromptVolumes } from '@/lib/actions/volumes';import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import { percentageChange } from '@/lib/metrics';-import { parsePlatformRows, platformChanges, type PlatformChange } from '@/lib/insights-summary';+import {+ parsePlatformRows,+ platformChanges,+ platformTable,+ type PlatformChange,+ type PlatformRow,+ type PlatformTableRow,+} from '@/lib/insights-summary';import {coverage as coverageRate,kpiRates,@@ -727,6 +734,8 @@ export interface InsightsData {* window, before the backfill, or when the read failed.*/platformChanges: PlatformChange[] | null;+ /** The "By AI platform" table (VIS-008); null under the same conditions. */+ platforms: PlatformTableRow[] | null;/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */trackingWindow: TrackingWindow | null;}@@ -822,6 +831,7 @@ type WindowedInsights = Pick<| 'coverage'| 'kpiSeries'| 'platformChanges'+ | 'platforms'>;type InsightsFilterArgs = {@@ -863,36 +873,27 @@ async function loadWindowedInsights(return fallback;});- const [- summary,- competitors,- sov,- filterOptions,- trend,- same,- coverage,- kpiSeries,- platformChangesData,- ] = await Promise.all([- getInsightsSummary(brandId, filterOpts),- lenient(- getCompetitorComparison(brandId, filterOpts),- EMPTY_COMPETITORS,- 'competitor comparison',- ),- lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),- getInsightsFilterOptions(brandId),- // The chart follows the same window as every other number on the page.- lenient<VisibilityRateTrendData | null>(- getVisibilityRateTrend(brandId, filterOpts),- null,- 'visibility trend',- ),- getSamePromptComparison(brandId, filterOpts),- lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),- lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),- lenient(getPlatformChanges(brandId, filterOpts), null, 'platform changes'),- ]);+ const [summary, competitors, sov, filterOptions, trend, same, coverage, kpiSeries, platformData] =+ await Promise.all([+ getInsightsSummary(brandId, filterOpts),+ lenient(+ getCompetitorComparison(brandId, filterOpts),+ EMPTY_COMPETITORS,+ 'competitor comparison',+ ),+ lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),+ getInsightsFilterOptions(brandId),+ // The chart follows the same window as every other number on the page.+ lenient<VisibilityRateTrendData | null>(+ getVisibilityRateTrend(brandId, filterOpts),+ null,+ 'visibility trend',+ ),+ getSamePromptComparison(brandId, filterOpts),+ lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),+ lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),+ lenient(getPlatformData(brandId, filterOpts), null, 'platforms'),+ ]);const windowed = {...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),competitors,@@ -900,7 +901,15 @@ async function loadWindowedInsights(trend,coverage,kpiSeries,- platformChanges: platformChangesData,+ platformChanges: platformData?.changes ?? null,+ platforms: platformData+ ? platformTable(+ platformData.rows,+ platformData.changes ?? [],+ sov.byPlatform,+ resolveProvider,+ )+ : null,};return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);}@@ -996,49 +1005,59 @@ async function getKpiSeries(}/**- * Each platform's Visibility change over the card's windows, for the summary- * line's "Up most / Down most" (VIS-006). With Same prompts on (the default)- * only the prompts answered in both windows count, like every other change.+ * Each platform in the comparison windows (VIS-006, VIS-008): the rows over+ * every prompt, for the "By AI platform" table's values, and each platform's+ * Visibility change for the summary line's movers and the table's Change+ * column. With Same prompts on (the default) the changes count only the+ * prompts answered in both windows, like every other change. All time reads+ * the current window alone and has no changes.*/-async function getPlatformChanges(+async function getPlatformData(brandId: string,opts?: InsightsFilterArgs,-): Promise<PlatformChange[] | null> {+): Promise<{ rows: PlatformRow[]; changes: PlatformChange[] | null } | null> {const windows = comparisonWindows(opts);- if (!windows.prev) return null;const supabase = await dbClient();const base = {p_brand_id: brandId,p_models: modelFilterArray(opts?.model),p_region: opts?.region ?? undefined,- p_same_prompts: opts?.samePrompts !== false,};- let res;- if (windows.cur.kind === 'days') {- const { cur, prev } = deltaDayWindows(windows.cur.days);- res = await supabase.rpc('insights_platform_compare_daily', {- ...base,- p_cur_from: cur.dayFrom,- p_cur_to: cur.dayTo,- p_prev_from: prev.dayFrom,- p_prev_to: prev.dayTo,- });- } else {- const cur = windowBounds(windows.cur);- const prev = windowBounds(windows.prev);- res = await supabase.rpc('insights_platform_compare', {- ...base,- p_cur_from: cur.from,- p_cur_to: cur.to,- p_prev_from: prev.from,- p_prev_to: prev.to,- p_topic_id: opts?.topicId ?? undefined,- });- }- if (res.error) throw new Error(res.error.message);- const rows = parsePlatformRows(res.data);- return rows && platformChanges(rows, (model, platform) => resolveProvider(model, platform));+ // An absent bound is open; without a previous window only the current one is read.+ const prev = windows.prev && windowBounds(windows.prev);+ const read = async (samePrompts: boolean) => {+ const res =+ windows.cur.kind === 'days'+ ? await supabase.rpc('insights_platform_compare_daily', {+ ...base,+ p_same_prompts: samePrompts,+ p_cur_from: windows.cur.days.dayFrom,+ p_cur_to: windows.cur.days.dayTo,+ p_prev_from: prev?.from,+ p_prev_to: prev?.to,+ })+ : await supabase.rpc('insights_platform_compare', {+ ...base,+ p_same_prompts: samePrompts,+ p_cur_from: windows.cur.from,+ p_cur_to: windows.cur.to,+ p_prev_from: prev?.from,+ p_prev_to: prev?.to,+ p_topic_id: opts?.topicId ?? undefined,+ });+ if (res.error) throw new Error(res.error.message);+ return parsePlatformRows(res.data);+ };++ const samePrompts = prev !== null && opts?.samePrompts !== false;+ const [all, same] = await Promise.all([+ read(false),+ samePrompts ? read(true) : Promise.resolve(null),+ ]);+ const changeRows = samePrompts ? same : all;+ if (!all || !changeRows) return null;+ return { rows: all, changes: prev ? platformChanges(changeRows, resolveProvider) : null };}/**diff --git a/web/src/lib/insights-summary.test.ts b/web/src/lib/insights-summary.test.tsindex 0d501300b..96a23f019 100644--- a/web/src/lib/insights-summary.test.ts+++ b/web/src/lib/insights-summary.test.ts@@ -4,7 +4,9 @@ import {parsePlatformRows,platformChanges,platformMovers,+ platformTable,rankSummary,+ type PlatformChange,type PlatformRow,} from './insights-summary';@@ -14,6 +16,7 @@ const row = (win: 'cur' | 'prev',answers: number,mentions: number,+ extra: Partial<PlatformRow> = {},): PlatformRow => ({model_used,platform,@@ -23,9 +26,13 @@ const row = (citation_answers: 0,sum_inv_position: null,position_count: 0,+ sum_position: null,+ visible_prompt_ids: [],+ active_prompt_ids: [],+ ...extra,});-// Model slugs fold into the platform names "Share of Voice by Platform" uses.+// Model slugs fold into platform names, as resolveProvider does.const platformOf = (model: string | null, platform: string | null) =>platform === 'google-aimode' ? 'Google AI Mode' : model?.startsWith('gpt-') ? 'ChatGPT' : 'Other';@@ -57,7 +64,21 @@ describe('platformChanges', () => {});it('leaves out platforms not answered in both windows', () => {- expect(platformChanges([row('gpt-5-mini', null, 'cur', 10, 5)], platformOf)).toEqual([]);+ expect(platformChanges([row('gpt-5-mini', null, 'cur', 30, 5)], platformOf)).toEqual([]);+ });++ it('leaves out a change over fewer than 20 answers in either window', () => {+ const changes = platformChanges(+ [+ row('gpt-4o', null, 'cur', 40, 4),+ row('gpt-4o', null, 'prev', 19, 15),+ row(null, 'google-aimode', 'cur', 20, 10),+ row(null, 'google-aimode', 'prev', 20, 2),+ ],+ platformOf,+ );++ expect(changes.map((c) => c.name)).toEqual(['Google AI Mode']);});});@@ -122,8 +143,121 @@ describe('parsePlatformRows', () => {citation_answers: 0,sum_inv_position: null,position_count: 0,+ sum_position: null,+ visible_prompt_ids: [],+ active_prompt_ids: [],},]);expect(parsePlatformRows({ complete: false, platforms: [] })).toBeNull();});++ it('reads the 00133 position sum and prompt ids', () => {+ expect(+ parsePlatformRows({+ complete: true,+ platforms: [+ {+ model_used: 'gpt-4o',+ win: 'cur',+ sum_position: '12',+ visible_prompt_ids: ['p1'],+ active_prompt_ids: ['p1', 'p2'],+ },+ ],+ })?.[0],+ ).toMatchObject({+ sum_position: 12,+ visible_prompt_ids: ['p1'],+ active_prompt_ids: ['p1', 'p2'],+ });+ });+});++describe('platformTable', () => {+ const change = (name: string, c: number): PlatformChange => ({+ name,+ cur: 0,+ prev: 0,+ change: c,+ });++ it('folds model slugs and fills each column from the current window', () => {+ const [chatgpt] = platformTable(+ [+ row('gpt-5-mini', null, 'cur', 30, 6, {+ sum_inv_position: 2,+ position_count: 4,+ sum_position: 10,+ visible_prompt_ids: ['p1', 'p2'],+ active_prompt_ids: ['p1', 'p2', 'p3', 'p4'],+ }),+ // The same prompts on another ChatGPT model count once.+ row('gpt-4o', null, 'cur', 30, 6, {+ sum_inv_position: 1,+ position_count: 2,+ sum_position: 8,+ visible_prompt_ids: ['p2', 'p3'],+ active_prompt_ids: ['p1', 'p2', 'p3', 'p4', 'p5'],+ }),+ row('gpt-4o', null, 'prev', 60, 50),+ ],+ [change('ChatGPT', -3.2)],+ [{ provider: 'ChatGPT', sov: 41.5 }],+ platformOf,+ );++ expect(chatgpt).toEqual({+ name: 'ChatGPT',+ status: 'ok',+ runs: 60,+ visibility: computeAiVisibilityScore({+ answers: 60,+ mentionAnswers: 12,+ citationAnswers: 0,+ positionFactor: 3 / 6,+ }),+ change: -3.2,+ coverage: 60,+ shareOfVoice: 41.5,+ avgPosition: 3,+ worst: true,+ });+ });++ it('shows why instead of numbers below 20 answers or without runs', () => {+ const table = platformTable(+ [+ row(null, 'google-aimode', 'prev', 50, 10),+ row('claude-sonnet', null, 'cur', 12, 6),+ row('gpt-4o', null, 'cur', 40, 4),+ ],+ [change('Other', -5)],+ [{ provider: 'Other', sov: 80 }],+ platformOf,+ );++ expect(table.map((r) => [r.name, r.status, r.runs])).toEqual([+ ['ChatGPT', 'ok', 40],+ ['Other', 'lowSample', 12],+ ['Google AI Mode', 'noRuns', 0],+ ]);+ // A low-sample row has no values, so its drop doesn't tint it.+ expect(table[1]).toMatchObject({ visibility: null, change: null, shareOfVoice: null });+ expect(table.some((r) => r.worst)).toBe(false);+ });++ it('sorts by Visibility and tints only the biggest drop', () => {+ const table = platformTable(+ [row('gpt-4o', null, 'cur', 40, 4), row(null, 'google-aimode', 'cur', 40, 30)],+ [change('ChatGPT', -1), change('Google AI Mode', -4)],+ [],+ platformOf,+ );++ expect(table.map((r) => [r.name, r.worst])).toEqual([+ ['Google AI Mode', true],+ ['ChatGPT', false],+ ]);+ expect(table[0].shareOfVoice).toBeNull();+ });});diff --git a/web/src/lib/insights-summary.ts b/web/src/lib/insights-summary.tsindex 4cfe1743d..9f48cc8fb 100644--- a/web/src/lib/insights-summary.ts+++ b/web/src/lib/insights-summary.ts@@ -1,4 +1,5 @@import { computeAiVisibilityScore } from '@/lib/visibility-score';+import { coverage } from '@/lib/insights-kpis';/*** The Insights summary line (VIS-006): the brand's rank and the gap to its@@ -8,7 +9,7 @@ import { computeAiVisibilityScore } from '@/lib/visibility-score';const round1 = (n: number) => Math.round(n * 10) / 10;-/** One row of insights_platform_compare[_daily] (00132). */+/** One row of insights_platform_compare[_daily] (00132, 00133). */export interface PlatformRow {model_used: string | null;platform: string | null;@@ -18,6 +19,14 @@ export interface PlatformRow {citation_answers: number;sum_inv_position: number | null;position_count: number;+ /** 00133: for the platform table's Avg. position. */+ sum_position: number | null;+ /**+ * 00133, current window only: the prompts answered on this engine and the+ * ones where the brand appeared, for the platform table's Coverage.+ */+ visible_prompt_ids: string[];+ active_prompt_ids: string[];}/** A platform's Visibility in both windows. */@@ -29,6 +38,7 @@ export interface PlatformChange {}const num = (v: unknown): number => Number(v ?? 0);+const ids = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : []);/*** The RPC payload, or null when it can't be used: missing, or read from@@ -50,6 +60,10 @@ export function parsePlatformRows(raw: unknown): PlatformRow[] | null {? null: num(p.sum_inv_position),position_count: num(p.position_count),+ sum_position:+ p.sum_position === null || p.sum_position === undefined ? null : num(p.sum_position),+ visible_prompt_ids: ids(p.visible_prompt_ids),+ active_prompt_ids: ids(p.active_prompt_ids),}));}@@ -69,10 +83,14 @@ const score = (s: Sums) =>positionFactor: s.positions > 0 ? s.invPosition / s.positions : null,});+/** Fewer answers than this and a platform's numbers aren't shown (spec v2: "Low sample"). */+export const LOW_SAMPLE_ANSWERS = 20;+/*** Each platform's Visibility change, with model slugs folded into their- * platform the way "Share of Voice by Platform" names them. Only platforms- * answered in both windows; biggest rise first.+ * platform (`platformOf`). Only platforms with at least LOW_SAMPLE_ANSWERS+ * answers in both windows, so a swing over a handful of answers is never+ * named; biggest rise first.*/export function platformChanges(rows: PlatformRow[],@@ -102,6 +120,7 @@ export function platformChanges(for (const [name, { cur, prev }] of sums) {const c = score(cur);const p = score(prev);+ if (cur.answers < LOW_SAMPLE_ANSWERS || prev.answers < LOW_SAMPLE_ANSWERS) continue;if (c === null || p === null) continue;out.push({ name, cur: c, prev: p, change: round1(c - p) });}@@ -140,3 +159,99 @@ export function rankSummary(neighbour: { name: other.name, gap, side: gap === 0 ? 'tied' : i > 0 ? 'behind' : 'ahead' },};}++// ─── By AI platform table (VIS-008) ─────────────────────────────────────────++export interface PlatformTableRow {+ name: string;+ /** 'noRuns': no answers this period; 'lowSample': too few to show rates. */+ status: 'ok' | 'lowSample' | 'noRuns';+ /** Answers this period. */+ runs: number;+ visibility: number | null;+ /** Visibility change, following Same prompts; null without one. */+ change: number | null;+ /** % of the prompts answered on the platform where the brand appeared. */+ coverage: number | null;+ shareOfVoice: number | null;+ avgPosition: number | null;+ /** The row with the biggest drop, tinted in the table. */+ worst: boolean;+}++/**+ * The "By AI platform" rows: each platform's values over every prompt in+ * the current window, its change (the same numbers the summary line's movers+ * use) and its share of voice. Platforms answered only in the previous+ * window read "No runs this period", never 0%. Sorted by Visibility, then the+ * low-sample ones, then the ones without runs.+ */+export function platformTable(+ rows: PlatformRow[],+ changes: PlatformChange[],+ shareOfVoice: { provider: string; sov: number }[],+ platformOf: (modelUsed: string | null, platform: string | null) => string,+): PlatformTableRow[] {+ const cur = new Map<+ string,+ Sums & { sumPosition: number; visible: Set<string>; active: Set<string> }+ >();+ const seen = new Set<string>();+ for (const r of rows) {+ const name = platformOf(r.model_used, r.platform);+ seen.add(name);+ if (r.win !== 'cur') continue;+ const s = cur.get(name) ?? {+ answers: 0,+ mentions: 0,+ citations: 0,+ invPosition: 0,+ positions: 0,+ sumPosition: 0,+ visible: new Set<string>(),+ active: new Set<string>(),+ };+ s.answers += r.answers;+ s.mentions += r.mention_answers;+ s.citations += r.citation_answers;+ s.invPosition += r.sum_inv_position ?? 0;+ s.positions += r.position_count;+ s.sumPosition += r.sum_position ?? 0;+ // A prompt answered by two of the platform's engines counts once.+ r.visible_prompt_ids.forEach((id) => s.visible.add(id));+ r.active_prompt_ids.forEach((id) => s.active.add(id));+ cur.set(name, s);+ }++ const out: PlatformTableRow[] = [...seen].map((name) => {+ const s = cur.get(name);+ const runs = s?.answers ?? 0;+ const status = runs === 0 ? 'noRuns' : runs < LOW_SAMPLE_ANSWERS ? 'lowSample' : 'ok';+ const ok = status === 'ok' && s;+ return {+ name,+ status,+ runs,+ visibility: ok ? score(s) : null,+ change: ok ? (changes.find((c) => c.name === name)?.change ?? null) : null,+ coverage: ok ? coverage(s.visible.size, s.active.size) : null,+ shareOfVoice: ok ? (shareOfVoice.find((p) => p.provider === name)?.sov ?? null) : null,+ avgPosition: ok && s.positions > 0 ? round1(s.sumPosition / s.positions) : null,+ worst: false,+ };+ });++ const drops = out.filter((r) => r.change !== null && r.change < 0);+ if (drops.length > 0) {+ drops.reduce((a, b) => (b.change! < a.change! ? b : a)).worst = true;+ }++ const order = { ok: 0, lowSample: 1, noRuns: 2 };+ return out.sort(+ (a, b) =>+ order[a.status] - order[b.status] ||+ (b.visibility ?? 0) - (a.visibility ?? 0) ||+ b.runs - a.runs ||+ a.name.localeCompare(b.name),+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 9d0e4f1bd..5d2798998 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3108,11 +3108,11 @@ export type Database = {insights_platform_compare: {Args: {p_brand_id: string- p_cur_from: string- p_cur_to: string+ p_cur_from?: string+ p_cur_to?: stringp_models?: string[]- p_prev_from: string- p_prev_to: string+ p_prev_from?: string+ p_prev_to?: stringp_region?: stringp_same_prompts?: booleanp_topic_id?: string@@ -3122,11 +3122,11 @@ export type Database = {insights_platform_compare_daily: {Args: {p_brand_id: string- p_cur_from: string- p_cur_to: string+ p_cur_from?: string+ p_cur_to?: stringp_models?: string[]- p_prev_from: string- p_prev_to: string+ p_prev_from?: string+ p_prev_to?: stringp_region?: stringp_same_prompts?: boolean}