import 'dart:async'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_account_usage.dart'; import '../domain/chat_usage_limit.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'; /// 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"), the account that hit it and /// "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 { ChatUsageLimitBanner({ super.key, required this.thread, required this.composer, this.accounts, ChatAutoContinue? autoContinue, this.now = DateTime.now, }) : autoContinue = autoContinue ?? ChatAutoContinue.shared; final ChatThreadController thread; final ChatComposerController composer; /// 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 State createState() => _ChatUsageLimitBannerState(); } class _ChatUsageLimitBannerState extends State { 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 _requested = {}; @override void initState() { super.initState(); unawaited(widget.autoContinue.load()); } @override void dispose() { _reset?.cancel(); super.dispose(); } /// Rebuilds when the reset passes, so the banner leaves on time. void _watchReset(DateTime? at, DateTime now) { if (at == _resetFor) return; _resetFor = at; _reset?.cancel(); _reset = at == null ? null : Timer(at.difference(now) + const Duration(milliseconds: 50), () { if (mounted) setState(() {}); }); } /// 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 _pending(DateTime now) { final seen = {}; 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 _cancel(List pending) async { for (final prompt in pending) { final id = '${prompt['operation_id'] ?? prompt['id'] ?? ''}'; await widget.composer.unqueue(() => widget.thread.unqueue(id)); } } Future _toggle(bool on, List pending) async { // Rechecking may schedule the same refusal again. _requested.clear(); await widget.autoContinue.set(on); if (!on) await _cancel(pending); } Future _tryAgain(ChatRefusedTurn refused, List 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, widget.autoContinue, ]), builder: (context, _) { final now = widget.now(); final thread = widget.thread; final limit = chatThreadUsageLimit( thread.accountUsage, thread.messages, now, ); _watchReset(limit?.resetsAt, now); if (limit == null) return const SizedBox.shrink(); 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, ChatRefusedTurn? refused, List pending, DateTime now, ) { final composer = widget.composer; 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 email = widget.thread.accountUsage?.email ?? ''; final status = [ // The account that hit the limit. if (email.isNotEmpty) email, 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.surfaceContainerHigh, borderRadius: BorderRadius.circular(16), child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 12, 8), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Icon(Icons.hourglass_bottom, color: scheme.error), const SizedBox(width: 12), Expanded( child: Column( 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.onSurfaceVariant, ), ), if (note != null) Text( note, key: const Key('chat-usage-limit-note'), style: text.bodySmall?.copyWith( color: scheme.onSurfaceVariant, ), ), ], ), ), ], ), 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 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), ], ), ), ); } }