diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 85143b61..f3b11c00 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -134,8 +134,15 @@ class ChatComposerBar extends StatefulWidget { this.enterSends, this.images, this.chatColor, + this.limitBanner, }); + /// 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 Function(int sendAt) sendDraft)? + limitBanner; + /// The chat's colour name (see `chatSessionColor`), the accent of the /// field's focus ring; null takes the host's primary colour. final String? chatColor; @@ -706,7 +713,7 @@ class _ChatComposerBarState extends State { /// draft's text and operation id. The chips stay while the prompt is in /// flight so a refusal leaves the draft and its files together; only an /// accepted prompt clears them. - Future _send() async { + Future _send({int sendAt = 0}) async { final composer = widget.composer; if (_uploading || composer.sending || composer.draft.trim().isEmpty) { return; @@ -755,7 +762,7 @@ class _ChatComposerBarState extends State { _focus.requestFocus(); // Acceptance (here or through the bubble's Retry) clears the chips via // the composer's accepted-send count. - await composer.send(attachments: parts); + await composer.send(attachments: parts, sendAt: sendAt); } /// Adds the operator's explicit selection through the host seam. A dismissed @@ -913,6 +920,8 @@ class _ChatComposerBarState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + if (widget.limitBanner case final banner?) + banner((sendAt) => _send(sendAt: sendAt)), if (commands.isNotEmpty) Padding( padding: const EdgeInsetsDirectional.only(bottom: 8), diff --git a/app/lib/features/chat/conversation/chat_composer_controller.dart b/app/lib/features/chat/conversation/chat_composer_controller.dart index d08173ad..441a1737 100644 --- a/app/lib/features/chat/conversation/chat_composer_controller.dart +++ b/app/lib/features/chat/conversation/chat_composer_controller.dart @@ -154,8 +154,12 @@ class ChatComposerController extends ChangeNotifier { /// device until the server accepts it. A refusal restores the exact draft /// (unless newer text is present) and shows the message as "Not sent"; an /// unchanged re-send (same text and parts) reuses its operation id, and a - /// changed one replaces it. Returns whether the server accepted this prompt. - Future send({List attachments = const []}) async { + /// changed one replaces it. A [sendAt] (epoch ms) asks the server to hold + /// the prompt until then. Returns whether the server accepted this prompt. + Future send({ + List attachments = const [], + int sendAt = 0, + }) async { if (_disposed || _sending) return false; final exact = _draft; final text = exact.trim(); @@ -164,6 +168,7 @@ class ChatComposerController extends ChangeNotifier { late final ChatComposerSend intent; if (previous != null && previous.text == text && + previous.sendAt == sendAt && _sameAttachments(previous.attachments, attachments)) { intent = previous; } else { @@ -176,6 +181,7 @@ class ChatComposerController extends ChangeNotifier { operationId: operationId, nativeMessageId: nativeChatMessageId(operationId), attachments: attachments, + sendAt: sendAt, ); } _pending = intent; @@ -185,6 +191,23 @@ 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 schedule(String text, int sendAt) async { + final trimmed = text.trim(); + if (_disposed || _sending || trimmed.isEmpty) return false; + final operationId = _nextOperationId(); + final intent = ChatComposerSend( + sessionId: sessionId, + text: trimmed, + operationId: operationId, + nativeMessageId: nativeChatMessageId(operationId), + sendAt: sendAt, + ); + return _deliver(intent, clearDraft: false); + } + /// Sends an unsent intent again with its own operation id, so the server and /// the transcript see the same message rather than a second one. When its /// text is back in the composer, the composer is cleared as for a send. @@ -285,6 +308,7 @@ class ChatComposerController extends ChangeNotifier { intent.text, operationId: intent.operationId, attachments: intent.attachments, + sendAt: intent.sendAt, ); if (_disposed) return false; final queued = reply['chat_queued'] == true; @@ -297,7 +321,9 @@ class ChatComposerController extends ChangeNotifier { _composerSendsAccepted++; } deliveries.accepted(intent, queued: queued, steered: steered); - _queued = deliveries.isQueued(intent.operationId) || deliveries.ownQueued; + _queued = + (intent.sendAt == 0 && deliveries.isQueued(intent.operationId)) || + deliveries.ownQueued; onAccepted?.call(intent, queued); _settle(null); // The accepted intent's stored copy is gone before the send completes. diff --git a/app/lib/features/chat/conversation/chat_composer_send.dart b/app/lib/features/chat/conversation/chat_composer_send.dart index 4d6a63bf..000f3c5d 100644 --- a/app/lib/features/chat/conversation/chat_composer_send.dart +++ b/app/lib/features/chat/conversation/chat_composer_send.dart @@ -11,6 +11,7 @@ class ChatComposerSend { required this.nativeMessageId, this.attachments = const [], this.attachmentsOmitted = false, + this.sendAt = 0, }); final String sessionId; @@ -29,6 +30,10 @@ class ChatComposerSend { /// intent cannot be re-sent as it was. final bool attachmentsOmitted; + /// Epoch milliseconds the server holds this prompt until (`send_at`), or 0 + /// for one sent as soon as the harness is free. + final int sendAt; + /// Whether this exact intent can be sent again. bool get canRetry => !attachmentsOmitted; @@ -43,6 +48,7 @@ class ChatComposerSend { 'role': 'user', 'operation_id': operationId, 'native_message_id': nativeMessageId, + if (sendAt > 0) 'send_at': sendAt, 'parts': [ {'type': 'text', 'text': text}, for (final attachment in attachments) @@ -86,6 +92,7 @@ class ChatComposerSend { : Map.from(attachment), ], if (omit && attachments.isNotEmpty) 'attachments_omitted': true, + if (sendAt > 0) 'send_at': sendAt, }; } @@ -105,6 +112,7 @@ class ChatComposerSend { if (attachment is Map) Map.from(attachment), ], attachmentsOmitted: value['attachments_omitted'] == true, + sendAt: value['send_at'] is num ? (value['send_at'] as num).toInt() : 0, ); } diff --git a/app/lib/features/chat/conversation/chat_deliveries.dart b/app/lib/features/chat/conversation/chat_deliveries.dart index a094a8e3..b04eb826 100644 --- a/app/lib/features/chat/conversation/chat_deliveries.dart +++ b/app/lib/features/chat/conversation/chat_deliveries.dart @@ -73,6 +73,7 @@ class ChatDeliveries extends ChangeNotifier { void sending(ChatComposerSend send) { _own.add(send.operationId); + if (send.sendAt > 0) _scheduled.add(send.operationId); _unsent.removeWhere((item) => item.operationId == send.operationId); _set(send, ChatDelivery.sending); } @@ -118,12 +119,20 @@ class ChatDeliveries extends ChangeNotifier { /// only its own prompts, not another device's. final Set _own = {}; + /// Own operation ids the server holds until a set time (`send_at`); they + /// do not wait for the current turn, so they never raise its notice. + final Set _scheduled = {}; + /// Set once the server reported its queue: from then on only its reports /// move a prompt out of "Queued". bool _serverQueueKnown = false; - /// Whether one of this composer's own prompts waits in the server's queue. - bool get ownQueued => _own.any(_serverQueued.contains); + /// Whether one of this composer's own prompts waits in the server's queue + /// for the current turn (a scheduled one waits for its time instead). + bool get ownQueued => _own.any( + (operation) => + _serverQueued.contains(operation) && !_scheduled.contains(operation), + ); /// Whether the server reports its queue (so no local heuristic applies). bool get serverQueueKnown => _serverQueueKnown; diff --git a/app/lib/features/chat/conversation/chat_delivery_indicator.dart b/app/lib/features/chat/conversation/chat_delivery_indicator.dart index 7caef61e..3eb245c2 100644 --- a/app/lib/features/chat/conversation/chat_delivery_indicator.dart +++ b/app/lib/features/chat/conversation/chat_delivery_indicator.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'chat_deliveries.dart'; +import 'chat_schedule_time.dart'; /// The words each delivery state reads as, beside its icon. String chatDeliveryLabel(ChatDelivery state) => switch (state) { @@ -15,7 +16,8 @@ String chatDeliveryLabel(ChatDelivery state) => switch (state) { /// server has the message. "Not sent" takes the error colour and offers the /// native Retry (same operation id) and Edit (back into the composer) — or /// Discard when the stored intent can no longer be sent as it was. "Queued" -/// offers Remove, which takes the message off the server's queue. +/// offers Remove, which takes the message off the server's queue; one the +/// server holds until a later [sendAt] reads "Scheduled · sends at 15:01". class ChatDeliveryIndicator extends StatelessWidget { const ChatDeliveryIndicator({ super.key, @@ -24,6 +26,7 @@ class ChatDeliveryIndicator extends StatelessWidget { this.onEdit, this.editLabel = 'Edit', this.onRemove, + this.sendAt, }); final ChatDelivery state; @@ -34,6 +37,10 @@ class ChatDeliveryIndicator extends StatelessWidget { /// Takes a "Queued" message back off the server's queue before it is sent. final VoidCallback? onRemove; + /// When a queued message is scheduled to send; null for one that waits + /// only for the turn in flight. + final DateTime? sendAt; + @override Widget build(BuildContext context) { final failed = state == ChatDelivery.failed; @@ -43,17 +50,26 @@ class ChatDeliveryIndicator extends StatelessWidget { final style = DefaultTextStyle.of( context, ).style.merge(TextStyle(fontSize: 12, color: color)); - final label = chatDeliveryLabel(state); + final scheduled = state == ChatDelivery.queued && sendAt != null; + final label = scheduled + ? 'Scheduled · sends at ${chatScheduleTime(context, sendAt!)}' + : chatDeliveryLabel(state); return Semantics( container: true, label: 'Delivery: $label', child: Wrap( - key: Key('chat-delivery-${state.name}'), + key: Key( + scheduled ? 'chat-delivery-scheduled' : 'chat-delivery-${state.name}', + ), spacing: 4, crossAxisAlignment: WrapCrossAlignment.center, children: [ ExcludeSemantics( - child: Icon(_icon, size: style.fontSize! + 2, color: color), + child: Icon( + scheduled ? Icons.schedule_send : _icon, + size: style.fontSize! + 2, + color: color, + ), ), ExcludeSemantics(child: Text(label, style: style)), if (failed && onRetry != null) diff --git a/app/lib/features/chat/conversation/chat_schedule_time.dart b/app/lib/features/chat/conversation/chat_schedule_time.dart new file mode 100644 index 00000000..a966d13d --- /dev/null +++ b/app/lib/features/chat/conversation/chat_schedule_time.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +/// A scheduled time in the operator's local time, 24-hour as the chat's +/// message timestamps are: "15:01" today, "Fri 28 Nov 15:01" on another day. +String chatScheduleTime( + BuildContext context, + DateTime at, { + DateTime Function() now = DateTime.now, +}) { + final local = at.toLocal(); + final material = MaterialLocalizations.of(context); + final time = material.formatTimeOfDay( + TimeOfDay.fromDateTime(local), + alwaysUse24HourFormat: true, + ); + final today = now().toLocal(); + if (local.year == today.year && + local.month == today.month && + local.day == today.day) { + return time; + } + return '${material.formatMediumDate(local)} $time'; +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index b22cfbdc..191e2669 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -44,6 +44,8 @@ import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; import 'chat_escape_stop.dart'; import 'chat_delivery_indicator.dart'; +import 'chat_usage_limit_banner.dart'; +import '../domain/chat_usage_limit.dart'; import 'chat_draft_store.dart'; import 'chat_effort_control.dart'; import 'chat_efforts.dart'; @@ -1238,6 +1240,11 @@ class _ChatThreadViewState extends State { pasteTarget: widget.pasteTarget, ownsPasteWhenFocused: widget.ownsPasteWhenFocused, runShell: _shellRuns.start, + limitBanner: (sendDraft) => ChatUsageLimitBanner( + thread: _controller, + composer: _composer, + sendDraft: sendDraft, + ), backgroundTasks: ChatBackgroundTasks( key: ValueKey('chat-background-tasks-${widget.sessionId}'), gateway: widget.gateway, @@ -1755,6 +1762,9 @@ class _ChatThreadViewState extends State { ? _composer.deliveries.stateFor(message) : null; final onRemove = _removeAction('${message?['operation_id'] ?? ''}'); + final sendAt = delivery == ChatDelivery.queued + ? _scheduledAt(message!) + : null; // An unchanged finished row hands back its previous widget, so a streamed // delta rebuilds only the live turn. Transcript snapshots are copied on // write, never mutated, so a deep-equal row is the same content. Permission @@ -1763,7 +1773,15 @@ class _ChatThreadViewState extends State { return _rowWidgets.widgetFor( key, row, - [delivery, onRemove != null, _images, _controller, _composer, _shellRuns], + [ + delivery, + onRemove != null, + sendAt, + _images, + _controller, + _composer, + _shellRuns, + ], () => ChatMessageView( row: row, speechScope: widget.sessionId, @@ -1779,7 +1797,11 @@ class _ChatThreadViewState extends State { footer: [ ...chips, if (delivery != null) - ChatDeliveryIndicator(state: delivery, onRemove: onRemove), + ChatDeliveryIndicator( + state: delivery, + onRemove: onRemove, + sendAt: sendAt, + ), ], images: _images, ), @@ -1806,6 +1828,19 @@ class _ChatThreadViewState extends State { unawaited(_composer.unqueue(() => controller.unqueue(operationId))); } + /// When the server will send a queued [message]: its queue entry's + /// `send_at`, else the one this device asked for; null once it has passed. + DateTime? _scheduledAt(JsonMap message) { + final operationId = '${message['operation_id'] ?? ''}'; + final now = DateTime.now(); + for (final prompt in _controller.queuedPrompts) { + if (operationId.isNotEmpty && prompt['operation_id'] == operationId) { + return chatScheduledSendAt(prompt['send_at'], now); + } + } + return chatScheduledSendAt(message['send_at'], now); + } + /// One prompt the server holds queued that the transcript does not show, /// as the sender's bubble with "Queued" and its Remove. Widget _queuedRow(JsonMap prompt) { @@ -1818,6 +1853,7 @@ class _ChatThreadViewState extends State { ChatDeliveryIndicator( state: ChatDelivery.queued, onRemove: _removeAction('${prompt['operation_id'] ?? ''}'), + sendAt: chatScheduledSendAt(prompt['send_at'], DateTime.now()), ), ], ); diff --git a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart new file mode 100644 index 00000000..9d11a061 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart @@ -0,0 +1,177 @@ +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), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 4f0f5741..f992874d 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -249,6 +249,7 @@ class ChatRepository { required String operationId, List files = const [], List attachments = const [], + int sendAt = 0, }) { if (sessionId.trim().isEmpty) { throw ArgumentError('Select a chat session first.'); @@ -264,6 +265,9 @@ class ChatRepository { }; if (files.isNotEmpty) body['files'] = files; if (attachments.isNotEmpty) body['attachments'] = attachments; + // The server queues a prompt with `send_at` (epoch ms) and delivers it + // once that time has passed. + if (sendAt > 0) body['send_at'] = sendAt; return gateway.call('chat_prompt', {'chat_prompt': body}); } diff --git a/app/lib/features/chat/domain/chat_usage_limit.dart b/app/lib/features/chat/domain/chat_usage_limit.dart new file mode 100644 index 00000000..caadd2ab --- /dev/null +++ b/app/lib/features/chat/domain/chat_usage_limit.dart @@ -0,0 +1,112 @@ +/// 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. +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. +const Duration chatScheduleMargin = Duration(minutes: 1); + +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. + DateTime get sendAt => resetsAt.add(chatScheduleMargin); +} + +/// The limit [usage] reports at [now]: any window at or past 100% whose reset +/// is still ahead. The reset is the latest among those windows, since every +/// one of them must have reset before a prompt can run. Null when nothing is +/// exhausted, a reset time is unknown, or every reset has already passed. +ChatUsageLimit? chatUsageLimit(ChatAccountUsage? usage, DateTime now) { + if (usage == null || usage.unsupported) return null; + var latest = 0; + for (final window in usage.windows) { + if (window.usedPercent < 100) continue; + if (window.resetsAt <= now.millisecondsSinceEpoch) continue; + if (window.resetsAt > latest) latest = window.resetsAt; + } + if (latest == 0) return null; + return ChatUsageLimit(resetsAt: DateTime.fromMillisecondsSinceEpoch(latest)); +} + +/// Claude Code ends a refused turn with `Claude AI usage limit reached|`; 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; + final seconds = int.tryParse(match.group(1)!); + if (seconds == null || seconds <= 0) return null; + final reset = DateTime.fromMillisecondsSinceEpoch(seconds * 1000); + if (!reset.isAfter(now)) return null; + return ChatUsageLimit(resetsAt: reset); +} + +final RegExp _limitText = RegExp(r'usage limit reached\|(\d{9,11})\b'); + +/// 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). +ChatUsageLimit? chatThreadUsageLimit( + ChatAccountUsage? usage, + List messages, + DateTime now, +) { + final quota = chatUsageLimit(usage, now); + if (quota != null) return quota; + final last = messages.lastWhere( + (message) => message['send_at'] == null, + orElse: () => const {}, + ); + if (last.isEmpty || last['role'] == 'user') 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; +} + +/// The newest user message in [messages] with text, or null. +ChatLastPrompt? chatLastPrompt(List 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; +} + +String _text(JsonMap message) { + final parts = message['parts']; + if (parts is! List) return '${message['text'] ?? ''}'; + return [ + for (final part in parts) + if (part is Map && part['type'] == 'text') '${part['text'] ?? ''}', + ].join('\n'); +} + +/// A queued prompt's `send_at` as a time, or null when it has none or it has +/// already passed. +DateTime? chatScheduledSendAt(Object? sendAt, DateTime now) { + if (sendAt is! num || !sendAt.isFinite || sendAt <= 0) return null; + final at = DateTime.fromMillisecondsSinceEpoch(sendAt.toInt()); + return at.isAfter(now) ? at : null; +} diff --git a/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart b/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart new file mode 100644 index 00000000..0160ea38 --- /dev/null +++ b/app/test/features/chat/conversation/chat_usage_limit_banner_test.dart @@ -0,0 +1,267 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_schedule_time.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +/// A thread gateway that records prompt bodies and answers them as queued, +/// as the server does for one carrying `send_at`. +class _Gateway extends FakeChatGateway { + final promptBodies = []; + List messages = []; + + _Gateway() { + history = (_) async => chatPage(messages); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_prompt') { + final body = fields['chat_prompt'] as JsonMap; + promptBodies.add(body); + return {'chat_queued': body['send_at'] != null}; + } + return super.call(type, fields); + } +} + +JsonMap _text(String text) => {'type': 'text', 'text': text}; + +JsonMap _limitFrame(DateTime reset, {double percent = 100}) => { + 'session_id': 's', + 'kind': 'usage', + 'usage': { + 'account': { + 'harness': 'Claude Code', + 'plan': 'max', + 'windows': [ + { + 'id': 'five_hour', + 'label': '5-hour', + 'used_percent': percent, + 'resets_at': reset.millisecondsSinceEpoch, + }, + { + 'id': 'seven_day', + 'label': 'Weekly', + 'used_percent': 40, + 'resets_at': reset + .add(const Duration(days: 2)) + .millisecondsSinceEpoch, + }, + ], + }, + }, +}; + +Future _pump(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); +} + +Future<_Gateway> _host( + WidgetTester tester, { + List? messages, + Future Function()? subscribe, +}) async { + final gateway = _Gateway() + ..messages = + messages ?? + [ + chatMessage('u1', 'user', parts: [_text('first')]), + chatMessage( + 'u2', + 'user', + parts: [ + _text('Fix the flaky build'), + {'type': 'file', 'name': 'log.txt', 'uri': 'file://log.txt'}, + ], + ), + chatMessage('a1', 'assistant', parts: [_text('On it.')]), + ] + ..subscribe = subscribe; + addTearDown(gateway.close); + var sequence = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: MemoryChatDraftStore(), + newOperationId: () => 'op-${++sequence}', + ), + ), + ), + ); + await _pump(tester); + return gateway; +} + +String _time(WidgetTester tester, DateTime at) => + chatScheduleTime(tester.element(find.byType(Scaffold)), at); + +final _banner = find.byKey(const Key('chat-usage-limit')); +final _button = find.byKey(const Key('chat-usage-limit-schedule')); + +void main() { + testWidgets('no banner until a window is exhausted', (tester) async { + final gateway = await _host(tester); + expect(_banner, findsNothing); + final reset = DateTime.now().add(const Duration(hours: 2)); + gateway.emitEvent(_limitFrame(reset, percent: 97)); + await _pump(tester); + expect(_banner, findsNothing); + }); + + testWidgets('the button schedules the last message a minute after reset', ( + tester, + ) async { + final gateway = await _host(tester); + final reset = DateTime.fromMillisecondsSinceEpoch( + DateTime.now().add(const Duration(hours: 2)).millisecondsSinceEpoch, + ); + gateway.emitEvent(_limitFrame(reset)); + await _pump(tester); + + final sendAt = reset.add(const Duration(minutes: 1)); + expect( + find.text('Usage limit reached · resets at ${_time(tester, reset)}'), + findsOneWidget, + ); + expect( + find.text('Send last message at ${_time(tester, sendAt)}'), + findsOneWidget, + ); + // The earlier message's file is not repeated, and the banner says so. + expect(find.text('Its attachments are not sent again.'), findsOneWidget); + + await tester.tap(_button); + await _pump(tester); + + final body = gateway.promptBodies.single; + expect(body['text'], 'Fix the flaky build'); + expect(body['send_at'], sendAt.millisecondsSinceEpoch); + expect(body.containsKey('attachments'), isFalse); + // The new bubble reads as scheduled rather than plain "Queued". + expect(find.byKey(const Key('chat-delivery-scheduled')), findsOneWidget); + expect( + find.text('Scheduled · sends at ${_time(tester, sendAt)}'), + findsOneWidget, + ); + // It waits for its time, not the current turn, and is not offered twice. + expect(find.byKey(const Key('chat-composer-queued')), findsNothing); + expect(find.textContaining('1 message scheduled'), findsOneWidget); + expect(_button, findsNothing); + }); + + testWidgets('with a draft the button schedules the draft and clears it', ( + tester, + ) async { + final gateway = await _host(tester); + final reset = DateTime.now().add(const Duration(minutes: 40)); + gateway.emitEvent(_limitFrame(reset)); + await _pump(tester); + final sendAt = DateTime.fromMillisecondsSinceEpoch( + reset.millisecondsSinceEpoch, + ).add(const Duration(minutes: 1)); + + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + 'Then run the tests', + ); + await _pump(tester); + expect(find.text('Send this at ${_time(tester, sendAt)}'), findsOneWidget); + expect(find.text('Its attachments are not sent again.'), findsNothing); + + await tester.tap(_button); + await _pump(tester); + + final body = gateway.promptBodies.single; + expect(body['text'], 'Then run the tests'); + expect(body['send_at'], sendAt.millisecondsSinceEpoch); + final field = tester.widget( + find.byKey(const Key('chat-composer-field')), + ); + expect(field.controller!.text, isEmpty); + }); + + testWidgets('nothing to send hides the button', (tester) async { + final gateway = await _host( + tester, + messages: [ + chatMessage('a1', 'assistant', parts: [_text('Hello.')]), + ], + ); + gateway.emitEvent( + _limitFrame(DateTime.now().add(const Duration(hours: 1))), + ); + await _pump(tester); + expect(_banner, findsOneWidget); + expect(_button, findsNothing); + }); + + testWidgets('a passed reset is not a limit', (tester) async { + final gateway = await _host(tester); + gateway.emitEvent( + _limitFrame(DateTime.now().subtract(const Duration(minutes: 1))), + ); + await _pump(tester); + expect(_banner, findsNothing); + }); + + testWidgets('a queued prompt with send_at reads Scheduled with Remove', ( + tester, + ) async { + final sendAt = DateTime.fromMillisecondsSinceEpoch( + DateTime.now().add(const Duration(hours: 1)).millisecondsSinceEpoch, + ); + final gateway = await _host( + tester, + subscribe: () async => { + 'chat_queue': { + 'session_id': 's', + 'prompts': [ + { + 'operation_id': 'later', + 'text': 'continue', + 'send_at': sendAt.millisecondsSinceEpoch, + }, + {'operation_id': 'next', 'text': 'and then this'}, + ], + }, + }, + ); + expect( + find.text('Scheduled · sends at ${_time(tester, sendAt)}'), + findsOneWidget, + ); + expect(find.text('Queued'), findsOneWidget); + expect(find.byKey(const Key('chat-delivery-remove')), findsNWidgets(2)); + + // With a message already scheduled the banner offers no second re-send. + gateway.emitEvent(_limitFrame(sendAt.subtract(const Duration(minutes: 1)))); + await _pump(tester); + expect(find.textContaining('1 message scheduled'), findsOneWidget); + expect(_button, findsNothing); + }); + + testWidgets('chatScheduleTime names another day', (tester) async { + await tester.pumpWidget(const MaterialApp(home: Scaffold())); + final context = tester.element(find.byType(Scaffold)); + final now = DateTime(2026, 11, 25, 9); + expect( + chatScheduleTime(context, DateTime(2026, 11, 25, 15, 1), now: () => now), + '15:01', + ); + expect( + chatScheduleTime(context, DateTime(2026, 11, 28, 7, 5), now: () => now), + 'Sat, Nov 28 07:05', + ); + }); +} diff --git a/app/test/features/chat/domain/chat_usage_limit_test.dart b/app/test/features/chat/domain/chat_usage_limit_test.dart new file mode 100644 index 00000000..8dec3c79 --- /dev/null +++ b/app/test/features/chat/domain/chat_usage_limit_test.dart @@ -0,0 +1,160 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart'; +import 'package:pipelines_app/features/chat/domain/chat_usage_limit.dart'; + +ChatAccountUsage _usage(List<(double, DateTime?)> windows) => ChatAccountUsage( + harness: 'Claude Code', + plan: 'max', + asOf: 0, + unsupported: false, + windows: [ + for (final (index, (percent, reset)) in windows.indexed) + ChatQuotaWindow( + id: 'w$index', + label: 'W$index', + usedPercent: percent, + resetsAt: reset?.millisecondsSinceEpoch ?? 0, + ), + ], +); + +void main() { + final now = DateTime(2026, 11, 25, 12); + + group('chatUsageLimit', () { + test('an exhausted window with a future reset is a limit', () { + final reset = now.add(const Duration(hours: 3)); + final limit = chatUsageLimit( + _usage([(42, now.add(const Duration(days: 2))), (100, reset)]), + now, + )!; + expect(limit.resetsAt, reset); + expect(limit.sendAt, reset.add(const Duration(minutes: 1))); + }); + + test('below 100% or unknown quota is not a limit', () { + expect(chatUsageLimit(null, now), isNull); + expect( + chatUsageLimit( + _usage([(99.9, now.add(const Duration(hours: 1)))]), + now, + ), + isNull, + ); + final unsupported = ChatAccountUsage( + harness: 'OpenCode', + plan: '', + asOf: 0, + windows: const [], + unsupported: true, + ); + expect(chatUsageLimit(unsupported, now), isNull); + }); + + test('a reset that has passed, or is unknown, is not a limit', () { + expect( + chatUsageLimit( + _usage([(100, now.subtract(const Duration(minutes: 1)))]), + now, + ), + isNull, + ); + expect(chatUsageLimit(_usage([(100, null)]), now), isNull); + }); + + test('several exhausted windows wait for the latest reset', () { + final early = now.add(const Duration(hours: 1)); + final late = now.add(const Duration(days: 3)); + final limit = chatUsageLimit( + _usage([ + (100, early), + (104, late), + (60, now.add(const Duration(days: 9))), + (100, now.subtract(const Duration(hours: 1))), + ]), + now, + )!; + expect(limit.resetsAt, late); + }); + }); + + test('Claude Code limit text carries the reset in epoch seconds', () { + final reset = now.add(const Duration(hours: 2)); + final seconds = reset.millisecondsSinceEpoch ~/ 1000; + expect( + chatUsageLimitFromText( + 'Claude AI usage limit reached|$seconds', + now, + )!.resetsAt, + DateTime.fromMillisecondsSinceEpoch(seconds * 1000), + ); + expect(chatUsageLimitFromText('Hello there', now), isNull); + final past = now.subtract(const Duration(hours: 1)); + expect( + chatUsageLimitFromText( + 'Claude AI usage limit reached|${past.millisecondsSinceEpoch ~/ 1000}', + now, + ), + isNull, + ); + }); + + test('the thread limit prefers quota, then the last reply text', () { + final seconds = + now.add(const Duration(hours: 2)).millisecondsSinceEpoch ~/ 1000; + final refused = { + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'Claude AI usage limit reached|$seconds'}, + ], + }; + expect(chatThreadUsageLimit(null, [refused], now), isNotNull); + expect( + chatThreadUsageLimit(null, [ + refused, + { + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'continue'}, + ], + }, + ], now), + isNull, + ); + }); + + test('the last prompt is the newest user text and notes its files', () { + final last = chatLastPrompt([ + { + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'first'}, + ], + }, + { + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': ' fix the build '}, + {'type': 'file', 'name': 'log.txt'}, + ], + }, + { + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'ok'}, + ], + }, + ])!; + expect(last.text, 'fix the build'); + expect(last.hadAttachments, isTrue); + expect(chatLastPrompt(const []), isNull); + }); + + test('scheduled send_at is a future epoch-ms time only', () { + final later = now.add(const Duration(minutes: 5)); + expect(chatScheduledSendAt(later.millisecondsSinceEpoch, now), later); + expect(chatScheduledSendAt(now.millisecondsSinceEpoch - 1, now), isNull); + expect(chatScheduledSendAt(null, now), isNull); + expect(chatScheduledSendAt('x', now), isNull); + }); +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index 74f06bdf..22f56a28 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -6,8 +6,9 @@ // `?chats=N` N chat sessions in the chat list, each opening a short // markdown transcript; // `?graph=1` run 7 carries its pinned graph (plan -> build); -// `?quota=claude|opencode` (with `?chats=N`) pushes a usage frame with -// that harness's account quota after a chat subscribes. +// `?quota=claude|opencode|limit` (with `?chats=N`) pushes a usage frame +// with that harness's account quota after a chat subscribes; +// `limit` is Claude Code with its 5-hour window exhausted. // `?colors=1` (with `?chats=N`) names the chats, stars and colours some of // them, and keeps colours picked with chat_color; // `?activity=1` (with `?chats=N`) lists a running chat, one with @@ -143,6 +144,24 @@ List perfChatFollowUps(JsonMap request) { if (answered.isNotEmpty) return answered; final shell = chatShellFollowUps(request); if (shell.isNotEmpty) return shell; + if (_scheduledPrompt(request) case final prompt?) { + return [ + { + 'type': 'chat_queue', + 'chat_queue': { + 'session_id': prompt['session_id'], + 'prompts': [ + { + 'operation_id': prompt['operation_id'], + 'native_message_id': prompt['native_message_id'], + 'text': prompt['text'], + 'send_at': prompt['send_at'], + }, + ], + }, + }, + ]; + } final quota = _params['quota']; if (_chats == 0 || quota == null || request['type'] != 'chat_subscribe') { return const []; @@ -160,7 +179,7 @@ List perfChatFollowUps(JsonMap request) { { 'id': 'five_hour', 'label': '5-hour', - 'used_percent': 42, + 'used_percent': quota == 'limit' ? 100 : 42, 'resets_at': at( const Duration(hours: 2, minutes: 14, seconds: 30), ), @@ -191,6 +210,13 @@ List perfChatFollowUps(JsonMap request) { ]; } +/// A `chat_prompt` body carrying `send_at`, or null. +Map? _scheduledPrompt(JsonMap request) { + if (request['type'] != 'chat_prompt') return null; + final body = request['chat_prompt']; + return body is Map && body['send_at'] is num ? body : null; +} + /// Run 7's pinned graph for `?graph=1`. JsonMap perfRunGraphFixture() => { 'name': 'Release train', @@ -305,7 +331,8 @@ JsonMap? perfChatReply(JsonMap request) { return { 'id': id, 'type': 'chat_prompt', - 'chat_queued': false, + // A scheduled prompt (`send_at`) is always held, as the server does. + 'chat_queued': _scheduledPrompt(request) != null, if (_params['steered'] == '1') 'chat_steered': true, }; case 'chat_shells':