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.

Harness Monitor stops syncing while closed, hidden or frozen (#1982)

0xken15f8db621b350f
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f7cc564a0..225320803 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -974,15 +974,16 @@ 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;
+ /// (`inactive`). A browser tab behind others, or a minimised window, cannot. Harness Monitor's
+ /// page reads every machine while it is seen, and stops when this turns false.
+ final ValueNotifier<bool> inSight = ValueNotifier(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 =
+ inSight.value =
state == null ||
state == AppLifecycleState.resumed ||
state == AppLifecycleState.inactive;
@@ -9754,7 +9755,7 @@ class AppNotifier extends ChangeNotifier {
/// 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 &&
+ inSight.value &&
_viewerIsDeaf &&
_machineRecoveryTimer == null &&
_retryInFlight == null;
@@ -21799,6 +21800,7 @@ class AppNotifier extends ChangeNotifier {
_stopWakeFollowers();
modelStarts.dispose();
foreground.dispose();
+ inSight.dispose();
// Its sweep timer would otherwise outlive the window it was drawing into.
agentAlerts.dispose();
agentUnread.dispose();
diff --git a/desktop/lib/viewer/interactive_viewer.dart b/desktop/lib/viewer/interactive_viewer.dart
index f8bba31f9..744814380 100644
--- a/desktop/lib/viewer/interactive_viewer.dart
+++ b/desktop/lib/viewer/interactive_viewer.dart
@@ -30,7 +30,10 @@ class InteractiveViewerSession extends ChangeNotifier {
bool Function()? focusInput;
final _events = <Map<String, dynamic>>[];
Timer? _timer;
- bool _disposed = false, _busy = false, _reload = false;
+ bool _disposed = false, _busy = false, _reload = false, _paused = false;
+
+ /// Bumped by every pause, so a frame asked for before one is never taken as an answer after it.
+ int _pauses = 0;
int _width = 0, _height = 0;
bool _dark = true;
@@ -39,11 +42,33 @@ class InteractiveViewerSession extends ChangeNotifier {
_width = size.width.round().clamp(160, 1920);
_height = size.height.round().clamp(120, 1200);
_dark = dark;
- if (!_busy && _timer == null) _schedule(Duration.zero);
+ if (!_busy && _timer == null && !_paused) _schedule(Duration.zero);
+ }
+
+ /// Out of sight: pull nothing, and have the machine close its renderer now rather than after its
+ /// 30-second idle timeout. The rendered page runs for as long as its renderer does, and a Harness
+ /// Monitor page keeps its viewer reading every machine on the account while it runs (2026-10-28).
+ /// Back in sight, the next frame starts a fresh renderer; the last picture stays meanwhile.
+ bool get paused => _paused;
+ set paused(bool value) {
+ if (_disposed || value == _paused) return;
+ _paused = value;
+ if (value) {
+ _pauses++;
+ _timer?.cancel();
+ _timer = null;
+ _events.clear();
+ unawaited(
+ request({'surfaceId': id, 'op': 'close'})
+ .catchError((_) => <String, dynamic>{}),
+ );
+ } else if (!_busy) {
+ _schedule(Duration.zero);
+ }
}
void input(Map<String, dynamic> event) {
- if (_disposed || error != null || image == null) return;
+ if (_disposed || _paused || error != null || image == null) return;
// Mouse motion can be coalesced, but never across a press/release or key event.
if (event['event'] == 'mouseMoved' &&
_events.isNotEmpty &&
@@ -68,7 +93,7 @@ class InteractiveViewerSession extends ChangeNotifier {
_events.clear();
_reload = true;
notifyListeners();
- if (!_busy) _schedule(Duration.zero);
+ if (!_busy && !_paused) _schedule(Duration.zero);
}
void _schedule(Duration delay) {
@@ -80,8 +105,9 @@ class InteractiveViewerSession extends ChangeNotifier {
}
Future<void> _frame() async {
- if (_disposed || _busy || _width == 0 || error != null) return;
+ if (_disposed || _paused || _busy || _width == 0 || error != null) return;
_busy = true;
+ final pauses = _pauses;
final events = List<Map<String, dynamic>>.of(_events);
_events.clear();
final reload = _reload;
@@ -96,7 +122,8 @@ class InteractiveViewerSession extends ChangeNotifier {
'reload': reload,
'events': events,
});
- if (_disposed) return;
+ // Paused while it was asked: the machine closed that renderer, and its answer is no news.
+ if (_disposed || pauses != _pauses) return;
if (reply['error'] != null) {
error =
reply['detail'] as String? ??
@@ -115,12 +142,12 @@ class InteractiveViewerSession extends ChangeNotifier {
}
}
} on WsRequestTimeout {
- if (!_disposed) {
+ if (!_disposed && pauses == _pauses) {
error =
'Update Harness on this machine to use its viewer in the browser.';
}
} on WsRequestFailure catch (failure) {
- if (!_disposed) {
+ if (!_disposed && pauses == _pauses) {
error = failure.code == 'UNSUPPORTED'
? 'Update Harness on this machine to use its viewer in the browser.'
: (failure.detail?.trim().isNotEmpty == true
@@ -128,14 +155,14 @@ class InteractiveViewerSession extends ChangeNotifier {
: 'The viewer disconnected. Reconnect and try again.');
}
} catch (_) {
- if (!_disposed) {
+ if (!_disposed && pauses == _pauses) {
error = 'The viewer disconnected. Reconnect and try again.';
}
} finally {
_busy = false;
if (!_disposed) {
notifyListeners();
- if (error == null) {
+ if (error == null && !_paused) {
_schedule(
_events.isEmpty && !_reload
? const Duration(milliseconds: 160)
diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dart
index c46d84f21..8c4b4d6b3 100644
--- a/desktop/lib/widgets/web_pane_panel.dart
+++ b/desktop/lib/widgets/web_pane_panel.dart
@@ -142,13 +142,44 @@ class _WebPanePanelState extends State<WebPanePanel> {
/// The appearance last stamped on the page, so a rebuild that changed nothing runs no script.
Brightness? _stampedBrightness;
+ /// Whether the person can see this pane: its tab in front, no other pane zoomed over it, and the
+ /// window not minimised or hidden.
+ bool get _shown => widget.visible && widget.notifier.inSight.value;
+
+ /// What the Monitor's page was last told, so a rebuild that changed nothing runs no script.
+ bool? _stampedShown;
+
@override
void initState() {
super.initState();
+ widget.notifier.inSight.addListener(_shownChanged);
_mountRemote();
if (WebPanePanel.webviewAvailable) unawaited(_mountController());
}
+ /// Harness Monitor's page reads every machine on the account for as long as it is connected, and a
+ /// tile in a tab behind another stays mounted with its page loaded. Out of sight, its page is told
+ /// to disconnect and its rendered surface stops pulling frames; back in sight, both resume and the
+ /// page catches up once (2026-10-28). Other viewers are left exactly as they were.
+ void _shownChanged() {
+ _stampShown();
+ _remote?.paused = _isMonitor && !_shown;
+ }
+
+ void _stampShown() {
+ final controller = _controller;
+ if (!_isMonitor || controller == null || _loadedUrl == null) return;
+ final shown = _shown;
+ if (shown == _stampedShown) return;
+ _stampedShown = shown;
+ controller
+ .runJavaScript(
+ "document.documentElement.dataset.hostVisible='$shown';"
+ "document.dispatchEvent(new Event('harness-host-visibility'))",
+ )
+ .catchError((_) {});
+ }
+
void _mountRemote() {
if (!kIsWeb &&
!(_isMonitor && !kUnderTest && !WebPanePanel.webviewAvailable)) {
@@ -170,12 +201,14 @@ class _WebPanePanelState extends State<WebPanePanel> {
_remote!.addListener(_remoteLoaded);
}
pane.focusViewerInput = _focusRemote;
+ _remote!.paused = _isMonitor && !_shown;
}
bool _focusRemote() => _remote?.focusInput?.call() ?? false;
@override
void dispose() {
+ widget.notifier.inSight.removeListener(_shownChanged);
_finishLoad?.call(ProductOutcome.cancelled);
_viewerLoad.dispose();
if (widget.pane.focusViewerInput == _focusRemote) {
@@ -207,6 +240,8 @@ class _WebPanePanelState extends State<WebPanePanel> {
// A fresh document has no stamp; give it the app's appearance before it is looked at.
_stampedBrightness = null;
_stampTheme();
+ _stampedShown = null;
+ _stampShown();
},
onWebResourceError: (error) {
// Only the page itself: a harness's viewer pulls fonts, models
@@ -344,7 +379,12 @@ class _WebPanePanelState extends State<WebPanePanel> {
@override
void didUpdateWidget(WebPanePanel oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (oldWidget.notifier != widget.notifier) {
+ oldWidget.notifier.inSight.removeListener(_shownChanged);
+ widget.notifier.inSight.addListener(_shownChanged);
+ }
_mountRemote();
+ _shownChanged();
// The daemon named a different page — the newest artifact, a viewer
// restarted on another port. Navigate in place; the tile stays.
if (widget.pane.url != _loadedUrl) _load();
diff --git a/desktop/test/interactive_viewer_test.dart b/desktop/test/interactive_viewer_test.dart
index 0cbae6d06..536e8c8cc 100644
--- a/desktop/test/interactive_viewer_test.dart
+++ b/desktop/test/interactive_viewer_test.dart
@@ -14,6 +14,42 @@ Map<String, dynamic> picture() => {
};
void main() {
+ testWidgets(
+ 'a paused surface pulls no frames and lets the machine close its renderer; resuming pulls at once',
+ (tester) async {
+ final requests = <Map<String, dynamic>>[];
+ final session = InteractiveViewerSession((payload) async {
+ requests.add(payload);
+ return payload['op'] == 'close' ? {'closed': true} : picture();
+ });
+ session.configure(const Size(800, 600), false);
+ await tester.pump(const Duration(seconds: 1));
+ final pulled = requests.where((r) => r['op'] == 'frame').length;
+ expect(pulled, greaterThan(3), reason: 'a shown surface keeps pulling');
+
+ session.paused = true;
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(requests.last['op'], 'close');
+ final atPause = requests.length;
+ // Input and a resize while out of sight ask nothing either.
+ session.input({'type': 'text', 'text': 'x'});
+ session.configure(const Size(900, 600), false);
+ await tester.pump(const Duration(minutes: 1));
+ expect(requests, hasLength(atPause));
+ expect(session.image, isNotNull, reason: 'the last picture stays');
+
+ session.paused = false;
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(requests[atPause]['op'], 'frame');
+ expect(requests[atPause]['events'], isEmpty);
+ await tester.pump(const Duration(seconds: 1));
+ expect(
+ requests.skip(atPause).where((r) => r['op'] == 'frame').length,
+ greaterThan(3),
+ );
+ session.dispose();
+ },
+ );
testWidgets('host navigation is delivered once and ignored after disposal', (
tester,
) async {
diff --git a/desktop/test/support/fake_webview.dart b/desktop/test/support/fake_webview.dart
index 626a9f942..fc9eaa393 100644
--- a/desktop/test/support/fake_webview.dart
+++ b/desktop/test/support/fake_webview.dart
@@ -36,6 +36,7 @@ class FakeWebViewController extends PlatformWebViewController {
final FakeWebViewPlatform _platform;
final loads = <Uri>[];
+ final scripts = <String>[];
int reloads = 0;
FakeNavigationDelegate? delegate;
@@ -67,7 +68,9 @@ class FakeWebViewController extends PlatformWebViewController {
}
@override
- Future<void> runJavaScript(String javaScript) async {}
+ Future<void> runJavaScript(String javaScript) async {
+ scripts.add(javaScript);
+ }
@override
Future<String?> currentUrl() async =>
diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dart
index 3cdd763a3..fe123acdf 100644
--- a/desktop/test/web_pane_test.dart
+++ b/desktop/test/web_pane_test.dart
@@ -565,6 +565,110 @@ void main() {
},
);
+ testWidgets(
+ 'Harness Monitor is told when it is out of sight, so its page stops reading the fleet',
+ (tester) async {
+ final app = await open(tester, dsh: harnessMonitorId);
+ final controller = platform.controllers.single;
+ const url = 'http://127.0.0.1:4179/';
+ controller.delegate!
+ ..onPageStarted!(url)
+ ..onPageFinished!(url);
+ await tester.pump();
+ // What the page last heard: `data-host-visible` on its root, then the event it listens for.
+ bool? told() {
+ for (final script in controller.scripts.reversed) {
+ final match = RegExp(
+ r"dataset\.hostVisible='(true|false)';document\.dispatchEvent\(new Event\('harness-host-visibility'\)\)",
+ ).firstMatch(script);
+ if (match != null) return match[1] == 'true';
+ }
+ return null;
+ }
+
+ expect(told(), isTrue, reason: 'a page that loads in front is told so');
+ final monitorTab = app.activeSwarm.id;
+
+ app.newSwarm(name: 'Other');
+ await tester.pump();
+ expect(told(), isFalse, reason: 'another tab in front');
+
+ app.selectSwarm(monitorTab);
+ await tester.pump();
+ expect(told(), isTrue);
+
+ app.appLifecycleChanged(AppLifecycleState.inactive);
+ await tester.pump();
+ expect(
+ told(),
+ isTrue,
+ reason: 'a window behind another app can still be seen',
+ );
+ app.appLifecycleChanged(AppLifecycleState.hidden);
+ await tester.pump();
+ expect(told(), isFalse, reason: 'a minimised or hidden window cannot');
+ app.appLifecycleChanged(AppLifecycleState.resumed);
+ await tester.pump();
+ expect(told(), isTrue);
+
+ final stamps = controller.scripts.length;
+ app.notifyListeners();
+ await tester.pump();
+ expect(
+ controller.scripts,
+ hasLength(stamps),
+ reason: 'nothing new to say, nothing said',
+ );
+
+ // A reload is a new page: it hears where it stands.
+ controller.delegate!
+ ..onPageStarted!(url)
+ ..onPageFinished!(url);
+ await tester.pump();
+ expect(controller.scripts.length, greaterThan(stamps));
+ expect(told(), isTrue);
+ await tester.pump(const Duration(milliseconds: 300));
+ },
+ );
+
+ testWidgets(
+ "closing the Monitor's tab takes its page down, and with it the page's connection",
+ (tester) async {
+ final app = await open(tester, dsh: harnessMonitorId);
+ expect(find.byKey(const ValueKey('fake-webview')), findsOneWidget);
+ final tab = app.activeSwarm;
+ unawaited(app.requestCloseSwarm(tab.id));
+ await tester.pumpAndSettle();
+ expect(app.swarms, isNot(contains(tab)));
+ expect(find.byType(WebPanePanel), findsNothing);
+ expect(find.byKey(const ValueKey('fake-webview')), findsNothing);
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,
+ isFalse,
+ reason: 'its assistant stays for the next open',
+ );
+ },
+ );
+
+ testWidgets('a viewer other than the Monitor is not told anything', (
+ tester,
+ ) async {
+ final app = 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();
+ app.newSwarm(name: 'Other');
+ await tester.pump();
+ expect(
+ controller.scripts.where((s) => s.contains('hostVisible')),
+ isEmpty,
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ });
+
testWidgets(
'a viewer that refuses is tried again by itself; a cancelled navigation shows nothing',
(tester) async {
diff --git a/store/agents/harness-monitor/test/live.test.mjs b/store/agents/harness-monitor/test/live.test.mjs
new file mode 100644
index 000000000..5cda5d054
--- /dev/null
+++ b/store/agents/harness-monitor/test/live.test.mjs
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { hostHidden, liveConnection, observedAt } from '../viewer/live.js'
+
+/** A stand-in for the page's EventSource: counts what was opened and closed. */
+function streams() {
+ const opened = []
+ return { opened, open: () => { const stream = { closed: false, close() { this.closed = true } }; opened.push(stream); return stream } }
+}
+
+test('a page nobody can see, or one that is frozen, holds no connection; showing it again opens exactly one', () => {
+ const fake = streams()
+ let paused = false
+ const live = liveConnection({ open: fake.open, paused: () => paused })
+
+ live.sync(); live.sync()
+ assert.equal(fake.opened.length, 1, 'a visible page opens one connection, however often it checks')
+ assert.equal(live.open, true)
+
+ paused = true
+ live.sync()
+ assert.equal(fake.opened[0].closed, true, 'hidden or frozen: the connection is closed, so the server stops reading')
+ assert.equal(live.open, false)
+ live.sync()
+ assert.equal(fake.opened.length, 1, 'and nothing is opened while it stays that way')
+
+ paused = false
+ live.sync()
+ assert.equal(fake.opened.length, 2, 'shown or unfrozen again: one new connection, which brings the current readings')
+ assert.equal(fake.opened[1].closed, false)
+})
+
+test('Harness says when its tab is out of sight by marking the page', () => {
+ assert.equal(hostHidden({ dataset: { hostVisible: 'false' } }), true)
+ assert.equal(hostHidden({ dataset: { hostVisible: 'true' } }), false)
+ assert.equal(hostHidden({ dataset: {} }), false, 'a page opened outside Harness, or by an older Harness, is visible')
+})
+
+test('readings are dated by when they were observed, so a reopened page does not call old readings new', () => {
+ const now = 1_000_000
+ assert.equal(observedAt({ observedAt: now - 600_000 }, now), now - 600_000, 'readings kept while nobody watched say how old they are')
+ assert.equal(observedAt({ observedAt: null, status: 'starting' }, now), now, 'the first, empty snapshot has no observation yet')
+ assert.equal(observedAt({ observedAt: now + 5_000 }, now), now, 'never dated in the future')
+})
diff --git a/store/agents/harness-monitor/test/page.test.mjs b/store/agents/harness-monitor/test/page.test.mjs
index f76cc302a..385ac2309 100644
--- a/store/agents/harness-monitor/test/page.test.mjs
+++ b/store/agents/harness-monitor/test/page.test.mjs
@@ -39,7 +39,7 @@ test('the page loads only files the server is willing to serve', async () => {
assert.match(server, new RegExp(`'/${file.replace('.', '\\.')}'`), `viewer.mjs does not serve ${file}`)
}
for (const file of await readdir(join(PACKAGE, 'viewer'))) {
- assert.ok(['index.html', 'app.js', 'app.css', 'scale.js', 'table.js', 'icons'].includes(file), `unexpected file in viewer/: ${file}`)
+ assert.ok(['index.html', 'app.js', 'app.css', 'scale.js', 'table.js', 'live.js', 'icons'].includes(file), `unexpected file in viewer/: ${file}`)
}
})
diff --git a/store/agents/harness-monitor/test/server.test.mjs b/store/agents/harness-monitor/test/server.test.mjs
index 9decc0253..c2d8664ed 100644
--- a/store/agents/harness-monitor/test/server.test.mjs
+++ b/store/agents/harness-monitor/test/server.test.mjs
@@ -53,7 +53,7 @@ test('the page is served with a token in it and a CSP that forbids inline script
assert.match(response.headers.get('content-security-policy'), /script-src 'self'/)
assert.equal(html.includes('__HPS_TOKEN__'), false)
assert.match(html, new RegExp(`content="${viewer.token}"`))
- for (const path of ['/app.js', '/app.css', '/scale.js']) {
+ for (const path of ['/app.js', '/app.css', '/scale.js', '/live.js']) {
assert.equal((await fetch(`${base}${path}`)).status, 200, path)
}
assert.equal((await fetch(`${base}/../viewer.mjs`)).status, 404)
@@ -284,3 +284,91 @@ test('the fleet is read on a tick only while a pane is connected; remote machine
await fetch(`${base}/api/refresh`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-hps-token': viewer.token }, body: '{}' })
assert.equal(calls.at(-1), 0, 'a refresh forces the remote read')
})
+
+test('the machine connections are let go once nobody is looking, and opened again by the next pane', async (t) => {
+ let reads = 0, released = 0
+ const { viewer, base } = await serve(undefined, {
+ intervalMs: 40,
+ collect: async () => { reads += 1; return { rows: [], machines: [], problems: [], observedAt: Date.now() } },
+ releaseBridges: () => { released += 1 },
+ })
+ t.after(() => viewer.close())
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms))
+ await sleep(60)
+ assert.equal(released, 1, 'the start-up read keeps nothing open for a pane that never came')
+
+ const response = await fetch(`${base}/events`)
+ const reader = response.body.getReader()
+ await reader.read()
+ await sleep(150)
+ assert.equal(released, 1, 'a watched pane keeps its connections between ticks')
+ assert.ok(reads >= 3)
+
+ await reader.cancel()
+ await sleep(100)
+ assert.equal(released, 2, 'the last pane leaving lets them go, once')
+ await sleep(100)
+ assert.equal(released, 2)
+})
+
+test('a write still under way keeps the connections it is using', async (t) => {
+ let released = 0, finish
+ const { viewer, base } = await serve(undefined, {
+ releaseBridges: () => { released += 1 },
+ verbs: { stop: () => new Promise((done) => { finish = done }) },
+ })
+ t.after(() => viewer.close())
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms))
+ const before = released
+ const snapshot = await (await fetch(`${base}/api/snapshot`)).json()
+ const target = snapshot.rows[0]
+ const acting = post(base, viewer.token, '/api/act', { verb: 'stop', ids: [target.id], manual: true, expected: [target] })
+ // A pane comes and goes while the stop is still waiting for its machine.
+ const response = await fetch(`${base}/events`)
+ const reader = response.body.getReader()
+ await reader.read()
+ await reader.cancel()
+ await sleep(60)
+ assert.equal(released, before, 'a stop waiting on its machine is not cut off')
+ finish({ ok: true, id: target.id, name: target.name, action: 'stop', detail: 'engine stopped' })
+ await acting
+ await sleep(60)
+ assert.equal(released, before + 1, 'and once it is done, nothing is left open')
+})
+
+test('a cleanup preview with no page watching lets its connections go when it ends', async (t) => {
+ let released = 0
+ const { viewer, base } = await serve(undefined, {
+ releaseBridges: () => { released += 1 },
+ cleanup: { preview: async () => ({ rows: [], kept: 0, problems: [], reviewId: 'r1' }), close: async () => ({}) },
+ })
+ t.after(() => viewer.close())
+ const before = released
+ const preview = await post(base, viewer.token, '/api/cleanup/preview', {})
+ assert.equal(preview.reviewId, 'r1')
+ assert.equal(released, before + 1, 'the preview opened a connection to every machine; none is left open after it')
+})
+
+test('the last page leaving during a cleanup preview does not cut the preview off', async (t) => {
+ let released = 0, finish
+ const { viewer, base } = await serve(undefined, {
+ releaseBridges: () => { released += 1 },
+ cleanup: { preview: () => new Promise((done) => { finish = done }), close: async () => ({}) },
+ })
+ t.after(() => viewer.close())
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms))
+ const response = await fetch(`${base}/events`)
+ const reader = response.body.getReader()
+ await reader.read()
+ await sleep(30)
+ const before = released
+ const previewing = post(base, viewer.token, '/api/cleanup/preview', {})
+ await sleep(30)
+ await reader.cancel()
+ await sleep(60)
+ assert.equal(released, before, 'a preview still reading its machines keeps their connections')
+ finish({ rows: [], kept: 0, problems: [], reviewId: 'r2' })
+ await previewing
+ await sleep(30)
+ assert.equal(released, before + 1, 'and lets them go once it has its answer')
+})
diff --git a/store/agents/harness-monitor/viewer.mjs b/store/agents/harness-monitor/viewer.mjs
index fcb81893a..217123230 100644
--- a/store/agents/harness-monitor/viewer.mjs
+++ b/store/agents/harness-monitor/viewer.mjs
@@ -16,7 +16,7 @@ import { pin, readLog, readState, record, savePolicyValues, writeState, writeVer
const PACKAGE = dirname(fileURLToPath(import.meta.url))
const VERBS = new Set(['stop', 'open', 'pin', 'unpin', 'delete-review', 'delete', 'worktree-review', 'worktree-delete', 'workspace-inspect'])
-export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { stop, open, previewDelete, deleteHarness, worktreeAction, inspectWorkspace }, cleanup = cleanupReviews() }) {
+export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteIntervalMs = 15_000, now = () => Date.now(), collect = collectFleet, verbs = { stop, open, previewDelete, deleteHarness, worktreeAction, inspectWorkspace }, cleanup = cleanupReviews(), releaseBridges = closeBridges }) {
const token = randomBytes(24).toString('base64url')
const clients = new Set()
const cache = new Map()
@@ -24,7 +24,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
// `remoteIntervalMs`, the local machine every `intervalMs`, and only while a pane is connected.
const remote = { at: 0, answers: new Map(), problems: [] }
let snapshot = { spec: 1, status: 'starting', rows: [], summary: null, policy: DEFAULT_POLICY, plan: [], totals: null, problems: [], log: [], observedAt: null, intervalMs }
- let stopped = false, timer, heartbeat, polling = null
+ let stopped = false, timer, heartbeat, polling = null, using = 0
// Resolves after the first observation lands. The server starts listening before it, so the pane draws
// its shell immediately; anything that needs the first real snapshot (a test, a caller) awaits this.
let observed
@@ -83,6 +83,13 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
if (stopped || clients.size === 0) return
timer = setTimeout(() => { void poll() }, intervalMs)
}
+ // Nobody is looking and nothing is under way (a read, a write, a cleanup preview): let go of the kept
+ // machine connections as well. Each one is a bridge socket here and, behind it, a relay session the
+ // daemon holds open to that machine; a closed or frozen Monitor kept all of them open for as long as its
+ // viewer ran (2026-10-28). The next pane opens them again on its first read.
+ const release = () => {
+ if (!stopped && clients.size === 0 && !polling && using === 0) releaseBridges()
+ }
// Someone wants the observation now: read again if the one we have is older than a tick.
const wake = () => {
if (stopped || polling || now() - lastPollAt < intervalMs) return
@@ -101,16 +108,24 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
})()
try { await polling } finally { polling = null; lastPollAt = now() }
if (!stopped && !immediate) schedule()
+ release()
}
/** The write surface. One verb, up to 64 rows, and a receipt per row — the same library call the CLI
* makes, so a click and a typed command cannot behave differently. */
let writes = Promise.resolve()
function write(operation) {
+ using += 1
const result = writes.then(operation)
- writes = result.catch(() => {})
+ writes = result.catch(() => {}).finally(() => { using -= 1; release() })
return result
}
+ /** Anything else that talks to the machines over the kept connections, such as a cleanup preview: they stay open
+ * while it runs and are let go after it if nobody is looking. */
+ async function use(operation) {
+ using += 1
+ try { return await operation() } finally { using -= 1; release() }
+ }
const act = payload => write(() => actOnce(payload))
async function actOnce({ verb, ids, manual = false, expected, reviewId, path, discardChanges, choices }) {
if (!VERBS.has(verb)) return { error: `Not a verb Harness Monitor has: ${verb}` }
@@ -196,7 +211,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
for await (const chunk of req) { body += chunk; if (body.length > 64 * 1024) { json(res, 413, { error: 'Too large.' }); return } }
let payload; try { payload = JSON.parse(body || '{}') } catch { json(res, 400, { error: 'Send JSON.' }); return }
if (url.pathname === '/api/act') { json(res, 200, await act(payload)); return }
- if (url.pathname === '/api/cleanup/preview') { json(res, 200, await cleanup.preview()); return }
+ if (url.pathname === '/api/cleanup/preview') { json(res, 200, await use(() => cleanup.preview())); return }
if (url.pathname === '/api/cleanup/close') {
let result
try { result = await write(() => cleanup.close(payload.reviewId, payload.id)) }
@@ -222,7 +237,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', connection: 'keep-alive', 'x-accel-buffering': 'no' })
res.write(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`)
clients.add(res)
- res.on('close', () => { clients.delete(res); if (clients.size === 0) { clearTimeout(timer); timer = null } })
+ res.on('close', () => { clients.delete(res); if (clients.size === 0) { clearTimeout(timer); timer = null; release() } })
// A pane just opened: catch up if the observation is stale, and start ticking either way.
wake()
if (!timer && !polling) schedule()
@@ -243,6 +258,7 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, remoteInt
'/app.css': ['app.css', 'text/css; charset=utf-8'],
'/scale.js': ['scale.js', 'text/javascript; charset=utf-8'],
'/table.js': ['table.js', 'text/javascript; charset=utf-8'],
+ '/live.js': ['live.js', 'text/javascript; charset=utf-8'],
}
if (!assets[url.pathname]) { json(res, 404, { error: 'Not found' }); return }
const [file, contentType] = assets[url.pathname]
diff --git a/store/agents/harness-monitor/viewer/app.js b/store/agents/harness-monitor/viewer/app.js
index 1dc7a7daa..366f3f05a 100644
--- a/store/agents/harness-monitor/viewer/app.js
+++ b/store/agents/harness-monitor/viewer/app.js
@@ -1,4 +1,5 @@
import { ACTIVITY, SPINNER, COLUMNS, PRESETS, isLive, visibleRows, number, memory, bytes, age, formatValue, sumReading, storageTotal } from './table.js'
+import { hostHidden, liveConnection, observedAt } from './live.js'
const el = id => document.getElementById(id)
const dom = {
search: el('search'), filter: el('filter'), machine: el('machine'), columns: el('columns'), columnOptions: el('column-options'),
@@ -26,7 +27,7 @@ const state = {
preset: Object.hasOwn(PRESETS, saved.preset) ? saved.preset : 'overview',
visible: new Set(Array.isArray(saved.visible) ? saved.visible : PRESETS.overview), widths: {},
selected: null, inspecting: null, busy: new Set(), nodes: new Map(), shown: [],
- frozen: false, pending: null, connected: false, receivedAt: 0, review: null, workspaceInspection: null,
+ frozen: false, connected: false, receivedAt: 0, observedAt: 0, review: null, workspaceInspection: null,
}
for (const col of COLUMNS) state.widths[col.key] = Math.max(64, Math.min(600, Number(saved.widths?.[col.key]) || col.width))
const text = (node, value) => { if (node.textContent !== String(value)) node.textContent = value }
@@ -239,7 +240,7 @@ function render() {
text(dom.empty.lastElementChild, !ready ? 'Open harnesses will appear here.' : filtered ? 'Try another search, machine, or status.' : 'Harnesses appear here while they are open, including when idle.')
const active = state.rows.filter(isLive).length
text(dom.count, state.filter === 'stopped' ? `${state.shown.length} stopped harnesses` : `${filtered ? state.shown.length + ' of ' : ''}${active} open ${active === 1 ? 'harness' : 'harnesses'}`)
- text(dom.updated, state.frozen ? 'Updates frozen' : state.receivedAt ? 'Updated ' + age(state.receivedAt) : 'Connecting…')
+ text(dom.updated, state.frozen ? 'Updates frozen' : state.observedAt ? 'Updated ' + age(state.observedAt) : 'Connecting…')
text(dom.live, state.frozen ? 'Frozen' : !state.connected ? 'Reconnecting' : state.snapshot?.status === 'starting' ? 'Connecting' : !currentSnapshot() ? 'Unavailable' : 'Live')
dom.live.classList.toggle('inactive', state.frozen || !state.connected || !currentSnapshot())
if (ready) summary()
@@ -447,11 +448,10 @@ dom.refresh.onclick = async () => {
}
dom.freeze.onclick = () => {
state.frozen = !state.frozen; text(dom.freeze, state.frozen ? 'Live updates' : 'Freeze updates'); dom.freeze.setAttribute('aria-pressed', String(state.frozen))
- if (!state.frozen && state.pending) { applySnapshot(state.pending); state.pending = null }
- render()
+ syncLive(); render()
}
function applySnapshot(snapshot) {
- state.snapshot = snapshot; state.rows = (snapshot.rows ?? []).filter(row => row.online !== false); state.receivedAt = Date.now()
+ state.snapshot = snapshot; state.rows = (snapshot.rows ?? []).filter(row => row.online !== false); state.receivedAt = Date.now(); state.observedAt = observedAt(snapshot)
const machines = new Map((snapshot.machines ?? []).map(m => [m.machineId, m.name]))
for (const row of state.rows) machines.set(row.machineId, row.machine)
const signature = JSON.stringify([...machines])
@@ -465,32 +465,36 @@ function applySnapshot(snapshot) {
text(dom.problems, (snapshot.problems ?? []).map(p => p.machine + ': ' + String(p.error ?? 'Unavailable').replace('Offline — showing the last known sessions.', 'Offline — reconnect to view open harnesses.')).join(' · '))
render()
}
-let stream
-function connect() {
- if (stream || document.hidden) return
- stream = new EventSource('/events')
+// Out of sight (a hidden page, or Harness marking its tab hidden) or frozen: no connection, so the server
+// reads no machine for this page. Back again: one connection, which brings the readings up to date.
+const paused = () => document.hidden || hostHidden(document.documentElement) || state.frozen
+const live = liveConnection({ paused, open: () => {
+ const stream = new EventSource('/events')
stream.addEventListener('snapshot', event => {
try {
const snapshot = JSON.parse(event.data); state.connected = true
if (dom.message.textContent.startsWith('Readings are stale.')) message('')
- if (state.frozen) state.pending = snapshot; else applySnapshot(snapshot)
+ applySnapshot(snapshot)
} catch { message('Could not read the monitor update. Refresh and try again.') }
})
stream.onerror = () => { state.connected = false; message('Connection interrupted. Showing last readings; reconnecting…'); render() }
stream.onopen = () => { if (dom.message.textContent.startsWith('Connection interrupted.')) message('') }
-}
-document.addEventListener('visibilitychange', () => { if (document.hidden) { stream?.close(); stream = null; state.connected = false } else connect() })
+ return stream
+} })
+function syncLive() { if (!live.sync()) state.connected = false }
+document.addEventListener('visibilitychange', syncLive)
+document.addEventListener('harness-host-visibility', syncLive)
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)')
setInterval(() => {
- if (document.hidden || reducedMotion.matches || state.frozen || !state.connected) return
+ if (paused() || reducedMotion.matches || !state.connected) return
const mark = SPINNER[Math.floor(Date.now() / 100) % SPINNER.length]
for (const node of dom.body.querySelectorAll('.working .mark')) text(node, mark)
}, 100)
setInterval(() => {
- if (document.hidden || state.frozen || !state.receivedAt) return
+ if (paused() || !state.receivedAt) return
if (state.connected && Date.now() - state.receivedAt > 45_000) {
state.connected = false; message('Readings are stale. Showing the last update; refresh to reconnect.')
}
render()
}, 10_000)
-columnMenu(); buildColumns(); connect()
+columnMenu(); buildColumns(); syncLive()
diff --git a/store/agents/harness-monitor/viewer/live.js b/store/agents/harness-monitor/viewer/live.js
new file mode 100644
index 000000000..f5efe0660
--- /dev/null
+++ b/store/agents/harness-monitor/viewer/live.js
@@ -0,0 +1,28 @@
+/**
+ * The page's one live connection to its viewer server, open only while someone can see the page and has
+ * not frozen it. The server reads every machine on the account for as long as a page is connected, so a
+ * Monitor tab behind another tab, in a minimised window or frozen kept the whole fleet answering it
+ * (2026-10-28). Opening again brings the current readings at once and the server reads anything stale.
+ */
+
+/** Harness marks the page `data-host-visible="false"` while its tab is out of sight: a web view kept
+ * alive behind another tab can still report itself visible to the page. */
+export const hostHidden = root => root?.dataset?.hostVisible === 'false'
+
+export function liveConnection({ open, paused }) {
+ let stream = null
+ return {
+ /** Open or close the connection to match `paused()`; true when it is open afterwards. */
+ sync() {
+ if (paused()) { stream?.close(); stream = null; return false }
+ stream ??= open()
+ return true
+ },
+ get open() { return stream !== null },
+ }
+}
+
+/** When a snapshot's readings were taken. A page that reconnects first gets the readings the server
+ * kept while nobody watched, and those must not read as "Updated just now" until the next read lands. */
+export const observedAt = (snapshot, now = Date.now()) =>
+ Number.isFinite(snapshot?.observedAt) ? Math.min(snapshot.observedAt, now) : now