Files
openchamber-android-native/lib/screens/stats_screen.dart
T

924 lines
30 KiB
Dart
Raw Normal View History

// 统计: 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)),
),
],
),
);
}
}