From b65498d73e9524bcaf96867f7452119d37dcc7d6 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Thu, 26 Nov 2026 17:18:09 +0800 Subject: [PATCH] feat: stats page, and the client becomes Chamber Go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 全部功能 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 --- PLAN.md | 11 + README.md | 7 +- android/app/src/main/AndroidManifest.xml | 2 +- .../openchamber/flutter/MainActivity.kt | 9 + ios/Runner/Info.plist | 2 +- lib/api/client.dart | 41 +- lib/api/usage_stats.dart | 364 +++++++ lib/l10n/zh.dart | 53 +- lib/screens/features_screen.dart | 9 + lib/screens/settings_screen.dart | 8 +- lib/screens/stats_screen.dart | 924 ++++++++++++++++++ lib/time_zone.dart | 21 + lib/widgets/project_picker.dart | 52 +- linux/runner/my_application.cc | 2 +- pubspec.yaml | 2 +- test/l10n_test.dart | 1 + test/project_picker_test.dart | 38 + test/scheduled_tasks_test.dart | 2 + test/usage_stats_test.dart | 114 +++ 19 files changed, 1637 insertions(+), 25 deletions(-) create mode 100644 lib/api/usage_stats.dart create mode 100644 lib/screens/stats_screen.dart create mode 100644 lib/time_zone.dart create mode 100644 test/usage_stats_test.dart diff --git a/PLAN.md b/PLAN.md index 2a54193..2e97d41 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,17 @@ --- +## 0.5.6 统计页面与 Chamber Go(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 统计 | 全部功能里新增【统计】:时间范围(今天 / 7 天 / 30 天 / 90 天 / 全部)、项目筛选(所有项目或某个检出)、会话 / 提示词 / 令牌 / 费用 / 活跃天数 / 连续天数、每日(超过 92 天按周)活动柱状图、令牌构成、效率指标、模型排行(按令牌 / 费用 / 步数)、按需加载的工具调用统计(调用次数、成功率、失败、中位耗时)。数据来自 `/api/experimental/session/stats`;时区取设备的 IANA 名称(Android 平台通道,桌面回退 UTC) | +| 命名 | 客户端显示名改为 **Chamber Go**(Android 启动器、iOS、Linux 窗口、关于页),包名不变。配对兑换上报的 `clientLabel` / `deviceName`、登录标签与请求 user-agent(`chamber-go/<版本>`)一并改名 | +| 名称来源 | 网页端「连接到此服务器」列表显示服务器保存的 client label:操作员建配对链接时填的名字优先;否则沿用同设备(dedupeKey)已有的名字;第一次配对且都没填时才用客户端自报的 `clientLabel` / `deviceName`。因此老设备改名后仍显示旧名,要在列表里重命名,或撤销后重新配对 | +| 版本 | **0.5.6(code 506)** | + +--- + ## 0.5.5 项目选择与计划任务运行位置(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 0e48b2e..34aad49 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ -# OpenChamber Native +# Chamber Go -A lightweight OpenChamber client for phones, written in **Flutter** (Dart). +Chamber Go is a lightweight OpenChamber client for phones, written in +**Flutter** (Dart). Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.5.5 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.5.6 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link over the OpenChamber private relay with end-to-end encryption; the pairing link is pasted or scanned with the camera), session list with search and live diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index da1fd8a..dc09398 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -8,7 +8,7 @@ result.notImplemented() } } + // The statistics API buckets days by an IANA zone; Dart only knows the + // abbreviation, so the platform reports the real id. + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/device") + .setMethodCallHandler { call, result -> + when (call.method) { + "ianaTimeZone" -> result.success(java.util.TimeZone.getDefault().id) + else -> result.notImplemented() + } + } } } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index af74a5b..4de0daf 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -7,7 +7,7 @@ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName - Openchamber + Chamber Go CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier diff --git a/lib/api/client.dart b/lib/api/client.dart index f0e0e5d..e716335 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -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> 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 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? ?? const {}); + } + Future> listMessages(String id, {int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async { final query = { @@ -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 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 = { '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) { diff --git a/lib/api/usage_stats.dart b/lib/api/usage_stats.dart new file mode 100644 index 0000000..63b5cae --- /dev/null +++ b/lib/api/usage_stats.dart @@ -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? 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); diff --git a/lib/l10n/zh.dart b/lib/l10n/zh.dart index dfd9191..a43ef1a 100644 --- a/lib/l10n/zh.dart +++ b/lib/l10n/zh.dart @@ -481,7 +481,7 @@ const Map 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 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 移动客户端', }; diff --git a/lib/screens/features_screen.dart b/lib/screens/features_screen.dart index f04c57a..431d79a 100644 --- a/lib/screens/features_screen.dart +++ b/lib/screens/features_screen.dart @@ -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), + )), + ), ], ), ], diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index e207693..c6413f1 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -923,10 +923,10 @@ class _AboutSettingsPageState extends State { 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)), ], diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart new file mode 100644 index 0000000..b0d9de0 --- /dev/null +++ b/lib/screens/stats_screen.dart @@ -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 createState() => _StatsScreenState(); +} + +class _StatsScreenState extends State { + 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 _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 _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 _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 _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(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)), + ), + ], + ), + ); + } +} diff --git a/lib/time_zone.dart b/lib/time_zone.dart new file mode 100644 index 0000000..308c4dc --- /dev/null +++ b/lib/time_zone.dart @@ -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 deviceTimeZone() async { + final cached = _cached; + if (cached != null) return cached; + try { + final name = await _channel.invokeMethod('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'; +} diff --git a/lib/widgets/project_picker.dart b/lib/widgets/project_picker.dart index b25cda7..59b9e07 100644 --- a/lib/widgets/project_picker.dart +++ b/lib/widgets/project_picker.dart @@ -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 showProjectPicker( BuildContext context, { required AppState app, required String selected, + bool includeAll = false, + bool includeChat = true, }) { return showModalBottomSheet( context: context, @@ -39,6 +53,8 @@ Future showProjectPicker( builder: (context, controller) => _ProjectPickerSheet( app: app, selected: selected, + includeAll: includeAll, + includeChat: includeChat, controller: controller, ), ), @@ -65,11 +81,15 @@ List 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), diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 34210fd..07a00ea 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -33,7 +33,7 @@ static void my_application_activate(GApplication* application) { // gtk_header_bar_set_show_close_button(header_bar, TRUE); // gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - gtk_window_set_title(window, "openchamber"); + gtk_window_set_title(window, "Chamber Go"); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments( diff --git a/pubspec.yaml b/pubspec.yaml index 66f7fcc..4c24c8d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.5.5+505 +version: 0.5.6+506 environment: sdk: ^3.14.0 diff --git a/test/l10n_test.dart b/test/l10n_test.dart index 28abad0..40fcccd 100644 --- a/test/l10n_test.dart +++ b/test/l10n_test.dart @@ -10,6 +10,7 @@ import 'package:openchamber/l10n/zh.dart'; const _notTranslated = { 'English', '中文', + 'Chamber Go', // Product names, separators and glyphs read the same everywhere. 'OpenChamber', 'OpenCode', diff --git a/test/project_picker_test.dart b/test/project_picker_test.dart index 7569117..ee3f920 100644 --- a/test/project_picker_test.dart +++ b/test/project_picker_test.dart @@ -58,6 +58,44 @@ void main() { expect(choice!.isChat, isFalse); }); + testWidgets('the stats picker adds All projects and drops the Chat row', + (tester) async { + final app = AppState(); + addTearDown(app.dispose); + app.projects = const [ + ProjectInfo(id: 'p1', canonical: '/home/me/project', name: 'My project'), + ]; + + ProjectChoice? choice; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + choice = await showProjectPicker(context, + app: app, + selected: allProjectsTarget, + includeAll: true, + includeChat: false); + }, + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.text('All projects'), findsOneWidget); + expect(find.text('Chat'), findsNothing); + expect(find.text('My project'), findsOneWidget); + + await tester.tap(find.text('All projects')); + await tester.pumpAndSettle(); + expect(choice, isNotNull); + expect(choice!.isAll, isTrue); + }); + testWidgets('scheduled tasks open the same project sheet', (tester) async { final app = AppState(); addTearDown(app.dispose); diff --git a/test/scheduled_tasks_test.dart b/test/scheduled_tasks_test.dart index 85bfe0d..5242957 100644 --- a/test/scheduled_tasks_test.dart +++ b/test/scheduled_tasks_test.dart @@ -151,6 +151,8 @@ void main() { expect(find.text('全部功能'), findsOneWidget); expect(find.text('计划任务'), findsOneWidget); expect(find.text('按时间向会话发送提示词'), findsOneWidget); + expect(find.text('统计'), findsOneWidget); + expect(find.text('提示词、词元、费用与模型活动'), findsOneWidget); await tester.tap(find.text('计划任务')); await tester.pumpAndSettle(); diff --git a/test/usage_stats_test.dart b/test/usage_stats_test.dart new file mode 100644 index 0000000..cfde667 --- /dev/null +++ b/test/usage_stats_test.dart @@ -0,0 +1,114 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/usage_stats.dart'; + +void main() { + test('a report reads tokens, tools and models', () { + final stats = UsageStats.fromJson({ + 'range': {'from': 1000, 'to': 2000}, + 'sessions': 3, + 'subagents': 5, + 'prompts': 12, + 'steps': 240, + 'tokens': { + 'input': 100, + 'output': 40, + 'reasoning': 10, + 'cache': {'read': 900, 'write': 50}, + }, + 'cost': 0.25, + 'activeDays': 2, + 'streak': 1, + 'activity': [ + {'date': '2026-11-25', 'steps': 40}, + ], + 'tools': { + 'mode': 'detail', + 'totals': {'calls': 9, 'succeeded': 8, 'failed': 1, 'unfinished': 0}, + 'usage': [ + { + 'name': 'read', + 'calls': 4, + 'succeeded': 4, + 'failed': 0, + 'unfinished': 0, + 'durationP50': 25.5, + }, + ], + }, + 'models': [ + { + 'model': {'providerID': 'p', 'id': 'm', 'variant': 'high'}, + 'steps': 240, + 'tokens': { + 'input': 100, + 'output': 40, + 'reasoning': 10, + 'cache': {'read': 900, 'write': 50}, + }, + 'cost': 0.25, + }, + ], + }); + + expect(stats.isEmpty, isFalse); + expect(stats.sessions, 3); + expect(stats.tokens.total, 1100); + expect(stats.tokens.produced, 50); + expect(stats.tools.hasTotals, isTrue); + expect(stats.tools.rows.single.durationP50, 25.5); + expect(stats.models.single.variant, 'high'); + expect(stats.models.single.tokens.cacheRead, 900); + }); + + test('an empty report says so', () { + expect(const UsageStats().isEmpty, isTrue); + }); + + test('ranges start at local midnight', () { + final now = DateTime(2026, 11, 26, 15, 30); + expect(UsageRange.day.startFrom(now), + DateTime(2026, 11, 26).millisecondsSinceEpoch); + expect(UsageRange.week.startFrom(now), + DateTime(2026, 11, 20).millisecondsSinceEpoch); + expect(UsageRange.month.startFrom(now), + DateTime(2026, 10, 28).millisecondsSinceEpoch); + expect(UsageRange.all.startFrom(now), isNull); + }); + + test('activity fills quiet days and groups long ranges into weeks', () { + final from = DateTime(2026, 11, 20).millisecondsSinceEpoch; + final to = DateTime(2026, 11, 26).millisecondsSinceEpoch; + final series = buildUsageActivity(UsageStats( + from: from, + to: to, + activity: const [ + UsageActivityDay('2026-11-21', 4), + UsageActivityDay('2026-11-24', 6), + ], + )); + expect(series.weekly, isFalse); + expect(series.bars.length, 6); + expect(series.bars.map((bar) => bar.steps), [0, 4, 0, 0, 6, 0]); + expect(series.max, 6); + + // More than 92 days become weekly bars. + final long = buildUsageActivity(UsageStats( + from: DateTime(2026, 1, 1).millisecondsSinceEpoch, + to: DateTime(2026, 6, 1).millisecondsSinceEpoch, + )); + expect(long.weekly, isTrue); + expect(long.bars.length, lessThanOrEqualTo(92)); + }); + + test('the number and duration helpers read like the web client', () { + expect(usageCompactNumber(999), '999'); + expect(usageCompactNumber(1234), '1.2K'); + expect(usageCompactNumber(1234567), '1.2M'); + expect(usageCompactNumber(123.4), '123'); + expect(usagePercent(0.1234), '12.3%'); + expect(usageCost(1.5), r'$1.50'); + expect(usageDuration(48), '48 ms'); + expect(usageDuration(1500), '1.5 s'); + expect(usageDuration(65000), '1 min 5 s'); + }); +}