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');
}
}
}