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 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 00:31:31 +00:00
parent ed9072b79a
commit 18e0e565ca
10 changed files with 386 additions and 11 deletions
@@ -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<void> showChatClaudeAccountsDialog(
BuildContext context,
@@ -68,6 +69,13 @@ Future<void> 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<ChatClaudeAccount> onSwitch;
final VoidCallback onSave;
final ValueChanged<bool> 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',
),
),
],
);
}
@@ -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<void> save(String name) => _run('claude_account_save', name);
Future<ChatClaudeAccounts?> _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<void> setAutoSwitch(bool on) =>
_run('claude_account_auto_switch', null, autoSwitch: on);
Future<ChatClaudeAccounts?> _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) {
@@ -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<ChatUsageLimitBanner> {
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);
@@ -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<ChatClaudeAccount> 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,
},
);
}
}
@@ -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-<refusal id>`);
/// 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<JsonMap> queued) => queued.any(
(prompt) =>
'${prompt['operation_id'] ?? ''}'.startsWith(chatAutoSwitchPrefix),
);
class ChatUsageLimit {
const ChatUsageLimit({required this.resetsAt});
@@ -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 = <JsonMap>[];
@override
Future<JsonMap> 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<void> _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<CheckboxListTile>(_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);
});
}
@@ -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 = <JsonMap>[];
final held = <JsonMap>[];
List<JsonMap> 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<JsonMap> 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<void> _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);
});
}