diff --git a/app/lib/features/chat/conversation/chat_row_keys.dart b/app/lib/features/chat/conversation/chat_row_keys.dart index f677ac09..8415982a 100644 --- a/app/lib/features/chat/conversation/chat_row_keys.dart +++ b/app/lib/features/chat/conversation/chat_row_keys.dart @@ -60,6 +60,17 @@ class ChatRowKeys { } static List _messageIds(JsonMap row) { + // A sent message is the same row before and after the server's copy + // replaces the local one, even if the copy carries another id. + final message = row['message']; + final operation = row['kind'] == 'user' && message is Map + ? '${message['operation_id'] ?? ''}'.trim() + : ''; + final ids = _recordedIds(row); + return operation.isEmpty ? ids : [...ids, 'operation:$operation']; + } + + static List _recordedIds(JsonMap row) { final listed = row['messageIds']; if (listed is List) { return listed diff --git a/app/lib/features/chat/conversation/chat_sent_entrance.dart b/app/lib/features/chat/conversation/chat_sent_entrance.dart new file mode 100644 index 00000000..2164fdc1 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_sent_entrance.dart @@ -0,0 +1,126 @@ +import 'package:flutter/widgets.dart'; + +import '../../../ui/motion/motion.dart'; + +/// The messages this device has just sent that have not yet been drawn. +/// +/// A send marks its operation id; the first [ChatSentEntrance] built for that +/// id claims it and plays. Everything else (history, a scroll back into view, +/// another device's message, the server's copy replacing the local one, a +/// remount) finds nothing to claim and simply appears. +class ChatSentEntrances { + final Set _pending = {}; + + /// Marks [operationId] as just sent, so its row enters once. + void mark(String operationId) { + if (operationId.isNotEmpty) _pending.add(operationId); + } + + /// Forgets [operationId] (a refused send) without playing it. + void forget(String operationId) => _pending.remove(operationId); + + /// True once for a marked [operationId]. + bool claim(String operationId) => _pending.remove(operationId); +} + +/// One transcript row that rises from the composer when it is a message the +/// operator has just sent: up [Motion.sentMessageRise], growing from +/// [Motion.sentMessageScaleBegin] and fading in. Paint-only, so the row is +/// laid out (and scrolled to) at its resting place from the first frame. +/// +/// Whether it plays is decided once, when it is first built; under reduced +/// motion it never plays. +class ChatSentEntrance extends StatefulWidget { + const ChatSentEntrance({ + super.key, + required this.entrances, + required this.operationId, + required this.child, + }); + + final ChatSentEntrances entrances; + + /// The row's message operation id, or empty for a row that is not a sent + /// message. + final String operationId; + final Widget child; + + @override + State createState() => _ChatSentEntranceState(); +} + +class _ChatSentEntranceState extends State + with SingleTickerProviderStateMixin { + AnimationController? _controller; + Animation _motion = kAlwaysCompleteAnimation; + Animation _opacity = kAlwaysCompleteAnimation; + bool _decided = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_decided) return; + _decided = true; + if (widget.operationId.isEmpty || + !widget.entrances.claim(widget.operationId)) { + return; + } + final duration = Motion.of(context, Motion.sentMessageDuration); + if (duration == Duration.zero) return; + // Reduced motion is already settled through the MediaQuery above, so the + // controller does not shorten itself a second time. + final controller = AnimationController( + vsync: this, + duration: duration, + animationBehavior: AnimationBehavior.preserve, + ); + _controller = controller; + _motion = CurvedAnimation( + parent: controller, + curve: Motion.sentMessageCurve, + ); + _opacity = CurvedAnimation( + parent: controller, + curve: const Interval( + 0, + Motion.sentMessageOpacityPortion, + curve: Curves.easeOut, + ), + ); + controller.forward(); + } + + @override + void dispose() { + if (_motion case final CurvedAnimation curved) curved.dispose(); + if (_opacity case final CurvedAnimation curved) curved.dispose(); + _controller?.dispose(); + super.dispose(); + } + + // The same tree whether or not it plays, so the row's element (and any + // state in it) is never remounted. At rest the transforms are identities + // and the opacity is full, which paint the row directly. + @override + Widget build(BuildContext context) => FadeTransition( + opacity: _opacity, + alwaysIncludeSemantics: true, + child: AnimatedBuilder( + animation: _motion, + child: widget.child, + builder: (context, child) { + final t = _motion.value; + return Transform.translate( + offset: Offset(0, (1 - t) * Motion.sentMessageRise), + child: Transform.scale( + scale: + Motion.sentMessageScaleBegin + + (1 - Motion.sentMessageScaleBegin) * t, + alignment: AlignmentDirectional.bottomEnd, + child: child, + ), + ); + }, + ), + ); +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 56c5710d..79e85230 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -38,6 +38,7 @@ import 'chat_models.dart'; import 'chat_row_keys.dart'; import 'chat_row_widgets.dart'; import 'chat_scroll.dart'; +import 'chat_sent_entrance.dart'; import 'chat_server_queue.dart'; import 'chat_thread_controller.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; @@ -159,6 +160,7 @@ class _ChatThreadViewState extends State { late ChatThreadController _controller = _attach(); late ChatComposerController _composer = _attachComposer(); late ChatRowKeys _rowKeys = ChatRowKeys(); + final _sentEntrances = ChatSentEntrances(); final _rowWidgets = ChatRowWidgets(); /// The floating bar and composer, reused while their inputs hold so a @@ -334,6 +336,9 @@ class _ChatThreadViewState extends State { void _onOptimistic(ChatComposerSend send) { if (!mounted) return; _controller.removeLocal(send.operationId); + // Only this message rises in from the composer; its server copy, history + // and other devices' messages appear in place. + _sentEntrances.mark(send.operationId); _controller.insertLocal(send.toMessage()); // Sending always shows the end of the conversation, even when the // operator had scrolled up or the message is taller than the screen; @@ -353,6 +358,7 @@ class _ChatThreadViewState extends State { /// sent" from the composer's deliveries instead. void _onRejected(ChatComposerSend send, String error) { if (!mounted) return; + _sentEntrances.forget(send.operationId); _controller.removeLocal(send.operationId); } @@ -958,15 +964,18 @@ class _ChatThreadViewState extends State { Padding( key: ValueKey(keys[index]), padding: const EdgeInsets.symmetric(horizontal: 16), - child: _transcriptRow( + child: _entering( rows[index], - keys[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition(rows[index]) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition(rows[index]) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), ), ), ]; @@ -1306,6 +1315,18 @@ class _ChatThreadViewState extends State { ); } + /// A user row in the entrance a just-sent message plays; every user row is + /// wrapped, so its server copy replacing it keeps the same element. + Widget _entering(JsonMap row, Widget child) { + if (row['kind'] != 'user') return child; + final message = row['message']; + return ChatSentEntrance( + entrances: _sentEntrances, + operationId: message is Map ? '${message['operation_id'] ?? ''}' : '', + child: child, + ); + } + /// Remove for a message the server still holds queued, or null. VoidCallback? _removeAction(String operationId) { if (operationId.isEmpty || !_controller.isQueued(operationId)) return null; diff --git a/app/lib/ui/motion/motion.dart b/app/lib/ui/motion/motion.dart index 14f7239d..9de23d1b 100644 --- a/app/lib/ui/motion/motion.dart +++ b/app/lib/ui/motion/motion.dart @@ -74,6 +74,24 @@ abstract final class Motion { damping: 28, ); + /// How long a message the operator just sent takes to rise into the + /// conversation from the composer. + static const Duration sentMessageDuration = Duration(milliseconds: 280); + + /// How far below its resting place a just-sent message starts, in logical + /// pixels. + static const double sentMessageRise = 20; + + /// The scale a just-sent message grows from. + static const double sentMessageScaleBegin = 0.96; + + /// The fraction of a just-sent message's entrance spent fading in. + static const double sentMessageOpacityPortion = 0.6; + + /// Material's emphasized decelerate: quick off the composer, settling + /// softly with no overshoot. + static const Curve sentMessageCurve = Cubic(0.05, 0.7, 0.1, 1); + static const Curve curve = Curves.easeOutCubic; /// [duration], or zero under the system's reduce-motion setting. diff --git a/app/test/features/chat/conversation/chat_row_keys_test.dart b/app/test/features/chat/conversation/chat_row_keys_test.dart index b57e5b9e..8f40d0bd 100644 --- a/app/test/features/chat/conversation/chat_row_keys_test.dart +++ b/app/test/features/chat/conversation/chat_row_keys_test.dart @@ -98,4 +98,22 @@ void main() { expect(paged.toSet(), hasLength(paged.length)); }); + + test('the server copy of a sent message keeps the local row key', () { + final keys = ChatRowKeys(); + final local = keys.forRows( + transcriptRows([ + _assistant('msg_0'), + {..._user('local-op1'), 'operation_id': 'op1'}, + ]), + ); + final echoed = keys.forRows( + transcriptRows([ + _assistant('msg_0'), + {..._user('srv-1'), 'operation_id': 'op1'}, + ]), + ); + + expect(echoed, local); + }); } diff --git a/app/test/features/chat/conversation/chat_sent_entrance_test.dart b/app/test/features/chat/conversation/chat_sent_entrance_test.dart new file mode 100644 index 00000000..35d7bf59 --- /dev/null +++ b/app/test/features/chat/conversation/chat_sent_entrance_test.dart @@ -0,0 +1,213 @@ +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_sent_entrance.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/ui/motion/motion.dart'; + +import 'chat_thread_fixtures.dart'; + +// A message the operator sends rises in from the composer once; history, its +// server copy, other devices' messages and replies simply appear. +void main() { + Future open( + WidgetTester tester, + FakeChatGateway gateway, { + bool reduced = false, + }) async { + var serial = 0; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: child!, + ), + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + newOperationId: () => 'op${++serial}', + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + JsonMap text(String id, String role, String body, {String? operation}) => { + ...chatMessage( + id, + role, + parts: [ + {'type': 'text', 'text': body}, + ], + ), + 'operation_id': ?operation, + }; + + Future send(WidgetTester tester, String message) async { + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + message, + ); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pump(); + } + + Finder entranceOf(String body) => find.ancestor( + of: find.text(body), + matching: find.byType(ChatSentEntrance), + ); + + double opacityOf(WidgetTester tester, String body) => tester + .widget( + find + .descendant( + of: entranceOf(body), + matching: find.byType(FadeTransition), + ) + .first, + ) + .opacity + .value; + + // How far the drawn text sits below where its row is laid out: the + // entrance only moves the painting, never the layout. + double dropOf(WidgetTester tester, String body) => + tester.getRect(find.text(body)).bottom - + tester.getRect(entranceOf(body)).bottom; + + bool animating(WidgetTester tester, String body) => + opacityOf(tester, body) < 1; + + testWidgets('a sent message rises in and settles fully visible at rest', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => + chatPage([text('h1', 'user', 'From history')]); + await open(tester, gateway); + expect(animating(tester, 'From history'), isFalse); + + await send(tester, 'Hello there'); + expect(entranceOf('Hello there'), findsOneWidget); + expect(opacityOf(tester, 'Hello there'), lessThan(0.05)); + await tester.pump(Motion.sentMessageDuration ~/ 4); + final midOpacity = opacityOf(tester, 'Hello there'); + final midDrop = dropOf(tester, 'Hello there'); + expect(midOpacity, inExclusiveRange(0, 1)); + + await tester.pump(Motion.sentMessageDuration); + await tester.pump(); + expect(opacityOf(tester, 'Hello there'), 1); + final restDrop = dropOf(tester, 'Hello there'); + expect(midDrop, greaterThan(restDrop + 0.5)); + // At rest the transforms are identities. + final transforms = tester.widgetList( + find.descendant( + of: entranceOf('Hello there'), + matching: find.byType(Transform), + ), + ); + for (final transform in transforms.take(2)) { + expect(transform.transform.isIdentity(), isTrue); + } + }); + + testWidgets('the server copy replacing a sent message keeps its row and ' + 'does not play again', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + await open(tester, gateway); + + await send(tester, 'Echo me'); + await tester.pump(Motion.sentMessageDuration); + await tester.pump(); + final before = tester.state(entranceOf('Echo me')); + + // The authoritative copy carries another id but the same operation. + gateway.history = (_) async => chatPage([ + { + ...text('srv-1', 'user', 'Echo me', operation: 'op1'), + 'native_message_id': 'msg_op1', + }, + ]); + gateway.emitEvent({'session_id': 's', 'kind': 'resync'}); + await tester.pump(); + await tester.pump(); + expect(find.text('Echo me'), findsOneWidget); + expect(tester.state(entranceOf('Echo me')), same(before)); + expect(animating(tester, 'Echo me'), isFalse); + }); + + testWidgets('history, other devices and replies appear without the ' + 'entrance', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage([ + text('h1', 'user', 'Earlier question', operation: 'old'), + text('h2', 'assistant', 'Earlier answer'), + ]); + await open(tester, gateway); + expect(animating(tester, 'Earlier question'), isFalse); + + gateway.emitEvent({ + 'session_id': 's', + 'kind': 'user', + 'message_id': 'other-device', + 'operation_id': 'elsewhere', + 'part': {'type': 'text', 'text': 'From the phone'}, + }); + await tester.pump(); + await tester.pump(); + expect(find.text('From the phone'), findsOneWidget); + expect(animating(tester, 'From the phone'), isFalse); + // A reply is not a sent message, so it has no entrance at all. + gateway.emitEvent(chatTextFrame('Agent reply')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + final reply = find.textContaining('Agent reply', findRichText: true); + expect(reply, findsWidgets); + expect( + find.ancestor(of: reply, matching: find.byType(ChatSentEntrance)), + findsNothing, + ); + }); + + testWidgets('a message queued while a turn runs rises in too', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + await open(tester, gateway); + gateway.emitEvent(chatStepFrame('started')); + await tester.pump(); + + await send(tester, 'Queued one'); + expect(animating(tester, 'Queued one'), isTrue); + await tester.pump(Motion.sentMessageDuration); + await tester.pump(); + expect(opacityOf(tester, 'Queued one'), 1); + }); + + testWidgets('under reduced motion a sent message appears at once', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + await open(tester, gateway, reduced: true); + + await send(tester, 'Right away'); + expect(opacityOf(tester, 'Right away'), 1); + expect(dropOf(tester, 'Right away'), lessThanOrEqualTo(0)); + await tester.pump(const Duration(milliseconds: 16)); + expect(opacityOf(tester, 'Right away'), 1); + }); +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index 24d65929..2e3800ed 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -228,6 +228,10 @@ JsonMap? perfChatReply(JsonMap request) { return perfChatNewSessionReply(request, _chatRow); case 'chat_subscribe': return {'id': id, 'type': 'chat_subscribed'}; + case 'chat_prompt': + // Accepted, as the server does; no reply follows, so a capture can + // watch the sent message itself. + return {'id': id, 'type': 'chat_prompt', 'chat_queued': false}; case 'chat_shells': return {'id': id, 'type': 'chat_shells', 'chat_shells': const []}; case 'chat_messages':