Skip to content

feat(prompts): count only active prompt locations toward the plan limit - #1034

Merged
gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feature/prompt-quota-active-locations
Oct 15, 2026
Merged

gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feature/prompt-quota-active-locations

Conversation

@cihan-gyk

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

Copy link
Copy Markdown
Collaborator

Summary

The plan's prompt limit (maxPrompts, counted in prompt locations since #691) also counted paused prompts. Paused prompts don't run (the tracking worker only picks is_active prompts), so users were paying plan room for prompts that cost nothing.

Now only active prompt locations count. To keep the limit meaningful, resuming a paused prompt is metered like adding it. Otherwise someone could pause prompts, fill their room with new ones, then resume the old ones and end up over the limit. With this PR, that resume is refused with the usual plan-limit message.

What changes:

  • Migration 00128_count_active_prompt_locations.sql: org_prompt_location_usage adds and p.is_active. Same signature, grants and security invoker as 00070. schema.sql is regenerated.
  • setPromptActive(id, isActive) (new server action): the only way a prompt's active state changes after it's created.
  • activationDelta() in prompt-locations.ts: how many locations making prompts active adds. Ready for the bulk resume in feat(prompts): add a bulk action bar for selected prompts #1029.
  • Location edits on a paused prompt cost nothing until it's resumed. This applies to updatePromptLocations and to bulkUpdatePromptLocations / planBulkLocationChange. The resume then meters the full count.
  • savePromptSet counts only the prompts it saves as active.
  • UI
    • The All Prompts toggle, the brand Prompts page toggle and the edit dialog's Active checkbox all use setPromptActive. A refusal shows "Not enough room to resume" with the exact numbers; the edit dialog shows it inline.
    • The brand page refreshes its quota after a pause or resume.
    • A paused prompt's location picker is capped at what it could take back when resumed.
    • The copy now says "active prompt locations" and "paused prompts don't count": the usage meter, its tooltip, the limit-reached banner and the Insights "Tracked Prompts" sub-line.

Scope notes:

  • Brand-level pause (brands.is_active) is unchanged. A paused brand's active prompts still count, which is the conservative side and leaves no way past the limit.
  • Race: the resume check and the write aren't atomic, so two simultaneous resumes at the edge could both pass. The existing add paths (addPromptToSet, updatePromptLocations) have the same check-then-write shape. A locked RPC (like claim_opportunity_usage) could cover all of them in a follow-up.
  • Follow-up for feat(prompts): add a bulk action bar for selected prompts #1029: its bulk pause/resume (setPromptsActive) should use activationDelta for resumes once this merges. I'll do that on whichever PR lands second.

Review

I ran a code review before opening this. It found 10 things and 9 are fixed here:

  • the limit banner still said paused prompts count;
  • the brand page didn't refresh its quota after a toggle;
  • a paused prompt's location cap was too generous;
  • updatePrompt kept a second, throwing activation path;
  • the edit dialog didn't refresh the table after a partial save;
  • the resume check priced a list of ids by the first one's org;
  • setPromptActive had no tests;
  • two doc comments were stale.

The race above is the one left, as a note.

A second review pass found 8 more and 5 are fixed in a follow-up commit:

  • the edit dialog showed the raw database error for non-plan failures;
  • setPromptActive threw (masked in production) when the limit check itself failed;
  • a failed quota refresh on the brand page left the location pickers uncapped;
  • prompt-usage.ts still said paused prompts count;
  • tests were missing for a missing prompt, a failed check, and location edits on paused vs active prompts.

Left as notes:

Related issue

Builds on #691 (location-based prompt quota). No issue for this one: it's a product request to stop paused prompts counting, without opening a way around the limit.

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 the migration (supabase/migrations/00128_count_active_prompt_locations.sql).
  2. Set NEXT_PUBLIC_IS_CLOUD=true in web/.env.local, set the demo org's plan to starter (50 locations), and restart the web dev server.
  3. Go to Prompts → All prompts and note the meter, e.g. "78 / 50 active prompt locations".
  4. Pause a prompt with 3 locations: the meter drops by 3.
  5. Resume it: it's refused with "Not enough room to resume", e.g. "This change would use 78 (75 in place + 3 added). Remove or pause 28 locations…". The prompt stays paused.
  6. Open the prompt's edit dialog, tick Active and save: the same message shows inline, and nothing else is saved.
  7. Switch the org to growth (200): resuming works.
  8. Repeat the pause/resume on Brands → (brand) → Prompts.
  9. Set the plan back to self_hosted and NEXT_PUBLIC_IS_CLOUD=false: no limit, and pause/resume work as before.

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: 522/522, including the new actions/prompt.test.ts (9 cases) and the activationDelta / paused-bulk cases.
  • yarn build: passed.
  • bash supabase/build-schema.sh: schema.sql is up to date.
  • Browser check of steps 3–8 in cloud mode (Starter and Growth), then a self-hosted pause/resume.

🤖 Generated with Claude Code

Paused prompts don't run, so they no longer take room on the plan
(org_prompt_location_usage now filters on is_active, 00128). Resuming a
paused prompt brings its locations back, so it is metered like adding
them: setPromptActive refuses with a plan_limit value when there is no
room. That closes the pause, add new prompts, resume the old ones way
past the limit. Location edits on paused prompts cost nothing until the
prompt is resumed.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is ready for review.

Paused prompts no longer count toward the plan's prompt-location limit, and resuming one is metered like adding it, so the "pause, add new ones, resume the old ones" way past the limit is closed.

Things to look at:

  • Migration 00128 redefines org_prompt_location_usage with and p.is_active. It needs to run on deploy, and schema.sql is regenerated.
  • Overlap with feat(prompts): add a bulk action bar for selected prompts #1029 (bulk actions): whichever merges second, its bulk resume (setPromptsActive) should use activationDelta so bulk resumes are metered too. I'll handle that rebase.
  • The race note in the description: the check-then-write is the same shape as the existing add paths. A locked RPC could cover all of them in a follow-up if you want.

Code review, yarn test (518/518), lint, typecheck and build all pass. It was also checked in the browser in cloud mode (Starter refuses the resume, Growth allows it).

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

Second review pass on the active-only prompt quota:

- the edit dialog shows a plain message for non-plan failures instead of
  the raw database error;
- setPromptActive returns a failed limit check as a value (ansvisor#427) instead
  of throwing;
- the brand Prompts page keeps its last quota when the refresh after a
  toggle fails, so the location pickers don't become uncapped;
- the prompt-usage doc no longer says paused prompts count;
- tests for a missing prompt, a failed limit check, and location edits
  on paused vs active prompts.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk I pushed a follow-up commit (19ad264) after a second review pass:

  • The edit dialog now shows a plain message for non-plan failures instead of the raw database error.
  • setPromptActive returns a failed limit check as a value (Query fan-out: long hang then production-masked server error surfaced raw in the UI #427) instead of throwing.
  • The brand Prompts page keeps its last quota if the refresh after a pause/resume fails, so the location pickers don't become uncapped.
  • prompt-usage.ts no longer says paused prompts count.
  • 4 more tests: a missing prompt, a failed limit check, and location edits on paused vs active prompts.

The description's Review section is updated. Lint, typecheck, yarn test (522/522) and build pass, and pause/resume was re-checked in the browser.

Resolves the conflicts with the bulk import (ansvisor#1013): prompt.ts keeps both
setPromptActive and importPrompts, and the Prompts page imports both. The
import RPC (00122) counts locations through org_prompt_location_usage, which
00128 limits to active prompts, so imports follow the same count.

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.

Looks good, thanks. Migration 00128 is applied to production.

@gkhngyk
gkhngyk merged commit a846445 into ansvisor:main Oct 15, 2026
5 checks passed
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 15, 2026
Since ansvisor#1034, only active prompts count toward the plan and resuming one is
metered like adding its locations. The bulk bar's Resume went straight to
the write, so pausing prompts, filling their room and resuming them all at
once got past the limit. setPromptsActive now prices the paused prompts in
the selection with activationDelta, through the same check as
setPromptActive, and writes nothing when they don't fit; the bar shows the
limit message as the row menu does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 15, 2026
* feat(content): show and enforce the monthly content opportunity quota

Plans get a monthly limit on new content opportunities (Starter 10,
Growth 50, Enterprise/self-hosted unlimited), counted separately from the
existing brief quota and renewing with the subscription. Usage is recorded
in opportunity_usage, so dismissed and deleted opportunities still count.

The nightly generation claims slots atomically per organization
(claim_opportunity_usage) before calling the model and hands back the ones
it doesn't use. The Content page leads its stat row with a usage card for
both counters, and GET /api/content/usage exposes the same figures.

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

* feat(content): skip opportunities whose prompt and fan-out baskets duplicate an existing one

Before the model is called, every open cluster's prompt basket and fan-out
basket are compared with the brand's open, sent and recently dismissed
opportunities (Dice overlap, prompts weighted 0.6, queries 0.4). A match is
not generated, so it costs no model call and no quota slot; an open match
takes the cluster in as a related cluster and counts it as
duplicatesMerged, which the detail panel shows. Dismissed opportunities
block their baskets for 90 days. The threshold is configurable through
OPPORTUNITY_DUPLICATE_THRESHOLD and tuned against a test set of known
duplicate and distinct pairs.

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

* feat(content): add a "+ New" button to generate opportunities on demand

The header gets a primary "+ New" (replacing the self-hosted-only Generate)
that opens a dialog: an optional focus (topic or prompt), an optional
free-text idea and a count capped by the plan (Starter 3, Growth 5 per
request) and what is left of the month. POST
/api/content/opportunities/generate validates the request, returns the
job a repeated idempotency key already started, and queues the same
per-cluster generation with the count, focus and idea; quota slots are
claimed atomically and handed back on failure. Placeholder rows show while
it runs, the result toast reports created and skipped duplicates, and a
failure offers Retry.

Opportunities now record their source (system, manual, prompt) in a new
column; the list shows a badge for non-system ones and filters by source,
and the summary aggregates take the same filter.

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

* feat(content): show when each opportunity was suggested, with sort and date filter

The list gets a Suggested column (relative for a week, then a short date,
in the UI's language, full date and time on hover, hidden below 1280px),
Newest/Oldest sorting, a date filter (All time, This month, Last 30 days,
Custom) kept in the URL and applied to the summary figures too (migration
00127), a dot on rows suggested since the last visit, and suggested_at in
ISO 8601 in the CSV export. The detail panel's date now follows the UI
language instead of the browser's. Each row also says what it was built
for: a topic's prompt group with its prompt count, or a single prompt.

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

* fix(content): keep internal indexes and misspelled competitors out of opportunity text

Opportunity text leaked the generator's bracketed indexes ("targeting
prompt [0]", "improve [P2] by … from [P1]") and misspelled competitor
names ("Profund"). New opportunities are cleaned before they're saved:
each index becomes what it stood for in that run (cluster label, page
title, existing opportunity) and near-miss competitor names their
configured spelling. Stored opportunities are left as they are and
cleaned when read: list, detail, CSV, webhooks, brief generation and the
Action Center title all show readable text. Since the lists an old index
pointed into weren't stored, read-time cleaning doesn't guess by
position: pages read "the page" and prompt indexes the opportunity's own
prompt.

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

* feat(content): suggest another angle on an opportunity

An opportunity's panel gets "Another angle": one more opportunity for the
same need with a different content type, format, audience or decision,
optionally steered by a short direction. POST
/api/content/:id/alternative queues it as a content job for the
opportunity's cluster (or the cluster its prompt is in today), skipping
coverage and the duplicate check since the user asked for it; it uses one
quota slot, handed back on failure. The alternative stands beside the
original, marked "Alternative" with a link to it.

Dismissing from the panel now asks why: the topic doesn't matter, or the
topic is right and the angle wrong, which goes on to ask for another
angle. The reason is kept in source_data while the opportunity stays
dismissed and dropped when it's restored; the write only lands on an
unchanged row, so it can't drop a concurrent source_data update.

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

* feat(prompts): suggest content for a prompt from its row menu

PROMPT-006: the prompts table's row menu gets "Suggest content", which
writes one content opportunity for that prompt's cluster, tagged
source 'prompt' and counted against the monthly content quota.

- POST /api/content/prompts/:promptId/suggest checks, in order: a
  repeated request, a job still running for the prompt, an open
  opportunity that already answers it ({ existingId }, no quota used),
  then the quota (429), and only then queues the job.
- The generator's explicit mode revisits a cluster whose opportunity
  was dismissed or finished, never one with an open opportunity, skips
  the duplicate check, merging and reopening, and reports the created
  or covering opportunity id.
- GET /api/content/prompts/:promptId/suggestion lets the menu open an
  existing suggestion once the quota is used up.
- The page follows the job and toasts "Content suggestion created ·
  Open" or "Open existing".

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

* feat(prompts): add a bulk action bar for selected prompts

PROMPT-006: ticking rows in the prompts table opens a bar with the row
menu's actions for all of them: Pause / Resume, Suggest content and
Delete.

- Selection is limited to the rows on screen and starts over when the
  page, search, filters, sort, location, date range or brand change.
- Pause / Resume and Delete each write once (setPromptsActive,
  deletePrompts). Delete asks first and keeps the 10-second Undo; rows
  the write leaves out come back into view.
- Suggest content takes as many prompts as one "+ New" request may
  (Starter 3, Growth 5, never more than is left of the month) and asks
  for them one after another, stopping at the monthly limit or at a job
  that outlives the wait, then sums the run up in one toast.
- The single-row flow now goes through suggestForPrompt, so the row
  menu and the bar report outcomes the same way.

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

* fix(prompts): meter a bulk resume against the plan's prompt locations

Since #1034, only active prompts count toward the plan and resuming one is
metered like adding its locations. The bulk bar's Resume went straight to
the write, so pausing prompts, filling their room and resuming them all at
once got past the limit. setPromptsActive now prices the paused prompts in
the selection with activationDelta, through the same check as
setPromptActive, and writes nothing when they don't fit; the bar shows the
limit message as the row menu does.

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

* fix(prompts): delete selected prompts a few per call

A bulk delete sent up to a page of prompts in one statement. Each prompt
takes its answers and citations with it, so on big brands the statement
outran the 8-second timeout and everything rolled back.

- deletePrompts takes at most PROMPT_DELETE_BATCH (3) prompts per call.
- The page deletes with deleteInBatches, one call after another, after
  the Undo window and on unmount alike; deletes queue behind each other.
- The bulk bar shows the progress of a delete that needs several calls.
- A failed call stops the run: what came before stays deleted, the rest
  comes back into the list and the toast says how many were deleted.

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

---------

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