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 ...[
if (plan.isNotEmpty)
if (plan.isNotEmpty || usage.email.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
usage.harness.isEmpty
? '$plan plan'
: '${usage.harness} · $plan plan',
[
if (usage.email.isNotEmpty) usage.email,
if (usage.harness.isNotEmpty) usage.harness,
if (plan.isNotEmpty) '$plan plan',
].join(' · '),
key: const Key('chat-account-usage-plan'),
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
/// 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".
/// button's tooltip (hover, or long-press on touch) adds the account and
/// 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,
/// 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) {
final now = widget.now();
final ring = chatUsageRing(widget.usage(), now);
final usage = widget.usage();
final ring = chatUsageRing(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)}',
),
child: widget.button(chatSendTooltip(widget.label, usage, ring, now)),
);
}
@@ -513,6 +513,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
controller.transcriptChanges.addListener(
() => _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
// when the report arrives: it is not built yet while this one is.
controller.onQueue = (queue) {
@@ -1559,6 +1568,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_controller.running,
// The More menu offers Dismiss all finished commands only with one.
_shellRuns.finishedIds.isNotEmpty,
// The Claude account item names the signed-in account.
_controller.accountUsage?.email,
],
() => _buildHeader(session, inShellBar, canGoBack, answeredBy, inWindow),
);
@@ -1651,6 +1662,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
ChatBarAction(
key: const Key('chat-claude-account-menu'),
label: 'Claude account',
// The account the chat's Claude Code is signed in to now.
subtitle: _controller.accountUsage?.email,
identifier: 'chat-claude-account',
onPressed: () =>
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
/// 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.
///
/// 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
? limit.sendAt
: chatScheduledSendAt(pending.first['send_at'], now)!;
final email = widget.thread.accountUsage?.email ?? '';
final status = [
// The account that hit the limit.
if (email.isNotEmpty) email,
if (enabled && refused != null)
'Auto-resuming at ${time(resumesAt)}'
else
@@ -31,8 +31,15 @@ class ChatAccountUsage {
required this.unsupported,
this.switchedAt = 0,
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").
final String harness;
final String plan;
@@ -131,9 +138,10 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
}
}
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;
final email = '${value['email'] ?? ''}'.trim();
// A switched or newly named account replaces the previous report even with
// no windows yet; otherwise an empty report keeps the last one.
if (windows.isEmpty && switchedAt == 0 && email.isEmpty) return null;
return ChatAccountUsage(
harness: harness,
plan: '${value['plan'] ?? ''}'.trim(),
@@ -142,6 +150,8 @@ ChatAccountUsage? chatAccountUsage(Object? value) {
unsupported: false,
switchedAt: switchedAt,
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';
}
/// 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
/// extra usage note.
String chatUsageRingSummary(ChatUsageRing ring, DateTime now) => [
@@ -9,9 +9,14 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
required this.materialIcon,
this.identifier,
this.destructive = false,
this.subtitle,
});
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 IconData materialIcon;
@@ -27,14 +32,18 @@ class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
icon: materialIcon,
onPressed: onPressed,
destructive: destructive,
subtitle: subtitle,
);
@override
Widget build(BuildContext context) {
final subtitle = this.subtitle;
return Semantics(
identifier: identifier,
child: IconButton(
tooltip: label,
tooltip: subtitle == null || subtitle.isEmpty
? label
: '$label\n$subtitle',
onPressed: onPressed,
icon: Icon(materialIcon),
),
@@ -11,11 +11,15 @@ class AppSheetAction {
this.selected = false,
this.choices = const [],
this.key,
this.subtitle,
});
final String label;
final IconData? icon;
/// A short second line under [label].
final String? subtitle;
/// Runs once the sheet has closed. Null (with no [choices]) disables it.
final VoidCallback? onSelected;
@@ -162,6 +166,10 @@ class _ActionRow extends StatelessWidget {
action.label,
style: color == null || !enabled ? null : TextStyle(color: color),
),
subtitle: switch (action.subtitle) {
final subtitle? when subtitle.isNotEmpty => Text(subtitle),
_ => null,
},
trailing: action.choices.isNotEmpty
? const Icon(Icons.chevron_right)
: action.selected
@@ -30,11 +30,15 @@ class SegmentedOverflowEntry {
this.choices = const [],
this.shortcut,
this.destructive = false,
this.subtitle,
});
final String label;
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,
/// after a divider, in the error colour.
final bool destructive;
@@ -108,6 +112,7 @@ class SegmentedMoreButton extends StatelessWidget {
for (final entry in entries)
AppSheetAction(
label: entry.label,
subtitle: entry.subtitle,
icon: entry.icon,
onSelected: entry.onPressed,
destructive: entry.destructive,
@@ -132,7 +137,7 @@ class SegmentedMoreButton extends StatelessWidget {
leadingIcon: Icon(entry.icon),
onPressed: entry.onPressed,
shortcut: entry.shortcut,
child: Text(entry.label),
child: _EntryText(entry),
)
else
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`
or `quota=opencode` (`tool/perf/perf_fixture.dart`), opened at
`/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;
final now = DateTime.now().millisecondsSinceEpoch;
usage = {
usage = _named({
'harness': 'Claude Code',
'plan': 'max',
'as_of': now,
'switched_at': now,
};
});
}
return {
'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) {
if (_count == 0) return null;
final percent = switch (_params['claudeUsage']) {
'limit' => 100.0,
'warn' => 88.0,
_ => 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();
return {
'type': 'chat_event',
@@ -85,21 +101,22 @@ JsonMap? chatClaudeUsageFrame(String sessionId) {
'session_id': sessionId,
'kind': 'usage',
'usage': {
'account': {
'account': _named({
'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,
},
if (percent != null)
{
'id': 'five_hour',
'label': '5-hour',
'used_percent': percent,
'resets_at': now
.add(const Duration(hours: 2, minutes: 10))
.millisecondsSinceEpoch,
},
],
},
}),
},
},
};
+1 -1
View File
@@ -218,7 +218,7 @@ List<JsonMap> perfChatFollowUps(JsonMap request) {
'total_tokens': 132408,
'context_tokens': 42000,
'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
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.
`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
the subscription limits) from the same events, kept until a later event says
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()
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)
}
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)
}
// 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 {
// switchAccount records that configDir now signs in as account: 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 account and
// 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()
c.quotaMu.Lock()
usage := c.quotas[key].Clone()
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
if c.quotas == nil {
@@ -116,9 +119,29 @@ func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *
continue
}
s.mu.Lock()
s.account = accountIdentity{key: key, plan: plan}
s.account = account
s.mu.Unlock()
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 {
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"))
if !strings.Contains(string(data), "refresh-a1") {
t.Fatal("credentials not switched")
+3 -3
View File
@@ -427,7 +427,7 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
s.mu.Lock()
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil {
usage := *frame.Usage
usage.Account = s.chat.accountUsage(s.account.key)
usage.Account = s.chat.accountUsage(s.account)
frame.Usage = &usage
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).
frame := *s.usage
usage := *frame.Usage
usage.Account = s.chat.accountUsage(s.account.key)
usage.Account = s.chat.accountUsage(s.account)
frame.Usage = &usage
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}}
}
if s.compaction != nil {
+4 -1
View File
@@ -133,7 +133,10 @@ func TestTurnStreamsTextWithoutDuplicatingAndReportsUsage(t *testing.T) {
ended = true
}
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:
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.lastErr = ""
s.mu.Unlock()
if account.email != "" {
// Watchers learn which account this chat now runs on.
s.republishUsage()
}
return p, nil
}
+12 -14
View File
@@ -25,10 +25,13 @@ const quotaHarness = "Claude Code"
const quotaSource = "rate_limit_event"
// 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 {
key string
plan string
key string
plan string
email string
organization string
}
func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
@@ -45,7 +48,12 @@ func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
if strings.Trim(key, "\x00") == "" {
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 {
@@ -175,16 +183,6 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
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
// republishes the latest usage snapshot, with the new quota, to every session
// of that account.
+15 -3
View File
@@ -87,9 +87,14 @@ func TestMergeRateLimitCarriesExtraUsage(t *testing.T) {
func TestDecodeAccountIdentity(t *testing.T) {
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)
}
// 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 != "" {
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 {
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
}).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 {
t.Fatalf("account usage = %+v", quota)
}
+5
View File
@@ -808,6 +808,11 @@ type ChatAccountUsage struct {
Source string `json:"source,omitempty"`
// Plan is the harness's plan identifier when it reports one ("max", "plus").
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 int64 `json:"as_of,omitempty"`
Windows []ChatQuotaWindow `json:"windows,omitempty"`