Skip to content

feat(chat): charge Chat's model calls to the one AI budget - #1788

Merged
gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-budget
Oct 29, 2026
Merged

gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-budget

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat P0, part C2: each Chat model step is charged to the workspace's one AI budget at its real cost (1x) (CHAT-04 §C items 11–14, 17; CHAT-16 items 22, 28, 29; DECISIONS P). Behind CHAT_AGENTIC.

The product owner confirmed on 2026-10-29: the plan budget is charged at 1x, and the 2x markup applies only to extra credit packs (CHAT-16 30a).

Server: internal endpoints /api/internal/chat/budget/{reserve,charge,release}

  • Contract: CRON_SECRET, Zod bodies. They never throw; every answer has a typed code. No dollars are sent or received: the web sends no cost, and the server prices each step.
  • reserve: holds the step's worst case.
    • 201 { usageId };
    • 429 ai_limit { trial };
    • 402 plan_limit;
    • 404 not_found (the run isn't this workspace's);
    • 403 chat_off.
  • charge: turns the hold into the real cost (generationCostUsd). If the provider reports no usage, the hold stays as the cost, so usage can be over-counted but never under-counted.
  • release: lets the hold go. It is idempotent. A Stop keeps the hold as the cost, since the provider still bills an aborted call.
  • Rate limiter: the general /api limiter skips /api/internal/chat/budget/*, but only with a valid CRON_SECRET (constant-time webhookSecretsMatch). Vercel's calls can come from one IP, and 250 per 15 min would stop Chat.

Migration 00405

  • prompt_improve_usage:
    • feature adds chat, agent, schedule and image;
    • new columns own_key, chat_run_id and chat_run_step_id (FK on delete set null, partial indexes).
  • reserve_chat_ai_usage:
    • Takes the same organization lock as reserve_ai_usage, but stricter: a step starts only if spent + in-flight holds + this step's worst case ≤ the budget.
    • Checks that the run belongs to the organization.
  • Own-key rows: reserve_ai_usage, ai_usage_by_feature and plan-guard's reads skip rows written with the workspace's own key.
  • organizations.legacy_key_grandfathered: a server-only column.
    • Set at migration for Starter workspaces, and for Growth workspaces on a trial, that have a key.
    • The ai-providers PUT also sets it while the flag is off, so the cut-off is the moment the flag goes on.

Which key (web/src/lib/chat/key.ts)

Case Key Budget
Flag off Today's behaviour (cloud: the customer's key only) Nothing written
Growth or Enterprise with own key Own key Row written (own_key); % doesn't move
Grandfathered Starter with a key Own key Same
Starter, Growth trial, or no key Ansvisor's ANTHROPIC_API_KEY Charged
Self-hosted The operator's key Unlimited; row still written

Web

  • web/src/lib/chat/budget.ts: the engine's client. Every call has a 5 s limit.
    • If reserve gets no answer or a 502, the step doesn't start, and the client returns { ok: false, refusal: 'unavailable', retryable: true, message } with chatBudget copy.
    • reserve isn't retried, since a lost answer retried would hold twice. charge and release retry once.
  • Billing meter: gets a "Chat" line, as a % only. With the flag on, "Agent Chat runs on your own AI key" is replaced.

Related issue

None (Chat P0, Drive › Chat).

Type of change

  • feat — New feature (behind CHAT_AGENTIC)

How to test

  1. Apply 00405 after 00400–00402.
  2. Server tests: cd server && npx vitest run src/lib/chat-budget.test.js src/routes/internal-chat-budget.test.js src/middleware/rate-limiter.test.js. They cover:
    • every step writes a row;
    • 20 parallel steps never pass the cap (7 fit, 13 get 429 with 1% left);
    • own-key use doesn't move the %;
    • the trial budget isn't reset;
    • chat_off;
    • the limiter skips only secret-carrying budget calls (260 pass), while the rest still get 429 after 250.
  3. Web tests: cd web && yarn vitest run src/lib/chat/budget.test.ts src/lib/chat/key.test.ts src/components/settings/ai-usage-card.test.tsx.
  4. The migration ran on the dev database inside a rolled-back transaction.
    • Of 3 holds against what was left, 2 fit and the third was refused.
    • An own-key row didn't move the meter.
    • Another organization's run, and a non-chat feature, were refused.
    • Deleting a run kept its usage rows.

For the maintainer:

  • Deploy: cloud Chat needs ANTHROPIC_API_KEY in the web's Vercel environment.
  • Trial budget: it reads $1 here until feat(billing): give the free trial $2 of AI usage instead of $1 #1744 ($2) merges. The tests use the constant.
  • Follow-ups:
    • clear the grandfathered flag on plan change or cancel (Stripe webhook, wave 4);
    • the aiUsageHint copy on plan cards;
    • a sweep for orphaned holds after a reserve timeout;
    • a docs PR for MCP get_ai_usage's new lines.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • bash supabase/build-schema.sh: schema.sql is current
  • Server: format and lint clean; related tests pass (787 + the limiter's 35)
  • Web: related tests (335) pass; prettier, eslint and typecheck clean
  • Full suite and build: CI

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 29, 2026 19:32
CHAT-04 §C items 11–14 and CHAT-16 items 22, 26 and 28–30 (DECISIONS P),
behind CHAT_AGENTIC. With the flag on, Chat runs on Ansvisor's key and
each model step draws on the monthly AI budget that Improve, the Content
Editor and the task writer already share, at the model's real cost (1x;
the margin stays with purchased AI credits).

- 00405: prompt_improve_usage.feature takes chat, agent, schedule and
  image; own_key, chat_run_id and chat_run_step_id (on delete set null).
  reserve_chat_ai_usage holds a step's worst case under the same
  per-organization lock as reserve_ai_usage, and only while spend, holds
  in flight and that worst case stay within the budget, so parallel runs
  can't pass it. Own-key rows are written but left out of every sum
  (reserve_ai_usage, ai_usage_by_feature, plan-guard's reads).
  organizations.legacy_key_grandfathered marks Starter (and Growth trial)
  workspaces that had a key, guarded as a server column.
- Server: lib/chat-budget.js and /api/internal/chat/budget/{reserve,
  charge,release} (CRON_SECRET, Zod). The server prices every step; the
  web never sends a cost, and no answer carries dollars.
- Web: lib/chat/key.ts picks the key (own key on Growth+, a kept Starter
  key, else Ansvisor's ANTHROPIC_API_KEY); lib/chat/budget.ts reserves,
  then charges, releases or keeps (a Stop's call is still billed). It
  never throws: a refusal comes back typed with its words (chatBudget),
  calls have 5 s limits, a reserve that gets no answer refuses the step,
  and charge/release retry once after a 502.
- Billing: a Chat row in percent, and the "Agent Chat runs on your own AI
  key" line changes while Chat is on. A key saved while Chat is off marks
  the workspace to keep it.

With the flag off nothing changes: Agent Chat keeps the workspace's own
key only, and nothing is held or written.

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

Every Chat model step makes two calls to /api/internal/chat/budget, and on
Vercel the web's calls come from a few shared addresses, so the API
limiter's 250-a-quarter-hour IP bucket would stop Chat for every
workspace at once. apiLimiter now skips a request only when it is on that
path and carries the internal secret (CRON_SECRET, compared in constant
time); the same path without it, or the secret on any other path, is
counted as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 29, 2026
… a paid model at $0

The synced OpenRouter prices replaced improve-cost.js's table for every AI
call in the deployment once CHAT_AGENTIC was on, not only for the pilot
workspaces' Chat steps, and a catalog price of $0 metered a paid model's
calls at nothing. priceFor now reads the synced price only when asked
(chat-budget.js's hold and charge), and falls back to the table, or
FALLBACK_PRICE, when a paid model's synced rate is $0. The table also
prices OpenRouter's dotted ids (claude-haiku-5.5) as its own.
…on their own

They're server to server (CRON_SECRET) and keyed by a run, not a brand,
so the demo-brand guard on routes/index.js doesn't apply. The demo
coverage test failed without the entry.

@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 with 0d593fc (take-1788). I merged main in (one conflict, an import list in rate-limiter.test.js) and added two commits.

What I changed

  • Synced prices now price Chat's steps only, and a $0 catalog rate never meters a paid model.
    • Before, with CHAT_AGENTIC=true, priceFor read the synced OpenRouter price first for every AI call in the deployment: Improve, the Content Editor, briefs and the task writer, in every workspace, not only the pilot ones. A catalog rate of $0 for a paid model metered its calls at $0.
    • Now priceFor and generationCostUsd read the synced price only with { synced: true }. Only chat-budget.js asks for it, for the hold and the charge, and its routes answer chat_off outside CHAT_AGENTIC_ORGS.
    • A synced price with a $0 input or output rate is ignored unless the model is a :free one. The table prices it instead, or FALLBACK_PRICE.
    • The table also prices OpenRouter's dotted ids as its own. Chat's budget ids are anthropic/claude-haiku-5.5 and anthropic/claude-sonnet-5.5. Before, when the sync had no row for them, they fell to FALLBACK_PRICE ($5/$25, about 50x Haiku's price).
    • Every other call is priced from improve-cost.js's table, as before #1771.
  • The demo coverage test failed. demo-brand.test.js lists the route files mounted outside routes/index.js, and internal-chat-budget.js is one of them. It's server to server and keyed by a run, so I added it to the list with that reason.

What I checked

  • Every Chat model call is metered once.
    • reserve holds the step's worst case, under the same per-organization lock as reserve_ai_usage. It is never retried, because a lost answer retried would hold twice.
    • Then exactly one of these happens:
      • charge: the row becomes the real cost (1x). Retrying it is safe, since it sets the row.
      • release: the row goes. The web's settled guard makes it a no-op after a charge.
      • keep: a Stop. The hold stays as the cost.
    • If the API doesn't answer, the step doesn't run. If the web's flag is on and the API's is off, reserve answers chat_off and the step doesn't run either, so there is no unmetered path.
    • Own-key rows are written but left out of every sum: both SQL functions and the three plan-guard.js reads.
  • Flag off.
    • reserveChatStep returns the unmetered no-op and calls nothing.
    • The routes answer chat_off before any read.
    • getAiUsage only adds chatMetered: false.
    • The one write with the flag off is by design: the AI-providers PUT marks legacy_key_grandfathered on Starter and Growth-trial workspaces, so the cut-off is when the flag goes on.
  • Rate limiter. It skips only /api/internal/chat/budget/* with the right CRON_SECRET, compared in constant time.
  • Migration 00405.
    • It widens prompt_improve_usage.feature. Adding the check scans the table once while holding an exclusive lock on it (see the sizing query below).
    • It adds three columns:
      • own_key boolean not null default false. That default is metadata-only, so no table rewrite.
      • chat_run_id and chat_run_step_id, both on delete set null, with partial indexes.
    • reserve_ai_usage and ai_usage_by_feature are recreated with the same signatures, so their grants stay.
    • reserve_chat_ai_usage is security definer, with search_path = public. It's revoked from public, anon and authenticated, and granted to service_role. It checks that the run belongs to the organization, and that the step belongs to the run.
    • organizations.legacy_key_grandfathered is added to guard_organization_server_columns(). The function is otherwise exactly main's current one (00276).
    • prompt_improve_usage stays service-only: RLS on, no policies.
  • The rest.
    • No embeds.
    • No client→server import (plan-row.test.ts passes).

Deploy order (important)

00405 must be on prod before this merges. Two things depend on it:

  • The API's plan-guard.js now filters on own_key. Without the column, every AI budget read fails.
  • The web's AI-providers PUT writes legacy_key_grandfathered.

The web deploys on merge. Then the API.

Follow-ups (not blocking)

  1. A sweep for holds whose reserve answer was lost after 5 s. Today they stay as cost: over, never under.
  2. release deletes any of the workspace's Chat rows by id. The web never releases after a charge, but deleting only a row that is still a hold would be safer if another caller is ever added.
  3. Clearing legacy_key_grandfathered on a plan change, as the PR says.

Tests:

  • improve-cost, chat-budget, internal-chat-budget, rate-limiter, model-prices, model-price-cache and demo-brand pass.
  • I checked that each new test fails without its fix.
  • The full stack passes (see #1794).

@gkhngyk
gkhngyk merged commit 2ca91b0 into ansvisor:main Oct 29, 2026
4 of 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