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:
2026-11-30 15:10:08 +00:00
parent 1772100af2
commit c490f71042
33 changed files with 2958 additions and 4 deletions
@@ -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);
});
}