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
Discover shared Super Tabs across computers (#1440)
Dee0f64b46e3b38
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex cc4930393..299b051d3 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1654,6 +1654,41 @@ class AppNotifier extends ChangeNotifier {late final superTabs = SuperTabClient(storage: localStore ?? HarnessFileStore.shared,+ discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),+ onTabs: (tabs, hidden) {+ // The browser can learn its account before the saved layout finishes+ // loading. Discovery must not persist over that workspace during boot.+ if (_disposed ||+ status != AppStatus.authenticated ||+ currentUser?.id == null) {+ return;+ }+ var changed = false;+ for (final tab in tabs) {+ final existing = swarms.where((s) => s.superTabId == tab.id).firstOrNull;+ if (existing != null) {+ if (existing.name != tab.name || !existing.nameIsCustom) {+ existing.name = tab.name;+ existing.nameIsCustom = true;+ changed = true;+ }+ } else if (!hidden.contains(tab.id)) {+ swarms.add(+ Swarm(+ id: newDeskId(),+ name: tab.name,+ nameIsCustom: true,+ kind: 'superTab',+ )..superTabId = tab.id,+ );+ changed = true;+ }+ }+ if (changed) {+ _persistLayout();+ notifyListeners();+ }+ },onSnapshot: (controller) {if (_disposed || controller.accountId != currentUser?.id) return;var shown = false;@@ -1718,16 +1753,29 @@ class AppNotifier extends ChangeNotifier {void bindSuperTab(String swarmId, String tabId, String name) {final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;if (swarm == null) return;+ // A discovery response can beat the creation response back to this+ // computer. Keep the lead form's tab and retain any already-open panes.+ for (final duplicate in swarms+ .where((s) => s.id != swarmId && s.superTabId == tabId)+ .toList()) {+ for (final pane in duplicate.panes) {+ if (!swarm.panes.contains(pane)) swarm.panes.add(pane);+ }+ if (_activeSwarmId == duplicate.id) _activeSwarmId = swarm.id;+ swarms.remove(duplicate);+ }swarm.kind = 'superTab';swarm.superTabId = tabId;swarm.name = name;swarm.nameIsCustom = true;swarm.isNewTabPage = false;+ _rememberSuperTabVisibility(tabId, true);_persistLayout();notifyListeners();}void openSuperTab(String tabId, String name) {+ _rememberSuperTabVisibility(tabId, true);final existing = swarms.where((s) => s.superTabId == tabId).firstOrNull;if (existing != null) {selectSwarm(existing.id);@@ -1737,6 +1785,13 @@ class AppNotifier extends ChangeNotifier {bindSuperTab(activeSwarmId, tabId, name);}+ void _rememberSuperTabVisibility(String tabId, bool visible) {+ if (localStore == null) return;+ unawaited(superTabs.setTabVisible(tabId, visible).catchError((Object error) {+ appLog.warn('super-tab', 'Could not save tab visibility: $error');+ }));+ }+void markSuperTabDraft(String swarmId) {final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;if (swarm == null) return;@@ -3001,6 +3056,9 @@ class AppNotifier extends ChangeNotifier {return;}final removed = swarms.removeAt(index);+ if (removed.superTabId case final tabId?) {+ _rememberSuperTabVisibility(tabId, false);+ }Swarm? replacement;if (swarms.isEmpty) {replacement = Swarm(id: 'swarm-${_nextSwarmId++}');@@ -3335,6 +3393,9 @@ class AppNotifier extends ChangeNotifier {final saved = _closedHistory[index] as ClosedSwarm;if (!_canReopenSwarm(saved)) return;_closedHistory.removeAt(index);+ if (saved.superTabId case final tabId?) {+ _rememberSuperTabVisibility(tabId, true);+ }if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {swarms.clear();}diff --git a/desktop/lib/state/machine_profile.dart b/desktop/lib/state/machine_profile.dartindex 14ac6cb13..1420b56a9 100644--- a/desktop/lib/state/machine_profile.dart+++ b/desktop/lib/state/machine_profile.dart@@ -9,7 +9,9 @@ import 'swarm.dart';/// stay, so there is always a place to start one.bool swarmMatchesMachineProfile(Swarm swarm, String? machineId) {if (machineId == null || machineId.isEmpty) return true;- if (swarm.isUtility) return true;+ // Super Tab membership spans machines. Its current terminal selection does+ // not make the shared conversation belong to that terminal's computer.+ if (swarm.isUtility || swarm.isSuperTab) return true;final paneIds = <String>{for (final pane in swarm.panes)if (pane.machineId.isNotEmpty) pane.machineId,diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 1308a730d..852e3ad1b 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -11,6 +11,8 @@ typedef SuperTabTransport = Future<Object?> Function(Map<String, dynamic>? body,});+typedef SuperTabListing = ({String id, String name});+/// Account-scoped client state. Backend membership never comes from the saved/// layout, and a late response cannot cross an account change.class SuperTabClient {@@ -18,12 +20,23 @@ class SuperTabClient {required this.transport,required this.storage,this.onSnapshot,+ this.onTabs,+ this.discoveryInterval = const Duration(seconds: 15),});final SuperTabTransport transport;final LocalKeyValueStore storage;final void Function(SuperTabController)? onSnapshot;+ final void Function(List<SuperTabListing>, Set<String> hidden)? onTabs;+ final Duration discoveryInterval;String? _account;int _generation = 0;+ Timer? _discoveryTimer;+ Future<void>? _discovering, _loadingHidden;+ Future<void> _savingHidden = Future.value();+ Set<String> _hidden = {};+ final _creating = <String>{};+ final _visibility = <String, bool>{};+ Object? discoveryError;final _controllers = <String, Future<SuperTabController>>{};final _loaded = <String, SuperTabController>{};SuperTabController? peek(String id) => _loaded[id];@@ -32,6 +45,13 @@ class SuperTabClient {if (_account == account) return;_account = account;_generation++;+ _discoveryTimer?.cancel();+ _discovering = null;+ _loadingHidden = null;+ _hidden = {};+ _creating.clear();+ _visibility.clear();+ discoveryError = null;for (final controller in _loaded.values) {controller.revokeAccess('The account changed. Open this Super Tab again.',@@ -49,6 +69,112 @@ class SuperTabClient {}_controllers.clear();_loaded.clear();+ if (account != null &&+ onTabs != null &&+ discoveryInterval > Duration.zero) {+ unawaited(refreshTabs());+ _discoveryTimer = Timer.periodic(+ discoveryInterval,+ (_) => unawaited(refreshTabs()),+ );+ }+ }++ Future<void> _readHidden(String account, int generation) =>+ _loadingHidden ??= () async {+ final raw = await storage.read('super_tab.hidden.$account');+ if (generation != _generation) return;+ _hidden = raw == null+ ? <String>{}+ : (jsonDecode(raw) as List).whereType<String>().toSet();+ for (final entry in _visibility.entries) {+ if (entry.value) {+ _hidden.remove(entry.key);+ } else {+ _hidden.add(entry.key);+ }+ }+ }();++ /// Closing a tab hides its view on this computer. Membership and running+ /// agents stay on the backend; another computer still discovers that tab.+ Future<void> setTabVisible(String id, bool visible) async {+ final account = _account;+ final generation = _generation;+ if (account == null) return;+ if (visible) _creating.remove(id);+ _visibility[id] = visible;+ if (visible) {+ _hidden.remove(id);+ } else {+ _hidden.add(id);+ }+ await _readHidden(account, generation);+ if (generation != _generation) return;+ final saved = jsonEncode(_hidden.toList()..sort());+ final write = _savingHidden+ .catchError((Object _) {})+ .then((_) => storage.write('super_tab.hidden.$account', saved));+ _savingHidden = write;+ await write;+ }++ /// The lead form already represents a creation in flight on this computer.+ /// Its backend row can arrive through discovery before the lead is ready.+ void deferTabDiscovery(String id) => _creating.add(id);++ /// Discovery is account membership, independent of this computer's saved+ /// layout. Read every page before applying; a failed page cannot drop tabs.+ Future<void> refreshTabs() {+ if (_account == null || onTabs == null) return Future.value();+ if (_discovering case final active?) return active;+ final generation = _generation;+ final account = _account!;+ final read = () async {+ try {+ await _readHidden(account, generation);+ if (generation != _generation) return;+ final tabs = <String, SuperTabListing>{};+ final cursors = <String>{};+ String? after;+ do {+ final page = await map(+ 'GET',+ '/api/super-tabs${after == null ? '' : '?after=${Uri.encodeComponent(after)}'}',+ );+ if (generation != _generation) return;+ if (page['tabs'] is! List) {+ throw const FormatException('Missing tabs');+ }+ for (final raw in page['tabs'] as List) {+ final row = superTabMap(raw);+ if (row['id'] is! String || row['name'] is! String) {+ throw const FormatException('Invalid tab');+ }+ final id = row['id'] as String;+ tabs[id] = (id: id, name: row['name'] as String);+ }+ after = page['next'] as String?;+ if (after != null && !cursors.add(after)) {+ throw const FormatException('Repeated tab cursor');+ }+ } while (after != null);+ discoveryError = null;+ onTabs!(+ tabs.values.toList(),+ Set.unmodifiable({..._hidden, ..._creating}),+ );+ } catch (error) {+ if (generation == _generation) {+ discoveryError = error;+ _loadingHidden = null;+ }+ }+ }();+ _discovering = read;+ return read.whenComplete(() {+ if (identical(_discovering, read)) _discovering = null;+ });}Future<Object?> request(diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex 8a8724125..4d2f62743 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -115,8 +115,10 @@ class SuperTabLaunch {body: {'operationId': saved['operationId'], 'name': 'Super Tab'},);saved['tabId'] = created['id'];+ app.superTabs.deferTabDiscovery(saved['tabId'] as String);await persist();}+ app.superTabs.deferTabDiscovery(saved['tabId'] as String);final command = 'harness super-tab --tab ${saved['tabId']}';final prompt ='You are an agent in a shared Harness Super Tab. 'diff --git a/desktop/test/machine_profile_test.dart b/desktop/test/machine_profile_test.dartindex e71a98e26..91ef0eed9 100644--- a/desktop/test/machine_profile_test.dart+++ b/desktop/test/machine_profile_test.dart@@ -18,6 +18,12 @@ Swarm tab(}void main() {+ test('Super Tabs stay visible when their terminals run on another computer', () {+ final shared = tab('shared', ['m2'], kind: 'superTab');+ expect(swarmsForMachineProfile([tab('local', ['m1']), shared], 'm1'),+ contains(shared));+ });+test('no profile shows every tab', () {final tabs = [tab('local', ['m1']), tab('remote', ['m2'])];expect(swarmsForMachineProfile(tabs, null).map((s) => s.id), ['local', 'remote']);diff --git a/desktop/test/super_tab_discovery_test.dart b/desktop/test/super_tab_discovery_test.dartnew file mode 100644index 000000000..b2b13a68a--- /dev/null+++ b/desktop/test/super_tab_discovery_test.dart@@ -0,0 +1,330 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore, createApp;+import 'swarm_screen_test.dart' show mount;+import 'support/super_tab_fixture.dart';++class _Catalog {+ final tabs = <Map<String, dynamic>>[+ {'id': '0123456789abcdef01234567', 'name': 'Pilot'},+ ];+ final paths = <String>[];+ final server = ConversationServer();+ String? fail;+ Completer<void>? hold;++ Future<Object?> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ if (Uri.parse(path).path != '/api/super-tabs') {+ return server.request(method, path, body: body);+ }+ expectSync(method, 'GET');+ paths.add(path);+ final after = Uri.parse(path).queryParameters['after'];+ final index = after == null+ ? 0+ : tabs.indexWhere((t) => t['id'] == after) + 1;+ final rows = index < tabs.length ? [Map.of(tabs[index])] : [];+ final next = index + 1 < tabs.length ? tabs[index]['id'] : null;+ if (hold case final waiting?) await waiting.future;+ if (fail == path) throw StateError('Connection lost');+ return {'tabs': rows, 'next': next};+ }+}++class _Connection extends WsConn {+ _Connection(this.catalog)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final _Catalog catalog;+ final calls = <String>[];+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ calls.add(type);+ if (type != 'super_tabs') return {};+ return {+ 'value': await catalog.request(+ payload['method'] as String,+ payload['path'] as String,+ body: payload['body'] as Map<String, dynamic>?,+ ),+ };+ }+}++AppNotifier _computer(_Catalog catalog, MemoryStore store) {+ final connection = _Connection(catalog);+ final app = createApp(+ store: store,+ connected: true,+ connectionForTest: (_) => connection,+ );+ app.machineStates['m']!.localOnly = true;+ app.status = AppStatus.authenticated;+ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ addTearDown(app.dispose);+ return app;+}++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ testWidgets(+ 'another computer opens the discovered tab and its shared messages',+ (tester) async {+ final catalog = _Catalog();+ catalog.server.state['id'] = catalog.tabs.single['id'];+ catalog.server.append('Plan agreed on the first computer');+ final second = _computer(catalog, MemoryStore());+ final previous = second.activeSwarmId;+ await mount(tester, second);+ await second.superTabs.refreshTabs();+ await tester.pump();+ final shared = second.swarms.singleWhere((s) => s.isSuperTab);+ expect(find.byKey(ValueKey('tab-label:${shared.id}')), findsOneWidget);+ expect(second.activeSwarmId, previous);+ await tester.tap(find.byKey(ValueKey('tab-label:${shared.id}')));+ await tester.pumpAndSettle();+ expect(second.activeSwarm.superTabId, catalog.tabs.single['id']);+ expect(+ find.text('Plan agreed on the first computer', findRichText: true),+ findsOneWidget,+ );+ expect(second.allPanes, isEmpty);+ expect(catalog.server.posts, isEmpty);+ await tester.pumpWidget(const SizedBox.shrink());+ await second.superTabs.peek(shared.superTabId!)!.flush();+ second.superTabs.dispose();+ await tester.pump();+ },+ );++ test(+ 'discovery waits for the saved workspace before adding shared tabs',+ () async {+ final store = MemoryStore();+ await PaneLayoutStore(storage: store)+ .saveSwarms([Swarm(id: 'saved', name: 'Existing work')], 'saved');+ final catalog = _Catalog();+ final app = _computer(catalog, store)..status = AppStatus.bootstrapping;+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), isEmpty);+ await app.restorePaneLayoutForTest();+ expect(app.activeSwarm.name, 'Existing work');+ app.status = AppStatus.authenticated;+ await app.superTabs.refreshTabs();+ expect(app.activeSwarm.name, 'Existing work');+ expect(app.swarms.where((s) => s.isSuperTab), hasLength(1));+ },+ );++ test(+ 'two computers discover the same tab without navigation or a local copy',+ () async {+ final catalog = _Catalog();+ final first = _computer(catalog, MemoryStore());+ final second = _computer(catalog, MemoryStore());+ final firstFocus = first.activeSwarmId,+ secondFocus = second.activeSwarmId;+ await Future.wait([+ first.superTabs.refreshTabs(),+ second.superTabs.refreshTabs(),+ ]);+ for (final app in [first, second]) {+ expect(+ app.swarms.where((s) => s.isSuperTab).single.superTabId,+ catalog.tabs.single['id'],+ );+ expect(app.allPanes, isEmpty);+ }+ expect(first.activeSwarmId, firstFocus);+ expect(second.activeSwarmId, secondFocus);+ catalog.tabs.single['name'] = 'Research';+ catalog.tabs.add({'id': '1123456789abcdef01234567', 'name': 'Build'});+ await second.superTabs.refreshTabs();+ expect(second.swarms.where((s) => s.isSuperTab).map((s) => s.name), [+ 'Research',+ 'Build',+ ]);+ await second.superTabs.refreshTabs();+ expect(second.swarms.where((s) => s.isSuperTab), hasLength(2));+ },+ );++ test('closing hides only this computer and survives restart until explicitly opened', () async {+ final catalog = _Catalog();+ final store = MemoryStore();+ final first = _computer(catalog, store);+ final other = _computer(catalog, MemoryStore());+ await first.superTabs.refreshTabs();+ final tab = first.swarms.singleWhere((s) => s.isSuperTab);+ await first.closeSwarm(tab.id);+ // Flush the same visibility intent before simulating a process restart.+ await first.superTabs.setTabVisible(tab.superTabId!, false);+ await first.superTabs.refreshTabs();+ await other.superTabs.refreshTabs();+ expect(first.swarms.where((s) => s.isSuperTab), isEmpty);+ expect(other.swarms.where((s) => s.isSuperTab), hasLength(1));+ final restarted = _computer(catalog, store);+ await restarted.superTabs.refreshTabs();+ expect(restarted.swarms.where((s) => s.isSuperTab), isEmpty);+ restarted.openSuperTab(tab.superTabId!, 'Pilot');+ await restarted.superTabs.setTabVisible(tab.superTabId!, true);+ await restarted.superTabs.refreshTabs();+ expect(restarted.swarms.where((s) => s.isSuperTab), hasLength(1));+ expect(restarted.activeSwarm.superTabId, tab.superTabId);+ });++ test(+ 'a discovery reply racing lead creation cannot duplicate the finished tab',+ () async {+ final catalog = _Catalog();+ final app = _computer(catalog, MemoryStore());+ final draft = app.activeSwarm;+ app.markSuperTabDraft(draft.id);+ await app.superTabs.refreshTabs();+ app.bindSuperTab(draft.id, catalog.tabs.single['id'] as String, 'Pilot');+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), [draft]);+ expect(app.activeSwarm, same(draft));+ },+ );++ test(+ 'a failed later page applies nothing and a retry discovers all pages',+ () async {+ final catalog = _Catalog()+ ..tabs.add({'id': '1123456789abcdef01234567', 'name': 'Build'})+ ..fail = '/api/super-tabs?after=0123456789abcdef01234567';+ final app = _computer(catalog, MemoryStore());+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), isEmpty);+ expect(app.superTabs.discoveryError, isNotNull);+ catalog.fail = null;+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), hasLength(2));+ expect(app.superTabs.discoveryError, isNull);+ },+ );++ test(+ 'an old account response cannot add its tabs after switching accounts',+ () async {+ final hold = Completer<void>();+ final catalog = _Catalog()..hold = hold;+ final seen = <List<SuperTabListing>>[];+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: catalog.request,+ discoveryInterval: Duration.zero,+ onTabs: (rows, _) => seen.add(rows),+ );+ addTearDown(client.dispose);+ client.bind('first');+ final old = client.refreshTabs();+ await Future<void>.delayed(Duration.zero);+ expect(catalog.paths, hasLength(1));+ client.bind('second');+ catalog.hold = null;+ catalog.tabs[0] = {'id': 'second-tab', 'name': 'Second account'};+ await client.refreshTabs();+ hold.complete();+ await old;+ expect(seen, hasLength(1));+ expect(seen.single.single.id, 'second-tab');+ },+ );++ test(+ 'hiding during a pending response wins and does not affect another account',+ () async {+ final catalog = _Catalog();+ final hiddenSnapshots = <Set<String>>[];+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: catalog.request,+ discoveryInterval: Duration.zero,+ onTabs: (_, hidden) => hiddenSnapshots.add(hidden),+ );+ addTearDown(client.dispose);+ client.bind('first');+ final hold = catalog.hold = Completer<void>();+ final reading = client.refreshTabs();+ await client.setTabVisible('0123456789abcdef01234567', false);+ hold.complete();+ await reading;+ expect(hiddenSnapshots.single, {'0123456789abcdef01234567'});+ client.bind('second');+ await client.refreshTabs();+ expect(hiddenSnapshots.last, isEmpty);+ },+ );++ testWidgets('sign-in discovers tabs and retries while the app stays open', (+ tester,+ ) async {+ final catalog = _Catalog()..fail = '/api/super-tabs';+ final seen = <List<SuperTabListing>>[];+ final client = SuperTabClient(+ storage: MemoryStore(),+ transport: catalog.request,+ discoveryInterval: const Duration(seconds: 15),+ onTabs: (rows, _) => seen.add(rows),+ );+ addTearDown(client.dispose);+ client.bind('owner');+ await tester.pump();+ expect(client.discoveryError, isA<StateError>());+ catalog.fail = null;+ await tester.pump(const Duration(seconds: 15));+ await tester.pump();+ expect(catalog.paths, hasLength(2));+ expect(client.discoveryError, isNull);+ expect(seen.single.single.name, 'Pilot');+ client.dispose();+ final count = catalog.paths.length;+ await tester.pump(const Duration(seconds: 30));+ expect(catalog.paths, hasLength(count));+ });++ test(+ 'lead creation defers its own discovery until bound to the form tab',+ () async {+ final catalog = _Catalog();+ final app = _computer(catalog, MemoryStore());+ final id = catalog.tabs.single['id'] as String;+ app.superTabs.deferTabDiscovery(id);+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), isEmpty);+ app.bindSuperTab(app.activeSwarmId, id, 'Pilot');+ await app.superTabs.refreshTabs();+ expect(app.swarms.where((s) => s.isSuperTab), hasLength(1));+ },+ );+}