From f105bf34248b7b87dae663d0c90a1e0d75b53e5a Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:29:50 +0100 Subject: [PATCH 1/7] feat: compute spend over any window and add a cycle range Spend is estimated over any window, across billing cycles, by sharing each cycle's billed total over the usage events of the window. The 24h range is a true rolling 24 hours: the window starts exactly 24 hours ago, so events of the oldest partial hour count. It is returned hour by hour, from the hour of the cutoff to the current hour, with per-hour request counts. The stats, analytics and user APIs accept days=cycle. Co-Authored-By: Claude Sonnet 5.5 --- src/app/api/analytics/route.ts | 6 +- src/app/api/stats/route.ts | 5 +- src/app/api/users/[email]/route.ts | 5 +- src/lib/data/sqlite.ts | 424 ++++++++++++++++++----------- src/lib/data/types.ts | 2 + tests/hourly-spend.test.ts | 73 +++++ tests/rolling-24h.test.ts | 85 ++++++ tests/window-spend.test.ts | 87 ++++++ 8 files changed, 517 insertions(+), 170 deletions(-) create mode 100644 tests/hourly-spend.test.ts create mode 100644 tests/rolling-24h.test.ts create mode 100644 tests/window-spend.test.ts diff --git a/src/app/api/analytics/route.ts b/src/app/api/analytics/route.ts index 34b923e..c8929a0 100644 --- a/src/app/api/analytics/route.ts +++ b/src/app/api/analytics/route.ts @@ -12,6 +12,7 @@ import { getUsersByClientVersion, getPlanExhaustionStats, getModelEfficiency, + getCycleWindowDays, getGroupsWithMembers, getRepoAIAttribution, } from "@/lib/data"; @@ -39,7 +40,8 @@ function resolveGroupEmails(group: string): string[] | undefined { export function GET(request: Request) { const { searchParams } = new URL(request.url); - const days = parseInt(searchParams.get("days") ?? "30", 10); + const param = searchParams.get("days") ?? "30"; + const days = param === "cycle" ? getCycleWindowDays() : parseInt(param, 10) || 30; const group = searchParams.get("group") ?? "all"; const emails = resolveGroupEmails(group); @@ -56,7 +58,7 @@ export function GET(request: Request) { clientVersions: getAnalyticsClientVersionsSummary(), versionUsers: getUsersByClientVersion(), planExhaustion: getPlanExhaustionStats(emails), - modelEfficiency: getModelEfficiency(emails), + modelEfficiency: getModelEfficiency(emails, days), repoAttribution: getRepoAIAttribution(days, emails), }); } catch { diff --git a/src/app/api/stats/route.ts b/src/app/api/stats/route.ts index 5096a2d..911373c 100644 --- a/src/app/api/stats/route.ts +++ b/src/app/api/stats/route.ts @@ -5,8 +5,9 @@ export const dynamic = "force-dynamic"; export function GET(request: Request) { const url = new URL(request.url); - const days = parseInt(url.searchParams.get("days") ?? "30", 10); + const param = url.searchParams.get("days") ?? "30"; + const range = param === "cycle" ? "cycle" : parseInt(param, 10) || 30; - const dashboard = getFullDashboard(days); + const dashboard = getFullDashboard(range); return NextResponse.json(dashboard); } diff --git a/src/app/api/users/[email]/route.ts b/src/app/api/users/[email]/route.ts index a94aaff..da02f03 100644 --- a/src/app/api/users/[email]/route.ts +++ b/src/app/api/users/[email]/route.ts @@ -7,9 +7,10 @@ export function GET(request: Request, { params }: { params: Promise<{ email: str return params.then((p) => { const email = decodeURIComponent(p.email); const url = new URL(request.url); - const days = parseInt(url.searchParams.get("days") ?? "30", 10); + const param = url.searchParams.get("days") ?? "30"; + const range = param === "cycle" ? "cycle" : parseInt(param, 10) || 30; - const stats = getUserStats(email, days); + const stats = getUserStats(email, range); return NextResponse.json(stats); }); } diff --git a/src/lib/data/sqlite.ts b/src/lib/data/sqlite.ts index 3aa0c52..03aff81 100644 --- a/src/lib/data/sqlite.ts +++ b/src/lib/data/sqlite.ts @@ -959,9 +959,147 @@ export type { CycleSummaryData, }; -export function getFullDashboard(days: number = 7): FullDashboard { +export type TimeRange = number | "cycle"; + +const DAY_MS = 86_400_000; +const HOUR_MS = 3_600_000; + +function dayStart(daysAgo: number): string { + return new Date(Date.now() - daysAgo * DAY_MS).toISOString().slice(0, 10); +} + +// the 24h range measures exactly the last 24 hours... +const last24HoursStart = () => Date.now() - 24 * HOUR_MS; + +// ...and charts it one point per hour, keyed "YYYY-MM-DDTHH" (UTC), from the hour of the cutoff +// to the current hour (25 points, both ends partial) +const chartHourKeys = (sinceMs: number) => + Array.from({ length: 25 }, (_, i) => new Date(sinceMs + i * HOUR_MS).toISOString().slice(0, 13)); + +// Number of days back from today that lands on the start of the current billing cycle. +export function getCycleWindowDays(): number { + const row = getDb().prepare("SELECT MAX(cycle_start) as cs FROM spending").get() as { + cs: string | null; + }; + const start = (row?.cs ?? getMetadata("cycle_start"))?.slice(0, 10); + if (!start) return 30; + const elapsed = Date.parse(`${dayStart(0)}T00:00:00.000Z`) - Date.parse(`${start}T00:00:00.000Z`); + return Math.max(1, Math.round(elapsed / DAY_MS)); +} + +function getCycleStarts(db: Database.Database): string[] { + return ( + db.prepare("SELECT DISTINCT cycle_start FROM spending ORDER BY cycle_start").all() as Array<{ + cycle_start: string; + }> + ).map((r) => r.cycle_start); +} + +// Spend per user is billed per cycle, so a window is estimated by sharing each cycle's billed +// total across the usage events that fall inside the window. +function spendSince(db: Database.Database, sinceMs: number, hourly = false) { + const bucket = hourly + ? "strftime('%Y-%m-%dT%H', CAST(timestamp AS INTEGER) / 1000, 'unixepoch')" + : "date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch')"; + const names = new Map( + (db.prepare("SELECT email, name FROM members").all() as Array<{ email: string; name: string }>).map( + (m) => [m.email, m.name], + ), + ); + const totals = new Map(); + const daily: Array<{ date: string; email: string; name: string; spend_cents: number }> = []; + const starts = getCycleStarts(db); + const now = Date.now(); + + starts.forEach((start, i) => { + const startMs = Date.parse(`${start}T12:00:00.000Z`); + const next = starts[i + 1]; + const endMs = next ? Date.parse(`${next}T12:00:00.000Z`) : Number.MAX_SAFE_INTEGER; + if (endMs <= sinceMs) return; + + const billed = db + .prepare("SELECT email, spend_cents FROM spending WHERE cycle_start = ?") + .all(start) as Array<{ email: string; spend_cents: number }>; + const rawByUser = new Map( + ( + db + .prepare( + `SELECT user_email as email, SUM(total_cents) as t FROM usage_events + WHERE CAST(timestamp AS INTEGER) >= ? AND CAST(timestamp AS INTEGER) < ? + GROUP BY user_email`, + ) + .all(startMs, endMs) as Array<{ email: string; t: number }> + ).map((r) => [r.email, r.t]), + ); + const from = Math.max(startMs, sinceMs); + const rawDays = db + .prepare( + `SELECT user_email as email, ${bucket} as date, + SUM(total_cents) as t + FROM usage_events + WHERE CAST(timestamp AS INTEGER) >= ? AND CAST(timestamp AS INTEGER) < ? + GROUP BY user_email, date`, + ) + .all(from, endMs) as Array<{ email: string; date: string; t: number }>; + + const billedBy = new Map(billed.map((b) => [b.email, b.spend_cents])); + const windowRaw = new Map(); + for (const r of rawDays) { + windowRaw.set(r.email, (windowRaw.get(r.email) ?? 0) + r.t); + const spend = billedBy.get(r.email) ?? 0; + const rawTotal = rawByUser.get(r.email) ?? 0; + if (spend > 0 && rawTotal > 0) { + daily.push({ + date: r.date, + email: r.email, + name: names.get(r.email) ?? r.email, + spend_cents: Math.round((r.t * spend) / rawTotal), + }); + } + } + + const coveredEnd = Math.min(now, endMs); + const share = Math.min(1, Math.max(0, (coveredEnd - from) / Math.max(1, coveredEnd - startMs))); + for (const { email, spend_cents } of billed) { + if (spend_cents <= 0) continue; + const rawTotal = rawByUser.get(email) ?? 0; + const part = + sinceMs <= startMs + ? spend_cents + : rawTotal > 0 + ? ((windowRaw.get(email) ?? 0) * spend_cents) / rawTotal + : spend_cents * share; + totals.set(email, (totals.get(email) ?? 0) + part); + } + }); + + for (const [email, v] of totals) totals.set(email, Math.round(v)); + daily.sort((x, y) => x.date.localeCompare(y.date) || y.spend_cents - x.spend_cents); + return { totals, daily }; +} + +export function getFullDashboard(range: TimeRange = 7): FullDashboard { const db = getDb(); - const dateFilter = `-${days} days`; + + const cycleRow = db.prepare("SELECT MAX(cycle_start) as cycle_start FROM spending").get() as { + cycle_start: string | null; + }; + const cycleStart = + getMetadata("cycle_start") ?? cycleRow?.cycle_start ?? new Date().toISOString().slice(0, 10); + const cycleEnd = getMetadata("cycle_end") ?? ""; + const cycleDays = Math.max(1, Math.ceil((Date.now() - new Date(cycleStart).getTime()) / DAY_MS)); + + const billing = cycleBillingAnchor(db); + + const days = range === "cycle" ? cycleDays : range; + const since = range === "cycle" ? (billing?.cycleStart ?? cycleStart).slice(0, 10) : dayStart(days); + // the 24h range spends over the last 24 hours, not since yesterday's midnight + const hourly = range === 1; + const sinceMs = hourly + ? last24HoursStart() + : range === "cycle" && billing + ? billing.cycleStartMs + : Date.parse(`${since}T00:00:00.000Z`); const totalMembers = (db.prepare("SELECT COUNT(*) as c FROM members WHERE is_removed = 0").get() as { c: number }) @@ -971,23 +1109,13 @@ export function getFullDashboard(days: number = 7): FullDashboard { ( db .prepare( - "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= date('now', ?)", + "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= ?", ) - .get(dateFilter) as { c: number } + .get(since) as { c: number } )?.c ?? 0; - const cycleRow = db.prepare("SELECT MAX(cycle_start) as cycle_start FROM spending").get() as { - cycle_start: string | null; - }; - const cycleStart = - getMetadata("cycle_start") ?? cycleRow?.cycle_start ?? new Date().toISOString().slice(0, 10); - const cycleEnd = getMetadata("cycle_end") ?? ""; - const cycleDays = Math.max( - 1, - Math.ceil((Date.now() - new Date(cycleStart).getTime()) / 86_400_000), - ); - - const billing = cycleBillingAnchor(db); + const windowSpend = spendSince(db, sinceMs); + const chartSpend = hourly ? spendSince(db, sinceMs, true) : windowSpend; const dailySpendWindowFromGroups = () => ( @@ -995,46 +1123,24 @@ export function getFullDashboard(days: number = 7): FullDashboard { .prepare( `SELECT COALESCE(SUM(spend), 0) as total FROM ( SELECT date, email, MAX(spend_cents) as spend FROM daily_spend - WHERE date >= date('now', ?) GROUP BY date, email + WHERE date >= ? GROUP BY date, email )`, ) - .get(dateFilter) as { total: number } + .get(since) as { total: number } ).total; - let totalSpendCentsForWindow: number; - if (billing && billing.teamBilledCents > 0) { - const fullRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events WHERE CAST(timestamp AS INTEGER) >= ?`, - ) - .get(billing.cycleStartMs) as { t: number } - ).t; - if (fullRaw > 0) { - const windowRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?)`, - ) - .get(billing.cycleStartMs, dateFilter) as { t: number } - ).t; - totalSpendCentsForWindow = Math.round((billing.teamBilledCents * windowRaw) / fullRaw); - } else { - totalSpendCentsForWindow = dailySpendWindowFromGroups(); - } - } else { - totalSpendCentsForWindow = dailySpendWindowFromGroups(); - } + const totalSpendCentsForWindow = + billing && billing.teamBilledCents > 0 + ? [...windowSpend.totals.values()].reduce((sum, v) => sum + v, 0) + : dailySpendWindowFromGroups(); const spendRow = { total: totalSpendCentsForWindow }; const agentRow = db .prepare( - "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= date('now', ?)", + "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= ?", ) - .get(dateFilter) as { total: number }; + .get(since) as { total: number }; const activeAnomalies = ( @@ -1050,29 +1156,24 @@ export function getFullDashboard(days: number = 7): FullDashboard { SUM(lines_added) as total_lines_added, COUNT(DISTINCT CASE WHEN is_active = 1 THEN email END) as active_users FROM daily_usage - WHERE date >= date('now', ?) + WHERE date >= ? GROUP BY date ORDER BY date`, ) - .all(dateFilter) as Array<{ + .all(since) as Array<{ date: string; total_agent_requests: number; total_lines_added: number; active_users: number; }>; - const rankedUsers = db + const rankedRows = db .prepare( - `WITH user_spend AS ( - SELECT email, spend_cents - FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) - ), - user_cache AS ( + `WITH user_cache AS ( SELECT user_email as email, ROUND(AVG(CASE WHEN cache_read_tokens > 0 THEN cache_read_tokens END)) as avg_cache_read, ROUND(100.0 * SUM(CASE WHEN max_mode = 1 THEN 1 ELSE 0 END) / COUNT(*)) as max_mode_pct FROM usage_events - WHERE date(timestamp/1000, 'unixepoch') >= date('now', ?) + WHERE date(timestamp/1000, 'unixepoch') >= ? GROUP BY user_email ), activity AS ( @@ -1086,12 +1187,12 @@ export function getFullDashboard(days: number = 7): FullDashboard { COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_days, MAX(most_used_model) as most_used_model FROM daily_usage - WHERE date >= date('now', ?) AND is_active = 1 + WHERE date >= ? AND is_active = 1 GROUP BY email ) SELECT m.email, m.name, - COALESCE(us.spend_cents, 0) as spend_cents, + 0 as spend_cents, 0 as included_spend_cents, 0 as fast_premium_requests, COALESCE(a.agent_requests, 0) as agent_requests, COALESCE(a.lines_added, 0) as lines_added, @@ -1103,16 +1204,14 @@ export function getFullDashboard(days: number = 7): FullDashboard { COALESCE(a.total_accepts, 0) as total_accepts, COALESCE(uc.avg_cache_read, 0) as avg_cache_read, COALESCE(uc.max_mode_pct, 0) as max_mode_pct, - RANK() OVER (ORDER BY COALESCE(us.spend_cents, 0) DESC) as spend_rank, + 0 as spend_rank, RANK() OVER (ORDER BY COALESCE(a.agent_requests, 0) DESC) as activity_rank FROM members m - LEFT JOIN user_spend us ON m.email = us.email LEFT JOIN user_cache uc ON m.email = uc.email LEFT JOIN activity a ON m.email = a.email - WHERE m.is_removed = 0 - ORDER BY COALESCE(us.spend_cents, 0) DESC`, + WHERE m.is_removed = 0`, ) - .all(dateFilter, dateFilter) as Array<{ + .all(since, since) as Array<{ email: string; name: string; spend_cents: number; @@ -1132,34 +1231,24 @@ export function getFullDashboard(days: number = 7): FullDashboard { activity_rank: number; }>; - const chartDays = Math.max(days, 7); - const chartDateFilter = `-${chartDays} days`; + const rankedUsers = rankedRows + .map((u) => ({ ...u, spend_cents: windowSpend.totals.get(u.email) ?? 0 })) + .sort((x, y) => y.spend_cents - x.spend_cents); + for (const u of rankedUsers) { + u.spend_rank = 1 + rankedUsers.filter((o) => o.spend_cents > u.spend_cents).length; + } let teamDailySpend: Array<{ date: string; spend_cents: number }> = []; if (billing && billing.teamBilledCents > 0) { - const fullRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events WHERE CAST(timestamp AS INTEGER) >= ?`, - ) - .get(billing.cycleStartMs) as { t: number } - ).t; - const rawByDay = db - .prepare( - `SELECT date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as date, - SUM(total_cents) as raw_cents - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?) - GROUP BY date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') - ORDER BY date`, - ) - .all(billing.cycleStartMs, chartDateFilter) as Array<{ date: string; raw_cents: number }>; - if (fullRaw > 0) { - const f = billing.teamBilledCents / fullRaw; - teamDailySpend = rawByDay.map((r) => ({ - date: r.date, - spend_cents: Math.round(r.raw_cents * f), + const byDate = new Map(); + for (const r of chartSpend.daily) { + byDate.set(r.date, (byDate.get(r.date) ?? 0) + r.spend_cents); + } + teamDailySpend = [...byDate].map(([date, spend_cents]) => ({ date, spend_cents })); + if (hourly && teamDailySpend.length > 0) { + teamDailySpend = chartHourKeys(sinceMs).map((date) => ({ + date, + spend_cents: byDate.get(date) ?? 0, })); } } @@ -1169,62 +1258,14 @@ export function getFullDashboard(days: number = 7): FullDashboard { ` SELECT date, SUM(spend) as spend_cents FROM ( SELECT date, email, MAX(spend_cents) as spend FROM daily_spend - WHERE date >= date('now', ?) GROUP BY date, email + WHERE date >= ? GROUP BY date, email ) GROUP BY date ORDER BY date `, ) - .all(chartDateFilter) as Array<{ date: string; spend_cents: number }>; + .all(since) as Array<{ date: string; spend_cents: number }>; } - let dailySpendBreakdown: Array<{ - date: string; - email: string; - name: string; - spend_cents: number; - }> = []; - if (billing && billing.teamBilledCents > 0) { - dailySpendBreakdown = db - .prepare( - ` - WITH cb AS ( - SELECT email, spend_cents FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) - ), - ur AS ( - SELECT user_email as email, SUM(total_cents) as tr - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - GROUP BY user_email - ), - dr AS ( - SELECT user_email, date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as date, - SUM(total_cents) as rd - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?) - GROUP BY user_email, date - ) - SELECT x.date, x.email, x.name, x.spend_cents FROM ( - SELECT dr.date, dr.user_email as email, COALESCE(m.name, dr.user_email) as name, - CASE WHEN COALESCE(ur.tr, 0) > 0 AND COALESCE(cb.spend_cents, 0) > 0 - THEN CAST(ROUND(dr.rd * cb.spend_cents * 1.0 / ur.tr) AS INTEGER) - ELSE 0 END as spend_cents - FROM dr - LEFT JOIN ur ON ur.email = dr.user_email - LEFT JOIN cb ON cb.email = dr.user_email - LEFT JOIN members m ON m.email = dr.user_email - ) x - WHERE x.spend_cents > 0 - ORDER BY x.date, x.spend_cents DESC - `, - ) - .all(billing.cycleStartMs, billing.cycleStartMs, chartDateFilter) as Array<{ - date: string; - email: string; - name: string; - spend_cents: number; - }>; - } + let dailySpendBreakdown = billing && billing.teamBilledCents > 0 ? chartSpend.daily : []; if (dailySpendBreakdown.length === 0) { dailySpendBreakdown = db .prepare( @@ -1235,7 +1276,7 @@ export function getFullDashboard(days: number = 7): FullDashboard { FROM ( SELECT date, email, MAX(spend_cents) as spend_cents FROM daily_spend - WHERE date >= date('now', ?) + WHERE date >= ? GROUP BY date, email ) ds LEFT JOIN members m ON ds.email = m.email @@ -1243,7 +1284,7 @@ export function getFullDashboard(days: number = 7): FullDashboard { ORDER BY ds.date, ds.spend_cents DESC `, ) - .all(chartDateFilter) as Array<{ + .all(since) as Array<{ date: string; email: string; name: string; @@ -1251,43 +1292,48 @@ export function getFullDashboard(days: number = 7): FullDashboard { }>; } - const modelCosts = db + const modelRows = db .prepare( ` WITH user_model AS ( SELECT email, most_used_model, SUM(agent_requests) as reqs - FROM daily_usage WHERE is_active = 1 AND most_used_model != '' AND date >= date('now', ?) + FROM daily_usage WHERE is_active = 1 AND most_used_model != '' AND date >= ? GROUP BY email, most_used_model ), primary_model AS ( SELECT email, most_used_model FROM user_model WHERE (email, reqs) IN (SELECT email, MAX(reqs) FROM user_model GROUP BY email) - ), - user_spend AS ( - SELECT email, spend_cents FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) ) SELECT pm.most_used_model as model, COUNT(*) as users, - ROUND(AVG(COALESCE(us.spend_cents, 0))/100, 0) as avg_spend, - ROUND(SUM(COALESCE(us.spend_cents, 0))/100, 0) as total_spend, COALESCE(SUM(du.reqs), 0) as total_reqs, GROUP_CONCAT(pm.email) as emails FROM primary_model pm - LEFT JOIN user_spend us ON pm.email = us.email - LEFT JOIN (SELECT email, SUM(agent_requests) as reqs FROM daily_usage WHERE date >= date('now', ?) GROUP BY email) du ON pm.email = du.email + LEFT JOIN (SELECT email, SUM(agent_requests) as reqs FROM daily_usage WHERE date >= ? GROUP BY email) du ON pm.email = du.email GROUP BY pm.most_used_model - ORDER BY total_spend DESC `, ) - .all(dateFilter, dateFilter) as Array<{ + .all(since, since) as Array<{ model: string; users: number; - avg_spend: number; - total_spend: number; total_reqs: number; - emails: string; + emails: string | null; }>; + const modelCosts = modelRows + .map((mc) => { + const emails = mc.emails ? mc.emails.split(",") : []; + const spend = emails.reduce((sum, e) => sum + (windowSpend.totals.get(e) ?? 0), 0); + return { + model: mc.model, + users: mc.users, + avg_spend: Math.round(spend / 100 / Math.max(1, mc.users)), + total_spend: Math.round(spend / 100), + total_reqs: mc.total_reqs, + emails, + }; + }) + .sort((x, y) => y.total_spend - x.total_spend); + const stats: DashboardStats = { totalMembers, activeMembers, @@ -1303,13 +1349,12 @@ export function getFullDashboard(days: number = 7): FullDashboard { return { days, + range, stats, - modelCosts: modelCosts.map((mc) => ({ - ...mc, - emails: mc.emails ? mc.emails.split(",") : [], - })), + modelCosts, teamDailySpend, dailySpendBreakdown, + cycleStarts: getCycleStarts(db), }; } @@ -1597,8 +1642,16 @@ export function getDashboardStats(days: number = 7): DashboardStats { return getFullDashboard(days).stats; } -export function getUserStats(email: string, days: number = 7) { +export function getUserStats(email: string, range: TimeRange = 7) { const db = getDb(); + const days = range === "cycle" ? getCycleWindowDays() : range; + const sinceMs = + range === 1 + ? last24HoursStart() + : ((range === "cycle" ? cycleBillingAnchor(db)?.cycleStartMs : undefined) ?? + Date.parse(`${dayStart(days)}T00:00:00.000Z`)); + const windowSpend = spendSince(db, sinceMs); + const windowSpendCents = windowSpend.totals.get(email) ?? 0; const member = db.prepare("SELECT * FROM members WHERE email = ?").get(email) as | (TeamMember & { first_seen: string; last_seen: string }) @@ -1652,7 +1705,47 @@ export function getUserStats(email: string, days: number = 7) { .prepare(`${ANOMALY_SELECT} WHERE user_email = ? ORDER BY detected_at DESC LIMIT 20`) .all(email) as Anomaly[]; - const dailySpend = getUserDailySpend(email); + const hourly = range === 1; + const firstDate = new Date(sinceMs).toISOString().slice(0, 10); + const spendByDate = new Map( + (hourly ? spendSince(db, sinceMs, true) : windowSpend).daily + .filter((r) => r.email === email) + .map((r) => [r.date, r.spend_cents]), + ); + if (spendByDate.size === 0 && !hourly) { + for (const d of getUserDailySpend(email)) { + if (d.date >= firstDate) spendByDate.set(d.date, d.spend_cents); + } + } + const dailySpend: Array<{ date: string; spend_cents: number; requests?: number }> = []; + if (hourly) { + // activity is only kept per day, so the hourly $/req counts the usage events of each hour + const requestsByHour = new Map( + ( + db + .prepare( + `SELECT strftime('%Y-%m-%dT%H', CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as hour, + COUNT(*) as n + FROM usage_events + WHERE user_email = ? AND CAST(timestamp AS INTEGER) >= ? + GROUP BY hour`, + ) + .all(email, sinceMs) as Array<{ hour: string; n: number }> + ).map((r) => [r.hour, r.n]), + ); + for (const date of chartHourKeys(sinceMs)) { + dailySpend.push({ + date, + spend_cents: spendByDate.get(date) ?? 0, + requests: requestsByHour.get(date), + }); + } + } else { + for (let t = Date.parse(`${firstDate}T00:00:00.000Z`); t <= Date.now(); t += DAY_MS) { + const date = new Date(t).toISOString().slice(0, 10); + dailySpend.push({ date, spend_cents: spendByDate.get(date) ?? 0 }); + } + } const billCycleStart = spending[0]?.cycle_start ?? null; const usageEventsSummaryRaw = getUserUsageEventsSummary(email, days, billCycleStart); const billedCents = spending[0]?.spend_cents ?? 0; @@ -1771,6 +1864,8 @@ export function getUserStats(email: string, days: number = 7) { aiAdoption, planExhaustion, repoBreakdown, + windowSpendCents, + cycleStarts: getCycleStarts(db), }; } @@ -2291,7 +2386,7 @@ export function getUsersByClientVersion(): Record "?").join(",")})` : ""; const params = emails?.length ? [...emails] : []; @@ -2326,12 +2421,13 @@ export function getModelEfficiency(emails?: string[]): ModelEfficiency[] { AND du.most_used_model != '' AND du.agent_requests > 0 AND ds.spend_cents > 0 + AND du.date >= date('now', ?) ${emailFilter} GROUP BY du.most_used_model HAVING COUNT(DISTINCT du.email) >= ${emails?.length ? "1" : "3"} AND SUM(ds.spend_cents) >= ${emails?.length ? "0" : "2000"} ORDER BY total_spend_usd DESC`, ) - .all(...params, ...params) as ModelEfficiency[]; + .all(...params, `-${days} days`, ...params) as ModelEfficiency[]; } export function getAllMembers(): Array { diff --git a/src/lib/data/types.ts b/src/lib/data/types.ts index cce620d..d9173f3 100644 --- a/src/lib/data/types.ts +++ b/src/lib/data/types.ts @@ -55,6 +55,7 @@ export interface DashboardStats { export interface FullDashboard { days: number; + range: number | "cycle"; stats: DashboardStats; modelCosts: Array<{ model: string; @@ -66,6 +67,7 @@ export interface FullDashboard { }>; teamDailySpend: Array<{ date: string; spend_cents: number }>; dailySpendBreakdown: Array<{ date: string; email: string; name: string; spend_cents: number }>; + cycleStarts: string[]; } export interface ModelEfficiency { diff --git a/tests/hourly-spend.test.ts b/tests/hourly-spend.test.ts new file mode 100644 index 0000000..82a1036 --- /dev/null +++ b/tests/hourly-spend.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-hourly-spend.db"); +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; + +const hourKey = (ms: number) => new Date(ms).toISOString().slice(0, 13); +const daysAgo = (n: number) => new Date(Date.now() - n * DAY_MS).toISOString().slice(0, 10); + +describe("charts zoom on the selected range", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + const now = Date.now(); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, ?)").run( + "a@x.com", + "A", + "member", + ); + db.prepare("INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)").run( + "a@x.com", + daysAgo(10), + 900, + ); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', 100)", + ); + event.run("a@x.com", String(now - 30 * 60_000)); + event.run("a@x.com", String(now - 5 * HOUR_MS)); + event.run("a@x.com", String(now - 3 * DAY_MS + HOUR_MS)); + event.run("a@x.com", String(now - 6 * DAY_MS)); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + it("charts the last 24 hours hour by hour on the 24h range", () => { + const d = sqlite.getFullDashboard(1); + expect(d.teamDailySpend).toHaveLength(25); + expect(d.teamDailySpend.every((r) => r.date.length === 13)).toBe(true); + const latest = d.teamDailySpend.find((r) => r.date === hourKey(now - 30 * 60_000)); + expect(latest?.spend_cents).toBe(225); + expect(d.dailySpendBreakdown.every((r) => r.date.length === 13)).toBe(true); + }); + + it("shows only the selected days on short ranges", () => { + const dates = sqlite.getFullDashboard(3).teamDailySpend.map((r) => r.date); + expect(dates.length).toBeGreaterThan(0); + expect(dates.every((date) => date >= daysAgo(3))).toBe(true); + }); + + it("gives the user page the same hourly points on the 24h range", () => { + const stats = sqlite.getUserStats("a@x.com", 1); + expect(stats.dailySpend).toHaveLength(25); + expect(stats.dailySpend.every((r) => r.date.length === 13)).toBe(true); + }); + + it("counts the requests of each hour so the user chart can draw $/req", () => { + const stats = sqlite.getUserStats("a@x.com", 1); + const latest = stats.dailySpend.find((r) => r.date === hourKey(now - 30 * 60_000)); + expect(latest?.requests).toBe(1); + expect(stats.dailySpend.filter((r) => r.requests != null)).toHaveLength(2); + }); +}); diff --git a/tests/rolling-24h.test.ts b/tests/rolling-24h.test.ts new file mode 100644 index 0000000..8d98d38 --- /dev/null +++ b/tests/rolling-24h.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-rolling-24h.db"); +const at = (iso: string) => String(Date.parse(iso)); + +describe("24h range is a rolling window with hourly bars", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + const member = db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, 'member')"); + const spending = db.prepare( + "INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)", + ); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', 100)", + ); + // at 14:41 UTC on the 13th, "24h" starts at 14:41 on the 12th + member.run("b@x.com", "b"); + spending.run("b@x.com", "2026-11-01", 1000); + member.run("c@x.com", "c"); + spending.run("c@x.com", "2026-11-01", 900); + event.run("b@x.com", at("2026-11-12T14:51:00Z")); // 23h50 ago: inside the oldest partial hour + event.run("b@x.com", at("2026-11-13T14:30:00Z")); + event.run("c@x.com", at("2026-11-12T14:30:00Z")); // 24h11 ago: just outside + event.run("c@x.com", at("2026-11-12T14:51:00Z")); + event.run("c@x.com", at("2026-11-13T14:30:00Z")); + // the night the clocks go back in Paris (01:00 UTC on 25 October 2026) + member.run("e@x.com", "e"); + spending.run("e@x.com", "2026-10-01", 900); + event.run("e@x.com", at("2026-10-24T01:45:00Z")); // 23h45 ago + event.run("e@x.com", at("2026-10-24T01:15:00Z")); // 24h15 ago + event.run("e@x.com", at("2026-10-25T01:10:00Z")); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + const freeze = (iso: string) => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date(iso)); + }; + + it("counts an event from the oldest partial hour and leaves out an older one", () => { + freeze("2026-11-13T14:41:00Z"); + expect(sqlite.getUserStats("b@x.com", 1).windowSpendCents).toBe(1000); + expect(sqlite.getUserStats("c@x.com", 1).windowSpendCents).toBe(600); + }); + + it("charts from the hour 24h back to the current hour, partial ends included", () => { + freeze("2026-11-13T14:41:00Z"); + const chart = sqlite.getFullDashboard(1).teamDailySpend; + expect(chart[0]?.date).toBe("2026-11-12T14"); + expect(chart.at(-1)?.date).toBe("2026-11-13T14"); + expect(chart.reduce((sum, r) => sum + r.spend_cents, 0)).toBe(1000 + 600); + }); + + it("is unaffected by a daylight saving change in the local time zone", () => { + const tz = process.env.TZ; + process.env.TZ = "Europe/Paris"; + try { + freeze("2026-10-25T01:30:00Z"); + const stats = sqlite.getUserStats("e@x.com", 1); + expect(stats.windowSpendCents).toBe(600); + expect(stats.dailySpend).toHaveLength(25); + expect(stats.dailySpend[0]?.date).toBe("2026-10-24T01"); + expect(stats.dailySpend.at(-1)?.date).toBe("2026-10-25T01"); + } finally { + if (tz === undefined) delete process.env.TZ; + else process.env.TZ = tz; + } + }); +}); diff --git a/tests/window-spend.test.ts b/tests/window-spend.test.ts new file mode 100644 index 0000000..8f21b99 --- /dev/null +++ b/tests/window-spend.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-window-spend.db"); +const DAY_MS = 86_400_000; + +const midnight = Date.UTC( + new Date().getUTCFullYear(), + new Date().getUTCMonth(), + new Date().getUTCDate(), +); +const daysAgo = (n: number) => new Date(midnight - n * DAY_MS).toISOString().slice(0, 10); +const noon = (n: number) => String(midnight - n * DAY_MS + DAY_MS / 2); + +describe("getFullDashboard spend over a window", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, ?)").run( + "a@x.com", + "A", + "member", + ); + const bill = db.prepare( + "INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)", + ); + bill.run("a@x.com", daysAgo(35), 1000); + bill.run("a@x.com", daysAgo(5), 500); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', ?)", + ); + event.run("a@x.com", noon(34), 100); + event.run("a@x.com", noon(15), 100); + event.run("a@x.com", noon(4), 50); + event.run("a@x.com", noon(2), 50); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + const spend = (range: number | "cycle") => { + const d = sqlite.getFullDashboard(range); + return { + user: d.stats.rankedUsers[0]?.spend_cents, + team: d.stats.totalSpendCents, + chart: d.teamDailySpend.reduce((sum, r) => sum + r.spend_cents, 0), + }; + }; + + it("uses the billed total for the current cycle", () => { + expect(spend("cycle")).toEqual({ user: 500, team: 500, chart: 500 }); + expect(spend(7).user).toBe(500); + }); + + it("shares the previous cycle's bill over the events inside the window", () => { + expect(spend(30)).toEqual({ user: 1000, team: 1000, chart: 1000 }); + }); + + it("counts nothing when no event falls inside the window", () => { + expect(spend(1).user).toBe(0); + }); + + it("returns the user's spend for the selected range", () => { + const spendFor = (range: number | "cycle") => + sqlite.getUserStats("a@x.com", range).windowSpendCents; + expect(spendFor("cycle")).toBe(500); + expect(spendFor(30)).toBe(1000); + expect(spendFor(1)).toBe(0); + }); + + it("lists the cycle starts so charts can mark them", () => { + expect(sqlite.getFullDashboard(30).cycleStarts).toEqual([daysAgo(35), daysAgo(5)]); + expect(sqlite.getUserStats("a@x.com", 30).cycleStarts).toEqual([daysAgo(35), daysAgo(5)]); + }); + + it("finds how many days back the current cycle started", () => { + expect(sqlite.getCycleWindowDays()).toBe(5); + }); +}); From fbd801cf87720b136840e236a959a0758d76f2d0 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:21:33 +0100 Subject: [PATCH 2/7] feat: add a shared time range selector with a cycle range The Overview, Insights and user pages share one selector: 24h, 3d, 7d, 14d, 30d or Cycle (default). The range lives in the URL (?range=) and the main menu forwards it to Overview and Insights. The members table headers no longer repeat the range, the selector already shows it. Co-Authored-By: Claude Sonnet 5.5 --- docs/FEATURES.md | 9 +- src/app/dashboard-client.tsx | 105 +++++++------------ src/app/insights/insights-client.tsx | 53 ++++------ src/app/insights/page.tsx | 32 +++--- src/app/layout.tsx | 5 +- src/app/page.tsx | 12 ++- src/app/users/[email]/page.tsx | 14 ++- src/app/users/[email]/user-detail-client.tsx | 36 ++++--- src/components/charts/spend-bar-chart.tsx | 15 ++- src/components/dashboard/members-table.tsx | 21 ++-- src/components/nav-links.tsx | 11 +- src/components/time-range-selector.tsx | 52 +++++++++ src/lib/time-range.ts | 17 +++ 13 files changed, 231 insertions(+), 151 deletions(-) create mode 100644 src/components/time-range-selector.tsx create mode 100644 src/lib/time-range.ts diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 3e7f76a..a70c244 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -8,7 +8,7 @@ - Search by name/email - Filter by billing group -- Time range: 24h / 3d / 7d / 14d / 30d +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default, from the billing cycle start). Spend, ranks, $/req and the charts all follow the selected range, over as many billing cycles as it spans. ### Stat Cards @@ -57,10 +57,11 @@ - Name, email, role, billing group link - Profile badges (same as dashboard) +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default) ### KPI Cards -- **Cycle Spend** — total $ in billing cycle, $/day +- **Spend** — total $ in time range, $/day - **$/Req** — cost per agent request - **Agent Reqs** — total requests in time range - **Diffs Accepted** — % of agent diffs accepted (accepts/applies), raw counts @@ -86,6 +87,10 @@ **Team analytics — adoption, efficiency, trends.** +### Controls + +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default), all sections except Plan Exhaustion and Client Versions + ### Stat Cards - Avg DAU, Commands total, Agent lines accepted, Tab lines accepted, MCP tools count diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index 59518fc..e3be241 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -10,6 +10,12 @@ import { MembersTable } from "@/components/dashboard/members-table"; import Link from "next/link"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; +import { DEFAULT_RANGE } from "@/lib/time-range"; +import { + TimeRangeSelector, + formatTimeLabel, + type TimeRange, +} from "@/components/time-range-selector"; interface BillingGroupWithMembers { id: string; @@ -28,19 +34,6 @@ interface ModelCost { emails: string[]; } -const TIME_RANGES = [ - { label: "24h", days: 1 }, - { label: "3d", days: 3 }, - { label: "7d", days: 7 }, - { label: "14d", days: 14 }, - { label: "30d", days: 30 }, -] as const; - -function formatTimeLabel(days: number): string { - if (days === 1) return "24h"; - return `${days}d`; -} - function fmt(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`; @@ -58,14 +51,12 @@ interface SpendBreakdownRow { interface DashboardClientProps { initialData: FullDashboard; + initialRange: TimeRange; } -export function DashboardClient({ initialData }: DashboardClientProps) { +export function DashboardClient({ initialData: data, initialRange: range }: DashboardClientProps) { const searchParams = useSearchParams(); - const [data, setData] = useState(initialData); - const [days, setDays] = useState(30); const [search, setSearch] = useState(""); - const [loading, setLoading] = useState(false); const [sortCol, setSortCol] = useState("spend"); const [sortAsc, setSortAsc] = useState(false); const [badgeFilter, setBadgeFilter] = useState(null); @@ -114,11 +105,6 @@ export function DashboardClient({ initialData }: DashboardClientProps) { ) .catch(() => {}); } - const saved = localStorage.getItem("dashboard-days"); - if (saved) { - const parsed = parseInt(saved, 10); - if (parsed !== 30) changeTimeRange(parsed); - } }, []); const groupEmailSet = useMemo(() => { @@ -269,20 +255,8 @@ export function DashboardClient({ initialData }: DashboardClientProps) { ); }, [stats.rankedUsers, search]); - async function changeTimeRange(newDays: number) { - setDays(newDays); - localStorage.setItem("dashboard-days", String(newDays)); - setLoading(true); - try { - const res = await fetch(`/api/stats?days=${newDays}`); - const newData: FullDashboard = await res.json(); - setData(newData); - } finally { - setLoading(false); - } - } - - const timeLabel = formatTimeLabel(days); + const days = data.days; + const timeLabel = formatTimeLabel(range); const isSearching = search.trim().length > 0 || selectedGroup !== "all" || @@ -290,7 +264,6 @@ export function DashboardClient({ initialData }: DashboardClientProps) { exhaustionFilter !== null || modelFilter !== null; const totalLines = stats.dailyTeamActivity.reduce((s, d) => s + d.total_lines_added, 0); - const effectiveDays = Math.min(days, stats.cycleDays); const cycleStartDate = new Date(stats.cycleStart); const cycleEndDate = stats.cycleEnd ? new Date(stats.cycleEnd) @@ -365,6 +338,19 @@ export function DashboardClient({ initialData }: DashboardClientProps) { )} +
+ {isSearching ? `${filteredUsers.length} / ` : ""} + {stats.totalMembers} members + {selectedGroup !== "all" && ( + + )} +
{groups.length > 1 && ( )} -
- {TIME_RANGES.map((r) => ( - - ))} -
+ @@ -338,7 +331,7 @@ export function InsightsClient({ value={dauSummary.avgDau.toString()} sub={`Peak: ${dauSummary.peakDau}`} /> - + @@ -364,7 +357,7 @@ export function InsightsClient({ @@ -591,7 +584,7 @@ export function InsightsClient({ {/* Tables Row: Repo Attribution + File Extensions */}
- + {data.repoAttribution?.length > 0 ? ( (() => { const grandTotal = data.repoAttribution.reduce((s, r) => s + r.total_lines, 0) || 1; @@ -968,11 +961,11 @@ function PlanExhaustionSection({ function ModelEfficiencySection({ data, - days, + windowLabel, groupName, }: { data: ModelEfficiencyEntry[]; - days: number; + windowLabel: string; groupName?: string; }) { const [showDetail, setShowDetail] = useState(false); @@ -1006,8 +999,8 @@ function ModelEfficiencySection({ const maxSpend = bySpend[0]?.total_spend_usd ?? 1; const subtitle = groupName - ? `${groupName} · Last ${days} days` - : `Models with $30+ spend · Last ${days} days`; + ? `${groupName} · ${windowLabel}` + : `Models with $30+ spend · ${windowLabel}`; return (
diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx index 518e5b7..dc0188a 100644 --- a/src/app/insights/page.tsx +++ b/src/app/insights/page.tsx @@ -13,32 +13,40 @@ import { getPlanExhaustionStats, getGroupsWithMembers, getRepoAIAttribution, + getCycleWindowDays, } from "@/lib/data"; +import { parseRange } from "@/lib/time-range"; import { InsightsClient } from "./insights-client"; export const dynamic = "force-dynamic"; -export default function InsightsPage() { +export default async function InsightsPage({ + searchParams, +}: { + searchParams: Promise<{ range?: string }>; +}) { + const range = parseRange((await searchParams).range); try { + const days = range === "cycle" ? getCycleWindowDays() : range; const data = { - dau: getAnalyticsDAU(30), - modelSummary: getAnalyticsModelUsageSummary(30), - modelTrend: getAnalyticsModelUsageTrend(30), - agentEdits: getAnalyticsAgentEditsTrend(30), - tabs: getAnalyticsTabsTrend(30), - mcp: getAnalyticsMCPSummary(30), - commands: getAnalyticsCommandsSummary(30), - fileExtensions: getAnalyticsFileExtensionsSummary(30), + dau: getAnalyticsDAU(days), + modelSummary: getAnalyticsModelUsageSummary(days), + modelTrend: getAnalyticsModelUsageTrend(days), + agentEdits: getAnalyticsAgentEditsTrend(days), + tabs: getAnalyticsTabsTrend(days), + mcp: getAnalyticsMCPSummary(days), + commands: getAnalyticsCommandsSummary(days), + fileExtensions: getAnalyticsFileExtensionsSummary(days), clientVersions: getAnalyticsClientVersionsSummary(), versionUsers: getUsersByClientVersion(), - modelEfficiency: getModelEfficiency(), + modelEfficiency: getModelEfficiency(undefined, days), planExhaustion: getPlanExhaustionStats(), - repoAttribution: getRepoAIAttribution(30), + repoAttribution: getRepoAIAttribution(days), }; const groups = getGroupsWithMembers(); - return ; + return ; } catch { return (
diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 192028b..e561b5e 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,3 +1,4 @@ +import { Suspense } from "react"; import type { Metadata } from "next"; import Image from "next/image"; import Link from "next/link"; @@ -27,7 +28,9 @@ export default async function RootLayout({ children }: { children: React.ReactNo Cursor Tracker - + + +
diff --git a/src/app/page.tsx b/src/app/page.tsx index 95bf64e..e4e15cc 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,15 +1,21 @@ import { Suspense } from "react"; import { getFullDashboard } from "@/lib/data"; +import { parseRange } from "@/lib/time-range"; import { DashboardClient } from "./dashboard-client"; export const dynamic = "force-dynamic"; -export default function HomePage() { +export default async function HomePage({ + searchParams, +}: { + searchParams: Promise<{ range?: string }>; +}) { + const range = parseRange((await searchParams).range); try { - const data = getFullDashboard(30); + const data = getFullDashboard(range); return ( - + ); } catch { diff --git a/src/app/users/[email]/page.tsx b/src/app/users/[email]/page.tsx index fdf53a3..847d871 100644 --- a/src/app/users/[email]/page.tsx +++ b/src/app/users/[email]/page.tsx @@ -1,31 +1,37 @@ import Link from "next/link"; import { getUserStats } from "@/lib/data"; +import { overviewHref, parseRange } from "@/lib/time-range"; import { UserDetailClient } from "./user-detail-client"; export const dynamic = "force-dynamic"; interface PageProps { params: Promise<{ email: string }>; + searchParams: Promise<{ range?: string }>; } -export default async function UserPage({ params }: PageProps) { +export default async function UserPage({ params, searchParams }: PageProps) { const { email } = await params; const decodedEmail = decodeURIComponent(email); + const range = parseRange((await searchParams).range); let stats; try { - stats = getUserStats(decodedEmail, 30); + stats = getUserStats(decodedEmail, range); } catch { return (

User Not Found

No data found for {decodedEmail}

- + ← Back to overview
); } - return ; + return ; } diff --git a/src/app/users/[email]/user-detail-client.tsx b/src/app/users/[email]/user-detail-client.tsx index 09722e4..c3a07b7 100644 --- a/src/app/users/[email]/user-detail-client.tsx +++ b/src/app/users/[email]/user-detail-client.tsx @@ -5,10 +5,17 @@ import { SpendTrendChart } from "@/components/charts/spend-trend-chart"; import { formatDateShort } from "@/lib/date-utils"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; +import { + TimeRangeSelector, + formatTimeLabel, + type TimeRange, +} from "@/components/time-range-selector"; import type { Anomaly } from "@/lib/types"; +import { overviewHref } from "@/lib/time-range"; import type { UsageBadge, SpendBadge, ContextBadge, AdoptionBadge } from "@/lib/data"; interface UserStats { + windowSpendCents: number; member: | { name: string; email: string; role: string; first_seen: string; last_seen: string } | undefined; @@ -107,6 +114,7 @@ interface UserStats { interface UserDetailClientProps { email: string; stats: UserStats; + initialRange: TimeRange; } function fmt(n: number): string { @@ -189,27 +197,22 @@ const BADGE_STYLES: Record sum + d.agent_requests, 0); const cycleStart = currentSpend?.cycle_start; - const cycleAgentRequests = cycleStart - ? stats.dailyActivity - .filter((d) => d.date >= cycleStart) - .reduce((sum, d) => sum + d.agent_requests, 0) - : totalAgentRequests; - const billedCycleCents = currentSpend?.spend_cents ?? 0; - const cycleSpendDollars = billedCycleCents / 100; + const windowSpendDollars = stats.windowSpendCents / 100; const dollarsPerReq = - cycleAgentRequests > 0 ? (billedCycleCents / cycleAgentRequests / 100).toFixed(2) : null; + totalAgentRequests > 0 ? (stats.windowSpendCents / totalAgentRequests / 100).toFixed(2) : null; const cycleDaysElapsed = cycleStart ? Math.max( 1, Math.ceil((Date.now() - new Date(`${cycleStart}T12:00:00Z`).getTime()) / 86_400_000), ) : Math.max(1, stats.dailySpend.length); - const dailyAvgSpend = cycleSpendDollars / cycleDaysElapsed; + const windowDays = range === "cycle" ? cycleDaysElapsed : range; + const dailyAvgSpend = windowSpendDollars / windowDays; const mergedDailyData = buildMergedDailyData(stats.dailySpend, stats.dailyActivity); const hasUsageEvents = stats.usageEventsSummary.length > 0; @@ -223,7 +226,7 @@ export function UserDetailClient({ email, stats }: UserDetailClientProps) { return (
- + ← Back
@@ -258,12 +261,15 @@ export function UserDetailClient({ email, stats }: UserDetailClientProps) { )}

+
+ +
- + ; highlightEmail?: string; expanded?: boolean; + timeLabel: string; + range: TimeRange; } const TOOLTIP_STYLE = { @@ -35,7 +38,13 @@ const BAR_HOVER_COLOR = "#60a5fa"; const HIGHLIGHT_COLOR = "#f59e0b"; const HIGHLIGHT_HOVER_COLOR = "#fbbf24"; -export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartProps) { +export function SpendBarChart({ + data, + highlightEmail, + expanded, + timeLabel, + range, +}: SpendBarChartProps) { const router = useRouter(); const [hoveredIndex, setHoveredIndex] = useState(null); @@ -50,7 +59,7 @@ export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartP const handleBarClick = useCallback( (entry: (typeof chartData)[number]) => { - router.push(`/users/${encodeURIComponent(entry.email)}`); + router.push(userHref(entry.email, range)); }, [router], ); @@ -67,7 +76,7 @@ export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartP className={`bg-zinc-900 rounded-lg border border-zinc-800 p-4 ${expanded ? "h-full flex flex-col" : ""}`} >

- Top Spenders (Current Cycle) + Top Spenders ({timeLabel})

diff --git a/src/components/dashboard/members-table.tsx b/src/components/dashboard/members-table.tsx index e77ca4c..05d1b04 100644 --- a/src/components/dashboard/members-table.tsx +++ b/src/components/dashboard/members-table.tsx @@ -5,6 +5,7 @@ import { useState, useRef, useEffect } from "react"; import type { RankedUser, UsageBadge, SpendBadge, ContextBadge, AdoptionBadge } from "@/lib/data"; import type { SortColumn } from "@/app/dashboard-client"; import { shortModel } from "@/lib/format-utils"; +import { userHref, type TimeRange } from "@/lib/time-range"; interface MembersTableProps { data: RankedUser[]; @@ -13,6 +14,7 @@ interface MembersTableProps { onSort: (col: SortColumn) => void; highlightEmail?: string; timeLabel: string; + range: TimeRange; badgeFilter: string | null; onBadgeFilter: (badge: string | null) => void; } @@ -293,6 +295,7 @@ export function MembersTable({ onSort, highlightEmail, timeLabel, + range, badgeFilter, onBadgeFilter, }: MembersTableProps) { @@ -375,14 +378,14 @@ export function MembersTable({ className="text-right px-4 py-3 font-medium cursor-pointer hover:text-zinc-300 select-none" onClick={() => onSort("spend")} > - Spend (cycle) + Spend onSort("reqs")} > - Reqs ({timeLabel}) + Reqs - Lines ({timeLabel}) + Lines @@ -400,7 +403,9 @@ export function MembersTable({ className="text-right px-4 py-3 font-medium cursor-pointer hover:text-zinc-300 select-none" onClick={() => onSort("cpr")} > - $/req + + $/req + Model @@ -414,7 +419,7 @@ export function MembersTable({ Ranks @@ -442,7 +447,7 @@ export function MembersTable({ {row.name} @@ -557,7 +562,7 @@ export function MembersTable({
${row.spend_rank} @@ -571,7 +576,7 @@ export function MembersTable({ → diff --git a/src/components/nav-links.tsx b/src/components/nav-links.tsx index 5bccc6a..829c091 100644 --- a/src/components/nav-links.tsx +++ b/src/components/nav-links.tsx @@ -1,26 +1,27 @@ "use client"; import Link from "next/link"; -import { usePathname } from "next/navigation"; +import { usePathname, useSearchParams } from "next/navigation"; const LINKS = [ - { href: "/", label: "Overview" }, - { href: "/insights", label: "Insights" }, + { href: "/", label: "Overview", ranged: true }, + { href: "/insights", label: "Insights", ranged: true }, { href: "/anomalies", label: "Anomalies" }, { href: "/settings", label: "Settings" }, ]; export function NavLinks() { const pathname = usePathname(); + const range = useSearchParams().get("range"); return ( <> - {LINKS.map(({ href, label }) => { + {LINKS.map(({ href, label, ranged }) => { const active = href === "/" ? pathname === "/" : pathname.startsWith(href); return ( = [ + { label: "24h", days: 1 }, + { label: "3d", days: 3 }, + { label: "7d", days: 7 }, + { label: "14d", days: 14 }, + { label: "30d", days: 30 }, + { label: "Cycle", days: "cycle" }, +]; + +export function formatTimeLabel(range: TimeRange): string { + if (range === "cycle") return "cycle"; + return range === 1 ? "24h" : `${range}d`; +} + +export function TimeRangeSelector({ value }: { value: TimeRange }) { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const [pending, startTransition] = useTransition(); + + function select(range: TimeRange) { + const params = new URLSearchParams(searchParams); + if (range === DEFAULT_RANGE) params.delete("range"); + else params.set("range", String(range)); + const query = params.toString(); + startTransition(() => router.replace(query ? `${pathname}?${query}` : pathname)); + } + + return ( +
+ {TIME_RANGES.map((r) => ( + + ))} +
+ ); +} diff --git a/src/lib/time-range.ts b/src/lib/time-range.ts new file mode 100644 index 0000000..86fa7c8 --- /dev/null +++ b/src/lib/time-range.ts @@ -0,0 +1,17 @@ +export type TimeRange = number | "cycle"; + +export const DEFAULT_RANGE: TimeRange = "cycle"; + +export function parseRange(value?: string): TimeRange { + if (value === "cycle") return "cycle"; + return parseInt(value ?? "", 10) || DEFAULT_RANGE; +} + +export function userHref(email: string, range: TimeRange): string { + const base = `/users/${encodeURIComponent(email)}`; + return range === DEFAULT_RANGE ? base : `${base}?range=${range}`; +} + +export function overviewHref(range: TimeRange): string { + return range === DEFAULT_RANGE ? "/" : `/?range=${range}`; +} From eb5853b1a5119fc3cd087dffc2b4f9390e220ad5 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:31:39 +0100 Subject: [PATCH 3/7] feat: mark billing cycle changes on the spend charts A vertical line marks each billing cycle change on the daily spend trend and on the daily spend by user bars, labelled previous cycle / new cycle. A label is left out when it would not fit inside the plot area, so it never runs over the axis near the edge of the chart. Co-Authored-By: Claude Sonnet 5.5 --- docs/FEATURES.md | 4 +- src/app/dashboard-client.tsx | 7 +- src/app/users/[email]/user-detail-client.tsx | 2 + src/components/charts/cycle-marker.tsx | 44 ++++++++++++ src/components/charts/daily-spend-chart.tsx | 50 +++++++++++++- src/components/charts/spend-trend-chart.tsx | 72 +++++++++++++------- 6 files changed, 147 insertions(+), 32 deletions(-) create mode 100644 src/components/charts/cycle-marker.tsx diff --git a/docs/FEATURES.md b/docs/FEATURES.md index a70c244..8d7e912 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -21,10 +21,10 @@ ### Charts -- **Daily Spend Trend** — area chart with avg line, provisional zone (last 2d), spike detection +- **Daily Spend Trend** — area chart with avg line, provisional zone (last 2d), cycle change marker, spike detection - **Model Cost Comparison** — table with $/request, relative multiplier (1x–8x+), color-coded - **Top Spenders** — horizontal bar chart, top 8 -- **Daily Spend by User** — stacked bar, top 6 + Others, clickable legend +- **Daily Spend by User** — stacked bar, top 6 + Others, clickable legend, cycle change marker ### Members Table diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index e3be241..304c699 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -493,6 +493,7 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash data={filteredTeamDailySpend} selectedDays={days} avgPerDay={filteredSpendCents / 100 / (days || 1)} + cycleStarts={data.cycleStarts} /> @@ -522,7 +523,11 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash )} - setSearch(name)} /> + setSearch(name)} + cycleStarts={data.cycleStarts} + />
diff --git a/src/app/users/[email]/user-detail-client.tsx b/src/app/users/[email]/user-detail-client.tsx index c3a07b7..0ef801b 100644 --- a/src/app/users/[email]/user-detail-client.tsx +++ b/src/app/users/[email]/user-detail-client.tsx @@ -16,6 +16,7 @@ import type { UsageBadge, SpendBadge, ContextBadge, AdoptionBadge } from "@/lib/ interface UserStats { windowSpendCents: number; + cycleStarts: string[]; member: | { name: string; email: string; role: string; first_seen: string; last_seen: string } | undefined; @@ -313,6 +314,7 @@ export function UserDetailClient({ email, stats, initialRange: range }: UserDeta { const activity = stats.dailyActivity.find((a) => a.date === d.date); return { diff --git a/src/components/charts/cycle-marker.tsx b/src/components/charts/cycle-marker.tsx new file mode 100644 index 0000000..d884e20 --- /dev/null +++ b/src/components/charts/cycle-marker.tsx @@ -0,0 +1,44 @@ +import { usePlotArea } from "recharts"; + +export const AXIS_STROKE = "#71717a"; +// the cycle change line sits between the widget border (zinc-800) and the "previous cycle" label (zinc-600) +export const CYCLE_STROKE = "#3f3f46"; +export const CYCLE_STROKE_WIDTH = 2; +// the "previous cycle" label is dimmer (zinc-600) than the new one +const CYCLE_TEXT = "#52525b"; + +// approximate widths of the labels, to leave out one that would run past the plot (over the axis) +const PREVIOUS_WIDTH = 84; +const NEW_WIDTH = 56; + +// labels of a billing cycle change, drawn above the plot on each side of the line: +// the old cycle in the dimmer colour, the new one in the axis text colour +export function CycleLabels({ viewBox }: { viewBox?: { x?: number; y?: number } }) { + const x = viewBox?.x ?? 0; + const y = viewBox?.y ?? 0; + const plot = usePlotArea(); + const left = plot?.x ?? 0; + const right = plot ? plot.x + plot.width : Infinity; + return ( + + + {x - 8 - PREVIOUS_WIDTH >= left && ( + + previous cycle + + )} + {x + 8 + NEW_WIDTH <= right && ( + + new cycle + + )} + + ); +} diff --git a/src/components/charts/daily-spend-chart.tsx b/src/components/charts/daily-spend-chart.tsx index a422167..7d8ca8f 100644 --- a/src/components/charts/daily-spend-chart.tsx +++ b/src/components/charts/daily-spend-chart.tsx @@ -1,8 +1,20 @@ "use client"; -import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from "recharts"; +import { + BarChart, + Bar, + XAxis, + YAxis, + Tooltip, + ResponsiveContainer, + CartesianGrid, + DefaultZIndexes, + ZIndexLayer, + usePlotArea, +} from "recharts"; import type { DailySpendDataPoint } from "@/app/dashboard-client"; import { formatDateTick, formatDateLabel } from "@/lib/date-utils"; +import { CYCLE_STROKE, CYCLE_STROKE_WIDTH, CycleLabels } from "./cycle-marker"; const COLORS = ["#3b82f6", "#8b5cf6", "#f59e0b", "#10b981", "#ef4444", "#ec4899"]; const OTHERS_COLOR = "#52525b"; @@ -10,9 +22,36 @@ const OTHERS_COLOR = "#52525b"; interface DailySpendChartProps { data: { points: DailySpendDataPoint[]; topNames: string[] }; onNameClick?: (name: string) => void; + cycleStarts?: string[]; } -export function DailySpendChart({ data, onNameClick }: DailySpendChartProps) { +// bars sit in equal bands, so a cycle change is the edge between two bands +function CycleBoundaries({ boundaries, count }: { boundaries: number[]; count: number }) { + const plot = usePlotArea(); + if (!plot) return null; + return ( + + {boundaries.map((i, k) => { + const x = plot.x + (i * plot.width) / count; + return ( + + + + + ); + })} + + ); +} + +export function DailySpendChart({ data, onNameClick, cycleStarts = [] }: DailySpendChartProps) { const { points, topNames } = data; if (!points.length) { @@ -29,11 +68,15 @@ export function DailySpendChart({ data, onNameClick }: DailySpendChartProps) { colorMap.set(key, key === "Others" ? OTHERS_COLOR : (COLORS[i % COLORS.length] ?? "#71717a")); }); + const boundaries = cycleStarts + .map((start) => points.findIndex((p) => p.date >= start)) + .filter((i) => i > 0); + return (

Daily Spend by Top Users

- + ))} +
diff --git a/src/components/charts/spend-trend-chart.tsx b/src/components/charts/spend-trend-chart.tsx index 40bbdb6..253e22f 100644 --- a/src/components/charts/spend-trend-chart.tsx +++ b/src/components/charts/spend-trend-chart.tsx @@ -11,8 +11,10 @@ import { CartesianGrid, ReferenceLine, ReferenceArea, + DefaultZIndexes, } from "recharts"; import { formatDateTick, formatDateLabel } from "@/lib/date-utils"; +import { AXIS_STROKE, CYCLE_STROKE, CYCLE_STROKE_WIDTH, CycleLabels } from "./cycle-marker"; interface SpendDataPoint { date: string; @@ -26,6 +28,7 @@ interface SpendTrendChartProps { data: Array; selectedDays?: number; avgPerDay?: number; + cycleStarts?: string[]; } function fmtDollars(v: number): string { @@ -41,7 +44,12 @@ const TOOLTIP_STYLE = { color: "#fafafa", } as const; -export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendChartProps) { +export function SpendTrendChart({ + data, + selectedDays, + avgPerDay, + cycleStarts = [], +}: SpendTrendChartProps) { if (!data.length) { return (
@@ -58,6 +66,7 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha const costPerReq = d.agent_requests && d.agent_requests > 0 ? spend / d.agent_requests : undefined; return { + idx: i, date: d.date, spend, change, @@ -77,15 +86,22 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha ? chartData[chartData.length - provisionalDays]?.date : undefined; + // a new cycle starts between two days: the line sits halfway between them + const cycleLines = cycleStarts + .map((start) => chartData.findIndex((d) => d.date >= start)) + .filter((i) => i > 0) + .map((i) => i - 0.5); + + const step = chartData.length <= 14 ? 1 : Math.floor(chartData.length / 10) + 1; + const tickIdx = chartData.map((d) => d.idx).filter((i) => i % step === 0); + const cutoffDate = selectedDays && selectedDays < data.length ? data[data.length - selectedDays]?.date : undefined; const avg = avgPerDay ?? chartData.reduce((s, d) => s + d.spend, 0) / (chartData.length || 1); - const dimEndDate = - cutoffDate && data.length > 0 - ? data[Math.max(0, data.length - (selectedDays ?? 0) - 1)]?.date - : undefined; + const dimEndIdx = + cutoffDate && data.length > 0 ? Math.max(0, data.length - (selectedDays ?? 0) - 1) : undefined; return (
@@ -109,16 +125,21 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha )}
- + formatDateTick(chartData[i]?.date ?? "")} /> - + {hasCostPerReq && ( { + content={({ active, payload }) => { if (!active || !payload?.length) return null; const pt = payload[0]?.payload as (typeof chartData)[0] | undefined; if (!pt) return null; @@ -144,7 +165,7 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha return (
- {formatDateLabel(String(label))} + {formatDateLabel(pt.date)} {!isInRange && (context)} {isProvisional && (partial)}
@@ -205,28 +226,27 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha ); }} /> - {dimEndDate && cutoffDate && ( + {dimEndIdx != null && ( )} - {provisionalStart && ( - ( + } /> - )} + ))} Date: Fri, 13 Nov 2026 17:31:50 +0100 Subject: [PATCH 4/7] feat: zoom the spend charts on the selected range The charts show exactly the selected range. The 24h range is drawn hour by hour (UTC), one bar or point per hour like the other ranges, with an axis tick every 3 hours on fixed clock hours (0h, 3h, 6h...), an average over 24 hours and $/req computed from the events of each hour. The charts are titled Hourly Spend there, and cycle markers are skipped. The trend no longer states how many days or hours it shows. Co-Authored-By: Claude Sonnet 5.5 --- src/app/dashboard-client.tsx | 33 +++++++---- src/app/users/[email]/user-detail-client.tsx | 17 ++++-- src/components/charts/daily-spend-chart.tsx | 21 +++++-- src/components/charts/spend-trend-chart.tsx | 62 +++++++------------- src/lib/date-utils.ts | 13 +++- 5 files changed, 83 insertions(+), 63 deletions(-) diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index 304c699..2e3106f 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -11,6 +11,7 @@ import Link from "next/link"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; import { DEFAULT_RANGE } from "@/lib/time-range"; +import { isHourKey } from "@/lib/date-utils"; import { TimeRangeSelector, formatTimeLabel, @@ -301,20 +302,28 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash return data.dailySpendBreakdown.filter((r) => filteredEmails.has(r.email)); }, [isSearching, data.dailySpendBreakdown, filteredEmails]); + // the 24h range comes back hour by hour: keep every hour, empty ones included + const hourKeys = useMemo( + () => + isHourKey(data.teamDailySpend[0]?.date ?? "") ? data.teamDailySpend.map((r) => r.date) : null, + [data.teamDailySpend], + ); + const filteredTeamDailySpend = useMemo(() => { if (!isSearching) return data.teamDailySpend; const byDate = new Map(); for (const r of filteredBreakdown) { byDate.set(r.date, (byDate.get(r.date) ?? 0) + r.spend_cents); } + if (hourKeys) return hourKeys.map((date) => ({ date, spend_cents: byDate.get(date) ?? 0 })); return [...byDate.entries()] .sort(([a], [b]) => a.localeCompare(b)) .map(([date, spend_cents]) => ({ date, spend_cents })); - }, [isSearching, data.teamDailySpend, filteredBreakdown]); + }, [isSearching, data.teamDailySpend, filteredBreakdown, hourKeys]); const dailySpendData = useMemo(() => { - return buildDailySpendData(filteredBreakdown); - }, [filteredBreakdown]); + return buildDailySpendData(filteredBreakdown, hourKeys); + }, [filteredBreakdown, hourKeys]); return (
@@ -491,7 +500,6 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash @@ -560,7 +568,10 @@ function shortDisplayName(fullName: string): string { return parts[0] ?? fullName; } -function buildDailySpendData(breakdown: SpendBreakdownRow[]): { +function buildDailySpendData( + breakdown: SpendBreakdownRow[], + hourKeys: string[] | null, +): { points: DailySpendDataPoint[]; topNames: string[]; } { @@ -592,12 +603,14 @@ function buildDailySpendData(breakdown: SpendBreakdownRow[]): { const topNames = topFullNames.map((n) => fullToDisplay.get(n) ?? n); const byDate = new Map(); + const addPoint = (date: string) => { + const point: DailySpendDataPoint = { date, total: 0, Others: 0 }; + for (const n of topNames) point[n] = 0; + byDate.set(date, point); + }; + for (const date of hourKeys ?? []) addPoint(date); for (const row of breakdown) { - if (!byDate.has(row.date)) { - const point: DailySpendDataPoint = { date: row.date, total: 0, Others: 0 }; - for (const n of topNames) point[n] = 0; - byDate.set(row.date, point); - } + if (!byDate.has(row.date)) addPoint(row.date); const point = byDate.get(row.date) as Record; const display = fullToDisplay.get(row.name); const dollars = row.spend_cents / 100; diff --git a/src/app/users/[email]/user-detail-client.tsx b/src/app/users/[email]/user-detail-client.tsx index 0ef801b..de88d00 100644 --- a/src/app/users/[email]/user-detail-client.tsx +++ b/src/app/users/[email]/user-detail-client.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { SpendTrendChart } from "@/components/charts/spend-trend-chart"; -import { formatDateShort } from "@/lib/date-utils"; +import { formatDateShort, isHourKey } from "@/lib/date-utils"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; import { @@ -40,7 +40,7 @@ interface UserStats { }>; modelBreakdown: Array<{ model: string; days_used: number; total_requests: number }>; anomalies: Anomaly[]; - dailySpend: Array<{ date: string; spend_cents: number }>; + dailySpend: Array<{ date: string; spend_cents: number; requests?: number }>; usageEventsSummary: Array<{ model: string; requests: number; @@ -215,7 +215,16 @@ export function UserDetailClient({ email, stats, initialRange: range }: UserDeta const windowDays = range === "cycle" ? cycleDaysElapsed : range; const dailyAvgSpend = windowSpendDollars / windowDays; - const mergedDailyData = buildMergedDailyData(stats.dailySpend, stats.dailyActivity); + // the 24h range charts hours; the table below stays per day + const spendByDay = new Map(); + for (const d of stats.dailySpend) { + const day = d.date.slice(0, 10); + spendByDay.set(day, (spendByDay.get(day) ?? 0) + d.spend_cents); + } + const dailySpendRows = isHourKey(stats.dailySpend[0]?.date ?? "") + ? [...spendByDay].map(([date, spend_cents]) => ({ date, spend_cents })) + : stats.dailySpend; + const mergedDailyData = buildMergedDailyData(dailySpendRows, stats.dailyActivity); const hasUsageEvents = stats.usageEventsSummary.length > 0; const userBadges: string[] = []; @@ -319,7 +328,7 @@ export function UserDetailClient({ email, stats, initialRange: range }: UserDeta const activity = stats.dailyActivity.find((a) => a.date === d.date); return { ...d, - agent_requests: activity?.agent_requests, + agent_requests: activity?.agent_requests ?? d.requests, lines_added: activity?.lines_added, lines_deleted: activity?.lines_deleted, }; diff --git a/src/components/charts/daily-spend-chart.tsx b/src/components/charts/daily-spend-chart.tsx index 7d8ca8f..a04b032 100644 --- a/src/components/charts/daily-spend-chart.tsx +++ b/src/components/charts/daily-spend-chart.tsx @@ -13,7 +13,7 @@ import { usePlotArea, } from "recharts"; import type { DailySpendDataPoint } from "@/app/dashboard-client"; -import { formatDateTick, formatDateLabel } from "@/lib/date-utils"; +import { formatDateTick, formatDateLabel, isHourKey, isTickHour } from "@/lib/date-utils"; import { CYCLE_STROKE, CYCLE_STROKE_WIDTH, CycleLabels } from "./cycle-marker"; const COLORS = ["#3b82f6", "#8b5cf6", "#f59e0b", "#10b981", "#ef4444", "#ec4899"]; @@ -68,17 +68,26 @@ export function DailySpendChart({ data, onNameClick, cycleStarts = [] }: DailySp colorMap.set(key, key === "Others" ? OTHERS_COLOR : (COLORS[i % COLORS.length] ?? "#71717a")); }); - const boundaries = cycleStarts - .map((start) => points.findIndex((p) => p.date >= start)) - .filter((i) => i > 0); + const hourly = isHourKey(points[0]?.date ?? ""); + const boundaries = hourly + ? [] + : cycleStarts.map((start) => points.findIndex((p) => p.date >= start)).filter((i) => i > 0); return (
-

Daily Spend by Top Users

+

+ {hourly ? "Hourly" : "Daily"} Spend by Top Users +

- + p.date).filter(isTickHour), interval: 0 })} + /> ; - selectedDays?: number; avgPerDay?: number; cycleStarts?: string[]; } @@ -44,12 +42,7 @@ const TOOLTIP_STYLE = { color: "#fafafa", } as const; -export function SpendTrendChart({ - data, - selectedDays, - avgPerDay, - cycleStarts = [], -}: SpendTrendChartProps) { +export function SpendTrendChart({ data, avgPerDay, cycleStarts = [] }: SpendTrendChartProps) { if (!data.length) { return (
@@ -80,34 +73,33 @@ export function SpendTrendChart({ const hasCostPerReq = chartData.some((d) => d.costPerReq != null); - const provisionalDays = 2; + const hourly = isHourKey(data[0]?.date ?? ""); + const provisionalDays = hourly ? 1 : 2; const provisionalStart = chartData.length > provisionalDays ? chartData[chartData.length - provisionalDays]?.date : undefined; // a new cycle starts between two days: the line sits halfway between them - const cycleLines = cycleStarts - .map((start) => chartData.findIndex((d) => d.date >= start)) - .filter((i) => i > 0) - .map((i) => i - 0.5); + const cycleLines = hourly + ? [] + : cycleStarts + .map((start) => chartData.findIndex((d) => d.date >= start)) + .filter((i) => i > 0) + .map((i) => i - 0.5); const step = chartData.length <= 14 ? 1 : Math.floor(chartData.length / 10) + 1; - const tickIdx = chartData.map((d) => d.idx).filter((i) => i % step === 0); + const tickIdx = chartData + .filter((d) => (hourly ? isTickHour(d.date) : d.idx % step === 0)) + .map((d) => d.idx); - const cutoffDate = - selectedDays && selectedDays < data.length ? data[data.length - selectedDays]?.date : undefined; - - const avg = avgPerDay ?? chartData.reduce((s, d) => s + d.spend, 0) / (chartData.length || 1); - - const dimEndIdx = - cutoffDate && data.length > 0 ? Math.max(0, data.length - (selectedDays ?? 0) - 1) : undefined; + const total = chartData.reduce((s, d) => s + d.spend, 0); + const avg = hourly ? total / 24 : (avgPerDay ?? total / (chartData.length || 1)); return (
-

Daily Spend

- {data.length} days of data +

{hourly ? "Hourly" : "Daily"} Spend

spend @@ -120,7 +112,9 @@ export function SpendTrendChart({ )} {provisionalStart && ( - Last {provisionalDays}d may be partial · daily shape from events, totals match billing + {hourly + ? "Current hour may be partial · hourly shape from events, totals match billing" + : `Last ${provisionalDays}d may be partial · daily shape from events, totals match billing`} )}
@@ -158,7 +152,6 @@ export function SpendTrendChart({ if (!active || !payload?.length) return null; const pt = payload[0]?.payload as (typeof chartData)[0] | undefined; if (!pt) return null; - const isInRange = !cutoffDate || pt.date >= cutoffDate; const isProvisional = provisionalStart != null && pt.date >= provisionalStart; const changeColor = pt.change > 0 ? "#ef4444" : pt.change < 0 ? "#22c55e" : "#a1a1aa"; const changeSign = pt.change > 0 ? "+" : ""; @@ -166,7 +159,6 @@ export function SpendTrendChart({
{formatDateLabel(pt.date)} - {!isInRange && (context)} {isProvisional && (partial)}
@@ -175,11 +167,11 @@ export function SpendTrendChart({ {pt.change !== 0 && (
{changeSign} - {pt.changePct.toFixed(0)}% vs prev day + {pt.changePct.toFixed(0)}% vs prev {hourly ? "hour" : "day"}
)}
- avg ${Math.round(avg).toLocaleString()}{" "} + avg {fmtDollars(avg)}{" "} avg ? "#ef4444" : "#22c55e" }}> ({pt.spend > avg ? "+" : ""} {(((pt.spend - avg) / avg) * 100).toFixed(0)}%) @@ -226,16 +218,6 @@ export function SpendTrendChart({ ); }} /> - {dimEndIdx != null && ( - - )} {cycleLines.map((x, k) => ( key.length === 13; + +// the 24h charts tick every 3 hours on fixed clock hours (0h, 3h, 6h...) so the marks stay stable +export const isTickHour = (key: string) => Number(key.slice(11)) % 3 === 0; + export function formatDateTick(dateStr: string): string { + if (isHourKey(dateStr)) return `${dateStr.slice(11)}h`; const d = new Date(dateStr + "T00:00:00"); const day = DAYS[d.getDay()] ?? ""; return `${day} ${dateStr.slice(8)}`; } export function formatDateLabel(dateStr: string): string { - const d = new Date(dateStr + "T00:00:00"); - const day = DAYS[d.getDay()] ?? ""; - return `${day}, ${dateStr}`; + const date = dateStr.slice(0, 10); + const day = DAYS[new Date(`${date}T00:00:00`).getDay()] ?? ""; + return isHourKey(dateStr) ? `${day}, ${date} ${dateStr.slice(11)}:00 UTC` : `${day}, ${dateStr}`; } export function timeAgo(dateStr: string): string { From 58241c4aeb24515c36c7b9caa9665e8354a69ba2 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:32:03 +0100 Subject: [PATCH 5/7] feat: count requests and active members from usage events on the 24h range On the 24h range the spend covers the last 24 hours, but requests, active members and the $/request ratios came from daily data starting at yesterday's midnight, so the figures did not describe the same window. They now come from the usage events of the last 24 hours, on the Overview and on the user page. Lines are only kept per day, so the Lines card is left out of the 24h range. Co-Authored-By: Claude Sonnet 5.5 --- src/app/dashboard-client.tsx | 12 ++-- src/app/users/[email]/user-detail-client.tsx | 6 +- src/lib/data/sqlite.ts | 60 ++++++++++++++------ tests/rolling-24h.test.ts | 11 ++++ 4 files changed, 67 insertions(+), 22 deletions(-) diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index 2e3106f..8304811 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -470,11 +470,13 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash value={fmt(filteredAgentRequests)} sub={`~${fmt(Math.round(filteredAgentRequests / (days || 1)))}/day`} /> - + {range !== 1 && ( + + )}
{/* Search result banner */} diff --git a/src/app/users/[email]/user-detail-client.tsx b/src/app/users/[email]/user-detail-client.tsx index de88d00..684c427 100644 --- a/src/app/users/[email]/user-detail-client.tsx +++ b/src/app/users/[email]/user-detail-client.tsx @@ -201,7 +201,11 @@ const BADGE_STYLES: Record sum + d.agent_requests, 0); + // the 24h range counts the usage events of each hour, daily activity cannot start at an exact hour + const totalAgentRequests = + range === 1 + ? stats.dailySpend.reduce((sum, d) => sum + (d.requests ?? 0), 0) + : stats.dailyActivity.reduce((sum, d) => sum + d.agent_requests, 0); const cycleStart = currentSpend?.cycle_start; const windowSpendDollars = stats.windowSpendCents / 100; const dollarsPerReq = diff --git a/src/lib/data/sqlite.ts b/src/lib/data/sqlite.ts index 03aff81..bcb5553 100644 --- a/src/lib/data/sqlite.ts +++ b/src/lib/data/sqlite.ts @@ -1101,18 +1101,34 @@ export function getFullDashboard(range: TimeRange = 7): FullDashboard { ? billing.cycleStartMs : Date.parse(`${since}T00:00:00.000Z`); + // daily activity cannot start at an exact hour: the 24h range counts usage events instead, + // so requests and active members cover the same window as the spend + const eventRequests = hourly + ? new Map( + ( + db + .prepare( + `SELECT user_email as email, COUNT(*) as n FROM usage_events + WHERE is_chargeable = 1 AND CAST(timestamp AS INTEGER) >= ? GROUP BY user_email`, + ) + .all(sinceMs) as Array<{ email: string; n: number }> + ).map((r) => [r.email, r.n]), + ) + : null; + const totalMembers = (db.prepare("SELECT COUNT(*) as c FROM members WHERE is_removed = 0").get() as { c: number }) ?.c ?? 0; - const activeMembers = - ( - db - .prepare( - "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= ?", - ) - .get(since) as { c: number } - )?.c ?? 0; + const activeMembers = eventRequests + ? eventRequests.size + : (( + db + .prepare( + "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= ?", + ) + .get(since) as { c: number } + )?.c ?? 0); const windowSpend = spendSince(db, sinceMs); const chartSpend = hourly ? spendSince(db, sinceMs, true) : windowSpend; @@ -1136,11 +1152,13 @@ export function getFullDashboard(range: TimeRange = 7): FullDashboard { const spendRow = { total: totalSpendCentsForWindow }; - const agentRow = db - .prepare( - "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= ?", - ) - .get(since) as { total: number }; + const agentRow = eventRequests + ? { total: [...eventRequests.values()].reduce((sum, n) => sum + n, 0) } + : (db + .prepare( + "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= ?", + ) + .get(since) as { total: number }); const activeAnomalies = ( @@ -1232,10 +1250,18 @@ export function getFullDashboard(range: TimeRange = 7): FullDashboard { }>; const rankedUsers = rankedRows - .map((u) => ({ ...u, spend_cents: windowSpend.totals.get(u.email) ?? 0 })) + .map((u) => ({ + ...u, + spend_cents: windowSpend.totals.get(u.email) ?? 0, + // lines are only kept per day + ...(eventRequests && { agent_requests: eventRequests.get(u.email) ?? 0, lines_added: 0 }), + })) .sort((x, y) => y.spend_cents - x.spend_cents); for (const u of rankedUsers) { u.spend_rank = 1 + rankedUsers.filter((o) => o.spend_cents > u.spend_cents).length; + if (eventRequests) { + u.activity_rank = 1 + rankedUsers.filter((o) => o.agent_requests > u.agent_requests).length; + } } let teamDailySpend: Array<{ date: string; spend_cents: number }> = []; @@ -1328,7 +1354,9 @@ export function getFullDashboard(range: TimeRange = 7): FullDashboard { users: mc.users, avg_spend: Math.round(spend / 100 / Math.max(1, mc.users)), total_spend: Math.round(spend / 100), - total_reqs: mc.total_reqs, + total_reqs: eventRequests + ? emails.reduce((sum, e) => sum + (eventRequests.get(e) ?? 0), 0) + : mc.total_reqs, emails, }; }) @@ -1727,7 +1755,7 @@ export function getUserStats(email: string, range: TimeRange = 7) { `SELECT strftime('%Y-%m-%dT%H', CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as hour, COUNT(*) as n FROM usage_events - WHERE user_email = ? AND CAST(timestamp AS INTEGER) >= ? + WHERE user_email = ? AND is_chargeable = 1 AND CAST(timestamp AS INTEGER) >= ? GROUP BY hour`, ) .all(email, sinceMs) as Array<{ hour: string; n: number }> diff --git a/tests/rolling-24h.test.ts b/tests/rolling-24h.test.ts index 8d98d38..02b8558 100644 --- a/tests/rolling-24h.test.ts +++ b/tests/rolling-24h.test.ts @@ -67,6 +67,17 @@ describe("24h range is a rolling window with hourly bars", () => { expect(chart.reduce((sum, r) => sum + r.spend_cents, 0)).toBe(1000 + 600); }); + it("counts requests and active members from the events of the last 24 hours", () => { + freeze("2026-11-13T14:41:00Z"); + const { stats } = sqlite.getFullDashboard(1); + expect(stats.totalAgentRequests).toBe(4); // b: 2, c: 2 (its event at 14:30 yesterday is out) + expect(stats.activeMembers).toBe(2); + expect(stats.rankedUsers.find((u) => u.email === "c@x.com")?.agent_requests).toBe(2); + // the user page counts the same events, hour by hour + const hours = sqlite.getUserStats("c@x.com", 1).dailySpend; + expect(hours.reduce((sum, r) => sum + (r.requests ?? 0), 0)).toBe(2); + }); + it("is unaffected by a daylight saving change in the local time zone", () => { const tz = process.env.TZ; process.env.TZ = "Europe/Paris"; From 99674580c908b8d1100c7a52e1e69f89bc63bbb1 Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:33:32 +0100 Subject: [PATCH 6/7] feat: stack the time charts and the rankings in columns Daily Spend by Top Users now sits under Team Spend Trend and Top Spenders under Model Cost Comparison, so the two charts over time share a column instead of being read diagonally. Co-Authored-By: Claude Sonnet 5.5 --- src/app/dashboard-client.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index 8304811..b6b853b 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -521,6 +521,13 @@ export function DashboardClient({ initialData: data, initialRange: range }: Dash {/* ── Charts ── */}
+ + setSearch(name)} + cycleStarts={data.cycleStarts} + /> + {(exp) => ( )} - - setSearch(name)} - cycleStarts={data.cycleStarts} - /> -
{/* ── Table ── */} From c50b93e9c44d03d60bd9ec2322caec142e02368a Mon Sep 17 00:00:00 2001 From: Alexandre Paixao <368155+alex-pex@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:58:19 +0100 Subject: [PATCH 7/7] feat: make the whole members row clickable The row now opens the user page, keeping the selected range. The arrow lightens on row hover instead of on its own hover. Co-Authored-By: Claude Sonnet 5.5 --- src/components/dashboard/members-table.tsx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/components/dashboard/members-table.tsx b/src/components/dashboard/members-table.tsx index 05d1b04..9becccc 100644 --- a/src/components/dashboard/members-table.tsx +++ b/src/components/dashboard/members-table.tsx @@ -1,6 +1,7 @@ "use client"; import Link from "next/link"; +import { useRouter } from "next/navigation"; import { useState, useRef, useEffect } from "react"; import type { RankedUser, UsageBadge, SpendBadge, ContextBadge, AdoptionBadge } from "@/lib/data"; import type { SortColumn } from "@/app/dashboard-client"; @@ -299,6 +300,7 @@ export function MembersTable({ badgeFilter, onBadgeFilter, }: MembersTableProps) { + const router = useRouter(); const sortLabel = sortCol === "spend" ? "Spend" @@ -434,7 +436,11 @@ export function MembersTable({ return ( { + if ((e.target as HTMLElement).closest("a, button")) return; + router.push(userHref(row.email, range)); + }} + className={`border-b border-zinc-800/50 transition-colors cursor-pointer group ${ isHighlighted ? "bg-blue-500/10 ring-1 ring-blue-500/30" : "hover:bg-zinc-800/30" @@ -577,7 +583,7 @@ export function MembersTable({ →