Animate chat composer while turns run

Replace the running Stop button with an animated composer border and task spinner. Add Escape, slash-command, and touch-menu stopping paths with focused widget coverage, including reduced-motion behavior.
This commit is contained in:
2026-11-12 02:24:46 +00:00
parent e4f3ebdcab
commit f3a469c356
14 changed files with 997 additions and 300 deletions
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import 'chat_background_tasks_controller.dart';
import 'chat_background_tasks_dialog.dart';
import 'chat_task_spinner.dart';
/// Compact live task count: a quiet control inside the composer beside Send,
/// shown only while tasks run. Details live only in its modal.
@@ -146,10 +147,13 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
visualDensity: VisualDensity.compact,
),
onPressed: _open,
icon: Icon(
automationOnly ? Icons.schedule : Icons.layers_outlined,
size: 16,
),
// The layers turn only while a task runs; automations stay still.
icon: automationOnly
? const Icon(Icons.schedule, size: 16)
: ChatTaskSpinner(
spinning: count > 0,
child: const Icon(Icons.layers_outlined, size: 16),
),
label: caption(),
);
return Padding(
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import '../../../ui/scale/ui_scale.dart';
import '../../../ui/motion/surface_visibility.dart';
import 'chat_stop_icon.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
@@ -30,6 +29,7 @@ import 'composer_focus_request.dart';
import 'composer_focus_restore.dart';
import 'chat_bar_tint.dart';
import 'composer_focus_ring.dart';
import 'composer_running_border.dart';
import '../shell/chat_shell_command.dart';
import '../shell/chat_shell_mode_indicator.dart';
@@ -70,8 +70,10 @@ double chatComposerBottomMargin([TargetPlatform? platform]) =>
? kChatComposerDesktopBottomMargin
: kChatComposerBottomMargin;
/// The single primary control's words while a turn is and is not running.
/// The single primary control's words.
const String chatSendLabel = 'Send';
/// The chat's More-menu word for stopping a running turn.
const String chatStopLabel = 'Stop';
/// The primary control's words while the draft is a `!` shell command.
@@ -95,7 +97,8 @@ const String chatQueuedNotice =
'Queued — it will send when the current turn finishes.';
/// The foot of one conversation: a native multiline field and Send control,
/// with a separate Stop while a turn runs, driven by [ChatComposerController].
/// driven by [ChatComposerController]. A running turn shows a travelling
/// border, not a stop control.
///
/// The field owns only its [TextEditingController] and focus; the durable draft
/// text lives in the composer controller, so a live transcript rebuild never
@@ -153,7 +156,7 @@ class ChatComposerBar extends StatefulWidget {
/// session (null) keeps those commands on the unavailable report.
final ChatCommandActions? commands;
/// The thread controller's running bit; shows Stop without hiding Send.
/// The thread controller's running bit; shows the running border.
final bool running;
/// The host picker seam; production uses [hostChatAttachmentPicker].
@@ -400,6 +403,13 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
/// 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.
bool _paletteCompletes() =>
_paletteCommands().isNotEmpty &&
chatCommandNamed(widget.composer.draft) == null;
/// The recorded commands matching the current draft while the palette is
/// open. A dismissed or completed draft keeps its palette closed until the
/// operator types something newer.
@@ -512,8 +522,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
(keyboard.isShiftPressed || keyboard.isAltPressed)) {
return;
}
final commands = _paletteCommands();
if (commands.isNotEmpty) {
if (_paletteCompletes()) {
final commands = _paletteCommands();
_completeCommand(commands[_selectedCommand % commands.length]);
return;
}
@@ -943,10 +953,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
),
child: widget.backgroundTasks!,
),
if (widget.running) ...[
_primary(context, stop: true),
const SizedBox(width: 4),
],
_primary(context),
],
),
@@ -973,21 +979,41 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// the transcript, so the composer reads as a single input rather than a
/// row of separate controls, and the conversation shows through it. While
/// the field has focus a ring in the chat's colour runs along its edge.
Widget _pill(BuildContext context, Widget child) => ComposerFocusRing(
focus: _focus,
accent: chatFocusRingColor(context, widget.chatColor),
shape: _pillShape,
child: GlassPill(
key: const Key('chat-composer-pill'),
shape: _pillShape,
// The end controls keep the same gap from the pill's sides as from
// its bottom (and its top while the field is one line).
child: Padding(
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
child: child,
),
),
);
///
/// While a turn runs a highlight travels around the same edge
/// ([ComposerRunningBorder]); it is mounted only for that time.
Widget _pill(BuildContext context, Widget child) {
final accent = chatFocusRingColor(context, widget.chatColor);
return Stack(
children: [
ComposerFocusRing(
focus: _focus,
accent: accent,
shape: _pillShape,
child: GlassPill(
key: const Key('chat-composer-pill'),
shape: _pillShape,
// The end controls keep the same gap from the pill's sides as from
// its bottom (and its top while the field is one line).
child: Padding(
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
child: child,
),
),
),
if (widget.running)
Positioned.fill(
child: IgnorePointer(
child: ComposerRunningBorder(
shape: _pillShape,
primary: accent,
tertiary: Theme.of(context).colorScheme.tertiary,
),
),
),
],
);
}
/// The attach control: a host button that opens the picker, disabled when the
/// host has no picker or one prompt is already awaiting its reply.
@@ -1167,21 +1193,19 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
Widget _primary(BuildContext context, {bool stop = false}) {
/// The single primary control: Send (or Run command for a `!` draft). A
/// prompt sent while a turn runs takes the server's queued-prompt path; the
/// running turn is stopped by Escape twice, `/stop`, or the More menu.
Widget _primary(BuildContext context) {
final composer = widget.composer;
final enabled = stop
? !composer.stopping
: !_uploading &&
!_shellStarting &&
!composer.sending &&
composer.draft.trim().isNotEmpty;
final enabled =
!_uploading &&
!_shellStarting &&
!composer.sending &&
composer.draft.trim().isNotEmpty;
void press() {
if (stop) {
unawaited(composer.stop());
return;
}
final commands = _paletteCommands();
if (commands.isNotEmpty) {
if (_paletteCompletes()) {
final commands = _paletteCommands();
_completeCommand(commands[_selectedCommand % commands.length]);
} else if (chatDraftIsShell(composer.draft)) {
unawaited(_runShellDraft());
@@ -1192,36 +1216,23 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
}
}
// Sending while the turn runs uses the server's existing queued-prompt path.
// Stopping is always a separate, explicitly named action.
final label = stop
? chatStopLabel
: chatDraftIsShell(composer.draft)
final label = chatDraftIsShell(composer.draft)
? chatRunShellLabel
: chatSendLabel;
final key = Key(stop ? 'chat-composer-stop' : 'chat-composer-primary');
// A coloured chat's send button takes the chat's colour (its seeded
// primary, like the focus ring); stop stays the host's error red.
// primary, like the focus ring).
final tinted = chatSchemeOf(context, widget.chatColor);
final scheme = Theme.of(context).colorScheme;
return IconButton.filled(
key: key,
key: const Key('chat-composer-primary'),
tooltip: label,
style: stop
? IconButton.styleFrom(
backgroundColor: scheme.error,
foregroundColor: scheme.onError,
)
: tinted == null
style: tinted == null
? null
: IconButton.styleFrom(
backgroundColor: tinted.primary,
foregroundColor: tinted.onPrimary,
),
onPressed: enabled ? press : null,
icon: stop
? const ChatStopIcon(child: Icon(Icons.stop))
: const Icon(Icons.arrow_upward),
icon: const Icon(Icons.arrow_upward),
);
}
@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// The longest gap between two Escape presses that still stops a running turn.
const Duration chatEscapeStopWindow = Duration(seconds: 1);
/// The hint shown after the first Escape while a turn runs.
const String chatEscapeStopHint = 'Press Esc again to stop';
/// Two presses of Escape stop a running turn: the first shows [chatEscapeStopHint]
/// and the second, inside [chatEscapeStopWindow], stops it. Pure timing, so the
/// clock is the caller's.
class ChatEscapeStopTracker {
DateTime? _firstAt;
/// Records one plain Escape press at [now]. Returns true when it completes a
/// pair; a press that completes nothing starts a new pair.
bool press(DateTime now) {
final first = _firstAt;
if (first != null && now.difference(first) <= chatEscapeStopWindow) {
_firstAt = null;
return true;
}
_firstAt = now;
return false;
}
/// Forgets a pending first press, for example once the turn has ended.
void reset() => _firstAt = null;
}
/// Lets two presses of Escape stop the turn while focus is anywhere inside
/// [child] (the composer or the transcript). It only consumes Escape while
/// [running]; an idle chat, and any Escape a descendant already handled (a
/// command palette, a notice), pass through untouched.
class ChatEscapeStop extends StatefulWidget {
const ChatEscapeStop({
super.key,
required this.running,
required this.onStop,
required this.child,
this.clock = DateTime.now,
});
final bool running;
/// Stops the running turn; called on the second press.
final VoidCallback onStop;
/// Injected time source, so tests control the window.
final DateTime Function() clock;
final Widget child;
@override
State<ChatEscapeStop> createState() => _ChatEscapeStopState();
}
class _ChatEscapeStopState extends State<ChatEscapeStop> {
final ChatEscapeStopTracker _tracker = ChatEscapeStopTracker();
@override
void didUpdateWidget(covariant ChatEscapeStop oldWidget) {
super.didUpdateWidget(oldWidget);
if (!widget.running) _tracker.reset();
}
KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {
if (event.logicalKey != LogicalKeyboardKey.escape || !widget.running) {
return KeyEventResult.ignored;
}
final keyboard = HardwareKeyboard.instance;
if (keyboard.isControlPressed ||
keyboard.isMetaPressed ||
keyboard.isShiftPressed ||
keyboard.isAltPressed) {
return KeyEventResult.ignored;
}
// Holding Escape is one press, and releasing it is not a press at all.
if (event is! KeyDownEvent) {
return event is KeyRepeatEvent
? KeyEventResult.handled
: KeyEventResult.ignored;
}
if (_tracker.press(widget.clock())) {
_tracker.reset();
_hideHint();
widget.onStop();
} else {
_showHint();
}
return KeyEventResult.handled;
}
void _showHint() {
final messenger = ScaffoldMessenger.maybeOf(context);
if (messenger == null) return;
messenger
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
key: Key('chat-escape-stop-hint'),
content: Text(chatEscapeStopHint),
duration: chatEscapeStopWindow,
behavior: SnackBarBehavior.floating,
),
);
}
void _hideHint() => ScaffoldMessenger.maybeOf(context)?.hideCurrentSnackBar();
@override
Widget build(BuildContext context) => Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _onKeyEvent,
child: widget.child,
);
}
@@ -1,48 +0,0 @@
import 'package:flutter/widgets.dart';
/// Slow, continuous progress motion confined to the Stop glyph. The native
/// button, hit target and semantics never rotate. TickerMode pauses hidden UI.
class ChatStopIcon extends StatefulWidget {
const ChatStopIcon({super.key, required this.child});
final Widget child;
static const period = Duration(seconds: 8);
@override
State<ChatStopIcon> createState() => _ChatStopIconState();
}
class _ChatStopIconState extends State<ChatStopIcon>
with SingleTickerProviderStateMixin {
late final _rotation = AnimationController(
vsync: this,
duration: ChatStopIcon.period,
);
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (MediaQuery.maybeDisableAnimationsOf(context) ?? false) {
_rotation.stop();
_rotation.value = 0;
} else if (!_rotation.isAnimating) {
_rotation.repeat();
}
}
@override
void dispose() {
_rotation.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RepaintBoundary(
key: const Key('chat-stop-paint-boundary'),
child: RotationTransition(
key: const Key('chat-stop-rotation'),
turns: _rotation,
child: widget.child,
),
);
}
@@ -0,0 +1,71 @@
import 'package:flutter/widgets.dart';
/// Turns [child] once every [period] while [spinning]; static otherwise. With
/// reduced motion it never turns. Hidden UI is silenced by TickerMode.
class ChatTaskSpinner extends StatefulWidget {
const ChatTaskSpinner({
super.key,
required this.spinning,
required this.child,
});
final bool spinning;
final Widget child;
/// One full turn while tasks run.
static const Duration period = Duration(milliseconds: 2500);
@override
State<ChatTaskSpinner> createState() => _ChatTaskSpinnerState();
}
class _ChatTaskSpinnerState extends State<ChatTaskSpinner>
with SingleTickerProviderStateMixin {
late final AnimationController _turns = AnimationController(
vsync: this,
duration: ChatTaskSpinner.period,
);
bool _reduced = false;
@override
void initState() {
super.initState();
_sync();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
_sync();
}
@override
void didUpdateWidget(covariant ChatTaskSpinner oldWidget) {
super.didUpdateWidget(oldWidget);
_sync();
}
void _sync() {
if (widget.spinning && !_reduced) {
if (!_turns.isAnimating) _turns.repeat();
} else {
_turns
..stop()
..value = 0;
}
}
@override
void dispose() {
_turns.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RotationTransition(
key: const Key('chat-background-tasks-spinner'),
turns: _turns,
child: widget.child,
);
}
@@ -42,6 +42,7 @@ import 'chat_background_tasks.dart';
import 'chat_command_actions.dart';
import 'chat_composer_bar.dart';
import 'chat_composer_controller.dart';
import 'chat_escape_stop.dart';
import 'chat_delivery_indicator.dart';
import 'chat_draft_store.dart';
import 'chat_effort_control.dart';
@@ -1383,7 +1384,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// The bar and the jump control float over the transcript and the
// composer sits below it; the wheel over them scrolls it, as a page
// scrolls under fixed bars.
final column = VerticalWheelForwarder(controller: _scroll, child: page);
// Two Escape presses stop a running turn while the conversation has
// the keyboard; the wheel over the page still scrolls it.
final column = ChatEscapeStop(
running: _controller.running,
onStop: _stopTurn,
child: VerticalWheelForwarder(controller: _scroll, child: page),
);
final wideFiles =
_filesVisible && MediaQuery.sizeOf(context).width >= 700;
_reportCenterStageFilesWidth();
@@ -1479,6 +1486,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
],
moreActions: [
?widget.sidebarControl,
// Touch devices have no Escape key; the menu is their way to stop.
if (_controller.running)
ChatBarAction(
key: const Key('chat-thread-stop-menu'),
label: chatStopLabel,
identifier: 'chat-thread-stop',
onPressed: _stopTurn,
materialIcon: Icons.stop,
),
// A window's own title bar names the chat, and its narrow action
// bar has no room for the title that opens the details.
if (WindowScope.maybeOf(context) != null)
@@ -1534,6 +1550,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
onChanged: widget.onModeChanged,
);
/// Stops the running turn, as the composer's `/stop` does.
void _stopTurn() => unawaited(_composer.stop());
void _runShellFromMenu() => unawaited(
runChatShellFromMenu(context, _shellRuns, showNotice: _showCommandNotice),
);
@@ -0,0 +1,146 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
/// The composer's "agent is working" edge: a soft highlight that travels once
/// around the pill's rounded border in [primary] and [tertiary], with a faint
/// glow beneath it. Mount it only while a turn runs; disposing it stops the
/// animation, so the border ends cleanly with the turn.
///
/// With reduced motion (the platform's disable-animations setting) it draws
/// a static, evenly highlighted border instead and never ticks.
class ComposerRunningBorder extends StatefulWidget {
const ComposerRunningBorder({
super.key,
required this.shape,
required this.primary,
required this.tertiary,
});
/// The pill's shape, so the highlight follows its edge.
final OutlinedBorder shape;
final Color primary;
final Color tertiary;
/// One lap of the highlight around the border.
static const Duration period = Duration(seconds: 4);
/// The stroke drawn just inside the pill's edge.
static const double strokeWidth = 2;
/// The static border's opacity under reduced motion.
static const double staticOpacity = 0.7;
@override
State<ComposerRunningBorder> createState() => _ComposerRunningBorderState();
}
class _ComposerRunningBorderState extends State<ComposerRunningBorder>
with SingleTickerProviderStateMixin {
late final AnimationController _lap = AnimationController(
vsync: this,
duration: ComposerRunningBorder.period,
);
bool _reduced = false;
@override
void initState() {
super.initState();
_lap.repeat();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
if (reduced == _reduced) return;
_reduced = reduced;
if (reduced) {
_lap.stop();
} else {
_lap.repeat();
}
}
@override
void dispose() {
_lap.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => RepaintBoundary(
key: const Key('chat-composer-running-border'),
child: CustomPaint(
painter: _RunningBorderPainter(
shape: widget.shape,
primary: widget.primary,
tertiary: widget.tertiary,
lap: _reduced ? null : _lap,
),
),
);
}
class _RunningBorderPainter extends CustomPainter {
_RunningBorderPainter({
required this.shape,
required this.primary,
required this.tertiary,
required this.lap,
}) : super(repaint: lap);
final OutlinedBorder shape;
final Color primary;
final Color tertiary;
/// The lap's progress, or null for the static reduced-motion border.
final Animation<double>? lap;
@override
void paint(Canvas canvas, Size size) {
if (size.isEmpty) return;
const width = ComposerRunningBorder.strokeWidth;
final rect = Offset.zero & size;
final path = shape.getOuterPath(rect.deflate(width / 2));
final glow = Paint()
..style = PaintingStyle.stroke
..strokeWidth = width * 3
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4);
final line = Paint()
..style = PaintingStyle.stroke
..strokeWidth = width;
final progress = lap?.value;
if (progress == null) {
final solid = primary.withValues(
alpha: ComposerRunningBorder.staticOpacity,
);
glow.color = solid.withValues(alpha: solid.a * .4);
line.color = solid;
} else {
final shader = SweepGradient(
colors: [
primary.withValues(alpha: 0),
primary,
tertiary,
tertiary.withValues(alpha: 0),
primary.withValues(alpha: 0),
],
stops: const [0, .12, .24, .38, 1],
transform: GradientRotation(progress * 2 * math.pi),
).createShader(rect);
glow.shader = shader;
line.shader = shader;
}
canvas
..drawPath(path, glow)
..drawPath(path, line);
}
@override
bool shouldRepaint(_RunningBorderPainter oldDelegate) =>
oldDelegate.shape != shape ||
oldDelegate.primary != primary ||
oldDelegate.tertiary != tertiary ||
oldDelegate.lap != lap;
}