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
Merge branch 'app-v2' into main
0xdiego25cb2436135eb6
diff --cc desktop/lib/state/app_state.dartindex df4972424,b83348c73..a28accf4c--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@@ -290,6 -304,20 +304,21 @@@ class AppNotifier extends ChangeNotifiefinal Set<String> _offlineRecoveryInFlight = {};bool _disposed = false;+ // Account and inventory replies belong to the session that requested them.+ // Signing out invalidates them before asynchronous connection cleanup.+ int _authRevision = 0;+ Future<void>? _profileInFlight;+- bool _authWorkCurrent(int revision) => !_disposed && revision == _authRevision;++ bool _authWorkCurrent(int revision) =>++ !_disposed && revision == _authRevision;++ int _invalidateAuthWork() {+ _profileInFlight = null;+ _retryInFlight = null;+ machinesLoading = false;+ return ++_authRevision;+ }+WsPool? _pool;late String _autonomousEnv;String? _lastError;@@@ -330,8 -361,334 +362,334 @@@final Set<String> expandedMachines = {};String? selectedMachineId;- /// The grid, in reading order. At most [maxPanes].- final List<TerminalPane> panes = [];+ /// Swarms own arrangements; a shared pane owns one live terminal controller.+ final List<Swarm> swarms = [Swarm(id: 'swarm-1')];+ String _activeSwarmId = 'swarm-1';+ int _nextSwarmId = 2;+ static const maxSwarms = 24;+ static const maxClosedSwarms = 24;+ final List<ClosedWork> _closedHistory = [];+ int _nextClosedHistoryId = 1;+ List<ClosedWork> get closedHistory =>+ List.unmodifiable(_closedHistory.reversed);+ List<ClosedSwarm> get closedSwarms =>+ List.unmodifiable(_closedHistory.reversed.whereType<ClosedSwarm>());+ bool get canReopenClosedSwarm =>+ _closedHistory.any((entry) => entry is ClosedSwarm) &&+ swarms.length < maxSwarms;+ bool get canReopenLastClosed =>+ _closedHistory.isNotEmpty &&+ canReopenClosed(_closedHistory.last.historyId);++ bool canReopenClosed(String historyId) {+ if (_disposed) return false;+ final entry = _closedHistory+ .where((entry) => entry.historyId == historyId)+ .firstOrNull;+ if (entry is ClosedSwarm) return swarms.length < maxSwarms;+ if (entry is! ClosedAgent) return false;+ final target = swarms.where((s) => s.id == entry.swarmId).firstOrNull;+ return target == null+ ? swarms.length < maxSwarms+ : target.panes.length < maxPanes ||+ target.panes.any(+ (p) =>+ p.machineId == entry.machineId &&+ p.agentId == entry.agentId,+ );+ }++ void _rememberClosed(ClosedWork entry) {+ _closedHistory.add(entry);+ if (_closedHistory.length > maxClosedSwarms) _closedHistory.removeAt(0);+ }++ Swarm get activeSwarm => swarms.firstWhere(+ (s) => s.id == _activeSwarmId,+ orElse: () => swarms.first,+ );+ List<TerminalPane> get panes => activeSwarm.panes;+ Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();+ String get activeSwarmId => activeSwarm.id;++ void newSwarm({String name = 'New swarm'}) {+ if (swarms.length >= maxSwarms) return;+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ final swarm = Swarm(id: 'swarm-${_nextSwarmId++}', name: name);+ swarms.add(swarm);+ selectSwarm(swarm.id);+ }++ void selectSwarm(String id, {bool attachPending = true}) {+ if (!swarms.any((s) => s.id == id)) return;+ _activeSwarmId = id;+ railFocused = false;+ final pane = focusedPane;+ selectedMachineId = pane?.machineId;+ _persistLayout();- _announceFocusToDial();++ _announceAppFocus();+ if (attachPending) {+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine, retryExisting: false);+ }+ }+ notifyListeners();+ }++ /// Navigate to an existing view without opening, retrying or taking control+ /// of a terminal. A shared view prefers the current Swarm, then the requested+ /// owner. Publish the destination and its focus together, preserving layout.+ bool revealAgentView(+ String machineId,+ String agentId, {+ String? preferredSwarmId,+ }) {+ if (_disposed) return false;+ bool contains(Swarm swarm) => swarm.panes.any(+ (p) => p.machineId == machineId && p.agentId == agentId,+ );+ final owner = contains(activeSwarm)+ ? activeSwarm+ : swarms+ .where((s) => s.id == preferredSwarmId && contains(s))+ .firstOrNull ??+ swarms.where(contains).firstOrNull;+ if (owner == null) return false;+ final pane = owner.panes.firstWhere(+ (p) => p.machineId == machineId && p.agentId == agentId,+ );+ if (owner == activeSwarm) {+ focusPane(pane.id, reveal: true);+ return true;+ }+ if (owner.focusedPaneId != pane.id) {+ owner.previousPaneId = owner.focusedPaneId;+ owner.focusedPaneId = pane.id;+ }+ if (owner.zoomedPaneId != null) owner.zoomedPaneId = pane.id;+ _activeSwarmId = owner.id;+ railFocused = false;+ selectedMachineId = machineId;+ _paneFocusRequest++;+ _persistLayout();- _announceFocusToDial();++ _announceAppFocus();+ notifyListeners();+ return true;+ }++ void stepSwarm(int delta) {+ final index = swarms.indexOf(activeSwarm);+ selectSwarm(swarms[(index + delta) % swarms.length].id);+ }++ void renameSwarm(String id, String name) {+ final clean = name.trim();+ if (clean.isEmpty) return;+ final swarm = swarms.where((s) => s.id == id).firstOrNull;+ if (swarm == null) return;+ swarm.name = clean.length > 80 ? clean.substring(0, 80) : clean;+ _persistLayout();+ notifyListeners();+ }++ void reorderSwarm(String id, int destination) {+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ final swarm = swarms.removeAt(index);+ swarms.insert(destination.clamp(0, swarms.length), swarm);+ _persistLayout();+ notifyListeners();+ }++ Future<void> closeSwarm(String id) async {+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ // Held ⌘W must not manufacture and close an endless sequence of blank+ // welcome tabs, evicting the real work from recently closed history.+ if (swarms.length == 1 &&+ swarms.single.panes.isEmpty &&+ swarms.single.name == 'New swarm' &&+ swarms.single.presets.isEmpty) {+ return;+ }+ final removed = swarms.removeAt(index);+ Swarm? replacement;+ if (swarms.isEmpty) {+ replacement = Swarm(id: 'swarm-${_nextSwarmId++}');+ swarms.add(replacement);+ }+ _rememberClosed(+ ClosedSwarm(+ removed,+ historyId: 'closed-${_nextClosedHistoryId++}',+ index: index,+ replacement: replacement,+ ),+ );+ if (_activeSwarmId == id) {+ _activeSwarmId = swarms[index.clamp(0, swarms.length - 1)].id;+ }+ _persistLayout();+ notifyListeners();+ selectedMachineId = focusedPane?.machineId;- _announceFocusToDial();++ _announceAppFocus();+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ for (final pane in removed.panes) {+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);+ }+ }++ void reopenClosedSwarm({String? historyId}) {+ if (_disposed || !canReopenClosedSwarm) return;+ final index = _closedHistory.lastIndexWhere(+ (entry) =>+ entry is ClosedSwarm &&+ (historyId == null || entry.historyId == historyId),+ );+ if (index < 0) return;+ final saved = _closedHistory.removeAt(index) as ClosedSwarm;+ if (swarms.length == 1 && saved.replacesUntouchedWelcome(swarms.single)) {+ swarms.clear();+ }+ final pool = {+ for (final pane in allPanes) (pane.machineId, pane.agentId): pane,+ };+ var id = saved.id;+ while (swarms.any((swarm) => swarm.id == id)) {+ id = 'swarm-${_nextSwarmId++}';+ }+ final restored = Swarm(id: id, name: saved.name)+ ..gridColumns = saved.gridColumns+ ..presets.addAll(saved.presets)+ ..paneSizes.addAll(saved.paneSizes);+ for (final entry in saved.panes) {+ final pane = pool.putIfAbsent(+ (entry.machineId, entry.agentId),+ () => TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )..composerVisible = entry.composerVisible,+ );+ restored.panes.add(pane);+ if (entry.pinnedSlot != null) {+ restored.pinnedSlots[pane.id] = entry.pinnedSlot!;+ }+ }+ int? paneAt(int index) => index >= 0 && index < restored.panes.length+ ? restored.panes[index].id+ : null;+ restored.focusedPaneId =+ paneAt(saved.focus) ?? restored.panes.firstOrNull?.id;+ restored.previousPaneId = paneAt(saved.previousFocus);+ restored.zoomedPaneId = paneAt(saved.zoom);+ swarms.insert(saved.index.clamp(0, swarms.length), restored);+ selectSwarm(restored.id);+ }++ /// Reopen the chosen closure, or the newest closure for Cmd-Shift-T.+ /// Membership is restored synchronously; a slow detach cannot resurrect an+ /// old controller or redirect the destination after a network wait.+ bool reopenClosed({String? historyId}) {+ final id = historyId ?? _closedHistory.lastOrNull?.historyId;+ if (id == null || !canReopenClosed(id)) return false;+ final index = _closedHistory.indexWhere((entry) => entry.historyId == id);+ final saved = _closedHistory[index];+ if (saved is ClosedSwarm) {+ reopenClosedSwarm(historyId: id);+ return true;+ }+ final agent = saved as ClosedAgent;+ _closedHistory.removeAt(index);+ var target = swarms.where((s) => s.id == agent.swarmId).firstOrNull;+ if (target == null) {+ target = Swarm(id: agent.swarmId, name: agent.swarmName);+ swarms.add(target);+ }+ final pane =+ allPanes+ .where(+ (p) =>+ p.machineId == agent.machineId && p.agentId == agent.agentId,+ )+ .firstOrNull ??+ (TerminalPane(+ id: _nextPaneId++,+ machineId: agent.machineId,+ agentId: agent.agentId,+ )..composerVisible = agent.composerVisible);+ if (!target.panes.contains(pane)) {+ final restoreManual =+ agent.manualLayout != null &&+ listEquals(+ target.panes.map((p) => (p.machineId, p.agentId)).toList(),+ agent.remainingAgents,+ ) &&+ (target.panes.length == 1 ||+ listEquals(+ target.manualLayout?.tiles,+ agent.manualLayout!.remove(agent.index)?.tiles,+ ));+ if (restoreManual) {+ target.pinnedSlots.updateAll(+ (_, slot) => slot >= agent.index ? slot + 1 : slot,+ );+ }+ target.panes.insert(agent.index.clamp(0, target.panes.length), pane);+ if (restoreManual) {+ target.savePaneSizes(+ '${target.panes.length}:manual',+ agent.manualLayout!,+ );+ } else if (agent.manualLayout != null) {+ target.paneSizes.remove('${target.panes.length}:manual');+ }+ if (agent.pinnedSlot != null &&+ !target.pinnedSlots.containsValue(agent.pinnedSlot)) {+ target.pinnedSlots[pane.id] = agent.pinnedSlot!;+ }+ }+ if (target.focusedPaneId != pane.id) {+ target.previousPaneId = target.focusedPaneId;+ }+ target.focusedPaneId = pane.id;+ if (agent.zoomed || target.zoomedPaneId != null) {+ target.zoomedPaneId = pane.id;+ }+ _activeSwarmId = target.id;+ _settlePins();+ _paneFocusRequest++;+ selectSwarm(target.id);+ return true;+ }++ /// Capture the destination before any network wait or tab change.+ Future<void> addAgentToSwarm(+ String machineId,+ String agentId, {+ String? swarmId,+ }) => assignAgentToPane(null, machineId, agentId, swarmId: swarmId);++ Future<void> seedSwarm(+ String name,+ List<({String machineId, String agentId})> agents,+ ) async {+ final target = activeSwarm;+ renameSwarm(target.id, name);+ // Each call records membership synchronously, before its attachment waits.+ // A slow/offline host must not hold back the other panes or retarget a tab.+ final attachments = <Future<void>>[];+ for (final agent in agents) {+ attachments.add(+ addAgentToSwarm(agent.machineId, agent.agentId, swarmId: target.id),+ );+ }+ await Future.wait(attachments);+ }/// Which tile the keyboard, the dial and the rail's highlight all mean.///@@@ -659,38 -1108,41 +1109,41 @@@// Re-sending the same agent is safe: the daemon drops it against the dial's// real position (`agentId === this.dialFocus` in cableSession), which is the// only side that can judge, because only it knows where the dial is.- _announceFocusToDial();+ _announceAppFocus();- // Only a real move is worth a rebuild.- if (moved) notifyListeners();+ if (moved) _persistLayout();+ if (moved || reveal) notifyListeners();}- /// Tell the local daemon which agent this window is looking at, so the dial follows it.- ///- /// Said outright rather than left to be inferred. The daemon used to work this out from- /// `terminal_open`, which was equivalent while a window could only show one terminal: every move- /// opened a stream, so opening one meant it had moved.- ///- /// A pane grid breaks that equivalence. Clicking a tile that already holds a live session opens- /// nothing at all, so the dial stayed on whichever agent the last rail click had opened — which is- /// why the rail appeared to work and the panes did not.- ///- /// Fire-and-forget, and only for a tile that has an agent: a machine tile is not somewhere the- /// dial can go.- void _announceFocusToDial() {+ String? _announcedFocusMachineId;++ @visibleForTesting- Future<bool> Function(String machineId, String? agentId)? focusFrameSenderForTest;++ Future<bool> Function(String machineId, String? agentId)?++ focusFrameSenderForTest;++ /// Publish the selected pane to the existing local CLI connection. The CLI+ /// shares this focus with paired devices and the dial; terminal attachments+ /// and operating-system window activation do not define the selected agent.+ void _announceAppFocus() {final pane = focusedPane;- final agentId = pane?.agentId;- if (pane == null || agentId == null) return;- // The EXISTING connection, never `_conn`, which builds one. Opening a socket as a side effect of- // moving a focus ring is the wrong trade in both directions: it dials a machine nobody asked to- // reach, and `_conn` throws outright before the pool exists — which took focusPane down with it,- // so clicking a tile did nothing at all rather than merely failing to reach the dial.- //- // Nothing here is worth failing a click for: no dial attached, no daemon yet, a socket mid- // reconnect — the tile still focuses and the window still works.- final connection = _pool?[pane.machineId];- if (connection == null) return;- unawaited(- connection- .sendTerminalFrame('app_focus', {'agentId': agentId})- .catchError((_) => false),- );+ final machineId = pane?.agentId == null ? null : pane?.machineId;+ final previousMachineId = _announcedFocusMachineId;+ _announcedFocusMachineId = machineId;+ if (previousMachineId != null && previousMachineId != machineId) {+ _sendAppFocus(previousMachineId, null);+ }+ if (machineId != null) _sendAppFocus(machineId, pane!.agentId);+ }++ void _sendAppFocus(String machineId, String? agentId) {+ // Never create a socket just to move focus, and never queue stale focus+ // across a reconnect. The connected callback reasserts the current pane.+ final send = focusFrameSenderForTest;+ final pending = send != null+ ? send(machineId, agentId)- : _pool?[machineId]?.sendTerminalFrame('app_focus', {'agentId': agentId});++ : _pool?[machineId]?.sendTerminalFrame('app_focus', {++ 'agentId': agentId,++ });+ if (pending != null) unawaited(pending.catchError((_) => false));}/// Tell the daemon which agents have a tile on the grid, so the dial can stay@@@ -1523,7 -2067,9 +2068,10 @@@);},);+ if (!_authWorkCurrent(revision)) return;await _finishBootstrapSignedIn();- if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) return;++ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated)++ return;analytics.signedIn();// Restarts the clock even if `_trackAppOpened` already started one: this// person met the login screen, so their wait begins where the launch's@@@ -2113,12 -2682,14 +2684,15 @@@notifyListeners();return;}- if (status == AppStatus.unauthenticated) return;- if (currentUser == null) await _loadProfile();- if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) return;++ if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated)++ return;+ if (currentUser == null) unawaited(_loadProfile());try {await refreshMachines();+ if (!_authWorkCurrent(revision)) return;_lastError = null;} catch (error) {+ if (!_authWorkCurrent(revision)) return;_lastError = 'Could not load machines: $error';_lastErrorRetryable = true;notifyListeners();@@@ -2448,6 -3035,28 +3038,25 @@@Future<void> _loadTerminalCapabilities(MachineState machine,WsConn connection,+ int revision,+ ) {+ final pending = machine.terminalCapabilityLoadInFlight;+ if (pending != null) return pending;+ late final Future<void> load;- load = _readTerminalCapabilities(- machine,- connection,- revision,- ).whenComplete(() {- if (identical(machine.terminalCapabilityLoadInFlight, load)) {- machine.terminalCapabilityLoadInFlight = null;- }- });++ load = _readTerminalCapabilities(machine, connection, revision)++ .whenComplete(() {++ if (identical(machine.terminalCapabilityLoadInFlight, load)) {++ machine.terminalCapabilityLoadInFlight = null;++ }++ });+ machine.terminalCapabilityLoadInFlight = load;+ return load;+ }++ Future<void> _readTerminalCapabilities(+ MachineState machine,+ WsConn connection,+ int revision,) async {try {final result = await connection.request(@@@ -3311,23 -3939,10 +3940,10 @@@notifyListeners();return;}- if (!canAddPane) {- // Full grid: reuse the focused tile rather than refusing. Someone who- // clicked "link required" asked to see it, and a click that did nothing- // at all would read as a broken row.- if (target != null) {- unawaited(_detachSession(target, sendClose: true));- target.machineId = machineId;- target.agentId = null;- _announceAppFocus();- _persistLayout();- notifyListeners();- }- return;- }+ if (!canAddPane) return;final pane = TerminalPane(id: _nextPaneId++, machineId: machineId);panes.add(pane);- focusedPaneId = pane.id;+ focusPane(pane.id);notifyListeners();}@@@ -3399,7 -4053,7 +4054,7 @@@// After _persistLayout, so the daemon has the new tile roster before it is told to move onto it. A// duplicate with the inferred one is free: the daemon drops the second against where the dial// already is.- _announceAppFocus();- if (target == activeSwarm) _announceFocusToDial();++ if (target == activeSwarm) _announceAppFocus();if (machine.nodeOnline == false) {machine.pendingOfflineAgentId = agentId;@@@ -3779,31 -4462,40 +4463,44 @@@}Future<void> closePane(int paneId, {bool persist = true}) async {- final index = panes.indexWhere((pane) => pane.id == paneId);- if (index == -1) return;- final pane = panes.removeAt(index);- // A zoom belongs to a tile, so closing that tile ends it. Left set, the grid- // would try to fill itself with a pane that is no longer in the list and- // draw nothing at all.- if (zoomedPaneId == paneId) zoomedPaneId = null;- if (_previousPaneId == paneId) _previousPaneId = null;- _settlePins();- if (focusedPaneId == paneId) {- focusedPaneId = panes.isEmpty- ? null- : panes[index.clamp(0, panes.length - 1)].id;- _announceAppFocus();+ final pane = panes.where((p) => p.id == paneId).firstOrNull;+ if (pane == null) return;+ if (pane.agentId != null) {+ final machine = stateOf(pane.machineId);+ final agent = machine?.agents+ .where((a) => a.id == pane.agentId)+ .firstOrNull;+ _rememberClosed(+ ClosedAgent(+ pane,+ activeSwarm,+ historyId: 'closed-${_nextClosedHistoryId++}',+ name: agent?.name ?? pane.session?.agentName ?? pane.agentId!,+ machineName: machine?.machine.displayName ?? pane.machineId,+ engine: agent?.engine ?? pane.session?.engineId,+ ),+ );}- await _detachSession(pane, sendClose: true);++ // Only a close that moves the focus is worth telling the daemon about: a++ // background tile going away changes nothing the dial can see.++ final wasFocused = focusedPaneId == paneId;+ activeSwarm.remove(pane);+ _settlePins();if (persist) _persistLayout();+ selectedMachineId = focusedPane?.machineId;- _announceFocusToDial();++ if (wasFocused) _announceAppFocus();notifyListeners();+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);}Future<void> _closeAllPanes({bool persist = true}) async {- final open = panes.toList();- panes.clear();- focusedPaneId = null;+ final open = allPanes.toList();+ for (final swarm in swarms) {+ swarm.panes.clear();+ swarm.focusedPaneId = null;+ swarm.zoomedPaneId = null;+ }+ _announceAppFocus();for (final pane in open) {await _detachSession(pane, sendClose: true);}