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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(hn): open graphical viewers from terminal sessions (#443)
Deee427e1dd5a22
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 092d3e657..31fbbda44 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -149,6 +149,11 @@ jobs:E2E_PORT: 19297HN_SOCKET_NAME: hn-ci-e2erun: bash tests/e2e.sh+ - name: Browser viewer commands and SSH handoff+ env:+ HN_VIEWER_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tui+ HN_VIEWER_TEST_PORT: 19671+ run: python3 -u tests/viewer.py- name: Persistent local shell lifecycleenv:HN_LOCAL_TEST_BINARY: ${{ github.workspace }}/tui/target/${{ matrix.target }}/release/harness-tuidiff --git a/cli/src/sharing/viewer.spec.ts b/cli/src/sharing/viewer.spec.tsindex dcf99f4b2..53321ab2f 100644--- a/cli/src/sharing/viewer.spec.ts+++ b/cli/src/sharing/viewer.spec.ts@@ -53,7 +53,7 @@ describe('private viewer capture', () => {})it('launches an isolated, credential-free renderer and sends only constrained screenshot commands', async () => {await capture.start('http://localhost:1234/')- expect(m.spawn.mock.calls[0][1]).toEqual(expect.arrayContaining(['--headless=new', '--disable-sync', '--disable-extensions', '--remote-debugging-address=127.0.0.1', '--user-data-dir=/tmp/share-viewer-fixture']))+ expect(m.spawn.mock.calls[0][1]).toEqual(expect.arrayContaining(['--headless=new', '--disable-sync', '--disable-extensions', '--use-mock-keychain', '--password-store=basic', '--remote-debugging-address=127.0.0.1', '--user-data-dir=/tmp/share-viewer-fixture']))expect(await capture.capture()).toBe('jpeg')const requests = m.sockets[0].send.mock.calls.map((args: any[]) => JSON.parse(args[0]))expect(requests.find((r: any) => r.method === 'Page.navigate')).toMatchObject({ sessionId: 'session', params: { url: 'http://localhost:1234/' } })diff --git a/cli/src/sharing/viewer.ts b/cli/src/sharing/viewer.tsindex 2cb814c70..c56d7bd25 100644--- a/cli/src/sharing/viewer.ts+++ b/cli/src/sharing/viewer.ts@@ -47,8 +47,11 @@ export class ViewerCapture {// while the owner's own pane showed the model (owner, 2026-09-18: "bên máy kia đang ra cái xe đạp,// bên này không thấy gì"). Without it Chrome renders on the GPU, or on SwiftShader where there is// none; `--enable-unsafe-swiftshader` keeps that fallback available on Chrome builds that gate it.+ // This disposable profile never holds account credentials. OS credential stores can block+ // its first navigation behind an invisible unlock prompt on a locked or SSH-only host.this.child = spawn(browser, ['--headless=new', '--enable-unsafe-swiftshader', '--no-first-run', '--no-default-browser-check','--disable-sync', '--disable-extensions', '--disable-background-networking', '--mute-audio',+ '--use-mock-keychain', '--password-store=basic','--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0',`--user-data-dir=${this.directory}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] })const endpoint = await new Promise<string>((resolve, reject) => {diff --git a/desktop/README.md b/desktop/README.mdindex dd6758c74..2bfdafcfa 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -6,6 +6,13 @@ experience.** Linux builds exist, with feature parity still in progress; Windowsplanned and its runner is unexercised. Native embedded harness viewers require macOS;the browser renders managed viewers on their connected machine.+`hn view` can open a viewer companion at `/?viewer=1&machine=<id>&agent=<id>`.+This owner-only destination uses normal sign-in and machine linking. It does not restore or+save the workspace, join the shared desk, or attach a terminal. OAuth returns to the same+viewer after sign-in. The existing website root rewrite serves it without a new route.+Publish the browser build before the corresponding native hn release so the entry point+recognizes the viewer destination.+The browser target uses this same Flutter package and `lib/main.dart`: workspace,swarms, pickers, settings, state, and the patched xterm renderer are shared. Browsersupport is available as a public preview atdiff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dartindex 877492359..fa312a586 100644--- a/desktop/integration_test/native_workspace_e2e_test.dart+++ b/desktop/integration_test/native_workspace_e2e_test.dart@@ -208,6 +208,17 @@ class _FirstCreationApp extends AppNotifier {}class _WorkspaceLinks implements PeerLinkClient {+ @override+ Future<CliLinkConnectResult> connectWithCode(+ String machineId,+ String code, {+ required String label,+ String? displayName,+ String? expectedFingerprint,+ }) async => const CliLinkConnectResult(+ error: 'Code linking is not used by this fixture.',+ );+final requests = <String>[];final replies = <Completer<CliLinkConnectResult>>[];diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex c6d708fec..7dda09000 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -36,6 +36,8 @@ import 'widgets/update_notice.dart';import 'widgets/window_chrome.dart';import 'sharing/shared_agent_location.dart';import 'sharing/shared_agent_page.dart';+import 'viewer/viewer_location.dart';+import 'viewer/viewer_page.dart';import 'viewer/pending_pair.dart';import 'viewer/pending_pair_store.dart';import 'widgets/add_machine_dialog.dart';@@ -367,7 +369,18 @@ class _RootShellState extends ConsumerState<RootShell>_holdPhoneLink(app);case AppStatus.authenticated:_webQrStarted = false;- screen = widget.authenticatedScreen(app);+ final viewerLocation = kIsWeb+ ? ViewerLocation.parse(Uri.base)+ : null;+ screen = viewerLocation != null+ ? ViewerPage(app: app, location: viewerLocation)+ : kIsWeb && ViewerLocation.isRoute(Uri.base)+ ? const Center(+ child: Text(+ 'This viewer link is incomplete. Run hn view again.',+ ),+ )+ : widget.authenticatedScreen(app);_askAboutPendingPair(app);}// Preserve the fragment pin while dialogs navigate; an OAuth callback can restore it later.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 4b851108e..3fb15f83e 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -20,6 +20,7 @@ import '../api/api_client.dart';import '../viewer/sign_in_browser.dart';import '../viewer/direct_link.dart';import '../viewer/viewer_services.dart';+import '../viewer/viewer_location.dart';import '../e2ee/bytes.dart' show b64d;import '../e2ee/keys.dart' show fingerprint;import '../viewer/group_sync.dart'@@ -1956,6 +1957,7 @@ class AppNotifier extends ChangeNotifier {PeerLinkClient? peerLinks,ViewerServices? viewer,PaneLayoutStore? paneLayoutStore,+ this.workspaceEnabled,this.turnActivityTimeout = const Duration(seconds: 12),AlertSounds? alerts,AgentAlerts? agentAlerts,@@ -2084,6 +2086,10 @@ class AppNotifier extends ChangeNotifier {/// [appStateProvider].final PaneLayoutStore? _paneLayout;+ /// A viewer companion uses auth and machine connections without restoring, claiming or+ /// writing workspace panes. Read after OAuth has restored the browser destination.+ final bool Function()? workspaceEnabled;+/// The dial on this desk, for the rail's device row. Fed by `dial_status`/// frames from the local daemon; its own notifier, so the row rebuilds/// without dragging the whole rail through a machine-list rebuild.@@ -11540,8 +11546,9 @@ class AppNotifier extends ChangeNotifier {int _layoutRevision = 0;- Future<void> flushPaneLayout() =>- _paneLayout?.flushSwarms() ?? Future<void>.value();+ Future<void> flushPaneLayout() => workspaceEnabled?.call() == false+ ? Future<void>.value()+ : _paneLayout?.flushSwarms() ?? Future<void>.value();// ── desk sync ────────────────────────────────────────────────────────────@@ -11615,6 +11622,7 @@ class AppNotifier extends ChangeNotifier {/// the desk are given desk ids and seeded (every machine's tabs land; the/// person closes the extras), and the merged desk is applied.Future<void> _deskStart(int authRevision) async {+ if (workspaceEnabled?.call() == false) return;if (_deskJoining != null) return _deskJoining;final run = _deskJoin(authRevision);_deskJoining = run;@@ -11631,6 +11639,7 @@ class AppNotifier extends ChangeNotifier {/// backend link coming back — because a daemon whose backend was offline/// answered the first read with an error, not with a desk.void _deskEnsure(int authRevision) {+ if (workspaceEnabled?.call() == false) return;if (_desk.enabled || _deskJoining != null) return;unawaited(_deskStart(authRevision));}@@ -12026,6 +12035,7 @@ class AppNotifier extends ChangeNotifier {}void _persistLayout() {+ if (workspaceEnabled?.call() == false) return;for (final pane in allPanes) {if (pane.agentId case final id?) {rememberOpenedHarness(pane.machineId, id);@@ -12082,6 +12092,7 @@ class AppNotifier extends ChangeNotifier {/// [TerminalPane.claimOnFirstAttach]. False for a restore that is merely/// bookkeeping (a machine re-keyed under the window), which nobody asked for.Future<void> _restorePaneLayout({bool claimOnAttach = false}) async {+ if (workspaceEnabled?.call() == false) return;final store = _paneLayout;if (store == null) return;final initialSwarm = activeSwarm;@@ -13482,6 +13493,8 @@ final appStateProvider = Provider<AppNotifier>((ref) {authSession: AuthSession(),configStore: ConfigStore(),paneLayoutStore: PaneLayoutStore(),+ workspaceEnabled: () =>+ !kIsWeb || ViewerLocation.workspaceAllowed(Uri.base),);app.bootstrap();return app;diff --git a/desktop/lib/viewer/browser_login.dart b/desktop/lib/viewer/browser_login.dartindex 82d3974b6..2cf655bfa 100644--- a/desktop/lib/viewer/browser_login.dart+++ b/desktop/lib/viewer/browser_login.dart@@ -9,6 +9,7 @@ import '../e2ee/keys.dart' show fingerprint;import 'direct_auth.dart';import 'direct_auth_api.dart';import '../sharing/shared_agent_location.dart';+import 'viewer_location.dart';import 'pending_pair_store.dart';import 'qr_sign_in.dart';import 'viewer_key_store.dart';@@ -81,7 +82,9 @@ class BrowserLogin implements SignInClient {'This sign-in expired or started in another tab. Sign in again.',);}- final returnTo = SharedAgentLocation.returnPath(saved['returnTo']);+ final returnTo =+ SharedAgentLocation.returnPath(saved['returnTo']) ??+ ViewerLocation.returnPath(saved['returnTo']);if (returnTo != null) browser.replaceLocation(returnTo);if (uri.queryParameters.containsKey('error')) {throw const DirectAuthException(@@ -171,7 +174,8 @@ class BrowserLogin implements SignInClient {'tx': start.tx,'state': state,'createdAt': _clock().millisecondsSinceEpoch,- if (SharedAgentLocation.parse(location) != null)+ if (SharedAgentLocation.parse(location) != null ||+ ViewerLocation.parse(location) != null)'returnTo': Uri(path: location.path,query: location.hasQuery ? location.query : null,diff --git a/desktop/lib/viewer/interactive_viewer.dart b/desktop/lib/viewer/interactive_viewer.dartindex ed0015747..1cb5f224f 100644--- a/desktop/lib/viewer/interactive_viewer.dart+++ b/desktop/lib/viewer/interactive_viewer.dart@@ -116,7 +116,9 @@ class InteractiveViewerSession extends ChangeNotifier {if (!_disposed) {error = failure.code == 'UNSUPPORTED'? 'Update Harness on this machine to use its viewer in the browser.'- : 'The viewer disconnected. Reconnect and try again.';+ : (failure.detail?.trim().isNotEmpty == true+ ? failure.detail!+ : 'The viewer disconnected. Reconnect and try again.');}} catch (_) {if (!_disposed) {@@ -375,6 +377,11 @@ class _InteractiveViewerState extends State<RemoteViewerSurface> {},child: Image.memory(bytes,+ // A viewer frame can be smaller than the viewport (the renderer caps its+ // resolution). Keep painting and pointer coordinates on the same surface,+ // including while the first image codec is still decoding.+ width: _size.width,+ height: _size.height,fit: BoxFit.fill,gaplessPlayback: true,excludeFromSemantics: true,diff --git a/desktop/lib/viewer/viewer_location.dart b/desktop/lib/viewer/viewer_location.dartnew file mode 100644index 000000000..4301685ea--- /dev/null+++ b/desktop/lib/viewer/viewer_location.dart@@ -0,0 +1,67 @@+/// An owner's viewer destination. IDs identify work; the URL grants no access. The browser+/// still needs its own sign-in and a trusted, encrypted link to the selected machine.+class ViewerLocation {+ const ViewerLocation(this.machineId, this.agentId);+ final String machineId, agentId;++ static bool isRoute(Uri uri) {+ if (uri.path != '/') return false;+ // Inspect keys without decoding values: a damaged identity must still stay on+ // the viewer error page instead of throwing or restoring the normal desk.+ for (final field in uri.query.split('&')) {+ try {+ if (Uri.decodeQueryComponent(field.split('=').first) == 'viewer') {+ return true;+ }+ } on FormatException {+ // An unrelated damaged key cannot hide a later viewer flag.+ }+ }+ return false;+ }++ static ViewerLocation? parse(Uri uri) {+ if (!isRoute(uri)) return null;+ try {+ if (uri.queryParametersAll['viewer']?.length != 1 ||+ uri.queryParameters['viewer'] != '1') {+ return null;+ }+ String? id(String key) {+ final values = uri.queryParametersAll[key];+ if (values == null || values.length != 1) return null;+ final value = values.single;+ if (value.isEmpty ||+ value.length > 160 ||+ value.runes.any((c) => c < 32 || c == 127)) {+ return null;+ }+ return value;+ }++ final machine = id('machine'), agent = id('agent');+ return machine == null || agent == null+ ? null+ : ViewerLocation(machine, agent);+ } on FormatException {+ return null;+ }+ }++ static String? returnPath(Object? value) {+ if (value is! String) return null;+ final uri = Uri.tryParse(value);+ if (uri == null ||+ uri.hasScheme ||+ uri.hasAuthority ||+ parse(uri) == null) {+ return null;+ }+ return uri.toString();+ }++ /// OAuth restores its destination before signed-in bootstrap. Until that happens, no callback+ /// tab should restore or claim a terminal from the saved workspace.+ static bool workspaceAllowed(Uri uri) =>+ !isRoute(uri) && uri.path != '/auth/callback' && uri.path != '/callback';+}diff --git a/desktop/lib/viewer/viewer_page.dart b/desktop/lib/viewer/viewer_page.dartnew file mode 100644index 000000000..302928e4e--- /dev/null+++ b/desktop/lib/viewer/viewer_page.dart@@ -0,0 +1,145 @@+import 'package:flutter/material.dart';++import '../state/app_state.dart';+import '../state/terminal_pane.dart';+import '../terminal/terminal_text.dart';+import '../widgets/link_machine_screen.dart';+import '../widgets/terminal_text_action.dart';+import '../widgets/web_pane_panel.dart';+import '../core/models.dart';+import 'viewer_location.dart';++/// A browser companion to hn. This pane is never added to a swarm, never persisted, and never+/// opens a terminal stream. Closing the tab only closes its viewer surface.+class ViewerPage extends StatefulWidget {+ const ViewerPage({super.key, required this.app, required this.location});+ final AppNotifier app;+ final ViewerLocation location;+ @override+ State<ViewerPage> createState() => _ViewerPageState();+}++class _ViewerPageState extends State<ViewerPage> {+ TerminalPane? _pane;++ Widget _message(String text, {VoidCallback? retry}) => Center(+ child: Padding(+ padding: EdgeInsets.all(terminalCellSizeOf(context).height),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ text,+ style: terminalContentStyle(),+ textAlign: TextAlign.center,+ ),+ if (retry != null) ...[+ SizedBox(height: terminalCellSizeOf(context).height),+ TerminalTextAction(label: 'Retry', onPressed: retry),+ ],+ ],+ ),+ ),+ );++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.app,+ builder: (context, _) {+ final app = widget.app, location = widget.location;+ final machine = app.stateOf(location.machineId);+ if (machine == null) {+ if (app.machineListError != null) {+ return _message(+ app.machineListError!,+ retry: () {+ app.retryMachines();+ },+ );+ }+ if (!app.machineInventoryLoaded || app.machinesLoading) {+ return _message('Finding this machine…');+ }+ return _message(+ 'This machine is not available to this account.',+ retry: () {+ app.retryMachines();+ },+ );+ }+ if (machine.machine.isShared) {+ return _message('Sign in as the owner to open this viewer.');+ }+ if (machine.needsLink) {+ return Center(+ child: LinkMachineScreen(notifier: app, machineState: machine),+ );+ }+ if (machine.nodeOnline == false) {+ return _message(+ '${machine.machine.name} is offline.',+ retry: () {+ app.retryOfflineMachine(location.machineId);+ },+ );+ }+ if (machine.agentLoadStatus == AgentLoadStatus.error ||+ machine.connectionStatus == ConnectionStatus.disconnected) {+ return _message(+ 'The machine is disconnected. Reconnect to open its viewer.',+ retry: () {+ app.reloadMachineData(location.machineId);+ },+ );+ }+ if (machine.connectionStatus != ConnectionStatus.connected ||+ machine.agentLoadStatus != AgentLoadStatus.loaded) {+ return _message('Connecting to ${machine.machine.name}…');+ }+ final agent = machine.agents+ .where((a) => a.id == location.agentId)+ .firstOrNull;+ if (agent == null) {+ return _message(+ 'This harness is no longer available.',+ retry: () {+ app.reloadMachineData(location.machineId);+ },+ );+ }+ if (agent.viewerUrl == null) {+ return _message(+ agent.viewerError ??+ (agent.viewerName != null+ ? '${agent.viewerName} is starting. You can keep working in hn.'+ : 'This harness has no viewer.'),+ retry: () {+ app.reloadMachineData(location.machineId);+ },+ );+ }+ final pane =+ _pane?.machineId == location.machineId &&+ _pane?.ownerAgentId == location.agentId+ ? _pane!+ : (_pane = TerminalPane(+ id: -1,+ machineId: location.machineId,+ ownerAgentId: location.agentId,+ kind: PaneKind.web,+ ));+ pane.url = agent.viewerUrl;+ pane.viewerError = agent.viewerError;+ return WebPanePanel(+ key: ValueKey('${location.machineId}/${location.agentId}'),+ notifier: app,+ pane: pane,+ title: agent.viewerName ?? 'Viewer',+ ownerName: agent.name,+ ownerEngine: agent.identityEngine,+ ownerDisplayName: agent.identityDisplayName,+ verdict: agent.verdict,+ );+ },+ );+}diff --git a/desktop/test/browser_login_test.dart b/desktop/test/browser_login_test.dartindex 5dff63016..c0c2aa62d 100644--- a/desktop/test/browser_login_test.dart+++ b/desktop/test/browser_login_test.dart@@ -136,6 +136,40 @@ void main() {}});+ test('sign-in preserves the exact private viewer destination', () async {+ const destination = '/?viewer=1&machine=server-1&agent=blender%20model';+ browser.uri = Uri.parse('https://harness.example$destination');+ final pending = login.login(onAuthorizeUrl: (_) {});+ final cancelled = expectLater(pending, throwsA(isA<DirectAuthException>()));+ api.authorization.complete((+ authorizeUrl: Uri.https('sso.example', '/authorize', {+ 'state': 'expected',+ 'redirect_uri': 'https://harness.example/auth/callback',+ }).toString(),+ tx: 'transaction',+ ));+ await Future<void>.delayed(Duration.zero);+ final saved = browser.transaction!;+ expect(jsonDecode(saved)['returnTo'], destination);+ login.cancel();+ await cancelled;+ browser.transaction = saved;+ browser.uri = Uri.parse(+ 'https://harness.example/auth/callback?state=expected&code=one-use',+ );+ final status = login.checkStatus();+ await Future<void>.delayed(Duration.zero);+ expect(browser.uri.toString(), 'https://harness.example$destination');+ api.exchanged.complete(+ const IssuedTokens(+ token: 'access',+ refreshToken: 'refresh',+ expiresIn: 3600,+ ),+ );+ expect((await status).loggedIn, isTrue);+ });+test('authorization stays in this tab and cancellation discards its transaction',() async {diff --git a/desktop/test/interactive_viewer_test.dart b/desktop/test/interactive_viewer_test.dartindex 0d21e5d40..97a834334 100644--- a/desktop/test/interactive_viewer_test.dart+++ b/desktop/test/interactive_viewer_test.dart@@ -4,6 +4,7 @@ import 'dart:convert';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/viewer/interactive_viewer.dart';+import 'package:harness/ws/ws_conn.dart';Map<String, dynamic> picture() => {'data': base64Encode([1, 2, 3]),@@ -115,4 +116,21 @@ void main() {session.dispose();},);+ testWidgets(+ 'renderer refusals preserve recovery guidance from the real RPC transport',+ (tester) async {+ final session = InteractiveViewerSession((payload) async {+ if (payload['op'] == 'close') return {'closed': true};+ throw const WsRequestFailure(+ responseType: 'viewer_surface_result',+ code: 'VIEWER_LIMIT',+ detail: 'Close another viewer to open this one.',+ );+ });+ session.configure(const Size(800, 600), false);+ await tester.pump(const Duration(milliseconds: 1));+ expect(session.error, 'Close another viewer to open this one.');+ session.dispose();+ },+ );}diff --git a/desktop/test/viewer_location_test.dart b/desktop/test/viewer_location_test.dartnew file mode 100644index 000000000..93fed7e8e--- /dev/null+++ b/desktop/test/viewer_location_test.dart@@ -0,0 +1,87 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/viewer/viewer_location.dart';++void main() {+ test(+ 'viewer destinations round trip escaped identities without granting access',+ () {+ const path = '/?viewer=1&machine=server&agent=a%20%2F%3F%26%C3%A9';+ final location = ViewerLocation.parse(+ Uri.parse('https://harness.example$path'),+ )!;+ expect(location.machineId, 'server');+ expect(location.agentId, 'a /?&é');+ expect(ViewerLocation.returnPath(path), path);+ for (final invalid in [+ 'https://other.example$path',+ '//other.example$path',+ '/auth/callback?code=secret',+ '/?viewer=1&machine=m',+ '/?viewer=1&machine=m&agent=',+ '/?viewer=1&machine=m&agent=a&agent=b',+ '/?viewer=1&machine=m&agent=%0A',+ '/view/else?machine=m&agent=a',+ ]) {+ expect(ViewerLocation.returnPath(invalid), isNull, reason: invalid);+ }+ },+ );++ test('viewer and OAuth tabs cannot restore terminal workspace', () {+ for (final path in [+ '/?viewer=1&machine=m&agent=a',+ '/?viewer=1',+ '/auth/callback',+ '/callback',+ ]) {+ expect(+ ViewerLocation.workspaceAllowed(+ Uri.parse('https://harness.example$path'),+ ),+ isFalse,+ );+ }+ expect(+ ViewerLocation.workspaceAllowed(Uri.parse('https://harness.example/')),+ isTrue,+ );+ });++ test(+ 'malformed UTF-8 and duplicate viewer flags fail closed without throwing',+ () {+ for (final query in [+ 'viewer=1&machine=m&agent=%FF',+ 'viewer=1&machine=%C0%AF&agent=a',+ 'viewer=%FF&machine=m&agent=a',+ 'viewer=1&machine=m&agent=a&unknown=%FF',+ '%FF=x&viewer=1&machine=m&agent=a',+ 'viewer=1&viewer=0&machine=m&agent=a',+ 'viewer=0&machine=m&agent=a',+ 'viewer=1&machine=m&machine=n&agent=a',+ 'viewer=1&machine=m&agent=%7F',+ 'viewer=1&machine=m&agent=${'a' * 161}',+ ]) {+ final uri = Uri.parse('https://harness.example/?$query');+ expect(ViewerLocation.isRoute(uri), isTrue, reason: query);+ expect(ViewerLocation.parse(uri), isNull, reason: query);+ expect(ViewerLocation.workspaceAllowed(uri), isFalse, reason: query);+ expect(ViewerLocation.returnPath('/?$query'), isNull, reason: query);+ }+ expect(ViewerLocation.returnPath(null), isNull);+ expect(ViewerLocation.returnPath(42), isNull);+ expect(ViewerLocation.returnPath('http://[invalid'), isNull);+ },+ );++ test('encoded query keys and boundary identities survive sign-in', () {+ final uri = Uri.parse(+ 'https://harness.example/?view%65r=1&machine=${'m' * 160}&agent=%E6%B5%8B%E8%AF%95%2B%23',+ );+ expect(ViewerLocation.isRoute(uri), isTrue);+ expect(ViewerLocation.parse(uri)!.machineId.length, 160);+ expect(ViewerLocation.parse(uri)!.agentId, '测试+#');+ expect(ViewerLocation.workspaceAllowed(uri), isFalse);+ expect(ViewerLocation.parse(Uri.parse('https://harness.example/')), isNull);+ });+}diff --git a/desktop/test/viewer_page_test.dart b/desktop/test/viewer_page_test.dartnew file mode 100644index 000000000..cf6439a55--- /dev/null+++ b/desktop/test/viewer_page_test.dart@@ -0,0 +1,269 @@+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/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/viewer/viewer_location.dart';+import 'package:harness/viewer/viewer_page.dart';+import 'package:harness/widgets/link_machine_screen.dart';+import 'package:harness/widgets/web_pane_panel.dart';++import 'swarm_state_test.dart' show MemoryStore;++class _App extends AppNotifier {+ _App({MemoryStore? storage})+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryStore()),+ configStore: null,+ paneLayoutStore: storage == null+ ? null+ : PaneLayoutStore(storage: storage),+ workspaceEnabled: () => false,+ );+ bool inventoryLoaded = true;+ String? inventoryError;+ @override+ bool get machineInventoryLoaded => inventoryLoaded;+ @override+ String? get machineListError => inventoryError;+ int retries = 0, inventoryRetries = 0, offlineRetries = 0;+ @override+ Future<void> retryMachines() async {+ inventoryRetries++;+ }++ @override+ Future<void> retryOfflineMachine(String machineId) async {+ offlineRetries++;+ }++ @override+ Future<void> reloadMachineData(String machineId) async {+ retries++;+ }+}++class _Desk extends ApiClient {+ _Desk()+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ );+ int reads = 0;+ @override+ Future<Map<String, dynamic>?> desk() async {+ reads++;+ throw StateError('A viewer must not join the desk');+ }+}++void main() {+ test(+ 'companion never restores, claims, joins or overwrites the saved desk',+ () async {+ final storage = MemoryStore();+ await PaneLayoutStore(storage: storage).saveSwarms([+ Swarm(id: 'saved', name: 'Work')+ ..panes.add(TerminalPane(id: 1, machineId: 'm', agentId: 'other')),+ ], 'saved');+ final before = Map.of(storage.values);+ final desk = _Desk();+ final app = _App(storage: storage)..api = desk;+ addTearDown(app.dispose);+ await app.restorePaneLayoutForTest(claimOnAttach: true);+ await app.deskStartForTest();+ app.newSwarm(name: 'Transient');+ await app.flushPaneLayout();+ expect(app.allPanes, isEmpty);+ expect(app.deskSyncForTest.enabled, isFalse);+ expect(desk.reads, 0);+ expect(storage.values, before);+ },+ );++ testWidgets(+ 'viewer follows its named harness, requires linking and never opens a terminal',+ (tester) async {+ final app = _App();+ const machine = Machine(+ machineId: 'm',+ name: 'Render server',+ authMode: MachineAuthMode.remote,+ );+ final state = MachineState(machine)+ ..nodeOnline = true+ ..needsLink = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ app.machineStates['m'] = state;+ app.machines = [machine];+ Future<void> mount() => tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: ViewerPage(+ app: app,+ location: const ViewerLocation('m', 'blender'),+ ),+ ),+ );+ await mount();+ expect(find.byType(LinkMachineScreen), findsOneWidget);+ state.needsLink = false;+ state.agents = [+ const Agent(id: 'blender', name: 'Chair', viewerName: '3D Viewer'),+ ];+ app.notifyListeners();+ await tester.pump();+ expect(find.textContaining('is starting'), findsOneWidget);+ state.agents = [+ const Agent(+ id: 'blender',+ name: 'Chair',+ viewerName: '3D Viewer',+ viewerUrl: 'http://127.0.0.1:19679/model',+ ),+ ];+ app.notifyListeners();+ await tester.pump();+ expect(find.byType(WebPanePanel), findsOneWidget);+ final pane = tester.widget<WebPanePanel>(find.byType(WebPanePanel)).pane;+ expect(pane.ownerAgentId, 'blender');+ expect(pane.agentId, isNull);+ expect(app.allPanes, isEmpty);+ state.agents = [];+ app.notifyListeners();+ await tester.pump();+ expect(find.textContaining('no longer available'), findsOneWidget);+ await tester.tap(find.textContaining('Retry'));+ await tester.pump();+ expect(app.retries, 1);+ state.nodeOnline = false;+ app.notifyListeners();+ await tester.pump();+ expect(find.text('Render server is offline.'), findsOneWidget);+ await tester.pumpWidget(const SizedBox.shrink());+ app.dispose();+ expect(tester.takeException(), isNull);+ },+ );++ testWidgets(+ 'inventory, ownership, connection and viewer failures each recover without a terminal',+ (tester) async {+ final app = _App()..inventoryLoaded = false;+ addTearDown(app.dispose);+ Future<void> update() async {+ app.notifyListeners();+ await tester.pump();+ }++ Future<void> retry() async {+ await tester.tap(find.textContaining('Retry'));+ await tester.pump();+ }++ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: ViewerPage(app: app, location: const ViewerLocation('m', 'a')),+ ),+ );+ expect(find.text('Finding this machine…'), findsOneWidget);+ app.inventoryError = 'Inventory is unavailable';+ await update();+ expect(find.text('Inventory is unavailable'), findsOneWidget);+ await retry();+ expect(app.inventoryRetries, 1);+ app.inventoryError = null;+ app.inventoryLoaded = true;+ await update();+ expect(+ find.textContaining('not available to this account'),+ findsOneWidget,+ );+ await retry();+ expect(app.inventoryRetries, 2);+ app.machineStates['m'] = MachineState(+ const Machine(+ machineId: 'm',+ name: 'Shared',+ authMode: MachineAuthMode.remote,+ isShared: true,+ ),+ );+ await update();+ expect(find.textContaining('Sign in as the owner'), findsOneWidget);+ final machine = MachineState(+ const Machine(+ machineId: 'm',+ name: 'Renderer',+ authMode: MachineAuthMode.remote,+ ),+ )..nodeOnline = false;+ app.machineStates['m'] = machine;+ await update();+ expect(find.text('Renderer is offline.'), findsOneWidget);+ await retry();+ expect(app.offlineRetries, 1);+ machine.nodeOnline = true;+ machine.connectionStatus = ConnectionStatus.disconnected;+ await update();+ expect(find.textContaining('machine is disconnected'), findsOneWidget);+ await retry();+ expect(app.retries, 1);+ machine.connectionStatus = ConnectionStatus.connecting;+ machine.agentLoadStatus = AgentLoadStatus.loading;+ await update();+ expect(find.text('Connecting to Renderer…'), findsOneWidget);+ machine.connectionStatus = ConnectionStatus.connected;+ machine.agentLoadStatus = AgentLoadStatus.error;+ await update();+ expect(find.textContaining('machine is disconnected'), findsOneWidget);+ machine.agentLoadStatus = AgentLoadStatus.loaded;+ machine.agents = [const Agent(id: 'a', name: 'Fixture')];+ await update();+ expect(find.text('This harness has no viewer.'), findsOneWidget);+ await retry();+ expect(app.retries, 2);+ machine.agents = [+ const Agent(+ id: 'a',+ name: 'Fixture',+ viewerError: 'Renderer could not start',+ ),+ ];+ await update();+ expect(find.text('Renderer could not start'), findsOneWidget);+ machine.agents = [+ const Agent(+ id: 'a',+ name: 'Fixture',+ viewerUrl: 'http://127.0.0.1:19679/first',+ ),+ ];+ await update();+ final first = tester.widget<WebPanePanel>(find.byType(WebPanePanel)).pane;+ machine.agents = [+ const Agent(+ id: 'a',+ name: 'Fixture',+ viewerUrl: 'http://127.0.0.1:19679/restarted',+ ),+ ];+ await update();+ final next = tester.widget<WebPanePanel>(find.byType(WebPanePanel)).pane;+ expect(next, same(first));+ expect(next.url, endsWith('/restarted'));+ expect(app.allPanes, isEmpty);+ await tester.pumpWidget(const SizedBox.shrink());+ expect(tester.takeException(), isNull);+ },+ );+}diff --git a/desktop/test/web/browser_viewer_test.dart b/desktop/test/web/browser_viewer_test.dartnew file mode 100644index 000000000..338d50a58--- /dev/null+++ b/desktop/test/web/browser_viewer_test.dart@@ -0,0 +1,190 @@+@TestOn('browser')+library;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/app_shell.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/screens/login_screen.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/viewer/interactive_viewer.dart';+import 'package:harness/viewer/viewer_page.dart';+import 'package:web/web.dart' as web;++import '../swarm_state_test.dart' show MemoryStore;++// A small opaque JPEG, generated for this transport test; no external assets or real viewers.+const picture =+ '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAYACADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDyOiiitCQooooAKKKKACiiigD/2Q==';++class _App extends AppNotifier {+ _App()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryStore()),+ configStore: null,+ workspaceEnabled: () => false,+ );+ final requests = <Map<String, dynamic>>[];+ bool fail = false;+ @override+ Future<Map<String, dynamic>> viewerSurface(+ String machineId,+ String agentId,+ Map<String, dynamic> payload,+ ) async {+ requests.add({'machine': machineId, 'agent': agentId, ...payload});+ if (payload['op'] == 'close') return {'closed': true};+ if (fail) {+ return {'error': 'VIEWER_UNAVAILABLE', 'detail': 'Fixture disconnected'};+ }+ return {+ 'data': picture,+ 'mime': 'image/jpeg',+ 'width': payload['width'],+ 'height': payload['height'],+ };+ }+}++void main() {+ testWidgets('a damaged viewer link remains an error page after sign-in', (+ tester,+ ) async {+ final previous = web.window.location.href;+ web.window.history.replaceState(+ null,+ '',+ '/?viewer=1&machine=%FF&agent=model',+ );+ addTearDown(() => web.window.history.replaceState(null, '', previous));+ final app = _App()..status = AppStatus.authenticated;+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: HarnessApp(+ authenticatedScreen: (_) => const Text('Workspace must stay closed'),+ ),+ ),+ );+ await tester.pump();+ expect(+ find.text('This viewer link is incomplete. Run hn view again.'),+ findsOneWidget,+ );+ expect(find.text('Workspace must stay closed'), findsNothing);+ expect(find.byType(ViewerPage), findsNothing);+ expect(app.requests, isEmpty);+ expect(app.allPanes, isEmpty);+ await tester.pumpWidget(const SizedBox.shrink());+ app.dispose();+ expect(tester.takeException(), isNull);+ });+ testWidgets(+ 'hn browser link gates sign-in, drives only its viewer and closes only its surface',+ (tester) async {+ final previous = web.window.location.href;+ web.window.history.replaceState(+ null,+ '',+ '/?viewer=1&machine=render&agent=chair',+ );+ addTearDown(() => web.window.history.replaceState(null, '', previous));+ final app = _App()..status = AppStatus.unauthenticated;+ const machine = Machine(+ machineId: 'render',+ name: 'Render server',+ authMode: MachineAuthMode.remote,+ );+ app.machines = [machine];+ app.machineStates['render'] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [+ const Agent(+ id: 'chair',+ name: 'Chair',+ viewerName: '3D Viewer',+ viewerUrl: 'http://127.0.0.1:19679/',+ ),+ ];+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: HarnessApp(+ authenticatedScreen: (_) =>+ const Text('Workspace must stay closed'),+ ),+ ),+ );+ await tester.pump();+ expect(find.byType(LoginScreen), findsOneWidget);+ expect(find.byType(ViewerPage), findsNothing);+ expect(app.requests, isEmpty);+ app.status = AppStatus.authenticated;+ app.notifyListeners();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 50));+ expect(find.byType(ViewerPage), findsOneWidget);+ expect(find.text('Workspace must stay closed'), findsNothing);+ expect(app.requests, isNotEmpty);+ expect(+ app.requests.every(+ (r) => r['machine'] == 'render' && r['agent'] == 'chair',+ ),+ isTrue,+ );+ final surface = tester.widget<RemoteViewerSurface>(+ find.byType(RemoteViewerSurface),+ );+ expect(surface.session.image, isNotNull);+ await tester.pump(const Duration(milliseconds: 400));+ await tester.pump();+ final image = find.descendant(+ of: find.byType(RemoteViewerSurface),+ matching: find.byType(Image),+ );+ expect(+ tester.getSize(image),+ tester.getSize(find.byType(RemoteViewerSurface)),+ );+ expect(tester.getSize(image).width, greaterThan(100));+ await tester.tap(find.byType(RemoteViewerSurface));+ await tester.pump(const Duration(milliseconds: 50));+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);+ await tester.pump(const Duration(milliseconds: 50));+ expect(+ app.requests+ .expand((r) => (r['events'] as List?) ?? [])+ .any((e) => e['event'] == 'mousePressed'),+ isTrue,+ );+ expect(+ app.requests+ .expand((r) => (r['events'] as List?) ?? [])+ .any((e) => e['type'] == 'key' && e['key'] == 'ArrowLeft'),+ isTrue,+ );+ app.fail = true;+ await tester.pump(const Duration(milliseconds: 500));+ await tester.pump();+ expect(find.text('Fixture disconnected'), findsOneWidget);+ app.fail = false;+ await tester.tap(find.textContaining('Retry'));+ await tester.pump(const Duration(milliseconds: 50));+ expect(app.requests.any((r) => r['reload'] == true), isTrue);+ expect(app.allPanes, isEmpty);+ await tester.pumpWidget(const SizedBox.shrink());+ await tester.pump();+ expect(app.requests.last['op'], 'close');+ expect(app.machineStates['render']!.agents.single.id, 'chair');+ app.dispose();+ expect(tester.takeException(), isNull);+ },+ );+}diff --git a/desktop/tool/machines_preview.dart b/desktop/tool/machines_preview.dartindex 7d15e28ca..2bdf0187d 100644--- a/desktop/tool/machines_preview.dart+++ b/desktop/tool/machines_preview.dart@@ -175,7 +175,7 @@ class _App extends AppNotifier {Future<void> retryMachines() async => notifyListeners();@override- Future<void> login() async {+ Future<void> login({bool? qr}) async {await Future<void>.delayed(const Duration(seconds: 1));signedIn = true;notifyListeners();diff --git a/docs/research/2026-09-28-hn-browser-viewer.md b/docs/research/2026-09-28-hn-browser-viewer.mdnew file mode 100644index 000000000..45aea5ddb--- /dev/null+++ b/docs/research/2026-09-28-hn-browser-viewer.md@@ -0,0 +1,123 @@+# hn browser viewer handoff++`hn view` opens the focused harness's existing viewer in the user's default browser.+`hn view -t <harness>` also works from a shell without starting or attaching a terminal.+The command palette exposes `open-viewer`; tmux's keys are unchanged. The harness preview+and a focused harness's ready notification tell the user when a viewer is available.++On a local desktop, a local harness opens its managed viewer URL directly. SSH, another+linked machine, `-w`, and copying with `-c` use the browser app's authenticated destination:+`/?viewer=1&machine=<encoded-id>&agent=<encoded-id>`. The existing website root rewrite+serves this entry point. No new server route, public listener, or share is created. URLs+contain identities, never account tokens or link credentials. The browser still signs in+as the owner and establishes its own machine link.++The invoking CLI process chooses whether to launch a browser. A request forwarded to an+existing hn client only obtains the URL; the client's older SSH/display environment cannot+make the invoking shell launch a browser on the wrong host. `-p` prints only, `-c` copies+through the terminal clipboard when supported, and an unavailable/failed browser opener+falls back to printing the link. URL schemes, credentials and control characters are checked+before starting an opener, which receives a single argv value without a shell.++The browser companion reuses the existing interactive viewer. It never joins the shared+desk, restores or saves its terminal layout, or attaches a terminal stream. Its destination+survives OAuth's callback. It shows linking, offline, missing harness, waiting viewer and+retry states. Closing it only releases its viewer surface; the agent remains running.+A Chrome interaction test also exposed the viewer image's missing explicit dimensions:+the image now fills the same viewport used to normalize pointer coordinates, including+while decoding and when the remote renderer caps its resolution.++## Boundaries++The existing remote interactive-viewer transport renders on the harness machine using+Chrome or Chromium and relays encrypted images and input. This change reuses that transport;+it does not introduce browser-side WebGL rendering or install a renderer. Local direct+viewers use the user's browser without that additional renderer. Existing browser viewer+limitations, including server-side rendering requirements, remain.++Release the browser app before native hn so new links are understood before hn emits them.+This work does not publish a release, reinstall the user's hn, change the production daemon,+or change creature behavior.++## Validation++All hn tests use a disposable HOME, a frozen binary, an explicit socket prefix, matching+`PORT`/`--port`, unset tmux/socket variables, and guarded test ports. Test processes,+harnesses and named tmux servers are cleaned up after success or failure.++- 124 Rust release unit tests and the existing terminal end-to-end suite pass.+- `tui/tests/viewer.py` exercises standalone, IPC and real TUI command-prompt paths: local+ opening, every SSH environment variable, peers, print/copy, exact opener arguments,+ missing/failed/hung openers, ambiguous names, waiting/error/unsafe viewers and damaged IPC+ replies. Linux also checks a headless shell and Wayland. Both Linux CI architecture jobs+ run this suite.+- 157 Flutter regressions cover routing, OAuth, QR sign-in integration, account transitions,+ machine linking, desk isolation and existing workspace behavior. Another 23 headless Chrome+ checks exercise browser routing and input.+- `tui/tests/viewer-live.mjs` passes on a physical Apple Silicon Mac with the actual hn,+ daemon, backend, MongoDB replica set, Redis, Blender DSH package, model viewer and Chrome.+ It renders a glTF fixture, completes browser OAuth and encrypted password linking, sends+ mouse/Unicode/special-key input, checks pointer mapping above the renderer resolution cap,+ reloads, stops and restarts the backend, and checks malformed UTF-8 links.+ Closing the browser leaves the harnesses running. No browser input reaches their terminals,+ and the browser never reads or overwrites the shared desk.+- The live test substitutes only the OAuth provider and model CLI with deterministic local+ fixtures. This is a real local stack test, not a production-account or two-computer test.+ Its browser blocks HTTP requests outside loopback. The installed hn and production daemons+ are never used.++Coverage is **100% of executable lines** in the three new modules: `tui/src/viewer.rs`+(120/120 production lines, excluding its unit tests), `viewer_location.dart` (29/29) and+`viewer_page.dart` (76/76). Rust coverage combines unit tests with instrumented public CLI+and TUI runs; Flutter coverage comes from routing and page tests. The existing renderer+and input transport also reach 195/195 lines in their 34 tests, with 95.37% branch coverage.+These figures do not claim repository-wide coverage or prove every possible edge case is+covered. Coverage artifacts and screenshots stay outside the repository.++### Failures caught before merge++- Invalid UTF-8 in viewer queries threw before validation. The route now recognizes its flag+ without decoding broken values and shows an error without restoring the workspace.+- A configured browser base with a non-root path produced a link the app could not route.+ hn now rejects it with a useful error.+- RPC failures hid renderer guidance behind a generic disconnect message. The browser now+ displays the daemon's error detail, including renderer and viewer-limit guidance.+- On this Mac, the private Chrome renderer's first navigation timed out even on a plain local+ page. The same process with `--use-mock-keychain` navigated in 23–93 ms and rendered the+ Blender model. Its temporary, credential-free profile now bypasses OS credential stores+ (`--use-mock-keychain`, `--password-store=basic`), avoiding an invisible unlock prompt.+ The user's regular browser profile is untouched. See+ [Chromium's Mac instructions](https://github.com/chromium/chromium/blob/main/docs/mac_build_instructions.md).++### Reproduce the physical-machine check++Install repository CLI/backend dependencies and `store/viewers/model-viewer` dependencies,+then build hn. The opt-in runner requires Chrome/Chromium, tmux, MongoDB and Redis executables,+plus a separate test-tools directory containing `[email protected]`,+`[email protected]` and `[email protected]`. It installs nothing and+changes no real Harness installation. Its fixed ports are 19680–19686.++Build the browser entrypoint from `desktop/`:++```sh+flutter build web --release --no-pub --no-wasm-dry-run --no-web-resources-cdn \+ --dart-define=HARNESS_TEST=true --dart-define=HARNESS_API_URL=http://127.0.0.1:19680 \+ --output=/tmp/hn-viewer-web+```++Then run from the repository root, substituting paths to your test dependencies:++```sh+HN_VIEWER_LIVE_TEST=1 \+HN_VIEWER_SERVICES_DIR=/path/to/test-tools \+HN_VIEWER_TOOLS_DIR=/path/to/test-tools \+HN_VIEWER_WEB_DIR=/tmp/hn-viewer-web \+HN_VIEWER_BINARY="$PWD/tui/target/release/harness-tui" \+HN_VIEWER_MONGOD=/path/to/mongod \+HN_VIEWER_REDIS=/path/to/redis-server \+node tui/tests/viewer-live.mjs+```++Set `HN_VIEWER_CHROME` and `HN_VIEWER_TMUX` if executables are elsewhere. The runner prints+its private temporary directory containing results, screenshots and logs. It has only been+run on macOS; Linux native behavior is covered separately by CI.diff --git a/docs/research/2026-09-28-hn-upgrade-launcher.md b/docs/research/2026-09-28-hn-upgrade-launcher.mdindex fd4e689cf..d67a8bdff 100644--- a/docs/research/2026-09-28-hn-upgrade-launcher.md+++ b/docs/research/2026-09-28-hn-upgrade-launcher.md@@ -50,3 +50,44 @@ already-current update, exercises its original download/checksum/canary/stagingpath, and runs the repaired launcher against the frozen native binary. Everynative invocation has a disposable home, explicit socket prefix and port; noreal daemon, harness or installed hn is used.+++## Published CLI 0.3.22++[PR #417](https://github.com/autonomous-ai/openharness/pull/417) added the migration.+[PR #418](https://github.com/autonomous-ai/openharness/pull/418) corrected the+native cancellation test's baseline: a pane-dead event precedes asynchronous PTY+reaping, so the test now waits for only its two live anchor children before+checking that cancellation leaves no extra child.++[CLI 0.3.22](https://github.com/autonomous-ai/openharness/releases/tag/v0.3.22_cli)+was published from `27064e2f2eba6df23f91b1fc733f6862be2a8f03`.+[The release workflow](https://github.com/autonomous-ai/openharness/actions/runs/36398977008)+passed publication, downloaded checksum/version checks, installer verification,+and GitHub release creation.++[Final CI](https://github.com/autonomous-ai/openharness/actions/runs/36398238429)+passed all four jobs at `7e947723a5b06fc94848d88df85fa36922fe5a3c`: the full CLI+suite, packaged upgrade regression, updater coverage, static Linux x86-64/ARM64+builds and native integrations, and backend compatibility. The release commit's+CLI, hn, store and workflow files match that tested revision; four unrelated+device firmware files landed during the merge. Local macOS checks passed+7,084 CLI tests, with 37 opt-in/platform skips, typechecking, and the native+terminal suite against the published hn 0.1.1 binary.++The public downloads were verified independently after publication:++| Artifact | SHA-256 |+| --- | --- |+| CLI 0.3.22 | `bd728d59965c1d44302154886aedb33d7cdf67bf32c432d7013d4c5f62c451c1` |+| notify.mjs | `a8ac3ccfcf1499507843e22c2533a6fe14dea6f3944d207f27c8f2d8b139a4fa` |+| CDN installer | `ae952b99a2a7d9ecf59642445183ad980e4a4976183f2882c2f7f7c8fad85a9b` |++The original published 0.3.21 updater installed the downloaded 0.3.22 bundle in a+disposable home. An already-current update then created hn, preserved arguments+and the update pin, tolerated concurrent starts, and preserved an existing hn+symlink. A separate old-install fixture had neither hn nor a native client;+`harness version` repaired its launcher, and the first `hn --version` downloaded+and ran checksum-verified hn 0.1.1. The actual invocation supplied the guarded+port and private socket flags described above. All owned runtime processes were+cleaned up. The native TUI remains hn 0.1.1, with creatures outside its interface.diff --git a/tui/README.md b/tui/README.mdindex 09ae08791..2f8dd303a 100644--- a/tui/README.md+++ b/tui/README.md@@ -199,6 +199,34 @@ it reversed, so you know before you start more agents),(another window has the pane to type in, and who), and `#{waiting}` (the harnesses waiting onyou).+## Graphical viewers++For a Blender, CAD, video or other domain harness, run `view` from `C-b :` or choose+`open-viewer` in the command list. The harness preview shows when its viewer is ready.++```sh+hn view # current hn pane+hn view -t 'My Blender scene' # by harness name or id, without opening a terminal pane+hn view -p -t 'My Blender scene' # print its URL, without launching a browser+hn view -c # copy its browser-app link through the terminal clipboard+hn view -w # open in the authenticated browser app even on this machine+```++On a local desktop, the current machine's viewer opens directly in your default browser.+Over SSH, `hn` prints a link you open on your own computer; it never launches a browser on the+SSH host. A harness on another linked machine uses the same browser-app link. Sign in as its+owner and link the machine if this browser has not done so before. The URL contains machine+and harness identifiers, not credentials, and does not grant access or create a public share.++The browser companion opens only that viewer. It does not restore your desk, attach a terminal,+or take the keyboard from `hn`. Closing either view leaves the harness running. Browser-based+remote viewers use Harness's existing encrypted interactive-viewer transport, which requires+Chrome or Chromium on the harness machine for rendering. Local direct viewers do not need that+renderer. A missing renderer is reported in the viewer with a retry action.++`-p` also works for scripts and terminals without clipboard support. Browser launch failure+prints the link instead. No tmux key bindings are changed.+## From a shellAs `tmux` is: any tmux command, run in the client you have open, its output printed here.diff --git a/tui/src/app.rs b/tui/src/app.rsindex 22f2ea64f..f8f77e77a 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -403,6 +403,7 @@ struct LinkState {pub struct App {pub port: u16,+ pub viewer_web_url: String,pub sink: UnboundedSender<Event>,pub fleet: Fleet,links: HashMap<String, LinkState>,@@ -778,6 +779,7 @@ impl App {};App {port,+ viewer_web_url: String::new(),sink,fleet: Fleet::default(),links: HashMap::new(),@@ -1087,6 +1089,7 @@ impl App {self.spawn(async move { http_json(port, "GET", "/api/status", None).await }, |app, status| match status {Ok(status) => {app.daemon_down = false;+ app.viewer_web_url = status.get("webUrl").and_then(Value::as_str).unwrap_or("").to_string();let id = status.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();if status.get("signedIn").and_then(Value::as_bool) == Some(false) {app.say("This computer is not signed in — run `harness login`", theme::DANGER);@@ -1297,8 +1300,13 @@ impl App {if ty == "agent_renamed" && row.get("engine").is_none() {if let (Some(agent), Some(name)) = (self.fleet.agents.get_mut(&key), row.get("name").and_then(Value::as_str)) { agent.name = name.to_string() }} else {- let agent = fleet::agent_from(machine_id, &row, self.fleet.agents.get(&key));+ let previous = self.fleet.agents.get(&key);+ let agent = fleet::agent_from(machine_id, &row, previous);+ let viewer_ready = !agent.viewer_url.is_empty() && previous.is_none_or(|a| a.viewer_url.is_empty())+ && crate::input::focused_key(self).as_ref() == Some(&key);+ let viewer_name = if agent.viewer_name.is_empty() { "Viewer".to_string() } else { agent.viewer_name.clone() };self.fleet.agents.insert(key, agent);+ if viewer_ready { self.say(format!("{viewer_name} ready — C-b : view opens it"), theme::ONLINE) }}self.sync_titles();}@@ -1984,7 +1992,7 @@ impl App {let opens_shell = words.iter().any(|w| matches!(crate::cmd::find(w).map(|e| e.name), Ok("new-session" | "new-window" | "split-window" | "respawn-pane" | "respawn-window" | "display-popup")));// list-harnesses from a client just started (hn with no terminal, for a script): once// every machine's harnesses are known, so it says what each one is doing.- let asks_fleet = matches!(words.first().map(String::as_str), Some("list-harnesses" | "lsh" | "answer-harness" | "answer" | "open-harness" | "openh" | "send-message" | "restart-harness" | "restarth" | "pause-harness" | "resume-harness" | "clone-harness" | "rename-harness"));+ let asks_fleet = matches!(words.first().map(String::as_str), Some("open-viewer" | "view" | "list-harnesses" | "lsh" | "answer-harness" | "answer" | "open-harness" | "openh" | "send-message" | "restart-harness" | "restarth" | "pause-harness" | "resume-harness" | "clone-harness" | "rename-harness"));self.last_cli = Instant::now();if !self.cli_held.is_empty() || (opens_shell && !self.cli_ready()) || (asks_fleet && !self.fleet_ready()) { self.cli_held.push_back(job); return }job(self)diff --git a/tui/src/cli.rs b/tui/src/cli.rsindex e98e57d2f..88cbe851f 100644--- a/tui/src/cli.rs+++ b/tui/src/cli.rs@@ -85,6 +85,7 @@ pub async fn run(args: &[String], explicit_port: Option<u16>, socket: Option<&stlet name = name.map(str::to_string);let cmd = args.first()?.as_str();match cmd {+ "view" | "open-viewer" => Some(crate::viewer::cli(port, &args[1..], socket.as_deref(), name.as_deref()).await),// Every harness on every machine (hn's; `ls` is tmux's list-sessions).// The running client knows each one's state (what it asks, does, did); with none, the// daemons' rosters.@@ -400,7 +401,7 @@ async fn offline(port: u16, args: &[String], name: Option<&str>) -> i32 {}}-async fn machines(port: u16) -> Result<(String, Vec<(String, String, bool)>), String> {+pub(crate) async fn machines(port: u16) -> Result<(String, Vec<(String, String, bool)>), String> {let status = http_json(port, "GET", "/api/status", None).await.map_err(|e| format!("the daemon is not running ({e}) — harness start"))?;let local = status.get("machineId").and_then(Value::as_str).unwrap_or("").to_string();let reply = http_json(port, "GET", "/api/machines", None).await.unwrap_or(json!({}));@@ -417,7 +418,7 @@ async fn machines(port: u16) -> Result<(String, Vec<(String, String, bool)>), StOk((local, out))}-async fn roster(port: u16, machine: &str) -> Vec<crate::fleet::Agent> {+pub(crate) async fn roster(port: u16, machine: &str) -> Vec<crate::fleet::Agent> {let (tx, _rx) = mpsc::unbounded_channel();let link = Link::spawn(port, machine, 0, tx);let reply = link.rpc("agents_list", json!({}), Duration::from_secs(8)).await.unwrap_or(json!({}));diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex ff669ece5..182d53512 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -41,6 +41,7 @@ pub const COMMANDS: &[(&str, &str, &str)] = &[("list-keys", "lsk", "Key bindings (-T a table, -1N one key)"),("keys", "keys", "Every key binding, searched as you type (C-b ? lists them as tmux does)"),("answer-harness", "answer", "Answer a harness's question: answer -t name 2 (its second choice), 1,3, or your own words"),+ ("open-viewer", "view", "Open viewer in your browser (-t harness, -p print link, -c copy, -w browser app)"),("open-harness", "openh", "A harness into a window of its own (-h/-v beside/below -t's pane, -d not gone to): open-harness -s name"),("list-windows", "lsw", "The windows (-F a format)"),("list-panes", "lsp", "The panes (-a/-s every window, -t one, -F a format)"),@@ -3460,6 +3461,15 @@ fn run_words_in(app: &mut App, words: &[String]) {app.modal = Some(Modal::Confirm { prompt, command, key, enter_yes: flag(words, "-y") });app.wait_cli = app.capture.is_some() && !flag(words, "-b");}+ "open-viewer" => {+ let options = match crate::viewer::Options::parse(&words[1..]) { Ok(o) => o, Err(e) => return app.error(e) };+ let key = match harness_target(app, words) {+ Ok(Some(k)) => k,+ Ok(None) => match input::focused_key(app) { Some(k) => k, None => return app.error("no harness here — use view -t <harness>") },+ Err(e) => return app.error(e),+ };+ crate::viewer::show(app, key, options);+ }"new-harness" => { if words.len() < 2 { input::run(app, "new") } else { input::new_harness_words(app, &words[1..]) } }"new-terminal" => input::run(app, "terminal"),// A harness's verbs, on -t's harness (the hook's in a harness-* hook), else the focuseddiff --git a/tui/src/fleet.rs b/tui/src/fleet.rsindex 6d5b0d630..40da846b5 100644--- a/tui/src/fleet.rs+++ b/tui/src/fleet.rs@@ -68,6 +68,9 @@ pub struct Agent {pub question: Option<Question>,pub unread: bool,pub dsh: String,+ pub viewer_url: String,+ pub viewer_name: String,+ pub viewer_error: String,/// The runtime profile it runs (`runtime-v1:…:claude:opus@high`) — what ⌥I switches.pub model: String,pub project_root: String,@@ -285,6 +288,9 @@ pub fn agent_from(machine_id: &str, row: &Value, previous: Option<&Agent>) -> Agquestion: previous.and_then(|p| p.question.clone()),unread: previous.map(|p| p.unread).unwrap_or(false),dsh,+ viewer_url: s(row, "viewerUrl"),+ viewer_name: s(row, "viewerName"),+ viewer_error: s(row, "viewerError"),model: s(row, "selectedModel"),project_root: { let r = s(&project, "root"); if r.is_empty() { s(&project, "cwd") } else { r } },doing: previous.and_then(|p| p.doing.clone()),diff --git a/tui/src/main.rs b/tui/src/main.rsindex 6793fca47..f11745162 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -42,6 +42,7 @@ mod term_out;mod term_input;mod tmuxconf;mod ui;+mod viewer;use std::io::{self, BufWriter, Write};use std::time::{Duration, Instant};diff --git a/tui/src/preview.rs b/tui/src/preview.rsindex 65831ee96..21bacc572 100644--- a/tui/src/preview.rs+++ b/tui/src/preview.rs@@ -46,6 +46,11 @@ fn harness(app: &App, machine_id: &str, agent_id: &str) -> Vec<Line<'static>> {let mut out = vec![Line::from(vec![Span::styled(word.to_string(), Style::default().fg(color).add_modifier(Modifier::BOLD)), dim(format!(" {}", ago(a.state_since(state))))]),];+ if !a.viewer_url.is_empty() || !a.viewer_name.is_empty() || !a.viewer_error.is_empty() {+ let label = if a.viewer_name.is_empty() { "Viewer" } else { &a.viewer_name };+ let state = if !a.viewer_error.is_empty() { a.viewer_error.as_str() } else if a.viewer_url.is_empty() { "starting" } else { "ready" };+ out.push(dim(format!("{label}: {state} · :view opens · :view -c copies link")).into());+ }// Its latest turns, when its session's index has them: as its terminal shows them, the newest// at the bottom (where the preview starts), what it asks you below them.if let Some(tail) = app.tails.get(&a.session_id) {diff --git a/tui/src/viewer.rs b/tui/src/viewer.rsnew file mode 100644index 000000000..b5c87c048--- /dev/null+++ b/tui/src/viewer.rs@@ -0,0 +1,196 @@+//! A harness's graphics live in the user's browser. SSH returns an authenticated web-app+//! destination; only the invoking terminal process may launch a local browser.++use std::io::IsTerminal;+use std::process::Stdio;+use std::time::Duration;+use tokio_tungstenite::tungstenite::http::Uri;++use crate::{app::App, fleet::Agent};++pub const USAGE: &str = "usage: hn view [-pcw] [-t harness]";++#[derive(Default, Debug)]+pub struct Options { pub print: bool, pub copy: bool, pub web: bool, pub target: Option<String> }+impl Options {+ pub fn parse(args: &[String]) -> Result<Self, String> {+ let mut out = Self::default();+ let mut args = args.iter();+ while let Some(arg) = args.next() {+ match arg.as_str() {+ "-t" => out.target = Some(args.next().filter(|s| !s.is_empty()).ok_or(USAGE)?.clone()),+ "-p" | "--print" => out.print = true,+ "-c" | "--copy" => out.copy = true,+ "-w" | "--web" => out.web = true,+ _ if arg.starts_with('-') && arg.len() > 1 && arg[1..].chars().all(|c| "pcw".contains(c)) => {+ out.print |= arg.contains('p'); out.copy |= arg.contains('c'); out.web |= arg.contains('w');+ }+ _ => return Err(USAGE.into()),+ }+ }+ Ok(out)+ }+}++fn valid_url(value: &str) -> bool {+ if value.chars().any(|c| c.is_control() || c.is_whitespace()) || value.contains('\\') { return false }+ let Ok(uri) = value.split('#').next().unwrap_or("").parse::<Uri>() else { return false };+ matches!(uri.scheme_str(), Some("http" | "https")) && uri.host().is_some_and(|h| !h.is_empty())+ && !uri.authority().is_some_and(|a| a.as_str().contains('@'))+}++fn encode(value: &str) -> String {+ let mut out = String::new();+ for b in value.bytes() {+ if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { out.push(b as char) }+ else { use std::fmt::Write; let _ = write!(out, "%{b:02X}"); }+ }+ out+}++pub fn web_link(base: &str, machine: &str, agent: &str) -> Result<String, String> {+ if !valid_url(base) || base.contains(['?', '#']) || machine.is_empty() || agent.is_empty() {+ return Err("the daemon has no browser address — update Harness on this machine".into())+ }+ let uri: Uri = base.parse().map_err(|_| "invalid browser address")?;+ if uri.path() != "/" && !uri.path().is_empty() {+ return Err("the daemon browser address must point to the website root".into())+ }+ if uri.scheme_str() != Some("https") && !matches!(uri.host(), Some("localhost" | "127.0.0.1" | "[::1]" | "::1")) {+ return Err("the browser address must use HTTPS (HTTP is allowed for localhost development)".into())+ }+ Ok(format!("{}/?viewer=1&machine={}&agent={}", base.trim_end_matches('/'), encode(machine), encode(agent)))+}++pub fn destination(agent: &Agent, local: &str, web: &str, remote: bool) -> Result<String, String> {+ if agent.viewer_url.is_empty() && agent.viewer_name.is_empty() {+ return Err(if agent.viewer_error.is_empty() { "this harness has no viewer".into() } else { agent.viewer_error.clone() })+ }+ // A peer's loopback URL is owned by a particular daemon connection and can disappear when+ // that connection closes. Use the browser's own authenticated connection for every peer.+ if !remote && agent.machine_id == local && !agent.viewer_url.is_empty() {+ if !valid_url(&agent.viewer_url) { return Err("the harness returned an invalid viewer address".into()) }+ return Ok(agent.viewer_url.clone())+ }+ web_link(web, &agent.machine_id, &agent.id)+}++pub fn ssh() -> bool {+ ["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"].iter().any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty()))+}++async fn open(url: &str) -> bool {+ if !valid_url(url) || ssh() { return false }+ if cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].iter().all(|k| std::env::var_os(k).is_none_or(|v| v.is_empty())) { return false }+ let mut command = tokio::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" });+ let Ok(mut child) = command.arg(url).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).spawn() else { return false };+ matches!(tokio::time::timeout(Duration::from_secs(5), child.wait()).await, Ok(Ok(status)) if status.success())+}++pub fn show(app: &mut App, key: (String, String), options: Options) {+ let Some(agent) = app.fleet.agent(&key.0, &key.1) else { return app.error("can't find harness") };+ let url = match destination(agent, &app.fleet.local_id, &app.viewer_web_url, options.web || options.copy || (app.capture.is_none() && ssh())) {+ Ok(url) => url, Err(e) => return app.error(e),+ };+ if app.capture.is_some() || options.print { app.print("Viewer", vec![url]); return }+ if options.copy {+ crate::clipboard::store(&url);+ app.say("Viewer link sent to the terminal clipboard", crate::theme::ONLINE);+ return+ }+ if ssh() { show_link(app, &url); return }+ app.spawn(async move { let opened = open(&url).await; (url, opened) }, |app, (url, opened)| {+ if opened { app.say("Opened viewer in your browser", crate::theme::ONLINE) } else { show_link(app, &url) }+ });+}++fn show_link(app: &mut App, url: &str) {+ app.print("Viewer", vec!["Open this link in your browser:".into(), url.into(), String::new(), "Use :view -c to copy the browser link. Sign in and link this machine if asked.".into()]);+}++pub async fn cli(port: u16, args: &[String], socket: Option<&str>, name: Option<&str>) -> i32 {+ if args == ["--help"] || args == ["-h"] { println!("{USAGE}\nOpen the current harness's viewer. Over SSH, prints a browser link.\n-p Print only -c Copy browser link -w Use authenticated browser app"); return 0 }+ let options = match Options::parse(args) { Ok(o) => o, Err(e) => { eprintln!("{e}"); return 2 } };+ let remote = options.web || options.copy || ssh();+ let result = if crate::ipc::alive(socket, name) {+ let Some(path) = crate::ipc::chosen(socket, name) else { eprintln!("hn: no client running"); return 1 };+ let mut words = vec!["open-viewer".into(), "-p".into()];+ if remote { words.push("-w".into()) }+ if let Some(t) = &options.target { words.extend(["-t".into(), t.clone()]) }+ match tokio::task::spawn_blocking(move || crate::ipc::ask(&path, &words)).await {+ Ok(Some((out, err, 0))) if err.is_empty() && out.len() == 1 => Ok(out[0].clone()),+ Ok(Some((_, err, _))) => Err(err.join("\n")),+ _ => Err("could not reach the hn client".into()),+ }+ } else { standalone(port, &options, remote).await };+ let url = match result { Ok(url) if valid_url(&url) => url, Ok(_) => { eprintln!("hn: invalid viewer address"); return 1 }, Err(e) => { eprintln!("hn: {e}"); return 1 } };+ if options.copy && std::io::stdout().is_terminal() { crate::clipboard::store(&url) }+ if !options.print && !options.copy && !ssh() && open(&url).await { return 0 }+ // Plain output remains usable with any terminal and in scripts; terminal apps can recognize+ // the URL without an OSC extension. Never start a browser process on an SSH host.+ println!("{url}");+ if !options.print && !options.copy { eprintln!("Open this link in your browser. Sign in and link the machine if asked.") }+ 0+}++async fn standalone(port: u16, options: &Options, remote: bool) -> Result<String, String> {+ let target = options.target.as_deref().ok_or("no current hn pane — use hn view -t <harness>")?;+ let status = crate::daemon::http_json(port, "GET", "/api/status", None).await.map_err(|_| "the daemon is not running — harness start")?;+ let (local, machines) = crate::cli::machines(port).await?;+ let mut all = Vec::new();+ for (id, name, online) in machines {+ if !online { continue }+ let wanted = match target.split_once(':') {+ Some((m, a)) if m == id || m == name => a,+ Some(_) => continue,+ None => target,+ };+ for agent in crate::cli::roster(port, &id).await {+ let exact = agent.id == wanted || agent.name == wanted;+ if exact || agent.name.starts_with(wanted) { all.push((exact, agent)) }+ }+ }+ if all.iter().any(|(exact, _)| *exact) { all.retain(|(exact, _)| *exact) }+ match all.as_slice() {+ [(_, agent)] => destination(agent, &local, status.get("webUrl").and_then(serde_json::Value::as_str).unwrap_or(""), remote),+ [] => Err(format!("can't find harness: {target}")),+ _ => Err(format!("more than one harness: {target} — use -t machine:agent-id")),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ #[test]+ fn addresses_are_data_and_ssh_never_uses_remote_loopback() {+ let a = crate::fleet::agent_from("remote", &json!({"id":"a /?&é", "viewerUrl":"http://127.0.0.1:19777/?file=model.glb", "viewerName":"3D Viewer"}), None);+ assert_eq!(destination(&a, "remote", "https://harness.example", false).unwrap(), a.viewer_url);+ let expected = "https://harness.example/?viewer=1&machine=remote&agent=a%20%2F%3F%26%C3%A9";+ assert_eq!(destination(&a, "remote", "https://harness.example/", true).unwrap(), expected);+ assert_eq!(destination(&a, "local", "https://harness.example", false).unwrap(), expected);+ for url in ["javascript:alert(1)", "file:///tmp/a", "https://a\nInjected", "https://user:pass@host/", "https://a/\\x", "https://a/a b"] { assert!(!valid_url(url), "{url}") }+ assert!(web_link("http://example.com", "m", "a").is_err());+ assert!(web_link("http://127.0.0.1:19778", "m", "a").is_ok());+ assert!(web_link("https://harness.example?x=1", "m", "a").is_err());+ assert!(web_link("https://harness.example/workspace", "m", "a").is_err());+ for base in ["http://localhost:19682", "http://[::1]:19682", "https://harness.example/"] {+ assert!(web_link(base, "m", "a").is_ok(), "{base}");+ }+ for base in ["", "https://", "https://harness.example/#token", "https://user@host", "file:///tmp/test", "--help"] {+ assert!(web_link(base, "m", "a").is_err(), "{base}");+ }+ }+ #[test]+ fn no_viewer_is_an_error_and_waiting_viewer_gets_its_own_page() {+ let mut a = crate::fleet::agent_from("m", &json!({"id":"a"}), None);+ assert!(destination(&a, "m", "https://harness.example", false).is_err());+ a.viewer_name = "3D Viewer".into();+ assert_eq!(destination(&a, "m", "https://harness.example", false).unwrap(), "https://harness.example/?viewer=1&machine=m&agent=a");+ assert!(Options::parse(&["--unknown".into()]).is_err());+ assert!(Options::parse(&["-t".into()]).is_err());+ let o = Options::parse(&["-pcw".into(), "-t".into(), "name with spaces".into()]).unwrap();+ assert!(o.print && o.copy && o.web);+ assert_eq!(o.target.as_deref(), Some("name with spaces"));+ }+}diff --git a/tui/tests/mock-daemon.mjs b/tui/tests/mock-daemon.mjsindex 09401c639..5a54389fe 100644--- a/tui/tests/mock-daemon.mjs+++ b/tui/tests/mock-daemon.mjs@@ -44,6 +44,24 @@ const agents = DEMO ? {[LOCAL]: [agent(randomUUID(), 'Mock Claude', 'claude'), agent(randomUUID(), 'Mock Codex', 'codex'), agent(randomUUID(), 'Mock paused', 'claude', 'stopped')],[REMOTE]: [agent(randomUUID(), 'Remote shell', 'terminal')],}+// Opt-in viewer fixtures, so the normal terminal roster and its tests keep their identities.+if (process.env.MOCK_VIEWER === '1') {+ agents[LOCAL].push({ ...agent('mock-blender', 'Mock Blender', 'claude'), dsh: 'autonomous/blender',+ viewerName: '3D Viewer', viewerUrl: `http://127.0.0.1:${port}/test-viewer?file=model.glb` })+ agents[REMOTE].push({ ...agent('remote-blender', 'Remote Blender', 'claude'), dsh: 'autonomous/blender',+ viewerName: '3D Viewer', viewerUrl: 'http://127.0.0.1:19679/?file=model.glb' })+}+if (process.env.MOCK_VIEWER_EDGES === '1') {+ agents[LOCAL].push(+ { ...agent('waiting-viewer', 'Waiting Viewer', 'claude'), viewerName: '3D Viewer' },+ { ...agent('failed-viewer', 'Failed Viewer', 'claude'), viewerError: 'Renderer could not start' },+ { ...agent('unsafe-viewer', 'Unsafe Viewer', 'claude'), viewerName: 'Viewer', viewerUrl: 'javascript:alert(1)' },+ { ...agent('quoted-viewer', 'Quoted " viewer; $(false)', 'claude'), viewerName: 'Viewer', viewerUrl: `http://127.0.0.1:${port}/test-viewer?x=a&y=b` },+ { ...agent('mock-blender-extended', 'Mock Blender Extended', 'claude'), viewerName: 'Viewer' },+ { ...agent('duplicate-local', 'Duplicate Viewer', 'claude'), viewerName: 'Viewer' },+ )+ agents[REMOTE].push({ ...agent('duplicate-remote', 'Duplicate Viewer', 'claude'), viewerName: 'Viewer' })+}// Claude Code and Codex conversations on this machine that Harness did not start (session_search's// `external` hits): two closed, one still open in a terminal (not to be opened twice).const HOUR = 3_600_000@@ -138,7 +156,7 @@ let demoAsked = falseconst json = (res, body) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ success: true, data: body })) }const server = http.createServer((req, res) => {- if (req.url === '/api/status') return json(res, { machineId: LOCAL, signedIn: true, version: 'mock' })+ if (req.url === '/api/status') return json(res, { machineId: LOCAL, signedIn: true, version: 'mock', webUrl: process.env.MOCK_WEB_URL || 'https://harness.example' })if (req.url === '/api/machines') return json(res, { machines: [{ machineId: LOCAL, name: DEMO ? 'studio' : 'mock-local', status: 'running' },{ machineId: REMOTE, name: DEMO ? 'gpu-box' : 'mock-remote', status: 'running' },diff --git a/tui/tests/viewer-live.mjs b/tui/tests/viewer-live.mjsnew file mode 100644index 000000000..d46410c63--- /dev/null+++ b/tui/tests/viewer-live.mjs@@ -0,0 +1,315 @@+// Opt-in local integration: real hn, daemon, backend, Mongo/Redis, DSH viewers and Chrome.+// The OAuth provider and model process are deterministic fixtures; no production account is used.+import assert from 'node:assert/strict'+import { spawn, execFile } from 'node:child_process'+import { createServer } from 'node:http'+import { createServer as netServer } from 'node:net'+import { createWriteStream, existsSync, readFileSync } from 'node:fs'+import { mkdtemp, mkdir, writeFile, cp, readFile } from 'node:fs/promises'+import { join, resolve, extname, sep, dirname } from 'node:path'+import { createRequire } from 'node:module'+import { promisify } from 'node:util'+import { randomUUID, createHash } from 'node:crypto'+import { once } from 'node:events'+import { fileURLToPath } from 'node:url'++assert.equal(process.env.HN_VIEWER_LIVE_TEST, '1', 'Opt in with HN_VIEWER_LIVE_TEST=1')+for (const key of ['HN_VIEWER_SERVICES_DIR', 'HN_VIEWER_TOOLS_DIR', 'HN_VIEWER_WEB_DIR', 'HN_VIEWER_BINARY', 'HN_VIEWER_MONGOD', 'HN_VIEWER_REDIS']) {+ assert.ok(process.env[key] && existsSync(process.env[key]), `Set ${key} to an existing test dependency`)+}+const repo = resolve(process.env.HN_VIEWER_REPO || join(dirname(fileURLToPath(import.meta.url)), '../..'))+const cliRequire = createRequire(join(repo, 'cli/package.json'))+const { WebSocket } = cliRequire('ws')+const services = createRequire(join(process.env.HN_VIEWER_SERVICES_DIR, 'package.json'))+const { MongoMemoryReplSet } = services('mongodb-memory-server')+const { RedisMemoryServer } = services('redis-memory-server')+const { chromium } = createRequire(join(process.env.HN_VIEWER_TOOLS_DIR, 'package.json'))('playwright')+const exec = promisify(execFile)+const ports = { backend: 19680, proxy: 19681, web: 19682, sso: 19683, daemon: 19684, mongo: 19685, redis: 19686 }+for (const port of Object.values(ports)) {+ assert.ok(port >= 19680 && port <= 19699 && ![18473, 18907].includes(port))+ const probe = netServer().listen(port, '127.0.0.1')+ await once(probe, 'listening')+ await new Promise(resolve => probe.close(resolve))+}+const root = await mkdtemp('/tmp/hnvl-')+const prefix = `hn-viewer-live-${process.pid}`+const webDir = resolve(process.env.HN_VIEWER_WEB_DIR)+const chrome = process.env.HN_VIEWER_CHROME || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : '/usr/bin/chromium')+const tmux = process.env.HN_VIEWER_TMUX || (process.platform === 'darwin' ? '/opt/homebrew/bin/tmux' : '/usr/bin/tmux')+const base = `http://127.0.0.1:${ports.backend}`, webBase = `http://127.0.0.1:${ports.web}`, ssoBase = `http://127.0.0.1:${ports.sso}`+const cleanups = [], checks = []+if (process.platform === 'darwin') {+ const awake = spawn('/usr/bin/caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' })+ cleanups.push(() => awake.kill())+}+let complete = false, context, browser+console.log(`Isolated test directory: ${root}`)+const pass = s => { checks.push(s); console.log(`PASS ${s}`) }+async function until(label, check, ms = 60000) {+ const end = Date.now() + ms+ while (!await check()) {+ if (Date.now() >= end) throw new Error(`Timed out: ${label}`)+ await new Promise(resolve => setTimeout(resolve, 100))+ }+}+async function stop(child) {+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null) return+ const exited = once(child, 'exit')+ try { process.kill(-child.pid, 'SIGTERM') } catch { return }+ const timer = setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL') } catch {} }, 6000)+ await exited+ clearTimeout(timer)+}+function run(name, cwd, args, env) {+ const child = spawn(process.execPath, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })+ const log = createWriteStream(join(root, `${name}.log`))+ child.stdout.pipe(log); child.stderr.pipe(log)+ cleanups.push(() => stop(child))+ return child+}+async function listen(server, port) {+ server.listen(port, '127.0.0.1'); await once(server, 'listening')+ cleanups.push(() => { server.closeAllConnections?.(); server.close() })+}+const safeEnv = { PATH: process.env.PATH, TMPDIR: root, HOME: join(root, 'home'), LANG: 'en_US.UTF-8',+ XDG_CONFIG_HOME: join(root, 'config'), XDG_DATA_HOME: join(root, 'share'), XDG_CACHE_HOME: join(root, 'cache'),+ NODE_ENV: 'test', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }+const token = `hn-viewer-${randomUUID()}`, userId = randomUUID().replaceAll('-', '')+const password = `hn-test-${randomUUID()}`+const authHeaders = { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'x-autonomous-env': 'prod' }+const codes = new Map()+let hnEnv, hnBinary, owner, agentId, controlsId+async function hn(...args) {+ assert.equal(hnEnv.PORT, String(ports.daemon)); assert.equal(hnEnv.HN_SOCKET_NAME, prefix)+ return exec(hnBinary, ['-L', prefix, '--port', String(ports.daemon), ...args], { env: hnEnv, timeout: 30000 })+}+async function desktop(machineId) {+ const ws = new WebSocket(`ws://127.0.0.1:${ports.daemon}/api/local-ws`)+ cleanups.push(() => ws.terminate())+ const frames = []+ ws.on('message', (raw, binary) => { if (!binary) frames.push(JSON.parse(raw.toString())) })+ await once(ws, 'open')+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ await until('local machine connection', () => frames.some(f => f.type === 'connected'))+ return { ws, async rpc(type, payload = {}) {+ const requestId = randomUUID()+ ws.send(JSON.stringify({ type, payload: { ...payload, requestId } }))+ await until(type, () => frames.some(f => f.payload?.requestId === requestId))+ const result = frames.find(f => f.payload?.requestId === requestId).payload+ assert.ok(!result.error, `${type}: ${JSON.stringify(result)}`)+ return result+ } }+}+async function semantics(page) {+ await page.locator('flt-glass-pane').waitFor({ state: 'attached', timeout: 45000 })+ const enable = page.locator('flt-semantics-placeholder')+ await until('Flutter accessibility entrypoint', async () => await enable.count() || await page.locator('flt-semantics').count())+ if (await enable.count()) await enable.evaluate(el => el.click())+}+try {+ for (const dir of [safeEnv.HOME, safeEnv.XDG_CONFIG_HOME, safeEnv.XDG_DATA_HOME, safeEnv.XDG_CACHE_HOME, join(root, 'bin'), join(root, 'auth'), join(root, 'data'), join(root, 'dsh'), join(root, 'runtime')]) await mkdir(dir, { recursive: true })+ const mongo = await MongoMemoryReplSet.create({ binary: { systemBinary: process.env.HN_VIEWER_MONGOD },+ instanceOpts: [{ port: ports.mongo }], replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ cleanups.push(() => mongo.stop())+ const redis = new RedisMemoryServer({ binary: { systemBinary: process.env.HN_VIEWER_REDIS }, instance: { port: ports.redis } })+ assert.equal(await redis.getPort(), ports.redis)+ cleanups.push(() => redis.stop())+ await listen(createServer(async (req, res) => {+ const u = new URL(req.url, ssoBase)+ if (u.pathname === '/oauth2/authorize') {+ const redirect = new URL(u.searchParams.get('redirect_uri'))+ assert.equal(redirect.origin, webBase)+ const code = randomUUID(); codes.set(code, u.searchParams.get('code_challenge'))+ redirect.searchParams.set('state', u.searchParams.get('state')); redirect.searchParams.set('code', code)+ res.writeHead(302, { location: redirect.href }).end(); return+ }+ res.setHeader('content-type', 'application/json')+ if (u.pathname === '/oauth2/token') {+ let body = ''; for await (const chunk of req) body += chunk+ const form = new URLSearchParams(body), challenge = codes.get(form.get('code'))+ codes.delete(form.get('code'))+ if (challenge !== createHash('sha256').update(form.get('code_verifier') || '').digest('base64url')) { res.writeHead(400).end('{}'); return }+ res.end(JSON.stringify({ access_token: token, refresh_token: 'test-refresh', expires_in: 3600, token_type: 'Bearer' })); return+ }+ if (req.headers.authorization !== `Bearer ${token}`) { res.writeHead(401).end('{}'); return }+ res.end(JSON.stringify({ status: 1, data: { id: userId, email: `${userId}@local.invalid` } }))+ }), ports.sso)+ await listen(createServer(async (req, res) => {+ try {+ const u = new URL(req.url, webBase), pathname = decodeURIComponent(u.pathname)+ const file = resolve(webDir, '.' + (pathname === '/' || pathname === '/callback' ? '/index.html' : pathname))+ if (!file.startsWith(webDir + sep)) { res.writeHead(403).end(); return }+ const mime = { '.html': 'text/html', '.js': 'application/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ttf': 'font/ttf', '.woff2': 'font/woff2' }[extname(file)] || 'application/octet-stream'+ const data = await readFile(file)+ res.writeHead(200, { 'content-type': mime, 'cache-control': 'no-store' }); res.end(data)+ } catch { res.writeHead(404).end() }+ }), ports.web)+ const backendEnv = { ...safeEnv, PORT: String(ports.backend), PORT_APP_PROXY: String(ports.proxy),+ DATABASE_URL: mongo.getUri('hn_viewer'), REDIS_URL: `redis://127.0.0.1:${ports.redis}`,+ HARNESS_BILLING_ENABLED: 'false', MESH_ENABLED: 'false', SSO_ISSUER: ssoBase, SSO_CLIENT_ID: 'hn-viewer-test',+ SSO_PROFILE_URL: ssoBase + '/profile', SSO_IDENTITY_URL: '', WEB_URL: webBase, WEB_ORIGINS: webBase,+ AUTONOMOUS_BFF_URL: ssoBase, AUTONOMOUS_CAMPAIGN_API_URL: ssoBase,+ TERMINAL_P2P_ROLLOUT_PERCENT: '0', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }+ await exec(join(repo, 'backend/node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], { cwd: join(repo, 'backend'), env: backendEnv, timeout: 60000 })+ let backend = run('backend', join(repo, 'backend'), ['--import', 'tsx', 'src/server.ts'], backendEnv)+ await until('backend health', () => fetch(base + '/api/health').then(r => r.ok).catch(() => false))+ const computerId = randomUUID().replaceAll('-', '')+ const registered = await fetch(base + '/api/machines/resolve-computer', { method: 'POST', headers: authHeaders, body: JSON.stringify({ computerId, label: 'hn viewer test' }) }).then(r => r.json())+ const machineId = registered.data?.machine?.machineId+ assert.ok(machineId, JSON.stringify(registered))+ await writeFile(join(root, 'auth/session.json'), JSON.stringify({ version: 1, accessToken: token, refreshToken: 'test-refresh', expiresAt: Date.now() + 3600000, autonomousEnv: 'prod', computerId, machineId, updatedAt: Date.now() }), { mode: 0o600 })+ const engine = join(root, 'bin/claude')+ await writeFile(engine, `#!${process.execPath}\nif(process.argv.includes('--version')){console.log('2.1.0 (Claude Code)');process.exit(0)}\nif(process.argv.includes('--help')){console.log('--dangerously-skip-permissions --permission-mode --model');process.exit(0)}\nprocess.title='claude';process.stdin.setRawMode?.(true);console.log('HN_VIEWER_ENGINE_READY');process.stdin.on('data',x=>{require('node:fs').appendFileSync(${JSON.stringify(join(root, 'engine-input.log'))},x);process.stdout.write('ECHO:'+x+'\\r\\n')});setInterval(()=>{},1000);\n`, { mode: 0o700 })+ // Every daemon tmux operation is forced onto this test's server, even with TMUX unset.+ await writeFile(join(root, 'bin/tmux'), `#!/bin/sh\nfor arg in "$@"; do case "$arg" in -L*|-S*) exit 125;; esac; done\nexec '${tmux.replaceAll("'", "'\\''")}' -L '${prefix}' "$@"\n`, { mode: 0o700 })+ const daemonEnv = { ...safeEnv, PATH: join(root, 'bin') + ':' + safeEnv.PATH, PORT: String(ports.daemon),+ HARNESS_AUTH_DIR: join(root, 'auth'), ADAPTER_COMPUTER_ID: computerId, ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),+ ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'), DSH_DIR: join(root, 'dsh'),+ CLAUDE_PATH: engine, CLAUDE_CONFIG_DIR: join(root, 'claude'), CLAUDE_PROJECTS_DIR: join(root, 'claude/projects'),+ BACKEND_WS_URL: base.replace('http:', 'ws:'), WEB_URL: webBase, HARNESS_STORE_CATALOG_URL: ssoBase + '/empty-catalog',+ HARNESS_GRID_BIN: join(root, 'no-grid'), DISABLE_GRID_INSTALL: 'true', DISABLE_HOOK_INSTALL: 'true',+ ADAPTER_UPDATE_DISABLE: 'true', ANALYTICS_ENABLED: 'false', RECAP_FORCE: 'false', RECAP_WITHOUT_DEVICE: 'false',+ CABLE_DISABLE: 'true', CABLE_FW_DISABLE: 'true', TERMINAL_BACKENDS: 'tmux', HARNESS_VIEWER_BROWSER: chrome,+ LOG_FRAMES: 'true', TMUX_REAP_INTERVAL_MS: '5000', TERMINAL_RECONCILE_INTERVAL_MS: '5000' }+ await exec(tmux, ['-L', prefix, '-f', '/dev/null', 'new-session', '-d', '-s', 'fixture-keeper'], { env: daemonEnv })+ cleanups.push(() => exec(tmux, ['-L', prefix, 'kill-server'], { env: daemonEnv }).catch(() => {}))+ const packages = ['agents/blender', 'viewers/model-viewer']+ const controls = join(root, 'controls-package')+ await mkdir(join(controls, 'template'), { recursive: true })+ await writeFile(join(controls, 'template/fixture.txt'), 'Disposable viewer input fixture')+ await writeFile(join(controls, 'AGENTS.md'), 'Disposable local viewer integration fixture.\n')+ await writeFile(join(controls, 'harness.json'), JSON.stringify({ spec: 1, id: 'fixture/hn-viewer', name: 'Viewer controls', engine: 'claude', workspace: { template: 'template', marker: 'fixture.txt' }, agent: { instructions: 'AGENTS.md' }, viewer: { command: './viewer.mjs', url: 'http://127.0.0.1:${port}/' } }))+ const controlHtml = '<html><body style="margin:0;background:#152238;color:white;font:32px sans-serif"><h1 style="position:absolute;left:20px;top:20px;margin:0;font-size:32px">Viewer input fixture</h1><button style="position:absolute;left:20px;top:100px;width:200px;height:56px;font-size:24px" onclick="fetch(\'/event?click=1\')">Click me</button><input aria-label="Viewer text" style="position:absolute;left:20px;top:180px;width:400px;height:56px;font-size:24px" oninput="fetch(\'/event?text=\'+encodeURIComponent(this.value))"><script>addEventListener("keydown",e=>fetch("/event?key="+encodeURIComponent(e.key)))</script></body></html>'+ await writeFile(join(controls, 'viewer.mjs'), `#!${process.execPath}\nimport {createServer} from 'node:http';import {appendFileSync} from 'node:fs';createServer((req,res)=>{if(req.url.startsWith('/event?')){appendFileSync(${JSON.stringify(join(root, 'viewer-events.log'))},req.url+'\\n');res.end('ok');return}res.setHeader('content-type','text/html');res.end(${JSON.stringify(controlHtml)})}).listen(Number(process.env.HARNESS_VIEWER_PORT),'127.0.0.1');\n`, { mode: 0o700 })+ await writeFile(join(root, 'dsh/installed.json'), JSON.stringify([...packages.map(path => {+ const dir = join(repo, 'store', path)+ return { id: JSON.parse(readFileSync(join(dir, 'harness.json'), 'utf8')).id, dir, source: dir, ref: null, commit: null, linked: true, installedAt: Date.now() }+ }), { id: 'fixture/hn-viewer', dir: controls, source: controls, ref: null, commit: null, linked: true, installedAt: Date.now() }]))+ const daemon = run('daemon', join(repo, 'cli'), ['--import', 'tsx', 'src/cli.ts', '__run'], daemonEnv)+ await until('real daemon ready', () => {+ if (daemon.exitCode !== null) throw new Error('Test daemon exited; inspect its isolated log')+ return fetch(`http://127.0.0.1:${ports.daemon}/api/status`, { headers: { 'x-adapter-local': '1' } }).then(r => r.json()).then(v => v.connected && v.discoveryReady).catch(() => false)+ })+ const setPassword = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'remote-password', 'set', '--stdin'], { cwd: join(repo, 'cli'), env: daemonEnv, stdio: ['pipe', 'pipe', 'pipe'] })+ setPassword.stdin.end(password + '\n')+ const [passwordCode] = await once(setPassword, 'exit'); assert.equal(passwordCode, 0)+ owner = await desktop(machineId)+ const workspace = join(root, 'workspace')+ await cp(join(repo, 'store/agents/blender/template'), workspace, { recursive: true })+ await mkdir(join(workspace, 'out'), { recursive: true })+ const positions = Buffer.from(new Float32Array([-1, 0, 0, 1, 0, 0, 0, 2, 0]).buffer)+ await writeFile(join(workspace, 'out/triangle.gltf'), JSON.stringify({ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: 'Live hn triangle' }], meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }], buffers: [{ uri: `data:application/octet-stream;base64,${positions.toString('base64')}`, byteLength: positions.length }], bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: positions.length }], accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [-1, 0, 0], max: [1, 2, 0] }] }))+ const created = await owner.rpc('agent_create', { engine: 'claude', cwd: workspace, dsh: 'autonomous/blender', bypassPermission: false, name: 'hn Blender test', creationId: randomUUID() })+ agentId = created.agent?.id; assert.ok(agentId, JSON.stringify(created))+ let viewerUrl+ await until('real Blender viewer', async () => { const a = (await owner.rpc('agents_list')).agents.find(a => a.id === agentId); assert.ok(!a?.viewerError, a?.viewerError); viewerUrl = a?.viewerUrl; return viewerUrl })+ hnBinary = join(root, 'hn'); await cp(process.env.HN_VIEWER_BINARY, hnBinary)+ hnEnv = { ...daemonEnv, HN_SOCKET_NAME: prefix, HN_TMPDIR: root, HN_DESKTOP: 'off', HARNESS_TUI_DESK: 'off', HARNESS_TUI_NOTIFY: 'off' }+ cleanups.push(() => hn('kill-server').catch(() => {}))+ assert.equal((await hn('view', '-p', '-t', agentId)).stdout.trim(), viewerUrl)+ const link = (await hn('view', '-pw', '-t', agentId)).stdout.trim()+ assert.equal(new URL(link).origin, webBase)+ assert.equal(new URL(link).searchParams.get('agent'), agentId)+ pass('real hn discovers a real Blender harness and produces direct and private-browser destinations')+ browser = await chromium.launch({ executablePath: chrome, headless: true, args: ['--enable-unsafe-swiftshader'] })+ cleanups.push(() => browser.close())+ context = await browser.newContext({ viewport: { width: 1200, height: 850 } })+ // A wrong web build must not contact a production backend or sign-in provider.+ await context.route('**/*', route => new URL(route.request().url()).hostname === '127.0.0.1' ? route.continue() : route.abort())+ const direct = await context.newPage(); await direct.goto(viewerUrl)+ await direct.waitForFunction(() => document.querySelector('#model-name')?.textContent === 'triangle.gltf' && !!document.querySelector('#tree .row'))+ await direct.screenshot({ path: join(root, 'blender-direct.png') })+ pass('Chrome opens the actual model viewer and renders the glTF fixture')+ await direct.close()+ const page = await context.newPage(), pageErrors = [], requests = []+ page.on('pageerror', e => pageErrors.push(e.message))+ page.on('request', req => requests.push(req.url()))+ await page.goto(link); await semantics(page)+ const exchanged = page.waitForResponse(r => r.url() === base + '/api/auth/exchange' && r.status() === 200, { timeout: 45000 })+ await page.getByRole('button', { name: 'Continue with SSO', exact: true }).click({ timeout: 45000 })+ await exchanged+ await page.waitForURL(url => url.searchParams.get('viewer') === '1' && url.searchParams.get('agent') === agentId, { timeout: 45000 })+ await semantics(page)+ await page.getByRole('textbox').fill(password, { timeout: 45000 })+ await page.getByRole('textbox').press('Enter')+ await until('browser linked machine', () => page.evaluate(() => localStorage.getItem('harness.web.v1.viewer_e2ee_machine_peers')?.includes('machineId')))+ await page.getByRole('textbox', { name: 'Viewer input' }).waitFor({ state: 'attached', timeout: 60000 })+ await page.waitForTimeout(500)+ await page.screenshot({ path: join(root, 'browser-companion.png') })+ await writeFile(join(root, 'browser-dom.html'), await page.content())+ assert.ok(!requests.some(u => /\/api\/desk(?:\?|$|\/)/.test(u)), 'viewer tab must not read or overwrite the desk')+ assert.deepEqual(pageErrors, [])+ pass('real browser sign-in round trip preserves hn destination and password-links to the isolated daemon')+ await mkdir(join(root, 'controls-workspace'))+ const second = await owner.rpc('agent_create', { engine: 'claude', cwd: join(root, 'controls-workspace'), dsh: 'fixture/hn-viewer', bypassPermission: false, name: 'hn input test', creationId: randomUUID() })+ controlsId = second.agent?.id; assert.ok(controlsId, JSON.stringify(second))+ await until('controls viewer', async () => (await owner.rpc('agents_list')).agents.some(a => a.id === controlsId && a.viewerUrl))+ const controlsLink = (await hn('view', '-pw', '-t', controlsId)).stdout.trim()+ await page.goto(controlsLink); await semantics(page)+ const input = page.getByRole('textbox', { name: 'Viewer input' })+ await input.waitFor({ state: 'attached', timeout: 60000 })+ async function pointer(x, y) {+ const bounds = await input.boundingBox(); assert.ok(bounds)+ await page.mouse.click(bounds.x + x * bounds.width / Math.max(160, Math.min(1920, Math.round(bounds.width))), bounds.y + y * bounds.height / Math.max(120, Math.min(1200, Math.round(bounds.height))))+ }+ const events = () => existsSync(join(root, 'viewer-events.log')) ? readFileSync(join(root, 'viewer-events.log'), 'utf8') : ''+ await pointer(100, 128)+ await until('real viewer mouse input', () => events().includes('click=1'))+ await pointer(150, 208)+ await page.keyboard.insertText('Hello é 中文')+ await until('real Unicode viewer input', () => events().includes(encodeURIComponent('Hello é 中文')))+ await page.keyboard.press('ArrowLeft')+ await until('real special key input', () => events().includes('key=ArrowLeft'))+ await page.setViewportSize({ width: 2400, height: 1400 })+ await page.waitForTimeout(800)+ const oldClicks = events().split('click=1').length+ await pointer(100, 128)+ await until('pointer mapping after renderer resolution cap', () => events().split('click=1').length > oldClicks)+ await page.screenshot({ path: join(root, 'browser-input-resized.png') })+ assert.ok(!existsSync(join(root, 'engine-input.log')), 'browser input must not reach the terminal')+ pass('real mouse, Unicode text, special keys and resize reach the viewer without typing into its terminal')+ await page.getByRole('button', { name: 'Reload viewer', exact: true }).click()+ await input.waitFor({ state: 'attached', timeout: 60000 })+ await page.setViewportSize({ width: 1200, height: 850 })+ await page.reload(); await semantics(page)+ await input.waitFor({ state: 'attached', timeout: 60000 })+ assert.ok(!requests.some(u => /\/api\/desk(?:\?|$|\/)/.test(u)))+ assert.deepEqual(pageErrors, [])+ pass('reload and a fresh browser connection recover the viewer without restoring the desk')+ await stop(backend)+ await input.waitFor({ state: 'detached', timeout: 45000 })+ await page.screenshot({ path: join(root, 'browser-disconnected.png') })+ backend = run('backend-restarted', join(repo, 'backend'), ['--import', 'tsx', 'src/server.ts'], backendEnv)+ await until('restarted backend health', () => fetch(base + '/api/health').then(r => r.ok).catch(() => false))+ await input.waitFor({ state: 'attached', timeout: 60000 })+ const beforeReconnectClick = events().split('click=1').length+ await pointer(100, 128)+ await until('input after backend reconnect', () => events().split('click=1').length > beforeReconnectClick)+ pass('a real backend outage shows disconnection and reconnects with working viewer input')+ await page.goto(webBase + '/?viewer=1&machine=%FF&agent=fixture')+ await semantics(page)+ await page.getByText('This viewer link is incomplete. Run hn view again.', { exact: true }).waitFor()+ assert.ok(!requests.some(u => /\/api\/desk(?:\?|$|\/)/.test(u)))+ assert.deepEqual(pageErrors, [])+ assert.ok(!existsSync(join(root, 'engine-input.log')))+ pass('a malformed UTF-8 viewer link shows recovery guidance without opening the workspace')+ assert.ok((await owner.rpc('agents_list')).agents.some(a => a.id === agentId))+ await page.close()+ assert.ok((await owner.rpc('agents_list')).agents.some(a => a.id === agentId))+ pass('closing the browser leaves the harness running')+ await owner.rpc('agent_delete', { agentId: controlsId }); controlsId = null+ await owner.rpc('agent_delete', { agentId }); agentId = null+ complete = true+} catch (error) {+ if (context) for (const [i, page] of context.pages().entries()) {+ await page.screenshot({ path: join(root, `failure-${i}.png`), timeout: 5000 }).catch(() => {})+ await writeFile(join(root, `failure-${i}.html`), await page.content().catch(() => 'unavailable'))+ }+ throw error+} finally {+ if (controlsId && owner?.ws.readyState === WebSocket.OPEN) await owner.rpc('agent_delete', { agentId: controlsId }).catch(() => {})+ if (agentId && owner?.ws.readyState === WebSocket.OPEN) await owner.rpc('agent_delete', { agentId }).catch(() => {})+ for (const cleanup of cleanups.reverse()) { try { await cleanup() } catch (error) { console.error('Cleanup:', error.message) } }+ await writeFile(join(root, 'results.json'), JSON.stringify({ complete, checks, topology: 'one physical Mac; real daemon/backend/Mongo/Redis/Chrome; fixture OAuth provider/model process' }, null, 2))+}diff --git a/tui/tests/viewer.py b/tui/tests/viewer.pynew file mode 100644index 000000000..d80efd45d--- /dev/null+++ b/tui/tests/viewer.py@@ -0,0 +1,194 @@+#!/usr/bin/env python3+"""Exercise hn's public viewer commands against a private mock and a recording browser opener."""+import json+import os+from pathlib import Path+import shutil+import shlex+import socket+import threading+import subprocess+import sys+import tempfile+import time+import urllib.parse+import urllib.request++root = Path(__file__).resolve().parents[1]+source = Path(os.environ.get('HN_VIEWER_TEST_BINARY', root / 'target/release/harness-tui')).resolve()+port = int(os.environ.get('HN_VIEWER_TEST_PORT', '19671'))+if not 19000 <= port <= 19999 or port in (18473, 18907):+ raise SystemExit('Viewer tests require an isolated port in 19000–19999')+prefix = f'hn-viewer-test-{os.getpid()}'+with tempfile.TemporaryDirectory(prefix='hnv-', dir='/tmp') as tmp:+ home = Path(tmp)+ binary = home / 'hn'+ shutil.copy2(source, binary)+ bin_dir = home / 'bin'+ bin_dir.mkdir()+ log = home / 'browser.jsonl'+ for name in ('open', 'xdg-open'):+ opener = bin_dir / name+ opener.write_text('#!' + sys.executable + '\nimport json,os,sys,time\nwith open(os.environ["HN_VIEWER_OPENER_LOG"],"a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\ntime.sleep(float(os.environ.get("HN_VIEWER_OPENER_DELAY","0")))\nsys.exit(int(os.environ.get("HN_VIEWER_OPENER_EXIT","0")))\n')+ opener.chmod(0o700)+ env = {k: v for k, v in os.environ.items() if k not in ('TMUX', 'TMUX_PANE', 'HN_SOCKET', 'SSH_TTY', 'SSH_CONNECTION', 'SSH_CLIENT')}+ env.update(HOME=tmp, PORT=str(port), HN_SOCKET_NAME=prefix, HN_TMPDIR=tmp,+ HARNESS_TUI_DESK='off', HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off',+ HN_VIEWER_OPENER_LOG=str(log), PATH=str(bin_dir) + os.pathsep + env.get('PATH', ''),+ MOCK_VIEWER='1', MOCK_VIEWER_EDGES='1', MOCK_WEB_URL='https://harness.example', DISPLAY=':hn-test')+ def hn(*args, extra=None, ok=True):+ result = subprocess.run([str(binary), '-L', prefix, '--port', str(port), *args],+ env={**env, **(extra or {})}, text=True, capture_output=True, timeout=20)+ if ok and result.returncode:+ raise AssertionError(f'{args}: {result.returncode}: {result.stderr}')+ return result+ def opened():+ return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []+ def web_link(result, agent):+ uri = urllib.parse.urlparse(result.stdout.strip())+ assert uri.scheme == 'https' and uri.netloc == 'harness.example', result.stdout+ assert uri.path == '/', result.stdout+ assert urllib.parse.parse_qs(uri.query) == {+ 'viewer': ['1'], 'machine': ['mock000000000000000000000000000' + ('2' if agent.startswith('remote') or agent.endswith('-remote') else '1')],+ 'agent': [agent]}, result.stdout+ mock = subprocess.Popen(['node', str(root / 'tests/mock-daemon.mjs'), str(port)], env=env,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ try:+ for _ in range(100):+ if mock.poll() is not None: raise AssertionError(mock.stderr.read().decode())+ try:+ with urllib.request.urlopen(f'http://127.0.0.1:{port}/api/status', timeout=.2): break+ except OSError: time.sleep(.05)+ else: raise AssertionError('Mock did not start')+ local = f'http://127.0.0.1:{port}/test-viewer?file=model.glb'+ assert hn('view', '-p', '-t', 'Mock Blender').stdout.strip() == local+ assert not opened()+ hn('view', '-t', 'Mock Blender')+ assert opened() == [[local]], opened()+ web_link(hn('view', '-t', 'Mock Blender', extra={'SSH_CONNECTION': 'fixture ssh'}), 'mock-blender')+ assert opened() == [[local]], 'SSH must never launch a server-side browser'+ web_link(hn('view', '-p', '-t', 'Remote Blender'), 'remote-blender')+ web_link(hn('view', '-pw', '-t', 'Mock Blender'), 'mock-blender')+ assert hn('view', '-p', '-t', 'Mock Claude', ok=False).returncode == 1+ assert hn('view', '-p', '-t', 'Missing', ok=False).returncode == 1+ assert hn('view', '--unknown', ok=False).returncode == 2+ assert hn('view', '-t', ok=False).returncode == 2+ assert hn('view', '-t', 'Mock Blender', extra={'HN_VIEWER_OPENER_EXIT': '1'}).stdout.strip() == local+ assert hn('view', '-t', 'Mock Blender', extra={'PATH': ''}).stdout.strip() == local+ started = time.monotonic()+ assert hn('view', '-t', 'Mock Blender', extra={'HN_VIEWER_OPENER_DELAY': '12'}).stdout.strip() == local+ assert time.monotonic() - started < 10, 'a stuck browser opener must not hold the terminal'+ if sys.platform.startswith('linux'):+ count = len(opened())+ assert hn('view', '-t', 'Mock Blender', extra={'DISPLAY': '', 'WAYLAND_DISPLAY': ''}).stdout.strip() == local+ assert len(opened()) == count+ hn('view', '-t', 'Mock Blender', extra={'DISPLAY': '', 'WAYLAND_DISPLAY': 'fixture'})+ assert len(opened()) == count + 1+ assert 'usage: hn view' in hn('view', '--help').stdout+ assert hn('view', ok=False).returncode == 1+ assert hn('view', '-t', '', ok=False).returncode == 2+ assert hn('view', '-p', '-t', 'Mock B', ok=False).returncode == 1+ assert 'more than one harness' in hn('view', '-p', '-t', 'Duplicate Viewer', ok=False).stderr+ for key in ('SSH_CLIENT', 'SSH_TTY', 'SSH_CONNECTION'):+ count = len(opened())+ web_link(hn('view', '-t', 'mock-blender', extra={key: 'fixture'}), 'mock-blender')+ assert len(opened()) == count+ web_link(hn('view', '-c', '-t', 'mock-blender'), 'mock-blender')+ web_link(hn('view', '-pcw', '-t', 'Waiting Viewer'), 'waiting-viewer')+ assert 'Renderer could not start' in hn('view', '-p', '-t', 'Failed Viewer', ok=False).stderr+ assert 'invalid viewer address' in hn('view', '-p', '-t', 'Unsafe Viewer', ok=False).stderr+ assert hn('view', '-p', '-t', 'Quoted " viewer; $(false)').stdout.strip() == f'http://127.0.0.1:{port}/test-viewer?x=a&y=b'+ web_link(hn('view', '-p', '-t', 'mock0000000000000000000000000002:duplicate-remote'), 'duplicate-remote')+ print('PASS: standalone viewer, exact opener argv, SSH, remote target, print and browser-failure fallback')+ hn('new-session', '-d', '-s', 'viewer-test')+ hn('open-harness', '-s', 'Mock Blender')+ assert hn('view', '-p').stdout.strip() == local+ count = len(opened())+ web_link(hn('view', extra={'SSH_TTY': '/dev/fixture'}), 'mock-blender')+ assert len(opened()) == count+ assert hn('view', '-p', '-t', 'Mock Claude', ok=False).returncode == 1+ assert 'more than one harness' in hn('view', '-p', '-t', 'Duplicate Viewer', ok=False).stderr+ web_link(hn('view', '-pc', '-t', 'Waiting Viewer'), 'waiting-viewer')+ assert hn('view', '-p', '-t', 'Quoted " viewer; $(false)').stdout.strip() == f'http://127.0.0.1:{port}/test-viewer?x=a&y=b'+ assert 'invalid viewer address' in hn('view', '-p', '-t', 'Unsafe Viewer', ok=False).stderr+ assert 'open-viewer' in hn('list-commands').stdout+ print('PASS: active pane through hn IPC; caller SSH environment controls the handoff')++ # An hn client can disappear or lose its reply while a shell asks for a viewer.+ # A private Unix socket returning a damaged response exercises that recovery path.+ broken = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ broken_path = home / (prefix + '-broken.sock')+ broken.bind(str(broken_path))+ broken.listen()+ broken.settimeout(.1)+ stopped = threading.Event()+ def damaged_client():+ while not stopped.is_set():+ try: peer, _ = broken.accept()+ except socket.timeout: continue+ except OSError: return+ with peer:+ peer.settimeout(1)+ try:+ if peer.recv(8192): peer.sendall(b'not-json\n')+ except OSError: pass+ worker = threading.Thread(target=damaged_client, daemon=True)+ worker.start()+ try:+ result = hn('-S', str(broken_path), 'view', '-p', '-t', 'Mock Blender', ok=False)+ assert result.returncode == 1 and 'could not reach the hn client' in result.stderr, result+ finally:+ stopped.set()+ worker.join(timeout=2)+ broken.close()++ tmux = shutil.which('tmux')+ assert tmux, 'Viewer command-prompt tests need tmux'+ tmux_prefix = prefix + '-ui'+ def mux(*args, ok=True):+ result = subprocess.run([tmux, '-L', tmux_prefix, *args], env=env, capture_output=True, text=True, timeout=10)+ if ok: assert result.returncode == 0, result.stderr+ return result.stdout+ def until(label, predicate):+ end = time.monotonic() + 15+ while not predicate():+ if time.monotonic() > end: raise AssertionError(label + ': ' + mux('capture-pane', '-p', '-t', 'viewer-ui'))+ time.sleep(.05)+ def command(text):+ mux('send-keys', '-t', 'viewer-ui', 'C-b', ':')+ mux('send-keys', '-t', 'viewer-ui', '-l', text)+ mux('send-keys', '-t', 'viewer-ui', 'Enter')+ try:+ for mode in ('local', 'ssh', 'failed-opener'):+ extra = ['SSH_CONNECTION=fixture'] if mode == 'ssh' else ['HN_VIEWER_OPENER_EXIT=1'] if mode == 'failed-opener' else []+ launch = ['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET', *extra,+ str(binary), '-L', prefix, '--port', str(port), 'attach-session', '-t', 'viewer-test']+ mux('new-session', '-d', '-s', 'viewer-ui', '-x', '140', '-y', '35', shlex.join(launch))+ until('interactive viewer pane attached', lambda: 'Mock Blender' in mux('capture-pane', '-p', '-t', 'viewer-ui'))+ if mode == 'local':+ before = len(opened())+ command('view')+ until('local command opens browser', lambda: len(opened()) > before)+ command('view -c')+ until('clipboard confirmation', lambda: 'terminal clipboard' in mux('capture-pane', '-p', '-t', 'viewer-ui'))+ command('view -p')+ until('print-only viewer modal', lambda: local in mux('capture-pane', '-p', '-t', 'viewer-ui'))+ else:+ before = len(opened())+ command('view')+ until('viewer fallback link', lambda: 'Open this link in your browser' in mux('capture-pane', '-p', '-t', 'viewer-ui'))+ if mode == 'ssh': assert len(opened()) == before+ # Detach normally so hn saves its session and coverage counters before tmux exits.+ mux('send-keys', '-t', 'viewer-ui', 'Escape')+ mux('send-keys', '-t', 'viewer-ui', 'C-b', 'd')+ until('interactive client detached', lambda: not mux('capture-pane', '-p', '-t', 'viewer-ui', ok=False))+ mux('kill-session', '-t', 'viewer-ui', ok=False)+ print('PASS: real TUI command prompt opens, prints, copies and falls back correctly locally and over SSH')+ finally:+ mux('kill-server', ok=False)++ finally:+ hn('kill-server', ok=False)+ mock.terminate()+ try: mock.wait(timeout=5)+ except subprocess.TimeoutExpired: mock.kill(); mock.wait(timeout=5)