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 loads faster on a phone (read on connect, lighter poll, messages beside the state, font preload) (#1710)

Jacob Pham110a86305999
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index df0b6c0a1..9cf55c21d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1810,6 +1810,9 @@ class AppNotifier extends ChangeNotifier {
Map<String, String> _superTabNames = {};
bool _superTabsEntered = false;
+ /// Whether a machine could serve Swarm reads at the last connection change.
+ bool _superTabsServed = false;
+
/// Membership alone must not reveal the hidden feature in a regular workspace.
/// The hidden shortcut, an explicit open, or a restored Swarm supplies that intent.
void enterSuperTabs() => _superTabsEntered = true;
@@ -8780,6 +8783,11 @@ class AppNotifier extends ChangeNotifier {
);
}
}
+ // Swarm reads go through a connected machine: the moment one can serve
+ // them again, the Swarm on screen reads (`SuperTabReading.readsOnConnect`).
+ final served = sharedTabsTarget != null;
+ if (served && !_superTabsServed) superTabs.serverAvailable();
+ _superTabsServed = served;
notifyListeners();
}
diff --git a/desktop/lib/state/workspace_chrome.dart b/desktop/lib/state/workspace_chrome.dart
index 87357be44..6e5533122 100644
--- a/desktop/lib/state/workspace_chrome.dart
+++ b/desktop/lib/state/workspace_chrome.dart
@@ -1,5 +1,7 @@
import 'package:flutter/widgets.dart';
+import '../super_tabs/reading.dart';
+
/// The workspace's command table as a host composition sees it: the same ids
/// and callbacks keys, native menus and the command box already run.
class WorkspaceCommands {
@@ -70,6 +72,7 @@ class WorkspaceChrome {
this.labelsPaneStatus = false,
this.compactPaneHeader = false,
this.superTabRecovers = false,
+ this.superTabReading = const SuperTabReading(),
});
/// What a workspace with no host chrome (Desktop) reads: every switch at
@@ -153,6 +156,10 @@ class WorkspaceChrome {
/// findings S12, P5.
final bool superTabRecovers;
+ /// How the Swarm tabs keep themselves current. The default is Desktop's: a
+ /// full read every 3 s, on screen or not. #180's report, fixes 1, 2a and 3.
+ final SuperTabReading superTabReading;
+
/// Whether a window [width] wide gets the compact pane header.
bool compactPaneHeaderAt(double width) =>
compactPaneHeader && width < compactBelow;
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index fed7ef064..5c47e24df 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -6,6 +6,7 @@ import 'attachment_upload.dart';
import 'controller.dart';
import 'model.dart';
import 'notifications.dart';
+import 'reading.dart';
typedef SuperTabTransport = Future<Object?> Function(
String method,
@@ -47,10 +48,72 @@ class SuperTabClient {
/// The tags waiting for this account in a Swarm: its own state once open,
/// else what discovery last read, so a tab not opened yet still shows them.
- int waitingTags(String id) =>
- _loaded[id]?.snapshot?.mentionsWaiting ?? _tagCounts[id] ?? 0;
+ /// A Swarm paused while away ([SuperTabReading.pausesAway]) reads nothing:
+ /// discovery's count is the fresh one until it is shown again.
+ int waitingTags(String id) {
+ final counted = _tagCounts[id];
+ if (counted != null && _paused(id)) return counted;
+ return _loaded[id]?.snapshot?.mentionsWaiting ?? _tagCounts[id] ?? 0;
+ }
+
+ /// Open here, but not polling: not on screen while the reading pauses.
+ bool _paused(String id) =>
+ _reading.pausesAway && (_loaded[id]?.away ?? false);
final SuperTabUpload upload;
final Duration discoveryInterval;
+
+ /// How every Swarm tab here keeps itself current. Desktop's unless the host
+ /// composition sets another (`SuperTabWorkspace` hands on its chrome's).
+ SuperTabReading get reading => _reading;
+ set reading(SuperTabReading value) {
+ if (identical(value, _reading)) return;
+ _reading = value;
+ for (final controller in _loaded.values) {
+ controller.reading = value;
+ }
+ }
+
+ SuperTabReading _reading = const SuperTabReading();
+ String? _shown;
+ bool _pageVisible = true, _serverRead = false;
+
+ /// The Swarm tab on screen, or null for none: every other one is away.
+ void show(String? tabId) {
+ if (_shown == tabId) return;
+ _shown = tabId;
+ _applyAway();
+ }
+
+ /// False while the page or window is hidden: every Swarm tab is away.
+ set pageVisible(bool visible) {
+ if (_pageVisible == visible) return;
+ _pageVisible = visible;
+ _applyAway();
+ }
+
+ bool _isAway(String id) => !_pageVisible || id != _shown;
+
+ void _applyAway() {
+ for (final entry in _loaded.entries) {
+ entry.value.away = _isAway(entry.key);
+ }
+ }
+
+ /// A machine able to serve Swarm reads connected ([SuperTabReading.readsOnConnect]):
+ /// one read of the tab on screen and one discovery, however many machines
+ /// connect in the same moment.
+ void serverAvailable() {
+ if (!_reading.readsOnConnect || _account == null || _serverRead) return;
+ _serverRead = true;
+ scheduleMicrotask(() {
+ _serverRead = false;
+ for (final controller in _loaded.values) {
+ unawaited(controller.machineAvailable());
+ }
+ unawaited(refreshTabs());
+ });
+ }
+
String? _account;
int _generation = 0;
Timer? _discoveryTimer;
@@ -209,7 +272,9 @@ class SuperTabClient {
onTabs!(tabs.values.toList(), hidden);
await _readTags([
for (final id in tabs.keys)
- if (!hidden.contains(id) && !_loaded.containsKey(id)) id,
+ if (!hidden.contains(id) &&
+ (!_loaded.containsKey(id) || _paused(id)))
+ id,
], generation);
} catch (error) {
if (generation == _generation) {
@@ -284,7 +349,8 @@ class SuperTabClient {
},
save: (state) => storage.write(key, jsonEncode(state)),
upload: upload,
- );
+ reading: _reading,
+ )..away = _isAway(id);
var seenRevision = -1;
var seenSelected = controller.selectedId;
controller.addListener(() {
@@ -318,17 +384,32 @@ class SuperTabClient {
'GET',
'/api/super-tabs/${Uri.encodeComponent(id)}/mentions?state=waiting',
);
- if (generation != _generation || _loaded.containsKey(id)) continue;
+ if (generation != _generation ||
+ (_loaded.containsKey(id) && !_paused(id))) {
+ continue;
+ }
final waiting = [
for (final row in answer['mentions'] as List)
SuperTabMention.fromJson(superTabMap(row)),
];
- final seen = _tagsSeen[id];
+ // A paused Swarm already knows the tags it read before it was away.
+ final mentions = _loaded[id] == null
+ ? null
+ : SuperTabMentions.of(_loaded[id]!);
+ final seen = mentions == null
+ ? _tagsSeen[id]
+ : {...?_tagsSeen[id], for (final m in mentions.waiting) m.id};
+ final told = <String>{};
if (seen != null) {
for (final mention in waiting.reversed) {
- if (!seen.contains(mention.id)) onMention?.call(mention);
+ if (!seen.contains(mention.id)) {
+ onMention?.call(mention);
+ told.add(mention.id);
+ }
}
}
+ // Not news again when the Swarm is shown and reads its own.
+ mentions?.seen(told);
_tagsSeen[id] = {...?seen, for (final m in waiting) m.id};
if (_tagCounts[id] != waiting.length) {
_tagCounts[id] = waiting.length;
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 081d57cda..f0236bd02 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:math';
+import 'package:clock/clock.dart';
+import 'package:collection/collection.dart' show DeepCollectionEquality;
import 'package:dio/dio.dart' show CancelToken, DioException, DioExceptionType;
import 'package:flutter/foundation.dart';
@@ -8,8 +10,12 @@ import '../logging/app_log.dart';
import '../state/harness_attachments.dart';
import 'attachment_upload.dart';
import 'model.dart';
+import 'reading.dart';
import 'review_verdict.dart';
+/// A messages read started beside a state read, and what it asked for.
+typedef _EarlyRead = ({String query, Future<Map<String, dynamic>> page});
+
typedef SuperTabRequest = Future<Map<String, dynamic>> Function(
String method,
String path, {
@@ -44,8 +50,10 @@ class SuperTabController extends ChangeNotifier {
this.uploadTimeout = const Duration(minutes: 2),
Map<String, dynamic> initial = const {},
this.pollInterval = const Duration(seconds: 3),
- }) {
+ SuperTabReading reading = const SuperTabReading(),
+ }) : _policy = reading {
if (initial['tabId'] == tabId && initial['accountId'] == accountId) {
+ _savedSelection = initial['selectedId'] is String;
expandedProjects.addAll(
(initial['expandedProjects'] as List? ?? const []).whereType<String>(),
);
@@ -124,9 +132,53 @@ class SuperTabController extends ChangeNotifier {
bool loading = false, saving = false, uploading = false;
bool accessRevoked = false;
bool _disposed = false;
- Timer? _poll, _draftSave;
+ Timer? _poll, _draftSave, _graceEnd;
Future<void>? _refreshing;
+ /// How this tab keeps itself current; Desktop's unless a host sets another.
+ SuperTabReading get reading => _policy;
+ set reading(SuperTabReading value) {
+ if (identical(value, _policy)) return;
+ _policy = value;
+ if (_startedAt != null) _schedule();
+ }
+
+ SuperTabReading _policy;
+ DateTime? _startedAt, _lastFullRead;
+
+ /// The state last drawn, while the reading adapts ([_read]).
+ Map<String, dynamic>? _shownState;
+
+ /// 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();
+
+ /// The saved state named the open conversation before any read.
+ bool _savedSelection = false;
+
+ /// The first reads found no machine connected, within the grace
+ /// ([SuperTabReading.connectGrace]): still loading rather than failed.
+ bool _waitingForMachine = false;
+ Object? _graceFailure;
+
+ /// Not on screen: another tab is shown, or the page is hidden. Only a
+ /// reading that [SuperTabReading.pausesAway] stops polling for it; coming
+ /// back reads at once.
+ bool get away => _away;
+ bool _away = false;
+ set away(bool value) {
+ if (_away == value) return;
+ _away = value;
+ if (!_policy.pausesAway || _startedAt == null || _disposed) return;
+ if (value) {
+ _poll?.cancel();
+ return;
+ }
+ _acted();
+ unawaited(refresh());
+ _schedule();
+ }
+
/// The latest read of the Swarm's state failed (and the tab is still ours). While it is, what the
/// machines last reported cannot be told from what they report now: a machine is neither online nor
/// offline, and the Swarm says its backend is unreachable instead of calling machines offline.
@@ -336,11 +388,57 @@ class SuperTabController extends ChangeNotifier {
void start() {
if (_disposed) return;
+ _startedAt = _lastActivity = clock.now();
unawaited(refresh());
+ _schedule();
+ }
+
+ /// [after] is what is left of the poll once a read took the rest of it.
+ void _schedule([Duration? after]) {
_poll?.cancel();
- if (pollInterval > Duration.zero) {
+ if (_disposed || pollInterval <= Duration.zero) return;
+ if (!_policy.adapts) {
_poll = Timer.periodic(pollInterval, (_) => unawaited(refresh()));
+ return;
+ }
+ if (accessRevoked || (_policy.pausesAway && _away)) return;
+ final wait = after ?? pollInterval;
+ _poll = Timer(
+ wait > Duration.zero ? wait : Duration.zero,
+ () => unawaited(_tick()),
+ );
+ }
+
+ /// One adaptive poll: the full read when it is due, else only the open
+ /// conversation's new messages and its own unsettled receipt. The next one
+ /// comes a poll after this one began, however long its answer took.
+ Future<void> _tick() async {
+ final began = clock.now();
+ await (_fullReadDue ? refresh() : _readMessages(selectedId, light: true));
+ _schedule(pollInterval - clock.now().difference(began));
+ }
+
+ bool get _fullReadDue {
+ final quiet = _policy.quietPoll;
+ if (quiet == null || snapshot == null || _refreshFailing) return true;
+ final now = clock.now();
+ if (now.difference(_lastActivity) < _policy.quietAfter) return true;
+ final last = _lastFullRead;
+ return last == null || now.difference(last) >= quiet;
+ }
+
+ void _acted() => _lastActivity = clock.now();
+
+ /// 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() {
+ if (!_policy.readsOnConnect ||
+ _disposed ||
+ accessRevoked ||
+ (_policy.pausesAway && _away)) {
+ return Future.value();
}
+ return refresh();
}
void _changed() {
@@ -403,6 +501,7 @@ class SuperTabController extends ChangeNotifier {
}
void setDraft(String conversationId, String value) {
+ _acted();
_drafts[conversationId] = value;
_mentions[conversationId]?.removeWhere(
(_, token) => !containsMention(value, token),
@@ -431,6 +530,7 @@ class SuperTabController extends ChangeNotifier {
return;
}
devicesSelected = false;
+ _acted();
if (!snapshot!.isProjectLead(id)) {
final group = snapshot!.conversation(id)!;
expandedProjects.add(group.projectId);
@@ -463,14 +563,36 @@ class SuperTabController extends ChangeNotifier {
}
Future<void> _read() async {
+ // An adapting read that changes nothing redraws nothing: on a phone each
+ // redraw of the whole tab is a long frame, every poll.
+ final quiet = _policy.adapts && snapshot != null;
+ final before = _shown;
+ var stateChanged = false;
loading = snapshot == null;
- _changed();
+ if (!quiet) _changed();
+ _lastFullRead = clock.now();
final took = Stopwatch()..start();
+ // The open conversation's messages, asked for beside the state
+ // ([SuperTabReading.messagesWithState]); dropped if the state moves the
+ // selection elsewhere.
+ final earlyId = selectedId;
+ final earlyQuery = _earlyQuery(earlyId);
+ final early = earlyQuery == null
+ ? null
+ : (request('GET', '${_messagesPath(earlyId)}$earlyQuery')..ignore());
+ // A conversation the state already has takes its answer as it comes, so
+ // a reply shows without waiting for the state.
+ final messagesRead = early != null && snapshot != null
+ ? (_readMessages(earlyId, early: (query: earlyQuery!, page: early))
+ ..ignore())
+ : null;
try {
final answer = await request('GET', _path);
if (_disposed || accessRevoked) return;
_refreshFailing = false;
unreachableSince = null;
+ _waitingForMachine = false;
+ _graceEnd?.cancel();
stateReads++;
final nextRevision = (answer['revision'] as num).toInt();
// How long the Swarm took to answer, and nothing it said: the log shows a slow or failing
@@ -479,7 +601,14 @@ class SuperTabController extends ChangeNotifier {
'swarm',
'state read in ${took.elapsedMilliseconds} ms (revision $nextRevision)',
);
- final next = SuperTabSnapshot.fromJson(superTabMap(answer['state']));
+ final raw = superTabMap(answer['state']);
+ // Some of the state is worked out at read time (an agent seen down, a
+ // limit that ran out) and changes with no new revision.
+ if (_policy.adapts) {
+ stateChanged = !const DeepCollectionEquality().equals(raw, _shownState);
+ _shownState = raw;
+ }
+ final next = SuperTabSnapshot.fromJson(raw);
if (next.id != tabId) {
throw const FormatException('A different Swarm was returned.');
}
@@ -518,9 +647,22 @@ class SuperTabController extends ChangeNotifier {
error = null;
if (localAccessChanged) _saveSoon();
}
- await loadMessages(selectedId);
+ await (selectedId == earlyId && messagesRead != null
+ ? messagesRead
+ : _readMessages(
+ selectedId,
+ early: selectedId == earlyId && early != null
+ ? (query: earlyQuery!, page: early)
+ : null,
+ ));
} catch (failure) {
- _readFailure(failure);
+ if (_inConnectGrace(failure)) {
+ _waitingForMachine = true;
+ _graceFailure = failure;
+ } else {
+ _waitingForMachine = false;
+ _readFailure(failure);
+ }
if (!_disposed && !accessRevoked) {
_refreshFailing = true;
unreachableSince ??= DateTime.now();
@@ -532,9 +674,81 @@ class SuperTabController extends ChangeNotifier {
'${failure is SuperTabFailure ? '${failure.code} (status ${failure.statusCode})' : failure.runtimeType}',
);
} finally {
+ loading = _waitingForMachine;
+ if (!quiet || stateChanged || _shown != before) _changed();
+ }
+ }
+
+ /// What a state read can change on screen, beside the messages.
+ ({int revision, String? error, bool failing, bool revoked, bool loading})
+ get _shown => (
+ revision: revision,
+ error: error,
+ failing: _refreshFailing,
+ revoked: accessRevoked,
+ loading: loading,
+ );
+
+ /// A first read that found no machine connected, before the grace
+ /// ([SuperTabReading.connectGrace]) runs out: its error waits for the grace.
+ bool _inConnectGrace(Object failure) {
+ final since = _startedAt;
+ if (snapshot != null ||
+ since == null ||
+ failure is! SuperTabFailure ||
+ failure.code != 'MACHINE_UNAVAILABLE') {
+ return false;
+ }
+ final left = _policy.connectGrace - clock.now().difference(since);
+ if (left <= Duration.zero) return false;
+ _graceEnd ??= Timer(left, () {
+ if (_disposed || !_waitingForMachine) return;
+ _waitingForMachine = false;
+ _readFailure(_graceFailure!);
loading = false;
_changed();
+ });
+ return true;
+ }
+
+ /// The same messages with the same receipts: posted text does not change.
+ static bool _sameMessages(
+ List<SuperTabMessage>? shown,
+ List<SuperTabMessage> next,
+ ) {
+ if (shown == null || shown.length != next.length) return false;
+ for (var i = 0; i < next.length; i++) {
+ final a = shown[i], b = next[i];
+ if (a.id != b.id || a.deliveries.length != b.deliveries.length) {
+ return false;
+ }
+ for (var j = 0; j < b.deliveries.length; j++) {
+ if (!mapEquals(a.deliveries[j], b.deliveries[j])) return false;
+ }
}
+ return true;
+ }
+
+ String _messagesPath(String id) =>
+ '$_path/conversations/${Uri.encodeComponent(id)}/messages';
+
+ /// What a read of [id]'s messages asks for: the page before the oldest
+ /// shown, what came after the newest, or the latest page.
+ String _query(String id, {bool older = false}) {
+ if (older) return '?before=${_before[id]}';
+ final tail = _messages[id]?.lastOrNull?.sequence;
+ return tail != null ? '?after=$tail' : '';
+ }
+
+ /// The query of [id]'s messages read to start beside a state read, or null.
+ /// On first open only for the conversation the saved state named; after
+ /// that, for a conversation the state has and no read of it under way.
+ String? _earlyQuery(String id) {
+ if (!_policy.messagesWithState || _reading.containsKey(id)) return null;
+ final known = snapshot == null
+ ? _savedSelection
+ : snapshot!.conversation(id) != null;
+ return known ? _query(id) : null;
}
void _readFailure(Object failure, {bool revokeTab = true}) {
@@ -554,13 +768,32 @@ class SuperTabController extends ChangeNotifier {
}
/// Joins a read of [id] already under way, so a caller can wait for it.
- Future<void> loadMessages(String id, {bool older = false}) =>
- _reading[id] ??= _loadMessages(id, older: older).whenComplete(() {
- // A block: whenComplete would wait on the removed future, itself.
- _reading.remove(id);
- });
+ Future<void> loadMessages(String id, {bool older = false}) {
+ if (older) _acted();
+ return _readMessages(id, older: older);
+ }
+
+ /// [light] asks only for new messages (and the person's own unsettled
+ /// receipt), not the page again; [early] is a read already asked for.
+ Future<void> _readMessages(
+ String id, {
+ bool older = false,
+ bool light = false,
+ _EarlyRead? early,
+ }) => _reading[id] ??=
+ _loadMessages(id, older: older, light: light, early: early).whenComplete(
+ () {
+ // A block: whenComplete would wait on the removed future, itself.
+ _reading.remove(id);
+ },
+ );
- Future<void> _loadMessages(String id, {required bool older}) async {
+ Future<void> _loadMessages(
+ String id, {
+ required bool older,
+ bool light = false,
+ _EarlyRead? early,
+ }) async {
if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
return;
}
@@ -570,17 +803,18 @@ class SuperTabController extends ChangeNotifier {
final tail = known != null && known.isNotEmpty
? known.last.sequence
: null;
- final query = older
- ? '?before=${_before[id]}'
- : tail != null
- ? '?after=$tail'
- : '';
- var answer = await request(
- 'GET',
- '$_path/conversations/${Uri.encodeComponent(id)}/messages$query',
- );
+ final query = _query(id, older: older);
+ final first = early != null && early.query == query ? early.page : null;
+ var answer = first != null
+ ? await first.catchError(
+ (Object _) => request('GET', '${_messagesPath(id)}$query'),
+ )
+ : await request('GET', '${_messagesPath(id)}$query');
+ final arrived =
+ !older && tail != null && (answer['messages'] as List).isNotEmpty;
if (!_disposed &&
!older &&
+ !light &&
tail != null &&
(answer['messages'] as List).isEmpty) {
// No new text: refresh delivery receipts in the page already shown.
@@ -644,12 +878,17 @@ class SuperTabController extends ChangeNotifier {
combined[row.id] = row;
}
}
- _messages[id] = combined.values.toList()
+ final next = combined.values.toList()
..sort((a, b) => a.sequence.compareTo(b.sequence));
+ // 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)) {
_before[id] = (answer['next'] as num?)?.toInt();
}
- _changed();
+ // Something new in the conversation on screen keeps the full poll.
+ if (arrived && id == selectedId) _acted();
+ if (!same) _changed();
} catch (failure) {
_readFailure(failure, revokeTab: false);
if (failure is SuperTabFailure &&
@@ -665,6 +904,7 @@ class SuperTabController extends ChangeNotifier {
if (_disposed || !_maySend(command) || saving || _pending != null) {
return null;
}
+ _acted();
_pending = {
'operationId': superTabOperationId(),
'command': Map<String, dynamic>.of(command),
@@ -935,6 +1175,7 @@ class SuperTabController extends ChangeNotifier {
void dispose() {
_disposed = true;
_poll?.cancel();
+ _graceEnd?.cancel();
_draftSave?.cancel();
for (final files in _attachments.values) {
files.dispose();
diff --git a/desktop/lib/super_tabs/reading.dart b/desktop/lib/super_tabs/reading.dart
new file mode 100644
index 000000000..ea88ea27f
--- /dev/null
+++ b/desktop/lib/super_tabs/reading.dart
@@ -0,0 +1,42 @@
+/// How a Swarm tab keeps itself current. The defaults are Desktop's: a full
+/// read every poll, whether or not the tab is on screen, the first read's
+/// failure shown at once, and the messages read after the state. The web
+/// build turns on the rest (`lib/web/shell/web_chrome.dart`), because a phone
+/// pays for every read in data, battery and main-thread time (#180's report).
+class SuperTabReading {
+ const SuperTabReading({
+ this.quietPoll,
+ this.quietAfter = const Duration(seconds: 30),
+ this.pausesAway = false,
+ this.readsOnConnect = false,
+ this.connectGrace = Duration.zero,
+ this.messagesWithState = false,
+ });
+
+ /// Null keeps a full read every poll. Otherwise, once the open conversation
+ /// has had no new message and the person has done nothing for [quietAfter],
+ /// the full read comes this often; the polls between only ask the open
+ /// conversation for new messages and settle the person's own unsettled
+ /// message, so a reply still shows within one poll.
+ final Duration? quietPoll;
+ final Duration quietAfter;
+
+ /// True stops the poll while the tab is not the one on screen or the page is
+ /// hidden, and reads at once when it is shown again.
+ final bool pausesAway;
+
+ /// True reads at once when a machine able to serve Swarm reads connects,
+ /// instead of at the next poll.
+ final bool readsOnConnect;
+
+ /// How long a first read that found no connected machine keeps the loading
+ /// state before it shows the error; a machine is usually still connecting.
+ final Duration connectGrace;
+
+ /// True starts the saved conversation's messages read beside the first
+ /// state read, instead of after it.
+ final bool messagesWithState;
+
+ /// 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/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index 44c9ef152..453b55d92 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
import '../state/terminal_pane.dart';
+import '../state/workspace_chrome.dart';
import 'agent_group_picker.dart';
import 'controller.dart';
import 'dialog_scope.dart';
@@ -47,6 +48,31 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
final _failures = <(String, String?), String>{};
final _nativeHeartbeats = <Timer>[];
+ /// The Swarm tab last told to the client as the one on screen.
+ String? _shown;
+ late final _lifecycle = AppLifecycleListener(
+ onStateChange: (state) => app.superTabs.pageVisible =
+ state != AppLifecycleState.hidden &&
+ state != AppLifecycleState.paused &&
+ state != AppLifecycleState.detached,
+ );
+
+ @override
+ void initState() {
+ super.initState();
+ _lifecycle;
+ }
+
+ /// Which Swarm tab is on screen, told after the frame: a change can start
+ /// a read, and a read notifies listeners this build may be one of.
+ void _showTab(String? id) {
+ if (_shown == id) return;
+ _shown = id;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _shown == id) app.superTabs.show(id);
+ });
+ }
+
void _clearNativeContext() {
for (final timer in _nativeHeartbeats) {
timer.cancel();
@@ -71,6 +97,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
@override
void dispose() {
+ _lifecycle.dispose();
_clearNativeContext();
super.dispose();
}
@@ -398,6 +425,9 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
final canvas = KeyedSubtree(key: _canvasKey, child: widget.canvas);
final tab = app.activeSwarm;
final id = tab.superTabId;
+ // Before any open below: a controller starts reading the way it is made.
+ app.superTabs.reading = WorkspaceChrome.of(context).superTabReading;
+ _showTab(tab.isSuperTab ? id : null);
if (!tab.isSuperTab || id == null) {
_clearNativeContext();
_terminalRequest = null;
diff --git a/desktop/lib/web/shell/web_chrome.dart b/desktop/lib/web/shell/web_chrome.dart
index 3b7da0a20..47b0b9481 100644
--- a/desktop/lib/web/shell/web_chrome.dart
+++ b/desktop/lib/web/shell/web_chrome.dart
@@ -1,4 +1,5 @@
import '../../state/app_state.dart';
+import '../../super_tabs/reading.dart';
import '../../state/workspace_chrome.dart';
import '../onboarding/web_first_machine.dart';
import '../footer/web_footer_bar.dart';
@@ -43,4 +44,14 @@ WorkspaceChrome _webWorkspaceChrome(AppNotifier app) => WorkspaceChrome(
labelsPaneStatus: true,
compactPaneHeader: true,
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.
+ superTabReading: const SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ readsOnConnect: true,
+ connectGrace: Duration(seconds: 10),
+ messagesWithState: true,
+ ),
);
diff --git a/desktop/scripts/build-web-release.sh b/desktop/scripts/build-web-release.sh
index 0c08be1fe..061baed9b 100644
--- a/desktop/scripts/build-web-release.sh
+++ b/desktop/scripts/build-web-release.sh
@@ -41,6 +41,30 @@ manifest_path.write_text(json.dumps([e for e in manifest if e not in unused], se
print(f"Dropped {len(unused)} unused icon fonts from the web release.")
PY
+# Flutter asks for the font manifest, then its fonts, only once main.dart.js has run: a step in
+# series after the app's 3 MB on a phone (0.7 s on fast 4G, 3.3 s on slow 4G, #180's report).
+# Preloaded with the same fetch Flutter makes, they come beside main.dart.js and Flutter reuses them.
+python3 - <<'PY'
+import html
+import json
+from pathlib import Path
+import sys
+
+root = Path('build/web-release')
+index_path = root / 'index.html'
+index = index_path.read_text()
+if '</head>' not in index:
+ sys.exit('index.html has no </head>; update the font preload step in build-web-release.sh.')
+manifest = json.loads((root / 'assets/FontManifest.json').read_text())
+assets = ['FontManifest.json'] + [font['asset'] for entry in manifest for font in entry['fonts']]
+links = ''.join(
+ f' <link rel="preload" href="assets/{html.escape(asset)}" as="fetch" crossorigin>\n'
+ for asset in assets
+)
+index_path.write_text(index.replace('</head>', links + '</head>', 1))
+print(f"Preloaded the font manifest and {len(assets) - 1} fonts.")
+PY
+
python3 - "$version" "$source_commit" <<'PY'
import hashlib
import json
diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dart
new file mode 100644
index 000000000..f78203fbe
--- /dev/null
+++ b/desktop/test/super_tab_reading_client_test.dart
@@ -0,0 +1,226 @@
+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/notifications.dart';
+import 'package:harness/super_tabs/reading.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+import 'support/super_tab_fixture.dart';
+
+const _web = SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ readsOnConnect: true,
+ connectGrace: Duration(seconds: 10),
+ messagesWithState: true,
+);
+
+/// Two Swarms behind one machine that may not be connected yet.
+class _Backend {
+ final servers = {'tab': ConversationServer(), 'other': ConversationServer()};
+ final paths = <String>[];
+ bool machine = true;
+
+ _Backend() {
+ servers['other']!.state['id'] = 'other';
+ }
+
+ Future<Object?> call(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ paths.add(path);
+ if (!machine) {
+ throw const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'Connect one of your machines to open Swarm.',
+ );
+ }
+ if (path.startsWith('/api/super-tabs?') || path == '/api/super-tabs') {
+ return {
+ 'tabs': [
+ {'id': 'tab', 'name': 'Pilot'},
+ {'id': 'other', 'name': 'Other'},
+ ],
+ 'next': null,
+ };
+ }
+ final id = Uri.parse(path).pathSegments[2];
+ return servers[id]!.request(method, path, body: body);
+ }
+
+ int states(String id) =>
+ paths.where((p) => p == '/api/super-tabs/$id').length;
+ int get discoveries =>
+ paths.where((p) => Uri.parse(p).path == '/api/super-tabs').length;
+}
+
+SuperTabClient _client(
+ _Backend backend, {
+ SuperTabReading? reading,
+ void Function(SuperTabMention)? onMention,
+}) {
+ final client = SuperTabClient(
+ transport: backend.call,
+ storage: MemoryStore(),
+ onTabs: (_, _) {},
+ onMention: onMention,
+ discoveryInterval: const Duration(seconds: 15),
+ );
+ if (reading != null) client.reading = reading;
+ return client;
+}
+
+void main() {
+ test('only the Swarm tab on screen polls; the others wait until shown', () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final client = _client(backend, reading: _web)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ client.open('other');
+ async.elapse(const Duration(seconds: 1));
+ backend.paths.clear();
+ async.elapse(const Duration(seconds: 20));
+ expect(backend.states('other'), 0);
+ expect(backend.states('tab'), 7);
+ client.show('other');
+ async.flushMicrotasks();
+ expect(backend.states('other'), 1);
+ backend.paths.clear();
+ async.elapse(const Duration(seconds: 30));
+ expect(backend.states('tab'), 0);
+ client.dispose();
+ });
+ });
+
+ test('a hidden page reads nothing; showing it again reads at once', () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final client = _client(backend, reading: _web)
+ ..bind('owner')
+ ..show('tab');
+ client.open('tab');
+ async.elapse(const Duration(seconds: 1));
+ client.pageVisible = false;
+ backend.paths.clear();
+ async.elapse(const Duration(minutes: 2));
+ expect(backend.states('tab'), 0);
+ client.pageVisible = true;
+ async.flushMicrotasks();
+ expect(backend.states('tab'), 1);
+ client.dispose();
+ });
+ });
+
+ test('machines connecting together make one read and one discovery', () {
+ fakeAsync((async) {
+ final backend = _Backend()..machine = false;
+ final client = _client(backend, reading: _web)
+ ..bind('owner')
+ ..show('tab');
+ SuperTabController? opened;
+ client.open('tab').then((c) => opened = c);
+ async.elapse(const Duration(seconds: 1));
+ expect(opened!.snapshot, isNull);
+ backend
+ ..machine = true
+ ..paths.clear();
+ client
+ ..serverAvailable()
+ ..serverAvailable()
+ ..serverAvailable();
+ async.flushMicrotasks();
+ expect(backend.states('tab'), 1);
+ expect(backend.discoveries, 1);
+ expect(opened!.snapshot, isNotNull);
+ client.dispose();
+ });
+ });
+
+ for (final (name, reading) in [('web', _web), ('Desktop', null)]) {
+ test(
+ '$name: a tag in a Swarm opened earlier but not shown is counted and told once',
+ () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final told = <String>[];
+ final client = _client(
+ backend,
+ reading: reading,
+ onMention: (m) => told.add(m.id),
+ )..bind('owner');
+ client.show('tab');
+ client.open('tab');
+ client.open('other');
+ async.elapse(const Duration(seconds: 5));
+ final other = backend.servers['other']!..append('Please confirm.');
+ other.tag(other.messages.last['id'] as String);
+ async.elapse(const Duration(minutes: 2));
+ expect(client.waitingTags('other'), 1);
+ expect(told, ['mention-1']);
+ // Shown again, the Swarm reads its own tags: not told a second time.
+ client.show('other');
+ async.elapse(const Duration(seconds: 10));
+ expect(client.waitingTags('other'), 1);
+ expect(told, ['mention-1']);
+ client.dispose();
+ });
+ },
+ );
+ }
+
+ test('web: a tag that arrives just after the Swarm goes away is told', () {
+ fakeAsync((async) {
+ final backend = _Backend();
+ final told = <String>[];
+ final client = _client(
+ backend,
+ reading: _web,
+ onMention: (m) => told.add(m.id),
+ )..bind('owner');
+ final other = backend.servers['other']!..append('First.');
+ other.tag(other.messages.last['id'] as String);
+ client.show('other');
+ client.open('other');
+ client.open('tab');
+ // On screen, the Swarm reads its own tags: the first is not news.
+ async.elapse(const Duration(seconds: 20));
+ expect(client.waitingTags('other'), 1);
+ client.show('tab');
+ async.flushMicrotasks();
+ other.append('Second.');
+ other.tag(other.messages.last['id'] as String);
+ async.elapse(const Duration(seconds: 16));
+ expect(client.waitingTags('other'), 2);
+ expect(told, ['mention-2']);
+ client.dispose();
+ });
+ });
+
+ test('Desktop reading: a connect waits for the poll, every tab polls', () {
+ fakeAsync((async) {
+ final backend = _Backend()..machine = false;
+ final client = _client(backend)..bind('owner');
+ SuperTabController? opened;
+ client.open('tab').then((c) => opened = c);
+ client.open('other');
+ async.elapse(const Duration(seconds: 1));
+ backend
+ ..machine = true
+ ..paths.clear();
+ client.serverAvailable();
+ async.flushMicrotasks();
+ expect(backend.paths, isEmpty);
+ expect(opened!.error, 'Connect one of your machines to open Swarm.');
+ client.pageVisible = false;
+ async.elapse(const Duration(seconds: 30));
+ expect(backend.states('tab'), 10);
+ expect(backend.states('other'), 10);
+ client.dispose();
+ });
+ });
+}
diff --git a/desktop/test/super_tab_reading_test.dart b/desktop/test/super_tab_reading_test.dart
new file mode 100644
index 000000000..4bd34d079
--- /dev/null
+++ b/desktop/test/super_tab_reading_test.dart
@@ -0,0 +1,508 @@
+import 'dart:async';
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/reading.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// What the web build reads with (`webWorkspaceChrome`).
+const _web = SuperTabReading(
+ quietPoll: Duration(seconds: 15),
+ pausesAway: true,
+ readsOnConnect: true,
+ connectGrace: Duration(seconds: 10),
+ messagesWithState: true,
+);
+
+/// Every read the controller made, in order.
+class _Reads {
+ _Reads(this.server);
+ final ConversationServer server;
+ final paths = <String>[];
+ bool machineMissing = false;
+
+ /// How long each answer takes, as a phone on 4G waits for it.
+ Duration latency = Duration.zero;
+
+ /// While set, each state read waits for a completer added here.
+ List<Completer<void>>? holdState;
+
+ Future<Map<String, dynamic>> call(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) {
+ if (method == 'GET') paths.add(path);
+ if (machineMissing) {
+ return Future.error(
+ const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'Connect one of your machines to open Swarm.',
+ ),
+ );
+ }
+ if (holdState case final held? when path == '/api/super-tabs/tab') {
+ final wait = Completer<void>();
+ held.add(wait);
+ return wait.future.then((_) => server.request(method, path, body: body));
+ }
+ if (latency > Duration.zero) {
+ return Future.delayed(
+ latency,
+ () => server.request(method, path, body: body),
+ );
+ }
+ return server.request(method, path, body: body);
+ }
+
+ int get states => paths.where((p) => p == '/api/super-tabs/tab').length;
+ int get pages => paths.where((p) => p.contains('messages?before=')).length;
+ int get tails => paths.where((p) => p.contains('messages?after=')).length;
+ int get receipts => paths.where((p) => p.contains('messageId=')).length;
+ Iterable<String> get messageReads =>
+ paths.where((p) => p.contains('/messages'));
+ void clear() => paths.clear();
+}
+
+SuperTabController _controller(
+ _Reads reads, {
+ SuperTabReading reading = const SuperTabReading(),
+ Map<String, dynamic> initial = const {},
+}) => SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: reads.call,
+ save: reads.server.save,
+ initial: initial,
+ reading: reading,
+);
+
+void _reply(ConversationServer server, String text) {
+ server.append(text);
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+}
+
+void main() {
+ group('Desktop reading (the default)', () {
+ test('a full read every 3 s, on screen or not, quiet or not', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads)..start();
+ async.flushMicrotasks();
+ c.away = true;
+ async.elapse(const Duration(seconds: 60));
+ reads.clear();
+ async.elapse(const Duration(seconds: 30));
+ expect(reads.states, 10);
+ // Nothing new: each poll reads the page again for its receipts.
+ expect(reads.pages, 10);
+ c.dispose();
+ });
+ });
+
+ test('each poll reads the state, then the messages', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads)..start();
+ async.flushMicrotasks();
+ server.holdReads = Completer<void>();
+ reads.clear();
+ async.elapse(const Duration(seconds: 3));
+ expect(reads.paths, ['/api/super-tabs/tab']);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ c.dispose();
+ });
+ });
+
+ test('every poll is drawn, changed or not', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads)..start();
+ async.elapse(const Duration(seconds: 61));
+ var notified = 0;
+ c.addListener(() => notified++);
+ async.elapse(const Duration(seconds: 30));
+ expect(notified, greaterThanOrEqualTo(10));
+ c.dispose();
+ });
+ });
+
+ test('the first read waits for the state before the messages', () {
+ fakeAsync((async) {
+ final server = ConversationServer()
+ ..append('Hello', conversationId: 'offline')
+ ..holdReads = Completer<void>();
+ final reads = _Reads(server);
+ final c = _controller(
+ reads,
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'offline',
+ },
+ )..start();
+ async.flushMicrotasks();
+ expect(reads.paths, ['/api/super-tabs/tab']);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(reads.messageReads, [
+ '/api/super-tabs/tab/conversations/offline/messages',
+ ]);
+ c.dispose();
+ });
+ });
+
+ test('a first read with no machine shows its error at once', () {
+ fakeAsync((async) {
+ final reads = _Reads(ConversationServer())..machineMissing = true;
+ final c = _controller(reads)..start();
+ async.flushMicrotasks();
+ expect(c.error, 'Connect one of your machines to open Swarm.');
+ expect(c.loading, isFalse);
+ c.dispose();
+ });
+ });
+ });
+
+ group('web reading', () {
+ test(
+ 'a quiet tab reads its state every 15 s, its new messages every 3 s',
+ () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.flushMicrotasks();
+ // Opening counts as the person acting: full reads for the first 30 s.
+ reads.clear();
+ async.elapse(const Duration(seconds: 27));
+ expect(reads.states, 9);
+ async.elapse(const Duration(seconds: 33));
+ reads.clear();
+ async.elapse(const Duration(seconds: 60));
+ expect(reads.states, 4);
+ expect(reads.tails, 20);
+ // The page is read again only with a full read.
+ expect(reads.pages, 4);
+ c.dispose();
+ });
+ },
+ );
+
+ test(
+ 'a reply in the open conversation shows within 3 s of a quiet minute',
+ () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 61));
+ _reply(server, 'The plan is ready.');
+ async.elapse(const Duration(seconds: 3));
+ expect(c.messages('lead').last.text, 'The plan is ready.');
+ // Something new: full reads every 3 s again.
+ reads.clear();
+ async.elapse(const Duration(seconds: 15));
+ expect(reads.states, 5);
+ c.dispose();
+ });
+ },
+ );
+
+ test('the person\'s unsettled message settles within one 3 s check', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Please start.');
+ server.messages.first['deliveries'] = [
+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'claimed'},
+ ];
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 61));
+ // Just after a full read: the next poll is a light check.
+ do {
+ reads.clear();
+ async.elapse(const Duration(seconds: 3));
+ } while (reads.states == 0);
+ expect(
+ c.messages('lead').single.deliveries.single['status'],
+ 'claimed',
+ );
+ server.messages.first['deliveries'] = [
+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'delivered'},
+ ];
+ reads.clear();
+ async.elapse(const Duration(seconds: 3));
+ expect(
+ c.messages('lead').single.deliveries.single['status'],
+ 'delivered',
+ );
+ expect(reads.states, 0);
+ expect(reads.pages, 0);
+ expect(reads.receipts, 1);
+ c.dispose();
+ });
+ });
+
+ test('a light check with nothing new redraws nothing', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 61));
+ do {
+ reads.clear();
+ async.elapse(const Duration(seconds: 3));
+ } while (reads.states == 0);
+ var notified = 0;
+ c.addListener(() => notified++);
+ // The four light checks before the next full read.
+ async.elapse(const Duration(seconds: 12));
+ expect(reads.tails, greaterThanOrEqualTo(5));
+ expect(notified, 0);
+ c.dispose();
+ });
+ });
+
+ test('a full read asks for new messages beside the state', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.flushMicrotasks();
+ server.holdReads = Completer<void>();
+ reads.clear();
+ async.elapse(const Duration(seconds: 3));
+ expect(reads.paths, [
+ '/api/super-tabs/tab/conversations/lead/messages?after=1',
+ '/api/super-tabs/tab',
+ ]);
+ _reply(server, 'Done.');
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ // Its answer is used, not asked for again.
+ expect(reads.tails, 1);
+ c.dispose();
+ });
+ });
+
+ test('a quiet full read with nothing new redraws nothing', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 61));
+ var notified = 0;
+ c.addListener(() => notified++);
+ reads.clear();
+ async.elapse(const Duration(seconds: 30));
+ expect(reads.states, 2);
+ expect(notified, 0);
+ // What the backend works out at read time changes the state without
+ // a new revision (an agent seen down, a limit that ran out): drawn.
+ server.state['name'] = 'Pilot, renamed';
+ reads.clear();
+ do {
+ async.elapse(const Duration(seconds: 3));
+ } while (reads.states == 0);
+ expect(notified, greaterThan(0));
+ expect(c.snapshot!.name, 'Pilot, renamed');
+ notified = 0;
+ // A change is still drawn.
+ server.append('A new line.');
+ async.elapse(const Duration(seconds: 3));
+ expect(notified, greaterThan(0));
+ expect(c.messages('lead').last.text, 'A new line.');
+ c.dispose();
+ });
+ });
+
+ test('a reply shows as its messages answer, not after the state', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.flushMicrotasks();
+ _reply(server, 'Done.');
+ // The state answers slowly; the messages at once.
+ server.holdReads = Completer<void>();
+ final heldStates = <Completer<void>>[];
+ reads.holdState = heldStates;
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.elapse(const Duration(seconds: 3));
+ expect(heldStates, hasLength(1));
+ expect(c.messages('lead').last.text, 'Done.');
+ heldStates.single.complete();
+ async.flushMicrotasks();
+ expect(reads.tails, 1);
+ c.dispose();
+ });
+ });
+
+ test('a slow answer does not stretch the 3 s poll', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server)
+ ..latency = const Duration(milliseconds: 900);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 2));
+ reads.clear();
+ async.elapse(const Duration(seconds: 27));
+ expect(reads.states, 9);
+ c.dispose();
+ });
+ });
+
+ test('away reads nothing; back reads at once', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 6));
+ // Sent away while a poll is under way: it does not schedule another.
+ server.holdReads = Completer<void>();
+ async.elapse(const Duration(seconds: 3));
+ c.away = true;
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ reads.clear();
+ async.elapse(const Duration(minutes: 5));
+ expect(reads.paths, isEmpty);
+ c.away = false;
+ async.flushMicrotasks();
+ expect(reads.states, 1);
+ reads.clear();
+ async.elapse(const Duration(seconds: 15));
+ expect(reads.states, 5);
+ c.dispose();
+ });
+ });
+
+ test('sending reads at once and keeps the full poll', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Hello');
+ final reads = _Reads(server);
+ final c = _controller(reads, reading: _web)..start();
+ async.elapse(const Duration(seconds: 61));
+ c.setDraft('lead', 'Go ahead.');
+ reads.clear();
+ unawaited(c.send());
+ async.flushMicrotasks();
+ expect(reads.states, greaterThanOrEqualTo(1));
+ reads.clear();
+ async.elapse(const Duration(seconds: 15));
+ expect(reads.states, 5);
+ c.dispose();
+ });
+ });
+
+ test('the saved conversation\'s messages are read beside the state', () {
+ fakeAsync((async) {
+ final server = ConversationServer()
+ ..append('Hello', conversationId: 'offline')
+ ..holdReads = Completer<void>();
+ final reads = _Reads(server);
+ final c = _controller(
+ reads,
+ reading: _web,
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'offline',
+ },
+ )..start();
+ async.flushMicrotasks();
+ expect(reads.paths, [
+ '/api/super-tabs/tab/conversations/offline/messages',
+ '/api/super-tabs/tab',
+ ]);
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(c.selectedId, 'offline');
+ expect(c.messages('offline').single.text, 'Hello');
+ // One page: the early read is the first round's.
+ expect(reads.messageReads, hasLength(1));
+ c.dispose();
+ });
+ });
+
+ test('a saved conversation that is gone drops its early page', () {
+ fakeAsync((async) {
+ final server = ConversationServer()
+ ..append('Hello')
+ ..holdReads = Completer<void>();
+ final reads = _Reads(server);
+ final c = _controller(
+ reads,
+ reading: _web,
+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'gone'},
+ )..start();
+ async.flushMicrotasks();
+ server.holdReads!.complete();
+ server.holdReads = null;
+ async.flushMicrotasks();
+ expect(c.selectedId, 'lead');
+ expect(c.messages('lead').single.text, 'Hello');
+ expect(c.messages('gone'), isEmpty);
+ expect(
+ reads.messageReads.last,
+ '/api/super-tabs/tab/conversations/lead/messages',
+ );
+ c.dispose();
+ });
+ });
+
+ test('with no machine yet it keeps loading for the grace, then errs', () {
+ fakeAsync((async) {
+ final reads = _Reads(ConversationServer())..machineMissing = true;
+ final c = _controller(reads, reading: _web)..start();
+ async.flushMicrotasks();
+ expect(c.error, isNull);
+ expect(c.loading, isTrue);
+ async.elapse(const Duration(seconds: 9));
+ expect(c.error, isNull);
+ expect(c.loading, isTrue);
+ async.elapse(const Duration(seconds: 1));
+ expect(c.error, 'Connect one of your machines to open Swarm.');
+ expect(c.loading, isFalse);
+ reads.machineMissing = false;
+ async.elapse(const Duration(seconds: 3));
+ expect(c.snapshot, isNotNull);
+ expect(c.error, isNull);
+ c.dispose();
+ });
+ });
+
+ test('a machine connecting within the grace never shows the error', () {
+ fakeAsync((async) {
+ final reads = _Reads(ConversationServer())..machineMissing = true;
+ final c = _controller(reads, reading: _web)..start();
+ final errors = <String?>[];
+ c.addListener(() => errors.add(c.error));
+ async.elapse(const Duration(seconds: 4));
+ reads.machineMissing = false;
+ unawaited(c.machineAvailable());
+ async.flushMicrotasks();
+ expect(c.snapshot, isNotNull);
+ async.elapse(const Duration(seconds: 10));
+ expect(errors.whereType<String>(), isEmpty);
+ c.dispose();
+ });
+ });
+ });
+}
diff --git a/desktop/test/super_tab_reading_workspace_test.dart b/desktop/test/super_tab_reading_workspace_test.dart
new file mode 100644
index 000000000..749d054b7
--- /dev/null
+++ b/desktop/test/super_tab_reading_workspace_test.dart
@@ -0,0 +1,193 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:harness/viewer/viewer_services.dart';
+import 'package:harness/state/workspace_chrome.dart';
+import 'package:harness/super_tabs/workspace.dart';
+import 'package:harness/web/shell/web_chrome.dart';
+
+import 'super_tab_launch_test.dart'
+ show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;
+import 'swarm_state_test.dart' show MemoryStore;
+
+/// The Swarm state reads the fixture's machine has answered.
+int _stateReads(SuperTabLaunchFixture f) => _connectionReads(f.connection);
+
+int _connectionReads(SuperTabFixtureConnection connection) => connection.calls
+ .where(
+ (c) =>
+ c.$1 == 'super_tabs' &&
+ c.$2['method'] == 'GET' &&
+ c.$2['path'] == '/api/super-tabs/$tabId',
+ )
+ .length;
+
+/// A browser's app with one computer of its own, not connected yet, and a
+/// Swarm tab restored on screen.
+({AppNotifier app, SuperTabFixtureConnection connection}) _viewer() {
+ final store = MemoryStore();
+ final connection = SuperTabFixtureConnection(store);
+ final session = AuthSession(storage: MemoryStore());
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ viewer: ViewerServices(
+ config: AppConfig.dev,
+ session: session,
+ keys: ViewerKeyStore(storage: MemoryStore()),
+ ),
+ connectionForTest: (_) => connection,
+ paneLayoutStore: PaneLayoutStore(storage: store),
+ );
+ connection.app = app;
+ const machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Studio Mac',
+ );
+ app.machines = [machine];
+ app.machineStates['m'] = MachineState(machine)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connecting
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ app.bindSuperTab(app.activeSwarmId, tabId, 'Pilot');
+ return (app: app, connection: connection);
+}
+
+/// The page hidden, the way a browser reports it: losing focus first.
+void _hide(WidgetTester tester) {
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
+}
+
+void _reveal(WidgetTester tester) {
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+}
+
+Future<void> _mount(
+ WidgetTester tester,
+ SuperTabLaunchFixture f, {
+ WorkspaceChrome? chrome,
+}) => _mountApp(tester, f.app, chrome: chrome);
+
+Future<void> _mountApp(
+ WidgetTester tester,
+ AppNotifier app, {
+ WorkspaceChrome? chrome,
+}) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: WorkspaceChromeScope(
+ chrome: chrome,
+ child: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: app,
+ canvas: const SizedBox.expand(),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+}
+
+void main() {
+ testWidgets('Desktop: a Swarm tab not shown keeps its 3 s poll', (
+ tester,
+ ) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ await _mount(tester, f);
+ final swarm = f.app.activeSwarmId;
+ f.app.newSwarm();
+ await tester.pump();
+ final before = _stateReads(f);
+ await tester.pump(const Duration(seconds: 30));
+ expect(_stateReads(f) - before, 10);
+ f.app.selectSwarm(swarm);
+ _hide(tester);
+ final hidden = _stateReads(f);
+ await tester.pump(const Duration(seconds: 30));
+ expect(_stateReads(f) - hidden, 10);
+ _reveal(tester);
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ });
+
+ testWidgets('web: another tab or a hidden page stops the Swarm tab reading', (
+ tester,
+ ) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ await _mount(tester, f, chrome: webWorkspaceChrome(f.app));
+ final swarm = f.app.activeSwarmId;
+ await tester.pump(const Duration(seconds: 3));
+ expect(_stateReads(f), greaterThanOrEqualTo(2));
+ f.app.newSwarm();
+ await tester.pump();
+ var before = _stateReads(f);
+ await tester.pump(const Duration(seconds: 30));
+ expect(_stateReads(f), before);
+ f.app.selectSwarm(swarm);
+ await tester.pump();
+ await tester.pump();
+ expect(_stateReads(f), before + 1);
+ _hide(tester);
+ await tester.pump();
+ before = _stateReads(f);
+ await tester.pump(const Duration(seconds: 30));
+ expect(_stateReads(f), before);
+ _reveal(tester);
+ await tester.pump();
+ expect(_stateReads(f), before + 1);
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ });
+
+ // At the app's level: a viewer's connect also loads the machine's data and
+ // its device log, whose timers a widget test would have to wait out.
+ test('web: the machine connecting reads the Swarm tab at once', () async {
+ final v = _viewer();
+ v.app.superTabs
+ ..reading = webWorkspaceChrome(v.app).superTabReading
+ ..show(tabId);
+ final c = await v.app.superTabs.open(tabId);
+ await pumpEventQueue();
+ expect(c.snapshot, isNull);
+ // Within the grace: loading, not the error.
+ expect(c.error, isNull);
+ expect(c.loading, isTrue);
+ v.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await pumpEventQueue();
+ expect(c.snapshot, isNotNull);
+ v.app.dispose();
+ });
+
+ test('Desktop reading: the machine connecting waits for the poll', () async {
+ final v = _viewer();
+ final c = await v.app.superTabs.open(tabId);
+ await pumpEventQueue();
+ expect(c.error, 'Connect one of your machines to open Swarm.');
+ final reads = _connectionReads(v.connection);
+ v.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await pumpEventQueue();
+ expect(_connectionReads(v.connection), reads);
+ expect(c.snapshot, isNull);
+ v.app.dispose();
+ });
+}
diff --git a/desktop/test/web_release_script_test.dart b/desktop/test/web_release_script_test.dart
index fd26e391d..c57fbff47 100644
--- a/desktop/test/web_release_script_test.dart
+++ b/desktop/test/web_release_script_test.dart
@@ -23,6 +23,11 @@ String _assetOf(String family) => switch (family) {
_ => 'fonts/${family.replaceAll(' ', '-')}.ttf',
};
+/// The page `flutter build web` writes, cut down to what the script edits.
+const _index =
+ '<!DOCTYPE html><html><head><base href="/harness-web/"></head>'
+ '<body><script>/* flutter_bootstrap */</script></body></html>';
+
/// Stands in for `flutter build web`: writes the fonts a real build lists for
/// this app into the `--output` directory the script passes.
String _fakeFlutter(List<String> families) {
@@ -43,6 +48,7 @@ for arg in "\$@"; do
done
mkdir -p "\$out/assets"
printf '%s' '$manifest' > "\$out/assets/FontManifest.json"
+printf '%s' '$_index' > "\$out/index.html"
for asset in $assets; do
mkdir -p "\$out/assets/\$(dirname "\$asset")"
echo font > "\$out/assets/\$asset"
@@ -92,6 +98,12 @@ List<String> _manifestFamilies(Directory repo) {
];
}
+String _builtIndex(Directory repo) =>
+ File(p.join(repo.path, 'build/web-release/index.html')).readAsStringSync();
+
+String _preload(String asset) =>
+ '<link rel="preload" href="assets/$asset" as="fetch" crossorigin>';
+
bool _shipped(Directory repo, String family) =>
File(p.join(repo.path, 'build/web-release/assets', _assetOf(family)))
.existsSync();
@@ -132,6 +144,21 @@ void main() {
expect(files.where((file) => file.endsWith('lucide.ttf')), isEmpty);
}, skip: skip);
+ test('the page fetches the fonts it ships beside the app, not after it', () async {
+ final result = await _release(repo, [..._others, ..._unusedLucide, _used]);
+
+ expect(result.exitCode, 0, reason: '${result.stderr}');
+ final index = _builtIndex(repo);
+ final head = index.substring(0, index.indexOf('</head>'));
+ expect(head, contains(_preload('FontManifest.json')));
+ for (final family in [..._others, _used]) {
+ expect(head, contains(_preload(_assetOf(family))), reason: family);
+ }
+ for (final family in _unusedLucide) {
+ expect(index, isNot(contains(_assetOf(family))), reason: family);
+ }
+ }, skip: skip);
+
test('a build with no Lucide 400 font fails instead of shipping blind', () async {
final result = await _release(repo, [..._others, ..._unusedLucide]);