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
mobile: set up a locked Harness OS computer in one stay on its hotspot (#1447)
Bubu-Dudu-52hz8332f35a2cc8
diff --git a/mobile/integration_test/add_device_unlock_test.dart b/mobile/integration_test/add_device_unlock_test.dartnew file mode 100644index 000000000..3a1f95ba0--- /dev/null+++ b/mobile/integration_test/add_device_unlock_test.dart@@ -0,0 +1,86 @@+import 'package:dio/dio.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import 'package:harness_mobile/demo/sample_runtime.dart';+import 'package:harness_mobile/phone/add_device/add_device_page.dart';+import 'package:harness_mobile/phone/add_device/setup_hotspot.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;++/// Set up a device that is locked as it starts, in the real app on a simulator, against a stand-in+/// device on the Mac (`fake_device.py`, which runs the startup's own page,+/// os/root/usr/lib/harness-os/unlock/http, until "harness" opens it). A screenshot each step.+///+/// python3 <stand-in device on 127.0.0.1:8042> os/root/usr/lib/harness-os/unlock/http &+/// flutter drive -d <simulator> --driver=test_driver/journey_driver.dart \+/// --target=integration_test/add_device_unlock_test.dart+void main() {+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ testWidgets('a locked device: its password, then its Wi-Fi', (tester) async {+ var step = 0;+ Future<void> shot(String name) async {+ await tester.pump(const Duration(milliseconds: 300));+ step++;+ await binding.takeScreenshot('${step.toString().padLeft(2, '0')}-$name');+ }++ Future<void> waitFor(Finder finder, {int seconds = 30}) async {+ for (var i = 0; i < seconds * 10; i++) {+ if (finder.evaluate().isNotEmpty) return;+ await tester.pump(const Duration(milliseconds: 100));+ }+ fail('never appeared: $finder');+ }++ final runtime = SampleRuntime();+ final hotspot = SetupHotspot(+ dio: Dio(+ BaseOptions(+ baseUrl: 'http://127.0.0.1:8042',+ connectTimeout: const Duration(seconds: 4),+ receiveTimeout: const Duration(seconds: 50),+ validateStatus: (_) => true,+ ),+ ),+ );+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: grid.AppTheme.brightness.value),+ home: AddDevicePage(notifier: runtime.notifier, hotspot: hotspot),+ ),+ );++ // A simulator joins no Wi-Fi by itself; the page finds the device as soon as it answers.+ await waitFor(find.byKey(const Key('add-device-unlock-password')));+ await shot('locked');++ await tester.enterText(+ find.byKey(const Key('add-device-unlock-password')),+ 'not it',+ );+ await tester.tap(find.byKey(const Key('add-device-unlock')));+ await waitFor(find.byKey(const Key('add-device-error')));+ await shot('wrong-password');++ await tester.enterText(+ find.byKey(const Key('add-device-unlock-password')),+ 'harness',+ );+ await tester.tap(find.byKey(const Key('add-device-unlock-reveal')));+ await tester.pump(const Duration(milliseconds: 300));+ await shot('typed-shown');+ await tester.tap(find.byKey(const Key('add-device-unlock')));+ await waitFor(find.byKey(const Key('add-device-unlocked-done')));+ await shot('unlocked-starting');++ // Started: its own setup page now, with the Wi-Fi it sees.+ await waitFor(+ find.byKey(const ValueKey('add-device-wifi-Glinks 1')),+ seconds: 60,+ );+ await shot('wifi-list');+ runtime.dispose();+ });+}diff --git a/mobile/lib/demo/sample_notifier.dart b/mobile/lib/demo/sample_notifier.dartindex e1b9cc288..9394db8ca 100644--- a/mobile/lib/demo/sample_notifier.dart+++ b/mobile/lib/demo/sample_notifier.dart@@ -72,6 +72,13 @@ class SampleApiClient extends ApiClient {@overrideFuture<Map<String, dynamic>?> me() async => null;+ /// Set up a device, in the sample: a ticket no backend ever sees (the device is a stand-in too).+ @override+ Future<Map<String, dynamic>> boxTicket() async => {+ 'ticket': 'sample-ticket',+ 'expiresIn': 600,+ };+@overrideFuture<List<Machine>> machines() async => machinesOnFile();diff --git a/mobile/lib/phone/add_device/add_device_page.dart b/mobile/lib/phone/add_device/add_device_page.dartindex 82c9f8221..64fad563f 100644--- a/mobile/lib/phone/add_device/add_device_page.dart+++ b/mobile/lib/phone/add_device/add_device_page.dart@@ -24,6 +24,10 @@ import 'setup_hotspot.dart';////// When the Wi-Fi fails (wrong password, out of reach, no Internet) the device brings its hotspot/// back with the reason; joining it again shows that reason above the list.+///+/// A device whose disk is locked as it starts hosts the same hotspot before anything else and asks+/// for the computer's password first; opened, it starts, and its hotspot comes back for the rest.+/// One on a cable is online already: it is only signed in, with no Wi-Fi to choose.class AddDevicePage extends StatefulWidget {const AddDevicePage({super.key, required this.notifier, this.hotspot});@@ -34,7 +38,7 @@ class AddDevicePage extends StatefulWidget {State<AddDevicePage> createState() => _AddDevicePageState();}-enum _Step { start, join, networks, password, waiting, done }+enum _Step { start, join, unlock, networks, password, waiting, done, back }/// Joining the device's hotspot, shown as it goes: the person picking it, the phone on it and/// asking the device, then reading its Wi-Fi list.@@ -80,6 +84,40 @@ class _AddDevicePageState extends State<AddDevicePage> {final _password = TextEditingController();final _name = TextEditingController();+ /// The computer's own password, for a device still locked as it starts.+ final _secret = TextEditingController();++ /// Unlocked from here: it is starting, and its hotspot comes back under the same name.+ bool _unlocked = false;++ /// A device still locked that takes the whole setup with its password (protocol 2): its Wi-Fi is+ /// chosen from the list its startup scanned, then the computer's password sends it all in one stay+ /// on its hotspot — set up before or not, and whatever account it was on.+ bool _lockedSetup = false;++ /// Asked for by Look again on a locked device's list: scanned again beside its hotspot.+ bool _rescan = false;++ /// A locked device that checks the computer's password on its own (protocol 3): the password is+ /// asked first and checked — nothing opens — then the Wi-Fi, then both go in one unlock.+ bool _checkFirst = false;++ /// The computer's password once the device said it is the right one: kept in memory only, for the+ /// unlock that follows the Wi-Fi.+ String? _checked;++ /// The device found online after a locked setup: it said no computer id while locked, so it is told+ /// apart in the account instead — new there, or offline when the password was sent ([_sentAt]).+ Machine? _found;+ Map<String, String>? _sentAt;++ /// After an unlock: the account's computers that were not online then. One of them online now is+ /// the one just unlocked, set up before — on its own Wi-Fi, signed in, with no hotspot to come+ /// back ([_Step.back]).+ Set<String> _offlineAtUnlock = const {};+ Timer? _backWatch;+ Machine? _backOnline;+_Step _step = _Step.start;bool _busy = false;String _error = '';@@ -115,10 +153,12 @@ class _AddDevicePageState extends State<AddDevicePage> {@overridevoid dispose() {_poll?.cancel();+ _backWatch?.cancel();unawaited(_hotspot.leave());_ssid.dispose();_password.dispose();_name.dispose();+ _secret.dispose();super.dispose();}@@ -156,6 +196,36 @@ class _AddDevicePageState extends State<AddDevicePage> {await _join();}+ /// A ticket handed to the device already: the next try needs a new one.+ bool _ticketSent = false;++ /// A new ticket, tried for a while: the phone may still be finding its way back to its own Wi-Fi.+ Future<bool> _freshTicket() async {+ Object? failure;+ for (var attempt = 0; attempt < 5; attempt++) {+ try {+ final ticket = await _app.api.boxTicket();+ final value = ticket['ticket'] as String? ?? '';+ if (value.isNotEmpty) {+ _ticket = value;+ _ticketSent = false;+ return true;+ }+ } catch (e) {+ failure = e;+ }+ await Future<void>.delayed(const Duration(seconds: 3));+ if (!mounted) return false;+ }+ _show(+ _Step.join,+ error: failure == null+ ? 'Could not prepare the sign-in. Try again.'+ : describeApiError(failure),+ );+ return false;+ }+// -- 2. onto the device's hotspot, picked from the Wi-Fi list --Future<void> _join() async {@@ -165,8 +235,17 @@ class _AddDevicePageState extends State<AddDevicePage> {_progress = _Progress.choosing;_address = null;});+ // Back to the device after it was handed a ticket: that one is spent (or will be, by a sign-in+ // that failed), so a new one now, while this phone is on its own Wi-Fi again. Sent again, the old+ // one came back "This ticket was already used or has expired".+ if (_ticketSent && !await _freshTicket()) return;if (SetupHotspot.joinsByItself) {- final joined = await _hotspot.join();+ // The same device again once it has started: only its own name in Android's list.+ final joined = await _hotspot.join(+ // Back after a locked setup that did not come online: the same device, on setup.py's+ // hotspot now, with why.+ name: _unlocked || _lockedSetup ? _device['hotspot'] as String? : null,+ );if (!mounted) return;if (joined.state == 'joined') {setState(() {@@ -199,17 +278,48 @@ class _AddDevicePageState extends State<AddDevicePage> {try {final info = await _hotspot.info();if (info == null || !mounted || _step != _Step.join) return;+ // Still the locked one, just unlocked from here: it has not started yet.+ if (_unlocked && info['locked'] == true) return;_poll?.cancel();_device = info;_retrying = false;- setState(() => _progress = _Progress.reading);- final networks = await _hotspot.networks();- if (!mounted) return;+ if (info['locked'] == true) {+ _secret.clear();+ final protocol = (info['protocol'] as num?)?.toInt() ?? 1;+ if (protocol >= 2) {+ // The whole setup while it is locked. Protocol 3: the computer's password first, checked,+ // then its Wi-Fi; protocol 2: its Wi-Fi first.+ _lockedSetup = true;+ _checkFirst = protocol >= 3;+ if (_checkFirst && _checked == null) {+ _show(_Step.unlock);+ return;+ }+ await _lockedNetworks();+ return;+ }+ _show(_Step.unlock);+ return;+ }+ _unlocked = false;+ // Started: the page setup.py hosts, which says what it is (its computer id) and why a try failed.+ _lockedSetup = false;+ _found = null;// A failed try before this one: the device says why, once the phone is back on its hotspot.final last = info['result'];- final why = last is Map && last['state'] == 'failed'+ final why =+ last is Map && (last['state'] == 'failed' || last['error'] != null)? last['message'] as String? ?? '': '';+ // On a cable: online already, so it is only signed in. Not again after that failed: the+ // person sees why, and may give it a Wi-Fi instead.+ if (info['online'] == true && info['signedIn'] != true && why.isEmpty) {+ await _sendWired();+ return;+ }+ setState(() => _progress = _Progress.reading);+ final networks = await _hotspot.networks();+ if (!mounted) return;setState(() {_networks = networks;_step = _Step.networks;@@ -226,6 +336,171 @@ class _AddDevicePageState extends State<AddDevicePage> {}}+ /// A locked device's Wi-Fi: the list its startup scanned, or scanned again beside its hotspot.+ Future<void> _lockedNetworks() async {+ setState(() => _progress = _Progress.reading);+ final rescan = _rescan;+ _rescan = false;+ final networks = await _hotspot.networks(rescan: rescan);+ if (!mounted) return;+ setState(() {+ _networks = networks;+ _step = _Step.networks;+ _error = '';+ _busy = false;+ });+ }++ // -- 2b. a device locked as it starts: the computer's password --++ Future<void> _unlock() async {+ final secret = _secret.text;+ if (secret.isEmpty) {+ _show(_Step.unlock, error: 'Enter the computer\'s password.');+ return;+ }+ setState(() => _busy = true);+ if (_checkFirst) {+ // Only checked: right, then the Wi-Fi; wrong, said now — before any Wi-Fi is chosen.+ final String? why;+ try {+ why = await _hotspot.check(secret);+ } on SetupException catch (e) {+ _show(_Step.unlock, error: e.message);+ return;+ }+ if (why != null) {+ _show(_Step.unlock, error: why);+ return;+ }+ _checked = secret;+ _secret.clear();+ try {+ await _lockedNetworks();+ } on SetupException catch (e) {+ _show(_Step.join, error: e.message);+ }+ return;+ }+ await _unlockWith(secret);+ }++ /// The disk opened with [secret] — and, for a locked setup, the Wi-Fi and the sign-in sent with it.+ Future<void> _unlockWith(String secret) async {+ setState(() => _busy = true);+ // The whole setup with it: a new ticket for a try after one that was handed over already.+ if (_lockedSetup && _ticketSent && !await _freshTicket()) return;+ final ssid = _ssid.text.trim();+ final secure = _chosen?.secure ?? _password.text.isNotEmpty;+ final Map<String, Object?>? setup = _lockedSetup+ ? {+ 'ssid': ssid,+ if (secure) 'password': _password.text,+ if (_chosen != null) 'security': _chosen!.security,+ 'ticket': _ticket,+ 'account': ?_app.currentUser?.id,+ }+ : null;+ // The account as it is now: the device is told apart in it once online, having given no id.+ _sentAt = {for (final m in _app.machines) m.machineId: m.status ?? ''};+ // Checked first: a failure now is said beside the Wi-Fi password, where the button was.+ final failedAt = _checkFirst ? _Step.password : _Step.unlock;+ final String? why;+ try {+ why = await _hotspot.unlock(secret, setup: setup);+ } on SetupException catch (e) {+ _show(failedAt, error: e.message);+ return;+ }+ _secret.clear();+ if (why != null) {+ _show(failedAt, error: why);+ return;+ }+ _checked = null;+ if (_lockedSetup) {+ // Opened, with its Wi-Fi and ticket: it joins and signs in as it starts. No second hotspot.+ _ticketSent = true;+ _alreadyHere = false;+ _wasRunning = false;+ await _hotspot.leave();+ _wait(ssid);+ return;+ }+ // It starts now. Its hotspot goes, and comes back under the same name for the rest of the+ // setup — unless it was set up before: then it goes on to its own Wi-Fi.+ _unlocked = true;+ _watchBack();+ await _hotspot.leave();+ _show(_Step.join);+ setState(() {+ _busy = true;+ _progress = _Progress.choosing;+ });+ await Future<void>.delayed(const Duration(seconds: 15));+ if (!mounted || _step != _Step.join) return;+ await _join();+ }++ /// While the phone looks for its hotspot again: a computer set up before goes on to its own Wi-Fi+ /// and signs in as it was, and no hotspot comes. The account says so — one that was offline at the+ /// unlock is online — and the search stops there, done. For a few minutes; a computer not set up+ /// yet comes back on its hotspot instead and the setup goes on as before.+ void _watchBack() {+ _offlineAtUnlock = {+ for (final machine in _app.machines)+ if (machine.status != 'running') machine.machineId,+ };+ _backWatch?.cancel();+ if (_offlineAtUnlock.isEmpty) return;+ final deadline = DateTime.now().add(const Duration(minutes: 3));+ _backWatch = Timer.periodic(const Duration(seconds: 3), (_) async {+ if (!mounted || !_unlocked || DateTime.now().isAfter(deadline)) {+ _backWatch?.cancel();+ return;+ }+ try {+ await _app.refreshMachines();+ } catch (_) {+ // The phone may still be on the device's Wi-Fi, or finding its way back to its own.+ }+ if (!mounted || !_unlocked) return;+ final back = _app.machines+ .where(+ (m) =>+ _offlineAtUnlock.contains(m.machineId) && m.status == 'running',+ )+ .toList();+ if (back.isEmpty) return;+ // The one named after this hotspot, when there are several; else the first back.+ final hotspot = _device['hotspot'] as String?;+ _backOnline =+ back.where((m) => m.displayName == hotspot).firstOrNull ?? back.first;+ _backWatch?.cancel();+ _poll?.cancel();+ _unlocked = false;+ unawaited(_hotspot.leave());+ _show(_Step.back);+ });+ }++ // -- 2c. on a cable: only the sign-in --++ Future<void> _sendWired() async {+ _alreadyHere = false;+ _wasRunning = _machine?.status == 'running';+ _ssid.clear();+ try {+ await _hotspot.connect(ssid: '', password: '', ticket: _ticket);+ _ticketSent = true;+ } on SetupException catch (e) {+ _show(_Step.join, error: e.message);+ return;+ }+ await _hotspot.leave();+ _wait('');+ }+// -- 3. the person's Wi-Fi --void _choose(SetupNetwork? network) {@@ -254,6 +529,18 @@ class _AddDevicePageState extends State<AddDevicePage> {_show(_Step.password, error: 'A Wi-Fi password has 8 to 63 characters.');return;}+ if (_lockedSetup) {+ // Its password checked already: unlocked now, the Wi-Fi with it. Not yet (protocol 2): the+ // computer's password next.+ final checked = _checked;+ if (_checkFirst && checked != null) {+ await _unlockWith(checked);+ return;+ }+ _secret.clear();+ _show(_Step.unlock);+ return;+ }setState(() => _busy = true);// Signed in already: only its Wi-Fi changes, so it keeps its name and is not new. One signed out// is set up afresh, even if its old record is still in the account.@@ -265,6 +552,7 @@ class _AddDevicePageState extends State<AddDevicePage> {password: secure ? password : '',ticket: _ticket,);+ _ticketSent = true;} on SetupException catch (e) {_show(_Step.password, error: e.message);return;@@ -283,13 +571,39 @@ class _AddDevicePageState extends State<AddDevicePage> {// -- 4. the device on the Internet, in this account --Machine? get _machine {- if (_computerId.isEmpty) return null;+ if (_computerId.isEmpty) return _lockedSetup ? _foundOnline() : null;for (final machine in _app.machines) {if (_bare(machine.computerId ?? '') == _computerId) return machine;}return null;}+ /// After a locked setup: the computer online in the account now that was not when the password+ /// went — new there, or offline then. The one named after the hotspot first, when there are more.+ /// Kept once found, for its name and Start.+ Machine? _foundOnline() {+ final found = _found;+ if (found != null) {+ return _app.machines+ .where((m) => m.machineId == found.machineId)+ .firstOrNull ??+ found;+ }+ final before = _sentAt;+ if (before == null) return null;+ final back = [+ for (final m in _app.machines)+ if (m.status == 'running' && before[m.machineId] != 'running') m,+ ];+ if (back.isEmpty) return null;+ final hotspot = _device['hotspot'] as String?;+ final machine =+ back.where((m) => m.displayName == hotspot).firstOrNull ?? back.first;+ // One the account had before: set up before, so it keeps its name and is not new.+ _alreadyHere = before.containsKey(machine.machineId);+ return _found = machine;+ }+// -- 5. its name, then Computers with it marked new --Future<void> _finish() async {@@ -318,7 +632,10 @@ class _AddDevicePageState extends State<AddDevicePage> {void _wait(String ssid) {_show(_Step.waiting);- final deadline = DateTime.now().add(_comeOnline);+ // A locked one starts first: its disk opens, then the system, then the Wi-Fi and the sign-in.+ final deadline = DateTime.now().add(+ _lockedSetup ? _comeOnline * 2 : _comeOnline,+ );_poll?.cancel();_poll = Timer.periodic(const Duration(seconds: 3), (_) async {if (!mounted || _step != _Step.waiting) return;@@ -451,6 +768,13 @@ class _AddDevicePageState extends State<AddDevicePage> {'The device is still trying the Wi-Fi. Its hotspot comes back within a minute.',),],+ if (_unlocked) ...[+ const SizedBox(height: 12),+ say(+ '$name is unlocked and starting. Its Wi-Fi comes back within a minute for the rest '+ 'of the setup. Set up before? Then it joins its own Wi-Fi instead, and you are done.',+ ),+ ],const SizedBox(height: 16),// Where it is, as a Wi-Fi settings page shows joining: what is done, and what is going on._Line(@@ -474,6 +798,39 @@ class _AddDevicePageState extends State<AddDevicePage> {text: 'Reading the Wi-Fi the device sees…',),];+ case _Step.unlock:+ return [+ say(+ _checkFirst+ ? '$name is locked. Enter the computer\'s password — the one set when it was '+ 'installed. It is checked first; then you choose its Wi-Fi.'+ : _lockedSetup+ ? 'Last, the computer\'s password — the one set when it was installed. $name '+ 'starts with it, joins "${_ssid.text.trim()}" and signs in to your account.'+ : '$name is locked. Enter the computer\'s password — the one set when it was '+ 'installed — to start it.',+ ),+ const SizedBox(height: 8),+ TtyField(+ key: const Key('add-device-unlock-password'),+ controller: _secret,+ hint: 'Computer password',+ autofocus: true,+ keyboardType: TextInputType.visiblePassword,+ obscure: !_reveal,+ onSubmitted: _busy ? null : () => unawaited(_unlock()),+ trailing: [+ AppIconButton(+ key: const Key('add-device-unlock-reveal'),+ icon: _reveal ? LucideIcons.eyeOff300 : LucideIcons.eye300,+ size: 20,+ tooltip: _reveal ? 'Hide password' : 'Show password',+ color: tty.dim,+ onPressed: () => setState(() => _reveal = !_reveal),+ ),+ ],+ ),+ ];case _Step.networks:return [say(@@ -482,6 +839,13 @@ class _AddDevicePageState extends State<AddDevicePage> {const SizedBox(height: 12),SettingsGroup(children: [+ if (_device['online'] == true)+ SettingsRow(+ key: const Key('add-device-cable'),+ title: 'Use its cable',+ value: 'Online',+ onTap: () => unawaited(_sendWired()),+ ),for (final network in _networks)SettingsRow(key: ValueKey('add-device-wifi-${network.ssid}'),@@ -542,10 +906,20 @@ class _AddDevicePageState extends State<AddDevicePage> {case _Step.waiting:return [say(- _error.isEmpty- ? '$name is joining "${_ssid.text.trim()}" and signing in to your account. '+ _error.isNotEmpty+ ? ''+ : _ssid.text.trim().isEmpty+ ? '$name is on a cable: it is signing in to your account. ''This phone goes back to its own Wi-Fi meanwhile.'- : '',+ : '$name is joining "${_ssid.text.trim()}" and signing in to your account. '+ 'This phone goes back to its own Wi-Fi meanwhile.',+ ),+ ];+ case _Step.back:+ return [+ say(+ '${_backOnline?.displayName ?? name} is unlocked and online again, on its own Wi-Fi '+ 'and signed in as before. Nothing else to set up.',),];case _Step.done:@@ -589,12 +963,40 @@ class _AddDevicePageState extends State<AddDevicePage> {onPressed: () =>unawaited(SetupHotspot.joinsByItself ? _join() : _reach()),),+ if (_unlocked)+ TtyTextButton(+ key: const Key('add-device-unlocked-done'),+ label: 'It was set up before: done',+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ];+ case _Step.unlock:+ return [+ TtyPrimaryButton(+ key: const Key('add-device-unlock'),+ label: _checkFirst+ ? 'Next'+ : _lockedSetup+ ? 'Unlock and set up'+ : 'Unlock',+ busy: _busy,+ busyLabel: _checkFirst ? 'Checking…' : 'Unlocking…',+ onPressed: () => unawaited(_unlock()),+ ),+ if (_lockedSetup && !_checkFirst)+ TtyTextButton(+ key: const Key('add-device-unlock-back'),+ label: 'Choose another Wi-Fi',+ onPressed: () => _show(_Step.networks),+ ),];case _Step.networks:return [TtyTextButton(label: 'Look again',onPressed: () {+ // A locked device scans again beside its hotspot; a started one rescans anyway.+ _rescan = _lockedSetup;_show(_Step.join);unawaited(_reach());},@@ -604,9 +1006,13 @@ class _AddDevicePageState extends State<AddDevicePage> {return [TtyPrimaryButton(key: const Key('add-device-connect'),- label: 'Connect',+ label: _checkFirst+ ? 'Unlock and set up'+ : _lockedSetup+ ? 'Next'+ : 'Connect',busy: _busy,- busyLabel: 'Sending…',+ busyLabel: _checkFirst ? 'Unlocking…' : 'Sending…',onPressed: () => unawaited(_send()),),TtyTextButton(@@ -638,6 +1044,14 @@ class _AddDevicePageState extends State<AddDevicePage> {),],];+ case _Step.back:+ return [+ TtyPrimaryButton(+ key: const Key('add-device-back-done'),+ label: 'Done',+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ];case _Step.done:return [TtyPrimaryButton(diff --git a/mobile/lib/phone/add_device/setup_hotspot.dart b/mobile/lib/phone/add_device/setup_hotspot.dartindex 2cd0d21c1..9bd404f4b 100644--- a/mobile/lib/phone/add_device/setup_hotspot.dart+++ b/mobile/lib/phone/add_device/setup_hotspot.dart@@ -1,4 +1,5 @@import 'dart:async';+import 'dart:convert';import 'dart:io';import 'package:dio/dio.dart';@@ -33,12 +34,13 @@ class SetupHotspot {static bool get joinsByItself => Platform.isAndroid;/// `joined` (with the address the hotspot gave this phone), `unavailable` (the person cancelled,- /// or no device was found), or `unsupported`. Android's list shows only the `Harness-…` Wi-Fi.- Future<({String state, String? address})> join() async {+ /// or no device was found), or `unsupported`. Android's list shows only the `Harness-…` Wi-Fi, or+ /// only [name]'s: the same device again, once it has started after being unlocked.+ Future<({String state, String? address})> join({String? name}) async {if (!joinsByItself) return (state: 'unsupported', address: null);try {final reply = await _channel.invokeMethod<Map<Object?, Object?>>('join', {- 'prefix': prefix,+ 'prefix': name ?? prefix,});return (state: reply?['state'] as String? ?? 'unavailable',@@ -63,8 +65,10 @@ class SetupHotspot {}}- /// The device: `{protocol, name, hotspot, run, computerId, signedIn, result}`, or null while the- /// phone is not on its hotspot.+ /// The device: `{protocol, name, hotspot, run, computerId, signedIn, online, result}`, or null+ /// while the phone is not on its hotspot. `online`: on a cable already, so no Wi-Fi is asked for.+ /// `{protocol, hotspot, locked: true, wait}` while its disk is still locked as it starts: it asks+ /// for the computer's password first (os/root/usr/lib/harness-os/unlock, in its startup).Future<Map<String, dynamic>?> info() async {try {final res = await _dio.get('/setup');@@ -76,8 +80,13 @@ class SetupHotspot {}/// The Wi-Fi the DEVICE sees: `[{ssid, signal, security}]`, strongest first.- Future<List<SetupNetwork>> networks() async {- final res = await _dio.get('/setup/networks');+ /// [rescan]: a device still locked lists the Wi-Fi of its startup's scan; asked to, it scans again+ /// beside its hotspot, where its card allows that.+ Future<List<SetupNetwork>> networks({bool rescan = false}) async {+ final res = await _dio.get(+ rescan ? '/setup/networks?rescan=1' : '/setup/networks',+ options: Options(receiveTimeout: const Duration(seconds: 20)),+ );final list = (res.data is Map ? (res.data as Map)['networks'] : null);if (res.statusCode != 200 || list is! List) {throw const SetupException('The device did not send its Wi-Fi list.');@@ -89,11 +98,78 @@ class SetupHotspot {ssid: row['ssid'] as String,signal: (row['signal'] as num?)?.toInt() ?? 0,secure: (row['security'] as String? ?? '').isNotEmpty,+ security: row['security'] as String? ?? '',),];}- /// Hands the device the Wi-Fi and the ticket. Answers the run to look for in a later result.+ /// The computer's password only checked, nothing opened (protocol 3): null when it is the disk's,+ /// otherwise why not. The phone asks it first, then the Wi-Fi, then [unlock]s with both.+ Future<String?> check(String password) async {+ final Response<dynamic> res;+ try {+ res = await _dio.post(+ '/setup/check',+ data: password,+ options: Options(+ contentType: 'text/plain; charset=utf-8',+ // Checked slowly on purpose, as the disk's password is.+ receiveTimeout: const Duration(seconds: 50),+ ),+ );+ } on DioException {+ throw const SetupException(+ 'Lost the device\'s Wi-Fi. Stay close to it and try again.',+ );+ }+ if (res.statusCode == 200) return null;+ final body = res.data is Map ? res.data as Map : const {};+ return body['message'] as String? ??+ 'The device said no (${res.statusCode}).';+ }++ /// The computer's password, for a device still locked as it starts: its disk opens with it, and+ /// it goes on starting. Null when it opened; otherwise why not (a wrong password, too many tries).+ ///+ /// [setup]: the rest of the setup with it, for a device that takes it (protocol 2) — the Wi-Fi, its+ /// password, the ticket, this phone's account — joined and signed in as it starts, with no second+ /// stay on its hotspot. It follows the password in the body, its length in a header.+ Future<String?> unlock(String password, {Map<String, Object?>? setup}) async {+ final rest = setup == null ? '' : jsonEncode(setup);+ final Response<dynamic> res;+ try {+ res = await _dio.post(+ '/setup/unlock',+ data: password + rest,+ options: Options(+ headers: {+ if (rest.isNotEmpty)+ 'X-Harness-Setup-Length': '${utf8.encode(rest).length}',+ },+ contentType: 'text/plain; charset=utf-8',+ // Opening the disk takes a few seconds: the password is checked slowly on purpose.+ receiveTimeout: const Duration(seconds: 50),+ ),+ );+ } on DioException catch (e) {+ // The page could not even be reached: the phone is off its hotspot.+ if (e.type == DioExceptionType.connectionTimeout) {+ throw const SetupException(+ 'Lost the device\'s Wi-Fi. Stay close to it and try again.',+ );+ }+ // Sent, and the hotspot went before the answer: most likely it opened, and the device is+ // starting (its startup stops the hotspot at once). Still locked, it asks again on rejoining.+ return null;+ }+ if (res.statusCode == 200) return null;+ final body = res.data is Map ? res.data as Map : const {};+ return body['message'] as String? ??+ 'The device said no (${res.statusCode}).';+ }++ /// Hands the device the Wi-Fi and the ticket, or on a cable ([ssid] empty) the ticket alone.+ /// Answers the run to look for in a later result.Future<int> connect({required String ssid,required String password,@@ -103,7 +179,9 @@ class SetupHotspot {try {res = await _dio.post('/setup/connect',- data: {'ssid': ssid, 'password': password, 'ticket': ticket},+ data: ssid.isEmpty+ ? {'ticket': ticket}+ : {'ssid': ssid, 'password': password, 'ticket': ticket},);} on DioException {throw const SetupException(@@ -125,11 +203,15 @@ class SetupNetwork {required this.ssid,required this.signal,required this.secure,+ this.security = '',});final String ssid;final int signal;final bool secure;++ /// As the device read it (`WPA2`, `WPA3`, `WPA2 WPA3`, empty for open): how it joins.+ final String security;}class SetupException implements Exception {diff --git a/mobile/lib/phone/find_row.dart b/mobile/lib/phone/find_row.dartindex 5bc014f71..9d05a3ef7 100644--- a/mobile/lib/phone/find_row.dart+++ b/mobile/lib/phone/find_row.dart@@ -31,6 +31,7 @@ class FindRow extends StatelessWidget {this.selected = false,this.enabled = true,this.onTap,+ this.onLongPress,this.strict = false,this.said,this.accessory,@@ -88,6 +89,10 @@ class FindRow extends StatelessWidget {final bool enabled;final VoidCallback? onTap;+ /// Holding the row: its actions — taken even while [enabled] is false, which is when a harness+ /// on a computer that does not answer most needs one (Remove from this list).+ final VoidCallback? onLongPress;+static const double height = 60;/// [height], or less for a row of one line where its second has been said once for a group of@@ -119,7 +124,8 @@ class FindRow extends StatelessWidget {Widget build(BuildContext context) {final tty = Tty.of(context);final ink = enabled ? tty.text : tty.faint;- final row = TtyTap(+ final held = onLongPress;+ final tapped = TtyTap(minHeight: minHeight,onTap: enabled && onTap != null? () {@@ -243,6 +249,16 @@ class FindRow extends StatelessWidget {),),);+ final row = held == null+ ? tapped+ : GestureDetector(+ behavior: HitTestBehavior.opaque,+ onLongPress: () {+ HapticFeedback.mediumImpact();+ held();+ },+ child: tapped,+ );final accessory = this.accessory;if (accessory == null) return row;final center = _lineOneCenter(context, tty);diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex 3f0e9a053..2453d5371 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -294,9 +294,8 @@ class _Body extends StatelessWidget {/// sends the download, and the account watched for the computer that opens it. A second computer/// is set up the way the first was (`welcome/your_computer.dart`).void _setUpComputer(BuildContext context) => unawaited(- Navigator.of(context).push(- phoneRoute((_) => YourComputerPage(notifier: notifier)),- ),+ Navigator.of(context)+ .push(phoneRoute((_) => YourComputerPage(notifier: notifier))),);/// [ownLine] false: its run's [_GroupLine] says what the second line would have, so it has none.@@ -335,8 +334,13 @@ class _Body extends StatelessWidget {(word, color) = ('trying…', tty.faint);} else if (notifier.isNewMachine(machineId) &&status == PhoneMachineStatus.ready) {- // Just set up from this phone (Set up a device): which one it is, among the rest.- word = 'new';+ // Just set up from this phone (Set up a device): which one it is, among the rest. Not green:+ // beside the green Start it read as a second button. Gone once Start is pressed: its spinner+ // says enough.+ (word, color) = (+ notifier.machineStarting(machineId) ? '' : 'new',+ tty.text,+ );}// Whether it runs Harness OS and has an update, for its sheet's Update and Change Wi-Fi; asked// at most every few minutes, the answer redrawing the list.@@ -665,7 +669,6 @@ class _RefreshButtonState extends State<_RefreshButton>}}-/// Start, on a computer just set up from this phone: its harness — OpenCode first — or, with none/// there yet, a new OpenCode in a fresh project of its own, opened as soon as it is up.class _StartButton extends StatefulWidget {@@ -682,23 +685,27 @@ class _StartButton extends StatefulWidget {}class _StartButtonState extends State<_StartButton> {- bool _busy = false;+ bool get _busy => _app.machineStarting(widget.machineId);AppNotifier get _app => widget.notifier;Agent? _harness() {final agents = _app.machineStates[widget.machineId]?.agents ?? const [];- bool opencode(Agent agent) => '${agent.name} ${agent.title ?? ''}'- .toLowerCase()- .contains('opencode');+ bool opencode(Agent agent) =>+ '${agent.name} ${agent.title ?? ''}'.toLowerCase().contains('opencode');return agents.where(opencode).firstOrNull ?? agents.firstOrNull;}Future<void> _start() async {final messenger = ScaffoldMessenger.maybeOf(context);var harness = _harness();+ _app.setMachineStarting(widget.machineId, true);+ // As the desktop's first run: the harness in a tab of its own, "code", on the account's desk —+ // the tab this computer's screen opens on when someone signs in there, rather than a second+ // OpenCode of its own. Read first, so the tab has a desk to be written to.+ await _app.readDesk();if (harness == null) {- setState(() => _busy = true);+ _app.openNextAgentInNewDeskTab(name: 'code');final failed = await _app.createAgent(widget.machineId,engine: 'opencode',@@ -706,7 +713,8 @@ class _StartButtonState extends State<_StartButton> {projectFolder: const ProjectFolderRequest.newProject(),);if (failed != null) {- if (mounted) setState(() => _busy = false);+ _app.forgetNewDeskTabIntent();+ _app.setMachineStarting(widget.machineId, false);messenger?.showSnackBar(SnackBar(content: Text(failed)));return;}@@ -716,27 +724,64 @@ class _StartButtonState extends State<_StartButton> {DateTime.now().isBefore(deadline)) {await Future<void>.delayed(const Duration(seconds: 1));}+ _app.setMachineStarting(widget.machineId, false);if (!mounted) return;- setState(() => _busy = false);if (harness == null) {messenger?.showSnackBar(const SnackBar(- content: Text('OpenCode is still starting there. Try again in a moment.'),+ content: Text(+ 'OpenCode is still starting there. Try again in a moment.',+ ),),);return;}+ } else {+ _app.setMachineStarting(widget.machineId, false);+ // There already, in a tab (the screen's own) or in none: one of none gets its "code" tab.+ final ref = (machineId: widget.machineId, agentId: harness.id);+ final tab = _app.deskTabs+ .where(+ (t) => t.panes.any(+ (p) => p.machineId == ref.machineId && p.agentId == ref.agentId,+ ),+ )+ .firstOrNull;+ if (tab != null) {+ _app.selectDeskTab(tab.id);+ } else {+ _app.createDeskTabFor(ref, name: 'code');+ }}_app.sawMachine(widget.machineId);if (mounted) openAgent(context, _app, widget.machineId, harness.id);}+ /// While it starts, a spinner where "Start" was: the word "Starting…" is wider than [room] and+ /// ran over the row's "new". The hidden "Start" keeps the place, so nothing beside it moves.@override- Widget build(BuildContext context) => TtyTextButton(- key: ValueKey('machines-start-${widget.machineId}'),- label: _busy ? 'Starting…' : 'Start',- color: Tty.of(context).green,- weight: FontWeight.w600,- onPressed: _busy ? null : () => unawaited(_start()),- );+ Widget build(BuildContext context) {+ final green = Tty.of(context).green;+ final button = TtyTextButton(+ key: ValueKey('machines-start-${widget.machineId}'),+ label: 'Start',+ color: green,+ weight: FontWeight.w600,+ onPressed: _busy ? null : () => unawaited(_start()),+ );+ if (!_busy) return button;+ return Semantics(+ label: 'Starting',+ child: Stack(+ alignment: Alignment.center,+ children: [+ ExcludeSemantics(child: Opacity(opacity: 0, child: button)),+ SizedBox.square(+ dimension: 16,+ child: CircularProgressIndicator(strokeWidth: 1.8, color: green),+ ),+ ],+ ),+ );+ }}diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex 246a82e0c..2b049b585 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -211,6 +211,7 @@ class _NewAgentPageState extends State<NewAgentPage> {@overridevoid dispose() {+ _holdCheck?.cancel();_keepDraft();_task.dispose();_attachments.dispose();@@ -977,6 +978,8 @@ class _NewAgentPageState extends State<NewAgentPage> {// own, made from the rows as they read then.if (!creation.awaitingConfirmation) _creation = null;if (error == null) {+ _held = null;+ _holdCheck?.cancel();// The harness exists: the draft that described it would be a second one waiting to be made// by accident. See [NewAgentDraft].newAgentDraft = null;@@ -985,13 +988,36 @@ class _NewAgentPageState extends State<NewAgentPage> {_open(creation.agentId);return;}+ // Held before anything started — an engine the machine is installing, a model waking: not a+ // failure. Said as a wait, not in red, and asked again by itself until the harness starts, is+ // refused, or is called off; Cancel request stays.+ if (creation.canCancelPending) {+ setState(() {+ _creating = false;+ _error = null;+ _failure = null;+ _held = error;+ });+ _holdCheck?.cancel();+ _holdCheck = Timer(const Duration(seconds: 4), () {+ if (mounted && identical(_creation, creation) && !_creating) {+ unawaited(_start());+ }+ });+ return;+ }setState(() {_creating = false;+ _held = null;_error = error;_failure = error;});}+ /// What the machine holds the request on, while it does (an engine installing): shown as a wait.+ String? _held;+ Timer? _holdCheck;+/// The files [creation] is to be handed once it exists, and the task that follows them — kept/// beside [_creation] so a Check status that finds it started still hands them over.({AgentCreationAttempt creation, List<HarnessAttachment> files, String task})?@@ -1468,6 +1494,32 @@ class _NewAgentPageState extends State<NewAgentPage> {),),],+ if (_held != null && _error == null)+ Padding(+ key: const ValueKey('new-agent-held'),+ padding: const EdgeInsets.only(top: 8),+ child: Row(+ children: [+ SizedBox.square(+ dimension: 12,+ child: CircularProgressIndicator(+ strokeWidth: 1.6,+ color: tty.dim,+ ),+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ _held!,+ style: tty.style(+ color: tty.dim,+ size: TtySize.meta,+ ),+ ),+ ),+ ],+ ),+ ),if (_error != null)Padding(padding: const EdgeInsets.only(top: 8),diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dartindex b807762c0..db18df81f 100644--- a/mobile/lib/phone/phone_search_results.dart+++ b/mobile/lib/phone/phone_search_results.dart@@ -1,6 +1,7 @@import 'dart:async';import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;import 'package:harness_mobile/shared/theme/app_theme.dart';@@ -9,6 +10,7 @@ import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/state/external_session.dart';import 'agent_index.dart';+import 'agents_page.dart' show showAgentActions;import 'desk_groups.dart';import 'desk_tab_filter_bar.dart';import 'find_row.dart';@@ -19,6 +21,7 @@ import 'phone_search_catalog.dart' show phoneAgentId;import 'phone_search_commands.dart';import 'phone_search_controller.dart';import 'phone_search_rank.dart';+import 'phone_sheet.dart';import 'phone_status.dart';import 'resume_agent.dart';import 'search_result_text.dart'@@ -592,6 +595,7 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {terms: terms,selected: selected,enabled: openable || _resuming == row.id,+ onLongPress: () => _hold(entry),// The harness on screen is where Cancel goes: a tap on it is Cancel.onTap: _resuming != null? null@@ -684,6 +688,44 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {row.entry?.machineId == showing.machineId &&row.entry?.agent.id == showing.agentId;+ /// Holding a harness: Stop it while its computer answers. While it does not — dialled again and+ /// again, its row only last known — Stop could never arrive, so the phone takes the row off its+ /// own list instead; the computer's list puts it back when it answers, if it is still there.+ void _hold(AgentEntry entry) {+ final notifier = widget.notifier;+ final machineId = entry.machine.machine.machineId;+ final agent = entry.agent;+ if (phoneMachineStatusOf(entry.machine) == PhoneMachineStatus.ready) {+ // Its computer answers: the sheet a computer's own list offers — Stop, Delete.+ unawaited(showAgentActions(context, notifier, machineId, agent));+ return;+ }+ final messenger = ScaffoldMessenger.maybeOf(context);+ unawaited(+ showPhoneSheet(+ context,+ title: agent.displayName,+ actions: [+ PhoneSheetAction(+ icon: LucideIcons.eyeOff300,+ label: 'Remove from this list',+ onTap: () {+ unawaited(notifier.forgetUnreachableAgent(machineId, agent.id));+ messenger?.showSnackBar(+ SnackBar(+ content: Text(+ '${entry.machineName} is not connected. If it comes back '+ 'and this harness is still there, it shows again.',+ ),+ ),+ );+ },+ ),+ ],+ ),+ );+ }+/// A tap goes to the controller first, which absorbs the ones that only move/// the search: a `?` row taking its mode, a project or machine narrowing it./// What comes back is something to actually open.diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex e2ea71d69..0c2d29974 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -761,7 +761,11 @@ class AppNotifier extends ChangeNotifier {/// The next agent made on this phone gets a tab of its own — armed by the `+`/// on the tab row before the new-agent form opens, and spent (or forgotten)/// by the time that form closes. See [PhoneDesk.openNextAgentInNewTab].- void openNextAgentInNewDeskTab() => _desk.openNextAgentInNewTab();+ void openNextAgentInNewDeskTab({String? name}) =>+ _desk.openNextAgentInNewTab(name: name);++ /// Read the desk now and wait for it, so a write that follows has a desk to go to.+ Future<void> readDesk() => _desk.refresh();/// That form closed without making anything.void forgetNewDeskTabIntent() => _desk.forgetNewTabIntent();@@ -1316,7 +1320,8 @@ class AppNotifier extends ChangeNotifier {productMeasurement.context = {'surface': 'phone',// The backend refuses a whole report whose release is not a plain x.y.z.- 'release': RegExp(r'^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){2}$').hasMatch(release)+ 'release':+ RegExp(r'^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){2}$').hasMatch(release)? release: 'unknown','platform': switch (defaultTargetPlatform) {@@ -6042,14 +6047,15 @@ class AppNotifier extends ChangeNotifier {/// Hands a sign-in this phone caught back to [machineId], to the program waiting for it there/// (`browser_callback`, cli core/terminals/browser.ts). `{'error': 'UNAVAILABLE'}` when the line is down.- Future<Map<String, dynamic>> browserCallback(String machineId, String url) async {+ Future<Map<String, dynamic>> browserCallback(+ String machineId,+ String url,+ ) async {final machine = machineStates[machineId];if (machine == null || machine.needsLink) return {'error': 'UNAVAILABLE'};try {- return await _conn(machineId).request(- 'browser_callback',- payload: {'url': url},- );+ return await _conn(machineId)+ .request('browser_callback', payload: {'url': url});} catch (_) {return {'error': 'UNAVAILABLE'};}@@ -6066,9 +6072,8 @@ class AppNotifier extends ChangeNotifier {final machine = machineStates[machineId];if (machine == null || machine.needsLink) return {'error': 'UNAVAILABLE'};try {- return await _conn(- machineId,- ).request('os_device', payload: payload, timeout: timeout);+ return await _conn(machineId)+ .request('os_device', payload: payload, timeout: timeout);} catch (_) {return {'error': 'UNAVAILABLE'};}@@ -6079,7 +6084,8 @@ class AppNotifier extends ChangeNotifier {final Map<String, Map<String, dynamic>> osStatus = {};final Map<String, DateTime> _osAsked = {};- bool runsHarnessOs(String machineId) => osStatus[machineId]?['harnessOs'] == true;+ bool runsHarnessOs(String machineId) =>+ osStatus[machineId]?['harnessOs'] == true;bool updateAvailable(String machineId) {final update = osStatus[machineId]?['update'];@@ -6113,11 +6119,8 @@ class AppNotifier extends ChangeNotifier {final machine = machineStates[machineId];if (machine == null || machine.needsLink) return {'error': 'UNAVAILABLE'};try {- return await _conn(machineId).request(- 'connectors',- payload: payload,- timeout: timeout,- );+ return await _conn(machineId)+ .request('connectors', payload: payload, timeout: timeout);} catch (_) {return {'error': 'UNAVAILABLE'};}@@ -6500,85 +6503,84 @@ class AppNotifier extends ChangeNotifier {String? detail,String machine, {Map<String, dynamic>? choices,- }) =>- switch (code) {- // A New Folder named after its first task (`projectNameMode:- // suggested`). A current machine numbers that name past a folder that- // exists (`robot-2`), so only one that predates the mode refuses it, and- // its sentence is written for a name somebody typed. The phone has no- // name field to change instead, so it says the way to a fresh folder.- 'PROJECT_EXISTS' when choices?['projectNameMode'] == 'suggested' =>- 'A folder named after this task already exists on $machine. '- 'Choose it from your projects, or update Harness there to make '- 'a new one.',- // Making the project folder (a new one, a clone, a worktree or a- // branch) before anything starts in it: `cli/src/lib/projectFolder.ts`- // and `gitProject.ts`. The machine's sentence says what to change: the- // URL, the branch, Worktree.- 'INVALID_PROJECT_SOURCE' ||- 'INVALID_REPOSITORY' ||- 'PROJECT_PREPARATION_FAILED' ||- 'PROJECT_EXISTS' ||- 'CLONE_FAILED' ||- 'CLONE_TIMEOUT' ||- 'GIT_PROJECT_UNAVAILABLE' ||- 'INVALID_BRANCH' ||- 'BRANCH_SWITCH_FAILED' ||- 'WORKTREE_FAILED' ||- 'GIT_UNAVAILABLE' =>- detail ?? 'Could not prepare the project folder on $machine.',- 'CWD_NOT_FOUND' || 'INVALID_CWD' =>- 'The project folder is unavailable on $machine. '- 'Choose another folder and try again.',- 'TMUX_UNAVAILABLE' =>- 'Harness needs tmux to start harnesses on $machine. '- 'Install tmux there, then try again.',- // The machine's own sentence names the engine and the flag it lacks.- // Without one, the phone's Approvals names the way out.- 'CODEX_CLI_TOO_OLD' =>- detail ??- 'The installed Codex CLI on $machine is too old for '- 'Auto-approve. Update Codex there, or choose Ask first under '- 'Approvals.',- 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>- 'Update the harness CLI on this machine to create a harness',- 'INVALID_DSH' =>- 'This harness is not installed on $machine. '- '${detail ?? 'Install it there, then try again.'}',- 'PROMPT_UNSUPPORTED' =>- 'This engine cannot be opened with a first message on $machine.',- 'PROMPT_TOO_LONG' =>- 'This first task is too long for $machine. Shorten it and try again.',- 'AGENT_UNSUPPORTED' =>- 'This engine cannot be opened as a named agent on $machine.',- 'INVALID_AGENT' =>- 'This engine cannot be opened as that named agent on $machine.',- 'INVALID_PERMISSION_MODE' =>- 'This engine has no such permission mode on $machine.',- // A daemon older than the engine refuses it by name, with no detail;- // the fix is the update the UNSUPPORTED codes ask for. A detail is a- // reason of its own (the sample runs only Claude Code and Codex).- 'INVALID_ENGINE' =>- detail ?? 'Update the harness CLI on $machine to start this agent.',- // Opening a conversation Harness did not start (`resumeSessionId`). The machine says what- // stopped it: open elsewhere, already a harness, gone.- 'SESSION_OPEN_ELSEWHERE' ||- 'SESSION_IN_HARNESS' ||- 'SESSION_NOT_FOUND' ||- 'SESSION_FOLDER_GONE' ||- 'SESSION_BUSY_IN_TERMINAL' ||- 'SESSION_STOP_FAILED' ||- 'INVALID_SESSION' =>- detail ?? 'Could not open that conversation on $machine.',- // Not the machine's own sentence: it ends "Moving it here quits it- // there", written for the desktop's take-over button. A phone sends no- // `takeOver` and has no such button, so what it can offer is the way- // that works from here.- 'SESSION_OPEN_IN_TERMINAL' =>- 'It is open in a terminal on $machine. Close it there, then open '- 'it here.',- _ => 'Create harness failed: ${detail ?? code}',- };+ }) => switch (code) {+ // A New Folder named after its first task (`projectNameMode:+ // suggested`). A current machine numbers that name past a folder that+ // exists (`robot-2`), so only one that predates the mode refuses it, and+ // its sentence is written for a name somebody typed. The phone has no+ // name field to change instead, so it says the way to a fresh folder.+ 'PROJECT_EXISTS' when choices?['projectNameMode'] == 'suggested' =>+ 'A folder named after this task already exists on $machine. '+ 'Choose it from your projects, or update Harness there to make '+ 'a new one.',+ // Making the project folder (a new one, a clone, a worktree or a+ // branch) before anything starts in it: `cli/src/lib/projectFolder.ts`+ // and `gitProject.ts`. The machine's sentence says what to change: the+ // URL, the branch, Worktree.+ 'INVALID_PROJECT_SOURCE' ||+ 'INVALID_REPOSITORY' ||+ 'PROJECT_PREPARATION_FAILED' ||+ 'PROJECT_EXISTS' ||+ 'CLONE_FAILED' ||+ 'CLONE_TIMEOUT' ||+ 'GIT_PROJECT_UNAVAILABLE' ||+ 'INVALID_BRANCH' ||+ 'BRANCH_SWITCH_FAILED' ||+ 'WORKTREE_FAILED' ||+ 'GIT_UNAVAILABLE' =>+ detail ?? 'Could not prepare the project folder on $machine.',+ 'CWD_NOT_FOUND' || 'INVALID_CWD' =>+ 'The project folder is unavailable on $machine. '+ 'Choose another folder and try again.',+ 'TMUX_UNAVAILABLE' =>+ 'Harness needs tmux to start harnesses on $machine. '+ 'Install tmux there, then try again.',+ // The machine's own sentence names the engine and the flag it lacks.+ // Without one, the phone's Approvals names the way out.+ 'CODEX_CLI_TOO_OLD' =>+ detail ??+ 'The installed Codex CLI on $machine is too old for '+ 'Auto-approve. Update Codex there, or choose Ask first under '+ 'Approvals.',+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>+ 'Update the harness CLI on this machine to create a harness',+ 'INVALID_DSH' =>+ 'This harness is not installed on $machine. '+ '${detail ?? 'Install it there, then try again.'}',+ 'PROMPT_UNSUPPORTED' =>+ 'This engine cannot be opened with a first message on $machine.',+ 'PROMPT_TOO_LONG' =>+ 'This first task is too long for $machine. Shorten it and try again.',+ 'AGENT_UNSUPPORTED' =>+ 'This engine cannot be opened as a named agent on $machine.',+ 'INVALID_AGENT' =>+ 'This engine cannot be opened as that named agent on $machine.',+ 'INVALID_PERMISSION_MODE' =>+ 'This engine has no such permission mode on $machine.',+ // A daemon older than the engine refuses it by name, with no detail;+ // the fix is the update the UNSUPPORTED codes ask for. A detail is a+ // reason of its own (the sample runs only Claude Code and Codex).+ 'INVALID_ENGINE' =>+ detail ?? 'Update the harness CLI on $machine to start this agent.',+ // Opening a conversation Harness did not start (`resumeSessionId`). The machine says what+ // stopped it: open elsewhere, already a harness, gone.+ 'SESSION_OPEN_ELSEWHERE' ||+ 'SESSION_IN_HARNESS' ||+ 'SESSION_NOT_FOUND' ||+ 'SESSION_FOLDER_GONE' ||+ 'SESSION_BUSY_IN_TERMINAL' ||+ 'SESSION_STOP_FAILED' ||+ 'INVALID_SESSION' =>+ detail ?? 'Could not open that conversation on $machine.',+ // Not the machine's own sentence: it ends "Moving it here quits it+ // there", written for the desktop's take-over button. A phone sends no+ // `takeOver` and has no such button, so what it can offer is the way+ // that works from here.+ 'SESSION_OPEN_IN_TERMINAL' =>+ 'It is open in a terminal on $machine. Close it there, then open '+ 'it here.',+ _ => 'Create harness failed: ${detail ?? code}',+ };/// Calls off a request the machine holds — the New form's Cancel request, the desktop's/// `cancelAgentCreation`. Null once the machine says it is cancelled; otherwise what to tell the@@ -6883,6 +6885,20 @@ class AppNotifier extends ChangeNotifier {if (_newMachines.remove(machineId)) notifyListeners();}+ /// New computers whose Start was pressed and is still bringing up their harness: their row drops+ /// "new" and its Start spins.+ final Set<String> _startingMachines = {};++ bool machineStarting(String machineId) =>+ _startingMachines.contains(machineId);++ void setMachineStarting(String machineId, bool starting) {+ final changed = starting+ ? _startingMachines.add(machineId)+ : _startingMachines.remove(machineId);+ if (changed) notifyListeners();+ }+/// Renames a machine via `PATCH /api/machines/:machineId` (control-plane REST — the machine's/// `name` is backend-owned, unlike an agent's, which lives on the harness CLI). Returns null on/// success, or an error message to show inline in the caller's dialog.@@ -6961,7 +6977,8 @@ class AppNotifier extends ChangeNotifier {Future<String?> _performDeleteMachine(String machineId) async {final revision = _authRevision;- final name = machineStates[machineId]?.machine.displayName ?? 'This computer';+ final name =+ machineStates[machineId]?.machine.displayName ?? 'This computer';final device = await _machineDeviceKey(machineId);// Signed out, or into another account, while the log was read: nothing here is theirs.if (!_authWorkCurrent(revision)) return null;@@ -6978,7 +6995,9 @@ class AppNotifier extends ChangeNotifier {// Gone from the log already — another device signed it out after this phone read the log:// what this step was for is done.if (failure == 'NOT_IN_LOG') failure = null;- if (failure != null) return 'Couldn’t sign $name out ($failure). Try again.';+ if (failure != null) {+ return 'Couldn’t sign $name out ($failure). Try again.';+ }// The account let it go meanwhile (removed from another device): no record is left to delete.if (machineStates[machineId] == null) return null;}@@ -7050,7 +7069,9 @@ class AppNotifier extends ChangeNotifier {return null;}().timeout(_machineKeyReadCap);} catch (error) {- debugPrint('devices: could not read the key of ${_shortId(machineId)}: $error');+ debugPrint(+ 'devices: could not read the key of ${_shortId(machineId)}: $error',+ );return null;}}@@ -7464,6 +7485,16 @@ class AppNotifier extends ChangeNotifier {return null;}+ /// Takes a harness off this phone's lists while its computer does not answer, so `agent_delete`+ /// cannot reach it: nothing is stopped there. Its desk tab keeps it, and the computer's own list+ /// brings it back as soon as it answers again (`_replaceAgents`) if it is still there.+ Future<void> forgetUnreachableAgent(String machineId, String agentId) async {+ final machine = machineStates[machineId];+ if (machine == null) return;+ await _removeAgent(machine, agentId);+ notifyListeners();+ }+/// Bring a stopped agent back, so something can be opened on it.////// The desktop's `resumeAgent`: a thin guard over [restartAgent], which is the@@ -10244,7 +10275,11 @@ class AppNotifier extends ChangeNotifier {case 'browser_open':final url = payload['url'];if (url is String && url.isNotEmpty) {- onBrowserOpen?.call(machineId, payload['agentId'] as String? ?? '', url);+ onBrowserOpen?.call(+ machineId,+ payload['agentId'] as String? ?? '',+ url,+ );}return;// ⚠️ Everything else changed nothing here, so it must not redraw. The machine streams everydiff --git a/mobile/lib/state/phone_desk.dart b/mobile/lib/state/phone_desk.dartindex a7b6b03b4..7af0397c3 100644--- a/mobile/lib/state/phone_desk.dart+++ b/mobile/lib/state/phone_desk.dart@@ -235,13 +235,15 @@ class PhoneDesk {void adopt(AgentRef agent, {String? name, String? tabId}) {if (!_state.enabled) return;final wanted = _newTabForNextAgent;+ final wantedName = _newTabName;_newTabForNextAgent = false;+ _newTabName = null;final pane = DeskPaneRef(machineId: agent.machineId,agentId: agent.agentId,);if (wanted) {- createTabFor(agent, name: name);+ createTabFor(agent, name: wantedName ?? name);return;}final picked = tabId == null@@ -349,12 +351,22 @@ class PhoneDesk {/// made minutes later from the terminal's own `+` — in a tab of its own./// [forgetNewTabIntent] is the cancel path; between the two, the flag cannot/// survive the screen that set it.- void openNextAgentInNewTab() => _newTabForNextAgent = true;+ ///+ /// [name]: the tab's, over the agent's own — Start on a computer just set up names it "code", the+ /// tab its screen then opens on.+ void openNextAgentInNewTab({String? name}) {+ _newTabForNextAgent = true;+ _newTabName = name;+ }/// The form closed without making anything — see [openNextAgentInNewTab].- void forgetNewTabIntent() => _newTabForNextAgent = false;+ void forgetNewTabIntent() {+ _newTabForNextAgent = false;+ _newTabName = null;+ }bool _newTabForNextAgent = false;+ String? _newTabName;/// The desk's ids are 32 hex characters (backend `lib/desk.ts`), and a tab/// made here has to look like one made anywhere else.