The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(phone): Jump to first unread in Swarm chats, as Desktop (#2347)
0xken15dcebba620eef
diff --git a/mobile/integration_test/swarm_jump_unread_test.dart b/mobile/integration_test/swarm_jump_unread_test.dartnew file mode 100644index 000000000..2323faea9--- /dev/null+++ b/mobile/integration_test/swarm_jump_unread_test.dart@@ -0,0 +1,133 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../test/swarm/swarm_fixture.dart';+import '../test/voice_fakes.dart' show MemoryKeyValueStore;++/// Jump to first unread on a simulator's own engine and scrolling: a chat+/// opened from a notice below its New messages line offers the way back, holds+/// steady on the way there, and goes once the line has landed.+///+/// Every answer is scripted in memory ([FakeSwarm]): nothing reaches an+/// account, a machine or the backend.+///+/// flutter test integration_test/swarm_jump_unread_test.dart -d <simulator>+void main() {+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('a tap lands on the line, with no flicker on the way', (+ tester,+ ) async {+ const chat = 'buddy-me';+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ buddyChatData(+ chat,+ agentIds: ['agent-wren'],+ lastMessageSequence: 40,+ ),+ ],+ agents: [buddyData('agent-wren', displayName: 'Wren')],+ derived: {+ 'readMarks': {chat: 5},+ },+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/conversations/$chat/messages'] = (_) => {+ 'messages': [+ for (var i = 40; i >= 1; i--)+ {+ 'id': 'msg-$i',+ 'conversationId': chat,+ 'text': 'Update $i.',+ 'sequence': i,+ 'author': {+ 'kind': 'agent',+ 'id': 'agent-wren',+ 'name': 'agent-wren',+ },+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 29, 1, i).toIso8601String(),+ },+ ],+ 'next': null,+ };+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ notices: SilentSystemNotices(),+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm},+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (_, child) => SwarmScope(notifier: host, child: child!),+ home: const SwarmConversationPage(+ swarmId: tab,+ conversationId: chat,+ messageId: 'msg-25',+ ),+ ),+ );+ await tester.pumpAndSettle();++ final pill = find.byKey(const ValueKey('swarm-jump-unread'));+ final line = find.byKey(const ValueKey('swarm-new-messages-line'));+ final list = find.byKey(const ValueKey('swarm-messages'));+ expect(find.text('Update 25.'), findsOneWidget);+ expect(line, findsNothing);+ expect(pill, findsOneWidget);+ expect(tester.getRect(pill).top, greaterThanOrEqualTo(0));++ await tester.tap(pill);+ final shown = <bool>[];+ for (var i = 0; i < 40; i++) {+ await tester.pump(const Duration(milliseconds: 16));+ shown.add(pill.evaluate().isNotEmpty);+ }+ await tester.pumpAndSettle();++ expect(shown.first, isTrue, reason: 'still there as the jump starts');+ expect(+ shown.skipWhile((s) => s),+ everyElement(isFalse),+ reason: 'no flicker: $shown',+ );+ expect(line, findsOneWidget);+ final view = tester.getRect(list);+ final landed = tester.getRect(line);+ expect(landed.top, greaterThanOrEqualTo(view.top - 1));+ expect(landed.bottom, lessThanOrEqualTo(view.bottom));+ expect(pill, findsNothing);+ expect(find.text('Update 6.'), findsOneWidget);+ });+}diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 249bf7ae3..00b0b1894 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -131,8 +131,9 @@ class SwarmConversationPage extends StatefulWidget {/// Swarm Home C's project chat (Tony, 2026-10-30): a New messages line/// above the first message the person had not read as it opened/// ([swarmFirstUnread]), placed once, the chat opening at it when it is- /// above the screen; and Jump to latest while they read more than a- /// screen back. The person's own Buddy chat has both too, in the project's+ /// above the screen; Jump to first unread while the line is above the view+ /// and has not been seen; and Jump to latest while they read more than a+ /// screen back. The person's own Buddy chat has them too, in the project's/// Buddy tab and on its own page.final bool homeC;@@ -231,6 +232,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>SwarmReadMarks? _marksAwaited;final _lineKey = GlobalKey(debugLabel: 'New messages line');+ /// The line has been in view this visit: reading on needs no way back.+ bool _lineSeen = false;++ /// The line is above the view and not yet seen, where Jump to first unread+ /// is offered ([_measureLine]).+ final _offersUnread = ValueNotifier<bool>(false);++ /// The jump still landing: its passing scroll neither counts the line as+ /// seen nor changes what is offered. Each jump takes a new number.+ int? _landing;+ int _landings = 0;+ bool _measuring = false;+/// No message has this id: held at it, a chat reads nothing until its New/// messages line is placed ([SwarmConversation.heldAt]).static const _undecided = '';@@ -313,19 +327,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>widget.buddy != null ||swarmIsOwnBuddyChat(reader, widget.conversationId);// Set before what the chat kept is shown, so it is read only as far as- // it is seen: opened at a message, through it until the person goes- // down to the foot; with a New messages line to place, nothing until it- // is placed.+ // it is seen: with a New messages line to place, nothing until it is+ // placed, a notice's message included, or the line would sit under it;+ // opened at a message, through it until the person goes down to the foot.final c = _conversation = SwarmConversation(reader,widget.conversationId,shown: _seen,- heldAt:- widget.messageId ??- _held.value ??- ((_unreadLine || _ownerUnknown) && !_lineDecided ? _undecided : null),+ heldAt: (_unreadLine || _ownerUnknown) && !_lineDecided+ ? _undecided+ : widget.messageId ?? _held.value,);c.composer.addListener(_drafted);+ c.addListener(_chatMoved);if (widget.mention case final agentId?) c.mention(agentId);reader.addListener(_see);session.inbox.addListener(_see);@@ -336,12 +350,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>// A chat left behind may finish reading after its replacement began.if (!mounted || _conversation != c) return;_firstRead = true;- _placeLine(c);- if (_noticeHandled) return;- if (widget.messageId case final messageId?) {- _noticeHandled = true;- unawaited(_jumpTo(c, messageId));- }+ _chatMoved();}),);if (rebuild && mounted) setState(() {});@@ -355,15 +364,17 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// once they are back ([_marksMoved]). It stays there however the chat and/// its marks move on. Without one, everything shown is read. A line above/// the screen opens the chat at it ([_openAtLine]), unless a notice opened- /// it at a message.+ /// it at a message. A read that failed says nothing of what is unread: the+ /// chat stays held, and the first read that works places it ([_chatMoved]).void _placeLine(SwarmConversation c) {if (!mounted || _conversation != c || _lineDecided || _ownerUnknown) {return;}if (!_unreadLine) {- if (c.heldAt == _undecided) c.heldAt = null;+ _releaseHold(c);return;}+ if (c.state != SwarmChatState.loaded || c.error != null) return;final marks = c.reader.readMarks;if (marks != null && !marks.loaded) {if (_marksAwaited != marks) {@@ -381,11 +392,40 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>hasOlder: c.hasOlder,);if (at == null) {- if (c.heldAt == _undecided) c.heldAt = null;+ _releaseHold(c);return;}setState(() => _lineAt = at);- if (widget.messageId == null) _openAtLine(c, at, 0);+ if (widget.messageId == null) {+ _openAtLine(c, at, 0);+ } else {+ _releaseHold(c);+ _measureLineSoon();+ }+ }++ /// The line is decided: the chat is read as far as a notice opened it at, or+ /// the person had read back to, else to its foot.+ void _releaseHold(SwarmConversation c) {+ if (c.heldAt == _undecided) c.heldAt = widget.messageId ?? _held.value;+ }++ /// A read came in: the line, if a failed read left it to place; the notice's+ /// message, once a read has brought what to look for it in; and what is+ /// offered of the line, since the list changed.+ void _chatMoved() {+ final c = _conversation;+ if (c == null || !_firstRead) return;+ if (!_lineDecided) _placeLine(c);+ if (!_noticeHandled &&+ c.state == SwarmChatState.loaded &&+ c.error == null) {+ if (widget.messageId case final messageId?) {+ _noticeHandled = true;+ unawaited(_jumpTo(c, messageId));+ }+ }+ _measureLineSoon();}/// The marks the line waits on moved: back, it is placed. Only the chat's@@ -403,15 +443,22 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// it, the chat goes to the line, and what came before the line is read/// while the rest waits until the person goes down to it. The list builds/// only the rows near what is shown, so it jumps near the line by its place- /// until its row is built, as [_reveal] does.- void _openAtLine(SwarmConversation c, String at, int attempt) {+ /// until its row is built, as [_reveal] does. Jump to first unread comes+ /// here at [attempt] 1: what is read does not move.+ void _openAtLine(+ SwarmConversation c,+ String at,+ int attempt, {+ int? landing,+ }) {+ final jump = landing ?? _land();WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted || _conversation != c || _lineAt != at) return;+ if (!mounted || _conversation != c || _lineAt != at) return _landed(jump);final row = _lineKey.currentContext;if (attempt == 0) {if (row != null && _onScreen(row)) {if (c.heldAt == _undecided) c.heldAt = null;- return;+ return _landed(jump);}final place = c.messages.indexWhere((m) => m.id == at);if (place > 0 && c.heldAt == _undecided) {@@ -419,34 +466,106 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>}}if (row != null) {- unawaited(Scrollable.ensureVisible(row, alignment: 1));+ unawaited(+ Scrollable.ensureVisible(+ row,+ alignment: 1,+ ).whenComplete(() => _landed(jump)),+ );return;}final index = _shown.indexWhere((entry) => entry is _LineEntry);- if (!_scroll.hasClients || index < 0 || attempt > 20) return;- final position = _scroll.position;- position.jumpTo(- (position.maxScrollExtent * (index + 1) / _shown.length).clamp(- 0,- position.maxScrollExtent,- ),- );- _openAtLine(c, at, attempt + 1);+ if (!_scroll.hasClients || index < 0 || attempt > 20) {+ return _landed(jump);+ }+ _scroll.position.jumpTo(_offsetNear(index));+ _openAtLine(c, at, attempt + 1, landing: jump);});WidgetsBinding.instance.scheduleFrame();}/// Whether [row]'s top is inside its list: the list runs from the foot, so/// a row drawn there is on screen unless it starts above the list's top.- static bool _onScreen(BuildContext row) {+ static bool _onScreen(BuildContext row) => (_topInList(row) ?? -1) >= 0;++ /// How far [row]'s top is below its list's top; null until both are laid+ /// out.+ static double? _topInList(BuildContext row) {final box = row.findRenderObject(), list = Scrollable.maybeOf(row);final view = list?.context.findRenderObject();- if (box is! RenderBox || view is! RenderBox) return false;- if (!box.hasSize || !view.hasSize) return false;- return box.localToGlobal(Offset.zero).dy >=+ if (box is! RenderBox || view is! RenderBox) return null;+ if (!box.hasSize || !view.hasSize) return null;+ return box.localToGlobal(Offset.zero).dy -view.localToGlobal(Offset.zero).dy;}+ /// Where the list scrolls to bring the entry at [index] of [_shown] near,+ /// by its place: the rows not built have no place of their own yet.+ double _offsetNear(int index) {+ final position = _scroll.position;+ return (position.maxScrollExtent * (index + 1) / _shown.length).clamp(+ 0,+ position.maxScrollExtent,+ );+ }++ /// A jump starts: what is offered stays as it is until it has landed.+ int _land() => _landing = ++_landings;++ /// Jump [landing] is over: the line is measured where the list lays out+ /// next, unless a newer jump has started.+ void _landed(int landing) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || _landing != landing) return;+ _landing = null;+ _measureLine();+ });+ WidgetsBinding.instance.scheduleFrame();+ }++ /// [_measureLine] once this frame is laid out: a scroll or a read may come+ /// in the middle of it.+ void _measureLineSoon() {+ if (_lineAt == null || _lineSeen || _measuring) return;+ _measuring = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _measuring = false;+ if (mounted) _measureLine();+ });+ WidgetsBinding.instance.ensureVisualUpdate();+ }++ /// Offers Jump to first unread while the line is above the view and has not+ /// been seen (Desktop's `_checkUnreadLine`). A line not laid out is told by+ /// its place in the list. A jump still landing passes lines it does not stop+ /// at: what is offered stays as it was until the line is measured where the+ /// jump landed.+ void _measureLine() {+ if (_landing != null) return;+ var offers = false;+ if (_lineAt != null && !_lineSeen && _scroll.hasClients) {+ final position = _scroll.position;+ final row = _lineKey.currentContext;+ final top = row == null ? null : _topInList(row);+ if (top != null) {+ // Less than a point past the top: where the jump to the line puts it.+ if (top >= -1 && top < position.viewportDimension) _lineSeen = true;+ offers = top < -1;+ } else {+ final index = _shown.indexWhere((entry) => entry is _LineEntry);+ offers = index >= 0 && _offsetNear(index) > position.pixels;+ }+ }+ _offersUnread.value = offers;+ }++ /// Takes the person to the New messages line.+ void _jumpToFirstUnread() {+ final c = _conversation, at = _lineAt;+ if (c == null || at == null) return;+ _openAtLine(c, at, 1);+ }+/// Its Swarm is watched while the chat is open and visible, so it is read/// every few seconds only then ([SwarmSession.watch]).void _watch() {@@ -508,6 +627,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>..removeListener(_see);if (_conversation case final c?) {c.composer.removeListener(_drafted);+ c.removeListener(_chatMoved);c.reader.removeListener(_see);c.dispose();}@@ -517,6 +637,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_madeFrom = null;_lineAt = null;_lineDecided = false;+ _lineSeen = false;+ _landing = null;+ _offersUnread.value = false;_ownerUnknown = false;_firstRead = false;_farBack.value = false;@@ -536,6 +659,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_view.dispose();_held.dispose();_farBack.dispose();+ _offersUnread.dispose();_litTimer?.cancel();_text.dispose();_focus.dispose();@@ -592,6 +716,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>void _scrolled() {_nearTop();if (!_scroll.hasClients) return;+ _measureLineSoon();final back = _scroll.offset > _readingBack;if (_unreadLine) {_farBack.value = _scroll.offset > _scroll.position.viewportDimension;@@ -652,15 +777,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>void _send(SwarmConversation c) {_target = null;_attachNote.value = null;- if (_scroll.hasClients && _scroll.offset > 0) {- unawaited(- _scroll.animateTo(- 0,- duration: const Duration(milliseconds: 250),- curve: Curves.easeOut,- ),- );- }+ if (_scroll.hasClients && _scroll.offset > 0) _toFoot();unawaited(_post(c));}@@ -789,6 +906,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// when it is further back — or says why it cannot.Future<void> _jumpTo(SwarmConversation c, String messageId) async {if (_finding) return;+ final landing = _land();setState(() {_decisionTarget = null;_finding = true;@@ -810,7 +928,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>if (!_scroll.hasClients || _scroll.offset <= _readingBack) {c.heldAt = null;}- return;+ return _landed(landing);}}setState(() {@@ -829,9 +947,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>if (!_scroll.hasClients || _scroll.offset <= _readingBack) {c.heldAt = null;}- return;+ return _landed(landing);}- _reveal(c, messageId, 0);+ _reveal(c, messageId, 0, landing: landing);_litTimer?.cancel();setState(() => _lit = messageId);_litTimer = Timer(const Duration(seconds: 2), () {@@ -842,10 +960,17 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// The list builds only the rows near what is shown: it jumps near the/// target by its place in the list until its row is built, then brings it/// to the middle (the desktop's `_revealTarget`).- void _reveal(SwarmConversation c, String messageId, int attempt) {+ void _reveal(+ SwarmConversation c,+ String messageId,+ int attempt, {+ int? landing,+ }) {+ final jump = landing ?? _land();WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted || (_target != messageId && _decisionTarget != messageId)) {- return;+ if (!mounted) return;+ if (_target != messageId && _decisionTarget != messageId) {+ return _landed(jump);}if (_targetKey.currentContext case final row?) {unawaited(@@ -853,7 +978,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>row,alignment: 0.5,duration: const Duration(milliseconds: 250),- ),+ ).whenComplete(() => _landed(jump)),);return;}@@ -863,15 +988,11 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>? entry is _AskEntry && entry.need.decision.id == messageId: entry is _MessageEntry && entry.message.id == messageId,);- if (!_scroll.hasClients || index < 0 || attempt > 20) return;- final position = _scroll.position;- position.jumpTo(- (position.maxScrollExtent * (index + 1) / shown.length).clamp(- 0,- position.maxScrollExtent,- ),- );- _reveal(c, messageId, attempt + 1);+ if (!_scroll.hasClients || index < 0 || attempt > 20) {+ return _landed(jump);+ }+ _scroll.position.jumpTo(_offsetNear(index));+ _reveal(c, messageId, attempt + 1, landing: jump);});WidgetsBinding.instance.scheduleFrame();}@@ -1059,6 +1180,24 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_messages(context, session, c, view, tty),),),+ // At the top of the list, as Jump to latest is at its foot: the+ // two can show at once.+ Positioned(+ left: 0,+ right: 0,+ top: 8,+ child: ListenableBuilder(+ listenable: Listenable.merge([c, _offersUnread]),+ builder: (context, _) =>+ _offersUnread.value &&+ c.state != SwarmChatState.lost &&+ c.stream.isNotEmpty+ ? Center(+ child: SwarmJumpToUnreadPill(onTap: _jumpToFirstUnread),+ )+ : const SizedBox.shrink(),+ ),+ ),Positioned(left: 0,right: 0,@@ -1627,12 +1766,15 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// Back to the foot, where the messages that waited show.void _toFoot() {if (!_scroll.hasClients) return;+ final landing = _land();unawaited(- _scroll.animateTo(- 0,- duration: const Duration(milliseconds: 250),- curve: Curves.easeOut,- ),+ _scroll+ .animateTo(+ 0,+ duration: const Duration(milliseconds: 250),+ curve: Curves.easeOut,+ )+ .whenComplete(() => _landed(landing)),);}@@ -2324,22 +2466,62 @@ class _Day extends StatelessWidget {class SwarmNewPill extends StatelessWidget {const SwarmNewPill({super.key, required this.count, required this.onTap});- static const double _height = 36;-final int count;final VoidCallback onTap;@override- Widget build(BuildContext context) => Semantics(- button: true,+ Widget build(BuildContext context) => _JumpPill(+ key: ValueKey(count == 0 ? 'swarm-jump-latest' : 'swarm-new-pill'),+ icon: LucideIcons.arrowDown,+ text: count == 0 ? 'Jump to latest' : '$count new',label: count == 0? 'Jump to latest': count == 1? '1 new message': '$count new messages',+ onTap: onTap,+ );+}++/// Shown while the New messages line, not yet seen this visit, is above the+/// view: takes the person up to it (Desktop's `SuperTabJumpToUnread`).+class SwarmJumpToUnreadPill extends StatelessWidget {+ const SwarmJumpToUnreadPill({super.key, required this.onTap});++ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => _JumpPill(+ key: const ValueKey('swarm-jump-unread'),+ icon: LucideIcons.arrowUp,+ text: 'Jump to first unread',+ label: 'Jump to first unread',+ onTap: onTap,+ );+}++/// A capsule over the chat that takes the person somewhere in it.+class _JumpPill extends StatelessWidget {+ const _JumpPill({+ super.key,+ required this.icon,+ required this.text,+ required this.label,+ required this.onTap,+ });++ static const double _height = 36;++ final IconData icon;+ final String text, label;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) => Semantics(+ button: true,+ label: label,excludeSemantics: true,child: GestureDetector(- key: ValueKey(count == 0 ? 'swarm-jump-latest' : 'swarm-new-pill'),behavior: HitTestBehavior.opaque,onTap: onTap,// 44 to tap, 36 to see.@@ -2357,14 +2539,18 @@ class SwarmNewPill extends StatelessWidget {child: Row(mainAxisSize: MainAxisSize.min,children: [- const Icon(LucideIcons.arrowDown, size: 16, color: AppInk.onFill),+ Icon(icon, size: 16, color: AppInk.onFill),const SizedBox(width: 6),- Text(- count == 0 ? 'Jump to latest' : '$count new',- style: swarmChatText(- 14,- color: AppInk.onFill,- weight: FontWeight.w600,+ Flexible(+ child: Text(+ text,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 14,+ color: AppInk.onFill,+ weight: FontWeight.w600,+ ),),),],diff --git a/mobile/test/swarm/swarm_jump_unread_shots_test.dart b/mobile/test/swarm/swarm_jump_unread_shots_test.dartnew file mode 100644index 000000000..3736b5bf5--- /dev/null+++ b/mobile/test/swarm/swarm_jump_unread_shots_test.dart@@ -0,0 +1,200 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/theme/color_palette.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Review screenshots of Jump to first unread in a phone chat: alone, with+/// Jump to latest at once, and where a tap lands. At 390 and 320 wide in both+/// phone themes, from made-up data only, to the folder+/// `SWARM_JUMP_UNREAD_SHOTS` names.+final shots = Platform.environment['SWARM_JUMP_UNREAD_SHOTS'];+void main() {+ setUpAll(() async {+ if (shots == null || !Platform.isMacOS) return;+ final sf = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(sf))).load();+ }+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {+ await (FontLoader(family)..addFont(Future.value(mono))).load();+ }+ final manifest =+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;+ for (final entry in manifest.cast<Map<String, dynamic>>()) {+ final loader = FontLoader(entry['family'] as String);+ for (final font in (entry['fonts'] as List).cast<Map>()) {+ loader.addFont(rootBundle.load(font['asset'] as String));+ }+ await loader.load();+ }+ });++ const chat = 'buddy-me';+ const lines = [+ 'The login screen now keeps the email you typed when the code fails.',+ 'Checked it on both themes. The error sits under the field.',+ 'Next I am looking at the retry timer, which resets too early.',+ 'Found it: the timer starts again each time the screen is rebuilt.',+ ];++ Map<String, dynamic> said(int sequence) => {+ 'id': 'msg-$sequence',+ 'conversationId': chat,+ 'text': lines[sequence % lines.length],+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'agent-wren', 'name': 'Wren'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 29, 1, sequence).toIso8601String(),+ };++ FakeSwarm backend() {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ buddyChatData(+ chat,+ agentIds: ['agent-wren'],+ lastMessageSequence: 40,+ ),+ ],+ agents: [buddyData('agent-wren', displayName: 'Wren')],+ derived: {+ 'readMarks': {chat: 5},+ },+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/conversations/$chat/messages'] = (_) => {+ 'messages': [for (var i = 40; i >= 1; i--) said(i)],+ 'next': null,+ };+ return fake;+ }++ testWidgets('the pill alone, with Jump to latest, and where it lands', (+ tester,+ ) async {+ for (final (width, height, top, bottom) in const [+ (390.0, 844.0, 47.0, 34.0),+ (320.0, 568.0, 20.0, 0.0),+ ]) {+ await tester.binding.setSurfaceSize(Size(width, height));+ tester.view.padding = FakeViewPadding(top: top * 3, bottom: bottom * 3);+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {+ final brightness = palette.brightness;+ AppTheme.palette.value = palette;+ AppTheme.brightness.value = brightness;+ final boundary = GlobalKey();+ Future<void> capture(String name) => tester.runAsync(() async {+ final image =+ await (boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 3);+ final png = await image.toByteData(format: ui.ImageByteFormat.png);+ await File(+ '$shots/jump-unread-$name-${width.toInt()}-${brightness.name}.png',+ ).writeAsBytes(png!.buffer.asUint8List());+ image.dispose();+ });++ /// The chat opened from a notice at [messageId].+ Future<SwarmHost> open(String messageId) async {+ final features = ExperimentalFeaturesStore(+ storage: MemoryKeyValueStore(),+ )..value = {PhoneExperiment.swarm};+ final host = SwarmHost(+ accountId: () => me,+ account: ValueNotifier<String?>(me),+ request: backend().request,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ builder: (_, child) =>+ SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ swarmId: tab,+ conversationId: chat,+ messageId: messageId,+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Future<void> close(SwarmHost host) async {+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 30));+ host.dispose();+ }++ final pill = find.byKey(const ValueKey('swarm-jump-unread'));+ final latest = find.byKey(const ValueKey('swarm-jump-latest'));++ // Near the foot: this pill alone.+ var host = await open('msg-39');+ expect(pill, findsOneWidget);+ expect(latest, findsNothing);+ await capture('alone');+ await close(host);++ // Further back: the pair.+ host = await open('msg-20');+ expect(pill, findsOneWidget);+ expect(latest, findsOneWidget);+ await capture('both');++ await tester.tap(pill);+ await tester.pumpAndSettle();+ expect(pill, findsNothing);+ await capture('landed');+ await close(host);+ }+ }+ await tester.binding.setSurfaceSize(null);+ tester.view.resetPadding();+ AppTheme.palette.value = HarnessPalette.graphite;+ AppTheme.brightness.value = Brightness.dark;+ }, skip: shots == null);+}diff --git a/mobile/test/swarm/swarm_jump_unread_test.dart b/mobile/test/swarm/swarm_jump_unread_test.dartnew file mode 100644index 000000000..492b602fb--- /dev/null+++ b/mobile/test/swarm/swarm_jump_unread_test.dart@@ -0,0 +1,704 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/notify/system_notices.dart';+import 'package:harness_mobile/settings/experimental_features.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// Jump to first unread in a phone chat (Desktop's #2273 and #2294): shown+/// only while the New messages line is above the view and has not been seen,+/// a tap lands on the line, and it holds steady while any jump lands.+void main() {+ const chat = 'buddy-me';+ const messages = '/api/super-tabs/$tab/conversations/$chat/messages';+ final line = find.byKey(const ValueKey('swarm-new-messages-line'));+ final pill = find.byKey(const ValueKey('swarm-jump-unread'));+ final latest = find.byKey(const ValueKey('swarm-jump-latest'));+ final list = find.byKey(const ValueKey('swarm-messages'));++ Map<String, dynamic> said(+ int sequence, {+ String? replyTo,+ String conversation = chat,+ }) => {+ 'id': 'msg-$sequence',+ 'conversationId': conversation,+ 'text': 'Update $sequence.',+ 'sequence': sequence,+ 'replyTo': ?replyTo,+ 'author': {'kind': 'agent', 'id': 'agent-wren', 'name': 'agent-wren'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 10, 29, 1, sequence).toIso8601String(),+ };++ List<Map<String, dynamic>> forty() => [for (var i = 1; i <= 40; i++) said(i)];++ /// The person's Buddy chat holding [page], read through [mark] on some+ /// device; [older] pages come before it.+ FakeSwarm backend(+ List<Map<String, dynamic>> page, {+ required int mark,+ bool older = false,+ }) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ number: 7,+ lastMessageSequence: 40,+ ),+ buddyChatData(+ chat,+ agentIds: ['agent-wren'],+ lastMessageSequence: page.last['sequence'] as int,+ ),+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ buddyData('agent-wren', displayName: 'Wren'),+ ],+ derived: {+ 'readMarks': {chat: mark, 'g1': 40},+ },+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': older+ ? {'sequence': page.first['sequence'], 'id': 'msg-older'}+ : null,+ };+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {+ 'messages': [for (var i = 40; i >= 1; i--) said(i, conversation: 'g1')],+ 'next': null,+ };+ return fake;+ }++ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ bool settle = true,+ String? messageId,+ String conversation = chat,+ ValueNotifier<String?>? signedIn,+ }) async {+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = signedIn ?? ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ upload: refuseSwarmUpload,+ notices: SilentSystemNotices(),+ features: features,+ readMarks: MemoryKeyValueStore(),+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ swarmId: tab,+ conversationId: conversation,+ messageId: messageId,+ ),+ ),+ );+ if (settle) {+ await tester.pumpAndSettle();+ } else {+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ }+ return host;+ }++ bool onScreen(WidgetTester tester, Finder f) {+ if (f.evaluate().isEmpty) return false;+ final view = tester.getRect(list);+ final row = tester.getRect(f);+ return row.top >= view.top && row.bottom <= view.bottom;+ }++ /// The read marks sent for the chat, in order.+ List<Object?> marksSent(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' &&+ call.path == '/api/super-tabs/$tab/conversations/$chat/read')+ call.body?['sequence'],+ ];++ /// Whether the pill showed in each of [frames] frames from now.+ Future<List<bool>> framesOf(WidgetTester tester, {int frames = 40}) async {+ final shown = <bool>[];+ for (var i = 0; i < frames; i++) {+ await tester.pump(const Duration(milliseconds: 16));+ shown.add(pill.evaluate().isNotEmpty);+ }+ return shown;+ }++ /// The chat opened from a notice at a message well below the line.+ Future<SwarmHost> openBelowLine(+ WidgetTester tester,+ FakeSwarm fake, {+ ValueNotifier<String?>? signedIn,+ }) async {+ final host = await pump(+ tester,+ fake,+ messageId: 'msg-25',+ signedIn: signedIn,+ );+ expect(onScreen(tester, find.text('Update 25.')), isTrue);+ expect(onScreen(tester, line), isFalse);+ return host;+ }++ const refused = SuperTabFailure(+ 'FORBIDDEN',+ 'You cannot read this Swarm.',+ statusCode: 403,+ );++ group('when it shows', () {+ testWidgets('opened at a message below the line, it says so in words at '+ 'the top of the list, with a full touch target', (tester) async {+ await openBelowLine(tester, backend(forty(), mark: 5));++ expect(pill, findsOneWidget);+ expect(find.text('Jump to first unread'), findsOneWidget);+ expect(tester.getSemantics(pill).label, 'Jump to first unread');+ expect(tester.getSize(pill).height, greaterThanOrEqualTo(minTouchTarget));+ final view = tester.getRect(list);+ final rect = tester.getRect(pill);+ expect(rect.top - view.top, lessThan(24));+ expect(rect.center.dx, moreOrLessEquals(view.center.dx));+ });++ testWidgets('opening at the line never shows it, on the way or after', (+ tester,+ ) async {+ await pump(tester, backend(forty(), mark: 5), settle: false);+ expect(await framesOf(tester), everyElement(isFalse));+ await tester.pumpAndSettle();++ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);+ });++ testWidgets('a line on screen as the chat opens counts as seen: pushed '+ 'above by what comes later, it is not offered', (tester) async {+ final fake = backend(forty(), mark: 38);+ final host = await pump(tester, fake);+ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);++ fake.routes[messages] = (_) => {+ 'messages': [for (var i = 70; i >= 1; i--) said(i)],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ groups: [+ part(+ chat,+ 9,+ buddyChatData(+ chat,+ agentIds: ['agent-wren'],+ lastMessageSequence: 70,+ ),+ ),+ ],+ );+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 70.')), isTrue);+ expect(onScreen(tester, line), isFalse);+ expect(pill, findsNothing);+ });++ testWidgets('a chat with no line has none, however far back', (+ tester,+ ) async {+ await pump(tester, backend(forty(), mark: 40));+ expect(line, findsNothing);++ await tester.drag(list, const Offset(0, 1500));+ await tester.pumpAndSettle();+ expect(latest, findsOneWidget);+ expect(pill, findsNothing);+ });++ testWidgets('a line below the view is not offered', (tester) async {+ await pump(tester, backend(forty(), mark: 30), messageId: 'msg-5');++ expect(onScreen(tester, find.text('Update 5.')), isTrue);+ expect(onScreen(tester, line), isFalse);+ expect(pill, findsNothing);+ });++ testWidgets('Jump to latest past a line never seen does not count as '+ 'seeing it: it is then above, and offered', (tester) async {+ await pump(tester, backend(forty(), mark: 30), messageId: 'msg-20');+ expect(pill, findsNothing);+ expect(latest, findsOneWidget);++ await tester.tap(latest);+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 40.')), isTrue);+ expect(pill, findsOneWidget);+ });++ testWidgets('a work chat has none', (tester) async {+ await pump(+ tester,+ backend(forty(), mark: 40),+ conversation: 'g1',+ messageId: 'msg-20',+ );+ expect(onScreen(tester, find.text('Update 20.')), isTrue);+ expect(pill, findsNothing);+ });+ });++ group('a tap', () {+ testWidgets('lands on the line, and it goes for the rest of the visit', (+ tester,+ ) async {+ await openBelowLine(tester, backend(forty(), mark: 5));++ await tester.tap(pill);+ await tester.pumpAndSettle();++ expect(onScreen(tester, line), isTrue);+ expect(onScreen(tester, find.text('Update 6.')), isTrue);+ expect(pill, findsNothing);++ await tester.fling(list, const Offset(0, -6000), 4000);+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.text('Update 40.')), isTrue);+ expect(pill, findsNothing, reason: 'the line has been seen');+ });++ testWidgets('moves nothing that was read: no mark goes past what the '+ 'chat had shown', (tester) async {+ final fake = backend(forty(), mark: 5);+ await openBelowLine(tester, fake);++ await tester.tap(pill);+ await tester.pumpAndSettle();+ await tester.pump(const Duration(seconds: 5));++ expect(marksSent(fake), everyElement(lessThanOrEqualTo(25)));+ });++ testWidgets('lands from the foot too, far above any row built', (+ tester,+ ) async {+ await pump(tester, backend(forty(), mark: 5), messageId: 'msg-25');+ await tester.fling(list, const Offset(0, -6000), 4000);+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.text('Update 40.')), isTrue);+ expect(pill, findsOneWidget);++ await tester.tap(pill);+ await tester.pumpAndSettle();++ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);+ });+ });++ group('while a jump lands', () {+ testWidgets('its own tap keeps it steady until the line has landed: it '+ 'goes once, never back', (tester) async {+ await openBelowLine(tester, backend(forty(), mark: 5));++ await tester.tap(pill);+ final shown = await framesOf(tester);+ expect(shown.first, isTrue, reason: 'still there as the jump starts');+ expect(shown.last, isFalse);+ expect(+ shown.skipWhile((s) => s),+ everyElement(isFalse),+ reason: 'no flicker: $shown',+ );+ });++ testWidgets('a quote followed in a chat showing it keeps it steady in '+ 'every frame, and after', (tester) async {+ final page = forty();+ page[24] = said(25, replyTo: 'msg-12');+ await openBelowLine(tester, backend(page, mark: 5));+ expect(pill, findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('swarm-quote-msg-25')));+ final shown = await framesOf(tester);++ expect(shown, everyElement(isTrue));+ await tester.pumpAndSettle();+ expect(onScreen(tester, find.text('Update 12.')), isTrue);+ expect(pill, findsOneWidget);+ });++ testWidgets('a quote passing the line on its way does not count as seeing '+ 'it', (tester) async {+ final page = forty();+ page[24] = said(25, replyTo: 'msg-2');+ await openBelowLine(tester, backend(page, mark: 10));+ expect(pill, findsOneWidget);++ await tester.tap(find.byKey(const ValueKey('swarm-quote-msg-25')));+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 2.')), isTrue);+ expect(onScreen(tester, line), isFalse);+ expect(pill, findsNothing, reason: 'the line is below now');++ // Back at the foot the line, never seen, is above again.+ await tester.tap(latest);+ await tester.pumpAndSettle();+ expect(pill, findsOneWidget);+ });++ testWidgets('a quote that cannot be read back ends the landing: no '+ 'Finding left, and the line is still measured', (tester) async {+ final fake = backend(forty(), mark: 12, older: true);+ final page = forty();+ page[24] = said(25, replyTo: 'msg-gone');+ final first = fake.routes[messages]!;+ fake.routes[messages] = (body) => {+ ...(first(body)! as Map<String, dynamic>),+ 'messages': page.reversed.toList(),+ };+ await pump(tester, fake, messageId: 'msg-25');+ expect(pill, findsOneWidget);++ fake.routes[messages] = (_) =>+ throw const SuperTabFailure('INTERNAL', 'Messages are down.');+ await tester.tap(find.byKey(const ValueKey('swarm-quote-msg-25')));+ await tester.pumpAndSettle();++ expect(find.textContaining('Finding the original'), findsNothing);+ expect(pill, findsOneWidget);++ // No landing left open: read up to the line, and it is seen.+ fake.routes[messages] = first;+ var steps = 0;+ while (!onScreen(tester, line) && steps++ < 40) {+ await tester.drag(list, const Offset(0, 120));+ await tester.pumpAndSettle();+ }+ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);+ });+ });++ group('seen by reading', () {+ testWidgets('scrolled up to, it goes and does not come back', (+ tester,+ ) async {+ await openBelowLine(tester, backend(forty(), mark: 12));+ expect(pill, findsOneWidget);++ var steps = 0;+ while (!onScreen(tester, line) && steps++ < 40) {+ await tester.drag(list, const Offset(0, 120));+ await tester.pumpAndSettle();+ }+ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);++ await tester.fling(list, const Offset(0, -6000), 4000);+ await tester.pumpAndSettle();+ expect(onScreen(tester, line), isFalse);+ expect(pill, findsNothing);+ });+ });++ group('its privacy edges', () {+ testWidgets('access taken away while it shows: it goes with the messages', (+ tester,+ ) async {+ final fake = backend(forty(), mark: 5);+ final host = await pump(tester, fake, messageId: 'msg-25');+ expect(pill, findsOneWidget);++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ unawaited(host.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();++ expect(pill, findsNothing);+ expect(line, findsNothing);+ expect(find.text('Update 25.'), findsNothing);+ });++ testWidgets('access taken away as a tap lands: nothing comes back', (+ tester,+ ) async {+ final fake = backend(forty(), mark: 5);+ final host = await pump(tester, fake, messageId: 'msg-25');++ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;+ await tester.tap(pill);+ unawaited(host.session!.inbox.reader(tab)!.refresh());+ await tester.pumpAndSettle();++ expect(pill, findsNothing);+ expect(line, findsNothing);+ expect(find.text('Update 6.'), findsNothing);+ });++ testWidgets('signing out takes it away, and a new session starts with '+ 'nothing kept of the old one', (tester) async {+ final signedIn = ValueNotifier<String?>(me);+ final fake = backend(forty(), mark: 40);+ final page = forty();+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ buddyChatData(+ chat,+ agentIds: ['agent-wren'],+ lastMessageSequence: 40,+ ),+ ],+ agents: [buddyData('agent-wren', displayName: 'Wren')],+ derived: {+ 'readMarks': {chat: signedIn.value == me ? 5 : 40},+ },+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes[messages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': null,+ };+ final host = await pump(+ tester,+ fake,+ messageId: 'msg-25',+ signedIn: signedIn,+ );+ expect(pill, findsOneWidget);++ signedIn.value = null;+ await tester.pump();+ expect(pill, findsNothing);++ // Back as someone whose mark is at the end: no line, so no pill.+ host.foreground = true;+ signedIn.value = 'person-other';+ await tester.pumpAndSettle();+ host.foreground = false;+ expect(pill, findsNothing);+ });++ testWidgets('a read left behind by a sign-out does not offer it in the '+ 'chat that replaced it', (tester) async {+ final fake = backend(forty(), mark: 5);+ final asked = <Completer<Object?>>[];+ final page = fake.routes[messages]!;+ fake.routes[messages] = (body) {+ asked.add(Completer<Object?>());+ return asked.last.future;+ };+ final signedIn = ValueNotifier<String?>(me);+ final host = await pump(+ tester,+ fake,+ settle: false,+ messageId: 'msg-25',+ signedIn: signedIn,+ );+ expect(asked, hasLength(1));++ signedIn.value = null;+ await tester.pump();+ host.foreground = true;+ signedIn.value = me;+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ host.foreground = false;+ expect(asked, hasLength(2));++ asked[0].complete(page(null));+ await tester.pump(const Duration(milliseconds: 50));+ expect(pill, findsNothing, reason: "the old chat's read is dropped");+ expect(line, findsNothing);++ asked[1].complete(page(null));+ await tester.pumpAndSettle();+ expect(pill, findsOneWidget, reason: "the new chat's own read");+ });+ });++ group('a first read that fails, then recovers', () {+ testWidgets('still places the line, with nothing read meanwhile, and the '+ 'chat opens at it', (tester) async {+ final fake = backend(forty(), mark: 5);+ final answer = fake.routes[messages]!;+ fake.routes[messages] = (_) =>+ throw const SuperTabFailure('INTERNAL', 'Messages are down.');+ final host = await pump(tester, fake);+ expect(find.text('Messages are down.'), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-chat-skeleton')), findsNothing);+ expect(line, findsNothing);++ fake.routes[messages] = answer;+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(onScreen(tester, line), isTrue, reason: 'opened at the line');+ expect(pill, findsNothing);+ expect(+ marksSent(fake).where((s) => (s! as int) > 5),+ isEmpty,+ reason: 'nothing past the line is read',+ );+ });++ testWidgets('still offers the way back in a chat a notice opened', (+ tester,+ ) async {+ final fake = backend(forty(), mark: 5);+ final answer = fake.routes[messages]!;+ fake.routes[messages] = (_) =>+ throw const SuperTabFailure('INTERNAL', 'Messages are down.');+ final host = await pump(tester, fake, messageId: 'msg-25');+ expect(pill, findsNothing);++ fake.routes[messages] = answer;+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(onScreen(tester, find.text('Update 25.')), isTrue);+ expect(pill, findsOneWidget);+ await tester.tap(pill);+ await tester.pumpAndSettle();+ expect(onScreen(tester, line), isTrue);+ expect(pill, findsNothing);+ });++ testWidgets('a refused first read that comes back places it too', (+ tester,+ ) async {+ final fake = backend(forty(), mark: 5);+ final answer = fake.routes[messages]!;+ fake.routes[messages] = (_) => throw refused;+ final host = await pump(tester, fake);+ expect(line, findsNothing);+ expect(marksSent(fake), isEmpty);++ fake.routes[messages] = answer;+ await host.session!.inbox.reader(tab)!.refresh();+ await tester.pumpAndSettle();++ expect(find.text('You cannot read this Swarm.'), findsNothing);+ expect(onScreen(tester, line), isTrue);+ });+ });++ group('with Jump to latest, on a small phone', () {+ /// Both pills up on a 320-wide phone, [keyboard] points of it covered.+ Future<void> bothShowing(WidgetTester tester, {double keyboard = 0}) async {+ await tester.binding.setSurfaceSize(const Size(320, 568));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ tester.view.viewInsets = FakeViewPadding(bottom: keyboard * 3);+ addTearDown(tester.view.resetViewInsets);+ await openBelowLine(tester, backend(forty(), mark: 5));+ expect(pill, findsOneWidget);+ expect(latest, findsOneWidget);+ }++ Future<void> expectClear(WidgetTester tester) async {+ final top = tester.getRect(pill);+ final bottom = tester.getRect(latest);+ final view = tester.getRect(list);+ final composer = tester.getRect(find.byType(TextField));+ expect(top.overlaps(bottom), isFalse, reason: '$top over $bottom');+ expect(bottom.bottom, lessThanOrEqualTo(composer.top));+ expect(top.bottom, lessThanOrEqualTo(composer.top));+ expect(top.left, greaterThanOrEqualTo(view.left));+ expect(top.right, lessThanOrEqualTo(view.right));+ expect(onScreen(tester, line), isFalse, reason: 'above the view');+ expect(tester.takeException(), isNull);+ }++ testWidgets('neither overlaps the other, the composer or the line', (+ tester,+ ) async {+ await bothShowing(tester);+ await expectClear(tester);+ });++ testWidgets('nor with the keyboard up', (tester) async {+ await bothShowing(tester, keyboard: 216);+ await expectClear(tester);+ });++ testWidgets('the pair look alike: the same capsule and the same type', (+ tester,+ ) async {+ await bothShowing(tester);+ Container capsule(Finder of) => tester.widget<Container>(+ find.descendant(of: of, matching: find.byType(Container)).first,+ );+ Text words(Finder of) => tester.widget<Text>(+ find.descendant(of: of, matching: find.byType(Text)),+ );+ expect(capsule(pill).decoration, capsule(latest).decoration);+ expect(words(pill).style, words(latest).style);+ expect(tester.getSize(pill).height, tester.getSize(latest).height);+ });++ testWidgets('its words fit at twice the text size, or end short', (+ tester,+ ) async {+ tester.platformDispatcher.textScaleFactorTestValue = 2;+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);+ await bothShowing(tester);+ expect(tester.takeException(), isNull);+ final rect = tester.getRect(pill);+ expect(rect.right, lessThanOrEqualTo(320));+ expect(rect.left, greaterThanOrEqualTo(0));+ });+ });+}