Files
pipelines/app/lib/features/chat/conversation/chat_usage_limit_banner.dart
T
alan 0dc805ae0e Chat: show the active Claude account in the send tooltip, menu and limit banner
usage.account now carries the email and organization of the account
Claude Code is signed in to (from its initialize account, or the saved
account just switched to), sent at process start and after a switch.
The app shows it as the send tooltip's usage prefix, the Claude account
menu subtitle, the usage-limit banner's status line and the info sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:33:46 +00:00

298 lines
10 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.
///
/// 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<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 = {};
@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<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) async {
// Rechecking may schedule the same refusal again.
_requested.clear();
await widget.autoContinue.set(on);
if (!on) await _cancel(pending);
}
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,
]),
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<JsonMap> 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<JsonMap> 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),
],
),
),
);
}
}