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.

Swarm chat: click a reply's quote to jump to the original (#1775)

0xken1580cf81994b15
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 709111bce..249b4875d 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -237,6 +237,11 @@ class SuperTabController extends ChangeNotifier {
int _uploadRun = 0;
final _messages = <String, List<SuperTabMessage>>{};
+ /// Originals of replies quoted from outside the pages read, one message
+ /// each, never part of the list: null when it is gone. Asked for once.
+ final _quoted = <String, Map<String, SuperTabMessage?>>{};
+ final _quoting = <String, Set<String>>{};
+
/// Where each conversation's older history continues: the oldest message
/// read, as the backend's page cursor names it (section 4.6). Null at the
/// start of the conversation.
@@ -389,12 +394,58 @@ class SuperTabController extends ChangeNotifier {
_changed();
}
+ /// The original [messageId] of a reply in [id] whose page is not read:
+ /// read by itself the first time it is asked for. Null until it is known;
+ /// a record holding null when the conversation no longer has it.
+ ({SuperTabMessage? message})? quoted(String id, String messageId) {
+ final known = _quoted[id];
+ if (known != null && known.containsKey(messageId)) {
+ return (message: known[messageId]);
+ }
+ if ((_quoting[id] ??= {}).add(messageId)) {
+ scheduleMicrotask(() => _readQuoted(id, messageId));
+ }
+ return null;
+ }
+
+ /// Reads one message of [id] only: the backend checks the reader may read
+ /// that conversation, as for its pages. A failed read leaves the quote
+ /// saying the original isn't loaded.
+ Future<void> _readQuoted(String id, String messageId) async {
+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
+ return;
+ }
+ try {
+ final answer = await request(
+ 'GET',
+ '${_messagesPath(id)}?messageId=${Uri.encodeComponent(messageId)}',
+ );
+ if (_disposed ||
+ accessRevoked ||
+ snapshot?.conversation(id) == null ||
+ _quoting[id]?.contains(messageId) != true) {
+ return;
+ }
+ final rows = (answer['messages'] as List)
+ .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
+ .toList();
+ if (rows.length > 1 ||
+ rows.any((m) => m.id != messageId || m.conversationId != id)) {
+ return;
+ }
+ // A row the list never lists is no original to quote either.
+ (_quoted[id] ??= {})[messageId] = rows.where(_listed).firstOrNull;
+ _changed();
+ } catch (_) {}
+ }
+
List<SuperTabMessage> messages(String id) => List.unmodifiable(
- (_messages[id] ?? const <SuperTabMessage>[]).where(
- (m) => m.source['kind'] != 'update-request',
- ),
+ (_messages[id] ?? const <SuperTabMessage>[]).where(_listed),
);
+ static bool _listed(SuperTabMessage m) =>
+ m.source['kind'] != 'update-request';
+
/// "Reviewer: Ada · Ready: yes on 1a2b3c4d5", from the newest `Ready:` message a
/// reviewer of [group] posted in the loaded history. Null without a reviewer.
String? reviewLine(SuperTabConversation? group) {
@@ -573,6 +624,8 @@ class SuperTabController extends ChangeNotifier {
_parts = null;
_partsReadAt = null;
_messages.clear();
+ _quoted.clear();
+ _quoting.clear();
_rows.clear();
_before.clear();
}
@@ -603,6 +656,8 @@ class SuperTabController extends ChangeNotifier {
snapshot = null;
_parts = null;
_messages.clear();
+ _quoted.clear();
+ _quoting.clear();
_poll?.cancel();
_changed();
}
@@ -961,6 +1016,8 @@ class SuperTabController extends ChangeNotifier {
(id) => !next.projects.any((project) => project.id == id),
);
_messages.removeWhere((id, _) => !allowed.contains(id));
+ _quoted.removeWhere((id, _) => !allowed.contains(id));
+ _quoting.removeWhere((id, _) => !allowed.contains(id));
_rows.removeWhere((id, _) => !allowed.contains(id));
_drafts.removeWhere((id, _) => removed.contains(id));
_attachments.removeWhere((id, files) {
@@ -1303,6 +1360,8 @@ class SuperTabController extends ChangeNotifier {
snapshot = null;
_parts = null;
_messages.clear();
+ _quoted.clear();
+ _quoting.clear();
_poll?.cancel();
}
}
@@ -1444,6 +1503,8 @@ class SuperTabController extends ChangeNotifier {
if (failure is SuperTabFailure &&
const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
_messages.remove(id);
+ _quoted.remove(id);
+ _quoting.remove(id);
unawaited(refresh());
}
_changed();
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 9632395f5..62bc3deea 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -25,9 +25,11 @@ class SuperTabMessageRow extends StatefulWidget {
this.machineName,
this.reply,
this.replyAuthor,
+ this.replyGone = false,
this.grouped = false,
this.onReply,
this.onOpenAgent,
+ this.onOpenReply,
this.references = const {},
this.onOpenGroup,
this.mentions = const [],
@@ -44,8 +46,15 @@ class SuperTabMessageRow extends StatefulWidget {
final String? machineName;
final SuperTabMessage? reply;
final String? replyAuthor;
+
+ /// The original [reply] would show is no longer in the conversation.
+ final bool replyGone;
final bool grouped;
final VoidCallback? onReply, onOpenAgent;
+
+ /// Follows the quote to the original, given this row so that the way back
+ /// can return it to the same place on screen.
+ final ValueChanged<BuildContext>? onOpenReply;
final VoidCallback onReturnToComposer;
final List<Widget> receipts;
@@ -292,7 +301,12 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
'Earlier message',
text:
widget.reply?.text ??
- 'The original message isn’t loaded.',
+ (widget.replyGone
+ ? 'The original message is no longer in this conversation.'
+ : 'The original message isn’t loaded.'),
+ onTap: widget.onOpenReply == null
+ ? null
+ : () => widget.onOpenReply!(context),
),
),
if (message.terminalNote case final note?)
@@ -387,32 +401,66 @@ class SuperTabReplyPreview extends StatelessWidget {
super.key,
required this.author,
required this.text,
+ this.onTap,
});
final String author, text;
+ /// Goes to the quoted message. Without it the quote is only read.
+ final VoidCallback? onTap;
+
@override
- Widget build(BuildContext context) => Container(
- padding: const EdgeInsets.only(left: 10),
- decoration: BoxDecoration(
- border: Border(left: BorderSide(color: DesktopChrome.muted, width: 2)),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- author,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(medium: true),
- ),
- const SizedBox(height: 2),
- Text(
- text.replaceAll(RegExp(r'\s+'), ' '),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.metadata(),
- ),
- ],
- ),
- );
+ Widget build(BuildContext context) {
+ final quote = Container(
+ padding: const EdgeInsets.only(left: 10),
+ decoration: BoxDecoration(
+ border: Border(left: BorderSide(color: DesktopChrome.muted, width: 2)),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ text.replaceAll(RegExp(r'\s+'), ' '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ );
+ if (onTap == null) return quote;
+ return Semantics(
+ container: true,
+ button: true,
+ hint: 'Go to original message',
+ child: InkWell(onTap: onTap, child: quote),
+ );
+ }
+}
+
+/// Lights a message briefly, as the one a quote was followed to.
+class SuperTabMessageHighlight extends StatelessWidget {
+ const SuperTabMessageHighlight({
+ super.key,
+ required this.on,
+ required this.child,
+ });
+ final bool on;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return AnimatedContainer(
+ duration: const Duration(milliseconds: 400),
+ color: on ? DesktopChrome.selection : Colors.transparent,
+ child: child,
+ );
+ }
}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index ba781082b..a23c3ba87 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -98,9 +98,25 @@ class _SuperTabViewState extends State<SuperTabView>
// The message a tag opened, scrolled to once it is laid out.
String? _target;
final _targetKey = GlobalKey();
+ // A quote followed to its original: the search still reading older pages,
+ // the reply to come back to (its row's top in the list), and the message
+ // lit for a moment on arrival.
+ int _jumpRequest = 0;
+ ({String conversationId, int pages})? _finding;
+ ({String conversationId, String messageId, double top})? _back;
+ String? _lit;
+ Timer? _litTimer;
bool _viewEnabled = true;
bool _chatCovered = false;
final _loadingOlder = <String>{};
+ // Conversations whose last read of earlier messages failed: they offer the
+ // button instead of reading again by themselves.
+ final _olderFailed = <String>{};
+ // The list's rows while built, by message: a page read in above finds the
+ // row the reader was looking at, to keep it in place.
+ final _built = <String, BuildContext>{};
+ // Rows to keep in place once their conversation is on screen again.
+ final _anchors = <String, ({String messageId, double top})>{};
int _mentionIndex = 0;
String? _dismissedMention;
String? _completionPrefix;
@@ -179,6 +195,10 @@ class _SuperTabViewState extends State<SuperTabView>
_following.clear();
_newAfter.clear();
_replies.clear();
+ _jumpRequest++;
+ _finding = null;
+ _back = null;
+ _anchors.clear();
_selected = null;
_changed();
} else {
@@ -212,6 +232,13 @@ class _SuperTabViewState extends State<SuperTabView>
if (_selected != id) {
_scrollRequest++;
_jumpingToEnd = false;
+ // A search or a way back belongs to the conversation it started in.
+ _jumpRequest++;
+ _finding = null;
+ _back = null;
+ if (_anchors.remove(id) case final anchor?) {
+ unawaited(_keepRow(id, anchor));
+ }
_dial.cancel(); // a fling from the last conversation never scrolls this one
}
if (_selected != id || _composer.text != draft) {
@@ -337,6 +364,7 @@ class _SuperTabViewState extends State<SuperTabView>
if (c.pmChatOpener == _openPmChat) c.pmChatOpener = null;
_unregisterDial?.call();
_dial.cancel();
+ _litTimer?.cancel();
_composer.dispose();
_focus.dispose();
_pullRequestsFocus.dispose();
@@ -569,23 +597,122 @@ class _SuperTabViewState extends State<SuperTabView>
_focus.requestFocus();
}
- Future<void> _earlier() async {
- final id = c.selectedId, scroll = _scroll[c.selectedId];
- if (scroll == null || !scroll.hasClients || !_loadingOlder.add(id)) return;
- final offset = scroll.offset, extent = scroll.position.maxScrollExtent;
+ Future<void> _earlier() => _loadEarlier(c.selectedId);
+
+ /// A scroll ending near the top reads the earlier page with no click.
+ void _readEarlierNearTop(String id, ScrollMetrics metrics) {
+ if (metrics.extentBefore > 400 ||
+ _finding != null ||
+ _loadingOlder.contains(id) ||
+ _olderFailed.contains(id) ||
+ !c.hasOlder(id)) {
+ return;
+ }
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && c.selectedId == id && !_loadingOlder.contains(id)) {
+ unawaited(_loadEarlier(id));
+ }
+ });
+ }
+
+ /// Reads the page before those loaded, keeping what is on screen in place:
+ /// the row of [keep] when it is built, else the topmost row. Rows can
+ /// regroup as earlier ones arrive, so the one the reader looks at is kept.
+ /// A read already under way is joined; its caller keeps the place. The
+ /// reader scrolling during the read keeps their own place instead.
+ Future<void> _loadEarlier(String id, {String? keep}) async {
+ final scroll = _scroll[id];
+ if (scroll == null || !scroll.hasClients || !_loadingOlder.add(id)) {
+ await c.loadMessages(id, older: true);
+ return;
+ }
+ final request = _scrollRequest;
+ final loaded = c.messages(id).length;
+ final started = _anchorRow(keep);
+ setState(() {});
try {
await c.loadMessages(id, older: true);
+ } finally {
+ _loadingOlder.remove(id);
+ }
+ if (!mounted) return;
+ // Measured again as the page lands, before its rows are laid out: what
+ // is on screen now, wherever the reader went meanwhile. A conversation
+ // left meanwhile keeps the place it had.
+ final anchor = c.selectedId == id ? _anchorRow(keep) : started;
+ setState(() {
+ // A read that brought nothing while more remain failed.
+ if (c.hasOlder(id) && c.messages(id).length == loaded) {
+ _olderFailed.add(id);
+ } else {
+ _olderFailed.remove(id);
+ }
+ });
+ if (anchor != null) await _keepRow(id, anchor, request: request);
+ }
+
+ /// The row of [keep] when it is built, else the topmost row, and its top.
+ ({String messageId, double top})? _anchorRow(String? keep) {
+ final kept = _built[keep];
+ final keptTop = kept != null && kept.mounted ? _topInList(kept) : null;
+ return keptTop != null
+ ? (messageId: keep!, top: keptTop)
+ : _firstVisibleRow();
+ }
+
+ /// The topmost row in view, and its top within the list.
+ ({String messageId, double top})? _firstVisibleRow() {
+ ({String messageId, double top})? first;
+ for (final MapEntry(key: messageId, value: row) in _built.entries) {
+ if (!row.mounted) continue;
+ final top = _topInList(row);
+ if (top == null || top < 0 || (first != null && top >= first.top)) {
+ continue;
+ }
+ first = (messageId: messageId, top: top);
+ }
+ return first;
+ }
+
+ /// Brings [anchor]'s row back to where it was in [id]'s list after rows
+ /// arrived above it: near it by its place in the list until it is built,
+ /// then exactly. A conversation no longer on screen does so on return;
+ /// the reader scrolling since [request] (default: now) ends it.
+ Future<void> _keepRow(
+ String id,
+ ({String messageId, double top}) anchor, {
+ int? request,
+ }) async {
+ request ??= _scrollRequest;
+ for (var attempt = 0; attempt < 20; attempt++) {
await WidgetsBinding.instance.endOfFrame;
- if (mounted && c.selectedId == id && scroll.hasClients) {
+ if (!mounted) return;
+ final scroll = _scroll[id];
+ if (c.selectedId != id || scroll == null || !scroll.hasClients) {
+ _anchors[id] = anchor;
+ return;
+ }
+ if (request != _scrollRequest) return;
+ final position = scroll.position;
+ final row = _built[anchor.messageId];
+ final top = row != null && row.mounted ? _topInList(row) : null;
+ if (top == null) {
+ final entries = superTabTranscriptEntries(_shownMessages(id));
+ final index = entries.indexWhere(
+ (e) => e.message.id == anchor.messageId,
+ );
+ if (index < 0) return;
scroll.jumpTo(
- (offset + scroll.position.maxScrollExtent - extent).clamp(
- 0.0,
- scroll.position.maxScrollExtent,
- ),
+ position.maxScrollExtent * (index + 1) / (entries.length + 1),
);
+ continue;
}
- } finally {
- _loadingOlder.remove(id);
+ if ((top - anchor.top).abs() < .5) return;
+ // The list's extent is an estimate until laid out there: only the
+ // start bounds the jump, and the next frame measures the row again.
+ scroll.jumpTo(
+ (position.pixels + top - anchor.top).clamp(0.0, double.infinity),
+ );
}
}
@@ -865,26 +992,166 @@ class _SuperTabViewState extends State<SuperTabView>
}
/// The list is lazy: jump near the target until its row is built, then
- /// bring it into view.
- void _revealTarget(String id, int attempt) {
+ /// bring it into view, or hand its row to [arrived] to place it.
+ void _revealTarget(
+ String id,
+ int attempt, {
+ void Function(BuildContext row)? arrived,
+ }) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || c.selectedId != id || _target == null) return;
if (_targetKey.currentContext case final target?) {
- unawaited(Scrollable.ensureVisible(target, alignment: .3));
+ if (arrived != null) {
+ arrived(target);
+ } else {
+ unawaited(Scrollable.ensureVisible(target, alignment: .3));
+ }
return;
}
final scroll = _scroll[id];
- final messages = c.messages(id);
- final index = messages.indexWhere((m) => m.id == _target);
+ final entries = superTabTranscriptEntries(_shownMessages(id));
+ final index = entries.indexWhere((e) => e.message.id == _target);
if (scroll == null || !scroll.hasClients || index < 0 || attempt > 20) {
return;
}
- scroll.jumpTo(scroll.position.maxScrollExtent * index / messages.length);
- _revealTarget(id, attempt + 1);
+ scroll.jumpTo(
+ scroll.position.maxScrollExtent * (index + 1) / (entries.length + 1),
+ );
+ _revealTarget(id, attempt + 1, arrived: arrived);
});
WidgetsBinding.instance.scheduleFrame();
}
+ /// The messages [id]'s list shows, in order.
+ List<SuperTabMessage> _shownMessages(String id) =>
+ c.messages(id).where(_shown).toList();
+
+ /// A message waiting for an agent is never announced; notices older
+ /// backends stored stay hidden, in the list and as a reply's quote.
+ static bool _shown(SuperTabMessage m) => m.source['kind'] != 'delivery-hold';
+
+ /// The row of [id]'s list that shows [messageId]: its own, or the notice
+ /// that folds it in. Null while the message is not loaded.
+ String? _rowShowing(String id, String messageId) {
+ final shown = _shownMessages(id);
+ final message = shown.where((m) => m.id == messageId).firstOrNull;
+ if (message == null) return null;
+ return superTabTranscriptEntries(shown)
+ .lastWhere(
+ (e) => superTabMessageOrder(e.message, message) <= 0,
+ orElse: () => (message: message, interruptions: 0),
+ )
+ .message
+ .id;
+ }
+
+ /// The top of [row] within the message list.
+ double? _topInList(BuildContext row) {
+ final box = row.findRenderObject(), list = Scrollable.maybeOf(row);
+ final viewport = list?.context.findRenderObject();
+ if (box is! RenderBox || viewport is! RenderBox || !box.attached) {
+ return null;
+ }
+ return box.localToGlobal(Offset.zero, ancestor: viewport).dy;
+ }
+
+ /// Follows [reply]'s quote to its original, reading older pages until it is
+ /// loaded. Only this conversation's own pages are read, so the original is
+ /// one the reader may read, or it is not found.
+ Future<void> _openOriginal(SuperTabMessage reply, BuildContext row) async {
+ final id = c.selectedId, original = reply.replyTo;
+ final top = _topInList(row);
+ if (original == null || top == null) return;
+ final request = ++_jumpRequest;
+ bool current() =>
+ request == _jumpRequest &&
+ c.selectedId == id &&
+ !c.accessRevoked &&
+ c.snapshot?.conversation(id) != null;
+ var target = _rowShowing(id, original);
+ String? note;
+ for (var pages = 0; target == null && c.hasOlder(id); pages++) {
+ // As far back as a tag is opened from.
+ if (pages == 50) {
+ note = 'The original message is too far back to open.';
+ break;
+ }
+ setState(() => _finding = (conversationId: id, pages: pages));
+ final loaded = c.messages(id).length;
+ await _loadEarlier(id, keep: reply.id);
+ if (!mounted || !current()) return;
+ target = _rowShowing(id, original);
+ if (target == null && c.messages(id).length == loaded) {
+ note = 'Couldn’t load earlier messages to find the original.';
+ break;
+ }
+ }
+ setState(() => _finding = null);
+ if (target == null) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(
+ content: Text(
+ note ?? 'The original message is no longer in this conversation.',
+ ),
+ ),
+ );
+ return;
+ }
+ final found = target;
+ setState(() {
+ _back = (conversationId: id, messageId: reply.id, top: top);
+ _target = found;
+ // Stop following the end: the original is what to see.
+ _scrollRequest++;
+ _jumpingToEnd = false;
+ _following[id] = false;
+ });
+ _revealTarget(
+ id,
+ 0,
+ arrived: (row) {
+ unawaited(Scrollable.ensureVisible(row, alignment: .3));
+ _light(found);
+ },
+ );
+ }
+
+ /// Returns to the reply a quote was followed from, where it was on screen.
+ void _goBack() {
+ final back = _back;
+ if (back == null || back.conversationId != c.selectedId) return;
+ final id = back.conversationId;
+ setState(() {
+ _back = null;
+ _target = back.messageId;
+ _scrollRequest++;
+ _jumpingToEnd = false;
+ });
+ _revealTarget(
+ id,
+ 0,
+ arrived: (row) {
+ final scroll = _scroll[id], top = _topInList(row);
+ if (scroll == null || !scroll.hasClients || top == null) return;
+ scroll.jumpTo(
+ (scroll.offset + top - back.top).clamp(
+ 0.0,
+ scroll.position.maxScrollExtent,
+ ),
+ );
+ },
+ );
+ _focus.requestFocus();
+ }
+
+ void _light(String messageId) {
+ _litTimer?.cancel();
+ setState(() => _lit = messageId);
+ _litTimer = Timer(const Duration(seconds: 2), () {
+ if (mounted) setState(() => _lit = null);
+ });
+ }
+
List<SuperTabAgent> _needsHuman(SuperTabConversation group) =>
c.snapshot?.agents
.where(
@@ -1325,7 +1592,14 @@ class _SuperTabViewState extends State<SuperTabView>
final agent = message.fromAgent
? c.snapshot?.agent(message.authorId)
: null;
- final reply = byId[message.replyTo];
+ // An original outside the pages read is read by itself for its quote.
+ final quoted = message.replyTo == null || byId.containsKey(message.replyTo)
+ ? null
+ : c.quoted(message.conversationId, message.replyTo!);
+ final fetched = quoted?.message;
+ final reply =
+ byId[message.replyTo] ??
+ (fetched != null && _shown(fetched) ? fetched : null);
return SuperTabMessageRow(
key: ValueKey('super-message-${message.id}'),
message: message,
@@ -1352,6 +1626,8 @@ class _SuperTabViewState extends State<SuperTabView>
grouped: grouped,
reply: reply,
replyAuthor: reply == null ? null : _shownAuthor(c, reply),
+ replyGone: quoted != null && reply == null,
+ onOpenReply: (row) => unawaited(_openOriginal(message, row)),
onReply: c.canWrite && c.selected?.archived == false
? () {
setState(() => _replies[c.selectedId] = message);
@@ -1476,16 +1752,14 @@ class _SuperTabViewState extends State<SuperTabView>
final group = c.selected;
final writable = c.canWrite && group != null && !group.archived;
final busy = c.saving || c.uploading;
- final allMessages = c.messages(c.selectedId);
- final latestOwn = allMessages.reversed
+ final latestOwn = c
+ .messages(c.selectedId)
+ .reversed
.where(
(m) => !m.fromAgent && !m.fromTerminal && m.authorId == c.accountId,
)
.firstOrNull;
- // A message waiting for an agent is never announced; notices older backends stored stay hidden.
- final messages = allMessages
- .where((m) => m.source['kind'] != 'delivery-hold')
- .toList();
+ final messages = _shownMessages(c.selectedId);
final entries = superTabTranscriptEntries(messages);
final byId = {for (final message in messages) message.id: message};
final grouped = SuperTabMessageRow.consecutiveUpdates(messages);
@@ -1494,6 +1768,8 @@ class _SuperTabViewState extends State<SuperTabView>
? 0
: messages.where((message) => message.sequence > newAfter).length;
final reply = _replies[c.selectedId];
+ final finding = _finding?.conversationId == c.selectedId ? _finding : null;
+ final back = finding == null && _back?.conversationId == c.selectedId;
final choices = _completionChoices;
// No conversation read yet: its error is the page itself, not a line over "Loading".
final unread = _readsFirst && c.snapshot == null;
@@ -1553,6 +1829,11 @@ class _SuperTabViewState extends State<SuperTabView>
final id = c.selectedId;
final atEnd = event.metrics.extentAfter < 40;
_following[id] = atEnd;
+ // Once the scroll ends, so keeping the place never
+ // cuts a drag short.
+ if (event is ScrollEndNotification) {
+ _readEarlierNearTop(id, event.metrics);
+ }
if (atEnd) {
final sequence = messages.lastOrNull?.sequence ?? 0;
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -1573,14 +1854,36 @@ class _SuperTabViewState extends State<SuperTabView>
itemCount: entries.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
- return c.hasOlder(c.selectedId)
- ? Align(
- child: TextButton(
- onPressed: () => unawaited(_earlier()),
- child: const Text('Earlier messages'),
- ),
- )
- : const SizedBox.shrink();
+ final id = c.selectedId;
+ if (!c.hasOlder(id)) {
+ return const SizedBox.shrink();
+ }
+ // The button only after a read failed: near
+ // the top, earlier pages read by themselves.
+ if (_olderFailed.contains(id)) {
+ return Align(
+ child: TextButton(
+ onPressed: () => unawaited(_earlier()),
+ child: const Text('Earlier messages'),
+ ),
+ );
+ }
+ return SizedBox(
+ height: 40,
+ child: _loadingOlder.contains(id)
+ ? const Center(
+ child: SizedBox.square(
+ key: ValueKey(
+ 'super-earlier-loading',
+ ),
+ dimension: 16,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ ),
+ ),
+ )
+ : null,
+ );
}
final entry = entries[index - 1];
final message = entry.message;
@@ -1600,51 +1903,130 @@ class _SuperTabViewState extends State<SuperTabView>
previous?.createdAt?.toLocal(),
))
_date(time),
- if (entry.interruptions > 0)
- SuperTabRecordingNotice(
- key: ValueKey(
- 'super-message-${message.id}',
- ),
- author: _shownAuthor(c, message),
- count: entry.interruptions,
- onOpenTerminal: agent == null
- ? null
- : () => _openAgent(agent),
- )
- else
- KeyedSubtree(
+ // The message itself is kept in place: its
+ // date moves above earlier ones as they come.
+ _BuiltRow(
+ id: message.id,
+ rows: _built,
+ child: KeyedSubtree(
key: message.id == _target
? _targetKey
: null,
- child: _message(
- message,
- grouped.contains(message.id),
- byId,
- showReceipt: message.id == latestOwn?.id,
+ child: SuperTabMessageHighlight(
+ on: message.id == _lit,
+ child: entry.interruptions > 0
+ ? SuperTabRecordingNotice(
+ key: ValueKey(
+ 'super-message-${message.id}',
+ ),
+ author: _shownAuthor(c, message),
+ count: entry.interruptions,
+ onOpenTerminal: agent == null
+ ? null
+ : () => _openAgent(agent),
+ )
+ : _message(
+ message,
+ grouped.contains(message.id),
+ byId,
+ showReceipt:
+ message.id == latestOwn?.id,
+ ),
),
),
+ ),
],
);
},
),
),
),
- if (newCount > 0)
+ if (finding != null)
Positioned(
- bottom: 12,
+ top: 12,
left: 20,
right: 20,
child: Center(
- child: FilledButton.icon(
- key: const ValueKey('super-new-messages'),
- onPressed: _jumpToLatest,
- icon: const Icon(AppIcons.chevronDown, size: 16),
- label: Text(
- '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
+ child: Material(
+ key: const ValueKey('super-reply-finding'),
+ color: DesktopChrome.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ side: BorderSide(color: DesktopChrome.rim),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.only(left: 12),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ finding.pages == 0
+ ? 'Finding the original message…'
+ : 'Finding the original message… '
+ '${finding.pages} '
+ '${finding.pages == 1 ? 'page' : 'pages'} back',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ ),
+ const SizedBox(width: 4),
+ TextButton(
+ onPressed: () => setState(() {
+ _jumpRequest++;
+ _finding = null;
+ }),
+ child: const Text('Cancel'),
+ ),
+ ],
+ ),
),
),
),
),
+ if (newCount > 0 || back)
+ Positioned(
+ bottom: 12,
+ left: 20,
+ right: 20,
+ child: Center(
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ alignment: WrapAlignment.center,
+ children: [
+ if (back)
+ FilledButton.icon(
+ key: const ValueKey('super-reply-back'),
+ onPressed: _goBack,
+ icon: const Icon(
+ AppIcons.chevronDown,
+ size: 16,
+ ),
+ label: const Text('Back to reply'),
+ ),
+ if (newCount > 0)
+ FilledButton.icon(
+ key: const ValueKey('super-new-messages'),
+ onPressed: _jumpToLatest,
+ icon: const Icon(
+ AppIcons.chevronDown,
+ size: 16,
+ ),
+ label: Text(
+ '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
],
),
),
@@ -2167,3 +2549,38 @@ class _SuperTabViewState extends State<SuperTabView>
},
);
}
+
+/// Records its row's context while built, so [_SuperTabViewState] can find
+/// the row a message is shown in.
+class _BuiltRow extends StatefulWidget {
+ const _BuiltRow({required this.id, required this.rows, required this.child});
+ final String id;
+ final Map<String, BuildContext> rows;
+ final Widget child;
+
+ @override
+ State<_BuiltRow> createState() => _BuiltRowState();
+}
+
+class _BuiltRowState extends State<_BuiltRow> {
+ @override
+ void didUpdateWidget(_BuiltRow oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ // The list reuses a row for another message.
+ if (oldWidget.id != widget.id && oldWidget.rows[oldWidget.id] == context) {
+ oldWidget.rows.remove(oldWidget.id);
+ }
+ }
+
+ @override
+ void dispose() {
+ if (widget.rows[widget.id] == context) widget.rows.remove(widget.id);
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ widget.rows[widget.id] = context;
+ return widget.child;
+ }
+}
diff --git a/desktop/test/super_tab_reply_jump_test.dart b/desktop/test/super_tab_reply_jump_test.dart
new file mode 100644
index 000000000..3e797310b
--- /dev/null
+++ b/desktop/test/super_tab_reply_jump_test.dart
@@ -0,0 +1,448 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/message_row.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ /// [count] notes in the Lead chat; the last one replies to [replyTo].
+ ConversationServer chat(int count, {required String replyTo}) {
+ final server = ConversationServer();
+ for (var i = 1; i <= count; i++) {
+ server.append('Note $i');
+ }
+ server.messages.last['replyTo'] = replyTo;
+ return server;
+ }
+
+ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));
+ Finder quoteIn(String id) =>
+ find.descendant(of: row(id), matching: find.byType(SuperTabReplyPreview));
+ bool highlighted(WidgetTester tester, String id) => tester
+ .widget<SuperTabMessageHighlight>(
+ find.ancestor(
+ of: row(id),
+ matching: find.byType(SuperTabMessageHighlight),
+ ),
+ )
+ .on;
+ Finder note(String text) =>
+ find.descendant(of: find.byType(SnackBar), matching: find.text(text));
+
+ testWidgets('tapping a quote brings its loaded original into view, lit', (
+ tester,
+ ) async {
+ await show(tester, chat(60, replyTo: 'message-1'));
+ expect(row('message-1').hitTestable(), findsNothing);
+ await tester.tap(quoteIn('message-60'));
+ await tester.pumpAndSettle();
+ expect(row('message-1').hitTestable(), findsOneWidget);
+ expect(highlighted(tester, 'message-1'), isTrue);
+ // The light is brief.
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pumpAndSettle();
+ expect(highlighted(tester, 'message-1'), isFalse);
+ });
+
+ testWidgets('one tap goes back to the reply, where it was on screen', (
+ tester,
+ ) async {
+ await show(tester, chat(60, replyTo: 'message-1'));
+ expect(find.byKey(const ValueKey('super-reply-back')), findsNothing);
+ final before = tester.getTopLeft(row('message-60'));
+ await tester.tap(quoteIn('message-60'));
+ await tester.pumpAndSettle();
+ expect(row('message-60').hitTestable(), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-reply-back')));
+ await tester.pumpAndSettle();
+ expect(tester.getTopLeft(row('message-60')), before);
+ expect(find.byKey(const ValueKey('super-reply-back')), findsNothing);
+ });
+
+ testWidgets('an original pages back reads older pages until it is there', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ final c = await show(tester, server);
+ expect(c.messages('lead').any((m) => m.id == 'message-10'), isFalse);
+ server.holdReads = Completer<void>();
+ await tester.tap(quoteIn('message-250'));
+ await tester.pump();
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsOneWidget);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsNothing);
+ expect(row('message-10').hitTestable(), findsOneWidget);
+ expect(highlighted(tester, 'message-10'), isTrue);
+ });
+
+ testWidgets('back after older pages arrive keeps the reply in its place', (
+ tester,
+ ) async {
+ await show(tester, chat(250, replyTo: 'message-10'));
+ final before = tester.getTopLeft(row('message-250'));
+ await tester.tap(quoteIn('message-250'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-reply-back')));
+ await tester.pumpAndSettle();
+ expect(tester.getTopLeft(row('message-250')), before);
+ });
+
+ testWidgets('reading older pages keeps what is on screen in place', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ await show(tester, server);
+ final before = tester.getTopLeft(row('message-250'));
+ // Each page waits, so the screen is seen between pages.
+ server.holdReads = Completer<void>();
+ await tester.tap(quoteIn('message-250'));
+ await tester.pump();
+ final first = server.holdReads!;
+ server.holdReads = Completer<void>();
+ first.complete();
+ // The next page is still on its way.
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsOneWidget);
+ expect(tester.getTopLeft(row('message-250')), before);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ });
+
+ Finder messageList() => find.byWidgetPredicate(
+ (w) => w is ListView && '${w.key}'.contains('super-messages-'),
+ );
+ ScrollPosition listPosition(WidgetTester tester) => tester
+ .state<ScrollableState>(
+ find.descendant(of: messageList(), matching: find.byType(Scrollable)),
+ )
+ .position;
+ // A spinner never settles: these pump a while instead.
+ Future<void> settle(WidgetTester tester) async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ /// The reader drags the chat to its top.
+ Future<void> dragToTop(WidgetTester tester) async {
+ await tester.drag(
+ messageList(),
+ Offset(0, listPosition(tester).pixels + 200),
+ );
+ await settle(tester);
+ }
+
+ final earlierLoading = find.byKey(const ValueKey('super-earlier-loading'));
+
+ testWidgets('near the top, earlier messages load by themselves in place', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ final c = await show(tester, server);
+ final loaded = c.messages('lead').length;
+ server.holdReads = Completer<void>();
+ await dragToTop(tester);
+ expect(earlierLoading, findsOneWidget);
+ expect(find.text('Earlier messages'), findsNothing);
+ final top = c.messages('lead').first.id;
+ final before = tester.getTopLeft(row(top));
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(c.messages('lead').length, greaterThan(loaded));
+ expect(tester.getTopLeft(row(top)), before);
+ expect(earlierLoading, findsNothing);
+ });
+
+ testWidgets('a failed earlier read offers the button to try again', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ final c = await show(tester, server);
+ final loaded = c.messages('lead').length;
+ server.holdReads = Completer<void>();
+ await dragToTop(tester);
+ // Tried with no click, then the read fails.
+ expect(earlierLoading, findsOneWidget);
+ server.holdReads!.completeError(StateError('Offline'));
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(find.text('Earlier messages'), findsOneWidget);
+ expect(earlierLoading, findsNothing);
+ server.failReads = false;
+ await tester.tap(find.text('Earlier messages'));
+ await tester.pumpAndSettle();
+ expect(c.messages('lead').length, greaterThan(loaded));
+ });
+
+ testWidgets('dragging while earlier messages load keeps the reader there', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ await show(tester, server);
+ server.holdReads = Completer<void>();
+ await dragToTop(tester);
+ expect(earlierLoading, findsOneWidget);
+ // The reader moves on while the page is slow.
+ await tester.drag(messageList(), const Offset(0, -300));
+ await settle(tester);
+ final dragged = listPosition(tester).pixels;
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(listPosition(tester).pixels, dragged);
+ });
+
+ testWidgets('a quote whose original is not loaded reads it and shows it', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ final reads = <String>[];
+ server.onRead = reads.add;
+ final c = await show(tester, server);
+ expect(c.messages('lead').any((m) => m.id == 'message-10'), isFalse);
+ final quote = quoteIn('message-250');
+ expect(
+ find.descendant(of: quote, matching: find.text('Note 10')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: quote, matching: find.text('Earlier message')),
+ findsNothing,
+ );
+ // Rebuilds never read it again.
+ await tester.pump(const Duration(seconds: 5));
+ await tester.pumpAndSettle();
+ expect(reads.where((p) => p.contains('messageId=message-10')).length, 1);
+ });
+
+ /// [count] notes in the Lead chat; the first is a [kind] row the chat
+ /// hides, and the last replies to it.
+ ConversationServer hiddenOriginal(int count, String kind) {
+ final server = ConversationServer()..append('Hidden $kind');
+ server.messages.last['source'] = {'kind': kind};
+ for (var i = 2; i <= count; i++) {
+ server.append('Note $i');
+ }
+ server.messages.last['replyTo'] = 'message-1';
+ return server;
+ }
+
+ Future<void> expectHiddenQuote(WidgetTester tester, String reply) async {
+ // Its read lands after the first frames.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Hidden'), findsNothing);
+ expect(
+ find.descendant(
+ of: quoteIn(reply),
+ matching: find.text(
+ 'The original message is no longer in this conversation.',
+ ),
+ ),
+ findsOneWidget,
+ );
+ }
+
+ testWidgets('a quote of a loaded waiting notice keeps it hidden', (
+ tester,
+ ) async {
+ await show(tester, hiddenOriginal(60, 'delivery-hold'));
+ await expectHiddenQuote(tester, 'message-60');
+ });
+
+ testWidgets('a quote of a waiting notice not loaded keeps it hidden', (
+ tester,
+ ) async {
+ final c = await show(tester, hiddenOriginal(250, 'delivery-hold'));
+ expect(c.hasOlder('lead'), isTrue);
+ await expectHiddenQuote(tester, 'message-250');
+ });
+
+ testWidgets('a quote of an update request not loaded keeps it hidden', (
+ tester,
+ ) async {
+ final c = await show(tester, hiddenOriginal(250, 'update-request'));
+ expect(c.hasOlder('lead'), isTrue);
+ await expectHiddenQuote(tester, 'message-250');
+ });
+
+ testWidgets('a quote whose original was deleted says so', (tester) async {
+ await show(tester, chat(60, replyTo: 'message-gone'));
+ // Its read lands after the first frames.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpAndSettle();
+ expect(
+ find.descendant(
+ of: quoteIn('message-60'),
+ matching: find.text(
+ 'The original message is no longer in this conversation.',
+ ),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a deleted original says so instead', (tester) async {
+ await show(tester, chat(60, replyTo: 'message-gone'));
+ await tester.tap(quoteIn('message-60'));
+ await tester.pumpAndSettle();
+ expect(
+ note('The original message is no longer in this conversation.'),
+ findsOneWidget,
+ );
+ expect(row('message-60').hitTestable(), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-reply-back')), findsNothing);
+ });
+
+ testWidgets('an original past the pages it reads back says so', (
+ tester,
+ ) async {
+ final server = chat(60, replyTo: 'message-1')..messagePage = 1;
+ final c = await show(tester, server);
+ await tester.tap(quoteIn('message-60'));
+ await tester.pumpAndSettle();
+ expect(
+ note('The original message is too far back to open.'),
+ findsOneWidget,
+ );
+ expect(c.hasOlder('lead'), isTrue);
+ });
+
+ testWidgets('an original in a chat the reader cannot read stays hidden', (
+ tester,
+ ) async {
+ final server = chat(60, replyTo: 'message-61');
+ server.append('Private plan', conversationId: 'offline');
+ await show(tester, server);
+ expect(find.textContaining('Private plan'), findsNothing);
+ await tester.tap(quoteIn('message-60'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Private plan'), findsNothing);
+ expect(
+ note('The original message is no longer in this conversation.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a failed page read says so and stops', (tester) async {
+ final server = chat(250, replyTo: 'message-10');
+ await show(tester, server);
+ server.failReads = true;
+ await tester.tap(quoteIn('message-250'));
+ await tester.pumpAndSettle();
+ expect(
+ note('Couldn’t load earlier messages to find the original.'),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsNothing);
+ });
+
+ testWidgets('cancelling the search stays where the reader is', (
+ tester,
+ ) async {
+ final server = chat(250, replyTo: 'message-10');
+ await show(tester, server);
+ final before = tester.getTopLeft(row('message-250'));
+ server.holdReads = Completer<void>();
+ await tester.tap(quoteIn('message-250'));
+ await tester.pump();
+ await tester.tap(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-reply-finding')),
+ matching: find.text('Cancel'),
+ ),
+ );
+ await tester.pump();
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsNothing);
+ expect(tester.getTopLeft(row('message-250')), before);
+ expect(find.byType(SnackBar), findsNothing);
+ });
+
+ testWidgets('switching chats mid-search abandons it there', (tester) async {
+ final server = chat(250, replyTo: 'message-10');
+ final c = await show(tester, server);
+ server.holdReads = Completer<void>();
+ await tester.tap(quoteIn('message-250'));
+ await tester.pump();
+ c.select('offline');
+ await tester.pump();
+ expect(find.byKey(const ValueKey('super-reply-finding')), findsNothing);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ expect(find.byType(SnackBar), findsNothing);
+ c.select('lead');
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-reply-back')), findsNothing);
+ expect(row('message-250').hitTestable(), findsOneWidget);
+ });
+
+ testWidgets('closing the chat mid-search ends it quietly', (tester) async {
+ final server = chat(250, replyTo: 'message-10');
+ await show(tester, server);
+ server.holdReads = Completer<void>();
+ await tester.tap(quoteIn('message-250'));
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('the quote reads as a link to the original, words and all', (
+ tester,
+ ) async {
+ await show(tester, chat(3, replyTo: 'message-1'));
+ expect(
+ tester.getSemantics(quoteIn('message-3')),
+ isSemantics(
+ label: 'You\nNote 1',
+ hint: 'Go to original message',
+ isButton: true,
+ hasTapAction: true,
+ isFocusable: true,
+ ),
+ );
+ });
+}