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 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 01:21:19 +00:00
parent 2889d59119
commit 7b045e5aab
13 changed files with 534 additions and 60 deletions
@@ -268,7 +268,9 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
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<ChatComposerBar> {
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<ChatComposerBar> {
);
}
/// 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<ChatComposerBar> {
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<ChatComposerBar> {
_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<ChatComposerBar> {
@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();
@@ -45,12 +45,48 @@ class _ChatSendUsageRingState extends State<ChatSendUsageRing> {
/// 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<ChatSendUsageRing> {
@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(
@@ -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<ChatThreadView> {
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(
@@ -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,
@@ -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;
}
@@ -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());
}
}
@@ -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<ChatAttachmentThumbnail> {
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) {
@@ -49,41 +49,48 @@ class _ChatResponsePendingState extends State<ChatResponsePending>
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),
),
),
),
],
],
),
),
),
),