Merge branch 'worktree-agent-a49d9cec6b60ce85a'

This commit is contained in:
2026-11-30 15:12:07 +00:00
33 changed files with 2958 additions and 4 deletions
@@ -0,0 +1,226 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../core/error_reason.dart';
import '../../../ui/adaptive/app_popups.dart';
import '../../../ui/layout/app_sheet_header.dart';
import '../domain/chat_claude_accounts.dart';
import 'chat_claude_accounts_controller.dart';
/// Switches the chat's Claude home to the saved account [account] and says
/// so in a snack bar; a refusal is shown the same way. [messenger] is taken
/// before any sheet closes, so the confirmation survives it.
Future<void> switchChatClaudeAccount(
ScaffoldMessengerState? messenger,
ChatClaudeAccountsController accounts,
ChatClaudeAccount account,
) async {
try {
final active = await accounts.use(account.name);
messenger?.showSnackBar(
SnackBar(content: Text(chatClaudeSwitchedMessage(active ?? account))),
);
} catch (error) {
_failed(messenger, error, 'The Claude account was not switched.');
}
}
void _failed(ScaffoldMessengerState? messenger, Object error, String fallback) {
messenger?.showSnackBar(
SnackBar(content: Text(describeErrorReason(error, fallback: fallback))),
);
}
/// The chat menu's "Claude account": the saved accounts of the chat's Claude
/// home with the active one checked (one tap switches), and "Save current
/// account…" for the active login. A dialog on a wide app, a bottom sheet on
/// a phone.
Future<void> showChatClaudeAccountsDialog(
BuildContext context,
ChatClaudeAccountsController accounts,
) {
unawaited(accounts.refresh());
final messenger = ScaffoldMessenger.maybeOf(context);
return showAppDetails<void>(
context,
maxWidth: 440,
builder: (sheetContext) => Column(
key: const Key('chat-claude-accounts'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const AppSheetHeader(title: 'Claude account'),
ListenableBuilder(
listenable: accounts,
builder: (context, _) => _AccountList(
accounts: accounts,
onSwitch: (account) {
Navigator.of(sheetContext).pop();
unawaited(switchChatClaudeAccount(messenger, accounts, account));
},
onSave: () async {
final name = await _askName(sheetContext, accounts.accounts);
if (name == null) return;
try {
await accounts.save(name);
} catch (error) {
_failed(messenger, error, 'The account was not saved.');
}
},
),
),
const SizedBox(height: 8),
],
),
);
}
class _AccountList extends StatelessWidget {
const _AccountList({
required this.accounts,
required this.onSwitch,
required this.onSave,
});
final ChatClaudeAccountsController accounts;
final ValueChanged<ChatClaudeAccount> onSwitch;
final VoidCallback onSave;
@override
Widget build(BuildContext context) {
final list = accounts.accounts;
final error = accounts.error;
if (list == null) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
child: error == null
? const LinearProgressIndicator()
: Text(
describeErrorReason(
error,
fallback: 'Claude accounts are not available.',
),
key: const Key('chat-claude-accounts-error'),
),
);
}
final unsaved = list.canSaveActive ? list.active : null;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (list.accounts.isEmpty && unsaved == null)
const ListTile(title: Text('No saved accounts')),
for (final account in list.accounts)
_AccountTile(
account: account,
onTap: account.active || accounts.busy
? null
: () => onSwitch(account),
),
if (unsaved != null)
_AccountTile(account: unsaved, onTap: null, note: 'Not saved'),
if (accounts.busy) const LinearProgressIndicator(),
const Divider(),
ListTile(
key: const Key('chat-claude-account-save'),
leading: const Icon(Icons.bookmark_add_outlined),
title: const Text('Save current account…'),
enabled: list.active != null && !accounts.busy,
onTap: onSave,
),
],
);
}
}
class _AccountTile extends StatelessWidget {
const _AccountTile({required this.account, required this.onTap, this.note});
final ChatClaudeAccount account;
final VoidCallback? onTap;
final String? note;
@override
Widget build(BuildContext context) {
final detail = [
if (account.name != account.label) account.name,
if (account.organization.isNotEmpty) account.organization,
if (account.plan.isNotEmpty) account.plan,
?note,
].join(' · ');
return ListTile(
key: Key('chat-claude-account-${account.name}'),
leading: const Icon(Icons.account_circle_outlined),
title: Text(account.label),
subtitle: detail.isEmpty ? null : Text(detail),
trailing: account.active
? Icon(
Icons.check,
color: Theme.of(context).colorScheme.primary,
semanticLabel: 'Active',
)
: null,
selected: account.active,
// An active row is informative, not disabled-looking.
enabled: onTap != null || account.active,
onTap: onTap,
);
}
}
/// Asks for the saved account's name, prefilled with the login's email.
Future<String?> _askName(BuildContext context, ChatClaudeAccounts? accounts) =>
showDialog<String>(
context: context,
builder: (context) => _NameDialog(initial: accounts?.active?.email ?? ''),
);
class _NameDialog extends StatefulWidget {
const _NameDialog({required this.initial});
final String initial;
@override
State<_NameDialog> createState() => _NameDialogState();
}
class _NameDialogState extends State<_NameDialog> {
late final TextEditingController _field = TextEditingController(
text: widget.initial,
);
@override
void dispose() {
_field.dispose();
super.dispose();
}
void _save() => Navigator.of(context).pop(_field.text.trim());
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Save current account'),
content: TextField(
key: const Key('chat-claude-account-name'),
controller: _field,
autofocus: true,
decoration: const InputDecoration(labelText: 'Name'),
onSubmitted: (_) => _save(),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
key: const Key('chat-claude-account-name-save'),
onPressed: _save,
child: const Text('Save'),
),
],
);
}
}
@@ -0,0 +1,112 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/app_popups.dart';
import '../domain/chat_claude_accounts.dart';
import 'chat_claude_account_dialog.dart';
import 'chat_claude_accounts_controller.dart';
/// A usage banner's "Switch to (other account)": shown when the chat's Claude
/// home has another saved account. With several it is "Switch account" and a
/// small menu of them. It loads the saved accounts the first time it shows.
class ChatClaudeAccountSwitchAction extends StatefulWidget {
const ChatClaudeAccountSwitchAction({
super.key,
required this.accounts,
this.foreground,
});
final ChatClaudeAccountsController accounts;
/// The banner's text colour, so the button reads on its container.
final Color? foreground;
@override
State<ChatClaudeAccountSwitchAction> createState() =>
_ChatClaudeAccountSwitchActionState();
}
class _ChatClaudeAccountSwitchActionState
extends State<ChatClaudeAccountSwitchAction> {
@override
void initState() {
super.initState();
unawaited(widget.accounts.ensureLoaded());
}
@override
void didUpdateWidget(ChatClaudeAccountSwitchAction oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.accounts != widget.accounts) {
unawaited(widget.accounts.ensureLoaded());
}
}
void _switch(ChatClaudeAccount account) => unawaited(
switchChatClaudeAccount(
ScaffoldMessenger.maybeOf(context),
widget.accounts,
account,
),
);
Future<void> _choose(
BuildContext anchor,
List<ChatClaudeAccount> others,
) async {
final chosen = await showAppChoiceMenu<ChatClaudeAccount>(
anchor,
semanticLabel: 'Switch Claude account',
builder: (menu) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final account in others)
AppChoiceMenuItem(
key: Key('chat-claude-switch-to-${account.name}'),
selected: false,
onTap: () => Navigator.of(menu).pop(account),
child: Text(account.label),
),
],
),
);
if (chosen != null && mounted) _switch(chosen);
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: widget.accounts,
builder: (context, _) {
final others = widget.accounts.accounts?.others ?? const [];
if (others.isEmpty) return const SizedBox.shrink();
final busy = widget.accounts.busy;
final style = TextButton.styleFrom(foregroundColor: widget.foreground);
if (others.length == 1) {
final account = others.single;
return TextButton.icon(
key: const Key('chat-claude-switch'),
style: style,
onPressed: busy ? null : () => _switch(account),
icon: const Icon(Icons.switch_account_outlined),
label: Text(
'Switch to ${account.label}',
overflow: TextOverflow.ellipsis,
),
);
}
return Builder(
builder: (anchor) => TextButton.icon(
key: const Key('chat-claude-switch'),
style: style,
onPressed: busy ? null : () => unawaited(_choose(anchor, others)),
icon: const Icon(Icons.switch_account_outlined),
label: const Text('Switch account'),
),
);
},
);
}
}
@@ -0,0 +1,94 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_claude_accounts.dart';
import 'chat_thread_controller.dart';
/// One Claude chat's saved accounts: loads `claude_accounts` once on demand,
/// switches with `claude_account_use` and saves with `claude_account_save`.
/// A switch hands the new account's quota to [thread], so its usage-limit
/// banner reflects the new account at once (the server also pushes it to
/// every open chat on the same Claude home).
class ChatClaudeAccountsController extends ChangeNotifier {
ChatClaudeAccountsController({
required this.gateway,
required this.sessionId,
this.thread,
});
final ApiGateway gateway;
final String sessionId;
final ChatThreadController? thread;
ChatClaudeAccounts? _accounts;
String? _error;
Future<void>? _loading;
bool _busy = false;
bool _disposed = false;
/// The last reply, or null before one arrived.
ChatClaudeAccounts? get accounts => _accounts;
/// The last refusal (for example a chat directory with no Claude home).
String? get error => _error;
/// A switch or save is in flight.
bool get busy => _busy;
/// Loads the accounts once; later calls reuse the first load.
Future<void> ensureLoaded() => _loading ??= refresh();
Future<void> refresh() async {
try {
await _run('claude_accounts', null);
} catch (_) {
// Recorded in [error].
}
}
/// Switches to the saved account [name] and returns the new active account.
Future<ChatClaudeAccount?> use(String name) async {
final accounts = await _run('claude_account_use', name);
final usage = accounts?.usage;
if (usage != null) thread?.accountSwitched(usage);
return accounts?.active;
}
/// Saves the active login as [name] ('' uses its email).
Future<void> save(String name) => _run('claude_account_save', name);
Future<ChatClaudeAccounts?> _run(String type, String? name) async {
_busy = type != 'claude_accounts';
_notify();
try {
final reply = await gateway.call(type, {
'claude_account': {'session_id': sessionId, 'name': ?name},
});
final accounts = ChatClaudeAccounts.fromJson(reply['claude_accounts']);
if (accounts == null) {
throw StateError('The server sent no Claude accounts.');
}
_accounts = accounts;
_error = null;
return accounts;
} catch (error) {
if (type == 'claude_accounts') _error = '$error';
rethrow;
} finally {
_busy = false;
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -167,6 +167,14 @@ class ChatThreadController extends ChangeNotifier {
/// is account state: a frame without one keeps the last known value.
ChatAccountUsage? get accountUsage => _accountUsage;
/// Adopts the quota of the Claude account the operator just switched to
/// (see ChatAccountUsage.switchedAt), which ends a limit the previous
/// account had reached.
void accountSwitched(ChatAccountUsage usage) {
_accountUsage = usage;
_notify(transcript: false);
}
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
@@ -42,6 +42,8 @@ import '../ui/transcript/chat_turn_diff_chip.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
import '../domain/chat_session_handoff.dart';
import 'chat_account_usage_section.dart';
import 'chat_claude_account_dialog.dart';
import 'chat_claude_accounts_controller.dart';
import 'chat_export_controller.dart';
import 'chat_session_section.dart';
import 'chat_background_tasks.dart';
@@ -237,6 +239,26 @@ class _ChatThreadViewState extends State<ChatThreadView> {
late ChatThreadController _controller = _attach();
late ChatComposerController _composer = _attachComposer();
/// The chat's saved Claude accounts (Claude Code chats only), loaded when
/// the menu or a usage banner first needs them.
ChatClaudeAccountsController? _claudeAccounts;
ChatClaudeAccountsController? get _accounts {
if ('${widget.session?['backend'] ?? ''}' != 'claude') return null;
final current = _claudeAccounts;
if (current != null &&
current.sessionId == widget.sessionId &&
current.gateway == widget.gateway &&
identical(current.thread, _controller)) {
return current;
}
current?.dispose();
return _claudeAccounts = ChatClaudeAccountsController(
gateway: widget.gateway,
sessionId: widget.sessionId,
thread: _controller,
);
}
/// The operator's own shell commands in this chat (see `../shell/`).
late ChatShellRunsController _shellRuns = _attachShellRuns();
ChatShellRunsController _attachShellRuns() =>
@@ -798,6 +820,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
widget.onComposerDisposed?.call(_composer);
_composer.dispose();
_controller.dispose();
_claudeAccounts?.dispose();
_shellRuns.dispose();
_files.removeListener(_persistFilesPreferences);
_files.dispose();
@@ -1264,8 +1287,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
thread: _controller,
composer: _composer,
sendDraft: sendDraft,
accounts: _accounts,
),
ChatUsageWarningBanner(
thread: _controller,
accounts: _accounts,
),
ChatUsageWarningBanner(thread: _controller),
],
),
backgroundTasks: ChatBackgroundTasks(
@@ -1625,6 +1652,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
...widget.paneControls.where((c) => !_closes(c)),
if (_shellRuns.finishedIds.isNotEmpty)
chatShellDismissAllMenuAction(onPressed: _dismissFinishedShellRuns),
if (_accounts case final accounts?)
ChatBarAction(
key: const Key('chat-claude-account-menu'),
label: 'Claude account',
identifier: 'chat-claude-account',
onPressed: () =>
unawaited(showChatClaudeAccountsDialog(context, accounts)),
materialIcon: Icons.switch_account_outlined,
),
?openTerminal,
// Closing comes last.
...widget.paneControls.where(_closes),
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
import '../domain/chat_commands.dart';
import '../domain/chat_usage_limit.dart';
import '../shell/chat_shell_command.dart';
import 'chat_claude_account_switch_action.dart';
import 'chat_claude_accounts_controller.dart';
import 'chat_composer_controller.dart';
import 'chat_schedule_time.dart';
import 'chat_thread_controller.dart';
@@ -25,12 +27,17 @@ class ChatUsageLimitBanner extends StatefulWidget {
required this.thread,
required this.composer,
required this.sendDraft,
this.accounts,
this.now = DateTime.now,
});
final ChatThreadController thread;
final ChatComposerController composer;
final ChatScheduleDraft sendDraft;
/// The chat's saved Claude accounts, for "Switch to (other account)";
/// null for a chat that is not Claude Code's.
final ChatClaudeAccountsController? accounts;
final DateTime Function() now;
@override
@@ -168,6 +175,11 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
icon: const Icon(Icons.schedule_send),
label: Text(label),
),
if (widget.accounts case final accounts?)
ChatClaudeAccountSwitchAction(
accounts: accounts,
foreground: scheme.onErrorContainer,
),
],
),
),
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_usage_limit.dart';
import '../domain/chat_usage_warning.dart';
import 'chat_claude_account_switch_action.dart';
import 'chat_claude_accounts_controller.dart';
import 'chat_schedule_time.dart';
import 'chat_thread_controller.dart';
import 'chat_usage_warnings.dart';
@@ -22,11 +24,16 @@ class ChatUsageWarningBanner extends StatefulWidget {
super.key,
required this.thread,
ChatUsageWarnings? warnings,
this.accounts,
this.now = DateTime.now,
}) : warnings = warnings ?? ChatUsageWarnings.shared;
final ChatThreadController thread;
final ChatUsageWarnings warnings;
/// The chat's saved Claude accounts, for "Switch to (other account)";
/// null for a chat that is not Claude Code's.
final ChatClaudeAccountsController? accounts;
final DateTime Function() now;
@override
@@ -168,6 +175,13 @@ class _ChatUsageWarningBannerState extends State<ChatUsageWarningBanner> {
),
),
),
if (widget.accounts case final accounts?)
Flexible(
child: ChatClaudeAccountSwitchAction(
accounts: accounts,
foreground: foreground,
),
),
IconButton(
key: const Key('chat-usage-warning-dismiss'),
tooltip: 'Dismiss',
@@ -29,6 +29,7 @@ class ChatAccountUsage {
required this.asOf,
required this.windows,
required this.unsupported,
this.switchedAt = 0,
});
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
@@ -41,6 +42,12 @@ class ChatAccountUsage {
/// The harness exposes no quota at all.
final bool unsupported;
/// Epoch milliseconds when the operator switched the chat's Claude account
/// to this one, 0 if never. The report then stands for the new account even
/// before any window is known, and an earlier usage-limit refusal in the
/// transcript no longer applies.
final int switchedAt;
}
int _millis(Object? value) =>
@@ -78,13 +85,17 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
);
}
}
if (windows.isEmpty) return null;
final switchedAt = _millis(value['switched_at']);
// A switched account replaces the previous report even with no windows
// yet; otherwise an empty report keeps the last one.
if (windows.isEmpty && switchedAt == 0) return null;
return ChatAccountUsage(
harness: harness,
plan: '${value['plan'] ?? ''}'.trim(),
asOf: _millis(value['as_of']),
windows: List.unmodifiable(windows),
unsupported: false,
switchedAt: switchedAt,
);
}
@@ -0,0 +1,96 @@
/// The saved Claude accounts of the Claude home a chat's directory selects
/// (its CLAUDE_CONFIG_DIR), as the server's `claude_accounts` reply reports
/// them. Replies describe accounts only; they never carry a token.
library;
import 'chat_account_usage.dart';
/// One Claude login.
class ChatClaudeAccount {
const ChatClaudeAccount({
required this.name,
required this.email,
required this.organization,
required this.plan,
required this.active,
required this.saved,
});
final String name;
final String email;
final String organization;
final String plan;
/// The Claude home is signed in with this account.
final bool active;
/// False for an active login with no saved slot yet.
final bool saved;
/// What the operator calls the account: its email, else its name.
String get label => email.isNotEmpty ? email : name;
static ChatClaudeAccount? fromJson(Object? value) {
if (value is! Map) return null;
final name = '${value['name'] ?? ''}'.trim();
final email = '${value['email'] ?? ''}'.trim();
if (name.isEmpty && email.isEmpty) return null;
return ChatClaudeAccount(
name: name.isEmpty ? email : name,
email: email,
organization: '${value['organization'] ?? ''}'.trim(),
plan: '${value['plan'] ?? ''}'.trim(),
active: value['active'] == true,
saved: value['saved'] == true,
);
}
}
/// A `claude_accounts` reply.
class ChatClaudeAccounts {
const ChatClaudeAccounts({
required this.configDir,
required this.active,
required this.accounts,
this.usage,
});
final String configDir;
/// The current login, saved or not; null when signed out.
final ChatClaudeAccount? active;
/// The saved accounts.
final List<ChatClaudeAccount> accounts;
/// After a switch, the new account's quota as the server knows it.
final ChatAccountUsage? usage;
/// Saved accounts other than the active one: the switch targets.
List<ChatClaudeAccount> get others => [
for (final account in accounts)
if (!account.active) account,
];
/// Whether the active login can be saved (it is not saved yet).
bool get canSaveActive => active != null && !active!.saved;
static ChatClaudeAccounts? fromJson(Object? value) {
if (value is! Map) return null;
final raw = value['accounts'];
return ChatClaudeAccounts(
configDir: '${value['config_dir'] ?? ''}',
active: ChatClaudeAccount.fromJson(value['active']),
accounts: [
if (raw is List)
for (final entry in raw) ?ChatClaudeAccount.fromJson(entry),
],
usage: chatAccountUsage(value['usage']),
);
}
}
/// The confirmation shown after a switch.
String chatClaudeSwitchedMessage(ChatClaudeAccount? account) =>
'Switched to ${account?.label ?? 'the saved account'} — send a message '
'to continue';
@@ -67,6 +67,13 @@ ChatUsageLimit? chatThreadUsageLimit(
orElse: () => const {},
);
if (last.isEmpty || last['role'] == 'user') return null;
// A refusal received before the operator switched accounts was the old
// account's.
final switchedAt = usage?.switchedAt ?? 0;
if (switchedAt > 0) {
final created = last['created_at'];
if (created is! num || created <= switchedAt) return null;
}
return chatUsageLimitFromText(_text(last), now);
}