release: charge credits per chat turn (#612)

Merged
SW
5mo ago
+533-79

Summary

Releases PR #612 from `test` โ†’ `main`.

  • Closes the silent revenue-loss gap: every successful chat workflow turn now atomically debits the account wallet AND records a `usage_events` audit row
  • Refactors to consolidate billing into the existing `handleChatCredits` orchestrator (one path for both `/api/chat` and `/api/chat/workflow`)
  • Switches `recordCreditDeduction` to the atomic `deduct_credits_with_audit` Postgres RPC (recoupable/database#26) โ€” eliminates wallet/meter drift for ALL callers, including the 3 research handlers
  • Closes #605 chat-workflow billing gap

Test plan

  • 3195 unit tests passing
  • Lint / format / tsc clean
  • E2E preview verification: wallet 998c โ†’ 997c, audit row `PenhKC1lRbdzyRQjcaSH0` landed with correct fields (`source='api'`, `agent_type='main'`, `model_id='anthropic/claude-haiku-4.5'`, `credits_deducted_cents=1`)
  • Post-merge: sanity check on `sandbox.recoupable.com` against `https://api.recoupable.com\` โ€” trigger a chat and confirm wallet drops

๐Ÿค– Generated with Claude Code


Summary by cubic

Charges credits for every successful chat workflow turn with an atomic wallet debit + audit, closing the chat-workflow billing gap. Consolidates billing for both /api/chat and /api/chat/workflow; closes #605.

  • New Features

    • Atomic debit + audit via deduct_credits_with_audit Postgres RPC for each turn (no wallet/meter drift).
    • runAgentWorkflow persists the assistant message, then bills using handleChatCredits with accountId, model, gateway cost, and token usage from message metadata.
    • getCreditUsage accepts a gateway-reported USD cost and short-circuits token math; 1ยข minimum still applies.
    • Source tagging on audit rows: workflow path uses source="api"; streaming path defaults to source="web".
  • Refactors

    • Unified billing through handleChatCredits for /api/chat and /api/chat/workflow.
    • Replaced deductCredits + insertUsageEvent with a single RPC wrapper: lib/supabase/credits_usage/deductCreditsWithAudit.
    • Threaded validated accountId into the workflow; updated tests and Supabase RPC types.