Schedule a message for when the usage limit resets
When the open chat's account has an exhausted quota window, a banner above the composer reads "Usage limit reached · resets at HH:MM" and offers to send the last message (or the current draft) a minute after the reset, via chat_prompt send_at. Queued prompts with a future send_at read "Scheduled · sends at HH:MM" and keep Remove. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<void> 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<ChatComposerBar> {
|
||||
/// 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<void> _send() async {
|
||||
Future<void> _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<ChatComposerBar> {
|
||||
_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<ChatComposerBar> {
|
||||
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),
|
||||
|
||||
@@ -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<bool> send({List<JsonMap> 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<bool> send({
|
||||
List<JsonMap> 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<bool> 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.
|
||||
|
||||
@@ -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<String, dynamic>.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<String, dynamic>.from(attachment),
|
||||
],
|
||||
attachmentsOmitted: value['attachments_omitted'] == true,
|
||||
sendAt: value['send_at'] is num ? (value['send_at'] as num).toInt() : 0,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String> _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<String> _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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
? _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<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
ChatDeliveryIndicator(
|
||||
state: ChatDelivery.queued,
|
||||
onRemove: _removeAction('${prompt['operation_id'] ?? ''}'),
|
||||
sendAt: chatScheduledSendAt(prompt['send_at'], DateTime.now()),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -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<void> 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<ChatUsageLimitBanner> createState() => _ChatUsageLimitBannerState();
|
||||
}
|
||||
|
||||
class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,7 @@ class ChatRepository {
|
||||
required String operationId,
|
||||
List<String> files = const [],
|
||||
List<JsonMap> 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});
|
||||
}
|
||||
|
||||
|
||||
@@ -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|<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;
|
||||
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<JsonMap> 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<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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user