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): land on Machines, open the agent after linking, reopen the last agent
bubu-dudub15831be01e8
diff --git a/mobile/lib/core/last_opened_agent.dart b/mobile/lib/core/last_opened_agent.dartnew file mode 100644index 000000000..ab0fac6f4--- /dev/null+++ b/mobile/lib/core/last_opened_agent.dart@@ -0,0 +1,72 @@+import 'dart:convert';++import 'local_key_value_store.dart';++typedef AgentRef = ({String machineId, String agentId});++/// The agent the phone had on screen, so a relaunch can put the person back on it.+///+/// ⚠️ **Cleared when the terminal is LEFT, not when the app goes away.** A process the OS kills —+/// swiped out of recents, reclaimed in the background — never runs `dispose`, so the record it+/// leaves behind is exactly "the agent that was open when the app closed". Backing out of the+/// terminal does run it, and then there is nothing to reopen: the person had already gone back to+/// the list.+class LastOpenedAgent {+ LastOpenedAgent(this._storage);++ final LocalKeyValueStore? _storage;+ static const _key = 'phone_last_agent_v1';++ AgentRef? _value;+ Future<void> _writes = Future.value();++ /// What the previous run left, or null. Anything malformed reads as nothing — a missing+ /// preference must never hold the app on its launch screen.+ Future<AgentRef?> read() async {+ try {+ final raw = await _storage?.read(_key);+ if (raw == null) return null;+ final decoded = jsonDecode(raw);+ if (decoded is! Map) return null;+ final machineId = decoded['machineId'];+ final agentId = decoded['agentId'];+ if (machineId is! String || machineId.isEmpty) return null;+ if (agentId is! String || agentId.isEmpty) return null;+ return (machineId: machineId, agentId: agentId);+ } catch (_) {+ return null;+ }+ }++ void remember(AgentRef agent) {+ if (_value == agent) return;+ _value = agent;+ final encoded = jsonEncode({+ 'machineId': agent.machineId,+ 'agentId': agent.agentId,+ });+ _write((storage) => storage.write(_key, encoded));+ }++ /// Clears the record only while it still names [agent].+ ///+ /// A terminal replaced by another one can be disposed AFTER its successor has remembered itself,+ /// and an unconditional clear would then erase the agent actually on screen.+ void forget(AgentRef agent) {+ if (_value != agent) return;+ _value = null;+ _write((storage) => storage.delete(_key));+ }++ void _write(Future<void> Function(LocalKeyValueStore storage) write) {+ final storage = _storage;+ if (storage == null) return;+ _writes = _writes.then((_) async {+ try {+ await write(storage);+ } catch (_) {+ // Losing the record only costs the reopen; the terminal itself is unaffected.+ }+ });+ }+}diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dartindex e950cd2a6..1ea23c9eb 100644--- a/mobile/lib/phone/agent_swipe.dart+++ b/mobile/lib/phone/agent_swipe.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:harness_mobile/state/app_state.dart';+import 'agent_index.dart';import 'terminal_page.dart';@@ -130,6 +131,8 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {// See [resetKeyboardSession].resetKeyboardSession();_attached.add(_current);+ // What a relaunch reopens — kept up to date on every swipe, and cleared only by leaving.+ widget.notifier.lastOpenedAgent.remember(_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@@ -151,6 +154,9 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {void dispose() {_controller?.dispose();_detachAll();+ // Leaving the terminal means the next launch starts on the list. A process the OS kills never+ // gets here, which is what leaves the record behind for the reopen.+ widget.notifier.lastOpenedAgent.forget(_current);super.dispose();}@@ -168,7 +174,9 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {for (final agent in _attached) {if (agent == keep) continue;final pane = notifier.panes- .where((p) => p.machineId == agent.machineId && p.agentId == agent.agentId)+ .where(+ (p) => p.machineId == agent.machineId && p.agentId == agent.agentId,+ ).firstOrNull;if (pane != null) unawaited(notifier.closePane(pane.id));}@@ -230,6 +238,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {// agent added here that never finishes attaching costs nothing: [_detachAll] looks for its pane// and finds none._attached.add(arrived);+ widget.notifier.lastOpenedAgent.remember(arrived);setState(() {_page = index;_current = arrived;diff --git a/mobile/lib/phone/link_page.dart b/mobile/lib/phone/link_page.dartindex 9ea5f934a..37773bfeb 100644--- a/mobile/lib/phone/link_page.dart+++ b/mobile/lib/phone/link_page.dart@@ -5,6 +5,7 @@ import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/widgets/link_machine_screen.dart';import 'phone_header.dart';+import 'phone_shell_scope.dart';/// A machine's password form, as a phone page — the same [LinkMachineScreen] the desktop pops/// up, since the exchange behind it is the same.@@ -84,8 +85,13 @@ class _LinkPageState extends State<LinkPage> {// machine's agent list, which is the navigation the Machines tab no longer does — agents// belong to the Agents tab, where the machine is a filter rather than a step. Going back is// what shows the result: the row this was opened from is now under "Linked".+ //+ // …and then the shell carries on to the agent, which is what the password was for. Read+ // before the pop: once the route starts leaving, this context is on its way out.+ final shell = PhoneShellScope.maybeOf(context);_leaving = true;navigator.maybePop();+ shell?.onMachineLinked(widget.machineId);return;}final closed =diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex f5c7e193c..429e288c7 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:harness_mobile/state/app_state.dart';@@ -6,6 +8,9 @@ import '../p2p/phone_terminal_p2p.dart';import 'agent_index.dart';import 'agents_tab.dart';import 'machines_tab.dart';+import 'phone_navigation.dart';+import 'phone_shell_scope.dart';+import 'phone_status.dart';import 'phone_tab_bar.dart';import 'settings_page.dart';@@ -44,17 +49,205 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {void initState() {super.initState();WidgetsBinding.instance.addObserver(this);+ widget.notifier.addListener(_onAppChanged);+ unawaited(_reopenLastAgent());}@overridevoid dispose() {WidgetsBinding.instance.removeObserver(this);+ widget.notifier.removeListener(_onAppChanged);+ _pendingDeadline?.cancel();for (final controller in _heroControllers.values) {controller.dispose();}super.dispose();}+ // ── Where the app lands ───────────────────────────────────────────────────────────────────────+ //+ // Three moves the shell makes on its own, each at most once and each abandoned the moment the+ // person picks a tab themselves — a screen that jumps after somebody has started using it is+ // worse than one that never jumped at all:+ //+ // - the agent open when the app last closed is opened again ([_reopenLastAgent]);+ // - failing that, a phone linked to no machine that answers opens on Machines ([_decideLanding]),+ // because the Agents tab would only be an empty list pointing there;+ // - a password accepted on the Machines tab carries on to that machine's first agent+ // ([_followLinkedMachine]).++ /// An agent waiting for its machine to answer before it can be opened.+ ({String machineId, String? agentId, bool afterLink})? _pending;+ Timer? _pendingDeadline;++ /// How long a machine gets to answer. Past this the phone stays where it is — on a list the person+ /// can act on — rather than jumping into a terminal a minute after they stopped expecting it.+ static const _pendingTimeout = Duration(seconds: 45);++ /// The last-agent record has not been read yet, so the landing tab cannot be chosen: a reopen+ /// would override it.+ bool _readingLastAgent = true;++ /// The landing has been decided — by the shell or by the person — and nothing moves on its own+ /// again except [_followLinkedMachine], which the person asked for by entering a password.+ bool _landed = false;++ Future<void> _reopenLastAgent() async {+ final last = await widget.notifier.lastOpenedAgent.read();+ if (!mounted) return;+ _readingLastAgent = false;+ if (last != null && !_landed) {+ _wait(machineId: last.machineId, agentId: last.agentId, afterLink: false);+ } else {+ _onAppChanged();+ }+ }++ void _followLinkedMachine(String machineId) {+ _landed = true;+ // Straight to Agents, before the machine has finished connecting: the row it lands on says+ // "Connecting…", which is what is actually happening, and the agent opens over it once it can.+ setState(() {+ _tab = PhoneTab.agents;+ _tabCanPop =+ _navigators[PhoneTab.agents]?.currentState?.canPop() ?? false;+ });+ _wait(machineId: machineId, agentId: null, afterLink: true);+ }++ void _wait({+ required String machineId,+ required String? agentId,+ required bool afterLink,+ }) {+ _pending = (machineId: machineId, agentId: agentId, afterLink: afterLink);+ _pendingDeadline?.cancel();+ _pendingDeadline = Timer(_pendingTimeout, _dropPending);+ _onAppChanged();+ }++ void _dropPending() {+ _pending = null;+ _pendingDeadline?.cancel();+ _pendingDeadline = null;+ if (mounted) _onAppChanged();+ }++ void _onAppChanged() {+ if (!mounted) return;+ final pending = _pending;+ if (pending == null) {+ _decideLanding();+ return;+ }+ final notifier = widget.notifier;+ final machine = notifier.stateOf(pending.machineId);+ if (machine == null) {+ // Not on the account — or the account's machines have not arrived yet.+ if (notifier.machines.isNotEmpty && !notifier.machinesLoading) {+ _dropPending();+ }+ return;+ }+ switch (phoneMachineStatusOf(machine)) {+ case PhoneMachineStatus.needsPassword:+ return _dropPending();+ case PhoneMachineStatus.offline:+ // ⚠️ Not given up on straight after a link. Accepting a password closes the machine's old+ // socket before dialling a new one, and that close marks the node offline for the moment+ // before the new socket answers. On a relaunch offline is the REST answer, and it holds.+ if (!pending.afterLink) _dropPending();+ return;+ case PhoneMachineStatus.connecting:+ return;+ case PhoneMachineStatus.ready:+ break;+ }+ switch (machine.agentLoadStatus) {+ case AgentLoadStatus.loaded:+ break;+ case AgentLoadStatus.error:+ return _dropPending();+ case AgentLoadStatus.idle ||+ AgentLoadStatus.loading ||+ AgentLoadStatus.needsLink:+ return;+ }+ // Something already open on the Agents tab was opened by the person; it is not covered over.+ if (_navigators[PhoneTab.agents]?.currentState?.canPop() ?? false) {+ _landed = true;+ return _dropPending();+ }+ // The same order the list draws, so the pager swipes to the neighbours the person would see —+ // and "first agent" means the first row of that machine, not the first one it reported.+ final entries = visibleAgents(agentIndex(notifier));+ final target = entries+ .where(+ (entry) =>+ entry.machineId == pending.machineId &&+ entry.agent.terminalAvailable &&+ (pending.agentId == null || entry.agent.id == pending.agentId),+ )+ .firstOrNull;+ if (target == null) {+ // A machine with no agents yet, or a remembered agent since deleted: the list is the answer.+ return _dropPending();+ }+ _landed = true;+ _pending = null;+ _pendingDeadline?.cancel();+ _pendingDeadline = null;+ // After the frame: this runs inside the notifier's notify, which can land mid-build, and a push+ // there trips the navigator's lock.+ _afterFrame(() {+ final navigator = _navigators[PhoneTab.agents]?.currentState;+ if (navigator == null) return;+ setState(() => _tab = PhoneTab.agents);+ openAgentPager(navigator.context, notifier, entries, target);+ _syncCanPop();+ });+ }++ /// Machines, once no machine on the account has answered and none is still trying.+ ///+ /// Waits on a machine that is connecting: whether it needs a password is only learned by dialling+ /// it, so a phone that IS linked reads exactly like one that is not for the first second or two.+ /// An empty account decides nothing either — until the list arrives, empty is indistinguishable+ /// from not loaded.+ void _decideLanding() {+ if (_landed || _readingLastAgent) return;+ final notifier = widget.notifier;+ if (notifier.machines.isEmpty) return;+ for (final machine in notifier.machines) {+ final state = notifier.stateOf(machine.machineId);+ if (state == null) return;+ switch (phoneMachineStatusOf(state)) {+ case PhoneMachineStatus.ready:+ _landed = true;+ return;+ case PhoneMachineStatus.connecting:+ return;+ case PhoneMachineStatus.needsPassword || PhoneMachineStatus.offline:+ continue;+ }+ }+ _landed = true;+ _afterFrame(() {+ setState(() {+ _tab = PhoneTab.machines;+ _tabCanPop =+ _navigators[PhoneTab.machines]?.currentState?.canPop() ?? false;+ });+ });+ }++ void _afterFrame(VoidCallback action) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) action();+ });+ WidgetsBinding.instance.ensureVisualUpdate();+ }+/// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine/// socket the phone lost while it was away. Going to the background needs nothing — the OS/// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.@@ -73,6 +266,9 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {NavigatorState? get _currentNavigator => _navigators[_tab]?.currentState;void _select(PhoneTab tab) {+ // The person chose where to be: nothing the shell was waiting to open lands on them later.+ _landed = true;+ if (_pending != null) _dropPending();if (tab == _tab) {// A second tap on the tab you are already on pops that tab back to its root — the phone// convention, and the only way back out of a deep stack without walking every page.@@ -137,48 +333,52 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {}@override- Widget build(BuildContext context) => ListenableBuilder(- listenable: widget.notifier,- builder: (context, _) => PopScope<Object?>(- // False while this tab has somewhere to go back to, so the gesture reaches [_handleBack]- // instead of leaving the app. True at a tab's root: the press then belongs to the system.- canPop: !_tabCanPop,- onPopInvokedWithResult: _handleBack,- child: NotificationListener<NavigationNotification>(- onNotification: _onNavigation,- child: Scaffold(- body: IndexedStack(- index: PhoneTab.values.indexOf(_tab),- sizing: StackFit.expand,- children: [- for (final tab in PhoneTab.values)- // ⚠️ Each tab's navigator needs its OWN HeroController, and without this the- // engine-mark flights simply never happen — silently, with no error.- //- // `MaterialApp` installs one controller for the ROOT navigator only; a nested- // `Navigator` inherits nothing, so its routes have no observer to drive a flight.- // One shared controller is not the fix either — `navigator.dart` on- // `HeroControllerScope`: "The hero controller ... can only subscribe to one- // navigator", and these three are all mounted at once inside the IndexedStack.- HeroControllerScope(- controller: _heroControllers[tab]!,- child: Navigator(- key: _navigators[tab],- // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.- // `NavigatorState._updateEffectiveObservers` appends the scope's controller to- // `widget.observers` itself, so listing it here registers it twice and trips- // "A HeroController can not be shared by multiple Navigators" — which reads- // like a sharing bug and is really a double-subscription by one navigator.- onGenerateRoute: (_) =>- MaterialPageRoute<void>(builder: (_) => _rootFor(tab)),+ Widget build(BuildContext context) => PhoneShellScope(+ onMachineLinked: _followLinkedMachine,+ child: ListenableBuilder(+ listenable: widget.notifier,+ builder: (context, _) => PopScope<Object?>(+ // False while this tab has somewhere to go back to, so the gesture reaches [_handleBack]+ // instead of leaving the app. True at a tab's root: the press then belongs to the system.+ canPop: !_tabCanPop,+ onPopInvokedWithResult: _handleBack,+ child: NotificationListener<NavigationNotification>(+ onNotification: _onNavigation,+ child: Scaffold(+ body: IndexedStack(+ index: PhoneTab.values.indexOf(_tab),+ sizing: StackFit.expand,+ children: [+ for (final tab in PhoneTab.values)+ // ⚠️ Each tab's navigator needs its OWN HeroController, and without this the+ // engine-mark flights simply never happen — silently, with no error.+ //+ // `MaterialApp` installs one controller for the ROOT navigator only; a nested+ // `Navigator` inherits nothing, so its routes have no observer to drive a flight.+ // One shared controller is not the fix either — `navigator.dart` on+ // `HeroControllerScope`: "The hero controller ... can only subscribe to one+ // navigator", and these three are all mounted at once inside the IndexedStack.+ HeroControllerScope(+ controller: _heroControllers[tab]!,+ child: Navigator(+ key: _navigators[tab],+ // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.+ // `NavigatorState._updateEffectiveObservers` appends the scope's controller to+ // `widget.observers` itself, so listing it here registers it twice and trips+ // "A HeroController can not be shared by multiple Navigators" — which reads+ // like a sharing bug and is really a double-subscription by one navigator.+ onGenerateRoute: (_) => MaterialPageRoute<void>(+ builder: (_) => _rootFor(tab),+ ),+ ),),- ),- ],- ),- bottomNavigationBar: PhoneTabBar(- current: _tab,- onSelect: _select,- waitingCount: waitingAgents(agentIndex(widget.notifier)).length,+ ],+ ),+ bottomNavigationBar: PhoneTabBar(+ current: _tab,+ onSelect: _select,+ waitingCount: waitingAgents(agentIndex(widget.notifier)).length,+ ),),),),diff --git a/mobile/lib/phone/phone_shell_scope.dart b/mobile/lib/phone/phone_shell_scope.dartnew file mode 100644index 000000000..07a83de62--- /dev/null+++ b/mobile/lib/phone/phone_shell_scope.dart@@ -0,0 +1,25 @@+import 'package:flutter/widgets.dart';++/// What a page deep inside one tab can ask of the shell around all three.+///+/// The pages live in per-tab navigators, so none of them can switch tabs or push onto another tab's+/// stack by itself. A password form finishing is the one moment that has to: the form is on the+/// Machines tab, and what the person came for is the agent, on the Agents tab.+class PhoneShellScope extends InheritedWidget {+ const PhoneShellScope({+ super.key,+ required this.onMachineLinked,+ required super.child,+ });++ /// Called once a machine's password has been accepted — the shell takes the person to that+ /// machine's first agent as soon as the machine answers.+ final void Function(String machineId) onMachineLinked;++ /// Null outside the shell — a page pumped on its own in a test simply has nowhere to go.+ static PhoneShellScope? maybeOf(BuildContext context) =>+ context.getInheritedWidgetOfExactType<PhoneShellScope>();++ @override+ bool updateShouldNotify(PhoneShellScope oldWidget) => false;+}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 589e123ac..4aff73f94 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -22,6 +22,7 @@ import '../core/agent_preference.dart';import '../core/engine_availability.dart';import '../core/local_hostname.dart';import '../core/local_git_projects.dart';+import '../core/last_opened_agent.dart';import '../core/test_run.dart';import '../core/models.dart';import '../core/project_folder.dart';@@ -1069,6 +1070,7 @@ class AppNotifier extends ChangeNotifier {dial = DialState(paneLayoutStore?.storage),agentPreference = AgentPreference(paneLayoutStore?.storage),projectHistory = ProjectHistory(paneLayoutStore?.storage),+ lastOpenedAgent = LastOpenedAgent(paneLayoutStore?.storage),session = authSession,_store = configStore,cliLink = cliLink ?? CliLink(),@@ -1134,6 +1136,9 @@ class AppNotifier extends ChangeNotifier {/// outlives the agent — which is what "recent" has to mean for the word to be true.final ProjectHistory projectHistory;+ /// The agent the phone's terminal had open, kept across launches — see [LastOpenedAgent].+ final LastOpenedAgent lastOpenedAgent;+TerminalPane? get focusedPane {final id = focusedPaneId;if (id == null) return null;