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
Phone: set up a device with no screen, and its update and Wi-Fi
bubu-dudu686ca33ff9c1
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex 91a212ed5..0a65c2fdc 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -9,6 +9,10 @@<!-- Lets libwebrtc notice a wifi↔cellular change and restart ICE rather thanwait out the disconnect grace. Not a runtime permission. --><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <!-- Joining a new device's setup hotspot (Settings ▸ Add a device): a WifiNetworkSpecifier+ request, which Android confirms with its own sheet. Neither is a runtime permission. -->+ <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><!-- Taking a picture to send to an agent. Picking an EXISTING picture needsno permission at all: image_picker goes through ACTION_GET_CONTENT / thephoto picker, which hands back one item the user chose rather thandiff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.ktindex 43c4b74b7..282c75897 100644--- a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/MainActivity.kt@@ -10,7 +10,13 @@ import android.graphics.BitmapFactoryimport android.media.AudioAttributesimport android.media.AudioManagerimport android.media.MediaPlayer+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.net.NetworkRequestimport android.net.Uri+import android.net.wifi.WifiNetworkSpecifier+import android.os.PatternMatcherimport android.os.Buildimport android.os.Handlerimport android.os.Looper@@ -112,6 +118,62 @@ class MainActivity : FlutterActivity() {val asset = call.arguments as? Stringresult.success(asset != null && playChime(asset))}++ // `harness/setup_wifi` — joining a new device's setup hotspot (Dart:+ // `lib/phone/add_device/setup_hotspot.dart`). `join` asks Android for any open Wi-Fi named+ // `Harness-…`; Android shows its own sheet listing those nearby and the person picks one.+ // The app's traffic is then bound to that Wi-Fi — it has no Internet, and Android would+ // otherwise send 10.42.0.1 over mobile data. `leave` drops it, and the phone+ // returns to its own Wi-Fi by itself.+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "harness/setup_wifi")+ .setMethodCallHandler { call, result ->+ when (call.method) {+ "join" -> {+ val prefix = call.argument<String>("prefix") ?: "Harness-"+ joinSetupWifi(prefix, result)+ }+ "leave" -> { leaveSetupWifi(); result.success(true) }+ else -> result.notImplemented()+ }+ }+ }++ private var setupNetwork: ConnectivityManager.NetworkCallback? = null++ private fun joinSetupWifi(prefix: String, result: MethodChannel.Result) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { result.success("unsupported"); return }+ leaveSetupWifi()+ val connectivity = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager+ val specifier = WifiNetworkSpecifier.Builder()+ .setSsidPattern(PatternMatcher(prefix, PatternMatcher.PATTERN_PREFIX))+ .build()+ val request = NetworkRequest.Builder()+ .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)+ .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)+ .setNetworkSpecifier(specifier)+ .build()+ val main = Handler(Looper.getMainLooper())+ var answered = false+ fun answer(value: String) = main.post { if (!answered) { answered = true; result.success(value) } }+ val callback = object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) {+ connectivity.bindProcessToNetwork(network)+ answer("joined")+ }+ override fun onUnavailable() { setupNetwork = null; answer("unavailable") }+ override fun onLost(network: Network) { connectivity.bindProcessToNetwork(null) }+ }+ setupNetwork = callback+ // The sheet waits on the person; give up after two minutes.+ connectivity.requestNetwork(request, callback, 120_000)+ }++ private fun leaveSetupWifi() {+ val callback = setupNetwork ?: return+ setupNetwork = null+ val connectivity = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager+ connectivity.bindProcessToNetwork(null)+ try { connectivity.unregisterNetworkCallback(callback) } catch (e: IllegalArgumentException) {}}/** Plays the Flutter asset [asset] once, as a sonification — the system's own sounds' stream —diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex a94d86589..7414c9596 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -252,6 +252,14 @@ class ApiClient {);}+ /// A sign-in already approved for this account, for a device with no screen to show a QR on:+ /// `{ticket, expiresIn}`. Handed to the device over its setup hotspot; it spends it once it is+ /// on the person's Wi-Fi (`harness login --ticket`).+ Future<Map<String, dynamic>> boxTicket() async {+ final res = await _dio.post('/api/auth/box/ticket', data: const {});+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);+ }+// -- the desk: the account's tabs, the same on every computer --/// `{revision, tabs}` as the backend holds it (its `routes/desk.ts`); null ondiff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex caa16f703..c2c3ec359 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -68,6 +68,9 @@ const Set<String> encryptedDownTypes = {// A sign-in this phone caught for a page a harness's program opened (`AppNotifier.browserCallback`): it// carries the code. A `MACHINE_REQUESTS` type in the CLI.'browser_callback',+ // A Harness OS computer managed from here (`AppNotifier.osDevice`, CLI services/osDevice.ts): its+ // update, and its Wi-Fi with the password. A `MACHINE_REQUESTS` type in the CLI.+ 'os_device','codex_profiles_list','codex_profile_link',// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missingdiff --git a/mobile/lib/phone/add_device/add_device_page.dart b/mobile/lib/phone/add_device/add_device_page.dartnew file mode 100644index 000000000..d81338dcd--- /dev/null+++ b/mobile/lib/phone/add_device/add_device_page.dart@@ -0,0 +1,580 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/api/api_client.dart' show describeApiError;+import 'package:harness_mobile/core/models.dart' show Machine;+import 'package:harness_mobile/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/state/app_state.dart';++import '../machines_tab.dart';+import '../phone_navigation.dart' show phoneRoute;+import '../settings_row.dart';+import '../tty.dart';+import '../tty_controls.dart';+import 'setup_hotspot.dart';++/// Settings ▸ Set up a device: a Harness with no screen (a box, a mini PC) put on the person's+/// Wi-Fi and signed in to this phone's account, through the device's own setup hotspot.+///+/// ticket (while this phone still has the Internet) → pick `Harness-XXXX` from the Wi-Fi list+/// → the Wi-Fi the device sees → password → the device leaves its hotspot for that Wi-Fi+/// → it shows up in this account's computers.+///+/// 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.+class AddDevicePage extends StatefulWidget {+ const AddDevicePage({super.key, required this.notifier, this.hotspot});++ final AppNotifier notifier;+ final SetupHotspot? hotspot;++ @override+ State<AddDevicePage> createState() => _AddDevicePageState();+}++enum _Step { start, join, networks, password, waiting, done }++class _AddDevicePageState extends State<AddDevicePage> {+ late final SetupHotspot _hotspot = widget.hotspot ?? SetupHotspot();+ final _ssid = TextEditingController();+ final _password = TextEditingController();+ final _name = TextEditingController();++ _Step _step = _Step.start;+ bool _busy = false;+ String _error = '';+ String _ticket = '';+ Map<String, dynamic> _device = const {};+ List<SetupNetwork> _networks = const [];+ SetupNetwork? _chosen;++ /// The Wi-Fi password shown as typed, by the eye at the field's end.+ bool _reveal = false;++ /// Back to the hotspot right after sending a Wi-Fi: the device may still be trying it.+ bool _retrying = false;++ /// The device's last failed Wi-Fi and why, read when the phone joined its hotspot again.+ ({String ssid, String why})? _failed;+ bool _alreadyHere = false;++ /// The device read `running` in the account when its Wi-Fi was sent.+ bool _wasRunning = false;+ Timer? _poll;++ /// How long the device gets to join the Wi-Fi, sign in and show up in the account.+ static const _comeOnline = Duration(seconds: 75);++ AppNotifier get _app => widget.notifier;++ @override+ void dispose() {+ _poll?.cancel();+ unawaited(_hotspot.leave());+ _ssid.dispose();+ _password.dispose();+ _name.dispose();+ super.dispose();+ }++ void _show(_Step step, {String error = ''}) {+ if (!mounted) return;+ setState(() {+ _step = step;+ _error = error;+ _busy = false;+ });+ }++ @override+ void initState() {+ super.initState();+ unawaited(_start());+ }++ // -- 1. a ticket while the Internet is still here --++ Future<void> _start() async {+ _show(_Step.start);+ setState(() => _busy = true);+ try {+ final ticket = await _app.api.boxTicket();+ _ticket = ticket['ticket'] as String? ?? '';+ } catch (e) {+ _show(_Step.start, error: describeApiError(e));+ return;+ }+ if (_ticket.isEmpty) {+ _show(_Step.start, error: 'Could not prepare the sign-in. Try again.');+ return;+ }+ await _join();+ }++ // -- 2. onto the device's hotspot, picked from the Wi-Fi list --++ Future<void> _join() async {+ _show(_Step.join);+ setState(() => _busy = true);+ if (SetupHotspot.joinsByItself) {+ final joined = await _hotspot.join();+ if (!mounted) return;+ if (joined == 'unavailable') {+ _show(+ _Step.join,+ error: 'No device was chosen. Check it is plugged in and nearby: its Wi-Fi is named "Harness-…".',+ );+ return;+ }+ }+ // Joined by Android, or by the person in Settings: wait for the page to answer.+ _poll?.cancel();+ _poll = Timer.periodic(+ const Duration(seconds: 2),+ (_) => unawaited(_reach()),+ );+ unawaited(_reach());+ }++ bool _reaching = false;++ Future<void> _reach() async {+ if (_reaching || _step != _Step.join) return;+ _reaching = true;+ try {+ final info = await _hotspot.info();+ if (info == null || !mounted || _step != _Step.join) return;+ _poll?.cancel();+ _device = info;+ _retrying = false;+ final networks = await _hotspot.networks();+ if (!mounted) return;+ // 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'+ ? last['message'] as String? ?? ''+ : '';+ setState(() {+ _networks = networks;+ _step = _Step.networks;+ _error = why;+ _failed = why.isEmpty+ ? null+ : (ssid: last['ssid'] as String? ?? '', why: why);+ _busy = false;+ });+ } on SetupException catch (e) {+ _show(_Step.join, error: e.message);+ } finally {+ _reaching = false;+ }+ }++ // -- 3. the person's Wi-Fi --++ void _choose(SetupNetwork? network) {+ _chosen = network;+ _ssid.text = network?.ssid ?? '';+ _password.clear();+ // The same Wi-Fi again after it failed: why, over the password being typed again.+ final failed = _failed;+ _show(+ _Step.password,+ error: failed != null && network != null && failed.ssid == network.ssid+ ? failed.why+ : '',+ );+ }++ Future<void> _send() async {+ final ssid = _ssid.text.trim();+ final password = _password.text;+ final secure = _chosen?.secure ?? password.isNotEmpty;+ if (ssid.isEmpty) {+ _show(_Step.password, error: 'Enter the Wi-Fi name.');+ return;+ }+ if (secure && (password.length < 8 || password.length > 63)) {+ _show(_Step.password, error: 'A Wi-Fi password has 8 to 63 characters.');+ 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.+ _alreadyHere = _device['signedIn'] == true;+ _wasRunning = _machine?.status == 'running';+ try {+ await _hotspot.connect(+ ssid: ssid,+ password: secure ? password : '',+ ticket: _ticket,+ );+ } on SetupException catch (e) {+ _show(_Step.password, error: e.message);+ return;+ }+ await _hotspot.leave();+ _wait(ssid);+ }++ /// The device's computer id as the backend keeps it (`normalizeComputerId`): its file has+ /// dashes, the account's record has none.+ String get _computerId => _bare(_device['computerId'] as String? ?? '');++ static String _bare(String id) =>+ id.toLowerCase().replaceAll(RegExp('[^a-z0-9]'), '');++ // -- 4. the device on the Internet, in this account --++ Machine? get _machine {+ if (_computerId.isEmpty) return null;+ for (final machine in _app.machines) {+ if (_bare(machine.computerId ?? '') == _computerId) return machine;+ }+ return null;+ }++ // -- 5. its name, then Computers with it marked new --++ Future<void> _finish() async {+ final machine = _machine;+ final name = _name.text.trim();+ if (machine != null) {+ if (name.isNotEmpty && name != machine.displayName) {+ setState(() => _busy = true);+ final failed = await _app.renameMachine(machine.machineId, name);+ if (!mounted) return;+ if (failed != null) {+ _show(_Step.done, error: failed);+ return;+ }+ }+ if (!_alreadyHere) _app.markMachineNew(machine.machineId);+ }+ if (!mounted) return;+ await Navigator.of(context).pushReplacement(+ phoneRoute((_) => MachinesTab(notifier: _app, large: false)),+ );+ }++ void _wait(String ssid) {+ _show(_Step.waiting);+ final deadline = DateTime.now().add(_comeOnline);+ _poll?.cancel();+ _poll = Timer.periodic(const Duration(seconds: 3), (_) async {+ if (!mounted || _step != _Step.waiting) return;+ try {+ await _app.refreshMachines();+ } catch (_) {+ // The phone may still be finding its way back to its own Wi-Fi.+ }+ if (!mounted || _step != _Step.waiting) return;+ // Done the moment it is online: `running` in the account (the backend sees its daemon). It+ // was offline while it hosted its hotspot, so a `running` now is this Wi-Fi working. Only one+ // that somehow read running all along is given time instead.+ final online = _machine?.status == 'running';+ final settled = _wasRunning+ ? DateTime.now().isAfter(+ deadline.subtract(const Duration(seconds: 45)),+ )+ : online;+ if (settled) {+ _poll?.cancel();+ // Named after its Wi-Fi, `Harness-XXXX`, the name the person just picked it by; a device+ // that was here already keeps its own.+ final machine = _machine;+ _name.text = _alreadyHere && machine != null+ ? machine.displayName+ : _device['hotspot'] as String? ?? machine?.displayName ?? '';+ _show(_Step.done);+ return;+ }+ if (DateTime.now().isAfter(deadline)) {+ _poll?.cancel();+ // Not online by now: the Wi-Fi most likely failed and the device is back on its hotspot with+ // the reason. Android goes back to it by itself; elsewhere the person rejoins it.+ if (SetupHotspot.joinsByItself) {+ _retrying = true;+ unawaited(_join());+ return;+ }+ _show(+ _Step.waiting,+ error:+ 'The device did not come online on "$ssid". If its hotspot is back, it tells why: '+ 'join it again.',+ );+ }+ });+ }++ // -- the page --++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Scaffold(+ backgroundColor: tty.ground,+ resizeToAvoidBottomInset: false,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Align(+ alignment: Alignment.centerLeft,+ child: TtyBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ),+ Expanded(+ child: ListView(+ padding: EdgeInsets.fromLTRB(+ Tty.origin,+ 8,+ Tty.origin,+ MediaQuery.paddingOf(context).bottom ++ MediaQuery.viewInsetsOf(context).bottom ++ 24,+ ),+ children: [+ const TtyText(+ 'Set up a device',+ size: TtySize.display,+ weight: FontWeight.w600,+ ),+ const SizedBox(height: 8),+ // Above the step, not under it: under a list of twenty Wi-Fi it was off screen.+ if (_error.isNotEmpty) ...[+ Text(+ _error,+ key: const Key('add-device-error'),+ style: tty.style(color: tty.red),+ ),+ const SizedBox(height: 12),+ ],+ ..._body(tty),+ const SizedBox(height: 20),+ ..._actions(),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }++ List<Widget> _body(Tty tty) {+ Text say(String text) => Text(text, style: tty.style(color: tty.dim));+ final name = _device['hotspot'] as String? ?? 'Harness-…';+ switch (_step) {+ case _Step.start:+ return [+ say(+ 'For a Harness with no screen. Plug it in and wait a minute: it opens a Wi-Fi named '+ '"Harness-…".',+ ),+ ];+ case _Step.join:+ return [+ if (SetupHotspot.joinsByItself)+ say(+ 'Choose the device, "Harness-…", from the Wi-Fi list. Then wait here.',+ )+ else+ say(+ 'Open Settings ▸ Wi-Fi on this phone and choose "Harness-…". Then come back here.',+ ),+ const SizedBox(height: 12),+ say(+ _retrying+ ? 'The device is still trying the Wi-Fi. Its hotspot comes back within a minute.'+ : 'Looking for the device…',+ ),+ ];+ case _Step.networks:+ return [+ say(+ 'Choose the Wi-Fi for the device. It is the list the device sees.',+ ),+ const SizedBox(height: 12),+ SettingsGroup(+ children: [+ for (final network in _networks)+ SettingsRow(+ key: ValueKey('add-device-wifi-${network.ssid}'),+ title: network.ssid,+ value: network.secure ? 'Locked' : 'Open',+ detail: _bars(network.signal),+ onTap: () => _choose(network),+ ),+ SettingsRow(+ key: const Key('add-device-wifi-other'),+ title: 'Other network…',+ onTap: () => _choose(null),+ ),+ ],+ ),+ ];+ case _Step.password:+ return [+ if (_chosen == null) ...[+ say('The Wi-Fi name, as it is written.'),+ const SizedBox(height: 8),+ TtyField(+ key: const Key('add-device-ssid'),+ controller: _ssid,+ hint: 'Wi-Fi name',+ action: TextInputAction.next,+ maxLength: 32,+ ),+ const SizedBox(height: 12),+ ] else+ say('The password for "${_chosen!.ssid}". It is case-sensitive.'),+ if (_chosen?.secure ?? true) ...[+ const SizedBox(height: 8),+ TtyField(+ key: const Key('add-device-password'),+ controller: _password,+ hint: _chosen == null+ ? 'Password (empty for an open Wi-Fi)'+ : 'Wi-Fi password',+ autofocus: _chosen != null,+ keyboardType: TextInputType.visiblePassword,+ obscure: !_reveal,+ maxLength: 63,+ onSubmitted: _busy ? null : () => unawaited(_send()),+ trailing: [+ AppIconButton(+ key: const Key('add-device-reveal'),+ icon: _reveal ? LucideIcons.eyeOff300 : LucideIcons.eye300,+ size: 20,+ tooltip: _reveal ? 'Hide password' : 'Show password',+ color: tty.dim,+ onPressed: () => setState(() => _reveal = !_reveal),+ ),+ ],+ ),+ ],+ ];+ case _Step.waiting:+ return [+ say(+ _error.isEmpty+ ? '$name is joining "${_ssid.text.trim()}" and signing in to your account. '+ 'This phone goes back to its own Wi-Fi meanwhile.'+ : '',+ ),+ ];+ case _Step.done:+ return [+ say(+ _alreadyHere+ ? '$name is moving to "${_ssid.text.trim()}". It shows in Computers once it is online.'+ : '$name is ready. Give it a name.',+ ),+ const SizedBox(height: 12),+ TtyField(+ key: const Key('add-device-name'),+ controller: _name,+ hint: 'Name',+ autofocus: true,+ maxLength: AppNotifier.machineNameMaxLength,+ onSubmitted: _busy ? null : () => unawaited(_finish()),+ ),+ ];+ }+ }++ List<Widget> _actions() {+ switch (_step) {+ case _Step.start:+ return [+ TtyPrimaryButton(+ key: const Key('add-device-continue'),+ label: 'Try again',+ busy: _busy,+ busyLabel: 'Preparing…',+ onPressed: () => unawaited(_start()),+ ),+ ];+ case _Step.join:+ return [+ if (_error.isNotEmpty || !SetupHotspot.joinsByItself)+ TtyPrimaryButton(+ key: const Key('add-device-retry-join'),+ label: SetupHotspot.joinsByItself ? 'Try again' : 'I joined it',+ onPressed: () =>+ unawaited(SetupHotspot.joinsByItself ? _join() : _reach()),+ ),+ ];+ case _Step.networks:+ return [+ TtyTextButton(+ label: 'Look again',+ onPressed: () {+ _show(_Step.join);+ unawaited(_reach());+ },+ ),+ ];+ case _Step.password:+ return [+ TtyPrimaryButton(+ key: const Key('add-device-connect'),+ label: 'Connect',+ busy: _busy,+ busyLabel: 'Sending…',+ onPressed: () => unawaited(_send()),+ ),+ TtyTextButton(+ label: 'Choose another Wi-Fi',+ onPressed: () => _show(_Step.networks),+ ),+ ];+ case _Step.waiting:+ return [+ if (_error.isNotEmpty)+ TtyPrimaryButton(+ key: const Key('add-device-rejoin'),+ label: 'Join the device again',+ onPressed: () => unawaited(_join()),+ )+ else ...[+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),+ const SizedBox(height: 20),+ // Not waiting out the whole wait: back to the device now. Once it has given up on the+ // Wi-Fi (in under a minute) its hotspot is back, and its Wi-Fi list comes up with why.+ TtyTextButton(+ key: const Key('add-device-retype'),+ label: 'Choose Wi-Fi again',+ onPressed: () {+ _poll?.cancel();+ _retrying = true;+ unawaited(_join());+ },+ ),+ ],+ ];+ case _Step.done:+ return [+ TtyPrimaryButton(+ key: const Key('add-device-done'),+ label: 'OK',+ busy: _busy,+ busyLabel: 'Saving…',+ onPressed: () => unawaited(_finish()),+ ),+ ];+ }+ }++ static String _bars(int signal) => signal >= 70+ ? 'Strong signal'+ : signal >= 40+ ? 'Good signal'+ : 'Weak signal';+}diff --git a/mobile/lib/phone/add_device/setup_hotspot.dart b/mobile/lib/phone/add_device/setup_hotspot.dartnew file mode 100644index 000000000..282c1806d--- /dev/null+++ b/mobile/lib/phone/add_device/setup_hotspot.dart@@ -0,0 +1,137 @@+import 'dart:async';+import 'dart:io';++import 'package:dio/dio.dart';+import 'package:flutter/services.dart';++/// A new device's setup hotspot, `Harness-XXXX`, and the page it answers on (os/setup.py).+///+/// It is open. On Android the app joins it itself (`harness/setup_wifi` in MainActivity): Android lists+/// the `Harness-…` Wi-Fi nearby for the person to pick. Elsewhere the person picks it in Settings ▸ Wi-Fi and+/// comes back; the app notices by reaching the page.+class SetupHotspot {+ SetupHotspot({Dio? dio})+ : _dio =+ dio ??+ Dio(+ BaseOptions(+ baseUrl: 'http://$address',+ connectTimeout: const Duration(seconds: 4),+ receiveTimeout: const Duration(seconds: 8),+ validateStatus: (_) => true,+ ),+ );++ static const address = '10.42.0.1';++ static const prefix = 'Harness-';+ static const _channel = MethodChannel('harness/setup_wifi');++ final Dio _dio;++ /// Whether this phone joins the hotspot by itself, or the person does in Settings.+ static bool get joinsByItself => Platform.isAndroid;++ /// `joined`, `unavailable` (the person cancelled, or no device was found), or `unsupported`.+ /// Android's list shows only the `Harness-…` Wi-Fi nearby.+ Future<String> join() async {+ if (!joinsByItself) return 'unsupported';+ try {+ return await _channel.invokeMethod<String>('join', {'prefix': prefix}) ??+ 'unavailable';+ } on PlatformException {+ return 'unavailable';+ } on MissingPluginException {+ return 'unsupported';+ }+ }++ /// Back to the phone's own Wi-Fi and the Internet.+ Future<void> leave() async {+ if (!joinsByItself) return;+ try {+ await _channel.invokeMethod<bool>('leave');+ } on PlatformException {+ // Nothing joined.+ } on MissingPluginException {+ // Not on this platform.+ }+ }++ /// The device: `{protocol, name, hotspot, run, computerId, signedIn, result}`, or null while the+ /// phone is not on its hotspot.+ Future<Map<String, dynamic>?> info() async {+ try {+ final res = await _dio.get('/setup');+ if (res.statusCode != 200 || res.data is! Map) return null;+ return Map<String, dynamic>.from(res.data as Map);+ } on DioException {+ return null;+ }+ }++ /// The Wi-Fi the DEVICE sees: `[{ssid, signal, security}]`, strongest first.+ Future<List<SetupNetwork>> networks() async {+ final res = await _dio.get('/setup/networks');+ 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.');+ }+ return [+ for (final row in list)+ if (row is Map && row['ssid'] is String)+ SetupNetwork(+ ssid: row['ssid'] as String,+ signal: (row['signal'] as num?)?.toInt() ?? 0,+ secure: (row['security'] as String? ?? '').isNotEmpty,+ ),+ ];+ }++ /// Hands the device the Wi-Fi and the ticket. Answers the run to look for in a later result.+ Future<int> connect({+ required String ssid,+ required String password,+ required String ticket,+ }) async {+ final Response<dynamic> res;+ try {+ res = await _dio.post(+ '/setup/connect',+ data: {'ssid': ssid, 'password': password, 'ticket': ticket},+ );+ } on DioException {+ throw const SetupException(+ 'Lost the device\'s Wi-Fi. Stay close to it and try again.',+ );+ }+ final body = res.data is Map ? res.data as Map : const {};+ if (res.statusCode != 202) {+ throw SetupException(+ body['message'] as String? ?? 'The device said no (${res.statusCode}).',+ );+ }+ return (body['run'] as num?)?.toInt() ?? 0;+ }+}++class SetupNetwork {+ const SetupNetwork({+ required this.ssid,+ required this.signal,+ required this.secure,+ });++ final String ssid;+ final int signal;+ final bool secure;+}++class SetupException implements Exception {+ const SetupException(this.message);++ final String message;++ @override+ String toString() => message;+}diff --git a/mobile/lib/phone/change_wifi_page.dart b/mobile/lib/phone/change_wifi_page.dartnew file mode 100644index 000000000..aa54d80fe--- /dev/null+++ b/mobile/lib/phone/change_wifi_page.dart@@ -0,0 +1,395 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'settings_row.dart';+import 'tty.dart';+import 'tty_controls.dart';++/// Computers ▸ a Harness OS computer ▸ Change Wi-Fi: the Wi-Fi the COMPUTER sees, picked from here+/// wherever this phone is (CLI services/osDevice.ts through the relay, os/setup.py `join` on it).+///+/// its list → password → it leaves its Wi-Fi for that one → back online there, or, when that one+/// fails (wrong password, out of reach, no Internet), back on the one it was on, with the reason.+///+/// It is unreachable while it moves; the result waits on it (`wifi_result`) for when it is back.+class ChangeWifiPage extends StatefulWidget {+ const ChangeWifiPage({+ super.key,+ required this.notifier,+ required this.machineId,+ });++ final AppNotifier notifier;+ final String machineId;++ @override+ State<ChangeWifiPage> createState() => _ChangeWifiPageState();+}++enum _Step { list, password, moving, done }++class _Network {+ const _Network(this.ssid, this.signal, this.secure, this.active);++ final String ssid;+ final int signal;+ final bool secure;+ final bool active;+}++class _ChangeWifiPageState extends State<ChangeWifiPage> {+ final _ssid = TextEditingController();+ final _password = TextEditingController();++ _Step _step = _Step.list;+ bool _busy = true;+ bool _reveal = false;+ String _error = '';+ List<_Network> _networks = const [];+ _Network? _chosen;+ Timer? _poll;++ /// How long the computer gets to try the Wi-Fi and be back, on it or on its old one.+ static const _moveFor = Duration(minutes: 2);++ AppNotifier get _app => widget.notifier;+ String get _name =>+ _app.stateOf(widget.machineId)?.machine.displayName ?? 'The computer';++ @override+ void initState() {+ super.initState();+ unawaited(_scan());+ }++ @override+ void dispose() {+ _poll?.cancel();+ _ssid.dispose();+ _password.dispose();+ super.dispose();+ }++ void _show(_Step step, {String error = ''}) {+ if (!mounted) return;+ setState(() {+ _step = step;+ _error = error;+ _busy = false;+ });+ }++ Future<void> _scan({String error = ''}) async {+ setState(() {+ _step = _Step.list;+ _busy = true;+ _error = error;+ });+ final reply = await _app.osDevice(widget.machineId, {+ 'action': 'wifi_scan',+ }, timeout: const Duration(seconds: 35));+ if (!mounted) return;+ final list = reply['networks'];+ if (list is! List) {+ _show(+ _Step.list,+ error: error.isNotEmpty+ ? error+ : 'Could not read the Wi-Fi $_name sees. Pull down to try again.',+ );+ return;+ }+ setState(() {+ _networks = [+ for (final row in list)+ if (row is Map && row['ssid'] is String)+ _Network(+ row['ssid'] as String,+ (row['signal'] as num?)?.toInt() ?? 0,+ (row['security'] as String? ?? '').isNotEmpty,+ row['active'] == true,+ ),+ ];+ _busy = false;+ });+ }++ void _choose(_Network? network) {+ _chosen = network;+ _ssid.text = network?.ssid ?? '';+ _password.clear();+ _show(_Step.password);+ }++ Future<void> _send() async {+ final ssid = _ssid.text.trim();+ final secure = _chosen?.secure ?? _password.text.isNotEmpty;+ final password = secure ? _password.text : '';+ if (ssid.isEmpty) {+ _show(_Step.password, error: 'Enter the Wi-Fi name.');+ return;+ }+ if (secure && (password.length < 8 || password.length > 63)) {+ _show(_Step.password, error: 'A Wi-Fi password has 8 to 63 characters.');+ return;+ }+ setState(() => _busy = true);+ // The run before this one: a result from an earlier change is not this one's.+ final before = await _app.osDevice(widget.machineId, {+ 'action': 'wifi_result',+ });+ final last = before['result'];+ final run = last is Map ? (last['run'] as num?)?.toInt() ?? 0 : 0;+ final reply = await _app.osDevice(widget.machineId, {+ 'action': 'wifi_join',+ 'ssid': ssid,+ 'password': password,+ });+ if (!mounted) return;+ if (reply['started'] != true) {+ _show(+ _Step.password,+ error:+ reply['message'] as String? ?? 'Could not reach $_name. Try again.',+ );+ return;+ }+ _wait(ssid, run);+ }++ /// Unreachable while it moves; asked again every few seconds until its result is in.+ void _wait(String ssid, int run) {+ _show(_Step.moving);+ final deadline = DateTime.now().add(_moveFor);+ var asking = false;+ _poll?.cancel();+ _poll = Timer.periodic(const Duration(seconds: 3), (_) async {+ if (asking || !mounted || _step != _Step.moving) return;+ asking = true;+ try {+ final reply = await _app.osDevice(widget.machineId, {+ 'action': 'wifi_result',+ }, timeout: const Duration(seconds: 6));+ if (!mounted || _step != _Step.moving) return;+ final result = reply['result'];+ final settled =+ result is Map &&+ ((result['run'] as num?)?.toInt() ?? 0) > run &&+ result['state'] != 'connecting';+ if (settled) {+ _poll?.cancel();+ if (result['state'] == 'done') {+ unawaited(_app.refreshOsStatus(widget.machineId, force: true));+ _show(_Step.done);+ } else {+ final why =+ result['message'] as String? ?? 'Could not join "$ssid".';+ final back = result['restored'] == true+ ? ' $_name is back on its Wi-Fi.'+ : '';+ unawaited(_scan(error: '$why$back'));+ }+ return;+ }+ if (DateTime.now().isAfter(deadline)) {+ _poll?.cancel();+ _show(+ _Step.moving,+ error:+ '$_name has not come back. If it lost its Wi-Fi, it opens its own "Harness-…" '+ 'Wi-Fi in a few minutes: then use Settings ▸ Set up a device near it.',+ );+ }+ } finally {+ asking = false;+ }+ });+ }++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ return Scaffold(+ backgroundColor: tty.ground,+ resizeToAvoidBottomInset: false,+ body: SafeArea(+ bottom: false,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Align(+ alignment: Alignment.centerLeft,+ child: TtyBackButton(+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ),+ Expanded(+ child: RefreshIndicator(+ onRefresh: () =>+ _step == _Step.list ? _scan() : Future<void>.value(),+ child: ListView(+ padding: EdgeInsets.fromLTRB(+ Tty.origin,+ 8,+ Tty.origin,+ MediaQuery.paddingOf(context).bottom ++ MediaQuery.viewInsetsOf(context).bottom ++ 24,+ ),+ children: [+ const TtyText(+ 'Change Wi-Fi',+ size: TtySize.display,+ weight: FontWeight.w600,+ ),+ const SizedBox(height: 8),+ if (_error.isNotEmpty) ...[+ Text(+ _error,+ key: const Key('change-wifi-error'),+ style: tty.style(color: tty.red),+ ),+ const SizedBox(height: 12),+ ],+ ..._body(tty),+ const SizedBox(height: 20),+ ..._actions(),+ ],+ ),+ ),+ ),+ ],+ ),+ ),+ );+ }++ List<Widget> _body(Tty tty) {+ Text say(String text) => Text(text, style: tty.style(color: tty.dim));+ switch (_step) {+ case _Step.list:+ return [+ say(+ 'The Wi-Fi $_name sees. If the new one fails, it goes back to the one it is on.',+ ),+ const SizedBox(height: 12),+ if (_busy)+ const Center(child: CircularProgressIndicator(strokeWidth: 2))+ else+ SettingsGroup(+ children: [+ for (final network in _networks)+ SettingsRow(+ key: ValueKey('change-wifi-${network.ssid}'),+ title: network.ssid,+ value: network.active+ ? 'Connected'+ : network.secure+ ? 'Locked'+ : 'Open',+ detail: network.signal >= 70+ ? 'Strong signal'+ : network.signal >= 40+ ? 'Good signal'+ : 'Weak signal',+ onTap: () => _choose(network),+ ),+ SettingsRow(+ key: const Key('change-wifi-other'),+ title: 'Other network…',+ onTap: () => _choose(null),+ ),+ ],+ ),+ ];+ case _Step.password:+ return [+ if (_chosen == null) ...[+ say('The Wi-Fi name, as it is written.'),+ const SizedBox(height: 8),+ TtyField(+ key: const Key('change-wifi-ssid'),+ controller: _ssid,+ hint: 'Wi-Fi name',+ action: TextInputAction.next,+ maxLength: 32,+ ),+ const SizedBox(height: 12),+ ] else+ say('The password for "${_chosen!.ssid}". It is case-sensitive.'),+ if (_chosen?.secure ?? true) ...[+ const SizedBox(height: 8),+ TtyField(+ key: const Key('change-wifi-password'),+ controller: _password,+ hint: _chosen == null+ ? 'Password (empty for an open Wi-Fi)'+ : 'Wi-Fi password',+ autofocus: _chosen != null,+ keyboardType: TextInputType.visiblePassword,+ obscure: !_reveal,+ maxLength: 63,+ onSubmitted: _busy ? null : () => unawaited(_send()),+ trailing: [+ AppIconButton(+ icon: _reveal ? LucideIcons.eyeOff300 : LucideIcons.eye300,+ size: 20,+ tooltip: _reveal ? 'Hide password' : 'Show password',+ color: tty.dim,+ onPressed: () => setState(() => _reveal = !_reveal),+ ),+ ],+ ),+ ],+ ];+ case _Step.moving:+ return [+ if (_error.isEmpty)+ say(+ '$_name is moving to "${_ssid.text.trim()}". It is out of reach for a moment.',+ ),+ ];+ case _Step.done:+ return [say('$_name is on "${_ssid.text.trim()}" now.')];+ }+ }++ List<Widget> _actions() {+ switch (_step) {+ case _Step.list:+ return const [];+ case _Step.password:+ return [+ TtyPrimaryButton(+ key: const Key('change-wifi-connect'),+ label: 'Connect',+ busy: _busy,+ busyLabel: 'Sending…',+ onPressed: () => unawaited(_send()),+ ),+ TtyTextButton(+ label: 'Choose another Wi-Fi',+ onPressed: () => _show(_Step.list),+ ),+ ];+ case _Step.moving:+ return [+ if (_error.isEmpty)+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),+ ];+ case _Step.done:+ return [+ TtyPrimaryButton(+ key: const Key('change-wifi-done'),+ label: 'Done',+ onPressed: () => Navigator.of(context).maybePop(),+ ),+ ];+ }+ }+}diff --git a/mobile/lib/phone/machine_actions.dart b/mobile/lib/phone/machine_actions.dartindex 7f6275ee8..286694763 100644--- a/mobile/lib/phone/machine_actions.dart+++ b/mobile/lib/phone/machine_actions.dart@@ -7,13 +7,50 @@ import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/widgets/rename_agent_dialog.dart'show showMachineRenameDialog;+import 'change_wifi_page.dart';import 'link_page.dart';import 'phone_navigation.dart';import 'phone_sheet.dart';import 'phone_status.dart';import 'remove_machine.dart';+import 'tty.dart';import 'unlink_machine.dart';+/// The Wi-Fi a Harness OS computer is on, as it last said.+String? _ssidOf(AppNotifier notifier, String machineId) {+ final wifi = notifier.osStatus[machineId]?['wifi'];+ return wifi is Map ? wifi['ssid'] as String? : null;+}++/// Update ▸ a Harness OS computer updates itself (`harness update`, the same as Super+u there). It+/// restarts its daemon on the way, so it reads offline for a moment and comes back on the new version.+Future<void> updateComputer(+ BuildContext context,+ AppNotifier notifier,+ String machineId,+) async {+ final messenger = ScaffoldMessenger.maybeOf(context);+ final name =+ notifier.stateOf(machineId)?.machine.displayName ?? 'The computer';+ final reply = await notifier.osDevice(machineId, {'action': 'update'});+ final String said;+ if (reply['started'] == true) {+ said =+ '$name is updating. It restarts by itself and comes back in a minute or two.';+ notifier.osStatus.remove(machineId);+ // Asked again once it is back on the new version.+ Timer(+ const Duration(minutes: 2),+ () => unawaited(notifier.refreshOsStatus(machineId, force: true)),+ );+ } else if (reply['error'] == 'BUSY') {+ said = '$name is already updating.';+ } else {+ said = 'Could not start the update. Try again.';+ }+ messenger?.showSnackBar(SnackBar(content: Text(said)));+}+/// The sheet of what can be done TO a computer — Settings ▸ Computers.////// Every computer opens it, whatever it reads, because what the account can do to a computer does@@ -93,15 +130,34 @@ void openMachineActions(onTap: () => unawaited(notifier.reloadMachineData(machineId)),),rename,- PhoneSheetAction(- icon: LucideIcons.keyRound300,- label: 'Re-enter password…',- onTap: () => Navigator.of(context).push(- phoneRoute(- (_) => LinkPage(notifier: notifier, machineId: machineId),+ // A Harness OS computer, often one with no screen: its update and its Wi-Fi, from here.+ if (notifier.runsHarnessOs(machineId)) ...[+ PhoneSheetAction(+ icon: LucideIcons.download300,+ label: 'Update',+ // The dot: a new version is waiting.+ value: notifier.updateAvailable(machineId)+ ? '● new version'+ : 'up to date',+ valueColor: notifier.updateAvailable(machineId)+ ? Tty.of(context).green+ : null,+ enabled: notifier.updateAvailable(machineId),+ onTap: () =>+ unawaited(updateComputer(context, notifier, machineId)),+ ),+ PhoneSheetAction(+ icon: LucideIcons.wifi300,+ label: 'Change Wi-Fi…',+ value: _ssidOf(notifier, machineId),+ chevron: true,+ onTap: () => Navigator.of(context).push(+ phoneRoute(+ (_) => ChangeWifiPage(notifier: notifier, machineId: machineId),+ ),),),- ),+ ],];destructive = [// No confirmation, the same as before: this sheet is the step between the tap and the@@ -116,6 +172,11 @@ void openMachineActions(remove,];}+ // Asked as the sheet opens; the rows above come from the last answer, and a new one rebuilds them+ // the next time.+ if (status == PhoneMachineStatus.ready) {+ unawaited(notifier.refreshOsStatus(machineId));+ }showPhoneSheet(context,title: machine.machine.displayName,diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex acc5e1162..5b4e542d9 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -331,6 +331,15 @@ class _Body extends StatelessWidget {(word, color) = ('removing…', tty.faint);} else if (notifier.machineRetrying(machineId)) {(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';+ }+ // 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.+ if (status == PhoneMachineStatus.ready) {+ unawaited(notifier.refreshOsStatus(machineId));}return FindRow(title: state.machine.displayName,@@ -348,8 +357,10 @@ class _Body extends StatelessWidget {/// One sheet for every computer, whatever it reads — see [openMachineActions]. A locked one has/// "Unlock…" at its head, the act its row offers; one place decides what a computer offers, so no/// state can lose the rename or the removal.- void _open(BuildContext context, MachineState state) =>- openMachineActions(context, notifier, state.machine.machineId);+ void _open(BuildContext context, MachineState state) {+ notifier.sawMachine(state.machine.machineId);+ openMachineActions(context, notifier, state.machine.machineId);+ }}/// Over a run of computers that want the same thing: what they are, then what to do about them —diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex 3a96d33f1..b41ef20b6 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -19,6 +19,7 @@ import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/terminal/terminal_font_store.dart';import 'package:harness_mobile/terminal/terminal_theme_store.dart';+import 'add_device/add_device_page.dart';import 'approve_sign_in.dart';import 'connectors_page.dart';import 'devices_page.dart';@@ -220,6 +221,15 @@ class _Body extends StatelessWidget {title: 'Sign in a computer',onTap: () => unawaited(signInAComputer(context, notifier)),),+ // A Harness with no screen (a box, a mini PC): onto the person's Wi-Fi and signed in to+ // this account through its setup hotspot.+ SettingsRow(+ key: const Key('settings-add-device'),+ title: 'Set up a device',+ onTap: () => Navigator.of(context).push(+ phoneRoute((_) => AddDevicePage(notifier: notifier)),+ ),+ ),SettingsRow(title: 'Your devices',value: notifier.newDevices.isEmpty ? null : '${notifier.newDevices.length} new',diff --git a/mobile/lib/phone/tty_controls.dart b/mobile/lib/phone/tty_controls.dartindex 85abbd8bf..f33db6886 100644--- a/mobile/lib/phone/tty_controls.dart+++ b/mobile/lib/phone/tty_controls.dart@@ -368,9 +368,13 @@ class TtyField extends StatefulWidget {this.autofocus = false,this.keyboardType,this.autofillHints,+ this.obscure = false,});final TextInputType? keyboardType;++ /// A password: one line, its characters hidden.+ final bool obscure;final Iterable<String>? autofillHints;final TextEditingController controller;@@ -440,8 +444,11 @@ class _TtyFieldState extends State<TtyField> {textInputAction: widget.action,// The keyboard's own composing, left on: Vietnamese Telex on iOS rides on// autocorrection. See `ComposingKeyboard`.- autocorrect: ComposingKeyboard.autocorrect,- enableSuggestions: ComposingKeyboard.enableSuggestions,+ autocorrect: !widget.obscure && ComposingKeyboard.autocorrect,+ enableSuggestions:+ !widget.obscure && ComposingKeyboard.enableSuggestions,+ // A password: dots, the platform showing the character just typed for a moment.+ obscureText: widget.obscure,smartDashesType: SmartDashesType.disabled,smartQuotesType: SmartQuotesType.disabled,textCapitalization: multidiff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex f88ddeab2..5023fc27b 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -5730,6 +5730,56 @@ class AppNotifier extends ChangeNotifier {}}+ /// A Harness OS computer, managed from here (CLI services/osDevice.ts): `status`, `update`,+ /// `wifi_scan`, `wifi_join` {ssid, password}, `wifi_result`. `{error: 'UNAVAILABLE'}` while it+ /// cannot be reached — as it is for a while after `update` and `wifi_join`.+ Future<Map<String, dynamic>> osDevice(+ String machineId,+ Map<String, dynamic> payload, {+ Duration timeout = const Duration(seconds: 25),+ }) async {+ final machine = machineStates[machineId];+ if (machine == null || machine.needsLink) return {'error': 'UNAVAILABLE'};+ try {+ return await _conn(+ machineId,+ ).request('os_device', payload: payload, timeout: timeout);+ } catch (_) {+ return {'error': 'UNAVAILABLE'};+ }+ }++ /// What each computer's `os_device` `status` said: whether it runs Harness OS, its update and its+ /// Wi-Fi. Asked again at most every few minutes ([refreshOsStatus]).+ final Map<String, Map<String, dynamic>> osStatus = {};+ final Map<String, DateTime> _osAsked = {};++ bool runsHarnessOs(String machineId) => osStatus[machineId]?['harnessOs'] == true;++ bool updateAvailable(String machineId) {+ final update = osStatus[machineId]?['update'];+ return update is Map && update['available'] == true;+ }++ /// Asks [machineId] what it is and whether it has an update, unless asked lately ([force] asks now).+ Future<void> refreshOsStatus(String machineId, {bool force = false}) async {+ final asked = _osAsked[machineId];+ if (!force &&+ asked != null &&+ DateTime.now().difference(asked) < const Duration(minutes: 5)) {+ return;+ }+ _osAsked[machineId] = DateTime.now();+ final status = await osDevice(machineId, {'action': 'status'});+ // An older CLI answers it UNSUPPORTED/SERVICE_UNAVAILABLE: not Harness OS as far as the phone knows.+ if (status['error'] == 'UNAVAILABLE') {+ _osAsked.remove(machineId);+ return;+ }+ osStatus[machineId] = status;+ notifyListeners();+ }+Future<Map<String, dynamic>> connectors(String machineId,Map<String, dynamic> payload, {@@ -6313,6 +6363,20 @@ class AppNotifier extends ChangeNotifier {/// `backend/src/routes/machines.ts` refuses anything longer.static const machineNameMaxLength = 40;+ /// Computers this phone just set up (Settings ▸ Set up a device): Computers marks them "new" until+ /// one is opened. This run only.+ final Set<String> _newMachines = {};++ bool isNewMachine(String machineId) => _newMachines.contains(machineId);++ void markMachineNew(String machineId) {+ if (_newMachines.add(machineId)) notifyListeners();+ }++ void sawMachine(String machineId) {+ if (_newMachines.remove(machineId)) 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.