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
fix: only a person at this window may take a terminal (#286)
0xken15333806651252
diff --git a/desktop/design/super-terminal-interaction.md b/desktop/design/super-terminal-interaction.mdindex 4ba573323..8e6fe32f3 100644--- a/desktop/design/super-terminal-interaction.md+++ b/desktop/design/super-terminal-interaction.md@@ -168,6 +168,27 @@ current fleet name. An older daemon, or a taker that said nothing, reads asunder its header. Retaking control introduces this app in turn, so the otherside sees this machine's name.+**Only a person at this window may take a terminal.** Every `terminal_open`+this app sends says whether a hand on THIS Mac asked for it (`AttachIntent`):+a click, a key, a menu item, the band's button. Everything else — a tab another+Mac opened arriving over the desk, a reconnect, a machine answering its agent+list, a push about an agent created elsewhere, the dial turning, `harness+remote` handing a session over — opens with `takeover: false` and is answered+as a WATCHER: real output, live, with the terminal left where it was and the+band offering it. Where the machine's CLI is too old to understand that key+(`features.noTakeover` absent) nothing opens by itself at all; the tile says so+and offers "Open here". This is what stops two screens trading one terminal+while somebody is typing in it.++Opening the app is itself a gesture, so the tiles a launch restores may claim+their terminals on their FIRST attach — the window comes back the way it was+left, typing where it was typing, even if another screen picked one of them up+meanwhile. That claim is spent on the attach it pays for and dropped from every+tile a few minutes after launch, so a machine that only comes back in the+afternoon is met by the ordinary rule rather than by a gesture made at+breakfast. Tiles that arrive later — over the desk, from a push — never carry+it.+## CreationCmd-N opens a compact launch menu with inherited arguments:diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex d7a367ec4..94256e99a 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -282,6 +282,15 @@ class MachineState {bool terminalCapabilityLoaded = false;bool terminalCapabilityAvailable = false;String? terminalCapabilityError;++ /// Whether this machine's CLI honours `takeover: false` on `terminal_open` —+ /// open as a watcher rather than closing whoever holds the terminal.+ ///+ /// ⚠️ False is not "opens are polite anyway", it is the opposite: an older+ /// CLI ignores the key and takes the terminal over like any other open. So+ /// nothing may be opened here without a person asking on this window — see+ /// [AppNotifier._attachPendingPanes] and [AttachIntent].+ bool terminalNoTakeoverAvailable = false;// Whether this machine's CLI daemon understands `terminal_paste` (a clipboard paste delivered as// one atomic tmux paste-buffer, not chunked like ordinary keystrokes — see TerminalSession.pasteText).// False for any CLI published before this existed; the panel falls back to the old chunked path.@@ -433,6 +442,17 @@ class _AgentStop {final result = Completer<String?>();}+/// Who asked for a terminal to be opened.+///+/// A terminal has ONE controller and an ordinary `terminal_open` wins it, so+/// every attach has to say whether a person on THIS window asked for it.+/// [person] may take the terminal from whoever holds it; [automatic] never may+/// — it opens as a watcher where the daemon supports that, and does not open at+/// all where it does not. Everything that is not a gesture on this Mac is+/// automatic: a tab another Mac opened arriving over the desk, a reconnect, a+/// machine answering its agent list, a push, the dial turning, a handoff.+enum AttachIntent { person, automatic }+class AppNotifier extends ChangeNotifier {final AuthSession session;@@ -598,6 +618,12 @@ class AppNotifier extends ChangeNotifier {// Update checks do not depend on the daemon or SSO. A signed-out user should// still be able to replace a broken desktop build from the login screen.Timer? _updateCheckTimer;++ /// Ends the window in which a restored tile may still claim its terminal —+ /// see [TerminalPane.claimOnFirstAttach]. Without it a machine that only+ /// came back in the afternoon would be met by a claim made at breakfast.+ Timer? _launchClaimTimer;+ static const launchClaimWindow = Duration(minutes: 5);late final DesktopUpdater _updater = desktopUpdater ?? DesktopUpdater();Future<ManualUpdateCheck>? _manualUpdateCheckInFlight;DesktopUpdateCheck? lastUpdateCheck;@@ -1006,7 +1032,8 @@ class AppNotifier extends ChangeNotifier {_announceAppFocus();if (attachPending) {for (final machine in machineStates.values) {- _attachPendingPanes(machine, retryExisting: false);+ // ⌘] / a tab clicked: a person is arriving at these tiles.+ _attachPendingPanes(machine, retryExisting: false, intent: AttachIntent.person);}}notifyListeners();@@ -1160,7 +1187,8 @@ class AppNotifier extends ChangeNotifier {selectedMachineId = focusedPane?.machineId;_announceAppFocus();for (final machine in machineStates.values) {- _attachPendingPanes(machine);+ // ⌘W closed a tab; the tiles it revealed are a person's.+ _attachPendingPanes(machine, intent: AttachIntent.person);}for (final pane in removed.panes) {if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);@@ -1338,7 +1366,14 @@ class AppNotifier extends ChangeNotifier {String machineId,String agentId, {String? swarmId,- }) => assignAgentToPane(null, machineId, agentId, swarmId: swarmId);+ AttachIntent intent = AttachIntent.person,+ }) => assignAgentToPane(+ null,+ machineId,+ agentId,+ swarmId: swarmId,+ intent: intent,+ );Future<void> seedSwarm(String name,@@ -2760,7 +2795,8 @@ class AppNotifier extends ChangeNotifier {// Every exit below clears the message: a boot superseded by a sign-out/sign-in mid-way (the// `_authWorkCurrent` returns) used to leave "Starting local service…" on a screen nothing would// ever repaint.- await _restorePaneLayout();+ await _restorePaneLayout(claimOnAttach: true);+ _armLaunchClaimExpiry();if (!_authWorkCurrent(revision)) {_bootStatusMessage = null;return;@@ -2965,7 +3001,8 @@ class AppNotifier extends ChangeNotifier {await _restorePaneLayout();if (_disposed) return;for (final machine in machineStates.values) {- _attachPendingPanes(machine);+ // A restore at launch, or a machine re-seated under it.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);}_announceAppFocus();}@@ -5322,7 +5359,8 @@ class AppNotifier extends ChangeNotifier {// Publish discovery immediately. The capability loader attaches waiting// panes when its reply arrives; either response may finish first.if (machine.terminalCapabilityLoadInFlight == null) {- _attachPendingPanes(machine);+ // The machine answered its agent list; nobody asked.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();}notifyListeners();@@ -5365,7 +5403,8 @@ class AppNotifier extends ChangeNotifier {if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;// Order matters: a restored tile for THIS machine claims its agent before// the first-run convenience gets to look, so the two can never both open.- _attachPendingPanes(machine);+ // Same list, the other branch of its reply.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();notifyListeners();}@@ -5398,6 +5437,7 @@ class AppNotifier extends ChangeNotifier {machine.terminalCapabilityLoaded = false;machine.terminalCapabilityAvailable = false;machine.terminalCapabilityError = null;+ machine.terminalNoTakeoverAvailable = false;machine.terminalPasteRawAvailable = false;machine.terminalImagePasteAvailable = false;machine.terminalPasteFileAvailable = false;@@ -5721,6 +5761,8 @@ class AppNotifier extends ChangeNotifier {features is Map && features['pasteFile'] == true;machine.mediaPreviewAvailable =features is Map && features['mediaPreview'] == true;+ machine.terminalNoTakeoverAvailable =+ features is Map && features['noTakeover'] == true;} catch (_) {if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {return;@@ -5736,7 +5778,8 @@ class AppNotifier extends ChangeNotifier {if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;if (machine.agentLoadStatus != AgentLoadStatus.loading &&!machine.agentsRefreshing) {- _attachPendingPanes(machine);+ // Terminal capabilities landed; nobody asked.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();notifyListeners();}@@ -8321,7 +8364,13 @@ class AppNotifier extends ChangeNotifier {(pane) => pane.machineId == machineId && pane.agentId == agentId,);if (!hasPane && selectedMachineId == machineId) {- await selectAgent(machineId, agentId);+ // A machine coming back is not a gesture: the tile opens, but as a+ // watcher where the terminal is already somebody's.+ await addAgentToSwarm(+ machineId,+ agentId,+ intent: AttachIntent.automatic,+ );} else {notifyListeners();}@@ -8416,7 +8465,7 @@ class AppNotifier extends ChangeNotifier {focusPane(tile.id, reveal: true);notifyListeners();_persistLayout();- unawaited(_attachSession(tile));+ unawaited(_attachSession(tile, intent: AttachIntent.automatic));// The old shell: `harness remote` has exited in it, and the tile is no// longer its. Ending it is what makes the switch a move, not a copy.await deleteAgent(fromMachineId, fromAgentId);@@ -8452,6 +8501,9 @@ class AppNotifier extends ChangeNotifier {String machineId,String agentId, {bool fromQuestion = false,+ /// The dial's own opens are [AttachIntent.automatic]; the Store's Resume+ /// button borrows this door and IS a person, so it says so.+ AttachIntent intent = AttachIntent.automatic,}) async {if (_fromDevice(() => revealAgentView(machineId, agentId))) {selectedMachineId = machineId;@@ -8470,7 +8522,12 @@ class AppNotifier extends ChangeNotifier {// there, with the usual capacity message if that tab is full.await _fromDevice(() {newSwarm();- return addAgentToSwarm(machineId, agentId, swarmId: activeSwarmId);+ return addAgentToSwarm(+ machineId,+ agentId,+ swarmId: activeSwarmId,+ intent: intent,+ );});}@@ -8595,12 +8652,22 @@ class AppNotifier extends ChangeNotifier {Future<void> focusAgentFromDevice(String machineId, String agentId) async {final existing = paneOfAgent(machineId, agentId);if (existing == null) {- await _fromDevice(() => addAgentToSwarm(machineId, agentId));+ await _fromDevice(+ () => addAgentToSwarm(+ machineId,+ agentId,+ intent: AttachIntent.automatic,+ ),+ );return;}_fromDevice(() => revealAgentView(machineId, agentId));machineStates[machineId]?.activeAgentId = agentId;- if (existing.session == null) await _attachSession(existing);+ // The dial turning is not a person at THIS Mac: show the terminal, never+ // take it from the window or phone that is driving it.+ if (existing.session == null) {+ await _attachSession(existing, intent: AttachIntent.automatic);+ }}Future<void> selectAgent(String machineId, String agentId) async {@@ -8615,13 +8682,19 @@ class AppNotifier extends ChangeNotifier {// terminal wasn't verified yet, the machine was briefly offline, ...). Nothing else retries a// null session on its own — see `_attachPendingPanes` — so a click here has to.await _attachSession(existing);+ } else if (terminal.watching) {+ if (!_canAttachPane(existing)) return;+ // A person landing on a pane this window is only WATCHING is the one+ // thing that turns it into control — the band's button takes this same+ // road. `force` arms the one takeover that asks for the terminal.+ await terminal.reopen(force: true);} else if (terminal.status != TerminalSessionStatus.opening &&terminal.status != TerminalSessionStatus.controlling &&terminal.status != TerminalSessionStatus.resyncing) {if (!_canAttachPane(existing)) return;// Retry the dead stream in place so its output and view context remain// available until the next keyframe. Healthy panes stay focus-only.- await terminal.reopen();+ await terminal.reopen(force: true);}return;}@@ -8687,6 +8760,11 @@ class AppNotifier extends ChangeNotifier {PaneSplitRequest? split,bool autoTile = false,bool focus = true,+ /// A rail click, a drag, a picker — a person. The device's own doors pass+ /// [AttachIntent.automatic]: they put an agent on screen without anybody+ /// touching this Mac, so the terminal they show must not be taken from+ /// whoever is typing in it.+ AttachIntent intent = AttachIntent.person,}) async {final target = swarms.where((s) => s.id == (swarmId ?? activeSwarmId))@@ -8827,7 +8905,7 @@ class AppNotifier extends ChangeNotifier {_stopOfflineRetry(machineId);notifyListeners();if (target == activeSwarm || pane.session != null) {- await _attachSession(pane);+ await _attachSession(pane, intent: intent);}}@@ -8856,7 +8934,10 @@ class AppNotifier extends ChangeNotifier {/// Separate from [assignAgentToPane] because a restored tile takes this path/// on its own, later, when its machine finally answers — the intent was/// settled at launch, and nothing about the selection should move again then.- Future<void> _attachSession(TerminalPane pane) async {+ Future<void> _attachSession(+ TerminalPane pane, {+ AttachIntent intent = AttachIntent.person,+ }) async {if (_disposed || !allPanes.contains(pane) || pane.session != null) return;final wantedAgentId = pane.agentId;if (wantedAgentId == null) return;@@ -8888,6 +8969,9 @@ class AppNotifier extends ChangeNotifier {agentName: agent.displayName,engineId: agent.engine,client: localClientDescriptor(),+ // Only a person at this window may take the terminal from whoever holds+ // it; everything else opens as a watcher. See [AttachIntent].+ takeover: intent == AttachIntent.person,send: (type, payload) =>_conn(pane.machineId).sendTerminalFrame(type, payload),sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),@@ -9892,7 +9976,8 @@ class AppNotifier extends ChangeNotifier {}_persistLayout();for (final machine in machineStates.values) {- _attachPendingPanes(machine, retryExisting: false);+ // A desk another Mac wrote arriving here.+ _attachPendingPanes(machine, retryExisting: false, intent: AttachIntent.automatic);}_announceAppFocus();notifyListeners();@@ -9930,6 +10015,18 @@ class AppNotifier extends ChangeNotifier {);}+ /// Closes the window in which a restored tile may still claim its terminal,+ /// so a machine that only answers hours later is met by the ordinary rule+ /// rather than by the gesture that opened the app.+ void _armLaunchClaimExpiry() {+ _launchClaimTimer?.cancel();+ _launchClaimTimer = Timer(launchClaimWindow, () {+ for (final pane in allPanes) {+ pane.claimOnFirstAttach = false;+ }+ });+ }+/// Rebuild the grid from disk as INTENT only — the tiles appear immediately,/// each saying which machine it is waiting for, and attach themselves as/// their machines answer.@@ -9937,7 +10034,12 @@ class AppNotifier extends ChangeNotifier {/// The tiles cannot wait for the machines: machines answer in an order this/// side does not decide, a restored grid commonly spans two of them, and one/// being slow or offline must not hold the others blank.- Future<void> _restorePaneLayout() async {+ ///+ /// [claimOnAttach]: this restore is the app opening, so the tiles it brings+ /// back may take their terminals on their first attach — see+ /// [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 {final store = _paneLayout;if (store == null) return;final initialSwarm = activeSwarm;@@ -10018,6 +10120,7 @@ class AppNotifier extends ChangeNotifier {agentId: entry.agentId,)..composerVisible = entry.composerVisible+ ..claimOnFirstAttach = claimOnAttach..pinnedSlot = entry.pinnedSlot,);if (!swarm.panes.contains(pane)) {@@ -10136,7 +10239,11 @@ class AppNotifier extends ChangeNotifier {/// and the machine's terminal protocol has been negotiated — become true at/// different moments, and a machine that goes away and returns has to be able/// to re-arrive at them.- void _attachPendingPanes(MachineState machine, {bool retryExisting = true}) {+ void _attachPendingPanes(+ MachineState machine, {+ bool retryExisting = true,+ required AttachIntent intent,+ }) {final machineId = machine.machine.machineId;for (final pane in allPanes.toList()) {if (!panes.contains(pane) && pane.session == null) continue;@@ -10145,12 +10252,34 @@ class AppNotifier extends ChangeNotifier {// or discard its output while the machine is unavailable.if (!retryExisting && pane.session != null) continue;if (!_paneNeedsAttach(pane)) continue;+ // A tile the app restored when it opened carries the gesture that opened+ // it, once. Everything else attaching here is [AttachIntent.automatic]+ // however this sweep was reached.+ final paneIntent = pane.claimOnFirstAttach+ ? AttachIntent.person+ : intent;+ // Nobody asked for this one, and this machine's CLI cannot open a+ // terminal without taking it from whoever has it: leave the tile as+ // intent (`pane_grid.dart` offers to open it) rather than pulling the+ // keyboard out from under somebody on another screen.+ if (paneIntent == AttachIntent.automatic &&+ !machine.terminalNoTakeoverAvailable) {+ continue;+ }+ // Asked before the claim is spent: a machine that is up but has not+ // verified this agent's terminal yet refuses here, and a claim spent on+ // that refusal would leave the tile watching the terminal it was opened+ // to take, once the agent does come ready.+ if (!_canAttachPane(pane)) continue;+ // Spent on the attach it pays for; a retry of that open is already the+ // ordinary rule, and the session carries the claim from here.+ pane.claimOnFirstAttach = false;// Covers a tile that never attached AND one holding a stream the machine// lost. Only the first used to be covered, and the second is why a// reconnect left every tile but one frozen on "restoring terminal…":// recovery ran off pendingOfflineAgentId, which is a single slot, so it// could only ever promise restoration to one of them.- unawaited(_reattachPane(pane));+ unawaited(_reattachPane(pane, intent: paneIntent));}}@@ -10165,6 +10294,9 @@ class AppNotifier extends ChangeNotifier {if (pane.agentId == null) return false;final session = pane.session;if (session == null) return true;+ // A watcher is a live stream, not a tile waiting on one: reattaching it+ // would ask again for a terminal somebody else is working in.+ if (session.watching) return false;return switch (session.status) {TerminalSessionStatus.error || TerminalSessionStatus.closed => true,_ => false,@@ -10173,13 +10305,16 @@ class AppNotifier extends ChangeNotifier {/// Reopen a dead stream in its existing session, keeping its rendered output./// An already-lost stream needs no close addressed to its previous owner.- Future<void> _reattachPane(TerminalPane pane) async {+ Future<void> _reattachPane(+ TerminalPane pane, {+ AttachIntent intent = AttachIntent.person,+ }) async {if (!_canAttachPane(pane)) return;final session = pane.session;if (session == null) {- await _attachSession(pane);+ await _attachSession(pane, intent: intent);} else {- await session.reopen();+ await session.reopen(force: intent == AttachIntent.person);}}@@ -10200,9 +10335,17 @@ class AppNotifier extends ChangeNotifier {for (final pane in allPanes) {final session = pane.session;if (session == null || session.readOnly) continue;- if (session.status != TerminalSessionStatus.takenOver) continue;+ // A watcher is the same thing from the other side: this window has the+ // output, another client has the terminal. Both come back on a gesture.+ if (session.status != TerminalSessionStatus.takenOver &&+ !session.watching) {+ continue;+ }if (!_canAttachPane(pane)) continue;- reopening.add(session.reopen());+ // `force`: a person is asking, so this open may take the terminal. A+ // plain reopen would inherit the polite claim the session was opened+ // with (see [AttachIntent]) and be refused all over again.+ reopening.add(session.reopen(force: true));}await Future.wait(reopening);}@@ -10495,7 +10638,7 @@ class AppNotifier extends ChangeNotifier {// A pane created before this agent's terminal was verified is still sitting on// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is// already `loaded`, so this push is the only signal that it can attach now.- _attachPendingPanes(machine);+ _attachPendingPanes(machine, intent: AttachIntent.automatic);} else {// A process replacement can briefly publish an agent before its// terminal route is verified. `agent_synced` is a snapshot, not@@ -10526,7 +10669,7 @@ class AppNotifier extends ChangeNotifier {_upsertAgent(machine, agent);// Same reattach as `agent_synced` above — a pane can be waiting on this exact agent// (e.g. one this window's own New Agent dialog just opened) with no session yet.- _attachPendingPanes(machine);+ _attachPendingPanes(machine, intent: AttachIntent.automatic);} catch (_) {unawaited(_loadMachineData(machine, force: true));}@@ -10662,7 +10805,8 @@ class AppNotifier extends ChangeNotifier {/// socket to arrive on — what they exercise is the bookkeeping either side of/// that, which is exactly what a live socket makes hard to reach.@visibleForTesting- Future<void> restorePaneLayoutForTest() => _restorePaneLayout();+ Future<void> restorePaneLayoutForTest({bool claimOnAttach = false}) =>+ _restorePaneLayout(claimOnAttach: claimOnAttach);@visibleForTestingFuture<void> handleMachineEventForTest(@@ -10726,6 +10870,7 @@ class AppNotifier extends ChangeNotifier {_monitorHarnesses.clear();_daemonSupervisionTimer?.cancel();_updateCheckTimer?.cancel();+ _launchClaimTimer?.cancel();_environmentRecheckTimer?.cancel();_stopAllOfflineRetries();_stopAllLinkRetries();diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dartindex 0b1936683..06a66fd99 100644--- a/desktop/lib/state/terminal_pane.dart+++ b/desktop/lib/state/terminal_pane.dart@@ -66,6 +66,13 @@ class TerminalPane {/// carries "this machine has no agents yet".String? agentId;+ /// A tile this window restored when it opened. Opening the app IS the+ /// gesture, so this tile's FIRST attach may claim the terminal even if+ /// another screen is driving it (see `AttachIntent`). Spent on that attach —+ /// a machine that only comes back hours later is not the same arrival — and+ /// dropped wholesale a few minutes after launch either way.+ bool claimOnFirstAttach = false;+TerminalSession? session;SharedHarness? sharedHarness;String? sharedOwnerName;diff --git a/desktop/lib/store/store_harness_actions.dart b/desktop/lib/store/store_harness_actions.dartindex c7f1b3bba..0d78f62e8 100644--- a/desktop/lib/store/store_harness_actions.dart+++ b/desktop/lib/store/store_harness_actions.dart@@ -90,7 +90,13 @@ Future<bool> resumeStoreHarness(}// This path reveals an existing tab first, or attaches a new view to the// existing agent. It never calls agent_create or opens the creation dialog.- await app.openAgentFromDial(target.machineId, target.agent.id);+ // A click on Resume, so this one may take the terminal back; the dial's own+ // opens through this door do not (`AttachIntent`).+ await app.openAgentFromDial(+ target.machineId,+ target.agent.id,+ intent: AttachIntent.person,+ );return true;}diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dartindex 0086d8cfc..fa427c556 100644--- a/desktop/lib/terminal/terminal_session.dart+++ b/desktop/lib/terminal/terminal_session.dart@@ -166,6 +166,37 @@ class TerminalSession extends ChangeNotifier {/// for a viewer that never takes control and so is never anyone's taker.final TerminalClientDescriptor? client;+ /// Whether the next `terminal_open` may TAKE the terminal from whoever holds+ /// it. A terminal has one controller, and an ordinary open wins it — which is+ /// right when a person on THIS window asked for the pane, and wrong for every+ /// other reason a pane attaches: a tab another Mac opened arriving over the+ /// desk, a reconnect, a machine answering its agent list, the dial turning.+ /// Those open with `takeover: false` and are answered as a WATCHER (the+ /// daemon attaches tmux read-only and the person typing keeps the terminal),+ /// or `CONTROL_LEASE_HELD` if the race is lost.+ ///+ /// ⚠️ **An arrival arms ONE open.** Lowered again the moment an open it armed+ /// is answered, because from then on this session HOLDS the lease and its+ /// later opens rest on holding it. Left standing, it would outlive the+ /// gesture: a window reconnecting hours later would take the terminal off+ /// whoever had it by then, with nobody having touched this Mac at all.+ ///+ /// ⚠️ Only meaningful against a daemon that advertises `noTakeover`; an older+ /// one ignores the key and takes over regardless, so the caller checks first+ /// — `MachineState.terminalNoTakeoverAvailable`.+ bool takeover;++ /// What the open now in flight asked for — [takeover] as it was when that+ /// frame was built. The two differ when a person lands on the pane while a+ /// polite open is still out.+ bool _openAskedTakeover = true;++ /// Whether the stream this session holds is a WATCHER: real output, live, but+ /// another client drives it and the daemon refuses anything typed here. Told+ /// by `readOnly` on `terminal_ready`. A normal state, not a failure — the+ /// pane shows the band and its "Take control" button. Reset by every open.+ bool watching = false;+TerminalSession({required this.machineId,required this.agentId,@@ -175,6 +206,7 @@ class TerminalSession extends ChangeNotifier {required this.sendBinary,this.client,this.onOpenStalled,+ this.takeover = true,this.readOnly = false,this.resyncTimeout = const Duration(seconds: 4),DateTime Function()? now,@@ -254,6 +286,7 @@ class TerminalSession extends ChangeNotifier {bool get acceptsInput =>!readOnly &&+ !watching &&status == TerminalSessionStatus.controlling &&streamId != null;@@ -295,10 +328,13 @@ class TerminalSession extends ChangeNotifier {/// Reconnect the same agent without discarding its last usable screen./// Input resumes only after the replacement stream's first keyframe.- Future<void> reopen() async {+ /// [force] is a person asking: it arms one takeover and reopens a stream this+ /// session is merely watching, which is what the band's "Take control" does.+ Future<void> reopen({bool force = false}) async {+ if (force) takeover = true;if (_disposed ||status == TerminalSessionStatus.opening ||- status == TerminalSessionStatus.controlling ||+ (status == TerminalSessionStatus.controlling && !(force && watching)) ||status == TerminalSessionStatus.resyncing) {return;}@@ -333,6 +369,7 @@ class TerminalSession extends ChangeNotifier {_inputSendTail = Future<void>.value();streamId = null;linkMode = null;+ watching = false;errorCode = null;errorMessage = null;takenOverBy = null;@@ -391,7 +428,11 @@ class TerminalSession extends ChangeNotifier {'rows': rows,'compression': const ['zlib', 'none'],if (client != null) 'client': client!.toJson(),+ // Absent is the takeover an open has always been; `false` asks the daemon+ // to leave whoever holds the terminal alone and hand this one a watcher.+ if (!takeover) 'takeover': false,};+ _openAskedTakeover = takeover;var sent = await send('terminal_open', openPayload);if (!_isCurrent(generation) ||status != TerminalSessionStatus.opening ||@@ -505,6 +546,13 @@ class TerminalSession extends ChangeNotifier {_fail('TERMINAL_READY_INVALID', 'Harness returned no stream id');return true;}+ // Which kind of stream came back. A watcher renders the terminal and+ // may not type into it; the band says who has it and offers to ask.+ watching = payload['readOnly'] == true;+ // The claim is spent here: from now on this session holds the lease,+ // and every later open of its own rests on holding it rather than on a+ // gesture nobody has made since. See [takeover].+ if (!watching) takeover = false;_resyncTimer?.cancel();_resyncTimer = null;_heartbeat = Timer.periodic(@@ -634,6 +682,29 @@ class TerminalSession extends ChangeNotifier {}return true;}+ // A polite open, refused: another client is driving this terminal and+ // this open asked not to take it from them. Not a failure, and it must+ // not read as one — `error` is what the notifier's reattach sweep+ // retries, which would ask again for as long as the other client stayed.+ // `takenOver` already means "someone else has it, and only a person+ // gets it back", which is exactly this.+ //+ // Only for an open that ASKED to be polite: the daemon answers the same+ // code to an ordinary open that lost a race, and that one keeps the+ // retry it has always had, below.+ if (errorCode == 'CONTROL_LEASE_HELD' && !_openAskedTakeover) {+ _cancelTimers();+ streamId = null;+ watching = false;+ status = TerminalSessionStatus.takenOver;+ this.errorCode = 'TERMINAL_TAKEN_OVER';+ errorMessage = 'Another client is using this terminal.';+ notifyListeners();+ // Somebody landed on this pane while the polite open was still out:+ // ask again, the way a pane a person is looking at always has.+ if (takeover) unawaited(reopen(force: true));+ return true;+ }// A genuine mid-transfer failure (the daemon couldn't write the clipboard/disk, or the// pty write itself failed) IS treated like a real transport/protocol failure — same as// TERMINAL_PASTE_FAILED already is, since it may mean the pty is in an unknown state.diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex bf446e1f2..78ef34852 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1618,6 +1618,25 @@ class _PaneContent extends StatelessWidget {onClose: close,);}+ // Nothing is attaching, and nothing will: this machine's CLI cannot open a+ // terminal without taking it from whoever has it, so an open here waits for+ // a person rather than happening behind one (`AttachIntent`). A spinner+ // would promise something that is never coming.+ if (!machine.terminalNoTakeoverAvailable) {+ return _PaneStatus(+ title: agentName,+ icon: Icons.terminal,+ message:+ 'Open this harness here. Another screen may be using its terminal; '+ 'opening takes it, because ${machine.machine.displayName} runs an '+ 'older Harness CLI.',+ onClose: single && !swarmMode ? null : close,+ actionLabel: 'Open here',+ onAction: () {+ notifier.selectAgent(pane.machineId, wantedAgentId).ignore();+ },+ );+ }return _PaneStatus(title: agentName,icon: Icons.hourglass_empty,diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex dd0f0ad2f..2ff98dc0d 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -665,7 +665,11 @@ class _TerminalPanelState extends State<TerminalPanel>bool get _inputBlocked =>!widget.readOnly &&widget.notice == null &&- widget.session.status == TerminalSessionStatus.takenOver;+ // A watcher is the same situation seen from the other side: this window+ // has the output but another client has the terminal, and the band's+ // button is how a person here asks for it.+ (widget.session.watching ||+ widget.session.status == TerminalSessionStatus.takenOver);/// Retakes the stream, the same path as the header chip: `selectAgent` on a/// dead pane is `reopen()`, and a repeat while it is already `opening` onlydiff --git a/desktop/test/attach_intent_test.dart b/desktop/test/attach_intent_test.dartnew file mode 100644index 000000000..1325c020b--- /dev/null+++ b/desktop/test/attach_intent_test.dart@@ -0,0 +1,514 @@+// Who may take a terminal: only a person at THIS window.+//+// A terminal has one controller, and an ordinary `terminal_open` wins it. Every+// other reason a pane attaches — a tab another Mac opened arriving over the+// desk, a reconnect, a machine answering its agent list, the dial turning —+// must open as a WATCHER (`takeover: false`) or not at all, so somebody typing+// on another screen keeps what they are typing into.+import 'dart:async';++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/screens/swarm_screen.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/desk_sync.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/ws/ws_conn.dart';++import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';++import 'swarm_state_test.dart' show MemoryStore, createApp;++DeskTab _tab(String id, List<String> agents) => DeskTab(+ id: id,+ name: 'Shared',+ nameIsCustom: true,+ panes: [for (final a in agents) DeskPaneRef(machineId: 'm', agentId: a)],+);++class _Api extends ApiClient {+ _Api() : super(config: AppConfig.dev, session: AuthSession());+ DeskDoc? doc = const DeskDoc(revision: 0, tabs: []);+ Map<String, dynamic>? _json(DeskDoc d) => {+ 'revision': d.revision,+ 'tabs': [for (final t in d.tabs) t.toJson()],+ };+ @override+ Future<Map<String, dynamic>?> desk() async => _json(doc!);+ @override+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {+ doc = DeskDoc(+ revision: doc!.revision + 1,+ tabs: applyDeskOps(doc!.tabs, ops),+ );+ return _json(doc!);+ }+}++class _Conn extends WsConn {+ _Conn()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final opens = <Map<String, dynamic>>[];++ @override+ Future<bool> sendTerminalFrame(+ String type,+ Map<String, dynamic> payload,+ ) async {+ if (type == 'terminal_open') opens.add(payload);+ return true;+ }+}++void main() {+ late _Api api;+ late _Conn conn;+ late AppNotifier app;+ late SwarmProjectStore projects;++ setUp(() {+ api = _Api();+ conn = _Conn();+ app = createApp(connectionForTest: (_) => conn)..api = api;+ projects = SwarmProjectStore();+ });++ /// [noTakeover]: whether this machine's daemon can open a terminal without+ /// taking it from whoever holds it.+ void seedMachine({bool noTakeover = true}) {+ app.stateOf('m')!+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true+ ..terminalNoTakeoverAvailable = noTakeover+ ..agents = [+ const Agent(id: 'a0', name: 'A0', terminalAvailable: true),+ const Agent(id: 'a1', name: 'A1', terminalAvailable: true),+ ];+ }++ Future<void> mount(WidgetTester tester) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ projectStore: projects,+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 200));+ }++ Future<void> finish(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ projects.dispose();+ // The open watchdog and any debounced layout write are armed by the work+ // above; let them fall due on a torn-down tree rather than at teardown,+ // where a pending timer fails the test for a reason nothing here is about.+ await tester.pump(const Duration(seconds: 20));+ }++ /// The other Mac opens [agents] in the shared tab; this window learns by+ /// fetching, as the `desk_changed` push and the poll both do.+ Future<void> deskSays(WidgetTester tester, List<String> agents) async {+ api.doc = DeskDoc(+ revision: api.doc!.revision + 1,+ tabs: [_tab('d1', agents)],+ );+ await app.deskFetchForTest();+ await tester.pump(const Duration(milliseconds: 300));+ }++ testWidgets('a pane the other Mac opened is watched here, never taken', (+ tester,+ ) async {+ seedMachine();+ api.doc = DeskDoc(+ revision: 1,+ tabs: [+ _tab('d1', ['a0']),+ ],+ );+ await app.deskStartForTest();+ await tester.pump(const Duration(milliseconds: 60));+ app.selectSwarm('d1');+ await mount(tester);+ conn.opens.clear();++ await deskSays(tester, ['a0', 'a1']);++ expect(+ app.swarms.firstWhere((s) => s.id == 'd1').panes.map((p) => p.agentId),+ containsAll(['a0', 'a1']),+ reason: 'the tab the other Mac opened is here',+ );+ final opened = conn.opens.where((o) => o['agentId'] == 'a1');+ expect(opened, hasLength(1), reason: 'it still shows the terminal');+ expect(+ opened.single['takeover'],+ isFalse,+ reason: 'but it does not take it from whoever is typing',+ );+ await finish(tester);+ });++ testWidgets('an older daemon cannot be polite, so nothing opens by itself', (+ tester,+ ) async {+ seedMachine(noTakeover: false);+ api.doc = DeskDoc(+ revision: 1,+ tabs: [+ _tab('d1', ['a0']),+ ],+ );+ await app.deskStartForTest();+ await tester.pump(const Duration(milliseconds: 60));+ app.selectSwarm('d1');+ await mount(tester);+ conn.opens.clear();++ await deskSays(tester, ['a0', 'a1']);++ expect(conn.opens, isEmpty, reason: 'every open here would be a takeover');+ // The tile says so, and offers the one way in.+ expect(find.text('Open here'), findsWidgets);+ await finish(tester);+ });++ testWidgets('a person choosing the pane takes the terminal', (tester) async {+ seedMachine(noTakeover: false);+ // Not awaited: the attach waits for the tile to measure itself, which only+ // happens once the tree below is pumped.+ unawaited(app.addAgentToSwarm('m', 'a0'));+ await mount(tester);+ final opened = List<Map<String, dynamic>>.from(conn.opens);+ conn.opens.clear();++ // The tile was put there by a person too, so its own open already claimed+ // the terminal — which is the frame this checks.+ expect(conn.opens, isEmpty, reason: 'nothing left to open');+ expect(+ opened.single.containsKey('takeover'),+ isFalse,+ reason: 'absent is the takeover an open has always been',+ );+ await finish(tester);+ });++ test('a watcher renders but does not type, and a person may ask', () async {+ final sent = <Map<String, dynamic>>[];+ final session = TerminalSession(+ machineId: 'm',+ agentId: 'a0',+ agentName: 'A0',+ engineId: 'codex',+ takeover: false,+ send: (type, payload) async {+ if (type == 'terminal_open') sent.add(payload);+ return true;+ },+ sendBinary: (_) async => true,+ );+ addTearDown(session.dispose);++ await session.open(initialCols: 80, initialRows: 24);+ expect(sent.single['takeover'], isFalse);+ await session.handleFrame('terminal_ready', {+ 'requestId': sent.single['requestId'],+ 'protocolVersion': 3,+ 'streamId': 's1',+ 'agentId': 'a0',+ 'readOnly': true,+ });+ expect(session.watching, isTrue);+ expect(session.acceptsInput, isFalse, reason: 'the daemon would refuse it');+ expect(+ session.takeover,+ isFalse,+ reason: 'watching is not a claim on the terminal',+ );++ // The first keyframe is what makes a stream live; stand in for it, since+ // the band only shows on a pane that is rendering something.+ session.status = TerminalSessionStatus.controlling;++ // The band's button: one takeover, asked for by a person.+ await session.reopen(force: true);+ expect(sent, hasLength(2), reason: 'it asked again');+ expect(+ sent.last.containsKey('takeover'),+ isFalse,+ reason: 'and asked for the terminal itself this time',+ );+ });++ testWidgets('a click takes back every stream, watchers included', (+ tester,+ ) async {+ seedMachine();+ // Two panes this window is only watching: the desk put them here, so+ // neither carries a claim of its own.+ api.doc = DeskDoc(+ revision: 1,+ tabs: [+ _tab('d1', ['a0', 'a1']),+ ],+ );+ await app.deskStartForTest();+ await tester.pump(const Duration(milliseconds: 60));+ app.selectSwarm('d1');+ await mount(tester);+ for (final pane in app.panes) {+ final session = pane.session;+ if (session == null) continue;+ await session.handleFrame('terminal_ready', {+ 'requestId': conn.opens.lastWhere(+ (o) => o['agentId'] == pane.agentId,+ )['requestId'],+ 'protocolVersion': 3,+ 'streamId': 'stream-${pane.agentId}',+ 'agentId': pane.agentId,+ 'readOnly': true,+ });+ session.status = TerminalSessionStatus.controlling;+ }+ expect(app.panes.every((p) => p.session?.watching == true), isTrue);+ conn.opens.clear();++ await app.retakeTakenOverPanes();+ await tester.pump(const Duration(milliseconds: 200));++ expect(conn.opens, hasLength(2), reason: 'both asked again');+ expect(+ conn.opens.any((o) => o.containsKey('takeover')),+ isFalse,+ reason: 'and asked for the terminals themselves',+ );+ await finish(tester);+ });++ group('opening the app is itself the gesture', () {+ /// A layout with two tiles, saved as a previous run would leave it.+ Future<MemoryStore> savedLayout() async {+ final storage = MemoryStore();+ final store = PaneLayoutStore(storage: storage);+ final saved = Swarm(id: 'swarm-1', name: 'Work', nameIsCustom: true)+ ..panes.addAll([+ TerminalPane(id: 1, machineId: 'm', agentId: 'a0'),+ TerminalPane(id: 2, machineId: 'm', agentId: 'a1'),+ ]);+ await store.saveSwarms([saved], 'swarm-1');+ return storage;+ }++ /// The app, opened on that layout, with its machine ready to answer.+ Future<AppNotifier> opened({+ required MemoryStore storage,+ bool noTakeover = true,+ }) async {+ final started = createApp(store: storage, connectionForTest: (_) => conn)+ ..api = api;+ started.stateOf('m')!+ ..nodeOnline = true+ ..terminalCapabilityAvailable = true+ ..terminalNoTakeoverAvailable = noTakeover+ ..agents = [+ const Agent(id: 'a0', name: 'A0', terminalAvailable: true),+ const Agent(id: 'a1', name: 'A1', terminalAvailable: true),+ ];+ await started.restorePaneLayoutForTest(claimOnAttach: true);+ return started;+ }++ /// The machine answering — the sweep that actually attaches a restored+ /// tile, and the same one a reconnect runs later.+ Future<void> machineAnswers(+ WidgetTester tester, {+ String about = 'a0',+ }) async {+ await app.handleEventForTest('m', {+ 'type': 'agent_synced',+ 'payload': {+ 'agent': {+ 'id': about,+ 'name': about.toUpperCase(),+ 'terminal': {'available': true},+ },+ },+ });+ await tester.pump(const Duration(milliseconds: 200));+ }++ testWidgets('every tile it restores takes its terminal back', (+ tester,+ ) async {+ final storage = await savedLayout();+ app.dispose();+ app = await opened(storage: storage);+ await mount(tester);+ conn.opens.clear();++ await machineAnswers(tester);++ expect(conn.opens, hasLength(2), reason: 'both tiles opened');+ expect(+ conn.opens.any((o) => o.containsKey('takeover')),+ isFalse,+ reason: 'and both asked for the terminal itself',+ );+ await finish(tester);+ });++ testWidgets('an older daemon is no obstacle to the app opening', (+ tester,+ ) async {+ final storage = await savedLayout();+ app.dispose();+ app = await opened(storage: storage, noTakeover: false);+ await mount(tester);+ conn.opens.clear();++ await machineAnswers(tester);++ expect(+ conn.opens,+ hasLength(2),+ reason: 'a person opened the app; the polite path is not needed',+ );+ await finish(tester);+ });++ testWidgets('an agent that is not ready yet keeps its tile\'s claim', (+ tester,+ ) async {+ final storage = await savedLayout();+ app.dispose();+ app = await opened(storage: storage);+ // The machine is up, but has not verified this agent's terminal yet:+ // every sweep meanwhile refuses the tile.+ app.stateOf('m')!.agents = [+ const Agent(id: 'a0', name: 'A0'),+ const Agent(id: 'a1', name: 'A1', terminalAvailable: true),+ ];+ await mount(tester);+ conn.opens.clear();+ // A sweep about the OTHER agent, so a0 is still unverified.+ await machineAnswers(tester, about: 'a1');+ expect(+ conn.opens.any((o) => o['agentId'] == 'a0'),+ isFalse,+ reason: 'nothing to attach to yet',+ );++ // It comes ready: the tile still carries the gesture that opened the app.+ app.stateOf('m')!.agents = [+ const Agent(id: 'a0', name: 'A0', terminalAvailable: true),+ const Agent(id: 'a1', name: 'A1', terminalAvailable: true),+ ];+ await machineAnswers(tester);++ final opened0 = conn.opens.where((o) => o['agentId'] == 'a0');+ expect(opened0, hasLength(1));+ expect(+ opened0.single.containsKey('takeover'),+ isFalse,+ reason: 'a refusal must not spend the claim',+ );+ await finish(tester);+ });++ testWidgets('the claim is spent once, not carried into a reconnect', (+ tester,+ ) async {+ final storage = await savedLayout();+ app.dispose();+ app = await opened(storage: storage);+ await mount(tester);+ await machineAnswers(tester);+ expect(+ app.panes.any((p) => p.claimOnFirstAttach),+ isFalse,+ reason: 'spent on the attach it paid for',+ );+ // The daemon answers each claim: from here the session holds the lease,+ // and its own later opens rest on holding it rather than on the launch.+ for (final pane in app.panes) {+ final session = pane.session;+ if (session == null) continue;+ await session.handleFrame('terminal_ready', {+ 'requestId': conn.opens.lastWhere(+ (o) => o['agentId'] == pane.agentId,+ )['requestId'],+ 'protocolVersion': 3,+ 'streamId': 'stream-${pane.agentId}',+ 'agentId': pane.agentId,+ });+ }+ conn.opens.clear();++ // The machine drops and comes back: nobody opened anything this time.+ for (final pane in app.panes) {+ pane.session?.transportLost('Harness reconnected');+ }+ await tester.pump();+ await machineAnswers(tester);++ expect(conn.opens, isNotEmpty, reason: 'it did reattach');+ expect(+ conn.opens.every((o) => o['takeover'] == false),+ isTrue,+ reason: 'reconnecting is not the same arrival: ${conn.opens}',+ );+ await finish(tester);+ });+ });++ test('a polite open that loses says so, and does not ask again', () async {+ final sent = <Map<String, dynamic>>[];+ final session = TerminalSession(+ machineId: 'm',+ agentId: 'a0',+ agentName: 'A0',+ engineId: 'codex',+ takeover: false,+ send: (type, payload) async {+ if (type == 'terminal_open') sent.add(payload);+ return true;+ },+ sendBinary: (_) async => true,+ );+ addTearDown(session.dispose);++ await session.open(initialCols: 80, initialRows: 24);+ await session.handleFrame('terminal_error', {+ 'requestId': sent.single['requestId'],+ 'code': 'CONTROL_LEASE_HELD',+ });+ expect(session.status, TerminalSessionStatus.takenOver);+ expect(+ sent,+ hasLength(1),+ reason: 'retrying would ask for as long as the other client stayed',+ );+ });+}diff --git a/desktop/test/machine_loading_test.dart b/desktop/test/machine_loading_test.dartindex 2a611dc13..7dc8005d0 100644--- a/desktop/test/machine_loading_test.dart+++ b/desktop/test/machine_loading_test.dart@@ -37,6 +37,9 @@ const _capabilities = {'protocolVersion': 3,'backend': 'tmux','available': true,+ // A current daemon: it honours `takeover: false`, which is what lets these+ // panes attach with nobody asking (see `AttachIntent`).+ 'features': {'noTakeover': true},};class DiscoveryConnection extends WsConn {diff --git a/desktop/test/swarm_reconnect_test.dart b/desktop/test/swarm_reconnect_test.dartindex 06fa164d1..63171612f 100644--- a/desktop/test/swarm_reconnect_test.dart+++ b/desktop/test/swarm_reconnect_test.dart@@ -39,7 +39,14 @@ class _ReconnectConnection extends WsConn {},],}- : {'protocolVersion': 3, 'backend': 'tmux', 'available': true};+ : {+ 'protocolVersion': 3,+ 'backend': 'tmux',+ 'available': true,+ // A current daemon — see `AttachIntent`: without `noTakeover` a+ // reconnect may not reopen anything on its own.+ 'features': {'noTakeover': true},+ };@overrideFuture<bool> sendTerminalFrame(String type,diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex b72a6296a..d718bad75 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -339,6 +339,16 @@ class RailRow {/// this app pairs as `'web'`, so it is honoured here.const kAgentsListPayload = {'includeStopped': true};+/// Who asked for a terminal to be opened.+///+/// A terminal has ONE controller and an ordinary `terminal_open` wins it, so+/// every attach has to say whether a person on THIS phone asked for it.+/// [person] may take the terminal from whoever holds it; [automatic] never may+/// — it opens as a watcher where the daemon supports that (`noTakeover`), and+/// does not open at all where it does not. The dial turning, a reconnect, a+/// desk another screen wrote, a push: all automatic.+enum AttachIntent { person, automatic }+class AppNotifier extends ChangeNotifier {final AuthSession session;AppConfig config;@@ -728,7 +738,12 @@ class AppNotifier extends ChangeNotifier {_announceAppFocus();if (attachPending) {for (final machine in machineStates.values) {- _attachPendingPanes(machine, retryExisting: false);+ // A tab the person switched to.+ _attachPendingPanes(+ machine,+ retryExisting: false,+ intent: AttachIntent.person,+ );}}notifyListeners();@@ -876,7 +891,8 @@ class AppNotifier extends ChangeNotifier {selectedMachineId = focusedPane?.machineId;_announceAppFocus();for (final machine in machineStates.values) {- _attachPendingPanes(machine);+ // A tab closed here; the tiles behind it are theirs.+ _attachPendingPanes(machine, intent: AttachIntent.person);}for (final pane in removed.panes) {if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);@@ -3971,7 +3987,8 @@ class AppNotifier extends ChangeNotifier {// Publish discovery immediately. The capability loader attaches waiting// panes when its reply arrives; either response may finish first.if (machine.terminalCapabilityLoadInFlight == null) {- _attachPendingPanes(machine);+ // The machine answered its agent list; nobody asked.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();}notifyListeners();@@ -4017,7 +4034,8 @@ class AppNotifier extends ChangeNotifier {if (!_machineWorkCurrent(machine, revision)) return;// Order matters: a restored tile for THIS machine claims its agent before// the first-run convenience gets to look, so the two can never both open.- _attachPendingPanes(machine);+ // Same list, the other branch of its reply.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();notifyListeners();}@@ -4221,7 +4239,8 @@ class AppNotifier extends ChangeNotifier {if (!_machineWorkCurrent(machine, revision)) return;if (machine.agentLoadStatus != AgentLoadStatus.loading &&!machine.agentsRefreshing) {- _attachPendingPanes(machine);+ // Terminal capabilities landed; nobody asked.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);_autoPickFirstAgent();notifyListeners();}@@ -5408,7 +5427,13 @@ class AppNotifier extends ChangeNotifier {// here would yank their focus back to what they were looking at before, mid-navigation.// The recovered agent still shows normally in the rail; they can click it themselves.if (selectedMachineId == machineId) {- await selectAgent(machineId, agentId);+ // A machine coming back is not somebody picking the phone up: the+ // agent shows again, its terminal stays with whoever holds it.+ await selectAgent(+ machineId,+ agentId,+ intent: AttachIntent.automatic,+ );} else {notifyListeners();}@@ -5466,7 +5491,8 @@ class AppNotifier extends ChangeNotifier {late Future<void> selection;_deviceFocusRevision = focusRevision;try {- selection = selectAgent(machineId, agentId);+ // The WiFi device asked, not a hand on this phone — see [AttachIntent].+ selection = _showAgentFromDevice(machineId, agentId);} finally {_deviceFocusRevision = null;}@@ -5480,7 +5506,27 @@ class AppNotifier extends ChangeNotifier {/// which tile it had walked off. The carousel walks only open panes now, so there is no off-desk/// landing left to place and nothing to replace.Future<void> selectAgentFromDial(String machineId, String agentId) async {- await selectAgent(machineId, agentId);+ // ⚠️ Not `selectAgent`: arriving is a claim, and the dial turning is+ // not a person arriving at THIS phone. The agent comes on screen; its+ // terminal stays with whoever types in it, and the band offers it back.+ await _showAgentFromDevice(machineId, agentId);+ }++ /// Put an agent on screen because a device asked — the dial, the WiFi+ /// device — without taking its terminal. See [AttachIntent].+ Future<void> _showAgentFromDevice(String machineId, String agentId) async {+ final existing = paneOfAgent(machineId, agentId);+ if (existing == null) {+ await selectAgent(machineId, agentId, intent: AttachIntent.automatic);+ return;+ }++ selectedMachineId = machineId;+ machineStates[machineId]?.activeAgentId = agentId;+ focusPane(existing.id);+ if (existing.session == null) {+ await _attachSession(existing, takeControl: false);+ }}/// Open [agentId] on this phone, taking its terminal.@@ -5496,7 +5542,14 @@ class AppNotifier extends ChangeNotifier {////// The one open that stays polite is [warmAgentPane]'s guess about the next swipe, which is/// nobody arriving anywhere. See [_attachSession].- Future<void> selectAgent(String machineId, String agentId) async {+ Future<void> selectAgent(+ String machineId,+ String agentId, {+ /// [AttachIntent.automatic] shows the agent without claiming its+ /// terminal — the road `_showAgentFromDevice` and recovery take.+ AttachIntent intent = AttachIntent.person,+ }) async {+ final person = intent == AttachIntent.person;final existing = paneOfAgent(machineId, agentId);if (existing != null) {selectedMachineId = machineId;@@ -5516,14 +5569,14 @@ class AppNotifier extends ChangeNotifier {// armed is answered (see the `terminal_ready` branch of `TerminalSession`), so a claim// cannot outlive the arrival that made it and come back as a reconnect hours later. Coming// back to the agent raises it again, because that is another arrival.- terminal.takeover = true;+ terminal.takeover = person;}if (terminal == null) {// The pane wanted this agent before `_attachSession` could actually attach it (the agent's// terminal wasn't verified yet, the machine was briefly offline, ...). Nothing else retries a// null session on its own — see `_attachPendingPanes` — so a click here has to.- await _attachSession(existing);- } else if (terminal.watching) {+ await _attachSession(existing, takeControl: person);+ } else if (terminal.watching && person) {// ⚠️ **The one reopen that replaces a perfectly live stream.** A watcher renders the// terminal without holding it (see [TerminalSession.watching]), so by every other measure// here it is healthy — `controlling`, with a stream id — and the branches below would@@ -5546,7 +5599,7 @@ class AppNotifier extends ChangeNotifier {}return;}- await addAgentToSwarm(machineId, agentId, takeControl: true);+ await addAgentToSwarm(machineId, agentId, takeControl: person);}/// Opens [agentId]'s stream for a tile nobody is looking at yet — the phone's@@ -6454,7 +6507,17 @@ class AppNotifier extends ChangeNotifier {/// and the machine's terminal protocol has been negotiated — become true at/// different moments, and a machine that goes away and returns has to be able/// to re-arrive at them.- void _attachPendingPanes(MachineState machine, {bool retryExisting = true}) {+ void _attachPendingPanes(+ MachineState machine, {+ bool retryExisting = true,+ required AttachIntent intent,+ }) {+ // Nobody asked on this phone, and this machine's CLI cannot open a terminal+ // without taking it from whoever has it — so it opens nothing.+ if (intent == AttachIntent.automatic &&+ !machine.terminalNoTakeoverAvailable) {+ return;+ }final machineId = machine.machine.machineId;for (final pane in allPanes.toList()) {if (!panes.contains(pane) && pane.session == null) continue;@@ -6468,7 +6531,7 @@ class AppNotifier extends ChangeNotifier {// reconnect left every tile but one frozen on "restoring terminal…":// recovery ran off pendingOfflineAgentId, which is a single slot, so it// could only ever promise restoration to one of them.- unawaited(_reattachPane(pane));+ unawaited(_reattachPane(pane, intent: intent));}}@@ -6491,12 +6554,19 @@ class AppNotifier extends ChangeNotifier {/// Reopen a dead stream in its existing session, keeping its rendered output./// An already-lost stream needs no close addressed to its previous owner.- Future<void> _reattachPane(TerminalPane pane) async {+ Future<void> _reattachPane(+ TerminalPane pane, {+ AttachIntent intent = AttachIntent.person,+ }) async {if (!_canAttachPane(pane)) return;final session = pane.session;if (session == null) {- await _attachSession(pane);+ await _attachSession(+ pane,+ takeControl: intent == AttachIntent.person,+ );} else {+ if (intent == AttachIntent.person) session.takeover = true;await session.reopen();}}@@ -6686,7 +6756,8 @@ class AppNotifier extends ChangeNotifier {// A pane created before this agent's terminal was verified is still sitting on// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is// already `loaded`, so this push is the only signal that it can attach now.- _attachPendingPanes(machine);+ // A push about an agent synced elsewhere.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);} else {await _removeAgent(machine, agent.id);}@@ -6705,7 +6776,8 @@ class AppNotifier extends ChangeNotifier {_upsertAgent(machine, agent);// Same reattach as `agent_synced` above — a pane can be waiting on this exact agent// (e.g. one this window's own New Agent dialog just opened) with no session yet.- _attachPendingPanes(machine);+ // A push about an agent created elsewhere.+ _attachPendingPanes(machine, intent: AttachIntent.automatic);} catch (_) {unawaited(_loadMachineData(machine, force: true));}