Merge branch 'main' into worktree-agent-a3ec65b20dc3028b9
This commit is contained in:
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,8 @@ import '../domain/chat_commands.dart';
|
|||||||
import 'chat_command_actions.dart';
|
import 'chat_command_actions.dart';
|
||||||
import 'chat_command_palette.dart';
|
import 'chat_command_palette.dart';
|
||||||
import 'chat_composer_controller.dart';
|
import 'chat_composer_controller.dart';
|
||||||
|
import 'chat_send_usage_ring.dart';
|
||||||
|
import 'chat_thread_controller.dart';
|
||||||
import 'chat_composer_paste_focus.dart';
|
import 'chat_composer_paste_focus.dart';
|
||||||
import 'chat_harness_command_loader.dart';
|
import 'chat_harness_command_loader.dart';
|
||||||
import '../ui/transcript/chat_attachment_frame.dart';
|
import '../ui/transcript/chat_attachment_frame.dart';
|
||||||
@@ -139,8 +141,13 @@ class ChatComposerBar extends StatefulWidget {
|
|||||||
this.chatColor,
|
this.chatColor,
|
||||||
this.limitBanner,
|
this.limitBanner,
|
||||||
this.loadHarnessCommands,
|
this.loadHarnessCommands,
|
||||||
|
this.usage,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/// The chat's thread, whose harness account usage the send button's ring
|
||||||
|
/// shows ([ChatSendUsageRing]); null draws no ring.
|
||||||
|
final ChatThreadController? usage;
|
||||||
|
|
||||||
/// Loads the session's harness commands and skills (`chat_commands`), which
|
/// Loads the session's harness commands and skills (`chat_commands`), which
|
||||||
/// the palette offers after the recorded commands. Choosing one inserts
|
/// the palette offers after the recorded commands. Choosing one inserts
|
||||||
/// `/<name> ` and sending passes the draft to the harness as a prompt. Null
|
/// `/<name> ` and sending passes the draft to the harness as a prompt. Null
|
||||||
@@ -1297,17 +1304,32 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
|||||||
// A coloured chat's send button takes the chat's colour (its seeded
|
// A coloured chat's send button takes the chat's colour (its seeded
|
||||||
// primary, like the focus ring).
|
// primary, like the focus ring).
|
||||||
final tinted = chatSchemeOf(context, widget.chatColor);
|
final tinted = chatSchemeOf(context, widget.chatColor);
|
||||||
return IconButton.filled(
|
final usage = widget.usage;
|
||||||
key: const Key('chat-composer-primary'),
|
return ChatSendUsageRing(
|
||||||
tooltip: label,
|
source: usage,
|
||||||
style: tinted == null
|
usage: () => usage?.accountUsage,
|
||||||
? null
|
label: label,
|
||||||
: IconButton.styleFrom(
|
// One shape with or without usage (a report never remounts the
|
||||||
backgroundColor: tinted.primary,
|
// button): the hover text can grow with usage, while assistive
|
||||||
foregroundColor: tinted.onPrimary,
|
// technology still names the button by its label alone.
|
||||||
),
|
button: (tooltip) => Semantics(
|
||||||
onPressed: enabled ? press : null,
|
label: label,
|
||||||
icon: const Icon(Icons.arrow_upward),
|
child: Tooltip(
|
||||||
|
message: tooltip,
|
||||||
|
excludeFromSemantics: true,
|
||||||
|
child: IconButton.filled(
|
||||||
|
key: const Key('chat-composer-primary'),
|
||||||
|
style: tinted == null
|
||||||
|
? null
|
||||||
|
: IconButton.styleFrom(
|
||||||
|
backgroundColor: tinted.primary,
|
||||||
|
foregroundColor: tinted.onPrimary,
|
||||||
|
),
|
||||||
|
onPressed: enabled ? press : null,
|
||||||
|
icon: const Icon(Icons.arrow_upward),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../domain/chat_account_usage.dart';
|
||||||
|
import '../domain/chat_usage_ring.dart';
|
||||||
|
|
||||||
|
/// A thin ring around the composer's send button showing how much of the
|
||||||
|
/// harness account's quota is used ([chatUsageRing]): barely visible
|
||||||
|
/// normally, the tertiary colour from 80% and the error colour from 95%. The
|
||||||
|
/// button's tooltip (hover, or long-press on touch) adds every window:
|
||||||
|
/// "Send" then "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00".
|
||||||
|
///
|
||||||
|
/// The ring is painted beside the button, never in its layout or hit test,
|
||||||
|
/// so the button keeps its size, target, states and animations. Without a
|
||||||
|
/// reported quota there is no ring and the tooltip is the label alone.
|
||||||
|
class ChatSendUsageRing extends StatefulWidget {
|
||||||
|
const ChatSendUsageRing({
|
||||||
|
super.key,
|
||||||
|
required this.source,
|
||||||
|
required this.usage,
|
||||||
|
required this.label,
|
||||||
|
required this.button,
|
||||||
|
this.now = DateTime.now,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Notifies when [usage] may have changed (the chat's thread controller).
|
||||||
|
final Listenable? source;
|
||||||
|
final ChatAccountUsage? Function() usage;
|
||||||
|
|
||||||
|
/// The button's own tooltip, e.g. "Send".
|
||||||
|
final String label;
|
||||||
|
|
||||||
|
/// Builds the button with the tooltip to show.
|
||||||
|
final Widget Function(String tooltip) button;
|
||||||
|
final DateTime Function() now;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ChatSendUsageRing> createState() => _ChatSendUsageRingState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ChatSendUsageRingState extends State<ChatSendUsageRing> {
|
||||||
|
/// Keeps the reset times and a passed reset current while a ring shows.
|
||||||
|
Timer? _tick;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_tick?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _ticking(bool on) {
|
||||||
|
if (on == (_tick != null)) return;
|
||||||
|
_tick?.cancel();
|
||||||
|
_tick = on
|
||||||
|
? Timer.periodic(const Duration(minutes: 1), (_) {
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final source = widget.source;
|
||||||
|
if (source == null) return _ring(context);
|
||||||
|
return ListenableBuilder(
|
||||||
|
listenable: source,
|
||||||
|
builder: (context, _) => _ring(context),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _ring(BuildContext context) {
|
||||||
|
final now = widget.now();
|
||||||
|
final ring = chatUsageRing(widget.usage(), now);
|
||||||
|
_ticking(ring != null);
|
||||||
|
// The button stays the same child with or without a ring, so a report
|
||||||
|
// arriving never remounts it (its hover, focus and ink stay).
|
||||||
|
return CustomPaint(
|
||||||
|
painter: ring == null ? null : _painter(context, ring),
|
||||||
|
child: widget.button(
|
||||||
|
ring == null
|
||||||
|
? widget.label
|
||||||
|
: '${widget.label}\n${chatUsageRingSummary(ring, now)}',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ChatUsageRingPainter _painter(BuildContext context, ChatUsageRing ring) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
return ChatUsageRingPainter(
|
||||||
|
fraction: ring.fraction,
|
||||||
|
color: switch (ring.tone) {
|
||||||
|
ChatUsageRingTone.quiet => scheme.onSurfaceVariant.withValues(
|
||||||
|
alpha: .45,
|
||||||
|
),
|
||||||
|
ChatUsageRingTone.warning => scheme.tertiary,
|
||||||
|
ChatUsageRingTone.urgent => scheme.error,
|
||||||
|
},
|
||||||
|
track: scheme.outlineVariant.withValues(alpha: .35),
|
||||||
|
circle: chatSendButtonDiameter(context),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The filled send button's visible circle: a Material 3 icon button's 40
|
||||||
|
/// logical pixels adjusted by its visual density, inside a target that may
|
||||||
|
/// be padded beyond it.
|
||||||
|
double chatSendButtonDiameter(BuildContext context) {
|
||||||
|
final density =
|
||||||
|
IconButtonTheme.of(context).style?.visualDensity ??
|
||||||
|
Theme.of(context).visualDensity;
|
||||||
|
return 40 + density.baseSizeAdjustment.dx;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ring: a faint full track and the used arc clockwise from the top, a
|
||||||
|
/// hairline gap outside the button's circle of diameter [circle], centred
|
||||||
|
/// in the painted box.
|
||||||
|
class ChatUsageRingPainter extends CustomPainter {
|
||||||
|
const ChatUsageRingPainter({
|
||||||
|
required this.fraction,
|
||||||
|
required this.color,
|
||||||
|
required this.track,
|
||||||
|
required this.circle,
|
||||||
|
});
|
||||||
|
|
||||||
|
final double fraction;
|
||||||
|
final Color color;
|
||||||
|
final Color track;
|
||||||
|
final double circle;
|
||||||
|
|
||||||
|
static const double stroke = 2;
|
||||||
|
static const double gap = 1;
|
||||||
|
|
||||||
|
/// The ring's centre-line radius.
|
||||||
|
double get radius => circle / 2 + gap + stroke / 2;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final rect = Rect.fromCircle(
|
||||||
|
center: size.center(Offset.zero),
|
||||||
|
radius: radius,
|
||||||
|
);
|
||||||
|
final paint = Paint()
|
||||||
|
..style = PaintingStyle.stroke
|
||||||
|
..strokeWidth = stroke
|
||||||
|
..isAntiAlias = true;
|
||||||
|
canvas.drawCircle(rect.center, radius, paint..color = track);
|
||||||
|
if (fraction <= 0) return;
|
||||||
|
canvas.drawArc(
|
||||||
|
rect,
|
||||||
|
-math.pi / 2,
|
||||||
|
2 * math.pi * fraction,
|
||||||
|
false,
|
||||||
|
paint
|
||||||
|
..color = color
|
||||||
|
..strokeCap = fraction >= 1 ? StrokeCap.butt : StrokeCap.round,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(ChatUsageRingPainter old) =>
|
||||||
|
old.fraction != fraction ||
|
||||||
|
old.color != color ||
|
||||||
|
old.track != track ||
|
||||||
|
old.circle != circle;
|
||||||
|
}
|
||||||
@@ -167,6 +167,14 @@ class ChatThreadController extends ChangeNotifier {
|
|||||||
/// is account state: a frame without one keeps the last known value.
|
/// is account state: a frame without one keeps the last known value.
|
||||||
ChatAccountUsage? get accountUsage => _accountUsage;
|
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;
|
String? get error => _error;
|
||||||
bool get subscribed => _subscribed;
|
bool get subscribed => _subscribed;
|
||||||
String? get subscriptionError => _subscriptionError;
|
String? get subscriptionError => _subscriptionError;
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ import '../ui/transcript/chat_turn_diff_chip.dart';
|
|||||||
import '../../artifacts/actions/artifact_file_bridge.dart';
|
import '../../artifacts/actions/artifact_file_bridge.dart';
|
||||||
import '../domain/chat_session_handoff.dart';
|
import '../domain/chat_session_handoff.dart';
|
||||||
import 'chat_account_usage_section.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_export_controller.dart';
|
||||||
import 'chat_session_section.dart';
|
import 'chat_session_section.dart';
|
||||||
import 'chat_background_tasks.dart';
|
import 'chat_background_tasks.dart';
|
||||||
@@ -237,6 +239,26 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
|||||||
late ChatThreadController _controller = _attach();
|
late ChatThreadController _controller = _attach();
|
||||||
late ChatComposerController _composer = _attachComposer();
|
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/`).
|
/// The operator's own shell commands in this chat (see `../shell/`).
|
||||||
late ChatShellRunsController _shellRuns = _attachShellRuns();
|
late ChatShellRunsController _shellRuns = _attachShellRuns();
|
||||||
ChatShellRunsController _attachShellRuns() =>
|
ChatShellRunsController _attachShellRuns() =>
|
||||||
@@ -798,6 +820,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
|||||||
widget.onComposerDisposed?.call(_composer);
|
widget.onComposerDisposed?.call(_composer);
|
||||||
_composer.dispose();
|
_composer.dispose();
|
||||||
_controller.dispose();
|
_controller.dispose();
|
||||||
|
_claudeAccounts?.dispose();
|
||||||
_shellRuns.dispose();
|
_shellRuns.dispose();
|
||||||
_files.removeListener(_persistFilesPreferences);
|
_files.removeListener(_persistFilesPreferences);
|
||||||
_files.dispose();
|
_files.dispose();
|
||||||
@@ -1242,6 +1265,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
|||||||
key: ValueKey<String>('chat-composer-${widget.sessionId}'),
|
key: ValueKey<String>('chat-composer-${widget.sessionId}'),
|
||||||
composer: _composer,
|
composer: _composer,
|
||||||
running: _controller.running,
|
running: _controller.running,
|
||||||
|
usage: _controller,
|
||||||
commands: _commandActions(),
|
commands: _commandActions(),
|
||||||
loadHarnessCommands: () async => chatHarnessCommandsFromWire(
|
loadHarnessCommands: () async => chatHarnessCommandsFromWire(
|
||||||
await ChatRepository(widget.gateway).commands(widget.sessionId),
|
await ChatRepository(widget.gateway).commands(widget.sessionId),
|
||||||
@@ -1263,8 +1287,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
|||||||
thread: _controller,
|
thread: _controller,
|
||||||
composer: _composer,
|
composer: _composer,
|
||||||
sendDraft: sendDraft,
|
sendDraft: sendDraft,
|
||||||
|
accounts: _accounts,
|
||||||
|
),
|
||||||
|
ChatUsageWarningBanner(
|
||||||
|
thread: _controller,
|
||||||
|
accounts: _accounts,
|
||||||
),
|
),
|
||||||
ChatUsageWarningBanner(thread: _controller),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
backgroundTasks: ChatBackgroundTasks(
|
backgroundTasks: ChatBackgroundTasks(
|
||||||
@@ -1624,6 +1652,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
|||||||
...widget.paneControls.where((c) => !_closes(c)),
|
...widget.paneControls.where((c) => !_closes(c)),
|
||||||
if (_shellRuns.finishedIds.isNotEmpty)
|
if (_shellRuns.finishedIds.isNotEmpty)
|
||||||
chatShellDismissAllMenuAction(onPressed: _dismissFinishedShellRuns),
|
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,
|
?openTerminal,
|
||||||
// Closing comes last.
|
// Closing comes last.
|
||||||
...widget.paneControls.where(_closes),
|
...widget.paneControls.where(_closes),
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import 'package:flutter/material.dart';
|
|||||||
import '../domain/chat_commands.dart';
|
import '../domain/chat_commands.dart';
|
||||||
import '../domain/chat_usage_limit.dart';
|
import '../domain/chat_usage_limit.dart';
|
||||||
import '../shell/chat_shell_command.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_composer_controller.dart';
|
||||||
import 'chat_schedule_time.dart';
|
import 'chat_schedule_time.dart';
|
||||||
import 'chat_thread_controller.dart';
|
import 'chat_thread_controller.dart';
|
||||||
@@ -25,12 +27,17 @@ class ChatUsageLimitBanner extends StatefulWidget {
|
|||||||
required this.thread,
|
required this.thread,
|
||||||
required this.composer,
|
required this.composer,
|
||||||
required this.sendDraft,
|
required this.sendDraft,
|
||||||
|
this.accounts,
|
||||||
this.now = DateTime.now,
|
this.now = DateTime.now,
|
||||||
});
|
});
|
||||||
|
|
||||||
final ChatThreadController thread;
|
final ChatThreadController thread;
|
||||||
final ChatComposerController composer;
|
final ChatComposerController composer;
|
||||||
final ChatScheduleDraft sendDraft;
|
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;
|
final DateTime Function() now;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -168,6 +175,11 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
|
|||||||
icon: const Icon(Icons.schedule_send),
|
icon: const Icon(Icons.schedule_send),
|
||||||
label: Text(label),
|
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_account_usage.dart';
|
||||||
import '../domain/chat_usage_limit.dart';
|
import '../domain/chat_usage_limit.dart';
|
||||||
import '../domain/chat_usage_warning.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_schedule_time.dart';
|
||||||
import 'chat_thread_controller.dart';
|
import 'chat_thread_controller.dart';
|
||||||
import 'chat_usage_warnings.dart';
|
import 'chat_usage_warnings.dart';
|
||||||
@@ -22,11 +24,16 @@ class ChatUsageWarningBanner extends StatefulWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.thread,
|
required this.thread,
|
||||||
ChatUsageWarnings? warnings,
|
ChatUsageWarnings? warnings,
|
||||||
|
this.accounts,
|
||||||
this.now = DateTime.now,
|
this.now = DateTime.now,
|
||||||
}) : warnings = warnings ?? ChatUsageWarnings.shared;
|
}) : warnings = warnings ?? ChatUsageWarnings.shared;
|
||||||
|
|
||||||
final ChatThreadController thread;
|
final ChatThreadController thread;
|
||||||
final ChatUsageWarnings warnings;
|
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;
|
final DateTime Function() now;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -168,6 +175,13 @@ class _ChatUsageWarningBannerState extends State<ChatUsageWarningBanner> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (widget.accounts case final accounts?)
|
||||||
|
Flexible(
|
||||||
|
child: ChatClaudeAccountSwitchAction(
|
||||||
|
accounts: accounts,
|
||||||
|
foreground: foreground,
|
||||||
|
),
|
||||||
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
key: const Key('chat-usage-warning-dismiss'),
|
key: const Key('chat-usage-warning-dismiss'),
|
||||||
tooltip: 'Dismiss',
|
tooltip: 'Dismiss',
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ class ChatAccountUsage {
|
|||||||
required this.asOf,
|
required this.asOf,
|
||||||
required this.windows,
|
required this.windows,
|
||||||
required this.unsupported,
|
required this.unsupported,
|
||||||
|
this.switchedAt = 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
|
/// Display name of the harness ("Claude Code", "Codex", "OpenCode").
|
||||||
@@ -41,6 +42,12 @@ class ChatAccountUsage {
|
|||||||
|
|
||||||
/// The harness exposes no quota at all.
|
/// The harness exposes no quota at all.
|
||||||
final bool unsupported;
|
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) =>
|
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(
|
return ChatAccountUsage(
|
||||||
harness: harness,
|
harness: harness,
|
||||||
plan: '${value['plan'] ?? ''}'.trim(),
|
plan: '${value['plan'] ?? ''}'.trim(),
|
||||||
asOf: _millis(value['as_of']),
|
asOf: _millis(value['as_of']),
|
||||||
windows: List.unmodifiable(windows),
|
windows: List.unmodifiable(windows),
|
||||||
unsupported: false,
|
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 {},
|
orElse: () => const {},
|
||||||
);
|
);
|
||||||
if (last.isEmpty || last['role'] == 'user') return null;
|
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);
|
return chatUsageLimitFromText(_text(last), now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
/// What the composer's send-button usage ring shows: the harness account's
|
||||||
|
/// 5-hour window (the most constrained short window harnesses report), or the
|
||||||
|
/// most used window when there is no 5-hour one, and how loudly to draw it.
|
||||||
|
/// Only reported windows count; one whose reset has passed is stale and left
|
||||||
|
/// out, and nothing is estimated.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'chat_account_usage.dart';
|
||||||
|
import 'chat_usage_warning.dart';
|
||||||
|
|
||||||
|
/// How the ring is drawn: barely visible, a warning from the first warning
|
||||||
|
/// level (80%), urgent from [chatQuotaUrgentLevel] (95%).
|
||||||
|
enum ChatUsageRingTone { quiet, warning, urgent }
|
||||||
|
|
||||||
|
class ChatUsageRing {
|
||||||
|
const ChatUsageRing({required this.shown, required this.windows});
|
||||||
|
|
||||||
|
/// The window the ring's arc measures.
|
||||||
|
final ChatQuotaWindow shown;
|
||||||
|
|
||||||
|
/// Every live window, in the harness's order, for the tooltip.
|
||||||
|
final List<ChatQuotaWindow> windows;
|
||||||
|
|
||||||
|
/// The arc's share of the circle, 0–1 (past a cap stays full).
|
||||||
|
double get fraction => (shown.usedPercent / 100).clamp(0.0, 1.0);
|
||||||
|
|
||||||
|
ChatUsageRingTone get tone {
|
||||||
|
final level = chatQuotaLevel(shown.usedPercent);
|
||||||
|
if (level >= chatQuotaUrgentLevel) return ChatUsageRingTone.urgent;
|
||||||
|
if (level > 0) return ChatUsageRingTone.warning;
|
||||||
|
return ChatUsageRingTone.quiet;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _fiveHour(ChatQuotaWindow window) =>
|
||||||
|
window.id == 'five_hour' || window.label.toLowerCase() == '5-hour';
|
||||||
|
|
||||||
|
/// The ring for [usage] at [now], or null when the harness reports no quota
|
||||||
|
/// (unknown, unsupported, or every window already reset).
|
||||||
|
ChatUsageRing? chatUsageRing(ChatAccountUsage? usage, DateTime now) {
|
||||||
|
if (usage == null || usage.unsupported) return null;
|
||||||
|
final at = now.millisecondsSinceEpoch;
|
||||||
|
final live = [
|
||||||
|
for (final window in usage.windows)
|
||||||
|
if (window.resetsAt <= 0 || window.resetsAt > at) window,
|
||||||
|
];
|
||||||
|
if (live.isEmpty) return null;
|
||||||
|
var shown = live.firstWhere(_fiveHour, orElse: () => live.first);
|
||||||
|
if (!_fiveHour(shown)) {
|
||||||
|
for (final window in live) {
|
||||||
|
if (window.usedPercent > shown.usedPercent) shown = window;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ChatUsageRing(shown: shown, windows: List.unmodifiable(live));
|
||||||
|
}
|
||||||
|
|
||||||
|
const List<String> _weekdays = [
|
||||||
|
'Mon',
|
||||||
|
'Tue',
|
||||||
|
'Wed',
|
||||||
|
'Thu',
|
||||||
|
'Fri',
|
||||||
|
'Sat',
|
||||||
|
'Sun',
|
||||||
|
];
|
||||||
|
|
||||||
|
String _two(int value) => value.toString().padLeft(2, '0');
|
||||||
|
|
||||||
|
/// A reset time in local 24-hour time: "17:20" today, "Thu 09:00" within the
|
||||||
|
/// coming week, "28 Nov 09:00" further out.
|
||||||
|
String chatUsageRingResetTime(DateTime at, DateTime now) {
|
||||||
|
final local = at.toLocal();
|
||||||
|
final today = now.toLocal();
|
||||||
|
final time = '${_two(local.hour)}:${_two(local.minute)}';
|
||||||
|
final day = DateTime(local.year, local.month, local.day);
|
||||||
|
final days = day.difference(DateTime(today.year, today.month, today.day));
|
||||||
|
if (days.inHours.abs() < 12) return time;
|
||||||
|
if (!days.isNegative && days.inDays < 7) {
|
||||||
|
return '${_weekdays[local.weekday - 1]} $time';
|
||||||
|
}
|
||||||
|
const months = [
|
||||||
|
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', //
|
||||||
|
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
||||||
|
];
|
||||||
|
return '${local.day} ${months[local.month - 1]} $time';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00".
|
||||||
|
String chatUsageRingSummary(ChatUsageRing ring, DateTime now) => [
|
||||||
|
for (final window in ring.windows) ...[
|
||||||
|
'${window.label} ${window.usedPercent.round()}%',
|
||||||
|
if (window.resetsAt > 0)
|
||||||
|
'resets ${chatUsageRingResetTime(DateTime.fromMillisecondsSinceEpoch(window.resetsAt), now)}',
|
||||||
|
],
|
||||||
|
].join(' · ');
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Chat: usage ring around Send
|
||||||
|
|
||||||
|
A thin ring around the composer's send button shows the harness account's
|
||||||
|
5-hour window used share (fallback: the most used live window). Quiet
|
||||||
|
(onSurfaceVariant at 45%) below 80%, tertiary from 80%, error from 95%, on a
|
||||||
|
faint outlineVariant track. The button's tooltip (hover / long-press) becomes
|
||||||
|
"Send" plus every live window: "5-hour 42% · resets 17:20 · Weekly 61% ·
|
||||||
|
resets Thu 09:00". No ring for unknown or unsupported quota, or once every
|
||||||
|
window's reset has passed. The ring is a background CustomPaint around the
|
||||||
|
unchanged IconButton.filled, so size, hit target and states are unchanged.
|
||||||
|
|
||||||
|
Code: `lib/features/chat/domain/chat_usage_ring.dart`,
|
||||||
|
`lib/features/chat/conversation/chat_send_usage_ring.dart`.
|
||||||
|
Tests: `test/features/chat/domain/chat_usage_ring_test.dart`,
|
||||||
|
`test/features/chat/conversation/chat_send_usage_ring_test.dart`.
|
||||||
|
Captures: probe fixture `?chats=1"a=claude|warn80|warn95`, `/chat/perf-chat-0`
|
||||||
|
at 1280x900 and 412x900 (Android UA), light and dark, plus a desktop hover.
|
||||||
@@ -0,0 +1,370 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_claude_account_dialog.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_claude_accounts_controller.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_usage_limit_banner.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_usage_warning_banner.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_usage_warnings.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/domain/chat_usage_limit.dart';
|
||||||
|
import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import 'chat_thread_fixtures.dart';
|
||||||
|
|
||||||
|
final _now = DateTime.now();
|
||||||
|
|
||||||
|
JsonMap _account(String email, {bool active = false, bool saved = true}) => {
|
||||||
|
'name': email,
|
||||||
|
'email': email,
|
||||||
|
'organization': 'Org',
|
||||||
|
'plan': 'max',
|
||||||
|
'active': active,
|
||||||
|
'saved': saved,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A chat gateway whose Claude home has saved accounts; `use` makes the named
|
||||||
|
/// one active and reports the switch.
|
||||||
|
class _AccountsGateway extends FakeChatGateway {
|
||||||
|
_AccountsGateway(this.emails);
|
||||||
|
|
||||||
|
final List<String> emails;
|
||||||
|
int active = 0;
|
||||||
|
|
||||||
|
JsonMap _list({JsonMap? usage}) => {
|
||||||
|
'claude_accounts': {
|
||||||
|
'config_dir': '/home/op/caplens/.claude-profile',
|
||||||
|
'active': _account(emails[active], active: true),
|
||||||
|
'accounts': [
|
||||||
|
for (var i = 0; i < emails.length; i++)
|
||||||
|
_account(emails[i], active: i == active),
|
||||||
|
],
|
||||||
|
'usage': ?usage,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||||
|
if (!type.startsWith('claude_account')) return super.call(type, fields);
|
||||||
|
calls.add((type: type, fields: fields));
|
||||||
|
final name = '${(fields['claude_account'] as Map)['name'] ?? ''}';
|
||||||
|
if (type == 'claude_account_use') {
|
||||||
|
active = emails.indexOf(name);
|
||||||
|
return _list(
|
||||||
|
usage: {
|
||||||
|
'harness': 'Claude Code',
|
||||||
|
'plan': 'max',
|
||||||
|
'as_of': _now.millisecondsSinceEpoch,
|
||||||
|
'switched_at': _now.millisecondsSinceEpoch,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (type == 'claude_account_save') emails.add('saved:$name');
|
||||||
|
return _list();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> accountCalls() => [
|
||||||
|
for (final call in calls)
|
||||||
|
if (call.type.startsWith('claude_account'))
|
||||||
|
'${call.type} ${(call.fields['claude_account'] as Map)['name'] ?? ''}'
|
||||||
|
.trim(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonMap _limited({double five = 100}) => {
|
||||||
|
'session_id': 's',
|
||||||
|
'kind': 'usage',
|
||||||
|
'usage': {
|
||||||
|
'account': {
|
||||||
|
'harness': 'Claude Code',
|
||||||
|
'windows': [
|
||||||
|
{
|
||||||
|
'id': 'five_hour',
|
||||||
|
'label': '5-hour',
|
||||||
|
'used_percent': five,
|
||||||
|
'resets_at': _now
|
||||||
|
.add(const Duration(hours: 2))
|
||||||
|
.millisecondsSinceEpoch,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
Future<(ChatThreadController, ChatClaudeAccountsController)> _pump(
|
||||||
|
WidgetTester tester,
|
||||||
|
_AccountsGateway gateway,
|
||||||
|
Widget Function(ChatThreadController, ChatClaudeAccountsController) build,
|
||||||
|
) async {
|
||||||
|
final thread = ChatThreadController(gateway, 's');
|
||||||
|
final accounts = ChatClaudeAccountsController(
|
||||||
|
gateway: gateway,
|
||||||
|
sessionId: 's',
|
||||||
|
thread: thread,
|
||||||
|
);
|
||||||
|
addTearDown(gateway.close);
|
||||||
|
addTearDown(thread.dispose);
|
||||||
|
addTearDown(accounts.dispose);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(body: Column(children: [build(thread, accounts)])),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return (thread, accounts);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => SharedPreferences.setMockInitialValues({}));
|
||||||
|
|
||||||
|
for (final backend in ['claude', 'codex']) {
|
||||||
|
testWidgets('the chat menu offers Claude account for a $backend chat: '
|
||||||
|
'${backend == 'claude'}', (tester) async {
|
||||||
|
final gateway = _AccountsGateway([
|
||||||
|
'a@example.invalid',
|
||||||
|
'b@example.invalid',
|
||||||
|
]);
|
||||||
|
addTearDown(gateway.close);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: ChatThreadView(
|
||||||
|
gateway: gateway,
|
||||||
|
sessionId: 's',
|
||||||
|
session: {'id': 's', 'backend': backend, 'directory': '/x'},
|
||||||
|
syncToken: 0,
|
||||||
|
onBack: () {},
|
||||||
|
drafts: MemoryChatDraftStore(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
// A chat with nothing else to offer has no More menu at all.
|
||||||
|
final more = find.byKey(segmentedMoreKey).hitTestable();
|
||||||
|
if (more.evaluate().isNotEmpty) {
|
||||||
|
await tester.tap(more.first);
|
||||||
|
await tester.pump(const Duration(milliseconds: 500));
|
||||||
|
}
|
||||||
|
final entry = find.text('Claude account');
|
||||||
|
if (backend != 'claude') {
|
||||||
|
expect(entry, findsNothing);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
expect(entry, findsOneWidget);
|
||||||
|
await tester.tap(entry);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 500));
|
||||||
|
expect(gateway.accountCalls(), ['claude_accounts']);
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('chat-claude-account-b@example.invalid')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a switched report replaces the old one and voids an old refusal', () {
|
||||||
|
final usage = chatAccountUsage({
|
||||||
|
'harness': 'Claude Code',
|
||||||
|
'switched_at': 2000,
|
||||||
|
});
|
||||||
|
expect(usage, isNotNull);
|
||||||
|
expect(usage!.switchedAt, 2000);
|
||||||
|
expect(usage.windows, isEmpty);
|
||||||
|
expect(chatAccountUsage({'harness': 'Claude Code'}), isNull);
|
||||||
|
final reset = _now.add(const Duration(hours: 1));
|
||||||
|
final refusal = {
|
||||||
|
'id': 'm',
|
||||||
|
'role': 'assistant',
|
||||||
|
'created_at': 1000,
|
||||||
|
'parts': [
|
||||||
|
{
|
||||||
|
'type': 'text',
|
||||||
|
'text':
|
||||||
|
'Claude AI usage limit reached|'
|
||||||
|
'${reset.millisecondsSinceEpoch ~/ 1000}',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
expect(chatThreadUsageLimit(null, [refusal], _now), isNotNull);
|
||||||
|
expect(chatThreadUsageLimit(usage, [refusal], _now), isNull);
|
||||||
|
final later = {...refusal, 'created_at': 3000};
|
||||||
|
expect(chatThreadUsageLimit(usage, [later], _now), isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the Claude account menu checks the active account and switches '
|
||||||
|
'with one tap', (tester) async {
|
||||||
|
final gateway = _AccountsGateway([
|
||||||
|
'a@example.invalid',
|
||||||
|
'b@example.invalid',
|
||||||
|
]);
|
||||||
|
late ChatClaudeAccountsController accounts;
|
||||||
|
await _pump(tester, gateway, (thread, controller) {
|
||||||
|
accounts = controller;
|
||||||
|
return Builder(
|
||||||
|
builder: (context) => TextButton(
|
||||||
|
onPressed: () => showChatClaudeAccountsDialog(context, accounts),
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Claude account'), findsOneWidget);
|
||||||
|
final active = find.byKey(
|
||||||
|
const Key('chat-claude-account-a@example.invalid'),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
find.descendant(of: active, matching: find.byIcon(Icons.check)),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
final other = find.byKey(
|
||||||
|
const Key('chat-claude-account-b@example.invalid'),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
find.descendant(of: other, matching: find.byIcon(Icons.check)),
|
||||||
|
findsNothing,
|
||||||
|
);
|
||||||
|
expect(find.text('Save current account…'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(other);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(gateway.accountCalls(), [
|
||||||
|
'claude_accounts',
|
||||||
|
'claude_account_use b@example.invalid',
|
||||||
|
]);
|
||||||
|
expect(find.text('Claude account'), findsNothing);
|
||||||
|
expect(
|
||||||
|
find.text('Switched to b@example.invalid — send a message to continue'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'Save current account asks for a name, prefilled with the email',
|
||||||
|
(tester) async {
|
||||||
|
final gateway = _AccountsGateway(['a@example.invalid']);
|
||||||
|
await _pump(
|
||||||
|
tester,
|
||||||
|
gateway,
|
||||||
|
(thread, accounts) => Builder(
|
||||||
|
builder: (context) => TextButton(
|
||||||
|
onPressed: () => showChatClaudeAccountsDialog(context, accounts),
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byKey(const Key('chat-claude-account-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final field = tester.widget<TextField>(
|
||||||
|
find.byKey(const Key('chat-claude-account-name')),
|
||||||
|
);
|
||||||
|
expect(field.controller!.text, 'a@example.invalid');
|
||||||
|
await tester.enterText(
|
||||||
|
find.byKey(const Key('chat-claude-account-name')),
|
||||||
|
'Work',
|
||||||
|
);
|
||||||
|
await tester.tap(find.byKey(const Key('chat-claude-account-name-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(gateway.accountCalls().last, 'claude_account_save Work');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('the usage-limit banner offers the other account and clears '
|
||||||
|
'once switched', (tester) async {
|
||||||
|
final gateway = _AccountsGateway([
|
||||||
|
'a@example.invalid',
|
||||||
|
'b@example.invalid',
|
||||||
|
]);
|
||||||
|
final composer = ChatComposerController(gateway, 's');
|
||||||
|
addTearDown(composer.dispose);
|
||||||
|
final (thread, _) = await _pump(
|
||||||
|
tester,
|
||||||
|
gateway,
|
||||||
|
(thread, accounts) => ChatUsageLimitBanner(
|
||||||
|
thread: thread,
|
||||||
|
composer: composer,
|
||||||
|
sendDraft: (_) async {},
|
||||||
|
accounts: accounts,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
gateway.emitEvent(_limited());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const Key('chat-usage-limit')), findsOneWidget);
|
||||||
|
final action = find.byKey(const Key('chat-claude-switch'));
|
||||||
|
expect(
|
||||||
|
find.descendant(
|
||||||
|
of: action,
|
||||||
|
matching: find.text('Switch to b@example.invalid'),
|
||||||
|
),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
await tester.tap(action);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(gateway.accountCalls().last, 'claude_account_use b@example.invalid');
|
||||||
|
expect(thread.accountUsage?.switchedAt, greaterThan(0));
|
||||||
|
expect(find.byKey(const Key('chat-usage-limit')), findsNothing);
|
||||||
|
expect(
|
||||||
|
find.text('Switched to b@example.invalid — send a message to continue'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('with several other accounts the warning banner offers a menu', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final gateway = _AccountsGateway([
|
||||||
|
'a@example.invalid',
|
||||||
|
'b@example.invalid',
|
||||||
|
'c@example.invalid',
|
||||||
|
]);
|
||||||
|
await _pump(
|
||||||
|
tester,
|
||||||
|
gateway,
|
||||||
|
(thread, accounts) => ChatUsageWarningBanner(
|
||||||
|
thread: thread,
|
||||||
|
warnings: ChatUsageWarnings(announce: (_) => true),
|
||||||
|
accounts: accounts,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
gateway.emitEvent(_limited(five: 90));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
|
||||||
|
await tester.tap(find.text('Switch account'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('chat-claude-switch-to-a@example.invalid')),
|
||||||
|
findsNothing,
|
||||||
|
);
|
||||||
|
await tester.tap(
|
||||||
|
find.byKey(const Key('chat-claude-switch-to-c@example.invalid')),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(gateway.accountCalls().last, 'claude_account_use c@example.invalid');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a banner without another saved account offers no switch', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final gateway = _AccountsGateway(['a@example.invalid']);
|
||||||
|
await _pump(
|
||||||
|
tester,
|
||||||
|
gateway,
|
||||||
|
(thread, accounts) => ChatUsageWarningBanner(
|
||||||
|
thread: thread,
|
||||||
|
warnings: ChatUsageWarnings(announce: (_) => true),
|
||||||
|
accounts: accounts,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
gateway.emitEvent(_limited(five: 90));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const Key('chat-usage-warning')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('chat-claude-switch')), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
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_send_usage_ring.dart';
|
||||||
|
|
||||||
|
import 'chat_composer_bar_fixtures.dart';
|
||||||
|
|
||||||
|
JsonMap _usage(Object account) => {
|
||||||
|
'session_id': 's',
|
||||||
|
'kind': 'usage',
|
||||||
|
'usage': {'account': account},
|
||||||
|
};
|
||||||
|
|
||||||
|
JsonMap _quota({double five = 42, double week = 61}) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
return _usage({
|
||||||
|
'harness': 'Claude Code',
|
||||||
|
'plan': 'max',
|
||||||
|
'windows': [
|
||||||
|
{
|
||||||
|
'id': 'five_hour',
|
||||||
|
'label': '5-hour',
|
||||||
|
'used_percent': five,
|
||||||
|
'resets_at': now.add(const Duration(hours: 2)).millisecondsSinceEpoch,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'id': 'seven_day',
|
||||||
|
'label': 'Weekly',
|
||||||
|
'used_percent': week,
|
||||||
|
'resets_at': now.add(const Duration(days: 3)).millisecondsSinceEpoch,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
final _primary = find.byKey(const Key('chat-composer-primary'));
|
||||||
|
|
||||||
|
ChatUsageRingPainter? _painter(WidgetTester tester) {
|
||||||
|
final paint = tester.widget<CustomPaint>(
|
||||||
|
find.ancestor(of: _primary, matching: find.byType(CustomPaint)).first,
|
||||||
|
);
|
||||||
|
final painter = paint.painter;
|
||||||
|
return painter is ChatUsageRingPainter ? painter : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _tooltip(WidgetTester tester) => tester
|
||||||
|
.widget<Tooltip>(
|
||||||
|
find.ancestor(
|
||||||
|
of: find.byIcon(Icons.arrow_upward),
|
||||||
|
matching: find.byType(Tooltip),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.message;
|
||||||
|
|
||||||
|
ColorScheme _scheme(WidgetTester tester) =>
|
||||||
|
Theme.of(tester.element(_primary)).colorScheme;
|
||||||
|
|
||||||
|
Future<ComposerBarGateway> _open(WidgetTester tester) async {
|
||||||
|
final gateway = ComposerBarGateway();
|
||||||
|
addTearDown(gateway.close);
|
||||||
|
await tester.pumpWidget(composerThread(gateway));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
return gateway;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _emit(
|
||||||
|
WidgetTester tester,
|
||||||
|
ComposerBarGateway gateway,
|
||||||
|
JsonMap frame,
|
||||||
|
) async {
|
||||||
|
gateway.emitEvent(frame);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('no report: no ring and the plain Send tooltip', (tester) async {
|
||||||
|
await _open(tester);
|
||||||
|
expect(_primary, findsOneWidget);
|
||||||
|
expect(_painter(tester), isNull);
|
||||||
|
expect(_tooltip(tester), 'Send');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a report draws a quiet ring at the 5-hour share and lists '
|
||||||
|
'every window in the tooltip, without moving the button', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
final before = tester.getRect(_primary);
|
||||||
|
await _emit(tester, gateway, _quota());
|
||||||
|
final painter = _painter(tester)!;
|
||||||
|
expect(painter.fraction, closeTo(.42, 1e-9));
|
||||||
|
expect(
|
||||||
|
painter.color,
|
||||||
|
_scheme(tester).onSurfaceVariant.withValues(alpha: .45),
|
||||||
|
);
|
||||||
|
expect(tester.getRect(_primary), before);
|
||||||
|
final tooltip = _tooltip(tester)!;
|
||||||
|
expect(tooltip, startsWith('Send\n5-hour 42% · resets '));
|
||||||
|
expect(tooltip, contains(' · Weekly 61% · resets '));
|
||||||
|
// The button is still the same element: a report never remounts it.
|
||||||
|
expect(find.byType(IconButton), findsWidgets);
|
||||||
|
// Assistive technology still names it by its label alone.
|
||||||
|
expect(find.bySemanticsLabel('Send'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('long-press shows the usage tooltip on touch', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
await _emit(tester, gateway, _quota());
|
||||||
|
await tester.longPress(_primary);
|
||||||
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
expect(find.textContaining('5-hour 42%'), findsOneWidget);
|
||||||
|
await tester.pump(const Duration(seconds: 2));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('tertiary from 80%, error from 95%', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
await _emit(tester, gateway, _quota(five: 84, week: 99));
|
||||||
|
expect(_painter(tester)!.color, _scheme(tester).tertiary);
|
||||||
|
await _emit(tester, gateway, _quota(five: 96));
|
||||||
|
expect(_painter(tester)!.color, _scheme(tester).error);
|
||||||
|
expect(_painter(tester)!.fraction, closeTo(.96, 1e-9));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('an unsupported harness draws no ring', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
await _emit(
|
||||||
|
tester,
|
||||||
|
gateway,
|
||||||
|
_usage({'harness': 'OpenCode', 'unsupported': true}),
|
||||||
|
);
|
||||||
|
expect(_painter(tester), isNull);
|
||||||
|
expect(_tooltip(tester), 'Send');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Send still sends with the ring shown', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
await _emit(tester, gateway, _quota());
|
||||||
|
await tester.enterText(find.byKey(const Key('chat-composer-field')), 'hi');
|
||||||
|
await tester.pump();
|
||||||
|
await tester.tap(_primary);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(gateway.promptBodies.single['text'], 'hi');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the ring hugs the visible circle outside it', (tester) async {
|
||||||
|
final gateway = await _open(tester);
|
||||||
|
await _emit(tester, gateway, _quota());
|
||||||
|
final painter = _painter(tester)!;
|
||||||
|
final circle = tester.getSize(
|
||||||
|
find.descendant(of: _primary, matching: find.byType(Material)).first,
|
||||||
|
);
|
||||||
|
expect(painter.circle, circle.width);
|
||||||
|
expect(
|
||||||
|
painter.radius - ChatUsageRingPainter.stroke / 2,
|
||||||
|
circle.width / 2 + ChatUsageRingPainter.gap,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/domain/chat_usage_ring.dart';
|
||||||
|
|
||||||
|
final _now = DateTime(2026, 11, 30, 12); // a Monday
|
||||||
|
|
||||||
|
ChatQuotaWindow _window(String id, String label, double used, DateTime? at) =>
|
||||||
|
ChatQuotaWindow(
|
||||||
|
id: id,
|
||||||
|
label: label,
|
||||||
|
usedPercent: used,
|
||||||
|
resetsAt: at?.millisecondsSinceEpoch ?? 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
ChatAccountUsage _usage(List<ChatQuotaWindow> windows) => ChatAccountUsage(
|
||||||
|
harness: 'Claude Code',
|
||||||
|
plan: 'max',
|
||||||
|
asOf: 0,
|
||||||
|
windows: windows,
|
||||||
|
unsupported: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('shows the 5-hour window even when another is higher', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([
|
||||||
|
_window('seven_day', 'Weekly', 93, null),
|
||||||
|
_window('five_hour', '5-hour', 42, null),
|
||||||
|
]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(ring.shown.label, '5-hour');
|
||||||
|
expect(ring.fraction, closeTo(.42, 1e-9));
|
||||||
|
expect(ring.tone, ChatUsageRingTone.quiet);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a harness labelling its window "5-hour" counts as the 5-hour', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([
|
||||||
|
_window('secondary', 'Weekly', 70, null),
|
||||||
|
_window('primary', '5-hour', 10, null),
|
||||||
|
]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(ring.shown.id, 'primary');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('without a 5-hour window the most used one is shown', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([
|
||||||
|
_window('a', 'Daily', 20, null),
|
||||||
|
_window('b', 'Weekly', 61, null),
|
||||||
|
]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(ring.shown.label, 'Weekly');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tones: quiet below 80, warning from 80, urgent from 95', () {
|
||||||
|
ChatUsageRingTone tone(double used) => chatUsageRing(
|
||||||
|
_usage([_window('five_hour', '5-hour', used, null)]),
|
||||||
|
_now,
|
||||||
|
)!.tone;
|
||||||
|
expect(tone(79.4), ChatUsageRingTone.quiet);
|
||||||
|
expect(tone(80), ChatUsageRingTone.warning);
|
||||||
|
expect(tone(94.9), ChatUsageRingTone.warning);
|
||||||
|
expect(tone(95), ChatUsageRingTone.urgent);
|
||||||
|
expect(tone(130), ChatUsageRingTone.urgent);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('past a cap the ring is full, never more', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([_window('five_hour', '5-hour', 130, null)]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(ring.fraction, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no ring for unknown, unsupported or entirely reset quota', () {
|
||||||
|
expect(chatUsageRing(null, _now), isNull);
|
||||||
|
expect(
|
||||||
|
chatUsageRing(
|
||||||
|
const ChatAccountUsage(
|
||||||
|
harness: 'OpenCode',
|
||||||
|
plan: '',
|
||||||
|
asOf: 0,
|
||||||
|
windows: [],
|
||||||
|
unsupported: true,
|
||||||
|
),
|
||||||
|
_now,
|
||||||
|
),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
final past = _now.subtract(const Duration(minutes: 1));
|
||||||
|
expect(
|
||||||
|
chatUsageRing(_usage([_window('five_hour', '5-hour', 90, past)]), _now),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a reset 5-hour window falls back to the live ones', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([
|
||||||
|
_window(
|
||||||
|
'five_hour',
|
||||||
|
'5-hour',
|
||||||
|
90,
|
||||||
|
_now.subtract(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
_window('seven_day', 'Weekly', 61, null),
|
||||||
|
]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(ring.shown.label, 'Weekly');
|
||||||
|
expect(ring.windows.map((w) => w.label), ['Weekly']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('summary names every window with its reset time', () {
|
||||||
|
final ring = chatUsageRing(
|
||||||
|
_usage([
|
||||||
|
_window('five_hour', '5-hour', 42.4, DateTime(2026, 11, 30, 17, 20)),
|
||||||
|
_window('seven_day', 'Weekly', 61, DateTime(2026, 12, 3, 9)),
|
||||||
|
]),
|
||||||
|
_now,
|
||||||
|
)!;
|
||||||
|
expect(
|
||||||
|
chatUsageRingSummary(ring, _now),
|
||||||
|
'5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reset times: today, this week, further out', () {
|
||||||
|
expect(chatUsageRingResetTime(DateTime(2026, 11, 30, 8, 5), _now), '08:05');
|
||||||
|
expect(
|
||||||
|
chatUsageRingResetTime(DateTime(2026, 12, 1, 0, 30), _now),
|
||||||
|
'Tue 00:30',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
chatUsageRingResetTime(DateTime(2026, 12, 9, 9), _now),
|
||||||
|
'9 Dec 09:00',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<String, String> _params = const {};
|
||||||
|
int _active = 0;
|
||||||
|
|
||||||
|
const _emails = [
|
||||||
|
'alex@caplens.example',
|
||||||
|
'sam@caplens.example',
|
||||||
|
'ops@caplens.example',
|
||||||
|
];
|
||||||
|
|
||||||
|
void configureChatClaudeAccountsFixture(Map<String, String> 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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
// (tool/perf/chat_new_session_fixture.dart).
|
// (tool/perf/chat_new_session_fixture.dart).
|
||||||
import 'package:pipelines_app/core/api_gateway.dart';
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
|
|
||||||
|
import 'chat_claude_accounts_fixture.dart';
|
||||||
import 'chat_effort_fixture.dart';
|
import 'chat_effort_fixture.dart';
|
||||||
import 'chat_catalog_fixture.dart';
|
import 'chat_catalog_fixture.dart';
|
||||||
import 'chat_new_session_fixture.dart';
|
import 'chat_new_session_fixture.dart';
|
||||||
@@ -47,6 +48,7 @@ void configurePerfFixture(Map<String, String> params) {
|
|||||||
);
|
);
|
||||||
configureChatScrollFixture(params);
|
configureChatScrollFixture(params);
|
||||||
configureChatShownPush(params);
|
configureChatShownPush(params);
|
||||||
|
configureChatClaudeAccountsFixture(params);
|
||||||
configureChatQuestionFixture(params);
|
configureChatQuestionFixture(params);
|
||||||
configureChatShellFixture(params);
|
configureChatShellFixture(params);
|
||||||
configureTerminalFixture(params);
|
configureTerminalFixture(params);
|
||||||
@@ -281,6 +283,8 @@ JsonMap? perfChatReply(JsonMap request) {
|
|||||||
final terminal = terminalFixtureReply(request);
|
final terminal = terminalFixtureReply(request);
|
||||||
if (terminal != null) return terminal;
|
if (terminal != null) return terminal;
|
||||||
if (_chats == 0) return null;
|
if (_chats == 0) return null;
|
||||||
|
final accounts = chatClaudeAccountsReply(request);
|
||||||
|
if (accounts != null) return accounts;
|
||||||
final question = chatQuestionReply(request);
|
final question = chatQuestionReply(request);
|
||||||
if (question != null) return question;
|
if (question != null) return question;
|
||||||
final shell = chatShellReply(request);
|
final shell = chatShellReply(request);
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
|||||||
import 'fixture_host/fixture_host.dart';
|
import 'fixture_host/fixture_host.dart';
|
||||||
import 'perf/chat_search_fixture.dart';
|
import 'perf/chat_search_fixture.dart';
|
||||||
import 'perf/chat_shown_fixture.dart';
|
import 'perf/chat_shown_fixture.dart';
|
||||||
|
import 'perf/chat_claude_accounts_fixture.dart';
|
||||||
import 'perf/chat_question_fixture.dart';
|
import 'perf/chat_question_fixture.dart';
|
||||||
import 'capture/window_probe.dart';
|
import 'capture/window_probe.dart';
|
||||||
import 'perf/chat_scroll_fixture.dart';
|
import 'perf/chat_scroll_fixture.dart';
|
||||||
@@ -824,6 +825,13 @@ class _FixtureChannel implements WebSocketChannel {
|
|||||||
chatScrollStream('${subscribe['session_id'] ?? ''}', emit);
|
chatScrollStream('${subscribe['session_id'] ?? ''}', emit);
|
||||||
chatQuestionStream('${subscribe['session_id'] ?? ''}', emit);
|
chatQuestionStream('${subscribe['session_id'] ?? ''}', emit);
|
||||||
chatShownPush('${subscribe['session_id'] ?? ''}', emit);
|
chatShownPush('${subscribe['session_id'] ?? ''}', emit);
|
||||||
|
final usage = chatClaudeUsageFrame('${subscribe['session_id'] ?? ''}');
|
||||||
|
if (usage != null) {
|
||||||
|
Future<void>.delayed(
|
||||||
|
const Duration(milliseconds: 300),
|
||||||
|
() => emit(usage),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (reply == null && followUps.isEmpty) return;
|
if (reply == null && followUps.isEmpty) return;
|
||||||
Future<void>.delayed(const Duration(milliseconds: 120), () {
|
Future<void>.delayed(const Duration(milliseconds: 120), () {
|
||||||
|
|||||||
+39
@@ -520,6 +520,45 @@ five minutes) and merges `account/rateLimits/updated` notifications.
|
|||||||
OpenCode has no quota API, so it sends `{"harness":"OpenCode","unsupported":true}`.
|
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
|
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.
|
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
|
||||||
|
`<config dir>/pipelines-accounts/<slug>/` (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 <name> | remove <name>
|
||||||
|
[--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
|
The brokered OpenCode chat exposes the operator's own sessions, separate from the
|
||||||
sessions pipeline runs create. The protocol types are:
|
sessions pipeline runs create. The protocol types are:
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -123,8 +123,13 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
|
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
|
||||||
if next.Plan == "" && previous != nil {
|
if previous != nil {
|
||||||
next.Plan = previous.Plan
|
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 {
|
for _, entry := range quotaWindowOrder {
|
||||||
if w, ok := windows[entry.id]; ok {
|
if w, ok := windows[entry.id]; ok {
|
||||||
|
|||||||
@@ -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
|
||||||
|
// <config>/.oauth_refresh.lock while it refreshes a token,
|
||||||
|
// <config>/.storage-write.lock around every credential write and
|
||||||
|
// <config>/.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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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 <config>/pipelines-accounts/<slug>/ (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
|
||||||
|
}
|
||||||
@@ -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\": \"<a&b>\"\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, `"<a&b>"`) {
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -294,6 +294,9 @@ func (a App) Run(ctx context.Context, args []string) error {
|
|||||||
if len(args) > 0 && args[0] == "harness" {
|
if len(args) > 0 && args[0] == "harness" {
|
||||||
return a.harness(ctx, args[1:])
|
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" {
|
if len(args) > 0 && args[0] == "--version" {
|
||||||
args = append([]string{"version"}, args[1:]...)
|
args = append([]string{"version"}, args[1:]...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 <name> | remove <name> [--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, ", ") + ")"
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,6 +38,7 @@ var usage = map[string]string{
|
|||||||
"stats": "stats [--json]",
|
"stats": "stats [--json]",
|
||||||
"rpc": "rpc <request.json|->",
|
"rpc": "rpc <request.json|->",
|
||||||
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
|
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
|
||||||
|
"claude-account": "claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]",
|
||||||
"tui": "tui",
|
"tui": "tui",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ SERVER / INTERFACE
|
|||||||
harness setup <claude|codex|opencode|pi>
|
harness setup <claude|codex|opencode|pi>
|
||||||
Install check, sign-in, models and verify for one harness
|
Install check, sign-in, models and verify for one harness
|
||||||
harness list Installed / signed-in / configured / default for all four
|
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)
|
tui Open the dashboard (default with no command)
|
||||||
serve Start native server in the foreground (Ctrl+C stops it)
|
serve Start native server in the foreground (Ctrl+C stops it)
|
||||||
service enable Configure user autostart
|
service enable Configure user autostart
|
||||||
|
|||||||
@@ -812,6 +812,11 @@ type ChatAccountUsage struct {
|
|||||||
AsOf int64 `json:"as_of,omitempty"`
|
AsOf int64 `json:"as_of,omitempty"`
|
||||||
Windows []ChatQuotaWindow `json:"windows,omitempty"`
|
Windows []ChatQuotaWindow `json:"windows,omitempty"`
|
||||||
Unsupported bool `json:"unsupported,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
|
// ChatQuotaWindow is one rolling quota window. UsedPercent is 0-100 (it can
|
||||||
|
|||||||
@@ -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 <config dir>/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"`
|
||||||
|
}
|
||||||
@@ -250,6 +250,10 @@ type Message struct {
|
|||||||
ChatModels []ChatModel `json:"chat_models,omitempty"`
|
ChatModels []ChatModel `json:"chat_models,omitempty"`
|
||||||
// ChatCommands is the chat_commands reply: the session's slash commands.
|
// ChatCommands is the chat_commands reply: the session's slash commands.
|
||||||
ChatCommands []ChatCommand `json:"chat_commands,omitempty"`
|
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 is the chat_model body and echoed selection.
|
||||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||||
|
|||||||
@@ -253,6 +253,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
|||||||
case protocol.ChatCommands:
|
case protocol.ChatCommands:
|
||||||
handleChatCommands(ctx, request, broker, write)
|
handleChatCommands(ctx, request, broker, write)
|
||||||
return true
|
return true
|
||||||
|
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove:
|
||||||
|
handleClaudeAccounts(ctx, request, broker, write)
|
||||||
|
return true
|
||||||
case protocol.ChatModelSelect:
|
case protocol.ChatModelSelect:
|
||||||
handleChatModelSwitch(ctx, request, broker, write)
|
handleChatModelSwitch(ctx, request, broker, write)
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -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})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user