From 18e0e565ca84427b6a7f9064b9646a31bd063d71 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 1 Dec 2026 00:31:31 +0000 Subject: [PATCH] App: Claude account auto-switch setting; the limit banner leaves a refusal the server is continuing alone The Claude account dialog shows 'Auto-switch account when usage runs out' (claude_account_auto_switch) when the server reports it. The usage-limit banner schedules no auto-continue while the server's auto-switch continue prompt is queued. A chat refused after another chat already switched the Claude home gets a fresh switch stamp, so its banner clears too. Co-Authored-By: Claude Opus 5.5 --- .../chat_claude_account_dialog.dart | 27 ++- .../chat_claude_accounts_controller.dart | 20 +- .../conversation/chat_usage_limit_banner.dart | 12 +- .../chat/domain/chat_claude_accounts.dart | 10 + .../chat/domain/chat_usage_limit.dart | 12 ++ .../chat_claude_auto_switch_setting_test.dart | 122 ++++++++++++ .../chat_usage_limit_auto_switch_test.dart | 183 ++++++++++++++++++ internal/claude/auto_switch.go | 6 +- internal/claude/auto_switch_test.go | 3 +- internal/server/chat_auto_switch.go | 2 +- 10 files changed, 386 insertions(+), 11 deletions(-) create mode 100644 app/test/features/chat/conversation/chat_claude_auto_switch_setting_test.dart create mode 100644 app/test/features/chat/conversation/chat_usage_limit_auto_switch_test.dart diff --git a/app/lib/features/chat/conversation/chat_claude_account_dialog.dart b/app/lib/features/chat/conversation/chat_claude_account_dialog.dart index bf18ba31..46159065 100644 --- a/app/lib/features/chat/conversation/chat_claude_account_dialog.dart +++ b/app/lib/features/chat/conversation/chat_claude_account_dialog.dart @@ -33,8 +33,9 @@ void _failed(ScaffoldMessengerState? messenger, Object error, String 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 +/// home with the active one checked (one tap switches), "Save current +/// account…" for the active login and the home's "Auto-switch account when +/// usage runs out" choice. A dialog on a wide app, a bottom sheet on /// a phone. Future showChatClaudeAccountsDialog( BuildContext context, @@ -68,6 +69,13 @@ Future showChatClaudeAccountsDialog( _failed(messenger, error, 'The account was not saved.'); } }, + onAutoSwitch: (on) async { + try { + await accounts.setAutoSwitch(on); + } catch (error) { + _failed(messenger, error, 'The setting was not changed.'); + } + }, ), ), const SizedBox(height: 8), @@ -81,11 +89,13 @@ class _AccountList extends StatelessWidget { required this.accounts, required this.onSwitch, required this.onSave, + required this.onAutoSwitch, }); final ChatClaudeAccountsController accounts; final ValueChanged onSwitch; final VoidCallback onSave; + final ValueChanged onAutoSwitch; @override Widget build(BuildContext context) { @@ -130,6 +140,19 @@ class _AccountList extends StatelessWidget { enabled: list.active != null && !accounts.busy, onTap: onSave, ), + if (list.autoSwitch case final on?) + CheckboxListTile( + key: const Key('chat-claude-account-auto-switch'), + value: on, + onChanged: accounts.busy + ? null + : (value) => onAutoSwitch(value ?? false), + title: const Text('Auto-switch account when usage runs out'), + subtitle: const Text( + 'Continues on a saved account with usage left, after asking ' + 'the agent to check it is on track', + ), + ), ], ); } diff --git a/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart b/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart index ba9eb8de..b53a0e11 100644 --- a/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart +++ b/app/lib/features/chat/conversation/chat_claude_accounts_controller.dart @@ -7,7 +7,8 @@ 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`. +/// switches with `claude_account_use`, saves with `claude_account_save` and +/// sets automatic switching with `claude_account_auto_switch`. /// 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). @@ -59,12 +60,25 @@ class ChatClaudeAccountsController extends ChangeNotifier { /// 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 { + /// Turns automatic switching (to another saved account when usage runs + /// out) on or off for the chat's Claude home. + Future setAutoSwitch(bool on) => + _run('claude_account_auto_switch', null, autoSwitch: on); + + Future _run( + String type, + String? name, { + bool? autoSwitch, + }) async { _busy = type != 'claude_accounts'; _notify(); try { final reply = await gateway.call(type, { - 'claude_account': {'session_id': sessionId, 'name': ?name}, + 'claude_account': { + 'session_id': sessionId, + 'name': ?name, + 'auto_switch': ?autoSwitch, + }, }); final accounts = ChatClaudeAccounts.fromJson(reply['claude_accounts']); if (accounts == null) { 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 8f68e42f..aed8e297 100644 --- a/app/lib/features/chat/conversation/chat_usage_limit_banner.dart +++ b/app/lib/features/chat/conversation/chat_usage_limit_banner.dart @@ -25,7 +25,9 @@ import 'chat_thread_controller.dart'; /// already worked on it. The server holds it durably, so it is sent with the /// app closed or the server restarted. Unchecking takes it back out of the /// server's queue; Try again takes it out and sends now. The banner hides -/// once the reset passes. +/// once the reset passes, or once the account is switched (by the operator +/// or by the server's automatic switch, whose queued continue prompt also +/// stops auto-continue from being scheduled). class ChatUsageLimitBanner extends StatefulWidget { ChatUsageLimitBanner({ super.key, @@ -156,7 +158,13 @@ class _ChatUsageLimitBannerState extends State { final refused = chatRefusedTurn(thread.messages, thread.accountUsage); final pending = _pending(now); final auto = widget.autoContinue; - if (auto.loaded && auto.enabled && refused != null && pending.isEmpty) { + // The server already switched accounts and is continuing the chat. + final switching = chatAutoSwitchPending(thread.queuedPrompts); + if (auto.loaded && + auto.enabled && + refused != null && + pending.isEmpty && + !switching) { _arm(refused, limit); } return _banner(context, limit, refused, pending, now); diff --git a/app/lib/features/chat/domain/chat_claude_accounts.dart b/app/lib/features/chat/domain/chat_claude_accounts.dart index b657451c..6b3d0f7f 100644 --- a/app/lib/features/chat/domain/chat_claude_accounts.dart +++ b/app/lib/features/chat/domain/chat_claude_accounts.dart @@ -53,6 +53,7 @@ class ChatClaudeAccounts { required this.active, required this.accounts, this.usage, + this.autoSwitch, }); final String configDir; @@ -66,6 +67,11 @@ class ChatClaudeAccounts { /// After a switch, the new account's quota as the server knows it. final ChatAccountUsage? usage; + /// Whether the server switches this Claude home to another saved account + /// with usage left, and continues the chat, when usage runs out; null from + /// a server that does not switch automatically. + final bool? autoSwitch; + /// Saved accounts other than the active one: the switch targets. List get others => [ for (final account in accounts) @@ -86,6 +92,10 @@ class ChatClaudeAccounts { for (final entry in raw) ?ChatClaudeAccount.fromJson(entry), ], usage: chatAccountUsage(value['usage']), + autoSwitch: switch (value['auto_switch']) { + final bool on => on, + _ => null, + }, ); } } diff --git a/app/lib/features/chat/domain/chat_usage_limit.dart b/app/lib/features/chat/domain/chat_usage_limit.dart index 4b0c0a3d..bc7bf408 100644 --- a/app/lib/features/chat/domain/chat_usage_limit.dart +++ b/app/lib/features/chat/domain/chat_usage_limit.dart @@ -20,6 +20,18 @@ const String chatAutoContinueText = 'continue'; /// auto-continue can find them in the server's queue. const String chatAutoContinuePrefix = 'auto-continue-'; +/// The operation id prefix of the prompt the server queues after it switched +/// a refused chat to another Claude account (`auto-switch-`); +/// while one waits, the chat is already being continued. +const String chatAutoSwitchPrefix = 'auto-switch-'; + +/// Whether the server's queue for the chat holds its automatic-switch +/// continue prompt. +bool chatAutoSwitchPending(Iterable queued) => queued.any( + (prompt) => + '${prompt['operation_id'] ?? ''}'.startsWith(chatAutoSwitchPrefix), +); + class ChatUsageLimit { const ChatUsageLimit({required this.resetsAt}); diff --git a/app/test/features/chat/conversation/chat_claude_auto_switch_setting_test.dart b/app/test/features/chat/conversation/chat_claude_auto_switch_setting_test.dart new file mode 100644 index 00000000..6f8170d0 --- /dev/null +++ b/app/test/features/chat/conversation/chat_claude_auto_switch_setting_test.dart @@ -0,0 +1,122 @@ +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/domain/chat_claude_accounts.dart'; + +import 'chat_thread_fixtures.dart'; + +/// A Claude home with two saved accounts and an automatic-switch choice; +/// [reports] false models a server that does not report one. +class _Gateway extends FakeChatGateway { + _Gateway({this.reports = true}); + + final bool reports; + bool autoSwitch = true; + final requests = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (!type.startsWith('claude_account')) return super.call(type, fields); + final body = fields['claude_account'] as JsonMap; + requests.add({'type': type, ...body}); + if (type == 'claude_account_auto_switch') { + autoSwitch = body['auto_switch'] as bool; + } + JsonMap account(String email, bool active) => { + 'name': email, + 'email': email, + 'active': active, + 'saved': true, + }; + return { + 'claude_accounts': { + 'config_dir': '/home/op/.claude-profile', + 'active': account('a@example.invalid', true), + 'accounts': [ + account('a@example.invalid', true), + account('b@example.invalid', false), + ], + if (reports) 'auto_switch': autoSwitch, + }, + }; + } +} + +Future _open(WidgetTester tester, _Gateway gateway) async { + final accounts = ChatClaudeAccountsController( + gateway: gateway, + sessionId: 's', + ); + addTearDown(gateway.close); + addTearDown(accounts.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showChatClaudeAccountsDialog(context, accounts), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); +} + +final _setting = find.byKey(const Key('chat-claude-account-auto-switch')); + +bool _checked(WidgetTester tester) => + tester.widget(_setting).value!; + +void main() { + test('the accounts reply carries the automatic-switch choice', () { + expect( + ChatClaudeAccounts.fromJson({ + 'accounts': [], + 'auto_switch': false, + })!.autoSwitch, + isFalse, + ); + expect(ChatClaudeAccounts.fromJson({'accounts': []})!.autoSwitch, isNull); + }); + + testWidgets('the Claude account dialog turns automatic switching off and ' + 'on', (tester) async { + final gateway = _Gateway(); + await _open(tester, gateway); + expect( + find.text('Auto-switch account when usage runs out'), + findsOneWidget, + ); + expect(_checked(tester), isTrue); + + await tester.tap(_setting); + await tester.pumpAndSettle(); + expect(gateway.requests.last, { + 'type': 'claude_account_auto_switch', + 'session_id': 's', + 'auto_switch': false, + }); + expect(_checked(tester), isFalse); + + await tester.tap(_setting); + await tester.pumpAndSettle(); + expect(gateway.requests.last['auto_switch'], isTrue); + expect(_checked(tester), isTrue); + }); + + testWidgets('a server that does not switch automatically shows no setting', ( + tester, + ) async { + await _open(tester, _Gateway(reports: false)); + expect( + find.byKey(const Key('chat-claude-account-b@example.invalid')), + findsOneWidget, + ); + expect(_setting, findsNothing); + }); +} diff --git a/app/test/features/chat/conversation/chat_usage_limit_auto_switch_test.dart b/app/test/features/chat/conversation/chat_usage_limit_auto_switch_test.dart new file mode 100644 index 00000000..0714485c --- /dev/null +++ b/app/test/features/chat/conversation/chat_usage_limit_auto_switch_test.dart @@ -0,0 +1,183 @@ +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_auto_continue.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +/// A thread gateway that keeps the server's prompt queue, including prompts +/// the server queued itself ([serverQueue]). +class _Gateway extends FakeChatGateway { + final promptBodies = []; + final held = []; + List messages = []; + + _Gateway() { + history = (_) async => chatPage(messages); + } + + void pushQueue({String? removed}) => emitRaw({ + 'type': 'chat_queue', + 'chat_queue': { + 'session_id': 's', + 'prompts': [...held], + 'removed': ?removed, + }, + }); + + /// The server switched accounts: its continue prompt is queued and the app's + /// auto-continue prompts are removed. + void serverSwitched() { + final removed = [ + for (final p in held) + if ('${p['operation_id']}'.startsWith('auto-continue-')) + '${p['operation_id']}', + ]; + held.removeWhere((p) => removed.contains(p['operation_id'])); + held.add({ + 'operation_id': 'auto-switch-r1', + 'text': '[Sent automatically by Pipelines] Usage ran out…', + 'client': 'Pipelines (automatic)', + }); + for (final id in removed) { + pushQueue(removed: id); + } + pushQueue(); + emitEvent({ + 'session_id': 's', + 'kind': 'usage', + 'usage': { + 'account': { + 'harness': 'Claude Code', + 'email': 'b@example.invalid', + 'switched_at': DateTime.now().millisecondsSinceEpoch, + }, + }, + }); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_prompt') { + final body = fields['chat_prompt'] as JsonMap; + promptBodies.add(body); + held.add({ + 'operation_id': body['operation_id'], + 'text': body['text'], + 'send_at': body['send_at'], + }); + pushQueue(); + return {'chat_queued': true}; + } + return super.call(type, fields); + } +} + +const _hit = + "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of " + 'usage credits'; + +JsonMap _exhausted() => { + 'session_id': 's', + 'kind': 'usage', + 'usage': { + 'account': { + 'harness': 'Claude Code', + 'email': 'a@example.invalid', + 'windows': [ + { + 'id': 'five_hour', + 'label': '5-hour', + 'used_percent': 100, + 'resets_at': DateTime.now() + .add(const Duration(hours: 2)) + .millisecondsSinceEpoch, + }, + ], + }, + }, +}; + +Future _pump(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); +} + +Future<_Gateway> _host(WidgetTester tester) async { + final gateway = _Gateway() + ..messages = [ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'Fix it'}, + ], + ), + { + ...chatMessage( + 'r1', + 'assistant', + parts: [ + {'type': 'text', 'text': _hit}, + ], + ), + 'created_at': DateTime.now() + .subtract(const Duration(seconds: 5)) + .millisecondsSinceEpoch, + }, + ]; + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: MemoryChatDraftStore(), + autoContinue: ChatAutoContinue(), + ), + ), + ), + ); + await _pump(tester); + return gateway; +} + +final _banner = find.byKey(const Key('chat-usage-limit')); + +void main() { + testWidgets('the server switching accounts clears the banner and its ' + 'auto-continue stays removed', (tester) async { + final gateway = await _host(tester); + gateway.emitEvent(_exhausted()); + await _pump(tester); + expect(_banner, findsOneWidget); + expect(gateway.promptBodies.single['operation_id'], 'auto-continue-r1'); + + gateway.serverSwitched(); + await _pump(tester); + expect(_banner, findsNothing); + // The removed auto-continue is not asked for again. + expect(gateway.promptBodies, hasLength(1)); + expect( + gateway.held.map((p) => p['operation_id']), + equals(['auto-switch-r1']), + ); + }); + + testWidgets('a refusal the server is already continuing schedules no ' + 'auto-continue', (tester) async { + final gateway = await _host(tester); + // The server's continue prompt is queued before the quota report lands. + gateway.held.add({'operation_id': 'auto-switch-r1', 'text': 'continue'}); + gateway.pushQueue(); + await _pump(tester); + gateway.emitEvent(_exhausted()); + await _pump(tester); + expect(gateway.promptBodies, isEmpty); + }); +} diff --git a/internal/claude/auto_switch.go b/internal/claude/auto_switch.go index 435a31ba..744e5ed1 100644 --- a/internal/claude/auto_switch.go +++ b/internal/claude/auto_switch.go @@ -84,9 +84,11 @@ func (c *Chat) AutoSwitchAccount(ctx context.Context, refusal UsageRefusal) (Aut c.markRefused(from, organizationOf(list, from), now) active := *list.Active if !strings.EqualFold(active.Email, from) && c.usable(active, now) { - // Another chat's refusal already moved the home on. + // Another chat's refusal already moved the home on. The switch is + // stamped again so this chat's later refusal reads as the old + // account's too. identity := accountIdentity{key: accountKeyFor(active.Email, active.Organization), plan: active.Plan, email: active.Email, organization: active.Organization} - return AutoSwitch{From: from, To: active.Email, Usage: c.accountUsage(identity)}, nil + return AutoSwitch{From: from, To: active.Email, Usage: c.switchAccount(ctx, configDir, identity)}, nil } candidate, ok := c.pickAccount(list, from, now) if !ok { diff --git a/internal/claude/auto_switch_test.go b/internal/claude/auto_switch_test.go index bccafa5d..af242c6b 100644 --- a/internal/claude/auto_switch_test.go +++ b/internal/claude/auto_switch_test.go @@ -130,7 +130,8 @@ func TestAutoSwitchMovesToTheSavedAccountWithTheMostUsageLeft(t *testing.T) { if result.From != "a@example.invalid" { t.Fatalf("from = %+v", result) } - if result.Switched && (result.Usage == nil || result.Usage.SwitchedAt == 0) { + // Both chats' refusals predate a switch stamp, so their banners clear. + if result.Usage == nil || result.Usage.SwitchedAt == 0 { t.Fatalf("the switch was not marked: %+v", result.Usage) } } diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index 7d204994..f4d268a3 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -158,7 +158,7 @@ func refusalKey(refusal claude.UsageRefusal) string { // claim reports whether refusal is new, remembering it. func (s *chatAutoSwitchState) claim(refusal claude.UsageRefusal) bool { - key := refusal.SessionID + "\x00" + refusal.TurnID + key := refusal.SessionID + "\x00" + refusal.TurnID + "\x00" + refusal.MessageID s.mu.Lock() defer s.mu.Unlock() if s.handled[key] {