Skip to content

feat(traffic): connect AI bots from Cloudflare or Vercel in the sources strip - #1181

Merged
gkhngyk merged 38 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-bot-connect
Oct 19, 2026
Merged

gkhngyk merged 38 commits into
ansvisor:mainfrom
cihan-gyk:feature/traffic-bot-connect

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

AI Traffic Analytics, spec AT-010 part C (§6.1, §6.4, §7): the AI bots card in the sources strip. It opens a dialog to connect the brand's own Cloudflare Worker, Logpush job or Vercel drain. Before connecting, the dialog says what each way costs on the customer's own bill. After connecting, it shows the settings to copy, with the secret in them once.

Stacked on #1180 (→ #1179 → … → #1176). This PR's own change is the last commit, bafb79e7. Web only; it uses the routes from parts A and B. The bot report itself is AT-011.

Why

  • Spec §6.4: "The connect dialog says this plainly before the user connects", meaning the Cloudflare Workers, Logpush and Vercel Drains costs on the customer's side.
  • Spec §7: "AI bot report: Starter Locked (sample data + Upgrade); Growth ✓ (2M events/month); Enterprise ✓ (20M, adjustable)."
  • AT-001's strip has said "Cloudflare / Vercel · coming soon" until now.

What changes

  • The AI bots card (BotsSource in _bots-connect.tsx) reads GET /api/bots/connections/:brandId and shows one of four states:
    • Locked (a plan with maxBotEventsPerMonth 0, i.e. Starter): "Cloudflare / Vercel · Growth+" with Upgrade, which links to /dashboard/settings?tab=billing like the Prompts page's usage cards.
    • Not connected: "Cloudflare / Vercel · see which AI bots read your pages" with Connect. It is disabled, with a tooltip, for people who aren't admins or managers.
    • Waiting (amber): "Connected · waiting for the first AI-bot request" with Manage.
    • Active (green): "Cloudflare / Vercel · last event 5m ago" with Manage.
  • The dialog (BotsDialog):
    • Choosing a way: three options (Cloudflare Worker, Recommended; Cloudflare Logpush; Vercel Drain). Each says what it does and what it costs on the customer's own bill (§6.4):
      • Workers: free up to 100k requests a day, then $5/month for 10M and $0.30 per extra million. Busy sites may need the paid plan.
      • Logpush: on all plans, with no per-request cost; dataset availability depends on the account.
      • Vercel Drains: Pro and Enterprise only, at $0.50/GB.
    • After Create connection: a warning that the secret isn't shown again, then numbered steps and copy blocks for that way:
      • the Worker code;
      • the Logpush destination plus the job settings for the API;
      • the drain's endpoint, custom header, format and sources.
    • Manage:
      • The connections, with their last request.
      • A two-step Revoke.
      • This month's use ("12,400 of 2,000,000 detailed rows"), with "Detailed rows paused until Nov 1, totals still counted." once the cap is reached (§6.3).
    • Layout: content can't widen the dialog, so long code scrolls inside its own box. The same cause sits behind the overflowing snippet-code dialog, which is a separate task.
  • lib/actions/ai-bots.ts: server actions getBotConnections, createBotConnection and revokeBotConnection. They call the API with the member's session and return errors rather than throwing them.
  • lib/ai-bots.ts: the card state (locked | off | waiting | on), the newest request, and the day detailed rows start again.
  • SourceCard moves to _source-card.tsx so the strip and the bots card share it. SourcesStrip takes brandId.

Related issue

None. Spec AT-010 (AI Traffic Analytics plan, approved by product).

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. With parts A and B deployed, open AI Traffic Analytics as an admin on a Growth (or self-hosted) org. The AI bots card offers Connect.
  2. Connect: each way states its cost on your bill. Pick one and Create connection. The settings appear once, with the secret, plus steps for Cloudflare or Vercel.
  3. Done: the card waits for the first request, then shows the last one. Manage lists the connection and this month's use; Revoke asks once more, then removes it.
  4. On a Starter org, the card shows "Growth+" with Upgrade.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no errors; 6 warnings, all in files this PR does not 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 (1680) and yarn build pass. No server change.
  • Tests:
    • _bots-connect.test.tsx:
      • Upgrade on a locked plan.
      • The costs shown before connecting.
      • The Vercel and Logpush settings shown once; no untranslated keys.
      • Manage, with use and the "paused until" line, and Revoke.
      • The waiting state, and members kept from connecting.
    • ai-bots.test.ts: the card states, newest request and pause date.
    • actions/ai-bots.test.ts: API calls and mapping, the plan limit, revoke, and a missing session.
    • _sources-strip.test.tsx: updated for the card.
  • Browser (local server and web against the dev database):
    • Created a Worker and a Logpush connection, saw their settings, saw "waiting" and then "last event just now" after a verified event, and revoked both.
    • Starter: with IS_CLOUD=true and the demo org temporarily on Starter, the card showed Growth+ and Upgrade. The plan and its update time were restored.
    • Checked light and dark and a narrow screen; measured 1440 px (one row of four) and 1024 px (two by two) with no overflow.
    • The test rows were removed afterwards.

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits October 19, 2026 11:35
…l Trend card

AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab.
It draws AI visits and Google organic clicks, each indexed to 100 on its
first day with data, with markers on the days actions entered the Action
Center or prompts were added.

- 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the
  first and latest day it has rows for the brand, and the markers.
  Security invoker; RLS decides the brand.
- The Google line is blank (not 0) before Search Console's history and
  after Google's latest reported day, which the view names.
- A range that starts mid-day leaves out its partial first day so it
  doesn't set a misleading 100.
- The 24-hour range offers "Show last 7 days" (Google reports by day).
- Without Search Console the view keeps the AI line and says what the
  Google line needs (§3.8b). The view shows the "Needs Google Search
  Console" tag.

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

AT-008 part B (spec §3.6): a Google Search Console section with "Is AI
taking Google clicks?" — pages whose impressions rose 15% or more while
their CTR fell 20% or more against the period before, most clicks lost
first. Each row's next step is the Positions panel of a tracked prompt
about the page, or Add prompts when there is none.

- 00181: gsc_page_stats (Search Console by page and day, member select
  policy) and ai_traffic_google_pages. The window keeps the range's
  length and ends on Google's latest reported day (§3.01). Pages need 100
  impressions in the period before. When the page history doesn't reach
  back to that period, it says so rather than reading every page as
  rising. Security definer with an organization check (citations).
- Server: the daily GSC sync also pulls pages. A brand's first page sync
  reads 190 days in 28-day steps, later ones the last 28, and the prune
  keeps 190 days. A failed page step leaves the query rows synced.
- Web: the section with its connection states (§3.8b), the "Needed for"
  list, and the export sheet "Is AI taking Google clicks".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd Track all

AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the
top Search Console queries by clicks that no tracked prompt covers. Track
adds a query as a prompt; Track all adds the listed ones within the plan's
prompt slots (PROMPT-012). The summary line states their number while
Search Console is connected (§3.1, §3.8b rule 5).

- 00182 ai_traffic_google_queries: queries with clicks between two days,
  most clicks first, ending on Google's latest reported day (§3.01).
- Server: GET /api/prompts/untracked-queries/:brandId drops the queries
  an active prompt covers, by the rule Prompt Suggestions uses for Google
  queries, so the two pages agree. Prompts are tokenized once and read
  past the 1,000-row page.
- Web: UntrackedQueriesCard, the summary line's count (counted again after
  tracking), the export sheet "Untracked Google queries" and the "Needed
  for" list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…within a monthly cap

AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report.

- 00183: ai_bot_connections (one secret per sender, stored as its
  SHA-256, hidden from members), ai_bot_events (verified rows, 90 days),
  ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization
  and month) and ai_bot_ingest, which stores rows while the month has room
  and always adds counters, locking the usage row so concurrent batches
  can't pass the cap. Pages are keyed like the Pages section's.
- ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers,
  search crawlers and user fetchers. A request counts only when its user
  agent names one and its IP is in the operator's published ranges, read
  daily. No IP is kept.
- POST /bots/ingest (public, by connection secret) and
  /api/bots/connections/:brandId (list with this month's use, create with
  the secret shown once and the Cloudflare Worker, revoke). Admins and
  managers only; Starter has the report locked.
- Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable),
  Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once
  a month; past the cap only counters are written.
- The daily run prunes rows past their retention.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bot requests, within a raw cap

AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the
body by the connection's kind.

- Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any
  timestamp format); the job's test upload reads as no requests.
- Vercel drain: a JSON array or NDJSON of log entries; only those with a
  proxy object are requests, build and function output is skipped.
- 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log
  sender's batch under the usage row's lock. Batches are read while the
  month is under the plan's raw cap (Growth 20M, Enterprise 200M), only
  counted after. Verified events from a whole file are written in chunks
  of 500.
- Creating a Logpush or Vercel connection returns what to copy: a Logpush
  job filtered at the edge to the bot list with the secret as a header,
  or a drain's endpoint, header and format.
- The sender body is read raw before the app's JSON and form parsers.

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

AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card
opens a dialog to connect the brand's own Cloudflare Worker, Logpush job
or Vercel drain.

- The card is locked with Upgrade on a plan without the bot report
  (Starter), offers Connect, then waits for the first request, then shows
  the last one; Manage opens the same dialog.
- The dialog says what each way costs on the customer's own Cloudflare or
  Vercel bill before connecting. After it, it shows the settings to copy
  (the Worker, a Logpush job, or a drain's endpoint and header), with the
  secret in them once. It lists connections with their last request,
  revokes one in two steps, and shows the month's use and when the cap
  paused detailed rows.
- Server actions in lib/actions/ai-bots.ts and card state helpers in
  lib/ai-bots.ts. SourceCard moves to its own file.
- The dialog's content can't widen past it: long code scrolls inside its
  box.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk AT-010 part C is stacked on #1180 → #1179 → #1178 → #1177 → #1176, so please merge those first. This PR's own change is the last commit, bafb79e7. It is web only: no migration and no server change.

With A–C deployed, the Cloudflare and Vercel checks I asked for on #1179 and #1180 can start from this dialog: AI Traffic › sources strip › AI bots › Connect.

cihan-gyk and others added 5 commits October 19, 2026 16:13
main now has ansvisor#1176 (squash a98c35c, identical to this branch's 27f2ad2)
and ansvisor#1193. The conflicts are the files ansvisor#1177 extends after ansvisor#1176: this
branch's side kept; schema.sql rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…raffic-untracked-queries

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-google-pages, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ure/traffic-bot-ingest

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-untracked-queries, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ffic-bot-logs

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-bot-ingest, which carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ic-bot-connect

main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193;
merged through feature/traffic-bot-logs, which carries it.

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

@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.

No blockers of its own. It shows the endpoint from #1179, so it follows that fix.

One note: the raw cap (raw_capped_at from 00184) is never returned or shown. Past it nothing is read and no counters are added, but the only note in the dialog covers the event cap ("totals still counted"). Returning raw_records, raw_capped_at and the cap, with a note in the dialog, would explain a report that stops mid-month.

cihan-gyk and others added 7 commits October 19, 2026 18:49
…ap its counters

Review of ansvisor#1179:
- The endpoint written into a Worker, Logpush job or drain came from the
  request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on
  localhost outside production), and no connection is made without it.
- ai_bot_daily grew by about a row an event past the month's cap. Hits past
  it now go on one '(other)' row per bot and day, and /bots/ingest has a
  per-connection limit (600 a minute, keyed by the secret's hash).
- Also: the Worker passes requests through on its own errors and sends the
  page without its query string, and ingest errors go to the app logger.

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

Review of ansvisor#1177:
- ai_traffic_google_pages spent its time on normalize_page_path, twice a
  row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores
  page_key as a generated column and the function groups by it; only the
  ranked rows work out their display path. Plus an index on date for the
  table-wide prune.
- A first page sync cut short left 28 days of history for months. The sync
  now reads the 190 days until one gets through them all for the property
  (brands.gsc_pages_backfilled_property), and drops the old property's
  pages when it changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of ansvisor#1180:
- gunzipSync on up to 64 MB and a synchronous parse could hold up the API.
  Files are now inflated asynchronously to at most 16 MB, hold at most
  20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the
  Logpush job we suggest sends at most 10,000 records a file.
- A file retried after a timeout was counted twice. Each connection's
  files are claimed by the SHA-256 of their body (ai_bot_ingested_files,
  kept 7 days) and a resent one is answered without reading it; a read that
  fails gives its claim back.
- Also: a line with an unreadable time is dropped, not the whole file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	server/src/lib/bot-ingest.test.js
#	server/src/routes/bot-ingest.js
#	server/src/routes/bots.js
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk This one only has the fixes below it merged forward (f4de782); the endpoint now comes from #1179's PUBLIC_SERVER_URL. The raw-cap note (returning raw_records / raw_capped_at / the cap and explaining it in the dialog) goes into a follow-up.

cihan-gyk and others added 5 commits October 19, 2026 20:55
The fallback prompt for a page in "Is AI taking Google clicks?" counted every citation of the page over 90 days, which read every answer that cited it (35,798 on the largest brand, 15 s cold, past the 8 s timeout). It now reads the page's latest citation and that one answer, at most one each per ranked page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cihan-gyk and others added 15 commits October 19, 2026 22:48
Ordering a page's citations by created_at still read every one of them from the heap, since the (url_id, brand_id) index has no created_at: 35,700 rows and 7.5 s cold on the largest brand's 50 pages. The lateral now stops at the first citation in 90 days whose prompt is active (2 s there, gkhngyk's measure), which also skips a paused prompt instead of leaving the page without one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 19, 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.

Tests pass on main with the whole stack, and the connection secret stays out of the member grant on prod. The raw-cap note stays as a follow-up.

@gkhngyk
gkhngyk merged commit c3c1dae into ansvisor:main Oct 19, 2026
5 checks passed
gkhngyk pushed a commit that referenced this pull request Oct 20, 2026
… the bot report stops (#1224)

* feat(traffic): show log senders' records against the raw cap, and why the bot report stops

A Logpush job's or a Vercel drain's files count against the month's raw
cap (00184). Past it they are counted but not read, so no rows and no
totals are added and the bot report stops mid-month, but nothing said so:
the only note covered the event cap ("totals still counted").

GET /api/bots/connections now returns the month's raw records, when the
raw cap was reached, and the cap. For a brand with a log sender, the
connect dialog shows "Log records this month: X of Y" and, once the cap is
reached, that log files are paused until the next month; the report
section shows the same note under the bot types. A Worker's batches don't
count against the raw cap, so a Worker-only brand sees neither.

Follow-up to #1181's review.

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

* fix(traffic): read the log-file pause against today's plan

The pause note keyed on rawCappedAt, which 00184 sets once a month and
never clears. The server reads files while raw < cap with today's plan,
so an upgraded org kept seeing "paused until" after its files were read
again, and a downgraded one over its new cap saw no note. Read it as
the server does, and say the files aren't read (they're still counted).

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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