Skip to content

feat(insights): send opportunities to the Action Center and suggest content - #1047

Merged
gkhngyk merged 85 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-opportunity-actions
Oct 16, 2026
Merged

gkhngyk merged 85 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-opportunity-actions

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Stacked on #1046 (VIS-011 part 1) → #1045 → #1044 → #1043 → #1042 → #1041 → #1039 → #1038 → #1037 → #1036 → #1035. Until those merge, this PR also shows their commits. This part is the last commit, 89e48ce.

Summary

The second part of VIS-011 in the Visibility spec v2: the Opportunities card's second buttons, beside Track. They are outline buttons, as in the mockup. The spec's lines:

Topic items: "23 prompts · ~186k/mo · leader 44.0", buttons Track 23 and Send action.
Prompt items: "~38.4k/mo · not tracked", buttons Track and Suggest content.
Suggest content uses the Content quota (CONTENT-001).

Send action (topic items)

It opens a Growth action for the topic: its suggested prompts and the monthly AI demand behind them.

  • Plan: chosen from the action library by how far the brand already is in the topic (a product decision):
    • G16 Create Content for Topic Gaps when none of the brand's prompts track the topic: identify the content need, brief, draft, internal links, publish, validate, measure.
    • G05 Expand Topic Visibility when some do: map the prompts to content, find the gaps, optimize or brief and draft, publish, validate, measure.
    • The tasks come straight from the library definitions, not a copy.
  • The server decides, not the page. POST /api/topics/:id/opportunity-action takes suggestionIds (1–25, z.guid()). It then:
    1. checks the topic (404) and the caller's org (assertBrandAccess, 403);
    2. reads the suggestions again: the brand's, in this topic, relevant (≥ 0.6), and open or tracked from the card, never dismissed;
    3. answers 409 when none is left.
  • One open action per topic (dedup_key = topic_opportunity:<topic>). A second send answers "Already in the Action Center as AC-n".
  • The action: a new person-sent kind, topic_opportunity.
    • Title: "Capture ~92k/mo of AI demand in GEO tools for agencies".
    • Impact: high from 50k/mo, medium from 10k.
    • KPIs: ai_visibility and share_of_voice.
    • Payload: the suggestions with their volumes, the demand, the plan, and the topic's tracked prompts.
    • Trend marker: its "created" event carries the sender, so it shows as an A marker on the trend (feat(insights): pin competitors and mark prompt and action days on the trend #1043).
  • Drawer: a section with the source, the topic link, the plan in a sentence, and the suggested prompts with their volumes. The Signals tab explains that there are none.
  • Measurement: validate.js measures it on the topic's prompts. A topic that had none when sent takes the prompts it has later (basketScope). Such a topic has no answers before the action, so its outcome reads "not measurable" until a later action has a baseline. That's honest, and noted below.
  • After Track: Track takes the topic off the card, so the "Now tracking N prompts" toast offers Send action for what it just tracked.

Suggest content (prompt items)

It runs the existing "+ New" generation (CONTENT-003) for the prompt's topic, steered by the prompt's text, for one suggestion under the Content quota (CONTENT-001). The flow matches the Prompts table's Suggest content:

  • "Writing a content suggestion…" while the job runs, then Open on the new suggestion;
  • "Couldn't write a new suggestion for this topic yet" when every cluster of the topic is already covered or has no answers, and then nothing is used from the quota;
  • a clear message on failure, a spent quota, or a job still running after 3 minutes.

Disabled, with the reason on hover:

  • The prompt's topic isn't tracked: content is written from the answers of the topic's tracked prompts, so there's nothing to write from. This was a product decision.
  • The month's content suggestions are used: "Monthly content limit reached · resets Nov 12". The count includes what this page has written since it loaded.

The quota is read with the card's data, only when there are suggestions.

Review

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

  • tracking a topic first made Send action impossible (the server now also takes suggestions tracked from the card, and the Track toast offers Send action);
  • a branch for an "existing suggestion" the server never returns for a topic request;
  • the buttons' rules were untested (now secondaryBlock and contentLeft in insights-opportunities.ts, with tests);
  • the content quota was read on every load;
  • the hint mentioned a monthly quota on unlimited plans.

Left as notes:

  • G16 measurement: a topic sent before any of its prompts was tracked has no "before" answers, so its outcome reads "not measurable".
  • Topic with no answers yet: Suggest content stays enabled for a tracked topic whose prompts have no answers yet. The run ends in "Couldn't write a new suggestion… nothing was used". A stricter check would depend on the page's date range, not the generator's window.

Related issue

None. Product spec: Visibility spec v2, task VIS-011 (part 2). Depends on #1046 and the PRs under it.

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. Refresh suggestions on Prompts › Suggestions, then open Insights. Every Opportunities item has Track and an outline button.
  2. Send action on a topic item:
    • a toast shows "AC-n sent to the Action Center", and Open goes to the action;
    • the action is titled "Capture ~…/mo of AI demand in …";
    • its drawer shows the topic, the plan and the suggested prompts;
    • its tasks are G16's for a topic you don't track, G05's for one you do.
  3. Click Send action again: "Already in the Action Center as AC-n".
  4. Click Track N on another topic item, then Send action in its toast. The action opens with G05's plan.
  5. Suggest content:
    • on a prompt item whose topic you track, it writes a content suggestion, and Open goes to Content;
    • on one whose topic you don't track, it's disabled and says why.
  6. With the month's content suggestions used (a Starter org at 10), Suggest content is disabled and shows the reset date.
  7. Check light and dark mode, at 1440px and 1024px.

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:

  • web: yarn test 650/650 and yarn build pass. New tests:
    • insights-opportunities.test.ts: which button is off and why, and the content quota left;
    • display.test.ts: the new kind's title, and no signals chip.
  • server: npm run format, npm run lint and npm test (1228/1228) pass. New tests:
    • from-topic-opportunity.test.js: the G16/G05 choice and tasks, the payload and demand, the relevance filter, the open action, a race, no suggestions left;
    • topics-opportunity-action.test.js: the route's validation, 404, 403 and passthrough;
    • basket-metrics.test.js: the topic fallback.
  • npm run version:check: passed. No migration.
  • In the browser, with temporary demo suggestions (since removed):
    • Send action on an untracked topic (G16, 9 tasks) and on a tracked one (G05, 8 tasks), plus the duplicate send;
    • Track 3 then Send action from its toast (G05);
    • the drawer;
    • Suggest content disabled on an untracked topic, and the "nothing new to write" path on a tracked one;
    • light and dark mode, at 1440px and 1024px.
    • The dev server has no model key, so a successful content generation wasn't run live; that path is the Prompts table's existing one.

🤖 Generated with Claude Code

cihan-gyk and others added 12 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]>
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]>
The v2 mockup's "Send biggest gap to Actions" (VIS-010, part 2): the heat
map's button opens a Compete action for the topic you trail by the most,
against the competitor leading it. The server measures the gap again from
the rollups (00137) rather than trusting the page, refuses a topic it
doesn't see a gap in or with fewer than 20 answers, and keeps one open gap
action per topic. The action carries C04's (close_topic_coverage_gap) task
plan and a person's "created" event, and is measured on the topic's
prompts once completed, like an opportunity sent from Content.

- server: POST /api/topics/:id/gap-action and from-topic-gap.js, with
  route and action tests; validate.js measures the new kind on its basket.
- Action Center: the person-sent kind topic_competitor_gap, titled "Close
  the 26.5-pt gap with Peec AI in AI Rank Tracker", without a "0 signals"
  chip, and a drawer section with the topic and the scores when sent.
- Insights: the button, disabled with a reason when no competitor leads,
  a toast with the AC number and a link, and a plain message when the gap
  has closed since the page loaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Insights' Recommendations row becomes the v2 mockup's Opportunities card,
under the topic heat map: stored prompt suggestions grouped by topic,
ranked by relevance x demand x gap, those under 0.6 relevance hidden, with
Track (one prompt) and Track N (a topic's prompts) within the plan's prompt
locations.

The suggestion refresh rates each suggestion's relevance in the same model
call. What that adds is capped at 0.1% of the plan price a month, reserved
atomically per organization before a refresh rates (migration 00138).

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

The Opportunities card's second buttons, as in the v2 mockup. A topic
item's Send action opens a Growth action for its suggested prompts and
their demand, on the library's G16 plan when none of the brand's prompts
track the topic and G05 when some do; one open action per topic, measured
on the topic's prompts. A prompt item's Suggest content runs "+ New" for
its topic, steered by the prompt, under the Content quota; it's disabled
for an untracked topic or a spent quota.

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 second part of VIS-011 from the Visibility spec v2, stacked on #1046 (the Opportunities card) and the PRs under it. Until those merge, this part is the last commit.

It adds the card's outline buttons from the mockup: Send action on topic items and Suggest content on prompt items.

Things to look at:

  • Send action opens a new person-sent kind topic_opportunity (Growth).
    • Its plan comes from the action library by how far the brand is in the topic: G16 when none of its prompts track it, G05 when some do. This was a product decision.
    • The tasks are read from the definitions, not copied.
    • One open action per topic; the "created" event carries the sender.
  • New route POST /api/topics/:id/opportunity-action. It re-reads the suggestions on the server: the brand's, in the topic, relevant, and open or tracked from the card. It refuses with 409 when none is left.
  • Measurement: basketScope now falls back to the topic's current prompts when the action was sent with none. Such a G16 action has no "before" answers, so it reads "not measurable"; this is noted in the description.
  • Suggest content reuses "+ New" (CONTENT-003) for the prompt's topic, with the prompt as the idea, under the Content quota.
    • It's disabled for an untracked topic, since there are no answers to write from, and when the month's quota is spent.
    • The flow matches the Prompts table's Suggest content.
  • Not tested live: my dev server has no model key, so a successful generation wasn't run live. Send action (G16 and G05), Track → Send action, the drawer, and Suggest content's disabled and "nothing new" paths were checked in the browser with temporary demo data.

Code review: 5 of 7 findings fixed; the two left are noted in the description. Web tests (650/650), server tests (1228/1228), lint, typecheck and build pass. No migration.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 14, 2026
…i-cards

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
…pic-gap-action

# Conflicts:
#	web/src/components/action-center/action-drawer.tsx
…pportunity-actions

# Conflicts:
#	web/src/components/action-center/action-drawer.tsx
cihan-gyk and others added 27 commits October 16, 2026 11:32
…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.
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]>
…portunity-actions

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking.ts
#	web/src/lib/insights-topics.test.ts
#	web/src/lib/insights-topics.ts
…portunity-actions

# Conflicts:
#	server/src/lib/action-center/validate.js
#	server/src/routes/topics.js
#	web/messages/en.json
#	web/src/components/action-center/action-drawer.tsx
#	web/src/lib/action-center/display.test.ts
#	web/src/lib/action-center/display.ts
#	web/src/lib/action-center/registry.ts
#	web/src/lib/actions/topic.ts
…portunity-actions

# Conflicts:
#	server/src/lib/suggestion-relevance.js
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/_opportunities.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking.ts
#	web/src/lib/insights-opportunities.test.ts
#	web/src/lib/insights-opportunities.ts
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 16, 2026

@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, approving. Against main the diff is only this PR. On this head schema.sql matches build-schema.sh, server tests pass (1246), web tests pass (754) and CI is green. No migration and no new RPC.

The server rereads the suggestions, and keeps one open action per topic. Its active statuses match the actions_active_dedup_idx predicate, so the race path finds the winner.

Minor, for a follow-up if you agree:

  • getContentUsage now sits on the Insights load path without a timeout, unlike getPromptSuggestions (15 s). It runs only after the suggestions answer, so the risk is small.
  • basketScope's topic fallback takes inactive prompts too, while the send counts only active ones.

@gkhngyk
gkhngyk merged commit fda6d5e 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants