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.

Desktop: viewer panes retry a viewer that stops answering; count loads and redials once (#1392)

Dee76fd78dbcd46
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 353d41cfa..27fddb072 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -984,6 +984,29 @@ class AppNotifier extends ChangeNotifier {
final Map<TerminalPane, Timer> _paneRetryTimers = {};
final Map<TerminalPane, int> _paneRetryAttempts = {};
+ /// What the pane sweep saw of each session when it last ran (see [_retryPhase]).
+ final Map<TerminalSession, int> _sweptRetryPhases = {};
+ int _paneSweeps = 0;
+
+ /// How many times the pane sweep ([_schedulePaneRetries]) has run.
+ @visibleForTesting
+ int get paneSweepsForTest => _paneSweeps;
+
+ /// When [_forceRedial] last redialled each machine, on [redialClock].
+ final Map<String, Duration> _lastForcedRedial = {};
+
+ /// Machines whose socket a forced redial has taken down and not yet brought back, with when it began.
+ final Map<String, Duration> _forcedRedials = {};
+
+ /// Monotonic, so a wall-clock change can neither hold redials off nor let a burst through.
+ @visibleForTesting
+ Duration Function() redialClock = _monotonicClock();
+
+ static Duration Function() _monotonicClock() {
+ final watch = Stopwatch()..start();
+ return () => watch.elapsed;
+ }
+
/// One reload per machine, owed after this computer's daemon was too slow to answer its list while
/// still on the socket — the error strip says "retrying", and this is the retry.
final Map<String, Timer> _slowReloadTimers = {};
@@ -1523,7 +1546,7 @@ class AppNotifier extends ChangeNotifier {
orElse: () => swarms.first,
);
List<TerminalPane> get panes => activeSwarm.panes;
- Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();
+ Set<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();
String get activeSwarmId => activeSwarm.id;
/// Agent Messages (docs/design/2026-10-10-agent-messages.md): whether the
@@ -3849,10 +3872,12 @@ class AppNotifier extends ChangeNotifier {
void _measureConnection(
String key,
ConnectionStatus status,
- ProductFlow flow,
- ) {
+ ProductFlow flow, {
+ bool suppressStart = false,
+ }) {
if (status == ConnectionStatus.connecting ||
status == ConnectionStatus.reconnecting) {
+ if (suppressStart) return;
if (_measurementConnections.length < 64) {
_measurementConnections.putIfAbsent(
key,
@@ -3935,6 +3960,9 @@ class AppNotifier extends ChangeNotifier {
Duration(seconds: 16),
Duration(seconds: 30),
];
+
+ /// At most one forced redial of a machine's link in this long (see [_forceRedial]).
+ static const forcedRedialWindow = Duration(seconds: 30);
static const localDaemonReconnectDelay = Duration(seconds: 1);
static const agentSyncInterval = Duration(seconds: 60);
@@ -7470,6 +7498,20 @@ class AppNotifier extends ChangeNotifier {
machine.needsLink &&
(nextStatus == ConnectionStatus.connecting ||
nextStatus == ConnectionStatus.reconnecting);
+ // A forced redial ([_forceRedial]) takes a connected link down and dials it again: neither a
+ // person nor the app connecting, so it opens no observation of its own, and one already open
+ // still ends with it. Each one used to start a new remote_connect; the day #1378 made dead panes
+ // redial, prod's remote_connect went from 1,683 to 2,834 started and 106 to 205 unknown
+ // (2026-10-15 → 16). Bounded by the window, so a redial that never reported back cannot hide a
+ // later ordinary connection.
+ final forcedSince = _forcedRedials[machineId];
+ final forced =
+ forcedSince != null && redialClock() - forcedSince < forcedRedialWindow;
+ if (!forced ||
+ nextStatus == ConnectionStatus.connected ||
+ (nextStatus == ConnectionStatus.disconnected && !settling)) {
+ _forcedRedials.remove(machineId);
+ }
productConnections.status(
machineId,
connecting:
@@ -7477,7 +7519,7 @@ class AppNotifier extends ChangeNotifier {
nextStatus == ConnectionStatus.connecting ||
nextStatus == ConnectionStatus.reconnecting,
connected: nextStatus == ConnectionStatus.connected,
- suppressStart: viewer == null && retryingLink,
+ suppressStart: (viewer == null && retryingLink) || forced,
failure: machine.needsLink
? ProductHealthMeasure.connectErrorUnlinked
: machine.nodeOnline == false
@@ -7496,6 +7538,7 @@ class AppNotifier extends ChangeNotifier {
machine.isLocalMachine
? ProductFlow.workspaceConnect
: ProductFlow.remoteConnect,
+ suppressStart: forced,
);
}
machine.connectionStatus = settling
@@ -10327,6 +10370,29 @@ class AppNotifier extends ChangeNotifier {
return connection;
}
+ /// Force a fresh dial of [machineId]'s link ([WsConn.forceReconnect]), at most once per
+ /// [forcedRedialWindow].
+ ///
+ /// A redial knocks every pane on the machine over, and since #1378 each dead pane's first reattach
+ /// may ask for one when its open goes unanswered: N dead panes on one machine redialled it N times,
+ /// each knocking the others' fresh opens over again. A stalled open inside the window resends on
+ /// the link the first redial brought back instead ([TerminalSession]'s recovery polls for that).
+ Future<void> _forceRedial(String machineId, [WsConn? connection]) {
+ final now = redialClock();
+ final last = _lastForcedRedial[machineId];
+ if (last != null && now - last < forcedRedialWindow) {
+ return Future<void>.value();
+ }
+ final link = connection ?? _conn(machineId);
+ if (link.isClosed) return Future<void>.value();
+ _lastForcedRedial[machineId] = now;
+ _forcedRedials[machineId] = now;
+ return link.forceReconnect();
+ }
+
+ @visibleForTesting
+ Future<void> forceRedialForTest(String machineId) => _forceRedial(machineId);
+
// Every machine — this computer's own, or a relayed one — now speaks the same plaintext local wire
// protocol to the CLI (which terminates E2EE itself for relayed machines; see remoteRelay.ts in the
// harness CLI repo). There is no per-machine branching left here at all.
@@ -10533,7 +10599,7 @@ class AppNotifier extends ChangeNotifier {
// process restarting, which drops its in-memory session state but doesn't touch the socket.
// Nothing else would ever notice, so force a fresh dial rather than let every future retry
// keep timing out against the same dead session.
- unawaited(connection.forceReconnect());
+ unawaited(_forceRedial(machine.machine.machineId, connection));
}
} else {
machine.agentsLoadError = 'Could not load harnesses: $error';
@@ -16420,7 +16486,7 @@ class AppNotifier extends ChangeNotifier {
send: (type, payload) =>
_conn(pane.machineId).sendTerminalFrame(type, payload),
sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),
- onOpenStalled: () => _conn(pane.machineId).forceReconnect(),
+ onOpenStalled: () => _forceRedial(pane.machineId),
// A `terminal_open` can round-trip app → local CLI → (for a relayed
// machine) the E2EE relay → the remote peer → tmux → back, possibly
// negotiating P2P on the way, so a cold open legitimately takes several
@@ -18024,7 +18090,33 @@ class AppNotifier extends ChangeNotifier {
/// Every session change repaints, and may mean a pane's stream just died.
void _onSessionChanged() {
notifyListeners();
- _schedulePaneRetries();
+ // Sessions notify on every change — a title, a resize, a watcher band — and the sweep answers
+ // differently only when a stream dies, closes here or comes back live. Run on each notification,
+ // it rebuilt the pane set for every dead pane and every timer: with 40 panes, 10 of them dead, a
+ // notification cost ~53 µs, and ~3 µs with the set built once and this check (2026-10-17, VM test).
+ if (_retryPhasesChanged()) _schedulePaneRetries();
+ }
+
+ /// What the sweep reads of a session's status: dead (error/closed, here or not), live (which resets
+ /// the pane's backoff), or neither.
+ static int _retryPhase(TerminalSession session) => switch (session.status) {
+ TerminalSessionStatus.error ||
+ TerminalSessionStatus.closed => session.closedHere ? 1 : 2,
+ TerminalSessionStatus.controlling => 3,
+ _ => 0,
+ };
+
+ bool _retryPhasesChanged() {
+ for (final swarm in swarms) {
+ for (final pane in swarm.panes) {
+ final session = pane.session;
+ if (session != null &&
+ _sweptRetryPhases[session] != _retryPhase(session)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
/// Keep one timer for each pane whose stream died while its machine stays reachable, in whichever
@@ -18032,8 +18124,14 @@ class AppNotifier extends ChangeNotifier {
/// is cheap; an app with every terminal live holds no timer.
void _schedulePaneRetries() {
if (_disposed) return;
- for (final pane in allPanes) {
- if (!_paneRetryWanted(pane)) {
+ _paneSweeps++;
+ final all = allPanes;
+ _sweptRetryPhases.clear();
+ for (final pane in all) {
+ if (pane.session case final session?) {
+ _sweptRetryPhases[session] = _retryPhase(session);
+ }
+ if (!_paneRetryWanted(pane, all: all)) {
_paneRetryTimers.remove(pane)?.cancel();
if (pane.session?.status == TerminalSessionStatus.controlling) {
_paneRetryAttempts.remove(pane);
@@ -18060,17 +18158,17 @@ class AppNotifier extends ChangeNotifier {
});
}
_paneRetryTimers.removeWhere((pane, timer) {
- if (allPanes.contains(pane)) return false;
+ if (all.contains(pane)) return false;
timer.cancel();
return true;
});
- _paneRetryAttempts.removeWhere((pane, _) => !allPanes.contains(pane));
+ _paneRetryAttempts.removeWhere((pane, _) => !all.contains(pane));
}
/// A dead stream on a machine that is up and can open terminals politely. Offline machines are left
/// to the offline/online path, and `takenOver` panes to a person. A dead watcher is included, unlike
/// in [_paneNeedsAttach]: the reopen is polite, so it comes back as a watcher and takes nothing.
- bool _paneRetryWanted(TerminalPane pane) {
+ bool _paneRetryWanted(TerminalPane pane, {Set<TerminalPane>? all}) {
final session = pane.session;
final machine = machineStates[pane.machineId];
return pane.agentId != null &&
@@ -18081,7 +18179,7 @@ class AppNotifier extends ChangeNotifier {
machine != null &&
machine.nodeOnline == true &&
machine.terminalNoTakeoverAvailable &&
- _canAttachPane(pane);
+ _canAttachPane(pane, all: all);
}
void _cancelPaneRetries() {
@@ -18166,8 +18264,9 @@ class AppNotifier extends ChangeNotifier {
await Future.wait(reopening);
}
- bool _canAttachPane(TerminalPane pane) {
- if (_disposed || !allPanes.contains(pane)) return false;
+ /// [all] is [allPanes] when the caller already holds it.
+ bool _canAttachPane(TerminalPane pane, {Set<TerminalPane>? all}) {
+ if (_disposed || !(all ?? allPanes).contains(pane)) return false;
final machine = machineStates[pane.machineId];
return machine != null &&
machine.nodeOnline != false &&
diff --git a/desktop/lib/state/viewer_load_tracker.dart b/desktop/lib/state/viewer_load_tracker.dart
new file mode 100644
index 000000000..0be3a7ce1
--- /dev/null
+++ b/desktop/lib/state/viewer_load_tracker.dart
@@ -0,0 +1,204 @@
+import 'dart:async';
+
+import '../measurement/product_measurement.dart';
+
+/// One embedded viewer's navigations, as the webview reports them, turned into what the pane shows
+/// and one `viewer_load` observation per load the app asked for.
+///
+/// It knows nothing of the webview: [WebPanePanel] passes each navigation callback in, and loads
+/// what [load] names. Pure, so the decisions below are unit tested without a native view.
+///
+/// Why each rule exists (prod, 2026-10-15 → 16: viewer_load started 54 → 112, failed 0 → 23):
+/// - WKWebView reports every failed navigation as the main frame's, so the panel's main-frame filter
+/// filtered nothing, and a navigation cancelled by the next one (NSURLErrorCancelled, -999; WebKit's
+/// "frame load interrupted", 102) counted as a failed load and put the overlay up.
+/// - A late error belonging to an earlier address marked the current load failed, and finishing a
+/// load never took the overlay down.
+/// - Every page start began an observation: Reload, Retry, the page's own navigations.
+/// - A remote viewer's address lives only as long as one connection (the CLI's per-connection
+/// gateway), and a forced reconnect or a CLI update takes it down: the viewer stops answering for a
+/// moment and nothing tried again.
+class ViewerLoadTracker {
+ ViewerLoadTracker({
+ required this.begin,
+ required this.load,
+ required this.changed,
+ });
+
+ /// Opens a `viewer_load` observation and returns how to end it.
+ final void Function(ProductOutcome) Function() begin;
+
+ /// Loads [url] into the webview again: an automatic retry.
+ final void Function(String url) load;
+
+ /// What [failure] or [loading] reads has changed.
+ final void Function() changed;
+
+ /// Waits before each automatic retry of a viewer that refused or dropped the connection: about
+ /// 30 s in all, long enough for a reconnect to bring the machine back and name the viewer's new
+ /// address, which then loads in place of these retries.
+ static const retryDelays = <Duration>[
+ Duration(seconds: 1),
+ Duration(seconds: 2),
+ Duration(seconds: 4),
+ Duration(seconds: 8),
+ Duration(seconds: 8),
+ Duration(seconds: 8),
+ ];
+
+ /// NSURLErrorCancelled: this navigation was replaced by another, which reports for itself.
+ static const _cancelled = -999;
+
+ /// WebKitErrorFrameLoadInterruptedByPolicyChange: likewise, a load stopped rather than failed.
+ static const _interrupted = 102;
+
+ /// NSURLErrorCannotConnectToHost and NSURLErrorNetworkConnectionLost: nothing is listening at
+ /// the address yet, or it went away mid-load.
+ static const _retryable = {-1004, -1005};
+
+ void Function(ProductOutcome)? _finish;
+ Timer? _retry;
+ int _attempt = 0;
+ String? _target;
+ bool _expectingStart = false;
+ final _urls = <String>{};
+
+ /// Why the viewer is not showing, for the pane's notice; null while it is (or may be) fine.
+ String? get failure => _failure;
+ String? _failure;
+
+ /// A navigation is under way, or a retry is waiting to start one.
+ bool get loading => _loading;
+ bool _loading = false;
+
+ /// Whether a `viewer_load` observation is open.
+ bool get measuring => _finish != null;
+
+ /// The app is about to load [url]: the first load, a new address from the daemon, or a person's
+ /// Retry or Reload. An observation still open goes on with it — it is the same viewer still
+ /// trying to load — and one begins if none is.
+ void request(String url) {
+ _retry?.cancel();
+ _retry = null;
+ _attempt = 0;
+ _target = url;
+ _expectingStart = true;
+ _urls
+ ..clear()
+ ..add(url);
+ _failure = null;
+ _loading = true;
+ _finish ??= begin();
+ }
+
+ /// The webview started a navigation to [url] (`onPageStarted`): the one just requested or retried,
+ /// or the page's own, which starts no observation.
+ void started(String url) {
+ _retry?.cancel();
+ _retry = null;
+ if (!_expectingStart) _urls.clear();
+ _expectingStart = false;
+ if (url.isNotEmpty) _urls.add(url);
+ _loading = true;
+ changed();
+ }
+
+ /// The webview finished loading [url] (`onPageFinished`).
+ void finished(String url) {
+ if (!_belongs(url)) return;
+ _retry?.cancel();
+ _retry = null;
+ _attempt = 0;
+ _expectingStart = false;
+ _failure = null;
+ _loading = false;
+ _end(ProductOutcome.ok);
+ changed();
+ }
+
+ /// The webview could not load [url] (`onWebResourceError`). [domain] is the NSError domain where
+ /// the platform gives one.
+ void failed({
+ required int code,
+ String? domain,
+ String? url,
+ required String description,
+ }) {
+ if (!_belongs(url)) return;
+ if (_isCancellation(code, domain)) {
+ // Whatever replaced it reports its own outcome; an observation still open waits for that.
+ _loading = false;
+ changed();
+ return;
+ }
+ final target = _target;
+ final message = description.isNotEmpty
+ ? description
+ : 'The viewer did not answer.';
+ if (target != null &&
+ _isRetryable(code, domain) &&
+ _attempt < retryDelays.length) {
+ _failure = message;
+ _loading = true;
+ _retry?.cancel();
+ _retry = Timer(retryDelays[_attempt++], () {
+ _retry = null;
+ _expectingStart = true;
+ load(target);
+ });
+ changed();
+ return;
+ }
+ _retry?.cancel();
+ _retry = null;
+ _failure = message;
+ _loading = false;
+ _end(ProductOutcome.failed);
+ changed();
+ }
+
+ /// The pane is going away: an open observation ends unfinished.
+ void dispose() {
+ _retry?.cancel();
+ _retry = null;
+ _end(ProductOutcome.cancelled);
+ }
+
+ void _end(ProductOutcome outcome) {
+ final finish = _finish;
+ _finish = null;
+ finish?.call(outcome);
+ }
+
+ static bool _isCancellation(int code, String? domain) =>
+ (code == _cancelled &&
+ (domain == null || domain == 'NSURLErrorDomain')) ||
+ (code == _interrupted &&
+ (domain == null || domain == 'WebKitErrorDomain'));
+
+ static bool _isRetryable(int code, String? domain) =>
+ _retryable.contains(code) &&
+ (domain == null || domain == 'NSURLErrorDomain');
+
+ /// Whether a report about [url] is about the current navigation. A report with no address is (the
+ /// web content process ending names none). A redirect stays on its origin — a remote viewer's
+ /// gateway answers its first address with a redirect to the viewer's own path — so any address on
+ /// the current navigation's origin belongs to it; a new viewer address is another port, and a
+ /// report about that one is late.
+ bool _belongs(String? url) {
+ if (url == null || url.isEmpty || _urls.isEmpty) return true;
+ if (_urls.contains(url)) return true;
+ final reported = Uri.tryParse(url);
+ if (reported == null || reported.host.isEmpty) return false;
+ for (final known in _urls) {
+ final current = Uri.tryParse(known);
+ if (current != null &&
+ current.scheme == reported.scheme &&
+ current.host == reported.host &&
+ current.port == reported.port) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index cca3a3a06..c46d84f21 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -19,6 +19,7 @@ import '../state/app_state.dart';
import '../measurement/product_measurement.dart';
import '../state/harness_monitor_controller.dart';
import '../state/terminal_pane.dart';
+import '../state/viewer_load_tracker.dart';
import '../theme/app_theme.dart';
import '../viewer/interactive_viewer.dart';
import 'agent_drag.dart';
@@ -84,7 +85,12 @@ class WebPanePanel extends StatefulWidget {
/// Whether this build can put a real webview on screen. One place, so the
/// panel and its tests agree on when the placeholder is the right answer.
- static bool get webviewAvailable => !kUnderTest && RuntimePlatform.isMacOS;
+ static bool get webviewAvailable =>
+ webviewAvailableForTest ?? (!kUnderTest && RuntimePlatform.isMacOS);
+
+ /// A test that installs a fake `WebViewPlatform` mounts the real webview path.
+ @visibleForTesting
+ static bool? webviewAvailableForTest;
@override
State<WebPanePanel> createState() => _WebPanePanelState();
@@ -102,11 +108,21 @@ class _WebPanePanelState extends State<WebPanePanel> {
) ==
true;
WebViewController? _controller;
+
+ /// Whether [_controller] has its JavaScript channel. A load before then was cancelled by the one
+ /// [_mountController] makes once it is added, and the cancellation counted as a failed load.
+ bool _controllerReady = false;
InteractiveViewerSession? _remote;
String? _remoteIdentity;
String? _loadedUrl;
- bool _loading = false;
- String? _failure;
+ late final _viewerLoad = ViewerLoadTracker(
+ begin: () =>
+ widget.notifier.productMeasurement.begin(ProductFlow.viewerLoad),
+ load: _navigate,
+ changed: () => _set(() {}),
+ );
+
+ /// The remote viewer surface's load, measured by its own first frame.
void Function(ProductOutcome)? _finishLoad;
void _startLoad() {
_finishLoad?.call(ProductOutcome.cancelled);
@@ -161,6 +177,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
@override
void dispose() {
_finishLoad?.call(ProductOutcome.cancelled);
+ _viewerLoad.dispose();
if (widget.pane.focusViewerInput == _focusRemote) {
widget.pane.focusViewerInput = null;
}
@@ -184,14 +201,9 @@ class _WebPanePanelState extends State<WebPanePanel> {
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
- onPageStarted: (_) => _set(() {
- _startLoad();
- _loading = true;
- _failure = null;
- }),
- onPageFinished: (_) {
- _finishLoad?.call(ProductOutcome.ok);
- _set(() => _loading = false);
+ onPageStarted: _viewerLoad.started,
+ onPageFinished: (url) {
+ _viewerLoad.finished(url);
// A fresh document has no stamp; give it the app's appearance before it is looked at.
_stampedBrightness = null;
_stampTheme();
@@ -199,15 +211,16 @@ class _WebPanePanelState extends State<WebPanePanel> {
onWebResourceError: (error) {
// Only the page itself: a harness's viewer pulls fonts, models
// and images of its own, and one of those failing is its business
- // to show, not ours to call a dead viewer.
+ // to show, not ours to call a dead viewer. (WKWebView reports
+ // every navigation failure as the main frame's; the tracker
+ // tells them apart.)
if (error.isForMainFrame == false) return;
- _finishLoad?.call(ProductOutcome.failed);
- _set(() {
- _loading = false;
- _failure = error.description.isNotEmpty
- ? error.description
- : 'The viewer did not answer.';
- });
+ _viewerLoad.failed(
+ code: error.errorCode,
+ domain: error is WebKitWebResourceError ? error.domain : null,
+ url: error.url,
+ description: error.description,
+ );
},
),
);
@@ -233,6 +246,7 @@ class _WebPanePanelState extends State<WebPanePanel> {
},
);
}
+ _controllerReady = true;
if (mounted) _load();
}
@@ -262,11 +276,11 @@ class _WebPanePanelState extends State<WebPanePanel> {
void _load() {
final url = widget.pane.url;
final controller = _controller;
- if (url == null || controller == null) return;
+ if (url == null || controller == null || !_controllerReady) return;
final uri = Uri.tryParse(url);
if (uri == null) return;
_loadedUrl = url;
- _failure = null;
+ _viewerLoad.request(url);
// The window colour behind the page, so a dark app never flashes white
// while a viewer loads. WKWebView on macOS has no such setting (the plugin
// throws UnimplementedError, seen live 2026-09-15 as a red pane), so only
@@ -277,6 +291,13 @@ class _WebPanePanelState extends State<WebPanePanel> {
controller.loadRequest(uri);
}
+ /// An automatic retry of [url], on the load already being measured.
+ void _navigate(String url) {
+ final uri = Uri.tryParse(url);
+ if (!mounted || uri == null) return;
+ _controller?.loadRequest(uri);
+ }
+
/// Tell the page which appearance the app is in.
///
/// The web view follows the SYSTEM's light/dark setting on its own (`prefers-color-scheme`),
@@ -313,12 +334,10 @@ class _WebPanePanelState extends State<WebPanePanel> {
return;
}
if (_controller == null) return;
- if (_loadedUrl != widget.pane.url) {
- _load();
- } else {
- _failure = null;
- _controller!.reload();
- }
+ // The pane's address, never the webview's own reload: a remote viewer's address lasts one
+ // connection (the CLI's per-connection gateway), and reloading the page went back to a gateway
+ // that had closed.
+ _load();
setState(() {});
}
@@ -415,8 +434,8 @@ class _WebPanePanelState extends State<WebPanePanel> {
),
const SizedBox(width: 8),
// coverage:ignore-start
- // Only a real webview's navigation sets _loading; none under test.
- if (_loading)
+ // Only a webview's navigation sets loading; the placeholder has none.
+ if (_viewerLoad.loading)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 6),
child: SizedBox(
@@ -473,13 +492,14 @@ class _WebPanePanelState extends State<WebPanePanel> {
fit: StackFit.expand,
children: [
WebViewWidget(controller: controller),
- if (_failure != null)
+ if (_viewerLoad.failure case final failure?)
ColoredBox(
+ key: const ValueKey('web-pane-waiting'),
color: grid.AppPalette.windowBg,
child: _Notice(
icon: AppIcons.unplug,
title: 'Waiting for the viewer',
- detail: _failure!,
+ detail: failure,
action: TextButton(
onPressed: _reload,
child: const Text('Retry'),
diff --git a/desktop/test/pane_retry_test.dart b/desktop/test/pane_retry_test.dart
index fc1690f9f..e75c2ebee 100644
--- a/desktop/test/pane_retry_test.dart
+++ b/desktop/test/pane_retry_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
@@ -24,9 +25,15 @@ class _Connection extends WsConn {
);
final opened = <String>[];
final opens = <Map<String, dynamic>>[];
+ int forceReconnects = 0;
+
+ /// The machine's link is gone: nothing sent on it goes through.
+ bool refuse = false;
@override
Future<void> waitUntilReady({required Duration timeout}) async {}
@override
+ Future<void> forceReconnect() async => forceReconnects++;
+ @override
Future<Map<String, dynamic>> request(
String type, {
Map<String, dynamic> payload = const {},
@@ -62,7 +69,7 @@ class _Connection extends WsConn {
opened.add(payload['agentId'] as String);
opens.add(payload);
}
- return true;
+ return !refuse;
}
}
@@ -264,4 +271,67 @@ void main() {
}
r.app.dispose();
});
+
+ // Each dead pane's first reattach may redial the machine when its open goes unanswered, and a
+ // redial knocks every pane on the machine over: N dead panes redialled one machine N times.
+ testWidgets('dead panes on one machine redial its link once, not once each', (
+ tester,
+ ) async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ app.machineStates['m']!.nodeOnline = true;
+ // Tiles the app attaches itself once the machine answers, so an unanswered open asks the app to
+ // redial the machine.
+ unawaited(app.addAgentToSwarm('m', 'a0'));
+ unawaited(app.addAgentToSwarm('m', 'a1'));
+ await app.handleEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': false},
+ });
+ await app.handleEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': true},
+ });
+ for (var i = 0; i < 30; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ final sessions = [for (final pane in app.panes) pane.session!];
+ expect(sessions, hasLength(2));
+ expect(connection.opened, ['a0', 'a1']);
+
+ connection.refuse = true;
+ for (final session in sessions) {
+ session.transportLost('gone');
+ }
+ // Both first reattaches (1 s), each with its redial and resends (3 s).
+ for (var i = 0; i < 50; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ expect(connection.opened.skip(2).toSet(), {
+ 'a0',
+ 'a1',
+ }, reason: 'both reattached');
+ expect(connection.forceReconnects, 1);
+ app.dispose();
+ });
+
+ testWidgets('only a stream dying or coming back runs the sweep', (
+ tester,
+ ) async {
+ final r = await rig(tester);
+ final sweeps = r.app.paneSweepsForTest;
+
+ // A live session notifies on all sorts of changes: a title, a resize, a watcher band.
+ for (var i = 0; i < 100; i++) {
+ r.background.setEngineId(i.isEven ? 'claude' : 'codex');
+ }
+ expect(r.app.paneSweepsForTest, sweeps);
+
+ r.background.transportLost('gone');
+ expect(r.app.paneSweepsForTest, sweeps + 1);
+ await tester.pump(const Duration(milliseconds: 1100));
+ expect(r.connection.opened, ['a0'], reason: 'the retry still runs');
+ r.app.dispose();
+ });
}
diff --git a/desktop/test/remote_connect_measurement_test.dart b/desktop/test/remote_connect_measurement_test.dart
index 9f9bbffe9..119843461 100644
--- a/desktop/test/remote_connect_measurement_test.dart
+++ b/desktop/test/remote_connect_measurement_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/ws/ws_conn.dart';
class _Recorder extends ProductMeasurement {
_Recorder() : super(surface: 'desktop', automatic: false, sendSetup: (_) async => {});
+ final started = <String>[];
final ended = <String>[];
final healthCounts = <ProductHealthMeasure>[];
@@ -21,8 +22,10 @@ class _Recorder extends ProductMeasurement {
void health(ProductHealthMeasure measure) => healthCounts.add(measure);
@override
- void Function(ProductOutcome) begin(ProductFlow flow) =>
- (outcome) => ended.add('${flow.name}:${outcome.name}');
+ void Function(ProductOutcome) begin(ProductFlow flow) {
+ started.add(flow.name);
+ return (outcome) => ended.add('${flow.name}:${outcome.name}');
+ }
}
/// A daemon that answers every request with nothing: connecting loads the machine's data.
@@ -44,6 +47,17 @@ class _Daemon extends WsConn {
Map<String, dynamic> payload = const {},
Duration timeout = const Duration(seconds: 20),
}) async => const {};
+
+ int forceReconnects = 0;
+
+ /// What the redial reports through the pool, played by the test.
+ void Function()? onForceReconnect;
+
+ @override
+ Future<void> forceReconnect() async {
+ forceReconnects++;
+ onForceReconnect?.call();
+ }
}
/// A remote machine that is not linked is redialled every five seconds by the
@@ -54,16 +68,18 @@ class _Daemon extends WsConn {
void main() {
late AppNotifier app;
late _Recorder usage;
+ late _Daemon daemon;
const mid = 'remote';
setUp(() {
usage = _Recorder();
+ daemon = _Daemon();
app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
productMeasurement: usage,
- connectionForTest: (_) => _Daemon(),
+ connectionForTest: (_) => daemon,
);
const machine = Machine(
machineId: mid,
@@ -115,4 +131,118 @@ void main() {
expect(usage.ended.where((event) => event.startsWith('remoteConnect:')),
['remoteConnect:failed', 'remoteConnect:ok']);
});
+
+ // #1378's dead panes redial their machine's link when an open goes unanswered. Each redial took a
+ // connected link to `connecting` and was counted as a new remote_connect.
+ test(
+ 'a forced redial of a connected machine is not a new connection',
+ () async {
+ app.connectionStatusForTest(mid, ConnectionStatus.connecting);
+ app.connectionStatusForTest(mid, ConnectionStatus.connected);
+ usage.started.clear();
+ // WsConn.forceReconnect drops the link and dials it again from the first attempt.
+ daemon.onForceReconnect = () {
+ app.connectionStatusForTest(mid, ConnectionStatus.connecting);
+ app.connectionStatusForTest(mid, ConnectionStatus.reconnecting);
+ app.connectionStatusForTest(mid, ConnectionStatus.connected);
+ };
+ await app.forceRedialForTest(mid);
+ daemon.onForceReconnect = null;
+
+ expect(daemon.forceReconnects, 1);
+ expect(usage.started, isEmpty);
+
+ // A socket that drops and is dialled back is measured as before.
+ app.connectionStatusForTest(mid, ConnectionStatus.reconnecting);
+ app.connectionStatusForTest(mid, ConnectionStatus.connected);
+ expect(usage.started, ['connectAuto', 'remoteConnect']);
+ expect(usage.ended.where((event) => event.startsWith('remoteConnect:')), [
+ 'remoteConnect:ok',
+ 'remoteConnect:ok',
+ ]);
+ },
+ );
+
+ test('a machine is redialled at most once in the window', () async {
+ var now = Duration.zero;
+ app.redialClock = () => now;
+
+ await app.forceRedialForTest(mid);
+ now += const Duration(seconds: 29);
+ await app.forceRedialForTest(mid);
+ expect(daemon.forceReconnects, 1);
+
+ now += const Duration(seconds: 1);
+ await app.forceRedialForTest(mid);
+ expect(daemon.forceReconnects, 2);
+ });
+
+ // A real pool, because what a replaced socket reports is the pool's to deliver or drop: Connect
+ // closes the socket the app is redialling, and the pool stops listening to it first
+ // (WsPool.connFor's ownsMachine), so the close never ends the attempt as failed.
+ test('Connect while the app is redialling neither fails nor restarts the attempt', () async {
+ final pooledUsage = _Recorder();
+ final pooled = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ productMeasurement: pooledUsage,
+ );
+ addTearDown(pooled.dispose);
+ const machine = Machine(
+ machineId: mid,
+ name: 'Box',
+ authMode: MachineAuthMode.remote,
+ );
+ pooled.machines.add(machine);
+ pooled.machineStates[mid] = MachineState(machine)..nodeOnline = true;
+ pooled
+ ..status = AppStatus.authenticated
+ ..currentUser = const CurrentUserProfile(
+ id: 'u1',
+ email: '[email protected]',
+ );
+ pooled.notifyListeners();
+ // This computer's daemon, at a loopback port nothing listens on (1): every dial is refused.
+ pooled.ownDaemonMachineIdForTest('this-computer');
+ // Any socket makes the pool; this one is never dialled.
+ pooled.adoptPoolConnectionForTest('unused', _Daemon());
+
+ // The first dial is refused and the socket goes on redialling on its own.
+ expect(
+ await pooled.connectTrusted(
+ mid,
+ timeout: const Duration(milliseconds: 300),
+ ),
+ isFalse,
+ );
+ for (var wait = 0; wait < 50; wait++) {
+ if (pooled.stateOf(mid)!.connectionStatus ==
+ ConnectionStatus.reconnecting) {
+ break;
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ expect(
+ pooled.stateOf(mid)!.connectionStatus,
+ ConnectionStatus.reconnecting,
+ );
+ // Connect again, mid-redial: the socket is closed and replaced.
+ expect(
+ await pooled.connectTrusted(
+ mid,
+ timeout: const Duration(milliseconds: 300),
+ ),
+ isFalse,
+ );
+
+ expect(
+ pooledUsage.started.where((flow) => flow == 'remoteConnect'),
+ hasLength(1),
+ );
+ expect(
+ pooledUsage.ended.where((event) => event.startsWith('remoteConnect:')),
+ isEmpty,
+ );
+ });
}
diff --git a/desktop/test/support/fake_webview.dart b/desktop/test/support/fake_webview.dart
new file mode 100644
index 000000000..626a9f942
--- /dev/null
+++ b/desktop/test/support/fake_webview.dart
@@ -0,0 +1,110 @@
+import 'dart:async';
+
+import 'package:flutter/widgets.dart';
+import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
+
+/// A webview platform with no native view: records what the app asks of each controller and lets a
+/// test play the navigation callbacks WKWebView would make.
+class FakeWebViewPlatform extends WebViewPlatform {
+ final controllers = <FakeWebViewController>[];
+
+ /// While set, adding a JavaScript channel waits for it, as the native call does.
+ Completer<void>? channelGate;
+
+ @override
+ PlatformWebViewController createPlatformWebViewController(
+ PlatformWebViewControllerCreationParams params,
+ ) {
+ final controller = FakeWebViewController(params, this);
+ controllers.add(controller);
+ return controller;
+ }
+
+ @override
+ PlatformNavigationDelegate createPlatformNavigationDelegate(
+ PlatformNavigationDelegateCreationParams params,
+ ) => FakeNavigationDelegate(params);
+
+ @override
+ PlatformWebViewWidget createPlatformWebViewWidget(
+ PlatformWebViewWidgetCreationParams params,
+ ) => _FakeWebViewWidget(params);
+}
+
+class FakeWebViewController extends PlatformWebViewController {
+ FakeWebViewController(super.params, this._platform) : super.implementation();
+
+ final FakeWebViewPlatform _platform;
+ final loads = <Uri>[];
+ int reloads = 0;
+ FakeNavigationDelegate? delegate;
+
+ @override
+ Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) async {}
+
+ @override
+ Future<void> setPlatformNavigationDelegate(
+ PlatformNavigationDelegate handler,
+ ) async {
+ delegate = handler as FakeNavigationDelegate;
+ }
+
+ @override
+ Future<void> addJavaScriptChannel(
+ JavaScriptChannelParams javaScriptChannelParams,
+ ) async {
+ await _platform.channelGate?.future;
+ }
+
+ @override
+ Future<void> loadRequest(LoadRequestParams params) async {
+ loads.add(params.uri);
+ }
+
+ @override
+ Future<void> reload() async {
+ reloads++;
+ }
+
+ @override
+ Future<void> runJavaScript(String javaScript) async {}
+
+ @override
+ Future<String?> currentUrl() async =>
+ loads.isEmpty ? null : loads.last.toString();
+
+ @override
+ Future<void> setBackgroundColor(Color color) async {}
+}
+
+class FakeNavigationDelegate extends PlatformNavigationDelegate {
+ FakeNavigationDelegate(super.params) : super.implementation();
+
+ PageEventCallback? onPageStarted, onPageFinished;
+ WebResourceErrorCallback? onWebResourceError;
+
+ @override
+ Future<void> setOnPageStarted(PageEventCallback onPageStarted) async {
+ this.onPageStarted = onPageStarted;
+ }
+
+ @override
+ Future<void> setOnPageFinished(PageEventCallback onPageFinished) async {
+ this.onPageFinished = onPageFinished;
+ }
+
+ @override
+ Future<void> setOnWebResourceError(
+ WebResourceErrorCallback onWebResourceError,
+ ) async {
+ this.onWebResourceError = onWebResourceError;
+ }
+}
+
+class _FakeWebViewWidget extends PlatformWebViewWidget {
+ _FakeWebViewWidget(super.params) : super.implementation();
+
+ @override
+ Widget build(BuildContext context) =>
+ const SizedBox.expand(key: ValueKey('fake-webview'));
+}
diff --git a/desktop/test/viewer_load_tracker_test.dart b/desktop/test/viewer_load_tracker_test.dart
new file mode 100644
index 000000000..ed7f7ca28
--- /dev/null
+++ b/desktop/test/viewer_load_tracker_test.dart
@@ -0,0 +1,243 @@
+// What a viewer pane makes of its webview's navigation reports: which ones fail a load, which put
+// the "Waiting for the viewer" notice up, and when it tries again by itself.
+
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/measurement/product_measurement.dart';
+import 'package:harness/state/viewer_load_tracker.dart';
+
+const _viewer = 'http://127.0.0.1:4179/';
+
+class _Rig {
+ _Rig() {
+ tracker = ViewerLoadTracker(
+ begin: () {
+ begun++;
+ return outcomes.add;
+ },
+ load: loads.add,
+ changed: () => changes++,
+ );
+ }
+
+ late final ViewerLoadTracker tracker;
+ int begun = 0, changes = 0;
+ final outcomes = <ProductOutcome>[];
+ final loads = <String>[];
+
+ /// The app asks for [url] and the webview starts on it.
+ void open(String url) {
+ tracker
+ ..request(url)
+ ..started(url);
+ }
+
+ void refused(String url) => tracker.failed(
+ code: -1004,
+ domain: 'NSURLErrorDomain',
+ url: url,
+ description: 'Could not connect to the server.',
+ );
+}
+
+void main() {
+ test(
+ 'a navigation cancelled by the next one fails nothing and shows nothing',
+ () {
+ final r = _Rig()..open(_viewer);
+
+ r.tracker.failed(
+ code: -999,
+ domain: 'NSURLErrorDomain',
+ url: _viewer,
+ description: 'cancelled',
+ );
+ r.tracker.failed(
+ code: 102,
+ domain: 'WebKitErrorDomain',
+ url: _viewer,
+ description: 'Frame load interrupted',
+ );
+
+ expect(r.tracker.failure, isNull);
+ expect(r.outcomes, isEmpty);
+ expect(r.tracker.measuring, isTrue, reason: 'what replaced it reports');
+ r.tracker
+ ..started(_viewer)
+ ..finished(_viewer);
+ expect(r.outcomes, [ProductOutcome.ok]);
+ expect(r.begun, 1);
+ },
+ );
+
+ test(
+ 'a late error about an earlier address leaves the current load alone',
+ () {
+ final r = _Rig()..open('http://127.0.0.1:4179/deck');
+ // The daemon names the viewer's new address (another gateway port) while the first is loading.
+ r.open('http://127.0.0.1:5200/__harness_viewer/t?path=%2F');
+
+ r.refused('http://127.0.0.1:4179/deck');
+ r.tracker.failed(
+ code: -1100,
+ domain: 'NSURLErrorDomain',
+ url: 'http://127.0.0.1:4179/deck',
+ description: 'The requested URL was not found on this server.',
+ );
+
+ expect(r.tracker.failure, isNull);
+ expect(r.loads, isEmpty, reason: 'nothing to retry');
+ r.tracker.finished('http://127.0.0.1:5200/');
+ expect(r.outcomes, [ProductOutcome.ok]);
+ expect(
+ r.begun,
+ 1,
+ reason: 'one viewer, still loading when its address moved',
+ );
+ },
+ );
+
+ test('a finished load takes the notice down', () {
+ final r = _Rig()..open(_viewer);
+ r.tracker.failed(
+ code: 2,
+ domain: 'WKErrorDomain',
+ description: 'The web content process ended.',
+ );
+ expect(r.tracker.failure, 'The web content process ended.');
+ expect(r.outcomes, [ProductOutcome.failed]);
+
+ r.tracker
+ ..started(_viewer)
+ ..finished(_viewer);
+
+ expect(r.tracker.failure, isNull);
+ expect(r.tracker.loading, isFalse);
+ });
+
+ test('a refused viewer is retried on the same load, and fails once when the retries run out', () {
+ fakeAsync((async) {
+ final r = _Rig()..open(_viewer);
+ final waits = <Duration>[];
+ var waited = Duration.zero;
+
+ r.refused(_viewer);
+ for (var retry = 0; retry < 20 && r.tracker.measuring; retry++) {
+ expect(r.tracker.failure, 'Could not connect to the server.');
+ expect(r.tracker.loading, isTrue, reason: 'waiting to try again');
+ final before = r.loads.length;
+ var wait = Duration.zero;
+ while (r.loads.length == before && wait < const Duration(minutes: 1)) {
+ async.elapse(const Duration(milliseconds: 500));
+ wait += const Duration(milliseconds: 500);
+ }
+ if (r.loads.length == before) break;
+ waits.add(wait);
+ waited += wait;
+ expect(r.loads.last, _viewer);
+ r.tracker.started(_viewer);
+ r.refused(_viewer);
+ }
+
+ expect(waits, const [
+ Duration(seconds: 1),
+ Duration(seconds: 2),
+ Duration(seconds: 4),
+ Duration(seconds: 8),
+ Duration(seconds: 8),
+ Duration(seconds: 8),
+ ]);
+ expect(waited, const Duration(seconds: 31));
+ expect(r.begun, 1);
+ expect(r.outcomes, [ProductOutcome.failed]);
+ expect(r.tracker.loading, isFalse);
+ expect(r.tracker.failure, isNotNull);
+ async.elapse(const Duration(minutes: 1));
+ expect(r.loads, hasLength(6), reason: 'no retry after the last');
+ });
+ });
+
+ test('a retry that loads counts the load once, ok', () {
+ fakeAsync((async) {
+ final r = _Rig()..open(_viewer);
+ r.tracker.failed(
+ code: -1005,
+ domain: 'NSURLErrorDomain',
+ url: _viewer,
+ description: 'The network connection was lost.',
+ );
+ async.elapse(const Duration(seconds: 1));
+ expect(r.loads, [_viewer]);
+
+ r.tracker
+ ..started(_viewer)
+ ..finished(_viewer);
+
+ expect(r.outcomes, [ProductOutcome.ok]);
+ expect(r.tracker.failure, isNull);
+ expect(r.begun, 1);
+ });
+ });
+
+ test('a new address stops the old retries and carries on the same load', () {
+ fakeAsync((async) {
+ final r = _Rig()..open(_viewer);
+ r.refused(_viewer);
+ const moved = 'http://127.0.0.1:5200/';
+ r.open(moved);
+ expect(r.tracker.failure, isNull);
+
+ async.elapse(const Duration(minutes: 1));
+ expect(r.loads, isEmpty);
+ r.tracker.finished(moved);
+ expect(r.begun, 1);
+ expect(r.outcomes, [ProductOutcome.ok]);
+ });
+ });
+
+ test("a remote viewer's redirect belongs to its navigation", () {
+ fakeAsync((async) {
+ // The CLI's gateway answers its bootstrap address with a redirect to the viewer's own path.
+ final r = _Rig()
+ ..open('http://127.0.0.1:5200/__harness_viewer/t?path=%2F');
+
+ r.tracker.failed(
+ code: -1005,
+ domain: 'NSURLErrorDomain',
+ url: 'http://127.0.0.1:5200/',
+ description: 'The network connection was lost.',
+ );
+ async.elapse(const Duration(seconds: 1));
+
+ expect(r.loads, ['http://127.0.0.1:5200/__harness_viewer/t?path=%2F']);
+ });
+ });
+
+ test("the page's own navigations and a Reload after a load start no new observation until asked", () {
+ final r = _Rig()..open(_viewer);
+ r.tracker.finished(_viewer);
+ r.tracker
+ ..started('${_viewer}page2')
+ ..finished('${_viewer}page2');
+ expect(r.begun, 1);
+
+ // A person's Reload is a load of its own.
+ r.open(_viewer);
+ r.tracker.finished(_viewer);
+ expect(r.begun, 2);
+ expect(r.outcomes, [ProductOutcome.ok, ProductOutcome.ok]);
+ });
+
+ test('a pane closed mid-load ends its load unfinished', () {
+ fakeAsync((async) {
+ final r = _Rig()..open(_viewer);
+ r.refused(_viewer);
+
+ r.tracker.dispose();
+ async.elapse(const Duration(minutes: 1));
+
+ expect(r.outcomes, [ProductOutcome.cancelled]);
+ expect(r.loads, isEmpty);
+ });
+ });
+}
diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dart
index 0d2dc2a86..3cdd763a3 100644
--- a/desktop/test/web_pane_test.dart
+++ b/desktop/test/web_pane_test.dart
@@ -2,16 +2,21 @@
// agent's frame names a viewer, navigated when that URL changes, left closed
// once the person closes it, and taken down with the agent.
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/open_in_browser.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_monitor_controller.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/state/terminal_pane.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/web_pane_panel.dart';
+import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart';
+import 'support/fake_webview.dart';
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
@@ -22,11 +27,12 @@ Map<String, dynamic> _frame(
String? viewerError,
String? viewerName,
Map<String, dynamic>? verdict,
+ String dsh = 'autonomous/autonomous-circuit',
}) => {
'id': id,
'name': 'Agent $id',
'engine': 'claude',
- 'dsh': 'autonomous/autonomous-circuit',
+ 'dsh': dsh,
'dshName': 'Autonomous Circuit',
'viewerUrl': ?viewerUrl,
'viewerError': ?viewerError,
@@ -49,6 +55,7 @@ Future<void> _synced(
String? viewerError,
String? viewerName,
Map<String, dynamic>? verdict,
+ String? dsh,
}) => app.handleEventForTest('m', {
'type': 'agent_synced',
'payload': {
@@ -59,6 +66,7 @@ Future<void> _synced(
viewerError: viewerError,
viewerName: viewerName,
verdict: verdict,
+ dsh: dsh ?? 'autonomous/autonomous-circuit',
),
},
});
@@ -509,4 +517,116 @@ void main() {
expect(tester.takeException(), isNull);
},
);
+
+ group('with a webview', () {
+ late FakeWebViewPlatform platform;
+ setUp(() {
+ final previous = WebViewPlatform.instance;
+ platform = FakeWebViewPlatform();
+ WebViewPlatform.instance = platform;
+ WebPanePanel.webviewAvailableForTest = true;
+ addTearDown(() {
+ WebPanePanel.webviewAvailableForTest = null;
+ if (previous != null) WebViewPlatform.instance = previous;
+ });
+ });
+
+ Future<AppNotifier> open(
+ WidgetTester tester, {
+ String? dsh,
+ String url = 'http://127.0.0.1:4179/',
+ }) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.stateOf('m')!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', <TerminalBinaryFrame>[]));
+ await mount(tester, app);
+ await _synced(app, 'a0', viewerUrl: url, dsh: dsh);
+ await tester.pump();
+ return app;
+ }
+
+ testWidgets(
+ 'Harness Monitor loads its page once, though the tile rebuilds while its channel is added',
+ (tester) async {
+ final gate = platform.channelGate = Completer<void>();
+ final app = await open(tester, dsh: harnessMonitorId);
+ final controller = platform.controllers.single;
+ // The workspace repaints before the native channel call returns.
+ app.notifyListeners();
+ await tester.pump();
+ gate.complete();
+ await tester.pump();
+
+ // A second load cancelled the first (-999), and that read as a failed viewer load.
+ expect(controller.loads, [Uri.parse('http://127.0.0.1:4179/')]);
+ // Let the terminal's batched resize run out.
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+
+ testWidgets(
+ 'a viewer that refuses is tried again by itself; a cancelled navigation shows nothing',
+ (tester) async {
+ await open(tester);
+ final controller = platform.controllers.single;
+ final delegate = controller.delegate!;
+ const url = 'http://127.0.0.1:4179/';
+ expect(controller.loads, [Uri.parse(url)]);
+
+ delegate.onPageStarted!(url);
+ delegate.onWebResourceError!(
+ const WebResourceError(
+ errorCode: -999,
+ description: 'cancelled',
+ isForMainFrame: true,
+ url: url,
+ ),
+ );
+ await tester.pump();
+ expect(find.byKey(const ValueKey('web-pane-waiting')), findsNothing);
+
+ delegate.onWebResourceError!(
+ const WebResourceError(
+ errorCode: -1004,
+ description: 'Could not connect to the server.',
+ isForMainFrame: true,
+ url: url,
+ ),
+ );
+ await tester.pump();
+ expect(find.byKey(const ValueKey('web-pane-waiting')), findsOneWidget);
+ expect(find.text('Could not connect to the server.'), findsOneWidget);
+
+ await tester.pump(const Duration(seconds: 1));
+ expect(controller.loads, [Uri.parse(url), Uri.parse(url)]);
+
+ delegate.onPageStarted!(url);
+ delegate.onPageFinished!(url);
+ await tester.pump();
+ expect(find.byKey(const ValueKey('web-pane-waiting')), findsNothing);
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+
+ testWidgets(
+ "Reload loads the pane's address, never the webview's own reload",
+ (tester) async {
+ await open(tester);
+ final controller = platform.controllers.single;
+ const url = 'http://127.0.0.1:4179/';
+ controller.delegate!
+ ..onPageStarted!(url)
+ ..onPageFinished!(url);
+ await tester.pump();
+
+ await tester.tap(find.byTooltip(RegExp(r'^Reload viewer(?: · .+)?$')));
+ await tester.pump();
+
+ expect(controller.reloads, 0);
+ expect(controller.loads, [Uri.parse(url), Uri.parse(url)]);
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+ });
}