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: add client descriptors to terminal sessions to display specific takeover sources in banners

0xken153a763613839e
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index bfd71b800..dc9e0aacd 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -243,6 +243,8 @@ const COMPUTER_ID_FILE = env.ADAPTER_COMPUTER_ID_FILE
// The machine's display name, mirrored from the backend (`machine_meta` on connect + web renames) by the
// daemon so the separate `harness status` process can print it. Absent = unnamed machine.
const MACHINE_NAME_FILE = join(env.ADAPTER_DATA_DIR, 'machine-name')
+/** Pairing labels that stand in for a name rather than being one (manager.ts `addPaired` callers). */
+const GENERIC_PAIR_LABELS: ReadonlySet<string> = new Set(['harness link', 'browser'])
/** The name a new terminal tile greets with: the machine's display name the backend gave it, else the host's. */
function terminalHintMachineName(): string {
try { return readFileSync(MACHINE_NAME_FILE, 'utf-8').trim() || hostname() } catch { return hostname() }
@@ -1766,6 +1768,15 @@ async function runForeground(session: AuthSession): Promise<void> {
sendTarget: (connId, type, payload) => backend.sendTerminalTo(connId, type, payload),
sendBinaryTarget: (connId, frame) => backend.sendTerminalBinaryTo(connId, frame),
isLoopback: isLocalClientId,
+ // For a client that did not introduce itself on `terminal_open` (an older build). A loopback
+ // window can only be this computer's desktop; a paired peer is named by its pairing label unless
+ // that label is one of the placeholders pairing hands out — those name nothing.
+ describeClient: (connId) => {
+ if (isLocalClientId(connId)) return { kind: 'desktop', name: terminalHintMachineName() }
+ const label = backend.e2ee.sessionLabel(connId)
+ if (!label || GENERIC_PAIR_LABELS.has(label)) return null
+ return { kind: backend.e2ee.sessionRole(connId) === 'device' ? 'device' : 'web', name: label }
+ },
streamingAvailable: tmuxBackend != null,
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
})
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index a65eaab96..9fb16a39b 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -156,6 +156,11 @@ export class E2eeManager {
hasSession(connId: string): boolean { return this.sessions.has(connId) }
sessionIdentity(connId: string): string | null { return this.sessions.get(connId)?.webIdentityPub ?? null }
sessionRole(connId: string): C.PairRole | null { return this.sessions.get(connId)?.role ?? null }
+ /** The label this connection's identity was paired under, or null for a session with none on file. */
+ sessionLabel(connId: string): string | null {
+ const pub = this.sessions.get(connId)?.webIdentityPub
+ return pub ? this.store.pairedLabel(pub) : null
+ }
deviceConnected(): boolean { return [...this.sessions.values()].some((s) => s.role === 'device') }
dropSessionsByRole(role: C.PairRole, preserve: (connId: string) => boolean = () => false): void {
for (const [connId, s] of [...this.sessions.entries()]) {
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index a1cf7de99..e185f37e3 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -101,6 +101,10 @@ export class E2eeStore {
return this.paired.get(identityPubB64)?.role ?? null
}
+ pairedLabel(identityPubB64: string): string | null {
+ return this.paired.get(identityPubB64)?.label ?? null
+ }
+
addPaired(identityPubB64: string, label: string, at: number, role: PairRole = 'web'): void {
this.paired.set(identityPubB64, { identityPub: identityPubB64, label, pairedAt: at, role })
writeSecure(PAIRED_FILE, [...this.paired.values()])
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index d83ac1b38..19adaa437 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ENGINES } from '../engines/types.js'
import type { RegisteredSession } from './registry.js'
-import { TerminalStreamManager, terminalEngineCapabilities, UPLOAD_CHUNK_BYTES } from './terminalStreamManager.js'
+import { TerminalStreamManager, clientDescriptorFrom, terminalEngineCapabilities, UPLOAD_CHUNK_BYTES } from './terminalStreamManager.js'
import {
TERMINAL_ACTION_SUCCEEDED,
terminalActionPossiblyExecuted,
@@ -74,7 +74,7 @@ describe('TerminalStreamManager', () => {
let outputBeforeOpen: Uint8Array | null
let terminals: TerminalBackendCoordinator
- const newManager = (extra: { isLoopback?: (connId: string) => boolean } = {}): TerminalStreamManager =>
+ const newManager = (extra: Partial<ConstructorParameters<typeof TerminalStreamManager>[0]> = {}): TerminalStreamManager =>
new TerminalStreamManager({
terminals,
resolveAgent: (id) => agents.get(id),
@@ -591,6 +591,57 @@ describe('TerminalStreamManager', () => {
&& frame.payload.reason === 'heartbeat timeout')).toBe(true)
})
+ // The incumbent's banner says WHO took over, so the close it gets carries what the winner
+ // declared on open — verbatim through a relay, since the daemon never learns a peer's name.
+ it('names the taker on the close when the winner introduced itself', async () => {
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ })
+ await manager.handleFrame('web-2', 'terminal_open', {
+ requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ client: { kind: 'desktop', name: ' Mac mini ', machineId: 'ab12ab12ab12ab12' },
+ })
+ const closed = sent.find((frame) => frame.connId === 'web-1' && frame.type === 'terminal_closed')
+ expect(closed?.payload).toMatchObject({
+ code: 'TERMINAL_TAKEN_OVER',
+ takenBy: { kind: 'desktop', name: 'Mac mini', machineId: 'ab12ab12ab12ab12' },
+ })
+ })
+
+ it('falls back to what the daemon can say about a silent winner, and says nothing over a bad claim', async () => {
+ manager = newManager({
+ describeClient: (connId) => connId === 'local-2' ? { kind: 'desktop', name: 'This Mac' } : null,
+ })
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ })
+ await manager.handleFrame('local-2', 'terminal_open', {
+ requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ })
+ expect(sent.find((frame) => frame.connId === 'web-1' && frame.type === 'terminal_closed')?.payload.takenBy)
+ .toEqual({ kind: 'desktop', name: 'This Mac' })
+ // A claim the daemon will not repeat: a kind with spaces, or a name that is not a name.
+ await manager.handleFrame('web-3', 'terminal_open', {
+ requestId: 'open-3', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ client: { kind: 'not a kind', name: 'x'.repeat(500) },
+ })
+ const closed = sent.find((frame) => frame.connId === 'local-2' && frame.type === 'terminal_closed')
+ expect(closed?.payload.code).toBe('TERMINAL_TAKEN_OVER')
+ expect(closed?.payload).not.toHaveProperty('takenBy')
+ expect(sent.findLast((frame) => frame.type === 'terminal_ready')?.connId).toBe('web-3')
+ })
+
+ it('reads a client descriptor strictly', () => {
+ expect(clientDescriptorFrom({ kind: 'phone', name: 'Hieu\u2019s iPhone' })).toEqual({ kind: 'phone', name: 'Hieu\u2019s iPhone' })
+ expect(clientDescriptorFrom({ kind: 'desktop', name: 'a\u0000b', machineId: 'ab12ab12ab12ab12' }))
+ .toEqual({ kind: 'desktop', name: 'a b', machineId: 'ab12ab12ab12ab12' })
+ expect(clientDescriptorFrom({ kind: 'desktop', name: 'Mac', machineId: '../etc' })).toBeUndefined()
+ expect(clientDescriptorFrom({ kind: 'Desktop', name: 'Mac' })).toBeUndefined()
+ expect(clientDescriptorFrom({ kind: 'desktop', name: ' ' })).toBeUndefined()
+ expect(clientDescriptorFrom('Mac')).toBeUndefined()
+ expect(clientDescriptorFrom(undefined)).toBeUndefined()
+ })
+
it('takes over a second agent alias that resolves to the same tmux pane', async () => {
agents.set('agent-alias', session('claude', 'agent-alias'))
await manager.handleFrame('web-1', 'terminal_open', {
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index fe3bb457f..a3ac35d5e 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -43,6 +43,37 @@ interface PendingUpload {
type FramePayload = Record<string, unknown>
+/**
+ * Who a terminal client says it is, from `terminal_open`'s optional `client` — so the incumbent it
+ * displaces can be told WHO took control ("Mac mini took control of this terminal") rather than
+ * "another app". Self-declared and trusted as such: every client on a machine is the same account's,
+ * and the daemon could not do better on its own (a local window is `local:<uuid>`, a relayed
+ * desktop's E2EE label is the literal 'harness link', a phone's is 'browser'). `machineId` is the
+ * desktop's own machine in the fleet, so the receiver can show that machine's CURRENT name.
+ */
+export interface TerminalClientDescriptor {
+ kind: string
+ name: string
+ machineId?: string
+}
+
+const CLIENT_KIND_RE = /^[a-z]{1,16}$/
+const CLIENT_MACHINE_ID_RE = /^[a-f0-9]{16,64}$/
+const CLIENT_NAME_MAX = 64
+
+/** The declared client, or undefined for a client that said nothing or said it badly — never an error. */
+export function clientDescriptorFrom(raw: unknown): TerminalClientDescriptor | undefined {
+ if (!raw || typeof raw !== 'object') return undefined
+ const { kind, name, machineId } = raw as Record<string, unknown>
+ if (typeof kind !== 'string' || !CLIENT_KIND_RE.test(kind)) return undefined
+ if (typeof name !== 'string') return undefined
+ // eslint-disable-next-line no-control-regex
+ const cleanName = name.replace(/[\u0000-\u001f\u007f]/g, ' ').trim()
+ if (!cleanName || cleanName.length > CLIENT_NAME_MAX) return undefined
+ if (machineId !== undefined && (typeof machineId !== 'string' || !CLIENT_MACHINE_ID_RE.test(machineId))) return undefined
+ return { kind, name: cleanName, ...(machineId ? { machineId } : {}) }
+}
+
const PROTOCOL_VERSION = 3
const HEARTBEAT_TIMEOUT_MS = 30_000
const SYNC_INTERVAL_MS = 5_000
@@ -63,6 +94,8 @@ interface PendingOutput {
interface ActiveStream {
connId: string
+ /** What the client declared on open, or what `describeClient` could tell; absent when neither knew. */
+ client?: TerminalClientDescriptor
streamId: string
agentId: string
engineId: string
@@ -106,6 +139,12 @@ export interface TerminalStreamManagerDeps {
sendBinaryTarget: (connId: string, frame: TerminalBinaryClear) => boolean
/** Whether this connection is the desktop app on THIS computer's loopback (never the cloud). */
isLoopback?: (connId: string) => boolean
+ /**
+ * A name for a connection that declared none on `terminal_open` (an older client): the daemon's
+ * own machine name for a loopback window, a paired peer's label when it is a real one. Null when
+ * nothing better than "another app" is known.
+ */
+ describeClient?: (connId: string) => TerminalClientDescriptor | null
streamingAvailable: boolean
now?: () => number
diagnostic?: (event: string, fields: Record<string, unknown>) => void
@@ -324,10 +363,14 @@ export class TerminalStreamManager {
return
}
const reservedPlacement = terminalPlacementKey(streamRuntime)
+ // The fallback is read as strictly as a claim: a machine name the backend handed out is not
+ // this module's to trust with the wire shape either.
+ const client = clientDescriptorFrom(payload.client) ?? clientDescriptorFrom(this.deps.describeClient?.(connId))
await this.withLeaseLock(reservedPlacement, async () => {
// 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)
+ // receives a targeted close notification; it must not be broadcast to other clients. The
+ // notification names the winner when it can (`takenBy`), so the incumbent's banner can too.
+ if (!this.deps.readOnly) await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId, client)
// 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
@@ -390,6 +433,7 @@ export class TerminalStreamManager {
const wantsZlib = requestedCompression.includes('zlib') && !this.deps.isLoopback?.(connId)
state = {
connId,
+ ...(client ? { client } : {}),
streamId,
agentId: session.agentId,
engineId: session.engine,
@@ -1078,7 +1122,12 @@ 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> {
+ private async closeStreamsForTakeover(
+ agentId: string,
+ placementKey: string,
+ nextConnId: string,
+ takenBy?: TerminalClientDescriptor,
+ ): Promise<void> {
const incumbents = [...this.streams.values()].filter((state) =>
!state.closing && state.connId !== nextConnId
&& (state.agentId === agentId || state.placementKey === placementKey))
@@ -1087,6 +1136,7 @@ export class TerminalStreamManager {
'another client connected',
true,
'TERMINAL_TAKEN_OVER',
+ takenBy,
)))
}
@@ -1095,12 +1145,14 @@ export class TerminalStreamManager {
reason: string,
notify: boolean,
code?: string,
+ takenBy?: TerminalClientDescriptor,
): Promise<void> {
if (state.closing) return
state.closing = true
if (state.pausedAt != null) state.pausedMs += Math.max(0, this.now() - state.pausedAt)
this.diagnostic(state, 'closed', {
reason,
+ ...(takenBy ? { takenBy: takenBy.name } : {}),
lifetimeMs: Math.max(0, this.now() - state.openedAt),
outputFrames: state.outputFrames,
outputPlainBytes: state.outputPlainBytes,
@@ -1124,6 +1176,7 @@ export class TerminalStreamManager {
streamId: state.streamId,
reason,
...(code ? { code } : {}),
+ ...(takenBy ? { takenBy } : {}),
})
}
diff --git a/desktop/design/super-terminal-interaction.md b/desktop/design/super-terminal-interaction.md
index 62dacceeb..442021e20 100644
--- a/desktop/design/super-terminal-interaction.md
+++ b/desktop/design/super-terminal-interaction.md
@@ -155,6 +155,18 @@ clipboard content sends no input to a shell. Clipboard read errors leave the
session usable and offer a retry. Older daemons keep bracketed paste, and
remote agents retain their image-upload path.
+A terminal has one controller. When another client opens the same agent, the
+displaced pane keeps its last screen, read only, under a band that says who:
+"Mac mini took control of this terminal", with Take control (or ⏎) as the
+way back. The name comes from the taker's own introduction on `terminal_open`
+(`client: {kind, name, machineId}` — a desktop names its machine in the fleet,
+a phone its device name), which the daemon repeats on the incumbent's
+`terminal_closed` as `takenBy`; a machine this app knows is shown by its
+current fleet name. An older daemon, or a taker that said nothing, reads as
+"Another app took control of this terminal". The phone draws the same line
+under its header. Retaking control introduces this app in turn, so the other
+side sees this machine's name.
+
## Creation
Cmd-N opens a compact launch menu with inherited arguments:
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 40d376dce..c10af5f93 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -8028,6 +8028,26 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// How this window introduces itself on `terminal_open`, so a pane it
+ /// displaces elsewhere can say "(this Mac) took control": this computer's
+ /// machine in the fleet, by id and current name, else the hostname. A viewer
+ /// (read-only) never takes control and so declares nothing.
+ TerminalClientDescriptor? localClientDescriptor() {
+ if (viewer != null) return null;
+ final local = machineStates.values
+ .where((state) => state.isLocalMachine)
+ .firstOrNull
+ ?.machine;
+ final name = local?.displayName ?? localHostnameOrNull() ?? 'Desktop';
+ return TerminalClientDescriptor(
+ kind: 'desktop',
+ name: name.length > TerminalClientDescriptor.nameMax
+ ? name.substring(0, TerminalClientDescriptor.nameMax)
+ : name,
+ machineId: local?.machineId,
+ );
+ }
+
/// Open the stream for a tile that already knows what it wants.
///
/// Separate from [assignAgentToPane] because a restored tile takes this path
@@ -8064,6 +8084,7 @@ class AppNotifier extends ChangeNotifier {
agentId: agent.id,
agentName: agent.displayName,
engineId: agent.engine,
+ client: localClientDescriptor(),
send: (type, payload) =>
_conn(pane.machineId).sendTerminalFrame(type, payload),
sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index c611f7559..06a57f7c4 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -26,6 +26,67 @@ enum TerminalSessionStatus {
error,
}
+/// Who a terminal client is, as it says on `terminal_open` (`client`) and as
+/// the daemon repeats to the client it displaces (`terminal_closed.takenBy`) —
+/// so the banner can say "Mac mini took control" rather than "another app".
+/// Self-declared: every client of a machine is the same account's, and the
+/// daemon has no better name for a relayed desktop or a phone. [machineId] is
+/// a desktop's own machine in the fleet, so the receiver can show that
+/// machine's current name over the one declared.
+class TerminalClientDescriptor {
+ const TerminalClientDescriptor({
+ required this.kind,
+ required this.name,
+ this.machineId,
+ });
+
+ /// `desktop`, `phone`, … — one lower-case word.
+ final String kind;
+ final String name;
+ final String? machineId;
+
+ static const nameMax = 64;
+
+ Map<String, dynamic> toJson() => {
+ 'kind': kind,
+ 'name': name,
+ if (machineId != null) 'machineId': machineId,
+ };
+
+ /// The wire shape, or null for anything else — a daemon that predates the
+ /// field sends nothing, and a malformed one is treated the same.
+ static TerminalClientDescriptor? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final kind = raw['kind'];
+ final name = raw['name'];
+ final machineId = raw['machineId'];
+ if (kind is! String || !RegExp(r'^[a-z]{1,16}$').hasMatch(kind)) {
+ return null;
+ }
+ if (name is! String) return null;
+ final clean = name.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
+ if (clean.isEmpty || clean.length > nameMax) return null;
+ if (machineId != null &&
+ (machineId is! String ||
+ !RegExp(r'^[a-f0-9]{16,64}$').hasMatch(machineId))) {
+ return null;
+ }
+ return TerminalClientDescriptor(
+ kind: kind,
+ name: clean,
+ machineId: machineId as String?,
+ );
+ }
+
+ /// The name to show: the fleet's current name for [machineId] when the
+ /// caller knows one, else the name the client declared.
+ String label(String? Function(String machineId) resolveMachine) {
+ final id = machineId;
+ final fleet = id == null ? null : resolveMachine(id)?.trim();
+ return fleet == null || fleet.isEmpty ? name : fleet;
+ }
+}
+
/// Transient progress for an in-flight [TerminalSession.pasteImage]/[TerminalSession.pasteFile]
/// chunked upload. `bytesWritten` reflects the daemon's own per-chunk ACKs, not bytes merely handed
/// to the local socket.
@@ -101,6 +162,10 @@ class TerminalSession extends ChangeNotifier {
/// of "attaching" instead of a hang the user has to notice and manually retry.
final Future<void> Function()? onOpenStalled;
+ /// This client's own introduction, sent with every `terminal_open`; null
+ /// for a viewer that never takes control and so is never anyone's taker.
+ final TerminalClientDescriptor? client;
+
TerminalSession({
required this.machineId,
required this.agentId,
@@ -108,6 +173,7 @@ class TerminalSession extends ChangeNotifier {
required this.engineId,
required this.send,
required this.sendBinary,
+ this.client,
this.onOpenStalled,
this.readOnly = false,
this.resyncTimeout = const Duration(seconds: 4),
@@ -132,6 +198,11 @@ class TerminalSession extends ChangeNotifier {
String? linkMode;
String? errorCode;
String? errorMessage;
+
+ /// Who took this terminal, while [status] is [TerminalSessionStatus.takenOver]
+ /// and the daemon said (`terminal_closed.takenBy`); null from an older daemon
+ /// or a taker that did not introduce itself — "another app", then.
+ TerminalClientDescriptor? takenOverBy;
int cols = 80;
int rows = 24;
@@ -264,6 +335,7 @@ class TerminalSession extends ChangeNotifier {
linkMode = null;
errorCode = null;
errorMessage = null;
+ takenOverBy = null;
_expectedSeq = null;
_lastRenderedSeq = -1;
_framesSinceAck = 0;
@@ -318,6 +390,7 @@ class TerminalSession extends ChangeNotifier {
'cols': cols,
'rows': rows,
'compression': const ['zlib', 'none'],
+ if (client != null) 'client': client!.toJson(),
};
var sent = await send('terminal_open', openPayload);
if (!_isCurrent(generation) ||
@@ -496,8 +569,13 @@ class TerminalSession extends ChangeNotifier {
? TerminalSessionStatus.takenOver
: TerminalSessionStatus.closed;
errorCode = takenOver ? code : null;
+ takenOverBy = takenOver
+ ? TerminalClientDescriptor.fromJson(payload['takenBy'])
+ : null;
errorMessage = takenOver
- ? 'Another client connected to this terminal.'
+ ? (takenOverBy == null
+ ? 'Another client connected to this terminal.'
+ : '${takenOverBy!.name} connected to this terminal.')
: payload['reason']?.toString();
streamId = null;
linkMode = null;
@@ -611,6 +689,7 @@ class TerminalSession extends ChangeNotifier {
_autoReopenAttempts = 0;
errorCode = null;
errorMessage = null;
+ takenOverBy = null;
_resyncTimer?.cancel();
_resyncTimer = null;
status = TerminalSessionStatus.controlling;
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 2574eb40f..f581cc60e 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1519,6 +1519,10 @@ class _TerminalPanelState extends State<TerminalPanel>
busy: !_inputBlocked,
nudged: _controlNudged,
nudge: _controlNudge,
+ takerName: session.takenOverBy?.label(
+ (id) =>
+ widget.notifier.stateOf(id)?.machine.displayName,
+ ),
onTakeControl: _inputBlocked
? () => unawaited(_takeControl())
: null,
@@ -1719,6 +1723,9 @@ class _TerminalHeader extends StatelessWidget {
.where((agent) => agent.id == session.agentId)
.firstOrNull
?.codexHome;
+ final taker = session.takenOverBy?.label(
+ (id) => notifier.stateOf(id)?.machine.displayName,
+ );
final status =
notice ??
switch (session.status) {
@@ -1737,7 +1744,8 @@ class _TerminalHeader extends StatelessWidget {
TerminalSessionStatus.takenOver => (
label: 'Take control',
icon: Icons.lock_outline,
- detail: 'Read only: another app controls this terminal. Take control moves input ownership to this app.',
+ detail:
+ 'Read only: ${taker ?? 'another app'} controls this terminal. Take control moves input ownership to this app.',
),
TerminalSessionStatus.error || TerminalSessionStatus.closed => (
label: 'Reconnect',
@@ -2138,16 +2146,25 @@ class _ControlBanner extends StatelessWidget {
/// even when the person reached the pane with the mouse.
final VoidCallback? onFocusTerminal;
+ /// Who has the terminal now, when the daemon said (`terminal_closed.takenBy`
+ /// — the fleet's current name for that machine when this app knows it);
+ /// null from an older daemon or a taker that did not introduce itself.
+ final String? takerName;
+
const _ControlBanner({
required this.busy,
required this.nudged,
required this.nudge,
required this.onTakeControl,
required this.onFocusTerminal,
+ this.takerName,
});
- String get title =>
- busy ? 'Taking control…' : 'Another app took control of this terminal';
+ String get title => busy
+ ? 'Taking control…'
+ : takerName == null
+ ? 'Another app took control of this terminal'
+ : '$takerName took control of this terminal';
String? get detail {
if (busy) return null;
diff --git a/desktop/test/terminal_control_banner_test.dart b/desktop/test/terminal_control_banner_test.dart
index 2d7efb50f..f7f5c4d14 100644
--- a/desktop/test/terminal_control_banner_test.dart
+++ b/desktop/test/terminal_control_banner_test.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
@@ -112,8 +113,61 @@ void main() {
final banner = find.widgetWithText(FilledButton, 'Take control');
final takenOverTitle = find.text('Another app took control of this terminal');
+ /// The daemon named the taker; `machineId` is another machine in the fleet
+ /// when [inFleet], so the app can show that machine's current name instead.
+ void takeOverBy({bool inFleet = false}) {
+ if (inFleet) {
+ const studio = Machine(
+ machineId: 'ab12ab12ab12ab12',
+ authMode: MachineAuthMode.remote,
+ name: 'Studio',
+ );
+ app.machineStates['ab12ab12ab12ab12'] = MachineState(studio);
+ }
+ session.handleFrame('terminal_closed', {
+ 'streamId': 'stream-a0',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'another client connected',
+ 'takenBy': {
+ 'kind': 'desktop',
+ 'name': 'Mac mini',
+ 'machineId': 'ab12ab12ab12ab12',
+ },
+ });
+ }
+
final hint = find.textContaining('Press ⏎');
+ testWidgets('the banner names who took control when the daemon said', (
+ tester,
+ ) async {
+ await pump(tester);
+ takeOverBy();
+ await tester.pump();
+ expect(find.text('Mac mini took control of this terminal'), findsOneWidget);
+ expect(takenOverTitle, findsNothing);
+ expect(banner, findsOneWidget);
+ // The chip's tooltip says the same.
+ expect(
+ find.byWidgetPredicate(
+ (w) => w is Tooltip && (w.message ?? '').contains('Mac mini controls'),
+ ),
+ findsOneWidget,
+ );
+ await finish(tester);
+ });
+
+ testWidgets('a taker in the fleet is named as the fleet names it', (
+ tester,
+ ) async {
+ await pump(tester);
+ takeOverBy(inFleet: true);
+ await tester.pump();
+ expect(find.text('Studio took control of this terminal'), findsOneWidget);
+ expect(find.textContaining('Mac mini'), findsNothing);
+ await finish(tester);
+ });
+
testWidgets('the banner appears over a taken-over pane and only there', (
tester,
) async {
diff --git a/desktop/test/terminal_session_test.dart b/desktop/test/terminal_session_test.dart
index 74836721e..4db29d1a4 100644
--- a/desktop/test/terminal_session_test.dart
+++ b/desktop/test/terminal_session_test.dart
@@ -941,6 +941,100 @@ void main() {
},
);
+ // Who took the terminal rides on the close (`takenBy`), so the banner can
+ // name them; the name goes away with the next open, so a retaken pane never
+ // shows a stale one.
+ test('a takeover names its taker when the daemon says who', () async {
+ await ready();
+ await session.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'another client connected',
+ 'takenBy': {
+ 'kind': 'desktop',
+ 'name': 'Mac mini',
+ 'machineId': 'ab12ab12ab12ab12',
+ },
+ });
+ expect(session.status, TerminalSessionStatus.takenOver);
+ expect(session.takenOverBy?.name, 'Mac mini');
+ expect(session.takenOverBy?.kind, 'desktop');
+ expect(session.takenOverBy?.machineId, 'ab12ab12ab12ab12');
+ expect(session.errorMessage, contains('Mac mini'));
+ // The fleet's current name for that machine wins over the declared one.
+ expect(
+ session.takenOverBy!.label(
+ (id) => id == 'ab12ab12ab12ab12' ? 'Studio' : null,
+ ),
+ 'Studio',
+ );
+ expect(session.takenOverBy!.label((_) => null), 'Mac mini');
+
+ await session.reopen();
+ expect(session.takenOverBy, isNull);
+ });
+
+ test(
+ 'a takeover with no or a malformed taker reads as another app',
+ () async {
+ await ready();
+ await session.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'takenBy': {'kind': 'not a kind', 'name': 'x'},
+ });
+ expect(session.status, TerminalSessionStatus.takenOver);
+ expect(session.takenOverBy, isNull);
+ expect(session.errorMessage, contains('Another client'));
+ expect(
+ TerminalClientDescriptor.fromJson({'kind': 'phone', 'name': ' iPhone '})
+ ?.name,
+ 'iPhone',
+ );
+ expect(
+ TerminalClientDescriptor.fromJson({
+ 'kind': 'desktop',
+ 'name': 'a',
+ 'machineId': '../x',
+ }),
+ isNull,
+ );
+ expect(TerminalClientDescriptor.fromJson('Mac'), isNull);
+ },
+ );
+
+ test(
+ 'terminal_open carries this client\'s introduction when it has one',
+ () async {
+ final introduced = TerminalSession(
+ machineId: 'machine-1',
+ agentId: 'agent-1',
+ agentName: 'backend-api',
+ engineId: 'codex',
+ client: const TerminalClientDescriptor(
+ kind: 'desktop',
+ name: 'This Mac',
+ machineId: 'ab12ab12ab12ab12',
+ ),
+ send: (type, payload) async {
+ sent.add((type: type, payload: Map<String, dynamic>.from(payload)));
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ addTearDown(introduced.dispose);
+ await introduced.open(initialCols: 100, initialRows: 30);
+ expect(sent.single.payload['client'], {
+ 'kind': 'desktop',
+ 'name': 'This Mac',
+ 'machineId': 'ab12ab12ab12ab12',
+ });
+ sent.clear();
+ await session.open(initialCols: 100, initialRows: 30);
+ expect(sent.single.payload.containsKey('client'), isFalse);
+ },
+ );
+
test(
'terminal_link_mode updates linkMode, ignoring a stale stream id',
() async {
diff --git a/mobile/lib/phone/phone_status.dart b/mobile/lib/phone/phone_status.dart
index b56620842..634a25d58 100644
--- a/mobile/lib/phone/phone_status.dart
+++ b/mobile/lib/phone/phone_status.dart
@@ -114,9 +114,12 @@ 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.
+/// [takerName]: who took the terminal, when known ([phoneTakerName]) — the
+/// dot's tooltip then says "Taken over by Mac mini" rather than just that it was.
PhoneSummary phoneSessionSummary(
- TerminalSession? session,
-) => switch (session?.status) {
+ TerminalSession? session, {
+ String? takerName,
+}) => switch (session?.status) {
null ||
TerminalSessionStatus.opening => (label: 'Attaching…', tone: PhoneTone.busy),
TerminalSessionStatus.resyncing => (
@@ -125,13 +128,31 @@ PhoneSummary phoneSessionSummary(
),
TerminalSessionStatus.controlling => (label: 'Live', tone: PhoneTone.good),
TerminalSessionStatus.takenOver => (
- label: 'Taken over',
+ label: takerName == null ? 'Taken over' : 'Taken over by $takerName',
tone: PhoneTone.attention,
),
TerminalSessionStatus.error => (label: 'Disconnected', tone: PhoneTone.bad),
TerminalSessionStatus.closed => (label: 'Closed', tone: PhoneTone.quiet),
};
+/// Who took this session's terminal, by the fleet's current name for their
+/// machine when this phone knows it, else the name they declared; null while
+/// nobody has, or when the daemon did not say (an older one, or a taker that
+/// did not introduce itself).
+String? phoneTakerName(
+ TerminalSession? session,
+ String? Function(String machineId) resolveMachine,
+) => session?.status == TerminalSessionStatus.takenOver
+ ? session?.takenOverBy?.label(resolveMachine)
+ : null;
+
+/// The one line under the header while another client drives this terminal —
+/// the desktop's banner, at phone size. Null in every other state.
+String? phoneTakeoverNotice(TerminalSession? session, String? takerName) =>
+ session?.status == TerminalSessionStatus.takenOver
+ ? '${takerName ?? 'Another app'} took control of this terminal'
+ : null;
+
/// 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.
///
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 7ac1cb443..54601e85d 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -486,9 +486,8 @@ class _TerminalPageState extends State<TerminalPage>
/// Awaited for the same reason [_newAgent] is: the list is backed out of as often as it is tapped
/// through, and this page gets no rebuild when it lands back on top.
Future<void> _openAgentList() async {
- await Navigator.of(context).push(
- phoneRoute((_) => AgentsListPage(notifier: widget.notifier)),
- );
+ await Navigator.of(context)
+ .push(phoneRoute((_) => AgentsListPage(notifier: widget.notifier)));
if (mounted) setState(() {});
}
@@ -817,9 +816,7 @@ class _TerminalPageState extends State<TerminalPage>
_watchKeyBar();
final pane = widget.notifier.panes
.where(
- (p) =>
- p.machineId == widget.machineId &&
- p.agentId == widget.agentId,
+ (p) => p.machineId == widget.machineId && p.agentId == widget.agentId,
)
.firstOrNull;
if (pane != null) {
@@ -872,6 +869,11 @@ class _TerminalPageState extends State<TerminalPage>
// Captured while the agent is still listed, for the sentence above.
if (agent != null) _cachedAgentName = agent.name;
final reclaim = phoneReclaimAction(session);
+ final takerName = phoneTakerName(
+ session,
+ (id) => widget.notifier.stateOf(id)?.machine.displayName,
+ );
+ final takeoverNotice = phoneTakeoverNotice(session, takerName);
// Creating needs the machine to list its folders and name its engines,
// so one that is offline or still wants its password cannot host a new
// agent — the same gate the Agents tab puts on its fab.
@@ -1052,14 +1054,12 @@ class _TerminalPageState extends State<TerminalPage>
// older CLI never advertises the binary kind, so the
// upload would go nowhere silently. Null leaves the
// buttons undrawn rather than drawn dead.
- onPickImage:
- machine?.terminalImagePasteAvailable == true
+ onPickImage: machine?.terminalImagePasteAvailable == true
? () => unawaited(
_sendImage(session, ImageSource.gallery),
)
: null,
- onTakePhoto:
- machine?.terminalImagePasteAvailable == true
+ onTakePhoto: machine?.terminalImagePasteAvailable == true
? () => unawaited(
_sendImage(session, ImageSource.camera),
)
@@ -1102,7 +1102,10 @@ class _TerminalPageState extends State<TerminalPage>
children: [
TerminalHeader(
agent: agent,
- status: phoneSessionSummary(session),
+ status: phoneSessionSummary(
+ session,
+ takerName: takerName,
+ ),
trailing: [
// Read-only is a state to get OUT of, so its way
// out is a labelled button in the header rather
@@ -1110,7 +1113,10 @@ class _TerminalPageState extends State<TerminalPage>
// where you go having decided to do something,
// and this is the thing telling you that typing
// will go nowhere until you do.
- if (reclaim != null)
+ // While the strip below says who took over, its
+ // button is the way back; two "Take control" a
+ // finger apart would be noise.
+ if (reclaim != null && takeoverNotice == null)
_ReclaimButton(
action: reclaim,
onPressed: () => widget.notifier.selectAgent(
@@ -1130,8 +1136,7 @@ class _TerminalPageState extends State<TerminalPage>
// the header's own right inset.
last: true,
onPressed: () => _showActions(
- machineName:
- machine?.machine.displayName ?? '',
+ machineName: machine?.machine.displayName ?? '',
agentName: agent.name,
project: agent.project,
),
@@ -1139,6 +1144,17 @@ class _TerminalPageState extends State<TerminalPage>
],
),
Divider(height: 1, color: AppGlass.hair),
+ // The desktop's "took control" band, at phone size: a
+ // status dot alone is easy to miss, and the person is
+ // about to wonder why typing does nothing.
+ if (takeoverNotice != null)
+ _TakeoverStrip(
+ notice: takeoverNotice,
+ onTakeControl: () => widget.notifier.selectAgent(
+ widget.machineId,
+ widget.agentId,
+ ),
+ ),
],
),
),
@@ -1317,6 +1333,61 @@ class _TerminalPageState extends State<TerminalPage>
}
}
+/// One line under the header while another client drives this terminal:
+/// who, and the way back. Pairs with [_ReclaimButton] in the header; the
+/// strip says who, the button in it is the same gesture.
+class _TakeoverStrip extends StatelessWidget {
+ const _TakeoverStrip({required this.notice, required this.onTakeControl});
+
+ final String notice;
+ final VoidCallback onTakeControl;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final color = phoneToneColor(PhoneTone.attention);
+ return Semantics(
+ key: const ValueKey('phone-takeover-strip'),
+ liveRegion: true,
+ child: Container(
+ color: color.withValues(alpha: 0.12),
+ padding: const EdgeInsets.only(left: 14, right: 6, top: 4, bottom: 4),
+ child: Row(
+ children: [
+ Icon(LucideIcons.lock300, size: 13, color: color),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ notice,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ fontSize: 12,
+ color: color,
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ),
+ TextButton(
+ onPressed: onTakeControl,
+ style: TextButton.styleFrom(
+ foregroundColor: color,
+ minimumSize: Size.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ ),
+ child: const Text(
+ 'Take control',
+ style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
/// The header's way back into a session this device is not driving.
///
/// Re-selecting the agent is what reclaims it — the same call the desktop tile's
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index ed0e8e9e2..5ce0fa57f 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -3647,7 +3647,9 @@ class AppNotifier extends ChangeNotifier {
// assigns `machines` from the account's own answer and drops any state not
// in it, so nothing cached outlives the round-trip it was covering.
machines = warmMachines;
- StartupTrace.mark('warm-started $warmed machine(s), $warmedAgents agent(s)');
+ StartupTrace.mark(
+ 'warm-started $warmed machine(s), $warmedAgents agent(s)',
+ );
notifyListeners();
}
@@ -5356,6 +5358,19 @@ 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.
+ /// How this phone introduces itself on `terminal_open`, so a desktop it
+ /// displaces can say "(this phone) took control". The OS's device name when
+ /// it will give one, else just "Phone".
+ TerminalClientDescriptor phoneClientDescriptor() {
+ final name = localHostnameOrNull() ?? 'Phone';
+ return TerminalClientDescriptor(
+ kind: 'phone',
+ name: name.length > TerminalClientDescriptor.nameMax
+ ? name.substring(0, TerminalClientDescriptor.nameMax)
+ : name,
+ );
+ }
+
Future<void> _attachSession(TerminalPane pane) async {
if (_disposed || !allPanes.contains(pane) || pane.session != null) return;
final wantedAgentId = pane.agentId;
@@ -5379,6 +5394,7 @@ class AppNotifier extends ChangeNotifier {
agentId: agent.id,
agentName: agent.name,
engineId: agent.engine,
+ client: phoneClientDescriptor(),
send: (type, payload) =>
_conn(pane.machineId).sendTerminalFrame(type, payload),
sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 20fa65fb5..16e170c80 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -28,6 +28,67 @@ enum TerminalSessionStatus {
error,
}
+/// Who a terminal client is, as it says on `terminal_open` (`client`) and as
+/// the daemon repeats to the client it displaces (`terminal_closed.takenBy`) —
+/// so the banner can say "Mac mini took control" rather than "another app".
+/// Self-declared: every client of a machine is the same account's, and the
+/// daemon has no better name for a relayed desktop or a phone. [machineId] is
+/// a desktop's own machine in the fleet, so the receiver can show that
+/// machine's current name over the one declared.
+class TerminalClientDescriptor {
+ const TerminalClientDescriptor({
+ required this.kind,
+ required this.name,
+ this.machineId,
+ });
+
+ /// `desktop`, `phone`, … — one lower-case word.
+ final String kind;
+ final String name;
+ final String? machineId;
+
+ static const nameMax = 64;
+
+ Map<String, dynamic> toJson() => {
+ 'kind': kind,
+ 'name': name,
+ if (machineId != null) 'machineId': machineId,
+ };
+
+ /// The wire shape, or null for anything else — a daemon that predates the
+ /// field sends nothing, and a malformed one is treated the same.
+ static TerminalClientDescriptor? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final kind = raw['kind'];
+ final name = raw['name'];
+ final machineId = raw['machineId'];
+ if (kind is! String || !RegExp(r'^[a-z]{1,16}$').hasMatch(kind)) {
+ return null;
+ }
+ if (name is! String) return null;
+ final clean = name.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
+ if (clean.isEmpty || clean.length > nameMax) return null;
+ if (machineId != null &&
+ (machineId is! String ||
+ !RegExp(r'^[a-f0-9]{16,64}$').hasMatch(machineId))) {
+ return null;
+ }
+ return TerminalClientDescriptor(
+ kind: kind,
+ name: clean,
+ machineId: machineId as String?,
+ );
+ }
+
+ /// The name to show: the fleet's current name for [machineId] when the
+ /// caller knows one, else the name the client declared.
+ String label(String? Function(String machineId) resolveMachine) {
+ final id = machineId;
+ final fleet = id == null ? null : resolveMachine(id)?.trim();
+ return fleet == null || fleet.isEmpty ? name : fleet;
+ }
+}
+
/// Transient progress for an in-flight [TerminalSession.pasteImage]/[TerminalSession.pasteFile]
/// chunked upload. `bytesWritten` reflects the daemon's own per-chunk ACKs, not bytes merely handed
/// to the local socket.
@@ -95,6 +156,10 @@ class TerminalSession extends ChangeNotifier {
/// spending it on a no-op.
final Future<bool> Function()? onOpenStalled;
+ /// This client's own introduction, sent with every `terminal_open`; null
+ /// for a viewer that never takes control and so is never anyone's taker.
+ final TerminalClientDescriptor? client;
+
TerminalSession({
required this.machineId,
required this.agentId,
@@ -102,6 +167,7 @@ class TerminalSession extends ChangeNotifier {
required this.engineId,
required this.send,
required this.sendBinary,
+ this.client,
this.onOpenStalled,
this.resyncTimeout = const Duration(seconds: 4),
}) {
@@ -124,6 +190,11 @@ class TerminalSession extends ChangeNotifier {
String? linkMode;
String? errorCode;
String? errorMessage;
+
+ /// Who took this terminal, while [status] is [TerminalSessionStatus.takenOver]
+ /// and the daemon said (`terminal_closed.takenBy`); null from an older daemon
+ /// or a taker that did not introduce itself — "another app", then.
+ TerminalClientDescriptor? takenOverBy;
int cols = 80;
int rows = 24;
@@ -259,6 +330,7 @@ class TerminalSession extends ChangeNotifier {
linkMode = null;
errorCode = null;
errorMessage = null;
+ takenOverBy = null;
_expectedSeq = null;
_lastRenderedSeq = -1;
_framesSinceAck = 0;
@@ -313,6 +385,7 @@ class TerminalSession extends ChangeNotifier {
'cols': cols,
'rows': rows,
'compression': const ['zlib', 'none'],
+ if (client != null) 'client': client!.toJson(),
};
var sent = await send('terminal_open', openPayload);
if (!_isCurrent(generation) ||
@@ -500,8 +573,13 @@ class TerminalSession extends ChangeNotifier {
? TerminalSessionStatus.takenOver
: TerminalSessionStatus.closed;
errorCode = takenOver ? code : null;
+ takenOverBy = takenOver
+ ? TerminalClientDescriptor.fromJson(payload['takenBy'])
+ : null;
errorMessage = takenOver
- ? 'Another client connected to this terminal.'
+ ? (takenOverBy == null
+ ? 'Another client connected to this terminal.'
+ : '${takenOverBy!.name} connected to this terminal.')
: payload['reason']?.toString();
streamId = null;
linkMode = null;
@@ -615,6 +693,7 @@ class TerminalSession extends ChangeNotifier {
_autoReopenAttempts = 0;
errorCode = null;
errorMessage = null;
+ takenOverBy = null;
_resyncTimer?.cancel();
_resyncTimer = null;
status = TerminalSessionStatus.controlling;
diff --git a/mobile/lib/widgets/terminal_pane_header.dart b/mobile/lib/widgets/terminal_pane_header.dart
index 85f5baf55..231629b66 100644
--- a/mobile/lib/widgets/terminal_pane_header.dart
+++ b/mobile/lib/widgets/terminal_pane_header.dart
@@ -96,7 +96,8 @@ class TerminalPaneHeader extends StatelessWidget {
TerminalSessionStatus.takenOver => (
label: 'Take control',
icon: Icons.lock_outline,
- detail: 'Read only: another app controls this terminal. Take control moves input ownership to this app.',
+ detail:
+ 'Read only: ${session.takenOverBy?.name ?? 'another app'} controls this terminal. Take control moves input ownership to this app.',
),
TerminalSessionStatus.error || TerminalSessionStatus.closed => (
label: 'Reconnect',
diff --git a/mobile/test/phone_reclaim_test.dart b/mobile/test/phone_reclaim_test.dart
index ead5f9e95..947945ea6 100644
--- a/mobile/test/phone_reclaim_test.dart
+++ b/mobile/test/phone_reclaim_test.dart
@@ -47,4 +47,76 @@ void main() {
expect(action?.tone, PhoneTone.bad, reason: '$status');
}
});
+
+ group('who took control', () {
+ TerminalSession taken({Map<String, dynamic>? takenBy}) {
+ final session = _session(TerminalSessionStatus.controlling)
+ ..streamId = 's';
+ session.handleFrame('terminal_closed', {
+ 'streamId': 's',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'another client connected',
+ 'takenBy': ?takenBy,
+ });
+ return session;
+ }
+
+ test('the summary and the strip name the taker when the daemon said', () {
+ final session = taken(
+ takenBy: {
+ 'kind': 'desktop',
+ 'name': 'Mac mini',
+ 'machineId': 'ab12ab12ab12ab12',
+ },
+ );
+ expect(session.status, TerminalSessionStatus.takenOver);
+ final name = phoneTakerName(session, (_) => null);
+ expect(name, 'Mac mini');
+ expect(
+ phoneSessionSummary(session, takerName: name).label,
+ 'Taken over by Mac mini',
+ );
+ expect(
+ phoneTakeoverNotice(session, name),
+ 'Mac mini took control of this terminal',
+ );
+ // The fleet's current name for that machine wins over the declared one.
+ expect(
+ phoneTakerName(
+ session,
+ (id) => id == 'ab12ab12ab12ab12' ? 'Studio' : null,
+ ),
+ 'Studio',
+ );
+ });
+
+ test('an older daemon, or a nameless taker, reads as another app', () {
+ final session = taken();
+ expect(phoneTakerName(session, (_) => null), isNull);
+ expect(phoneSessionSummary(session).label, 'Taken over');
+ expect(
+ phoneTakeoverNotice(session, null),
+ 'Another app took control of this terminal',
+ );
+ expect(
+ phoneTakerName(
+ taken(takenBy: {'kind': 'not a kind', 'name': 'x'}),
+ (_) => null,
+ ),
+ isNull,
+ );
+ });
+
+ test('nothing to say while this phone drives, or nobody does', () {
+ expect(phoneTakeoverNotice(null, null), isNull);
+ for (final status in [
+ TerminalSessionStatus.controlling,
+ TerminalSessionStatus.closed,
+ TerminalSessionStatus.error,
+ ]) {
+ expect(phoneTakeoverNotice(_session(status), 'Mac'), isNull);
+ expect(phoneTakerName(_session(status), (_) => 'Mac'), isNull);
+ }
+ });
+ });
}
diff --git a/mobile/test/phone_takeover_strip_test.dart b/mobile/test/phone_takeover_strip_test.dart
new file mode 100644
index 000000000..252ddaac5
--- /dev/null
+++ b/mobile/test/phone_takeover_strip_test.dart
@@ -0,0 +1,108 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+import 'voice_fakes.dart';
+
+/// Another client took this terminal: the page says who, in one line under
+/// the header, with the way back beside it. A status dot alone was easy to
+/// miss, and the person was about to wonder why typing did nothing.
+void main() {
+ late AppNotifier notifier;
+ late TerminalSession session;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+ late List<String> opens;
+
+ setUp(() {
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ opens = [];
+ session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, _) async {
+ if (type == 'terminal_open') opens.add(type);
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's';
+ session.terminal.write('output\r\n');
+ notifier.adoptSessionForTest(session);
+ language = ValueNotifier('en');
+ voice = VoiceInputController(
+ transcriber: FakeTranscriber().call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ });
+
+ tearDown(() {
+ voice.dispose();
+ language.dispose();
+ notifier.dispose();
+ });
+
+ Future<void> pump(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ final strip = find.byKey(const ValueKey('phone-takeover-strip'));
+
+ testWidgets(
+ 'the strip names the taker and is absent while this phone drives',
+ (tester) async {
+ await pump(tester);
+ expect(strip, findsNothing);
+ await session.handleFrame('terminal_closed', {
+ 'streamId': 's',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'another client connected',
+ 'takenBy': {'kind': 'desktop', 'name': 'Mac mini'},
+ });
+ await tester.pump();
+ expect(strip, findsOneWidget);
+ expect(
+ find.text('Mac mini took control of this terminal'),
+ findsOneWidget,
+ );
+ // One way back, on the strip; the header's own button stands down.
+ expect(find.text('Take control'), findsOneWidget);
+ },
+ );
+
+ testWidgets('without a name it is another app', (tester) async {
+ await pump(tester);
+ await session.handleFrame('terminal_closed', {
+ 'streamId': 's',
+ 'code': 'TERMINAL_TAKEN_OVER',
+ });
+ await tester.pump();
+ expect(
+ find.text('Another app took control of this terminal'),
+ findsOneWidget,
+ );
+ });
+}