Chat info: account quota per harness (Claude rate_limit_event, Codex account/rateLimits, OpenCode unsupported)

Usage frames carry optional usage.account {harness, source, plan, as_of,
windows[{id,label,used_percent,resets_at}], unsupported}. Claude Code quota
comes from its rate_limit_event stream lines and the initialize account
(plan), shared across chats on the same account. Codex reads
account/rateLimits/read once per connection (re-read when a chat opens after
5 min) and merges account/rateLimits/updated. OpenCode exposes no quota API
and says so. The app's chat info sheet shows an Account usage section with a
progress bar and reset countdown per window, Material and Cupertino.
This commit is contained in:
2026-11-02 18:57:13 +00:00
parent 8a402c1114
commit 10049b8062
26 changed files with 1469 additions and 19 deletions
@@ -0,0 +1,173 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/chat_account_usage.dart';
/// The info sheet's "Account usage" section: one progress bar per quota
/// window the harness reported, the plan and the report's age. It draws
/// nothing for an unknown quota, and one muted line when the harness has no
/// quota API. Reset countdowns tick while the sheet is open.
class ChatAccountUsageSection extends StatefulWidget {
const ChatAccountUsageSection({
super.key,
required this.usage,
required this.cupertino,
this.now = DateTime.now,
});
final ChatAccountUsage? usage;
final bool cupertino;
final DateTime Function() now;
@override
State<ChatAccountUsageSection> createState() =>
_ChatAccountUsageSectionState();
}
class _ChatAccountUsageSectionState extends State<ChatAccountUsageSection> {
Timer? _tick;
@override
void initState() {
super.initState();
_tick = Timer.periodic(const Duration(seconds: 30), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_tick?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final usage = widget.usage;
if (usage == null) return const SizedBox.shrink();
final cupertino = widget.cupertino;
final now = widget.now();
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final body = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final title = cupertino
? CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(context).textTheme.titleSmall;
final muted = body?.copyWith(color: secondary);
final asOf = chatQuotaAsOf(usage.asOf, now);
final plan = chatPlanLabel(usage.plan);
return Padding(
key: const Key('chat-account-usage'),
padding: const EdgeInsetsDirectional.fromSTEB(24, 12, 24, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Account usage', style: title),
if (usage.unsupported)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
'Not reported by ${usage.harness}',
key: const Key('chat-account-usage-unsupported'),
style: muted,
),
)
else ...[
if (plan.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
usage.harness.isEmpty
? '$plan plan'
: '${usage.harness} · $plan plan',
key: const Key('chat-account-usage-plan'),
style: muted,
),
),
for (final window in usage.windows)
_QuotaWindowRow(
window: window,
now: now,
cupertino: cupertino,
body: body,
muted: muted,
),
if (asOf.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
asOf,
key: const Key('chat-account-usage-as-of'),
style: muted,
),
),
],
],
),
);
}
}
class _QuotaWindowRow extends StatelessWidget {
const _QuotaWindowRow({
required this.window,
required this.now,
required this.cupertino,
required this.body,
required this.muted,
});
final ChatQuotaWindow window;
final DateTime now;
final bool cupertino;
final TextStyle? body;
final TextStyle? muted;
@override
Widget build(BuildContext context) {
final summary = chatQuotaSummary(window, now);
final fraction = (window.usedPercent / 100).clamp(0.0, 1.0);
final high = window.usedPercent >= 90;
// Cupertino has no linear progress control; the standard indicator is
// drawn with the system fill and tint colors, like UIProgressView.
final bar = cupertino
? LinearProgressIndicator(
value: fraction,
backgroundColor: CupertinoColors.systemFill.resolveFrom(context),
color:
(high ? CupertinoColors.systemRed : CupertinoColors.activeBlue)
.resolveFrom(context),
borderRadius: BorderRadius.circular(2),
semanticsLabel: '${window.label} quota',
)
: LinearProgressIndicator(
value: fraction,
color: high ? Theme.of(context).colorScheme.error : null,
borderRadius: BorderRadius.circular(2),
semanticsLabel: '${window.label} quota',
);
return Padding(
key: Key('chat-account-window-${window.id}'),
padding: const EdgeInsets.only(top: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(window.label, style: body),
Padding(padding: const EdgeInsets.symmetric(vertical: 4), child: bar),
Text(
summary,
key: Key('chat-account-window-summary-${window.id}'),
style: muted,
),
],
),
);
}
}
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import 'chat_server_queue.dart';
@@ -73,6 +74,7 @@ class ChatThreadController extends ChangeNotifier {
String? _liveAssistantMessageId;
String? _awaitingResponseOperation;
JsonMap? _usage;
ChatAccountUsage? _accountUsage;
String? _error;
bool _subscribed = false;
@@ -147,6 +149,10 @@ class ChatThreadController extends ChangeNotifier {
/// Unknown fields stay null, so a viewer can distinguish them from zero.
JsonMap? get usage => _usage;
/// The harness account's latest reported quota, or null while unknown. It
/// is account state: a frame without one keeps the last known value.
ChatAccountUsage? get accountUsage => _accountUsage;
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
@@ -348,8 +354,14 @@ class ChatThreadController extends ChangeNotifier {
// Usage replaces the last snapshot and never adds a message, runs a turn
// or admits a queued prompt. An unusable snapshot keeps the previous
// recorded values instead of replacing them with fabricated zeros.
final usage = chatUsageSnapshot(body['usage']);
if (usage == null || !_reportedUsage(usage)) return;
final raw = body['usage'];
final account = chatAccountUsage(raw is Map ? raw['account'] : null);
if (account != null) _accountUsage = account;
final usage = chatUsageSnapshot(raw);
if (usage == null || !_reportedUsage(usage)) {
if (account != null) _notify(transcript: false);
return;
}
_usage = usage;
_notify(transcript: false);
return;
@@ -17,6 +17,7 @@ import '../ui/sessions/session_actions.dart';
import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_view.dart';
import '../ui/transcript/chat_injected_rows.dart';
import 'chat_account_usage_section.dart';
import 'chat_background_tasks.dart';
import 'chat_command_actions.dart';
import 'chat_composer_bar.dart';
@@ -1530,6 +1531,10 @@ class _ChatInfoSheet extends StatelessWidget {
),
for (final metric in _chatInfoMetrics(controller.usage))
_ChatInfoRow(metric: metric, cupertino: cupertino),
ChatAccountUsageSection(
usage: controller.accountUsage,
cupertino: cupertino,
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16),
child: Text(
@@ -0,0 +1,130 @@
/// The harness account's subscription quota, as carried by a usage frame's
/// `usage.account` (see docs/cli.md). Only reported values are kept: a window
/// without a usable percentage is dropped and nothing is estimated.
library;
/// One rolling quota window, e.g. "5-hour" or "Weekly".
class ChatQuotaWindow {
const ChatQuotaWindow({
required this.id,
required this.label,
required this.usedPercent,
required this.resetsAt,
});
final String id;
final String label;
/// 0–100; a harness may report more than 100 past a cap.
final double usedPercent;
/// Epoch milliseconds, 0 when the harness did not say.
final int resetsAt;
}
class ChatAccountUsage {
const ChatAccountUsage({
required this.harness,
required this.plan,
required this.asOf,
required this.windows,
required this.unsupported,
});
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
final String harness;
final String plan;
/// Epoch milliseconds when the server received the report, 0 if unknown.
final int asOf;
final List<ChatQuotaWindow> windows;
/// The harness exposes no quota at all.
final bool unsupported;
}
int _millis(Object? value) =>
value is num && value.isFinite && value > 0 ? value.toInt() : 0;
/// Parses `usage.account`, or null when it reports nothing usable.
ChatAccountUsage? chatAccountUsage(Object? value) {
if (value is! Map) return null;
final harness = '${value['harness'] ?? ''}'.trim();
if (value['unsupported'] == true) {
return ChatAccountUsage(
harness: harness.isEmpty ? 'the harness' : harness,
plan: '',
asOf: 0,
windows: const [],
unsupported: true,
);
}
final windows = <ChatQuotaWindow>[];
final raw = value['windows'];
if (raw is List) {
for (final entry in raw) {
if (entry is! Map) continue;
final percent = entry['used_percent'];
final label = '${entry['label'] ?? ''}'.trim();
if (percent is! num || !percent.isFinite || percent < 0) continue;
if (label.isEmpty) continue;
windows.add(
ChatQuotaWindow(
id: '${entry['id'] ?? label}',
label: label,
usedPercent: percent.toDouble(),
resetsAt: _millis(entry['resets_at']),
),
);
}
}
if (windows.isEmpty) return null;
return ChatAccountUsage(
harness: harness,
plan: '${value['plan'] ?? ''}'.trim(),
asOf: _millis(value['as_of']),
windows: List.unmodifiable(windows),
unsupported: false,
);
}
/// "42% used · resets in 2h 14m". The percentage is rounded, never clamped.
String chatQuotaSummary(ChatQuotaWindow window, DateTime now) {
final used = '${window.usedPercent.round()}% used';
if (window.resetsAt <= 0) return used;
final left = DateTime.fromMillisecondsSinceEpoch(
window.resetsAt,
).difference(now);
if (left.isNegative) return '$used · reset since this report';
return '$used · resets in ${_countdown(left)}';
}
String _countdown(Duration left) {
if (left.inMinutes < 1) return 'under a minute';
final days = left.inDays;
final hours = left.inHours % 24;
final minutes = left.inMinutes % 60;
if (days > 0) return hours > 0 ? '${days}d ${hours}h' : '${days}d';
if (left.inHours > 0) {
return minutes > 0 ? '${left.inHours}h ${minutes}m' : '${left.inHours}h';
}
return '${minutes}m';
}
/// "as of 5 min ago"; empty when the report time is unknown.
String chatQuotaAsOf(int asOf, DateTime now) {
if (asOf <= 0) return '';
final age = now.difference(DateTime.fromMillisecondsSinceEpoch(asOf));
if (age.inMinutes < 1) return 'as of just now';
if (age.inHours < 1) return 'as of ${age.inMinutes} min ago';
if (age.inDays < 1) return 'as of ${age.inHours} h ago';
return 'as of ${age.inDays} d ago';
}
/// A native plan id as a label: "max" -> "Max", "self_serve_business" ->
/// "Self serve business".
String chatPlanLabel(String plan) {
final words = plan.replaceAll('_', ' ').trim();
if (words.isEmpty) return '';
return words[0].toUpperCase() + words.substring(1);
}
+13
View File
@@ -0,0 +1,13 @@
# Chat info: account usage
The chat information sheet shows an "Account usage" section from
`usage.account` (wire shape in docs/cli.md): one LinearProgressIndicator per
reported window ("42% used · resets in 2h 14m"), the plan and "as of <age>".
Cupertino draws the same indicator in system fill/tint colors, since Cupertino
has no linear progress control. An unknown quota hides the section; OpenCode
(no quota API) shows "Not reported by OpenCode". Countdowns tick every 30 s.
Evidence: `test/features/chat/conversation/chat_account_usage_test.dart`
(both hosts), and captures from the probe fixture with `?chats=1&quota=claude`
or `quota=opencode` (`tool/perf/perf_fixture.dart`), opened at
`/chat/perf-chat-0` and clicking the title, 560x1000, Material and Cupertino.
@@ -0,0 +1,230 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
import 'chat_thread_fixtures.dart';
Widget _host(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget _cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: child),
);
JsonMap _usageFrame(JsonMap usage) => {
'session_id': 's',
'kind': 'usage',
'usage': usage,
};
/// Synthetic numbers in the server's `usage.account` wire shape.
JsonMap _claudeAccount(DateTime now) => {
'harness': 'Claude Code',
'source': 'rate_limit_event',
'plan': 'max',
'as_of': now.millisecondsSinceEpoch,
'windows': [
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': 42,
'resets_at': now
.add(const Duration(hours: 2, minutes: 14, seconds: 40))
.millisecondsSinceEpoch,
},
{
'id': 'seven_day',
'label': 'Weekly',
'used_percent': 93.4,
'resets_at': now
.add(const Duration(days: 3, hours: 5, minutes: 10))
.millisecondsSinceEpoch,
},
],
};
Future<FakeChatGateway> _thread(
WidgetTester tester, {
bool cupertino = false,
}) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([]);
final thread = ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
);
await tester.pumpWidget(cupertino ? _cupertinoHost(thread) : _host(thread));
await tester.pumpAndSettle();
return gateway;
}
Future<void> _openInfo(WidgetTester tester) async {
await tester.tap(find.byKey(const Key('chat-info')));
await tester.pumpAndSettle();
}
void main() {
group('domain', () {
final now = DateTime.utc(2026, 11, 2, 12);
test('parses reported windows and drops unusable ones', () {
final usage = chatAccountUsage({
'harness': 'Codex',
'plan': 'plus',
'as_of': now.millisecondsSinceEpoch,
'windows': [
{'id': 'primary', 'label': '5-hour', 'used_percent': 37},
{'id': 'bad', 'label': 'Bad', 'used_percent': 'x'},
{'id': 'neg', 'label': 'Neg', 'used_percent': -1},
{'id': 'nolabel', 'used_percent': 5},
],
})!;
expect(usage.harness, 'Codex');
expect(usage.windows.map((w) => w.id), ['primary']);
expect(usage.windows.single.resetsAt, 0);
expect(chatQuotaSummary(usage.windows.single, now), '37% used');
});
test('unknown quota is null; an unsupported harness is explicit', () {
expect(chatAccountUsage(null), isNull);
expect(chatAccountUsage({'harness': 'Codex', 'windows': []}), isNull);
final none = chatAccountUsage({
'harness': 'OpenCode',
'unsupported': true,
})!;
expect(none.unsupported, isTrue);
expect(none.harness, 'OpenCode');
});
test('countdown and report age wording', () {
ChatQuotaWindow window(Duration left) => ChatQuotaWindow(
id: 'w',
label: 'W',
usedPercent: 99.6,
resetsAt: now.add(left).millisecondsSinceEpoch,
);
expect(
chatQuotaSummary(window(const Duration(hours: 2, minutes: 14)), now),
'100% used · resets in 2h 14m',
);
expect(
chatQuotaSummary(window(const Duration(minutes: 9)), now),
'100% used · resets in 9m',
);
expect(
chatQuotaSummary(window(const Duration(seconds: 20)), now),
'100% used · resets in under a minute',
);
expect(
chatQuotaSummary(window(const Duration(days: 2, hours: 3)), now),
'100% used · resets in 2d 3h',
);
expect(
chatQuotaSummary(window(const Duration(minutes: -5)), now),
'100% used · reset since this report',
);
final at = now.millisecondsSinceEpoch;
expect(chatQuotaAsOf(at, now), 'as of just now');
expect(chatQuotaAsOf(at - 5 * 60000, now), 'as of 5 min ago');
expect(chatQuotaAsOf(at - 3 * 3600000, now), 'as of 3 h ago');
expect(chatQuotaAsOf(0, now), '');
expect(chatPlanLabel('self_serve_business'), 'Self serve business');
});
});
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('$host: account usage shows windows, plan and age', (
tester,
) async {
final gateway = await _thread(tester, cupertino: cupertino);
gateway.emitEvent(
_usageFrame({
'scope': 'session',
'total_tokens': 1200,
'account': _claudeAccount(DateTime.now()),
}),
);
await tester.pump();
await _openInfo(tester);
expect(find.text('Account usage'), findsOneWidget);
expect(find.text('Claude Code · Max plan'), findsOneWidget);
expect(find.text('5-hour'), findsOneWidget);
expect(find.text('42% used · resets in 2h 14m'), findsOneWidget);
expect(find.text('Weekly'), findsOneWidget);
expect(find.text('93% used · resets in 3d 5h'), findsOneWidget);
expect(find.text('as of just now'), findsOneWidget);
final bars = tester
.widgetList<LinearProgressIndicator>(
find.byType(LinearProgressIndicator),
)
.toList();
expect(bars.map((bar) => bar.value), [
closeTo(.42, 1e-9),
closeTo(.934, 1e-9),
]);
expect(bars.first.semanticsLabel, '5-hour quota');
// Token metrics are still shown beside the quota.
expect(find.text('1,200'), findsOneWidget);
});
testWidgets(
'$host: unknown quota hides the section; no-API harness says so',
(tester) async {
final gateway = await _thread(tester, cupertino: cupertino);
gateway.emitEvent(_usageFrame({'scope': 'session', 'total_tokens': 5}));
await tester.pump();
await _openInfo(tester);
expect(find.byKey(const Key('chat-account-usage')), findsNothing);
expect(find.text('Account usage'), findsNothing);
expect(find.byType(LinearProgressIndicator), findsNothing);
gateway.emitEvent(
_usageFrame({
'scope': 'session',
'total_tokens': 6,
'account': {'harness': 'OpenCode', 'unsupported': true},
}),
);
await tester.pumpAndSettle();
expect(find.text('Account usage'), findsOneWidget);
expect(find.text('Not reported by OpenCode'), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsNothing);
},
);
}
testWidgets('an account-only frame keeps the recorded token metrics', (
tester,
) async {
final gateway = await _thread(tester);
gateway.emitEvent(
_usageFrame({'scope': 'session', 'total_tokens': 132408}),
);
await tester.pump();
gateway.emitEvent(_usageFrame({'account': _claudeAccount(DateTime.now())}));
await tester.pump();
await _openInfo(tester);
expect(find.text('132,408'), findsOneWidget);
expect(find.text('42% used · resets in 2h 14m'), findsOneWidget);
// A later frame without an account keeps the last known quota.
gateway.emitEvent(
_usageFrame({'scope': 'session', 'total_tokens': 140000}),
);
await tester.pumpAndSettle();
expect(find.text('140,000'), findsOneWidget);
expect(find.text('42% used · resets in 2h 14m'), findsOneWidget);
});
}
+53 -1
View File
@@ -5,7 +5,9 @@
// `?hits=N` N more `release` run hits in Search;
// `?chats=N` N chat sessions in the chat list, each opening a short
// markdown transcript;
// `?graph=1` run 7 carries its pinned graph (plan -> build).
// `?graph=1` run 7 carries its pinned graph (plan -> build);
// `?quota=claude|opencode` (with `?chats=N`) pushes a usage frame with
// that harness's account quota after a chat subscribes.
import 'package:pipelines_app/core/api_gateway.dart';
Map<String, String> _params = const {};
@@ -16,6 +18,56 @@ int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0;
int get _chats => int.tryParse(_params['chats'] ?? '') ?? 0;
bool get perfRunGraph => _params['graph'] == '1';
/// Unsolicited envelopes that follow a reply: the `?quota=` usage frame.
List<JsonMap> perfChatFollowUps(JsonMap request) {
final quota = _params['quota'];
if (_chats == 0 || quota == null || request['type'] != 'chat_subscribe') {
return const [];
}
final now = DateTime.now();
int at(Duration offset) => now.add(offset).millisecondsSinceEpoch;
final account = quota == 'opencode'
? {'harness': 'OpenCode', 'unsupported': true}
: {
'harness': 'Claude Code',
'source': 'rate_limit_event',
'plan': 'max',
'as_of': at(const Duration(minutes: -4)),
'windows': [
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': 42,
'resets_at': at(
const Duration(hours: 2, minutes: 14, seconds: 30),
),
},
{
'id': 'seven_day',
'label': 'Weekly',
'used_percent': 93,
'resets_at': at(const Duration(days: 3, hours: 5)),
},
],
};
return [
{
'type': 'chat_event',
'chat_event': {
'session_id': (request['chat_subscribe'] as Map?)?['session_id'],
'kind': 'usage',
'usage': {
'scope': 'session',
'total_tokens': 132408,
'context_tokens': 42000,
'context_window': 200000,
'account': account,
},
},
},
];
}
/// Run 7's pinned graph for `?graph=1`.
JsonMap perfRunGraphFixture() => {
'name': 'Release train',
+7 -2
View File
@@ -506,9 +506,14 @@ class _FixtureChannel implements WebSocketChannel {
final decoded = jsonDecode(data);
if (decoded is! Map<String, dynamic>) return;
final reply = probeReply(decoded);
if (reply == null) return;
final followUps = perfChatFollowUps(decoded);
if (reply == null && followUps.isEmpty) return;
Future<void>.delayed(const Duration(milliseconds: 120), () {
if (!_incoming.isClosed) _incoming.add(jsonEncode(reply));
if (_incoming.isClosed) return;
if (reply != null) _incoming.add(jsonEncode(reply));
for (final frame in followUps) {
_incoming.add(jsonEncode(frame));
}
});
}