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.

Merge remote-tracking branch 'origin/main' into feat/mobile-ios-android

Dev jacob59cd9f0271bb
diff --cc cli/src/lib/terminalStreamManager.ts
index e24e472a0,a3ac35d5e..5cebeaa75
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@@ -63,10 -94,9 +94,12 @@@ 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
+ /** 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
@@@ -361,28 -363,14 +400,32 @@@ 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
+ // 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 () => {
+ 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.
+ // 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)
+ if (!this.deps.readOnly && !watching) {
- await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
++ 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
@@@ -446,8 -433,8 +489,9 @@@
const wantsZlib = requestedCompression.includes('zlib') && !this.deps.isLoopback?.(connId)
state = {
connId,
+ ...(client ? { client } : {}),
streamId,
+ watching,
agentId: session.agentId,
engineId: session.engine,
placementKey,
@@@ -1137,16 -1122,15 +1181,21 @@@
await Promise.all(own.map((state) => this.closeStream(state, 'replaced', false)))
}
+ /// 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> {
+ 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))
+ const incumbents = this.incumbentsFor(agentId, placementKey, nextConnId)
await Promise.all(incumbents.map((state) => this.closeStream(
state,
'another client connected',
diff --cc mobile/lib/phone/agent_home.dart
index 99a7bca88,7ef18d661..c74c7fe1a
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@@ -13,8 -13,6 +13,7 @@@ import 'agent_index.dart'
import 'agent_swipe.dart';
import 'agent_swipe_list.dart';
import 'agents_page.dart' show openNewAgent;
+import 'desk_groups.dart';
- import 'desk_tab_strip.dart';
import 'machines_tab.dart';
import 'phone_fab.dart';
import 'phone_header.dart';
diff --cc mobile/lib/phone/desk_tabs_sheet.dart
index 000000000,000000000..83345fbe4
new file mode 100644
--- /dev/null
+++ b/mobile/lib/phone/desk_tabs_sheet.dart
@@@ -1,0 -1,0 +1,81 @@@
++import 'dart:async';
++
++import 'package:flutter/widgets.dart';
++import 'package:lucide_icons_flutter/lucide_icons.dart';
++
++import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
++import 'package:harness_mobile/state/app_state.dart';
++
++import 'agent_index.dart';
++import 'desk_groups.dart';
++import 'phone_navigation.dart';
++import 'phone_sheet.dart';
++
++/// The account's tabs, as a sheet — the way to another tab on a phone, now that
++/// a swipe stays inside the one you are in.
++///
++/// ⚠️ **A sheet and not a row of chips along the top, and the difference is the
++/// terminal.** The terminal is the screen; every point of chrome above it is a
++/// line of somebody's session that is not shown. A rail of tabs cost a line and
++/// a half permanently, for a decision that is made a few times a day — so what
++/// stays on screen is one mark in the header beside `⋯`, and the list lives
++/// behind it.
++///
++/// [showing] is the agent on screen, which is what decides the tab the phone is
++/// in — see [activeDeskGroup]. Opened from the terminal page, so it always has
++/// one.
++Future<void> showDeskTabsSheet(
++ BuildContext context,
++ AppNotifier notifier, {
++ required AgentRef showing,
++}) {
++ final groups = deskGroups(notifier, visibleAgents(agentIndex(notifier)));
++ final active = activeDeskGroup(notifier, groups, showing);
++ return showPhoneSheet(
++ context,
++ title: 'Tabs',
++ actions: [
++ for (final group in groups)
++ PhoneSheetAction(
++ // The tab you are in wears the tick; the rest wear the tab mark. A
++ // colour alone would say it to fewer people.
++ icon: group.id == active.id
++ ? LucideIcons.check300
++ : LucideIcons.layoutGrid300,
++ label: group.name,
++ value: switch (group.entries.length) {
++ // Its agents are on a machine that is asleep or wants its password.
++ // Listed anyway: a tab missing from this list reads as one somebody
++ // deleted. See [DeskGroup].
++ 0 => 'not here now',
++ 1 => '1 agent',
++ final count => '$count agents',
++ },
++ // A tab with nothing this phone can open is a row to read, not one to
++ // press — [showPhoneSheet] draws it dimmed and stays open on a tap.
++ enabled: !group.isEmpty,
++ onTap: () => _open(context, notifier, group),
++ ),
++ ],
++ );
++}
++
++/// Switch to [group]: the phone is in that tab from here, and the agent it
++/// opens is the one this phone was last on in it — its first, the first time.
++///
++/// ⚠️ The order matters. [AppNotifier.selectDeskTab] is what settles which tab
++/// an agent that sits on TWO of them belongs to (see [activeDeskGroup]); set
++/// after the open, it would be read a frame too late and the sheet would tick
++/// the tab that was left.
++void _open(BuildContext context, AppNotifier notifier, DeskGroup group) {
++ if (group.isEmpty) return;
++ notifier.selectDeskTab(group.id);
++ final remembered = notifier.deskLastAgentIn(group.id);
++ final target = remembered != null && group.holds(remembered)
++ ? remembered
++ : (
++ machineId: group.entries.first.machineId,
++ agentId: group.entries.first.agent.id,
++ );
++ openAgent(context, notifier, target.machineId, target.agentId);
++}
diff --cc mobile/lib/phone/phone_shell.dart
index edc4fe670,edc4fe670..9045fe15e
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@@ -148,6 -148,6 +148,13 @@@ class _PhoneShellState extends State<Ph
/// who was looking straight at it, with a network that would have answered at once.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
++ if (state == AppLifecycleState.paused) {
++ // The other half of the resume below: work that only makes sense in
++ // front of somebody stops here. The sockets are not touched — the OS
++ // suspends them, and the redial on the way back is what recovers them.
++ widget.notifier.handleAppPaused();
++ return;
++ }
if (state != AppLifecycleState.resumed) return;
phoneTerminalP2p.kickRetry();
widget.notifier.handleAppResumed();
diff --cc mobile/lib/phone/phone_status.dart
index 72ca4fe81,634a25d58..aeebdead5
--- a/mobile/lib/phone/phone_status.dart
+++ b/mobile/lib/phone/phone_status.dart
@@@ -114,32 -114,45 +114,55 @@@ PhoneSummary phoneAgentSummary(MachineS
/// 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) {
+ /// [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, {
+ String? takerName,
-}) => 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: 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),
-};
++}) {
+ // ⚠️ 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',
++ 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 --cc mobile/lib/phone/terminal_page.dart
index de3754674,54601e85d..00eed7b22
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@@ -23,6 -23,6 +23,7 @@@ import 'package:harness_mobile/widgets/
import 'agents_list_page.dart';
import 'agents_page.dart' show openNewAgent;
import 'delete_agent.dart';
++import 'desk_tabs_sheet.dart';
import 'held_height.dart';
import 'machines_tab.dart';
import 'phone_navigation.dart' show phoneRoute;
@@@ -181,6 -167,6 +168,7 @@@ typedef _PageFacts = (
PhoneMachineStatus? machineStatus,
bool imagePaste,
String? machineName,
++ bool deskTabs,
});
class _TerminalPageState extends State<TerminalPage>
@@@ -427,6 -407,6 +415,11 @@@
machineStatus: machine == null ? null : phoneMachineStatusOf(machine),
imagePaste: machine?.terminalImagePasteAvailable ?? false,
machineName: machine?.machine.displayName,
++ // ⚠️ Read here, and not in `build` alone, because this page is rebuilt
++ // only when one of these facts moves. Tabs arriving from another computer
++ // change nothing else about this agent, and the mark that opens them
++ // would not appear until something unrelated happened to redraw the page.
++ deskTabs: notifier.deskTabs.isNotEmpty,
);
}
@@@ -904,12 -869,11 +894,17 @@@
// Captured while the agent is still listed, for the sentence above.
if (agent != null) _cachedAgentName = agent.name;
final reclaim = phoneReclaimAction(session);
+ // Read-only either way — the terminal was never this pane's (a watcher) or was taken from it.
+ // `_AgentGone` owns the page when the agent itself is missing, so this stays out of its way.
+ final blocked =
+ !agentGone &&
+ session != null &&
+ (session.watching || session.status == TerminalSessionStatus.takenOver);
+ 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.
@@@ -1166,23 -1113,17 +1162,51 @@@
// where you go having decided to do something,
// and this is the thing telling you that typing
// will go nowhere until you do.
- // 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)
+ // ⚠️ **Not while the band is up.** The band below
+ // carries the same words and the same button, a
+ // finger's width under this one, and two "Take
+ // control"s stacked read as two different offers.
+ // The band is the better of the two — it says WHY
- // typing stopped — so this one gives way to it.
++ // typing stopped, and by whom — so this one gives
++ // way to it.
+ //
+ // Kept for the states the band does not cover:
+ // "Reconnect", for a stream that died with nobody
+ // else involved. See [_ControlBanner].
+ if (reclaim != null && !blocked && !_takingControl)
_ReclaimButton(
action: reclaim,
- onPressed: () => widget.notifier.selectAgent(
- widget.machineId,
- widget.agentId,
+ // The same call the band's button makes — see
+ // [_takeControl].
+ onPressed: () => unawaited(_takeControl()),
+ ),
++ // The account's tabs, one mark before `⋯` — the
++ // only way to another tab now that a swipe stays
++ // inside the one you are in (see [showDeskTabsSheet]).
++ //
++ // ⚠️ **A mark, not a rail of tabs across the top.**
++ // The terminal is the screen; chrome above it is
++ // somebody's session not being shown, and this is a
++ // choice made a few times a day.
++ //
++ // Undrawn for an account with no tabs at all: there
++ // would be one row in the sheet, naming every agent
++ // on the account, which is what a swipe already does.
++ if (widget.notifier.deskTabs.isNotEmpty)
++ _HeaderAction(
++ icon: LucideIcons.layoutGrid300,
++ tooltip: 'Tabs',
++ onPressed: () => unawaited(
++ showDeskTabsSheet(
++ context,
++ widget.notifier,
++ showing: (
++ machineId: widget.machineId,
++ agentId: widget.agentId,
++ ),
++ ),
+ ),
+ ),
// Null while the agent is not loaded: there is
// nothing to act on yet, and a menu of actions
// that all fail is worse than no menu.
@@@ -1203,21 -1143,17 +1226,16 @@@
),
],
),
- // Under the names and above the divider: one bar, which
- // slides away as one. Which tab the phone is in is part
- // of where this terminal IS — the swipe either side of it
- // stays inside that tab — so it belongs with the identity
- // rather than beside the floating buttons.
- ?widget.tabStrip,
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,
- ),
+ // ⚠️ Inside the header's own slide, not under it: the two are one bar as far
+ // as a scroll is concerned, and a band left behind while the header left
+ // would sit on the output with nothing above it.
+ if (blocked || _takingControl)
+ _ControlBanner(
+ watching: session?.watching ?? false,
+ busy: !blocked,
++ takeoverNotice: takeoverNotice,
+ onTakeControl: _takeControl,
),
],
),
@@@ -1524,131 -1491,6 +1542,137 @@@ class _AgentGone extends StatelessWidge
);
}
+/// The band over the output saying this pane cannot be typed into, and offering the way in.
+///
+/// ⚠️ **Over the output, not in the header.** The header's status word is 11pt in a corner beside
+/// the agent's name, and somebody mid-sentence never looks there — the keystrokes simply stop
+/// landing and nothing on screen says why. This sits where the eyes already are. The desktop puts
+/// the same band in the same place for the same reason (`widgets/terminal_panel.dart`); this is
+/// that band at phone width.
+///
+/// Covers both ways a pane goes read-only. A WATCHER never held the terminal — the page attached
+/// to an agent the desktop was already driving, output and all (see [TerminalSession.watching]) —
+/// while `takenOver` is a terminal this phone HAD and lost. One sentence each, because "another
- /// app has it, press this" is the part that matters either way.
++/// app has it, press this" is the part that matters either way; the lost one names the taker when
++/// the daemon said who.
+class _ControlBanner extends StatelessWidget {
+ const _ControlBanner({
+ required this.watching,
+ required this.busy,
++ required this.takeoverNotice,
+ required this.onTakeControl,
+ });
+
+ /// True where the terminal was never this pane's; false where it was taken away.
+ final bool watching;
+
+ /// The take is in flight — its `terminal_open` is out and this pane is waiting to hear.
+ final bool busy;
+
++ /// Who took it, as the one sentence [phoneTakeoverNotice] writes. Null for a watcher, which
++ /// never lost a terminal, and while a take is in flight.
++ final String? takeoverNotice;
++
+ final VoidCallback onTakeControl;
+
+ String get _title {
+ if (busy) return 'Taking control…';
- return watching
- ? 'Another app is using this terminal'
- : 'Another app took control of this terminal';
++ if (watching) return 'Another app is using this terminal';
++ return takeoverNotice ?? 'Another app took control of this terminal';
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final ink = phoneToneColor(PhoneTone.attention);
+ return Semantics(
++ key: const ValueKey('phone-takeover-strip'),
+ container: true,
+ liveRegion: true,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ // Composited over the pane's own ground rather than laid on as a wash: the terminal
+ // theme behind this band may be any colour, and a bare translucent fill would read
+ // differently on each of them.
+ color: Color.alphaBlend(
+ ink.withValues(alpha: 0.12),
+ AppPalette.windowBg,
+ ),
+ border: Border(
+ bottom: BorderSide(color: ink.withValues(alpha: 0.55)),
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(14, 10, 10, 10),
+ child: Row(
+ children: [
+ if (busy)
+ SizedBox(
+ width: 15,
+ height: 15,
+ child: CircularProgressIndicator(strokeWidth: 2, color: ink),
+ )
+ else
+ Icon(LucideIcons.lock300, size: 15, color: ink),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ _title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 12,
+ fontWeight: FontWeight.w700,
+ ),
+ ),
+ if (!busy) ...[
+ const SizedBox(height: 2),
+ Text(
+ 'Typing is paused. Take control to type here.',
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontSize: 11,
+ height: 1.3,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (!busy) ...[
+ const SizedBox(width: 10),
+ TextButton(
+ onPressed: onTakeControl,
+ style: TextButton.styleFrom(
+ foregroundColor: ink,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ minimumSize: Size.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ child: const Text(
+ 'Take control',
+ style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
/// The terminal's body while its first keyframe is still crossing the network.
///
/// ⚠️ **A skeleton here, not a spinner, because the shape IS known** — that is
diff --cc mobile/lib/state/app_state.dart
index d0ff08e25,5ce0fa57f..917bed927
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@@ -5512,10 -5358,20 +5514,23 @@@ class AppNotifier extends ChangeNotifie
/// 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 {
+ 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;
@@@ -6587,16 -6423,8 +6603,21 @@@
///
/// Safe to call on every resume. [WsPool.reconnectAll] skips connections that are already open
/// and connections somebody closed on purpose, so a tab switch that cost nothing costs nothing.
- void handleAppResumed() => _pool?.reconnectAll();
+ void handleAppResumed() {
+ _pool?.reconnectAll();
+ // ⚠️ **The desk is re-read here and not only on a push.** A backgrounded
+ // phone runs no code, so every `desk_changed` sent while it was away
+ // reached a socket nobody was listening on: without this the tabs would be
+ // whatever they were when the phone went into a pocket, until something
+ // else happened to change them.
+ unawaited(_desk.refresh());
+ }
+
++ /// The app went into a pocket: stop the reads that only make sense in front
++ /// of somebody. The sockets are left to the OS, which suspends them anyway —
++ /// [handleAppResumed] is what puts both back.
++ void handleAppPaused() => _desk.pause();
+
/// What the local CLI closing this machine's socket with [code] does to the
/// model — the `WsPool.onLocalFailure` path, without a socket.
@visibleForTesting
diff --cc mobile/lib/state/phone_desk.dart
index 13401a14a,000000000..3212029e9
mode 100644,000000..100644
--- a/mobile/lib/state/phone_desk.dart
+++ b/mobile/lib/state/phone_desk.dart
@@@ -1,295 -1,0 +1,339 @@@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/last_opened_agent.dart' show AgentRef;
+import '../logging/app_log.dart';
+import 'desk_sync.dart';
+
+/// The account's desk — its tabs, the same on every computer — as a PHONE holds
+/// it.
+///
+/// `desk_sync.dart` (vendored from the desktop, unchanged) has the document's
+/// shape and the backend's own rules replayed for optimistic writes. This is
+/// the phone's half of it, and it is deliberately not the desktop's half:
+///
+/// ⚠️ **The phone FOLLOWS the desk; it does not project itself onto it.** A
+/// window's tabs are its `swarms`, so the desktop diffs that projection after
+/// every layout change and sends the difference. The phone's `swarms` are not
+/// tabs at all — they are the one-pane container a pager attaches into, and it
+/// attaches the agents either side of the one on screen ahead of a swipe. A
+/// projection of THAT would add every agent a thumb passes to whatever tab the
+/// phone happened to be in, on every computer the person owns. So nothing here
+/// is derived from `swarms`: the tabs are read, and the only writes are the two
+/// a person makes by hand on the phone — [adopt] for an agent created here, and
+/// [drop] for one deleted here.
+///
+/// What is NOT on the desk stays per device, as it does on a window: which tab
+/// is open ([activeTabId]) is this phone's own, and so is the agent within it.
+class PhoneDesk {
- PhoneDesk({required this.read, required this.write, required this.onChanged});
++ PhoneDesk({
++ required this.read,
++ required this.write,
++ required this.onChanged,
++ this.pollInterval = const Duration(seconds: 15),
++ });
++
++ /// How often a phone in the FOREGROUND re-reads the desk on its own.
++ ///
++ /// ⚠️ **Not belt-and-braces on a phone: it is the main wire.** A
++ /// `desk_changed` push reaches this app only over a machine's relay socket —
++ /// the backend has no per-phone socket to send it on — so a backend that
++ /// predates that forwarding, or a moment with no machine connected, delivers
++ /// nothing at all, and the tabs would sit at whatever they were when the app
++ /// last launched. 15s is the beat the desktop reads the desk on.
++ ///
++ /// Stopped while the app is in the background ([pause]) and armed again by
++ /// the [refresh] a resume makes.
++ final Duration pollInterval;
+
+ /// `GET /api/desk` — the document, or null where the backend has no desk to
+ /// give (see `ApiClient.desk`).
+ final Future<Map<String, dynamic>?> Function() read;
+
+ /// `POST /api/desk/ops` — the ops, answered with the document they produced.
+ final Future<Map<String, dynamic>?> Function(List<Map<String, dynamic>> ops)
+ write;
+
+ /// The app has tabs it did not have a moment ago: rebuild.
+ final VoidCallback onChanged;
+
+ final DeskSyncState _state = DeskSyncState();
+ Timer? _retry;
++ Timer? _poll;
+ Future<void>? _joining;
+ bool _disposed = false;
+
+ /// Bumped by [reset] — a sign-out, or a switch of account. Everything in
+ /// flight reads it on the way back and drops what it was carrying if it
+ /// moved, so the next account never inherits the last one's answer.
+ int _generation = 0;
+
+ /// The tabs, in the desk's order, with this phone's unacknowledged writes
+ /// already laid over them — what the tab strip draws.
+ List<DeskTab> get tabs => _state.synced;
+
+ /// Whether the desk answered at all. False leaves the phone as it was before
+ /// the desk existed: no strip, and a swipe over every agent on the account.
+ bool get enabled => _state.enabled;
+
+ /// The tab the phone is in, or null for the agents no tab holds (and for a
+ /// phone whose desk is empty). Device-local by decision — see the class note.
+ String? get activeTabId => _activeTabId;
+ String? _activeTabId;
+
+ /// A tab was picked by hand. The screen answers by opening an agent of that
+ /// tab; nothing else here moves.
+ void select(String? tabId) {
+ if (_activeTabId == tabId) return;
+ _activeTabId = tabId;
+ onChanged();
+ }
+
+ /// The screen worked out which tab it is showing, and which agent of it.
+ /// Silent: this is called from a build, and it is a record of what is already
+ /// drawn, not a change to draw.
+ void note(String? tabId, {AgentRef? showing}) {
+ _activeTabId = tabId;
+ if (showing != null) _lastAgent[tabId] = showing;
+ }
+
+ /// The agent this phone last had on screen in [tabId], if it has been in it.
+ ///
+ /// What makes a tab switch feel like the desktop's: going back to a tab returns
+ /// to where you were in it rather than to its first agent. Per device and never
+ /// written down — a tab is a place you were, and only this phone was there.
+ AgentRef? lastAgentIn(String? tabId) => _lastAgent[tabId];
+
+ final Map<String?, AgentRef> _lastAgent = {};
+
+ // ── reading ──────────────────────────────────────────────────────────────
+
+ /// Join the desk unless this phone already has, or is joining now. Called from
+ /// every path that finishes a sign-in, because the first read of a session
+ /// that had no network yet answers with an error rather than with a desk.
+ void ensure() {
+ if (_state.enabled || _joining != null || _disposed) return;
+ unawaited(_join());
+ }
+
+ Future<void> _join() async {
+ final run = _read(first: true);
+ _joining = run;
+ try {
+ await run;
+ } finally {
+ if (identical(_joining, run)) _joining = null;
+ }
+ }
+
+ /// Read the desk again — a `desk_changed` push, or the app coming back to the
+ /// foreground after however long in somebody's pocket.
++ ///
++ /// A resume comes through here, so this is also where the poll is armed again
++ /// after [pause].
+ Future<void> refresh() {
+ if (!_state.enabled) {
+ ensure();
+ return Future<void>.value();
+ }
++ _startPolling();
+ return _read(first: false);
+ }
+
++ /// The app is no longer in front of anybody: stop reading the desk until it
++ /// is. iOS suspends the process anyway; Android does not always, and a phone
++ /// in a pocket has no tabs to show.
++ void pause() {
++ _poll?.cancel();
++ _poll = null;
++ }
++
++ void _startPolling() {
++ if (_poll != null || _disposed || !_state.enabled) return;
++ _poll = Timer.periodic(pollInterval, (_) {
++ // Nothing while a write of this phone's own is in the air: its answer is
++ // the document, and a read underneath it would only race that.
++ if (_state.pending.isNotEmpty || _state.inFlight) return;
++ unawaited(_read(first: false));
++ });
++ }
++
+ /// A `desk_changed` frame: the payload carries only the revision, so a phone
+ /// already at it has nothing to fetch.
+ ///
+ /// ⚠️ It arrives once PER MACHINE the phone is connected to — the frame rides
+ /// each machine's socket (backend `lib/webWs.ts`) because a phone holds no
+ /// adapter socket of its own. The revision test is what keeps four machines
+ /// from meaning four GETs.
+ void noticeRevision(Object? revision) {
+ if (!_state.enabled) return;
+ if (revision is int && revision <= _state.revision) return;
+ unawaited(refresh());
+ }
+
+ Future<void> _read({required bool first}) async {
+ if (_disposed) return;
+ final generation = _generation;
+ Map<String, dynamic>? raw;
+ try {
+ raw = await read();
+ } catch (error) {
+ appLog.warn('desk', '${first ? 'first read' : 'read'} failed: $error');
+ return;
+ }
+ if (_disposed || generation != _generation) return;
+ final doc = DeskDoc.fromJson(raw);
+ if (doc == null) {
+ if (first) appLog.info('desk', 'not available here — no tabs to show');
+ return;
+ }
+ if (first) {
+ _state.enabled = true;
+ appLog.info(
+ 'desk',
+ 'joined at rev ${doc.revision} · ${doc.tabs.length} tabs',
+ );
++ _startPolling();
+ }
+ _apply(doc);
+ }
+
+ /// Take [doc] as the desk, with this phone's unacknowledged ops laid back over
+ /// it. A document older than one already applied is ignored — two machines'
+ /// sockets can deliver the same change out of order.
+ void _apply(DeskDoc doc) {
+ if (doc.revision < _state.revision) return;
+ _state.revision = doc.revision;
+ _state.synced = applyDeskOps(doc.tabs, _state.pending);
+ onChanged();
+ }
+
+ // ── the two writes a phone makes ─────────────────────────────────────────
+
+ /// An agent created ON THIS PHONE joins the tab the phone is in, the way one
+ /// created in a window joins that window's tab.
+ ///
+ /// Without this a phone-made agent would belong to no tab at all: invisible in
+ /// every window's tab bar, and — now that a swipe stays inside the tab — only
+ /// reachable here through search. Nothing to do when the phone is not in a tab
+ /// (the desk is empty, or the person is in the group for agents no tab holds):
+ /// the agent is then exactly where it would have been anyway.
+ void adopt(AgentRef agent) {
+ final tabId = _activeTabId;
+ if (!_state.enabled || tabId == null) return;
+ final tab = _state.synced.where((t) => t.id == tabId).firstOrNull;
+ if (tab == null) return;
+ final pane = DeskPaneRef(
+ machineId: agent.machineId,
+ agentId: agent.agentId,
+ );
+ if (tab.panes.contains(pane)) return;
+ _queue([
+ {'op': 'pane.add', 'tabId': tabId, ...pane.toJson()},
+ ]);
+ }
+
+ /// An agent deleted on this phone leaves every tab that held it.
+ ///
+ /// A window that had it open removes it too, as soon as it hears the agent is
+ /// gone — but only a window that is RUNNING, and the person deleting an agent
+ /// from a phone is by definition away from it. Left undone, the tab keeps a
+ /// pane that can never attach.
+ void drop(AgentRef agent) {
+ if (!_state.enabled) return;
+ final pane = DeskPaneRef(
+ machineId: agent.machineId,
+ agentId: agent.agentId,
+ );
+ final ops = [
+ for (final tab in _state.synced)
+ if (tab.panes.contains(pane))
+ {'op': 'pane.remove', 'tabId': tab.id, ...pane.toJson()},
+ ];
+ if (ops.isEmpty) return;
+ _queue(ops);
+ }
+
+ /// Believe the write, show it, and send it. The desk's answer (or a document
+ /// from another computer) is applied over it afterwards, with anything still
+ /// unacknowledged laid back on top.
+ void _queue(List<Map<String, dynamic>> ops) {
+ _state.synced = applyDeskOps(_state.synced, ops);
+ _state.pending.addAll(ops);
+ appLog.debug('desk', 'queued ${ops.map((op) => op['op']).join(' ')}');
+ onChanged();
+ unawaited(_flush());
+ }
+
+ Future<void> _flush() async {
+ if (_disposed ||
+ !_state.enabled ||
+ _state.inFlight ||
+ _state.pending.isEmpty) {
+ return;
+ }
+ _state.inFlight = true;
+ final generation = _generation;
+ final batch = List<Map<String, dynamic>>.from(_state.pending);
+ Map<String, dynamic>? raw;
+ try {
+ raw = await write(batch);
+ } catch (error) {
+ _state.inFlight = false;
+ if (_disposed || generation != _generation) return;
+ // Kept, not dropped: an agent created in a tunnel still joins that tab
+ // once there is a network again. Backoff, capped at a minute.
+ _state.failures++;
+ final wait = Duration(
+ seconds: (5 * (1 << (_state.failures - 1).clamp(0, 4))).clamp(5, 60),
+ );
+ appLog.warn(
+ 'desk',
+ 'write failed (${batch.length} ops, retry in ${wait.inSeconds}s): $error',
+ );
+ _retry?.cancel();
+ _retry = Timer(wait, () => unawaited(_flush()));
+ return;
+ }
+ _state.inFlight = false;
+ if (_disposed || generation != _generation) return;
+ _state.failures = 0;
+ _retry?.cancel();
+ _retry = null;
+ // Acknowledged, or refused for good — either way these are no longer this
+ // phone's to replay.
+ _state.pending.removeRange(0, batch.length.clamp(0, _state.pending.length));
+ final doc = DeskDoc.fromJson(raw);
+ if (doc == null) {
+ appLog.info('desk', 'write not accepted — the desk is left alone');
+ _state.enabled = false;
+ _state.pending.clear();
+ onChanged();
+ return;
+ }
+ _apply(doc);
+ if (_state.pending.isNotEmpty) unawaited(_flush());
+ }
+
+ /// Sign-out, or a different account signing in: everything about the last
+ /// desk goes, including writes it never managed to send. They were that
+ /// account's, and this phone is no longer holding it.
+ void reset() {
+ _generation++;
+ _retry?.cancel();
+ _retry = null;
++ pause();
+ _joining = null;
+ _activeTabId = null;
+ _lastAgent.clear();
+ _state.reset();
+ }
+
+ void dispose() {
+ _disposed = true;
+ _retry?.cancel();
+ _retry = null;
++ pause();
+ }
+}
diff --cc mobile/lib/terminal/terminal_session.dart
index bfd3ff119,16e170c80..ad13c05e2
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@@ -102,9 -167,9 +167,10 @@@ class TerminalSession extends ChangeNot
required this.engineId,
required this.send,
required this.sendBinary,
+ this.client,
this.onOpenStalled,
this.resyncTimeout = const Duration(seconds: 4),
+ this.takeover = true,
}) {
terminal = _newTerminal();
}
@@@ -306,9 -328,9 +377,10 @@@
_inputSendTail = Future<void>.value();
streamId = null;
linkMode = null;
+ watching = false;
errorCode = null;
errorMessage = null;
+ takenOverBy = null;
_expectedSeq = null;
_lastRenderedSeq = -1;
_framesSinceAck = 0;
@@@ -364,8 -385,7 +436,9 @@@
'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,
+ if (client != null) 'client': client!.toJson(),
};
var sent = await send('terminal_open', openPayload);
if (!_isCurrent(generation) ||
diff --cc mobile/test/desk_fixture.dart
index d195773fe,000000000..e07e16fd5
mode 100644,000000..100644
--- a/mobile/test/desk_fixture.dart
+++ b/mobile/test/desk_fixture.dart
@@@ -1,73 -1,0 +1,78 @@@
+import 'package:harness_mobile/api/api_client.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/desk_sync.dart';
+
+import 'agent_pager_fixture.dart';
+
+/// The backend's desk routes, answered in memory: a document, and ops applied
+/// to it the way `backend/src/routes/desk.ts` applies them.
+///
+/// Every other call is the real [ApiClient]'s, which in a test reaches a Dio
+/// that is never built — nothing here makes one.
+class DeskApi extends ApiClient {
+ DeskApi({this.tabs = const []})
+ : super(config: AppConfig.dev, session: AuthSession());
+
+ List<DeskTab> tabs;
+ int revision = 0;
+
+ /// The ops this phone sent, in order.
+ final List<Map<String, dynamic>> written = [];
+
+ Map<String, dynamic> get doc => {
+ 'revision': revision,
+ 'tabs': [for (final tab in tabs) tab.toJson()],
+ };
+
+ @override
+ Future<Map<String, dynamic>?> desk() async => doc;
+
+ @override
+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {
+ written.addAll(ops);
+ tabs = applyDeskOps(tabs, ops);
+ revision++;
+ return doc;
+ }
+}
+
+/// A tab of `m`'s agents, named.
+DeskTab deskTab(String id, String name, List<String> agentIds) => DeskTab(
+ id: id,
+ name: name,
+ panes: [
+ for (final agentId in agentIds)
+ DeskPaneRef(machineId: 'm', agentId: agentId),
+ ],
+);
+
+/// The pager fixture's app — one machine `m` running [pagerAgentIds] — signed
+/// in to an account whose desk holds [tabs].
+///
+/// [opensTerminals] false leaves the machine listing its agents while refusing
+/// to open a stream for any of them (`AppNotifier._canAttachAgent`). For a test
+/// about which agents a tab offers, that is the difference between asserting on
+/// a list and nursing four terminal sessions through their keyframes.
+Future<AppNotifier> deskApp(
+ PagerConn conn, {
+ List<DeskTab> tabs = const [],
+ bool opensTerminals = true,
+}) async {
+ final app = pagerApp(conn);
+ app.api = DeskApi(tabs: tabs);
+ if (!opensTerminals) {
+ app.stateOf('m')!.terminalCapabilityAvailable = false;
+ }
+ await app.deskSyncForTest();
++ // ⚠️ A test is not a phone somebody is holding. Joining the desk arms the
++ // foreground poll (see [PhoneDesk.pollInterval]), and `testWidgets` fails a
++ // test that leaves a timer running. Tests about the poll itself drive
++ // [PhoneDesk] directly, with an interval of their own.
++ app.handleAppPaused();
+ return app;
+}
+
+/// The desk this app is talking to.
+DeskApi deskApiOf(AppNotifier app) => app.api as DeskApi;