Repository navigation
feat(billing): sell AI credit and storage packs, granted only by the Stripe webhook (W1-31) - #1845
Conversation
…iles, Help and add-on packs Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types and the demo's coverage only; the code that uses them comes in the Wave 1 PRs. - 00407: chat_conversations gets shared_at (Share with team: every member of the workspace reads it), last_read_at (unread results), deleted_at (Delete with Undo; deleted chats are hidden from every member) and a title search column; chat_messages gets context_json (what a person's message was scoped to) and a text search column. 'simple' text search, so a chat in any language is found. The author policy now leaves deleted chats out, and a shared policy reads shared ones. - 00408: chat_user_prefs gets the rest of Settings › General and the one-time notices: rail_open, panel_size, default_mode, answer_language, notify_via, show_thought, panel_on_pages, focus_prompted_at, usage_notice_period, legacy_imported_at. - 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file, the composer's 11 types, 5 a message (a trigger backs the server's check), kept 90 days. - 00410: chat_tool_cache (a chat's read results by tool and scope, server only) and each step's and model call's measure: latency, cache hit, truncation, result tokens on chat_run_steps (never granted to members), prompt cache read/write tokens and latency on the ledger. - 00411: chat_files (filed deliverables and saved answers, the workspace's, kept a year, searchable by title, summary and tags), chat_file_task_links, chat_storage_usage kept by a trigger, and the private bucket chat-files. - 00412: help_answer_cache and help_gaps (server only, no workspace or person ids). - 00413: add_on_products seeded with the owner's packs (AI credits $10, $50, $250, $1,000 at half their price in budget, 12 months; storage +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked), add_on_purchases (Admins read), ai_credit_grants and storage_grants (server only), and prompt_improve_usage.grant_id. Members only ever read; every write is the server's. Tool names, tool results and dollars stay server only. web/src/types/supabase.ts carries the new tables and columns; schema.test.ts checks the policies, the server-only tables, the limits and the seeded packs from the SQL; steps.test.ts keeps the step measure out of the member columns. The demo coverage skips chat_files and chat_tool_cache (a person's own Chat work). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Stripe webhook
CHAT-18 (W1-31), behind CHAT_AGENTIC, on 00413's tables. An Admin of a
workspace on a paid, active plan buys a pack; nothing is granted before
Stripe says it was paid.
- Buying (startAddOnPurchase, a server action that never throws): AI
credits open a Stripe Checkout in payment mode with an invoice; storage
is a monthly item on the plan's subscription, prorated and charged to
the card on file at once (a declined card fails the purchase with
Stripe's words). A pending add_on_purchases row is written first and
every Stripe object names it. Refused for non-Admins, the free trial, a
plan that isn't active, Chat off, and a pack without a Stripe price
("unavailable", no Stripe call); storage also on a plan billed yearly.
- Granting (the webhook, before the plan's handlers): checkout.session
.completed / async_payment_succeeded and the pack's invoice.paid write
one ai_credit_grants row (half the price in model cost, 12 months from
the payment); invoice.paid with a storage item writes storage_grants
until the period's end and moves it on at each renewal. A purchase is
paid once (only from pending) and a grant written once (unique
purchase_id), however often or early the event comes; an item not yet
written down is found by its pack's price. A full charge.refunded takes
back the unused credits or ends the storage, and a refunded pack isn't
renewed. A pack's invoice never changes the plan's status.
- Spending (server): with Chat on, a hold passes on the credits once the
included budget is spent (creditRoomUsd), and a charged call's cost past
the included budget is drawn from the grant ending soonest, its ledger
row split by grant_id (drawCredits), for Chat's steps and every other AI
feature. Credits outlive the monthly reset; own-key rows never touch
them.
- The plan's routes take the plan's subscription item, never a pack's.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e plan themselves startAddOnPurchase refuses a workspace without an active, paid plan itself (trial, no_plan), answering a reason rather than throwing, as prepareImageUpload and Chat's settings do: the read-only coverage test lists it with why. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s it lib/stripe.ts makes its client when it is loaded and throws without STRIPE_SECRET_KEY (local development, self-hosted). The add-on actions imported it at the top, so on Settings, whose server actions are bundled together, every action beside them broke with it (Billing's AI usage card among them). loadStripe (lib/billing/add-ons.ts) imports it on demand and gives null without the key: a purchase then answers "unavailable", and the webhook's lookups load it only when they run. lib/stripe.ts and its routes are as they were. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…heckouts, and let pages use purchased AI credits
- A full refund of a storage pack now takes its item off the plan's
subscription (no proration), so it isn't charged each month for storage
it no longer grants. An item already gone is fine; any other Stripe error
answers 500 so Stripe sends the event again.
- checkout.session.completed grants AI credits only when payment_status is
'paid' ('no_payment_required' never grants).
- getAiUsage says whether purchased credits are left (a boolean, no
dollars), and aiUsageTone stays a warning at 100% while they are, so the
Content Editor, the banners and Chat's composer don't say "used up" while
calls still run on the credits. The Improve tab's quota counts them too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good with a77230f (one fix commit on this branch, described below).
I reviewed only what this PR adds on top of #1812 (af43140df..894cebd9c). #1812's head hasn't moved since. I covered the purchase action, the webhook's pack handling, the plan route's planItemOf, and the credit draw on the AI budget. The fixes are on take-1845 in one commit, each with a test that fails without it.
What the fix commit changes
-
A refunded storage pack keeps getting charged. On a full refund,
refund()ends the storage grant and marks the purchaserefunded. The pack's item stays on the plan's subscription, though, so every renewal invoice charges for it.grantStoragethen skips the refunded purchase, which means the workspace pays each month and gets no storage. Your test "no renewal brings it back" checks the grant side, but nothing removes the item.
Fix: on a full refund of a storage pack,removeStorageItemdeletes its subscription item withproration_behavior: 'none', since the refund already settled the money. If Stripe answersresource_missing, the item is already gone and that's fine. Any other error throws, so the webhook answers 500 and Stripe sends the event again; the purchase stayspaiduntil then. -
The pages say "used up" while credits are left. The server's hold counts the credits (
creditRoomUsd), butgetAiUsagestill reports the plan's share alone. At 100%,aiUsageTonereturnsexhausted, and then:- the Content Editor's agent buttons switch off (
aiUsedUp) - the banners say the allowance is used up
- with #1840, Chat's composer turns off (
chatAtCapreadsaiUsageTone) - the Improve tab's quota (
getImproveQuotaStatus) givesremainingUsd0 andexhausted: true
So a workspace that just bought credits can't use them from the UI.
Fix:creditsLeftUsd(orgId)inai-credits.jsreturns 0 with Chat off.getAiUsagereturnscreditsLeft(a boolean, no dollars), andaiUsageTonestayswarningat 100% while credits are left.getImproveQuotaStatuscounts the credits the same wayreserveAiBudgetdoes:budget + creditRoomUsd − spent, withpercentLeftcapped at 100.- The meter still shows 100% of the plan's share. #1846's "AI credit left" line can explain the rest.
- the Content Editor's agent buttons switch off (
-
Grant on
payment_status === 'paid'only.checkout.session.completedgranted on anything butunpaid, sono_payment_requiredalso granted. No current path gives a pack Checkout that status, because Checkout gets no discounts or promotion codes, but the grant should depend on being paid.
Suggested commit: fix(billing): stop billing a refunded storage pack, grant only paid Checkouts, and let pages use purchased AI credits.
Checked and fine
- Who can buy: the check runs on the server, in this order: signed in, Chat on for the workspace,
role = 'admin'read fromprofileswith the service client, cloud,subscription_status = 'active'. A trial getstrialand anything else getsno_plan. The workspace is always the caller's own, fromprofiles. The browser sends only a product id, checked by regex. The Stripe price comes fromadd_on_products, and a pack withoutstripe_price_idor notactiveis never sold. No amount or price id from the client reaches Stripe. The action is listed inOPEN_ACTIONSwith a reason, andsubscription-guard-coveragepasses. - Webhook: the signature is checked before
handleAddOnEvent. Grants come only fromcheckout.session.completed/async_payment_succeededwhen paid, or frominvoice.paid. A return from Checkout grants nothing. - Replays: grants are
upsert … onConflict purchase_id, ignoreDuplicates, sopurchase_idis unique.markPaidonly moves a purchase frompending.stripe_checkout_session_idandstripe_subscription_item_idare unique. The dry run below confirms each on the real schema. - Organization: every grant takes
organization_idfrom the purchase row (purchase.organization_id), never from Stripe metadata or the customer.claimByPriceonly looks at pending purchases of the workspace that owns the invoice's customer. So the mismatch #1812's review raised can't come from this code. The composite FK stays a nice-to-have for the schema. - Plan handlers: pack Checkouts and pack-only invoices return
trueand skip the plan's handlers. A declined storage invoice doesn't setpast_due, and an AI invoice doesn't setactive. Plan changes useplanItemOf, so a storage item is never swapped for the plan's price. - Credit draw: the included budget is used first, then the grant that ends soonest. A row that crosses the line is split by
grant_id, own-key rows are never drawn, and nothing is read with Chat off.ai_usage_by_featuresums the split rows (dry run), so the meter's total is still the true spend. - Storage cap: nothing in this PR reads
storage_grantsyet. #1856 does (readChatStorage,active_until > now), so the cap goes up once both land. - Embeds: none. Migrations: none of its own (00413 is #1812's).
- Client bundle:
plan-row.test.tspasses on the merge with main.add-ons.tsloads Stripe lazily, and its no-key test passes.
Follow-ups (not blocking)
- Disputes aren't handled. After a chargeback, the unused credits or the storage stay. Handling
charge.dispute.funds_withdrawnthe same way as a full refund would cover it. Until then staff handle it in Stripe, which emails every dispute. Partial refunds are also left to staff, as the PR says. - Buying the same storage pack twice fails. Stripe won't take two items with the same price on one subscription. The second purchase gets a generic
failedand its row stayspending. Raising the existing item's quantity, or refusing up front, would read better. - Storage and yearly plans don't mix. With a storage item on, switching the plan to yearly fails in Stripe, because the items' intervals must match. The plan route returns an error. The page could say why, or the pack could move with the plan.
- A plan cancelled to its period end (#1823) can still buy credits. Those credits stop counting once the plan ends, since there's no active plan. Consider refusing a purchase when
cancel_at_period_endis set. - The draw isn't atomic. If
splitRowfails aftertakeFromGrants, the credit is used while the row stays on the included budget, so that cost is counted twice. It's logged. A single RPC would close this. - Credits count only with Chat on. If Chat is turned off for a workspace that bought credits, the budget goes back to the plan's own. That matches the flag, but keep it in mind for any rollback.
cancelledis never set. Nothing marks a storage purchase ascancelledwhen its item or the plan's subscription ends. The grant still lapses atactive_until, but the history keeps showingpaid.- Subscription coupons apply to the storage item. A coupon on the plan's subscription also discounts the storage item, and a 100% one makes it free. Decide whether that's intended.
Merge status
- Base: #1812 at
af43140df(unchanged). - On
main:take-1845merges cleanly into origin/main (a8121a6c8). - Other PRs: no textual conflicts with #1804, #1806, #1818, #1823, #1840 or #1846. #1846 changes
add-on-webhook.tsonly through the merge of this branch, so it needs this fix merged in. #1840'schatAtCappicks up thecreditsLeftchange throughaiUsageTonewith no change of its own.
Tests (on take-1845)
- Server: the full suite passes, except 8 regex/parse timing tests that fail under load. All of them pass when run on their own, and this PR doesn't touch them.
chat-budget.testhas the new credit test, and demo coverage passes. - Web: vitest for
lib/billing,lib/chat, the add-on actions, the Stripe routes,ai-usagecomponents,subscription-guard-coverageandplan-row: 47 files, 622 tests.tsc --noEmitis clean, and eslint and prettier are clean on the touched files.
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved Chat PRs. This head merges current main; where they overlapped, both sides are kept. Its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build. Chat stays behind CHAT_AGENTIC.
Summary
Chat Wave 1, behind
CHAT_AGENTIC. Stacked on #1812 (W1-DB). The diff against main includes the PRs below it until they merge. The product owner saw this in a local preview and approved it.W1-31: AI credit and storage packs, granted only by the Stripe webhook (CHAT-18).
startAddOnPurchase, Admin only; it never throws.stripe_price_id(unavailable, Stripe never called).checkout.session.completed,invoice.paid,charge.refunded).grant_idwhere the limit is crossed. Own-key usage never touches credit.loadStripe()), so Settings works withoutSTRIPE_SECRET_KEY, as on self-hosted installs. A test proves the module loads and a purchase returnsunavailablewithout the key.No migration, no new dependency.
Related issue
Part of Chat (Wave 1, CHAT-18).
Type of change
feat— New featureHow to test
Tests: webhook grants, idempotency, refunds, the spending order, a pack without a price, and the module without a Stripe key. Server 4,503 tests.
Checklist
help/chat/*,approved: false)🤖 Generated with Claude Code