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>
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/error_reason.dart';
|
||||
import '../../../ui/adaptive/app_popups.dart';
|
||||
import '../../../ui/layout/app_sheet_header.dart';
|
||||
import '../domain/chat_claude_accounts.dart';
|
||||
import 'chat_claude_accounts_controller.dart';
|
||||
|
||||
/// Switches the chat's Claude home to the saved account [account] and says
|
||||
/// so in a snack bar; a refusal is shown the same way. [messenger] is taken
|
||||
/// before any sheet closes, so the confirmation survives it.
|
||||
Future<void> switchChatClaudeAccount(
|
||||
ScaffoldMessengerState? messenger,
|
||||
ChatClaudeAccountsController accounts,
|
||||
ChatClaudeAccount account,
|
||||
) async {
|
||||
try {
|
||||
final active = await accounts.use(account.name);
|
||||
messenger?.showSnackBar(
|
||||
SnackBar(content: Text(chatClaudeSwitchedMessage(active ?? account))),
|
||||
);
|
||||
} catch (error) {
|
||||
_failed(messenger, error, 'The Claude account was not switched.');
|
||||
}
|
||||
}
|
||||
|
||||
void _failed(ScaffoldMessengerState? messenger, Object error, String fallback) {
|
||||
messenger?.showSnackBar(
|
||||
SnackBar(content: Text(describeErrorReason(error, fallback: fallback))),
|
||||
);
|
||||
}
|
||||
|
||||
/// The chat menu's "Claude account": the saved accounts of the chat's Claude
|
||||
/// home with the active one checked (one tap switches), and "Save current
|
||||
/// account…" for the active login. A dialog on a wide app, a bottom sheet on
|
||||
/// a phone.
|
||||
Future<void> showChatClaudeAccountsDialog(
|
||||
BuildContext context,
|
||||
ChatClaudeAccountsController accounts,
|
||||
) {
|
||||
unawaited(accounts.refresh());
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
return showAppDetails<void>(
|
||||
context,
|
||||
maxWidth: 440,
|
||||
builder: (sheetContext) => Column(
|
||||
key: const Key('chat-claude-accounts'),
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const AppSheetHeader(title: 'Claude account'),
|
||||
ListenableBuilder(
|
||||
listenable: accounts,
|
||||
builder: (context, _) => _AccountList(
|
||||
accounts: accounts,
|
||||
onSwitch: (account) {
|
||||
Navigator.of(sheetContext).pop();
|
||||
unawaited(switchChatClaudeAccount(messenger, accounts, account));
|
||||
},
|
||||
onSave: () async {
|
||||
final name = await _askName(sheetContext, accounts.accounts);
|
||||
if (name == null) return;
|
||||
try {
|
||||
await accounts.save(name);
|
||||
} catch (error) {
|
||||
_failed(messenger, error, 'The account was not saved.');
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _AccountList extends StatelessWidget {
|
||||
const _AccountList({
|
||||
required this.accounts,
|
||||
required this.onSwitch,
|
||||
required this.onSave,
|
||||
});
|
||||
|
||||
final ChatClaudeAccountsController accounts;
|
||||
final ValueChanged<ChatClaudeAccount> onSwitch;
|
||||
final VoidCallback onSave;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final list = accounts.accounts;
|
||||
final error = accounts.error;
|
||||
if (list == null) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
|
||||
child: error == null
|
||||
? const LinearProgressIndicator()
|
||||
: Text(
|
||||
describeErrorReason(
|
||||
error,
|
||||
fallback: 'Claude accounts are not available.',
|
||||
),
|
||||
key: const Key('chat-claude-accounts-error'),
|
||||
),
|
||||
);
|
||||
}
|
||||
final unsaved = list.canSaveActive ? list.active : null;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (list.accounts.isEmpty && unsaved == null)
|
||||
const ListTile(title: Text('No saved accounts')),
|
||||
for (final account in list.accounts)
|
||||
_AccountTile(
|
||||
account: account,
|
||||
onTap: account.active || accounts.busy
|
||||
? null
|
||||
: () => onSwitch(account),
|
||||
),
|
||||
if (unsaved != null)
|
||||
_AccountTile(account: unsaved, onTap: null, note: 'Not saved'),
|
||||
if (accounts.busy) const LinearProgressIndicator(),
|
||||
const Divider(),
|
||||
ListTile(
|
||||
key: const Key('chat-claude-account-save'),
|
||||
leading: const Icon(Icons.bookmark_add_outlined),
|
||||
title: const Text('Save current account…'),
|
||||
enabled: list.active != null && !accounts.busy,
|
||||
onTap: onSave,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AccountTile extends StatelessWidget {
|
||||
const _AccountTile({required this.account, required this.onTap, this.note});
|
||||
|
||||
final ChatClaudeAccount account;
|
||||
final VoidCallback? onTap;
|
||||
final String? note;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final detail = [
|
||||
if (account.name != account.label) account.name,
|
||||
if (account.organization.isNotEmpty) account.organization,
|
||||
if (account.plan.isNotEmpty) account.plan,
|
||||
?note,
|
||||
].join(' · ');
|
||||
return ListTile(
|
||||
key: Key('chat-claude-account-${account.name}'),
|
||||
leading: const Icon(Icons.account_circle_outlined),
|
||||
title: Text(account.label),
|
||||
subtitle: detail.isEmpty ? null : Text(detail),
|
||||
trailing: account.active
|
||||
? Icon(
|
||||
Icons.check,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
semanticLabel: 'Active',
|
||||
)
|
||||
: null,
|
||||
selected: account.active,
|
||||
// An active row is informative, not disabled-looking.
|
||||
enabled: onTap != null || account.active,
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks for the saved account's name, prefilled with the login's email.
|
||||
Future<String?> _askName(BuildContext context, ChatClaudeAccounts? accounts) =>
|
||||
showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => _NameDialog(initial: accounts?.active?.email ?? ''),
|
||||
);
|
||||
|
||||
class _NameDialog extends StatefulWidget {
|
||||
const _NameDialog({required this.initial});
|
||||
|
||||
final String initial;
|
||||
|
||||
@override
|
||||
State<_NameDialog> createState() => _NameDialogState();
|
||||
}
|
||||
|
||||
class _NameDialogState extends State<_NameDialog> {
|
||||
late final TextEditingController _field = TextEditingController(
|
||||
text: widget.initial,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_field.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _save() => Navigator.of(context).pop(_field.text.trim());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Save current account'),
|
||||
content: TextField(
|
||||
key: const Key('chat-claude-account-name'),
|
||||
controller: _field,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
key: const Key('chat-claude-account-name-save'),
|
||||
onPressed: _save,
|
||||
child: const Text('Save'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/app_popups.dart';
|
||||
import '../domain/chat_claude_accounts.dart';
|
||||
import 'chat_claude_account_dialog.dart';
|
||||
import 'chat_claude_accounts_controller.dart';
|
||||
|
||||
/// A usage banner's "Switch to (other account)": shown when the chat's Claude
|
||||
/// home has another saved account. With several it is "Switch account" and a
|
||||
/// small menu of them. It loads the saved accounts the first time it shows.
|
||||
class ChatClaudeAccountSwitchAction extends StatefulWidget {
|
||||
const ChatClaudeAccountSwitchAction({
|
||||
super.key,
|
||||
required this.accounts,
|
||||
this.foreground,
|
||||
});
|
||||
|
||||
final ChatClaudeAccountsController accounts;
|
||||
|
||||
/// The banner's text colour, so the button reads on its container.
|
||||
final Color? foreground;
|
||||
|
||||
@override
|
||||
State<ChatClaudeAccountSwitchAction> createState() =>
|
||||
_ChatClaudeAccountSwitchActionState();
|
||||
}
|
||||
|
||||
class _ChatClaudeAccountSwitchActionState
|
||||
extends State<ChatClaudeAccountSwitchAction> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(widget.accounts.ensureLoaded());
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatClaudeAccountSwitchAction oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.accounts != widget.accounts) {
|
||||
unawaited(widget.accounts.ensureLoaded());
|
||||
}
|
||||
}
|
||||
|
||||
void _switch(ChatClaudeAccount account) => unawaited(
|
||||
switchChatClaudeAccount(
|
||||
ScaffoldMessenger.maybeOf(context),
|
||||
widget.accounts,
|
||||
account,
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> _choose(
|
||||
BuildContext anchor,
|
||||
List<ChatClaudeAccount> others,
|
||||
) async {
|
||||
final chosen = await showAppChoiceMenu<ChatClaudeAccount>(
|
||||
anchor,
|
||||
semanticLabel: 'Switch Claude account',
|
||||
builder: (menu) => Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (final account in others)
|
||||
AppChoiceMenuItem(
|
||||
key: Key('chat-claude-switch-to-${account.name}'),
|
||||
selected: false,
|
||||
onTap: () => Navigator.of(menu).pop(account),
|
||||
child: Text(account.label),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (chosen != null && mounted) _switch(chosen);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: widget.accounts,
|
||||
builder: (context, _) {
|
||||
final others = widget.accounts.accounts?.others ?? const [];
|
||||
if (others.isEmpty) return const SizedBox.shrink();
|
||||
final busy = widget.accounts.busy;
|
||||
final style = TextButton.styleFrom(foregroundColor: widget.foreground);
|
||||
if (others.length == 1) {
|
||||
final account = others.single;
|
||||
return TextButton.icon(
|
||||
key: const Key('chat-claude-switch'),
|
||||
style: style,
|
||||
onPressed: busy ? null : () => _switch(account),
|
||||
icon: const Icon(Icons.switch_account_outlined),
|
||||
label: Text(
|
||||
'Switch to ${account.label}',
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
);
|
||||
}
|
||||
return Builder(
|
||||
builder: (anchor) => TextButton.icon(
|
||||
key: const Key('chat-claude-switch'),
|
||||
style: style,
|
||||
onPressed: busy ? null : () => unawaited(_choose(anchor, others)),
|
||||
icon: const Icon(Icons.switch_account_outlined),
|
||||
label: const Text('Switch account'),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_claude_accounts.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
|
||||
/// One Claude chat's saved accounts: loads `claude_accounts` once on demand,
|
||||
/// switches with `claude_account_use` and saves with `claude_account_save`.
|
||||
/// A switch hands the new account's quota to [thread], so its usage-limit
|
||||
/// banner reflects the new account at once (the server also pushes it to
|
||||
/// every open chat on the same Claude home).
|
||||
class ChatClaudeAccountsController extends ChangeNotifier {
|
||||
ChatClaudeAccountsController({
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
this.thread,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
final ChatThreadController? thread;
|
||||
|
||||
ChatClaudeAccounts? _accounts;
|
||||
String? _error;
|
||||
Future<void>? _loading;
|
||||
bool _busy = false;
|
||||
bool _disposed = false;
|
||||
|
||||
/// The last reply, or null before one arrived.
|
||||
ChatClaudeAccounts? get accounts => _accounts;
|
||||
|
||||
/// The last refusal (for example a chat directory with no Claude home).
|
||||
String? get error => _error;
|
||||
|
||||
/// A switch or save is in flight.
|
||||
bool get busy => _busy;
|
||||
|
||||
/// Loads the accounts once; later calls reuse the first load.
|
||||
Future<void> ensureLoaded() => _loading ??= refresh();
|
||||
|
||||
Future<void> refresh() async {
|
||||
try {
|
||||
await _run('claude_accounts', null);
|
||||
} catch (_) {
|
||||
// Recorded in [error].
|
||||
}
|
||||
}
|
||||
|
||||
/// Switches to the saved account [name] and returns the new active account.
|
||||
Future<ChatClaudeAccount?> use(String name) async {
|
||||
final accounts = await _run('claude_account_use', name);
|
||||
final usage = accounts?.usage;
|
||||
if (usage != null) thread?.accountSwitched(usage);
|
||||
return accounts?.active;
|
||||
}
|
||||
|
||||
/// Saves the active login as [name] ('' uses its email).
|
||||
Future<void> save(String name) => _run('claude_account_save', name);
|
||||
|
||||
Future<ChatClaudeAccounts?> _run(String type, String? name) async {
|
||||
_busy = type != 'claude_accounts';
|
||||
_notify();
|
||||
try {
|
||||
final reply = await gateway.call(type, {
|
||||
'claude_account': {'session_id': sessionId, 'name': ?name},
|
||||
});
|
||||
final accounts = ChatClaudeAccounts.fromJson(reply['claude_accounts']);
|
||||
if (accounts == null) {
|
||||
throw StateError('The server sent no Claude accounts.');
|
||||
}
|
||||
_accounts = accounts;
|
||||
_error = null;
|
||||
return accounts;
|
||||
} catch (error) {
|
||||
if (type == 'claude_accounts') _error = '$error';
|
||||
rethrow;
|
||||
} finally {
|
||||
_busy = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,14 @@ class ChatThreadController extends ChangeNotifier {
|
||||
/// is account state: a frame without one keeps the last known value.
|
||||
ChatAccountUsage? get accountUsage => _accountUsage;
|
||||
|
||||
/// Adopts the quota of the Claude account the operator just switched to
|
||||
/// (see ChatAccountUsage.switchedAt), which ends a limit the previous
|
||||
/// account had reached.
|
||||
void accountSwitched(ChatAccountUsage usage) {
|
||||
_accountUsage = usage;
|
||||
_notify(transcript: false);
|
||||
}
|
||||
|
||||
String? get error => _error;
|
||||
bool get subscribed => _subscribed;
|
||||
String? get subscriptionError => _subscriptionError;
|
||||
|
||||
@@ -42,6 +42,8 @@ import '../ui/transcript/chat_turn_diff_chip.dart';
|
||||
import '../../artifacts/actions/artifact_file_bridge.dart';
|
||||
import '../domain/chat_session_handoff.dart';
|
||||
import 'chat_account_usage_section.dart';
|
||||
import 'chat_claude_account_dialog.dart';
|
||||
import 'chat_claude_accounts_controller.dart';
|
||||
import 'chat_export_controller.dart';
|
||||
import 'chat_session_section.dart';
|
||||
import 'chat_background_tasks.dart';
|
||||
@@ -237,6 +239,26 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
late ChatThreadController _controller = _attach();
|
||||
late ChatComposerController _composer = _attachComposer();
|
||||
|
||||
/// The chat's saved Claude accounts (Claude Code chats only), loaded when
|
||||
/// the menu or a usage banner first needs them.
|
||||
ChatClaudeAccountsController? _claudeAccounts;
|
||||
ChatClaudeAccountsController? get _accounts {
|
||||
if ('${widget.session?['backend'] ?? ''}' != 'claude') return null;
|
||||
final current = _claudeAccounts;
|
||||
if (current != null &&
|
||||
current.sessionId == widget.sessionId &&
|
||||
current.gateway == widget.gateway &&
|
||||
identical(current.thread, _controller)) {
|
||||
return current;
|
||||
}
|
||||
current?.dispose();
|
||||
return _claudeAccounts = ChatClaudeAccountsController(
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
thread: _controller,
|
||||
);
|
||||
}
|
||||
|
||||
/// The operator's own shell commands in this chat (see `../shell/`).
|
||||
late ChatShellRunsController _shellRuns = _attachShellRuns();
|
||||
ChatShellRunsController _attachShellRuns() =>
|
||||
@@ -798,6 +820,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
widget.onComposerDisposed?.call(_composer);
|
||||
_composer.dispose();
|
||||
_controller.dispose();
|
||||
_claudeAccounts?.dispose();
|
||||
_shellRuns.dispose();
|
||||
_files.removeListener(_persistFilesPreferences);
|
||||
_files.dispose();
|
||||
@@ -1263,8 +1286,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
thread: _controller,
|
||||
composer: _composer,
|
||||
sendDraft: sendDraft,
|
||||
accounts: _accounts,
|
||||
),
|
||||
ChatUsageWarningBanner(
|
||||
thread: _controller,
|
||||
accounts: _accounts,
|
||||
),
|
||||
ChatUsageWarningBanner(thread: _controller),
|
||||
],
|
||||
),
|
||||
backgroundTasks: ChatBackgroundTasks(
|
||||
@@ -1624,6 +1651,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
...widget.paneControls.where((c) => !_closes(c)),
|
||||
if (_shellRuns.finishedIds.isNotEmpty)
|
||||
chatShellDismissAllMenuAction(onPressed: _dismissFinishedShellRuns),
|
||||
if (_accounts case final accounts?)
|
||||
ChatBarAction(
|
||||
key: const Key('chat-claude-account-menu'),
|
||||
label: 'Claude account',
|
||||
identifier: 'chat-claude-account',
|
||||
onPressed: () =>
|
||||
unawaited(showChatClaudeAccountsDialog(context, accounts)),
|
||||
materialIcon: Icons.switch_account_outlined,
|
||||
),
|
||||
?openTerminal,
|
||||
// Closing comes last.
|
||||
...widget.paneControls.where(_closes),
|
||||
|
||||
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
|
||||
import '../domain/chat_commands.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import '../shell/chat_shell_command.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';
|
||||
@@ -25,12 +27,17 @@ class ChatUsageLimitBanner extends StatefulWidget {
|
||||
required this.thread,
|
||||
required this.composer,
|
||||
required this.sendDraft,
|
||||
this.accounts,
|
||||
this.now = DateTime.now,
|
||||
});
|
||||
|
||||
final ChatThreadController thread;
|
||||
final ChatComposerController composer;
|
||||
final ChatScheduleDraft sendDraft;
|
||||
|
||||
/// 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 DateTime Function() now;
|
||||
|
||||
@override
|
||||
@@ -168,6 +175,11 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
||||
icon: const Icon(Icons.schedule_send),
|
||||
label: Text(label),
|
||||
),
|
||||
if (widget.accounts case final accounts?)
|
||||
ChatClaudeAccountSwitchAction(
|
||||
accounts: accounts,
|
||||
foreground: scheme.onErrorContainer,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
|
||||
import '../domain/chat_account_usage.dart';
|
||||
import '../domain/chat_usage_limit.dart';
|
||||
import '../domain/chat_usage_warning.dart';
|
||||
import 'chat_claude_account_switch_action.dart';
|
||||
import 'chat_claude_accounts_controller.dart';
|
||||
import 'chat_schedule_time.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_usage_warnings.dart';
|
||||
@@ -22,11 +24,16 @@ class ChatUsageWarningBanner extends StatefulWidget {
|
||||
super.key,
|
||||
required this.thread,
|
||||
ChatUsageWarnings? warnings,
|
||||
this.accounts,
|
||||
this.now = DateTime.now,
|
||||
}) : warnings = warnings ?? ChatUsageWarnings.shared;
|
||||
|
||||
final ChatThreadController thread;
|
||||
final ChatUsageWarnings warnings;
|
||||
|
||||
/// 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 DateTime Function() now;
|
||||
|
||||
@override
|
||||
@@ -168,6 +175,13 @@ class _ChatUsageWarningBannerState extends State<ChatUsageWarningBanner> {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.accounts case final accounts?)
|
||||
Flexible(
|
||||
child: ChatClaudeAccountSwitchAction(
|
||||
accounts: accounts,
|
||||
foreground: foreground,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('chat-usage-warning-dismiss'),
|
||||
tooltip: 'Dismiss',
|
||||
|
||||
@@ -29,6 +29,7 @@ class ChatAccountUsage {
|
||||
required this.asOf,
|
||||
required this.windows,
|
||||
required this.unsupported,
|
||||
this.switchedAt = 0,
|
||||
});
|
||||
|
||||
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
|
||||
@@ -41,6 +42,12 @@ class ChatAccountUsage {
|
||||
|
||||
/// 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) =>
|
||||
@@ -78,13 +85,17 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (windows.isEmpty) return null;
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/// The saved Claude accounts of the Claude home a chat's directory selects
|
||||
/// (its CLAUDE_CONFIG_DIR), as the server's `claude_accounts` reply reports
|
||||
/// them. Replies describe accounts only; they never carry a token.
|
||||
library;
|
||||
|
||||
import 'chat_account_usage.dart';
|
||||
|
||||
/// One Claude login.
|
||||
class ChatClaudeAccount {
|
||||
const ChatClaudeAccount({
|
||||
required this.name,
|
||||
required this.email,
|
||||
required this.organization,
|
||||
required this.plan,
|
||||
required this.active,
|
||||
required this.saved,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final String email;
|
||||
final String organization;
|
||||
final String plan;
|
||||
|
||||
/// The Claude home is signed in with this account.
|
||||
final bool active;
|
||||
|
||||
/// False for an active login with no saved slot yet.
|
||||
final bool saved;
|
||||
|
||||
/// What the operator calls the account: its email, else its name.
|
||||
String get label => email.isNotEmpty ? email : name;
|
||||
|
||||
static ChatClaudeAccount? fromJson(Object? value) {
|
||||
if (value is! Map) return null;
|
||||
final name = '${value['name'] ?? ''}'.trim();
|
||||
final email = '${value['email'] ?? ''}'.trim();
|
||||
if (name.isEmpty && email.isEmpty) return null;
|
||||
return ChatClaudeAccount(
|
||||
name: name.isEmpty ? email : name,
|
||||
email: email,
|
||||
organization: '${value['organization'] ?? ''}'.trim(),
|
||||
plan: '${value['plan'] ?? ''}'.trim(),
|
||||
active: value['active'] == true,
|
||||
saved: value['saved'] == true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `claude_accounts` reply.
|
||||
class ChatClaudeAccounts {
|
||||
const ChatClaudeAccounts({
|
||||
required this.configDir,
|
||||
required this.active,
|
||||
required this.accounts,
|
||||
this.usage,
|
||||
});
|
||||
|
||||
final String configDir;
|
||||
|
||||
/// The current login, saved or not; null when signed out.
|
||||
final ChatClaudeAccount? active;
|
||||
|
||||
/// The saved accounts.
|
||||
final List<ChatClaudeAccount> accounts;
|
||||
|
||||
/// After a switch, the new account's quota as the server knows it.
|
||||
final ChatAccountUsage? usage;
|
||||
|
||||
/// Saved accounts other than the active one: the switch targets.
|
||||
List<ChatClaudeAccount> get others => [
|
||||
for (final account in accounts)
|
||||
if (!account.active) account,
|
||||
];
|
||||
|
||||
/// Whether the active login can be saved (it is not saved yet).
|
||||
bool get canSaveActive => active != null && !active!.saved;
|
||||
|
||||
static ChatClaudeAccounts? fromJson(Object? value) {
|
||||
if (value is! Map) return null;
|
||||
final raw = value['accounts'];
|
||||
return ChatClaudeAccounts(
|
||||
configDir: '${value['config_dir'] ?? ''}',
|
||||
active: ChatClaudeAccount.fromJson(value['active']),
|
||||
accounts: [
|
||||
if (raw is List)
|
||||
for (final entry in raw) ?ChatClaudeAccount.fromJson(entry),
|
||||
],
|
||||
usage: chatAccountUsage(value['usage']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The confirmation shown after a switch.
|
||||
String chatClaudeSwitchedMessage(ChatClaudeAccount? account) =>
|
||||
'Switched to ${account?.label ?? 'the saved account'} — send a message '
|
||||
'to continue';
|
||||
@@ -67,6 +67,13 @@ ChatUsageLimit? chatThreadUsageLimit(
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_claude_account_dialog.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_claude_accounts_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_usage_limit_banner.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_usage_warning_banner.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_usage_warnings.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_usage_limit.dart';
|
||||
import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'chat_thread_fixtures.dart';
|
||||
|
||||
final _now = DateTime.now();
|
||||
|
||||
JsonMap _account(String email, {bool active = false, bool saved = true}) => {
|
||||
'name': email,
|
||||
'email': email,
|
||||
'organization': 'Org',
|
||||
'plan': 'max',
|
||||
'active': active,
|
||||
'saved': saved,
|
||||
};
|
||||
|
||||
/// A chat gateway whose Claude home has saved accounts; `use` makes the named
|
||||
/// one active and reports the switch.
|
||||
class _AccountsGateway extends FakeChatGateway {
|
||||
_AccountsGateway(this.emails);
|
||||
|
||||
final List<String> emails;
|
||||
int active = 0;
|
||||
|
||||
JsonMap _list({JsonMap? usage}) => {
|
||||
'claude_accounts': {
|
||||
'config_dir': '/home/op/caplens/.claude-profile',
|
||||
'active': _account(emails[active], active: true),
|
||||
'accounts': [
|
||||
for (var i = 0; i < emails.length; i++)
|
||||
_account(emails[i], active: i == active),
|
||||
],
|
||||
'usage': ?usage,
|
||||
},
|
||||
};
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (!type.startsWith('claude_account')) return super.call(type, fields);
|
||||
calls.add((type: type, fields: fields));
|
||||
final name = '${(fields['claude_account'] as Map)['name'] ?? ''}';
|
||||
if (type == 'claude_account_use') {
|
||||
active = emails.indexOf(name);
|
||||
return _list(
|
||||
usage: {
|
||||
'harness': 'Claude Code',
|
||||
'plan': 'max',
|
||||
'as_of': _now.millisecondsSinceEpoch,
|
||||
'switched_at': _now.millisecondsSinceEpoch,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (type == 'claude_account_save') emails.add('saved:$name');
|
||||
return _list();
|
||||
}
|
||||
|
||||
List<String> accountCalls() => [
|
||||
for (final call in calls)
|
||||
if (call.type.startsWith('claude_account'))
|
||||
'${call.type} ${(call.fields['claude_account'] as Map)['name'] ?? ''}'
|
||||
.trim(),
|
||||
];
|
||||
}
|
||||
|
||||
JsonMap _limited({double five = 100}) => {
|
||||
'session_id': 's',
|
||||
'kind': 'usage',
|
||||
'usage': {
|
||||
'account': {
|
||||
'harness': 'Claude Code',
|
||||
'windows': [
|
||||
{
|
||||
'id': 'five_hour',
|
||||
'label': '5-hour',
|
||||
'used_percent': five,
|
||||
'resets_at': _now
|
||||
.add(const Duration(hours: 2))
|
||||
.millisecondsSinceEpoch,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Future<(ChatThreadController, ChatClaudeAccountsController)> _pump(
|
||||
WidgetTester tester,
|
||||
_AccountsGateway gateway,
|
||||
Widget Function(ChatThreadController, ChatClaudeAccountsController) build,
|
||||
) async {
|
||||
final thread = ChatThreadController(gateway, 's');
|
||||
final accounts = ChatClaudeAccountsController(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
thread: thread,
|
||||
);
|
||||
addTearDown(gateway.close);
|
||||
addTearDown(thread.dispose);
|
||||
addTearDown(accounts.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(body: Column(children: [build(thread, accounts)])),
|
||||
),
|
||||
);
|
||||
return (thread, accounts);
|
||||
}
|
||||
|
||||
void main() {
|
||||
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||
|
||||
for (final backend in ['claude', 'codex']) {
|
||||
testWidgets('the chat menu offers Claude account for a $backend chat: '
|
||||
'${backend == 'claude'}', (tester) async {
|
||||
final gateway = _AccountsGateway([
|
||||
'a@example.invalid',
|
||||
'b@example.invalid',
|
||||
]);
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
session: {'id': 's', 'backend': backend, 'directory': '/x'},
|
||||
syncToken: 0,
|
||||
onBack: () {},
|
||||
drafts: MemoryChatDraftStore(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
// A chat with nothing else to offer has no More menu at all.
|
||||
final more = find.byKey(segmentedMoreKey).hitTestable();
|
||||
if (more.evaluate().isNotEmpty) {
|
||||
await tester.tap(more.first);
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
}
|
||||
final entry = find.text('Claude account');
|
||||
if (backend != 'claude') {
|
||||
expect(entry, findsNothing);
|
||||
return;
|
||||
}
|
||||
expect(entry, findsOneWidget);
|
||||
await tester.tap(entry);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
expect(gateway.accountCalls(), ['claude_accounts']);
|
||||
expect(
|
||||
find.byKey(const Key('chat-claude-account-b@example.invalid')),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('a switched report replaces the old one and voids an old refusal', () {
|
||||
final usage = chatAccountUsage({
|
||||
'harness': 'Claude Code',
|
||||
'switched_at': 2000,
|
||||
});
|
||||
expect(usage, isNotNull);
|
||||
expect(usage!.switchedAt, 2000);
|
||||
expect(usage.windows, isEmpty);
|
||||
expect(chatAccountUsage({'harness': 'Claude Code'}), isNull);
|
||||
final reset = _now.add(const Duration(hours: 1));
|
||||
final refusal = {
|
||||
'id': 'm',
|
||||
'role': 'assistant',
|
||||
'created_at': 1000,
|
||||
'parts': [
|
||||
{
|
||||
'type': 'text',
|
||||
'text':
|
||||
'Claude AI usage limit reached|'
|
||||
'${reset.millisecondsSinceEpoch ~/ 1000}',
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(chatThreadUsageLimit(null, [refusal], _now), isNotNull);
|
||||
expect(chatThreadUsageLimit(usage, [refusal], _now), isNull);
|
||||
final later = {...refusal, 'created_at': 3000};
|
||||
expect(chatThreadUsageLimit(usage, [later], _now), isNotNull);
|
||||
});
|
||||
|
||||
testWidgets('the Claude account menu checks the active account and switches '
|
||||
'with one tap', (tester) async {
|
||||
final gateway = _AccountsGateway([
|
||||
'a@example.invalid',
|
||||
'b@example.invalid',
|
||||
]);
|
||||
late ChatClaudeAccountsController accounts;
|
||||
await _pump(tester, gateway, (thread, controller) {
|
||||
accounts = controller;
|
||||
return Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () => showChatClaudeAccountsDialog(context, accounts),
|
||||
child: const Text('open'),
|
||||
),
|
||||
);
|
||||
});
|
||||
await tester.tap(find.text('open'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Claude account'), findsOneWidget);
|
||||
final active = find.byKey(
|
||||
const Key('chat-claude-account-a@example.invalid'),
|
||||
);
|
||||
expect(
|
||||
find.descendant(of: active, matching: find.byIcon(Icons.check)),
|
||||
findsOneWidget,
|
||||
);
|
||||
final other = find.byKey(
|
||||
const Key('chat-claude-account-b@example.invalid'),
|
||||
);
|
||||
expect(
|
||||
find.descendant(of: other, matching: find.byIcon(Icons.check)),
|
||||
findsNothing,
|
||||
);
|
||||
expect(find.text('Save current account…'), findsOneWidget);
|
||||
|
||||
await tester.tap(other);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.accountCalls(), [
|
||||
'claude_accounts',
|
||||
'claude_account_use b@example.invalid',
|
||||
]);
|
||||
expect(find.text('Claude account'), findsNothing);
|
||||
expect(
|
||||
find.text('Switched to b@example.invalid — send a message to continue'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'Save current account asks for a name, prefilled with the email',
|
||||
(tester) async {
|
||||
final gateway = _AccountsGateway(['a@example.invalid']);
|
||||
await _pump(
|
||||
tester,
|
||||
gateway,
|
||||
(thread, accounts) => Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () => showChatClaudeAccountsDialog(context, accounts),
|
||||
child: const Text('open'),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('open'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-claude-account-save')));
|
||||
await tester.pumpAndSettle();
|
||||
final field = tester.widget<TextField>(
|
||||
find.byKey(const Key('chat-claude-account-name')),
|
||||
);
|
||||
expect(field.controller!.text, 'a@example.invalid');
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('chat-claude-account-name')),
|
||||
'Work',
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('chat-claude-account-name-save')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.accountCalls().last, 'claude_account_save Work');
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('the usage-limit banner offers the other account and clears '
|
||||
'once switched', (tester) async {
|
||||
final gateway = _AccountsGateway([
|
||||
'a@example.invalid',
|
||||
'b@example.invalid',
|
||||
]);
|
||||
final composer = ChatComposerController(gateway, 's');
|
||||
addTearDown(composer.dispose);
|
||||
final (thread, _) = await _pump(
|
||||
tester,
|
||||
gateway,
|
||||
(thread, accounts) => ChatUsageLimitBanner(
|
||||
thread: thread,
|
||||
composer: composer,
|
||||
sendDraft: (_) async {},
|
||||
accounts: accounts,
|
||||
),
|
||||
);
|
||||
gateway.emitEvent(_limited());
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-usage-limit')), findsOneWidget);
|
||||
final action = find.byKey(const Key('chat-claude-switch'));
|
||||
expect(
|
||||
find.descendant(
|
||||
of: action,
|
||||
matching: find.text('Switch to b@example.invalid'),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.tap(action);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.accountCalls().last, 'claude_account_use b@example.invalid');
|
||||
expect(thread.accountUsage?.switchedAt, greaterThan(0));
|
||||
expect(find.byKey(const Key('chat-usage-limit')), findsNothing);
|
||||
expect(
|
||||
find.text('Switched to b@example.invalid — send a message to continue'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('with several other accounts the warning banner offers a menu', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _AccountsGateway([
|
||||
'a@example.invalid',
|
||||
'b@example.invalid',
|
||||
'c@example.invalid',
|
||||
]);
|
||||
await _pump(
|
||||
tester,
|
||||
gateway,
|
||||
(thread, accounts) => ChatUsageWarningBanner(
|
||||
thread: thread,
|
||||
warnings: ChatUsageWarnings(announce: (_) => true),
|
||||
accounts: accounts,
|
||||
),
|
||||
);
|
||||
gateway.emitEvent(_limited(five: 90));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
|
||||
await tester.tap(find.text('Switch account'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('chat-claude-switch-to-a@example.invalid')),
|
||||
findsNothing,
|
||||
);
|
||||
await tester.tap(
|
||||
find.byKey(const Key('chat-claude-switch-to-c@example.invalid')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.accountCalls().last, 'claude_account_use c@example.invalid');
|
||||
});
|
||||
|
||||
testWidgets('a banner without another saved account offers no switch', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _AccountsGateway(['a@example.invalid']);
|
||||
await _pump(
|
||||
tester,
|
||||
gateway,
|
||||
(thread, accounts) => ChatUsageWarningBanner(
|
||||
thread: thread,
|
||||
warnings: ChatUsageWarnings(announce: (_) => true),
|
||||
accounts: accounts,
|
||||
),
|
||||
);
|
||||
gateway.emitEvent(_limited(five: 90));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-claude-switch')), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// `?claudeAccounts=N` (with `?chats=1&harness=claude`): the chat's Claude
|
||||
// home has N saved accounts (alex@caplens.example, sam@caplens.example,
|
||||
// ops@caplens.example), the first one active, and `claude_account_use`
|
||||
// switches between them. `?claudeUsage=limit` pushes the active account's
|
||||
// quota at 100% on subscribe (the usage-limit banner); `?claudeUsage=warn`
|
||||
// pushes it at 88% (the usage warning banner).
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
Map<String, String> _params = const {};
|
||||
int _active = 0;
|
||||
|
||||
const _emails = [
|
||||
'alex@caplens.example',
|
||||
'sam@caplens.example',
|
||||
'ops@caplens.example',
|
||||
];
|
||||
|
||||
void configureChatClaudeAccountsFixture(Map<String, String> params) {
|
||||
_params = params;
|
||||
}
|
||||
|
||||
int get _count =>
|
||||
(int.tryParse(_params['claudeAccounts'] ?? '') ?? 0).clamp(0, 3);
|
||||
|
||||
JsonMap _account(int i) => {
|
||||
'name': _emails[i],
|
||||
'email': _emails[i],
|
||||
'organization': 'Caplens',
|
||||
'plan': i == 2 ? 'pro' : 'max',
|
||||
'active': i == _active,
|
||||
'saved': true,
|
||||
};
|
||||
|
||||
JsonMap _list({JsonMap? usage}) => {
|
||||
'config_dir': '/home/alex/caplens/.claude-profile',
|
||||
'active': _account(_active),
|
||||
'accounts': [for (var i = 0; i < _count; i++) _account(i)],
|
||||
'usage': ?usage,
|
||||
};
|
||||
|
||||
/// Replies to the claude_account* requests, or null for any other request.
|
||||
JsonMap? chatClaudeAccountsReply(JsonMap request) {
|
||||
final type = '${request['type']}';
|
||||
if (_count == 0 || !type.startsWith('claude_account')) return null;
|
||||
final body = request['claude_account'];
|
||||
final name = body is Map ? '${body['name'] ?? ''}' : '';
|
||||
JsonMap? usage;
|
||||
if (type == 'claude_account_use') {
|
||||
final index = _emails.indexOf(name);
|
||||
if (index < 0 || index >= _count) {
|
||||
return {
|
||||
'id': request['id'],
|
||||
'type': 'error',
|
||||
'error': 'no saved Claude account "$name"',
|
||||
};
|
||||
}
|
||||
_active = index;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
usage = {
|
||||
'harness': 'Claude Code',
|
||||
'plan': 'max',
|
||||
'as_of': now,
|
||||
'switched_at': now,
|
||||
};
|
||||
}
|
||||
return {
|
||||
'id': request['id'],
|
||||
'type': type,
|
||||
'claude_accounts': _list(usage: usage),
|
||||
};
|
||||
}
|
||||
|
||||
/// The active account's quota frame for `?claudeUsage=`, or null.
|
||||
JsonMap? chatClaudeUsageFrame(String sessionId) {
|
||||
final percent = switch (_params['claudeUsage']) {
|
||||
'limit' => 100.0,
|
||||
'warn' => 88.0,
|
||||
_ => null,
|
||||
};
|
||||
if (percent == null) return null;
|
||||
final now = DateTime.now();
|
||||
return {
|
||||
'type': 'chat_event',
|
||||
'chat_event': {
|
||||
'session_id': sessionId,
|
||||
'kind': 'usage',
|
||||
'usage': {
|
||||
'account': {
|
||||
'harness': 'Claude Code',
|
||||
'plan': 'max',
|
||||
'as_of': now.millisecondsSinceEpoch,
|
||||
'windows': [
|
||||
{
|
||||
'id': 'five_hour',
|
||||
'label': '5-hour',
|
||||
'used_percent': percent,
|
||||
'resets_at': now
|
||||
.add(const Duration(hours: 2, minutes: 10))
|
||||
.millisecondsSinceEpoch,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -26,6 +26,7 @@
|
||||
// (tool/perf/chat_new_session_fixture.dart).
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
import 'chat_claude_accounts_fixture.dart';
|
||||
import 'chat_effort_fixture.dart';
|
||||
import 'chat_catalog_fixture.dart';
|
||||
import 'chat_new_session_fixture.dart';
|
||||
@@ -47,6 +48,7 @@ void configurePerfFixture(Map<String, String> params) {
|
||||
);
|
||||
configureChatScrollFixture(params);
|
||||
configureChatShownPush(params);
|
||||
configureChatClaudeAccountsFixture(params);
|
||||
configureChatQuestionFixture(params);
|
||||
configureChatShellFixture(params);
|
||||
configureTerminalFixture(params);
|
||||
@@ -281,6 +283,8 @@ JsonMap? perfChatReply(JsonMap request) {
|
||||
final terminal = terminalFixtureReply(request);
|
||||
if (terminal != null) return terminal;
|
||||
if (_chats == 0) return null;
|
||||
final accounts = chatClaudeAccountsReply(request);
|
||||
if (accounts != null) return accounts;
|
||||
final question = chatQuestionReply(request);
|
||||
if (question != null) return question;
|
||||
final shell = chatShellReply(request);
|
||||
|
||||
@@ -42,6 +42,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'fixture_host/fixture_host.dart';
|
||||
import 'perf/chat_search_fixture.dart';
|
||||
import 'perf/chat_shown_fixture.dart';
|
||||
import 'perf/chat_claude_accounts_fixture.dart';
|
||||
import 'perf/chat_question_fixture.dart';
|
||||
import 'capture/window_probe.dart';
|
||||
import 'perf/chat_scroll_fixture.dart';
|
||||
@@ -824,6 +825,13 @@ class _FixtureChannel implements WebSocketChannel {
|
||||
chatScrollStream('${subscribe['session_id'] ?? ''}', emit);
|
||||
chatQuestionStream('${subscribe['session_id'] ?? ''}', emit);
|
||||
chatShownPush('${subscribe['session_id'] ?? ''}', emit);
|
||||
final usage = chatClaudeUsageFrame('${subscribe['session_id'] ?? ''}');
|
||||
if (usage != null) {
|
||||
Future<void>.delayed(
|
||||
const Duration(milliseconds: 300),
|
||||
() => emit(usage),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (reply == null && followUps.isEmpty) return;
|
||||
Future<void>.delayed(const Duration(milliseconds: 120), () {
|
||||
|
||||
Reference in New Issue
Block a user