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),
},
},
},