Files
pipelines/app/lib/features/chat/domain/chat_account_usage.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

142 lines
4.5 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// The harness account's subscription quota, as carried by a usage frame's
/// `usage.account` (see docs/cli.md). Only reported values are kept: a window
/// without a usable percentage is dropped and nothing is estimated.
library;
/// One rolling quota window, e.g. "5-hour" or "Weekly".
class ChatQuotaWindow {
const ChatQuotaWindow({
required this.id,
required this.label,
required this.usedPercent,
required this.resetsAt,
});
final String id;
final String label;
/// 0–100; a harness may report more than 100 past a cap.
final double usedPercent;
/// Epoch milliseconds, 0 when the harness did not say.
final int resetsAt;
}
class ChatAccountUsage {
const ChatAccountUsage({
required this.harness,
required this.plan,
required this.asOf,
required this.windows,
required this.unsupported,
this.switchedAt = 0,
});
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
final String harness;
final String plan;
/// Epoch milliseconds when the server received the report, 0 if unknown.
final int asOf;
final List<ChatQuotaWindow> windows;
/// The harness exposes no quota at all.
final bool unsupported;
/// Epoch milliseconds when the operator switched the chat's Claude account
/// to this one, 0 if never. The report then stands for the new account even
/// before any window is known, and an earlier usage-limit refusal in the
/// transcript no longer applies.
final int switchedAt;
}
int _millis(Object? value) =>
value is num && value.isFinite && value > 0 ? value.toInt() : 0;
/// Parses `usage.account`, or null when it reports nothing usable.
ChatAccountUsage? chatAccountUsage(Object? value) {
if (value is! Map) return null;
final harness = '${value['harness'] ?? ''}'.trim();
if (value['unsupported'] == true) {
return ChatAccountUsage(
harness: harness.isEmpty ? 'the harness' : harness,
plan: '',
asOf: 0,
windows: const [],
unsupported: true,
);
}
final windows = <ChatQuotaWindow>[];
final raw = value['windows'];
if (raw is List) {
for (final entry in raw) {
if (entry is! Map) continue;
final percent = entry['used_percent'];
final label = '${entry['label'] ?? ''}'.trim();
if (percent is! num || !percent.isFinite || percent < 0) continue;
if (label.isEmpty) continue;
windows.add(
ChatQuotaWindow(
id: '${entry['id'] ?? label}',
label: label,
usedPercent: percent.toDouble(),
resetsAt: _millis(entry['resets_at']),
),
);
}
}
final switchedAt = _millis(value['switched_at']);
// A switched account replaces the previous report even with no windows
// yet; otherwise an empty report keeps the last one.
if (windows.isEmpty && switchedAt == 0) return null;
return ChatAccountUsage(
harness: harness,
plan: '${value['plan'] ?? ''}'.trim(),
asOf: _millis(value['as_of']),
windows: List.unmodifiable(windows),
unsupported: false,
switchedAt: switchedAt,
);
}
/// "42% used · resets in 2h 14m". The percentage is rounded, never clamped.
String chatQuotaSummary(ChatQuotaWindow window, DateTime now) {
final used = '${window.usedPercent.round()}% used';
if (window.resetsAt <= 0) return used;
final left = DateTime.fromMillisecondsSinceEpoch(
window.resetsAt,
).difference(now);
if (left.isNegative) return '$used · reset since this report';
return '$used · resets in ${_countdown(left)}';
}
String _countdown(Duration left) {
if (left.inMinutes < 1) return 'under a minute';
final days = left.inDays;
final hours = left.inHours % 24;
final minutes = left.inMinutes % 60;
if (days > 0) return hours > 0 ? '${days}d ${hours}h' : '${days}d';
if (left.inHours > 0) {
return minutes > 0 ? '${left.inHours}h ${minutes}m' : '${left.inHours}h';
}
return '${minutes}m';
}
/// "as of 5 min ago"; empty when the report time is unknown.
String chatQuotaAsOf(int asOf, DateTime now) {
if (asOf <= 0) return '';
final age = now.difference(DateTime.fromMillisecondsSinceEpoch(asOf));
if (age.inMinutes < 1) return 'as of just now';
if (age.inHours < 1) return 'as of ${age.inMinutes} min ago';
if (age.inDays < 1) return 'as of ${age.inHours} h ago';
return 'as of ${age.inDays} d ago';
}
/// A native plan id as a label: "max" -> "Max", "self_serve_business" ->
/// "Self serve business".
String chatPlanLabel(String plan) {
final words = plan.replaceAll('_', ' ').trim();
if (words.isEmpty) return '';
return words[0].toUpperCase() + words.substring(1);
}