From 3951c65a7a35351107fa1162d8591ae98c133a20 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 30 Nov 2026 14:55:42 +0000 Subject: [PATCH] Chat: a discreet usage ring around the composer's Send button A thin ring around Send shows the harness account's 5-hour window used share (the most used live window when there is no 5-hour one): barely visible normally, tertiary from 80%, error from 95%. The button's tooltip (hover, long-press on touch) adds every window with its reset time. No ring when the quota is unknown or unsupported. Painted behind the unchanged button, so its size, target, states and animations stay as they were. Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_composer_bar.dart | 35 ++-- .../conversation/chat_send_usage_ring.dart | 167 ++++++++++++++++++ .../chat/conversation/chat_thread_view.dart | 1 + .../features/chat/domain/chat_usage_ring.dart | 95 ++++++++++ app/notes/chat-send-usage-ring.md | 17 ++ .../chat_send_usage_ring_test.dart | 156 ++++++++++++++++ .../chat/domain/chat_usage_ring_test.dart | 143 +++++++++++++++ 7 files changed, 603 insertions(+), 11 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_send_usage_ring.dart create mode 100644 app/lib/features/chat/domain/chat_usage_ring.dart create mode 100644 app/notes/chat-send-usage-ring.md create mode 100644 app/test/features/chat/conversation/chat_send_usage_ring_test.dart create mode 100644 app/test/features/chat/domain/chat_usage_ring_test.dart diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index bd1386ed..5fcbaffc 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -19,6 +19,8 @@ import '../domain/chat_commands.dart'; import 'chat_command_actions.dart'; import 'chat_command_palette.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_harness_command_loader.dart'; import '../ui/transcript/chat_attachment_frame.dart'; @@ -139,8 +141,13 @@ class ChatComposerBar extends StatefulWidget { this.chatColor, this.limitBanner, 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 /// the palette offers after the recorded commands. Choosing one inserts /// `/ ` and sending passes the draft to the harness as a prompt. Null @@ -1297,17 +1304,23 @@ class _ChatComposerBarState extends State { // A coloured chat's send button takes the chat's colour (its seeded // primary, like the focus ring). final tinted = chatSchemeOf(context, widget.chatColor); - return IconButton.filled( - key: const Key('chat-composer-primary'), - tooltip: label, - style: tinted == null - ? null - : IconButton.styleFrom( - backgroundColor: tinted.primary, - foregroundColor: tinted.onPrimary, - ), - onPressed: enabled ? press : null, - icon: const Icon(Icons.arrow_upward), + final usage = widget.usage; + return ChatSendUsageRing( + source: usage, + usage: () => usage?.accountUsage, + label: label, + button: (tooltip) => IconButton.filled( + key: const Key('chat-composer-primary'), + tooltip: tooltip, + style: tinted == null + ? null + : IconButton.styleFrom( + backgroundColor: tinted.primary, + foregroundColor: tinted.onPrimary, + ), + onPressed: enabled ? press : null, + icon: const Icon(Icons.arrow_upward), + ), ); } diff --git a/app/lib/features/chat/conversation/chat_send_usage_ring.dart b/app/lib/features/chat/conversation/chat_send_usage_ring.dart new file mode 100644 index 00000000..56700e4c --- /dev/null +++ b/app/lib/features/chat/conversation/chat_send_usage_ring.dart @@ -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 createState() => _ChatSendUsageRingState(); +} + +class _ChatSendUsageRingState extends State { + /// 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; +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 82980b56..bd70e36d 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -1242,6 +1242,7 @@ class _ChatThreadViewState extends State { key: ValueKey('chat-composer-${widget.sessionId}'), composer: _composer, running: _controller.running, + usage: _controller, commands: _commandActions(), loadHarnessCommands: () async => chatHarnessCommandsFromWire( await ChatRepository(widget.gateway).commands(widget.sessionId), diff --git a/app/lib/features/chat/domain/chat_usage_ring.dart b/app/lib/features/chat/domain/chat_usage_ring.dart new file mode 100644 index 00000000..afe86e4b --- /dev/null +++ b/app/lib/features/chat/domain/chat_usage_ring.dart @@ -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 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 _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(' · '); diff --git a/app/notes/chat-send-usage-ring.md b/app/notes/chat-send-usage-ring.md new file mode 100644 index 00000000..6194316d --- /dev/null +++ b/app/notes/chat-send-usage-ring.md @@ -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. diff --git a/app/test/features/chat/conversation/chat_send_usage_ring_test.dart b/app/test/features/chat/conversation/chat_send_usage_ring_test.dart new file mode 100644 index 00000000..4bb95536 --- /dev/null +++ b/app/test/features/chat/conversation/chat_send_usage_ring_test.dart @@ -0,0 +1,156 @@ +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( + 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( + find.ancestor( + of: find.byIcon(Icons.arrow_upward), + matching: find.byType(Tooltip), + ), + ) + .message; + +ColorScheme _scheme(WidgetTester tester) => + Theme.of(tester.element(_primary)).colorScheme; + +Future _open(WidgetTester tester) async { + final gateway = ComposerBarGateway(); + addTearDown(gateway.close); + await tester.pumpWidget(composerThread(gateway)); + await tester.pumpAndSettle(); + return gateway; +} + +Future _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); + }); + + 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, + ); + }); +} diff --git a/app/test/features/chat/domain/chat_usage_ring_test.dart b/app/test/features/chat/domain/chat_usage_ring_test.dart new file mode 100644 index 00000000..b19b57e3 --- /dev/null +++ b/app/test/features/chat/domain/chat_usage_ring_test.dart @@ -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 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', + ); + }); +}