Skip to content

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.

Desktop Swarm chat: a reader scrolled up keeps their place when more than a page arrives (#2019)

0xken1599116baeafae
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 180afd581..6c3555b13 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -680,6 +680,52 @@ class SuperTabController extends ChangeNotifier {
bool hasOlder(String id) => _before[id] != null;
+ /// Conversations whose reader is scrolled up ([readingBack]).
+ final _readingBack = <String>{};
+
+ /// Conversations with messages after the newest held that no read has
+ /// brought yet ([hasNewer]).
+ final _newer = <String>{};
+
+ /// Conversations whose next read takes the latest page whole
+ /// ([showLatest]).
+ final _latestWanted = <String>{};
+
+ /// How many pages joined below the rows of a reader scrolled up, by
+ /// conversation.
+ final _pagesBelow = <String, int>{};
+
+ /// At most this many pages join below a reader scrolled up: past them the
+ /// rest waits for [showLatest], so a long burst is not all held.
+ static const _pagesBelowReader = 3;
+
+ /// Forgets reading back in [id], or in every conversation.
+ void _forgetNewer([String? id]) {
+ for (final kept in [_readingBack, _newer, _latestWanted]) {
+ id == null ? kept.clear() : kept.remove(id);
+ }
+ id == null ? _pagesBelow.clear() : _pagesBelow.remove(id);
+ }
+
+ /// The reader of [id] scrolled up, or back to its end. While they read
+ /// back, a read that finds more than a page new keeps the rows they are
+ /// reading and adds the next page below; [showLatest] reads the rest.
+ void readingBack(String id, bool reading) =>
+ reading ? _readingBack.add(id) : _readingBack.remove(id);
+
+ /// Whether more messages came after the newest held than reads brought.
+ bool hasNewer(String id) => _newer.contains(id);
+
+ /// Brings [id]'s newest messages: when more are waiting than reads
+ /// brought, the latest page replaces what is held.
+ Future<void> showLatest(String id) async {
+ _readingBack.remove(id);
+ await _reading[(id, false)];
+ if (_disposed || !_newer.contains(id)) return;
+ _latestWanted.add(id);
+ await _readMessages(id);
+ }
+
/// Each conversation's reaction counter as its last page said it.
final _reactionSeq = <String, int>{};
int _loadedMessageSequence(String id) =>
@@ -880,6 +926,7 @@ class SuperTabController extends ChangeNotifier {
snapshot = null;
_parts = null;
_messages.clear();
+ _forgetNewer();
_quoted.clear();
_quoting.clear();
_sent.clear();
@@ -1693,7 +1740,7 @@ class SuperTabController extends ChangeNotifier {
}
// A saved page may be stale in its receipts as well as short of new
// messages: the first read after it takes the latest page whole.
- if (_showingSaved) return '';
+ if (_showingSaved || _latestWanted.contains(id)) return '';
final tail = _messages[id]?.lastOrNull?.sequence;
return tail != null ? '?after=$tail' : '';
}
@@ -1738,6 +1785,7 @@ class SuperTabController extends ChangeNotifier {
snapshot = null;
_parts = null;
_messages.clear();
+ _forgetNewer();
_quoted.clear();
_quoting.clear();
_poll?.cancel();
@@ -1782,6 +1830,7 @@ class SuperTabController extends ChangeNotifier {
? known.last.sequence
: null;
final query = _query(id, older: older);
+ final latest = !older && _latestWanted.remove(id);
final from = _before[id];
final first = early != null && early.query == query ? early.page : null;
var answer = first != null
@@ -1797,10 +1846,28 @@ class SuperTabController extends ChangeNotifier {
final reactionSeq = older ? null : answer['reactionSeq'];
// More than a page arrived after the newest held (back from another
// conversation, or from sleep): the page after it would show messages
- // from hours ago as the newest. The latest page replaces what is held.
+ // from hours ago as the newest. The latest page replaces what is held,
+ // unless the reader is scrolled up: their rows stay, the page joins
+ // below them, and the rest waits for [showLatest].
final skipped = query.startsWith('?after=') && answer['next'] != null;
- if (!_disposed && skipped) {
+ final keepPlace = skipped && _readingBack.contains(id);
+ final full = keepPlace && (_pagesBelow[id] ?? 0) >= _pagesBelowReader;
+ if (!_disposed && skipped && !keepPlace) {
answer = await request('GET', _messagesPath(id));
+ } else if (!_disposed && keepPlace) {
+ // A changed reaction refreshes the page ending at the newest held:
+ // the latest page, under rows read back, would leave a gap.
+ final shown = reacted
+ ? (await request(
+ 'GET',
+ '${_messagesPath(id)}?before=${tail! + 1}',
+ ))['messages']
+ as List
+ : const [];
+ answer = {
+ ...answer,
+ 'messages': [...shown, if (!full) ...answer['messages'] as List],
+ };
} else if (!_disposed &&
!older &&
(!light || reacted) &&
@@ -1843,7 +1910,8 @@ class SuperTabController extends ChangeNotifier {
}
// The first read over a saved page replaces it: merged, the saved
// page would leave a gap when more than a page arrived since.
- final replacing = (_showingSaved || skipped) && !older;
+ final replacing =
+ (_showingSaved || latest || (skipped && !keepPlace)) && !older;
if (replacing) _rows.remove(id);
_keepRows(id, answer['messages'] as List);
final combined = {
@@ -1905,6 +1973,13 @@ class SuperTabController extends ChangeNotifier {
// An adapting read that found nothing new changes nothing on screen.
final same = _policy.adapts && _sameMessages(_messages[id], next);
_messages[id] = next;
+ if (keepPlace) {
+ _newer.add(id);
+ if (!full) _pagesBelow[id] = (_pagesBelow[id] ?? 0) + 1;
+ } else if (!older) {
+ _newer.remove(id);
+ _pagesBelow.remove(id);
+ }
_dropShownSends(id);
if (reactionSeq is int) _reactionSeq[id] = reactionSeq;
if (older || replacing || !_before.containsKey(id)) {
@@ -1922,6 +1997,7 @@ class SuperTabController extends ChangeNotifier {
if (failure is SuperTabFailure &&
const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
_messages.remove(id);
+ _forgetNewer(id);
_quoted.remove(id);
_quoting.remove(id);
unawaited(refresh());
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 21b782878..195d4adf7 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -370,14 +370,28 @@ class _SuperTabViewState extends State<SuperTabView>
scroll.position.extentAfter >= 40) {
return;
}
- _following[id] = true;
+ _follow(id, true);
if (_newAfter.containsKey(id)) setState(() => _newAfter.remove(id));
c.markRead(id, through: sequence);
}
+ /// Whether [id]'s list follows its end; the controller keeps a reader's
+ /// rows while they read back.
+ void _follow(String id, bool following) {
+ _following[id] = following;
+ c.readingBack(id, !following);
+ }
+
void _jumpToLatest() {
- _followEnd(c.selectedId);
+ final id = c.selectedId;
_focus.requestFocus();
+ if (!c.hasNewer(id)) return _followEnd(id);
+ // More are waiting than were read: the latest page first, then its end.
+ unawaited(
+ c.showLatest(id).then((_) {
+ if (mounted && c.selectedId == id) _followEnd(id);
+ }),
+ );
}
@override
@@ -1139,11 +1153,12 @@ class _SuperTabViewState extends State<SuperTabView>
Future<void> _openMention(SuperTabMention mention) async {
final id = mention.conversationId;
if (c.snapshot?.conversation(id) == null) return;
- SuperTabMessage? held() => c
- .messages(id)
- .where((m) => m.id == mention.messageId)
- .firstOrNull;
+ SuperTabMessage? held() =>
+ c.messages(id).where((m) => m.id == mention.messageId).firstOrNull;
var message = held();
+ // The tag is what to see, not the rows read back: the first read goes up
+ // to the latest, never only a few pages below them.
+ if (message == null) c.readingBack(id, false);
// Up to 50 pages (5,000 messages). A tag newer than what was read earlier
// is after it, so the first read is up to the latest; the rest go back.
for (var page = 0; message == null && page < 50; page++) {
@@ -1174,7 +1189,7 @@ class _SuperTabViewState extends State<SuperTabView>
// Stop following the end: the tagged message is what to see.
_scrollRequest++;
_jumpingToEnd = false;
- _following[id] = false;
+ _follow(id, false);
});
_revealTarget(id, 0);
_focus.requestFocus();
@@ -1291,7 +1306,7 @@ class _SuperTabViewState extends State<SuperTabView>
// Stop following the end: the original is what to see.
_scrollRequest++;
_jumpingToEnd = false;
- _following[id] = false;
+ _follow(id, false);
});
_revealTarget(
id,
@@ -2172,6 +2187,8 @@ class _SuperTabViewState extends State<SuperTabView>
final newCount = newAfter == null
? 0
: messages.where((message) => message.sequence > newAfter).length;
+ // More came than were read: the count is a floor.
+ final moreNew = c.hasNewer(c.selectedId);
final reply = _replies[c.selectedId];
final outgoing = c.outgoing(c.selectedId);
// A failed message says so in its own row, with what can be done.
@@ -2246,7 +2263,7 @@ class _SuperTabViewState extends State<SuperTabView>
if (_jumpingToEnd) return false;
final id = c.selectedId;
final atEnd = event.metrics.extentAfter < 40;
- _following[id] = atEnd;
+ _follow(id, atEnd);
// Once the scroll ends, so keeping the place never
// cuts a drag short.
if (event is ScrollEndNotification) {
@@ -2410,7 +2427,9 @@ class _SuperTabViewState extends State<SuperTabView>
size: 16,
),
label: Text(
- '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
+ moreNew
+ ? '$newCount+ new messages'
+ : '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
),
),
],
diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dart
index 89457c285..36a527e07 100644
--- a/desktop/test/super_tab_chat_test.dart
+++ b/desktop/test/super_tab_chat_test.dart
@@ -613,6 +613,52 @@ void main() {
},
);
+ testWidgets(
+ 'more than a page arriving while scrolled up keeps the place, and the '
+ 'jump reads the newest',
+ (tester) async {
+ final server = ConversationServer()..messagePage = 20;
+ for (var i = 1; i <= 40; i++) {
+ server.append(
+ 'Agent update $i: checking the offline queue and reconnect behavior.',
+ );
+ }
+ final c = await show(tester, server);
+ ScrollController scroll() => tester
+ .widget<ScrollView>(
+ find.byKey(const PageStorageKey('super-messages-tab-lead')),
+ )
+ .controller!;
+ scroll().jumpTo(0);
+ await tester.pumpAndSettle();
+ final reading = scroll().offset;
+ for (var i = 41; i <= 90; i++) {
+ server.append('Agent update $i: still checking.');
+ }
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(scroll().offset, reading);
+ expect(
+ find.text(
+ 'Agent update 21: checking the offline queue and reconnect behavior.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('20+ new messages'), findsOneWidget);
+
+ await tester.tap(find.byKey(const ValueKey('super-new-messages')));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Agent update 90: still checking.'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-new-messages')), findsNothing);
+ expect(scroll().position.extentAfter, lessThan(40));
+ expect(c.hasNewer('lead'), isFalse);
+ expect(c.unread(c.selected!), isFalse);
+ expect(tester.takeException(), isNull);
+ await closeReadView(tester, c);
+ },
+ );
+
testWidgets(
'revocation removes the quoted original as well as the transcript',
(tester) async {
diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dart
index 54b87ca9a..c4f9e6a95 100644
--- a/desktop/test/super_tab_mentions_test.dart
+++ b/desktop/test/super_tab_mentions_test.dart
@@ -566,6 +566,41 @@ void main() {
);
});
+ testWidgets('a tag far past a reader scrolled up opens at its message', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ server.state['conversations'] = [
+ ...server.state['conversations'] as List,
+ conversationFixture('group', 'Release'),
+ ];
+ for (var i = 1; i <= 100; i++) {
+ server.append('Note $i', conversationId: 'group');
+ }
+ final c = await showView(tester, server);
+ await c.loadMessages('group');
+ // The reader had scrolled up there, then 600 arrived: more than the
+ // pages that join below them.
+ c.readingBack('group', true);
+ for (var i = 101; i <= 700; i++) {
+ server.append('Note $i', conversationId: 'group');
+ }
+ server.tag('message-650', conversationId: 'group', text: 'Note 650');
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('This message is no longer in the conversation.'),
+ findsNothing,
+ );
+ expect(c.selectedId, 'group');
+ expect(
+ find.byKey(const ValueKey('super-message-message-650')).hitTestable(),
+ findsOneWidget,
+ );
+ });
+
testWidgets('opening a tag shows its message with the reply box on it', (
tester,
) async {
diff --git a/desktop/test/super_tab_message_paging_test.dart b/desktop/test/super_tab_message_paging_test.dart
index 6c9868863..99ae260ae 100644
--- a/desktop/test/super_tab_message_paging_test.dart
+++ b/desktop/test/super_tab_message_paging_test.dart
@@ -176,6 +176,153 @@ void main() {
expect(c.hasOlder('lead'), isTrue);
});
+ test('a reader scrolled up keeps their rows when more than a page arrives, '
+ 'and the jump to the newest reads the latest page', () async {
+ final server = ConversationServer();
+ for (var i = 1; i <= 100; i++) {
+ server.append('lead $i');
+ }
+ final c = server.controller();
+ await c.refresh();
+ c.readingBack('lead', true);
+ for (var i = 101; i <= 700; i++) {
+ server.append('lead $i');
+ }
+
+ await c.loadMessages('lead');
+
+ var shown = c.messages('lead').map((m) => m.sequence).toList();
+ expect(shown, List.generate(200, (i) => i + 1));
+ expect(c.hasNewer('lead'), isTrue);
+
+ await c.showLatest('lead');
+
+ shown = c.messages('lead').map((m) => m.sequence).toList();
+ expect(shown, List.generate(100, (i) => i + 601));
+ expect(c.hasNewer('lead'), isFalse);
+ expect(c.hasOlder('lead'), isTrue);
+ });
+
+ test('the next page read while scrolled up that reaches the end leaves '
+ 'nothing newer', () async {
+ final server = ConversationServer()..messagePage = 2;
+ for (final text in ['one', 'two']) {
+ server.append(text);
+ }
+ final c = server.controller();
+ await c.refresh();
+ c.readingBack('lead', true);
+ for (final text in ['three', 'four', 'five']) {
+ server.append(text);
+ }
+ await c.loadMessages('lead');
+ expect(c.hasNewer('lead'), isTrue);
+
+ await c.loadMessages('lead');
+
+ expect(c.messages('lead').map((m) => m.text), [
+ 'one',
+ 'two',
+ 'three',
+ 'four',
+ 'five',
+ ]);
+ expect(c.hasNewer('lead'), isFalse);
+ });
+
+ test('a reaction changing in the same poll as a burst while scrolled up '
+ 'leaves no gap', () async {
+ final server = ConversationServer();
+ for (var i = 1; i <= 100; i++) {
+ server.append('lead $i');
+ }
+ final c = server.controller();
+ await c.refresh();
+ c.readingBack('lead', true);
+ for (var i = 101; i <= 700; i++) {
+ server.append('lead $i');
+ }
+ // Someone reacts to a row the reader is on, in the same poll.
+ server.messages[49]['reactions'] = [
+ {
+ 'emoji': 'thumbs_up',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': 'peer'},
+ ],
+ },
+ ];
+ final group = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'lead');
+ group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
+
+ await c.loadMessages('lead');
+
+ final shown = c.messages('lead').map((m) => m.sequence).toList();
+ expect(shown, List.generate(200, (i) => i + 1));
+ expect(
+ c
+ .messages('lead')
+ .firstWhere((m) => m.sequence == 50)
+ .reactions
+ .single
+ .emoji
+ .key,
+ 'thumbs_up',
+ );
+ expect(c.hasNewer('lead'), isTrue);
+ });
+
+ test('pages stop joining below a reader scrolled up after a few, and the '
+ 'jump still reads the latest', () async {
+ final server = ConversationServer()..messagePage = 2;
+ for (final text in ['one', 'two']) {
+ server.append(text);
+ }
+ final c = server.controller();
+ await c.refresh();
+ c.readingBack('lead', true);
+ for (var i = 3; i <= 40; i++) {
+ server.append('message $i');
+ }
+
+ for (var poll = 0; poll < 10; poll++) {
+ await c.loadMessages('lead');
+ }
+
+ // The two held, and three pages of two joined below them.
+ expect(
+ c.messages('lead').map((m) => m.sequence),
+ List.generate(8, (i) => i + 1),
+ );
+ expect(c.hasNewer('lead'), isTrue);
+
+ await c.showLatest('lead');
+
+ expect(c.messages('lead').map((m) => m.sequence), [39, 40]);
+ expect(c.hasNewer('lead'), isFalse);
+ });
+
+ test('access removed forgets that newer messages were waiting', () async {
+ final server = ConversationServer()..messagePage = 2;
+ for (final text in ['one', 'two']) {
+ server.append(text);
+ }
+ final c = server.controller();
+ await c.refresh();
+ c.readingBack('lead', true);
+ for (final text in ['three', 'four', 'five']) {
+ server.append(text);
+ }
+ await c.loadMessages('lead');
+ expect(c.hasNewer('lead'), isTrue);
+
+ c.revokeAccess('Access removed.');
+
+ expect(c.hasNewer('lead'), isFalse);
+ });
+
test('a new message is read after the newest one', () async {
final server = ConversationServer()..append('one');
final c = server.controller();