Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(terminal): watch an agent another app is driving

tony8c60dd596d8f
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index fe3bb457f..e24e472a0 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -64,6 +64,9 @@ interface PendingOutput {
interface ActiveStream {
connId: string
streamId: string
+ /** A stream opened as a WATCHER: it renders, but it never took the control lease and its input is
+ * refused. See the `takeover: false` branch of `open()`. */
+ watching: boolean
agentId: string
engineId: string
placementKey: string
@@ -168,11 +171,35 @@ export class TerminalStreamManager {
}
}
+ /** The frames a stream that does not hold the terminal may still send: they read, ack or end it. */
+ private static readonly WATCH_SAFE_TYPES = [
+ 'terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_resync', 'terminal_close',
+ ]
+
+ /** Whether this frame names a WATCHER's stream — one that renders without holding the terminal. */
+ private isWatching(connId: string, payload: FramePayload): boolean {
+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''
+ if (!streamId) return false
+ const state = this.streams.get(streamId)
+ return state?.connId === connId && state.watching
+ }
+
async handleFrame(connId: string, type: string, payload: FramePayload): Promise<boolean> {
- if (this.deps.readOnly && !['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_resync', 'terminal_close'].includes(type)) {
+ if (this.deps.readOnly && !TerminalStreamManager.WATCH_SAFE_TYPES.includes(type)) {
this.sendError(connId, 'VIEW_ONLY', { requestId: payload.requestId })
return true
}
+ // ⚠️ **One gate, not one per write path.** A watcher shares every other code path with a real
+ // controller, so anything that reaches tmux — input, resize, paste, scroll, an upload — has to
+ // be stopped, and stopping them one by one is how the next write path added gets forgotten.
+ // Same allow-list a read-only deployment uses, for the same reason.
+ if (!TerminalStreamManager.WATCH_SAFE_TYPES.includes(type) && this.isWatching(connId, payload)) {
+ this.sendError(connId, 'VIEW_ONLY', {
+ requestId: payload.requestId,
+ streamId: typeof payload.streamId === 'string' ? payload.streamId : undefined,
+ })
+ return true
+ }
switch (type) {
case 'terminal_capabilities':
this.capabilities(connId, payload.requestId)
@@ -223,6 +250,10 @@ export class TerminalStreamManager {
async handleBinary(connId: string, frame: TerminalBinaryClear): Promise<void> {
if (this.deps.readOnly) return
+ // Every binary kind below writes to the terminal, so a watcher's are dropped outright — see the
+ // gate in `handleFrame`. Silent, like the other drops here: the client already knows it is
+ // read-only (`terminal_ready`) and withholds input itself; this is the backstop.
+ if (this.isWatching(connId, { streamId: frame.streamId })) return
if (frame.kind !== TerminalBinaryKind.input && frame.kind !== TerminalBinaryKind.paste
&& frame.kind !== TerminalBinaryKind.imagePaste && frame.kind !== TerminalBinaryKind.pasteFile) return
const state = this.streams.get(frame.streamId)
@@ -274,6 +305,12 @@ export class TerminalStreamManager {
// though creating an agent is not terminal streaming; this is the message a client already
// asks every machine.
projectFolder: !this.deps.readOnly,
+ // `terminal_open` honours `takeover: false`: never close the incumbent. A terminal nobody
+ // else holds opens as usual; one another client is driving opens READ-ONLY, so the asking
+ // client renders it without taking it (`readOnly` on `terminal_ready`) — see `open()`. A
+ // client has to see this before relying on it: a CLI that predates it ignores the key and
+ // takes the terminal over like any other open, which is the one thing the key is for.
+ noTakeover: !this.deps.readOnly,
},
engines: terminalEngineCapabilities(this.deps.streamingAvailable),
})
@@ -324,10 +361,28 @@ export class TerminalStreamManager {
return
}
const reservedPlacement = terminalPlacementKey(streamRuntime)
+ // `takeover: false` is a client opening a terminal AHEAD of anyone looking at it — the phone's
+ // pager attaching the agents a swipe away from the one on screen. That is a guess, and a guess
+ // must not cost another client the terminal it is working in: refused while anyone else holds
+ // it, and the client asks again, without the key, once a person actually lands there. Absent
+ // (every older client) is the takeover it has always been.
+ const takeover = payload.takeover !== false
await this.withLeaseLock(reservedPlacement, async () => {
+ const incumbents = this.incumbentsFor(session.agentId, reservedPlacement, connId)
+ // Inside the lock, so the answer cannot go stale against an open racing this one for the
+ // same placement.
+ //
+ // ⚠️ **Refusing would have been the wrong answer.** A client that asks not to take over still
+ // wants to SEE the terminal — the phone swiping onto an agent the desktop is driving shows
+ // its output, and only typing is withheld until a person asks for it. So the open succeeds as
+ // a WATCHER: tmux attaches read-only (no control lease, no resize, no input), the incumbent
+ // keeps the terminal, and the client is told which it got by `readOnly` on `terminal_ready`.
+ const watching = !this.deps.readOnly && !takeover && incumbents.length > 0
// A terminal is single-controller. A later client explicitly wins the lease and the incumbent
// receives a targeted close notification; it must not be broadcast to other clients.
- if (!this.deps.readOnly) await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
+ if (!this.deps.readOnly && !watching) {
+ await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
+ }
// Only THIS connection's stream for THIS terminal, not every stream it holds.
//
// It used to be closeConnection(connId), i.e. "opening a terminal ends every other terminal
@@ -338,8 +393,9 @@ export class TerminalStreamManager {
// looked alive, but its session never reached `controlling`, so every keystroke into it was
// dropped in silence.
await this.closeOwnStreamsFor(connId, session.agentId, reservedPlacement)
- if (!this.deps.readOnly) this.controllerByAgent.set(session.agentId, connId)
- if (!this.deps.readOnly) this.controllerByPlacement.set(reservedPlacement, connId)
+ // A watcher never becomes the controller — that is the whole point of it.
+ if (!this.deps.readOnly && !watching) this.controllerByAgent.set(session.agentId, connId)
+ if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(reservedPlacement, connId)
const streamId = randomUUID()
const buffered: Buffer[] = []
let state: ActiveStream | null = null
@@ -353,7 +409,7 @@ export class TerminalStreamManager {
onClose: (reason) => {
if (state) void this.closeStream(state, reason, true)
},
- }, this.deps.readOnly)
+ }, this.deps.readOnly || watching)
} catch {
if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
@@ -369,7 +425,7 @@ export class TerminalStreamManager {
const placementKey = terminalPlacementKey(opened.value.runtime)
const actualController = this.controllerByPlacement.get(placementKey)
- if (!this.deps.readOnly && actualController && actualController !== connId) {
+ if (!this.deps.readOnly && !watching && actualController && actualController !== connId) {
if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
await opened.value.close().catch(() => { /* best effort */ })
@@ -379,7 +435,7 @@ export class TerminalStreamManager {
if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {
this.controllerByPlacement.delete(reservedPlacement)
}
- if (!this.deps.readOnly) this.controllerByPlacement.set(placementKey, connId)
+ if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(placementKey, connId)
const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
// Never compress for the loopback desktop, whatever it asks for: the bytes cross 127.0.0.1,
@@ -391,6 +447,7 @@ export class TerminalStreamManager {
state = {
connId,
streamId,
+ watching,
agentId: session.agentId,
engineId: session.engine,
placementKey,
@@ -431,7 +488,9 @@ export class TerminalStreamManager {
agentId: session.agentId,
engineId: session.engine,
backend: 'tmux',
- readOnly: this.deps.readOnly === true,
+ // True for a watcher too: the client draws output and withholds input, exactly as it does
+ // for an observer's stream. See the `takeover: false` branch above.
+ readOnly: this.deps.readOnly === true || watching,
})) {
await this.closeStream(state, 'backend disconnected', false)
return
@@ -1078,10 +1137,16 @@ export class TerminalStreamManager {
await Promise.all(own.map((state) => this.closeStream(state, 'replaced', false)))
}
- private async closeStreamsForTakeover(agentId: string, placementKey: string, nextConnId: string): Promise<void> {
- const incumbents = [...this.streams.values()].filter((state) =>
+ /// The live streams OTHER connections hold on this terminal — exactly the ones a takeover would
+ /// close, which is what makes it the right question for an open that must not take over.
+ private incumbentsFor(agentId: string, placementKey: string, nextConnId: string): ActiveStream[] {
+ return [...this.streams.values()].filter((state) =>
!state.closing && state.connId !== nextConnId
&& (state.agentId === agentId || state.placementKey === placementKey))
+ }
+
+ private async closeStreamsForTakeover(agentId: string, placementKey: string, nextConnId: string): Promise<void> {
+ const incumbents = this.incumbentsFor(agentId, placementKey, nextConnId)
await Promise.all(incumbents.map((state) => this.closeStream(
state,
'another client connected',
diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dart
index ffce3de91..781163a71 100644
--- a/mobile/lib/phone/agent_swipe.dart
+++ b/mobile/lib/phone/agent_swipe.dart
@@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ScrollCacheExtent;
import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart'
+ show TerminalSessionStatus;
import 'agent_pane_prune.dart';
import 'agent_swipe_list.dart';
@@ -94,11 +96,12 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
/// Recorded rather than recomputed: by the time this page is disposed the list may have moved on,
/// and the panes to close are the ones actually opened, not the ones a fresh list would name.
///
- /// ⚠️ **Attaching ahead of the swipe takes those agents' terminals away from the desktop**, and
- /// they are agents nobody has asked for yet. That was once the reason not to; the phone is the
- /// primary now, and the desktop wins them back the moment it opens one (see
- /// `AppNotifier.warmAgentPane` for what a taken-over warm page does — nothing). What bounds it
- /// is [_keepSet]: a few agents around the one on screen, never a lap of the list.
+ /// ⚠️ **Attaching ahead of the swipe must not cost another app its terminal**: these are agents
+ /// nobody has asked for yet, and the daemon keeps one controller per agent. So a page attached
+ /// ahead of time asks only for a terminal that is FREE (`AppNotifier.warmAgentPane`) — one the
+ /// desktop, or anyone else, is driving stays theirs, and that page simply attaches when it is
+ /// landed on, as every page did before. What the phone already holds is left as it is. What
+ /// bounds the rest is [_keepSet]: a few agents around the one on screen, never a lap of the list.
final Set<AgentRef> _attached = {};
/// Closes every agent outside [_keepSet], a beat after each swipe. Null for a passthrough page,
@@ -478,18 +481,25 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
/// Completes once [agent]'s session has drawn its first keyframe — or after [limit], or as soon
/// as [run] is stale, whichever comes first.
+ ///
+ /// Also once the session is `takenOver`: another app is driving that terminal and the page asked
+ /// not to take it (see `AppNotifier.warmAgentPane`), so there is no keyframe coming and nothing
+ /// for the next ring to wait behind.
Future<void> _awaitRendered(
AgentRef agent,
int run, {
Duration limit = _renderWait,
}) async {
final notifier = widget.notifier;
- bool rendered() =>
- notifier
- .paneOfAgent(agent.machineId, agent.agentId)
- ?.session
- ?.hasRenderedFrame ??
- false;
+ bool rendered() {
+ final session = notifier
+ .paneOfAgent(agent.machineId, agent.agentId)
+ ?.session;
+ if (session == null) return false;
+ return session.hasRenderedFrame ||
+ session.status == TerminalSessionStatus.takenOver;
+ }
+
if (rendered()) return;
final done = Completer<void>();
void check() {
diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dart
index b56620842..72ca4fe81 100644
--- a/mobile/lib/phone/phone_status.dart
+++ b/mobile/lib/phone/phone_status.dart
@@ -114,23 +114,31 @@ PhoneSummary phoneAgentSummary(MachineState machine, Agent agent) {
/// The terminal's own state, for the header over it. No session yet reads as attaching: the
/// page opens before the pane has one.
-PhoneSummary phoneSessionSummary(
- TerminalSession? session,
-) => switch (session?.status) {
- null ||
- TerminalSessionStatus.opening => (label: 'Attaching…', tone: PhoneTone.busy),
- TerminalSessionStatus.resyncing => (
- label: 'Resyncing…',
- tone: PhoneTone.busy,
- ),
- TerminalSessionStatus.controlling => (label: 'Live', tone: PhoneTone.good),
- TerminalSessionStatus.takenOver => (
- label: 'Taken over',
- tone: PhoneTone.attention,
- ),
- TerminalSessionStatus.error => (label: 'Disconnected', tone: PhoneTone.bad),
- TerminalSessionStatus.closed => (label: 'Closed', tone: PhoneTone.quiet),
-};
+PhoneSummary phoneSessionSummary(TerminalSession? session) {
+ // ⚠️ Checked BEFORE the status, because a watcher's status is `controlling` — it holds a live
+ // stream and renders every byte; what it does not hold is the terminal. "Live" would promise a
+ // prompt that ignores typing. See [TerminalSession.watching].
+ if (session != null && session.watching) {
+ return (label: 'Watching', tone: PhoneTone.attention);
+ }
+ return switch (session?.status) {
+ null || TerminalSessionStatus.opening => (
+ label: 'Attaching…',
+ tone: PhoneTone.busy,
+ ),
+ TerminalSessionStatus.resyncing => (
+ label: 'Resyncing…',
+ tone: PhoneTone.busy,
+ ),
+ TerminalSessionStatus.controlling => (label: 'Live', tone: PhoneTone.good),
+ TerminalSessionStatus.takenOver => (
+ label: 'Taken over',
+ tone: PhoneTone.attention,
+ ),
+ TerminalSessionStatus.error => (label: 'Disconnected', tone: PhoneTone.bad),
+ TerminalSessionStatus.closed => (label: 'Closed', tone: PhoneTone.quiet),
+ };
+}
/// The way back into a session this device is not driving, or is no longer
/// driving — and what the button offers to do about it.
@@ -142,13 +150,19 @@ PhoneSummary phoneSessionSummary(
/// The desktop puts the same two words on the same two states, in the tile
/// header it draws (`widgets/terminal_panel.dart`); a phone hides that header
/// and draws its own, which is how the way out went missing here.
-PhoneSummary? phoneReclaimAction(TerminalSession? session) =>
- switch (session?.status) {
- TerminalSessionStatus.takenOver => (
- label: 'Take control',
- tone: PhoneTone.attention,
- ),
- TerminalSessionStatus.error ||
- TerminalSessionStatus.closed => (label: 'Reconnect', tone: PhoneTone.bad),
- _ => null,
- };
+PhoneSummary? phoneReclaimAction(TerminalSession? session) {
+ // A watcher is the ordinary way onto an agent another app is driving: output is already on
+ // screen, and this is the button that asks for the keyboard. See [TerminalSession.watching].
+ if (session != null && session.watching) {
+ return (label: 'Take control', tone: PhoneTone.attention);
+ }
+ return switch (session?.status) {
+ TerminalSessionStatus.takenOver => (
+ label: 'Take control',
+ tone: PhoneTone.attention,
+ ),
+ TerminalSessionStatus.error ||
+ TerminalSessionStatus.closed => (label: 'Reconnect', tone: PhoneTone.bad),
+ _ => null,
+ };
+}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 7ac1cb443..f50cb2eab 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -1012,6 +1012,14 @@ class _TerminalPageState extends State<TerminalPage>
// waited in front of was a mounted terminal with an
// empty buffer: a black rectangle, for as long as the
// keyframe took.
+ //
+ // ⚠️ **A page on a terminal another app holds still
+ // renders.** It attaches as a WATCHER — live output,
+ // no typing (see [TerminalSession.watching]) — so the
+ // keyframe this covers arrives exactly as it does for
+ // any other page, and nothing here needs to know the
+ // difference. The header says who has it and offers
+ // "Take control"; the body is the terminal.
if (session != null && !session.hasRenderedFrame)
const Positioned.fill(child: _Attaching()),
// The mic, Search and New agent, floating in the
@@ -1113,9 +1121,16 @@ class _TerminalPageState extends State<TerminalPage>
if (reclaim != null)
_ReclaimButton(
action: reclaim,
+ // ⚠️ `takeControl` — the press IS the claim. Merely
+ // swiping to this page does not take a terminal
+ // another app is driving; this button is the whole
+ // way in, which is why it sits in the header rather
+ // than in the actions sheet. See
+ // [AppNotifier.selectAgent].
onPressed: () => widget.notifier.selectAgent(
widget.machineId,
widget.agentId,
+ takeControl: true,
),
),
// Null while the agent is not loaded: there is
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index ed0e8e9e2..c14505f09 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -207,6 +207,14 @@ class MachineState {
// person as "the project folder is unavailable, choose another folder", advice about a folder
// they never chose and that has nothing to do with what went wrong.
bool projectFolderAvailable = false;
+ // Whether this machine's CLI honours `takeover: false` on `terminal_open` — open only a terminal
+ // no other app is driving, refused with CONTROL_LEASE_HELD otherwise. See
+ // [TerminalSession.takeover].
+ //
+ // ⚠️ 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 AHEAD of a person on a
+ // machine that does not say this — see [AppNotifier.warmAgentPane].
+ bool terminalNoTakeoverAvailable = false;
// Which engines this machine actually has, as this machine answered it. Kept
// on MachineState rather than globally because that is the whole point: two
// machines on one account hold different engines, and the Docker rig holds
@@ -954,7 +962,14 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String agentId, {
String? swarmId,
- }) => assignAgentToPane(null, machineId, agentId, swarmId: swarmId);
+ bool takeControl = false,
+ }) => assignAgentToPane(
+ null,
+ machineId,
+ agentId,
+ swarmId: swarmId,
+ takeControl: takeControl,
+ );
Future<void> seedSwarm(
String name,
@@ -3996,6 +4011,8 @@ class AppNotifier extends ChangeNotifier {
features is Map && features['mediaPreview'] == true;
machine.projectFolderAvailable =
features is Map && features['projectFolder'] == true;
+ machine.terminalNoTakeoverAvailable =
+ features is Map && features['noTakeover'] == true;
}
Future<void> _readTerminalCapabilities(
@@ -4027,6 +4044,7 @@ class AppNotifier extends ChangeNotifier {
machine.terminalPasteFileAvailable = false;
machine.mediaPreviewAvailable = false;
machine.projectFolderAvailable = false;
+ machine.terminalNoTakeoverAvailable = false;
}
if (!_machineWorkCurrent(machine, revision)) return;
if (machine.agentLoadStatus != AgentLoadStatus.loading &&
@@ -4927,7 +4945,15 @@ class AppNotifier extends ChangeNotifier {
/// that can no longer receive anything. Records what was open so the next
/// `connected` can put it back (`_recoverPendingAgent`).
void _markSessionsUnreachable(MachineState machine, String message) {
- for (final pane in panesFor(machine.machine.machineId)) {
+ // The tile being looked at first. `pendingOfflineAgentId` is ONE slot, filled by the first tile
+ // that qualifies, and `_recoverPendingAgent` SELECTS what is in it — focus, `activeAgentId`
+ // and the right to take the terminal back all go with that. A phone holds several tiles per
+ // machine now (the pager's neighbours, see [warmAgentPane]), and list order says nothing
+ // about which of them a person is reading.
+ final focused = focusedPane;
+ final tiles = panesFor(machine.machine.machineId).toList();
+ if (focused != null && tiles.remove(focused)) tiles.insert(0, focused);
+ for (final pane in tiles) {
final session = pane.session;
if (session == null) continue;
machine.activeAgentId ??= session.agentId;
@@ -4935,7 +4961,11 @@ class AppNotifier extends ChangeNotifier {
// themselves (see `_paneNeedsAttach`) — recording it here would have `_recoverPendingAgent`
// call `selectAgent` on reconnect and silently win it back the moment the connection
// returns, fighting whichever machine holds it now.
- if (session.status != TerminalSessionStatus.takenOver) {
+ //
+ // Nor a warm tile, for the same reason one step removed: nobody ever looked at it, and
+ // selecting it is what would let it take a terminal another app picked up meanwhile. It
+ // comes back with the rest, through `_attachPendingPanes`, as politely as it first opened.
+ if (session.status != TerminalSessionStatus.takenOver && !pane.warm) {
machine.pendingOfflineAgentId ??= session.agentId;
}
// Do not send terminal_close: the adapter is already gone and the
@@ -5111,7 +5141,27 @@ class AppNotifier extends ChangeNotifier {
await selectAgent(machineId, agentId);
}
- Future<void> selectAgent(String machineId, String agentId) async {
+ /// Look at [agentId], opening its terminal if it has none.
+ ///
+ /// ⚠️ **Looking is not taking.** The daemon keeps ONE controller per agent, so every
+ /// `terminal_open` this sends is a claim — and going to an agent another app is driving used to
+ /// be enough to pull the terminal out from under it: swiping past an agent open on the desktop
+ /// took it, every time, for as long as it took to swipe past. Arriving somewhere is not asking
+ /// for it. So this opens POLITELY (see [TerminalSession.takeover]) and a terminal somebody else
+ /// holds stays theirs; the page shows it as taken over, with the way in beside the words.
+ ///
+ /// [takeControl] is that way in, and the only thing that sets it is a person pressing "Take
+ /// control" — see `phoneReclaimAction`. It is the one gesture that means the claim, rather than
+ /// merely arriving where the claim could be made.
+ ///
+ /// A machine whose CLI predates the key cannot be asked politely (it takes over regardless), so
+ /// arriving at one of its agents takes the terminal the way it always did — see
+ /// [MachineState.terminalNoTakeoverAvailable].
+ Future<void> selectAgent(
+ String machineId,
+ String agentId, {
+ bool takeControl = false,
+ }) async {
final existing = paneOfAgent(machineId, agentId);
if (existing != null) {
selectedMachineId = machineId;
@@ -5126,11 +5176,38 @@ class AppNotifier extends ChangeNotifier {
_persistLayout();
}
final terminal = existing.session;
+ if (terminal != null) {
+ // A press STICKS, for every later open this session makes — its own reconnects included.
+ // A person who took this terminal once keeps it through a tunnel dropping; asked politely
+ // again on the way back, they would lose it to whoever picked it up meanwhile.
+ //
+ // Otherwise the tile is merely being looked at, and asks politely from here on. Left alone
+ // while the session already holds the terminal: the flag decides what its NEXT open asks
+ // for, and lowering it mid-stream would mean losing the terminal to a reconnect.
+ if (takeControl) {
+ terminal.takeover = true;
+ } else if (!terminal.holdsTerminal) {
+ terminal.takeover = false;
+ }
+ }
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);
+ await _attachSession(existing, takeControl: takeControl);
+ } else if (takeControl && terminal.watching) {
+ // ⚠️ **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
+ // leave it alone. The press is a request for the KEYBOARD, and the only way to ask for it
+ // is a fresh open that takes the lease. Its retained output stays on screen meanwhile.
+ if (!_canAttachPane(existing)) return;
+ await terminal.reopen(force: true);
+ } else if (terminal.status == TerminalSessionStatus.takenOver) {
+ // Somebody else is driving it. Only the press reopens — see [takeControl]. Arriving here
+ // leaves it exactly as it is, which is what the button in the header is FOR.
+ if (!takeControl || !_canAttachPane(existing)) return;
+ await terminal.reopen();
} else if (terminal.status != TerminalSessionStatus.opening &&
terminal.status != TerminalSessionStatus.controlling &&
terminal.status != TerminalSessionStatus.resyncing) {
@@ -5141,7 +5218,7 @@ class AppNotifier extends ChangeNotifier {
}
return;
}
- await addAgentToSwarm(machineId, agentId);
+ await addAgentToSwarm(machineId, agentId, takeControl: takeControl);
}
/// Opens [agentId]'s stream for a tile nobody is looking at yet — the phone's
@@ -5155,16 +5232,36 @@ class AppNotifier extends ChangeNotifier {
/// is the one thing that marks it, and [selectAgent] is what happens when the
/// guess comes true.
///
- /// A tile already there is left alone — except one holding a dead stream,
- /// which is reopened the way `_attachPendingPanes` would. A stream someone
- /// else took over is NOT reopened from here: that is the tug-of-war
+ /// A tile already there is left alone — except a warm one holding a dead
+ /// stream, which is reopened the way `_attachPendingPanes` would. A stream
+ /// someone else took over is NOT reopened from here: that is the tug-of-war
/// `_paneNeedsAttach` exists to avoid, and a page nobody is looking at has no
/// business starting it.
+ ///
+ /// ⚠️ **Never takes a terminal another app is driving** — like every other
+ /// open the phone makes now (see [selectAgent]); the machine answers only if
+ /// the terminal is free. The tile then sits as `takenOver`, a dead end
+ /// nothing retries, and landing on it changes nothing: only a person pressing
+ /// "Take control" claims a terminal somebody else holds.
+ ///
+ /// ⚠️ **Nothing is opened ahead of a person on an OLDER machine.** A CLI that
+ /// predates the key ignores it and takes the terminal over like any other
+ /// open — so on such a machine this guess would cost the desktop its terminal
+ /// silently, which is the one thing it must never do. Landing on a page there
+ /// still opens, because that is a person arriving, not a guess. See
+ /// [MachineState.terminalNoTakeoverAvailable].
Future<void> warmAgentPane(String machineId, String agentId) async {
if (_disposed) return;
+ if (machineStates[machineId]?.terminalNoTakeoverAvailable != true) return;
final existing = paneOfAgent(machineId, agentId);
if (existing != null) {
- if (_paneNeedsAttach(existing)) await _reattachPane(existing);
+ // Only a tile that is still warm, whose session asks politely. One a
+ // person has looked at reopens WITH a takeover, and that is for the
+ // recovery every tile shares (`_attachPendingPanes`) to decide, never
+ // for a guess about the next swipe.
+ if (existing.warm && _paneNeedsAttach(existing)) {
+ await _reattachPane(existing);
+ }
return;
}
if (!canAddPane || !_canAttachAgent(machineId, agentId)) return;
@@ -5232,6 +5329,7 @@ class AppNotifier extends ChangeNotifier {
String agentId, {
String? swarmId,
PaneSplitRequest? split,
+ bool takeControl = false,
}) async {
final target = swarms
.where((s) => s.id == (swarmId ?? activeSwarmId))
@@ -5347,7 +5445,7 @@ class AppNotifier extends ChangeNotifier {
_stopOfflineRetry(machineId);
notifyListeners();
if (target == activeSwarm || pane.session != null) {
- await _attachSession(pane);
+ await _attachSession(pane, takeControl: takeControl);
}
}
@@ -5356,7 +5454,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, {
+ bool takeControl = false,
+ }) async {
if (_disposed || !allPanes.contains(pane) || pane.session != null) return;
final wantedAgentId = pane.agentId;
if (wantedAgentId == null) return;
@@ -5403,6 +5504,16 @@ class AppNotifier extends ChangeNotifier {
await connection.forceReconnect();
return true;
},
+ // ⚠️ **Opening is not taking.** The only thing that claims a terminal another app is
+ // driving is a person pressing "Take control" ([selectAgent]'s `takeControl`). Everything
+ // else — a warm tile the pager opened ahead of the thumb, a page swiped to, a tile restored
+ // at launch — asks for the terminal only if it is FREE, and is told no otherwise. See
+ // [TerminalSession.takeover].
+ //
+ // A machine whose CLI predates the key ignores it and takes over anyway; nothing is opened
+ // AHEAD of a person there at all (see [warmAgentPane]), so what reaches this line on such a
+ // machine is a tile somebody is looking at.
+ takeover: takeControl,
);
pane.session = terminal;
terminal.addListener(notifyListeners);
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 20fa65fb5..bfd3ff119 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -104,10 +104,41 @@ class TerminalSession extends ChangeNotifier {
required this.sendBinary,
this.onOpenStalled,
this.resyncTimeout = const Duration(seconds: 4),
+ this.takeover = true,
}) {
terminal = _newTerminal();
}
+ /// Whether opening this session may take the terminal away from another app that is driving it.
+ ///
+ /// True is what an open has always been: the daemon keeps one controller per agent, and the
+ /// latest `terminal_open` wins. False is for a session nobody is looking at yet — the phone's
+ /// pager attaching the agents a swipe away (see `AppNotifier.warmAgentPane`) — which asks only
+ /// for a terminal that is FREE, and is answered `CONTROL_LEASE_HELD` while anyone else holds it.
+ ///
+ /// Read by every open this session sends, its own recoveries included, so a polite session never
+ /// turns into a takeover behind a reconnect. The ONLY thing that sets it is a person pressing
+ /// "Take control" (`AppNotifier.selectAgent`'s `takeControl`) — arriving on a page does not, and
+ /// a refusal that arrives after a press asks again, properly — see the `terminal_error` branch of
+ /// [handleFrame].
+ ///
+ /// ⚠️ Only meaningful against a daemon that advertises `noTakeover`: an older one ignores the key
+ /// and takes over regardless. The caller checks — `MachineState.terminalNoTakeoverAvailable`.
+ bool takeover;
+
+ /// What the open now in flight asked for — [takeover] as it was when that `terminal_open` was
+ /// built. The two differ when a person lands on the page while its polite open is still out.
+ bool _openAskedTakeover = true;
+
+ /// Whether the stream this session holds is a WATCHER: it renders the terminal, live, but does
+ /// not hold it — another app does, and the daemon refuses anything this one tries to type (see
+ /// `terminalStreamManager.ts`). Told by `readOnly` on `terminal_ready`.
+ ///
+ /// ⚠️ **This is a normal, useful state, not a failure.** The page shows real output and the
+ /// header offers "Take control"; pressing it is what asks for the terminal itself. Reset by every
+ /// open, so it can never outlive the stream it describes.
+ bool watching = false;
+
late Terminal terminal;
TerminalSessionStatus status = TerminalSessionStatus.closed;
String? streamId;
@@ -188,7 +219,19 @@ class TerminalSession extends ChangeNotifier {
Future<void> _inputSendTail = Future<void>.value();
bool get acceptsInput =>
- status == TerminalSessionStatus.controlling && streamId != null;
+ status == TerminalSessionStatus.controlling &&
+ streamId != null &&
+ // A watcher draws the terminal but never types into it — the daemon would refuse the frame
+ // anyway, and a keystroke that vanishes reads as a broken pane. See [watching].
+ !watching;
+
+ /// Whether this session is the one driving the far terminal right now — the claim [takeover] is
+ /// about, held rather than asked for. A session opening or resyncing is on its way to it and is
+ /// counted, so an open in flight is not lowered to a polite one behind its own back.
+ bool get holdsTerminal =>
+ status == TerminalSessionStatus.controlling ||
+ status == TerminalSessionStatus.opening ||
+ status == TerminalSessionStatus.resyncing;
/// Grok's CLI declares terminal mouse-tracking (so tmux defers wheel bytes to it, same as any
/// alt-buffer program) but doesn't correctly handle wheel reports itself — confirmed live: it
@@ -219,11 +262,17 @@ 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 {
- if (_disposed ||
- status == TerminalSessionStatus.opening ||
- status == TerminalSessionStatus.controlling ||
- status == TerminalSessionStatus.resyncing) {
+ ///
+ /// [force] reopens a stream that is perfectly alive, which is normally the one thing this must
+ /// not do. The case for it is a WATCHER being promoted: it is `controlling` a read-only stream
+ /// and a person has just asked for the keyboard, so the only way to get it is a fresh open that
+ /// takes the lease. See [watching] and `AppNotifier.selectAgent`.
+ Future<void> reopen({bool force = false}) async {
+ if (_disposed) return;
+ if (!force &&
+ (status == TerminalSessionStatus.opening ||
+ status == TerminalSessionStatus.controlling ||
+ status == TerminalSessionStatus.resyncing)) {
return;
}
await _open(
@@ -257,6 +306,7 @@ class TerminalSession extends ChangeNotifier {
_inputSendTail = Future<void>.value();
streamId = null;
linkMode = null;
+ watching = false;
errorCode = null;
errorMessage = null;
_expectedSeq = null;
@@ -306,6 +356,7 @@ class TerminalSession extends ChangeNotifier {
return;
}
+ _openAskedTakeover = takeover;
final openPayload = {
'protocolVersion': protocolVersion,
'requestId': _openRequestId,
@@ -313,6 +364,8 @@ class TerminalSession extends ChangeNotifier {
'cols': cols,
'rows': rows,
'compression': const ['zlib', 'none'],
+ // Only ever sent as `false`: absent is the takeover every daemon understands — see [takeover].
+ if (!takeover) 'takeover': false,
};
var sent = await send('terminal_open', openPayload);
if (!_isCurrent(generation) ||
@@ -436,6 +489,9 @@ class TerminalSession extends ChangeNotifier {
_fail('TERMINAL_READY_INVALID', 'Harness returned no stream id');
return true;
}
+ // The daemon's answer to a polite open on a terminal somebody else holds: it opened, it
+ // renders, and it may not type. See [watching].
+ watching = payload['readOnly'] == true;
_resyncTimer?.cancel();
_resyncTimer = null;
_heartbeat = Timer.periodic(
@@ -560,6 +616,33 @@ class TerminalSession extends ChangeNotifier {
}
return true;
}
+ // A polite open, refused: another app is driving this terminal and this session asked not
+ // to take it from them — see [takeover]. 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 app stayed. `takenOver` is the state that already means "someone else has
+ // it, and only a person gets it back".
+ //
+ // Only for an open that ASKED to be polite. The daemon also answers this code to an
+ // ordinary open that lost a race for the placement, and that one keeps the retry it has
+ // always had, below.
+ if (errorCode == 'CONTROL_LEASE_HELD' && !_openAskedTakeover) {
+ if (takeover) {
+ // Landed on while that open was still out: somebody is looking at this page now, so
+ // it asks again the way a page being read always has.
+ unawaited(
+ _open(
+ initialCols: _measuredViewport?.cols ?? cols,
+ initialRows: _measuredViewport?.rows ?? rows,
+ waitForViewportSize: false,
+ resetRecovery: true,
+ preserveTerminal: true,
+ ),
+ );
+ } else {
+ _heldElsewhere(errorCode);
+ }
+ 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.
@@ -1431,6 +1514,22 @@ class TerminalSession extends ChangeNotifier {
notifyListeners();
}
+ /// A polite open was refused — see [takeover]. The same dead end as a stream that was taken
+ /// over, for the same reason: reopening is a person's call, never this session's.
+ void _heldElsewhere(String code) {
+ if (_disposed) return;
+ _generation++;
+ _cancelTimers();
+ _inputBytes.clear();
+ streamId = null;
+ linkMode = null;
+ status = TerminalSessionStatus.takenOver;
+ errorCode = code;
+ errorMessage = 'Another client controls this terminal.';
+ _abortActiveUpload();
+ notifyListeners();
+ }
+
void _fail(String code, String? message) {
if (_disposed) return;
_generation++;
diff --git a/mobile/lib/widgets/terminal_pane_header.dart b/mobile/lib/widgets/terminal_pane_header.dart
index 85f5baf55..68a682e0d 100644
--- a/mobile/lib/widgets/terminal_pane_header.dart
+++ b/mobile/lib/widgets/terminal_pane_header.dart
@@ -64,14 +64,20 @@ class TerminalPaneHeader extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final color = switch (session.status) {
- TerminalSessionStatus.controlling => AppColors.success,
- TerminalSessionStatus.opening ||
- TerminalSessionStatus.resyncing => AppColors.warning,
- TerminalSessionStatus.takenOver => AppColors.warning,
- TerminalSessionStatus.error => AppColors.danger,
- TerminalSessionStatus.closed => AppColors.mutedStrong,
- };
+ // A WATCHER renders the terminal without holding it (see [TerminalSession.watching]), and its
+ // status is `controlling` — so every switch below has to ask about it FIRST, or it reads as a
+ // pane that takes typing when it does not.
+ final watching = session.watching;
+ final color = watching
+ ? AppColors.warning
+ : switch (session.status) {
+ TerminalSessionStatus.controlling => AppColors.success,
+ TerminalSessionStatus.opening ||
+ TerminalSessionStatus.resyncing => AppColors.warning,
+ TerminalSessionStatus.takenOver => AppColors.warning,
+ TerminalSessionStatus.error => AppColors.danger,
+ TerminalSessionStatus.closed => AppColors.mutedStrong,
+ };
final profile = notifier
.stateOf(session.machineId)
?.agents
@@ -80,6 +86,13 @@ class TerminalPaneHeader extends StatelessWidget {
?.codexHome;
final status =
notice ??
+ (watching
+ ? (
+ label: 'Take control',
+ icon: Icons.lock_outline,
+ detail: 'Read only: another app controls this terminal. Take control moves input ownership to this app.',
+ )
+ : null) ??
switch (session.status) {
TerminalSessionStatus.controlling => null,
TerminalSessionStatus.opening => (
@@ -110,7 +123,8 @@ class TerminalPaneHeader extends StatelessWidget {
final canReconnect =
notice == null &&
!readOnly &&
- (session.status == TerminalSessionStatus.error ||
+ (watching ||
+ session.status == TerminalSessionStatus.error ||
session.status == TerminalSessionStatus.closed ||
session.status == TerminalSessionStatus.takenOver);
final machine = notifier.stateOf(session.machineId);
@@ -192,9 +206,13 @@ class TerminalPaneHeader extends StatelessWidget {
message: status.detail,
child: TextButton(
onPressed: canReconnect
+ // The press is the claim: nothing else takes a
+ // terminal another app holds. See
+ // [AppNotifier.selectAgent].
? () => notifier.selectAgent(
session.machineId,
session.agentId,
+ takeControl: true,
)
: null,
style: TextButton.styleFrom(