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: saved Super Tab view fixes from the #1723 review, view back on (#1727)

Jacob Pham0d3485bad365
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 039800925..50bc59b6e 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -70,7 +70,11 @@ class SuperTabClient {
SuperTabReading get reading => _reading;
set reading(SuperTabReading value) {
if (identical(value, _reading)) return;
+ final claims = value.drawsSaved && !_reading.drawsSaved;
_reading = value;
+ // The account bound before the host said views are kept, at boot. With
+ // none bound yet, the bind that follows claims.
+ if (claims && _account != null) _claimViews();
for (final controller in _loaded.values) {
controller.reading = value;
}
@@ -99,11 +103,22 @@ class SuperTabClient {
late final _views = SuperTabSavedViews(storage);
final _viewSaves = <String, Timer>{};
final _viewSavedAt = <String, DateTime>{};
+ final _viewVersions = <String, int>{};
+
+ /// Only the account using this device keeps views on it: any other one,
+ /// after a reload too, is forgotten ([SuperTabSavedViews.claim]).
+ void _claimViews() {
+ if (!_reading.drawsSaved) return;
+ unawaited(_views.claim(_account).catchError((Object _) {}));
+ }
/// 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);
+ /// How long an open waits for a saved view before drawing without one.
+ static const _viewLockWait = Duration(milliseconds: 250);
+
void _saveViewSoon(String id) {
if (_viewSaves.containsKey(id)) return;
final last = _viewSavedAt[id];
@@ -117,9 +132,12 @@ class SuperTabClient {
void _saveView(String id) {
_viewSaves.remove(id)?.cancel();
final account = _account;
- final view = _loaded[id]?.savedView;
+ final controller = _loaded[id];
+ final view = controller?.savedView;
+ // Nothing to keep is no write: the 15 s wait starts with a real one.
if (account == null || view == null) return;
_viewSavedAt[id] = clock.now();
+ _viewVersions[id] = controller!.viewVersion;
unawaited(_views.write(account, id, view).catchError((Object _) {}));
}
@@ -187,14 +205,15 @@ 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();
+ _viewVersions.clear();
_account = account;
+ // Nothing of an account that left stays on this device.
+ _claimViews();
_generation++;
_discoveryTimer?.cancel();
_discovering = null;
@@ -400,8 +419,10 @@ class SuperTabClient {
if (_reading.drawsSaved && generation == _generation) {
if (controller.accessRevoked) {
_viewSaves.remove(id)?.cancel();
- unawaited(_views.forget(account, id));
- } else if (!controller.showingSaved) {
+ unawaited(_views.forget(account, id).catchError((Object _) {}));
+ } else if (controller.viewVersion != _viewVersions[id]) {
+ // Kept only when what it holds changed; none while a saved view
+ // is still on screen ([SuperTabController.savedView]).
_saveViewSoon(id);
}
}
@@ -424,7 +445,11 @@ class SuperTabClient {
// 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);
+ // Behind the lock shared with this browser's other tabs: one iOS has
+ // suspended may hold it. Past a short wait, open with no saved view.
+ final view = await _views
+ .read(account, id)
+ .timeout(_viewLockWait, onTimeout: () => null);
if (view != null && generation == _generation) {
controller.drawSaved(view);
}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 320534f9e..bd68d5333 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -157,6 +157,12 @@ class SuperTabController extends ChangeNotifier {
bool get showingSaved => _showingSaved;
bool _showingSaved = false;
+ /// Moves when what a [savedView] holds changes: the state as read, or the
+ /// open conversation and its page. Not for what only the page around them
+ /// does (read marks, open groups), which needs no new copy kept.
+ int get viewVersion => _viewVersion;
+ int _viewVersion = 0;
+
/// 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();
@@ -450,7 +456,12 @@ class SuperTabController extends ChangeNotifier {
/// 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;
+ if (!_policy.drawsSaved ||
+ state == null ||
+ accessRevoked ||
+ _showingSaved) {
+ return null;
+ }
final id = selectedId;
final shown = _messages[id] ?? const <SuperTabMessage>[];
final page = shown.length > _savedPage
@@ -624,6 +635,7 @@ class SuperTabController extends ChangeNotifier {
if (group.archived) closedOpenProjects.add(group.projectId);
}
selectedId = id;
+ _viewVersion++;
operationNotice = null;
_saveSoon();
_changed();
@@ -694,12 +706,14 @@ class SuperTabController extends ChangeNotifier {
if (_policy.adapts) {
stateChanged = !const DeepCollectionEquality().equals(raw, _shownState);
_shownState = raw;
+ if (stateChanged) _viewVersion++;
}
final next = SuperTabSnapshot.fromJson(raw);
if (next.id != tabId) {
throw const FormatException('A different Swarm was returned.');
}
- if (nextRevision >= revision) {
+ // The first read over a saved view wins, whatever revision was saved.
+ if (nextRevision >= revision || _showingSaved) {
snapshot = next;
final allowed = next.conversations.map((c) => c.id).toSet();
final localAccessChanged =
@@ -928,9 +942,14 @@ class SuperTabController extends ChangeNotifier {
if (incoming.any((m) => m.conversationId != id)) {
throw const FormatException('A different conversation was returned.');
}
+ // The first read over a saved page replaces it: merged, the saved
+ // page would leave a gap when more than a page arrived since.
+ final replacing = _showingSaved && !older;
+ if (replacing) _rows.remove(id);
_keepRows(id, answer['messages'] as List);
final combined = {
- for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,
+ if (!replacing)
+ for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,
for (final m in incoming) m.id: m,
};
final own = combined.values
@@ -981,12 +1000,15 @@ class SuperTabController extends ChangeNotifier {
// An adapting read that found nothing new changes nothing on screen.
final same = _policy.adapts && _sameMessages(_messages[id], next);
_messages[id] = next;
- if (older || !_before.containsKey(id)) {
+ if (older || replacing || !_before.containsKey(id)) {
_before[id] = (answer['next'] as num?)?.toInt();
}
// Something new in the conversation on screen keeps the full poll.
if (arrived && id == selectedId) _acted();
- if (!same) _changed();
+ if (!same) {
+ if (id == selectedId) _viewVersion++;
+ _changed();
+ }
} catch (failure) {
// The state read waits for a machine within the grace: so do these.
if (!_inConnectGrace(failure)) _readFailure(failure, revokeTab: false);
diff --git a/desktop/lib/super_tabs/saved_view.dart b/desktop/lib/super_tabs/saved_view.dart
index f7b8c1fc7..6ae7560a3 100644
--- a/desktop/lib/super_tabs/saved_view.dart
+++ b/desktop/lib/super_tabs/saved_view.dart
@@ -39,6 +39,22 @@ class SuperTabSavedViews {
String _key(String account, String tabId) => 'super_tab.view.$account.$tabId';
String _index(String account) => 'super_tab.views.$account';
+ /// The account whose views this device keeps: the one to forget when
+ /// another signs in, in this page or after a reload.
+ static const _owner = 'super_tab.saved_by';
+
+ Future<void> _tail = Future.value();
+
+ /// One operation at a time here, and across this browser's tabs under its
+ /// lock: each one reads and rewrites the account's index.
+ Future<T> _serial<T>(Future<T> Function() action) {
+ final run = _tail.then(
+ (_) => storage.synchronized('super_tab.views', action),
+ );
+ _tail = run.then((_) {}, onError: (Object _) {});
+ return run;
+ }
+
Future<List<String>> _tabs(String account) async {
try {
final raw = await storage.read(_index(account));
@@ -50,6 +66,8 @@ class SuperTabSavedViews {
}
}
+ /// Puts [tabId] first in the account's index. Best effort when reading: a
+ /// storage that refuses must not fail the open.
Future<void> _use(String account, String tabId) async {
final tabs = (await _tabs(account))..remove(tabId);
tabs.insert(0, tabId);
@@ -62,58 +80,96 @@ class SuperTabSavedViews {
);
}
- /// 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;
- }
- }
+ /// The view saved for [tabId], or null: none, unreadable, another shape,
+ /// or a storage that refuses (full, private mode). It never throws.
+ Future<Map<String, dynamic>?> read(String account, String tabId) =>
+ _serial(() async {
+ try {
+ final raw = await storage.read(_key(account, tabId));
+ if (raw == null) return null;
+ final view = jsonDecode(raw);
+ if (view is! Map<String, dynamic> ||
+ view['state'] is! Map<String, dynamic> ||
+ view['revision'] is! int) {
+ return null;
+ }
+ try {
+ await _use(account, tabId);
+ } catch (_) {}
+ return view;
+ } catch (_) {
+ 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> write(String account, String tabId, Map<String, dynamic> view) =>
+ _serial(() async {
+ // Only for the account using this device: after a sign-out in
+ // another tab, or another account's claim, a late write keeps nothing.
+ if (await storage.read(_owner) != account) return;
+ 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 (_utf8Length(text) > maxBytes) {
+ await _forget(account, tabId);
+ return;
+ }
+ await storage.write(_key(account, tabId), text);
+ await _use(account, tabId);
+ });
+
+ Future<void> forget(String account, String tabId) =>
+ _serial(() => _forget(account, tabId));
- Future<void> forget(String account, String tabId) async {
+ 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 {
+ Future<void> forgetAccount(String account) =>
+ _serial(() => _forgetAccount(account));
+
+ Future<void> _forgetAccount(String account) async {
for (final tab in await _tabs(account)) {
await storage.delete(_key(account, tab));
}
await storage.delete(_index(account));
}
+
+ /// [account] (null when signed out) is the one using this device now: the
+ /// views of any other account that used it, before a reload too, go.
+ Future<void> claim(String? account) => _serial(() async {
+ final owner = await storage.read(_owner);
+ if (owner == account) return;
+ if (owner != null) await _forgetAccount(owner);
+ if (account == null) {
+ await storage.delete(_owner);
+ } else {
+ await storage.write(_owner, account);
+ }
+ });
+
+ /// UTF-8 bytes of [text], without encoding a copy of it to count them.
+ static int _utf8Length(String text) {
+ var bytes = 0;
+ for (final rune in text.runes) {
+ bytes += rune < 0x80
+ ? 1
+ : rune < 0x800
+ ? 2
+ : rune < 0x10000
+ ? 3
+ : 4;
+ }
+ return bytes;
+ }
}
diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dart
index aef4136a6..f72bb857c 100644
--- a/desktop/lib/web/shell/web_chrome.dart
+++ b/desktop/lib/web/shell/web_chrome.dart
@@ -46,15 +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.
- // Drawing the last view kept on this device is off until its review findings
- // (a gap after more than 100 new messages, storage ordering) are fixed.
+ // 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: false,
+ drawsSaved: true,
),
);
diff --git a/desktop/test/super_tab_reading_workspace_test.dart b/desktop/test/super_tab_reading_workspace_test.dart
index 749d054b7..b568cda6d 100644
--- a/desktop/test/super_tab_reading_workspace_test.dart
+++ b/desktop/test/super_tab_reading_workspace_test.dart
@@ -140,6 +140,12 @@ void main() {
expect(_stateReads(f), greaterThanOrEqualTo(2));
f.app.newSwarm();
await tester.pump();
+ // The web keeps the view it read for the next open (#180 fix 4).
+ await tester.pump();
+ expect(
+ f.store.values.keys.where((k) => k.startsWith('super_tab.view.')),
+ isNotEmpty,
+ );
var before = _stateReads(f);
await tester.pump(const Duration(seconds: 30));
expect(_stateReads(f), before);
diff --git a/desktop/test/super_tab_saved_view_test.dart b/desktop/test/super_tab_saved_view_test.dart
index 84d2dac2c..9fe843ba9 100644
--- a/desktop/test/super_tab_saved_view_test.dart
+++ b/desktop/test/super_tab_saved_view_test.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/super_tabs/client.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/reading.dart';
@@ -35,10 +36,13 @@ Map<String, dynamic> _view({String tab = 'tab', int pad = 0}) {
void main() {
group('a controller', _controllerTests);
group('the client', _clientTests);
+ group('review of #1723', _reviewTests);
+ group('re-review of #1727', _reReviewTests);
test('keeps what the Swarm draws, not what it never shows', () async {
final store = MemoryStore();
final views = SuperTabSavedViews(store);
+ await views.claim('owner');
await views.write('owner', 'tab', _view());
final read = (await views.read('owner', 'tab'))!;
expect(read['revision'], 7);
@@ -53,6 +57,7 @@ void main() {
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.claim('owner');
await views.write('owner', 'tab', _view());
expect(await views.read('owner', 'tab'), isNotNull);
await views.write('owner', 'tab', _view(pad: 8000));
@@ -65,6 +70,7 @@ void main() {
test('an account keeps its three most recent Swarms', () async {
final views = SuperTabSavedViews(MemoryStore());
+ await views.claim('owner');
for (final tab in ['a', 'b', 'c', 'd']) {
await views.write('owner', tab, _view(tab: tab));
}
@@ -84,19 +90,23 @@ void main() {
() async {
final store = MemoryStore();
final views = SuperTabSavedViews(store);
+ await views.claim('owner');
await views.write('owner', 'tab', _view());
- await views.write('other', 'tab', _view());
expect(await views.read('stranger', 'tab'), isNull);
+ expect(await views.read('owner', 'tab'), isNotNull);
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);
+ expect(
+ store.values.keys.where((k) => k.startsWith('super_tab.view')),
+ isEmpty,
+ );
},
);
test('a lost Swarm is forgotten; a view it cannot read is none', () async {
final store = MemoryStore();
final views = SuperTabSavedViews(store);
+ await views.claim('owner');
await views.write('owner', 'tab', _view());
await views.forget('owner', 'tab');
expect(await views.read('owner', 'tab'), isNull);
@@ -530,3 +540,335 @@ void _clientTests() {
});
});
}
+
+/// A store that refuses, as a full (writes) or private-mode (reads too)
+/// browser storage does.
+class _FailingStore extends MemoryStore {
+ bool refuseReads = false, refuseWrites = false;
+ @override
+ Future<String?> read(String key) async {
+ if (refuseReads && key.startsWith('super_tab.view')) {
+ throw StateError('SecurityError');
+ }
+ return super.read(key);
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ if (refuseWrites && key.startsWith('super_tab.view')) {
+ throw StateError('QuotaExceededError');
+ }
+ return super.write(key, value);
+ }
+}
+
+/// Every key the client touched, reads and deletes included.
+class _TouchStore extends MemoryStore {
+ final touched = <String>[];
+ @override
+ Future<String?> read(String key) {
+ touched.add(key);
+ return super.read(key);
+ }
+
+ @override
+ Future<void> delete(String key) {
+ touched.add(key);
+ return super.delete(key);
+ }
+}
+
+/// Saves [server]'s Swarm as `owner` through a client on [store], then
+/// leaves it, as a person does before closing the page.
+void _visit(FakeAsync async, ConversationServer server, MemoryStore store) {
+ final client = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ client.show(null);
+ async.flushMicrotasks();
+ // Not disposed: closing a page signs nobody out (dispose is a sign-out).
+}
+
+/// A browser store whose cross-tab lock another tab holds: an iPhone
+/// suspending a background tab that held it.
+class _StuckLockStore extends MemoryStore
+ implements SynchronizedLocalKeyValueStore {
+ final release = Completer<void>();
+ @override
+ Future<T> synchronized<T>(String scope, Future<T> Function() action) =>
+ release.future.then((_) => action());
+}
+
+void _reReviewTests() {
+ // Minor a.
+ test('a lock another tab holds delays the open no more than 250 ms', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _StuckLockStore();
+ final client = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ client.open('tab').then((opened) => c = opened);
+ async.elapse(const Duration(milliseconds: 249));
+ expect(c, isNull);
+ async.elapse(const Duration(milliseconds: 2));
+ expect(c, isNotNull);
+ expect(c!.showingSaved, isFalse);
+ expect(c!.messages('lead').single.text, 'Hello');
+ store.release.complete();
+ async.flushMicrotasks();
+ client.dispose();
+ });
+ });
+
+ // Minor b.
+ test('after a sign-out elsewhere, a late write keeps nothing', () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store);
+ await views.claim('owner');
+ await views.write('owner', 'tab', _view());
+ expect(store.values[_viewKey], isNotNull);
+ // Another browser tab signs out: the device keeps nobody's views now.
+ await SuperTabSavedViews(store).claim(null);
+ expect(store.values[_viewKey], isNull);
+ await views.write('owner', 'tab', _view());
+ expect(store.values[_viewKey], isNull);
+ // Nor one written for another account than the one using the device.
+ await views.claim('someone-else');
+ await views.write('owner', 'tab', _view());
+ expect(store.values[_viewKey], isNull);
+ });
+}
+
+void _reviewTests() {
+ // Finding 1.
+ test('more than a page since the save leaves no gap in the transcript', () {
+ final server = ConversationServer();
+ for (var i = 1; i <= 120; i++) {
+ server.append('m$i');
+ }
+ final view = _saved(server);
+ fakeAsync((async) {
+ for (var i = 121; i <= 270; i++) {
+ server.append('m$i');
+ }
+ final c = _controller(_Reads(server))
+ ..drawSaved(view)
+ ..start();
+ async.flushMicrotasks();
+ final shown = c.messages('lead').map((m) => m.text).toList();
+ expect(shown.length, 100);
+ expect(shown.first, 'm171');
+ expect(shown.last, 'm270');
+ unawaited(c.loadMessages('lead', older: true));
+ async.flushMicrotasks();
+ final sequences = c.messages('lead').map((m) => m.sequence).toList();
+ expect(sequences.first, 71);
+ for (var i = 1; i < sequences.length; i++) {
+ expect(sequences[i], sequences[i - 1] + 1, reason: 'at $i');
+ }
+ c.dispose();
+ });
+ });
+
+ // Finding 2.
+ test('nothing is written back while the saved view is on screen', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _CountingStore();
+ _visit(async, server, store);
+ server.append('Newer.');
+ store.writes.clear();
+ final transport = _Transport(server)..hold = Completer<void>();
+ final client = _client(transport, store)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 2));
+ expect(store.writes.where((k) => k == _viewKey), isEmpty);
+ transport.hold!.complete();
+ transport.hold = null;
+ async.elapse(const Duration(seconds: 1));
+ // The fresh view is kept at once, not 15 s later.
+ expect(store.writes.where((k) => k == _viewKey), hasLength(1));
+ expect(store.values[_viewKey], contains('Newer.'));
+ client.dispose();
+ });
+ });
+
+ // Finding 3.
+ for (final (name, full, private) in [
+ ('full', true, false),
+ ('private mode', true, true),
+ ]) {
+ test('a $name storage opens the Swarm as today, with one poll', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _FailingStore();
+ _visit(async, server, store);
+ store
+ ..refuseWrites = full
+ ..refuseReads = private;
+ final reads = <String>[];
+ final transport = _Transport(server)..hold = Completer<void>();
+ final client =
+ SuperTabClient(
+ transport: (method, path, {body}) {
+ if (path == '/api/super-tabs/tab') reads.add(path);
+ return transport.call(method, path, body: body);
+ },
+ storage: store,
+ discoveryInterval: Duration.zero,
+ )
+ ..reading = _web
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ Object? failed;
+ client
+ .open('tab')
+ .then<void>(
+ (opened) => c = opened,
+ onError: (Object e) => failed = e,
+ );
+ async.flushMicrotasks();
+ // A full storage still reads: the saved view draws. Private mode
+ // reads nothing: the Swarm opens as today.
+ expect(failed, isNull);
+ expect(c!.showingSaved, !private);
+ transport.hold!.complete();
+ transport.hold = null;
+ async.elapse(const Duration(milliseconds: 7100));
+ expect(c!.error, isNull);
+ expect(c!.messages('lead').single.text, 'Hello');
+ expect(reads, hasLength(3));
+ // Leaving and signing out: no error escapes either.
+ client.show(null);
+ client.bind('someone-else');
+ async.flushMicrotasks();
+ client.dispose();
+ });
+ });
+ }
+
+ // Finding 4.
+ test('views saved at the same moment all stay listed, and all go', () async {
+ final store = MemoryStore();
+ final views = SuperTabSavedViews(store);
+ await views.claim('owner');
+ await Future.wait([
+ views.write('owner', 'a', _view(tab: 'a')),
+ views.write('owner', 'b', _view(tab: 'b')),
+ views.write('owner', 'c', _view(tab: 'c')),
+ ]);
+ for (final tab in ['a', 'b', 'c']) {
+ expect(store.values['super_tab.view.owner.$tab'], isNotNull, reason: tab);
+ }
+ // Signing out then finds every one of them.
+ await views.forgetAccount('owner');
+ expect(
+ store.values.keys.where((k) => k.startsWith('super_tab.view')),
+ isEmpty,
+ );
+ });
+
+ // Finding 5.
+ test('another account after a reload clears the one before', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ _visit(async, server, store);
+ expect(store.values[_viewKey], isNotNull);
+ // The same account after a reload keeps its view.
+ _client(_Transport(server), store).bind('owner');
+ async.flushMicrotasks();
+ expect(store.values[_viewKey], isNotNull);
+ // Another account on the next page load: nothing of the first stays.
+ final other = _client(_Transport(server), store)..bind('someone-else');
+ async.flushMicrotasks();
+ expect(
+ store.values.keys.where(
+ (k) => k.startsWith('super_tab.view') && k.contains('owner'),
+ ),
+ isEmpty,
+ );
+ other.dispose();
+ });
+ });
+
+ test('at boot the account binds before the web says views are kept', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = MemoryStore();
+ _visit(async, server, store);
+ // As AppNotifier does: the account first, the workspace's reading after.
+ SuperTabClient(
+ transport: _Transport(server).call,
+ storage: store,
+ discoveryInterval: Duration.zero,
+ )
+ ..bind('someone-else')
+ ..reading = _web;
+ async.flushMicrotasks();
+ expect(store.values[_viewKey], isNull);
+ });
+ });
+
+ // Finding 6.
+ test('the first read wins over a saved view, whatever its revision', () {
+ final server = ConversationServer()..append('Hello');
+ final view = _saved(server)..['revision'] = 999;
+ fakeAsync((async) {
+ server.state['name'] = 'Pilot, renamed';
+ final c = _controller(_Reads(server))
+ ..drawSaved(view)
+ ..start();
+ async.flushMicrotasks();
+ expect(c.showingSaved, isFalse);
+ expect(c.snapshot!.name, 'Pilot, renamed');
+ c.dispose();
+ });
+ });
+
+ // Finding 8.
+ test('a change of the page only, not of what was read, writes nothing', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final store = _CountingStore();
+ final client = _client(_Transport(server), store)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? c;
+ client.open('tab').then((opened) => c = opened);
+ async.elapse(const Duration(seconds: 20));
+ store.writes.clear();
+ c!.markRead('lead');
+ c!.toggleProject('lead');
+ async.elapse(const Duration(seconds: 20));
+ expect(store.writes.where((k) => k == _viewKey), isEmpty);
+ client.dispose();
+ });
+ });
+
+ // Finding 9.
+ test('Desktop: an account change reads and deletes no saved view', () {
+ fakeAsync((async) {
+ final store = _TouchStore();
+ final client =
+ _client(
+ _Transport(ConversationServer()),
+ store,
+ reading: const SuperTabReading(),
+ )
+ ..bind('owner')
+ ..bind('someone-else')
+ ..bind(null);
+ async.flushMicrotasks();
+ expect(store.touched.where((k) => k.contains('super_tab.view')), isEmpty);
+ client.dispose();
+ });
+ });
+}