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