Skip to content
Shell
6.6 KB
Raw Blame

Unified Token System & Usage Dashboard Plan

Summary

Build a unified credit system with proper tier allocations, API metering, and a slide-out Usage Panel for visualization.

User Requirements

  • Credit Allocation: Pay-per-use hybrid (Free: 100/mo, Pro: 1,000/mo, Elite: 5,000/mo with rollover capped at 2x)
  • Reset Policy: Hard monthly reset on billing date
  • Dashboard: Slide-out panel (not full page) - similar to Settings/Profile panels
  • Action Costs: Tiered by complexity (1-2 for simple, 5-10 for data, 15-30 for AI)

Tooling & Agent Assignments

MCP Servers

MCP Usage
mcp__supabase__* Apply migrations, execute SQL, verify schema
mcp__playwright-server__* Visual testing of Usage Panel UI
mcp__github__* PR creation when complete

Subagents

Phase Agent Purpose
1 database-architect Design & validate migration schema
2 backend-architect Design credit middleware architecture
4 frontend-developer Build Usage Panel components
5 test-engineer Generate comprehensive tests

Skills

Skill Phase Purpose
database-design 1 RLS policies, indexes, functions
supabase-expert 1 Migration best practices
state-management 3 Zustand store design
ui-builder 4 Component styling patterns

Plugins & Slash Commands

Plugin When
/testing-suite:generate-tests After each phase
/pr-review-toolkit:code-reviewer Before PR creation
/supabase-toolkit:supabase-migration-assistant Phase 1 validation

Verification Tools

Tool Purpose
Bash(npm run type-check) TypeScript validation
Bash(npm run lint) Code quality
Bash(pytest) Backend tests
mcp__playwright-server__browser_snapshot UI verification

Phase 1: Database Schema

1.1 Create Migration: 013_unified_credit_system.sql

File: /web/supabase/migrations/013_unified_credit_system.sql

  • Enhance profiles table with: credits_monthly_base, credits_rollover, credits_rollover_cap, billing_cycle_anchor, last_credit_reset
  • Create credit_tier_config table with tier allocations
  • Create credit_usage table for tracking with RLS
  • Create deduct_credits_v2() function for atomic deduction + logging
  • Create allocate_tier_credits() function for tier upgrades

Tier Config:

Tier Monthly Rollover Cap
free 100 No 100
pro 1,000 Yes 2,000
elite 5,000 Yes 10,000

Phase 2: Backend Credit Middleware

2.1 Create /core/api/credits.py (NEW)

  • ActionCost enum with tiered costs
  • CreditDeduction FastAPI dependency class
  • require_credits() and require_action() helpers

Cost Structure:

Category Endpoints Cost
Free /health, /api/calendar 0
Simple /quote, /api/market/quotes 1-2
Data /api/market/bars, /api/news, /api/options/chain 5-10
AI /api/chat, /api/analyze, /strategies/deep-value 15-30

2.2 Update /core/api_server.py

  • Modify _handle_checkout_completed() to call allocate_tier_credits()
  • Add credit middleware to all API routes

2.3 Update /web/src/app/api/chat/route.ts

  • Add server-side credit check before AI calls

Phase 3: Frontend - Credit Store

3.1 Create /web/src/lib/stores/credit-store.ts (NEW)

  • UserTier = 'free' | 'pro' | 'elite' (fixes Elite!)
  • Sync from response headers and profile

3.2 Update /web/src/lib/stores/ui-store.ts

  • Add usageOpen, toggleUsage, setUsageOpen

3.3 Update /web/src/lib/api.ts

  • Sync credits from X-DeepStack-Credits header
  • Dispatch paywall event on 402

Phase 4: Frontend - Usage Panel

4.1 Create /web/src/hooks/useUsageData.ts (NEW)

Returns: credits, tier, tierLimit, usagePercent, categories, recentActivity, resetDate, daysUntilReset

4.2 Create Usage Components (NEW)

  • /web/src/components/usage/UsageProgressRing.tsx - Circular progress
  • /web/src/components/usage/UsageCategoryBar.tsx - Horizontal bars
  • /web/src/components/usage/UsageActivityItem.tsx - Activity log item

4.3 Create /web/src/components/layout/UsagePanel.tsx (NEW)

Follow SettingsPanel.tsx pattern:

  • Slide-out 420px panel with glass-morphism
  • Sections: Header, Balance Card, Category Breakdown, Recent Activity, Reset Info

4.4 Add Triggers

  • /web/src/components/layout/LeftSidebar.tsx - Add Usage button
  • /web/src/components/layout/SettingsPanel.tsx - Make credits clickable

4.5 Add to /web/src/components/layout/DeepStackLayout.tsx


Phase 5: Testing

  • Update /tests/e2e_token_system.py
  • Add frontend tests for UsagePanel, useUsageData, credit-store

Implementation Order

# Task Tools/Agents Verify
1 Database migration mcp__supabase__apply_migration, Skill:database-design mcp__supabase__execute_sql
2 Backend credits module Agent:backend-architect pytest tests/
3 Stripe webhook update Direct edit pytest tests/unit/test_api_stripe.py
4 Apply middleware to routes Direct edit pytest tests/e2e_token_system.py
5 credit-store + ui-store Skill:state-management npm run type-check
6 useUsageData hook Skill:supabase-expert npm run type-check
7 Usage UI components Agent:frontend-developer, Skill:ui-builder npm run lint
8 UsagePanel.tsx Agent:frontend-developer mcp__playwright-server__browser_snapshot
9 Triggers & layout Direct edit mcp__playwright-server__browser_click
10 API client header sync Direct edit E2E test
11 Testing & Review /testing-suite:generate-tests, /pr-review-toolkit:code-reviewer All green

Watcher Role: Claude monitors each step, runs verification, fixes errors before proceeding.


Critical Files

Purpose Path
Migration /web/supabase/migrations/013_unified_credit_system.sql
Backend Credits /core/api/credits.py
Stripe Webhooks /core/api_server.py:1142-1345
Pattern Reference /market_api.py:128-195
UI State /web/src/lib/stores/ui-store.ts
Panel Pattern /web/src/components/layout/SettingsPanel.tsx
Ring Pattern /web/src/components/thesis/ValidationScoreRing.tsx

Deliverables

  1. Unified credit system with DB as source of truth
  2. Tier-based allocation (100/1000/5000)
  3. API metering on all endpoints
  4. Slide-out Usage Panel with visualization
  5. Elite tier support throughout