633b5953bb
When Claude Code refuses an operator chat's turn for a usage limit and the server does not continue it on another account, the server now queues a durable prompt (auto-continue-<refusal id>, sent as Pipelines (automatic)) for a minute after the reset: the refused operator message when the turn did no work, else "continue". The reset comes from the refusal's text, else the rejected rate_limit_event. Refusals of turns Claude Code started itself are handled too, with no client attached; a restarted server or a device scheduling the same refusal adds nothing. The choice is kept per Claude home beside auto-switch (or by the server for chats without one), read and set with chat_auto_continue, on by default. The app's limit banner now finds the refusal as the latest turn, ignoring notices, agent reports and activity rows after it, reads and writes the server's choice, and only schedules its own prompt for older servers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
373 lines
13 KiB
Dart
373 lines
13 KiB
Dart
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.
|
|
///
|
|
/// The chat counts as refused while its latest turn is the limit's refusal,
|
|
/// whatever notices or agent reports arrived after it. With auto-continue on,
|
|
/// the server queues 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), with no app involved; the choice is the server's
|
|
/// ([ChatServerAutoContinue], per Claude home, on by default), and the
|
|
/// banner shows the prompt it scheduled. An older server that keeps no such
|
|
/// choice falls back to the per-device [ChatAutoContinue] preference, and the
|
|
/// banner hands that server the prompt itself, under the same operation id
|
|
/// so a server copy is never doubled. 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, or once the account is switched (by the operator
|
|
/// or by the server's automatic switch, whose queued continue prompt also
|
|
/// stops auto-continue from being scheduled).
|
|
class ChatUsageLimitBanner extends StatefulWidget {
|
|
ChatUsageLimitBanner({
|
|
super.key,
|
|
required this.thread,
|
|
required this.composer,
|
|
this.accounts,
|
|
ChatAutoContinue? autoContinue,
|
|
this.serverAutoContinue,
|
|
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;
|
|
|
|
/// The server's choice for this chat; null builds one on [thread]'s
|
|
/// gateway.
|
|
final ChatServerAutoContinue? serverAutoContinue;
|
|
final DateTime Function() now;
|
|
|
|
@override
|
|
State<ChatUsageLimitBanner> createState() => _ChatUsageLimitBannerState();
|
|
}
|
|
|
|
class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|
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<String> _requested = {};
|
|
|
|
late ChatServerAutoContinue _server;
|
|
bool _ownsServer = false;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
unawaited(widget.autoContinue.load());
|
|
_server = _serverFor(widget);
|
|
}
|
|
|
|
ChatServerAutoContinue _serverFor(ChatUsageLimitBanner widget) {
|
|
_ownsServer = widget.serverAutoContinue == null;
|
|
return widget.serverAutoContinue ??
|
|
ChatServerAutoContinue(
|
|
gateway: widget.thread.gateway,
|
|
sessionId: widget.thread.sessionId,
|
|
);
|
|
}
|
|
|
|
@override
|
|
void didUpdateWidget(ChatUsageLimitBanner old) {
|
|
super.didUpdateWidget(old);
|
|
if (widget.serverAutoContinue != old.serverAutoContinue ||
|
|
widget.thread.sessionId != old.thread.sessionId) {
|
|
if (_ownsServer) _server.dispose();
|
|
_server = _serverFor(widget);
|
|
_requested.clear();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_reset?.cancel();
|
|
if (_ownsServer) _server.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
/// Whether auto-continue is on: the server's choice, or this device's for
|
|
/// an older server.
|
|
bool get _enabled =>
|
|
_server.supported ? _server.enabled : widget.autoContinue.enabled;
|
|
|
|
/// 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<JsonMap> _pending(DateTime now) {
|
|
final seen = <String>{};
|
|
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<void> _cancel(List<JsonMap> pending) async {
|
|
for (final prompt in pending) {
|
|
final id = '${prompt['operation_id'] ?? prompt['id'] ?? ''}';
|
|
await widget.composer.unqueue(() => widget.thread.unqueue(id));
|
|
}
|
|
}
|
|
|
|
Future<void> _toggle(
|
|
bool on,
|
|
List<JsonMap> pending,
|
|
ChatRefusedTurn? refused,
|
|
ChatUsageLimit limit,
|
|
) async {
|
|
// Rechecking may schedule the same refusal again.
|
|
_requested.clear();
|
|
if (!_server.supported) {
|
|
await widget.autoContinue.set(on);
|
|
if (!on) await _cancel(pending);
|
|
return;
|
|
}
|
|
await _server.set(on);
|
|
if (!on) {
|
|
await _cancel(pending);
|
|
} else if (refused != null && pending.isEmpty && mounted) {
|
|
// The server considered this refusal while it was off; ask for its
|
|
// prompt now, under the id the server would have used.
|
|
_arm(refused, limit);
|
|
}
|
|
}
|
|
|
|
Future<void> _tryAgain(ChatRefusedTurn refused, List<JsonMap> 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,
|
|
_server,
|
|
]),
|
|
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;
|
|
unawaited(_server.load());
|
|
// The server already switched accounts and is continuing the chat.
|
|
final switching = chatAutoSwitchPending(thread.queuedPrompts);
|
|
// A server that keeps the choice schedules the prompt itself; only
|
|
// for an older one does this device ask for it.
|
|
if (_server.unsupported &&
|
|
auto.loaded &&
|
|
auto.enabled &&
|
|
refused != null &&
|
|
pending.isEmpty &&
|
|
!switching) {
|
|
_arm(refused, limit);
|
|
}
|
|
return _banner(context, limit, refused, pending, now);
|
|
},
|
|
);
|
|
}
|
|
|
|
Widget _banner(
|
|
BuildContext context,
|
|
ChatUsageLimit limit,
|
|
ChatRefusedTurn? refused,
|
|
List<JsonMap> pending,
|
|
DateTime now,
|
|
) {
|
|
final composer = widget.composer;
|
|
final theme = Theme.of(context);
|
|
final scheme = theme.colorScheme;
|
|
final text = theme.textTheme;
|
|
final enabled = _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, refused, limit),
|
|
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<JsonMap> pending,
|
|
ChatRefusedTurn? refused,
|
|
ChatUsageLimit limit,
|
|
) {
|
|
void toggle(bool? on) =>
|
|
unawaited(_toggle(on ?? false, pending, refused, limit));
|
|
// 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),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|