From 7b045e5aab6a1edfd3ea53004742471b99bdbcce Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 2 Dec 2026 01:21:19 +0000 Subject: [PATCH] Chat perf: path-free running border, keystroke- and delta-quiet composer, spinners that do not relayout their list Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_composer_bar.dart | 68 ++++++++-- .../conversation/chat_send_usage_ring.dart | 46 +++++-- .../chat/conversation/chat_thread_view.dart | 5 +- .../conversation/composer_running_border.dart | 24 +++- .../composer_running_outline.dart | 119 ++++++++++++++++++ .../chat/ui/sessions/chat_adaptive.dart | 3 +- .../transcript/chat_attachment_thumbnail.dart | 3 +- .../ui/transcript/chat_response_pending.dart | 65 +++++----- app/lib/ui/status/app_spinner.dart | 14 ++- .../chat_composer_rebuild_test.dart | 78 ++++++++++++ .../composer_running_outline_test.dart | 87 +++++++++++++ app/test/ui/status/app_spinner_test.dart | 62 +++++++++ app/tool/perf/chat_4k_bench.mjs | 20 ++- 13 files changed, 534 insertions(+), 60 deletions(-) create mode 100644 app/lib/features/chat/conversation/composer_running_outline.dart create mode 100644 app/test/features/chat/conversation/chat_composer_rebuild_test.dart create mode 100644 app/test/features/chat/conversation/composer_running_outline_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 556a68b8..607b5982 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -268,7 +268,9 @@ class _ChatComposerBarState extends State { focus: _focus, canRestore: _composerIsCurrent, ); + _composerShown = _composerShownOf(widget.composer); widget.composer.addListener(_syncDraft); + widget.composer.addListener(_onComposerChanged); ChatComposerPasteFocus.register(_focus); ChatComposerPasteFocus.setOwnsFocusedPaste( _focus, @@ -296,8 +298,13 @@ class _ChatComposerBarState extends State { void didUpdateWidget(covariant ChatComposerBar oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.composer != widget.composer) { - oldWidget.composer.removeListener(_syncDraft); - widget.composer.addListener(_syncDraft); + oldWidget.composer + ..removeListener(_syncDraft) + ..removeListener(_onComposerChanged); + widget.composer + ..addListener(_syncDraft) + ..addListener(_onComposerChanged); + _composerShown = _composerShownOf(widget.composer); _seenAccepted = widget.composer.composerSendsAccepted; _syncDraft(); } @@ -436,6 +443,34 @@ class _ChatComposerBarState extends State { ); } + /// What the bar shows from the composer: everything [build] reads from it, + /// with the draft reduced to what the controls show of it. A keystroke + /// changes only the draft, which the field already shows itself, so typing + /// rebuilds the bar only when one of these changes (the first character + /// enables Send, `!` switches to the shell, a `/` command filters the + /// palette). + late Object _composerShown; + + static Object _composerShownOf(ChatComposerController composer) { + final draft = composer.draft; + return ( + composer.sending, + composer.queued, + composer.error, + composer.draftError, + chatDraftIsShell(draft), + draft.trim().isEmpty, + chatCommandQuery(draft) == null ? null : draft, + ); + } + + void _onComposerChanged() { + if (!mounted) return; + final shown = _composerShownOf(widget.composer); + if (shown == _composerShown) return; + setState(() => _composerShown = shown); + } + /// Whether a send completes the palette's highlighted row instead of running /// the draft. A draft that already names a whole command (`/stop`) runs on /// the first send; only a partial word is completed first. @@ -468,11 +503,21 @@ class _ChatComposerBarState extends State { void _onDraftEdited(String value) { _requestHarnessCommands(value); final suggestions = chatCommandSuggestions(value, _harness.commands); - setState(() { - _paletteClosedFor = null; - _dismissCommandReport(); - if (_selectedCommand >= suggestions.length) _selectedCommand = 0; - }); + final resetHighlight = + _selectedCommand != 0 && _selectedCommand >= suggestions.length; + // Plain typing changes none of this: the bar is left alone, and the + // draft below rebuilds it only if what it shows changes. + if (_paletteClosedFor != null || + _commandNotice != null || + _commandOffer != null || + _commandFailed || + resetHighlight) { + setState(() { + _paletteClosedFor = null; + _dismissCommandReport(); + if (resetHighlight) _selectedCommand = 0; + }); + } unawaited(widget.composer.setDraft(value)); _revealCaretLine(value); } @@ -890,7 +935,9 @@ class _ChatComposerBarState extends State { _stopListeningForPaste(); FocusManager.instance.removeEarlyKeyEventHandler(_nativePasteKey); ChatComposerPasteFocus.unregister(_focus); - widget.composer.removeListener(_syncDraft); + widget.composer + ..removeListener(_syncDraft) + ..removeListener(_onComposerChanged); _focusRestorer.dispose(); _focusRequests.dispose(); _text.dispose(); @@ -901,9 +948,8 @@ class _ChatComposerBarState extends State { @override Widget build(BuildContext context) { - return ListenableBuilder( - listenable: widget.composer, - builder: (context, _) { + return Builder( + builder: (context) { final composer = widget.composer; final error = composer.error ?? composer.draftError; final commands = _paletteCommands(); diff --git a/app/lib/features/chat/conversation/chat_send_usage_ring.dart b/app/lib/features/chat/conversation/chat_send_usage_ring.dart index d4b340af..9e8f7a5f 100644 --- a/app/lib/features/chat/conversation/chat_send_usage_ring.dart +++ b/app/lib/features/chat/conversation/chat_send_usage_ring.dart @@ -45,12 +45,48 @@ class _ChatSendUsageRingState extends State { /// Keeps the reset times and a passed reset current while a ring shows. Timer? _tick; + /// What the last build showed: the tooltip and the ring's arc and tone. + /// The source (the thread controller) notifies on every streamed delta; + /// only a change here rebuilds the button. + Object? _shown; + + @override + void initState() { + super.initState(); + widget.source?.addListener(_onSource); + } + + @override + void didUpdateWidget(ChatSendUsageRing oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.source != widget.source) { + oldWidget.source?.removeListener(_onSource); + widget.source?.addListener(_onSource); + } + } + @override void dispose() { + widget.source?.removeListener(_onSource); _tick?.cancel(); super.dispose(); } + void _onSource() { + if (!mounted) return; + final now = widget.now(); + final usage = widget.usage(); + if (_shownOf(usage, chatUsageRing(usage, now), now) == _shown) return; + setState(() {}); + } + + Object _shownOf(ChatAccountUsage? usage, ChatUsageRing? ring, DateTime now) => + ( + chatSendTooltip(widget.label, usage, ring, now), + ring?.fraction, + ring?.tone, + ); + void _ticking(bool on) { if (on == (_tick != null)) return; _tick?.cancel(); @@ -63,19 +99,11 @@ class _ChatSendUsageRingState extends State { @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 usage = widget.usage(); final ring = chatUsageRing(usage, now); _ticking(ring != null); + _shown = _shownOf(usage, ring, now); // 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( diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 6dc59802..270c9f41 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -3,6 +3,7 @@ import '../../terminal/terminal_open_action.dart'; import 'dart:async'; import 'package:flutter/material.dart'; +import '../../../ui/status/app_spinner.dart'; import 'package:flutter/rendering.dart'; import '../../../core/api_gateway.dart'; @@ -1404,9 +1405,7 @@ class _ChatThreadViewState extends State { Padding( key: const Key('chat-thread-loading'), padding: const EdgeInsets.all(16), - child: const Center( - child: CircularProgressIndicator(), - ), + child: const Center(child: AppSpinner()), ), if (_controller.hasMore) Padding( diff --git a/app/lib/features/chat/conversation/composer_running_border.dart b/app/lib/features/chat/conversation/composer_running_border.dart index e64c2a87..05d5fd28 100644 --- a/app/lib/features/chat/conversation/composer_running_border.dart +++ b/app/lib/features/chat/conversation/composer_running_border.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'composer_running_arc.dart'; +import 'composer_running_outline.dart'; /// The composer's "agent is working" edge: one short highlight in [primary] /// and [tertiary] that travels around the pill's rounded border at constant @@ -117,14 +118,33 @@ class _RunningBorderPainter extends CustomPainter { final progress = lap?.value; // Reduced motion: no highlight; the normal static border shows alone. if (progress == null || size.isEmpty) return; - final outline = shape.getOuterPath((Offset.zero & size).deflate(width / 2)); + final bounds = (Offset.zero & size).deflate(width / 2); final line = Paint() ..style = PaintingStyle.stroke ..strokeWidth = width; // The highlight is laid along the outline by arc length, so its speed is // even around corners and straight edges alike. Only its pieces are drawn. + // The pill's rounded rectangle draws them as lines and arcs; any other + // shape cuts them out of its measured path. + final rrect = RunningRRectOutline.of(shape, bounds); + if (rrect != null) { + for (final segment in runningHighlightSegments( + progress: progress, + length: rrect.length, + primary: primary, + tertiary: tertiary, + )) { + rrect.draw( + canvas, + segment.start, + segment.end, + line..color = segment.color, + ); + } + return; + } for (final stroke in runningHighlightStrokes( - outline: outline, + outline: shape.getOuterPath(bounds), progress: progress, primary: primary, tertiary: tertiary, diff --git a/app/lib/features/chat/conversation/composer_running_outline.dart b/app/lib/features/chat/conversation/composer_running_outline.dart new file mode 100644 index 00000000..a77ff0ef --- /dev/null +++ b/app/lib/features/chat/conversation/composer_running_outline.dart @@ -0,0 +1,119 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +/// A rounded rectangle's outline measured by arc length, drawn piece by piece +/// with plain lines and arcs. +/// +/// The running highlight moves every frame. Cutting its pieces out of a +/// [Path] (`PathMetric.extractPath`) costs a new path per piece per frame, +/// which the web engine rebuilds again when it draws; for the pill's shape the +/// same pieces are straight lines and circular arcs, so they are drawn as such. +/// +/// The outline starts where [Path.addRRect] starts it (the left edge's bottom +/// end) and runs the same way (up the left edge, then clockwise), so a range +/// of arc length covers the same part of the edge as on the path. +class RunningRRectOutline { + RunningRRectOutline._(this._rect, this._radius) + : _side = _rect.height - 2 * _radius, + _across = _rect.width - 2 * _radius, + _corner = math.pi / 2 * _radius; + + /// The outline [shape] draws around [rect], or null when it is not a + /// rectangle with one circular radius on every corner (then the path is + /// measured instead). + static RunningRRectOutline? of(OutlinedBorder shape, Rect rect) { + if (shape is! RoundedRectangleBorder || rect.isEmpty) return null; + final radii = shape.borderRadius.resolve(TextDirection.ltr); + final r = radii.topLeft; + if (r.x != r.y || + radii.topRight != r || + radii.bottomLeft != r || + radii.bottomRight != r) { + return null; + } + // Radii larger than half a side are scaled down, as a path's are. + final radius = math.max( + 0.0, + math.min(r.x, math.min(rect.width, rect.height) / 2), + ); + return RunningRRectOutline._(rect, radius); + } + + final Rect _rect; + final double _radius; + final double _side; + final double _across; + final double _corner; + + /// The outline's whole length. + double get length => 2 * (_side + _across) + 4 * _corner; + + /// Strokes the outline from arc length [start] to [end] (within one lap). + void draw(Canvas canvas, double start, double end, Paint paint) { + final l = _rect.left, t = _rect.top, r = _rect.right, b = _rect.bottom; + final rad = _radius; + var at = 0.0; + // Each part of the outline, in path order: a straight edge from one point + // to another, or a quarter circle from a start angle. + void edge(double length, Offset from, Offset to) { + final lo = math.max(start, at), hi = math.min(end, at + length); + if (hi > lo && length > 0) { + canvas.drawLine( + Offset.lerp(from, to, (lo - at) / length)!, + Offset.lerp(from, to, (hi - at) / length)!, + paint, + ); + } + at += length; + } + + void corner(Offset centre, double angle) { + final lo = math.max(start, at), hi = math.min(end, at + _corner); + if (hi > lo && rad > 0) { + canvas.drawArc( + Rect.fromCircle(center: centre, radius: rad), + angle + (lo - at) / rad, + (hi - lo) / rad, + false, + paint, + ); + } + at += _corner; + } + + edge(_side, Offset(l, b - rad), Offset(l, t + rad)); + corner(Offset(l + rad, t + rad), math.pi); + edge(_across, Offset(l + rad, t), Offset(r - rad, t)); + corner(Offset(r - rad, t + rad), 3 * math.pi / 2); + edge(_side, Offset(r, t + rad), Offset(r, b - rad)); + corner(Offset(r - rad, b - rad), 0); + edge(_across, Offset(r - rad, b), Offset(l + rad, b)); + corner(Offset(l + rad, b - rad), math.pi / 2); + } + + /// The point at arc length [distance] along the outline (for tests). + Offset pointAt(double distance) { + final l = _rect.left, t = _rect.top, r = _rect.right, b = _rect.bottom; + final rad = _radius; + var d = distance - (distance / length).floorToDouble() * length; + final parts = <(double, Offset Function(double))>[ + (_side, (s) => Offset(l, b - rad - s)), + (_corner, (s) => _arc(Offset(l + rad, t + rad), math.pi + s / rad)), + (_across, (s) => Offset(l + rad + s, t)), + (_corner, (s) => _arc(Offset(r - rad, t + rad), 1.5 * math.pi + s / rad)), + (_side, (s) => Offset(r, t + rad + s)), + (_corner, (s) => _arc(Offset(r - rad, b - rad), s / rad)), + (_across, (s) => Offset(r - rad - s, b)), + (_corner, (s) => _arc(Offset(l + rad, b - rad), .5 * math.pi + s / rad)), + ]; + for (final (len, at) in parts) { + if (len > 0 && d <= len) return at(d); + d -= len; + } + return Offset(l, b - rad); + } + + Offset _arc(Offset centre, double angle) => + centre + Offset(math.cos(angle), math.sin(angle)) * _radius; +} diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart index 22959462..6dcdc415 100644 --- a/app/lib/features/chat/ui/sessions/chat_adaptive.dart +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -1,5 +1,6 @@ import '../../../../ui/adaptive/segmented_bar_overflow.dart'; import 'package:flutter/material.dart'; +import '../../../../ui/status/app_spinner.dart'; class ChatBarAction extends StatelessWidget implements SegmentedOverflowable { const ChatBarAction({ @@ -187,7 +188,7 @@ class ChatLoadingIndicator extends StatelessWidget { @override Widget build(BuildContext context) { - return const Center(child: CircularProgressIndicator()); + return const Center(child: AppSpinner()); } } diff --git a/app/lib/features/chat/ui/transcript/chat_attachment_thumbnail.dart b/app/lib/features/chat/ui/transcript/chat_attachment_thumbnail.dart index d8079b2c..e38bc2bf 100644 --- a/app/lib/features/chat/ui/transcript/chat_attachment_thumbnail.dart +++ b/app/lib/features/chat/ui/transcript/chat_attachment_thumbnail.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; import 'package:flutter/material.dart'; +import '../../../../ui/status/app_spinner.dart'; import '../../data/chat_attachment_images.dart'; import 'chat_attachment_frame.dart'; @@ -92,7 +93,7 @@ class _ChatAttachmentThumbnailState extends State { Widget _pending(BuildContext context) => SizedBox.square( key: const Key('chat-attachment-thumbnail-loading'), dimension: 96, - child: const Center(child: CircularProgressIndicator()), + child: const Center(child: AppSpinner()), ); Widget _thumbnail(BuildContext context, Uint8List bytes) { diff --git a/app/lib/features/chat/ui/transcript/chat_response_pending.dart b/app/lib/features/chat/ui/transcript/chat_response_pending.dart index 65bab79a..b3356f49 100644 --- a/app/lib/features/chat/ui/transcript/chat_response_pending.dart +++ b/app/lib/features/chat/ui/transcript/chat_response_pending.dart @@ -49,41 +49,48 @@ class _ChatResponsePendingState extends State label: 'Assistant is responding', liveRegion: true, excludeSemantics: true, + // A fixed box (the three dots and their two gaps) with its own + // builder: each tick rebuilds the dots and lays out only this box, not + // the transcript row's builder and the list around it. child: SizedBox( key: const Key('chat-response-pending-dots'), height: fontSize, - child: AnimatedBuilder( - animation: _animation, - builder: (context, _) => Row( - mainAxisSize: MainAxisSize.min, - children: [ - for (var index = 0; index < 3; index++) - Padding( - padding: EdgeInsetsDirectional.only( - start: index == 0 ? 0 : dot * 0.6, - ), - child: Opacity( - opacity: MediaQuery.disableAnimationsOf(context) - ? 1 - : 0.35 + - 0.65 * - (0.5 + - 0.5 * - math.sin( - 2 * - math.pi * - (_animation.value - index / 3), - )), - child: DecoratedBox( - decoration: BoxDecoration( - color: color, - shape: BoxShape.circle, + width: dot * 4.2, + child: LayoutBuilder( + builder: (context, _) => AnimatedBuilder( + animation: _animation, + builder: (context, _) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (var index = 0; index < 3; index++) + Padding( + padding: EdgeInsetsDirectional.only( + start: index == 0 ? 0 : dot * 0.6, + ), + child: Opacity( + opacity: MediaQuery.disableAnimationsOf(context) + ? 1 + : 0.35 + + 0.65 * + (0.5 + + 0.5 * + math.sin( + 2 * + math.pi * + (_animation.value - + index / 3), + )), + child: DecoratedBox( + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + ), + child: SizedBox.square(dimension: dot), ), - child: SizedBox.square(dimension: dot), ), ), - ), - ], + ], + ), ), ), ), diff --git a/app/lib/ui/status/app_spinner.dart b/app/lib/ui/status/app_spinner.dart index 72d48c7f..e1e5a9ea 100644 --- a/app/lib/ui/status/app_spinner.dart +++ b/app/lib/ui/status/app_spinner.dart @@ -33,9 +33,17 @@ class _AppSpinnerState extends State super.dispose(); } + /// The indicator rebuilds on every animation frame. A rebuild under an + /// enclosing [LayoutBuilder] (a list row's) marks that builder for layout, + /// and a row in a list then relays the whole list out on every frame. Under + /// its own builder the rebuild lays out only this spinner (and, under loose + /// constraints, its parents up to the nearest relayout boundary); in a fixed + /// square, as in chat rows, it stops at the spinner. @override - Widget build(BuildContext context) => CircularProgressIndicator( - controller: _controller, - strokeWidth: widget.strokeWidth, + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, _) => CircularProgressIndicator( + controller: _controller, + strokeWidth: widget.strokeWidth, + ), ); } diff --git a/app/test/features/chat/conversation/chat_composer_rebuild_test.dart b/app/test/features/chat/conversation/chat_composer_rebuild_test.dart new file mode 100644 index 00000000..9a6db97c --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_rebuild_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_composer_bar_fixtures.dart'; + +/// Counts rebuilds of the composer's own controls (its attach button stands +/// for the whole bar, Send for the usage ring around it): typing and streamed +/// frames must leave them alone. +int _barBuilds = 0; + +const _controls = [Key('chat-composer-attach'), Key('chat-composer-primary')]; + +void _countBar(Element element, bool builtOnce) { + if (_controls.contains(element.widget.key)) _barBuilds++; +} + +void main() { + late ComposerBarGateway gateway; + + setUp(() { + gateway = ComposerBarGateway()..page = fixtureTurn(); + _barBuilds = 0; + }); + + tearDown(() { + debugOnRebuildDirtyWidget = null; + gateway.close(); + }); + + testWidgets('typing rebuilds the bar only when its controls change', ( + tester, + ) async { + await tester.pumpWidget(composerThread(gateway)); + await tester.pumpAndSettle(); + final field = find.byKey(const Key('chat-composer-field')); + debugOnRebuildDirtyWidget = _countBar; + + // The first character enables Send: one rebuild of each control. + await tester.enterText(field, 'h'); + await tester.pump(); + expect(_barBuilds, 2); + + // Further plain typing changes only the field's own text. + for (final draft in ['he', 'hel', 'hell', 'hello', 'hello there']) { + await tester.enterText(field, draft); + await tester.pump(); + } + expect(_barBuilds, 2); + + // A `/` command opens the palette, which the bar draws. + await tester.enterText(field, '/'); + await tester.pump(); + expect(_barBuilds, 4); + await tester.enterText(field, ''); + await tester.pump(); + }); + + testWidgets('a streamed frame does not rebuild the bar', (tester) async { + await tester.pumpWidget(composerThread(gateway)); + await tester.pumpAndSettle(); + debugOnRebuildDirtyWidget = _countBar; + for (var i = 0; i < 6; i++) { + // The first deltas start the turn, which the bar shows (its running + // edge); later ones only grow the reply. + if (i == 2) _barBuilds = 0; + gateway.emitEvent({ + 'session_id': 's', + 'message_id': 'live', + 'kind': 'text', + 'part': {'id': 'live#text#0'}, + 'delta': 'Streaming $i ', + }); + await tester.pump(); + } + expect(find.textContaining('Streaming'), findsOneWidget); + expect(_barBuilds, 0); + }); +} diff --git a/app/test/features/chat/conversation/composer_running_outline_test.dart b/app/test/features/chat/conversation/composer_running_outline_test.dart new file mode 100644 index 00000000..74aae3da --- /dev/null +++ b/app/test/features/chat/conversation/composer_running_outline_test.dart @@ -0,0 +1,87 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/composer_running_outline.dart'; + +/// Records the strokes a [RunningRRectOutline] draws. +class _Recorder implements Canvas { + final lines = <(Offset, Offset)>[]; + final arcs = <(Rect, double, double)>[]; + + @override + void drawLine(Offset p1, Offset p2, Paint paint) => lines.add((p1, p2)); + + @override + void drawArc(Rect rect, double start, double sweep, bool c, Paint paint) => + arcs.add((rect, start, sweep)); + + @override + dynamic noSuchMethod(Invocation invocation) => + throw UnsupportedError('${invocation.memberName}'); +} + +void main() { + const shape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(24)), + ); + + for (final size in const [Size(320, 48), Size(300, 100), Size(40, 30)]) { + test('follows the path outline of a $size pill by arc length', () { + final rect = Offset.zero & size; + final outline = RunningRRectOutline.of(shape, rect)!; + final metric = shape.getOuterPath(rect).computeMetrics().single; + // Path metrics approximate curves to about a pixel over the lap. + expect(outline.length, closeTo(metric.length, 1.5)); + for (var k = 0; k < 64; k++) { + final d = metric.length * k / 64; + final expected = metric.getTangentForOffset(d)!.position; + expect( + (outline.pointAt(d) - expected).distance, + lessThan(1.5), + reason: 'at $d of ${metric.length}', + ); + } + }); + } + + test('draws a range as lines along edges and arcs round corners', () { + final outline = RunningRRectOutline.of( + shape, + const Rect.fromLTWH(0, 0, 320, 48), + )!; + // A 320x48 pill with radius 24: no left straight, then the top-left + // corner, then the top edge. + final canvas = _Recorder(); + outline.draw(canvas, 10, 60, Paint()); + expect(canvas.arcs, hasLength(1)); + expect( + canvas.arcs.single.$1, + Rect.fromCircle(center: const Offset(24, 24), radius: 24), + ); + expect(canvas.arcs.single.$2, closeTo(math.pi + 10 / 24, 1e-9)); + expect(canvas.lines, hasLength(1)); + final (from, to) = canvas.lines.single; + expect(from, const Offset(24, 0)); + expect(to.dx, closeTo(24 + 60 - 12 * math.pi, 1e-9)); + }); + + test('other shapes fall back to the measured path', () { + expect( + RunningRRectOutline.of( + const StadiumBorder(), + const Rect.fromLTWH(0, 0, 9, 9), + ), + isNull, + ); + expect( + RunningRRectOutline.of( + const RoundedRectangleBorder( + borderRadius: BorderRadius.only(topLeft: Radius.circular(4)), + ), + const Rect.fromLTWH(0, 0, 9, 9), + ), + isNull, + ); + }); +} diff --git a/app/test/ui/status/app_spinner_test.dart b/app/test/ui/status/app_spinner_test.dart index 374dd2c6..6d36b265 100644 --- a/app/test/ui/status/app_spinner_test.dart +++ b/app/test/ui/status/app_spinner_test.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/ui/status/app_spinner.dart'; @@ -17,4 +18,65 @@ void main() { expect(indicator.strokeWidth, 2); await tester.pumpWidget(const SizedBox()); }); + + testWidgets('a spinning row does not lay its list out again every frame', ( + tester, + ) async { + final layouts = [0]; + await tester.pumpWidget( + MaterialApp( + home: ListView( + children: [ + for (var i = 0; i < 3; i++) + _LayoutCount( + layouts: layouts, + // A list row that picks its layout from its width, as + // AppListRow does. + child: LayoutBuilder( + builder: (context, constraints) => Row( + children: [ + if (i == 1) + const SizedBox.square( + dimension: 12, + child: AppSpinner(strokeWidth: 2), + ), + Text('row $i'), + ], + ), + ), + ), + ], + ), + ), + ); + final before = layouts[0]; + for (var frame = 0; frame < 10; frame++) { + await tester.pump(const Duration(milliseconds: 16)); + } + expect(layouts[0], before); + await tester.pumpWidget(const SizedBox()); + }); +} + +/// Counts the layouts of a list row. +class _LayoutCount extends SingleChildRenderObjectWidget { + const _LayoutCount({required this.layouts, required super.child}); + + final List layouts; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderLayoutCount(layouts); +} + +class _RenderLayoutCount extends RenderProxyBox { + _RenderLayoutCount(this.layouts); + + final List layouts; + + @override + void performLayout() { + layouts[0]++; + super.performLayout(); + } } diff --git a/app/tool/perf/chat_4k_bench.mjs b/app/tool/perf/chat_4k_bench.mjs index ad767a4a..95f18686 100644 --- a/app/tool/perf/chat_4k_bench.mjs +++ b/app/tool/perf/chat_4k_bench.mjs @@ -30,7 +30,7 @@ const { values: opts } = parseArgs({ options: { build: { type: 'string' }, out: { type: 'string' }, repeat: { type: 'string', default: '3' }, gpu: { type: 'boolean' }, size: { type: 'string', default: '3840x2160' }, dpr: { type: 'string', default: '1' }, - only: { type: 'string' }, live: { type: 'string', default: '200' }, + only: { type: 'string' }, live: { type: 'string', default: '200' }, data: { type: 'string' }, frames: { type: 'boolean' }, }, }); if (!opts.build || !opts.out) throw new Error('usage: --build --out [--gpu]'); @@ -39,6 +39,8 @@ const DPR = Number(opts.dpr); const DATA = { chats: '12', msgs: '150', rich: '1', links: '1', turnactivity: '1', timestamps: '1', shown: '1', turndiffs: '1', theme: 'light', + // --data 'chats=20&msgs=200,60&bgwork=1' adds or overrides fixture options. + ...Object.fromEntries(new URLSearchParams(opts.data ?? '')), }; const r1 = (x) => Math.round(x * 10) / 10; @@ -179,6 +181,8 @@ async function measure(name, extra, drive) { }; } if (errors.length) result.errors = [...new Set(errors)].slice(0, 3); + // --frames keeps every measured frame's build/raster ms in the JSON. + if (opts.frames) result.frameMs = frames.map((f) => `${r1(f[0] / 1000)}/${r1(f[1] / 1000)}`).join(' '); runs.push(result); } finally { await browser.close().catch(() => {}); @@ -216,6 +220,20 @@ const SCENARIOS = { } }, }, + ctrltab: { + extra: {}, + drive: async (io) => { + await io.tap(points.composer); + await delay(300); + for (let i = 0; i < 6; i++) { + await io.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Control', code: 'ControlLeft', modifiers: 2, windowsVirtualKeyCode: 17 }); + await io.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Tab', code: 'Tab', modifiers: 2, windowsVirtualKeyCode: 9 }); + await io.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', modifiers: 2, windowsVirtualKeyCode: 9 }); + await io.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Control', code: 'ControlLeft', modifiers: 0, windowsVirtualKeyCode: 17 }); + await delay(900); + } + }, + }, type: { extra: {}, drive: async (io) => {