Chat usage limit: Claude Code-style banner with auto-continue; drop the approaching-limit banner

- The usage-limit banner now reads 'Out of usage credits' (or the refusal's
  own 'You've hit your 5-hour limit'), 'Auto-resuming at <time>', an
  'Auto-continue when limits reset' checkbox and Try again, keeping the
  account switcher's 'Switch to <account>'.
- Auto-continue (a shared, persisted preference, on by default) hands the
  server a durable scheduled prompt (send_at = reset + 1 min) with an
  idempotent auto-continue-<refusal id> operation id: the refused operator
  message again, or 'continue' when the refused turn had already worked.
  Unchecking unqueues it; Try again unqueues it and sends now.
- Remove the approaching-limit banner, its SnackBar announcements and their
  marks; the send-button usage ring replaces them.
- Claude Code's rate_limit_event overage fields (overageStatus,
  isUsingOverage/overageInUse, overageDisabledReason, overageResetsAt) reach
  clients as usage.account.extra_usage; the ring tooltip and the banner say
  'Extra usage available' or 'Using extra usage'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 16:13:33 +00:00
parent 7a259d8f60
commit 293474ac3c
22 changed files with 905 additions and 1254 deletions
@@ -0,0 +1,70 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
const chatAutoContinuePreferenceKey = 'pipelines.chatAutoContinue.v1';
/// The usage-limit banner's "Auto-continue when limits reset" choice: one
/// preference for every chat, on by default, kept in shared preferences so a
/// reload remembers it.
class ChatAutoContinue extends ChangeNotifier {
ChatAutoContinue({this.preferences});
/// The instance chats use unless a test hands them their own.
static final ChatAutoContinue shared = ChatAutoContinue(
preferences: SharedPreferences.getInstance,
);
/// Where the choice is kept; null keeps it in memory.
final Future<SharedPreferences> Function()? preferences;
bool _enabled = true;
bool _loaded = false;
Future<void>? _loading;
bool get enabled => _enabled;
/// Whether the stored choice has been read, so nothing is scheduled on the
/// default before an operator's "off" is known.
bool get loaded => _loaded;
/// Reads the stored choice once.
Future<void> load() => _loading ??= _read();
Future<void> _read() async {
final preferences = this.preferences;
try {
if (preferences != null) {
final stored = (await preferences()).getBool(
chatAutoContinuePreferenceKey,
);
// A choice made while reading wins.
if (stored != null && !_loaded) _enabled = stored;
}
} on Object catch (error) {
// Without storage the default holds for this app session.
debugPrint('Auto-continue: could not read preferences: $error');
}
_loaded = true;
notifyListeners();
}
/// Records the operator's choice.
Future<void> set(bool enabled) async {
_loaded = true;
if (enabled == _enabled) return;
_enabled = enabled;
notifyListeners();
final preferences = this.preferences;
if (preferences == null) return;
try {
await (await preferences()).setBool(
chatAutoContinuePreferenceKey,
enabled,
);
} on Object catch (error) {
debugPrint('Auto-continue: could not save preferences: $error');
}
}
}
@@ -154,11 +154,8 @@ class ChatComposerBar extends StatefulWidget {
/// (no session) offers the recorded commands alone.
final Future<List<ChatCommand>> Function()? loadHarnessCommands;
/// Builds the usage-limit banner above the pill (see
/// ChatUsageLimitBanner); it is handed this bar's own send, so a scheduled
/// draft carries its files and clears the composer as Send does.
final Widget Function(Future<void> Function(int sendAt) sendDraft)?
limitBanner;
/// The usage-limit banner above the pill (see ChatUsageLimitBanner).
final Widget? limitBanner;
/// The chat's colour name (see `chatSessionColor`), the accent of the
/// field's focus ring; null takes the host's primary colour.
@@ -751,7 +748,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// draft's text and operation id. The chips clear with the text as the
/// prompt leaves; a refusal that restores the text restores them too, so
/// the draft and its files stay together.
Future<void> _send({int sendAt = 0}) async {
Future<void> _send() async {
final composer = widget.composer;
if (_uploading || composer.sending || composer.draft.trim().isEmpty) {
return;
@@ -807,7 +804,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
if (keptAttachments.isNotEmpty) {
setState(() => _replaceAttachments(const [], const []));
}
final accepted = await composer.send(attachments: parts, sendAt: sendAt);
final accepted = await composer.send(attachments: parts);
if (!mounted || accepted || keptAttachments.isEmpty) return;
if (_attachments.isEmpty && composer.draft == sentText) {
setState(() => _replaceAttachments(keptAttachments, keptBytes));
@@ -969,8 +966,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.limitBanner case final banner?)
banner((sendAt) => _send(sendAt: sendAt)),
?widget.limitBanner,
if (commands.isNotEmpty)
Padding(
padding: const EdgeInsetsDirectional.only(bottom: 8),
@@ -191,13 +191,15 @@ class ChatComposerController extends ChangeNotifier {
return _deliver(intent, clearDraft: true);
}
/// Asks the server to send [text] (text only) at [sendAt] epoch ms, as a
/// new message, leaving the draft alone: the usage-limit banner's re-send
/// of the operator's last message. Returns whether the server accepted it.
Future<bool> schedule(String text, int sendAt) async {
/// Asks the server to send [text] (text only) at [sendAt] epoch ms (0 sends
/// now), as a new message, leaving the draft alone: the usage-limit
/// banner's auto-continue and Try again. A given [operationId] makes the
/// send idempotent: the server keeps one prompt however many devices ask.
/// Returns whether the server accepted it.
Future<bool> schedule(String text, int sendAt, {String? operationId}) async {
final trimmed = text.trim();
if (_disposed || _sending || trimmed.isEmpty) return false;
final operationId = _nextOperationId();
operationId ??= _nextOperationId();
final intent = ChatComposerSend(
sessionId: sessionId,
text: trimmed,
@@ -52,8 +52,8 @@ import 'chat_composer_bar.dart';
import 'chat_composer_controller.dart';
import 'chat_escape_stop.dart';
import 'chat_delivery_indicator.dart';
import 'chat_auto_continue.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';
@@ -120,6 +120,7 @@ class ChatThreadView extends StatefulWidget {
this.onEffortChanged,
this.syncToken = 0,
this.drafts,
this.autoContinue,
this.newOperationId,
this.attachmentPicker,
this.scrollPositions,
@@ -214,6 +215,10 @@ class ChatThreadView extends StatefulWidget {
/// Draft persistence for tests and previews; production uses the app store.
final ChatDraftStore? drafts;
/// The usage-limit banner's auto-continue preference for tests; null
/// uses the shared one.
final ChatAutoContinue? autoContinue;
/// Test/fixture seam for deterministic operation ids.
final String Function()? newOperationId;
@@ -1279,21 +1284,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
pasteTarget: widget.pasteTarget,
ownsPasteWhenFocused: widget.ownsPasteWhenFocused,
runShell: _shellRuns.start,
limitBanner: (sendDraft) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ChatUsageLimitBanner(
thread: _controller,
composer: _composer,
sendDraft: sendDraft,
accounts: _accounts,
),
ChatUsageWarningBanner(
thread: _controller,
accounts: _accounts,
),
],
limitBanner: ChatUsageLimitBanner(
thread: _controller,
composer: _composer,
accounts: _accounts,
autoContinue: widget.autoContinue,
),
backgroundTasks: ChatBackgroundTasks(
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
@@ -2,42 +2,46 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../domain/chat_commands.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_usage_limit.dart';
import '../shell/chat_shell_command.dart';
import 'chat_auto_continue.dart';
import 'chat_claude_account_switch_action.dart';
import 'chat_claude_accounts_controller.dart';
import 'chat_composer_controller.dart';
import 'chat_schedule_time.dart';
import 'chat_thread_controller.dart';
/// Sends the composer's draft (text and files, as its Send does) for the
/// server to hold until [sendAt] epoch milliseconds.
typedef ChatScheduleDraft = Future<void> Function(int sendAt);
/// Above the composer while the chat's account is out of quota: "Usage limit
/// reached · resets at 15:00" and one button that hands the server a message
/// to send a minute after the reset, so nobody has to come back and say
/// "continue". With a draft it schedules the draft (and clears the composer
/// as Send does); otherwise it re-sends the operator's last message's text.
/// It hides itself once the reset passes.
/// Above the composer while the chat's account is out of quota, as Claude
/// Code's own app shows it: "Out of usage credits" (or the refusal's own
/// "You've hit your 5-hour limit"), "Auto-resuming at 15:41", an
/// "Auto-continue when limits reset" checkbox and Try again.
///
/// With auto-continue on (a preference shared by every chat, on by default,
/// [ChatAutoContinue]) and the transcript ending on the limit's refusal, the
/// banner hands the server a prompt to send a minute after the reset: the
/// refused operator message again, or "continue" when the refused turn had
/// already worked on it. The server holds it durably, so it is sent with the
/// app closed or the server restarted. Unchecking takes it back out of the
/// server's queue; Try again takes it out and sends now. The banner hides
/// once the reset passes.
class ChatUsageLimitBanner extends StatefulWidget {
const ChatUsageLimitBanner({
ChatUsageLimitBanner({
super.key,
required this.thread,
required this.composer,
required this.sendDraft,
this.accounts,
ChatAutoContinue? autoContinue,
this.now = DateTime.now,
});
}) : autoContinue = autoContinue ?? ChatAutoContinue.shared;
final ChatThreadController thread;
final ChatComposerController composer;
final ChatScheduleDraft sendDraft;
/// The chat's saved Claude accounts, for "Switch to (other account)";
/// null for a chat that is not Claude Code's.
final ChatClaudeAccountsController? accounts;
final ChatAutoContinue autoContinue;
final DateTime Function() now;
@override
@@ -48,6 +52,16 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
Timer? _reset;
DateTime? _resetFor;
/// Auto-continue prompts this banner already asked the server for, so a
/// refused request is not repeated on every rebuild.
final Set<String> _requested = {};
@override
void initState() {
super.initState();
unawaited(widget.autoContinue.load());
}
@override
void dispose() {
_reset?.cancel();
@@ -66,10 +80,68 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
});
}
/// The auto-continue prompts the server holds for this chat, and any this
/// device just sent that its queue report has not listed yet.
List<JsonMap> _pending(DateTime now) {
final seen = <String>{};
return [
for (final prompt in [
...widget.thread.queuedPrompts,
...widget.thread.messages,
])
if ('${prompt['operation_id'] ?? prompt['id'] ?? ''}' case final id
when id.startsWith(chatAutoContinuePrefix) &&
chatScheduledSendAt(prompt['send_at'], now) != null &&
seen.add(id))
prompt,
];
}
void _arm(ChatRefusedTurn refused, ChatUsageLimit limit) {
final id = refused.autoContinueId;
if (_requested.contains(id)) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _requested.contains(id)) return;
if (widget.composer.sending) return; // Its end rebuilds the banner.
_requested.add(id);
unawaited(
widget.composer.schedule(
refused.text,
limit.sendAt.millisecondsSinceEpoch,
operationId: id,
),
);
});
}
Future<void> _cancel(List<JsonMap> pending) async {
for (final prompt in pending) {
final id = '${prompt['operation_id'] ?? prompt['id'] ?? ''}';
await widget.composer.unqueue(() => widget.thread.unqueue(id));
}
}
Future<void> _toggle(bool on, List<JsonMap> pending) async {
// Rechecking may schedule the same refusal again.
_requested.clear();
await widget.autoContinue.set(on);
if (!on) await _cancel(pending);
}
Future<void> _tryAgain(ChatRefusedTurn refused, List<JsonMap> pending) async {
_requested.add(refused.autoContinueId);
await _cancel(pending);
await widget.composer.schedule(refused.text, 0);
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([widget.thread, widget.composer]),
listenable: Listenable.merge([
widget.thread,
widget.composer,
widget.autoContinue,
]),
builder: (context, _) {
final now = widget.now();
final thread = widget.thread;
@@ -80,79 +152,74 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
);
_watchReset(limit?.resetsAt, now);
if (limit == null) return const SizedBox.shrink();
return _banner(context, limit, now);
final refused = chatRefusedTurn(thread.messages, thread.accountUsage);
final pending = _pending(now);
final auto = widget.autoContinue;
if (auto.loaded && auto.enabled && refused != null && pending.isEmpty) {
_arm(refused, limit);
}
return _banner(context, limit, refused, pending, now);
},
);
}
Widget _banner(BuildContext context, ChatUsageLimit limit, DateTime now) {
Widget _banner(
BuildContext context,
ChatUsageLimit limit,
ChatRefusedTurn? refused,
List<JsonMap> pending,
DateTime now,
) {
final composer = widget.composer;
final scheme = Theme.of(context).colorScheme;
final text = Theme.of(context).textTheme;
final resets = chatScheduleTime(context, limit.resetsAt, now: () => now);
final sends = chatScheduleTime(context, limit.sendAt, now: () => now);
final draft = composer.draft.trim();
final last = chatLastPrompt(widget.thread.messages);
// Scheduled prompts the server reports, and any this device just sent
// that its queue report has not listed yet.
final scheduled = {
for (final prompt in [
...widget.thread.queuedPrompts,
...widget.thread.messages,
])
if (chatScheduledSendAt(prompt['send_at'], now) != null)
'${prompt['operation_id'] ?? prompt['id']}',
}.length;
final sendAt = limit.sendAt.millisecondsSinceEpoch;
String? label;
VoidCallback? onPressed;
String? note;
if (draft.isNotEmpty) {
// A `!` or `/` draft runs here rather than going to the agent.
if (!chatDraftIsShell(draft) && chatCommandWord(draft) == null) {
label = 'Send this at $sends';
onPressed = () => unawaited(widget.sendDraft(sendAt));
}
} else if (last != null && scheduled == 0) {
label = 'Send last message at $sends';
onPressed = () => unawaited(composer.schedule(last.text, sendAt));
if (last.hadAttachments) note = 'Its attachments are not sent again.';
}
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final text = theme.textTheme;
final enabled = widget.autoContinue.enabled;
String time(DateTime at) => chatScheduleTime(context, at, now: () => now);
final resumesAt = pending.isEmpty
? limit.sendAt
: chatScheduledSendAt(pending.first['send_at'], now)!;
final status = [
'Usage limit reached · resets at $resets',
if (scheduled == 1) '1 message scheduled',
if (scheduled > 1) '$scheduled messages scheduled',
if (enabled && refused != null)
'Auto-resuming at ${time(resumesAt)}'
else
'Resets at ${time(limit.resetsAt)}',
?chatExtraUsageNote(widget.thread.accountUsage),
].join(' · ');
final note = enabled && refused != null && refused.hadAttachments
? 'Its attachments are not sent again.'
: null;
return Padding(
padding: const EdgeInsetsDirectional.only(bottom: 8),
child: Material(
key: const Key('chat-usage-limit'),
color: scheme.errorContainer,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 10, 12, 10),
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 12,
runSpacing: 8,
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 12, 8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.hourglass_bottom, color: scheme.onErrorContainer),
Icon(Icons.hourglass_bottom, color: scheme.error),
const SizedBox(width: 12),
Flexible(
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
refused?.wording ?? 'Out of usage credits',
key: const Key('chat-usage-limit-title'),
style: text.titleSmall,
),
Text(
status,
key: const Key('chat-usage-limit-status'),
style: text.bodyMedium?.copyWith(
color: scheme.onErrorContainer,
fontWeight: FontWeight.w600,
color: scheme.onSurfaceVariant,
),
),
if (note != null)
@@ -160,7 +227,7 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
note,
key: const Key('chat-usage-limit-note'),
style: text.bodySmall?.copyWith(
color: scheme.onErrorContainer,
color: scheme.onSurfaceVariant,
),
),
],
@@ -168,22 +235,59 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
),
],
),
if (label != null)
FilledButton.icon(
key: const Key('chat-usage-limit-schedule'),
onPressed: composer.sending ? null : onPressed,
icon: const Icon(Icons.schedule_send),
label: Text(label),
),
if (widget.accounts case final accounts?)
ChatClaudeAccountSwitchAction(
accounts: accounts,
foreground: scheme.onErrorContainer,
),
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
_checkbox(context, enabled, pending),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (widget.accounts case final accounts?)
ChatClaudeAccountSwitchAction(
accounts: accounts,
foreground: scheme.primary,
),
if (refused != null)
FilledButton.tonal(
key: const Key('chat-usage-limit-try-again'),
onPressed: composer.sending
? null
: () => unawaited(_tryAgain(refused, pending)),
child: const Text('Try again'),
),
],
),
],
),
],
),
),
),
);
}
Widget _checkbox(BuildContext context, bool enabled, List<JsonMap> pending) {
void toggle(bool? on) => unawaited(_toggle(on ?? false, pending));
// A labelled checkbox: the label toggles it too, as one control.
return MergeSemantics(
child: InkWell(
key: const Key('chat-usage-limit-auto-continue'),
borderRadius: BorderRadius.circular(8),
onTap: () => toggle(!enabled),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(value: enabled, onChanged: toggle),
const Flexible(child: Text('Auto-continue when limits reset')),
const SizedBox(width: 8),
],
),
),
);
}
}
@@ -1,198 +0,0 @@
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_claude_account_switch_action.dart';
import 'chat_claude_accounts_controller.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.accounts,
this.now = DateTime.now,
}) : warnings = warnings ?? ChatUsageWarnings.shared;
final ChatThreadController thread;
final ChatUsageWarnings warnings;
/// The chat's saved Claude accounts, for "Switch to (other account)";
/// null for a chat that is not Claude Code's.
final ChatClaudeAccountsController? accounts;
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),
),
],
),
),
),
if (widget.accounts case final accounts?)
Flexible(
child: ChatClaudeAccountSwitchAction(
accounts: accounts,
foreground: foreground,
),
),
IconButton(
key: const Key('chat-usage-warning-dismiss'),
tooltip: 'Dismiss',
color: foreground,
onPressed: () => widget.warnings.dismiss(warning),
icon: const Icon(Icons.close),
),
],
),
),
),
);
}
}
@@ -1,135 +0,0 @@
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');
}
}
}
@@ -30,6 +30,7 @@ class ChatAccountUsage {
required this.windows,
required this.unsupported,
this.switchedAt = 0,
this.extraUsage,
});
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
@@ -48,6 +49,50 @@ class ChatAccountUsage {
/// before any window is known, and an earlier usage-limit refusal in the
/// transcript no longer applies.
final int switchedAt;
/// The account's extra usage (paid usage credits past the limits) as the
/// harness last reported it; null when it never said.
final ChatExtraUsage? extraUsage;
}
/// Claude Code's extra usage ("overage") state, `usage.account.extra_usage`.
class ChatExtraUsage {
const ChatExtraUsage({
required this.status,
required this.inUse,
required this.disabledReason,
});
/// "allowed", "allowed_warning" or "rejected"; empty when unknown.
final String status;
/// Requests are drawing on extra usage now.
final bool inUse;
/// Why extra usage is off, e.g. "out_of_credits"; empty when on.
final String disabledReason;
/// Extra usage would take over when a limit is reached.
bool get available => status == 'allowed' || status == 'allowed_warning';
}
ChatExtraUsage? _extraUsage(Object? value) {
if (value is! Map) return null;
final status = '${value['status'] ?? ''}'.trim();
final reason = '${value['disabled_reason'] ?? ''}'.trim();
final inUse = value['in_use'] == true;
if (status.isEmpty && reason.isEmpty && !inUse) return null;
return ChatExtraUsage(status: status, inUse: inUse, disabledReason: reason);
}
/// A discreet note on [usage]'s extra usage: "Using extra usage" or "Extra
/// usage available"; null when it is off or unknown.
String? chatExtraUsageNote(ChatAccountUsage? usage) {
final extra = usage?.extraUsage;
if (extra == null) return null;
if (extra.inUse) return 'Using extra usage';
if (extra.available) return 'Extra usage available';
return null;
}
int _millis(Object? value) =>
@@ -96,6 +141,7 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
windows: List.unmodifiable(windows),
unsupported: false,
switchedAt: switchedAt,
extraUsage: _extraUsage(value['extra_usage']),
);
}
@@ -1,23 +1,32 @@
/// Whether the open chat's harness account is out of quota, and when it is
/// back, from the account usage the server reports (see
/// chat_account_usage.dart) or, failing that, a turn that just ended on the
/// harness's own "usage limit reached" text.
/// harness's own "usage limit reached" text; and what auto-continue sends
/// once it is back.
library;
import '../../../core/api_gateway.dart';
import 'chat_account_usage.dart';
/// How long after the reported reset a scheduled message is sent, so it does
/// not race the quota coming back.
/// How long after the reported reset an auto-continue message is sent, so
/// it does not race the quota coming back.
const Duration chatScheduleMargin = Duration(minutes: 1);
/// What auto-continue sends when the refused turn had no operator message
/// of its own to send again.
const String chatAutoContinueText = 'continue';
/// The operation id prefix of auto-continue prompts, so unchecking
/// auto-continue can find them in the server's queue.
const String chatAutoContinuePrefix = 'auto-continue-';
class ChatUsageLimit {
const ChatUsageLimit({required this.resetsAt});
/// When the last exhausted window resets, local time.
final DateTime resetsAt;
/// When a message scheduled for this limit is sent.
/// When an auto-continue message for this limit is sent.
DateTime get sendAt => resetsAt.add(chatScheduleMargin);
}
@@ -37,9 +46,9 @@ ChatUsageLimit? chatUsageLimit(ChatAccountUsage? usage, DateTime now) {
return ChatUsageLimit(resetsAt: DateTime.fromMillisecondsSinceEpoch(latest));
}
/// Claude Code ends a refused turn with `Claude AI usage limit reached|<epoch
/// seconds>`; the number is the reset. Null for any other text, or a reset
/// that has passed.
/// Older Claude Code ends a refused turn with
/// `Claude AI usage limit reached|<epoch seconds>`; the number is the reset. Null for any other
/// text, or a reset that has passed.
ChatUsageLimit? chatUsageLimitFromText(String text, DateTime now) {
final match = _limitText.firstMatch(text);
if (match == null) return null;
@@ -52,6 +61,16 @@ ChatUsageLimit? chatUsageLimitFromText(String text, DateTime now) {
final RegExp _limitText = RegExp(r'usage limit reached\|(\d{9,11})\b');
/// Current Claude Code refuses with "You've hit your 5-hour limit · resets
/// 5:20pm (Europe/London) · out of usage credits" (or "your limit", "your
/// session limit"); the first clause is the limit's own wording.
final RegExp _hitText = RegExp(r"^\s*You['’]ve hit your [^·\n]*limit");
/// The last transcript message that is part of the conversation (a message
/// scheduled since is not yet), or an empty map.
JsonMap _lastSent(List<JsonMap> messages) =>
messages.lastWhere((m) => m['send_at'] == null, orElse: () => const {});
/// The limit for the open chat: the reported quota first, then the
/// transcript's last message when it is the harness's limit refusal (a
/// message scheduled since then is not part of the conversation yet).
@@ -62,43 +81,89 @@ ChatUsageLimit? chatThreadUsageLimit(
) {
final quota = chatUsageLimit(usage, now);
if (quota != null) return quota;
final last = messages.lastWhere(
(message) => message['send_at'] == null,
orElse: () => const {},
);
final last = _lastSent(messages);
if (last.isEmpty || last['role'] == 'user') return null;
// A refusal received before the operator switched accounts was the old
// account's.
final switchedAt = usage?.switchedAt ?? 0;
if (switchedAt > 0) {
final created = last['created_at'];
if (created is! num || created <= switchedAt) return null;
}
if (_beforeSwitch(usage, last)) return null;
return chatUsageLimitFromText(_text(last), now);
}
/// The operator's most recent message: its text and whether it carried files
/// (which a scheduled re-send does not repeat).
class ChatLastPrompt {
const ChatLastPrompt({required this.text, required this.hadAttachments});
final String text;
final bool hadAttachments;
/// A refusal received before the operator switched accounts was the old
/// account's.
bool _beforeSwitch(ChatAccountUsage? usage, JsonMap message) {
final switchedAt = usage?.switchedAt ?? 0;
if (switchedAt <= 0) return false;
final created = message['created_at'];
return created is! num || created <= switchedAt;
}
/// The newest user message in [messages] with text, or null.
ChatLastPrompt? chatLastPrompt(List<JsonMap> messages) {
for (final message in messages.reversed) {
if (message['role'] != 'user') continue;
final text = _text(message).trim();
if (text.isEmpty) continue;
final parts = message['parts'];
final files =
parts is List &&
parts.any((part) => part is Map && part['type'] != 'text');
return ChatLastPrompt(text: text, hadAttachments: files);
}
return null;
/// The turn the limit refused: the transcript ends on the harness's limit
/// refusal. Auto-continue and Try again send [text]: the operator's message
/// the refusal answered, or "continue" when the refusal ended a turn that
/// had already worked on it.
class ChatRefusedTurn {
const ChatRefusedTurn({
required this.refusalId,
required this.wording,
required this.text,
required this.resends,
required this.hadAttachments,
});
/// The refusal message's id.
final String refusalId;
/// The refusal's own first clause, "You've hit your 5-hour limit"; null
/// for the older `usage limit reached|<epoch>` text.
final String? wording;
/// What auto-continue and Try again send.
final String text;
/// [text] is the operator's refused message (rather than "continue").
final bool resends;
/// The refused message carried files, which a re-send does not repeat.
final bool hadAttachments;
/// The auto-continue prompt's operation id: one per refusal, so every
/// device that schedules it asks for the same prompt and the server keeps
/// one.
String get autoContinueId => '$chatAutoContinuePrefix$refusalId';
}
/// The refused turn [messages] end on, or null when the last message is not
/// a limit refusal (or came before an account switch in [usage]).
ChatRefusedTurn? chatRefusedTurn(
List<JsonMap> messages,
ChatAccountUsage? usage,
) {
final sent = [
for (final m in messages)
if (m['send_at'] == null) m,
];
if (sent.isEmpty) return null;
final last = sent.last;
if (last['role'] == 'user' || _beforeSwitch(usage, last)) return null;
final text = _text(last);
final hit = _hitText.firstMatch(text);
if (hit == null && !_limitText.hasMatch(text)) return null;
final before = sent.length > 1
? sent[sent.length - 2]
: const <String, Object?>{};
final prompt = before['role'] == 'user' ? _text(before).trim() : '';
return ChatRefusedTurn(
refusalId: '${last['id'] ?? ''}',
wording: hit?.group(0)?.trim(),
text: prompt.isEmpty ? chatAutoContinueText : prompt,
resends: prompt.isNotEmpty,
hadAttachments: prompt.isNotEmpty && _hasFiles(before),
);
}
bool _hasFiles(JsonMap message) {
final parts = message['parts'];
return parts is List &&
parts.any((part) => part is Map && part['type'] != 'text');
}
String _text(JsonMap message) {
@@ -6,14 +6,22 @@
library;
import 'chat_account_usage.dart';
import 'chat_usage_warning.dart';
/// The percentages at which the ring turns from quiet to a warning, then
/// urgent.
const int chatQuotaWarningLevel = 80;
const int chatQuotaUrgentLevel = 95;
/// How the ring is drawn: barely visible, a warning from the first warning
/// level (80%), urgent from [chatQuotaUrgentLevel] (95%).
enum ChatUsageRingTone { quiet, warning, urgent }
class ChatUsageRing {
const ChatUsageRing({required this.shown, required this.windows});
const ChatUsageRing({
required this.shown,
required this.windows,
this.extraUsage,
});
/// The window the ring's arc measures.
final ChatQuotaWindow shown;
@@ -21,13 +29,16 @@ class ChatUsageRing {
/// Every live window, in the harness's order, for the tooltip.
final List<ChatQuotaWindow> windows;
/// "Extra usage available" or "Using extra usage" ([chatExtraUsageNote]).
final String? extraUsage;
/// The arc's share of the circle, 0–1 (past a cap stays full).
double get fraction => (shown.usedPercent / 100).clamp(0.0, 1.0);
ChatUsageRingTone get tone {
final level = chatQuotaLevel(shown.usedPercent);
if (level >= chatQuotaUrgentLevel) return ChatUsageRingTone.urgent;
if (level > 0) return ChatUsageRingTone.warning;
final percent = shown.usedPercent;
if (percent >= chatQuotaUrgentLevel) return ChatUsageRingTone.urgent;
if (percent >= chatQuotaWarningLevel) return ChatUsageRingTone.warning;
return ChatUsageRingTone.quiet;
}
}
@@ -51,7 +62,11 @@ ChatUsageRing? chatUsageRing(ChatAccountUsage? usage, DateTime now) {
if (window.usedPercent > shown.usedPercent) shown = window;
}
}
return ChatUsageRing(shown: shown, windows: List.unmodifiable(live));
return ChatUsageRing(
shown: shown,
windows: List.unmodifiable(live),
extraUsage: chatExtraUsageNote(usage),
);
}
const List<String> _weekdays = [
@@ -85,11 +100,13 @@ String chatUsageRingResetTime(DateTime at, DateTime now) {
return '${local.day} ${months[local.month - 1]} $time';
}
/// "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00".
/// "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00", then any
/// extra usage note.
String chatUsageRingSummary(ChatUsageRing ring, DateTime now) => [
for (final window in ring.windows) ...[
'${window.label} ${window.usedPercent.round()}%',
if (window.resetsAt > 0)
'resets ${chatUsageRingResetTime(DateTime.fromMillisecondsSinceEpoch(window.resetsAt), now)}',
],
?ring.extraUsage,
].join(' · ');
@@ -1,178 +0,0 @@
/// 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';
}
@@ -7,9 +7,8 @@ import 'package:pipelines_app/features/chat/conversation/chat_composer_controlle
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_auto_continue.dart';
import 'package:pipelines_app/features/chat/conversation/chat_usage_limit_banner.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:pipelines_app/features/chat/domain/chat_account_usage.dart';
import 'package:pipelines_app/features/chat/domain/chat_usage_limit.dart';
import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart';
@@ -290,8 +289,8 @@ void main() {
(thread, accounts) => ChatUsageLimitBanner(
thread: thread,
composer: composer,
sendDraft: (_) async {},
accounts: accounts,
autoContinue: ChatAutoContinue(),
),
);
gateway.emitEvent(_limited());
@@ -316,7 +315,7 @@ void main() {
);
});
testWidgets('with several other accounts the warning banner offers a menu', (
testWidgets('with several other accounts the limit banner offers a menu', (
tester,
) async {
final gateway = _AccountsGateway([
@@ -324,18 +323,21 @@ void main() {
'b@example.invalid',
'c@example.invalid',
]);
final composer = ChatComposerController(gateway, 's');
addTearDown(composer.dispose);
await _pump(
tester,
gateway,
(thread, accounts) => ChatUsageWarningBanner(
(thread, accounts) => ChatUsageLimitBanner(
thread: thread,
warnings: ChatUsageWarnings(announce: (_) => true),
composer: composer,
accounts: accounts,
autoContinue: ChatAutoContinue(),
),
);
gateway.emitEvent(_limited(five: 90));
gateway.emitEvent(_limited());
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
expect(find.byKey(const Key('chat-usage-limit')), findsOneWidget);
await tester.tap(find.text('Switch account'));
await tester.pumpAndSettle();
expect(
@@ -353,18 +355,21 @@ void main() {
tester,
) async {
final gateway = _AccountsGateway(['a@example.invalid']);
final composer = ChatComposerController(gateway, 's');
addTearDown(composer.dispose);
await _pump(
tester,
gateway,
(thread, accounts) => ChatUsageWarningBanner(
(thread, accounts) => ChatUsageLimitBanner(
thread: thread,
warnings: ChatUsageWarnings(announce: (_) => true),
composer: composer,
accounts: accounts,
autoContinue: ChatAutoContinue(),
),
);
gateway.emitEvent(_limited(five: 90));
gateway.emitEvent(_limited());
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
expect(find.byKey(const Key('chat-usage-limit')), findsOneWidget);
expect(find.byKey(const Key('chat-claude-switch')), findsNothing);
});
}
@@ -1,28 +1,56 @@
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_auto_continue.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_schedule_time.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'chat_thread_fixtures.dart';
/// A thread gateway that records prompt bodies and answers them as queued,
/// as the server does for one carrying `send_at`.
/// A thread gateway that keeps the server's prompt queue: a prompt carrying
/// `send_at` is held (and reported in a `chat_queue` frame) until removed.
class _Gateway extends FakeChatGateway {
final promptBodies = <JsonMap>[];
final unqueued = <String>[];
final held = <JsonMap>[];
List<JsonMap> messages = [];
_Gateway() {
history = (_) async => chatPage(messages);
}
JsonMap get _queue => {
'session_id': 's',
'prompts': [...held],
};
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'chat_prompt') {
final body = fields['chat_prompt'] as JsonMap;
promptBodies.add(body);
return {'chat_queued': body['send_at'] != null};
final scheduled = body['send_at'] != null;
if (scheduled &&
!held.any((p) => p['operation_id'] == body['operation_id'])) {
held.add({
'operation_id': body['operation_id'],
'native_message_id': body['native_message_id'],
'text': body['text'],
'send_at': body['send_at'],
});
emitRaw({'type': 'chat_queue', 'chat_queue': _queue});
}
return {'chat_queued': scheduled};
}
if (type == 'chat_unqueue') {
final id = (fields['chat_unqueue'] as JsonMap)['operation_id'];
unqueued.add('$id');
held.removeWhere((p) => p['operation_id'] == id);
return {
'chat_queue': {..._queue, 'removed': id},
};
}
return super.call(type, fields);
}
@@ -30,7 +58,11 @@ class _Gateway extends FakeChatGateway {
JsonMap _text(String text) => {'type': 'text', 'text': text};
JsonMap _limitFrame(DateTime reset, {double percent = 100}) => {
const _hit =
"You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of "
'usage credits';
JsonMap _limitFrame(DateTime reset, {double percent = 100, JsonMap? extra}) => {
'session_id': 's',
'kind': 'usage',
'usage': {
@@ -44,15 +76,8 @@ JsonMap _limitFrame(DateTime reset, {double percent = 100}) => {
'used_percent': percent,
'resets_at': reset.millisecondsSinceEpoch,
},
{
'id': 'seven_day',
'label': 'Weekly',
'used_percent': 40,
'resets_at': reset
.add(const Duration(days: 2))
.millisecondsSinceEpoch,
},
],
'extra_usage': ?extra,
},
},
};
@@ -63,27 +88,27 @@ Future<void> _pump(WidgetTester tester) async {
await tester.pump();
}
/// A refused operator message: the refusal answers it directly.
List<JsonMap> _refusedPrompt() => [
chatMessage('u1', 'user', parts: [_text('first')]),
chatMessage('a1', 'assistant', parts: [_text('Done.')]),
chatMessage(
'u2',
'user',
parts: [
_text('Fix the flaky build'),
{'type': 'file', 'name': 'log.txt', 'uri': 'file://log.txt'},
],
),
chatMessage('r1', 'assistant', parts: [_text(_hit)]),
];
Future<_Gateway> _host(
WidgetTester tester, {
List<JsonMap>? messages,
Future<JsonMap> Function()? subscribe,
ChatAutoContinue? autoContinue,
}) async {
final gateway = _Gateway()
..messages =
messages ??
[
chatMessage('u1', 'user', parts: [_text('first')]),
chatMessage(
'u2',
'user',
parts: [
_text('Fix the flaky build'),
{'type': 'file', 'name': 'log.txt', 'uri': 'file://log.txt'},
],
),
chatMessage('a1', 'assistant', parts: [_text('On it.')]),
]
..subscribe = subscribe;
final gateway = _Gateway()..messages = messages ?? _refusedPrompt();
addTearDown(gateway.close);
var sequence = 0;
await tester.pumpWidget(
@@ -95,6 +120,9 @@ Future<_Gateway> _host(
onBack: () {},
drafts: MemoryChatDraftStore(),
newOperationId: () => 'op-${++sequence}',
autoContinue:
autoContinue ??
ChatAutoContinue(preferences: SharedPreferences.getInstance),
),
),
),
@@ -106,104 +134,167 @@ Future<_Gateway> _host(
String _time(WidgetTester tester, DateTime at) =>
chatScheduleTime(tester.element(find.byType(Scaffold)), at);
/// A reset on a whole millisecond, as the wire carries it.
DateTime _resetIn(Duration offset) => DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(offset).millisecondsSinceEpoch,
);
final _banner = find.byKey(const Key('chat-usage-limit'));
final _button = find.byKey(const Key('chat-usage-limit-schedule'));
final _status = find.byKey(const Key('chat-usage-limit-status'));
final _checkbox = find.byKey(const Key('chat-usage-limit-auto-continue'));
final _tryAgain = find.byKey(const Key('chat-usage-limit-try-again'));
String _statusText(WidgetTester tester) => tester.widget<Text>(_status).data!;
bool _checked(WidgetTester tester) => tester
.widget<Checkbox>(
find.descendant(of: _checkbox, matching: find.byType(Checkbox)),
)
.value!;
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
testWidgets('no banner until a window is exhausted', (tester) async {
final gateway = await _host(tester);
expect(_banner, findsNothing);
final reset = DateTime.now().add(const Duration(hours: 2));
gateway.emitEvent(_limitFrame(reset, percent: 97));
gateway.emitEvent(
_limitFrame(_resetIn(const Duration(hours: 2)), percent: 97),
);
await _pump(tester);
expect(_banner, findsNothing);
expect(gateway.promptBodies, isEmpty);
});
testWidgets('the button schedules the last message a minute after reset', (
tester,
) async {
testWidgets('auto-continue hands the server the refused message for a '
'minute after the reset, once', (tester) async {
final gateway = await _host(tester);
final reset = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(const Duration(hours: 2)).millisecondsSinceEpoch,
);
final reset = _resetIn(const Duration(hours: 2));
final sendAt = reset.add(const Duration(minutes: 1));
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
final sendAt = reset.add(const Duration(minutes: 1));
expect(
find.text('Usage limit reached · resets at ${_time(tester, reset)}'),
findsOneWidget,
);
expect(
find.text('Send last message at ${_time(tester, sendAt)}'),
findsOneWidget,
);
// The earlier message's file is not repeated, and the banner says so.
expect(find.text("You've hit your 5-hour limit"), findsOneWidget);
expect(_statusText(tester), 'Auto-resuming at ${_time(tester, sendAt)}');
expect(_checked(tester), isTrue);
expect(find.text('Its attachments are not sent again.'), findsOneWidget);
await tester.tap(_button);
await _pump(tester);
final body = gateway.promptBodies.single;
expect(body['text'], 'Fix the flaky build');
expect(body['send_at'], sendAt.millisecondsSinceEpoch);
expect(body['operation_id'], 'auto-continue-r1');
expect(body.containsKey('attachments'), isFalse);
// The new bubble reads as scheduled rather than plain "Queued".
expect(find.byKey(const Key('chat-delivery-scheduled')), findsOneWidget);
// The server holds it: it reads as scheduled and is not asked for again.
await _pump(tester);
expect(
find.text('Scheduled · sends at ${_time(tester, sendAt)}'),
findsOneWidget,
);
// It waits for its time, not the current turn, and is not offered twice.
expect(find.byKey(const Key('chat-composer-queued')), findsNothing);
expect(find.textContaining('1 message scheduled'), findsOneWidget);
expect(_button, findsNothing);
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
expect(gateway.promptBodies, hasLength(1));
});
testWidgets('with a draft the button schedules the draft and clears it', (
testWidgets('a refusal after the turn worked sends "continue"', (
tester,
) async {
final gateway = await _host(
tester,
messages: [
chatMessage('u1', 'user', parts: [_text('Fix it')]),
chatMessage('a1', 'assistant', parts: [_text('Working on it.')]),
chatMessage('r1', 'assistant', parts: [_text(_hit)]),
],
);
gateway.emitEvent(_limitFrame(_resetIn(const Duration(hours: 1))));
await _pump(tester);
expect(gateway.promptBodies.single['text'], 'continue');
expect(find.text('Its attachments are not sent again.'), findsNothing);
});
testWidgets('unchecking is remembered and takes the prompt back', (
tester,
) async {
final gateway = await _host(tester);
final reset = DateTime.now().add(const Duration(minutes: 40));
final reset = _resetIn(const Duration(hours: 2));
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
final sendAt = DateTime.fromMillisecondsSinceEpoch(
reset.millisecondsSinceEpoch,
).add(const Duration(minutes: 1));
expect(gateway.held, hasLength(1));
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'Then run the tests',
);
await tester.tap(_checkbox);
await _pump(tester);
expect(find.text('Send this at ${_time(tester, sendAt)}'), findsOneWidget);
expect(find.text('Its attachments are not sent again.'), findsNothing);
await tester.tap(_button);
expect(_checked(tester), isFalse);
expect(gateway.unqueued, ['auto-continue-r1']);
expect(gateway.held, isEmpty);
expect(find.textContaining('Scheduled · sends at'), findsNothing);
expect(_statusText(tester), 'Resets at ${_time(tester, reset)}');
final preferences = await SharedPreferences.getInstance();
expect(preferences.getBool(chatAutoContinuePreferenceKey), isFalse);
// Off, nothing is scheduled again.
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
expect(gateway.promptBodies, hasLength(1));
final body = gateway.promptBodies.single;
expect(body['text'], 'Then run the tests');
expect(body['send_at'], sendAt.millisecondsSinceEpoch);
final field = tester.widget<TextField>(
find.byKey(const Key('chat-composer-field')),
);
expect(field.controller!.text, isEmpty);
// Checking it again schedules the same prompt again.
await tester.tap(_checkbox);
await _pump(tester);
expect(_checked(tester), isTrue);
expect(preferences.getBool(chatAutoContinuePreferenceKey), isTrue);
expect(gateway.promptBodies, hasLength(2));
expect(gateway.held.single['operation_id'], 'auto-continue-r1');
});
testWidgets('nothing to send hides the button', (tester) async {
testWidgets('a stored "off" schedules nothing', (tester) async {
SharedPreferences.setMockInitialValues({
chatAutoContinuePreferenceKey: false,
});
final gateway = await _host(tester);
final reset = _resetIn(const Duration(hours: 2));
gateway.emitEvent(_limitFrame(reset));
await _pump(tester);
expect(_banner, findsOneWidget);
expect(_checked(tester), isFalse);
expect(_statusText(tester), 'Resets at ${_time(tester, reset)}');
expect(gateway.promptBodies, isEmpty);
});
testWidgets('Try again takes the scheduled prompt back and sends now', (
tester,
) async {
final gateway = await _host(tester);
gateway.emitEvent(_limitFrame(_resetIn(const Duration(hours: 2))));
await _pump(tester);
expect(gateway.held, hasLength(1));
await tester.tap(_tryAgain);
await _pump(tester);
expect(gateway.unqueued, ['auto-continue-r1']);
final now = gateway.promptBodies.last;
expect(now['text'], 'Fix the flaky build');
expect(now.containsKey('send_at'), isFalse);
expect(now['operation_id'], isNot('auto-continue-r1'));
expect(gateway.promptBodies, hasLength(2));
});
testWidgets('a quota limit with no refused turn only says when it resets', (
tester,
) async {
final gateway = await _host(
tester,
messages: [
chatMessage('a1', 'assistant', parts: [_text('Hello.')]),
],
);
gateway.emitEvent(
_limitFrame(DateTime.now().add(const Duration(hours: 1))),
);
final reset = _resetIn(const Duration(hours: 1));
gateway.emitEvent(_limitFrame(reset, extra: {'status': 'allowed'}));
await _pump(tester);
expect(_banner, findsOneWidget);
expect(_button, findsNothing);
expect(find.text('Out of usage credits'), findsOneWidget);
expect(
_statusText(tester),
'Resets at ${_time(tester, reset)} · Extra usage available',
);
expect(_tryAgain, findsNothing);
expect(gateway.promptBodies, isEmpty);
});
testWidgets('a passed reset is not a limit', (tester) async {
@@ -213,42 +304,7 @@ void main() {
);
await _pump(tester);
expect(_banner, findsNothing);
});
testWidgets('a queued prompt with send_at reads Scheduled with Remove', (
tester,
) async {
final sendAt = DateTime.fromMillisecondsSinceEpoch(
DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch,
);
final gateway = await _host(
tester,
subscribe: () async => {
'chat_queue': {
'session_id': 's',
'prompts': [
{
'operation_id': 'later',
'text': 'continue',
'send_at': sendAt.millisecondsSinceEpoch,
},
{'operation_id': 'next', 'text': 'and then this'},
],
},
},
);
expect(
find.text('Scheduled · sends at ${_time(tester, sendAt)}'),
findsOneWidget,
);
expect(find.text('Queued'), findsOneWidget);
expect(find.byKey(const Key('chat-delivery-remove')), findsNWidgets(2));
// With a message already scheduled the banner offers no second re-send.
gateway.emitEvent(_limitFrame(sendAt.subtract(const Duration(minutes: 1))));
await _pump(tester);
expect(find.textContaining('1 message scheduled'), findsOneWidget);
expect(_button, findsNothing);
expect(gateway.promptBodies, isEmpty);
});
testWidgets('chatScheduleTime names another day', (tester) async {
@@ -1,233 +0,0 @@
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);
});
}
@@ -123,31 +123,107 @@ void main() {
);
});
test('the last prompt is the newest user text and notes its files', () {
final last = chatLastPrompt([
{
'role': 'user',
'parts': [
{'type': 'text', 'text': 'first'},
],
},
{
'role': 'user',
'parts': [
{'type': 'text', 'text': ' fix the build '},
{'type': 'file', 'name': 'log.txt'},
],
},
{
'role': 'assistant',
'parts': [
{'type': 'text', 'text': 'ok'},
],
},
])!;
expect(last.text, 'fix the build');
expect(last.hadAttachments, isTrue);
expect(chatLastPrompt(const []), isNull);
group('chatRefusedTurn', () {
Map<String, Object?> message(
String id,
String role,
String text, {
bool file = false,
int? sendAt,
}) => {
'id': id,
'role': role,
'send_at': ?sendAt,
'parts': [
{'type': 'text', 'text': text},
if (file) {'type': 'file', 'name': 'log.txt'},
],
};
const hit =
"You've hit your 5-hour limit · resets 5:20pm (Europe/London) · "
'out of usage credits';
test('a refused operator message is sent again, without its files', () {
final turn = chatRefusedTurn([
message('u1', 'user', 'first'),
message('a1', 'assistant', 'done'),
message('u2', 'user', ' fix the build ', file: true),
message('r1', 'assistant', hit),
], null)!;
expect(turn.text, 'fix the build');
expect(turn.resends, isTrue);
expect(turn.hadAttachments, isTrue);
expect(turn.wording, "You've hit your 5-hour limit");
expect(turn.autoContinueId, 'auto-continue-r1');
});
test('a refusal after the turn worked continues it', () {
final turn = chatRefusedTurn([
message('u1', 'user', 'fix it'),
message('a1', 'assistant', 'Working on it.'),
message('r1', 'assistant', 'Claude AI usage limit reached|1900000000'),
// A prompt scheduled since is not part of the conversation yet.
message('q1', 'user', 'continue', sendAt: 1900000060000),
], null)!;
expect(turn.text, 'continue');
expect(turn.resends, isFalse);
expect(turn.wording, isNull);
});
test('anything but a refusal last is not a refused turn', () {
expect(chatRefusedTurn(const [], null), isNull);
expect(
chatRefusedTurn([message('a1', 'assistant', 'All done.')], null),
isNull,
);
expect(
chatRefusedTurn([
message('r1', 'assistant', hit),
message('u1', 'user', 'continue'),
], null),
isNull,
);
});
test('a refusal from before an account switch no longer counts', () {
final refusal = {...message('r1', 'assistant', hit), 'created_at': 10};
final switched = ChatAccountUsage(
harness: 'Claude Code',
plan: 'max',
asOf: 0,
windows: const [],
unsupported: false,
switchedAt: 20,
);
expect(chatRefusedTurn([refusal], switched), isNull);
expect(chatRefusedTurn([refusal], null), isNotNull);
});
});
test('extra usage reads as available or in use, else nothing', () {
ChatAccountUsage? parse(Map<String, Object?> extra) => chatAccountUsage({
'harness': 'Claude Code',
'windows': [
{'id': 'five_hour', 'label': '5-hour', 'used_percent': 10},
],
'extra_usage': extra,
});
expect(
chatExtraUsageNote(parse({'status': 'allowed'})),
'Extra usage available',
);
expect(
chatExtraUsageNote(parse({'status': 'allowed', 'in_use': true})),
'Using extra usage',
);
expect(
chatExtraUsageNote(
parse({'status': 'rejected', 'disabled_reason': 'out_of_credits'}),
),
isNull,
);
expect(chatExtraUsageNote(parse({})), isNull);
expect(chatExtraUsageNote(null), isNull);
});
test('scheduled send_at is a future epoch-ms time only', () {
@@ -129,6 +129,44 @@ void main() {
);
});
test('summary ends with extra usage when the account has it', () {
ChatUsageRing ring(ChatExtraUsage extra) => chatUsageRing(
ChatAccountUsage(
harness: 'Claude Code',
plan: 'max',
asOf: 0,
windows: [_window('five_hour', '5-hour', 42, null)],
unsupported: false,
extraUsage: extra,
),
_now,
)!;
const available = ChatExtraUsage(
status: 'allowed',
inUse: false,
disabledReason: '',
);
expect(
chatUsageRingSummary(ring(available), _now),
'5-hour 42% · Extra usage available',
);
const inUse = ChatExtraUsage(
status: 'allowed_warning',
inUse: true,
disabledReason: '',
);
expect(
chatUsageRingSummary(ring(inUse), _now),
'5-hour 42% · Using extra usage',
);
const off = ChatExtraUsage(
status: 'rejected',
inUse: false,
disabledReason: 'out_of_credits',
);
expect(chatUsageRingSummary(ring(off), _now), '5-hour 42%');
});
test('reset times: today, this week, further out', () {
expect(chatUsageRingResetTime(DateTime(2026, 11, 30, 8, 5), _now), '08:05');
expect(
@@ -1,197 +0,0 @@
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%',
);
});
}
+31 -3
View File
@@ -9,9 +9,10 @@
// `?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%.
// exhausted and the transcript ending on Claude Code's limit
// refusal, `warn80` and `warn95` with it at 84% and 96% (the
// send ring's warning tones) 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
@@ -351,6 +352,20 @@ JsonMap? perfChatReply(JsonMap request) {
'chat_queued': _scheduledPrompt(request) != null,
if (_params['steered'] == '1') 'chat_steered': true,
};
case 'chat_unqueue':
// The fixture holds at most the one scheduled prompt: removing it
// leaves the queue empty.
final body = request['chat_unqueue'];
final unqueue = body is Map ? body : const {};
return {
'id': id,
'type': 'chat_unqueue',
'chat_queue': {
'session_id': unqueue['session_id'],
'prompts': const [],
'removed': unqueue['operation_id'],
},
};
case 'chat_shells':
return {
'id': id,
@@ -447,6 +462,19 @@ JsonMap? perfChatReply(JsonMap request) {
},
],
},
if (_params['quota'] == 'limit')
{
'id': 'perf-limit-refusal',
'role': 'assistant',
'parts': [
{
'type': 'text',
'text':
"You've hit your 5-hour limit · resets 5:20pm "
'(Europe/London) · out of usage credits',
},
],
},
],
'next_cursor': '',
'has_more': false,
+7
View File
@@ -523,6 +523,13 @@ they were. No quota is estimated and no model call is made to obtain one.
`switched_at` (epoch ms) marks a report sent after the operator switched the
chat's Claude account: it replaces the previous account's report even with no
windows yet, and a usage-limit refusal received before it no longer applies.
`extra_usage` is Claude Code's extra usage ("overage", paid usage credits past
the subscription limits) from the same events, kept until a later event says
otherwise: `{"status","in_use","disabled_reason","resets_at"}`, where `status`
is its `overageStatus` (`allowed`, `allowed_warning`, `rejected`) and
`disabled_reason` its `overageDisabledReason` (e.g. `out_of_credits`). It is
informational: Claude Code offers no stream-json request to turn extra usage on
or to use a limit reset, so the server never applies one.
### Claude account switching
+36
View File
@@ -59,6 +59,32 @@ type rateLimitInfo struct {
RateLimitType string `json:"rateLimitType"`
Utilization *float64 `json:"utilization"`
UnifiedWindows map[string]*rateLimitWindowInfo `json:"unifiedWindows"`
// Extra usage ("overage"): paid usage credits past the subscription
// limits. Claude Code reports whether they would be accepted, whether
// they are in use and why they are off; nothing here applies them.
OverageStatus string `json:"overageStatus"`
OverageResetsAt *float64 `json:"overageResetsAt"`
OverageDisabledReason string `json:"overageDisabledReason"`
IsUsingOverage *bool `json:"isUsingOverage"`
OverageInUse *bool `json:"overageInUse"`
}
// extraUsage is the event's overage state, or nil when it names none.
func (info rateLimitInfo) extraUsage() *protocol.ChatExtraUsage {
if info.OverageStatus == "" && info.OverageDisabledReason == "" {
return nil
}
inUse := (info.IsUsingOverage != nil && *info.IsUsingOverage) ||
(info.OverageInUse != nil && *info.OverageInUse)
extra := &protocol.ChatExtraUsage{
Status: info.OverageStatus,
InUse: inUse,
DisabledReason: info.OverageDisabledReason,
}
if at := info.OverageResetsAt; at != nil && *at > 0 && !math.IsInf(*at, 0) {
extra.ResetsAt = int64(*at * 1000)
}
return extra
}
// quotaWindowOrder lists the windows Claude Code names, in display order.
@@ -119,6 +145,11 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
changed = true
}
}
// Overage news alone updates a report that already has windows.
extra := info.extraUsage()
if extra != nil && previous != nil {
changed = true
}
if !changed {
return nil
}
@@ -130,7 +161,12 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
// A switch stays recorded: the refusal it cleared is still in the
// transcript.
next.SwitchedAt = previous.SwitchedAt
if extra == nil && previous.ExtraUsage != nil {
kept := *previous.ExtraUsage
extra = &kept
}
}
next.ExtraUsage = extra
for _, entry := range quotaWindowOrder {
if w, ok := windows[entry.id]; ok {
next.Windows = append(next.Windows, w)
+30
View File
@@ -55,6 +55,36 @@ func TestMergeRateLimitKeepsUnmentionedWindowsAndIgnoresStatusOnly(t *testing.T)
}
}
func TestMergeRateLimitCarriesExtraUsage(t *testing.T) {
now := time.UnixMilli(1_800_000_000_000)
first := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "max", now)
if first.ExtraUsage != nil {
t.Fatalf("no overage fields, extra = %+v", first.ExtraUsage)
}
// Overage news alone updates a known report.
next := mergeRateLimit(first, json.RawMessage(`{"status":"rejected","overageStatus":"allowed","isUsingOverage":true,"overageResetsAt":1901000000}`), "", now)
want := &protocol.ChatExtraUsage{Status: "allowed", InUse: true, ResetsAt: 1_901_000_000_000}
if next == nil || !reflect.DeepEqual(next.ExtraUsage, want) || len(next.Windows) != 2 {
t.Fatalf("merge = %+v", next)
}
// A later window-only event keeps the last overage state.
kept := mergeRateLimit(next, json.RawMessage(`{"status":"allowed","rateLimitType":"five_hour","utilization":0.5,"resetsAt":1899990000}`), "", now)
if kept == nil || !reflect.DeepEqual(kept.ExtraUsage, want) {
t.Fatalf("kept = %+v", kept)
}
if clone := kept.Clone(); clone.ExtraUsage == kept.ExtraUsage {
t.Fatal("clone shares the extra usage")
}
off := mergeRateLimit(kept, json.RawMessage(`{"status":"rejected","overageStatus":"rejected","overageDisabledReason":"out_of_credits","isUsingOverage":false}`), "", now)
if off == nil || !reflect.DeepEqual(off.ExtraUsage, &protocol.ChatExtraUsage{Status: "rejected", DisabledReason: "out_of_credits"}) {
t.Fatalf("off = %+v", off)
}
// Without a report to attach to, overage alone shows nothing.
if got := mergeRateLimit(nil, json.RawMessage(`{"overageStatus":"allowed"}`), "", now); got != nil {
t.Fatalf("lone overage = %+v", got)
}
}
func TestDecodeAccountIdentity(t *testing.T) {
got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`))
if got.key == "" || got.plan != "max" {
+21
View File
@@ -804,6 +804,23 @@ type ChatAccountUsage struct {
// account even with no windows yet, and a usage-limit refusal the chat
// received before it no longer applies.
SwitchedAt int64 `json:"switched_at,omitempty"`
// ExtraUsage is the account's extra usage (Claude Code's "overage": paid
// usage credits past the subscription limits) as the harness last
// reported it; nil when it never said.
ExtraUsage *ChatExtraUsage `json:"extra_usage,omitempty"`
}
// ChatExtraUsage is Claude Code's overage state from rate_limit_event:
// Status is its overageStatus ("allowed", "allowed_warning" or "rejected"),
// InUse whether requests are drawing on extra usage now, and DisabledReason
// its overageDisabledReason (e.g. "out_of_credits", "org_level_disabled",
// "overage_not_provisioned") when it is off. ResetsAt is when the extra usage
// period resets (epoch milliseconds), 0 if unknown.
type ChatExtraUsage struct {
Status string `json:"status,omitempty"`
InUse bool `json:"in_use,omitempty"`
DisabledReason string `json:"disabled_reason,omitempty"`
ResetsAt int64 `json:"resets_at,omitempty"`
}
// ChatQuotaWindow is one rolling quota window. UsedPercent is 0-100 (it can
@@ -823,6 +840,10 @@ func (a *ChatAccountUsage) Clone() *ChatAccountUsage {
}
copy := *a
copy.Windows = append([]ChatQuotaWindow(nil), a.Windows...)
if a.ExtraUsage != nil {
extra := *a.ExtraUsage
copy.ExtraUsage = &extra
}
return &copy
}