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(mobile): swipe between agents on the terminal page
tony13e0f6f57ba8
diff --git a/mobile/lib/phone/agent_hero.dart b/mobile/lib/phone/agent_hero.dartdeleted file mode 100644index 99527e570..000000000--- a/mobile/lib/phone/agent_hero.dart+++ /dev/null@@ -1,258 +0,0 @@-import 'package:flutter/material.dart';--import 'package:harness/shared/theme/app_theme.dart';--/// The row expanding into the header of the page it opens.-///-/// ⚠️ **The Hero carries the HEADER, not the whole page.** Two earlier versions got this wrong in-/// opposite directions and both read as broken:-///-/// - Wrapping only the engine mark made one glyph fly across an otherwise ordinary push — a-/// detail escaping the transition rather than a transition.-/// - Wrapping the entire page made the flight cover the screen while the route was also fading,-/// so two full-screen layers crossed and the screen visibly flashed at both ends.-///-/// A row is header-shaped: a mark, a title, a status line, 70pt tall. The terminal page's header is-/// the same shape. So the row becomes the header — one object, one motion — and the terminal body-/// below it arrives on its own, sliding up under a header that has already landed. That is also the-/// order the data is ready in: the header can be drawn from the agent immediately, the terminal-/// cannot be drawn until the pane attaches.-///-/// ⚠️ **The tag must include where the flight STARTED, not just the agent.**-///-/// The phone shell is an [IndexedStack] of three tabs, and every tab stays MOUNTED — that is what-/// lets a tab remember its stack. Both the Agents tab and the Machines tab draw rows for the same-/// agents, so keying on the agent alone puts two Heroes with one tag in the same subtree, and-/// Flutter throws `There are multiple heroes that share the same tag within a subtree` the moment-/// either is pushed from.-String agentHeroTag({- required String machineId,- required String agentId,- required AgentHeroSource source,-}) => 'agent:$machineId/$agentId@${source.name}';--/// Which list a terminal page was opened from — the half of [agentHeroTag] that keeps two mounted-/// tabs from claiming one tag.-enum AgentHeroSource {- /// The Agents tab's cross-machine list.- agents,-- /// One machine's own agent list, under the Machines tab.- machine,-}--/// How long the body takes to arrive after the header has landed.-const Duration kAgentBodyDelay = Duration(milliseconds: 90);--/// How long the flight itself runs. Longer than Material's 300ms default: the box travels most of-/// the screen's height, and at 300ms that distance reads as a jump rather than a movement.-const Duration kAgentHeroDuration = Duration(milliseconds: 340);--/// Wraps a list row so it expands into the page's header.-///-/// [tag] is null where there is nothing to fly to — an agent with no terminal does not open, so a-/// Hero on it would be a tag with one end. That case draws the plain child.-class AgentHeroCard extends StatelessWidget {- const AgentHeroCard({super.key, required this.tag, required this.child});-- final String? tag;- final Widget child;-- @override- Widget build(BuildContext context) => _wrap(tag, child);-}--/// The header end of the flight.-class AgentHeroHeader extends StatelessWidget {- const AgentHeroHeader({super.key, required this.tag, required this.child});-- final String? tag;- final Widget child;-- @override- Widget build(BuildContext context) => _wrap(tag, child);-}--Widget _wrap(String? tag, Widget child) {- if (tag == null) return child;- return Hero(- tag: tag,- // A straight rect tween, not Material's default arc. The row and the header are both at the top- // of the screen and differ mostly in width, so an arced path bows the box sideways on the way —- // motion across an axis the two ends do not actually differ on.- createRectTween: (begin, end) => RectTween(begin: begin, end: end),- flightShuttleBuilder: (_, animation, direction, fromContext, toContext) =>- _Shuttle(- animation: animation,- forward: direction == HeroFlightDirection.push,- from: (fromContext.widget as Hero).child,- to: (toContext.widget as Hero).child,- ),- child: child,- );-}--/// What is drawn while the row is becoming the header.-///-/// The box itself is what moves — Flutter tweens its rect — and this only has to make the surface-/// inside it change from a card to a page header: the corner straightens and the row's fill drains-/// away to nothing, because the header sits directly on the page rather than on a card.-///-/// The two ends cross-fade over the middle of the flight rather than at its edges. At the start the-/// box is still row-shaped and the row's own layout is the only one that fits it; at the end it is-/// header-shaped and the header's is. Swapping in the middle is the one point where neither is-/// visibly wrong.-class _Shuttle extends StatelessWidget {- const _Shuttle({- required this.animation,- required this.forward,- required this.from,- required this.to,- });-- final Animation<double> animation;- final bool forward;- final Widget from;- final Widget to;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- // On a pop the flight runs backwards, so read the animation the other way for every tween below- // to follow the direction of travel.- final t = forward- ? animation- : ReverseAnimation(animation) as Animation<double>;- final eased = CurvedAnimation(parent: t, curve: Curves.easeInOutCubic);- return AnimatedBuilder(- animation: eased,- builder: (context, _) {- final v = eased.value;- // The card's surface fades out rather than lerping to the page colour: the header has no- // fill of its own, and lerping to `windowBg` would paint an opaque rectangle over whatever- // the page is drawing behind the header — the flash the full-page version had.- final fill = AppGlass.rowFill.withValues(- alpha: AppGlass.rowFill.a * (1 - v),- );- return DecoratedBox(- decoration: BoxDecoration(- color: fill,- borderRadius: BorderRadius.circular(AppCard.radius * (1 - v)),- border: Border.all(- color: AppGlass.hair.withValues(alpha: AppGlass.hair.a * (1 - v)),- ),- ),- child: ClipRRect(- borderRadius: BorderRadius.circular(AppCard.radius * (1 - v)),- child: Stack(- fit: StackFit.expand,- children: [- if (v < 0.6)- Opacity(- opacity: (1 - v / 0.6).clamp(0.0, 1.0),- child: _Loose(child: from),- ),- if (v > 0.4)- Opacity(- opacity: ((v - 0.4) / 0.6).clamp(0.0, 1.0),- child: _Loose(child: to),- ),- ],- ),- ),- );- },- );- }-}--/// Lays a flight end out at its own natural height inside the moving box.-///-/// Both ends are built for a height they do not have mid-flight, and letting either lay out against-/// the in-between box makes it reflow on every frame. An unbounded height plus the clip above shows-/// whatever fits and hides the rest.-class _Loose extends StatelessWidget {- const _Loose({required this.child});-- final Widget child;-- @override- Widget build(BuildContext context) => OverflowBox(- alignment: Alignment.topCenter,- minHeight: 0,- maxHeight: double.infinity,- child: child,- );-}--/// The terminal body, arriving after the header has landed.-///-/// Held back until the flight is nearly over and then slid up a short distance. Two reasons it is-/// not simply part of the page from the first frame: a full-screen terminal drawn behind a header-/// that is still mid-flight is the second layer that made the old version flash, and the body is-/// genuinely not ready that early — the pane attaches after the push.-class AgentBodyReveal extends StatefulWidget {- const AgentBodyReveal({super.key, required this.child});-- final Widget child;-- @override- State<AgentBodyReveal> createState() => _AgentBodyRevealState();-}--class _AgentBodyRevealState extends State<AgentBodyReveal>- with SingleTickerProviderStateMixin {- late final AnimationController _controller = AnimationController(- vsync: this,- duration: const Duration(milliseconds: 260),- );-- /// Guards the one-time start: `didChangeDependencies` runs again on any inherited-widget change- /// (a theme flip, a metrics change), and restarting the reveal there would replay it mid-session.- bool _started = false;-- @override- void didChangeDependencies() {- super.didChangeDependencies();- if (_started) return;- _started = true;- // `ModalRoute.of` needs a context that is already in the tree, so this cannot be `initState`.- //- // A route with no animation, or one already finished — a rebuild, a page restored under an- // existing one — resolves immediately and the body is simply there. Only a live push waits.- final animation = ModalRoute.of(context)?.animation;- if (animation == null || animation.isCompleted) {- _controller.value = 1;- return;- }- Future<void>.delayed(kAgentBodyDelay, () {- if (mounted) _controller.forward();- });- }-- @override- void dispose() {- _controller.dispose();- super.dispose();- }-- @override- Widget build(BuildContext context) {- final curve = CurvedAnimation(- parent: _controller,- curve: Curves.easeOutCubic,- );- return FadeTransition(- opacity: curve,- child: SlideTransition(- // A short rise — 4% of the body's height. Enough to read as arriving from under the header,- // small enough that nothing is off-screen long enough to notice.- position: Tween<Offset>(- begin: const Offset(0, 0.04),- end: Offset.zero,- ).animate(curve),- child: widget.child,- ),- );- }-}diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dartindex dc0bbaaf7..b1f6f47e6 100644--- a/mobile/lib/phone/agent_index.dart+++ b/mobile/lib/phone/agent_index.dart@@ -59,17 +59,38 @@ List<AgentEntry> waitingAgents(List<AgentEntry> entries) =>/// the one worth putting where the eye lands.List<AgentEntry> otherAgents(List<AgentEntry> entries) {final rest = entries.where((entry) => !entry.isWaiting).toList();- rest.sort((a, b) {- if (a.isWorking != b.isWorking) return a.isWorking ? -1 : 1;- // Then agents that can actually be opened, so a row with no terminal never heads the list.- final aOpen = a.agent.terminalAvailable;- final bOpen = b.agent.terminalAvailable;- if (aOpen != bOpen) return aOpen ? -1 : 1;- return 0;- });- return rest;+ // A stable sort, which `List.sort` is not — see [filterableMachines] for the same technique and+ // the same reason. It matters more here than it does for the chips: the terminal page walks this+ // order to find the next agent along, so an unstable tie would let two idle agents swap places on+ // an unrelated rebuild and send a swipe to a different agent than the list was offering.+ final indexed = [for (final (index, entry) in rest.indexed) (index, entry)]+ ..sort((a, b) {+ final aEntry = a.$2;+ final bEntry = b.$2;+ if (aEntry.isWorking != bEntry.isWorking) {+ return aEntry.isWorking ? -1 : 1;+ }+ // Then agents that can actually be opened, so a row with no terminal never heads the list.+ final aOpen = aEntry.agent.terminalAvailable;+ final bOpen = bEntry.agent.terminalAvailable;+ if (aOpen != bOpen) return aOpen ? -1 : 1;+ return a.$1.compareTo(b.$1);+ });+ return [for (final (_, entry) in indexed) entry];}+/// Every agent the list draws, in the order a finger meets them.+///+/// The tab draws two sections from the same entries — [waitingAgents] then [otherAgents] — and that+/// concatenation, not [agentIndex], is the order somebody actually sees. The terminal page swipes+/// along it, so it has to be built in ONE place: a page computing "the next agent" from a slightly+/// different order than the list it was opened from would skip an agent, or hand back the one just+/// left, and nothing on screen would explain why.+List<AgentEntry> visibleAgents(List<AgentEntry> entries) => [+ ...waitingAgents(entries),+ ...otherAgents(entries),+];+/// The machines the filter chips offer, in the order they are drawn.////// Every machine on the account, not just the ready ones: a chip is also how somebody notices thatdiff --git a/mobile/lib/phone/agent_row.dart b/mobile/lib/phone/agent_row.dartindex 0f85e51d2..0c68bad90 100644--- a/mobile/lib/phone/agent_row.dart+++ b/mobile/lib/phone/agent_row.dart@@ -3,7 +3,6 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness/shared/theme/app_theme.dart';import 'package:harness/widgets/engine_identity.dart';-import 'agent_hero.dart';import 'agent_index.dart';import 'phone_card.dart';import 'status_pill.dart';@@ -23,62 +22,51 @@ class AgentRow extends StatelessWidget {Widget build(BuildContext context) {AppTheme.watch(context);final agent = entry.agent;- return AgentHeroCard(- // An agent with no terminal does not open, so there is no page for the row to become — a tag- // here would be one end of a flight that never happens.- tag: agent.terminalAvailable- ? agentHeroTag(- machineId: entry.machineId,- agentId: agent.id,- source: AgentHeroSource.agents,- )+ return PhoneCard(+ onTap: agent.terminalAvailable ? onTap : null,+ // A rim in the attention colour, so a waiting agent is findable in a long list without+ // reading a word of it — the list's whole job on a phone.+ border: entry.isWaiting+ ? Border.all(color: AppPalette.warn.withValues(alpha: 0.42)): null,- child: PhoneCard(- onTap: agent.terminalAvailable ? onTap : null,- // A rim in the attention colour, so a waiting agent is findable in a long list without- // reading a word of it — the list's whole job on a phone.- border: entry.isWaiting- ? Border.all(color: AppPalette.warn.withValues(alpha: 0.42))- : null,- child: Row(- children: [- PhoneCardGlyph(- child: EngineMark(- engine: agent.engine,- displayName: agent.engineDisplayName,- size: 22,- ),+ child: Row(+ children: [+ PhoneCardGlyph(+ child: EngineMark(+ engine: agent.engine,+ displayName: agent.engineDisplayName,+ size: 22,),- const SizedBox(width: 14),- Expanded(- child: Column(- mainAxisAlignment: MainAxisAlignment.center,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- agent.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- color: AppPalette.textPrimary,- fontSize: 16,- fontWeight: FontWeight.w600,- ),+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ agent.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 16,+ fontWeight: FontWeight.w600,),- const SizedBox(height: 5),- _StatusAndMachine(entry: entry),- ],- ),+ ),+ const SizedBox(height: 5),+ _StatusAndMachine(entry: entry),+ ],),- const SizedBox(width: 8),- if (agent.terminalAvailable)- Icon(- LucideIcons.chevronRight300,- size: 22,- color: AppPalette.textFaint,- ),- ],- ),+ ),+ const SizedBox(width: 8),+ if (agent.terminalAvailable)+ Icon(+ LucideIcons.chevronRight300,+ size: 22,+ color: AppPalette.textFaint,+ ),+ ],),);}diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dartnew file mode 100644index 000000000..82921b3b9--- /dev/null+++ b/mobile/lib/phone/agent_swipe.dart@@ -0,0 +1,237 @@+import 'dart:async';++import 'package:flutter/material.dart';++import 'package:harness/state/app_state.dart';+import 'agent_index.dart';+import 'terminal_page.dart';++/// The agents a terminal page can swipe between, in the order the list drew them.+///+/// A SNAPSHOT, taken when the page opens. The Agents tab sorts partly on state that moves by itself+/// — an idle agent that starts working sorts upward — so a pager recomputing this list would+/// renumber its own pages under the finger: the page to the right could become a different agent+/// between one swipe and the next, for a reason nothing on screen explains.+///+/// Only entries that can actually be opened are kept. A row with no terminal does nothing when+/// tapped in the list, and a page for it would be a screen of "Attaching…" that never resolves —+/// worse mid-swipe than in a list, where at least the row is still readable.+class AgentSwipeList {+ AgentSwipeList(List<AgentEntry> entries)+ : entries = [+ for (final entry in entries)+ if (entry.agent.terminalAvailable) entry,+ ];++ final List<AgentEntry> entries;++ bool get isEmpty => entries.isEmpty;++ /// Whether the pager wraps around — past the last agent is the first one again.+ ///+ /// Needs at least TWO agents, and that is not a formality. With one, every page of an endless+ /// pager is the same agent: the screen would take a swipe, move, and land on what it just left,+ /// which reads as the gesture having failed rather than as a list with one thing in it. One agent+ /// gets one page and no swipe at all.+ bool get wraps => entries.length > 1;++ /// Where an agent sits in the snapshot, or null if it is not in it.+ ///+ /// Used once, to find the page to open on: the tapped row may be a "Waiting for you" row, an+ /// agent with no terminal may have been dropped by the constructor above, and neither the list's+ /// index nor the row's position can be assumed to survive either.+ int? indexOf(String machineId, String agentId) {+ for (final (index, entry) in entries.indexed) {+ if (entry.machineId == machineId && entry.agent.id == agentId) {+ return index;+ }+ }+ return null;+ }+}++/// One agent's terminal, with the agents beside it a swipe away.+///+/// ⚠️ **The pager holds the route, and [TerminalPage] no longer does.** The page draws one agent's+/// header and terminal, but a swipe has to move something ABOVE it — so this sits between the route+/// and the page. Without [neighbours] it is a passthrough, which is how the Machines tab still gets+/// the old single-page behaviour.+///+/// Exactly one page is ACTIVE at a time, and that word is load-bearing: [TerminalPanel] claims the+/// keyboard whenever it is built focused, so three mounted pages all claiming it would put the+/// software keyboard on a terminal nobody is looking at — and the characters typed into it would+/// reach that agent. See [TerminalPage.isActive].+class AgentSwipeHost extends StatefulWidget {+ const AgentSwipeHost({+ super.key,+ required this.notifier,+ required this.machineId,+ required this.agentId,+ required this.neighbours,+ });++ final AppNotifier notifier;++ /// The agent the route was opened on — the page that is shown first. Never changes; where the+ /// pager has moved to since is [_AgentSwipeHostState._current].+ final String machineId;+ final String agentId;++ /// Null for a page opened without neighbours, which is then simply the page.+ final AgentSwipeList? neighbours;++ @override+ State<AgentSwipeHost> createState() => _AgentSwipeHostState();+}++class _AgentSwipeHostState extends State<AgentSwipeHost> {+ /// How many laps of the list the opening page sits above zero — see [initState].+ static const _origin = 1000;++ PageController? _controller;++ /// The page being looked at, which is what decides [TerminalPage.isActive].+ ///+ /// ⚠️ **A page, not an agent, and on a short list the difference is a bug.** A wrapped pager of+ /// two agents mounts pages N-1, N and N+1 — and N-1 and N+1 are the SAME agent as each other.+ /// Testing "is this page's agent the current agent" would then mark two mounted pages active at+ /// once, and two live [TerminalPanel]s both claiming the keyboard is exactly what `isActive`+ /// exists to prevent: the one that wins can be the page off-screen.+ int _page = 0;++ /// The agent showing now — [_page]'s entry, named rather than numbered.+ ///+ /// Both forms are kept because the two questions genuinely differ once the pager wraps: which PAGE+ /// is on screen decides who may hold the keyboard, and which AGENT is on screen decides which pane+ /// [_detachAll] spares on the way out. A page number cannot answer the second — the agent it names+ /// has panes attached under other page numbers too.+ late ({String machineId, String agentId}) _current = (+ machineId: widget.machineId,+ agentId: widget.agentId,+ );++ /// Every agent this pager attached, so leaving can detach them again.+ ///+ /// ⚠️ **Without this the pager leaks terminals.** The phone's old rule was one pane, enforced by+ /// closing every other one on the way in; a pager has to keep its neighbours attached, so nothing+ /// would ever close them. Each pane left behind is a remote stream with a 10,000-line scrollback+ /// and a heartbeat, held for a screen that is gone — and swiping through ten agents and going back+ /// would leave ten of them.+ ///+ /// Recorded rather than recomputed: by the time this page is disposed the list may have moved on,+ /// and the panes to close are the ones actually opened, not the ones a fresh list would name.+ final Set<({String machineId, String agentId})> _attached = {};++ @override+ void initState() {+ super.initState();+ _attached.add(_current);+ final neighbours = widget.neighbours;+ if (neighbours == null || neighbours.isEmpty) return;+ // The snapshot is fixed for as long as this pager lives, so the opening page is the only index+ // that ever has to be looked up — from there the controller and the list stay in step, and+ // [_page] and [_current] both follow from `onPageChanged` alone.+ final start = neighbours.indexOf(widget.machineId, widget.agentId) ?? 0;+ // Opening in the MIDDLE of the endless run, not at its start, is what lets the first swipe go+ // either way: page 0 has nothing to its left, and the last agent has to be reachable by swiping+ // back from the first one. `_origin` is far enough from both ends that neither is reachable by+ // hand — ~1,000 laps of the list — and it is a whole number of laps, so `page % length` still+ // names the agent.+ _page = neighbours.wraps+ ? _origin * neighbours.entries.length + start+ : start;+ _controller = PageController(initialPage: _page);+ }++ @override+ void dispose() {+ _controller?.dispose();+ _detachAll();+ super.dispose();+ }++ /// Closes what this pager opened, keeping the one the phone is still pointed at.+ ///+ /// The agent last read stays attached — that is the pane the Agents tab's row now refers to, and+ /// re-opening it should be instant rather than a fresh "Attaching…". Everything swiped past goes.+ ///+ /// Not awaited, and deliberately: `dispose` cannot wait, and `closePane` only has to be STARTED —+ /// it detaches the session and tells the daemon on its own. The notifier outlives this widget, so+ /// nothing here is torn down underneath it.+ void _detachAll() {+ final notifier = widget.notifier;+ final keep = _current;+ for (final agent in _attached) {+ if (agent == keep) continue;+ final pane = notifier.panes+ .where((p) => p.machineId == agent.machineId && p.agentId == agent.agentId)+ .firstOrNull;+ if (pane != null) unawaited(notifier.closePane(pane.id));+ }+ }++ @override+ Widget build(BuildContext context) {+ final neighbours = widget.neighbours;+ final controller = _controller;+ if (neighbours == null || controller == null || neighbours.isEmpty) {+ return TerminalPage(+ notifier: widget.notifier,+ machineId: widget.machineId,+ agentId: widget.agentId,+ isActive: true,+ );+ }+ return PageView.builder(+ controller: controller,+ // The terminal below scrolls vertically and selects text only with a mouse, so the horizontal+ // axis is free. The one gesture still competing for it is the route's own edge-swipe back,+ // which wins at the left margin because it is registered above this in the tree — deliberately+ // kept: that is how a page goes back on iOS, and the page slides out the way it came in.+ physics: const PageScrollPhysics(),+ // No count is what makes it endless: the builder answers for any page, and the modulo below+ // wraps it back onto the list. A one-agent list keeps its single page instead — see+ // [AgentSwipeList.wraps].+ itemCount: neighbours.wraps ? null : neighbours.entries.length,+ onPageChanged: _onPageChanged,+ itemBuilder: (context, i) {+ final entry = neighbours.entries[i % neighbours.entries.length];+ return TerminalPage(+ // ⚠️ Keyed by PAGE, not by agent, and the difference only shows once the pager wraps: an+ // endless run holds several pages for the same agent — the lap before and the lap after —+ // and an agent-shaped key would make Flutter treat two live pages as one widget, which+ // throws on a duplicate key the moment both are mounted. Each page then learns its own+ // `_hadPane`, which is what that flag wants anyway: it is about this page's attach, not+ // about the agent.+ key: ValueKey(i),+ notifier: widget.notifier,+ machineId: entry.machineId,+ agentId: entry.agent.id,+ // Exactly one mounted page, by page number — see [_page].+ isActive: i == _page,+ );+ },+ );+ }++ void _onPageChanged(int index) {+ final neighbours = widget.neighbours;+ if (neighbours == null || neighbours.isEmpty) return;+ // The page number runs off in both directions once the pager wraps; the agent it names does not.+ final entry = neighbours.entries[index % neighbours.entries.length];+ final arrived = (machineId: entry.machineId, agentId: entry.agent.id);+ // Recorded BEFORE the attach, so a pane always has an owner to close it — see [_attached]. An+ // agent added here that never finishes attaching costs nothing: [_detachAll] looks for its pane+ // and finds none.+ _attached.add(arrived);+ setState(() {+ _page = index;+ _current = arrived;+ });+ // Attaching is what makes the terminal live, and it only happens once the page has SETTLED —+ // `onPageChanged` fires at the halfway point of a settled swipe, not on every dragged pixel, so+ // flicking across five agents attaches the ones passed through rather than all of them at once.+ // `selectAgent` reuses a pane that is already there, so coming back costs nothing.+ unawaited(widget.notifier.selectAgent(entry.machineId, entry.agent.id));+ }+}diff --git a/mobile/lib/phone/agent_tile.dart b/mobile/lib/phone/agent_tile.dartindex a334347b1..1b9e7ccb8 100644--- a/mobile/lib/phone/agent_tile.dart+++ b/mobile/lib/phone/agent_tile.dart@@ -5,7 +5,6 @@ import 'package:harness/core/models.dart';import 'package:harness/shared/theme/app_theme.dart';import 'package:harness/state/app_state.dart';import 'package:harness/widgets/engine_identity.dart';-import 'agent_hero.dart';import 'phone_card.dart';import 'phone_status.dart';import 'status_pill.dart';@@ -27,55 +26,45 @@ class AgentTile extends StatelessWidget {@overrideWidget build(BuildContext context) {AppTheme.watch(context);- return AgentHeroCard(- // Null where the row does not open — see [AgentHeroCard].- tag: agent.terminalAvailable- ? agentHeroTag(- machineId: machine.machine.machineId,- agentId: agent.id,- source: AgentHeroSource.machine,- )- : null,- child: PhoneCard(- onTap: agent.terminalAvailable ? onTap : null,- child: Row(- children: [- PhoneCardGlyph(- child: EngineMark(- engine: agent.engine,- displayName: agent.engineDisplayName,- size: 22,- ),+ return PhoneCard(+ onTap: agent.terminalAvailable ? onTap : null,+ child: Row(+ children: [+ PhoneCardGlyph(+ child: EngineMark(+ engine: agent.engine,+ displayName: agent.engineDisplayName,+ size: 22,),- const SizedBox(width: 14),- Expanded(- child: Column(- mainAxisAlignment: MainAxisAlignment.center,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- agent.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- color: AppPalette.textPrimary,- fontSize: 16,- fontWeight: FontWeight.w600,- ),+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ agent.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 16,+ fontWeight: FontWeight.w600,),- const SizedBox(height: 5),- StatusPill(summary: phoneAgentSummary(machine, agent)),- ],- ),- ),- const SizedBox(width: 8),- Icon(- LucideIcons.chevronRight300,- size: 22,- color: AppPalette.textFaint,+ ),+ const SizedBox(height: 5),+ StatusPill(summary: phoneAgentSummary(machine, agent)),+ ],),- ],- ),+ ),+ const SizedBox(width: 8),+ Icon(+ LucideIcons.chevronRight300,+ size: 22,+ color: AppPalette.textFaint,+ ),+ ],),);}diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dartindex 6780e4a9e..b7120903e 100644--- a/mobile/lib/phone/agents_page.dart+++ b/mobile/lib/phone/agents_page.dart@@ -8,7 +8,6 @@ import 'package:harness/shared/widgets/app_icon_button.dart';import 'package:harness/shared/widgets/empty_state.dart';import 'package:harness/state/app_state.dart';-import 'agent_hero.dart';import 'agent_tile.dart';import 'link_page.dart';import 'phone_card.dart';@@ -221,13 +220,7 @@ class _AgentsBody extends StatelessWidget {itemBuilder: (context, index) => AgentTile(machine: machine,agent: agents[index],- onTap: () => openAgent(- context,- notifier,- _machineId,- agents[index].id,- heroSource: AgentHeroSource.machine,- ),+ onTap: () => openAgent(context, notifier, _machineId, agents[index].id),),);}diff --git a/mobile/lib/phone/agents_tab.dart b/mobile/lib/phone/agents_tab.dartindex e7556b394..2e06f3d8c 100644--- a/mobile/lib/phone/agents_tab.dart+++ b/mobile/lib/phone/agents_tab.dart@@ -4,7 +4,6 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness/shared/theme/app_theme.dart';import 'package:harness/shared/widgets/empty_state.dart';import 'package:harness/state/app_state.dart';-import 'agent_hero.dart';import 'agent_index.dart';import 'agent_row.dart';import 'account_button.dart';@@ -155,8 +154,12 @@ class _Body extends StatelessWidget {);}- final waiting = waitingAgents(entries);- final rest = otherAgents(entries);+ // The order a swipe on the terminal page walks, split back into the two sections this list+ // draws. Taken from [visibleAgents] rather than assembled here so the page and the list cannot+ // drift apart — the split below is presentation, the order is not.+ final ordered = visibleAgents(entries);+ final waiting = ordered.where((entry) => entry.isWaiting).toList();+ final rest = ordered.where((entry) => !entry.isWaiting).toList();return RefreshIndicator(onRefresh: notifier.retryMachines,child: ListView(@@ -165,31 +168,28 @@ class _Body extends StatelessWidget {children: [if (waiting.isNotEmpty) ...[const _SectionLabel('Waiting for you'),- for (final entry in waiting) _row(context, entry),+ for (final entry in waiting) _row(context, ordered, entry),const SizedBox(height: 6),],if (rest.isNotEmpty) ...[if (waiting.isNotEmpty) const _SectionLabel('All agents'),- for (final entry in rest) _row(context, entry),+ for (final entry in rest) _row(context, ordered, entry),],],),);}- Widget _row(BuildContext context, AgentEntry entry) => Padding(- padding: const EdgeInsets.only(bottom: kPhoneCardGap),- child: AgentRow(- entry: entry,- onTap: () => openAgent(- context,- notifier,- entry.machineId,- entry.agent.id,- heroSource: AgentHeroSource.agents,- ),- ),- );+ Widget _row(BuildContext context, List<AgentEntry> ordered, AgentEntry entry) =>+ Padding(+ padding: const EdgeInsets.only(bottom: kPhoneCardGap),+ child: AgentRow(+ entry: entry,+ // The whole visible list goes with the tap, so the page opens as a pager over exactly the+ // agents on screen — the filter chip included. Swiping there walks this order.+ onTap: () => openAgentPager(context, notifier, ordered, entry),+ ),+ );}class _SectionLabel extends StatelessWidget {diff --git a/mobile/lib/phone/phone_navigation.dart b/mobile/lib/phone/phone_navigation.dartindex 95f0c8e92..8db5145ba 100644--- a/mobile/lib/phone/phone_navigation.dart+++ b/mobile/lib/phone/phone_navigation.dart@@ -3,45 +3,15 @@ import 'dart:async';import 'package:flutter/cupertino.dart';import 'package:harness/state/app_state.dart';-import 'agent_hero.dart';+import 'agent_index.dart';+import 'agent_swipe.dart';import 'agents_page.dart';import 'link_page.dart';-import 'terminal_page.dart';/// Every phone page slides in the iOS way, and goes back with the edge swipe.Route<void> phoneRoute(WidgetBuilder builder) =>CupertinoPageRoute<void>(builder: builder);-/// The route a terminal opens on: the row grows into the page's header, and nothing else moves.-///-/// ⚠️ **The page itself gets NO transition of its own, and that is the whole point.** A plain-/// [CupertinoPageRoute] slides the incoming page in from the right *while* the Hero flies the-/// header up out of the list — two motions in different directions, which is what makes a Hero-/// look like a piece escaping the transition. Fading the page instead is no better: the page-/// paints its own opaque background, so a fade is a full-screen rectangle changing opacity across-/// the flight, and the eye reads that as the screen flashing.-///-/// With no transition the page is simply *there*, under the flying header, and the only thing-/// moving is the header and the body rising under it ([AgentBodyReveal]).-///-/// Still a [CupertinoPageRoute] subclass so the edge-swipe back gesture survives — and the swipe-/// runs the Hero in reverse, which is the point of using one.-class _AgentPageRoute extends CupertinoPageRoute<void> {- _AgentPageRoute({required super.builder});-- /// Matches the flight, so the route is finished exactly when the header lands.- @override- Duration get transitionDuration => kAgentHeroDuration;-- @override- Widget buildTransitions(- BuildContext context,- Animation<double> animation,- Animation<double> secondaryAnimation,- Widget child,- ) => child;-}-/// Where a tap on a machine goes. A machine this device holds no link to opens on ITS password/// form — each machine has its own remote password — and only a linked one opens on its agents.void openMachine(BuildContext context, AppNotifier notifier, String machineId) {@@ -62,34 +32,65 @@ void openMachine(BuildContext context, AppNotifier notifier, String machineId) {/// for a second tile, so whatever else was open is closed rather than left attached somewhere/// nobody can see it. The page goes up first and says it is attaching; the attach follows.///-/// [heroSource] names the list this was opened from, so the engine mark's Hero tag matches the row-/// it is flying out of — see [agentHeroTag] for why the source has to be part of the tag at all.+/// [swipeNeighbours] turns the page into a pager over that list — see [AgentSwipeList] and+/// [openAgentPager], which is how the Agents tab calls this.void openAgent(BuildContext context,AppNotifier notifier,String machineId,String agentId, {- required AgentHeroSource heroSource,+ AgentSwipeList? swipeNeighbours,}) {Navigator.of(context).push(- _AgentPageRoute(- builder: (_) => TerminalPage(+ phoneRoute(+ (_) => AgentSwipeHost(notifier: notifier,machineId: machineId,agentId: agentId,- heroSource: heroSource,+ neighbours: swipeNeighbours,),),);- unawaited(_showOnly(notifier, machineId, agentId));+ unawaited(_openPane(notifier, machineId, agentId, keepOthers: swipeNeighbours != null));}-Future<void> _showOnly(+/// Opens one agent as a PAGER over [entries]: the page it lands on is the agent tapped, and a+/// horizontal swipe moves to the entry beside it.+///+/// Takes the entries as a SNAPSHOT rather than a way to recompute them. The list is sorted partly on+/// state that moves by itself — an agent that starts working sorts upward — so a page recomputing+/// "the next one" mid-session would renumber itself under the finger. What the person saw when they+/// tapped is the order they get, for as long as that screen is open.+void openAgentPager(+ BuildContext context,+ AppNotifier notifier,+ List<AgentEntry> entries,+ AgentEntry entry,+) => openAgent(+ context,+ notifier,+ entry.machineId,+ entry.agent.id,+ swipeNeighbours: AgentSwipeList(entries),+);++/// Attaches the agent's pane.+///+/// [keepOthers] is what separates the two ways in. A page opened on its own keeps the phone's old+/// rule — one pane, because a second one attached behind a screen nobody can see is a terminal+/// streaming for nothing. A PAGER deliberately keeps its neighbours attached: that is the whole+/// point of swiping, and the panes it keeps are exactly the pages it has mounted.+///+/// `selectAgent` already does the right thing either way — it reuses an existing pane and only+/// reopens a session that died, so arriving back on a page already attached costs nothing.+Future<void> _openPane(AppNotifier notifier,String machineId,- String agentId,-) async {+ String agentId, {+ required bool keepOthers,+}) async {await notifier.selectAgent(machineId, agentId);+ if (keepOthers) return;final keep = notifier.focusedPane?.id;for (final pane in [...notifier.panes]) {if (pane.id != keep) await notifier.closePane(pane.id);diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 7ebfe8785..fb8d939b1 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -9,7 +9,6 @@ import 'package:harness/state/app_state.dart';import 'package:harness/widgets/engine_identity.dart';import 'package:harness/widgets/rename_agent_dialog.dart';import 'package:harness/widgets/terminal_panel.dart';-import 'agent_hero.dart';import 'phone_header.dart';import 'phone_sheet.dart';import 'phone_status.dart';@@ -27,16 +26,24 @@ class TerminalPage extends StatefulWidget {required this.notifier,required this.machineId,required this.agentId,- required this.heroSource,+ this.isActive = true,});final AppNotifier notifier;final String machineId;final String agentId;- /// Which list opened this page — one half of the engine mark's Hero tag, so the flight pairs with- /// the row it came from rather than an identical row in the other mounted tab.- final AgentHeroSource heroSource;+ /// Whether this is the page being LOOKED AT, rather than one parked beside it in the pager.+ ///+ /// ⚠️ **Load-bearing for correctness, not just for tidiness.** [TerminalPanel] claims the keyboard+ /// whenever it is built focused — `requestKeyboard()` reopens the input connection on purpose — so+ /// two mounted pages both passing `focused: true` race for the software keyboard, and the winner+ /// can be the page off-screen. What gets typed then reaches an agent nobody is looking at.+ ///+ /// It also drives the panel's `visible`, which is what releases focus and stops the renderer and+ /// the auto-resize for a page that has slid away — three terminals all resizing themselves to the+ /// layout would send SIGWINCH to three remote shells at once.+ final bool isActive;@overrideState<TerminalPage> createState() => _TerminalPageState();@@ -74,9 +81,14 @@ class _TerminalPageState extends State<TerminalPage> {.firstOrNull;if (pane != null) {_hadPane = true;- } else if (_hadPane) {+ } else if (_hadPane && widget.isActive) {// The pane this page was showing is gone — another tab opened a different agent, or the// agent was deleted. Leave rather than spin: there is nothing here to come back.+ //+ // ⚠️ Only the ACTIVE page may leave, and only it ever should. A page parked beside the one+ // being read shares the route, so popping from there would take the whole pager down —+ // including the terminal actually on screen. A parked page whose pane went away simply+ // waits: swiping to it is what makes it attach again._leave();}final session = pane?.session;@@ -92,96 +104,83 @@ class _TerminalPageState extends State<TerminalPage> {bottom: !keyboardUp,child: Column(children: [- // The header alone carries the flight — see [AgentHeroHeader]. Only once the agent- // is known: the row's end of the flight is built from the agent, and a flight begun- // against a placeholder would land on content that then changes under it.- AgentHeroHeader(- tag: agent == null- ? null- : agentHeroTag(- machineId: widget.machineId,- agentId: widget.agentId,- source: widget.heroSource,- ),- child: PhoneHeader(- title: agent?.name ?? 'Agent',- leading: EngineMark(- engine: agent?.engine,- displayName: agent?.engineDisplayName,- size: 22,- ),- subtitle: StatusPill(- fontSize: 12,- summary: (- // The machine alone once the button beside it is saying- // the state: two words for one fact, in a row this- // narrow, is what truncated "Taken over" to "Ta…".- label: reclaim == null- ? '${machine?.machine.displayName ?? ''} · ${status.label}'- : machine?.machine.displayName ?? '',- tone: status.tone,- ),+ PhoneHeader(+ title: agent?.name ?? 'Agent',+ leading: EngineMark(+ engine: agent?.engine,+ displayName: agent?.engineDisplayName,+ size: 22,+ ),+ subtitle: StatusPill(+ fontSize: 12,+ summary: (+ // The machine alone once the button beside it is saying+ // the state: two words for one fact, in a row this+ // narrow, is what truncated "Taken over" to "Ta…".+ label: reclaim == null+ ? '${machine?.machine.displayName ?? ''} · ${status.label}'+ : machine?.machine.displayName ?? '',+ tone: status.tone,),- trailing: [- // Read-only is a state to get OUT of, so its way out is a- // labelled button in the header rather than a line in the- // actions sheet: the sheet is where you go having decided- // to do something, and this is the thing telling you that- // typing will go nowhere until you do.- if (reclaim != null)- _ReclaimButton(- action: reclaim,- onPressed: () => widget.notifier.selectAgent(- widget.machineId,- widget.agentId,- ),+ ),+ trailing: [+ // Read-only is a state to get OUT of, so its way out is a+ // labelled button in the header rather than a line in the+ // actions sheet: the sheet is where you go having decided+ // to do something, and this is the thing telling you that+ // typing will go nowhere until you do.+ if (reclaim != null)+ _ReclaimButton(+ action: reclaim,+ onPressed: () => widget.notifier.selectAgent(+ widget.machineId,+ 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.- if (agent != null)- AppIconButton(- icon: LucideIcons.ellipsis300,- size: 20,- tooltip: 'Agent actions',- color: AppPalette.textSecondary,- onPressed: () => _showActions(- machineName: machine?.machine.displayName ?? '',- agentName: agent.name,- ),+ ),+ // 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.+ if (agent != null)+ AppIconButton(+ icon: LucideIcons.ellipsis300,+ size: 20,+ tooltip: 'Agent actions',+ color: AppPalette.textSecondary,+ onPressed: () => _showActions(+ machineName: machine?.machine.displayName ?? '',+ agentName: agent.name,),- ],- ),+ ),+ ],),- // Everything under the header arrives after the flight lands, rising a little into- // place — see [AgentBodyReveal]. Drawn full-screen from the first frame it would be- // a second layer crossing the header still in flight, which is what made the old- // whole-page version flash.Expanded(- child: AgentBodyReveal(- child: Column(- children: [- Divider(height: 1, color: AppGlass.hair),- Expanded(- child: pane == null || session == null- ? const _Attaching()- : TerminalPanel(- key: ValueKey(pane.id),- notifier: widget.notifier,- session: session,- focused: true,- showHeader: false,- // No composer, and so no grip above it: the- // page hands the pane its full height and the- // software keyboard drives the terminal- // directly — `TerminalPanel` autofocuses the- // view precisely when no box is covering it.- // What goes with the box is the batched send,- // and the Esc/Tab/Ctrl an on-screen keyboard- // never had anyway.- ),- ),- ],- ),+ child: Column(+ children: [+ Divider(height: 1, color: AppGlass.hair),+ Expanded(+ child: pane == null || session == null+ ? const _Attaching()+ : TerminalPanel(+ key: ValueKey(pane.id),+ notifier: widget.notifier,+ session: session,+ // Only the page on screen takes the keyboard — see+ // [TerminalPage.isActive]. `visible` is the same answer for the+ // panel's other half: a page parked beside this one releases+ // focus, stops rendering and stops resizing its remote shell.+ focused: widget.isActive,+ visible: widget.isActive,+ showHeader: false,+ // No composer, and so no grip above it: the+ // page hands the pane its full height and the+ // software keyboard drives the terminal+ // directly — `TerminalPanel` autofocuses the+ // view precisely when no box is covering it.+ // What goes with the box is the batched send,+ // and the Esc/Tab/Ctrl an on-screen keyboard+ // never had anyway.+ ),+ ),+ ],),),],