Merge branch 'worktree-agent-a241489d88c80f413'

This commit is contained in:
2026-11-30 16:35:25 +00:00
22 changed files with 386 additions and 62 deletions
@@ -68,13 +68,15 @@ class _ChatAccountUsageSectionState extends State<ChatAccountUsageSection> {
), ),
) )
else ...[ else ...[
if (plan.isNotEmpty) if (plan.isNotEmpty || usage.email.isNotEmpty)
Padding( Padding(
padding: const EdgeInsets.only(top: 4), padding: const EdgeInsets.only(top: 4),
child: Text( child: Text(
usage.harness.isEmpty [
? '$plan plan' if (usage.email.isNotEmpty) usage.email,
: '${usage.harness} · $plan plan', if (usage.harness.isNotEmpty) usage.harness,
if (plan.isNotEmpty) '$plan plan',
].join(' · '),
key: const Key('chat-account-usage-plan'), key: const Key('chat-account-usage-plan'),
style: muted, style: muted,
), ),
@@ -9,8 +9,9 @@ import '../domain/chat_usage_ring.dart';
/// A thin ring around the composer's send button showing how much of the /// A thin ring around the composer's send button showing how much of the
/// harness account's quota is used ([chatUsageRing]): barely visible /// harness account's quota is used ([chatUsageRing]): barely visible
/// normally, the tertiary colour from 80% and the error colour from 95%. The /// 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: /// button's tooltip (hover, or long-press on touch) adds the account and
/// "Send" then "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00". /// every window: "Send" then "sam@example.com · 5-hour 42% · resets 17:20 ·
/// Weekly 61% · resets Thu 09:00" ([chatSendTooltip]).
/// ///
/// The ring is painted beside the button, never in its layout or hit test, /// 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 /// so the button keeps its size, target, states and animations. Without a
@@ -72,17 +73,14 @@ class _ChatSendUsageRingState extends State<ChatSendUsageRing> {
Widget _ring(BuildContext context) { Widget _ring(BuildContext context) {
final now = widget.now(); final now = widget.now();
final ring = chatUsageRing(widget.usage(), now); final usage = widget.usage();
final ring = chatUsageRing(usage, now);
_ticking(ring != null); _ticking(ring != null);
// The button stays the same child with or without a ring, so a report // The button stays the same child with or without a ring, so a report
// arriving never remounts it (its hover, focus and ink stay). // arriving never remounts it (its hover, focus and ink stay).
return CustomPaint( return CustomPaint(
painter: ring == null ? null : _painter(context, ring), painter: ring == null ? null : _painter(context, ring),
child: widget.button( child: widget.button(chatSendTooltip(widget.label, usage, ring, now)),
ring == null
? widget.label
: '${widget.label}\n${chatUsageRingSummary(ring, now)}',
),
); );
} }
@@ -513,6 +513,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
controller.transcriptChanges.addListener( controller.transcriptChanges.addListener(
() => _reconcileUnsent(controller), () => _reconcileUnsent(controller),
); );
// The menu's Claude account item names the signed-in account, which a
// usage frame (not a transcript change) reports.
var email = controller.accountUsage?.email;
controller.addListener(() {
final now = controller.accountUsage?.email;
if (now == email) return;
email = now;
if (mounted) setState(() {});
});
// Delivery states follow the server's queue reports. Read the composer // Delivery states follow the server's queue reports. Read the composer
// when the report arrives: it is not built yet while this one is. // when the report arrives: it is not built yet while this one is.
controller.onQueue = (queue) { controller.onQueue = (queue) {
@@ -1559,6 +1568,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_controller.running, _controller.running,
// The More menu offers Dismiss all finished commands only with one. // The More menu offers Dismiss all finished commands only with one.
_shellRuns.finishedIds.isNotEmpty, _shellRuns.finishedIds.isNotEmpty,
// The Claude account item names the signed-in account.
_controller.accountUsage?.email,
], ],
() => _buildHeader(session, inShellBar, canGoBack, answeredBy, inWindow), () => _buildHeader(session, inShellBar, canGoBack, answeredBy, inWindow),
); );
@@ -1651,6 +1662,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
ChatBarAction( ChatBarAction(
key: const Key('chat-claude-account-menu'), key: const Key('chat-claude-account-menu'),
label: 'Claude account', label: 'Claude account',
// The account the chat's Claude Code is signed in to now.
subtitle: _controller.accountUsage?.email,
identifier: 'chat-claude-account', identifier: 'chat-claude-account',
onPressed: () => onPressed: () =>
unawaited(showChatClaudeAccountsDialog(context, accounts)), unawaited(showChatClaudeAccountsDialog(context, accounts)),
@@ -14,7 +14,8 @@ import 'chat_thread_controller.dart';
/// Above the composer while the chat's account is out of quota, as Claude /// Above the composer while the chat's account is out of quota, as Claude
/// Code's own app shows it: "Out of usage credits" (or the refusal's own /// Code's own app shows it: "Out of usage credits" (or the refusal's own
/// "You've hit your 5-hour limit"), "Auto-resuming at 15:41", an /// "You've hit your 5-hour limit"), the account that hit it and
/// "Auto-resuming at 15:41", an
/// "Auto-continue when limits reset" checkbox and Try again. /// "Auto-continue when limits reset" checkbox and Try again.
/// ///
/// With auto-continue on (a preference shared by every chat, on by default, /// With auto-continue on (a preference shared by every chat, on by default,
@@ -179,7 +180,10 @@ class _ChatUsageLimitBannerState extends State<ChatUsageLimitBanner> {
final resumesAt = pending.isEmpty final resumesAt = pending.isEmpty
? limit.sendAt ? limit.sendAt
: chatScheduledSendAt(pending.first['send_at'], now)!; : chatScheduledSendAt(pending.first['send_at'], now)!;
final email = widget.thread.accountUsage?.email ?? '';
final status = [ final status = [
// The account that hit the limit.
if (email.isNotEmpty) email,
if (enabled && refused != null) if (enabled && refused != null)
'Auto-resuming at ${time(resumesAt)}' 'Auto-resuming at ${time(resumesAt)}'
else else
@@ -31,8 +31,15 @@ class ChatAccountUsage {
required this.unsupported, required this.unsupported,
this.switchedAt = 0, this.switchedAt = 0,
this.extraUsage, this.extraUsage,
this.email = '',
this.organization = '',
}); });
/// The account the harness is signed in to now ("sam@example.com"); empty
/// when it did not say (an API key, or a harness without accounts).
final String email;
final String organization;
/// Display name of the harness ("Claude Code", "Codex", "OpenCode"). /// Display name of the harness ("Claude Code", "Codex", "OpenCode").
final String harness; final String harness;
final String plan; final String plan;
@@ -131,9 +138,10 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
} }
} }
final switchedAt = _millis(value['switched_at']); final switchedAt = _millis(value['switched_at']);
// A switched account replaces the previous report even with no windows final email = '${value['email'] ?? ''}'.trim();
// yet; otherwise an empty report keeps the last one. // A switched or newly named account replaces the previous report even with
if (windows.isEmpty && switchedAt == 0) return null; // no windows yet; otherwise an empty report keeps the last one.
if (windows.isEmpty && switchedAt == 0 && email.isEmpty) return null;
return ChatAccountUsage( return ChatAccountUsage(
harness: harness, harness: harness,
plan: '${value['plan'] ?? ''}'.trim(), plan: '${value['plan'] ?? ''}'.trim(),
@@ -142,6 +150,8 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
unsupported: false, unsupported: false,
switchedAt: switchedAt, switchedAt: switchedAt,
extraUsage: _extraUsage(value['extra_usage']), extraUsage: _extraUsage(value['extra_usage']),
email: email,
organization: '${value['organization'] ?? ''}'.trim(),
); );
} }
@@ -100,6 +100,22 @@ String chatUsageRingResetTime(DateTime at, DateTime now) {
return '${local.day} ${months[local.month - 1]} $time'; return '${local.day} ${months[local.month - 1]} $time';
} }
/// The send button's tooltip: [label] ("Send"), then the account the chat
/// runs on and its usage: "sam@example.com · 5-hour 42% · resets 17:20 · …".
/// Either part may be missing; with neither the tooltip is the label alone.
String chatSendTooltip(
String label,
ChatAccountUsage? usage,
ChatUsageRing? ring,
DateTime now,
) {
final line = [
if (usage?.email case final email? when email.isNotEmpty) email,
if (ring != null) chatUsageRingSummary(ring, now),
].join(' · ');
return line.isEmpty ? label : '$label\n$line';
}
/// "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00", then any /// "5-hour 42% · resets 17:20 · Weekly 61% · resets Thu 09:00", then any
/// extra usage note. /// extra usage note.
String chatUsageRingSummary(ChatUsageRing ring, DateTime now) => [ String chatUsageRingSummary(ChatUsageRing ring, DateTime now) => [
@@ -9,9 +9,14 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
required this.materialIcon, required this.materialIcon,
this.identifier, this.identifier,
this.destructive = false, this.destructive = false,
this.subtitle,
}); });
final String label; final String label;
/// A short second line the More menu shows under [label] (the account the
/// action acts on); the bar's icon button adds it to its tooltip.
final String? subtitle;
final VoidCallback onPressed; final VoidCallback onPressed;
final IconData materialIcon; final IconData materialIcon;
@@ -27,14 +32,18 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
icon: materialIcon, icon: materialIcon,
onPressed: onPressed, onPressed: onPressed,
destructive: destructive, destructive: destructive,
subtitle: subtitle,
); );
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final subtitle = this.subtitle;
return Semantics( return Semantics(
identifier: identifier, identifier: identifier,
child: IconButton( child: IconButton(
tooltip: label, tooltip: subtitle == null || subtitle.isEmpty
? label
: '$label\n$subtitle',
onPressed: onPressed, onPressed: onPressed,
icon: Icon(materialIcon), icon: Icon(materialIcon),
), ),
@@ -11,11 +11,15 @@ class AppSheetAction {
this.selected = false, this.selected = false,
this.choices = const [], this.choices = const [],
this.key, this.key,
this.subtitle,
}); });
final String label; final String label;
final IconData? icon; final IconData? icon;
/// A short second line under [label].
final String? subtitle;
/// Runs once the sheet has closed. Null (with no [choices]) disables it. /// Runs once the sheet has closed. Null (with no [choices]) disables it.
final VoidCallback? onSelected; final VoidCallback? onSelected;
@@ -162,6 +166,10 @@ class _ActionRow extends StatelessWidget {
action.label, action.label,
style: color == null || !enabled ? null : TextStyle(color: color), style: color == null || !enabled ? null : TextStyle(color: color),
), ),
subtitle: switch (action.subtitle) {
final subtitle? when subtitle.isNotEmpty => Text(subtitle),
_ => null,
},
trailing: action.choices.isNotEmpty trailing: action.choices.isNotEmpty
? const Icon(Icons.chevron_right) ? const Icon(Icons.chevron_right)
: action.selected : action.selected
@@ -30,11 +30,15 @@ class SegmentedOverflowEntry {
this.choices = const [], this.choices = const [],
this.shortcut, this.shortcut,
this.destructive = false, this.destructive = false,
this.subtitle,
}); });
final String label; final String label;
final IconData icon; final IconData icon;
/// A short second line under [label] (the account an entry acts on).
final String? subtitle;
/// Closes or removes something (Close pane): listed last on a phone sheet, /// Closes or removes something (Close pane): listed last on a phone sheet,
/// after a divider, in the error colour. /// after a divider, in the error colour.
final bool destructive; final bool destructive;
@@ -108,6 +112,7 @@ class SegmentedMoreButton extends StatelessWidget {
for (final entry in entries) for (final entry in entries)
AppSheetAction( AppSheetAction(
label: entry.label, label: entry.label,
subtitle: entry.subtitle,
icon: entry.icon, icon: entry.icon,
onSelected: entry.onPressed, onSelected: entry.onPressed,
destructive: entry.destructive, destructive: entry.destructive,
@@ -132,7 +137,7 @@ class SegmentedMoreButton extends StatelessWidget {
leadingIcon: Icon(entry.icon), leadingIcon: Icon(entry.icon),
onPressed: entry.onPressed, onPressed: entry.onPressed,
shortcut: entry.shortcut, shortcut: entry.shortcut,
child: Text(entry.label), child: _EntryText(entry),
) )
else else
SubmenuButton( SubmenuButton(
@@ -163,3 +168,30 @@ class SegmentedMoreButton extends StatelessWidget {
); );
} }
} }
/// A menu entry's label, with its subtitle beneath in the muted small style.
class _EntryText extends StatelessWidget {
const _EntryText(this.entry);
final SegmentedOverflowEntry entry;
@override
Widget build(BuildContext context) {
final subtitle = entry.subtitle;
if (subtitle == null || subtitle.isEmpty) return Text(entry.label);
final theme = Theme.of(context);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(entry.label),
Text(
subtitle,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
);
}
}
+12
View File
@@ -11,3 +11,15 @@ Evidence: `test/features/chat/conversation/chat_account_usage_test.dart`
(both hosts), and captures from the probe fixture with `?chats=1&quota=claude` (both hosts), and captures from the probe fixture with `?chats=1&quota=claude`
or `quota=opencode` (`tool/perf/perf_fixture.dart`), opened at or `quota=opencode` (`tool/perf/perf_fixture.dart`), opened at
`/chat/perf-chat-0` and clicking the title, 560x1000, Material and Cupertino. `/chat/perf-chat-0` and clicking the title, 560x1000, Material and Cupertino.
## Active Claude account
`usage.account.email` (and `organization`) names the account Claude Code is
signed in to now; the server sends it at process start and after a switch. A
Claude chat shows it as the send tooltip's usage line prefix ("Send\nsam@… ·
5-hour 42% · …"), the ⋮ menu "Claude account" subtitle, the usage-limit
banner's status line ("sam@… · Resets at 18:43") and the info sheet's plan
line. Without an email (API key, other harnesses) nothing is shown. Tests:
`test/features/chat/conversation/chat_claude_active_account_test.dart`.
Captures: `?chats=1&msgs=4&harness=claude&claudeAccounts=2&quota=claude`
(hover Send; open ⋮) and `...&claudeAccounts=2&claudeUsage=limit` (banner).
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_auto_continue.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/conversation/chat_usage_limit_banner.dart';
import 'package:pipelines_app/features/chat/domain/chat_account_usage.dart';
import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'chat_composer_bar_fixtures.dart';
import 'chat_thread_fixtures.dart';
// The active Claude account is named wherever the chat shows its account:
// the send button's tooltip, the Claude account menu item and the
// usage-limit banner. It comes from usage.account.email.
const _email = 'sam@caplens.example';
JsonMap _usage({double? five, String email = _email}) {
final now = DateTime.now();
return {
'session_id': 's',
'kind': 'usage',
'usage': {
'account': {
'harness': 'Claude Code',
'plan': 'max',
'email': email,
'organization': 'Caplens',
'windows': [
if (five != null)
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': five,
'resets_at': now
.add(const Duration(hours: 2))
.millisecondsSinceEpoch,
},
],
},
},
};
}
String? _sendTooltip(WidgetTester tester) => tester
.widget<Tooltip>(
find.ancestor(
of: find.byIcon(Icons.arrow_upward),
matching: find.byType(Tooltip),
),
)
.message;
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));
test('usage.account names the account, even before any quota', () {
final named = chatAccountUsage(_usage()['usage']['account']);
expect(named?.email, _email);
expect(named?.organization, 'Caplens');
expect(named?.windows, isEmpty);
// No email (an API key) and no quota: nothing to show.
expect(chatAccountUsage({'harness': 'Claude Code', 'email': ''}), isNull);
});
testWidgets('the send tooltip leads its usage line with the account', (
tester,
) async {
final gateway = ComposerBarGateway();
addTearDown(gateway.close);
await tester.pumpWidget(composerThread(gateway));
await tester.pumpAndSettle();
gateway.emitEvent(_usage());
await tester.pump();
await tester.pump();
expect(_sendTooltip(tester), 'Send\n$_email');
gateway.emitEvent(_usage(five: 42));
await tester.pump();
await tester.pump();
expect(_sendTooltip(tester), startsWith('Send\n$_email · 5-hour 42% · '));
// Assistive technology still names the button by its label alone.
expect(find.bySemanticsLabel('Send'), findsOneWidget);
});
testWidgets('the Claude account menu item shows the active account', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(
gateway: gateway,
sessionId: 's',
session: const {'id': 's', 'backend': 'claude', 'directory': '/x'},
syncToken: 0,
onBack: () {},
drafts: MemoryChatDraftStore(),
),
),
),
);
await tester.pump();
gateway.emitEvent(_usage());
await tester.pump();
await tester.pump();
await tester.tap(find.byKey(segmentedMoreKey).hitTestable().first);
await tester.pump(const Duration(milliseconds: 500));
expect(find.text('Claude account'), findsOneWidget);
expect(find.text(_email), findsOneWidget);
});
testWidgets('the usage-limit banner names the account that hit it', (
tester,
) async {
final gateway = FakeChatGateway();
final thread = ChatThreadController(gateway, 's');
final composer = ChatComposerController(gateway, 's');
addTearDown(gateway.close);
addTearDown(thread.dispose);
addTearDown(composer.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
ChatUsageLimitBanner(
thread: thread,
composer: composer,
autoContinue: ChatAutoContinue(),
),
],
),
),
),
);
gateway.emitEvent(_usage(five: 100));
await tester.pumpAndSettle();
final status = tester.widget<Text>(
find.byKey(const Key('chat-usage-limit-status')),
);
expect(status.data, startsWith('$_email · Resets at '));
});
}
+31 -14
View File
@@ -56,12 +56,12 @@ JsonMap? chatClaudeAccountsReply(JsonMap request) {
} }
_active = index; _active = index;
final now = DateTime.now().millisecondsSinceEpoch; final now = DateTime.now().millisecondsSinceEpoch;
usage = { usage = _named({
'harness': 'Claude Code', 'harness': 'Claude Code',
'plan': 'max', 'plan': 'max',
'as_of': now, 'as_of': now,
'switched_at': now, 'switched_at': now,
}; });
} }
return { return {
'id': request['id'], 'id': request['id'],
@@ -70,14 +70,30 @@ JsonMap? chatClaudeAccountsReply(JsonMap request) {
}; };
} }
/// The active account's quota frame for `?claudeUsage=`, or null. /// The account usage.account names: the active one, as the server sends it.
JsonMap _named(JsonMap account) => {
...account,
'email': _emails[_active],
'organization': 'Caplens',
};
/// The usage.account of other fixtures (`?quota=`) with the active account's
/// name when the chat has Claude accounts.
JsonMap chatClaudeNamedAccount(JsonMap account) =>
_count == 0 ? account : _named(account);
/// The active account's frame on subscribe: its quota for `?claudeUsage=`,
/// else the account alone (as a process start reports it); null without
/// Claude accounts.
JsonMap? chatClaudeUsageFrame(String sessionId) { JsonMap? chatClaudeUsageFrame(String sessionId) {
if (_count == 0) return null;
final percent = switch (_params['claudeUsage']) { final percent = switch (_params['claudeUsage']) {
'limit' => 100.0, 'limit' => 100.0,
'warn' => 88.0, 'warn' => 88.0,
_ => null, _ => null,
}; };
if (percent == null) return null; // `?quota=` already reports the (named) account's quota.
if (percent == null && _params['quota'] != null) return null;
final now = DateTime.now(); final now = DateTime.now();
return { return {
'type': 'chat_event', 'type': 'chat_event',
@@ -85,21 +101,22 @@ JsonMap? chatClaudeUsageFrame(String sessionId) {
'session_id': sessionId, 'session_id': sessionId,
'kind': 'usage', 'kind': 'usage',
'usage': { 'usage': {
'account': { 'account': _named({
'harness': 'Claude Code', 'harness': 'Claude Code',
'plan': 'max', 'plan': 'max',
'as_of': now.millisecondsSinceEpoch, 'as_of': now.millisecondsSinceEpoch,
'windows': [ 'windows': [
{ if (percent != null)
'id': 'five_hour', {
'label': '5-hour', 'id': 'five_hour',
'used_percent': percent, 'label': '5-hour',
'resets_at': now 'used_percent': percent,
.add(const Duration(hours: 2, minutes: 10)) 'resets_at': now
.millisecondsSinceEpoch, .add(const Duration(hours: 2, minutes: 10))
}, .millisecondsSinceEpoch,
},
], ],
}, }),
}, },
}, },
}; };
+1 -1
View File
@@ -218,7 +218,7 @@ List<JsonMap> perfChatFollowUps(JsonMap request) {
'total_tokens': 132408, 'total_tokens': 132408,
'context_tokens': 42000, 'context_tokens': 42000,
'context_window': 200000, 'context_window': 200000,
'account': account, 'account': chatClaudeNamedAccount(account),
}, },
}, },
}, },
+4
View File
@@ -523,6 +523,10 @@ 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 `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 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. windows yet, and a usage-limit refusal received before it no longer applies.
`email` and `organization` name the account Claude Code is signed in to now
(from its initialize `account`, or the saved account just switched to; never a
credential). A chat's process start sends a report carrying only them, before
any quota is known; they are absent for an API-key login or another harness.
`extra_usage` is Claude Code's extra usage ("overage", paid usage credits past `extra_usage` is Claude Code's extra usage ("overage", paid usage credits past
the subscription limits) from the same events, kept until a later event says the subscription limits) from the same events, kept until a later event says
otherwise: `{"status","in_use","disabled_reason","resets_at"}`, where `status` otherwise: `{"status","in_use","disabled_reason","resets_at"}`, where `status`
+31 -8
View File
@@ -77,7 +77,8 @@ func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operati
} }
email, org, plan, ok := store.Identity() email, org, plan, ok := store.Identity()
if ok { if ok {
list.Usage = c.switchAccount(ctx, configDir, accountKeyFor(email, org), plan) account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir) log.Printf("claude account: %s switched to a saved account", configDir)
} }
return list, nil return list, nil
@@ -85,15 +86,17 @@ func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operati
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation) return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
} }
// switchAccount records that configDir now signs in as key: its quota report // switchAccount records that configDir now signs in as account: its quota
// is marked switched (an empty one when nothing is known yet), and every open // report is marked switched (an empty one when nothing is known yet), and
// session on that Claude home takes the new key and republishes its usage. // every open session on that Claude home takes the new account and
func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *protocol.ChatAccountUsage { // republishes its usage, which names it.
func (c *Chat) switchAccount(ctx context.Context, configDir string, account accountIdentity) *protocol.ChatAccountUsage {
key := account.key
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
c.quotaMu.Lock() c.quotaMu.Lock()
usage := c.quotas[key].Clone() usage := c.quotas[key].Clone()
if usage == nil { if usage == nil {
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: plan, AsOf: now} usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: account.plan, AsOf: now}
} }
usage.SwitchedAt = now usage.SwitchedAt = now
if c.quotas == nil { if c.quotas == nil {
@@ -116,9 +119,29 @@ func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *
continue continue
} }
s.mu.Lock() s.mu.Lock()
s.account = accountIdentity{key: key, plan: plan} s.account = account
s.mu.Unlock() s.mu.Unlock()
s.republishUsage() s.republishUsage()
} }
return usage.Clone() return c.accountUsage(account)
}
// accountUsage returns a copy of the latest quota for an account, naming the
// account. With no quota known yet it names the account alone; it is nil when
// neither is known (an API key login reports no email).
func (c *Chat) accountUsage(account accountIdentity) *protocol.ChatAccountUsage {
var usage *protocol.ChatAccountUsage
if account.key != "" {
c.quotaMu.Lock()
usage = c.quotas[account.key].Clone()
c.quotaMu.Unlock()
}
if account.email == "" {
return usage
}
if usage == nil {
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "initialize", Plan: account.plan}
}
usage.Email, usage.Organization = account.email, account.organization
return usage
} }
+4
View File
@@ -71,6 +71,10 @@ func TestUseAccountMovesTheHomesChatsToTheNewAccountQuota(t *testing.T) {
if len(pushed.Windows) != 0 { if len(pushed.Windows) != 0 {
t.Fatalf("the new account inherited the old quota: %+v", pushed) t.Fatalf("the new account inherited the old quota: %+v", pushed)
} }
// usage.account names the account the home is signed in to now.
if list.Usage.Email != "a@example.invalid" || pushed.Email != "a@example.invalid" || pushed.Organization != "Org" {
t.Fatalf("switched usage names %q / %q (%q)", list.Usage.Email, pushed.Email, pushed.Organization)
}
data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json")) data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json"))
if !strings.Contains(string(data), "refresh-a1") { if !strings.Contains(string(data), "refresh-a1") {
t.Fatal("credentials not switched") t.Fatal("credentials not switched")
+3 -3
View File
@@ -427,7 +427,7 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
s.mu.Lock() s.mu.Lock()
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil { if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil {
usage := *frame.Usage usage := *frame.Usage
usage.Account = s.chat.accountUsage(s.account.key) usage.Account = s.chat.accountUsage(s.account)
frame.Usage = &usage frame.Usage = &usage
s.usage = &frame s.usage = &frame
} }
@@ -463,10 +463,10 @@ func (s *session) subscribe() chan protocol.ChatEventFrame {
// Account quota may have moved since (another chat on the account). // Account quota may have moved since (another chat on the account).
frame := *s.usage frame := *s.usage
usage := *frame.Usage usage := *frame.Usage
usage.Account = s.chat.accountUsage(s.account.key) usage.Account = s.chat.accountUsage(s.account)
frame.Usage = &usage frame.Usage = &usage
ch <- frame ch <- frame
} else if account := s.chat.accountUsage(s.account.key); account != nil { } else if account := s.chat.accountUsage(s.account); account != nil {
ch <- protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Account: account}} ch <- protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Account: account}}
} }
if s.compaction != nil { if s.compaction != nil {
+4 -1
View File
@@ -133,7 +133,10 @@ func TestTurnStreamsTextWithoutDuplicatingAndReportsUsage(t *testing.T) {
ended = true ended = true
} }
case protocol.ChatEventUsage: case protocol.ChatEventUsage:
usage = frame.Usage // The account-only report at start carries no tokens.
if frame.Usage != nil && frame.Usage.TotalTokens != nil {
usage = frame.Usage
}
} }
case <-deadline: case <-deadline:
t.Fatalf("turn did not settle (ended=%v usage=%v text=%q)", ended, usage != nil, text) t.Fatalf("turn did not settle (ended=%v usage=%v text=%q)", ended, usage != nil, text)
+4
View File
@@ -181,6 +181,10 @@ func (s *session) spawnOnce(ctx context.Context) (*process, error) {
s.chat.rememberCatalog(models) s.chat.rememberCatalog(models)
s.lastErr = "" s.lastErr = ""
s.mu.Unlock() s.mu.Unlock()
if account.email != "" {
// Watchers learn which account this chat now runs on.
s.republishUsage()
}
return p, nil return p, nil
} }
+12 -14
View File
@@ -25,10 +25,13 @@ const quotaHarness = "Claude Code"
const quotaSource = "rate_limit_event" const quotaSource = "rate_limit_event"
// accountIdentity is the signed-in account a process reported at initialize. // accountIdentity is the signed-in account a process reported at initialize.
// key is never sent to clients; it only shares quota between sessions. // key is never sent to clients; it only shares quota between sessions. email
// and organization name the account to the operator (usage.account).
type accountIdentity struct { type accountIdentity struct {
key string key string
plan string plan string
email string
organization string
} }
func decodeAccountIdentity(raw json.RawMessage) accountIdentity { func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
@@ -45,7 +48,12 @@ func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
if strings.Trim(key, "\x00") == "" { if strings.Trim(key, "\x00") == "" {
key = "" key = ""
} }
return accountIdentity{key: key, plan: strings.TrimSpace(account.SubscriptionType)} return accountIdentity{
key: key,
plan: strings.TrimSpace(account.SubscriptionType),
email: strings.TrimSpace(account.Email),
organization: strings.TrimSpace(account.Organization),
}
} }
type rateLimitWindowInfo struct { type rateLimitWindowInfo struct {
@@ -175,16 +183,6 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
return next return next
} }
// accountUsage returns a copy of the latest quota for an account key.
func (c *Chat) accountUsage(key string) *protocol.ChatAccountUsage {
if key == "" {
return nil
}
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
return c.quotas[key].Clone()
}
// handleRateLimit records a rate_limit_event for the session's account and // handleRateLimit records a rate_limit_event for the session's account and
// republishes the latest usage snapshot, with the new quota, to every session // republishes the latest usage snapshot, with the new quota, to every session
// of that account. // of that account.
+15 -3
View File
@@ -87,9 +87,14 @@ func TestMergeRateLimitCarriesExtraUsage(t *testing.T) {
func TestDecodeAccountIdentity(t *testing.T) { func TestDecodeAccountIdentity(t *testing.T) {
got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`)) got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`))
if got.key == "" || got.plan != "max" { if got.key == "" || got.plan != "max" || got.email != "a@example.invalid" || got.organization != "Org" {
t.Fatalf("identity = %+v", got) t.Fatalf("identity = %+v", got)
} }
// An API key login names no account, so nothing is shown for it.
chat := &Chat{}
if usage := chat.accountUsage(decodeAccountIdentity(json.RawMessage(`{"apiProvider":"firstParty","apiKeySource":"ANTHROPIC_API_KEY"}`))); usage != nil {
t.Fatalf("API key usage = %+v", usage)
}
if empty := decodeAccountIdentity(json.RawMessage(`{}`)); empty.key != "" || empty.plan != "" { if empty := decodeAccountIdentity(json.RawMessage(`{}`)); empty.key != "" || empty.plan != "" {
t.Fatalf("empty account = %+v", empty) t.Fatalf("empty account = %+v", empty)
} }
@@ -103,10 +108,17 @@ func TestRateLimitEventReachesEverySessionOfTheAccount(t *testing.T) {
if err := chat.Prompt(context.Background(), first.ID, "hello"); err != nil { if err := chat.Prompt(context.Background(), first.ID, "hello"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
quota := waitFrame(t, frames, "account usage", func(frame protocol.ChatEventFrame) bool { // The process's start names the account before any quota is known.
named := waitFrame(t, frames, "account identity", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil
}).Usage.Account }).Usage.Account
if quota.Plan != "max" || len(quota.Windows) != 2 || quota.Windows[0].Label != "5-hour" || quota.Windows[0].UsedPercent != 42 || if named.Email != "fixture@example.invalid" || named.Organization != "Fixture Org" || len(named.Windows) != 0 {
t.Fatalf("account identity = %+v", named)
}
quota := waitFrame(t, frames, "account usage", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && len(frame.Usage.Account.Windows) > 0
}).Usage.Account
if quota.Plan != "max" || quota.Email != "fixture@example.invalid" || len(quota.Windows) != 2 || quota.Windows[0].Label != "5-hour" || quota.Windows[0].UsedPercent != 42 ||
quota.Windows[1].Label != "Weekly" || quota.Windows[1].UsedPercent != 73.1 || quota.Windows[1].ResetsAt != 1_900_400_000_000 { quota.Windows[1].Label != "Weekly" || quota.Windows[1].UsedPercent != 73.1 || quota.Windows[1].ResetsAt != 1_900_400_000_000 {
t.Fatalf("account usage = %+v", quota) t.Fatalf("account usage = %+v", quota)
} }
+5
View File
@@ -808,6 +808,11 @@ type ChatAccountUsage struct {
Source string `json:"source,omitempty"` Source string `json:"source,omitempty"`
// Plan is the harness's plan identifier when it reports one ("max", "plus"). // Plan is the harness's plan identifier when it reports one ("max", "plus").
Plan string `json:"plan,omitempty"` Plan string `json:"plan,omitempty"`
// Email and Organization name the account the harness is signed in to now
// (the operator's own login, never a credential); empty when it did not
// say (an API key, or a harness without accounts).
Email string `json:"email,omitempty"`
Organization string `json:"organization,omitempty"`
// AsOf is when the server received the report (epoch milliseconds). // AsOf is when the server received the report (epoch milliseconds).
AsOf int64 `json:"as_of,omitempty"` AsOf int64 `json:"as_of,omitempty"`
Windows []ChatQuotaWindow `json:"windows,omitempty"` Windows []ChatQuotaWindow `json:"windows,omitempty"`