Skip to content

fix(prompts): Tracked Prompts loads in one read, volumes beside it and never missing on first load - #2483

Merged
gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/prompts-tracked-load
Nov 17, 2026
Merged

gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/prompts-tracked-load

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Tracked Prompts: one read before the table, and volumes that don't go missing on first load

This PR fixes two problems on the Prompts page:

Problem 3 shares its code path with Problem 1 (loadData → getPromptsPageData), so both are fixed here. (Problem 2, the Suggestions jump, and the summary line's wording and spacing are separate PRs.)

Causes, by impact

  1. The table's read waited at the back of Next's server-action queue. Next runs client-called server actions one at a time. React runs child effects before parent effects, so on mount the queue was:

    • the menu's actions (layout): markSeen('prompts/tracked'), getMenuState (dots), getSettingsState (managers), and markGettingStartedPageOpened until it's recorded;
    • AllPromptsTab's getPromptTableViews, then getContentUsage (an API call with no timeout);
    • useFirstRun's getTrackingWindow;
    • only then PromptsPage's getPromptsPageData, the table itself;
    • and behind it, getBrandFilterOptions and getVolumeAnalysisStatus.

    That's 4 page-level sequential round trips before the table's data (6–8 counting the menu's). The landing page (feat(nav): analytics before execution; everyone lands on Prompts › Tracked Prompts #2475) makes this the first thing everyone waits for. On a fresh purchase the home URL carries ?jobId=, and TrackingJobHandoff then calls replaceState while those actions are in flight. That's the Next 16 queue stall the page's own comments describe.

  2. feat(prompts): manage prompts in one place, on the Prompts page #2473 added a read for Track now (_track-now.tsx useTrackNow → lib/track-now.ts readPromptsWithoutAnswers). It's a browser fetch to the API's GET /api/tracking/unanalyzed/:brandId on every manager's load whenever any active prompt had no answers in the window, which with the 24h default is almost always. That route reads the prompt_results rows of all active prompts (.in('prompt_id', 227 ids)) and PostgREST's 1,000-row cap cuts the list. So on a busy brand the count was also wrong, and the line appeared late in the status line.

  3. feat(prompts): show a tracked Improve action under the Work chip #2471 added one more server action per page of rows (_improving-link.tsx useImprovingPrompts → getImprovingPrompts). It fired after the rows, and again on every page, sort or filter that changed the rows on screen. When it landed, "AC-12 · Improving" appeared under the Work chip and made those rows taller.

  4. Problem 3: the volumes had no second chance, and their absence read as "not analyzed". The volumes came inside getPromptsPageData (getPromptVolumes → the API's GET /api/volumes/brand/:id, with a 15 s AbortSignal.timeout). When that call failed or timed out, the action degraded to volumes: [] (volumesDegraded). Then:

    • unanalyzedCount counted every active prompt (227);
    • every Volume and Competition cell read "—";
    • Insights (same loadData, tab === 'insights') showed "No volume data yet".

    Nothing read the volumes again until something reloaded the page data: a range change, or the volume-run watch reloading when a run finished, which is the "filled in by itself after a while". It is the first attempt failing, not just waiting. While the read is pending, loading is true and Insights shows its spinner and Tracked its skeleton. The empty state and the "227" need a finished read with no volumes. Waiting behind the queue (cause 1) made that read start late. Pages that loaded the volumes first (?range and the other tabs) also re-read them on every range change, although volumes have no date.

  5. getBrandFilterOptions (insights_filter_options) scans the brand's whole prompt_results history twice (DISTINCT region, DISTINCT model). It never blocked the table, but it was in the same queue. It's unchanged here; see the follow-ups.

The home redirect (/dashboard → readMyHome() → redirect) adds no round trip on the critical path. Next renders the /dashboard page segment alongside the dashboard layout: each segment's RSC has its own slot, see create-component-tree. readMyHome's three reads (auth getUser, profiles, organization_menu_roles for non-admins) are a subset of what the layout already reads in parallel. The hop itself existed before #2475, when it redirected to Action Center › Today. No change.

What changed

  • The table's read is a fetch, not a server action: POST /api/prompts/read (app/api/prompts/read/route.ts, client in lib/prompts-reads.ts). It follows the existing /api/visibility/read and /api/prompts/usage pattern: the member's session, RLS and the functions' brand checks, input validated with zod, and one log line per read with its duration.

  • getPromptsPageData brings everything the first view shows in its one Promise.all. Each extra degrades on its own:

    • the rows, visibility and positions, as before;
    • the Improve actions for every prompt of the brand (readBrandImprovingActions: one query, scoped to the brand, the same rule);
    • on first, the column views (getPromptTableViews), so the table opens on its own columns;
    • with withoutAnswers (managers), the active prompts with no answers yet. readUnansweredPromptIds (lib/prompts-without-answers.ts) joins each active prompt to at most one of its answers (prompt_results(id) with limit 1, by the prompt_id index, scoped to the brand). That's one index probe per prompt, never the result rows, and there's no 1,000-row cap on the answer;
    • volumes: false leaves the volumes out (other callers keep them).
  • The volumes are their own fetch, beside the rows (POST /api/prompts/read volumes). It returns the volumes and quota, plus getVolumeAnalysisStatus for "Analyzing…" on arrival, so that's no longer a server action either. The rows never wait for the volumes API. A failed read is tried once more at once. A range or location change doesn't read the volumes again. An older read landing after a newer one is dropped: there's a sequence guard on both reads, needed now that fetches run side by side.

  • While the volumes are pending:

    • Volume and Competition show a small skeleton in their cells;
    • the "not analyzed" line is not shown;
    • Insights shows a skeleton of its cards and chart, never "No volume data yet";
    • the CSV export waits;
    • a table sorted by volume waits rather than reordering.

    If both tries fail, Insights says "Volume data couldn't be loaded." with Retry, the existing warning toast shows, and the line stays hidden.

  • Track now takes its ids from the table's read. The /unanalyzed fetch and readPromptsWithoutAnswers are removed.

  • Improve links come with the rows (useImprovingPrompts gets them as seed). getImprovingPrompts now runs only when the positions panel closes, for the rows on screen, so an Improve sent from the panel shows.

  • getContentUsage (row menu and bulk bar quota) is read once the rows are in, not before them.

  • The Location filter reads the brand's locations through /api/visibility/read (filterOptions, as Visibility does), a fetch beside the table. While they're unread, a brand whose prompts track more than one location gets a placeholder of the filter's size, so the filter row doesn't shift.

No migration, no new dependency, no new write action. 'use server' files still export async functions only. The new constants and helpers live in plain modules.

Before / after: first view of Tracked Prompts (manager, brand with prompts lacking answers in 24h)

Before After
Page server actions dispatched before the table's data 3 (getPromptTableViews, getContentUsage, getTrackingWindow), then getPromptsPageData itself 0
Sequential round trips before the table's data (page-level) 4 (+ 2–4 menu actions ahead of them) 1 fetch, not queued
Requests on the table's critical path that go to the API (Express) 1 (/api/volumes/brand, 15 s timeout) 0
Reads per page of rows (Improve links) 1 server action per page, sort or filter 0 (one brand-wide query inside the table read)
Track now read 1 API fetch reading every active prompt's prompt_results rows (capped at 1,000) 0 extra: ≤ 1 index probe per active prompt inside the table read
Server actions on the first view, total 7–8 (+1 per page change): the 4 above, getBrandFilterOptions, getVolumeAnalysisStatus, getImprovingPrompts, and getTrackingCountries when a row shows "Within 24h" 2–3, all after the rows: getTrackingWindow (shared first-run hook), getContentUsage, and getTrackingCountries when a row shows "Within 24h"
A range change 1 server action (rows and volumes via the API) 1 fetch (rows only)
Volumes read failing once "N not analyzed", all "—", Insights "No volume data yet", until a reload retried once; until then cells wait in place and the line and empty state stay hidden

Tests

  • page.test.tsx:
    • first view: with the table's read pending, readPromptsPageData has been called once (first, withoutAnswers, volumes: false) and no server action at all. Once it lands, the table opens on its own columns and still no getImprovingPrompts or getVolumeAnalysisStatus has run;
    • no per-row calls: 30 rows → the rows, volumes and locations reads once each, and 0 server actions;
    • the Location filter keeps its place until the locations are read;
    • volumes on first render: Volume and Competition filled (Competition 42 of 100), "—" only for the prompt without a volume, the "not analyzed" count is the true one (1, not 3), and there's no range change;
    • pending volumes → cells show the skeleton and no "not analyzed" line; once they're in → the true count;
    • a failed volumes read is retried before anything is said, and when both tries fail there's a warning and still no "not analyzed";
    • out of order: a newer rows read keeps its rows when an older one lands after it (and the range change doesn't re-read the volumes), and a newer volumes read isn't overwritten by an older empty one;
    • Insights: the cards show on first render with volumes, a skeleton (not the empty state) while pending, the empty state only after a finished read with no rows, and a failure card with Retry;
    • the Improve link and Track now tests now assert no read of their own.
  • app/api/prompts/read/route.test.ts:
    • the options are passed through, with null turned into undefined;
    • volumes come with their status, and the status failing doesn't fail the volumes;
    • a signed-out caller gets 401;
    • an unknown read, a bad id or an unknown option gets 400;
    • a failed read gets 500 without details.
  • improving-actions.test.ts: the brand-wide read is one query with no prompt list, and another brand's rows are ignored.
  • _improving-link.test.tsx: the seed is shown with no read; a re-read happens only after the panel closes, and merges for the rows on screen; a newer seed wins; a failed re-read keeps the seed.
  • prompt.test.ts (getPromptsPageData): the Improve links come with the rows; the columns and Track now's prompts come only on request, in the same round; volumes: false makes no volumes API call; a failing extra leaves the rows intact.
  • prompts-without-answers.test.ts: one query, the brand's active prompts, limit 1 on prompt_results, no range; it lists the prompts whose probe found nothing.
  • subscription-guard-coverage.test.ts names prompts/read:POST as read-only, like visibility/read.
  • Checks: tsc --noEmit and ESLint on the changed files pass. Vitest passes 475 tests in 39 files: the Prompts page folder, src/app/api/prompts, the touched src/lib/actions tests (prompt, prompt-positions), improving-actions, prompts-without-answers, track-now, src/components/prompts, src/lib/help, src/i18n, use-server-exports and subscription-guard(-coverage). Merged with fix/prompts-summary-line and fix/prompt-suggestions-no-jump, in either order, tsc and the Prompts, AI-usage, Help and guard tests pass too (384 tests).

How to check in production

  1. Open /dashboard with DevTools › Network filtered to Fetch/XHR. Before the table shows, there is one POST /api/prompts/read (pageData) next to volumes, /api/visibility/read and /api/prompts/usage. There's no POST /dashboard/prompts/tracked with a Next-Action header ahead of it, and no GET …/api/tracking/unanalyzed.
  2. In Vercel logs, the line [prompts/read] pageData NNNms is the table's server time, and [prompts/read] volumes NNNms the volumes'. A … (slow) suffix marks one over 2 s.
  3. On the brand from the screenshot (227 tracked, 734 total, 24h), Volume and Competition fill on the first load, and the line counts only the prompts without a volume. /dashboard/prompts/insights opens on a skeleton, then the cards, never "No volume data yet".
  4. Before deploying, the cause of the first-load failures can be confirmed in the Vercel logs with [prompts] volumes fetch failed, rendering without them:. The message says which one: The operation was aborted due to timeout (the 15 s timeout), Server error: 429 (the API's rate limiter), or Not authenticated / 401.

Follow-ups (not in this PR)

  • insights_filter_options scans the brand's whole prompt_results history twice. Check it with EXPLAIN (ANALYZE, BUFFERS) select * from insights_filter_options('<brand>'), or with pg_stat_statements mean_exec_time for it. A rollup (insights_brand_daily's regions) would make it cheap, but the Visibility pages read it too.
  • /dashboard/prompts/similar-topics reads getPromptVolumes on its own and shows "No similar topics found." when that read fails: the same "a failure looks empty" pattern.

Generated by Claude Code

The table's read (getPromptsPageData) was a server action at the back of
Next's queue: the menu's actions, then the page's getPromptTableViews,
getContentUsage and getTrackingWindow went first, four round trips before
the table on everyone's landing page. It now goes through
POST /api/prompts/read, a fetch beside them, and brings the rest of the
first view in its one Promise.all: the column views, the Improve links for
every prompt (one brand-wide query, no read per page of rows), and Track
now's prompts (one index probe per active prompt instead of the API's
/tracking/unanalyzed, which read every active prompt's results and was cut
at 1,000 rows).

The volumes are their own fetch beside the rows, with the volume run's
status, so the table never waits for the volumes API and a range change
doesn't read them again. A failed volumes read is tried once more; until
the volumes are in, their cells wait in place, the not-analyzed line isn't
shown and Insights shows a skeleton, never "No volume data yet". Both
reads drop an answer older than the latest. The Location filter reads its
locations through /api/visibility/read, its place kept meanwhile, and the
content quota is read once the rows are in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9

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

Looks good: same filters as the old /unanalyzed read, RLS-scoped, single-FK embeds. Minor: readBrandImprovingActions now applies MAX_ROWS = 1000 brand-wide, so on a brand with >1000 open Improve actions the oldest prompts lose their 'Improving' link.

@gkhngyk
gkhngyk merged commit 3b4d242 into ansvisor:main Nov 17, 2026
13 checks passed
gkhngyk pushed a commit that referenced this pull request Nov 18, 2026
The page read getPromptVolumes as a server action with try/finally and no
catch: a failed or timed-out read left the volumes empty and showed "No
similar topics found." as if the brand had none. It now reads them as
Tracked Prompts and Insights do (#2483): through /api/prompts/read
(readPromptVolumes), one retry at once, a sequence guard so an older read
never lands over a newer one, a skeleton of the cards and list while
pending, and the same failure card with Retry.

Shared from the Prompts page: the failure card (prompts/_volumes-failed.tsx,
its two strings now in en.json) and VOLUME_READ_RETRIES (lib/prompts-reads.ts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
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.

3 participants