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.

Web: a Super Tab draws its last view at once, then reads (#180 fix 4) (#1723)

Jacob Pham7754ca93c4f2
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 5c47e24df..039800925 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -1,12 +1,15 @@
import 'dart:async';
import 'dart:convert';
+import 'package:clock/clock.dart';
+
import '../core/local_key_value_store.dart';
import 'attachment_upload.dart';
import 'controller.dart';
import 'model.dart';
import 'notifications.dart';
import 'reading.dart';
+import 'saved_view.dart';
typedef SuperTabTransport = Future<Object?> Function(
String method,
@@ -93,9 +96,42 @@ class SuperTabClient {
bool _isAway(String id) => !_pageVisible || id != _shown;
+ late final _views = SuperTabSavedViews(storage);
+ final _viewSaves = <String, Timer>{};
+ final _viewSavedAt = <String, DateTime>{};
+
+ /// How often a Swarm's view may be written while it keeps changing: each
+ /// write is a few hundred KB into the browser's storage.
+ static const _viewSaveEvery = Duration(seconds: 15);
+
+ void _saveViewSoon(String id) {
+ if (_viewSaves.containsKey(id)) return;
+ final last = _viewSavedAt[id];
+ final since = last == null ? _viewSaveEvery : clock.now().difference(last);
+ _viewSaves[id] = Timer(
+ since >= _viewSaveEvery ? Duration.zero : _viewSaveEvery - since,
+ () => _saveView(id),
+ );
+ }
+
+ void _saveView(String id) {
+ _viewSaves.remove(id)?.cancel();
+ final account = _account;
+ final view = _loaded[id]?.savedView;
+ if (account == null || view == null) return;
+ _viewSavedAt[id] = clock.now();
+ unawaited(_views.write(account, id, view).catchError((Object _) {}));
+ }
+
void _applyAway() {
for (final entry in _loaded.entries) {
- entry.value.away = _isAway(entry.key);
+ final away = _isAway(entry.key);
+ // Going away: what changed since the last write is kept now.
+ if (away && _viewSaves.containsKey(entry.key)) _saveView(entry.key);
+ // Back on screen, the Swarm reads its own tags: the count discovery
+ // kept while it was away is stale from now on.
+ if (!away && entry.value.away) _tagCounts.remove(entry.key);
+ entry.value.away = away;
}
}
@@ -151,6 +187,13 @@ class SuperTabClient {
void bind(String? account) {
if (_account == account) return;
+ // Nothing of an account that left stays on this device.
+ if (_account case final left?) unawaited(_views.forgetAccount(left));
+ for (final timer in _viewSaves.values) {
+ timer.cancel();
+ }
+ _viewSaves.clear();
+ _viewSavedAt.clear();
_account = account;
_generation++;
_discoveryTimer?.cancel();
@@ -354,6 +397,14 @@ class SuperTabClient {
var seenRevision = -1;
var seenSelected = controller.selectedId;
controller.addListener(() {
+ if (_reading.drawsSaved && generation == _generation) {
+ if (controller.accessRevoked) {
+ _viewSaves.remove(id)?.cancel();
+ unawaited(_views.forget(account, id));
+ } else if (!controller.showingSaved) {
+ _saveViewSoon(id);
+ }
+ }
if (controller.selectedId != seenSelected) {
seenSelected = controller.selectedId;
onSelection?.call(controller);
@@ -370,6 +421,14 @@ class SuperTabClient {
_tagCounts.remove(id);
_loaded[id] = controller;
controller.start();
+ // After the first read is asked for: reading and drawing a saved view
+ // takes the main thread a moment a phone's first read need not wait on.
+ if (_reading.drawsSaved) {
+ final view = await _views.read(account, id);
+ if (view != null && generation == _generation) {
+ controller.drawSaved(view);
+ }
+ }
return controller;
}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index f0236bd02..320534f9e 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -149,6 +149,14 @@ class SuperTabController extends ChangeNotifier {
/// The state last drawn, while the reading adapts ([_read]).
Map<String, dynamic>? _shownState;
+ /// The rows each conversation's messages were read from, kept only to save
+ /// the view ([SuperTabReading.drawsSaved]).
+ final _rows = <String, Map<String, Map<String, dynamic>>>{};
+
+ /// A saved view is on screen and no read has replaced it yet.
+ bool get showingSaved => _showingSaved;
+ bool _showingSaved = false;
+
/// The last time the person did something here, or a new message reached
/// the open conversation: what keeps the full poll ([SuperTabReading.quietPoll]).
DateTime _lastActivity = clock.now();
@@ -429,6 +437,85 @@ class SuperTabController extends ChangeNotifier {
void _acted() => _lastActivity = clock.now();
+ void _keepRows(String id, List rows) {
+ if (!_policy.drawsSaved) return;
+ final kept = _rows[id] ??= {};
+ for (final row in rows) {
+ final map = superTabMap(row);
+ kept[map['id'] as String] = map;
+ }
+ }
+
+ /// The view to keep on this device ([SuperTabReading.drawsSaved]): the
+ /// state as last read and the open conversation's last page, or null.
+ Map<String, dynamic>? get savedView {
+ final state = _shownState;
+ if (!_policy.drawsSaved || state == null || accessRevoked) return null;
+ final id = selectedId;
+ final shown = _messages[id] ?? const <SuperTabMessage>[];
+ final page = shown.length > _savedPage
+ ? shown.sublist(shown.length - _savedPage)
+ : shown;
+ final rows = [for (final message in page) ?_rows[id]?[message.id]];
+ return {
+ 'revision': revision,
+ 'state': state,
+ 'conversationId': id,
+ 'messages': rows,
+ 'next': page.length < shown.length ? page.first.sequence : _before[id],
+ };
+ }
+
+ /// A conversation's page as the backend reads it.
+ static const _savedPage = 100;
+
+ /// Draws a [savedView] kept from an earlier visit while the first read is
+ /// on its way: that read replaces it. One for another Swarm, one that no
+ /// longer parses, or one after a read has landed, draws nothing.
+ void drawSaved(Map<String, dynamic> view) {
+ if (!_policy.drawsSaved || snapshot != null || stateReads > 0) return;
+ try {
+ final state = superTabMap(view['state']);
+ final saved = SuperTabSnapshot.fromJson(state);
+ if (saved.id != tabId) return;
+ final id = view['conversationId'];
+ final rows = [
+ for (final row in view['messages'] as List? ?? const [])
+ superTabMap(row),
+ ];
+ final messages = rows.map(SuperTabMessage.fromJson).toList();
+ final revisionSaved = (view['revision'] as num).toInt();
+ snapshot = saved;
+ revision = revisionSaved;
+ _shownState = state;
+ if (id == selectedId &&
+ saved.conversation(id as String) != null &&
+ messages.every((m) => m.conversationId == id)) {
+ _messages[id] = messages
+ ..sort((a, b) => a.sequence.compareTo(b.sequence));
+ _keepRows(id, rows);
+ _before[id] = (view['next'] as num?)?.toInt();
+ }
+ _showingSaved = true;
+ loading = false;
+ if (_startedAt != null) _changed();
+ } on FormatException {
+ _dropSaved();
+ } on TypeError {
+ _dropSaved();
+ }
+ }
+
+ /// A view from an older shape: draw nothing, read as usual.
+ void _dropSaved() {
+ snapshot = null;
+ revision = -1;
+ _shownState = null;
+ _messages.clear();
+ _rows.clear();
+ _before.clear();
+ }
+
/// A machine able to serve Swarm reads just connected: read now instead of
/// at the next poll ([SuperTabReading.readsOnConnect]). Joins a read under way.
Future<void> machineAvailable() {
@@ -627,6 +714,7 @@ class SuperTabController extends ChangeNotifier {
(id) => !next.projects.any((project) => project.id == id),
);
_messages.removeWhere((id, _) => !allowed.contains(id));
+ _rows.removeWhere((id, _) => !allowed.contains(id));
_drafts.removeWhere((id, _) => !allowed.contains(id));
_attachments.removeWhere((id, files) {
if (allowed.contains(id)) return false;
@@ -655,6 +743,11 @@ class SuperTabController extends ChangeNotifier {
? (query: earlyQuery!, page: early)
: null,
));
+ if (_showingSaved) {
+ // Read now: the saved view, and its Updating line, give way.
+ _showingSaved = false;
+ stateChanged = true;
+ }
} catch (failure) {
if (_inConnectGrace(failure)) {
_waitingForMachine = true;
@@ -693,7 +786,7 @@ class SuperTabController extends ChangeNotifier {
/// ([SuperTabReading.connectGrace]) runs out: its error waits for the grace.
bool _inConnectGrace(Object failure) {
final since = _startedAt;
- if (snapshot != null ||
+ if (stateReads > 0 ||
since == null ||
failure is! SuperTabFailure ||
failure.code != 'MACHINE_UNAVAILABLE') {
@@ -736,6 +829,9 @@ class SuperTabController extends ChangeNotifier {
/// shown, what came after the newest, or the latest page.
String _query(String id, {bool older = false}) {
if (older) return '?before=${_before[id]}';
+ // 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 '';
final tail = _messages[id]?.lastOrNull?.sequence;
return tail != null ? '?after=$tail' : '';
}
@@ -832,6 +928,7 @@ class SuperTabController extends ChangeNotifier {
if (incoming.any((m) => m.conversationId != id)) {
throw const FormatException('A different conversation was returned.');
}
+ _keepRows(id, answer['messages'] as List);
final combined = {
for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,
for (final m in incoming) m.id: m,
@@ -877,6 +974,7 @@ class SuperTabController extends ChangeNotifier {
for (final row in rows) {
combined[row.id] = row;
}
+ _keepRows(id, receipt['messages'] as List);
}
final next = combined.values.toList()
..sort((a, b) => a.sequence.compareTo(b.sequence));
@@ -890,7 +988,8 @@ class SuperTabController extends ChangeNotifier {
if (arrived && id == selectedId) _acted();
if (!same) _changed();
} catch (failure) {
- _readFailure(failure, revokeTab: false);
+ // The state read waits for a machine within the grace: so do these.
+ if (!_inConnectGrace(failure)) _readFailure(failure, revokeTab: false);
if (failure is SuperTabFailure &&
const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
_messages.remove(id);
diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dart
index ea88ea27f..b3dbfd1b7 100644
--- a/desktop/lib/super_tabs/reading.dart
+++ b/desktop/lib/super_tabs/reading.dart
@@ -11,6 +11,7 @@ class SuperTabReading {
this.readsOnConnect = false,
this.connectGrace = Duration.zero,
this.messagesWithState = false,
+ this.drawsSaved = false,
});
/// Null keeps a full read every poll. Otherwise, once the open conversation
@@ -37,6 +38,11 @@ class SuperTabReading {
/// state read, instead of after it.
final bool messagesWithState;
+ /// True keeps the last view of each Swarm as read on this device and draws
+ /// it at once on the next open, until the first read replaces it
+ /// (`SuperTabSavedViews`).
+ final bool drawsSaved;
+
/// Whether the poll adapts at all; false is Desktop's fixed period.
bool get adapts => quietPoll != null || pausesAway;
}
diff --git a/desktop/lib/super_tabs/saved_view.dart b/desktop/lib/super_tabs/saved_view.dart
new file mode 100644
index 000000000..f7b8c1fc7
--- /dev/null
+++ b/desktop/lib/super_tabs/saved_view.dart
@@ -0,0 +1,119 @@
+import 'dart:convert';
+
+import '../core/local_key_value_store.dart';
+
+/// The last view of a Swarm tab as read: the state the tab draws and the open
+/// conversation's last page, kept on this device so the next open draws it at
+/// once and reads after ([SuperTabReading.drawsSaved]; the web, where that
+/// first read is seconds away). One per account and tab, a few per account,
+/// none over [maxBytes], and none of what the tab never shows.
+class SuperTabSavedViews {
+ SuperTabSavedViews(this.storage, {this.maxBytes = 512 * 1024});
+
+ final LocalKeyValueStore storage;
+ final int maxBytes;
+
+ /// How many Swarms an account keeps a view of, most recently used first.
+ static const maxTabs = 3;
+
+ /// What `SuperTabSnapshot.fromJson` reads: everything else in a state is
+ /// never drawn, so it is never kept (agent starts carry their tasks).
+ static const _drawn = {
+ 'version',
+ 'id',
+ 'name',
+ 'ownerId',
+ 'paused',
+ 'project',
+ 'people',
+ 'agents',
+ 'machines',
+ 'conversations',
+ 'invitations',
+ 'leadsConversationId',
+ 'localModels',
+ 'mentionsWaiting',
+ 'projects',
+ };
+
+ String _key(String account, String tabId) => 'super_tab.view.$account.$tabId';
+ String _index(String account) => 'super_tab.views.$account';
+
+ Future<List<String>> _tabs(String account) async {
+ try {
+ final raw = await storage.read(_index(account));
+ return raw == null
+ ? <String>[]
+ : (jsonDecode(raw) as List).whereType<String>().toList();
+ } on FormatException {
+ return <String>[];
+ }
+ }
+
+ Future<void> _use(String account, String tabId) async {
+ final tabs = (await _tabs(account))..remove(tabId);
+ tabs.insert(0, tabId);
+ for (final gone in tabs.skip(maxTabs)) {
+ await storage.delete(_key(account, gone));
+ }
+ await storage.write(
+ _index(account),
+ jsonEncode(tabs.take(maxTabs).toList()),
+ );
+ }
+
+ /// The view saved for [tabId], or null: none, unreadable, or another shape.
+ Future<Map<String, dynamic>?> read(String account, String tabId) async {
+ final raw = await storage.read(_key(account, tabId));
+ if (raw == null) return null;
+ try {
+ final view = jsonDecode(raw);
+ if (view is! Map<String, dynamic> ||
+ view['state'] is! Map<String, dynamic> ||
+ view['revision'] is! int) {
+ return null;
+ }
+ await _use(account, tabId);
+ return view;
+ } on FormatException {
+ return null;
+ }
+ }
+
+ /// Keeps [view] for [tabId]; one over the cap is not kept, and the older
+ /// one goes with it rather than staying behind, older still.
+ Future<void> write(
+ String account,
+ String tabId,
+ Map<String, dynamic> view,
+ ) async {
+ final state = view['state'] as Map<String, dynamic>;
+ final text = jsonEncode({
+ ...view,
+ 'state': {
+ for (final entry in state.entries)
+ if (_drawn.contains(entry.key)) entry.key: entry.value,
+ },
+ });
+ if (utf8.encode(text).length > maxBytes) {
+ await forget(account, tabId);
+ return;
+ }
+ await storage.write(_key(account, tabId), text);
+ await _use(account, tabId);
+ }
+
+ Future<void> forget(String account, String tabId) async {
+ await storage.delete(_key(account, tabId));
+ final tabs = (await _tabs(account))..remove(tabId);
+ await storage.write(_index(account), jsonEncode(tabs));
+ }
+
+ /// Signing out, or another account: nothing of this one stays behind.
+ Future<void> forgetAccount(String account) async {
+ for (final tab in await _tabs(account)) {
+ await storage.delete(_key(account, tab));
+ }
+ await storage.delete(_index(account));
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 32a1518b0..d42d4dea1 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -861,6 +861,26 @@ class _SuperTabViewState extends State<SuperTabView>
bool get _terminalsVisible =>
!_devicesVisible && (widget.terminalsVisible || widget.terminal != null);
+ /// The open conversation's name, or what the pane shows instead of one.
+ Widget _title(SuperTabConversation? group) => Text(
+ _devicesVisible
+ ? 'Your devices'
+ : _notificationsVisible
+ ? 'Notifications'
+ : group == null
+ ? c.snapshot?.projects.isEmpty == true
+ ? c.snapshot!.name
+ : 'Choose a project'
+ : c.snapshot!.isProjectLead(group.id)
+ ? c.snapshot!.projectFor(group.id)!.name
+ : group.id == c.snapshot!.leadsConversationId
+ ? 'Product Managers'
+ : group.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(medium: true),
+ );
+
Widget _header(SuperTabConversation? group, bool narrow, bool showRoster) =>
Container(
constraints: const BoxConstraints(minHeight: 52),
@@ -883,24 +903,22 @@ class _SuperTabViewState extends State<SuperTabView>
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
- Text(
- _devicesVisible
- ? 'Your devices'
- : _notificationsVisible
- ? 'Notifications'
- : group == null
- ? c.snapshot?.projects.isEmpty == true
- ? c.snapshot!.name
- : 'Choose a project'
- : c.snapshot!.isProjectLead(group.id)
- ? c.snapshot!.projectFor(group.id)!.name
- : group.id == c.snapshot!.leadsConversationId
- ? 'Product Managers'
- : group.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.text(medium: true),
- ),
+ // A view saved on this device, until the first read
+ // replaces it ([SuperTabReading.drawsSaved]).
+ if (c.showingSaved)
+ Row(
+ children: [
+ Flexible(child: _title(group)),
+ const SizedBox(width: 8),
+ Text(
+ 'Updating…',
+ key: const ValueKey('super-updating'),
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ )
+ else
+ _title(group),
if (!_devicesVisible && !_notificationsVisible)
if (c.reviewLine(group) case final line?)
Text(
diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dart
index 47b0b9481..f72bb857c 100644
--- a/desktop/lib/web/shell/web_chrome.dart
+++ b/desktop/lib/web/shell/web_chrome.dart
@@ -46,12 +46,14 @@ WorkspaceChrome _webWorkspaceChrome(AppNotifier app) => WorkspaceChrome(
superTabRecovers: true,
// A phone pays for every read: poll the Swarm on screen only, slow it while
// the conversation is quiet, read when a machine connects instead of at the
- // next poll, and ask for the saved conversation beside the first state.
+ // next poll, ask for the saved conversation beside the first state, and
+ // draw the last view kept on this device while the first read is on its way.
superTabReading: const SuperTabReading(
quietPoll: Duration(seconds: 15),
pausesAway: true,
readsOnConnect: true,
connectGrace: Duration(seconds: 10),
messagesWithState: true,
+ drawsSaved: true,
),
);
diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dart
index f78203fbe..cda75fcc7 100644
--- a/desktop/test/super_tab_reading_client_test.dart
+++ b/desktop/test/super_tab_reading_client_test.dart
@@ -201,6 +201,32 @@ void main() {
});
});
+ test('web: a tag marked done while shown does not come back on leaving', () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final client = _client(backend, reading: _web)..bind('owner');
+ final other = backend.servers['other']!..append('Please confirm.');
+ other.tag(other.messages.last['id'] as String);
+ client.show('tab');
+ client.open('tab');
+ client.open('other');
+ async.elapse(const Duration(seconds: 20));
+ expect(client.waitingTags('other'), 1);
+ client.show('other');
+ async.flushMicrotasks();
+ // Marked done on screen: the Swarm's own read says none wait.
+ other.mentions.single['resolvedAt'] = '2026-10-26T06:00:00Z';
+ other.state['mentionsWaiting'] = 0;
+ other.revision++;
+ async.elapse(const Duration(seconds: 3));
+ expect(client.waitingTags('other'), 0);
+ client.show('tab');
+ async.flushMicrotasks();
+ expect(client.waitingTags('other'), 0);
+ client.dispose();
+ });
+ });
+
test('Desktop reading: a connect waits for the poll, every tab polls', () {
fakeAsync((async) {
final backend = _Backend()..machine = false;
diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dart
new file mode 100644
index 000000000..84d2dac2c
--- /dev/null
+++ b/desktop/test/super_tab_saved_view_test.dart
@@ -0,0 +1,532 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/client.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/reading.dart';
+import 'package:harness/super_tabs/saved_view.dart';
+
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+/// A view as a controller hands it over: the state as read, the open
+/// conversation and its last page.
+Map<String, dynamic> _view({String tab = 'tab', int pad = 0}) {
+ final server = ConversationServer()..append('Hello');
+ server.state['id'] = tab;
+ server.state['starts'] = [
+ {
+ 'id': 'start',
+ 'request': {'task': 'A task the page never draws.'},
+ },
+ ];
+ if (pad > 0) server.state['name'] = 'x' * pad;
+ return {
+ 'revision': 7,
+ 'state': server.state,
+ 'conversationId': 'lead',
+ 'messages': server.messages,
+ 'next': null,
+ };
+}
+
+void main() {
+ group('a controller', _controllerTests);
+ group('the client', _clientTests);
+
+ test('keeps what the Swarm draws, not what it never shows', () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store);
+ await views.write('owner', 'tab', _view());
+ final read = (await views.read('owner', 'tab'))!;
+ expect(read['revision'], 7);
+ expect(read['conversationId'], 'lead');
+ expect((read['messages'] as List).single['text'], 'Hello');
+ final state = read['state'] as Map<String, dynamic>;
+ expect(state['name'], 'Pilot');
+ expect(state.containsKey('starts'), isFalse);
+ expect(store.values.values.join(), isNot(contains('never draws')));
+ });
+
+ test('a view over the size cap is not kept, and an older one goes', () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store, maxBytes: 4096);
+ await views.write('owner', 'tab', _view());
+ expect(await views.read('owner', 'tab'), isNotNull);
+ await views.write('owner', 'tab', _view(pad: 8000));
+ expect(await views.read('owner', 'tab'), isNull);
+ expect(
+ store.values.values.every((v) => utf8.encode(v).length <= 4096),
+ isTrue,
+ );
+ });
+
+ test('an account keeps its three most recent Swarms', () async {
+ final views = SuperTabSavedViews(MemoryStore());
+ for (final tab in ['a', 'b', 'c', 'd']) {
+ await views.write('owner', tab, _view(tab: tab));
+ }
+ expect(await views.read('owner', 'a'), isNull);
+ for (final tab in ['b', 'c', 'd']) {
+ expect(await views.read('owner', tab), isNotNull, reason: tab);
+ }
+ // Reading one makes it the most recent.
+ await views.read('owner', 'b');
+ await views.write('owner', 'e', _view(tab: 'e'));
+ expect(await views.read('owner', 'c'), isNull);
+ expect(await views.read('owner', 'b'), isNotNull);
+ });
+
+ test(
+ 'views are per account, and forgetting an account clears its own',
+ () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store);
+ await views.write('owner', 'tab', _view());
+ await views.write('other', 'tab', _view());
+ expect(await views.read('stranger', 'tab'), isNull);
+ await views.forgetAccount('owner');
+ expect(await views.read('owner', 'tab'), isNull);
+ expect(await views.read('other', 'tab'), isNotNull);
+ expect(store.values.keys.where((k) => k.contains('owner')), isEmpty);
+ },
+ );
+
+ test('a lost Swarm is forgotten; a view it cannot read is none', () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store);
+ await views.write('owner', 'tab', _view());
+ await views.forget('owner', 'tab');
+ expect(await views.read('owner', 'tab'), isNull);
+ await store.write('super_tab.view.owner.tab', '{not json');
+ expect(await views.read('owner', 'tab'), isNull);
+ });
+}
+
+const _web = SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ readsOnConnect: true,
+ connectGrace: Duration(seconds: 10),
+ messagesWithState: true,
+ drawsSaved: true,
+);
+
+/// Every GET the controller made, answered by [server] unless [missing].
+class _Reads {
+ _Reads(this.server);
+ final ConversationServer server;
+ final paths = <String>[];
+ bool missing = false;
+ Future<Map<String, dynamic>> call(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) {
+ if (method == 'GET') paths.add(path);
+ if (missing) {
+ return Future.error(
+ const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'Connect one of your machines to open Swarm.',
+ ),
+ );
+ }
+ return server.request(method, path, body: body);
+ }
+}
+
+SuperTabController _controller(
+ _Reads reads, {
+ SuperTabReading reading = _web,
+ String selected = 'lead',
+}) => SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: reads.call,
+ save: reads.server.save,
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': selected},
+ reading: reading,
+);
+
+/// What a controller that read [server] once would save.
+Map<String, dynamic> _saved(ConversationServer server) {
+ late Map<String, dynamic> view;
+ fakeAsync((async) {
+ final c = _controller(_Reads(server))..start();
+ async.flushMicrotasks();
+ view = c.savedView!;
+ c.dispose();
+ });
+ return jsonDecode(jsonEncode(view)) as Map<String, dynamic>;
+}
+
+void _controllerTests() {
+ test('a saved view draws at once, then the first read replaces it', () {
+ final server = ConversationServer()..append('Please start.');
+ server.messages.first['deliveries'] = [
+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'claimed'},
+ ];
+ final view = _saved(server);
+ fakeAsync((async) {
+ server
+ ..messages.first['deliveries'] = [
+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'delivered'},
+ ]
+ ..append('Done.')
+ ..holdReads = Completer<void>();
+ final reads = _Reads(server);
+ final c = _controller(reads)..drawSaved(view);
+ expect(c.snapshot!.name, 'Pilot');
+ expect(c.messages('lead').single.text, 'Please start.');
+ expect(c.showingSaved, isTrue);
+ expect(c.loading, isFalse);
+ c.start();
+ async.flushMicrotasks();
+ expect(c.loading, isFalse);
+ // The state and the latest page: receipts and new messages in one read.
+ expect(reads.paths, [
+ '/api/super-tabs/tab/conversations/lead/messages',
+ '/api/super-tabs/tab',
+ ]);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(c.showingSaved, isFalse);
+ expect(c.messages('lead').map((m) => m.text), ['Please start.', 'Done.']);
+ expect(c.messages('lead').first.deliveries.single['status'], 'delivered');
+ c.dispose();
+ });
+ });
+
+ test('a saved view of another conversation draws the state only', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ final c = _controller(_Reads(server), selected: 'offline')
+ ..drawSaved(view);
+ expect(c.snapshot, isNotNull);
+ expect(c.messages('offline'), isEmpty);
+ expect(c.messages('lead'), isEmpty);
+ c.dispose();
+ });
+ });
+
+ test('a saved view of another Swarm, or a broken one, draws nothing', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ final other = SuperTabController(
+ tabId: 'other',
+ accountId: 'owner',
+ request: _Reads(server).call,
+ save: server.save,
+ reading: _web,
+ )..drawSaved(view);
+ expect(other.snapshot, isNull);
+ final broken = _controller(_Reads(server))
+ ..drawSaved({
+ ...view,
+ 'state': {'id': 'tab'},
+ });
+ expect(broken.snapshot, isNull);
+ expect(broken.showingSaved, isFalse);
+ other.dispose();
+ broken.dispose();
+ });
+ });
+
+ test('with no machine yet the saved view stays, without the error', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ final reads = _Reads(server)..missing = true;
+ final c = _controller(reads)
+ ..drawSaved(view)
+ ..start();
+ async.elapse(const Duration(seconds: 9));
+ expect(c.error, isNull);
+ expect(c.messages('lead').single.text, 'Hello');
+ expect(c.showingSaved, isTrue);
+ reads.missing = false;
+ unawaited(c.machineAvailable());
+ async.flushMicrotasks();
+ expect(c.showingSaved, isFalse);
+ c.dispose();
+ });
+ });
+
+ test('Desktop reading keeps no saved view and draws none', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server);
+ fakeAsync((async) {
+ final c = _controller(_Reads(server), reading: const SuperTabReading())
+ ..drawSaved(view);
+ expect(c.snapshot, isNull);
+ c.start();
+ async.flushMicrotasks();
+ expect(c.savedView, isNull);
+ c.dispose();
+ });
+ });
+}
+
+/// One Swarm behind a transport that may hold its answers.
+class _Transport {
+ _Transport(this.server);
+ final ConversationServer server;
+ Completer<void>? hold;
+ SuperTabFailure? refuse;
+ Future<Object?> call(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (hold case final wait?) await wait.future;
+ if (refuse case final failure?) throw failure;
+ if (Uri.parse(path).path == '/api/super-tabs') {
+ return {
+ 'tabs': [
+ {'id': 'tab', 'name': 'Pilot'},
+ ],
+ 'next': null,
+ };
+ }
+ return server.request(method, path, body: body);
+ }
+}
+
+/// When the saved view is read, among the requests a test records.
+class _OrderStore extends MemoryStore {
+ final order = <String>[];
+
+ /// How long reading the saved view takes, as a slow device's storage.
+ Duration viewDelay = Duration.zero;
+ @override
+ Future<String?> read(String key) async {
+ if (key == _viewKey) {
+ order.add('view');
+ if (viewDelay > Duration.zero) await Future<void>.delayed(viewDelay);
+ }
+ return super.read(key);
+ }
+}
+
+/// Writes to the saved views, by key.
+class _CountingStore extends MemoryStore {
+ final writes = <String>[];
+ @override
+ Future<void> write(String key, String value) {
+ writes.add(key);
+ return super.write(key, value);
+ }
+}
+
+SuperTabClient _client(
+ _Transport transport,
+ MemoryStore store, {
+ SuperTabReading reading = _web,
+}) => SuperTabClient(
+ transport: transport.call,
+ storage: store,
+ discoveryInterval: Duration.zero,
+)..reading = reading;
+
+const _viewKey = 'super_tab.view.owner.tab';
+
+void _clientTests() {
+ test('the next open draws the saved view before anything answers', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ final first = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ first.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ first.show(null);
+ async.flushMicrotasks();
+ expect(store.values[_viewKey], isNotNull);
+ // A reload: a new client, on the same device, whose reads are slow.
+ final transport = _Transport(server)..hold = Completer<void>();
+ final second = _client(transport, store)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ second.open('tab').then((opened) => c = opened);
+ async.flushMicrotasks();
+ expect(c!.messages('lead').single.text, 'Hello');
+ expect(c!.showingSaved, isTrue);
+ transport.hold!.complete();
+ transport.hold = null;
+ async.flushMicrotasks();
+ expect(c!.showingSaved, isFalse);
+ first.dispose();
+ second.dispose();
+ });
+ });
+
+ test('a busy Swarm saves at most every 15 s, and at once on going away', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _CountingStore();
+ final client = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ store.writes.clear();
+ for (var i = 0; i < 20; i++) {
+ server.append('Update $i');
+ async.elapse(const Duration(seconds: 3));
+ }
+ expect(
+ store.writes.where((k) => k == _viewKey).length,
+ inInclusiveRange(4, 5),
+ );
+ store.writes.clear();
+ server.append('Last one.');
+ async.elapse(const Duration(seconds: 3));
+ client.show(null);
+ async.flushMicrotasks();
+ expect(store.writes, contains(_viewKey));
+ expect(store.values[_viewKey], contains('Last one.'));
+ client.dispose();
+ });
+ });
+
+ test('the first read is asked for before the saved view is read', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _OrderStore();
+ final first = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ first.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ first.show(null);
+ async.flushMicrotasks();
+ store.order.clear();
+ final transport = _Transport(server)..hold = Completer<void>();
+ final second =
+ SuperTabClient(
+ transport: (method, path, {body}) {
+ store.order.add('request');
+ return transport.call(method, path, body: body);
+ },
+ storage: store,
+ discoveryInterval: Duration.zero,
+ )
+ ..reading = _web
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ second.open('tab').then((opened) => c = opened);
+ async.flushMicrotasks();
+ expect(store.order.first, 'request');
+ expect(store.order, contains('view'));
+ expect(c!.showingSaved, isTrue);
+ expect(c!.messages('lead').single.text, 'Hello');
+ transport.hold!.complete();
+ transport.hold = null;
+ async.flushMicrotasks();
+ expect(c!.showingSaved, isFalse);
+ first.dispose();
+ second.dispose();
+ });
+ });
+
+ test('a first read that lands before the saved view is not drawn over', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _OrderStore();
+ final first = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ first.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ first.show(null);
+ async.flushMicrotasks();
+ server.append('Newer.');
+ store.viewDelay = const Duration(milliseconds: 500);
+ final second = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ second.open('tab').then((opened) => c = opened);
+ async.elapse(const Duration(seconds: 1));
+ expect(c!.showingSaved, isFalse);
+ expect(c!.messages('lead').map((m) => m.text), ['Hello', 'Newer.']);
+ first.dispose();
+ second.dispose();
+ });
+ });
+
+ test('signing out or losing the Swarm leaves no saved view behind', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ final transport = _Transport(server);
+ final client = _client(transport, store)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ client.show(null);
+ async.flushMicrotasks();
+ expect(store.values[_viewKey], isNotNull);
+ client.bind('someone-else');
+ async.flushMicrotasks();
+ expect(
+ store.values.keys.where(
+ (k) => k.startsWith('super_tab.view') && k.contains('owner'),
+ ),
+ isEmpty,
+ );
+ // Lost access forgets that Swarm's view.
+ client
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ client.show(null);
+ async.flushMicrotasks();
+ expect(store.values[_viewKey], isNotNull);
+ client.show('tab');
+ transport.refuse = const SuperTabFailure(
+ 'FORBIDDEN',
+ 'You no longer have access to this Swarm.',
+ statusCode: 403,
+ );
+ async.elapse(const Duration(seconds: 4));
+ expect(store.values[_viewKey], isNull);
+ client.dispose();
+ });
+ });
+
+ test('Desktop reading keeps nothing on the device', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ final client = _client(
+ _Transport(server),
+ store,
+ reading: const SuperTabReading(),
+ )..bind('owner');
+ client.open('tab');
+ for (var i = 0; i < 5; i++) {
+ server.append('Update $i');
+ async.elapse(const Duration(seconds: 3));
+ }
+ client.pageVisible = false;
+ async.flushMicrotasks();
+ expect(
+ store.values.keys.where((k) => k.contains('super_tab.view')),
+ isEmpty,
+ );
+ client.dispose();
+ });
+ });
+}
diff --git a/desktop/test/super_tab_saved_view_widget_test.dart b/desktop/test/super_tab_saved_view_widget_test.dart
new file mode 100644
index 000000000..ff51d1733
--- /dev/null
+++ b/desktop/test/super_tab_saved_view_widget_test.dart
@@ -0,0 +1,92 @@
+// The saved view on screen (#180 fix 4): a quiet "Updating…" beside the
+// Super Tab's title until the first read lands; the send box stays usable.
+import 'dart:async';
+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/controller.dart';
+import 'package:harness/super_tabs/reading.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+const _web = SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ messagesWithState: true,
+ drawsSaved: true,
+);
+
+SuperTabController _controller(ConversationServer server) => SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: server.request,
+ save: server.save,
+ initial: const {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},
+ reading: _web,
+ pollInterval: Duration.zero,
+);
+
+Future<void> _mount(WidgetTester tester, SuperTabController c) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+void main() {
+ testWidgets('the saved view says Updating until the first read lands', (
+ tester,
+ ) async {
+ final server = ConversationServer()..append('Hello');
+ final first = _controller(server);
+ await first.refresh();
+ final view =
+ jsonDecode(jsonEncode(first.savedView)) as Map<String, dynamic>;
+ first.dispose();
+
+ server.holdReads = Completer<void>();
+ final c = _controller(server)..drawSaved(view);
+ addTearDown(c.dispose);
+ await _mount(tester, c);
+ expect(find.text('Hello'), findsOneWidget);
+ expect(find.text('Updating…'), findsOneWidget);
+ // The send box takes a draft meanwhile.
+ await tester.enterText(find.byType(TextField).last, 'Go ahead.');
+ expect(c.draft('lead'), 'Go ahead.');
+
+ unawaited(c.refresh());
+ await tester.pump();
+ server.holdReads!.complete();
+ server.holdReads = null;
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Updating…'), findsNothing);
+ expect(find.text('Hello'), findsOneWidget);
+ // Reading the transcript saves where it was read to, a moment later.
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets('a read Swarm says nothing of the kind', (tester) async {
+ final server = ConversationServer()..append('Hello');
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await _mount(tester, c);
+ expect(find.text('Updating…'), findsNothing);
+ await tester.pump(const Duration(seconds: 1));
+ });
+}