From c490f71042a5a8472ceac7e8720d1769b3ed39ad Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 30 Nov 2026 15:10:08 +0000 Subject: [PATCH] Claude account switcher: save and switch a chat's Claude login in place Saved accounts live under /pipelines-accounts// (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 on the usage-limit and usage-warning banners, with a confirmation snack. Co-Authored-By: Claude Opus 5.5 --- .../chat_claude_account_dialog.dart | 226 +++++++++++ .../chat_claude_account_switch_action.dart | 112 ++++++ .../chat_claude_accounts_controller.dart | 94 +++++ .../conversation/chat_thread_controller.dart | 8 + .../chat/conversation/chat_thread_view.dart | 38 +- .../conversation/chat_usage_limit_banner.dart | 12 + .../chat_usage_warning_banner.dart | 14 + .../chat/domain/chat_account_usage.dart | 13 +- .../chat/domain/chat_claude_accounts.dart | 96 +++++ .../chat/domain/chat_usage_limit.dart | 7 + .../chat_claude_accounts_test.dart | 370 ++++++++++++++++++ .../perf/chat_claude_accounts_fixture.dart | 106 +++++ app/tool/perf/perf_fixture.dart | 4 + app/tool/search_selection_probe_entry.dart | 8 + docs/cli.md | 39 ++ internal/claude/accounts.go | 124 ++++++ internal/claude/accounts_test.go | 98 +++++ internal/claude/quota.go | 9 +- internal/claudeaccounts/files.go | 215 ++++++++++ internal/claudeaccounts/operations.go | 302 ++++++++++++++ internal/claudeaccounts/store.go | 285 ++++++++++++++ internal/claudeaccounts/store_test.go | 356 +++++++++++++++++ internal/cli/app.go | 3 + internal/cli/claude_account.go | 113 ++++++ internal/cli/claude_account_test.go | 78 ++++ internal/cli/commands.go | 1 + internal/cli/help.go | 3 + internal/protocol/chat.go | 5 + internal/protocol/claude_accounts.go | 57 +++ internal/protocol/message.go | 4 + internal/server/chat.go | 3 + internal/server/chat_claude_accounts.go | 69 ++++ internal/server/chat_claude_accounts_test.go | 90 +++++ 33 files changed, 2958 insertions(+), 4 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_claude_account_dialog.dart create mode 100644 app/lib/features/chat/conversation/chat_claude_account_switch_action.dart create mode 100644 app/lib/features/chat/conversation/chat_claude_accounts_controller.dart create mode 100644 app/lib/features/chat/domain/chat_claude_accounts.dart create mode 100644 app/test/features/chat/conversation/chat_claude_accounts_test.dart create mode 100644 app/tool/perf/chat_claude_accounts_fixture.dart create mode 100644 internal/claude/accounts.go create mode 100644 internal/claude/accounts_test.go create mode 100644 internal/claudeaccounts/files.go create mode 100644 internal/claudeaccounts/operations.go create mode 100644 internal/claudeaccounts/store.go create mode 100644 internal/claudeaccounts/store_test.go create mode 100644 internal/cli/claude_account.go create mode 100644 internal/cli/claude_account_test.go create mode 100644 internal/protocol/claude_accounts.go create mode 100644 internal/server/chat_claude_accounts.go create mode 100644 internal/server/chat_claude_accounts_test.go diff --git a/app/lib/features/chat/conversation/chat_claude_account_dialog.dart b/app/lib/features/chat/conversation/chat_claude_account_dialog.dart new file mode 100644 index 00000000..bf18ba31 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_claude_account_dialog.dart @@ -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 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 showChatClaudeAccountsDialog( + BuildContext context, + ChatClaudeAccountsController accounts, +) { + unawaited(accounts.refresh()); + final messenger = ScaffoldMessenger.maybeOf(context); + return showAppDetails( + 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 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 _askName(BuildContext context, ChatClaudeAccounts? accounts) => + showDialog( + 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'), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_claude_account_switch_action.dart b/app/lib/features/chat/conversation/chat_claude_account_switch_action.dart new file mode 100644 index 00000000..753a7d4b --- /dev/null +++ b/app/lib/features/chat/conversation/chat_claude_account_switch_action.dart @@ -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 createState() => + _ChatClaudeAccountSwitchActionState(); +} + +class _ChatClaudeAccountSwitchActionState + extends State { + @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 _choose( + BuildContext anchor, + List others, + ) async { + final chosen = await showAppChoiceMenu( + 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'), + ), + ); + }, + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart b/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart new file mode 100644 index 00000000..ba9eb8de --- /dev/null +++ b/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart @@ -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? _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 ensureLoaded() => _loading ??= refresh(); + + Future 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 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 save(String name) => _run('claude_account_save', name); + + Future _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(); + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index c301434f..5c96ff3e 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -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; diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 82980b56..9d0e8bd2 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -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 { 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 { 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 { 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 { ...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), diff --git a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart index 9d11a061..f693d5bf 100644 --- a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart +++ b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart @@ -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 { icon: const Icon(Icons.schedule_send), label: Text(label), ), + if (widget.accounts case final accounts?) + ChatClaudeAccountSwitchAction( + accounts: accounts, + foreground: scheme.onErrorContainer, + ), ], ), ), diff --git a/app/lib/features/chat/conversation/chat_usage_warning_banner.dart b/app/lib/features/chat/conversation/chat_usage_warning_banner.dart index 853b1ad6..44fac67c 100644 --- a/app/lib/features/chat/conversation/chat_usage_warning_banner.dart +++ b/app/lib/features/chat/conversation/chat_usage_warning_banner.dart @@ -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 { ), ), ), + if (widget.accounts case final accounts?) + Flexible( + child: ChatClaudeAccountSwitchAction( + accounts: accounts, + foreground: foreground, + ), + ), IconButton( key: const Key('chat-usage-warning-dismiss'), tooltip: 'Dismiss', diff --git a/app/lib/features/chat/domain/chat_account_usage.dart b/app/lib/features/chat/domain/chat_account_usage.dart index 3b8a773a..cdf6084b 100644 --- a/app/lib/features/chat/domain/chat_account_usage.dart +++ b/app/lib/features/chat/domain/chat_account_usage.dart @@ -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, ); } diff --git a/app/lib/features/chat/domain/chat_claude_accounts.dart b/app/lib/features/chat/domain/chat_claude_accounts.dart new file mode 100644 index 00000000..b657451c --- /dev/null +++ b/app/lib/features/chat/domain/chat_claude_accounts.dart @@ -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 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 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'; diff --git a/app/lib/features/chat/domain/chat_usage_limit.dart b/app/lib/features/chat/domain/chat_usage_limit.dart index caadd2ab..66f38f83 100644 --- a/app/lib/features/chat/domain/chat_usage_limit.dart +++ b/app/lib/features/chat/domain/chat_usage_limit.dart @@ -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); } diff --git a/app/test/features/chat/conversation/chat_claude_accounts_test.dart b/app/test/features/chat/conversation/chat_claude_accounts_test.dart new file mode 100644 index 00000000..f2f7f1c2 --- /dev/null +++ b/app/test/features/chat/conversation/chat_claude_accounts_test.dart @@ -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 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 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 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( + 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); + }); +} diff --git a/app/tool/perf/chat_claude_accounts_fixture.dart b/app/tool/perf/chat_claude_accounts_fixture.dart new file mode 100644 index 00000000..f83472a2 --- /dev/null +++ b/app/tool/perf/chat_claude_accounts_fixture.dart @@ -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 _params = const {}; +int _active = 0; + +const _emails = [ + 'alex@caplens.example', + 'sam@caplens.example', + 'ops@caplens.example', +]; + +void configureChatClaudeAccountsFixture(Map 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, + }, + ], + }, + }, + }, + }; +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index b5e814e3..24170251 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -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 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); diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index b87096ac..4c2d3d35 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -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.delayed( + const Duration(milliseconds: 300), + () => emit(usage), + ); + } } if (reply == null && followUps.isEmpty) return; Future.delayed(const Duration(milliseconds: 120), () { diff --git a/docs/cli.md b/docs/cli.md index f5195796..5f38495e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -520,6 +520,45 @@ five minutes) and merges `account/rateLimits/updated` notifications. OpenCode has no quota API, so it sends `{"harness":"OpenCode","unsupported":true}`. A usage frame with only `account` updates the quota and leaves token figures as they were. No quota is estimated and no model call is made to obtain one. +`switched_at` (epoch ms) marks a report sent after the operator switched the +chat's Claude account: it replaces the previous account's report even with no +windows yet, and a usage-limit refusal received before it no longer applies. + +### Claude account switching + +A chat whose directory selects its own Claude Code home (`CLAUDE_CONFIG_DIR`, +for example from a direnv `.envrc`) can keep several subscription logins and +switch between them. Saved accounts live in +`/pipelines-accounts//` (0700): `credentials.json` (that +account's `claudeAiOauth`), `account.json` (its `oauthAccount`) and `slot.json` +(its name), all 0600. Switching changes exactly what `/login` changes, in +place: the `claudeAiOauth` entry of `.credentials.json` (other entries such as +MCP OAuth are kept) and the `oauthAccount` object of `.claude.json` (every other +key kept, in order), each written to a temporary file and renamed, keeping the +file's mode; it also deletes the organization caches `/login` deletes +(`policy-limits.json`, `remote-settings.json` and their stamp, signature and +synced-at files). It holds Claude Code's own `.oauth_refresh.lock`, +`.storage-write.lock` and `.claude.json.lock` meanwhile, so a token refresh or a +config save cannot write the old account back. Running Claude Code processes notice the credentials file's new mtime and +continue on the new account without a restart, as after a terminal `/login`. +Before switching, the active login's current (possibly refreshed) tokens are +written back to its own slot; an unsaved login is saved under its email first, +so a switch never loses one. Accounts are compared by account uuid (else email +and organization), never by token, and no reply or log carries a token. + +Requests (body `claude_account: {"session_id", "name"}`; reply +`claude_accounts: {"config_dir", "active", "accounts": [{"name", "email", +"organization", "plan", "active", "saved"}], "usage"}`): +`claude_accounts` lists; `claude_account_save` snapshots the active login (name +defaults to its email); `claude_account_use` switches to a saved account and +pushes the new account's quota (`switched_at`) to every open chat on that +Claude home, which clears a usage limit the old account had reached; +`claude_account_remove` deletes a saved account. They are refused for chats +that are not Claude Code's and for directories without `CLAUDE_CONFIG_DIR`. +The same operations run locally with +`pipelines claude-account list | save [name] | use | remove +[--dir DIR] [--json]`, which resolves DIR's (default: the current directory's) +environment the way the server does. The brokered OpenCode chat exposes the operator's own sessions, separate from the sessions pipeline runs create. The protocol types are: diff --git a/internal/claude/accounts.go b/internal/claude/accounts.go new file mode 100644 index 00000000..e712a952 --- /dev/null +++ b/internal/claude/accounts.go @@ -0,0 +1,124 @@ +package claude + +import ( + "context" + "errors" + "log" + "os" + "path/filepath" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/claudeaccounts" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +// Account switching (see internal/claudeaccounts) acts on the Claude Code home +// a chat's directory selects: the CLAUDE_CONFIG_DIR its processes run with. + +// ErrNoConfigDir is returned for a chat whose directory selects no Claude +// home of its own. +var ErrNoConfigDir = errors.New("this chat's directory does not set CLAUDE_CONFIG_DIR, so it has no Claude home of its own to switch") + +// AccountConfigDir is the CLAUDE_CONFIG_DIR a process started in directory +// runs with: the directory's own environment (direnv, mise) over base. +func AccountConfigDir(ctx context.Context, resolver *workenv.Resolver, directory string, base []string) (string, error) { + env := base + if resolver != nil && strings.TrimSpace(directory) != "" { + env = resolver.Resolve(ctx, directory, base).Apply(base) + } + dir, ok := envValue(env, "CLAUDE_CONFIG_DIR") + dir = strings.TrimSpace(dir) + if !ok || dir == "" || !filepath.IsAbs(dir) { + return "", ErrNoConfigDir + } + return filepath.Clean(dir), nil +} + +func (c *Chat) accountConfigDir(ctx context.Context, directory string) (string, error) { + return AccountConfigDir(ctx, c.dirEnv, directory, os.Environ()) +} + +// accountKeyFor is the quota key decodeAccountIdentity derives from an +// initialize response for a subscription login. +func accountKeyFor(email, organization string) string { + return strings.TrimSpace(email) + "\x00" + strings.TrimSpace(organization) + "\x00" + "firstParty" +} + +// ClaudeAccounts runs one claude_account* operation for the chat sessionID in +// directory ("" uses the open session's directory). After a switch every +// open chat on the same Claude home is moved to the new account's quota and +// told so, which clears a usage limit the old account had reached. +func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) { + if strings.TrimSpace(directory) == "" { + if s := c.session(sessionID); s != nil { + s.mu.Lock() + directory = s.directory + s.mu.Unlock() + } + } + configDir, err := c.accountConfigDir(ctx, directory) + if err != nil { + return protocol.ClaudeAccountList{}, err + } + store := claudeaccounts.Store{ConfigDir: configDir} + switch operation { + case protocol.ClaudeAccounts: + return store.List() + case protocol.ClaudeAccountSave: + return store.Save(name) + case protocol.ClaudeAccountRemove: + return store.Remove(name) + case protocol.ClaudeAccountUse: + list, err := store.Use(name) + if err != nil { + return list, err + } + email, org, plan, ok := store.Identity() + if ok { + list.Usage = c.switchAccount(ctx, configDir, accountKeyFor(email, org), plan) + log.Printf("claude account: %s switched to a saved account", configDir) + } + return list, nil + } + return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation) +} + +// switchAccount records that configDir now signs in as key: its quota report +// is marked switched (an empty one when nothing is known yet), and every open +// session on that Claude home takes the new key and republishes its usage. +func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *protocol.ChatAccountUsage { + now := time.Now().UnixMilli() + c.quotaMu.Lock() + usage := c.quotas[key].Clone() + if usage == nil { + usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: plan, AsOf: now} + } + usage.SwitchedAt = now + if c.quotas == nil { + c.quotas = map[string]*protocol.ChatAccountUsage{} + } + c.quotas[key] = usage + c.quotaMu.Unlock() + + c.mu.Lock() + sessions := make([]*session, 0, len(c.sessions)) + for _, s := range c.sessions { + sessions = append(sessions, s) + } + c.mu.Unlock() + for _, s := range sessions { + s.mu.Lock() + directory := s.directory + s.mu.Unlock() + if dir, err := c.accountConfigDir(ctx, directory); err != nil || dir != configDir { + continue + } + s.mu.Lock() + s.account = accountIdentity{key: key, plan: plan} + s.mu.Unlock() + s.republishUsage() + } + return usage.Clone() +} diff --git a/internal/claude/accounts_test.go b/internal/claude/accounts_test.go new file mode 100644 index 00000000..9571ddcf --- /dev/null +++ b/internal/claude/accounts_test.go @@ -0,0 +1,98 @@ +package claude + +import ( + "bytes" + "context" + "log" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func writeLogin(t *testing.T, profile, email, uuid, token string) { + t.Helper() + writeFile(t, filepath.Join(profile, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"access-`+token+`","refreshToken":"refresh-`+token+`","expiresAt":1,"subscriptionType":"pro","accountUuid":"`+uuid+`"}}`) + writeFile(t, filepath.Join(profile, ".claude.json"), "{\n \"numStartups\": 3,\n \"oauthAccount\": {\"accountUuid\":\""+uuid+"\",\"emailAddress\":\""+email+"\",\"organizationName\":\"Org\"}\n}") +} + +func TestUseAccountMovesTheHomesChatsToTheNewAccountQuota(t *testing.T) { + chat := directoryChat(t) + var logs bytes.Buffer + log.SetOutput(&logs) + defer log.SetOutput(os.Stderr) + profile := t.TempDir() + directory := t.TempDir() + writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n") + writeFile(t, filepath.Join(directory, ".envrc.allowed"), "") + writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`) + ctx := context.Background() + + writeLogin(t, profile, "a@example.invalid", "uuid-a", "a1") + if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, ""); err != nil { + t.Fatal(err) + } + writeLogin(t, profile, "b@example.invalid", "uuid-b", "b1") + if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, "B"); err != nil { + t.Fatal(err) + } + + // Two chats on the home are on b, which is out of quota; a third chat + // elsewhere is on another account. + oldKey := accountKeyFor("b@example.invalid", "Org") + limited := &protocol.ChatAccountUsage{Harness: quotaHarness, Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: 100, ResetsAt: 1}}} + chat.quotas = map[string]*protocol.ChatAccountUsage{oldKey: limited} + here := chat.sessionFor("11111111-1111-4111-8111-111111111111", directory) + alsoHere := chat.sessionFor("22222222-2222-4222-8222-222222222222", directory) + elsewhere := chat.sessionFor("33333333-3333-4333-8333-333333333333", t.TempDir()) + for _, s := range []*session{here, alsoHere} { + s.account = accountIdentity{key: oldKey, plan: "pro"} + } + elsewhere.account = accountIdentity{key: "other"} + frames := subscribe(t, chat, here.id) + + list, err := chat.ClaudeAccounts(ctx, here.id, "", protocol.ClaudeAccountUse, "a@example.invalid") + if err != nil { + t.Fatal(err) + } + if list.Active == nil || list.Active.Email != "a@example.invalid" || list.Usage == nil || list.Usage.SwitchedAt == 0 || len(list.Usage.Windows) != 0 { + t.Fatalf("use reply = %+v usage=%+v", list, list.Usage) + } + newKey := accountKeyFor("a@example.invalid", "Org") + if here.account.key != newKey || alsoHere.account.key != newKey || elsewhere.account.key != "other" { + t.Fatalf("keys = %q %q %q", here.account.key, alsoHere.account.key, elsewhere.account.key) + } + pushed := waitFrame(t, frames, "switched usage", func(frame protocol.ChatEventFrame) bool { + return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && frame.Usage.Account.SwitchedAt != 0 + }).Usage.Account + if len(pushed.Windows) != 0 { + t.Fatalf("the new account inherited the old quota: %+v", pushed) + } + data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json")) + if !strings.Contains(string(data), "refresh-a1") { + t.Fatal("credentials not switched") + } + for _, secret := range []string{"access-", "refresh-"} { + if strings.Contains(logs.String(), secret) { + t.Fatalf("log carries a token: %s", logs.String()) + } + } + + // A later quota report on the new account keeps the switch. + known := mergeRateLimit(chat.quotas[newKey], []byte(`{"rateLimitType":"five_hour","utilization":0.2,"resetsAt":1900000000}`), "pro", time.Now()) + if known == nil || known.SwitchedAt != pushed.SwitchedAt { + t.Fatalf("merge dropped the switch: %+v", known) + } +} + +func TestAccountsRefusedWithoutAClaudeHome(t *testing.T) { + chat := directoryChat(t) + t.Setenv("CLAUDE_CONFIG_DIR", "") + os.Unsetenv("CLAUDE_CONFIG_DIR") + if _, err := chat.ClaudeAccounts(context.Background(), "s", t.TempDir(), protocol.ClaudeAccounts, ""); err != ErrNoConfigDir { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/claude/quota.go b/internal/claude/quota.go index c3c19cbb..6c7ae464 100644 --- a/internal/claude/quota.go +++ b/internal/claude/quota.go @@ -123,8 +123,13 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl return nil } next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()} - if next.Plan == "" && previous != nil { - next.Plan = previous.Plan + if previous != nil { + if next.Plan == "" { + next.Plan = previous.Plan + } + // A switch stays recorded: the refusal it cleared is still in the + // transcript. + next.SwitchedAt = previous.SwitchedAt } for _, entry := range quotaWindowOrder { if w, ok := windows[entry.id]; ok { diff --git a/internal/claudeaccounts/files.go b/internal/claudeaccounts/files.go new file mode 100644 index 00000000..de0dd89a --- /dev/null +++ b/internal/claudeaccounts/files.go @@ -0,0 +1,215 @@ +package claudeaccounts + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "time" +) + +// writeAtomic replaces path with data through a temporary file in the same +// directory and a rename, so a reader (a running Claude Code) sees either the +// old file or the new one, never a partial write. The file keeps the mode of +// the file it replaces (mode when there is none). Claude Code opens its +// credentials with O_NOFOLLOW, so a symlinked file is refused rather than +// replaced by a regular file behind the operator's back. +func writeAtomic(path string, data []byte, mode fs.FileMode) error { + if info, err := os.Lstat(path); err == nil { + if info.Mode()&fs.ModeSymlink != 0 { + return fmt.Errorf("%s is a symbolic link; refusing to replace it", filepath.Base(path)) + } + mode = info.Mode().Perm() + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".pipelines-*") + if err != nil { + return err + } + name := tmp.Name() + done := false + defer func() { + if !done { + _ = os.Remove(name) + } + }() + if err := tmp.Chmod(mode); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(name, path); err != nil { + return err + } + done = true + return nil +} + +type jsonRaw = json.RawMessage + +// orderedObject is a JSON object whose keys keep their file order, so a +// read-modify-write of .claude.json changes one key and leaves the rest +// exactly as Claude Code wrote them. +type orderedObject struct { + keys []string + values map[string]json.RawMessage +} + +func parseObject(data []byte) (*orderedObject, error) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + tok, err := dec.Token() + if err != nil { + return nil, err + } + if delim, ok := tok.(json.Delim); !ok || delim != '{' { + return nil, errors.New("not a JSON object") + } + obj := &orderedObject{values: map[string]json.RawMessage{}} + for dec.More() { + tok, err := dec.Token() + if err != nil { + return nil, err + } + key, ok := tok.(string) + if !ok { + return nil, errors.New("invalid JSON object key") + } + var raw json.RawMessage + if err := dec.Decode(&raw); err != nil { + return nil, err + } + if _, seen := obj.values[key]; !seen { + obj.keys = append(obj.keys, key) + } + obj.values[key] = raw + } + if _, err := dec.Token(); err != nil { + return nil, err + } + return obj, nil +} + +func (o *orderedObject) get(key string) json.RawMessage { return o.values[key] } + +func (o *orderedObject) set(key string, value json.RawMessage) { + if _, seen := o.values[key]; !seen { + o.keys = append(o.keys, key) + } + o.values[key] = value +} + +// encode writes the object compactly, or with Claude Code's two-space +// indentation when indent is set. +func (o *orderedObject) encode(indent bool) ([]byte, error) { + var buf bytes.Buffer + buf.WriteByte('{') + for i, key := range o.keys { + if i > 0 { + buf.WriteByte(',') + } + name, err := marshal(key) + if err != nil { + return nil, err + } + buf.Write(name) + buf.WriteByte(':') + buf.Write(o.values[key]) + } + buf.WriteByte('}') + var out bytes.Buffer + if indent { + if err := json.Indent(&out, buf.Bytes(), "", " "); err != nil { + return nil, err + } + } else if err := json.Compact(&out, buf.Bytes()); err != nil { + return nil, err + } + return out.Bytes(), nil +} + +// marshal encodes v without HTML escaping, as JSON.stringify does. +func marshal(v any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimRight(buf.Bytes(), "\n"), nil +} + +// dirLock is one proper-lockfile style lock: a directory whose existence is +// the lock and whose mtime is its heartbeat. Claude Code takes +// /.oauth_refresh.lock while it refreshes a token, +// /.storage-write.lock around every credential write and +// /.claude.json.lock around every .claude.json rewrite; holding all +// three keeps a concurrent refresh or config save from writing the old +// account back over a switch. + +type dirLock struct { + path string + stale time.Duration +} + +// lockWait bounds how long a switch waits for Claude Code to finish a +// refresh or config save. It outlasts the config lock's ten-second staleness, +// since a `claude` command that exits mid-save (as `claude auth status` does) +// leaves that lock behind. Tests shorten it. +var lockWait = 12 * time.Second + +func acquire(locks []dirLock, wait time.Duration) (func(), error) { + var held []string + release := func() { + for i := len(held) - 1; i >= 0; i-- { + _ = os.Remove(held[i]) + } + } + for _, lock := range locks { + if err := lock.acquire(wait); err != nil { + release() + return nil, err + } + held = append(held, lock.path) + } + return release, nil +} + +var errLocked = errors.New("Claude Code is updating this login right now; try again in a moment") + +func (l dirLock) acquire(wait time.Duration) error { + deadline := time.Now().Add(wait) + for { + err := os.Mkdir(l.path, 0o700) + if err == nil { + return nil + } + if !errors.Is(err, fs.ErrExist) { + return err + } + if info, statErr := os.Stat(l.path); statErr == nil && time.Since(info.ModTime()) > l.stale { + // An abandoned lock (its owner stopped updating it) is taken over + // the way proper-lockfile does. + _ = os.Remove(l.path) + continue + } + if time.Now().After(deadline) { + return errLocked + } + time.Sleep(100 * time.Millisecond) + } +} diff --git a/internal/claudeaccounts/operations.go b/internal/claudeaccounts/operations.go new file mode 100644 index 00000000..74723a08 --- /dev/null +++ b/internal/claudeaccounts/operations.go @@ -0,0 +1,302 @@ +package claudeaccounts + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// ErrNoLogin is returned when the config directory has no Claude subscription +// login to save. +var ErrNoLogin = errors.New("this Claude home has no subscription login; sign in with /login first") + +// List reports the saved accounts and the active login. It also writes the +// active login's current tokens back to its own slot, since Claude Code +// rotates them on refresh. +func (s Store) List() (protocol.ClaudeAccountList, error) { + if err := s.check(); err != nil { + return protocol.ClaudeAccountList{}, err + } + // Listing waits only briefly; the write-back can wait for the next call. + release, err := acquire(s.locks(), time.Second) + if err != nil { + return s.list() + } + defer release() + current, err := s.current() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + if err := s.syncBack(current); err != nil { + return protocol.ClaudeAccountList{}, err + } + return s.list() +} + +func (s Store) list() (protocol.ClaudeAccountList, error) { + out := protocol.ClaudeAccountList{ConfigDir: s.ConfigDir, Accounts: []protocol.ClaudeAccount{}} + current, err := s.current() + if err != nil { + return out, err + } + slots, err := s.slots() + if err != nil { + return out, err + } + for _, sl := range slots { + account := sl.login.describe(sl.name, true) + if current.same(sl.login) { + account.Active = true + // The active login's own record is the fresher description. + active := current.describe(sl.name, true) + active.Active = true + out.Active = &active + account = active + } + out.Accounts = append(out.Accounts, account) + } + if out.Active == nil && current != nil { + active := current.describe("", false) + active.Active = true + out.Active = &active + } + return out, nil +} + +// syncBack rewrites the slot of the active login with its current tokens +// and account record when they changed. +func (s Store) syncBack(current *login) error { + if current == nil { + return nil + } + slots, err := s.slots() + if err != nil { + return err + } + for _, sl := range slots { + if !current.same(sl.login) { + continue + } + if bytes.Equal(sl.login.oauth, current.oauth) && bytes.Equal(sl.login.account, current.account) { + return nil + } + return s.writeSlot(sl.slug, sl.name, current) + } + return nil +} + +// keepCurrent saves an active login that has no slot yet under its email, +// so switching away never discards a login. +func (s Store) keepCurrent(current *login) error { + if current == nil { + return nil + } + slots, err := s.slots() + if err != nil { + return err + } + for _, sl := range slots { + if current.same(sl.login) { + return nil + } + } + slug := slugify(current.email) + if _, err := os.Stat(filepath.Join(s.slotsDir(), slug)); err == nil || slug == "" { + return fmt.Errorf("the current login %s is not saved and its name is taken; save it under another name first", current.email) + } + return s.writeSlot(slug, current.email, current) +} + +// find returns the slot named by name: its name, slug or email. +func find(slots []slot, name string) (slot, bool) { + name = strings.TrimSpace(name) + for _, match := range []func(slot) bool{ + func(sl slot) bool { return sl.name == name }, + func(sl slot) bool { return strings.EqualFold(sl.name, name) }, + func(sl slot) bool { return sl.slug == slugify(name) }, + func(sl slot) bool { return strings.EqualFold(sl.login.email, name) }, + } { + for _, sl := range slots { + if match(sl) { + return sl, true + } + } + } + return slot{}, false +} + +// Save snapshots the active login as the saved account name ("" uses its +// email). Saving an account that already has a slot renames that slot. +func (s Store) Save(name string) (protocol.ClaudeAccountList, error) { + if err := s.check(); err != nil { + return protocol.ClaudeAccountList{}, err + } + release, err := acquire(s.locks(), lockWait) + if err != nil { + return protocol.ClaudeAccountList{}, err + } + defer release() + current, err := s.current() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + if current == nil { + return protocol.ClaudeAccountList{}, ErrNoLogin + } + name = strings.TrimSpace(name) + if name == "" { + name = current.email + } + slug := slugify(name) + if slug == "" { + return protocol.ClaudeAccountList{}, fmt.Errorf("%q is not a usable account name", name) + } + slots, err := s.slots() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + for _, sl := range slots { + if sl.slug == slug && !current.same(sl.login) { + return protocol.ClaudeAccountList{}, fmt.Errorf("%q already names %s; remove it first", sl.name, sl.login.email) + } + } + if err := s.writeSlot(slug, name, current); err != nil { + return protocol.ClaudeAccountList{}, err + } + for _, sl := range slots { + if sl.slug != slug && current.same(sl.login) { + if err := os.RemoveAll(filepath.Join(s.slotsDir(), sl.slug)); err != nil { + return protocol.ClaudeAccountList{}, err + } + } + } + return s.list() +} + +// Use makes the saved account name the active login. The active login's +// refreshed tokens are first written back to its own slot (a login with no +// slot is saved under its email, so it is never lost); then the target's +// .claude.json oauthAccount and .credentials.json claudeAiOauth replace the +// active ones (each file atomically, every other key kept), after the +// organization caches `/login` also drops. The credentials file is written +// last: its new mtime is what tells running Claude Code processes to reload. +func (s Store) Use(name string) (protocol.ClaudeAccountList, error) { + if err := s.check(); err != nil { + return protocol.ClaudeAccountList{}, err + } + release, err := acquire(s.locks(), lockWait) + if err != nil { + return protocol.ClaudeAccountList{}, err + } + defer release() + slots, err := s.slots() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + target, ok := find(slots, name) + if !ok { + return protocol.ClaudeAccountList{}, fmt.Errorf("no saved Claude account %q", strings.TrimSpace(name)) + } + current, err := s.current() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + if err := s.syncBack(current); err != nil { + return protocol.ClaudeAccountList{}, err + } + if current.same(target.login) { + return s.list() + } + if err := s.keepCurrent(current); err != nil { + return protocol.ClaudeAccountList{}, err + } + if err := s.install(target.login); err != nil { + return protocol.ClaudeAccountList{}, err + } + return s.list() +} + +func (s Store) install(target *login) error { + configPath := filepath.Join(s.ConfigDir, configFile) + credsPath := filepath.Join(s.ConfigDir, credentialsFile) + configBefore, err := os.ReadFile(configPath) + if err != nil && !os.IsNotExist(err) { + return err + } + config := &orderedObject{values: map[string]jsonRaw{}} + if len(configBefore) > 0 { + if config, err = parseObject(configBefore); err != nil { + return fmt.Errorf("%s is not valid JSON", configFile) + } + } + creds, err := readObject(credsPath) + if err != nil { + return err + } + if creds == nil { + creds = &orderedObject{values: map[string]jsonRaw{}} + } + config.set(accountKey, target.account) + creds.set(oauthKey, target.oauth) + configData, err := config.encode(true) + if err != nil { + return err + } + credsData, err := creds.encode(false) + if err != nil { + return err + } + for _, cache := range orgCaches { + if err := os.Remove(filepath.Join(s.ConfigDir, cache)); err != nil && !os.IsNotExist(err) { + return err + } + } + if err := writeAtomic(configPath, configData, 0o600); err != nil { + return err + } + if err := writeAtomic(credsPath, credsData, 0o600); err != nil { + // Leave the directory consistent: the old account record goes back + // with the old credentials still in place. + if len(configBefore) > 0 { + _ = writeAtomic(configPath, configBefore, 0o600) + } + return err + } + return nil +} + +// Remove deletes the saved account name. The active login is not changed. +func (s Store) Remove(name string) (protocol.ClaudeAccountList, error) { + if err := s.check(); err != nil { + return protocol.ClaudeAccountList{}, err + } + slots, err := s.slots() + if err != nil { + return protocol.ClaudeAccountList{}, err + } + target, ok := find(slots, name) + if !ok { + return protocol.ClaudeAccountList{}, fmt.Errorf("no saved Claude account %q", strings.TrimSpace(name)) + } + if err := os.RemoveAll(filepath.Join(s.slotsDir(), target.slug)); err != nil { + return protocol.ClaudeAccountList{}, err + } + return s.list() +} + +// Identity is the account key the CLI's initialize response would report for +// the active login (email, organization name, plan), or ok false when signed +// out. The chat adapter keys account quota by it. +func (s Store) Identity() (email, organization, plan string, ok bool) { + current, err := s.current() + if err != nil || current == nil { + return "", "", "", false + } + return current.email, current.orgName, current.plan, true +} diff --git a/internal/claudeaccounts/store.go b/internal/claudeaccounts/store.go new file mode 100644 index 00000000..89014d90 --- /dev/null +++ b/internal/claudeaccounts/store.go @@ -0,0 +1,285 @@ +// Package claudeaccounts saves and switches the Claude subscription login of +// one Claude Code home (CLAUDE_CONFIG_DIR). +// +// A login is two things Claude Code's own `/login` writes in that directory: +// the claudeAiOauth entry of .credentials.json (tokens, plan, account uuid) +// and the oauthAccount object of .claude.json (email, organization). `/login` +// also drops the organization's cached policy limits and remote managed +// settings, which Claude Code fetches again for the new account. Running +// Claude Code processes watch the credentials file's mtime and reload it +// before their next request, so changing these files in place switches them +// without a restart, exactly as a terminal `/login` does. +// +// Saved accounts are slots under /pipelines-accounts// (0700), +// each holding that account's claudeAiOauth (credentials.json), oauthAccount +// (account.json) and its name (slot.json), all 0600. Nothing here returns or +// logs a token. +package claudeaccounts + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// SlotsDir is the directory under the config directory holding saved accounts. +const SlotsDir = "pipelines-accounts" + +const ( + credentialsFile = ".credentials.json" + configFile = ".claude.json" + oauthKey = "claudeAiOauth" + accountKey = "oauthAccount" +) + +// orgCaches are the per-organization caches `/login` deletes so Claude Code +// fetches them again for the new account. +var orgCaches = []string{ + "policy-limits.json", "policy-limits.json.stamp.json", "policy-limits.json.signature.json", + "remote-settings.json", "remote-settings.json.synced-at", "remote-settings.json.signature.json", +} + +// Store is the saved accounts of one Claude Code config directory. +type Store struct { + ConfigDir string +} + +// login is one Claude login: the raw credential and account objects and the +// identity read from them. +type login struct { + oauth json.RawMessage + account json.RawMessage + uuid string + email string + orgUUID string + orgName string + plan string +} + +func (l *login) describe(name string, saved bool) protocol.ClaudeAccount { + if name == "" { + name = l.email + } + return protocol.ClaudeAccount{Name: name, Email: l.email, Organization: l.orgName, Plan: l.plan, Saved: saved} +} + +// same reports whether two logins are the same account: by account uuid when +// both have one, else by email and organization. Tokens are never compared. +func (l *login) same(other *login) bool { + if l == nil || other == nil { + return false + } + if l.uuid != "" && other.uuid != "" { + return l.uuid == other.uuid && (l.orgUUID == "" || other.orgUUID == "" || l.orgUUID == other.orgUUID) + } + return l.email != "" && strings.EqualFold(l.email, other.email) && l.orgUUID == other.orgUUID +} + +func decodeLogin(oauth, account json.RawMessage) (*login, error) { + var creds struct { + RefreshToken string `json:"refreshToken"` + SubscriptionType string `json:"subscriptionType"` + AccountUUID string `json:"accountUuid"` + OrganizationUUID string `json:"organizationUuid"` + } + if len(oauth) == 0 || string(oauth) == "null" || json.Unmarshal(oauth, &creds) != nil || creds.RefreshToken == "" { + return nil, errors.New("no Claude subscription login") + } + var info struct { + AccountUUID string `json:"accountUuid"` + EmailAddress string `json:"emailAddress"` + OrganizationUUID string `json:"organizationUuid"` + OrganizationName string `json:"organizationName"` + } + if len(account) == 0 || string(account) == "null" || json.Unmarshal(account, &info) != nil || info.EmailAddress == "" { + return nil, errors.New("the login names no account") + } + if creds.AccountUUID != "" && info.AccountUUID != "" && creds.AccountUUID != info.AccountUUID { + return nil, errors.New("the login's credentials and account record name different accounts; sign in again with /login") + } + l := &login{oauth: oauth, account: account, uuid: info.AccountUUID, email: info.EmailAddress, + orgUUID: info.OrganizationUUID, orgName: info.OrganizationName, plan: creds.SubscriptionType} + if l.uuid == "" { + l.uuid = creds.AccountUUID + } + if l.orgUUID == "" { + l.orgUUID = creds.OrganizationUUID + } + return l, nil +} + +// current reads the active login, or nil when the directory is signed out. +func (s Store) current() (*login, error) { + creds, err := readObject(filepath.Join(s.ConfigDir, credentialsFile)) + if err != nil { + return nil, err + } + config, err := readObject(filepath.Join(s.ConfigDir, configFile)) + if err != nil { + return nil, err + } + if creds == nil || config == nil { + return nil, nil + } + l, err := decodeLogin(creds.get(oauthKey), config.get(accountKey)) + if err != nil { + return nil, nil + } + return l, nil +} + +// readObject reads a JSON object file, or nil when it does not exist. +func readObject(path string) (*orderedObject, error) { + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + obj, err := parseObject(data) + if err != nil { + return nil, fmt.Errorf("%s is not valid JSON", filepath.Base(path)) + } + return obj, nil +} + +// slot is one saved account. +type slot struct { + slug string + name string + login *login +} + +func (s Store) slotsDir() string { return filepath.Join(s.ConfigDir, SlotsDir) } + +func (s Store) slots() ([]slot, error) { + entries, err := os.ReadDir(s.slotsDir()) + if errors.Is(err, fs.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []slot + for _, entry := range entries { + if !entry.IsDir() || entry.Name() != slugify(entry.Name()) { + continue + } + if sl, err := s.readSlot(entry.Name()); err == nil { + out = append(out, sl) + } + } + sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i].name) < strings.ToLower(out[j].name) }) + return out, nil +} + +func (s Store) readSlot(slug string) (slot, error) { + dir := filepath.Join(s.slotsDir(), slug) + creds, err := readObject(filepath.Join(dir, "credentials.json")) + if err != nil || creds == nil { + return slot{}, errors.New("missing credentials") + } + account, err := os.ReadFile(filepath.Join(dir, "account.json")) + if err != nil { + return slot{}, err + } + l, err := decodeLogin(creds.get(oauthKey), account) + if err != nil { + return slot{}, err + } + var meta struct { + Name string `json:"name"` + } + if data, err := os.ReadFile(filepath.Join(dir, "slot.json")); err == nil { + _ = json.Unmarshal(data, &meta) + } + if meta.Name == "" { + meta.Name = l.email + } + return slot{slug: slug, name: meta.Name, login: l}, nil +} + +// writeSlot stores l under slug with 0700/0600 permissions. +func (s Store) writeSlot(slug, name string, l *login) error { + for _, dir := range []string{s.slotsDir(), filepath.Join(s.slotsDir(), slug)} { + if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { + return err + } + if err := os.Chmod(dir, 0o700); err != nil { + return err + } + } + dir := filepath.Join(s.slotsDir(), slug) + creds := &orderedObject{values: map[string]json.RawMessage{}} + creds.set(oauthKey, l.oauth) + credsData, err := creds.encode(false) + if err != nil { + return err + } + meta, err := marshal(map[string]any{"name": name, "saved_at": time.Now().UnixMilli()}) + if err != nil { + return err + } + for file, data := range map[string][]byte{"credentials.json": credsData, "account.json": l.account, "slot.json": meta} { + path := filepath.Join(dir, file) + if err := writeAtomic(path, data, 0o600); err != nil { + return err + } + if err := os.Chmod(path, 0o600); err != nil { + return err + } + } + return nil +} + +// slugify makes a slot directory name: lower case letters, digits and +// @ . _ + -, other runs replaced by "-". +func slugify(name string) string { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(strings.TrimSpace(name)) { + ok := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || strings.ContainsRune("@._+-", r) + if ok { + b.WriteRune(r) + dash = false + } else if !dash { + b.WriteByte('-') + dash = true + } + } + slug := strings.Trim(b.String(), "-.") + if len(slug) > 100 { + slug = slug[:100] + } + return slug +} + +func (s Store) locks() []dirLock { + return []dirLock{ + {path: filepath.Join(s.ConfigDir, ".oauth_refresh.lock"), stale: time.Minute}, + {path: filepath.Join(s.ConfigDir, ".storage-write.lock"), stale: 15 * time.Second}, + // Claude Code rewrites .claude.json under this lock (proper-lockfile's + // default ten-second staleness), re-reading it first. + {path: filepath.Join(s.ConfigDir, configFile+".lock"), stale: 10 * time.Second}, + } +} + +func (s Store) check() error { + if s.ConfigDir == "" || !filepath.IsAbs(s.ConfigDir) { + return errors.New("no Claude config directory") + } + info, err := os.Stat(s.ConfigDir) + if err != nil || !info.IsDir() { + return fmt.Errorf("the Claude config directory %s does not exist", s.ConfigDir) + } + return nil +} diff --git a/internal/claudeaccounts/store_test.go b/internal/claudeaccounts/store_test.go new file mode 100644 index 00000000..bad1790b --- /dev/null +++ b/internal/claudeaccounts/store_test.go @@ -0,0 +1,356 @@ +package claudeaccounts + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" +) + +// fakeLogin writes a login the way Claude Code's /login leaves it: tokens in +// .credentials.json (beside an MCP OAuth entry it must keep) and the account +// in .claude.json among unrelated keys. +func fakeLogin(t *testing.T, dir, who, uuid, token string) { + t.Helper() + creds := map[string]any{ + "claudeAiOauth": map[string]any{ + "accessToken": "access-" + token, "refreshToken": "refresh-" + token, + "expiresAt": 1, "scopes": []string{"user:inference"}, "subscriptionType": "max", + "accountUuid": uuid, "organizationUuid": "org-" + uuid, + }, + "mcpOAuth": map[string]any{"server": map[string]any{"accessToken": "mcp-secret"}}, + } + writeJSON(t, filepath.Join(dir, ".credentials.json"), creds, false) + config := map[string]any{} + if data, err := os.ReadFile(filepath.Join(dir, ".claude.json")); err == nil { + if err := json.Unmarshal(data, &config); err != nil { + t.Fatal(err) + } + } else { + config = map[string]any{"numStartups": 4, "projects": map[string]any{"/x": map[string]any{"allowedTools": []any{}}}, "userID": "device"} + } + config["oauthAccount"] = map[string]any{"accountUuid": uuid, "emailAddress": who, "organizationUuid": "org-" + uuid, "organizationName": "Org " + uuid} + writeJSON(t, filepath.Join(dir, ".claude.json"), config, true) +} + +func writeJSON(t *testing.T, path string, v any, indent bool) { + t.Helper() + var data []byte + var err error + if indent { + data, err = json.MarshalIndent(v, "", " ") + } else { + data, err = json.Marshal(v) + } + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } +} + +func readJSON(t *testing.T, path string) map[string]any { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var out map[string]any + if err := json.Unmarshal(data, &out); err != nil { + t.Fatalf("%s: %v", path, err) + } + return out +} + +func activeRefresh(t *testing.T, dir string) string { + t.Helper() + return readJSON(t, filepath.Join(dir, ".credentials.json"))["claudeAiOauth"].(map[string]any)["refreshToken"].(string) +} + +func scratch(t *testing.T) (Store, string) { + t.Helper() + dir := t.TempDir() + return Store{ConfigDir: dir}, dir +} + +func noTokens(t *testing.T, v any) { + t.Helper() + data, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + for _, secret := range []string{"access-", "refresh-", "mcp-secret", "accessToken", "refreshToken"} { + if strings.Contains(string(data), secret) { + t.Fatalf("reply carries %q: %s", secret, data) + } + } +} + +func TestSaveUseRotateBackAndRemove(t *testing.T) { + store, dir := scratch(t) + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + list, err := store.Save("") + if err != nil { + t.Fatal(err) + } + noTokens(t, list) + if len(list.Accounts) != 1 || list.Accounts[0].Name != "a@example.invalid" || !list.Accounts[0].Active || list.Active == nil || !list.Active.Saved { + t.Fatalf("after save a: %+v", list) + } + // A terminal /login switches to b; it is the active, unsaved login. + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1") + list, err = store.List() + if err != nil { + t.Fatal(err) + } + if list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved || list.Accounts[0].Active { + t.Fatalf("list with unsaved b: %+v", list) + } + if _, err := store.Save("Work B"); err != nil { + t.Fatal(err) + } + // b's tokens rotate on refresh while it is active. + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b2") + + list, err = store.Use("a@example.invalid") + if err != nil { + t.Fatal(err) + } + noTokens(t, list) + if list.Active == nil || list.Active.Email != "a@example.invalid" || activeRefresh(t, dir) != "refresh-a1" { + t.Fatalf("after use a: %+v refresh=%s", list, activeRefresh(t, dir)) + } + config := readJSON(t, filepath.Join(dir, ".claude.json")) + if config["oauthAccount"].(map[string]any)["emailAddress"] != "a@example.invalid" || config["userID"] != "device" || config["numStartups"].(float64) != 4 || config["projects"] == nil { + t.Fatalf("config after use = %v", config) + } + creds := readJSON(t, filepath.Join(dir, ".credentials.json")) + if creds["mcpOAuth"] == nil { + t.Fatalf("other credentials dropped: %v", creds) + } + // The rotated b2 tokens were written back to b's slot, so switching back + // installs them, not the stale b1. + if _, err := store.Use("work b"); err != nil { + t.Fatal(err) + } + if got := activeRefresh(t, dir); got != "refresh-b2" { + t.Fatalf("switched back to %s, want the rotated refresh-b2", got) + } + + list, err = store.Remove("Work B") + if err != nil { + t.Fatal(err) + } + if len(list.Accounts) != 1 || list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved { + t.Fatalf("after remove: %+v", list) + } + if _, err := os.Stat(filepath.Join(dir, SlotsDir, "work-b")); !os.IsNotExist(err) { + t.Fatalf("slot still present: %v", err) + } +} + +func TestUseKeepsAnUnsavedLogin(t *testing.T) { + store, dir := scratch(t) + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + if _, err := store.Save("a"); err != nil { + t.Fatal(err) + } + // A terminal /login to c, never saved, then a switch back to a. + fakeLogin(t, dir, "c@example.invalid", "uuid-c", "c1") + list, err := store.Use("a") + if err != nil { + t.Fatal(err) + } + if len(list.Accounts) != 2 || list.Accounts[1].Email != "c@example.invalid" || list.Accounts[1].Active { + t.Fatalf("the unsaved login was not kept: %+v", list.Accounts) + } + if _, err := store.Use("c@example.invalid"); err != nil || activeRefresh(t, dir) != "refresh-c1" { + t.Fatalf("switch back to the kept login: %v", err) + } +} + +func TestPermissionsCachesAndFormat(t *testing.T) { + old := syscall.Umask(0o022) + defer syscall.Umask(old) + store, dir := scratch(t) + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + if _, err := store.Save("a"); err != nil { + t.Fatal(err) + } + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1") + if err := os.Chmod(filepath.Join(dir, ".claude.json"), 0o640); err != nil { + t.Fatal(err) + } + for _, cache := range orgCaches { + writeJSON(t, filepath.Join(dir, cache), map[string]any{}, false) + } + keep := filepath.Join(dir, "settings.json") + writeJSON(t, keep, map[string]any{}, false) + before, _ := os.Stat(filepath.Join(dir, ".credentials.json")) + time.Sleep(10 * time.Millisecond) + if _, err := store.Use("a"); err != nil { + t.Fatal(err) + } + for path, want := range map[string]os.FileMode{ + filepath.Join(dir, SlotsDir): 0o700, + filepath.Join(dir, SlotsDir, "a"): 0o700, + filepath.Join(dir, SlotsDir, "a", "credentials.json"): 0o600, + filepath.Join(dir, SlotsDir, "a", "account.json"): 0o600, + filepath.Join(dir, SlotsDir, "a", "slot.json"): 0o600, + filepath.Join(dir, ".credentials.json"): 0o600, + filepath.Join(dir, ".claude.json"): 0o640, + } { + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != want { + t.Fatalf("%s mode %v, want %v", path, info.Mode().Perm(), want) + } + } + after, _ := os.Stat(filepath.Join(dir, ".credentials.json")) + if !after.ModTime().After(before.ModTime()) { + t.Fatal("credentials mtime did not move; running Claude Code would not reload") + } + for _, cache := range orgCaches { + if _, err := os.Stat(filepath.Join(dir, cache)); !os.IsNotExist(err) { + t.Fatalf("%s kept after a switch", cache) + } + } + if _, err := os.Stat(keep); err != nil { + t.Fatal("an unrelated file was removed") + } + data, _ := os.ReadFile(filepath.Join(dir, ".claude.json")) + if !strings.HasPrefix(string(data), "{\n \"") { + t.Fatalf(".claude.json lost Claude Code's indentation: %.40q", data) + } + entries, _ := os.ReadDir(dir) + for _, entry := range entries { + if strings.Contains(entry.Name(), ".pipelines-") || strings.HasSuffix(entry.Name(), ".lock") { + t.Fatalf("left behind %s", entry.Name()) + } + } +} + +func TestClaudeJSONKeyOrderAndValuesKept(t *testing.T) { + store, dir := scratch(t) + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + if _, err := store.Save(""); err != nil { + t.Fatal(err) + } + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1") + raw := "{\n \"zeta\": 1,\n \"oauthAccount\": " + string(mustRead(t, filepath.Join(dir, ".claude.json"), "oauthAccount")) + + ",\n \"alpha\": {\n \"big\": 12345678901234567890,\n \"html\": \"\"\n }\n}" + if err := os.WriteFile(filepath.Join(dir, ".claude.json"), []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + if _, err := store.Use("a@example.invalid"); err != nil { + t.Fatal(err) + } + got := string(mustReadFile(t, filepath.Join(dir, ".claude.json"))) + if !(strings.Index(got, "zeta") < strings.Index(got, "oauthAccount") && strings.Index(got, "oauthAccount") < strings.Index(got, "alpha")) { + t.Fatalf("key order changed: %s", got) + } + if !strings.Contains(got, "12345678901234567890") || !strings.Contains(got, `""`) { + t.Fatalf("values rewritten: %s", got) + } +} + +func mustReadFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return data +} + +func mustRead(t *testing.T, path, key string) json.RawMessage { + t.Helper() + obj, err := parseObject(mustReadFile(t, path)) + if err != nil { + t.Fatal(err) + } + return obj.get(key) +} + +func TestRefusals(t *testing.T) { + store, dir := scratch(t) + if _, err := store.Save(""); err != ErrNoLogin { + t.Fatalf("save while signed out: %v", err) + } + if _, err := (Store{ConfigDir: "relative"}).List(); err == nil { + t.Fatal("a relative config dir was accepted") + } + if _, err := (Store{ConfigDir: filepath.Join(dir, "missing")}).List(); err == nil { + t.Fatal("a missing config dir was accepted") + } + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + if _, err := store.Use("nobody"); err == nil || !strings.Contains(err.Error(), "no saved Claude account") { + t.Fatalf("use unknown: %v", err) + } + if _, err := store.Save("!!!"); err == nil { + t.Fatal("an unusable name was accepted") + } + if _, err := store.Save("shared"); err != nil { + t.Fatal(err) + } + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1") + if _, err := store.Save("Shared"); err == nil || !strings.Contains(err.Error(), "already names") { + t.Fatalf("a name of another account was overwritten: %v", err) + } + // A credentials file that is a symlink is not replaced. + if _, err := store.Save("b"); err != nil { + t.Fatal(err) + } + real := filepath.Join(dir, "real-creds.json") + if err := os.Rename(filepath.Join(dir, ".credentials.json"), real); err != nil { + t.Fatal(err) + } + if err := os.Symlink(real, filepath.Join(dir, ".credentials.json")); err != nil { + t.Fatal(err) + } + before := mustReadFile(t, filepath.Join(dir, ".claude.json")) + if _, err := store.Use("shared"); err == nil { + t.Fatal("a symlinked credentials file was replaced") + } + if string(mustReadFile(t, filepath.Join(dir, ".claude.json"))) != string(before) { + t.Fatal(".claude.json was left naming the other account after a failed switch") + } +} + +func TestUseWaitsForAClaudeRefreshLock(t *testing.T) { + defer func(old time.Duration) { lockWait = old }(lockWait) + lockWait = 200 * time.Millisecond + store, dir := scratch(t) + fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1") + if _, err := store.Save(""); err != nil { + t.Fatal(err) + } + fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1") + lock := filepath.Join(dir, ".oauth_refresh.lock") + if err := os.Mkdir(lock, 0o700); err != nil { + t.Fatal(err) + } + if _, err := store.Use("a@example.invalid"); err != errLocked { + t.Fatalf("use under a live refresh lock: %v", err) + } + if activeRefresh(t, dir) != "refresh-b1" { + t.Fatal("switched while Claude Code held the refresh lock") + } + // An abandoned lock is taken over. + old := time.Now().Add(-2 * time.Minute) + if err := os.Chtimes(lock, old, old); err != nil { + t.Fatal(err) + } + if _, err := store.Use("a@example.invalid"); err != nil { + t.Fatal(err) + } + if activeRefresh(t, dir) != "refresh-a1" { + t.Fatal("did not switch after the stale lock") + } +} diff --git a/internal/cli/app.go b/internal/cli/app.go index d3e5a106..2911a65b 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -294,6 +294,9 @@ func (a App) Run(ctx context.Context, args []string) error { if len(args) > 0 && args[0] == "harness" { return a.harness(ctx, args[1:]) } + if len(args) > 0 && args[0] == "claude-account" { + return a.claudeAccount(ctx, args[1:]) + } if len(args) > 0 && args[0] == "--version" { args = append([]string{"version"}, args[1:]...) } diff --git a/internal/cli/claude_account.go b/internal/cli/claude_account.go new file mode 100644 index 00000000..9f43f0cc --- /dev/null +++ b/internal/cli/claude_account.go @@ -0,0 +1,113 @@ +package cli + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + + "git.a-wan.net/alan/pipelines/internal/claude" + "git.a-wan.net/alan/pipelines/internal/claudeaccounts" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +const claudeAccountUsage = "usage: pipelines claude-account list | save [name] | use | remove [--dir DIR] [--json]" + +// claudeAccount saves and switches the Claude login of the Claude home a +// directory selects (its CLAUDE_CONFIG_DIR after direnv/mise), locally and +// without a server. It changes the same files /login does, so running Claude +// Code processes there continue on the new account. +func (a App) claudeAccount(ctx context.Context, args []string) error { + f := flag.NewFlagSet("claude-account", flag.ContinueOnError) + f.SetOutput(a.Err) + dir := f.String("dir", "", "Directory whose environment selects the Claude home (default: current directory)") + jsonMode := f.Bool("json", false, "Machine-readable JSON") + if err := parse(f, args); err != nil { + if errors.Is(err, flag.ErrHelp) { + return nil + } + return err + } + pos := f.Args() + if len(pos) == 0 { + return errors.New(claudeAccountUsage) + } + directory := *dir + if directory == "" { + wd, err := os.Getwd() + if err != nil { + return err + } + directory = wd + } + directory, err := filepath.Abs(directory) + if err != nil { + return err + } + configDir, err := claude.AccountConfigDir(ctx, workenv.Default, directory, os.Environ()) + if err != nil { + return err + } + store := claudeaccounts.Store{ConfigDir: configDir} + var list protocol.ClaudeAccountList + switch { + case pos[0] == "list" && len(pos) == 1: + list, err = store.List() + case pos[0] == "save" && len(pos) <= 2: + list, err = store.Save(strings.Join(pos[1:], "")) + case pos[0] == "use" && len(pos) == 2: + list, err = store.Use(pos[1]) + case pos[0] == "remove" && len(pos) == 2: + list, err = store.Remove(pos[1]) + default: + return errors.New(claudeAccountUsage) + } + if err != nil { + return err + } + if *jsonMode { + return a.output(list) + } + fmt.Fprintf(a.Out, "Claude home: %s\n", list.ConfigDir) + if len(list.Accounts) == 0 { + fmt.Fprintln(a.Out, "No saved accounts.") + } + for _, account := range list.Accounts { + mark := " " + if account.Active { + mark = "*" + } + fmt.Fprintf(a.Out, "%s %s%s\n", mark, account.Name, accountDetail(account)) + } + if list.Active != nil && !list.Active.Saved { + fmt.Fprintf(a.Out, "* %s (signed in, not saved; pipelines claude-account save)\n", list.Active.Email) + } + if list.Active == nil { + fmt.Fprintln(a.Out, "Signed out.") + } + if pos[0] == "use" && list.Active != nil { + fmt.Fprintf(a.Out, "Switched to %s. Running Claude Code sessions continue on it.\n", list.Active.Email) + } + return nil +} + +func accountDetail(account protocol.ClaudeAccount) string { + var parts []string + if account.Email != "" && account.Email != account.Name { + parts = append(parts, account.Email) + } + if account.Organization != "" { + parts = append(parts, account.Organization) + } + if account.Plan != "" { + parts = append(parts, account.Plan) + } + if len(parts) == 0 { + return "" + } + return " (" + strings.Join(parts, ", ") + ")" +} diff --git a/internal/cli/claude_account_test.go b/internal/cli/claude_account_test.go new file mode 100644 index 00000000..4dedfe19 --- /dev/null +++ b/internal/cli/claude_account_test.go @@ -0,0 +1,78 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +func cliLogin(t *testing.T, profile, email, uuid, token string) { + t.Helper() + files := map[string]string{ + ".credentials.json": `{"claudeAiOauth":{"accessToken":"access-` + token + `","refreshToken":"refresh-` + token + `","subscriptionType":"max","accountUuid":"` + uuid + `"}}`, + ".claude.json": `{"userID":"device","oauthAccount":{"accountUuid":"` + uuid + `","emailAddress":"` + email + `","organizationName":"Org"}}`, + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(profile, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } +} + +func TestClaudeAccountCommandSavesAndSwitches(t *testing.T) { + profile := t.TempDir() + t.Setenv("CLAUDE_CONFIG_DIR", profile) + t.Setenv(workenv.DisableEnvKey, "off") + dir := t.TempDir() + run := func(args ...string) (string, error) { + var out, errs bytes.Buffer + err := App{Out: &out, Err: &errs}.Run(context.Background(), append([]string{"claude-account"}, args...)) + return out.String() + errs.String(), err + } + cliLogin(t, profile, "a@example.invalid", "uuid-a", "a1") + if out, err := run("save", "--dir", dir); err != nil || !strings.Contains(out, "* a@example.invalid (Org, max)") { + t.Fatalf("save a: %v\n%s", err, out) + } + cliLogin(t, profile, "b@example.invalid", "uuid-b", "b1") + if out, err := run("list", "--dir", dir); err != nil || !strings.Contains(out, " a@example.invalid") || !strings.Contains(out, "* b@example.invalid (signed in, not saved") { + t.Fatalf("list: %v\n%s", err, out) + } + if _, err := run("save", "work", "--dir", dir); err != nil { + t.Fatal(err) + } + out, err := run("use", "a@example.invalid", "--dir", dir, "--json") + if err != nil { + t.Fatalf("use: %v\n%s", err, out) + } + if strings.Contains(out, "access-") || strings.Contains(out, "refresh-") { + t.Fatalf("output carries a token: %s", out) + } + var list protocol.ClaudeAccountList + if err := json.Unmarshal([]byte(out), &list); err != nil { + t.Fatalf("json: %v\n%s", err, out) + } + if list.ConfigDir != profile || list.Active == nil || list.Active.Email != "a@example.invalid" || len(list.Accounts) != 2 { + t.Fatalf("use reply = %+v", list) + } + data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json")) + if !strings.Contains(string(data), "refresh-a1") { + t.Fatal("credentials not switched") + } + if out, err := run("remove", "work", "--dir", dir); err != nil || strings.Contains(out, "work") { + t.Fatalf("remove: %v\n%s", err, out) + } + if _, err := run("use", "--dir", dir); err == nil || !strings.Contains(err.Error(), "usage:") { + t.Fatalf("use without a name: %v", err) + } + t.Setenv("CLAUDE_CONFIG_DIR", "") + if _, err := run("list", "--dir", dir); err == nil || !strings.Contains(err.Error(), "CLAUDE_CONFIG_DIR") { + t.Fatalf("no Claude home: %v", err) + } +} diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 740e100c..06effde8 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -38,6 +38,7 @@ var usage = map[string]string{ "stats": "stats [--json]", "rpc": "rpc ", "retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]", + "claude-account": "claude-account list | save [name] | use | remove [--dir DIR] [--json]", "tui": "tui", } diff --git a/internal/cli/help.go b/internal/cli/help.go index a0d814d4..9acc1a76 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -56,6 +56,9 @@ SERVER / INTERFACE harness setup Install check, sign-in, models and verify for one harness harness list Installed / signed-in / configured / default for all four + claude-account list|save|use|remove + Save and switch the Claude login of this directory's + CLAUDE_CONFIG_DIR (--dir DIR); running sessions follow tui Open the dashboard (default with no command) serve Start native server in the foreground (Ctrl+C stops it) service enable Configure user autostart diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index e992a6c2..ad0883c1 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -799,6 +799,11 @@ type ChatAccountUsage struct { AsOf int64 `json:"as_of,omitempty"` Windows []ChatQuotaWindow `json:"windows,omitempty"` Unsupported bool `json:"unsupported,omitempty"` + // SwitchedAt is when the operator last switched the chat's Claude account + // to this one (epoch milliseconds). The report then stands for the new + // account even with no windows yet, and a usage-limit refusal the chat + // received before it no longer applies. + SwitchedAt int64 `json:"switched_at,omitempty"` } // ChatQuotaWindow is one rolling quota window. UsedPercent is 0-100 (it can diff --git a/internal/protocol/claude_accounts.go b/internal/protocol/claude_accounts.go new file mode 100644 index 00000000..110f90e6 --- /dev/null +++ b/internal/protocol/claude_accounts.go @@ -0,0 +1,57 @@ +package protocol + +// Claude account switching for a chat whose directory selects its own Claude +// Code home (CLAUDE_CONFIG_DIR, for example from a direnv .envrc). Each request +// body is ClaudeAccountRequest naming the chat; the server resolves the chat's +// directory environment to that config directory and replies with +// ClaudeAccountList. Saved accounts live in /pipelines-accounts/. +// Using one changes the same files `/login` changes, in place, so running +// Claude Code processes continue on the new account without a restart. No +// reply or log ever carries a token. +const ( + // ClaudeAccounts lists the saved accounts and the active login. + ClaudeAccounts = "claude_accounts" + // ClaudeAccountSave snapshots the active login as a saved account; Name + // defaults to its email. + ClaudeAccountSave = "claude_account_save" + // ClaudeAccountUse makes the saved account Name the active login, first + // writing the current login's refreshed tokens back to its own slot. + ClaudeAccountUse = "claude_account_use" + // ClaudeAccountRemove deletes the saved account Name. The active login is + // unchanged. + ClaudeAccountRemove = "claude_account_remove" +) + +// ClaudeAccountRequest is the body of every claude_account* request. +type ClaudeAccountRequest struct { + SessionID string `json:"session_id"` + // Name is the saved account (its name, slug or email); for a save, the + // name to save under ("" uses the email). + Name string `json:"name,omitempty"` +} + +// ClaudeAccount describes one Claude login without its credentials. +type ClaudeAccount struct { + Name string `json:"name"` + Email string `json:"email,omitempty"` + Organization string `json:"organization,omitempty"` + // Plan is the subscription type the login reports ("max", "pro"). + Plan string `json:"plan,omitempty"` + // Active is set on the account the config directory is signed in with. + Active bool `json:"active,omitempty"` + // Saved is false for an active login that has no saved slot yet. + Saved bool `json:"saved"` +} + +// ClaudeAccountList is the reply to every claude_account* request. +type ClaudeAccountList struct { + // ConfigDir is the Claude Code home the chat's directory selects. + ConfigDir string `json:"config_dir"` + // Active is the current login (saved or not); nil when signed out. + Active *ClaudeAccount `json:"active,omitempty"` + // Accounts are the saved accounts, sorted by name. + Accounts []ClaudeAccount `json:"accounts"` + // Usage is the newly active account's latest known quota after a + // claude_account_use (see ChatAccountUsage.SwitchedAt). + Usage *ChatAccountUsage `json:"usage,omitempty"` +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 166b0bfe..4f4ef957 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -250,6 +250,10 @@ type Message struct { ChatModels []ChatModel `json:"chat_models,omitempty"` // ChatCommands is the chat_commands reply: the session's slash commands. ChatCommands []ChatCommand `json:"chat_commands,omitempty"` + // ClaudeAccount is the body of the claude_account* requests and + // ClaudeAccounts their reply (claude_accounts.go). + ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"` + ClaudeAccounts *ClaudeAccountList `json:"claude_accounts,omitempty"` // ModelRequest is the chat_model body and echoed selection. ModelRequest *ChatModelRequest `json:"chat_model,omitempty"` // ChatModes is the chat_modes reply: the permission modes the session's diff --git a/internal/server/chat.go b/internal/server/chat.go index f0e40b54..0e310324 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -253,6 +253,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ChatCommands: handleChatCommands(ctx, request, broker, write) return true + case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove: + handleClaudeAccounts(ctx, request, broker, write) + return true case protocol.ChatModelSelect: handleChatModelSwitch(ctx, request, broker, write) return true diff --git a/internal/server/chat_claude_accounts.go b/internal/server/chat_claude_accounts.go new file mode 100644 index 00000000..e179a35e --- /dev/null +++ b/internal/server/chat_claude_accounts.go @@ -0,0 +1,69 @@ +package server + +import ( + "context" + "errors" + + "git.a-wan.net/alan/pipelines/internal/claude" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// chatAccountSwitcher is Claude Code's saved-account surface +// (claude.Chat.ClaudeAccounts): list, save, use and remove the logins of the +// Claude home a chat's directory selects. +type chatAccountSwitcher interface { + ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) +} + +var errNotClaudeChat = errors.New("Claude accounts apply to Claude Code chats only") + +// ClaudeAccounts routes a claude_account* request to the Claude adapter with +// the chat's recorded directory. Other harnesses are refused. +func (m *chatManager) ClaudeAccounts(ctx context.Context, sessionID, operation, name string) (protocol.ClaudeAccountList, error) { + if m.backendFor(ctx, sessionID) != claude.Backend { + return protocol.ClaudeAccountList{}, errNotClaudeChat + } + adapter, err := m.brokerFor(ctx, sessionID) + if err != nil { + return protocol.ClaudeAccountList{}, err + } + switcher, ok := adapter.(chatAccountSwitcher) + if !ok { + return protocol.ClaudeAccountList{}, errNotClaudeChat + } + directory := "" + if m.registry != nil { + if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found { + directory = row.Directory + } + } + return switcher.ClaudeAccounts(ctx, sessionID, directory, operation, name) +} + +// handleClaudeAccounts answers claude_accounts, claude_account_save, +// claude_account_use and claude_account_remove. Replies describe accounts +// only; no token ever leaves the server. +func handleClaudeAccounts(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) { + body := request.ClaudeAccount + if body == nil || !validChatSessionID(body.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"}) + return + } + if (request.Type == protocol.ClaudeAccountUse || request.Type == protocol.ClaudeAccountRemove) && body.Name == "" { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a saved account name is required"}) + return + } + switcher, ok := broker.(interface { + ClaudeAccounts(ctx context.Context, sessionID, operation, name string) (protocol.ClaudeAccountList, error) + }) + if !ok { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errNotClaudeChat.Error()}) + return + } + list, err := switcher.ClaudeAccounts(ctx, body.SessionID, request.Type, body.Name) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + _ = write(protocol.Message{Type: request.Type, ID: request.ID, ClaudeAccounts: &list}) +} diff --git a/internal/server/chat_claude_accounts_test.go b/internal/server/chat_claude_accounts_test.go new file mode 100644 index 00000000..83879fe1 --- /dev/null +++ b/internal/server/chat_claude_accounts_test.go @@ -0,0 +1,90 @@ +package server + +import ( + "context" + "encoding/json" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// accountChat is a Claude harness with saved accounts. +type accountChat struct { + *fakeChat + calls []string +} + +func (c *accountChat) ClaudeAccounts(_ context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) { + c.calls = append(c.calls, strings.Join([]string{sessionID, directory, operation, name}, "|")) + return protocol.ClaudeAccountList{ + ConfigDir: "/home/op/caplens/.claude-profile", + Active: &protocol.ClaudeAccount{Name: "b@example.invalid", Email: "b@example.invalid", Active: true, Saved: true}, + Accounts: []protocol.ClaudeAccount{ + {Name: "a@example.invalid", Email: "a@example.invalid", Plan: "max", Saved: true}, + {Name: "b@example.invalid", Email: "b@example.invalid", Active: true, Saved: true}, + }, + }, nil +} + +func TestClaudeAccountRequestsRouteToTheChatsClaudeHome(t *testing.T) { + ctx := context.Background() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + claudeID := "01900000-0000-7000-8000-000000000021" + codexID := "01900000-0000-7000-8000-000000000022" + for id, backend := range map[string]string{claudeID: "claude", codexID: "codex"} { + if err := store.RecordOperatorSession(ctx, id, "/home/op/caplens", "chat", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := store.SetOperatorSessionBackend(ctx, id, backend); err != nil { + t.Fatal(err) + } + } + claudeChat := &accountChat{fakeChat: scriptedChat()} + manager := &chatManager{claude: claudeChat, codex: scriptedChat(), registry: store, cache: map[string]string{}} + var reply protocol.Message + capture := func(msg protocol.Message) error { reply = msg; return nil } + + for _, kind := range []string{protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove} { + handled := handleChat(ctx, protocol.Message{Type: kind, ID: "r-" + kind, ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID, Name: "a@example.invalid"}}, manager, nil, store, "client", capture) + if !handled || reply.Type != kind || reply.ID != "r-"+kind || reply.ClaudeAccounts == nil || len(reply.ClaudeAccounts.Accounts) != 2 { + t.Fatalf("%s reply = %+v", kind, reply) + } + } + want := []string{ + claudeID + "|/home/op/caplens|claude_accounts|a@example.invalid", + claudeID + "|/home/op/caplens|claude_account_save|a@example.invalid", + claudeID + "|/home/op/caplens|claude_account_use|a@example.invalid", + claudeID + "|/home/op/caplens|claude_account_remove|a@example.invalid", + } + if strings.Join(claudeChat.calls, "\n") != strings.Join(want, "\n") { + t.Fatalf("calls = %v", claudeChat.calls) + } + wire, _ := json.Marshal(reply) + if !strings.Contains(string(wire), `"claude_accounts":{"config_dir":"/home/op/caplens/.claude-profile","active":{"name":"b@example.invalid"`) { + t.Fatalf("wire = %s", wire) + } + + // Other harnesses, a missing name for use/remove, and a bad id are refused. + for _, request := range []protocol.Message{ + {Type: protocol.ClaudeAccounts, ID: "x1", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: codexID}}, + {Type: protocol.ClaudeAccountUse, ID: "x2", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID}}, + {Type: protocol.ClaudeAccountRemove, ID: "x3", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID}}, + {Type: protocol.ClaudeAccounts, ID: "x4", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: "../etc"}}, + {Type: protocol.ClaudeAccounts, ID: "x5"}, + } { + handleChat(ctx, request, manager, nil, store, "client", capture) + if reply.Type != protocol.Error || reply.ID != request.ID { + t.Fatalf("%s accepted: %+v", request.ID, reply) + } + } + if len(claudeChat.calls) != 4 { + t.Fatalf("a refused request reached the harness: %v", claudeChat.calls) + } +}