The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(phone_desk): implement PhoneDesk class for managing desk tabs and agent operations
Dev jacob6491141a1cdc
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.tsindex 2c61f62f1..6fa95684d 100644--- a/backend/src/lib/webWs.ts+++ b/backend/src/lib/webWs.ts@@ -23,7 +23,7 @@ import { createWss, WS_LIMITS } from './wsServer.js'import { extractKey } from '../utils/crypto.js'import { machineIdFromKey } from '../utils/crypto.js'import { prisma, machineAlive } from './prisma.js'-import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair } from './bus.js'+import { getAgentPresence, getAgentPresenceMany, subscribeStatus, getDevicePresence, subscribeDeviceStatus, subscribeDeviceMachineListChanged, subscribeDeviceE2eePair, subscribeDeskChanged } from './bus.js'import { attachHubClient, trackSocketLiveness, type HubClient } from './hub.js'import { authenticateAccessToken, SsoAuthError, type AuthUser } from './ssoAuth.js'import type { Frame } from './tunnel.js'@@ -260,6 +260,22 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (closed) { machineListUnsub(); machineListUnsub = null }})().catch((err) => logger.warn('web-ws machine-list watch failed', { userId: user.sub, error: String(err) }))+ // ── The account's desk: its tabs changed somewhere ───────────────────────────────────────────+ // The same `desk:{userId}` invalidation every adapter socket hears (lib/adapterWs.ts), forwarded+ // to the clients that have no daemon to relay it — the phone. One frame carrying the revision;+ // the document itself is re-read over REST, so a burst of edits collapses into one GET.+ //+ // ⚠️ A phone holds one of these sockets PER MACHINE, so it hears this once per machine. The+ // revision is what makes that harmless: an app already at that revision fetches nothing.+ let deskUnsub: (() => void) | null = null+ void (async () => {+ deskUnsub = await subscribeDeskChanged(user.sub, (msg) => {+ if (ws.readyState !== WebSocket.OPEN) return+ send({ type: 'desk_changed', payload: { revision: msg.revision } })+ })+ if (closed) { deskUnsub(); deskUnsub = null }+ })().catch((err) => logger.warn('web-ws desk watch failed', { userId: user.sub, error: String(err) }))+// ── User-level E2EE device-pair requests ─────────────────────────────────────────────────────// Not tied to current machine selection: any logged-in page can receive the notice, then the frontend// checks whether this browser already trusts the target machine before showing the global popup.@@ -523,6 +539,7 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {if (deviceStatusUnsub) { deviceStatusUnsub(); deviceStatusUnsub = null }if (machineListUnsub) { machineListUnsub(); machineListUnsub = null }if (deviceE2eePairUnsub) { deviceE2eePairUnsub(); deviceE2eePairUnsub = null }+ if (deskUnsub) { deskUnsub(); deskUnsub = null }logger.info('web user disconnected', { userId: user.sub, machineId: currentAgentId ?? undefined })}ws.on('close', cleanup)diff --git a/mobile/README.md b/mobile/README.mdindex ac655156c..0b2a7cd27 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -23,7 +23,7 @@ The app it runs now lives under `lib/`, in the same folders the desktop app uses| | ||---|---|| `lib/core/` | models, config, platform, file store, crash log |-| `lib/state/` | `AppNotifier` — machines, agents, connections, panes |+| `lib/state/` | `AppNotifier` — machines, agents, connections, panes, the account's desk || `lib/api/`, `lib/ws/` | REST to the backend, and the relay socket per machine || `lib/auth/`, `lib/viewer/` | SSO, device linking, and the viewer's stand-ins for the harness CLI || `lib/e2ee/` | the end-to-end encryption this app terminates itself |@@ -39,6 +39,25 @@ Two folders are this package's own, and have no counterpart on the desktop:harness CLI opens with werift on the desktop's behalf, so a terminal rides p2p or TURN when it canand the relay only when it must.+## The account's tabs are the desk's, here too++The tabs a person has are one document per account on the backend (`/api/desk`), the same on every+computer they sign in on. The desktop owns its half of that in `desktop/lib/state/desk_sync.dart`,+which is **vendored here unchanged**; `lib/state/phone_desk.dart` is this package's own other half,+and it is deliberately not the window's:++- A window's tabs ARE its `swarms`, so the desktop diffs that projection after every layout change.+ A phone's `swarms` are not tabs — they are where the pager attaches the agents either side of the+ one on screen — so nothing here is projected onto the desk.+- The phone reads the tabs, follows them (`desk_changed` rides each machine's relay socket, since a+ phone holds no adapter socket of its own), and writes exactly twice: an agent created here joins+ the tab the phone is in, and one deleted here leaves every tab that held it.+- Which tab is open, and where you were inside it, stay on the device — as they do per window.++What the person sees of it is `lib/phone/desk_tab_strip.dart`, the chip rail under the terminal's+header, and a swipe that walks that tab's agents rather than the whole account+(`lib/phone/desk_groups.dart`).+## It is a VIEWER build, alwaysNo harness CLI runs beside this app and no agent is ever hosted here. It holds its own SSO session anddiff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex b38c2521f..efe117143 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -85,6 +85,30 @@ class ApiClient {unwrapApiResponse(res);}+ // -- the desk: the account's tabs, the same on every computer --++ /// `{revision, tabs}` as the backend holds it (its `routes/desk.ts`); null on+ /// a backend that predates the desk (404) or a session it will not take+ /// (401) — the phone then has no tabs to show and swipes the whole account,+ /// as it did before the desk existed.+ Future<Map<String, dynamic>?> desk() async {+ final res = await _dio.get('/api/desk');+ if (res.statusCode == 404 || res.statusCode == 401) return null;+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }++ /// Apply [ops] to the desk; answers the desk as it is afterwards. Null under+ /// the same two conditions as [desk].+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async {+ final res = await _dio.post(+ '/api/desk/ops',+ data: {'ops': ops},+ options: Options(headers: {'x-adapter-local': '1'}),+ );+ if (res.statusCode == 404 || res.statusCode == 401) return null;+ return unwrapApiResponse(res) as Map<String, dynamic>?;+ }+// -- voice (backend only: the viewer's own SSO session signs it) --/// The words in one WAV recording, in [lang] — `POST /api/voice/stt`, thediff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex 7ef18d661..99a7bca88 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -13,6 +13,8 @@ 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';@@ -504,27 +506,61 @@ class _AgentHomeState extends State<AgentHome> {return _AgentHomeEmpty(notifier: widget.notifier);}var chosen = (machineId: target.machineId, agentId: target.agent.id);+ // ⚠️ **A swipe stays inside one tab, and this is where that happens.** The+ // account's tabs are the desk's (`state/phone_desk.dart`); [deskGroups]+ // fills each one with the agents of it this phone can reach, and the tab+ // the agent about to be shown belongs to is the one the screen is in. The+ // pager is given THAT tab's agents and nothing else — so a tab of four is+ // four swipes, and the other tabs are a tap on the strip away.+ //+ // Derived from the agent rather than held as state on purpose: an agent+ // can arrive from search, from a notification or from the record of last+ // time, none of which know about tabs, and the strip still lights the tab+ // it belongs to. An account with no tabs gets one group over everything,+ // which is the phone exactly as it was.+ final groups = deskGroups(widget.notifier, entries);+ var group = activeDeskGroup(widget.notifier, groups, chosen);// ⚠️ **The swipe list is a snapshot, so it is retaken when the SET of agents changes.** It is// taken as the pager opens, and on launch that is as soon as one machine answers — a second// machine's agents arriving a moment later never reached it, and a pager built around one// agent has no neighbours: nothing to swipe to until the app was restarted. Order changes do// not count (see [_neighbours] for why they must not), only agents joining or leaving.//+ // ⚠️ The set is the TAB's now, so a tab changing on another computer+ // retakes it too — an agent added to this tab in a window is one swipe+ // away here a moment later, and one closed there stops being reachable.+ //// Rebuilt around the agent ON SCREEN, not the one the pager opened on — the person stays- // where they are, now with every agent beside them.+ // where they are, now with every agent of the tab beside them.final snapshot = _neighbours;if (snapshot != null &&- _neighboursFor != null &&- !_sameAgents(snapshot, entries)) {+ // ⚠️ **Only while the pager is STAYING where it is.** `target` is the+ // agent the pager opened on for as long as that agent is openable, so+ // anything else means the screen is being moved on purpose — a tab+ // tapped on the strip, an agent picked in search, a machine just+ // unlocked. The set of agents differs from the snapshot then by+ // definition (it is another tab's), and holding onto the agent on+ // screen below would quietly undo the move: the tab would light for+ // a frame and the terminal would stay where it was.+ _neighboursFor == chosen &&+ !_sameAgents(snapshot, group.entries)) {final showing = _showing;final onScreen = showing == null ? null : _entryFor(entries, showing);if (onScreen != null) {chosen = (machineId: onScreen.machineId, agentId: onScreen.agent.id);+ // The agent held onto may be in a different tab than the one the+ // target named — a tab closed on another computer moves what is on+ // screen into another group, or into "Other".+ group = activeDeskGroup(widget.notifier, groups, chosen);}_neighboursFor = null;_neighbours = null;_pagerGeneration++;}+ // What the phone is in, recorded for the paths that cannot derive it: an+ // agent created here joins this tab (`PhoneDesk.adopt`), and coming back+ // to a tab returns to the agent it was left on.+ widget.notifier.noteDeskTab(group.id, showing: chosen);// A pager already up for this agent is LEFT ALONE — same key, same snapshot, so it keeps the// page it is on, and [_showing] keeps naming whatever it has been swiped to. A pager is built// here only when there is none, or when the one there opened on an agent that can no longer be@@ -536,7 +572,7 @@ class _AgentHomeState extends State<AgentHome> {// every swipe the pager reported, one frame after it reported it.if (_neighboursFor != chosen) {_neighboursFor = chosen;- _neighbours = AgentSwipeList(entries);+ _neighbours = AgentSwipeList(group.entries);_showing = chosen;// ⚠️ **The attach, which nothing else makes for the page this screen opens on.** A pager// pushed from a list got it from `openAgent`, which starts `selectAgent` beside the push;@@ -577,12 +613,23 @@ class _AgentHomeState extends State<AgentHome> {notifier: widget.notifier,machineId: opened.machineId,agentId: opened.agentId,- // The whole reachable list, so a swipe walks every agent on the account. There is no list- // screen to go back to any more, which makes this the only way to another agent.+ // The tab's agents, so a swipe walks the tab and stops at its ends —+ // see the note above [groups].neighbours: _neighbours,// Told where it has swiped to, so [_showing] follows the pager rather than the pager being// dragged back to where this screen last put it.onAgentChanged: _onAgentChanged,+ // The way to the other tabs, now that a swipe is not one. Left off+ // where there is nothing to choose between — one tab, or an account+ // with no tabs at all — so a phone that has never seen a desk keeps the+ // header it always had.+ tabStrip: groups.length < 2+ ? null+ : DeskTabStrip(+ notifier: widget.notifier,+ groups: groups,+ active: group,+ ),);},);diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dartindex 781163a71..c2432a4e7 100644--- a/mobile/lib/phone/agent_swipe.dart+++ b/mobile/lib/phone/agent_swipe.dart@@ -33,6 +33,7 @@ class AgentSwipeHost extends StatefulWidget {required this.agentId,required this.neighbours,this.onAgentChanged,+ this.tabStrip,});final AppNotifier notifier;@@ -45,6 +46,14 @@ class AgentSwipeHost extends StatefulWidget {/// Null for a page opened without neighbours, which is then simply the page.final AgentSwipeList? neighbours;+ /// The desk's tabs, drawn under every page's header — see [DeskTabStrip].+ ///+ /// Handed down rather than built per page: the pages are this pager's, but the+ /// strip is about the SCREEN, and only the home screen has a tab to be in.+ /// Null everywhere else (a terminal opened from the Machines tab, a page+ /// pumped on its own), and the header is then exactly what it always was.+ final Widget? tabStrip;+/// Told which agent a swipe has arrived at, for a host that has to keep up with the pager.////// Only [AgentHome] passes it, and it needs it: the pager lives at the ROOT there and is rebuilt@@ -273,6 +282,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {agentId: widget.agentId,voice: _voice,isActive: true,+ tabStrip: widget.tabStrip,);}// ⚠️ **The keyboard goes at the START of the drag, not at [_onPageChanged].**@@ -341,6 +351,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {voice: _voice,// Exactly one mounted page, by page number — see [_page].isActive: i == _page,+ tabStrip: widget.tabStrip,),);},diff --git a/mobile/lib/phone/desk_groups.dart b/mobile/lib/phone/desk_groups.dartnew file mode 100644index 000000000..061a790be--- /dev/null+++ b/mobile/lib/phone/desk_groups.dart@@ -0,0 +1,136 @@+import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/state/desk_sync.dart';++import 'agent_index.dart';++/// The name of the group holding the agents no tab does.+///+/// Short because it is drawn as a chip beside real tab names, and a chip is the+/// one place on this screen with no room for a sentence.+const String kUntabbedGroupName = 'Other';++/// What the strip falls back to when the account has no tabs at all: one group+/// over everything, which is the phone exactly as it was before the desk.+const String kEveryAgentGroupName = 'All agents';++/// One tab of the desk as this phone can show it: its name, and the agents of it+/// that can actually be opened right now.+///+/// ⚠️ **A tab is not its agents.** The desk names `(machine, agent)` pairs, and a+/// phone reaches the ones whose machine is linked and answering — so a tab of+/// five can be a group of two, or of none, and the tab still exists. A group+/// with nothing in it is drawn and left inert rather than hidden: a tab that+/// vanished from the strip because its machine is asleep reads as a tab that was+/// deleted.+class DeskGroup {+ const DeskGroup({+ required this.id,+ required this.name,+ required this.entries,+ });++ /// The desk's id for the tab, or null for [kUntabbedGroupName] and for the+ /// single group a phone with no tabs shows.+ final String? id;++ final String name;++ /// The agents, in the tab's own order — which is the order a swipe walks.+ final List<AgentEntry> entries;++ bool get isEmpty => entries.isEmpty;++ bool holds(AgentRef agent) => entries.any(+ (entry) =>+ entry.machineId == agent.machineId && entry.agent.id == agent.agentId,+ );+}++/// The desk's tabs, filled with the agents from [visible] they hold.+///+/// [visible] is the phone's own list — [visibleAgents] — so the leftovers keep+/// the order the app would have shown them in. Agents with no terminal are left+/// out throughout: a group that counts agents nothing can open would offer a tab+/// that opens on "Attaching…" for ever.+///+/// The leftover group comes last, and only when there is something in it. Nobody+/// puts every agent on a tab, and with a swipe now staying inside one group the+/// agents outside them all would otherwise be reachable only through search.+///+/// Never empty: a phone with no tabs, and even one with no agents, still gets+/// the single group every caller below is allowed to assume.+List<DeskGroup> deskGroups(AppNotifier notifier, List<AgentEntry> visible) {+ final openable = [+ for (final entry in visible)+ if (entry.agent.terminalAvailable) entry,+ ];+ final tabs = notifier.deskTabs;+ // No desk, or a desk with nothing on it: one group over the lot. The strip+ // draws nothing for a single group, so this is the phone as it always was.+ if (tabs.isEmpty) {+ return [DeskGroup(id: null, name: kEveryAgentGroupName, entries: openable)];+ }+ final byKey = {+ for (final entry in openable)+ DeskPaneRef(machineId: entry.machineId, agentId: entry.agent.id).key:+ entry,+ };+ final claimed = <String>{};+ final groups = <DeskGroup>[];+ for (final tab in tabs) {+ final held = <AgentEntry>[];+ for (final pane in tab.panes) {+ final entry = byKey[pane.key];+ if (entry == null) continue;+ claimed.add(pane.key);+ held.add(entry);+ }+ groups.add(DeskGroup(id: tab.id, name: tab.name, entries: held));+ }+ final rest = [+ for (final entry in byKey.entries)+ if (!claimed.contains(entry.key)) entry.value,+ ];+ if (rest.isNotEmpty) {+ groups.add(DeskGroup(id: null, name: kUntabbedGroupName, entries: rest));+ }+ return groups;+}++/// The group the phone is in.+///+/// The agent on SCREEN decides it, not the other way round — which is what keeps+/// the strip honest when an agent is opened from somewhere with no idea of tabs+/// (search, a notification, the record of last time): whatever lands on screen,+/// the strip lights the tab it belongs to.+///+/// ⚠️ **The same agent can be on two tabs**, and then the tiebreak has to be+/// something that does not move on its own: the tab this phone was already in+/// ([AppNotifier.activeDeskTabId], which a tap on the strip sets before it opens+/// anything). Without it, an agent on two tabs would light whichever one the+/// desk happens to list first, and a tap on the other would appear to do nothing.+///+/// [groups] comes from [deskGroups] and is therefore never empty.+DeskGroup activeDeskGroup(+ AppNotifier notifier,+ List<DeskGroup> groups,+ AgentRef? showing,+) {+ final preferred = notifier.activeDeskTabId;+ if (showing != null) {+ final holding = [+ for (final group in groups)+ if (group.holds(showing)) group,+ ];+ if (holding.isNotEmpty) {+ return holding.where((group) => group.id == preferred).firstOrNull ??+ holding.first;+ }+ }+ // Nothing on screen yet — a launch, or the moment after a tab was tapped and+ // before its agent arrives. The tab last chosen holds the strip until then.+ return groups.where((group) => group.id == preferred).firstOrNull ??+ groups.where((group) => !group.isEmpty).firstOrNull ??+ groups.first;+}diff --git a/mobile/lib/phone/desk_tab_strip.dart b/mobile/lib/phone/desk_tab_strip.dartnew file mode 100644index 000000000..035bed6f4--- /dev/null+++ b/mobile/lib/phone/desk_tab_strip.dart@@ -0,0 +1,229 @@+import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'package:harness_mobile/shared/widgets/touch_target.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'desk_groups.dart';+import 'phone_navigation.dart';++/// The account's tabs, along the top of the terminal: one chip per tab, the one+/// you are in lit.+///+/// ⚠️ **This is the only way to change tabs on a phone, because a swipe no+/// longer does it.** A swipe used to walk every agent on the account; it walks+/// the agents of the tab you are in. That is the whole trade — a tab of four+/// agents is four swipes rather than forty — and it only works if the other+/// tabs are one tap away, in sight, without leaving the terminal.+///+/// ⚠️ **It draws nothing unless there is a choice.** One group is not a choice,+/// and a phone whose account has no tabs (or whose desk never answered) has+/// exactly one — so nothing about this screen changes for it.+class DeskTabStrip extends StatefulWidget {+ const DeskTabStrip({+ super.key,+ required this.notifier,+ required this.groups,+ required this.active,+ });++ final AppNotifier notifier;++ /// The tabs as this phone can show them — see [deskGroups].+ final List<DeskGroup> groups;++ /// The one the phone is in, from [activeDeskGroup].+ final DeskGroup? active;++ /// The row's height, insets included — what the header's column grows by.+ ///+ /// Shallow on purpose: every point of it is a point of terminal, and the row+ /// rides over one. A chip is 30pt tall inside it rather than the 44 a thumb+ /// wants, which the width makes up for — the target runs the whole length of+ /// the name, and [TouchTarget] takes what is left of the row around it.+ static const double height = 36;++ @override+ State<DeskTabStrip> createState() => _DeskTabStripState();+}++class _DeskTabStripState extends State<DeskTabStrip> {+ final _scroller = ScrollController();++ /// One key per tab, so the tab in play can be scrolled to.+ ///+ /// Kept across builds and keyed by the tab's own id: a strip of eight tabs is+ /// wider than a phone, and a tab switched to from outside the strip —+ /// search, a notification, the agent this launch opened on — is otherwise lit+ /// somewhere off the right edge.+ final _keys = <String?, GlobalKey>{};++ @override+ void dispose() {+ _scroller.dispose();+ super.dispose();+ }++ @override+ void didUpdateWidget(DeskTabStrip old) {+ super.didUpdateWidget(old);+ if (old.active?.id == widget.active?.id) return;+ // After the frame: the chip for the new tab may not have been laid out yet,+ // and `ensureVisible` needs a box to aim at.+ WidgetsBinding.instance.addPostFrameCallback((_) => _revealActive());+ }++ void _revealActive() {+ if (!mounted) return;+ final target = _keys[widget.active?.id]?.currentContext;+ if (target == null) return;+ unawaited(+ Scrollable.ensureVisible(+ target,+ alignment: 0.5,+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOut,+ ),+ );+ }++ /// A tab was tapped: the phone remembers it is in that tab, then opens the+ /// agent of it that the phone was last on — 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 strip would light+ /// the tab that was left.+ void _select(DeskGroup group) {+ if (group.id == widget.active?.id || group.isEmpty) return;+ widget.notifier.selectDeskTab(group.id);+ final remembered = widget.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, widget.notifier, target.machineId, target.agentId);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ _keys.removeWhere((id, _) => !widget.groups.any((group) => group.id == id));+ return SizedBox(+ height: DeskTabStrip.height,+ child: ListView.separated(+ controller: _scroller,+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3),+ itemCount: widget.groups.length,+ separatorBuilder: (_, _) => const SizedBox(width: 6),+ itemBuilder: (context, index) {+ final group = widget.groups[index];+ return _TabChip(+ key: _keys.putIfAbsent(group.id, GlobalKey.new),+ group: group,+ selected: group.id == widget.active?.id,+ onTap: () => _select(group),+ );+ },+ ),+ );+ }+}++/// One tab: its name, and how many of its agents this phone can open.+///+/// ⚠️ **A tab with none is drawn, dimmed and inert.** Its agents are on a+/// machine that is asleep or wants a password — a tab dropped from the strip for+/// that reads as a tab somebody deleted, and the count is the only thing on this+/// screen that says otherwise.+class _TabChip extends StatelessWidget {+ const _TabChip({+ super.key,+ required this.group,+ required this.selected,+ required this.onTap,+ });++ final DeskGroup group;+ final bool selected;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final color = group.isEmpty+ ? AppPalette.textFaint+ : selected+ ? AppPalette.accentOnSurface+ : AppPalette.textSecondary;+ return Semantics(+ button: !group.isEmpty,+ selected: selected,+ label: switch (group.entries.length) {+ 0 => '${group.name}, no agents here now',+ 1 => '${group.name}, 1 agent',+ final count => '${group.name}, $count agents',+ },+ child: TouchTarget(+ child: GestureDetector(+ onTap: group.isEmpty ? null : onTap,+ behavior: HitTestBehavior.opaque,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: selected+ ? AppSurface.accentWash+ : group.isEmpty+ ? null+ : AppSurface.selectedFill,+ borderRadius: BorderRadius.circular(999),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 11),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ // Bounded rather than ellipsed to a width: a tab is usually+ // named after a project, and half a name in a row of chips+ // tells you less than the next chip along would have.+ ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 140),+ child: Text(+ group.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: color,+ fontSize: 13,+ fontWeight: selected+ ? FontWeight.w600+ : FontWeight.w500,+ ),+ ),+ ),+ if (!group.isEmpty) ...[+ const SizedBox(width: 6),+ Text(+ '${group.entries.length}',+ style: TextStyle(+ color: selected+ ? AppPalette.accentOnSurface+ : AppPalette.textFaint,+ fontSize: 12,+ fontWeight: FontWeight.w500,+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 28ce99e3f..de3754674 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -51,6 +51,7 @@ class TerminalPage extends StatefulWidget {required this.agentId,required this.voice,this.isActive = true,+ this.tabStrip,});final AppNotifier notifier;@@ -73,6 +74,19 @@ class TerminalPage extends StatefulWidget {/// SIGWINCH to three remote shells at once.final bool isActive;+ /// The account's tabs, drawn under the header — see [DeskTabStrip], which is+ /// what this always is. Null on every terminal that is not the home screen's,+ /// and the header is then the row it has always been.+ ///+ /// ⚠️ **Handed in, not built here, and the reason is [_PageFacts].** This page+ /// only rebuilds itself when its OWN facts move (see [_onNotifier]) — a+ /// notifier tick that changed nothing about this agent is dropped, tabs+ /// included. A strip built in this build would therefore go stale the moment+ /// somebody changed the tabs on a computer. Built by [AgentHome], which does+ /// rebuild for the account, it arrives as a new widget and simply replaces+ /// the old one.+ final Widget? tabStrip;+@overrideState<TerminalPage> createState() => _TerminalPageState();}@@ -1189,6 +1203,12 @@ class _TerminalPageState extends State<TerminalPage>),],),+ // 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),// ⚠️ 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 leftdiff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex c14505f09..d0ff08e25 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -40,6 +40,8 @@ import 'dial_status.dart';import 'pane_layout_store.dart';import 'session_preview.dart';import 'terminal_pane.dart';+import 'desk_sync.dart';+import 'phone_desk.dart';import 'swarm.dart';import '../terminal/terminal_binary.dart';import '../update/desktop_updater.dart';@@ -516,6 +518,44 @@ class AppNotifier extends ChangeNotifier {final Set<String> expandedMachines = {};String? selectedMachineId;+ // ── the desk: the account's tabs, the same on every computer ─────────────+ //+ // `phone_desk.dart` holds the whole of it, including why a phone follows the+ // desk instead of projecting itself onto it the way a window does. Everything+ // here is a hand-off: the closures read `api` LAZILY, because signing in+ // replaces that client and a tear-off taken now would go on talking to the+ // old one.+ late final PhoneDesk _desk = PhoneDesk(+ read: () => api.desk(),+ write: (ops) => api.deskOps(ops),+ onChanged: notifyListeners,+ );++ /// The account's tabs, in the desk's order. Empty where the desk has nothing+ /// or has not answered — the phone then swipes the whole account, as it did+ /// before the desk existed.+ List<DeskTab> get deskTabs => _desk.tabs;++ /// The tab the phone is in, or null for the agents no tab holds.+ String? get activeDeskTabId => _desk.activeTabId;++ /// A tab picked by hand, in the strip. The screen answers by opening an agent+ /// of that tab.+ void selectDeskTab(String? tabId) => _desk.select(tabId);++ /// The tab the screen has worked out it is showing, and the agent of it on+ /// screen — see [PhoneDesk.note].+ void noteDeskTab(String? tabId, {AgentRef? showing}) =>+ _desk.note(tabId, showing: showing);++ /// Where this phone was in [tabId] last time it was in it.+ AgentRef? deskLastAgentIn(String? tabId) => _desk.lastAgentIn(tabId);++ /// Read the desk now, and wait for it — what a sign-in and the app coming+ /// back to the foreground both start without waiting.+ @visibleForTesting+ Future<void> deskSyncForTest() => _desk.refresh();+/// Swarms own arrangements; a shared pane owns one live terminal controller.final List<Swarm> swarms = [Swarm(id: 'swarm-1')];String _activeSwarmId = 'swarm-1';@@ -2239,6 +2279,10 @@ class AppNotifier extends ChangeNotifier {// The CLI has confirmed sign-in and daemon readiness. Display-name/avatar// metadata is independent of machine discovery and must not delay work.unawaited(_loadProfile());+ // The desk too: its tabs are what a swipe stays inside, and they are read+ // over REST rather than from any machine — so they can land before the+ // first machine has finished dialling.+ _desk.ensure();try {// The request a viewer already has in flight (above), or a fresh one where// there is none — a desktop, whose machine list is served by a daemon that@@ -2427,6 +2471,7 @@ class AppNotifier extends ChangeNotifier {signingIn = false;pendingAuthorizeUrl = null;_awaitingFirstMessage = null;+ _desk.reset();analyticsAccount.clear();_daemonSupervisionTimer?.cancel();_daemonSupervisionTimer = null;@@ -2687,6 +2732,9 @@ class AppNotifier extends ChangeNotifier {_daemonSupervisionTimer = null;_daemonGateFailed = false;_clearAllTurnActivity();+ // The desk belongs to the account, not to the phone: its tabs go with the+ // session, writes this phone never managed to send included.+ _desk.reset();currentUser = null;machines = [];machineStates.clear();@@ -3401,6 +3449,9 @@ class AppNotifier extends ChangeNotifier {return;}if (currentUser == null) unawaited(_loadProfile());+ // A boot that found the daemon still connecting finishes THROUGH here, so+ // the desk is joined here as well — [PhoneDesk.ensure] makes that once.+ _desk.ensure();try {await refreshMachines();if (!_authWorkCurrent(revision)) return;@@ -4792,6 +4843,10 @@ class AppNotifier extends ChangeNotifier {notifyListeners();return null;}+ // Created HERE, so it joins the tab this phone is in — the way an agent+ // created in a window joins that window's tab. See [PhoneDesk.adopt] for+ // what happens when the phone is in no tab.+ _desk.adopt((machineId: machineId, agentId: agent.id));await assignAgentToPane(null,machineId,@@ -4891,6 +4946,9 @@ class AppNotifier extends ChangeNotifier {final error = result['error'];if (error is String) return 'Delete failed: $error';await _removeAgent(machine, agentId);+ // Gone from the machine, so gone from the desk: a tab left holding it would+ // keep a pane no computer can ever attach. See [PhoneDesk.drop].+ _desk.drop((machineId: machineId, agentId: agentId));notifyListeners();return null;}@@ -6306,6 +6364,17 @@ class AppNotifier extends ChangeNotifier {}}break;+ case 'desk_changed':+ // The account's tabs changed — in a window on some computer, or on+ // another phone. The frame carries only the revision; the document+ // itself is fetched, so a burst of edits collapses into one read.+ //+ // ⚠️ It arrives once per MACHINE this phone is connected to (the backend+ // has no per-phone socket to send it on, so it rides each machine's —+ // `lib/webWs.ts`). [PhoneDesk.noticeRevision] is what makes four+ // machines mean one GET.+ _desk.noticeRevision(payload['revision']);+ return;case 'node_status':final online = payload['online'] == true;await _applyNodeStatus(machine, online);@@ -6518,7 +6587,15 @@ class AppNotifier extends ChangeNotifier {////// 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());+ }/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.@@ -6548,6 +6625,7 @@ class AppNotifier extends ChangeNotifier {}unawaited(_spokenTasks.close());sessionPreviews.dispose();+ _desk.dispose();super.dispose();}}diff --git a/mobile/lib/state/desk_sync.dart b/mobile/lib/state/desk_sync.dartnew file mode 100644index 000000000..2d2f58138--- /dev/null+++ b/mobile/lib/state/desk_sync.dart@@ -0,0 +1,326 @@+/// The desk: the account's tabs, the same on every computer.+///+/// The backend holds one document per user — `{ revision, tabs[] }`, each tab+/// `{ id, name, nameIsCustom?, panes: [{machineId, agentId}] }` — and changes it+/// through small idempotent ops (backend `lib/desk.ts` is the authority; the+/// copy of its rules here is for optimistic re-application only). This file is+/// the pure half: what a tab looks like on the wire, how two snapshots differ+/// as ops, and how ops apply to a snapshot. `AppNotifier` owns the other half —+/// turning `swarms` into a snapshot and a snapshot back into `swarms`.+///+/// What is NOT on the desk, by decision (owner, 2026-09-21): the active tab,+/// focus, zoom, pinned slots, presets, pane sizes, composer visibility, drafts,+/// Recently Closed, the Store tab and orchestrator tabs. Windows differ.+library;++import 'dart:math';++class DeskPaneRef {+ const DeskPaneRef({required this.machineId, required this.agentId});+ final String machineId;+ final String agentId;++ String get key => '$machineId\u0000$agentId';++ Map<String, dynamic> toJson() => {'machineId': machineId, 'agentId': agentId};++ static DeskPaneRef? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final machineId = raw['machineId'];+ final agentId = raw['agentId'];+ if (machineId is! String || machineId.isEmpty) return null;+ if (agentId is! String || agentId.isEmpty) return null;+ return DeskPaneRef(machineId: machineId, agentId: agentId);+ }++ @override+ bool operator ==(Object other) =>+ other is DeskPaneRef &&+ other.machineId == machineId &&+ other.agentId == agentId;++ @override+ int get hashCode => Object.hash(machineId, agentId);+}++class DeskTab {+ const DeskTab({+ required this.id,+ required this.name,+ this.nameIsCustom = false,+ this.panes = const [],+ });+ final String id;+ final String name;+ final bool nameIsCustom;+ final List<DeskPaneRef> panes;++ DeskTab copyWith({+ String? name,+ bool? nameIsCustom,+ List<DeskPaneRef>? panes,+ }) => DeskTab(+ id: id,+ name: name ?? this.name,+ nameIsCustom: nameIsCustom ?? this.nameIsCustom,+ panes: panes ?? this.panes,+ );++ Map<String, dynamic> toJson() => {+ 'id': id,+ 'name': name,+ if (nameIsCustom) 'nameIsCustom': true,+ 'panes': [for (final p in panes) p.toJson()],+ };++ static DeskTab? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final id = raw['id'];+ final name = raw['name'];+ if (id is! String || id.isEmpty || name is! String) return null;+ final panes = <DeskPaneRef>[];+ final seen = <String>{};+ if (raw['panes'] is List) {+ for (final item in raw['panes'] as List) {+ final pane = DeskPaneRef.fromJson(item);+ if (pane != null && seen.add(pane.key)) panes.add(pane);+ }+ }+ return DeskTab(+ id: id,+ name: name,+ nameIsCustom: raw['nameIsCustom'] == true,+ panes: panes,+ );+ }+}++class DeskDoc {+ const DeskDoc({required this.revision, required this.tabs});+ final int revision;+ final List<DeskTab> tabs;++ static DeskDoc? fromJson(Object? raw) {+ if (raw is! Map) return null;+ final revision = raw['revision'];+ if (revision is! int) return null;+ final tabs = <DeskTab>[];+ final seen = <String>{};+ if (raw['tabs'] is List) {+ for (final item in raw['tabs'] as List) {+ final tab = DeskTab.fromJson(item);+ if (tab != null && seen.add(tab.id)) tabs.add(tab);+ }+ }+ return DeskDoc(revision: revision, tabs: tabs);+ }+}++/// A desk id: a tab that has been on the desk (or is bound for it) carries a+/// random 128-bit id, never the per-window `swarm-N` two computers would both+/// mint. `isDeskId` is how a restored layout from before the desk is told apart.+String newDeskId() {+ final random = Random.secure();+ final bytes = List<int>.generate(16, (_) => random.nextInt(256));+ return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();+}++final _deskIdShape = RegExp(r'^[0-9a-f]{32}$');+bool isDeskId(String id) => _deskIdShape.hasMatch(id);++/// The ops that turn [before] into [after], in an order the backend applies+/// left to right: closes first, then creates, then renames and pane changes,+/// then order. Names are compared only where the person named the tab —+/// a derived name is each window's own to derive.+List<Map<String, dynamic>> deskDiff(List<DeskTab> before, List<DeskTab> after) {+ final ops = <Map<String, dynamic>>[];+ final beforeById = {for (final t in before) t.id: t};+ final afterById = {for (final t in after) t.id: t};++ for (final old in before) {+ if (!afterById.containsKey(old.id)) {+ ops.add({'op': 'tab.close', 'id': old.id});+ }+ }+ for (var i = 0; i < after.length; i++) {+ final tab = after[i];+ if (beforeById.containsKey(tab.id)) continue;+ ops.add({+ 'op': 'tab.create',+ 'id': tab.id,+ 'name': tab.name,+ if (tab.nameIsCustom) 'nameIsCustom': true,+ 'index': i,+ });+ for (var j = 0; j < tab.panes.length; j++) {+ ops.add({+ 'op': 'pane.add',+ 'tabId': tab.id,+ ...tab.panes[j].toJson(),+ 'index': j,+ });+ }+ }+ for (final tab in after) {+ final old = beforeById[tab.id];+ if (old == null) continue;+ if (tab.nameIsCustom && (tab.name != old.name || !old.nameIsCustom)) {+ ops.add({+ 'op': 'tab.rename',+ 'id': tab.id,+ 'name': tab.name,+ 'nameIsCustom': true,+ });+ }+ final oldKeys = old.panes.map((p) => p.key).toSet();+ final newKeys = tab.panes.map((p) => p.key).toSet();+ for (final p in old.panes) {+ if (!newKeys.contains(p.key)) {+ ops.add({'op': 'pane.remove', 'tabId': tab.id, ...p.toJson()});+ }+ }+ for (var j = 0; j < tab.panes.length; j++) {+ final p = tab.panes[j];+ if (!oldKeys.contains(p.key)) {+ ops.add({'op': 'pane.add', 'tabId': tab.id, ...p.toJson(), 'index': j});+ }+ }+ // Order among the panes both sides have: move the ones out of place.+ final kept = old.panes+ .where((p) => newKeys.contains(p.key))+ .map((p) => p.key)+ .toList();+ final wanted = tab.panes+ .where((p) => oldKeys.contains(p.key))+ .map((p) => p.key)+ .toList();+ if (!_sameOrder(kept, wanted)) {+ for (var j = 0; j < tab.panes.length; j++) {+ if (oldKeys.contains(tab.panes[j].key)) {+ ops.add({+ 'op': 'pane.move',+ 'tabId': tab.id,+ ...tab.panes[j].toJson(),+ 'index': j,+ });+ }+ }+ }+ }+ // Tab order, over the tabs both sides have.+ final keptTabs = before+ .where((t) => afterById.containsKey(t.id))+ .map((t) => t.id)+ .toList();+ final wantedTabs = after+ .where((t) => beforeById.containsKey(t.id))+ .map((t) => t.id)+ .toList();+ if (!_sameOrder(keptTabs, wantedTabs)) {+ for (var i = 0; i < after.length; i++) {+ if (beforeById.containsKey(after[i].id)) {+ ops.add({'op': 'tab.move', 'id': after[i].id, 'index': i});+ }+ }+ }+ return ops;+}++bool _sameOrder(List<String> a, List<String> b) {+ if (a.length != b.length) return false;+ for (var i = 0; i < a.length; i++) {+ if (a[i] != b[i]) return false;+ }+ return true;+}++/// The backend's rules, replayed here so a window can lay its unacknowledged+/// ops over a document that arrived meanwhile. Idempotent; an op on a tab+/// that is gone changes nothing.+List<DeskTab> applyDeskOps(List<DeskTab> tabs, List<Map<String, dynamic>> ops) {+ var next = [+ for (final t in tabs) t.copyWith(panes: [...t.panes]),+ ];+ int at(String id) => next.indexWhere((t) => t.id == id);+ int clamp(Object? index, int length) =>+ index is int ? index.clamp(0, length) : length;+ for (final op in ops) {+ switch (op['op']) {+ case 'tab.create':+ final id = op['id'] as String;+ if (at(id) >= 0) break;+ next.insert(+ clamp(op['index'], next.length),+ DeskTab(+ id: id,+ name: op['name'] as String,+ nameIsCustom: op['nameIsCustom'] == true,+ panes: [],+ ),+ );+ case 'tab.close':+ final i = at(op['id'] as String);+ if (i >= 0) next.removeAt(i);+ case 'tab.rename':+ final i = at(op['id'] as String);+ if (i < 0) break;+ next[i] = next[i].copyWith(+ name: op['name'] as String,+ nameIsCustom: op['nameIsCustom'] == true || next[i].nameIsCustom,+ );+ case 'tab.move':+ final i = at(op['id'] as String);+ if (i < 0) break;+ final tab = next.removeAt(i);+ next.insert(clamp(op['index'], next.length), tab);+ case 'pane.add':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane == null || next[i].panes.contains(pane)) break;+ next[i].panes.insert(clamp(op['index'], next[i].panes.length), pane);+ case 'pane.remove':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane != null) next[i].panes.remove(pane);+ case 'pane.move':+ final i = at(op['tabId'] as String);+ if (i < 0) break;+ final pane = DeskPaneRef.fromJson(op);+ if (pane == null) break;+ final j = next[i].panes.indexOf(pane);+ if (j < 0) break;+ next[i].panes.removeAt(j);+ next[i].panes.insert(clamp(op['index'], next[i].panes.length), pane);+ case 'seed':+ for (final raw in (op['tabs'] as List? ?? const [])) {+ final tab = DeskTab.fromJson(raw);+ if (tab == null || at(tab.id) >= 0) continue;+ next.add(tab.copyWith(panes: [...tab.panes]));+ }+ }+ }+ return next;+}++/// What a window holds about its sync with the desk: the last snapshot it and+/// the desk agreed on, the ops it has sent that the desk has not yet answered,+/// and the desk's revision as last heard.+class DeskSyncState {+ int revision = 0;+ List<DeskTab> synced = const [];+ final List<Map<String, dynamic>> pending = [];+ bool enabled = false;+ bool inFlight = false;+ int failures = 0;++ void reset() {+ revision = 0;+ synced = const [];+ pending.clear();+ enabled = false;+ inFlight = false;+ failures = 0;+ }+}diff --git a/mobile/lib/state/phone_desk.dart b/mobile/lib/state/phone_desk.dartnew file mode 100644index 000000000..13401a14a--- /dev/null+++ b/mobile/lib/state/phone_desk.dart@@ -0,0 +1,295 @@+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});++ /// `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;+ 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.+ Future<void> refresh() {+ if (!_state.enabled) {+ ensure();+ return Future<void>.value();+ }+ return _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',+ );+ }+ _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;+ _joining = null;+ _activeTabId = null;+ _lastAgent.clear();+ _state.reset();+ }++ void dispose() {+ _disposed = true;+ _retry?.cancel();+ _retry = null;+ }+}diff --git a/mobile/test/desk_fixture.dart b/mobile/test/desk_fixture.dartnew file mode 100644index 000000000..d195773fe--- /dev/null+++ b/mobile/test/desk_fixture.dart@@ -0,0 +1,73 @@+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();+ return app;+}++/// The desk this app is talking to.+DeskApi deskApiOf(AppNotifier app) => app.api as DeskApi;diff --git a/mobile/test/desk_groups_test.dart b/mobile/test/desk_groups_test.dartnew file mode 100644index 000000000..e7dacb1c5--- /dev/null+++ b/mobile/test/desk_groups_test.dart@@ -0,0 +1,126 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/agent_index.dart';+import 'package:harness_mobile/phone/desk_groups.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'agent_pager_fixture.dart';+import 'desk_fixture.dart';++/// The desk's tabs, as the phone's strip and its swipe see them.+///+/// The fixture's machine runs four agents — a, b, c, d — and every test below+/// is about which of them a given tab offers.+void main() {+ late PagerConn conn;++ setUp(() => conn = PagerConn());++ Future<AppNotifier> appWith(List<String> desktop, List<String> docker) async {+ final built = await deskApp(+ conn,+ tabs: [+ deskTab('t1', 'Desktop', desktop),+ deskTab('t2', 'Docker', docker),+ ],+ );+ addTearDown(built.dispose);+ return built;+ }++ List<String> agentsOf(DeskGroup group) => [+ for (final entry in group.entries) entry.agent.id,+ ];++ List<DeskGroup> groupsOf(AppNotifier built) =>+ deskGroups(built, visibleAgents(agentIndex(built)));++ test('each tab holds its own agents, in the tab\'s order', () async {+ final built = await appWith(['b', 'a'], ['c']);++ final groups = groupsOf(built);++ expect(+ [for (final group in groups) group.name],+ ['Desktop', 'Docker', kUntabbedGroupName],+ );+ expect(agentsOf(groups[0]), ['b', 'a']);+ expect(agentsOf(groups[1]), ['c']);+ });++ test('the agents no tab holds are a group of their own, last', () async {+ final built = await appWith(['a'], ['b']);++ final groups = groupsOf(built);++ expect(groups.last.name, kUntabbedGroupName);+ expect(groups.last.id, isNull);+ expect(agentsOf(groups.last), ['c', 'd']);+ });++ test('nothing left over means no group for it', () async {+ final built = await appWith(['a', 'b'], ['c', 'd']);++ expect(+ [for (final group in groupsOf(built)) group.name],+ ['Desktop', 'Docker'],+ );+ });++ test('an account with no tabs gets one group over every agent', () async {+ final built = await deskApp(conn);+ addTearDown(built.dispose);++ final groups = groupsOf(built);++ expect(groups, hasLength(1));+ expect(groups.single.name, kEveryAgentGroupName);+ expect(agentsOf(groups.single), ['a', 'b', 'c', 'd']);+ });++ test('a tab naming agents this phone cannot reach is drawn empty', () async {+ final built = await appWith(['nobody'], ['c']);++ final groups = groupsOf(built);++ expect(groups[0].isEmpty, isTrue);+ expect(agentsOf(groups[1]), ['c']);+ // And the unreachable agent is nobody's leftover either.+ expect(agentsOf(groups.last), ['a', 'b', 'd']);+ });++ test(+ 'the tab the phone is in is the one holding the agent on screen',+ () async {+ final built = await appWith(['a'], ['c']);+ final groups = groupsOf(built);++ final active = activeDeskGroup(built, groups, (+ machineId: 'm',+ agentId: 'c',+ ));++ expect(active.name, 'Docker');+ },+ );++ test('an agent on two tabs stays in the one the phone chose', () async {+ final built = await appWith(['a', 'c'], ['c']);+ final groups = groupsOf(built);+ const showing = (machineId: 'm', agentId: 'c');++ // Nothing chosen yet: the desk's own order settles it.+ expect(activeDeskGroup(built, groups, showing).name, 'Desktop');++ built.selectDeskTab('t2');+ expect(activeDeskGroup(built, groups, showing).name, 'Docker');+ });++ test('with nothing on screen the tab last chosen holds the strip', () async {+ final built = await appWith(['a'], ['c']);+ final groups = groupsOf(built);++ built.selectDeskTab('t2');++ expect(activeDeskGroup(built, groups, null).name, 'Docker');+ });+}diff --git a/mobile/test/desk_writes_test.dart b/mobile/test/desk_writes_test.dartnew file mode 100644index 000000000..715c92d44--- /dev/null+++ b/mobile/test/desk_writes_test.dart@@ -0,0 +1,108 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'agent_pager_fixture.dart';+import 'desk_fixture.dart';++/// A machine that starts and deletes the agents it is asked to, and answers+/// everything else with nothing.+class _Conn extends PagerConn {+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async => switch (type) {+ 'agent_create' => {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': {+ 'id': 'new',+ 'name': 'new',+ 'engine': 'claude',+ 'terminal': {'available': true},+ },+ },+ _ => {},+ };+}++/// What the phone tells the desk, and what the desk tells the phone.+///+/// The phone FOLLOWS the tabs — it never projects its own panes onto them, see+/// `state/phone_desk.dart` — so there are exactly two things it says, and both+/// are a person acting on this phone.+void main() {+ List<String> agentsOf(AppNotifier app, String tabId) => [+ for (final pane in app.deskTabs.firstWhere((t) => t.id == tabId).panes)+ pane.agentId,+ ];++ test('an agent created on the phone joins the tab the phone is in', () async {+ final app = await deskApp(+ _Conn(),+ opensTerminals: false,+ tabs: [+ deskTab('t1', 'Desktop', ['a']),+ deskTab('t2', 'Docker', ['c']),+ ],+ );+ addTearDown(app.dispose);+ // What the home screen records every time it draws — see `noteDeskTab`.+ app.noteDeskTab('t2');++ final error = await app.createAgent('m', engine: 'claude', folder: '/work');+ await pumpEventQueue();++ expect(error, isNull);+ expect(agentsOf(app, 't2'), ['c', 'new']);+ expect(deskApiOf(app).written, [+ {'op': 'pane.add', 'tabId': 't2', 'machineId': 'm', 'agentId': 'new'},+ ]);+ });++ test('an agent deleted on the phone leaves the tabs it was on', () async {+ final app = await deskApp(+ _Conn(),+ opensTerminals: false,+ tabs: [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['b']),+ ],+ );+ addTearDown(app.dispose);++ final error = await app.deleteAgent('m', 'b');+ await pumpEventQueue();++ expect(error, isNull);+ expect(agentsOf(app, 't1'), ['a']);+ expect(agentsOf(app, 't2'), isEmpty);+ expect(deskApiOf(app).written.map((op) => op['tabId']), ['t1', 't2']);+ });++ test('a desk_changed push brings the tabs from the other computer', () async {+ final app = await deskApp(+ _Conn(),+ opensTerminals: false,+ tabs: [+ deskTab('t1', 'Desktop', ['a']),+ ],+ );+ addTearDown(app.dispose);++ deskApiOf(app).tabs = [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['c']),+ ];+ deskApiOf(app).revision++;+ await app.handleEventForTest('m', {+ 'type': 'desk_changed',+ 'payload': {'revision': deskApiOf(app).revision},+ });+ await pumpEventQueue();++ expect([for (final tab in app.deskTabs) tab.name], ['Desktop', 'Docker']);+ expect(agentsOf(app, 't1'), ['a', 'b']);+ });+}diff --git a/mobile/test/phone_desk_tabs_test.dart b/mobile/test/phone_desk_tabs_test.dartnew file mode 100644index 000000000..a227daaa6--- /dev/null+++ b/mobile/test/phone_desk_tabs_test.dart@@ -0,0 +1,172 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/phone/agent_home.dart';+import 'package:harness_mobile/phone/agent_swipe.dart';+import 'package:harness_mobile/phone/desk_groups.dart';+import 'package:harness_mobile/phone/desk_tab_strip.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/state/desk_sync.dart';++import 'agent_pager_fixture.dart';+import 'desk_fixture.dart';++/// The home screen inside its tab: a swipe walks the tab the phone is in, and+/// the strip is how it gets to another one.+///+/// ⚠️ **The pager's `neighbours` is the assertion throughout, because it IS the+/// swipe.** [AgentSwipeHost] pages through exactly that list and nothing else,+/// so a list holding one tab's agents is a swipe that stays inside that tab —+/// which is the whole change, and it can be read without flinging anything.+void main() {+ /// The home screen as the shell mounts it: an agent picked anywhere else —+ /// the strip included — arrives through [AgentHome.openAgent], and the shell+ /// is what carries it there.+ Future<AppNotifier> pumpHome(+ WidgetTester tester, {+ required List<DeskTab> tabs,+ }) async {+ final app = await deskApp(+ PagerConn(),+ // Nothing here is about the terminals themselves — see [deskApp].+ opensTerminals: false,+ tabs: tabs,+ );+ addTearDown(app.dispose);+ final request = ValueNotifier<({String machineId, String agentId})?>(null);+ addTearDown(request.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: PhoneShellScope(+ onMachineLinked: (_) {},+ onOpenAgent: (machineId, agentId) =>+ request.value = (machineId: machineId, agentId: agentId),+ child: AgentHome(notifier: app, openAgent: request),+ ),+ ),+ );+ await tester.pump();+ return app;+ }++ AgentSwipeHost pager(WidgetTester tester) =>+ tester.widget<AgentSwipeHost>(find.byType(AgentSwipeHost));++ List<String> swipesOver(WidgetTester tester) => [+ for (final entry in pager(tester).neighbours!.entries) entry.agent.id,+ ];++ testWidgets('a swipe walks the tab the agent on screen is in', (+ tester,+ ) async {+ await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['c']),+ ],+ );++ expect(pager(tester).agentId, 'a');+ expect(swipesOver(tester), ['a', 'b']);+ });++ testWidgets('tapping a tab opens its first agent, and swipes inside it', (+ tester,+ ) async {+ await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['c', 'd']),+ ],+ );++ await tester.tap(find.text('Docker'));+ await tester.pump();+ await tester.pump();++ expect(pager(tester).agentId, 'c');+ expect(swipesOver(tester), ['c', 'd']);+ });++ testWidgets('the agents no tab holds are a tab of their own', (tester) async {+ await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a']),+ deskTab('t2', 'Docker', ['b']),+ ],+ );++ await tester.tap(find.text(kUntabbedGroupName));+ await tester.pump();+ await tester.pump();++ expect(pager(tester).agentId, 'c');+ expect(swipesOver(tester), ['c', 'd']);+ });++ testWidgets('coming back to a tab returns to the agent it was left on', (+ tester,+ ) async {+ final app = await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['c', 'd']),+ ],+ );++ // Swiped to `b` and then away to the other tab.+ app.noteDeskTab('t1', showing: (machineId: 'm', agentId: 'b'));+ await tester.tap(find.text('Docker'));+ await tester.pump();+ await tester.pump();+ expect(pager(tester).agentId, 'c');++ await tester.tap(find.text('Desktop'));+ await tester.pump();+ await tester.pump();++ expect(pager(tester).agentId, 'b');+ });++ testWidgets('one tab is no choice, so no strip is drawn', (tester) async {+ // Every agent on the one tab: nothing to switch to, and the header is the+ // row it has always been.+ await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a', 'b', 'c', 'd']),+ ],+ );++ expect(find.byType(DeskTabStrip), findsNothing);+ });++ testWidgets('a tab changed on another computer moves the swipe with it', (+ tester,+ ) async {+ final app = await pumpHome(+ tester,+ tabs: [+ deskTab('t1', 'Desktop', ['a']),+ deskTab('t2', 'Docker', ['c']),+ ],+ );+ expect(swipesOver(tester), ['a']);++ // A window on some computer adds an agent to the tab this phone is in.+ deskApiOf(app).tabs = [+ deskTab('t1', 'Desktop', ['a', 'b']),+ deskTab('t2', 'Docker', ['c']),+ ];+ deskApiOf(app).revision++;+ await app.deskSyncForTest();+ await tester.pump();++ expect(pager(tester).agentId, 'a');+ expect(swipesOver(tester), ['a', 'b']);+ });+}diff --git a/mobile/test/phone_desk_test.dart b/mobile/test/phone_desk_test.dartnew file mode 100644index 000000000..63b9bc284--- /dev/null+++ b/mobile/test/phone_desk_test.dart@@ -0,0 +1,277 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/state/desk_sync.dart';+import 'package:harness_mobile/state/phone_desk.dart';++/// A backend holding one desk document, which answers ops the way `routes/desk.ts`+/// does: apply them, bump the revision, hand back what that produced.+class _Backend {+ _Backend({this.tabs = const []});++ List<DeskTab> tabs;+ int _revision = 0;+ int reads = 0;++ /// Every op this backend was ever sent, in order — the phone's side of the+ /// conversation.+ final List<Map<String, dynamic>> received = [];++ /// Set to refuse the next write the way a daemon that has lost its session+ /// does: with nothing.+ bool refuseWrites = false;++ /// Set to fail every call, as a phone with no network does.+ bool offline = false;++ Map<String, dynamic> get _doc => {+ 'revision': _revision,+ 'tabs': [for (final tab in tabs) tab.toJson()],+ };++ Future<Map<String, dynamic>?> read() async {+ if (offline) throw StateError('no network');+ reads++;+ return _doc;+ }++ Future<Map<String, dynamic>?> write(List<Map<String, dynamic>> ops) async {+ if (offline) throw StateError('no network');+ received.addAll(ops);+ if (refuseWrites) return null;+ tabs = applyDeskOps(tabs, ops);+ _revision++;+ return _doc;+ }++ /// Another computer changing the tabs.+ void edit(List<Map<String, dynamic>> ops) {+ tabs = applyDeskOps(tabs, ops);+ _revision++;+ }+}++DeskTab _tab(String id, String name, List<String> agentIds) => DeskTab(+ id: id,+ name: name,+ panes: [+ for (final agentId in agentIds)+ DeskPaneRef(machineId: 'm', agentId: agentId),+ ],+);++List<String> _agentsOf(PhoneDesk desk, String tabId) => [+ for (final pane in desk.tabs.firstWhere((tab) => tab.id == tabId).panes)+ pane.agentId,+];++void main() {+ late _Backend backend;+ late PhoneDesk desk;+ var changes = 0;++ PhoneDesk deskOver(_Backend backend) => PhoneDesk(+ read: backend.read,+ write: backend.write,+ onChanged: () => changes++,+ );++ setUp(() {+ changes = 0;+ backend = _Backend(+ tabs: [+ _tab('t1', 'Desktop', ['a', 'b']),+ _tab('t2', 'Docker', ['c']),+ ],+ );+ desk = deskOver(backend);+ addTearDown(() => desk.dispose());+ });++ Future<void> join() async {+ desk.ensure();+ await pumpEventQueue();+ }++ test('a phone with no desk yet has no tabs, and says so', () {+ expect(desk.enabled, isFalse);+ expect(desk.tabs, isEmpty);+ });++ test('joining reads the desk once and keeps its tabs in order', () async {+ await join();++ expect(desk.enabled, isTrue);+ expect([for (final tab in desk.tabs) tab.name], ['Desktop', 'Docker']);+ expect(_agentsOf(desk, 't1'), ['a', 'b']);+ expect(backend.reads, 1);++ // Joined already: a second call is the no-op every sign-in path relies on.+ desk.ensure();+ await pumpEventQueue();+ expect(backend.reads, 1);+ });++ test(+ 'a read that fails leaves the phone without tabs, and it can join later',+ () async {+ backend.offline = true;+ await join();+ expect(desk.enabled, isFalse);++ backend.offline = false;+ await join();+ expect(desk.enabled, isTrue);+ expect(desk.tabs, hasLength(2));+ },+ );++ test(+ 'desk_changed only fetches for a revision the phone has not seen',+ () async {+ await join();+ final afterJoin = backend.reads;++ // The same revision, once per machine the phone is connected to.+ desk.noticeRevision(0);+ desk.noticeRevision(0);+ await pumpEventQueue();+ expect(backend.reads, afterJoin);++ backend.edit([+ {'op': 'tab.create', 'id': 't3', 'name': 'Research', 'index': 2},+ ]);+ desk.noticeRevision(1);+ await pumpEventQueue();+ expect(backend.reads, afterJoin + 1);+ expect(+ [for (final tab in desk.tabs) tab.name],+ ['Desktop', 'Docker', 'Research'],+ );+ },+ );++ test('an agent created on the phone joins the tab the phone is in', () async {+ await join();+ desk.note('t2');++ desk.adopt((machineId: 'm', agentId: 'new'));++ // Believed at once, so the strip and the swipe list have it this frame.+ expect(_agentsOf(desk, 't2'), ['c', 'new']);+ await pumpEventQueue();+ expect(backend.received, [+ {'op': 'pane.add', 'tabId': 't2', 'machineId': 'm', 'agentId': 'new'},+ ]);+ expect(_agentsOf(desk, 't2'), ['c', 'new']);+ });++ test('an agent created outside every tab changes nothing', () async {+ await join();+ // The group for the agents no tab holds — see `desk_groups.dart`.+ desk.note(null);++ desk.adopt((machineId: 'm', agentId: 'new'));+ await pumpEventQueue();++ expect(backend.received, isEmpty);+ });++ test('an agent deleted on the phone leaves every tab that held it', () async {+ backend = _Backend(+ tabs: [+ _tab('t1', 'Desktop', ['a', 'b']),+ _tab('t2', 'Docker', ['b']),+ ],+ );+ desk = deskOver(backend);+ await join();++ desk.drop((machineId: 'm', agentId: 'b'));+ await pumpEventQueue();++ expect(_agentsOf(desk, 't1'), ['a']);+ expect(_agentsOf(desk, 't2'), isEmpty);+ expect(backend.received.map((op) => op['tabId']), ['t1', 't2']);+ });++ test(+ 'a write held up by the network is kept and replayed, not dropped',+ () async {+ await join();+ desk.note('t2');+ backend.offline = true;++ desk.adopt((machineId: 'm', agentId: 'new'));+ await pumpEventQueue();++ // Shown as done here, and still owed to the backend.+ expect(_agentsOf(desk, 't2'), ['c', 'new']);+ expect(backend.received, isEmpty);++ // A document arriving meanwhile does not undo it: the unsent op is laid+ // back over whatever the desk says.+ backend.offline = false;+ backend.edit([+ {'op': 'pane.add', 'tabId': 't1', 'machineId': 'm', 'agentId': 'd'},+ ]);+ await desk.refresh();++ expect(_agentsOf(desk, 't1'), ['a', 'b', 'd']);+ expect(_agentsOf(desk, 't2'), ['c', 'new']);+ },+ );++ test('a write the backend will not take stops the phone writing', () async {+ await join();+ desk.note('t1');+ backend.refuseWrites = true;++ desk.adopt((machineId: 'm', agentId: 'new'));+ await pumpEventQueue();++ expect(desk.enabled, isFalse);+ expect(backend.received, hasLength(1));++ desk.adopt((machineId: 'm', agentId: 'later'));+ await pumpEventQueue();+ expect(backend.received, hasLength(1));+ });++ test(+ 'a tab picked by hand is remembered, with where the phone was in it',+ () async {+ await join();++ desk.select('t2');+ expect(desk.activeTabId, 't2');+ expect(changes, greaterThan(0));++ desk.note('t2', showing: (machineId: 'm', agentId: 'c'));+ desk.note('t1', showing: (machineId: 'm', agentId: 'b'));+ expect(desk.lastAgentIn('t2'), (machineId: 'm', agentId: 'c'));+ expect(desk.lastAgentIn('t1'), (machineId: 'm', agentId: 'b'));+ },+ );++ test(+ 'signing out takes the tabs, the tab you were in, and the unsent writes',+ () async {+ await join();+ desk.note('t1');+ backend.offline = true;+ desk.adopt((machineId: 'm', agentId: 'new'));+ await pumpEventQueue();++ desk.reset();++ expect(desk.enabled, isFalse);+ expect(desk.tabs, isEmpty);+ expect(desk.activeTabId, isNull);+ expect(desk.lastAgentIn('t1'), isNull);++ // The write belonged to the account that left: the next one must not send it.+ backend.offline = false;+ await pumpEventQueue();+ expect(backend.received, isEmpty);+ },+ );+}