Chat: warn before the harness account's usage limit runs out
A compact banner above the composer when any quota window of the chat's harness account reaches 80% (error colours from 95%), naming the most constrained window and a second one also at 80%+. Dismissing it holds per harness+window until the next level (80/90/95) or a reset, across chats and reloads; a newly crossed level is announced once with a root SnackBar. The usage-limit banner wins. Fixture: quota=warn80|warn95. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,7 @@ import 'chat_composer_controller.dart';
|
||||
import 'chat_escape_stop.dart';
|
||||
import 'chat_delivery_indicator.dart';
|
||||
import 'chat_usage_limit_banner.dart';
|
||||
import 'chat_usage_warning_banner.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_effort_control.dart';
|
||||
@@ -1254,10 +1255,17 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
pasteTarget: widget.pasteTarget,
|
||||
ownsPasteWhenFocused: widget.ownsPasteWhenFocused,
|
||||
runShell: _shellRuns.start,
|
||||
limitBanner: (sendDraft) => ChatUsageLimitBanner(
|
||||
thread: _controller,
|
||||
composer: _composer,
|
||||
sendDraft: sendDraft,
|
||||
limitBanner: (sendDraft) => Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ChatUsageLimitBanner(
|
||||
thread: _controller,
|
||||
composer: _composer,
|
||||
sendDraft: sendDraft,
|
||||
),
|
||||
ChatUsageWarningBanner(thread: _controller),
|
||||
],
|
||||
),
|
||||
backgroundTasks: ChatBackgroundTasks(
|
||||
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/chat_account_usage.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import '../domain/chat_usage_warning.dart';
|
||||
import 'chat_schedule_time.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_usage_warnings.dart';
|
||||
|
||||
/// Above the composer while the chat's harness account is nearly out of
|
||||
/// quota: "Claude Code 5-hour limit 84% used · resets in 1 h 20 m", in the
|
||||
/// error colours from 95%. It names the most constrained window and a second
|
||||
/// one also at a warning level. Dismissing it holds until a window reaches the
|
||||
/// next level or resets, in every chat of the account ([ChatUsageWarnings]).
|
||||
/// The usage-limit banner wins: this one hides while the account is out of
|
||||
/// quota. It also hands each new account report to [warnings], which
|
||||
/// announces a newly crossed level once.
|
||||
class ChatUsageWarningBanner extends StatefulWidget {
|
||||
ChatUsageWarningBanner({
|
||||
super.key,
|
||||
required this.thread,
|
||||
ChatUsageWarnings? warnings,
|
||||
this.now = DateTime.now,
|
||||
}) : warnings = warnings ?? ChatUsageWarnings.shared;
|
||||
|
||||
final ChatThreadController thread;
|
||||
final ChatUsageWarnings warnings;
|
||||
final DateTime Function() now;
|
||||
|
||||
@override
|
||||
State<ChatUsageWarningBanner> createState() => _ChatUsageWarningBannerState();
|
||||
}
|
||||
|
||||
class _ChatUsageWarningBannerState extends State<ChatUsageWarningBanner> {
|
||||
ChatAccountUsage? _reported;
|
||||
|
||||
/// Refreshes the countdown and drops a window once its reset passes.
|
||||
Timer? _tick;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(widget.warnings.load());
|
||||
widget.thread.addListener(_report);
|
||||
_report();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatUsageWarningBanner oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.thread == widget.thread) return;
|
||||
oldWidget.thread.removeListener(_report);
|
||||
widget.thread.addListener(_report);
|
||||
_report();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.thread.removeListener(_report);
|
||||
_tick?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _report() {
|
||||
final usage = widget.thread.accountUsage;
|
||||
if (usage == null || identical(usage, _reported)) return;
|
||||
_reported = usage;
|
||||
unawaited(widget.warnings.report(usage, now: widget.now()));
|
||||
}
|
||||
|
||||
void _ticking(bool on) {
|
||||
if (on == (_tick != null)) return;
|
||||
_tick?.cancel();
|
||||
_tick = on
|
||||
? Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
if (mounted) setState(() {});
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.thread, widget.warnings]),
|
||||
builder: (context, _) {
|
||||
final now = widget.now();
|
||||
final thread = widget.thread;
|
||||
final limited =
|
||||
chatThreadUsageLimit(thread.accountUsage, thread.messages, now) !=
|
||||
null;
|
||||
final warning = limited
|
||||
? null
|
||||
: chatUsageWarning(
|
||||
thread.accountUsage,
|
||||
now,
|
||||
widget.warnings.dismissed,
|
||||
);
|
||||
_ticking(warning != null);
|
||||
if (warning == null) return const SizedBox.shrink();
|
||||
return _banner(context, warning, now);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _resets(ChatQuotaWindow window, DateTime now) {
|
||||
if (window.resetsAt <= 0) return '';
|
||||
final relative = chatQuotaResetsIn(window, now);
|
||||
if (relative != null) return ' · resets $relative';
|
||||
final at = DateTime.fromMillisecondsSinceEpoch(window.resetsAt);
|
||||
return ' · resets ${chatScheduleTime(context, at, now: () => now)}';
|
||||
}
|
||||
|
||||
Widget _banner(BuildContext context, ChatUsageWarning warning, DateTime now) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final text = Theme.of(context).textTheme;
|
||||
final background = warning.urgent
|
||||
? scheme.errorContainer
|
||||
: scheme.secondaryContainer;
|
||||
final foreground = warning.urgent
|
||||
? scheme.onErrorContainer
|
||||
: scheme.onSecondaryContainer;
|
||||
final second = warning.second;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.only(bottom: 8),
|
||||
child: Material(
|
||||
key: const Key('chat-usage-warning'),
|
||||
color: background,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
warning.urgent ? Icons.error_outline : Icons.data_usage,
|
||||
color: foreground,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
chatQuotaWarningTitle(
|
||||
warning.harness,
|
||||
warning.primary,
|
||||
) +
|
||||
_resets(warning.primary, now),
|
||||
key: const Key('chat-usage-warning-status'),
|
||||
style: text.bodyMedium?.copyWith(
|
||||
color: foreground,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (second != null)
|
||||
Text(
|
||||
'${second.label} limit '
|
||||
'${second.usedPercent.round()}% used'
|
||||
'${_resets(second, now)}',
|
||||
key: const Key('chat-usage-warning-second'),
|
||||
style: text.bodySmall?.copyWith(color: foreground),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('chat-usage-warning-dismiss'),
|
||||
tooltip: 'Dismiss',
|
||||
color: foreground,
|
||||
onPressed: () => widget.warnings.dismiss(warning),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../application/clipboard_failures.dart';
|
||||
import '../domain/chat_account_usage.dart';
|
||||
import '../domain/chat_usage_warning.dart';
|
||||
|
||||
const chatQuotaMarksPreferenceKey = 'pipelines.chatQuotaMarks.v1';
|
||||
|
||||
/// The app session's quota warning state, shared by every open chat since a
|
||||
/// harness account's quota is account-wide: which windows the operator
|
||||
/// dismissed (and at which level and reset), and which levels were already
|
||||
/// announced with a SnackBar. Both are kept in shared preferences, so a reload
|
||||
/// neither brings a dismissed warning back nor repeats an announcement.
|
||||
class ChatUsageWarnings extends ChangeNotifier {
|
||||
ChatUsageWarnings({
|
||||
this.preferences,
|
||||
bool Function(String message)? announce,
|
||||
this.clock = DateTime.now,
|
||||
}) : _announce = announce ?? showAppMessage;
|
||||
|
||||
/// The instance chats use unless a test hands them their own.
|
||||
static final ChatUsageWarnings shared = ChatUsageWarnings(
|
||||
preferences: SharedPreferences.getInstance,
|
||||
);
|
||||
|
||||
/// Where the marks are kept across reloads; null keeps them in memory.
|
||||
final Future<SharedPreferences> Function()? preferences;
|
||||
final bool Function(String message) _announce;
|
||||
|
||||
/// The time stored marks are pruned against.
|
||||
final DateTime Function() clock;
|
||||
final Map<String, ChatQuotaMark> _dismissed = {};
|
||||
final Map<String, ChatQuotaMark> _announced = {};
|
||||
Future<void>? _loaded;
|
||||
|
||||
/// Dismissals by [chatQuotaKey].
|
||||
Map<String, ChatQuotaMark> get dismissed => Map.unmodifiable(_dismissed);
|
||||
|
||||
/// Reads the stored marks once; marks recorded meanwhile win.
|
||||
Future<void> load() => _loaded ??= _read();
|
||||
|
||||
Future<void> _read() async {
|
||||
final preferences = this.preferences;
|
||||
if (preferences == null) return;
|
||||
final String? raw;
|
||||
try {
|
||||
raw = (await preferences()).getString(chatQuotaMarksPreferenceKey);
|
||||
} on Object catch (error) {
|
||||
// Without storage the marks still hold for this app session.
|
||||
debugPrint('Quota warnings: could not read preferences: $error');
|
||||
return;
|
||||
}
|
||||
if (raw == null) return;
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! Map) return;
|
||||
var changed = false;
|
||||
for (final (name, into) in [
|
||||
('dismissed', _dismissed),
|
||||
('announced', _announced),
|
||||
]) {
|
||||
final marks = decoded[name];
|
||||
if (marks is! Map) continue;
|
||||
for (final MapEntry(:key, :value) in marks.entries) {
|
||||
if (value is! List || value.length != 2) continue;
|
||||
final [level, resetsAt] = value;
|
||||
if (level is! int || resetsAt is! int) continue;
|
||||
into.putIfAbsent('$key', () {
|
||||
changed = true;
|
||||
return ChatQuotaMark(level: level, resetsAt: resetsAt);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (changed) notifyListeners();
|
||||
} on FormatException {
|
||||
// A corrupt entry is replaced by the next save.
|
||||
}
|
||||
}
|
||||
|
||||
/// Announces each window of [usage] that reached a warning level not yet
|
||||
/// announced or dismissed since its last reset, once per app (and across
|
||||
/// reloads).
|
||||
Future<void> report(ChatAccountUsage usage, {DateTime? now}) async {
|
||||
await load();
|
||||
final crossed = chatQuotaNewlyCrossed(
|
||||
usage,
|
||||
now ?? clock(),
|
||||
_announced,
|
||||
_dismissed,
|
||||
);
|
||||
if (crossed.isEmpty) return;
|
||||
for (final window in crossed) {
|
||||
_announced[chatQuotaKey(usage.harness, window)] = chatQuotaMarkOf(window);
|
||||
}
|
||||
_announce(chatQuotaAnnouncement(usage.harness, crossed));
|
||||
await _save();
|
||||
}
|
||||
|
||||
/// Hides [warning] until one of its windows reaches the next level or
|
||||
/// resets.
|
||||
void dismiss(ChatUsageWarning warning) {
|
||||
for (final window in warning.windows) {
|
||||
_dismissed[chatQuotaKey(warning.harness, window)] = chatQuotaMarkOf(
|
||||
window,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
unawaited(_save());
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final preferences = this.preferences;
|
||||
if (preferences == null) return;
|
||||
final now = clock().millisecondsSinceEpoch;
|
||||
// A mark for a window that has reset since can never cover it again.
|
||||
Map<String, List<int>> live(Map<String, ChatQuotaMark> marks) => {
|
||||
for (final MapEntry(:key, :value) in marks.entries)
|
||||
if (value.resetsAt <= 0 || value.resetsAt > now)
|
||||
key: [value.level, value.resetsAt],
|
||||
};
|
||||
final value = jsonEncode({
|
||||
'dismissed': live(_dismissed),
|
||||
'announced': live(_announced),
|
||||
});
|
||||
try {
|
||||
await (await preferences()).setString(chatQuotaMarksPreferenceKey, value);
|
||||
} on Object catch (error) {
|
||||
debugPrint('Quota warnings: could not save preferences: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/// The early warning before a harness account runs out of quota: which
|
||||
/// windows of the reported account usage (chat_account_usage.dart) are
|
||||
/// nearly used up, which of them the operator has already been told about or
|
||||
/// has dismissed, and the text that says so.
|
||||
///
|
||||
/// A window warns at 80%, again at 90% and again at 95%. A dismissal or an
|
||||
/// announcement holds for the level it saw until the window reaches the next
|
||||
/// level or resets (its reset time changes).
|
||||
library;
|
||||
|
||||
import 'chat_account_usage.dart';
|
||||
|
||||
/// The percentages at which a window warns, lowest first.
|
||||
const List<int> chatQuotaWarningLevels = [80, 90, 95];
|
||||
|
||||
/// The level from which the warning is drawn as urgent.
|
||||
const int chatQuotaUrgentLevel = 95;
|
||||
|
||||
/// The highest warning level [percent] has reached, or 0 below the first.
|
||||
/// Past 100% stays at the top level.
|
||||
int chatQuotaLevel(double percent) {
|
||||
var level = 0;
|
||||
for (final threshold in chatQuotaWarningLevels) {
|
||||
if (percent >= threshold) level = threshold;
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
/// Identifies one window of one harness account across chats.
|
||||
String chatQuotaKey(String harness, ChatQuotaWindow window) =>
|
||||
'$harness|${window.id}';
|
||||
|
||||
/// The level a window was at when it was dismissed or announced, and the
|
||||
/// reset it had then.
|
||||
class ChatQuotaMark {
|
||||
const ChatQuotaMark({required this.level, required this.resetsAt});
|
||||
|
||||
final int level;
|
||||
final int resetsAt;
|
||||
|
||||
/// Whether this mark still covers [window]: the same reset and no higher
|
||||
/// level since.
|
||||
bool covers(ChatQuotaWindow window) =>
|
||||
resetsAt == window.resetsAt &&
|
||||
level >= chatQuotaLevel(window.usedPercent);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is ChatQuotaMark &&
|
||||
other.level == level &&
|
||||
other.resetsAt == resetsAt;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(level, resetsAt);
|
||||
}
|
||||
|
||||
/// A warning to show: the most constrained window and, when another is also
|
||||
/// at a warning level, the next one.
|
||||
class ChatUsageWarning {
|
||||
const ChatUsageWarning({
|
||||
required this.harness,
|
||||
required this.primary,
|
||||
this.second,
|
||||
});
|
||||
|
||||
final String harness;
|
||||
final ChatQuotaWindow primary;
|
||||
final ChatQuotaWindow? second;
|
||||
|
||||
int get level => chatQuotaLevel(primary.usedPercent);
|
||||
bool get urgent => level >= chatQuotaUrgentLevel;
|
||||
|
||||
/// The windows this warning shows.
|
||||
List<ChatQuotaWindow> get windows => [primary, ?second];
|
||||
}
|
||||
|
||||
/// The windows of [usage] at a warning level whose reset is still ahead (or
|
||||
/// unknown), most constrained first: the highest percentage, then the
|
||||
/// soonest reset, an unknown reset last.
|
||||
List<ChatQuotaWindow> chatQuotaWarningWindows(
|
||||
ChatAccountUsage? usage,
|
||||
DateTime now,
|
||||
) {
|
||||
if (usage == null || usage.unsupported) return const [];
|
||||
final at = now.millisecondsSinceEpoch;
|
||||
final windows = [
|
||||
for (final window in usage.windows)
|
||||
if (chatQuotaLevel(window.usedPercent) > 0 &&
|
||||
(window.resetsAt <= 0 || window.resetsAt > at))
|
||||
window,
|
||||
];
|
||||
int reset(ChatQuotaWindow window) =>
|
||||
window.resetsAt > 0 ? window.resetsAt : 1 << 62;
|
||||
windows.sort((a, b) {
|
||||
final percent = b.usedPercent.compareTo(a.usedPercent);
|
||||
return percent != 0 ? percent : reset(a).compareTo(reset(b));
|
||||
});
|
||||
return windows;
|
||||
}
|
||||
|
||||
/// The warning for [usage] at [now], leaving out windows whose dismissal in
|
||||
/// [dismissed] (by [chatQuotaKey]) still holds; null when nothing is left.
|
||||
ChatUsageWarning? chatUsageWarning(
|
||||
ChatAccountUsage? usage,
|
||||
DateTime now,
|
||||
Map<String, ChatQuotaMark> dismissed,
|
||||
) {
|
||||
final windows = [
|
||||
for (final window in chatQuotaWarningWindows(usage, now))
|
||||
if (!(dismissed[chatQuotaKey(usage!.harness, window)]?.covers(window) ??
|
||||
false))
|
||||
window,
|
||||
];
|
||||
if (windows.isEmpty) return null;
|
||||
return ChatUsageWarning(
|
||||
harness: usage!.harness,
|
||||
primary: windows.first,
|
||||
second: windows.length > 1 ? windows[1] : null,
|
||||
);
|
||||
}
|
||||
|
||||
/// The windows of [usage] that reached a level the operator has not been
|
||||
/// told about: neither announced (in [announced]) nor dismissed at that level
|
||||
/// since their last reset. Most constrained first.
|
||||
List<ChatQuotaWindow> chatQuotaNewlyCrossed(
|
||||
ChatAccountUsage? usage,
|
||||
DateTime now,
|
||||
Map<String, ChatQuotaMark> announced,
|
||||
Map<String, ChatQuotaMark> dismissed,
|
||||
) => [
|
||||
for (final window in chatQuotaWarningWindows(usage, now))
|
||||
if (!(announced[chatQuotaKey(usage!.harness, window)]?.covers(window) ??
|
||||
false) &&
|
||||
!(dismissed[chatQuotaKey(usage.harness, window)]?.covers(window) ??
|
||||
false))
|
||||
window,
|
||||
];
|
||||
|
||||
/// The mark recording [window] at its current level.
|
||||
ChatQuotaMark chatQuotaMarkOf(ChatQuotaWindow window) => ChatQuotaMark(
|
||||
level: chatQuotaLevel(window.usedPercent),
|
||||
resetsAt: window.resetsAt,
|
||||
);
|
||||
|
||||
/// "Claude Code 5-hour limit at 90%", announcing newly crossed [windows].
|
||||
String chatQuotaAnnouncement(String harness, List<ChatQuotaWindow> windows) {
|
||||
final first = windows.first;
|
||||
final name = harness.isEmpty ? '' : '$harness ';
|
||||
return [
|
||||
'$name${first.label} limit at ${first.usedPercent.round()}%',
|
||||
for (final other in windows.skip(1))
|
||||
'${other.label} at ${other.usedPercent.round()}%',
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
/// "Claude Code 5-hour limit 84% used".
|
||||
String chatQuotaWarningTitle(String harness, ChatQuotaWindow window) {
|
||||
final name = harness.isEmpty ? '' : '$harness ';
|
||||
return '$name${window.label} limit ${window.usedPercent.round()}% used';
|
||||
}
|
||||
|
||||
/// "in 1 h 20 m" (no-break spaces) for a reset within a day of [now]; null for an unknown
|
||||
/// reset or one a day or more away (shown as a local time instead).
|
||||
String? chatQuotaResetsIn(ChatQuotaWindow window, DateTime now) {
|
||||
if (window.resetsAt <= 0) return null;
|
||||
final left = DateTime.fromMillisecondsSinceEpoch(
|
||||
window.resetsAt,
|
||||
).difference(now);
|
||||
if (left >= const Duration(days: 1)) return null;
|
||||
if (left.inMinutes < 1) return 'in under a minute';
|
||||
final hours = left.inHours;
|
||||
final minutes = left.inMinutes % 60;
|
||||
// No-break spaces keep a wrapped line from splitting the duration.
|
||||
if (hours == 0) return 'in $minutes\u00a0m';
|
||||
return minutes == 0
|
||||
? 'in $hours\u00a0h'
|
||||
: 'in $hours\u00a0h\u00a0$minutes\u00a0m';
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/application/clipboard_failures.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_usage_warning_banner.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_usage_warnings.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
final _now = DateTime(2026, 11, 25, 12);
|
||||
final _fiveReset = _now.add(const Duration(hours: 1, minutes: 20));
|
||||
|
||||
JsonMap _frame({
|
||||
double five = 84,
|
||||
double week = 40,
|
||||
DateTime? fiveReset,
|
||||
String session = 's',
|
||||
}) => {
|
||||
'session_id': session,
|
||||
'kind': 'usage',
|
||||
'usage': {
|
||||
'account': {
|
||||
'harness': 'Claude Code',
|
||||
'plan': 'max',
|
||||
'windows': [
|
||||
{
|
||||
'id': 'five_hour',
|
||||
'label': '5-hour',
|
||||
'used_percent': five,
|
||||
'resets_at': (fiveReset ?? _fiveReset).millisecondsSinceEpoch,
|
||||
},
|
||||
{
|
||||
'id': 'seven_day',
|
||||
'label': 'Weekly',
|
||||
'used_percent': week,
|
||||
'resets_at': _now.add(const Duration(days: 3)).millisecondsSinceEpoch,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
class _Host {
|
||||
_Host(this.gateway, this.thread, this.warnings, this.announced);
|
||||
|
||||
final FakeChatGateway gateway;
|
||||
final ChatThreadController thread;
|
||||
final ChatUsageWarnings warnings;
|
||||
final List<String> announced;
|
||||
|
||||
Future<void> emit(WidgetTester tester, JsonMap frame) async {
|
||||
gateway.emitEvent(frame);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
Future<_Host> _host(
|
||||
WidgetTester tester, {
|
||||
ChatUsageWarnings? warnings,
|
||||
int panes = 1,
|
||||
}) async {
|
||||
final gateway = FakeChatGateway();
|
||||
addTearDown(gateway.close);
|
||||
final announced = <String>[];
|
||||
final store =
|
||||
warnings ??
|
||||
ChatUsageWarnings(
|
||||
announce: (message) {
|
||||
announced.add(message);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
final threads = [
|
||||
for (var pane = 0; pane < panes; pane++) ChatThreadController(gateway, 's'),
|
||||
];
|
||||
for (final thread in threads) {
|
||||
addTearDown(thread.dispose);
|
||||
}
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
scaffoldMessengerKey: appScaffoldMessengerKey,
|
||||
home: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
for (final thread in threads)
|
||||
ChatUsageWarningBanner(
|
||||
thread: thread,
|
||||
warnings: store,
|
||||
now: () => _now,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return _Host(gateway, threads.first, store, announced);
|
||||
}
|
||||
|
||||
final _banner = find.byKey(const Key('chat-usage-warning'));
|
||||
final _status = find.byKey(const Key('chat-usage-warning-status'));
|
||||
final _second = find.byKey(const Key('chat-usage-warning-second'));
|
||||
final _dismiss = find.byKey(const Key('chat-usage-warning-dismiss'));
|
||||
|
||||
Color? _color(WidgetTester tester) =>
|
||||
tester.widget<Material>(_banner.first).color;
|
||||
|
||||
ColorScheme _scheme(WidgetTester tester) =>
|
||||
Theme.of(tester.element(find.byType(Scaffold))).colorScheme;
|
||||
|
||||
void main() {
|
||||
testWidgets('80% shows a compact warning in the secondary colours', (
|
||||
tester,
|
||||
) async {
|
||||
final host = await _host(tester);
|
||||
expect(_banner, findsNothing);
|
||||
await host.emit(tester, _frame(five: 79));
|
||||
expect(_banner, findsNothing);
|
||||
await host.emit(tester, _frame(five: 84.2));
|
||||
expect(_banner, findsOneWidget);
|
||||
expect(
|
||||
tester.widget<Text>(_status).data,
|
||||
'Claude Code 5-hour limit 84% used · resets in 1\u00a0h\u00a020\u00a0m',
|
||||
);
|
||||
expect(_second, findsNothing);
|
||||
expect(_color(tester), _scheme(tester).secondaryContainer);
|
||||
});
|
||||
|
||||
testWidgets('95% escalates to the error colours and names a second window', (
|
||||
tester,
|
||||
) async {
|
||||
final host = await _host(tester);
|
||||
await host.emit(tester, _frame(five: 96, week: 88));
|
||||
expect(_color(tester), _scheme(tester).errorContainer);
|
||||
expect(
|
||||
tester.widget<Text>(_status).data,
|
||||
startsWith('Claude Code 5-hour limit 96% used'),
|
||||
);
|
||||
// The weekly reset is days away, so it reads as a local date and time.
|
||||
final second = tester.widget<Text>(_second).data!;
|
||||
expect(second, startsWith('Weekly limit 88% used · resets '));
|
||||
expect(second, isNot(contains(' in ')));
|
||||
});
|
||||
|
||||
testWidgets('a dismissal holds until the next level or a reset', (
|
||||
tester,
|
||||
) async {
|
||||
final host = await _host(tester);
|
||||
await host.emit(tester, _frame(five: 84));
|
||||
await tester.tap(_dismiss);
|
||||
await tester.pump();
|
||||
expect(_banner, findsNothing);
|
||||
await host.emit(tester, _frame(five: 88));
|
||||
expect(_banner, findsNothing);
|
||||
await host.emit(tester, _frame(five: 91));
|
||||
expect(_banner, findsOneWidget);
|
||||
await tester.tap(_dismiss);
|
||||
await tester.pump();
|
||||
expect(_banner, findsNothing);
|
||||
final later = _fiveReset.add(const Duration(hours: 5));
|
||||
await host.emit(tester, _frame(five: 91, fiveReset: later));
|
||||
expect(_banner, findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a dismissal is shared by every chat of the account', (
|
||||
tester,
|
||||
) async {
|
||||
final host = await _host(tester, panes: 2);
|
||||
await host.emit(tester, _frame(five: 84));
|
||||
expect(_banner, findsNWidgets(2));
|
||||
await tester.tap(_dismiss.first);
|
||||
await tester.pump();
|
||||
expect(_banner, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('hidden while the usage-limit banner shows', (tester) async {
|
||||
final host = await _host(tester);
|
||||
await host.emit(tester, _frame(five: 100, week: 90));
|
||||
expect(_banner, findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a crossed level is announced once', (tester) async {
|
||||
final host = await _host(tester);
|
||||
await host.emit(tester, _frame(five: 84));
|
||||
expect(host.announced, ['Claude Code 5-hour limit at 84%']);
|
||||
await host.emit(tester, _frame(five: 86));
|
||||
expect(host.announced, hasLength(1));
|
||||
await host.emit(tester, _frame(five: 92, week: 81));
|
||||
expect(host.announced, [
|
||||
'Claude Code 5-hour limit at 84%',
|
||||
'Claude Code 5-hour limit at 92% · Weekly at 81%',
|
||||
]);
|
||||
});
|
||||
|
||||
testWidgets('the announcement is a SnackBar in the app messenger', (
|
||||
tester,
|
||||
) async {
|
||||
final host = await _host(tester, warnings: ChatUsageWarnings());
|
||||
await host.emit(tester, _frame(five: 90));
|
||||
expect(find.text('Claude Code 5-hour limit at 90%'), findsOneWidget);
|
||||
expect(find.byType(SnackBar), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('dismissals and announcements survive a reload', (tester) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final first = ChatUsageWarnings(
|
||||
preferences: SharedPreferences.getInstance,
|
||||
clock: () => _now,
|
||||
announce: (_) => true,
|
||||
);
|
||||
final host = await _host(tester, warnings: first);
|
||||
await host.emit(tester, _frame(five: 84));
|
||||
await tester.tap(_dismiss);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final announced = <String>[];
|
||||
final reloaded = ChatUsageWarnings(
|
||||
preferences: SharedPreferences.getInstance,
|
||||
clock: () => _now,
|
||||
announce: (message) {
|
||||
announced.add(message);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
final again = await _host(tester, warnings: reloaded);
|
||||
await again.emit(tester, _frame(five: 84));
|
||||
await tester.pump();
|
||||
expect(_banner, findsNothing);
|
||||
expect(announced, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_usage_warning.dart';
|
||||
|
||||
final _now = DateTime(2026, 11, 25, 12);
|
||||
|
||||
ChatQuotaWindow _window(String id, double percent, Duration? resetIn) =>
|
||||
ChatQuotaWindow(
|
||||
id: id,
|
||||
label: id,
|
||||
usedPercent: percent,
|
||||
resetsAt: resetIn == null ? 0 : _now.add(resetIn).millisecondsSinceEpoch,
|
||||
);
|
||||
|
||||
ChatAccountUsage _usage(List<ChatQuotaWindow> windows) => ChatAccountUsage(
|
||||
harness: 'Claude Code',
|
||||
plan: 'max',
|
||||
asOf: 0,
|
||||
windows: windows,
|
||||
unsupported: false,
|
||||
);
|
||||
|
||||
const _hour = Duration(hours: 1);
|
||||
const _day = Duration(days: 1);
|
||||
|
||||
void main() {
|
||||
test('levels are 80, 90 and 95, and past 100% stays at 95', () {
|
||||
expect(chatQuotaLevel(79.9), 0);
|
||||
expect(chatQuotaLevel(80), 80);
|
||||
expect(chatQuotaLevel(89.99), 80);
|
||||
expect(chatQuotaLevel(90), 90);
|
||||
expect(chatQuotaLevel(95), 95);
|
||||
expect(chatQuotaLevel(130), 95);
|
||||
});
|
||||
|
||||
group('chatUsageWarning', () {
|
||||
test('nothing below 80%, unsupported or without usage', () {
|
||||
expect(chatUsageWarning(null, _now, const {}), isNull);
|
||||
expect(
|
||||
chatUsageWarning(_usage([_window('a', 79, _hour)]), _now, const {}),
|
||||
isNull,
|
||||
);
|
||||
const unsupported = ChatAccountUsage(
|
||||
harness: 'OpenCode',
|
||||
plan: '',
|
||||
asOf: 0,
|
||||
windows: [],
|
||||
unsupported: true,
|
||||
);
|
||||
expect(chatUsageWarning(unsupported, _now, const {}), isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'the highest percentage leads and a second warning window follows',
|
||||
() {
|
||||
final warning = chatUsageWarning(
|
||||
_usage([
|
||||
_window('five', 84, _hour),
|
||||
_window('week', 91, _day * 3),
|
||||
_window('opus', 50, _day),
|
||||
]),
|
||||
_now,
|
||||
const {},
|
||||
)!;
|
||||
expect(warning.primary.id, 'week');
|
||||
expect(warning.second?.id, 'five');
|
||||
expect(warning.level, 90);
|
||||
expect(warning.urgent, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('a second window below 80% is not mentioned', () {
|
||||
final warning = chatUsageWarning(
|
||||
_usage([_window('five', 84, _hour), _window('week', 70, _day)]),
|
||||
_now,
|
||||
const {},
|
||||
)!;
|
||||
expect(warning.second, isNull);
|
||||
});
|
||||
|
||||
test('a tie goes to the soonest reset, an unknown reset last', () {
|
||||
final warning = chatUsageWarning(
|
||||
_usage([
|
||||
_window('unknown', 88, null),
|
||||
_window('late', 88, _day * 2),
|
||||
_window('soon', 88, _hour),
|
||||
]),
|
||||
_now,
|
||||
const {},
|
||||
)!;
|
||||
expect(warning.primary.id, 'soon');
|
||||
expect(warning.second?.id, 'late');
|
||||
});
|
||||
|
||||
test('over 100% is urgent and leads', () {
|
||||
final warning = chatUsageWarning(
|
||||
_usage([_window('five', 96, _hour), _window('week', 104, null)]),
|
||||
_now,
|
||||
const {},
|
||||
)!;
|
||||
expect(warning.primary.id, 'week');
|
||||
expect(warning.urgent, isTrue);
|
||||
});
|
||||
|
||||
test('a window whose reset has passed is stale and left out', () {
|
||||
expect(
|
||||
chatUsageWarning(_usage([_window('five', 90, -_hour)]), _now, const {}),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('a dismissal holds until the next level or a reset', () {
|
||||
final at84 = _window('five', 84, _hour);
|
||||
final dismissed = {
|
||||
chatQuotaKey('Claude Code', at84): chatQuotaMarkOf(at84),
|
||||
};
|
||||
expect(chatUsageWarning(_usage([at84]), _now, dismissed), isNull);
|
||||
// Still within the 80 level.
|
||||
expect(
|
||||
chatUsageWarning(_usage([_window('five', 89, _hour)]), _now, dismissed),
|
||||
isNull,
|
||||
);
|
||||
// Crossing 90 brings it back, and so on to 95.
|
||||
expect(
|
||||
chatUsageWarning(_usage([_window('five', 90, _hour)]), _now, dismissed),
|
||||
isNotNull,
|
||||
);
|
||||
// A new reset brings it back at the same level.
|
||||
expect(
|
||||
chatUsageWarning(
|
||||
_usage([_window('five', 84, _hour * 5)]),
|
||||
_now,
|
||||
dismissed,
|
||||
),
|
||||
isNotNull,
|
||||
);
|
||||
// Another harness's window with the same id is its own account.
|
||||
final codex = ChatAccountUsage(
|
||||
harness: 'Codex',
|
||||
plan: '',
|
||||
asOf: 0,
|
||||
windows: [at84],
|
||||
unsupported: false,
|
||||
);
|
||||
expect(chatUsageWarning(codex, _now, dismissed), isNotNull);
|
||||
});
|
||||
|
||||
test('a dismissed window yields the lead to one still warning', () {
|
||||
final week = _window('week', 93, _day * 3);
|
||||
final warning = chatUsageWarning(
|
||||
_usage([week, _window('five', 82, _hour)]),
|
||||
_now,
|
||||
{chatQuotaKey('Claude Code', week): chatQuotaMarkOf(week)},
|
||||
)!;
|
||||
expect(warning.primary.id, 'five');
|
||||
expect(warning.second, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
test('a level is newly crossed once, and not when dismissed', () {
|
||||
final at84 = _window('five', 84, _hour);
|
||||
final usage = _usage([at84]);
|
||||
expect(chatQuotaNewlyCrossed(usage, _now, const {}, const {}), [at84]);
|
||||
final announced = {
|
||||
chatQuotaKey('Claude Code', at84): chatQuotaMarkOf(at84),
|
||||
};
|
||||
expect(chatQuotaNewlyCrossed(usage, _now, announced, const {}), isEmpty);
|
||||
expect(chatQuotaNewlyCrossed(usage, _now, const {}, announced), isEmpty);
|
||||
final at95 = _window('five', 95.5, _hour);
|
||||
expect(chatQuotaNewlyCrossed(_usage([at95]), _now, announced, const {}), [
|
||||
at95,
|
||||
]);
|
||||
});
|
||||
|
||||
test('texts', () {
|
||||
final five = _window('5-hour', 84.4, const Duration(hours: 1, minutes: 20));
|
||||
expect(
|
||||
chatQuotaWarningTitle('Claude Code', five),
|
||||
'Claude Code 5-hour limit 84% used',
|
||||
);
|
||||
expect(chatQuotaResetsIn(five, _now), 'in 1\u00a0h\u00a020\u00a0m');
|
||||
expect(chatQuotaResetsIn(_window('w', 90, _hour * 3), _now), 'in 3\u00a0h');
|
||||
expect(
|
||||
chatQuotaResetsIn(_window('w', 90, const Duration(minutes: 7)), _now),
|
||||
'in 7\u00a0m',
|
||||
);
|
||||
expect(chatQuotaResetsIn(_window('w', 90, _day), _now), isNull);
|
||||
expect(chatQuotaResetsIn(_window('w', 90, null), _now), isNull);
|
||||
expect(
|
||||
chatQuotaAnnouncement('Claude Code', [
|
||||
_window('5-hour', 90.2, _hour),
|
||||
_window('Weekly', 95, _day),
|
||||
]),
|
||||
'Claude Code 5-hour limit at 90% · Weekly at 95%',
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -6,9 +6,12 @@
|
||||
// `?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);
|
||||
// `?quota=claude|opencode|limit` (with `?chats=N`) pushes a usage frame
|
||||
// with that harness's account quota after a chat subscribes;
|
||||
// `limit` is Claude Code with its 5-hour window exhausted.
|
||||
// `?quota=claude|opencode|limit|warn80|warn95` (with `?chats=N`) pushes a
|
||||
// usage frame with that harness's account quota after a chat
|
||||
// subscribes; `limit` is Claude Code with its 5-hour window
|
||||
// exhausted, `warn80` and `warn95` with it at 84% and 96%
|
||||
// (the early warning) and the weekly window at 60% and 88%;
|
||||
// otherwise the weekly window is at 93%.
|
||||
// `?colors=1` (with `?chats=N`) names the chats, stars and colours some of
|
||||
// them, and keeps colours picked with chat_color;
|
||||
// `?activity=1` (with `?chats=N`) lists a running chat, one with
|
||||
@@ -179,7 +182,12 @@ List<JsonMap> perfChatFollowUps(JsonMap request) {
|
||||
{
|
||||
'id': 'five_hour',
|
||||
'label': '5-hour',
|
||||
'used_percent': quota == 'limit' ? 100 : 42,
|
||||
'used_percent': switch (quota) {
|
||||
'limit' => 100,
|
||||
'warn80' => 84,
|
||||
'warn95' => 96,
|
||||
_ => 42,
|
||||
},
|
||||
'resets_at': at(
|
||||
const Duration(hours: 2, minutes: 14, seconds: 30),
|
||||
),
|
||||
@@ -187,7 +195,11 @@ List<JsonMap> perfChatFollowUps(JsonMap request) {
|
||||
{
|
||||
'id': 'seven_day',
|
||||
'label': 'Weekly',
|
||||
'used_percent': 93,
|
||||
'used_percent': switch (quota) {
|
||||
'warn80' => 60,
|
||||
'warn95' => 88,
|
||||
_ => 93,
|
||||
},
|
||||
'resets_at': at(const Duration(days: 3, hours: 5)),
|
||||
},
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user