// The OpenCode session statistics report (`/experimental/session/stats`), as // the OpenChamber web client's 统计 page reads it: prompts, steps, tokens, // cost, activity, models and (on request) tool calls. import '../l10n.dart'; /// The ranges the page offers; the server only needs the start timestamp. enum UsageRange { day, week, month, quarter, all } extension UsageRangeX on UsageRange { /// Days included, today counted; null for all time. int? get days => switch (this) { UsageRange.day => 1, UsageRange.week => 7, UsageRange.month => 30, UsageRange.quarter => 90, UsageRange.all => null, }; /// Local midnight at the start of the range, in milliseconds; null for all /// time (the server then starts at the oldest message). int? startFrom(DateTime now) { final days = this.days; if (days == null) return null; final today = DateTime(now.year, now.month, now.day); return today.subtract(Duration(days: days - 1)).millisecondsSinceEpoch; } } class UsageTokens { final int input; final int output; final int reasoning; final int cacheRead; final int cacheWrite; const UsageTokens({ this.input = 0, this.output = 0, this.reasoning = 0, this.cacheRead = 0, this.cacheWrite = 0, }); /// Everything the model read or wrote, cache included. int get total => input + output + reasoning + cacheRead + cacheWrite; /// What the model produced: the answer plus its reasoning. int get produced => output + reasoning; factory UsageTokens.fromJson(Map? j) { if (j == null) return const UsageTokens(); final cache = j['cache'] as Map? ?? const {}; int n(Object? v) => (v as num?)?.toInt() ?? 0; return UsageTokens( input: n(j['input']), output: n(j['output']), reasoning: n(j['reasoning']), cacheRead: n(cache['read']), cacheWrite: n(cache['write']), ); } } class UsageModelStat { final String providerId; final String modelId; final String? variant; final int steps; final UsageTokens tokens; final double cost; const UsageModelStat({ required this.providerId, required this.modelId, this.variant, this.steps = 0, this.tokens = const UsageTokens(), this.cost = 0, }); factory UsageModelStat.fromJson(Map j) { final model = j['model'] as Map? ?? const {}; final variant = model['variant']; return UsageModelStat( providerId: model['providerID'] as String? ?? '', modelId: model['id'] as String? ?? '', variant: variant is String && variant.isNotEmpty ? variant : null, steps: (j['steps'] as num?)?.toInt() ?? 0, tokens: UsageTokens.fromJson(j['tokens'] as Map?), cost: (j['cost'] as num?)?.toDouble() ?? 0, ); } } class UsageToolStat { final String name; final int calls; final int succeeded; final int failed; final int unfinished; /// Median duration in milliseconds; null when the server did not measure it. final double? durationP50; const UsageToolStat({ required this.name, this.calls = 0, this.succeeded = 0, this.failed = 0, this.unfinished = 0, this.durationP50, }); factory UsageToolStat.fromJson(Map j) => UsageToolStat( name: j['name'] as String? ?? '', calls: (j['calls'] as num?)?.toInt() ?? 0, succeeded: (j['succeeded'] as num?)?.toInt() ?? 0, failed: (j['failed'] as num?)?.toInt() ?? 0, unfinished: (j['unfinished'] as num?)?.toInt() ?? 0, durationP50: (j['durationP50'] as num?)?.toDouble(), ); } class UsageTools { /// `none`, `summary` or `detail`. final String mode; final int calls; final int succeeded; final int failed; final int unfinished; final List rows; const UsageTools({ this.mode = 'none', this.calls = 0, this.succeeded = 0, this.failed = 0, this.unfinished = 0, this.rows = const [], }); bool get hasTotals => mode == 'summary' || mode == 'detail'; bool get hasDetail => mode == 'detail'; factory UsageTools.fromJson(Map? j) { if (j == null) return const UsageTools(); final totals = j['totals'] as Map? ?? const {}; int n(Object? v) => (v as num?)?.toInt() ?? 0; return UsageTools( mode: j['mode'] as String? ?? 'none', calls: n(totals['calls']), succeeded: n(totals['succeeded']), failed: n(totals['failed']), unfinished: n(totals['unfinished']), rows: [ for (final row in (j['usage'] as List?) ?? const []) if (row is Map) UsageToolStat.fromJson(row), ], ); } } class UsageActivityDay { final String date; final int steps; const UsageActivityDay(this.date, this.steps); factory UsageActivityDay.fromJson(Map j) => UsageActivityDay( j['date'] as String? ?? '', (j['steps'] as num?)?.toInt() ?? 0, ); } class UsageStats { final int from; final int to; final int sessions; final int subagents; final int prompts; final int steps; final UsageTokens tokens; final double cost; final int activeDays; final int streak; final List activity; final List models; final UsageTools tools; const UsageStats({ this.from = 0, this.to = 0, this.sessions = 0, this.subagents = 0, this.prompts = 0, this.steps = 0, this.tokens = const UsageTokens(), this.cost = 0, this.activeDays = 0, this.streak = 0, this.activity = const [], this.models = const [], this.tools = const UsageTools(), }); bool get isEmpty => prompts == 0 && steps == 0; factory UsageStats.fromJson(Map j) { final range = j['range'] as Map? ?? const {}; int n(Object? v) => (v as num?)?.toInt() ?? 0; return UsageStats( from: n(range['from']), to: n(range['to']), sessions: n(j['sessions']), subagents: n(j['subagents']), prompts: n(j['prompts']), steps: n(j['steps']), tokens: UsageTokens.fromJson(j['tokens'] as Map?), cost: (j['cost'] as num?)?.toDouble() ?? 0, activeDays: n(j['activeDays']), streak: n(j['streak']), activity: [ for (final day in (j['activity'] as List?) ?? const []) if (day is Map) UsageActivityDay.fromJson(day), ], models: [ for (final model in (j['models'] as List?) ?? const []) if (model is Map) UsageModelStat.fromJson(model), ], tools: UsageTools.fromJson(j['tools'] as Map?), ); } } /// One column of the activity chart: a day, or a week once the range is too /// long for daily bars. class UsageBar { final String start; final String end; final int steps; const UsageBar(this.start, this.end, this.steps); } class UsageActivitySeries { final bool weekly; final List bars; final int max; const UsageActivitySeries(this.weekly, this.bars, this.max); } const _maxDailyBars = 92; String _dateKey(DateTime date) => '${date.year}-${date.month.toString().padLeft(2, '0')}-' '${date.day.toString().padLeft(2, '0')}'; /// Fills the inactive days with zero so the chart shows the whole range, and /// groups into weeks past 92 days so the bars stay readable. UsageActivitySeries buildUsageActivity(UsageStats stats) { if (stats.from <= 0 || stats.to <= 0) { return const UsageActivitySeries(false, [], 0); } final stepsByDay = { for (final day in stats.activity) day.date: day.steps, }; final first = DateTime.fromMillisecondsSinceEpoch(stats.from); final last = DateTime.fromMillisecondsSinceEpoch(stats.to - 1); final lastKey = _dateKey(last); final days = []; var cursor = DateTime(first.year, first.month, first.day); while (true) { final key = _dateKey(cursor); days.add(UsageBar(key, key, stepsByDay[key] ?? 0)); if (key == lastKey) break; cursor = DateTime(cursor.year, cursor.month, cursor.day + 1); // A bogus timestamp must not spin forever. if (days.length > 4000) break; } if (days.length <= _maxDailyBars) { return UsageActivitySeries( false, days, days.fold(0, (peak, day) => day.steps > peak ? day.steps : peak)); } final weeks = []; for (var i = 0; i < days.length; i += 7) { final chunk = days.sublist(i, (i + 7).clamp(0, days.length)); weeks.add(UsageBar( chunk.first.start, chunk.last.end, chunk.fold(0, (sum, day) => sum + day.steps), )); } return UsageActivitySeries( true, weeks, weeks.fold(0, (peak, week) => week.steps > peak ? week.steps : peak)); } double? usageCacheHitRate(UsageTokens tokens) { final misses = tokens.input + tokens.cacheWrite + tokens.cacheRead; return misses > 0 ? tokens.cacheRead / misses : null; } double? usageReasoningShare(UsageTokens tokens) { final produced = tokens.produced; return produced > 0 ? tokens.reasoning / produced : null; } double? _average(int total, int count) => count > 0 ? total / count : null; double? usageTokensPerSession(UsageStats stats) => _average(stats.tokens.total, stats.sessions); double? usageStepsPerSession(UsageStats stats) => _average(stats.steps, stats.sessions); double? usageCostPerSession(UsageStats stats) => stats.sessions > 0 ? stats.cost / stats.sessions : null; double? usageCostPerMillionTokens(UsageStats stats) => stats.tokens.total > 0 ? stats.cost / stats.tokens.total * 1000000 : null; const _monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; /// `Nov 5` for the chart's ends and `11月5日` in Chinese. Kept here so every /// caller reads a day the same way. String usageDayLabel(String day) { final parts = day.split('-'); if (parts.length != 3) return day; final month = int.tryParse(parts[1]); final date = int.tryParse(parts[2]); if (month == null || date == null) return day; if (L10n.instance.isEnglish) return '${_monthNames[month - 1]} $date'; return '$month月$date日'; } /// 1.2K / 3.4M, as the web client compacts totals. String usageCompactNumber(num value) { if (value < 1000) return value.toStringAsFixed(0); final (unit, suffix) = value < 1000000 ? (1000.0, 'K') : value < 1000000000 ? (1000000.0, 'M') : (1000000000.0, 'B'); final scaled = value / unit; final text = scaled.toStringAsFixed(scaled >= 100 ? 0 : 1); return '${text.endsWith('.0') ? text.substring(0, text.length - 2) : text}$suffix'; } String usagePercent(double value) => '${(value * 100).toStringAsFixed(1)}%'; String usageCost(double value) => '\$${value.toStringAsFixed(2)}'; String usageDuration(double ms) { if (ms < 1000) return '${ms.round()} ms'; final seconds = ms / 1000; if (seconds < 60) return '${seconds.toStringAsFixed(1)} s'; final whole = seconds.floor(); return '${whole ~/ 60} min ${(whole % 60)} s'; } /// The local calendar key the report's activity days use. String usageDateKey(DateTime date) => _dateKey(date);