import 'dart:async'; import 'package:flutter/material.dart'; import '../domain/chat_commands.dart'; import '../domain/chat_usage_limit.dart'; import '../shell/chat_shell_command.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 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. class ChatUsageLimitBanner extends StatefulWidget { const ChatUsageLimitBanner({ super.key, required this.thread, required this.composer, required this.sendDraft, this.now = DateTime.now, }); final ChatThreadController thread; final ChatComposerController composer; final ChatScheduleDraft sendDraft; final DateTime Function() now; @override State createState() => _ChatUsageLimitBannerState(); } class _ChatUsageLimitBannerState extends State { Timer? _reset; DateTime? _resetFor; @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(() {}); }); } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: Listenable.merge([widget.thread, widget.composer]), 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(); return _banner(context, limit, now); }, ); } Widget _banner(BuildContext context, ChatUsageLimit limit, 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 status = [ 'Usage limit reached · resets at $resets', if (scheduled == 1) '1 message scheduled', if (scheduled > 1) '$scheduled messages scheduled', ].join(' · '); return Padding( padding: const EdgeInsetsDirectional.only(bottom: 8), child: Material( key: const Key('chat-usage-limit'), color: scheme.errorContainer, 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, children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.hourglass_bottom, color: scheme.onErrorContainer), const SizedBox(width: 12), Flexible( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( status, key: const Key('chat-usage-limit-status'), style: text.bodyMedium?.copyWith( color: scheme.onErrorContainer, fontWeight: FontWeight.w600, ), ), if (note != null) Text( note, key: const Key('chat-usage-limit-note'), style: text.bodySmall?.copyWith( color: scheme.onErrorContainer, ), ), ], ), ), ], ), 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), ), ], ), ), ), ); } }