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.

fix(web): one backed-off machine-list watch instead of three loops (#1801)

Jacob Phamc58f1064098d
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 2bfd2bf4c..eb0136c51 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -299,8 +299,14 @@ The native desktop target uses the CLI for cloud access and SSO tokens:
showing the machine as connecting; only a refusal that outlasts two rounds (~15s), or a frozen
log, asks for the password. The desk frames (`app_focus`, `app_panes`, `app_swarms`, `app_unread`,
`agent_seen`) are for this computer's daemon and only ride a loopback connection. A viewer with no
- machine connected hears no push, so it re-reads the machine list every 20s while that lasts
- (`deafMachineListInterval`) and when the tab comes back to the front.
+ machine connected hears no push, so it re-reads the machine list itself while that lasts
+ (`state/machine_list_watch.dart`): after 4 s, 8 s, then every 10 s under the connect page
+ (`waitsForFirstComputer`), or 15 s then every 30 s under the asleep band, and every 20 s
+ otherwise (a computer still connecting). A push, the tab coming back to the front (which reads
+ at once) and Retry start that pace over, and while recovery retries a failed or stale list it is
+ the only one asking. A hidden tab reads nothing on this pace; the one read it still makes is the
+ 5-minute safety net every window keeps (`machineListSafetyNetInterval`). The browser's connect
+ page and asleep band keep no timer of their own.
- **Both REST and the local WS prefer the daemon's Unix socket** (`lib/ws/local_daemon_transport.dart`;
CLI `lib/localSocket.ts`): `~/.harness/cli/data/daemon-<port>.sock`, 0600, named for the port in
`localCliBaseUrl` so it always leads to the same daemon as the TCP fallback. The loopback port takes
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 8feb49ef5..56d95521a 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -700,8 +700,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
_recordNavigation();
app.addListener(_recordNavigation);
app.addListener(_observeLearning);
- _syncMachineListWatch();
- app.addListener(_syncMachineListWatch);
// Its own notifier, so marking one agent does not rebuild the workspace —
// which means the badge has to ask for its own redraw.
app.agentUnread.addListener(_unreadChanged);
@@ -1008,8 +1006,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
terminalFontStore.removeListener(_fontChanged);
app.removeListener(_recordNavigation);
app.removeListener(_observeLearning);
- app.removeListener(_syncMachineListWatch);
- _machineListWatch?.cancel();
app.removeListener(_followTabStripFocus);
_tabStripFocus.removeListener(_tabStripFocusChanged);
_tabStripFocus.dispose();
@@ -7417,16 +7413,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
machine.connectionStatus == ConnectionStatus.connected,
);
- /// The inventory has answered, and answered for now: loaded, not loading,
- /// not stale, no error. What the account HAS, independent of what is open.
- bool get _machineInventorySettled =>
- app.machineInventoryLoaded &&
- !app.machinesLoading &&
- !app.machinesAreStale &&
- app.machineListError == null;
-
bool get _browserMachineSetupReady =>
- _machineInventorySettled &&
+ app.machineInventorySettled &&
!app.machineStates.values.any(
(machine) =>
!machine.machine.isShared &&
@@ -7441,53 +7429,14 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search == null &&
_routeIsCurrent;
- /// No computer of the account's is connected, and none is on its way: the
- /// inventory has answered, and every one is missing, offline or waiting to
- /// be linked — what the host's [WorkspaceChrome.firstMachine] is for. Not
- /// when every one is only asleep ([_asleepComputers]): that account has set
- /// one up, and keeps its panes.
- bool get _needsFirstConnection =>
- _machineInventorySettled &&
- !_computerConnectedOrComing &&
- _asleepComputers.isEmpty;
-
- /// A computer of the account's is connected, or on its way.
- bool get _computerConnectedOrComing =>
- _hasConnectedBrowserMachine ||
- app.machineStates.values.any(
- (machine) =>
- !machine.machine.isShared &&
- !machine.needsLink &&
- machine.nodeOnline != false &&
- (machine.connectionStatus == ConnectionStatus.connecting ||
- machine.connectionStatus == ConnectionStatus.reconnecting),
- );
-
- /// The account's own computers, all of them offline and none waiting on this
- /// one to be linked: set up before, asleep now. Empty for an account with
- /// none (a computer taken out of it does not count) — that one needs setting
- /// up — and while any is connected, on its way, or waiting to be linked.
- List<MachineState> get _asleepComputers {
- final own = [
- for (final machine in app.machineStates.values)
- if (!machine.machine.isShared &&
- !app.removedMachines.containsKey(machine.machine.machineId))
- machine,
- ];
- if (own.any((machine) => machine.needsLink || !machine.isOffline)) {
- return const [];
- }
- return own;
- }
-
/// The host's connect page covers the canvas: before the machine list first
/// answers — the page says it is looking, instead of a New tab page that
- /// then gives way — and while there is no computer to use. Never over a
- /// computer that is connected or on its way.
+ /// then gives way — and while there is no computer to use
+ /// ([AppNotifier.waitsForFirstComputer]). Never over a computer that is
+ /// connected or on its way, nor when every one is only asleep: that account
+ /// has set one up, and keeps its panes.
bool get _firstMachineCovers =>
- widget.chrome?.firstMachine != null &&
- (_needsFirstConnection ||
- (!app.machineInventoryLoaded && !_computerConnectedOrComing));
+ widget.chrome?.firstMachine != null && app.waitsForFirstComputer;
/// Under the host's connect page, the canvas is out of sight, out of the
/// accessibility tree and out of Tab's reach: its buttons cannot be pressed.
@@ -7506,37 +7455,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// that their panes come back with them. Never on Desktop.
bool get _showsAsleepBand =>
widget.chrome?.firstMachine != null &&
- _machineInventorySettled &&
- _asleepComputers.isNotEmpty;
+ app.machineInventorySettled &&
+ app.asleepComputers.isNotEmpty;
Widget? _asleepBand() => _showsAsleepBand
? _AsleepBand(
names: [
- for (final machine in _asleepComputers) machine.machine.displayName,
+ for (final machine in app.asleepComputers) machine.machine.displayName,
],
)
: null;
- /// The one timer asking for the machine list while the host's connect page
- /// or the asleep band shows: a browser with no computer connected hears of
- /// one signing in, or waking up, no other way — its connections to
- /// computers are what carry that news. Stopped once one is connected or on
- /// its way, and with the workspace.
- Timer? _machineListWatch;
- static const _machineListWatchEvery = Duration(seconds: 4);
-
- void _syncMachineListWatch() {
- if (!_firstMachineCovers && !_showsAsleepBand) {
- _machineListWatch?.cancel();
- _machineListWatch = null;
- return;
- }
- _machineListWatch ??= Timer.periodic(
- _machineListWatchEvery,
- (_) => unawaited(app.rereadMachines()),
- );
- }
-
/// The shared error banner shows — except when its only message is the
/// machine list's failure, which the host's connect page already shows with
/// its own Retry: a phone would read it twice.
@@ -8628,7 +8557,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// answered, and none of the account's own is in it. Never while it loads.
bool get _subscriptionsWaitForComputer =>
widget.chrome?.subscriptionsNeedComputer == true &&
- _machineInventorySettled &&
+ app.machineInventorySettled &&
!app.machineStates.values.any(
(machine) =>
!machine.machine.isShared &&
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index e5551aa3b..27a6942e1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -113,6 +113,7 @@ import '../widgets/engine_identity.dart'
show allEngines, engineIdentity, isCloudAgentId, isTerminalEngine;
import '../store/store_screen.dart' show openStoreAgent;
import 'dial_status.dart';
+import 'machine_list_watch.dart';
import 'grid_pictures.dart';
import 'model_start_watch.dart';
import 'harness_placement.dart';
@@ -961,11 +962,19 @@ class AppNotifier extends ChangeNotifier {
bool get inForeground => foreground.value;
+ /// Whether the window can be seen at all: in front, or in sight behind the window that has focus
+ /// (`inactive`). A browser tab behind others, or a minimised window, cannot.
+ bool _inSight = true;
+
/// Fed by the workspace's [AppLifecycleListener]. A null state is unknown, read as foreground.
void appLifecycleChanged(AppLifecycleState? state) {
if (_disposed) return;
final wasForeground = foreground.value;
foreground.value = state == null || state == AppLifecycleState.resumed;
+ _inSight =
+ state == null ||
+ state == AppLifecycleState.resumed ||
+ state == AppLifecycleState.inactive;
// Every transition, not only the three the listener has callbacks for: hidden -> inactive fires
// onShow, and a window shown again without focus must not keep telling the daemon it shows nothing.
_announceVisibleAgents();
@@ -990,8 +999,9 @@ class AppNotifier extends ChangeNotifier {
}
_refreshDeviceLogAfterReconnect();
// ...and, hearing no machine at all, looks again for one: the person most likely just went to
- // their computer to sign it in.
- _rereadMachinesWhileDeaf();
+ // their computer to sign it in. The wait for the next read starts over too.
+ _deafMachineListWatch.reset();
+ unawaited(_rereadMachinesWhileDeaf());
}
}
@@ -1103,7 +1113,17 @@ class AppNotifier extends ChangeNotifier {
Timer? _sharingDiscoveryTimer;
// A viewer with no machine socket open hears no push at all — a machine that joins the account is
// only found by this. See [_rereadMachinesWhileDeaf].
- Timer? _deafMachineListTimer;
+ late final _deafMachineListWatch = MachineListWatch(
+ wanted: () => _deafReadWanted,
+ read: _rereadMachinesWhileDeaf,
+ pace: () =>
+ deafMachineListPaceForTest ??
+ (waitsForFirstComputer
+ ? firstComputerMachineListPace
+ : asleepComputers.isNotEmpty
+ ? asleepComputersMachineListPace
+ : deafMachineListPace),
+ );
bool _sharingDiscoveryBusy = false;
bool _sharingDiscoveryAgain = false;
int _machineRecoveryAttempts = 0;
@@ -4724,8 +4744,27 @@ class AppNotifier extends ChangeNotifier {
/// running `harness login` on their computer — nothing tells it that computer has joined, and the
/// safety net above would leave the person staring at an empty list for five minutes. Only while
/// it is deaf, so the traffic note above holds for every window that has a machine.
+ ///
+ /// Every 20 s, except under the browser's connect page and asleep band: there it backs off, soon
+ /// at first and then less often while nothing changes, and soon again on a push, a return to the
+ /// tab or the person's Retry ([MachineListWatch]). An account waiting for its first computer
+ /// ([waitsForFirstComputer]) has a person at the connect page while it installs, which can take
+ /// minutes, so it never waits long; one whose computers are all asleep ([asleepComputers]) can
+ /// wait longer.
+ static const deafMachineListPace = <Duration>[Duration(seconds: 20)];
+ static const firstComputerMachineListPace = <Duration>[
+ Duration(seconds: 4),
+ Duration(seconds: 8),
+ Duration(seconds: 10),
+ ];
+ static const asleepComputersMachineListPace = <Duration>[
+ Duration(seconds: 4),
+ Duration(seconds: 8),
+ Duration(seconds: 15),
+ Duration(seconds: 30),
+ ];
@visibleForTesting
- Duration deafMachineListInterval = const Duration(seconds: 20);
+ List<Duration>? deafMachineListPaceForTest;
MachineState? stateOf(String machineId) => machineStates[machineId];
@@ -7315,8 +7354,7 @@ class AppNotifier extends ChangeNotifier {
_daemonSupervisionTimer = null;
_sharingDiscoveryTimer?.cancel();
_sharingDiscoveryTimer = null;
- _deafMachineListTimer?.cancel();
- _deafMachineListTimer = null;
+ _deafMachineListWatch.stop();
_groupSyncedAt.clear();
_sharingDiscoveryBusy = false;
_sharingDiscoveryAgain = false;
@@ -9058,6 +9096,8 @@ class AppNotifier extends ChangeNotifier {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return null;
final request = ++_machineInventoryRevision;
+ // From the first read on, answered or not: a list that failed is looked for again too.
+ if (viewer != null) _deafMachineListWatch.start();
if (localManualFixture != null) {
_machineInventoryLoaded = true;
notifyListeners();
@@ -9453,18 +9493,56 @@ class AppNotifier extends ChangeNotifier {
}
unawaited(_rereadMachinesInBackground(pushed: false));
});
- if (viewer != null) {
- // Only while the tab is in front: a tab left open behind others, its machines all off,
- // would otherwise ask every 20s for as long as the browser runs. Coming back to it asks at once.
- _deafMachineListTimer ??= Timer.periodic(deafMachineListInterval, (_) {
- if (foreground.value) _rereadMachinesWhileDeaf();
- });
- }
notifyListeners();
// A grant that has just arrived places what waited for it (R2).
_placeSharedPanesSoon();
}
+ /// The inventory has answered, and answered for now: loaded, not loading,
+ /// not stale, no error. What the account HAS, independent of what is open.
+ bool get machineInventorySettled =>
+ machineInventoryLoaded &&
+ !machinesLoading &&
+ !machinesAreStale &&
+ machineListError == null;
+
+ /// A computer of the account's is connected, or on its way.
+ bool get computerConnectedOrComing => machineStates.values.any(
+ (machine) =>
+ !machine.machine.isShared &&
+ !machine.needsLink &&
+ machine.nodeOnline != false &&
+ (machine.connectionStatus == ConnectionStatus.connected ||
+ machine.connectionStatus == ConnectionStatus.connecting ||
+ machine.connectionStatus == ConnectionStatus.reconnecting),
+ );
+
+ /// What a host's connect page is for: before the machine list first
+ /// answers, and once it has, while no computer of the account's is
+ /// connected or on its way and none is only asleep ([asleepComputers]) —
+ /// every one is missing, offline or waiting to be linked.
+ bool get waitsForFirstComputer =>
+ !computerConnectedOrComing &&
+ (!machineInventoryLoaded ||
+ (machineInventorySettled && asleepComputers.isEmpty));
+
+ /// The account's own computers, all of them offline and none waiting on this
+ /// one to be linked: set up before, asleep now. Empty for an account with
+ /// none (a computer taken out of it does not count) — that one needs setting
+ /// up — and while any is connected, on its way, or waiting to be linked.
+ List<MachineState> get asleepComputers {
+ final own = [
+ for (final machine in machineStates.values)
+ if (!machine.machine.isShared &&
+ !removedMachines.containsKey(machine.machine.machineId))
+ machine,
+ ];
+ if (own.any((machine) => machine.needsLink || !machine.isOffline)) {
+ return const [];
+ }
+ return own;
+ }
+
/// Whether this viewer has no machine socket open, so no push can reach it.
bool get _viewerIsDeaf =>
viewer != null &&
@@ -9474,13 +9552,24 @@ class AppNotifier extends ChangeNotifier {
m.connectionStatus == ConnectionStatus.connected,
);
+ /// Whether the deaf watch's next tick reads: a viewer that hears nothing, in sight — a tab left
+ /// open behind others, its machines all off, would otherwise ask for as long as the browser runs;
+ /// the 5-minute safety net ([machineListSafetyNetInterval]) is the one read it still makes —
+ /// and not while recovery is the one asking (a failed or stale list, see
+ /// [_scheduleMachineRecovery]) or a reload is open, so two never read side by side.
+ bool get _deafReadWanted =>
+ _inSight &&
+ _viewerIsDeaf &&
+ _machineRecoveryTimer == null &&
+ _retryInFlight == null;
+
/// A viewer that hears nothing re-reads the machine list: the computer the person is signing in
/// on right now appears, and the dial that follows reads the device log for its key first.
- void _rereadMachinesWhileDeaf() {
+ Future<void> _rereadMachinesWhileDeaf() async {
if (_disposed || status != AppStatus.authenticated || !_viewerIsDeaf) {
return;
}
- unawaited(_rereadMachinesInBackground(pushed: false));
+ await _rereadMachinesInBackground(pushed: false);
}
/// Re-read the machine list because something other than the person asked:
@@ -9491,14 +9580,9 @@ class AppNotifier extends ChangeNotifier {
/// exactly one more follows it. A bulk rename pushes once per machine;
/// without this each push would be its own pair of requests. A timer tick
/// that finds a read open has nothing to add and is dropped.
- /// Read the machine list again quietly — no loading state, the rows on
- /// screen stay — as a missed `machines_changed` push would. For a screen
- /// waiting on a computer this window has no connection to hear that push
- /// through: an account with none connected yet (the browser's connect page).
- Future<void> rereadMachines() => _rereadMachinesInBackground(pushed: false);
-
Future<void> _rereadMachinesInBackground({required bool pushed}) async {
if (_disposed || status != AppStatus.authenticated) return;
+ if (pushed) _deafMachineListWatch.reset();
if (_sharingDiscoveryBusy) {
if (pushed) _sharingDiscoveryAgain = true;
return;
@@ -11053,7 +11137,10 @@ class AppNotifier extends ChangeNotifier {
/// the error strip's own retry.
Future<void>? _retryInFlight;
- Future<void> retryMachines() => _retryMachines(automatic: false);
+ Future<void> retryMachines() {
+ _deafMachineListWatch.reset();
+ return _retryMachines(automatic: false);
+ }
Future<void> _retryMachines({required bool automatic}) {
if (_disposed) return Future<void>.value();
@@ -21515,7 +21602,7 @@ class AppNotifier extends ChangeNotifier {
_disposed = true;
_closeAttachmentSessions();
_sharingDiscoveryTimer?.cancel();
- _deafMachineListTimer?.cancel();
+ _deafMachineListWatch.stop();
_stopMachineRecovery();
if (signingIn) cliLogin.cancel();
_closedHistory.clear();
diff --git a/desktop/lib/state/machine_list_watch.dart b/desktop/lib/state/machine_list_watch.dart
new file mode 100644
index 000000000..ba7dabb0a
--- /dev/null
+++ b/desktop/lib/state/machine_list_watch.dart
@@ -0,0 +1,79 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+/// The pace of the machine-list reads a browser makes on its own while it hears no push
+/// ([AppNotifier]'s deaf watch): soon at first, then less often the longer nothing changes.
+///
+/// One timer at a time. A tick reads when [wanted] says so and moves one step along [pace]; a tick
+/// that does not read (the tab hidden, a computer connected, recovery asking instead) goes back to
+/// the first step, so the wait starts over the moment reading is wanted again. [reset] does the
+/// same from outside: a push, the tab coming back, the person's Retry.
+class MachineListWatch {
+ MachineListWatch({
+ required this.wanted,
+ required this.read,
+ required this.pace,
+ });
+
+ /// Whether a tick should read now.
+ final bool Function() wanted;
+ final Future<void> Function() read;
+
+ /// The waits between reads; the last one repeats. Asked once a read has finished, not while it
+ /// is open, since the read itself changes what the screen shows (the list loading).
+ final List<Duration> Function() pace;
+
+ Timer? _timer;
+ int _step = 0;
+ bool _running = false;
+
+ /// Bumped by [stop], so a read still open from before cannot arm a timer after it.
+ int _generation = 0;
+
+ bool get running => _running;
+
+ void start() {
+ if (_running) return;
+ _running = true;
+ _schedule();
+ }
+
+ void stop() {
+ _timer?.cancel();
+ _timer = null;
+ _running = false;
+ _step = 0;
+ _generation++;
+ }
+
+ /// The next read comes after the first wait again.
+ void reset() {
+ _step = 0;
+ final timer = _timer;
+ // No timer: a read is open, and it schedules from the first wait when it ends.
+ if (timer == null) return;
+ timer.cancel();
+ _schedule();
+ }
+
+ void _schedule() {
+ final steps = pace();
+ _timer = Timer(steps[math.min(_step, steps.length - 1)], _tick);
+ }
+
+ Future<void> _tick() async {
+ _timer = null;
+ final generation = _generation;
+ if (wanted()) {
+ _step++;
+ try {
+ await read();
+ } catch (_) {
+ // A failed read is the reader's to report; the pace goes on.
+ }
+ } else {
+ _step = 0;
+ }
+ if (generation == _generation) _schedule();
+ }
+}
diff --git a/desktop/test/device_viewer_notices_test.dart b/desktop/test/device_viewer_notices_test.dart
index 69084dcbb..d7c8501ac 100644
--- a/desktop/test/device_viewer_notices_test.dart
+++ b/desktop/test/device_viewer_notices_test.dart
@@ -355,7 +355,7 @@ void main() {
session: AuthSession(storage: MemoryStore()),
keys: keys,
),
- )..deafMachineListInterval = const Duration(milliseconds: 40);
+ )..deafMachineListPaceForTest = const [Duration(milliseconds: 40)];
final api = _Api(backend)..user = 'user-a';
app.api = api;
addTearDown(app.dispose);
@@ -378,7 +378,7 @@ void main() {
// Back to the tab (the person was signing in their computer): asked for at once.
final beforeResume = api.machineReads;
- app.deafMachineListInterval = const Duration(hours: 1);
+ app.deafMachineListPaceForTest = const [Duration(hours: 1)];
app.appLifecycleChanged(AppLifecycleState.resumed);
await settle();
expect(api.machineReads, greaterThan(beforeResume));
diff --git a/desktop/test/support/web_ux_app.dart b/desktop/test/support/web_ux_app.dart
index 99ac5cbd0..4d8695807 100644
--- a/desktop/test/support/web_ux_app.dart
+++ b/desktop/test/support/web_ux_app.dart
@@ -51,9 +51,6 @@ class WebUxApp extends AppNotifier {
@override
Future<bool> refreshMachines() async => true;
- @override
- Future<void> rereadMachines() async {}
-
@override
Future<bool> connectTrusted(String machineId, {Duration? timeout}) async =>
false;
diff --git a/desktop/test/unlinked_machine_load_test.dart b/desktop/test/unlinked_machine_load_test.dart
index 538cc214c..c42357741 100644
--- a/desktop/test/unlinked_machine_load_test.dart
+++ b/desktop/test/unlinked_machine_load_test.dart
@@ -45,9 +45,13 @@ class _Api extends ApiClient {
_Api() : super(config: AppConfig.dev, session: AuthSession());
int logReads = 0;
+ int machineReads = 0;
@override
- Future<List<Machine>> machines() async => const [_reachable, _unlinked];
+ Future<List<Machine>> machines() async {
+ machineReads++;
+ return const [_reachable, _unlinked];
+ }
@override
Future<DeviceLogFetched?> deviceKeys(int since, {String? self}) async {
@@ -225,21 +229,39 @@ void main() {
test('$host: four idle minutes load nothing and print nothing', () {
fakeAsync((clock) {
final rig = _Rig(clock, browser: browser)..start();
- // The connect page's watch, or any other machine-list reader.
- final watch = Timer.periodic(
- const Duration(seconds: 4),
- (_) => rig.app.rereadMachines(),
- );
+ Timer? pushes;
+ if (browser) {
+ // Its other computer gone too, the browser hears nothing and reads the list itself —
+ // the connect page's case — every 4 s here.
+ rig.app.connectionStatusForTest(
+ _reachable.machineId,
+ ConnectionStatus.disconnected,
+ );
+ rig.app.deafMachineListPaceForTest = const [Duration(seconds: 4)];
+ } else {
+ // Desktop reads it quietly when told it changed.
+ pushes = Timer.periodic(
+ const Duration(seconds: 4),
+ (_) => rig.app.handleEventForTest(_reachable.machineId, {
+ 'type': 'machines_changed',
+ 'payload': <String, dynamic>{},
+ }),
+ );
+ }
+ clock.flushMicrotasks();
lines.clear();
final dials = rig.dials;
+ final reads = rig.api.machineReads;
clock.elapse(const Duration(minutes: 4));
+ // The list really was read, every 4 s.
+ expect(rig.api.machineReads - reads, greaterThanOrEqualTo(60));
expect(loads(), 0);
expect(lines, isEmpty);
// The link retry alone, 30 s apart by now.
expect(rig.dials - dials, 8);
- watch.cancel();
+ pushes?.cancel();
rig.dispose();
});
});
diff --git a/desktop/test/web_machine_list_watch_test.dart b/desktop/test/web_machine_list_watch_test.dart
new file mode 100644
index 000000000..798026c58
--- /dev/null
+++ b/desktop/test/web_machine_list_watch_test.dart
@@ -0,0 +1,379 @@
+// A browser with no computer connected hears no push, so it asks for the machine list on its own
+// while the connect page or the asleep band shows. One loop does that, in the app model, backing
+// off as the wait goes on; these count its reads second by second, with the real app model and the
+// real workspace.
+//
+// Measured on main before the loop (five simulated minutes): the connect page read the list 15
+// times a minute, 15 with the tab hidden too; the asleep band 18 (the screen's 4 s timer beside the
+// app's 20 s one); with the backend down 10 to 15, beside recovery's own. Each read is two requests
+// (`/api/machines`, `/api/harness-shares`). A computer coming online showed within 4 s.
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/workspace_chrome.dart';
+import 'package:harness/viewer/viewer_key_store.dart';
+import 'package:harness/viewer/viewer_services.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+const _studioId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+
+/// The account's one computer, set up before and asleep now.
+const _asleep = Machine(
+ machineId: _studioId,
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ status: 'offline',
+);
+
+/// The same computer, signed in and online.
+const _online = Machine(
+ machineId: _studioId,
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ status: 'online',
+);
+
+class _Api extends ApiClient {
+ _Api() : super(config: AppConfig.dev, session: AuthSession());
+
+ List<Machine> answer = const [];
+
+ /// The backend is down: every read answers 503, which recovery retries.
+ bool down = false;
+
+ /// `GET /api/machines` asked.
+ int reads = 0;
+
+ @override
+ Future<Map<String, dynamic>?> me() async => null;
+
+ @override
+ Future<List<Machine>> machines() async {
+ reads++;
+ if (down) throw ApiException('Service unavailable', status: 503);
+ return answer;
+ }
+}
+
+/// A computer this window has no daemon on.
+class _NoDaemon extends LocalCliDiscovery {
+ _NoDaemon() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+/// A dial that never opens: the computer is asleep, or still starting. Waits give up when their
+/// timeout runs out, as the real connection's do.
+class _Unanswered extends WsConn {
+ _Unanswered(String machineId)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: machineId,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ @override
+ bool get isReady => false;
+ @override
+ Future<void> waitUntilReady({required Duration timeout}) =>
+ Future.delayed(timeout, () => throw TimeoutException('dial', timeout));
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) => Future.delayed(timeout, () => throw TimeoutException(type, timeout));
+ @override
+ Future<void> close() async {}
+}
+
+const _connectPage = Key('connect-page');
+
+void main() {
+ late _Api api;
+ late AppNotifier app;
+
+ /// Simulated seconds since the first machine list answered.
+ var now = 0;
+
+ /// A browser (or, with [browser] false, Desktop) signed in, its first machine list answered
+ /// with [machines], and the workspace up with the host's connect page.
+ Future<void> mount(
+ WidgetTester tester, {
+ List<Machine> machines = const [],
+ bool browser = true,
+ }) async {
+ now = 0;
+ api = _Api()..answer = machines;
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ configStore: null,
+ localCliDiscovery: browser ? null : _NoDaemon(),
+ viewer: browser
+ ? ViewerServices(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ keys: ViewerKeyStore(storage: MemoryStore()),
+ )
+ : null,
+ connectionForTest: _Unanswered.new,
+ );
+ app.api = api;
+ app.status = AppStatus.authenticated;
+ app.newSwarm(newTabPage: true);
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ chrome: browser
+ ? WorkspaceChrome(
+ leadingWidth: (_) => 0,
+ leading: (_, _) => const SizedBox(),
+ firstMachine: (_) => const SizedBox(key: _connectPage),
+ )
+ : null,
+ ),
+ ),
+ );
+ await app.refreshMachines();
+ await tester.pump();
+ }
+
+ Future<void> unmount(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox.shrink());
+ app.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ }
+
+ /// The seconds, counted from the first answer, in which the list was read during the next
+ /// [seconds].
+ Future<List<int>> readsIn(WidgetTester tester, int seconds) async {
+ final at = <int>[];
+ for (var s = 0; s < seconds; s++) {
+ final before = api.reads;
+ await tester.pump(const Duration(seconds: 1));
+ now++;
+ if (api.reads != before) at.add(now);
+ }
+ return at;
+ }
+
+ /// Whether the list was read in this turn of the event loop, with no time passing.
+ Future<bool> readAtOnce(WidgetTester tester, void Function() act) async {
+ final before = api.reads;
+ act();
+ await tester.pump();
+ return api.reads != before;
+ }
+
+ /// Seconds from [_online] being the backend's answer to it being in the app's list.
+ Future<int> secondsToShow(WidgetTester tester) async {
+ api.answer = const [_online];
+ for (var s = 1; s <= 60; s++) {
+ await tester.pump(const Duration(seconds: 1));
+ now++;
+ if (app.machines.any((m) => m.status == 'online')) return s;
+ }
+ return -1;
+ }
+
+ testWidgets('the connect page: 4 s, 8 s, then every 10 s', (tester) async {
+ await mount(tester);
+ expect(find.byKey(_connectPage), findsOneWidget);
+
+ expect(await readsIn(tester, 60), [4, 12, 22, 32, 42, 52]);
+ expect(await readsIn(tester, 60), [62, 72, 82, 92, 102, 112]);
+ await unmount(tester);
+ });
+
+ testWidgets('the asleep band: 4 s, 8 s, 15 s, then every 30 s', (
+ tester,
+ ) async {
+ await mount(tester, machines: const [_asleep]);
+ expect(find.byKey(_connectPage), findsNothing);
+
+ expect(await readsIn(tester, 120), [4, 12, 27, 57, 87, 117]);
+ await unmount(tester);
+ });
+
+ testWidgets('a computer stuck connecting: every 20 s, as before', (
+ tester,
+ ) async {
+ await mount(tester, machines: const [_online]);
+ // What the pool reports while its dial is under way.
+ app.connectionStatusForTest(_studioId, ConnectionStatus.connecting);
+ await tester.pump();
+ expect(find.byKey(_connectPage), findsNothing);
+
+ // The first wait was set while the list had not answered (the connect page, looking); from
+ // then on, every 20 s, as on main.
+ expect(await readsIn(tester, 64), [4, 24, 44, 64]);
+ await unmount(tester);
+ });
+
+ testWidgets('a hidden tab reads nothing; coming back reads at once', (
+ tester,
+ ) async {
+ await mount(tester);
+ app.appLifecycleChanged(AppLifecycleState.inactive);
+ app.appLifecycleChanged(AppLifecycleState.hidden);
+
+ expect(await readsIn(tester, 120), isEmpty);
+
+ expect(
+ await readAtOnce(
+ tester,
+ () => app.appLifecycleChanged(AppLifecycleState.resumed),
+ ),
+ isTrue,
+ );
+ expect(await readsIn(tester, 12), [124, 132]);
+ await unmount(tester);
+ });
+
+ testWidgets('a window in sight but not focused keeps reading; focus reads '
+ 'at once and starts the pace over', (tester) async {
+ await mount(tester, machines: const [_asleep]);
+ app.appLifecycleChanged(AppLifecycleState.inactive);
+
+ expect(await readsIn(tester, 60), [4, 12, 27, 57]);
+
+ expect(
+ await readAtOnce(
+ tester,
+ () => app.appLifecycleChanged(AppLifecycleState.resumed),
+ ),
+ isTrue,
+ );
+ expect(await readsIn(tester, 12), [64, 72]);
+ await unmount(tester);
+ });
+
+ testWidgets('a push reads at once and starts the pace over', (tester) async {
+ await mount(tester, machines: const [_asleep]);
+ expect(await readsIn(tester, 120), [4, 12, 27, 57, 87, 117]);
+
+ expect(
+ await readAtOnce(
+ tester,
+ () => unawaited(
+ app.handleEventForTest(_studioId, const {
+ 'type': 'machines_changed',
+ 'payload': <String, dynamic>{},
+ }),
+ ),
+ ),
+ isTrue,
+ );
+ expect(await readsIn(tester, 12), [124, 132]);
+ await unmount(tester);
+ });
+
+ testWidgets('the person\'s Retry reads at once and starts the pace over', (
+ tester,
+ ) async {
+ await mount(tester);
+ expect(await readsIn(tester, 120), [
+ 4,
+ 12,
+ 22,
+ 32,
+ 42,
+ 52,
+ 62,
+ 72,
+ 82,
+ 92,
+ 102,
+ 112,
+ ]);
+
+ expect(
+ await readAtOnce(tester, () => unawaited(app.retryMachines())),
+ isTrue,
+ );
+ expect(await readsIn(tester, 12), [124, 132]);
+ await unmount(tester);
+ });
+
+ testWidgets('with the backend down, recovery alone reads, then the pace '
+ 'starts over once the list is back', (tester) async {
+ await mount(tester, machines: const [_asleep]);
+ api.down = true;
+
+ // The loop's read at 4 s fails; from then on only recovery asks, at 2, 4, 8, 16, 30, 30 s.
+ expect(await readsIn(tester, 130), [4, 6, 10, 18, 34, 64, 94, 124]);
+ expect(app.machineRecoveryPending, isTrue);
+
+ api.down = false;
+ // Recovery's next read, at 154 s, answers and recovery stops. Its reload of the asleep
+ // computer waits out the dial; then the loop reads again, its pace from the start.
+ final after = await readsIn(tester, 60);
+ expect(after.first, 154);
+ expect(app.machineRecoveryPending, isFalse);
+ expect(
+ [for (var i = 2; i < after.length; i++) after[i] - after[i - 1]],
+ [8, 15],
+ );
+ await unmount(tester);
+ });
+
+ testWidgets('a computer coming online on the connect page shows within '
+ '10 s, however long the page has waited', (tester) async {
+ await mount(tester);
+
+ await readsIn(tester, 5);
+ expect(await secondsToShow(tester), 7);
+ await unmount(tester);
+
+ await mount(tester);
+ await readsIn(tester, 60);
+ expect(await secondsToShow(tester), 2);
+ await unmount(tester);
+
+ await mount(tester);
+ await readsIn(tester, 175);
+ expect(await secondsToShow(tester), 7);
+ await unmount(tester);
+ });
+
+ testWidgets('one asleep, waking after a minute, shows within 30 s', (
+ tester,
+ ) async {
+ await mount(tester, machines: const [_asleep]);
+ await readsIn(tester, 60);
+
+ expect(await secondsToShow(tester), 27);
+ await unmount(tester);
+ });
+
+ testWidgets('Desktop reads nothing on its own', (tester) async {
+ await mount(tester, browser: false);
+
+ expect(await readsIn(tester, 120), isEmpty);
+ await unmount(tester);
+ });
+}
diff --git a/desktop/test/workspace_first_connection_test.dart b/desktop/test/workspace_first_connection_test.dart
index 7aeee0ce2..27c9ba651 100644
--- a/desktop/test/workspace_first_connection_test.dart
+++ b/desktop/test/workspace_first_connection_test.dart
@@ -31,10 +31,16 @@ class _App extends AppNotifier {
@override
String? get lastError => listError ?? super.lastError;
- /// The quiet machine-list reads asked for while waiting on a computer.
+ /// The machine-list reads asked for.
var rereads = 0;
@override
- Future<void> rereadMachines() async => rereads++;
+ Future<bool> refreshMachines() async {
+ rereads++;
+ return true;
+ }
+
+ @override
+ Future<void> retryMachines() async => rereads++;
}
const _connectPage = Key('connect-page');
@@ -229,50 +235,25 @@ void main() {
await unmount(tester, app);
});
- // One timer asks for the machine list, every four seconds, while the
- // connect page or the asleep band shows: a second one would double the
- // reads, and one left running would read forever.
+ // The page and the band ask for nothing on their own: the app's one watch
+ // reads for them (test/web_machine_list_watch_test.dart). A timer here too
+ // would read beside it.
const every = Duration(seconds: 4);
- testWidgets('the connect page: one read every four seconds', (tester) async {
- final app = await mount(tester);
- final before = app.rereads;
-
- await tester.pump(every * 3);
-
- expect(app.rereads - before, 3);
- await unmount(tester, app);
- });
-
- testWidgets('the band: one read every four seconds, none once it is back', (
+ testWidgets('the connect page and the band read nothing of their own', (
tester,
) async {
- final app = await mount(tester, machine: asleep, pane: true);
- final before = app.rereads;
-
- await tester.pump(every * 3);
- expect(app.rereads - before, 3);
-
- app.machineStates['mac']!
- ..nodeOnline = true
- ..connectionStatus = ConnectionStatus.connected;
- app.notifyListeners();
- await tester.pump();
- final woken = app.rereads;
- await tester.pump(every * 3);
- expect(app.rereads, woken);
- await unmount(tester, app);
- });
-
- testWidgets('no read once the workspace is gone', (tester) async {
- final app = await mount(tester, machine: asleep, pane: true);
- await tester.pumpWidget(const SizedBox.shrink());
- final gone = app.rereads;
-
- await tester.pump(every * 3);
-
- expect(app.rereads, gone);
- app.dispose();
+ final page = await mount(tester);
+ final before = page.rereads;
+ await tester.pump(every * 15);
+ expect(page.rereads, before);
+ await unmount(tester, page);
+
+ final band = await mount(tester, machine: asleep, pane: true);
+ final asleepBefore = band.rereads;
+ await tester.pump(every * 15);
+ expect(band.rereads, asleepBefore);
+ await unmount(tester, band);
});
testWidgets('two asleep: the band names both', (tester) async {