Creator Analytics - Design Document

Status: Shipped. All three tabs are live at /analytics — My Stats (free, every user gets a personal dashboard), Creator Analytics (Pro, Phase 1.5 with 15 use cases including character leaderboard, model usage, follower/favorite growth), and Audience Insights (Pro, Phase 3, anonymized audience aggregation). UC-C18 conversation-origin tracking shipped alongside Phase 2 audience aggregation. Ghost stat/chart cards render while data loads.

Overview

We already store the data — materialized views (mv_character_stats, mv_user_stats, mv_mode_stats, mv_lorebook_stats) and per-message pipeline stats (web_message_stats) capture everything from conversation counts to token usage over time.

The analytics page has two tiers:

The same chart components power both tiers, so the free experience is the best advertisement for the paid one.


Strategic Positioning

Free tier is deliberately substantive — by design

The Free My Stats tier is intentionally generous: streaks, themes, word count, regen rate, paused-conversation pickup, drifted-away nudges. This will look like "leaving conversion money on the table" to anyone pattern-matching to typical SaaS funnels. It is not. Echo of Dreams is a passion project where adoption ranks above margin (consistent with the platform's broader pricing posture — see the ecosystem-thinking notes in project memory). A genuinely useful free product is the strongest organic-marketing channel the platform has, and the Pro upgrade story isn't "unlock the same charts about yourself" — it's "unlock charts about your audience." Different surface, different question, different reason to pay.

Pro value proposition

Pro Creator Analytics sells action loops, not status snapshots. Every other metric category in the document gets a column in the breakdown — but the load-bearing UCs for Pro are the iteration loops:

The pitch isn't "see how your content performs"; it's "feedback loops the rest of the industry hides." Creators who treat their work as craft want feedback loops. Pro is for them. Creators who don't aren't the target — and that's fine.

Privacy is a competitive moat

The anonymization design (UC-C8 — opaque session-salted IDs, min cohort suppression, no PII to creators, no conversation content) is unusual in this category. Competing RP platforms either don't have analytics or leak more than they should. In a market where users worry about being tracked or studied by creators, "your creator can see engagement, not you" is a brand asset, not just compliance. The anonymization rules aren't a constraint on what we'd otherwise build — they're the design choice that makes the audience-insights tier credible to users at all.

Engagement loops

Individual UCs compose into loops that make the dashboard sticky. Cutting any UC in a loop weakens the whole loop more than its individual contribution suggests:

Creator retention loop (Pro): UC-C9 (notice growth/decline) → UC-C10 / UC-C15 (diagnose where) → UC-C14 / UC-C17 (iterate on what) → return to UC-C9 next week to measure the change. Without UC-C9 the loop has no entry point; without UC-C14 / UC-C17 it has no exit; without UC-C10 / UC-C15 the middle is guesswork.

User retention loop (Free): UC-U10 / UC-U13 (re-engagement nudges find paused stories and drifted characters) → user returns → UC-U1 / UC-U8 (consistency cards reward the return) → UC-U2 / UC-U3 / UC-U12 (discovery shows them new things to try). Pull-shaped re-engagement: the user opens the page voluntarily and finds the nudge, not the other way around.

Creator conversion funnel (Free → Pro): UC-U6 (conversion mechanic) is the only UC in the Free tier whose job is conversion — and it succeeds only if the rest of Free is genuinely good. The upsell card lands harder when the user is already sold on the chart aesthetic and the data quality, not when it's gating their first impression.

Realistic scope

This is a multi-month build. Phase 1 alone is 4–6 weeks. The full design (Phases 1–3) is realistically 3+ months of focused work from one developer, including snapshot jobs, audience aggregation, opaque-ID HMAC, retention pruning, two new schema tables, conversation- origin instrumentation, and the shaped endpoints + frontend tabs. The phasing below is structured so each phase ships a coherent product slice — incremental delivery is non-negotiable.


Use Cases

This feature is grounded in concrete user and creator behaviors observed on the platform. Every dashboard section below maps to at least one of the use cases here — if a section doesn't answer a real question, it shouldn't ship.

My Stats (free) — user use cases

These are the people opening /settings/analytics without a Pro subscription. The unifying thread: curiosity about themselves, not about other users.

UC-U1 — "How much have I been chatting?"

UC-U2 — "Which character did I vibe with most?"

UC-U3 — "Which creators do I actually follow / spend time with?"

UC-U4 — "Am I actually using the model I think I'm using?"

UC-U5 — "When do I chat? Should I cut back?"

UC-U6 — "Show me proof the platform actually does charts before I pay"

UC-U7 — "Are my conversations actually long enough that the AI is summarizing them?"

UC-U8 — "What's my streak?"

UC-U9 — "How much have I written?"

UC-U10 — "You haven't chatted with [character] in a while."

UC-U11 — "Which of my personas do I actually use?"

UC-U12 — "What themes do I actually gravitate to?"

UC-U13 — "Which conversations should I pick back up?"

UC-U14 — "How often do I hit regenerate?"

Creator Analytics (Pro) — creator use cases

These are the people who have published content and pay for Pro. The unifying thread: they need to make decisions about what to build next, what to fix, and how to grow.

UC-C1 — "Which of my characters should I invest more time in?"

UC-C2 — "Is my lorebook actually being used, or is it dead weight?"

UC-C3 — "Is my custom mode actually preferred over the default?"

UC-C4 — "Should I bundle these into a package?"

UC-C5 — "Am I building a loyal audience or just getting drive-by traffic?"

UC-C6 — "When should I publish to maximize visibility?"

UC-C7 — "Which model should I optimize my prompts for?"

UC-C8 — "Who are my superfans, and what do they have in common?"

UC-C9 — "Am I growing? Show me the line going up."

UC-C10 — "Why did I lose users on this character?"

UC-C11 — "Are users having deep, sustained sessions with my characters, or short ones?"

UC-C12 — "Which of my characters / packages has the longest conversations?"

UC-C13 — "Which entity reaches the most unique users — am I going broad or deep?"

UC-C14 — "Which greeting hooks people, which one bounces them?"

UC-C15 — "Where does my character run out of steam?"

UC-C16 — "Are users coming back to this character, or is it one-and-done?"

UC-C17 — "How often do users hit regenerate on my character?"

UC-C19 — "Which genres / themes do my characters perform best in?"

Non-goals (use cases we are deliberately NOT serving)


What We Already Store

Materialized Views (snapshot stats, trigger-refreshed)

View Key Columns
mv_character_stats conversation_count, message_count, favorite_count, greeting_count
mv_user_stats public_character_count, public_mode_count, public_lorebook_count, follower_count, following_count, conversation_count
mv_mode_stats usage_count, favorite_count, sub_prompt_count, estimated_token_count
mv_lorebook_stats entry_count, favorite_count, always_on_entry_count

Time-Series Data (web_message_stats)

Column Use
user_id + created_at Messages over time (indexed: idx_web_message_stats_user_created)
character_id + created_at Per-character activity over time
provider, model Model usage breakdown
prompt_tokens, completion_tokens, total_tokens Token consumption
pipeline_duration_ms Response time trends
event_type Fresh vs. regeneration ratio
error_type Error rate tracking

Hub Statistics (vw_hub_statistics)

Platform-wide counts (public characters, modes, lorebooks, users, creators) — useful for contextualizing a creator's share of platform activity.


Dashboard Design

Route

/settings/analytics                 (tabbed: My Stats | Creator Analytics)
/creator/:id/analytics              (public analytics — future, opt-in)

Sections

1. Overview Cards (top row)

Quick-glance summary cards showing current totals from materialized views.

┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐
│  Characters  │  │    Modes     │  │  Lorebooks   │  │  Followers   │
│     12       │  │      4       │  │      3       │  │    1,280     │
│  ↑2 this mo  │  │  ↑1 this mo  │  │  — no change │  │  ↑48 this mo │
└──────────────┘  └──────────────┘  └──────────────┘  └──────────────┘

Data source: mv_user_stats (current values), delta computed from entity_changelog or snapshot comparison.

2. Activity Over Time (line chart)

Messages per day/week/month across all the creator's characters.

Messages (30d)
400 ┤
300 ┤       ╭──╮
200 ┤   ╭───╯  ╰──╮    ╭───╮
100 ┤──╯           ╰────╯   ╰──
  0 ┤
    └──────────────────────────→
     Feb 15        Mar 1      Mar 15

Data source: web_message_stats aggregated by created_at where character_id IN (creator's characters).

Query pattern:

SELECT
    date_trunc('day', created_at) AS day,
    COUNT(*) AS message_count,
    COUNT(*) FILTER (WHERE event_type = 'regenerate') AS regenerate_count
FROM web_message_stats
WHERE character_id = ANY(@CharacterIds)
  AND created_at >= @StartDate
GROUP BY 1
ORDER BY 1

3. Character Leaderboard (bar chart / table)

Ranked list of the creator's characters by engagement.

Character Performance (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Elara the Narrator       ████████████████ 2,340 msgs   ♥ 89
Crystal Dawn Merchant    ████████         1,120 msgs   ♥ 42
Tavern Keeper Bob        ████              580 msgs   ♥ 23

Data source: mv_character_stats for totals, web_message_stats for period-filtered counts.

4. Model Usage Breakdown (donut/pie chart)

Which LLM models users choose when chatting with this creator's characters.

Model Usage (30d)
┌──────────────────────┐
│  claude-sonnet  48%  │
│  gpt-4o         31%  │
│  gemini-pro     15%  │
│  other           6%  │
└──────────────────────┘

Data source: web_message_stats grouped by model.

5. Favorites & Followers Trend (sparkline or line chart)

Growth of favorites and followers over time.

Data source: entity_changelog entries for follow/favorite events, or a new daily snapshot table (see New Data Needed).

6. Entity Usage Breakdown (table with sparklines)

Not just characters — which modes and lorebooks are being used in conversations with the creator's content.

Entity Usage (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Entity                    Type       Messages   Users   Trend
Fantasy RPG Mode          Mode       4,280      189     ↗ +12%
Elara the Narrator        Character  2,340      142     → flat
Standard Chat Mode        Mode       1,820       98     ↘ -8%
Forgotten Realms Lore     Lorebook     890       67     ↗ +22%
Crystal Dawn Merchant     Character    580       45     → flat

Why this matters to creators: "Are users actually using my RPG mode or defaulting to the standard one? Is my lorebook getting picked up?" This informs what to invest time in next.

Data source:

7. Audience Insights (anonymized cohort analysis)

The centerpiece of Creator Analytics. Creators see their audience broken into behavioral cohorts with cross-entity engagement patterns. All data is fully anonymized — see Privacy & Anonymization.

Every metric in this section answers a specific question the creator actually has:

Cohort Overview

Users are segmented based on their engagement depth with the creator's content:

Your Audience (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  ┌───────────┐  ┌───────────┐  ┌───────────┐  ┌───────────┐
  │ Power     │  │ Regular   │  │ Casual    │  │ Churned   │
  │ Users     │  │ Users     │  │ Users     │  │ Users     │
  │    23     │  │    87     │  │   312     │  │    45     │
  │ 6,420 msgs│  │ 4,180 msgs│  │ 2,890 msgs│  │  — inactive│
  │ 3.8 chars │  │ 2.1 chars │  │ 1.2 chars │  │ 1.4 chars │
  │ 92% ret.  │  │ 68% ret.  │  │ 31% ret.  │  │  0% ret.  │
  └───────────┘  └───────────┘  └───────────┘  └───────────┘

  "23 power users drive 48% of your total engagement"

Cohort definitions:

Cohort Criteria What it tells the creator
Power users >100 messages in period, active in last 7 days "These are my superfans — they drive the most engagement and are worth building for"
Regular 20–100 messages, active in last 14 days "My core audience — steady, returning users"
Casual 5–19 messages, active in last 30 days "Drive-by visitors — could I convert them to regulars?"
Churned Had activity before the period but none during it "Who am I losing and which characters were they using?"

Per-cohort metrics:

Creator question answered: "Am I building a loyal audience or just getting drive-by traffic?"

Cross-Entity Correlation Matrix

Shows how users flow between the creator's entities. If someone chats with Character A, how likely are they to also use Character B or Mode C?

Entity Overlap
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
                  Elara    Crystal   Bob     RPG Mode
Elara               —       78%      34%      82%
Crystal Dawn       78%       —       52%      61%
Tavern Bob         34%      52%       —       45%
Fantasy RPG Mode   82%      61%      45%       —

How to read: "78% of users who chat with Elara also chat with Crystal Dawn." The matrix is symmetric.

Creator questions answered:

Data source: creator_audience_daily aggregated — for each pair of entities, count users who appear in both entity's audiences and divide by the smaller audience.

Anonymized Fan Table ("Biggest Fans")

Top N users by engagement, shown with opaque identifiers. No usernames, no avatars, no profile links.

Your Biggest Fans (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Fan     Messages  Entities Used                          Active Days
#1      892       Elara, Crystal Dawn, RPG Mode, Lore    28 of 30
#2      634       Elara, Tavern Bob, Standard Mode       22 of 30
#3      451       Crystal Dawn, RPG Mode                 18 of 30
#4      387       Elara, Crystal Dawn, Tavern Bob        15 of 30
#5      244       Tavern Bob                             12 of 30

What the creator sees per fan:

Creator question answered: "Users who like THIS character also liked 3 others — what do they have in common? What should I build next?"

What the creator does NOT see: Username, avatar, profile link, email, conversation content, message content, IP address, or any other PII. The fan identifiers are session-scoped hash-based opaque IDs — even the creator can't correlate "Fan #1" across different analytics sessions.

Retention by Entity

Which entities keep users coming back vs. which lose them?

Retention by Entity (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Entity                    Week 1→2   Week 2→3   Week 3→4
Elara the Narrator          82%        78%        75%
Crystal Dawn Merchant       71%        65%        58%
Fantasy RPG Mode            88%        85%        82%
Tavern Keeper Bob           45%        28%        15%

Creator question answered: "Elara has 82% week-over-week retention, Bob has 45% — what's different? Should I rework Bob's system prompt?"

Data source: creator_audience_daily — for each entity, count users present in consecutive weeks and compute the ratio.

Peak Activity Times (Creator View)

When do users engage with the creator's content?

Audience Activity by Hour (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
      ░░▒▒▒▒░░░░░░▒▓████▓▒░░░░
      6am  9am 12pm 3pm 6pm 9pm 12am

Peak: 8 PM – 11 PM (62% of daily activity)

Creator question answered: "When should I publish new content for maximum visibility? When are my users online?"

Data source: web_message_stats.created_at bucketed by hour, filtered to the creator's character IDs.

Model Preferences by Cohort
Model Usage by Cohort (30d)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              Claude   GPT-4o   Gemini   Other
Power users    62%      22%      12%      4%
Regular        48%      31%      15%      6%
Casual         35%      38%      20%      7%

Creator question answered: "Should I optimize my system prompts for Claude or GPT? My power users prefer Claude — maybe my long system prompts work better there."


Privacy & Anonymization

Creator analytics show engagement patterns, not individual user behavior. This section defines the anonymization guarantees enforced at the server level — the client never receives identifiable user data in creator analytics responses.

Hard Rules

Rule Enforcement
No user IDs The creator analytics API endpoints never return user_id, username, avatar_url, email, or any user profile fields. The server strips these before serialization.
No conversation content Analytics show message counts, not message text. The creator never sees what users said.
Opaque fan identifiers The "Biggest Fans" table uses session-scoped hash-based IDs (HMAC(user_id, session_salt)). A different salt is generated per API call, so "Fan #1" in one session is not the same as "Fan #1" in another.
Minimum cohort size Cohort metrics are only shown when the cohort has ≥5 users. A cohort of 1–4 users is merged into the next larger cohort to prevent singling out individuals.
Date rounding "First seen" and "Last active" dates in the fan table are rounded to the nearest week to reduce re-identification risk.
No cross-creator leakage A creator only sees engagement with their own entities. They cannot see which other creators their audience engages with.

Server-Side Enforcement

// The creator analytics response types NEVER include user identification fields.
// This is enforced by the DTO design — there is no UserName or UserId property to accidentally populate.

public record CohortSummary(
    string CohortName,
    int UserCount,          // aggregate only
    int TotalMessages,
    decimal AvgMessagesPerUser,
    decimal AvgEntitiesUsed,
    decimal RetentionRate,
    string TopModel
);

public record AnonymizedFan(
    string OpaqueId,        // HMAC(user_id, session_salt) — not stable across sessions
    int MessageCount,
    string[] EntitiesUsed,  // entity names only — no entity IDs
    int ActiveDays,
    string FirstSeenWeek,   // "2026-W09" — week granularity, not date
    string LastActiveWeek
);

Why This Level of Anonymization

Privacy Acceptance Criteria

UC-C8 (anonymized fans) and UC-C5 (cohorts) are the privacy-critical surfaces of this entire feature. Before the Phase 3 audience tab ships, the following must all have passing tests:

These tests live in EchoOfDreams.Database.Tests (for the SQL functions) and in the relevant ServerAPI test project (for the endpoint responses). They are blocking acceptance criteria for the Phase 3 release, not nice-to-haves.


Operational Policies

Cross-cutting concerns that apply uniformly across the analytics endpoints. Decided up-front so PR reviews don't relitigate.

Caching policy (per-endpoint)

Different endpoints have different freshness needs and query costs. Don't apply a single TTL to the whole feature.

Endpoint Cache-Control Rationale
GET /api/stats/{metric} (User scope) private, max-age=60, must-revalidate Per-user data; user expects same numbers within the minute
GET /api/creator/stats/{metric} (Creator scope) private, max-age=300, must-revalidate Creator-side aggregates change slowly; 5 min is fine
GET /api/analytics/my-stats private, max-age=60, must-revalidate Same as user-scope generic
GET /api/analytics/creator private, max-age=300, must-revalidate Same as creator-scope generic
GET /api/analytics/creator/audience private, max-age=900, must-revalidate Heaviest endpoint (cohort assignment + correlation matrix); 15 min cache prevents repeated re-computation when a creator stares at the page
GET /api/analytics/creator/entity/{type}/{uuid} private, max-age=300, must-revalidate Per-entity drill-down; matches the parent creator endpoint

All responses include Vary: Authorization because cache state must not leak across users. All private because no analytics response is shareable across viewers.

Rate limiting policy

Lower than the profile-page limits because the queries are heavier and each call composes multiple aggregations. Per authenticated user, not per IP (analytics is auth-required).

Endpoint group Limit
/api/stats/*, /api/creator/stats/* 30 calls / minute, 600 / hour
/api/analytics/my-stats, /api/analytics/creator 20 calls / minute, 300 / hour
/api/analytics/creator/audience, /api/analytics/creator/entity/* 10 calls / minute, 120 / hour

Exceeding the limit returns 429 Too Many Requests with the standard retry-after header. The frontend should debounce filter changes (250 ms default) so a user dragging a date slider doesn't burn through their budget.

Pro gate enforcement

The Pro gate is server-enforced as the last line of defense, not trusted to the frontend. The frontend's job is to never send a Free user to a Pro endpoint in normal flow; the server's job is to refuse the request anyway.

Data retention

Table Retention Rationale
web_message_stats Existing platform retention (TBD, set elsewhere) Source of truth; out of scope for this feature
web_summary_stats Existing platform retention Same
creator_daily_stats Indefinite One row per creator per day. At a realistic platform size of 10k creators × 5 years = 18M rows — small. Indefinite retention enables long-horizon trend charts (UC-C9). Revisit only if storage costs become material, which won't happen in the foreseeable future given the platform's current ~50 days of accumulated data.
creator_audience_daily 90 days Already specified. Larger table (creator × audience-user × day), retention bounds growth. Cohort window of 90 days is operationally meaningful.

Empty-state policy

A unified, simple copy convention. Don't bikeshed individual empty states per UC; pick one of two and apply consistently.

Condition Copy Component
User has zero conversations / messages "Chat to see your stats." EmptyState + Button → /browse
Creator has zero published content "Publish content to see how it performs." EmptyState + Button → /creator
Selected period has no data (but historical data exists) "Nothing to show for this period." EmptyState (no CTA)
Anonymizer wiped all cohorts (every cohort < 5) "Not enough audience activity yet." EmptyState (no CTA)
Snapshot job hasn't run yet (Day-1) "Stats will appear here tomorrow." EmptyState (no CTA)

Per-UC ad-hoc copy is forbidden — drift across 30+ UCs becomes unmanageable. If a future UC genuinely needs different wording, extend this table, don't bypass it.

Deferred — design decisions intentionally not made


Two Tiers: My Stats (Free) vs. Creator Stats (Pro)

The analytics page serves two audiences with the same UI framework. Free users get a genuinely useful personal stats dashboard — their own chat activity visualized in real charts. This isn't a crippled preview; it's a complete product that happens to make the creator-tier upsell feel natural because users already love the charts.

Free Tier: "My Stats"

Every user gets a full personal analytics dashboard showing their own chat activity. Real charts, real data, no blurring.

┌─ My Stats ───────────────────────────────────────────────────────┐
│                                                                   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │  Messages     │  │ Conversations│  │  Characters  │           │
│  │    1,842      │  │      23      │  │    Chatted   │           │
│  │  ↑124 this wk │  │  ↑3 this wk  │  │      14      │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
│                                                                   │
│  ┌─ Daily Activity (30d) ──────────────────────────────────┐     │
│  │  40 ┤       ╭╮                                           │     │
│  │  30 ┤   ╭───╯╰──╮    ╭───╮                              │     │
│  │  20 ┤──╯         ╰────╯   ╰──                           │     │
│  │  10 ┤                                                    │     │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
│  ┌─ Most Chatted Characters ───────────────────────────────┐     │
│  │  Elara the Narrator       ████████████████  312 msgs     │     │
│  │  Crystal Dawn Merchant    ████████          180 msgs     │     │
│  │  Tavern Keeper Bob        ████               92 msgs     │     │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
│  ┌─ Favorite Creators ─────────────────────────────────────┐     │
│  │  WorldBuilder42           ████████████████  492 msgs     │     │
│  │  NightfallStories         ████████          201 msgs     │     │
│  │  RuneMaster               ████               88 msgs     │     │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
│  ┌─ Model Usage ──────────────────────────────────────────┐      │
│  │  claude-sonnet-4-6        ████████████████  48%          │      │
│  │  gpt-4o                   ████████          31%          │      │
│  │  gemini-2.5-flash         ████              15%          │      │
│  │  other                    ██                 6%          │      │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
│  ┌─ Activity Insights ────────────────────────────────────┐      │
│  │                                                          │      │
│  │  When you chat          Activity Heatmap (4 weeks)       │      │
│  │  ┌──────────────┐      ┌─────────────────────────────┐  │      │
│  │  │ Peak hours:  │      │ Mon ░░░░▒▒░░░░░░▓▓██░░░░░░ │  │      │
│  │  │ 10 PM – 1 AM│      │ Tue ░░░░▒░░░░░░░▒▓██▒░░░░░ │  │      │
│  │  │              │      │ Wed ░░░░░░░░░░░░░▒▓█▓░░░░░ │  │      │
│  │  │ Busiest day: │      │ Thu ░░░░▒▒░░░░░░▓███▓░░░░░ │  │      │
│  │  │ Thursday     │      │ Fri ░░░░░░░░░░░░▒▓██░░░░░░ │  │      │
│  │  │              │      │ Sat ░░░░░░░░░▒▓████▓▒░░░░░ │  │      │
│  │  │ This week:   │      │ Sun ░░░░░░░░▒▓████▓▒░░░░░░ │  │      │
│  │  │ 42 msgs/day  │      │     6a  9a 12p 3p 6p 9p 12a│  │      │
│  │  │ ~3.2 hrs     │      └─────────────────────────────┘  │      │
│  │  └──────────────┘                                        │      │
│  │                                                          │      │
│  │  ┌── Session Stats (30d) ─────────────────────────────┐ │      │
│  │  │ Avg session: 28 min │ Longest: 3h 12m │ Total: 47h│ │      │
│  │  └────────────────────────────────────────────────────┘ │      │
│  │                                                          │      │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐     │
│  │  📊 Want to see how YOUR content performs?                │     │
│  │  Creator Analytics shows engagement, favorites, follower │     │
│  │  growth, and model usage across your published content.  │     │
│  │                              [ Upgrade to Pro → ]        │     │
│  └──────────────────────────────────────────────────────────┘     │
│                                                                   │
└───────────────────────────────────────────────────────────────────┘

Free tier sections:

Section Chart Type Data Source
Overview cards Stat cards with deltas web_message_stats aggregated by user_id
Daily activity Line chart (messages per day) web_message_stats WHERE user_id = @UserId
Most chatted characters Horizontal bar chart web_message_stats grouped by character_id, top 10
Favorite creators Horizontal bar chart web_message_stats → characters.created_by_user_id, grouped by creator, top 10
Model usage Horizontal bar chart web_message_stats grouped by model, top 10
Activity heatmap Day × hour grid (GitHub-style) web_message_stats.created_at bucketed by EXTRACT(dow) × EXTRACT(hour)
Peak hours & busiest day Text callouts Derived from heatmap aggregation — highest hour range and highest day
Session stats Stat cards web_message_stats.created_at with >30 min gap = new session boundary. Avg/longest/total session time.

All queries filter on user_id using the existing idx_web_message_stats_user_created index. No new tables needed — this is purely a read view over web_message_stats.

Model Usage Details

Which LLM models the user chats with most. Shown as a horizontal bar chart with percentages.

Data source: web_message_stats grouped by model where user_id = @UserId.

SELECT model, COUNT(*) AS count
FROM web_message_stats
WHERE user_id = @UserId AND created_at >= @StartDate
GROUP BY model
ORDER BY count DESC
LIMIT 10

Activity Insights (Time Ranges & Screen Time)

A "digital wellbeing" style section that shows when and how much the user chats. Framed as informational and fun — "Your busiest day was Thursday" not "You spent too much time."

Activity heatmap: A day-of-week × hour-of-day grid (7 rows × 24 columns) showing message density over the selected period. Each cell is shaded by message count — like GitHub's contribution graph, rotated.

SELECT
    EXTRACT(dow FROM created_at)::int AS day_of_week,   -- 0=Sun, 6=Sat
    EXTRACT(hour FROM created_at)::int AS hour,          -- 0-23
    COUNT(*) AS message_count
FROM web_message_stats
WHERE user_id = @UserId AND created_at >= @StartDate
GROUP BY 1, 2

Peak hours: Derived from the heatmap — find the contiguous 3-hour window with the most messages. Displayed as "You're most active between 10 PM – 1 AM."

Busiest day: The day of the week with the highest total. "Your busiest day is Thursday."

Session estimation: Sessions are derived from message timestamps — a gap of >30 minutes between consecutive messages starts a new session. This is an approximation (the user may be reading, not sending) but good enough for self-reflection.

-- Session detection uses a window function on the user's messages
WITH ordered AS (
    SELECT created_at,
           LAG(created_at) OVER (ORDER BY created_at) AS prev_at
    FROM web_message_stats
    WHERE user_id = @UserId AND created_at >= @StartDate
),
sessions AS (
    SELECT created_at,
           SUM(CASE WHEN prev_at IS NULL OR created_at - prev_at > INTERVAL '30 minutes' THEN 1 ELSE 0 END)
               OVER (ORDER BY created_at) AS session_id
    FROM ordered
)
SELECT
    session_id,
    MIN(created_at) AS session_start,
    MAX(created_at) AS session_end,
    MAX(created_at) - MIN(created_at) AS session_duration,
    COUNT(*) AS message_count
FROM sessions
GROUP BY session_id

Session stat cards:

Tone: The UI copy is lighthearted and self-aware. The header could be "Your Chat Habits" with a subtext like "Because someone was going to count eventually." No judgment — just data.

Why this works as an upsell funnel: Users see polished, interactive charts of their own activity. At the bottom, a non-intrusive banner says "Want to see how YOUR content performs?" — a natural next step, not a paywall. The charting components (line chart, bar chart, cards) are the exact same ones the Pro tier uses, so the user already knows what creator analytics will look like.

Pro Tier: "Creator Analytics"

Pro users see everything from the free tier plus the creator-focused sections from the Dashboard Design above:

Section Free Pro
Overview cards (personal) Yes (with deltas) Yes
Daily activity (personal) Yes Yes
Most chatted characters Yes Yes
Favorite creators Yes Yes
Model usage (personal) Yes Yes
Activity insights (heatmap, sessions) Yes Yes
Creator overview cards — Followers, favorites, published content counts with deltas
Content activity chart — Messages across creator's characters over time
Entity usage breakdown — Characters + modes + lorebooks ranked by engagement
Character leaderboard — Ranked table of creator's characters by engagement
Model usage by audience — Donut chart of which models users choose for creator's content
Follower/favorite trends — Line chart from creator_daily_stats
Audience cohort overview — Power / Regular / Casual / Churned segmentation with metrics
Cross-entity correlation — Matrix showing user overlap between creator's entities
Biggest fans (anonymized) — Top N fans by engagement with opaque IDs, entities used, active days
Retention by entity — Week-over-week retention per character/mode
Audience peak times — When the creator's audience is most active
Model preferences by cohort — Which models each cohort prefers
CSV export — Download stats data

The page is organized into two tab groups: My Activity (free) and Creator Analytics (Pro). Free users see the Creator Analytics tab but it shows the upsell banner instead of charts.

Subscription Limit Key

-- Add to subscription_tier_limits seed data
INSERT INTO subscription_tier_limits (tier_id, limit_key, limit_value, category, display_name, description)
VALUES
    ((SELECT id FROM subscription_tiers WHERE name = 'free'), 'analytics.dashboard', 'user', 'Analytics', 'Analytics', 'Personal chat stats and activity charts'),
    ((SELECT id FROM subscription_tiers WHERE name = 'pro'), 'analytics.dashboard', 'full', 'Analytics', 'Analytics', 'Personal stats + creator analytics, trends, and export');

Application-side check:

var level = await connection.QueryFirstAsync<string?>(
    "SELECT fn_get_user_subscription_limit(@UserId, @Key)",
    new { UserId = userId, Key = "analytics.dashboard" });

// level: "user" = personal stats only, "full" = personal + creator analytics

New Data Needed

Daily Stats Snapshots

The materialized views give current values but not history. To show trends (follower growth, favorite growth over time), we need daily snapshots.

CREATE TABLE creator_daily_stats (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    snapshot_date DATE NOT NULL DEFAULT CURRENT_DATE,

    -- From mv_user_stats
    public_character_count INTEGER NOT NULL DEFAULT 0,
    public_mode_count INTEGER NOT NULL DEFAULT 0,
    public_lorebook_count INTEGER NOT NULL DEFAULT 0,
    follower_count INTEGER NOT NULL DEFAULT 0,

    -- Aggregated from mv_character_stats for this user's characters
    total_conversation_count INTEGER NOT NULL DEFAULT 0,
    total_message_count INTEGER NOT NULL DEFAULT 0,
    total_favorite_count INTEGER NOT NULL DEFAULT 0,

    UNIQUE(user_id, snapshot_date)
);

CREATE INDEX idx_creator_daily_stats_user_date
    ON creator_daily_stats (user_id, snapshot_date DESC);

COMMENT ON TABLE creator_daily_stats IS 'Daily snapshot of creator statistics for trend charts. Populated by a scheduled job.';

Population: A scheduled function (cron or Railway scheduled task) runs once daily:

CREATE OR REPLACE FUNCTION fn_snapshot_creator_daily_stats()
RETURNS INTEGER AS $$
DECLARE
    v_count INTEGER;
BEGIN
    INSERT INTO creator_daily_stats (
        user_id, snapshot_date,
        public_character_count, public_mode_count, public_lorebook_count,
        follower_count, total_conversation_count, total_message_count, total_favorite_count
    )
    SELECT
        us.user_id,
        CURRENT_DATE,
        us.public_character_count,
        us.public_mode_count,
        us.public_lorebook_count,
        us.follower_count,
        us.conversation_count,
        COALESCE(msg.total, 0),
        COALESCE(fav.total, 0)
    FROM mv_user_stats us
    LEFT JOIN LATERAL (
        SELECT SUM(cs.message_count) AS total
        FROM mv_character_stats cs
        JOIN characters c ON c.id = cs.character_id
        WHERE c.created_by_user_id = us.user_id AND c.is_deleted = FALSE
    ) msg ON TRUE
    LEFT JOIN LATERAL (
        SELECT SUM(cs.favorite_count) AS total
        FROM mv_character_stats cs
        JOIN characters c ON c.id = cs.character_id
        WHERE c.created_by_user_id = us.user_id AND c.is_deleted = FALSE
    ) fav ON TRUE
    ON CONFLICT (user_id, snapshot_date) DO UPDATE SET
        public_character_count = EXCLUDED.public_character_count,
        public_mode_count = EXCLUDED.public_mode_count,
        public_lorebook_count = EXCLUDED.public_lorebook_count,
        follower_count = EXCLUDED.follower_count,
        total_conversation_count = EXCLUDED.total_conversation_count,
        total_message_count = EXCLUDED.total_message_count,
        total_favorite_count = EXCLUDED.total_favorite_count;

    GET DIAGNOSTICS v_count = ROW_COUNT;
    RETURN v_count;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION fn_snapshot_creator_daily_stats IS 'Takes a daily snapshot of all creator statistics. Idempotent — safe to run multiple times per day.';

Audience Daily Aggregates

Per-user-per-creator daily activity, used to compute cohorts, cross-entity overlap, and the anonymized fan table. This table is internal only — never exposed to creators directly. The server reads it, computes aggregates, and returns anonymized results.

CREATE TABLE creator_audience_daily (
    creator_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    audience_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    snapshot_date DATE NOT NULL DEFAULT CURRENT_DATE,

    message_count INTEGER NOT NULL DEFAULT 0,
    character_ids INTEGER[] NOT NULL DEFAULT '{}',   -- which of creator's characters were used
    mode_ids INTEGER[] NOT NULL DEFAULT '{}',        -- which modes were used
    models_used TEXT[] NOT NULL DEFAULT '{}',         -- which LLM models were used

    PRIMARY KEY (creator_user_id, audience_user_id, snapshot_date)
);

CREATE INDEX idx_creator_audience_daily_creator_date
    ON creator_audience_daily (creator_user_id, snapshot_date DESC);

CREATE INDEX idx_creator_audience_daily_audience
    ON creator_audience_daily (audience_user_id, snapshot_date DESC);

COMMENT ON TABLE creator_audience_daily IS
    'Per-user-per-creator daily engagement aggregates. Internal only — used for cohort computation, '
    'never returned to creators. Populated by fn_snapshot_creator_audience_daily.';

Population: Runs daily alongside fn_snapshot_creator_daily_stats:

CREATE OR REPLACE FUNCTION fn_snapshot_creator_audience_daily()
RETURNS INTEGER AS $$
DECLARE
    v_count INTEGER;
BEGIN
    INSERT INTO creator_audience_daily (
        creator_user_id, audience_user_id, snapshot_date,
        message_count, character_ids, mode_ids, models_used
    )
    SELECT
        c.created_by_user_id AS creator_user_id,
        ms.user_id AS audience_user_id,
        CURRENT_DATE,
        COUNT(*) AS message_count,
        ARRAY_AGG(DISTINCT ms.character_id) FILTER (WHERE ms.character_id IS NOT NULL),
        ARRAY_AGG(DISTINCT ms.mode_id) FILTER (WHERE ms.mode_id IS NOT NULL),
        ARRAY_AGG(DISTINCT ms.model) FILTER (WHERE ms.model IS NOT NULL)
    FROM web_message_stats ms
    JOIN characters c ON c.id = ms.character_id AND c.is_deleted = FALSE
    WHERE ms.created_at >= CURRENT_DATE
      AND ms.created_at < CURRENT_DATE + INTERVAL '1 day'
      AND c.created_by_user_id != ms.user_id   -- exclude creator chatting with their own characters
    GROUP BY c.created_by_user_id, ms.user_id
    ON CONFLICT (creator_user_id, audience_user_id, snapshot_date) DO UPDATE SET
        message_count = EXCLUDED.message_count,
        character_ids = EXCLUDED.character_ids,
        mode_ids = EXCLUDED.mode_ids,
        models_used = EXCLUDED.models_used;

    GET DIAGNOSTICS v_count = ROW_COUNT;
    RETURN v_count;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION fn_snapshot_creator_audience_daily IS
    'Snapshots per-user engagement with each creator''s content. Excludes self-usage. Idempotent.';

Retention policy: creator_audience_daily rows older than 90 days are pruned by a weekly cleanup job. This bounds storage growth and limits the analytics window to a meaningful timeframe.

Cohort Computation

Cohorts are computed server-side on the fly from creator_audience_daily — there is no separate cohort table. The query aggregates the daily rows for the requested period:

-- Cohort assignment for a creator's audience over a 30-day period
WITH audience AS (
    SELECT
        audience_user_id,
        SUM(message_count) AS total_messages,
        COUNT(DISTINCT snapshot_date) AS active_days,
        MAX(snapshot_date) AS last_active,
        -- Flatten arrays across days
        ARRAY(SELECT DISTINCT unnest(array_agg_cat(character_ids))) AS all_character_ids
    FROM creator_audience_daily
    WHERE creator_user_id = @CreatorId
      AND snapshot_date >= @StartDate
    GROUP BY audience_user_id
)
SELECT
    CASE
        WHEN total_messages > 100 AND last_active >= CURRENT_DATE - INTERVAL '7 days' THEN 'power'
        WHEN total_messages BETWEEN 20 AND 100 AND last_active >= CURRENT_DATE - INTERVAL '14 days' THEN 'regular'
        WHEN total_messages BETWEEN 5 AND 19 AND last_active >= CURRENT_DATE - INTERVAL '30 days' THEN 'casual'
        ELSE 'churned'
    END AS cohort,
    COUNT(*) AS user_count,
    SUM(total_messages) AS total_messages,
    AVG(total_messages)::numeric(10,1) AS avg_messages,
    AVG(array_length(all_character_ids, 1))::numeric(10,1) AS avg_entities_used
FROM audience
GROUP BY 1

Note: array_agg_cat is a custom aggregate that concatenates arrays — a utility function in the migration.


API

Endpoints

GET /api/analytics/my-stats                         # Personal shaped sections (all users)
GET /api/analytics/creator                          # Creator shaped sections (Pro only)
GET /api/analytics/creator/audience                  # Audience cohorts + fans + correlation (Pro only)
GET /api/analytics/creator/entity/{entityType}/{uuid}  # Entity drill-down (Pro only)

All authenticated. /my-stats returns the requesting user's own shaped sections (overview deltas, heatmap, sessions). /creator returns the creator's shaped sections (overview deltas, entity usage breakdown, leaderboard). /creator/audience returns the anonymized audience insights (cohorts, fans, correlation matrix). Time-series charts on these pages are fetched separately through the generic stats endpoints.

Response: /api/analytics/my-stats (all users)

{
  "overview": {
    "messagesSent": { "count": 1842, "delta": 124 },
    "conversations": { "count": 23, "delta": 3 },
    "charactersUsed": { "count": 14, "delta": 2 }
  },
  "dailyActivity": {
    "period": "30d",
    "dataPoints": [
      { "date": "2026-02-15", "messages": 38, "regenerations": 3 },
      { "date": "2026-02-16", "messages": 42, "regenerations": 1 }
    ]
  },
  "mostChattedCharacters": [
    { "characterUuid": "a1b2...", "name": "Elara the Narrator", "avatarUrl": "...", "creatorName": "WorldBuilder42", "messages": 312 },
    { "characterUuid": "c3d4...", "name": "Crystal Dawn Merchant", "avatarUrl": "...", "creatorName": "WorldBuilder42", "messages": 180 }
  ],
  "favoriteCreators": [
    { "creatorSlug": "worldbuilder42", "name": "WorldBuilder42", "avatarUrl": "...", "messages": 492, "charactersUsed": 4 },
    { "creatorSlug": "nightfallstories", "name": "NightfallStories", "avatarUrl": "...", "messages": 201, "charactersUsed": 2 }
  ],
  "modelUsage": [
    { "model": "claude-sonnet-4-6", "count": 884, "percentage": 48 },
    { "model": "gpt-4o", "count": 571, "percentage": 31 },
    { "model": "gemini-2.5-flash", "count": 276, "percentage": 15 },
    { "model": "other", "count": 111, "percentage": 6 }
  ],
  "activityInsights": {
    "heatmap": [
      { "dayOfWeek": 0, "hour": 22, "count": 48 },
      { "dayOfWeek": 0, "hour": 23, "count": 52 },
      { "dayOfWeek": 4, "hour": 21, "count": 61 }
    ],
    "peakHours": { "start": 22, "end": 1, "label": "10 PM – 1 AM" },
    "busiestDay": { "dayOfWeek": 4, "label": "Thursday" },
    "sessions": {
      "avgDurationMinutes": 28,
      "longestDurationMinutes": 192,
      "totalHours": 47,
      "countThisWeek": 14
    },
    "avgMessagesPerDay": 42
  }
}

Response: /api/analytics/creator (Pro only)

{
  "creatorOverview": {
    "publishedCharacters": { "count": 12, "delta": 2 },
    "publishedModes": { "count": 4, "delta": 1 },
    "publishedLorebooks": { "count": 3, "delta": 0 },
    "followers": { "count": 1280, "delta": 48 },
    "totalFavorites": { "count": 342, "delta": 19 },
    "totalMessages": { "count": 18420, "delta": 1830 }
  },
  "contentActivity": {
    "period": "30d",
    "dataPoints": [
      { "date": "2026-02-15", "messages": 142, "regenerations": 12 },
      { "date": "2026-02-16", "messages": 168, "regenerations": 8 }
    ]
  },
  "entityUsage": [
    { "entityType": "mode", "name": "Fantasy RPG Mode", "uuid": "...", "messages": 4280, "users": 189, "trend": 12.5 },
    { "entityType": "character", "name": "Elara the Narrator", "uuid": "...", "messages": 2340, "users": 142, "trend": 0.2 },
    { "entityType": "lorebook", "name": "Forgotten Realms Lore", "uuid": "...", "messages": 890, "users": 67, "trend": 22.1 }
  ],
  "characterLeaderboard": [
    { "characterUuid": "a1b2...", "name": "Elara the Narrator", "avatarUrl": "...", "messages": 2340, "conversations": 189, "favorites": 89 }
  ],
  "modelUsage": [
    { "model": "claude-sonnet-4-6", "count": 4820, "percentage": 48 },
    { "model": "gpt-4o", "count": 3100, "percentage": 31 }
  ],
  "followerTrend": {
    "period": "30d",
    "dataPoints": [
      { "date": "2026-02-15", "followers": 1232 },
      { "date": "2026-02-16", "followers": 1235 }
    ]
  },
  "audiencePeakHours": {
    "hourlyDistribution": [
      { "hour": 20, "percentage": 18 },
      { "hour": 21, "percentage": 22 },
      { "hour": 22, "percentage": 22 }
    ],
    "peakLabel": "8 PM – 11 PM (62% of daily activity)"
  }
}

Response: /api/analytics/creator/audience (Pro only)

Separate endpoint for the heavy audience analytics — called on demand when the creator opens the Audience tab.

{
  "cohorts": [
    { "name": "power", "userCount": 23, "totalMessages": 6420, "avgMessagesPerUser": 279.1, "avgEntitiesUsed": 3.8, "retentionRate": 0.92, "topModel": "claude-sonnet-4-6" },
    { "name": "regular", "userCount": 87, "totalMessages": 4180, "avgMessagesPerUser": 48.0, "avgEntitiesUsed": 2.1, "retentionRate": 0.68, "topModel": "claude-sonnet-4-6" },
    { "name": "casual", "userCount": 312, "totalMessages": 2890, "avgMessagesPerUser": 9.3, "avgEntitiesUsed": 1.2, "retentionRate": 0.31, "topModel": "gpt-4o" },
    { "name": "churned", "userCount": 45, "totalMessages": 0, "avgMessagesPerUser": 0, "avgEntitiesUsed": 1.4, "retentionRate": 0, "topModel": null }
  ],
  "topFans": [
    { "opaqueId": "Fan #1", "messageCount": 892, "entitiesUsed": ["Elara", "Crystal Dawn", "RPG Mode", "Forgotten Realms Lore"], "activeDays": 28, "firstSeenWeek": "2026-W05", "lastActiveWeek": "2026-W13" },
    { "opaqueId": "Fan #2", "messageCount": 634, "entitiesUsed": ["Elara", "Tavern Bob", "Standard Mode"], "activeDays": 22, "firstSeenWeek": "2026-W07", "lastActiveWeek": "2026-W13" }
  ],
  "entityCorrelation": {
    "entities": ["Elara", "Crystal Dawn", "Tavern Bob", "RPG Mode"],
    "matrix": [
      [1.0, 0.78, 0.34, 0.82],
      [0.78, 1.0, 0.52, 0.61],
      [0.34, 0.52, 1.0, 0.45],
      [0.82, 0.61, 0.45, 1.0]
    ]
  },
  "retentionByEntity": [
    { "name": "Elara the Narrator", "entityType": "character", "week1to2": 0.82, "week2to3": 0.78, "week3to4": 0.75 },
    { "name": "Fantasy RPG Mode", "entityType": "mode", "week1to2": 0.88, "week2to3": 0.85, "week3to4": 0.82 },
    { "name": "Tavern Keeper Bob", "entityType": "character", "week1to2": 0.45, "week2to3": 0.28, "week3to4": 0.15 }
  ],
  "modelByCohort": [
    { "cohort": "power", "models": [{ "model": "claude-sonnet-4-6", "percentage": 62 }, { "model": "gpt-4o", "percentage": 22 }] },
    { "cohort": "regular", "models": [{ "model": "claude-sonnet-4-6", "percentage": 48 }, { "model": "gpt-4o", "percentage": 31 }] },
    { "cohort": "casual", "models": [{ "model": "gpt-4o", "percentage": 38 }, { "model": "claude-sonnet-4-6", "percentage": 35 }] }
  ]
}

A caller without Creator insights on gets an empty-body 403 from /api/analytics/creator* and /api/creator/stats/{metric} ("fence, not signpost" — no upgrade body was ever sent). The tabs read that 403 and show the Turn on Creator insights card; the server is the only place the answer is decided.


Client Implementation

Shared component dependencies

Every chart, card, and row in this design uses a shared primitive. Before building anything in clientConsole/src/pages/settings/analytics/, check the table below. This is the canonical reuse map — adding a custom component (or a custom CSS-in-JS card style) requires justifying why none of these worked.

Already shipped — use directly

These live in @shared/components (and @shared/components/common/stats/ for the chart subsystem) today. No promotion needed.

Shared primitive UCs that consume it
TimeSeriesChart UC-U1, UC-U4, UC-U7, UC-C1, UC-C7, UC-C9, UC-C11, UC-C17 trends
StatsFilterBar Top-of-page date/granularity selector for both tabs
useStatsQuery Every generic-stack consumer
chartTheme (chartColors, chartAxis, chartTooltip, formatCompact, formatMs, formatBucketLabel, seriesColor) All chart styling — do not invent new color palettes
sumStatsResponse, sumSeriesByKey Period totals for overview cards / leaderboards
TabbedLayout Top-level My Stats / Creator / Audience tabs
Tabs Sub-tab switchers (e.g. "by category" in UC-U12 / UC-C19)
Card Every panel wrapper
Section (+ InfoSection, WarningSection) Empty states, anonymization disclosures, "tracking starts here" notices on UC-C18
EmptyState Day-0 state, Pro-gated tab empty states for Free users
Button (incl. iconOnly — never IconButton) Refresh, Export CSV, Resume conversation (UC-U13), Upgrade to Pro
Avatar Character / creator / persona avatars in every list-shaped UC
Badge Cohort labels (UC-C5), tier indicators, draft/state markers
ProBadge, ProPreviewNote UC-U6 conversion banner, Free-vs-Pro comparison, every Pro-tab empty state
ProgressBar Bar fills inside entity-usage rows, drop-off curve cells
LoadingSpinner, LoadingOverlay Initial query loads
MiniPagination Top-N+ pagination on leaderboards, biggest-fans table
MemberRow (extend it — don't replace it) UC-U2, UC-U3, UC-U10, UC-U13, UC-C1 leaderboard — avatar + title + secondary + value rows
RecentActivity (reference design) UC-U13 paused conversations — closest existing pattern; reuse if it fits, mirror its layout if it doesn't

Promote from local to shared before clientConsole work begins

The AdminConsole already has these as local components and the analytics design proposes the exact same patterns. Don't duplicate — promote.

Currently Should become
adminConsole/src/components/statistics/ChartCard.tsx (local) shared/src/components/common/stats/ChartCard.tsx
StatSummary (local, in same file as ChartCard) shared/src/components/common/stats/StatSummary.tsx (or merge into the new StatCard below)

Both are ~90 lines of CSS-in-JS that admin and clientConsole would otherwise re-implement. Do this before clientConsole analytics lands — two copies of the same component drift apart fast.

Build new in shared/src/components/common/stats/

Each is referenced by multiple UCs across both tiers. Build once, add a showcase entry, reuse forever.

New shared component Used by Notes
StatCard (with optional delta) UC-U1 overview, UC-U8 streak, UC-U9 word count, UC-U14 regen rate, UC-C9 creator overview Big number + label + optional delta (+12 ↑) + optional secondary line. Could replace StatSummary entirely if designed flexibly enough.
HorizontalBarChart UC-U2, UC-U3, UC-U4 (alt view), UC-U11, UC-U12, UC-C1 leaderboard, UC-C13, UC-C19 Avatar/icon prefix + label + bar + value. The most-reused chart shape in the entire design. Recharts wrapper.
Heatmap UC-U5 user heatmap, UC-C6 audience peak hours Day × hour 7×24 grid. Same component, two scopes. Cell-shading scale + tooltip.
CorrelationMatrix UC-C4 entity overlap Symmetric matrix, color-scaled cells, axis labels. Borderline whether shared — keep shared so the showcase forces a clean API.

Try-before-build

These are tempting to build but probably aren't necessary if existing components are pushed a little:

Tempting Try first
SurvivalCurve for UC-C15 Parameterize TimeSeriesChart with a custom x-axis (message number, not timestamp). Only build a new component if TimeSeriesChart's API can't be cleanly extended.
EntityRankRow for leaderboards Extend MemberRow with stat slots. Build new only if the prop surface gets unwieldy.
CreatorUpsellBanner It's Card + ProBadge + Button composed. Three primitives, not a new component.
PausedConversationCard for UC-U13 Card + Avatar + Button composed; or extend MemberRow.
New stat-panel layout component Card + StatCard × N in a grid. Don't wrap a wrap.

Forbidden

Per project conventions and reuse memory:

Component Structure

clientConsole/src/pages/settings/analytics/
├── AnalyticsPage.tsx              # Main page with tabs (My Stats | Creator | Audience)
├── my-stats/
│   ├── MyStatsTab.tsx             # Personal activity tab (all users)
│   ├── PersonalOverviewCards.tsx   # Messages sent, conversations, characters used
│   ├── DailyActivityChart.tsx     # Personal messages per day
│   ├── MostChattedCharacters.tsx  # Bar chart of favorite characters
│   ├── FavoriteCreators.tsx       # Bar chart of most-engaged creators
│   ├── ModelUsageChart.tsx        # Bar chart of user's model usage
│   └── ActivityInsights.tsx       # Heatmap, peak hours, session stats
├── creator/
│   ├── CreatorTab.tsx             # Creator analytics tab (Pro)
│   ├── CreatorOverviewCards.tsx   # Published content, followers, favorites
│   ├── ContentActivityChart.tsx   # Messages across creator's characters
│   ├── EntityUsageTable.tsx       # Characters + modes + lorebooks ranked
│   ├── CharacterLeaderboard.tsx   # Ranked table
│   ├── AudienceModelUsage.tsx     # Donut chart of audience model choices
│   ├── FollowerTrendChart.tsx     # Follower growth line chart
│   └── AudiencePeakHours.tsx     # When the audience is active
├── audience/
│   ├── AudienceTab.tsx            # Audience insights tab (Pro)
│   ├── CohortOverview.tsx         # Power/Regular/Casual/Churned cards
│   ├── EntityCorrelation.tsx      # Cross-entity overlap matrix
│   ├── BiggestFans.tsx            # Anonymized fan table
│   ├── RetentionByEntity.tsx      # Week-over-week retention chart
│   └── ModelByCohort.tsx          # Model preferences per cohort
├── shared/
│   ├── StatCard.tsx               # Reusable stat card with delta
│   ├── HorizontalBarChart.tsx     # Reusable bar chart
│   ├── LineChart.tsx              # Reusable line chart
│   ├── Heatmap.tsx                # Day × hour grid (reused: my-stats + audience peak times)
│   └── CorrelationMatrix.tsx      # Reusable matrix/table with color-scaled cells
├── CreatorUpsellBanner.tsx        # Non-intrusive upgrade prompt
└── useAnalytics.ts                # Data fetching hooks (all endpoints)

Chart Library

Use a lightweight chart library. Candidates:

Library Size Fit
Recharts ~45 KB gzip React-native, declarative, good defaults
Chart.js + react-chartjs-2 ~60 KB gzip More chart types, canvas-based
Lightweight custom (SVG) ~5 KB Minimal, but more work

Recommendation: Recharts — aligns with the React stack, declarative API, handles responsive sizing.

Creator Upsell Banner

The upsell is a styled card at the bottom of the My Stats tab — not a blocking overlay. It sits naturally below the user's real charts.

function CreatorUpsellBanner() {
  return (
    <Card style={styles.upsellCard}>
      <h3 style={styles.heading}>Want to see how your content performs?</h3>
      <p style={styles.subtext}>
        Creator Analytics shows engagement, favorites, follower growth,
        and model usage across your published characters and content.
      </p>
      <Button variant="primary" onClick={() => navigate('/settings/subscription')}>
        Upgrade to Pro
      </Button>
    </Card>
  )
}

The Creator Analytics tab itself shows the same banner in a centered empty state if the user is on the free tier. No blurring, no fake charts — just a clean prompt explaining what they'd get. The My Stats charts they already have are the best advertisement.


Implementation Order

The phasing below is structured so each phase ships a coherent product slice. Phase 1 lands a real free product. Phase 1.5 lands a credible day-one Pro tier before Phase 2/3 commit to the heavier audience backend. Phase 2/3 are deeper investments that should only be greenlit once Pro upgrade economics support the work.

Phase 1: Foundation (4–6 weeks)

Goal: ship the free tier as a complete product, plus capture forward-only data the later phases depend on.

  1. Shared chart components — StatCard, HorizontalBarChart, LineChart, Heatmap, CorrelationMatrix (reused across all tabs).
  2. My Stats API + tab — GET /api/analytics/my-stats with all sections: overview cards, daily activity, most chatted characters, favorite creators, model usage, activity insights (heatmap + sessions), summarization depth (UC-U7), streak (UC-U8), word count (UC-U9), drifted-away (UC-U10), personas usage (UC-U11), themes (UC-U12), paused conversations (UC-U13), regen rate (UC-U14).
  3. Creator upsell banner — Non-intrusive card on My Stats tab + empty state on Creator/Audience tabs.
  4. Conversation-origin instrumentation (UC-C18 prerequisite — START NOW) — schema columns, SQL function parameters, C# repo + endpoint plumbing, frontend audit on every "start chat" call site. The dashboard panel ships in Phase 1.5; the data capture must start in Phase 1 because backfill is impossible. ~3–5 days of work, ~1 day of which is the frontend audit.
  5. Summaries metric scope expansion — add StatsScope.User and StatsScope.Creator to the summaries metric in DefaultStatsMetrics.Build() and add the corresponding p_scope = 1 / 2 branches to fn_stats_summaries. Unblocks UC-U7 and UC-C11 chart panels for both tiers.

Phase 1.5: Pro day-one offering (4–6 weeks)

Goal: ship a credible Pro tier that justifies the upgrade on day one — does not depend on the audience aggregation backend.

  1. Daily snapshot job — creator_daily_stats only — fn_snapshot_creator_daily_stats + scheduled task. Skip creator_audience_daily for now (Phase 2 dependency).
  2. Creator Analytics API + tab — Pro gate — GET /api/analytics/creator with: creator overview cards + deltas (UC-C9, UC-C1), content activity chart (UC-C1 reusing existing fn_stats_messages Creator scope), entity usage breakdown with characters / modes / lorebooks / packages columns: messages / unique users / avg msgs/convo / repeat rate / regen rate (UC-C2, UC-C3, UC-C12, UC-C13, UC-C16, UC-C17), character leaderboard (UC-C1), follower trend chart (UC-C9), audience peak hours (UC-C6), audience model donut (UC-C7).
  3. Subscription limit seed — Add analytics.dashboard to tier limits.
  4. Greeting performance panel (UC-C14) — per-character drill-down using existing web_conversations.greeting_id. No new data needed.
  5. Drop-off curve panel (UC-C15) — per-character drill-down via window-function CTE on web_message_stats.
  6. Discovery funnel panel (UC-C18 dashboard) — once data has accumulated for ~2–4 weeks since Phase 1 instrumentation lands, surface the breakdown.
  7. Genre performance panel (UC-C19) — per-category bitfield aggregation on the creator's owned characters.
  8. Entity drill-down endpoint — GET /api/analytics/creator/entity/{entityType}/{uuid} returning a per-entity composite payload (time series, conversation-length distribution for UC-C12, drop-off curve for UC-C15, greeting performance for UC-C14, summary rate for UC-C11). Click an entity row in the breakdown to open the drill-down. Endpoint contract is shared with the parent creator endpoint — it's the same shaped responses, scoped to one entity instead of all of them.

Phase 2: Audience Aggregation (4–6 weeks)

Goal: land the audience-insights backend that powers cohorts, fans, correlation, retention.

  1. creator_audience_daily table + fn_snapshot_creator_audience_daily + scheduled task + 90-day retention cleanup.
  2. array_agg_cat custom aggregate for flattening arrays across rows.
  3. Anonymization enforcement — server-side session-salted HMAC for opaque fan IDs (HashDimensionKeys policy hook in the existing anonymizer), minimum cohort size (≥5) enforcement, date rounding to ISO week.

Phase 3: Audience Insights UI (2–3 weeks)

Goal: surface the audience aggregation backend as the deepest creator tab.

  1. Audience Insights API + tab — Pro gate — GET /api/analytics/creator/audience: cohort segmentation (UC-C5), anonymized fan table (UC-C8), entity correlation matrix (UC-C4), retention by entity (UC-C10), model preferences by cohort (UC-C7 deep-dive), bundle/package recommendations.

Phase 4: CSV Export (1–2 weeks)

Goal: power creators can take data offline for external pitches, sponsorship applications, and personal records.

  1. CSV export endpoint — GET /api/analytics/creator/export?metric={key}&from=&to=&granularity= returns Content-Type: text/csv. Reuses the existing shaped-endpoint queries; serializes to CSV instead of JSON. Pro-gated. Filename pattern: eod-analytics-{metric}-{from}-{to}.csv. Anonymization rules apply equally to the export — opaque fan IDs, min-cohort suppression, no PII. The export is NOT a backdoor.
  2. Frontend export button — Button with download icon on each Pro tab; calls the export endpoint and triggers a browser download. No new component.

Phase 4 is decoupled from Phases 1–3 — the endpoints designed in earlier phases already support a CSV serializer alternative, so this is mostly serialization plumbing plus a button. Ships when the rest is stable, not before.

Future / not phased


Future Extensions