feat: stats page, and the client becomes Chamber Go

- 全部功能 gains 统计 (Stats): ranges Today/7/30/90 days/all time, a
  project scope (reusing the shared project sheet, plus "All projects"),
  session/prompt/token/cost/active-days/streak tiles, a daily activity
  chart (weekly past 92 days), token composition, efficiency tiles, model
  ranking by tokens/cost/steps and on-request tool-call stats; data comes
  from /api/experimental/session/stats and the day buckets use the device's
  IANA zone (a small platform channel; desktop falls back to UTC)
- the model bars draw a full-width track with a left-aligned fill, so a
  small token share reads as a sliver instead of an empty bar
- AI token strings read 词元 (not 令牌) in Chinese
- the client's display name is Chamber Go (launcher, iOS, Linux window,
  About), package unchanged; pairing/login labels and the user-agent
  follow, so a newly paired device shows "Chamber Go" on the web client's
  "Connect to this server" list
- bump to 0.5.6
This commit is contained in:
blumia committed 2026-11-26 17:18:09 +08:00
1 parent a70e9290ef
commit b65498d73e
19 files changed
+1637 -25

No files matched your search

+36 -5
View File
@@ -9,6 +9,7 @@ import 'dart:typed_data';
import '../version.dart';
import 'models.dart';
import 'scheduled_tasks.dart';
import 'usage_stats.dart';
import 'shells.dart';
import 'terminal.dart';
import 'transport.dart';
@@ -21,6 +22,11 @@ class ApiError implements Exception {
String toString() => message.isEmpty ? 'HTTP $status' : message;
}
/// What the server sees in request headers; the connect page's device name
/// comes from the pairing label below, not from this.
String _userAgent() =>
'chamber-go/${appVersion.isEmpty ? '0.0' : appVersion}';
class Client {
final Uri base;
@@ -55,7 +61,7 @@ class Client {
required String pairingId,
required String secret,
required String installId,
String clientLabel = 'OpenChamber Native',
String clientLabel = 'Chamber Go',
String clientKind = 'mobile',
String? deviceName,
}) async {
@@ -78,7 +84,7 @@ class Client {
}
Future<Map<String, dynamic>> login(String password, String installId,
{String label = 'OpenChamber Native', String clientKind = 'mobile'}) async {
{String label = 'Chamber Go', String clientKind = 'mobile'}) async {
return _json('POST', '/auth/session', body: {
'password': password,
'trustDevice': true,
@@ -214,6 +220,31 @@ class Client {
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
}
/// The session statistics report. [from] is milliseconds since the epoch and
/// omitted for all time; [project] is the OpenCode project id (not the
/// settings row id); [timezone] is an IANA name and decides how the server
/// buckets days. Tool details cost a scan of every message, so they are only
/// read when [tools] is true.
Future<UsageStats> sessionStats({
int? from,
int? to,
String? project,
required String timezone,
bool tools = false,
String? directory,
}) async {
final r = await _json('GET', '/api/experimental/session/stats',
query: {
if (from != null) 'from': '$from',
if (to != null) 'to': '$to',
if (project != null && project.isNotEmpty) 'project': project,
'timezone': timezone,
'tools': tools ? 'detail' : 'none',
},
directory: directory);
return UsageStats.fromJson(r['data'] as Map<String, dynamic>? ?? const {});
}
Future<Page<Message>> listMessages(String id,
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
final query = <String, String>{
@@ -693,7 +724,7 @@ class Client {
headers: {
'accept': 'text/event-stream',
'cache-control': 'no-cache',
'user-agent': 'openchamber-native/0.3',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
},
));
@@ -976,7 +1007,7 @@ class Client {
/// The headers the terminal socket needs (auth, and the workspace the
/// server routes the upgrade by).
Map<String, String> get eventHeaders => {
'user-agent': 'openchamber-native/0.3',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
@@ -1033,7 +1064,7 @@ class Client {
bool noCompression = false}) async {
final headers = <String, String>{
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
'user-agent': 'openchamber-native/0.3',
'user-agent': _userAgent(),
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
};
if (directory != null && directory.isNotEmpty) {
+364
View File
@@ -0,0 +1,364 @@
// 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<String, dynamic>? j) {
if (j == null) return const UsageTokens();
final cache = j['cache'] as Map<String, dynamic>? ?? 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<String, dynamic> j) {
final model = j['model'] as Map<String, dynamic>? ?? 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<String, dynamic>?),
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<String, dynamic> 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<UsageToolStat> 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<String, dynamic>? j) {
if (j == null) return const UsageTools();
final totals = j['totals'] as Map<String, dynamic>? ?? 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<String, dynamic>) UsageToolStat.fromJson(row),
],
);
}
}
class UsageActivityDay {
final String date;
final int steps;
const UsageActivityDay(this.date, this.steps);
factory UsageActivityDay.fromJson(Map<String, dynamic> 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<UsageActivityDay> activity;
final List<UsageModelStat> 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<String, dynamic> j) {
final range = j['range'] as Map<String, dynamic>? ?? 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<String, dynamic>?),
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<String, dynamic>) UsageActivityDay.fromJson(day),
],
models: [
for (final model in (j['models'] as List?) ?? const [])
if (model is Map<String, dynamic>) UsageModelStat.fromJson(model),
],
tools: UsageTools.fromJson(j['tools'] as Map<String, dynamic>?),
);
}
}
/// 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<UsageBar> 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 = <UsageBar>[];
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 = <UsageBar>[];
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);
+52 -1
View File
@@ -481,7 +481,7 @@ const Map<String, String> chineseStrings = {
'Title': '标题',
'Today': '今天',
'Todos': '待办',
'Tokens used': '已用 tokens',
'Tokens used': '已用词元',
'Tool': '工具',
'Tools for servers and agents are collected here.': '服务器与智能体的工具都收在这里。',
'Transfer interrupted': '传输被中断',
@@ -548,4 +548,55 @@ const Map<String, String> chineseStrings = {
'“{0}” and its subagent sessions will be deleted permanently.': '“{0}”及其子会话将被删除,且无法恢复。',
'“{0}” will be removed from the list, and its device token will be deleted.': '“{0}”将从列表移除,设备令牌也会删除。',
'📎 {0} attachments': '📎 {0} 个附件',
// stats
'Stats': '统计',
'Prompts, tokens, cost and model activity': '提示词、词元、费用与模型活动',
'All projects': '所有项目',
'7 days': '7 天',
'30 days': '30 天',
'90 days': '90 天',
'All time': '全部时间',
"Couldn't load stats": '无法加载统计',
'Try again': '重试',
'No activity in this period': '这段时间没有活动',
'Sessions you run will show up here.': '你运行的会话会显示在这里。',
'No model usage in this period.': '这段时间没有模型使用。',
'Prompts': '提示词',
'Tokens': '词元',
'Cost': '费用',
'Active days': '活跃天数',
'Longest streak (days)': '最长连续天数',
'Weekly activity': '每周活动',
'Daily activity': '每日活动',
'Model steps per week': '每周的模型步数',
'Model steps per day': '每天的模型步数',
'Token composition': '词元构成',
'Efficiency': '效率',
'Cache hit rate': '缓存命中率',
'Cost / session': '每个会话费用',
'Cost per 1M tokens': '每百万词元费用',
'Tokens / session': '每个会话词元',
'Steps / session': '每个会话步数',
'Reasoning share': '推理占比',
'Input': '输入',
'Output + reasoning': '输出 + 推理',
'Cache reads': '缓存读取',
'Cache writes': '缓存写入',
'Models': '模型',
'Steps': '步数',
'Tool calls': '工具调用',
'Counting them reads every message in the period.': '统计工具调用需要读取这段时间的每条消息。',
'Calls': '调用次数',
'Success rate': '成功率',
'Failed': '失败',
'Unfinished': '未完成',
'Updated {0}': '更新于 {0}',
'Subagents: {0}': '子代理:{0}',
'In {0} · Out {1} · Cache {2}': '输入 {0} · 输出 {1} · 缓存 {2}',
'{0} · steps: {1}': '{0} · 步数 {1}',
'{0} steps': '{0} 步',
'calls: {0} · median: {1}': '调用 {0} · 中位耗时 {1}',
'calls: {0}': '调用 {0}',
'OpenChamber mobile client': 'OpenChamber 移动客户端',
};
+9
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../state.dart';
import 'scheduled_tasks_screen.dart';
import 'stats_screen.dart';
import '../l10n.dart';
class FeaturesScreen extends StatelessWidget {
@@ -37,6 +38,14 @@ class FeaturesScreen extends StatelessWidget {
builder: (_) => ScheduledTasksScreen(app: app),
)),
),
_FeatureTile(
icon: Icons.query_stats,
title: 'Stats',
caption: 'Prompts, tokens, cost and model activity',
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => StatsScreen(app: app),
)),
),
],
),
],
+4 -4
View File
@@ -923,10 +923,10 @@ class _AboutSettingsPageState extends State<AboutSettingsPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AppText('OpenChamber',
style: theme.textTheme.titleLarge
?.copyWith(fontWeight: FontWeight.w600)),
AppText('Mobile client',
const AppText('Chamber Go',
style: TextStyle(
fontSize: 22, fontWeight: FontWeight.w600)),
AppText('OpenChamber mobile client',
style: TextStyle(
fontSize: 12.5, color: theme.hintColor)),
],
+924
View File
@@ -0,0 +1,924 @@
// 统计: the OpenCode session statistics, as the OpenChamber web client shows
// them — prompts, steps, tokens, cost, activity, models and tool calls — sized
// for a phone. The numbers come from `/api/experimental/session/stats`.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../api/client.dart';
import '../api/models.dart';
import '../api/usage_stats.dart';
import '../l10n.dart';
import '../state.dart';
import '../time_zone.dart';
import '../widgets/project_icon.dart';
import '../widgets/project_picker.dart';
const _tokenColors = [
Color(0xFF7C6CF6),
Color(0xFF3FB6A8),
Color(0xFFE0A03A),
Color(0xFFB06AD6),
];
/// Tools mode used for the model filter of the models section.
enum _ModelDimension { tokens, cost, steps }
class StatsScreen extends StatefulWidget {
final AppState app;
const StatsScreen({super.key, required this.app});
@override
State<StatsScreen> createState() => _StatsScreenState();
}
class _StatsScreenState extends State<StatsScreen> {
UsageRange _range = UsageRange.month;
ProjectInfo? _project;
UsageStats? _stats;
bool _loading = true;
String? _error;
int _fetchedAt = 0;
int _generation = 0;
UsageTools? _tools;
bool _toolsLoading = false;
String? _toolsError;
_ModelDimension _dimension = _ModelDimension.tokens;
int? _activeBar;
AppState get app => widget.app;
@override
void initState() {
super.initState();
_load();
}
String? get _directory => (_project?.canonical.isNotEmpty ?? false)
? _project!.canonical
: app.directory;
Future<void> _load() async {
final client = app.client;
if (client == null) {
setState(() {
_loading = false;
_error = tr('Not connected to a server');
});
return;
}
final generation = ++_generation;
setState(() {
_loading = true;
_error = null;
_activeBar = null;
});
try {
final zone = await deviceTimeZone();
final stats = await client.sessionStats(
from: _range.startFrom(DateTime.now()),
project: _project?.id,
timezone: zone,
directory: _directory,
);
if (!mounted || generation != _generation) return;
setState(() {
_stats = stats;
_loading = false;
_fetchedAt = DateTime.now().millisecondsSinceEpoch;
_tools = null;
_toolsError = null;
});
} catch (e) {
if (!mounted || generation != _generation) return;
setState(() {
_loading = false;
_error = e is ApiError ? e.message : '$e';
});
}
}
/// Tool counts make the server read every message in the window, so they are
/// only requested when the person asks for them (as in the web client).
Future<void> _loadTools() async {
final client = app.client;
final stats = _stats;
if (client == null || stats == null) return;
setState(() {
_toolsLoading = true;
_toolsError = null;
});
try {
final zone = await deviceTimeZone();
final withTools = await client.sessionStats(
from: stats.from,
to: stats.to,
project: _project?.id,
timezone: zone,
tools: true,
directory: _directory,
);
if (!mounted) return;
setState(() {
_tools = withTools.tools;
_toolsLoading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_toolsLoading = false;
_toolsError = e is ApiError ? e.message : '$e';
});
}
}
Future<void> _pickProject() async {
final choice = await showProjectPicker(
context,
app: app,
selected: _project?.canonical ?? allProjectsTarget,
includeAll: true,
includeChat: false,
);
if (choice == null || !mounted) return;
setState(() => _project = choice.isAll ? null : choice.project);
await _load();
}
String _rangeLabel(UsageRange range) => switch (range) {
UsageRange.day => tr('Today'),
UsageRange.week => tr('7 days'),
UsageRange.month => tr('30 days'),
UsageRange.quarter => tr('90 days'),
UsageRange.all => tr('All time'),
};
String _updatedLabel() {
final at = DateTime.fromMillisecondsSinceEpoch(_fetchedAt);
final now = DateTime.now();
final time = '${at.hour.toString().padLeft(2, '0')}:'
'${at.minute.toString().padLeft(2, '0')}';
final sameDay = at.year == now.year && at.month == now.month && at.day == now.day;
final text = sameDay
? time
: '${at.month.toString().padLeft(2, '0')}-'
'${at.day.toString().padLeft(2, '0')} $time';
return trArgs('Updated {0}', [text]);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const AppText('Stats'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: tr('Refresh'),
onPressed: _loading ? null : _load,
),
],
),
body: RefreshIndicator(
onRefresh: _load,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 6, 16, 40),
children: [
Wrap(
spacing: 8,
runSpacing: 4,
children: [
for (final range in UsageRange.values)
ChoiceChip(
label: Text(_rangeLabel(range)),
selected: _range == range,
onSelected: (_) {
if (_range == range) return;
setState(() => _range = range);
_load();
},
),
],
),
const SizedBox(height: 2),
_scopeRow(theme),
if (_loading && _stats != null)
const Padding(
padding: EdgeInsets.only(top: 2),
child: LinearProgressIndicator(minHeight: 2),
),
if (!_loading && _error == null && _fetchedAt > 0)
Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(top: 2, right: 6),
child: Text(_updatedLabel(),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
),
),
const SizedBox(height: 6),
..._body(theme),
],
),
),
);
}
Widget _scopeRow(ThemeData theme) {
return InkWell(
borderRadius: BorderRadius.circular(10),
onTap: _pickProject,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
child: Row(
children: [
if (_project == null)
Icon(Icons.folder_copy_outlined,
size: 18, color: theme.hintColor)
else
ProjectIcon(app: app, project: _project, size: 18),
const SizedBox(width: 8),
Expanded(
child: Text(
_project?.label ?? tr('All projects'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14),
),
),
Icon(Icons.expand_more, size: 18, color: theme.hintColor),
],
),
),
);
}
List<Widget> _body(ThemeData theme) {
final stats = _stats;
if (stats == null) {
if (_loading) {
return const [
Padding(
padding: EdgeInsets.only(top: 48),
child: Center(child: CircularProgressIndicator()),
),
];
}
return [
Padding(
padding: const EdgeInsets.only(top: 40),
child: Column(
children: [
const AppText('Couldn\'t load stats',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),
if (_error != null)
Padding(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),
child: Text(_error!,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
),
const SizedBox(height: 12),
OutlinedButton(onPressed: _load, child: const AppText('Try again')),
],
),
),
];
}
if (stats.isEmpty) {
return [
Padding(
padding: const EdgeInsets.only(top: 48),
child: Column(
children: [
AppText('No activity in this period',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurface)),
const SizedBox(height: 4),
AppText('Sessions you run will show up here.',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
],
),
),
];
}
final today = _range == UsageRange.day;
final cache = stats.tokens.cacheRead + stats.tokens.cacheWrite;
final activity = buildUsageActivity(stats);
return [
_tiles(theme, [
(
label: tr('Sessions'),
value: usageCompactNumber(stats.sessions),
hint: trArgs('Subagents: {0}', [usageCompactNumber(stats.subagents)]),
),
(label: tr('Prompts'), value: usageCompactNumber(stats.prompts), hint: null),
(
label: tr('Tokens'),
value: usageCompactNumber(stats.tokens.total),
hint: trArgs('In {0} · Out {1} · Cache {2}', [
usageCompactNumber(stats.tokens.input),
usageCompactNumber(stats.tokens.produced),
usageCompactNumber(cache),
]),
),
(label: tr('Cost'), value: usageCost(stats.cost), hint: null),
if (!today)
(
label: tr('Active days'),
value: usageCompactNumber(stats.activeDays),
hint: null,
),
if (!today)
(
label: tr('Longest streak (days)'),
value: usageCompactNumber(stats.streak),
hint: null,
),
]),
if (!today) ...[
const SizedBox(height: 18),
_sectionTitle(
theme,
activity.weekly ? tr('Weekly activity') : tr('Daily activity'),
activity.weekly ? tr('Model steps per week') : tr('Model steps per day'),
),
_activity(theme, activity),
],
if (stats.tokens.total > 0) ...[
const SizedBox(height: 18),
_sectionTitle(theme, tr('Token composition'), null),
_tokenComposition(theme, stats),
],
const SizedBox(height: 18),
_sectionTitle(theme, tr('Efficiency'), null),
_tiles(theme, _efficiencyTiles(stats)),
const SizedBox(height: 18),
_models(theme, stats),
const SizedBox(height: 18),
_toolsSection(theme),
];
}
List<({String label, String value, String? hint})> _efficiencyTiles(
UsageStats stats) {
String? percent(double? value) =>
value == null ? null : usagePercent(value);
return [
(
label: tr('Cache hit rate'),
value: percent(usageCacheHitRate(stats.tokens)) ?? '—',
hint: null,
),
(
label: tr('Cost / session'),
value: usageCostPerSession(stats) == null
? '—'
: usageCost(usageCostPerSession(stats)!),
hint: null,
),
(
label: tr('Cost per 1M tokens'),
value: usageCostPerMillionTokens(stats) == null
? '—'
: usageCost(usageCostPerMillionTokens(stats)!),
hint: null,
),
(
label: tr('Tokens / session'),
value: usageTokensPerSession(stats) == null
? '—'
: usageCompactNumber(usageTokensPerSession(stats)!),
hint: null,
),
(
label: tr('Steps / session'),
value: usageStepsPerSession(stats) == null
? '—'
: usageStepsPerSession(stats)!.toStringAsFixed(1),
hint: null,
),
(
label: tr('Reasoning share'),
value: percent(usageReasoningShare(stats.tokens)) ?? '—',
hint: null,
),
];
}
Widget _sectionTitle(ThemeData theme, String title, String? caption) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(title,
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
color: theme.colorScheme.onSurface)),
if (caption != null) ...[
const SizedBox(width: 8),
Expanded(
child: Text(caption,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
),
],
],
),
);
}
Widget _tiles(
ThemeData theme, List<({String label, String value, String? hint})> tiles) {
return LayoutBuilder(builder: (context, constraints) {
final width = (constraints.maxWidth - 8) / 2;
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final tile in tiles)
SizedBox(
width: width,
child: _StatTile(
label: tile.label,
value: tile.value,
hint: tile.hint,
),
),
],
);
});
}
Widget _activity(ThemeData theme, UsageActivitySeries series) {
if (series.bars.isEmpty) {
return const SizedBox.shrink();
}
final active = _activeBar != null && _activeBar! < series.bars.length
? series.bars[_activeBar!]
: null;
String describe(UsageBar bar) {
final range = bar.start == bar.end
? usageDayLabel(bar.start)
: '${usageDayLabel(bar.start)} – ${usageDayLabel(bar.end)}';
return trArgs('{0} · steps: {1}', [range, usageCompactNumber(bar.steps)]);
}
return Container(
decoration: BoxDecoration(
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
height: 18,
child: Align(
alignment: Alignment.centerLeft,
child: Text(
active != null
? describe(active)
: trArgs('{0} steps', [usageCompactNumber(series.max)]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
),
),
const SizedBox(height: 4),
SizedBox(
height: 96,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
for (var i = 0; i < series.bars.length; i++)
Expanded(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(
() => _activeBar = _activeBar == i ? null : i),
child: Padding(
padding: const EdgeInsets.only(right: 1),
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: series.max > 0
? series.bars[i].steps > 0
? math.max(
3,
series.bars[i].steps /
series.max *
90)
: 1.5
: 1.5,
decoration: BoxDecoration(
color: series.bars[i].steps > 0
? (active == null || _activeBar == i
? theme.colorScheme.primary
: theme.colorScheme.primary
.withValues(alpha: 0.35))
: theme.dividerColor,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(1)),
),
),
),
),
),
),
],
),
),
const SizedBox(height: 4),
Row(
children: [
Text(usageDayLabel(series.bars.first.start),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
const Spacer(),
Text(usageDayLabel(series.bars.last.end),
style: TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
],
),
);
}
Widget _tokenComposition(ThemeData theme, UsageStats stats) {
final total = stats.tokens.total;
final segments = <({String label, int value, Color color})>[
(
label: tr('Input'),
value: stats.tokens.input,
color: _tokenColors[0]
),
(
label: tr('Output + reasoning'),
value: stats.tokens.produced,
color: _tokenColors[1]
),
(
label: tr('Cache reads'),
value: stats.tokens.cacheRead,
color: _tokenColors[2]
),
(
label: tr('Cache writes'),
value: stats.tokens.cacheWrite,
color: _tokenColors[3]
),
];
return Container(
decoration: BoxDecoration(
border: Border.all(color: theme.dividerColor.withValues(alpha: 0.5)),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.all(10),
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(5),
child: SizedBox(
height: 10,
child: Row(
children: [
for (final segment in segments)
if (segment.value > 0)
Expanded(
flex: segment.value,
child: ColoredBox(color: segment.color),
),
],
),
),
),
const SizedBox(height: 8),
LayoutBuilder(builder: (context, constraints) {
final width = (constraints.maxWidth - 12) / 2;
return Wrap(
spacing: 12,
runSpacing: 6,
children: [
for (final segment in segments)
SizedBox(
width: width,
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: segment.color, shape: BoxShape.circle),
),
const SizedBox(width: 6),
Expanded(
child: Text(segment.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11, color: theme.hintColor)),
),
const SizedBox(width: 4),
Text(
'${usageCompactNumber(segment.value)} · '
'${usagePercent(segment.value / total)}',
style: const TextStyle(fontSize: 11),
),
],
),
),
],
);
}),
],
),
);
}
Widget _models(ThemeData theme, UsageStats stats) {
double valueOf(UsageModelStat model) => switch (_dimension) {
_ModelDimension.tokens => model.tokens.total.toDouble(),
_ModelDimension.cost => model.cost,
_ModelDimension.steps => model.steps.toDouble(),
};
final ranked = [...stats.models]
..sort((a, b) => valueOf(b).compareTo(valueOf(a)));
final max = ranked.fold<double>(0, (peak, model) => math.max(peak, valueOf(model)));
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_sectionTitle(theme, tr('Models'), null),
if (stats.models.isNotEmpty)
Wrap(
spacing: 8,
children: [
for (final dimension in _ModelDimension.values)
ChoiceChip(
label: Text(switch (dimension) {
_ModelDimension.tokens => tr('Tokens'),
_ModelDimension.cost => tr('Cost'),
_ModelDimension.steps => tr('Steps'),
}),
selected: _dimension == dimension,
onSelected: (_) => setState(() => _dimension = dimension),
),
],
),
const SizedBox(height: 6),
if (stats.models.isEmpty)
AppText('No model usage in this period.',
style: TextStyle(fontSize: 12, color: theme.hintColor))
else
for (final model in ranked) _modelRow(theme, model, valueOf, max),
],
);
}
Widget _modelRow(ThemeData theme, UsageModelStat model,
double Function(UsageModelStat) valueOf, double max) {
final value = valueOf(model);
final share = max > 0 ? (value / max).clamp(0.0, 1.0) : 0.0;
final name = app.modelName(ModelRef(model.modelId, model.providerId,
model.variant));
final secondary = [
if (model.variant != null && model.variant != 'default') model.variant!,
model.providerId,
].join(' · ');
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 13.5)),
),
const SizedBox(width: 8),
Text(
_dimension == _ModelDimension.steps
? '${usageCompactNumber(model.steps)} · ${usageCost(model.cost)}'
: '${usageCompactNumber(model.tokens.total)} · ${usageCost(model.cost)}',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
],
),
if (secondary.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 1),
child: Text(secondary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: theme.hintColor)),
),
const SizedBox(height: 4),
SizedBox(
height: 6,
child: ClipRRect(
borderRadius: BorderRadius.circular(3),
child: Stack(
fit: StackFit.expand,
children: [
// A full-width track: a small share still reads as a sliver
// of colour on it, not as an empty bar.
ColoredBox(color: theme.dividerColor.withValues(alpha: 0.35)),
if (share > 0)
Align(
alignment: Alignment.centerLeft,
child: FractionallySizedBox(
widthFactor: share,
heightFactor: 1,
child: _dimension == _ModelDimension.tokens
? Row(children: [
for (final (i, value) in [
model.tokens.input,
model.tokens.produced,
model.tokens.cacheRead,
model.tokens.cacheWrite,
].indexed)
if (value > 0)
Expanded(
flex: value,
child: ColoredBox(color: _tokenColors[i]),
),
])
: ColoredBox(color: theme.colorScheme.primary),
),
),
],
),
),
),
],
),
);
}
Widget _toolsSection(ThemeData theme) {
final tools = _tools != null && _tools!.hasTotals ? _tools : null;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_sectionTitle(theme, tr('Tool calls'), tr('Counting them reads every message in the period.')),
if (tools == null) ...[
if (_toolsError != null)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(_toolsError!,
style: TextStyle(
fontSize: 12, color: theme.colorScheme.error)),
),
Align(
alignment: Alignment.centerLeft,
child: OutlinedButton.icon(
onPressed: _toolsLoading ? null : _loadTools,
icon: _toolsLoading
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.build_outlined, size: 18),
label: AppText(_toolsLoading ? 'Loading…' : 'Show tool calls'),
),
),
] else ...[
_tiles(theme, [
(label: tr('Calls'), value: usageCompactNumber(tools.calls), hint: null),
(
label: tr('Success rate'),
value: tools.calls > 0
? usagePercent(tools.succeeded / tools.calls)
: '—',
hint: null,
),
(
label: tr('Failed'),
value: usageCompactNumber(tools.failed),
hint: null
),
(
label: tr('Unfinished'),
value: usageCompactNumber(tools.unfinished),
hint: null
),
]),
const SizedBox(height: 8),
for (final row in tools.rows.where((row) => row.calls > 0).take(8))
_toolRow(theme, row),
],
],
);
}
Widget _toolRow(ThemeData theme, UsageToolStat tool) {
final stats = tool.durationP50 != null
? trArgs('calls: {0} · median: {1}', [
usageCompactNumber(tool.calls),
usageDuration(tool.durationP50!),
])
: trArgs('calls: {0}', [usageCompactNumber(tool.calls)]);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(tool.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5, fontFamily: 'monospace')),
),
const SizedBox(width: 8),
Text(stats,
style: TextStyle(fontSize: 11, color: theme.hintColor)),
],
),
const SizedBox(height: 3),
ClipRRect(
borderRadius: BorderRadius.circular(3),
child: SizedBox(
height: 5,
child: Row(
children: [
if (tool.succeeded > 0)
Expanded(
flex: tool.succeeded,
child: ColoredBox(color: theme.colorScheme.primary),
),
if (tool.failed > 0)
Expanded(
flex: tool.failed,
child: ColoredBox(color: theme.colorScheme.error),
),
],
),
),
),
],
),
);
}
}
class _StatTile extends StatelessWidget {
final String label;
final String value;
final String? hint;
const _StatTile({required this.label, required this.value, this.hint});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.45),
borderRadius: BorderRadius.circular(10),
),
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
const SizedBox(height: 2),
Text(value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 19,
fontWeight: FontWeight.w600,
fontFeatures: [FontFeature.tabularFigures()])),
if (hint != null)
Padding(
padding: const EdgeInsets.only(top: 1),
child: Text(hint!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 10.5, color: theme.hintColor)),
),
],
),
);
}
}
+21
View File
@@ -0,0 +1,21 @@
// The device's IANA time zone, which the statistics API wants for bucketing
// days. Dart only exposes the abbreviation ("CST"), and Guava/ICU's zone id
// lives on the Android side; the desktop build has no zone plugin, so it
// falls back to UTC (the UI still works, only the day boundaries shift).
import 'package:flutter/services.dart';
const _channel = MethodChannel('openchamber/device');
String? _cached;
Future<String> deviceTimeZone() async {
final cached = _cached;
if (cached != null) return cached;
try {
final name = await _channel.invokeMethod<String>('ianaTimeZone');
if (name != null && name.isNotEmpty) return _cached = name;
} catch (_) {
// No handler (desktop) or a platform failure: UTC keeps the request valid.
}
return _cached = 'UTC';
}
+44 -8
View File
@@ -8,17 +8,29 @@ import '../l10n.dart';
import '../state.dart';
import 'project_icon.dart';
/// What the picker returns: the Chat row or a project checkout.
/// The "All projects" row of the stats scope picker, where a report is not
/// narrowed to one checkout.
const allProjectsTarget = '\u0000all-projects';
/// What the picker returns: the Chat row, the All projects row, or a checkout.
class ProjectChoice {
/// Null for the Chat row: a chat is not tied to a project.
/// Null for the Chat and All projects rows.
final ProjectInfo? project;
final bool all;
const ProjectChoice.chat() : project = null;
const ProjectChoice.project(this.project);
const ProjectChoice.chat()
: project = null,
all = false;
const ProjectChoice.allProjects()
: project = null,
all = true;
const ProjectChoice.project(this.project) : all = false;
bool get isChat => project == null;
String get canonical => project?.canonical ?? AppState.chatTarget;
String get label => project?.label ?? tr('Chat');
bool get isChat => project == null && !all;
bool get isAll => all;
String get canonical =>
all ? allProjectsTarget : (project?.canonical ?? AppState.chatTarget);
String get label => all ? tr('All projects') : (project?.label ?? tr('Chat'));
}
/// Opens the project sheet and returns the chosen target, or null when the
@@ -28,6 +40,8 @@ Future<ProjectChoice?> showProjectPicker(
BuildContext context, {
required AppState app,
required String selected,
bool includeAll = false,
bool includeChat = true,
}) {
return showModalBottomSheet<ProjectChoice>(
context: context,
@@ -39,6 +53,8 @@ Future<ProjectChoice?> showProjectPicker(
builder: (context, controller) => _ProjectPickerSheet(
app: app,
selected: selected,
includeAll: includeAll,
includeChat: includeChat,
controller: controller,
),
),
@@ -65,11 +81,15 @@ List<ProjectInfo> selectableProjects(AppState app) {
class _ProjectPickerSheet extends StatefulWidget {
final AppState app;
final String selected;
final bool includeAll;
final bool includeChat;
final ScrollController controller;
const _ProjectPickerSheet({
required this.app,
required this.selected,
required this.includeAll,
required this.includeChat,
required this.controller,
});
@@ -131,7 +151,23 @@ class _ProjectPickerSheetState extends State<_ProjectPickerSheet> {
: ListView(
controller: widget.controller,
children: [
ListTile(
if (widget.includeAll)
ListTile(
dense: true,
leading: Icon(Icons.folder_copy_outlined,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant),
title: const AppText('All projects'),
trailing: widget.selected == allProjectsTarget
? Icon(Icons.check,
size: 18,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () => Navigator.pop(
context, const ProjectChoice.allProjects()),
),
if (widget.includeChat)
ListTile(
dense: true,
leading:
ProjectIcon(app: widget.app, chat: true, size: 20),