Skip to content

feat(insights): add the topics vs competitors heat map - #1044

Merged
gkhngyk merged 49 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-topic-heatmap
Oct 16, 2026
Merged

gkhngyk merged 49 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-topic-heatmap

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #1043 (VIS-007) → #1042 (VIS-009) → #1041 (VIS-004) → #1039 (VIS-008) → #1038 (VIS-006) → #1037 (VIS-003) → #1036 (VIS-002) → #1035 (VIS-001). Until those merge, this PR also shows their commits. The VIS-010 heat map is the last two commits: de6ec92 and the shading fix ec72a1d.

Summary

The v2 mockup compares you with your competitors topic by topic. This is the first part of VIS-010 in the Visibility spec v2: the heat map. The mockup's example:

Topics vs competitors
TOPIC                    YOU    SEMRUSH  PROFOUND  PEEC AI   GAP
Open Source AEO          48.6   12.0     18.4      20.1      Lead
AI Rank Tracker          17.5   41.2     44.0      24.3     −26.5
AI Visibility            21.4   39.0     40.2      31.5     −18.8

What it shows:

  • Rows: active topics answered in the range.
    • Order: topics you lead first, then the ones you trail (biggest gap first), then topics with fewer than 20 answers.
    • Low sample: those cells are faded and the Gap column says "Low sample".
    • Length: six rows show, and "Show all N" opens the rest.
  • Columns: you, then the competitors on the trend: the pinned ones (feat(insights): pin competitors and mark prompt and action days on the trend #1043), or the strongest four without pins. So the chart and the map always compare the same brands.
  • Cells: the topic's Visibility score.
    • Formula: the card's formula with your answers in the topic as the denominator, which is how the leaderboard scores competitors.
    • Shading: light to dark by where the score sits between the table's lowest and highest non-zero score, so the cells read in steps whatever the level. A brand scoring 50–80 everywhere would be one dark grey at the mockup's fixed 15/25/35/45 steps. A 0 stays the lightest, and the shades are soft theme tints that read in light and dark mode.
  • Gap: "Lead" in green, or your score minus the topic leader's in red ("−26.5").
  • Navigation: the topic name opens the topic. Cells are a mouse shortcut to the same page without adding keyboard stops.
  • Hidden: on the 24h view, where the rollups don't apply, and with a topic selected, where one row isn't a map.

Code:

  • lib/insights-topics.ts holds the logic:
    • parseTopicCompetitors;
    • topicHeatmap: scores, order and gap;
    • heatShade.
  • _topic-heatmap.tsx is the card.

Not in this PR: "Send biggest gap to Actions", the mockup button that opens a Compete action with tasks. It needs a server route and a new user-sent Action Center kind, so it follows in its own PR on top of this one.

Data

Migration 00137 adds insights_topic_competitors_daily(p_brand_id, p_day_from, p_day_to, p_models, p_region). It returns, per active topic, the brand's Visibility components over the topic's prompts and each live competitor's components over the same answers. It reads the prompt-grain rollups (00130), so it needs no new backfill.

  • Topic membership is read at query time, so a moved prompt takes its history with it.
  • Security: it's security invoker.
  • complete is false until the rollups are backfilled, and the map is hidden until then.

On a dev database, the topics' answers add up to the brand's 30-day total.

Review

I ran a code review before opening this. It found 6 things and 4 are fixed:

  • every cell was its own link (five keyboard stops per row to one page); the topic name is now the link;
  • whole-number gaps lost their decimal ("−29" next to "−20.3");
  • low-sample cells looked as solid as the rest;
  • with an empty trend, the columns were picked arbitrarily.

Left as notes:

  • the map scores topics from the rollups, while the topic page it opens scores on the raw path, so the two can differ slightly;
  • one more rollup read per page load.

Related issue

None. Product spec: Visibility spec v2, task VIS-010 (part 1). Depends on #1043, #1042, #1041, #1039, #1038, #1037, #1036 and #1035.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00137 (on top of 00129–00136).
  2. Open Insights on 30d for a brand with topics and competitors. "Topics vs competitors" sits under By AI platform / Why it changed.
  3. Check the columns and scores:
    • the columns match the trend's chips; pin a different competitor and the map's columns follow;
    • your score in a topic matches the brand's Visibility for that topic.
  4. A topic you trail shows the gap to its leader in red; one you lead shows "Lead".
  5. Click a topic name: its topic page opens.
  6. Pick 24h, or select a topic: the map is hidden.
  7. Check 1024px and dark mode.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): 0 errors; the 7 warnings are in code this PR doesn't touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • yarn test: 620/620. New tests are in insights-topics.test.ts:
    • scoring over your answers, with an unnamed competitor at 0;
    • row order;
    • a tie counting as a lead;
    • shades spread over the scores in view;
    • parsing.
  • yarn build: passed.
  • bash supabase/build-schema.sh: schema.sql is up to date.
  • npm run version:check: passed.
  • I checked it in the browser at 1440px and 1024px, in light and dark mode, and on 30d, 90d, 24h and a topic.
    • The demo brand has two topics, both led by the brand, so I checked shading and gaps with temporary sample topics, not committed.

🤖 Generated with Claude Code

cihan-gyk and others added 8 commits October 14, 2026 17:51
Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…form table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is ready for review. It's the first part of VIS-010 from the Visibility spec v2, stacked on #1043 → #1042 → #1041 → #1039 → #1038 → #1037 → #1036 → #1035. Until those merge, the heat map is the last commit.

It adds the mockup's "Topics vs competitors" heat map:

  • a row per topic and a column for you and each competitor on the trend;
  • each cell is the topic's Visibility score, shaded light to dark;
  • the last column shows "Lead" or the gap to the topic's leader.

Things to look at:

  • Migration 00137 adds insights_topic_competitors_daily: brand and competitor Visibility components per topic, from the prompt-grain rollups, security invoker. It needs no new backfill.
  • Scores use your answers in the topic as the denominator, as the leaderboard scores competitors.
  • The columns follow the trend's pins (feat(insights): pin competitors and mark prompt and action days on the trend #1043), so the chart and the map compare the same brands.
  • "Send biggest gap to Actions" isn't here yet. It needs a server route and a new user-sent Compete action kind, so it comes as the next PR on top of this one.

Code review (4 of 6 findings fixed, the rest noted in the description), yarn test (620/620), lint, typecheck and build pass. I checked it in the browser at 1440px and 1024px, in light and dark mode.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 14, 2026
The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cihan-gyk and others added 14 commits October 15, 2026 19:53
…i-cards

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
…bers

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
00147 (ansvisor#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nto feature/insights-kpi-cards

# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
…i-cards

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking-visibility-parity.test.ts
#	web/src/lib/actions/tracking.ts
#	web/src/lib/insights-same-prompts.test.ts
#	web/src/lib/insights-same-prompts.ts
#	web/src/types/supabase.ts
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
cihan-gyk and others added 25 commits October 16, 2026 01:20
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
…mmary-line

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking.ts
#	web/src/types/supabase.ts
…aderboard

# Conflicts:
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/insights-summary.test.ts
#	web/src/lib/insights-summary.ts
…to feature/insights-trend

# Conflicts:
#	supabase/schema.sql
# Conflicts:
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
…ture/insights-topic-heatmap

Brings in main with ansvisor#1042, squash-merged after this branch took its earlier
head. Resolved: en.json, insights/page.tsx, tracking.ts and the generated
supabase types keep both ansvisor#1042's Why-it-changed and this branch's Topics vs
competitors; schema.sql rebuilt.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the heat map reads well. One blocker, measured on production as a signed-in member of the largest brand over 30 days, with the body planned the way a SQL function is:

insights_topic_competitors_daily takes 13.5 s against the 8 s limit. As with #1036 and #1042, the SQL function is planned without its arguments, so the day range is a guess. The competitor rows (212k) are joined to the topic prompts (611) with a nested loop that discards 129M rows. Planned with the real arguments, the same body takes 1.3 s. 00137 isn't applied anywhere yet, so it can change in place: plpgsql with plan_cache_mode = force_custom_plan and work_mem, as in 00147/00148, with the explicit membership check if it becomes security definer. While there, the per-topic competitor subquery rescans all ~198k competitor rows once per topic (14 times here); grouping them once by topic and competitor avoids that.

The call sits in loadWindowedInsights's Promise.all, so until then big brands wait for the timeout before the map is hidden.

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk thanks, fixed in bed019b. insights_topic_competitors_daily is now plpgsql with plan_cache_mode = force_custom_plan and work_mem = 64MB, and security definer with the explicit organization check (service role, or a member of the brand's org; anyone else gets null, which hides the map), as 00147/00148 do. Each topic's competitors are folded once by topic and competitor and joined to its row, so the competitor rows aren't rescanned per topic.

One deviation from your suggestion: it's a new migration, 00152_insights_topic_competitors_definer.sql, rather than an edit of 00137, because our contributor rules say never to edit an existing migration file. Happy to fold it into 00137 instead if you'd prefer, since 00137 isn't applied anywhere.

Checked on my dev database inside a rolled-back transaction: the new function returns exactly the old output (topics and competitor entries compared after sorting), a member gets the data, and a non-member and an anonymous call get null. I couldn't measure the production timing locally; the plan change is the same as #1036/#1042's. parseTopicCompetitors(null) has a test now. Web 725/725 and the schema check pass.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the blocker is fixed, and a new migration is fine. I timed the 00152 body on production, planned with its arguments as force_custom_plan does, on the largest brand:

  • 30 days: 0.36 s (was 13.5 s).
  • 90 days: 0.66 s.
  • All time: 1.08 s.

The competitors are folded once, 229 topic and competitor groups, and every join is now a hash join. The membership check returns null for a non-member, and anon loses execute.

Against main the diff is only this PR (00137, 00152 and the heat map). On the merged tree schema.sql matches build-schema.sh and web tests pass (725). CI is green.

@gkhngyk
gkhngyk merged commit 1560599 into ansvisor:main Oct 16, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants