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
Desktop: a sticky day pill at the top of the Swarm chat and thread (#2784)
0xken1548a8cd1a0421
diff --git a/desktop/lib/super_tabs/day_pill.dart b/desktop/lib/super_tabs/day_pill.dartnew file mode 100644index 000000000..b443e0c65--- /dev/null+++ b/desktop/lib/super_tabs/day_pill.dart@@ -0,0 +1,232 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';++/// The day of the message at the top of a list, in a small pill over the+/// list's top while the reader is scrolled into it, as Slack's (Huy 11-03).+/// It replaces itself as the reader passes into another day.+///+/// The pill floats over [child] and takes no room in it, so no row moves when+/// it shows, changes or goes. Each message row in [child] is wrapped in a+/// [SuperTabDayMark] with its time; rows without one are not counted. With+/// nothing hidden above the list's top (the start of what is read) it shows+/// nothing, and the inline day line says the day.+class SuperTabStickyDay extends StatefulWidget {+ const SuperTabStickyDay({+ super.key,+ required this.child,+ this.pillKey,+ this.hidden = false,+ });++ final Widget child;++ /// The pill's key, so a chat and its thread can be told apart.+ final Key? pillKey;++ /// Another note holds the list's top (finding a quoted message).+ final bool hidden;++ @override+ State<SuperTabStickyDay> createState() => _SuperTabStickyDayState();+}++class _SuperTabStickyDayState extends State<SuperTabStickyDay> {+ final _marks = <_SuperTabDayMarkState>{};+ DateTime? _day;+ bool _measuring = false;++ @override+ void initState() {+ super.initState();+ _measureAfterFrame();+ }++ @override+ void didUpdateWidget(SuperTabStickyDay oldWidget) {+ super.didUpdateWidget(oldWidget);+ // Rows came or went with the list's rebuild.+ _measureAfterFrame();+ }++ void _measureAfterFrame() {+ if (_measuring) return;+ _measuring = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ _measuring = false;+ if (!mounted) return;+ final day = _dayAtTop();+ if (day != _day) setState(() => _day = day);+ });+ }++ /// The local day of the row at the top edge: the one the edge cuts+ /// through, else the highest one below it; null when nothing is hidden+ /// above the list's top.+ DateTime? _dayAtTop() {+ final list = context.findRenderObject();+ if (list is! RenderBox || !list.hasSize) return null;+ ({double top, DateTime time})? at;+ ScrollPosition? position;+ for (final mark in _marks) {+ final time = mark.widget.time;+ final box = mark.context.findRenderObject();+ if (time == null || box is! RenderBox || !box.attached || !box.hasSize) {+ continue;+ }+ final top = box.localToGlobal(Offset.zero, ancestor: list).dy;+ final bottom = top + box.size.height;+ if (bottom <= 0 || top >= list.size.height) continue;+ position ??= Scrollable.maybeOf(mark.context)?.position;+ final better =+ at == null ||+ (top <= 0 ? at.top > 0 || top > at.top : at.top > 0 && top < at.top);+ if (better) at = (top: top, time: time);+ }+ if (at == null || position == null || !position.hasPixels) return null;+ if (position.extentBefore <= 0) return null;+ final local = at.time.toLocal();+ return DateTime(local.year, local.month, local.day);+ }++ bool _onScroll(Notification event) {+ final depth = switch (event) {+ ScrollNotification(:final depth, :final metrics) ||+ ScrollMetricsNotification(+ :final depth,+ :final metrics,+ ) when metrics.axis == Axis.vertical => depth,+ _ => null,+ };+ if (depth == 0) _measureAfterFrame();+ return false;+ }++ @override+ Widget build(BuildContext context) {+ final day = _day;+ return _SuperTabDayScope(+ state: this,+ child: Stack(+ children: [+ Positioned.fill(+ child: NotificationListener<Notification>(+ onNotification: _onScroll,+ child: widget.child,+ ),+ ),+ if (day != null && !widget.hidden)+ Positioned(+ top: grid.AppDesktop.controlGap,+ left: 0,+ right: 0,+ child: IgnorePointer(+ // The day lines in the list say it to a screen reader.+ child: ExcludeSemantics(+ child: Center(+ child: SuperTabDayPill(key: widget.pillKey, day: day),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++class _SuperTabDayScope extends InheritedWidget {+ const _SuperTabDayScope({required this.state, required super.child});++ final _SuperTabStickyDayState state;++ @override+ bool updateShouldNotify(_SuperTabDayScope oldWidget) =>+ state != oldWidget.state;+}++/// A message row's time, for the [SuperTabStickyDay] above it.+class SuperTabDayMark extends StatefulWidget {+ const SuperTabDayMark({super.key, required this.time, required this.child});++ final DateTime? time;+ final Widget child;++ @override+ State<SuperTabDayMark> createState() => _SuperTabDayMarkState();+}++class _SuperTabDayMarkState extends State<SuperTabDayMark> {+ _SuperTabStickyDayState? _list;++ void _join() {+ final list = context+ .getInheritedWidgetOfExactType<_SuperTabDayScope>()+ ?.state;+ if (list == _list) return;+ _list?._marks.remove(this);+ _list = list?.._marks.add(this);+ }++ void _leave() {+ _list?._marks.remove(this);+ _list = null;+ }++ @override+ void activate() {+ super.activate();+ _join();+ }++ // A row taken out of the tree is not measured, even before it is disposed.+ @override+ void deactivate() {+ _leave();+ super.deactivate();+ }++ @override+ void dispose() {+ _leave();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ _join();+ return widget.child;+ }+}++/// The pill: the day as the chat's day lines say it.+class SuperTabDayPill extends StatelessWidget {+ const SuperTabDayPill({super.key, required this.day});++ final DateTime day;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return DecoratedBox(+ decoration: ShapeDecoration(+ color: DesktopChrome.surface,+ shape: StadiumBorder(side: BorderSide(color: DesktopChrome.rim)),+ // Lifted off the rows it floats over, as Slack's.+ shadows: grid.AppGlass.cardShadow,+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap + grid.AppDesktop.menuInset,+ vertical: grid.AppDesktop.listRowGap,+ ),+ child: Text(+ MaterialLocalizations.of(context).formatMediumDate(day),+ maxLines: 1,+ style: DesktopChrome.metadata(),+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex df3f76f1c..01600cc35 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -11,6 +11,7 @@ import '../widgets/desktop_chrome.dart';import 'buddy_sessions.dart';import 'composer_tags.dart';import 'composer_toggle.dart';+import 'day_pill.dart';import 'reply_box.dart';import 'controller.dart';import 'message_row.dart' show SuperTabMessageRow;@@ -83,6 +84,14 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {SuperTabController get c => widget.controller;+ /// [row] with its message's time, for the day pill over the list. Keyed+ /// by the message, so the list keeps each row's place as replies arrive.+ Widget _dated(SuperTabMessage message, Widget row) => SuperTabDayMark(+ key: ValueKey('super-thread-day-${message.id}'),+ time: message.createdAt,+ child: row,+ );+/// The conversation this thread is in.String get _conversationId => c.openedThread?.conversationId ?? c.selectedId;@@ -379,74 +388,86 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {Expanded(child: Stack(children: [- // As in the chat, a message's text can be selected and copied.- SelectionArea(- child: LaidOutListView(- controller: _scroll,- padding: const EdgeInsets.symmetric(- vertical: grid.AppDesktop.controlGap,- ),- children: [- if (root != null) widget.row(root, false),- if (count > 0)- Padding(- key: const ValueKey('super-thread-divider'),- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.groupGap,- vertical: grid.AppDesktop.controlGap,+ SuperTabStickyDay(+ pillKey: const ValueKey('super-thread-day-pill'),+ // As in the chat, a message's text can be selected and+ // copied.+ child: SelectionArea(+ child: LaidOutListView(+ controller: _scroll,+ padding: const EdgeInsets.symmetric(+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ if (root != null)+ _dated(root, widget.row(root, false)),+ if (count > 0)+ Padding(+ key: const ValueKey('super-thread-divider'),+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: Row(+ children: [+ Text(+ count == 1 ? '1 reply' : '$count replies',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(+ width: grid.AppDesktop.controlGap,+ ),+ Expanded(+ child: Divider(+ height: 1,+ thickness: 1,+ color: DesktopChrome.rim,+ ),+ ),+ ],+ ),),- child: Row(- children: [- Text(- count == 1 ? '1 reply' : '$count replies',- style: DesktopChrome.metadata(),- ),- const SizedBox(- width: grid.AppDesktop.controlGap,+ if (c.hasEarlierReplies(widget.root))+ Align(+ alignment: Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,),- Expanded(- child: Divider(- height: 1,- thickness: 1,- color: DesktopChrome.rim,+ child: TextButton(+ key: const ValueKey('super-thread-earlier'),+ onPressed: c.readingEarlierReplies+ ? null+ : () {+ // They read on from where they are.+ _scroll.holdPlace();+ unawaited(+ c.loadThread(earlier: true),+ );+ },+ child: Text(+ c.readingEarlierReplies+ ? 'Loading earlier replies…'+ : 'Show earlier replies',),),- ],- ),- ),- if (c.hasEarlierReplies(widget.root))- Align(- alignment: Alignment.centerLeft,- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: grid.AppDesktop.controlGap,),- child: TextButton(- key: const ValueKey('super-thread-earlier'),- onPressed: c.readingEarlierReplies- ? null- : () {- // They read on from where they are.- _scroll.holdPlace();- unawaited(c.loadThread(earlier: true));- },- child: Text(- c.readingEarlierReplies- ? 'Loading earlier replies…'- : 'Show earlier replies',- ),+ ),+ for (final (index, reply) in replies.indexed)+ _dated(+ reply,+ widget.row(+ reply,+ index > 0 &&+ replies[index - 1].authorId ==+ reply.authorId &&+ replies[index - 1].fromAgent ==+ reply.fromAgent,),),- ),- for (final (index, reply) in replies.indexed)- widget.row(- reply,- index > 0 &&- replies[index - 1].authorId == reply.authorId &&- replies[index - 1].fromAgent == reply.fromAgent,- ),- for (final sent in pending) widget.outgoing(sent),- ],+ for (final sent in pending) widget.outgoing(sent),+ ],+ ),),),if (_away)diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex b3bfe8f09..f6de5e855 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -54,6 +54,7 @@ import 'message_receipt.dart';import 'notifications.dart';import 'buddies.dart';import 'decisions.dart';+import 'day_pill.dart';import 'decisions_view.dart';import 'route_row.dart';import 'terminal_row.dart';@@ -3571,52 +3572,55 @@ class _SuperTabViewState extends State<SuperTabView>: null;final previous = index > 0 ? entries[index - 1].message : null;final time = message.createdAt;- return Column(+ return SuperTabDayMark(key: ValueKey(_rowKey(c.messageIdentity(message.id))),- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (time != null &&- !DateUtils.isSameDay(- time.toLocal(),- previous?.createdAt?.toLocal(),- ))- _date(time),- if (message.id == _unread.lineAt(c.selectedId))- SuperTabNewMessagesLine(key: _unread.key),- // 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: SuperTabMessageHighlight(- on: message.id == _lit,- child: pendingById.containsKey(message.id)- ? _outgoingRow(- pendingById[message.id]!,- byId,- grouped: grouped.contains(message.id),- )- : 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,- ),+ time: time,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (time != null &&+ !DateUtils.isSameDay(+ time.toLocal(),+ previous?.createdAt?.toLocal(),+ ))+ _date(time),+ if (message.id == _unread.lineAt(c.selectedId))+ SuperTabNewMessagesLine(key: _unread.key),+ // 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: SuperTabMessageHighlight(+ on: message.id == _lit,+ child: pendingById.containsKey(message.id)+ ? _outgoingRow(+ pendingById[message.id]!,+ byId,+ grouped: grouped.contains(message.id),+ )+ : 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,+ ),+ ),),),- ),- ],+ ],+ ),);}@@ -3744,98 +3748,103 @@ class _SuperTabViewState extends State<SuperTabView>Expanded(child: Stack(children: [- NotificationListener<ScrollNotification>(- onNotification: (event) {- if (event.depth != 0) return false;- if (event is ScrollStartNotification &&- event.dragDetails != null) {- _scrollRequest++;- _jumpingToEnd = false;- }- if (_jumpingToEnd) return false;- final id = c.selectedId;- final atEnd = event.metrics.extentAfter < 40;- _follow(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) {- // A row still sending has no place in the transcript.- final sequence =- ownMessages.lastOrNull?.sequence ?? 0;- WidgetsBinding.instance.addPostFrameCallback((- _,- ) {- if (mounted && c.selectedId == id) {- _readToEnd(id, sequence);- }- });- }- return false;- },- child: SelectionArea(- child: CustomScrollView(- controller: _scroll[c.selectedId],- key: PageStorageKey(- 'super-messages-${c.tabId}-${c.selectedId}',- ),- // Pages read in grow upward from the rows first- // shown, new messages downward: no row on screen- // moves for either.- center: _newerRows,- slivers: [- // Its spinner runs only near the view.- SliverLayoutBuilder(- builder: (context, constraints) =>- SliverToBoxAdapter(- child: Padding(- padding: EdgeInsets.only(- top: grid.AppDesktop.controlGap,- ),- child: _earlierRow(- near:- constraints- .remainingCacheExtent >- 0,+ SuperTabStickyDay(+ pillKey: const ValueKey('super-day-pill'),+ hidden: finding != null,+ child: NotificationListener<ScrollNotification>(+ onNotification: (event) {+ if (event.depth != 0) return false;+ if (event is ScrollStartNotification &&+ event.dragDetails != null) {+ _scrollRequest++;+ _jumpingToEnd = false;+ }+ if (_jumpingToEnd) return false;+ final id = c.selectedId;+ final atEnd = event.metrics.extentAfter < 40;+ _follow(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) {+ // A row still sending has no place in the transcript.+ final sequence =+ ownMessages.lastOrNull?.sequence ?? 0;+ WidgetsBinding.instance.addPostFrameCallback((+ _,+ ) {+ if (mounted && c.selectedId == id) {+ _readToEnd(id, sequence);+ }+ });+ }+ return false;+ },+ child: SelectionArea(+ child: CustomScrollView(+ controller: _scroll[c.selectedId],+ key: PageStorageKey(+ 'super-messages-${c.tabId}-${c.selectedId}',+ ),+ // Pages read in grow upward from the rows first+ // shown, new messages downward: no row on screen+ // moves for either.+ center: _newerRows,+ slivers: [+ // Its spinner runs only near the view.+ SliverLayoutBuilder(+ builder: (context, constraints) =>+ SliverToBoxAdapter(+ child: Padding(+ padding: EdgeInsets.only(+ top: grid.AppDesktop.controlGap,+ ),+ child: _earlierRow(+ near:+ constraints+ .remainingCacheExtent >+ 0,+ ),),),- ),- ),- LaidOutSliverList(- delegate: SliverChildBuilderDelegate(- (context, index) =>- row(split - 1 - index),- childCount: split,- findChildIndexCallback: (key) =>- switch (rowOf(key)) {- final i? when i < split =>- split - 1 - i,- _ => null,- },),- ),- SliverPadding(- key: _newerRows,- padding: EdgeInsets.only(- bottom: grid.AppDesktop.controlGap,- ),- sliver: LaidOutSliverList(+ LaidOutSliverList(delegate: SliverChildBuilderDelegate(- // Messages on their way end the list.- (context, index) => row(split + index),- childCount: entries.length - split,+ (context, index) =>+ row(split - 1 - index),+ childCount: split,findChildIndexCallback: (key) =>switch (rowOf(key)) {- final i? when i >= split =>- i - split,+ final i? when i < split =>+ split - 1 - i,_ => null,},),),- ),- ],+ SliverPadding(+ key: _newerRows,+ padding: EdgeInsets.only(+ bottom: grid.AppDesktop.controlGap,+ ),+ sliver: LaidOutSliverList(+ delegate: SliverChildBuilderDelegate(+ // Messages on their way end the list.+ (context, index) =>+ row(split + index),+ childCount: entries.length - split,+ findChildIndexCallback: (key) =>+ switch (rowOf(key)) {+ final i? when i >= split =>+ i - split,+ _ => null,+ },+ ),+ ),+ ),+ ],+ ),),),),diff --git a/desktop/test/benchmarks/super_tab_chat_scroll_benchmark.dart b/desktop/test/benchmarks/super_tab_chat_scroll_benchmark.dartnew file mode 100644index 000000000..64678bba9--- /dev/null+++ b/desktop/test/benchmarks/super_tab_chat_scroll_benchmark.dart@@ -0,0 +1,105 @@+// Run explicitly: flutter test test/benchmarks/super_tab_chat_scroll_benchmark.dart --reporter expanded+// Headless CPU time of one scrolled frame of the Swarm chat (build, layout,+// paint and post-frame work, the day pill's measure included), not display+// latency. Compare runs on the same machine and workload only.+import 'dart:convert';++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/view.dart';++import '../support/super_tab_fixture.dart';+import 'swarm_benchmark.dart' show distribution;++const _updates = [+ 'Reading the offline queue before the reconnect.',+ 'The reconnect keeps every queued edit in order.',+ 'Two devices editing at once settle on the newest edit.',+ 'Pushed the branch; the checks are running.',+];++void main() {+ testWidgets('Swarm chat: one scrolled frame, 300 messages over 5 days', (+ tester,+ ) async {+ final server = ConversationServer();+ for (var i = 1; i <= 300; i++) {+ server.append('${_updates[i % _updates.length]} ($i)');+ server.messages.last+ ..['author'] = i.isEven+ ? const {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'}+ : const {'kind': 'person', 'id': 'owner', 'name': '[email protected]'}+ // 60 a day, at noon UTC: five local days in every zone.+ ..['createdAt'] = DateTime.utc(+ 2026,+ 10,+ 28 + (i - 1) ~/ 60,+ 12,+ ).toIso8601String();+ }+ final c = server.controller();+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final scroll = tester+ .widget<CustomScrollView>(+ find.byWidgetPredicate(+ (w) =>+ w is CustomScrollView &&+ '${(w.key as PageStorageKey?)?.value}'.startsWith(+ 'super-messages-',+ ),+ ),+ )+ .controller!;+ final bottom = scroll.position.pixels;++ // Back and forth over the newest 2400 px, across day lines: the same+ // frames on every run.+ var step = -40.0;+ Future<int> frame() async {+ var next = scroll.position.pixels + step;+ if (next < bottom - 2400 || next > bottom) {+ step = -step;+ next = scroll.position.pixels + step;+ }+ final watch = Stopwatch()..start();+ scroll.jumpTo(next);+ await tester.pump();+ return watch.elapsedMicroseconds;+ }++ for (var i = 0; i < 60; i++) {+ await frame();+ }+ final times = [for (var i = 0; i < 600; i++) await frame()];+ // ignore: avoid_print+ print(+ jsonEncode({+ 'benchmark': 'super_tab_chat_scroll_frame',+ 'messages': 300,+ ...distribution(times),+ }),+ );++ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });+}diff --git a/desktop/test/super_tab_day_pill_test.dart b/desktop/test/super_tab_day_pill_test.dartnew file mode 100644index 000000000..407621b3d--- /dev/null+++ b/desktop/test/super_tab_day_pill_test.dart@@ -0,0 +1,331 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.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 'package:harness/widgets/laid_out_list.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_DAY_PILL_SHOTS'];++const _updates = [+ 'Reading the offline queue before the reconnect.',+ 'The reconnect keeps every queued edit in order.',+ 'Two devices editing at once settle on the newest edit.',+ 'Pushed the branch; the checks are running.',+];++// Noon UTC: two different local days in every time zone the tests run in.+const _monday = '2026-11-02T12:00:00Z', _tuesday = '2026-11-03T12:00:00Z';+const _peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};+const _lead = {'kind': 'agent', 'id': 'lead-agent', 'name': 'Lead'};++const _chatPill = ValueKey('super-day-pill');+const _threadPill = ValueKey('super-thread-day-pill');++/// Two days of chat, and a thread whose root and first replies are from the+/// first day: Huy 11-03, the day stays at the top while scrolling, as Slack's.+ConversationServer _twoDays() {+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ server.append('Should we do thread replies?');+ server.messages.last['createdAt'] = _monday;+ for (var i = 1; i <= 24; i++) {+ server.append('${_updates[i % _updates.length]} ($i)');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = _peer+ ..['createdAt'] = i <= 12 ? _monday : _tuesday;+ }+ for (var i = 1; i <= 60; i++) {+ server.append('${_updates[i % _updates.length]} ($i)');+ server.messages.last+ ..['author'] = _lead+ ..['createdAt'] = i <= 30 ? _monday : _tuesday;+ }+ return server;+}++Widget _app(SuperTabController c, {Brightness? brightness, Key? picture}) =>+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness ?? Brightness.light),+ builder: (context, child) => RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ );++String _day(WidgetTester tester, String iso) =>+ MaterialLocalizations.of(tester.element(find.byType(SuperTabView)))+ .formatMediumDate(DateTime.parse(iso).toLocal());++/// What the pill under [key] says, or null when it is not shown.+String? _pill(WidgetTester tester, Key key) {+ final pill = find.byKey(key);+ if (pill.evaluate().isEmpty) return null;+ final text = find.descendant(of: pill, matching: find.byType(Text));+ return tester.widget<Text>(text.first).data;+}++ScrollController _chatScroll(WidgetTester tester) => tester+ .widget<CustomScrollView>(+ find.byWidgetPredicate(+ (w) =>+ w is CustomScrollView &&+ w.key is PageStorageKey &&+ '${(w.key as PageStorageKey).value}'.startsWith('super-messages-'),+ ),+ )+ .controller!;++ScrollController _threadScroll(WidgetTester tester) => tester+ .widget<ListView>(+ find.descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: find.byType(LaidOutListView),+ ),+ )+ .controller!;++Future<void> _scrollTo(+ WidgetTester tester,+ ScrollController scroll,+ double pixels,+) async {+ scroll.jumpTo(pixels);+ await tester.pump();+ await tester.pump();+}++double _topOf(WidgetTester tester, String text) =>+ tester.getTopLeft(find.text(text, findRichText: true).first).dy;++String _textOf(Widget widget) => switch (widget) {+ Text(:final data?) => data,+ RichText(:final text) => text.toPlainText(),+ _ => '',+};++/// Some message row's text in view, below the top [margin] of the screen.+String _rowInView(WidgetTester tester, {double margin = 200}) {+ final rows = find.textContaining(RegExp(r'\(\d+\)$'), findRichText: true);+ for (final element in rows.evaluate()) {+ final text = _textOf(element.widget);+ final box = element.renderObject;+ if (box is! RenderBox || !box.attached || text.isEmpty) continue;+ final top = box.localToGlobal(Offset.zero).dy;+ if (top > margin &&+ top < 600 &&+ find.text(text, findRichText: true).evaluate().length == 1) {+ return text;+ }+ }+ throw StateError('no message row in view');+}++Future<void> _open(+ WidgetTester tester,+ SuperTabController c, {+ Brightness? brightness,+ Key? picture,+}) async {+ await c.refresh();+ if (brightness != null) {+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ }+ await tester.binding.setSurfaceSize(const Size(1400, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(_app(c, brightness: brightness, picture: picture));+ await tester.pumpAndSettle();+}++/// Scrolls [scroll] toward its start in 40-pixel steps until the pill under+/// [key] says [day]; how far it went.+Future<double> _scrollBackTo(+ WidgetTester tester,+ ScrollController scroll,+ Key key,+ String day,+) async {+ final start = scroll.position.pixels;+ while (_pill(tester, key) != day &&+ scroll.position.pixels - 40 > scroll.position.minScrollExtent) {+ await _scrollTo(tester, scroll, scroll.position.pixels - 40);+ }+ return start - scroll.position.pixels;+}++void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ testWidgets("the chat keeps the top message's day in a pill while "+ 'scrolling', (tester) async {+ final c = _twoDays().controller();+ addTearDown(c.dispose);+ await _open(tester, c);++ // At the newest message, Tuesday's rows fill the view.+ final tuesday = _day(tester, _tuesday), monday = _day(tester, _monday);+ expect(_pill(tester, _chatPill), tuesday);++ // Back into Monday: the pill follows the message at the top.+ final scroll = _chatScroll(tester);+ expect(await _scrollBackTo(tester, scroll, _chatPill, monday), isPositive);+ expect(_pill(tester, _chatPill), monday);++ // The pill floats over the list: a row moves exactly as far as the+ // list scrolls, and nothing is inserted above it.+ final row = _rowInView(tester), before = _topOf(tester, row);+ await _scrollTo(tester, scroll, scroll.position.pixels - 40);+ expect(_topOf(tester, row) - before, moreOrLessEquals(40, epsilon: .5));++ // And back down to Tuesday, it says Tuesday again.+ while (_pill(tester, _chatPill) != tuesday &&+ scroll.position.extentAfter > 0) {+ await _scrollTo(tester, scroll, scroll.position.pixels + 40);+ }+ expect(_pill(tester, _chatPill), tuesday);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ });++ testWidgets("the thread keeps the top reply's day in a pill while "+ 'scrolling, and none at its start', (tester) async {+ final c = _twoDays().controller();+ addTearDown(c.dispose);+ await _open(tester, c);+ c.openThread('message-1');+ await tester.pumpAndSettle();++ final tuesday = _day(tester, _tuesday), monday = _day(tester, _monday);+ expect(_pill(tester, _threadPill), tuesday);++ final scroll = _threadScroll(tester);+ expect(+ await _scrollBackTo(tester, scroll, _threadPill, monday),+ isPositive,+ );+ expect(_pill(tester, _threadPill), monday);++ // At the root, nothing is hidden above: no pill. Scrolling on shows it+ // over the list, which does not move for it.+ await _scrollTo(tester, scroll, scroll.position.minScrollExtent);+ expect(_pill(tester, _threadPill), isNull);+ const root = 'Should we do thread replies?';+ final threadRoot = find.descendant(+ of: find.byKey(const ValueKey('super-thread-panel')),+ matching: find.text(root),+ );+ final before = tester.getTopLeft(threadRoot).dy;+ await _scrollTo(tester, scroll, scroll.position.minScrollExtent + 30);+ expect(_pill(tester, _threadPill), monday);+ expect(+ tester.getTopLeft(threadRoot).dy - before,+ moreOrLessEquals(-30, epsilon: .5),+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ });++ testWidgets('the pill gives the top to "Finding the original message…" '+ 'and comes back after', (tester) async {+ // 250 notes from one day; the last replies to one pages back.+ final server = ConversationServer();+ for (var i = 1; i <= 250; i++) {+ server.append('Note $i');+ }+ server.messages.last['replyTo'] = 'message-10';+ final c = server.controller();+ addTearDown(c.dispose);+ await _open(tester, c);+ final day = _day(tester, '2026-10-18T00:00:00Z');+ expect(_pill(tester, _chatPill), day);++ server.holdReads = Completer<void>();+ await tester.tap(+ find.descendant(+ of: find.byKey(const ValueKey('super-message-message-250')),+ matching: find.byType(SuperTabReplyPreview),+ ),+ );+ await tester.pump();+ await tester.pump();+ expect(find.byKey(const ValueKey('super-reply-finding')), findsOneWidget);+ expect(_pill(tester, _chatPill), isNull);++ server.holdReads!.complete();+ server.holdReads = null;+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-reply-finding')), findsNothing);+ expect(_pill(tester, _chatPill), day);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final c = _twoDays().controller();+ addTearDown(c.dispose);+ await _open(tester, c, brightness: brightness, picture: picture);+ c.openThread('message-1');+ await tester.pumpAndSettle();+ final monday = _day(tester, _monday);+ // The chat back until Monday's last message is in its upper part, the+ // thread at Tuesday's replies: the same place on main, with no pill.+ final scroll = _chatScroll(tester);+ const lastMonday =+ 'Two devices editing at once settle on the newest edit. (30)';+ final row = find.text(lastMonday, findRichText: true);+ // Rows above the view are built too: scroll until it is well inside.+ while ((row.evaluate().isEmpty ||+ tester.getTopLeft(row.first).dy < 250) &&+ scroll.position.pixels - 40 > scroll.position.minScrollExtent) {+ await _scrollTo(tester, scroll, scroll.position.pixels - 40);+ }+ await tester.pumpAndSettle();++ // Written before the checks, so main's run writes the "before" image.+ if (shots != null) {+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/day-pill-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ expect(_pill(tester, _chatPill), monday);+ expect(_pill(tester, _threadPill), _day(tester, _tuesday));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ });+ }+}