Files
pipelines/app/lib/features/chat/domain/chat_usage_limit.dart
T
alan c490f71042 Claude account switcher: save and switch a chat's Claude login in place
Saved accounts live under <CLAUDE_CONFIG_DIR>/pipelines-accounts/<slug>/
(0700 dir, 0600 files). Switching changes what /login changes: the
claudeAiOauth entry of .credentials.json and oauthAccount of .claude.json
(atomic temp+rename, mode and other keys kept) and the org caches /login
drops, under Claude Code's own refresh, storage and config locks, so
running CLIs continue on the new account without a restart. The active
login's rotated tokens are written back to its slot first.

Server: claude_accounts / claude_account_save / _use / _remove, chat-scoped
and Claude-only; a switch moves the home's open chats to the new account's
quota (usage.account.switched_at), clearing a reached limit.
CLI: pipelines claude-account list|save|use|remove [--dir].
App: Claude account in the chat menu, and Switch to <account> on the
usage-limit and usage-warning banners, with a confirmation snack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:10:08 +00:00

120 lines
4.4 KiB
Dart

/// 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;
// A refusal received before the operator switched accounts was the old
// account's.
final switchedAt = usage?.switchedAt ?? 0;
if (switchedAt > 0) {
final created = last['created_at'];
if (created is! num || created <= switchedAt) 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;
}