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:
1 parent
a70e9290ef
commit
b65498d73e
19 files changed
+1637
-25
No files matched your search
+36
-5
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
Reference in new issue
Block a user