Chat: warn before the harness account's usage limit runs out
A compact banner above the composer when any quota window of the chat's harness account reaches 80% (error colours from 95%), naming the most constrained window and a second one also at 80%+. Dismissing it holds per harness+window until the next level (80/90/95) or a reset, across chats and reloads; a newly crossed level is announced once with a root SnackBar. The usage-limit banner wins. Fixture: quota=warn80|warn95. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,7 @@ import 'chat_composer_controller.dart';
|
||||
import 'chat_escape_stop.dart';
|
||||
import 'chat_delivery_indicator.dart';
|
||||
import 'chat_usage_limit_banner.dart';
|
||||
import 'chat_usage_warning_banner.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_effort_control.dart';
|
||||
@@ -1254,10 +1255,17 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
pasteTarget: widget.pasteTarget,
|
||||
ownsPasteWhenFocused: widget.ownsPasteWhenFocused,
|
||||
runShell: _shellRuns.start,
|
||||
limitBanner: (sendDraft) => ChatUsageLimitBanner(
|
||||
thread: _controller,
|
||||
composer: _composer,
|
||||
sendDraft: sendDraft,
|
||||
limitBanner: (sendDraft) => Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ChatUsageLimitBanner(
|
||||
thread: _controller,
|
||||
composer: _composer,
|
||||
sendDraft: sendDraft,
|
||||
),
|
||||
ChatUsageWarningBanner(thread: _controller),
|
||||
],
|
||||
),
|
||||
backgroundTasks: ChatBackgroundTasks(
|
||||
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/chat_account_usage.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import '../domain/chat_usage_warning.dart';
|
||||
import 'chat_schedule_time.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_usage_warnings.dart';
|
||||
|
||||
/// Above the composer while the chat's harness account is nearly out of
|
||||
/// quota: "Claude Code 5-hour limit 84% used · resets in 1 h 20 m", in the
|
||||
/// error colours from 95%. It names the most constrained window and a second
|
||||
/// one also at a warning level. Dismissing it holds until a window reaches the
|
||||
/// next level or resets, in every chat of the account ([ChatUsageWarnings]).
|
||||
/// The usage-limit banner wins: this one hides while the account is out of
|
||||
/// quota. It also hands each new account report to [warnings], which
|
||||
/// announces a newly crossed level once.
|
||||
class ChatUsageWarningBanner extends StatefulWidget {
|
||||
ChatUsageWarningBanner({
|
||||
super.key,
|
||||
required this.thread,
|
||||
ChatUsageWarnings? warnings,
|
||||
this.now = DateTime.now,
|
||||
}) : warnings = warnings ?? ChatUsageWarnings.shared;
|
||||
|
||||
final ChatThreadController thread;
|
||||
final ChatUsageWarnings warnings;
|
||||
final DateTime Function() now;
|
||||
|
||||
@override
|
||||
State<ChatUsageWarningBanner> createState() => _ChatUsageWarningBannerState();
|
||||
}
|
||||
|
||||
class _ChatUsageWarningBannerState extends State<ChatUsageWarningBanner> {
|
||||
ChatAccountUsage? _reported;
|
||||
|
||||
/// Refreshes the countdown and drops a window once its reset passes.
|
||||
Timer? _tick;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(widget.warnings.load());
|
||||
widget.thread.addListener(_report);
|
||||
_report();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatUsageWarningBanner oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.thread == widget.thread) return;
|
||||
oldWidget.thread.removeListener(_report);
|
||||
widget.thread.addListener(_report);
|
||||
_report();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.thread.removeListener(_report);
|
||||
_tick?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _report() {
|
||||
final usage = widget.thread.accountUsage;
|
||||
if (usage == null || identical(usage, _reported)) return;
|
||||
_reported = usage;
|
||||
unawaited(widget.warnings.report(usage, now: widget.now()));
|
||||
}
|
||||
|
||||
void _ticking(bool on) {
|
||||
if (on == (_tick != null)) return;
|
||||
_tick?.cancel();
|
||||
_tick = on
|
||||
? Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
if (mounted) setState(() {});
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.thread, widget.warnings]),
|
||||
builder: (context, _) {
|
||||
final now = widget.now();
|
||||
final thread = widget.thread;
|
||||
final limited =
|
||||
chatThreadUsageLimit(thread.accountUsage, thread.messages, now) !=
|
||||
null;
|
||||
final warning = limited
|
||||
? null
|
||||
: chatUsageWarning(
|
||||
thread.accountUsage,
|
||||
now,
|
||||
widget.warnings.dismissed,
|
||||
);
|
||||
_ticking(warning != null);
|
||||
if (warning == null) return const SizedBox.shrink();
|
||||
return _banner(context, warning, now);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _resets(ChatQuotaWindow window, DateTime now) {
|
||||
if (window.resetsAt <= 0) return '';
|
||||
final relative = chatQuotaResetsIn(window, now);
|
||||
if (relative != null) return ' · resets $relative';
|
||||
final at = DateTime.fromMillisecondsSinceEpoch(window.resetsAt);
|
||||
return ' · resets ${chatScheduleTime(context, at, now: () => now)}';
|
||||
}
|
||||
|
||||
Widget _banner(BuildContext context, ChatUsageWarning warning, DateTime now) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final text = Theme.of(context).textTheme;
|
||||
final background = warning.urgent
|
||||
? scheme.errorContainer
|
||||
: scheme.secondaryContainer;
|
||||
final foreground = warning.urgent
|
||||
? scheme.onErrorContainer
|
||||
: scheme.onSecondaryContainer;
|
||||
final second = warning.second;
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.only(bottom: 8),
|
||||
child: Material(
|
||||
key: const Key('chat-usage-warning'),
|
||||
color: background,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
warning.urgent ? Icons.error_outline : Icons.data_usage,
|
||||
color: foreground,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
chatQuotaWarningTitle(
|
||||
warning.harness,
|
||||
warning.primary,
|
||||
) +
|
||||
_resets(warning.primary, now),
|
||||
key: const Key('chat-usage-warning-status'),
|
||||
style: text.bodyMedium?.copyWith(
|
||||
color: foreground,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (second != null)
|
||||
Text(
|
||||
'${second.label} limit '
|
||||
'${second.usedPercent.round()}% used'
|
||||
'${_resets(second, now)}',
|
||||
key: const Key('chat-usage-warning-second'),
|
||||
style: text.bodySmall?.copyWith(color: foreground),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('chat-usage-warning-dismiss'),
|
||||
tooltip: 'Dismiss',
|
||||
color: foreground,
|
||||
onPressed: () => widget.warnings.dismiss(warning),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../application/clipboard_failures.dart';
|
||||
import '../domain/chat_account_usage.dart';
|
||||
import '../domain/chat_usage_warning.dart';
|
||||
|
||||
const chatQuotaMarksPreferenceKey = 'pipelines.chatQuotaMarks.v1';
|
||||
|
||||
/// The app session's quota warning state, shared by every open chat since a
|
||||
/// harness account's quota is account-wide: which windows the operator
|
||||
/// dismissed (and at which level and reset), and which levels were already
|
||||
/// announced with a SnackBar. Both are kept in shared preferences, so a reload
|
||||
/// neither brings a dismissed warning back nor repeats an announcement.
|
||||
class ChatUsageWarnings extends ChangeNotifier {
|
||||
ChatUsageWarnings({
|
||||
this.preferences,
|
||||
bool Function(String message)? announce,
|
||||
this.clock = DateTime.now,
|
||||
}) : _announce = announce ?? showAppMessage;
|
||||
|
||||
/// The instance chats use unless a test hands them their own.
|
||||
static final ChatUsageWarnings shared = ChatUsageWarnings(
|
||||
preferences: SharedPreferences.getInstance,
|
||||
);
|
||||
|
||||
/// Where the marks are kept across reloads; null keeps them in memory.
|
||||
final Future<SharedPreferences> Function()? preferences;
|
||||
final bool Function(String message) _announce;
|
||||
|
||||
/// The time stored marks are pruned against.
|
||||
final DateTime Function() clock;
|
||||
final Map<String, ChatQuotaMark> _dismissed = {};
|
||||
final Map<String, ChatQuotaMark> _announced = {};
|
||||
Future<void>? _loaded;
|
||||
|
||||
/// Dismissals by [chatQuotaKey].
|
||||
Map<String, ChatQuotaMark> get dismissed => Map.unmodifiable(_dismissed);
|
||||
|
||||
/// Reads the stored marks once; marks recorded meanwhile win.
|
||||
Future<void> load() => _loaded ??= _read();
|
||||
|
||||
Future<void> _read() async {
|
||||
final preferences = this.preferences;
|
||||
if (preferences == null) return;
|
||||
final String? raw;
|
||||
try {
|
||||
raw = (await preferences()).getString(chatQuotaMarksPreferenceKey);
|
||||
} on Object catch (error) {
|
||||
// Without storage the marks still hold for this app session.
|
||||
debugPrint('Quota warnings: could not read preferences: $error');
|
||||
return;
|
||||
}
|
||||
if (raw == null) return;
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! Map) return;
|
||||
var changed = false;
|
||||
for (final (name, into) in [
|
||||
('dismissed', _dismissed),
|
||||
('announced', _announced),
|
||||
]) {
|
||||
final marks = decoded[name];
|
||||
if (marks is! Map) continue;
|
||||
for (final MapEntry(:key, :value) in marks.entries) {
|
||||
if (value is! List || value.length != 2) continue;
|
||||
final [level, resetsAt] = value;
|
||||
if (level is! int || resetsAt is! int) continue;
|
||||
into.putIfAbsent('$key', () {
|
||||
changed = true;
|
||||
return ChatQuotaMark(level: level, resetsAt: resetsAt);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (changed) notifyListeners();
|
||||
} on FormatException {
|
||||
// A corrupt entry is replaced by the next save.
|
||||
}
|
||||
}
|
||||
|
||||
/// Announces each window of [usage] that reached a warning level not yet
|
||||
/// announced or dismissed since its last reset, once per app (and across
|
||||
/// reloads).
|
||||
Future<void> report(ChatAccountUsage usage, {DateTime? now}) async {
|
||||
await load();
|
||||
final crossed = chatQuotaNewlyCrossed(
|
||||
usage,
|
||||
now ?? clock(),
|
||||
_announced,
|
||||
_dismissed,
|
||||
);
|
||||
if (crossed.isEmpty) return;
|
||||
for (final window in crossed) {
|
||||
_announced[chatQuotaKey(usage.harness, window)] = chatQuotaMarkOf(window);
|
||||
}
|
||||
_announce(chatQuotaAnnouncement(usage.harness, crossed));
|
||||
await _save();
|
||||
}
|
||||
|
||||
/// Hides [warning] until one of its windows reaches the next level or
|
||||
/// resets.
|
||||
void dismiss(ChatUsageWarning warning) {
|
||||
for (final window in warning.windows) {
|
||||
_dismissed[chatQuotaKey(warning.harness, window)] = chatQuotaMarkOf(
|
||||
window,
|
||||
);
|
||||
}
|
||||
notifyListeners();
|
||||
unawaited(_save());
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final preferences = this.preferences;
|
||||
if (preferences == null) return;
|
||||
final now = clock().millisecondsSinceEpoch;
|
||||
// A mark for a window that has reset since can never cover it again.
|
||||
Map<String, List<int>> live(Map<String, ChatQuotaMark> marks) => {
|
||||
for (final MapEntry(:key, :value) in marks.entries)
|
||||
if (value.resetsAt <= 0 || value.resetsAt > now)
|
||||
key: [value.level, value.resetsAt],
|
||||
};
|
||||
final value = jsonEncode({
|
||||
'dismissed': live(_dismissed),
|
||||
'announced': live(_announced),
|
||||
});
|
||||
try {
|
||||
await (await preferences()).setString(chatQuotaMarksPreferenceKey, value);
|
||||
} on Object catch (error) {
|
||||
debugPrint('Quota warnings: could not save preferences: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user