Skip to content

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.

Settings: only settings; robots in Devices, your devices in Machines, and Agents (#1197)

Dee4f92ee5e9847
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index f1685b4ba..faaaf7b8c 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -664,6 +664,18 @@ add a kind there, not at the call site.
right. Appearance and Terminal both use it; a pane that invents its own row shape is the bug.
Controls come from `shared/widgets/` too (`AppSelectField`, `AppIconButton`) — raw Material
`DropdownButton`/`IconButton` do not match anything else in the app.
+ **Settings holds settings only** (owner, 2026-10-11): Account alone at the top, then General
+ (Appearance — the `customize` row, which opens Customize Harness over the workspace —
+ Notifications, Keyboard shortcuts), Agents (Agents, Connectors, Usage), Labs (Experimental) and
+ Help (About, Debug in dev builds). A thing is managed where it lives: the Autonomous robots —
+ Wi-Fi code pairing, Revoke, Still companion — in the Devices tab (`devices/wifi_robots.dart`);
+ the account's computers, phones and apps, each device's code, Remove (a computer: sign out AND
+ delete its machine record), History… and Show in this window in the Machines picker
+ (`state/machine_devices.dart`, `widgets/machine_picker_extras.dart`). A way in from outside the
+ workspace asks for Machines with `AppNotifier.requestMachines` (`openMachines` in
+ `widgets/new_device_notice.dart`). Settings ▸ Agents reads and writes this computer's daemon
+ (`/api/agent-settings`, bare JSON, not `{success, data}`); a setting the daemon's answer does
+ not name is not shown.
- **The log is written to files, and Settings ▸ Debug reads them back** (`lib/logging/`,
`settings/sections/debug_*.dart`). `appLog` (`app-YYYYMMDD.log`) is the narrative — `app`, `ws`,
`api`, `flutter` — and `cliLog` (`cli-YYYYMMDD.log`) is a transcript of every child process, both
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 89f391489..592ac11d8 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -159,6 +159,47 @@ class ApiClient {
return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);
}
+ // -- what agents may do on this computer (Settings ▸ Agents), kept by this computer's daemon --
+
+ /// `{agentsStartAgents, pullRequestLine?}` as this computer's daemon keeps them
+ /// (cli/src/lib/agentSettings.ts). A key a daemon predates is absent. Null when the daemon predates
+ /// the route altogether (404). The daemon answers the settings bare, not in `{success, data}`.
+ Future<Map<String, dynamic>?> agentSettings() async {
+ final res = await _dio.get('/api/agent-settings');
+ if (res.statusCode == 404) return null;
+ return _agentSettingsAnswer(res);
+ }
+
+ /// Changes one setting ([key] to [value]) and answers the settings as they are afterwards. A local
+ /// write to the daemon, like [deskOps].
+ Future<Map<String, dynamic>> setAgentSetting(String key, bool value) async {
+ final res = await _dio.patch(
+ '/api/agent-settings',
+ data: {key: value},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ return _agentSettingsAnswer(res);
+ }
+
+ Map<String, dynamic> _agentSettingsAnswer(Response res) {
+ final body = res.data;
+ if (body is Map && body.containsKey('success')) {
+ return Map<String, dynamic>.from(unwrapApiResponse(res) as Map);
+ }
+ final status = res.statusCode ?? 0;
+ if (status >= 200 && status < 300 && body is Map) {
+ return Map<String, dynamic>.from(body);
+ }
+ final error = body is Map ? body['error'] : null;
+ final message = error is Map ? error['message'] : null;
+ throw ApiException(
+ message is String && message.isNotEmpty
+ ? message
+ : 'Request failed ($status)',
+ status: res.statusCode,
+ );
+ }
+
// -- account-wide Experimental preferences --
Future<Map<String, dynamic>> experimentalSettings() async {
final res = await _dio.get('/api/experimental-settings');
diff --git a/desktop/lib/devices/device_settings.dart b/desktop/lib/devices/device_settings.dart
index b183d0c94..69b3855dc 100644
--- a/desktop/lib/devices/device_settings.dart
+++ b/desktop/lib/devices/device_settings.dart
@@ -8,6 +8,11 @@ import '../widgets/desktop_chrome.dart';
import 'devices_controller.dart';
import 'pet_settings.dart';
+/// Whether the robot offers to follow the desktop companion. Off while the companion skins are
+/// unfinished (owner, 2026-09-30): the firmware wears Focus whatever it is asked, so the switch would
+/// be a control that does nothing. Flip it with HABITAT_FOCUS_ONLY.
+const kDeviceCompanionSkins = false;
+
/// Face ids belong to the firmware (character.h), not screen dimensions.
/// Add future faces here only when production firmware can actually select them.
const deviceFaces = [
@@ -24,10 +29,14 @@ class DeviceSettingsPanel extends StatefulWidget {
this.petKey,
this.petGap = 0,
this.pickPetFile,
+ this.showCompanion = false,
});
final HarnessDevice device;
final DevicesController controller;
+ /// Whether the desktop companion is on (Experimental): only then can a robot follow it.
+ final bool showCompanion;
+
/// The dial's pet edit, when the screen shares it with a viewer of its own.
final PetEditor? petEditor;
@@ -128,6 +137,40 @@ class _DeviceSettingsPanelState extends State<DeviceSettingsPanel> {
),
),
const SizedBox(height: 10),
+ // A Pro has no companion artwork, so nothing here for it to still or follow.
+ if (!device.status.isPro &&
+ kDeviceCompanionSkins &&
+ widget.showCompanion &&
+ settings.followCompanion != null) ...[
+ SettingRow(
+ title: 'Follow desktop companion',
+ detail: settings.companion == null
+ ? 'Show the companion paired in your Zoo.'
+ : 'Showing ${settings.companion == 'gnu' ? 'GNU' : settings.companion!} from your Zoo.',
+ controlSemanticLabel: 'Follow desktop companion',
+ control: Switch(
+ key: ValueKey('devices-follow-companion-${device.key}'),
+ value: settings.followCompanion!,
+ onChanged: enabled
+ ? (value) => change({'followCompanion': value})
+ : null,
+ ),
+ ),
+ const SizedBox(height: 10),
+ ],
+ if (!device.status.isPro) ...[
+ SettingRow(
+ title: 'Still companion',
+ detail: 'Stops the artwork animating. Nothing else changes.',
+ controlSemanticLabel: 'Still companion',
+ control: Switch(
+ key: ValueKey('devices-quiet-${device.key}'),
+ value: settings.quiet,
+ onChanged: enabled ? (value) => change({'quiet': value}) : null,
+ ),
+ ),
+ const SizedBox(height: 10),
+ ],
SettingRow(
title: 'Sound',
detail: 'A quiet chime when your attention is needed.',
diff --git a/desktop/lib/devices/devices_screen.dart b/desktop/lib/devices/devices_screen.dart
index 3de791394..72b539c96 100644
--- a/desktop/lib/devices/devices_screen.dart
+++ b/desktop/lib/devices/devices_screen.dart
@@ -4,8 +4,10 @@ import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
+import '../settings/experimental_features.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_menu.dart';
import '../shared/widgets/skeleton.dart';
import '../shared/widgets/app_icon_button.dart';
import '../core/test_run.dart';
@@ -17,6 +19,7 @@ import 'device_setup_dialog.dart';
import 'devices_controller.dart';
import 'pet_settings.dart';
import 'pet_source.dart';
+import 'wifi_robots.dart';
final harnessDeviceShopUrl = Uri.parse(
'https://www.autonomous.ai/harness-device',
@@ -37,6 +40,11 @@ class _DevicesTabState extends State<DevicesTab> {
sendHostSettings: widget.notifier.setHostDeviceSettings,
petRequest: widget.notifier.petRequest,
);
+
+ /// The robots paired over the network, through this computer's CLI.
+ late final wifi = WifiRobotsController(
+ onLocalNetworkBlocked: widget.notifier.localNetworkBlocked,
+ );
Timer? _refresh;
@override
void initState() {
@@ -54,13 +62,23 @@ class _DevicesTabState extends State<DevicesTab> {
void dispose() {
_refresh?.cancel();
controller.dispose();
+ wifi.dispose();
super.dispose();
}
@override
- Widget build(BuildContext context) => DevicesScreen(
- controller: controller,
- onRefresh: widget.notifier.refreshDevices,
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: widget.notifier.experimentalFeatures,
+ builder: (context, _) => DevicesScreen(
+ controller: controller,
+ wifi: wifi,
+ showCompanion: widget.notifier.experimentalFeatures.enabled(
+ ExperimentalFeature.focusBarCreature,
+ ),
+ onRefresh: () async {
+ await Future.wait([widget.notifier.refreshDevices(), wifi.refresh()]);
+ },
+ ),
);
}
@@ -68,6 +86,8 @@ class DevicesScreen extends StatefulWidget {
const DevicesScreen({
super.key,
required this.controller,
+ this.wifi,
+ this.showCompanion = false,
this.openShop,
this.onRefresh,
this.pickPetFile,
@@ -75,6 +95,12 @@ class DevicesScreen extends StatefulWidget {
this.loadPetSheet,
});
final DevicesController controller;
+
+ /// The robots paired over the network. Null leaves Add device to the USB cable alone.
+ final WifiRobotsController? wifi;
+
+ /// Whether the desktop companion is on (Experimental), for the rows that follow it.
+ final bool showCompanion;
final Future<bool> Function(Uri)? openShop;
final Future<void> Function()? onRefresh;
@@ -126,6 +152,7 @@ class _DevicesScreenState extends State<DevicesScreen> {
super.initState();
_page.addListener(_place);
unawaited(widget.controller.load());
+ widget.wifi?.start();
}
@override
@@ -294,6 +321,62 @@ class _DevicesScreenState extends State<DevicesScreen> {
});
}
+ final _addMenu = MenuController();
+
+ Future<void> _pairWifi() async {
+ final wifi = widget.wifi;
+ if (wifi == null) return;
+ await showWifiPairDialog(context, wifi);
+ }
+
+ /// Add device: on a cable, or — with the network's robots on offer — by the code a robot shows.
+ Widget _addButton() {
+ final button = FilledButton(
+ key: const Key('devices-add'),
+ onPressed: widget.wifi == null
+ ? () => _setup()
+ : () => _addMenu.isOpen ? _addMenu.close() : _addMenu.open(),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(AppIcons.plus, size: 16),
+ const SizedBox(width: 7),
+ const Text('Add device'),
+ if (widget.wifi != null) ...[
+ const SizedBox(width: 5),
+ const Icon(AppIcons.chevronDown, size: 14),
+ ],
+ ],
+ ),
+ );
+ if (widget.wifi == null) return button;
+ return MenuAnchor(
+ controller: _addMenu,
+ consumeOutsideTap: true,
+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),
+ style: grid.AppMenu.style(),
+ menuChildren: [
+ AppMenuItem(
+ key: const Key('devices-add-usb'),
+ label: 'USB cable',
+ onPressed: () {
+ _addMenu.close();
+ unawaited(_setup());
+ },
+ ),
+ AppMenuItem(
+ key: const Key('devices-add-wifi'),
+ label: 'Wi-Fi code',
+ onPressed: () {
+ _addMenu.close();
+ unawaited(_pairWifi());
+ },
+ ),
+ ],
+ child: button,
+ );
+ }
+
Future<void> _setup({HarnessDevice? editing}) async {
final key = await showDeviceSetup(
context,
@@ -375,12 +458,7 @@ class _DevicesScreenState extends State<DevicesScreen> {
],
),
),
- FilledButton.icon(
- key: const Key('devices-add'),
- onPressed: () => _setup(),
- icon: const Icon(AppIcons.plus, size: 16),
- label: const Text('Add device'),
- ),
+ _addButton(),
],
),
],
@@ -411,6 +489,8 @@ class _DevicesScreenState extends State<DevicesScreen> {
],
),
],
+ if (widget.wifi case final wifi?)
+ WifiRobotsList(controller: wifi, topGap: 32),
const SizedBox(height: 32),
if (!widget.controller.loaded)
const SkeletonBlock(
@@ -520,6 +600,7 @@ class _DevicesScreenState extends State<DevicesScreen> {
petKey: _petKey,
petGap: beside ? _petGap : 0,
pickPetFile: widget.pickPetFile,
+ showCompanion: widget.showCompanion,
);
if (!wide) {
_settle(false);
diff --git a/desktop/lib/devices/wifi_robots.dart b/desktop/lib/devices/wifi_robots.dart
new file mode 100644
index 000000000..447e8e93c
--- /dev/null
+++ b/desktop/lib/devices/wifi_robots.dart
@@ -0,0 +1,660 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../autonomous_device/autonomous_device_cli.dart';
+import '../core/test_run.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../shared/widgets/app_select_field.dart';
+import '../shared/widgets/labeled_field.dart';
+import '../shared/widgets/setting_row.dart';
+import '../shared/widgets/skeleton.dart';
+import '../widgets/desktop_chrome.dart';
+
+/// The Autonomous robots paired with this computer over the network, through the CLI
+/// (`harness autonomous-device`): what is paired, what the network shows, and the two acts on them —
+/// pair with the six-character code a robot shows, and revoke.
+///
+/// The Devices tab owns one while it is open: its list of paired robots and the Wi-Fi code
+/// dialog read the same state, so a pairing shows up in the list the moment the CLI confirms it.
+/// The CLI keeps the trust and the connection; nothing here holds a code longer than one request.
+class WifiRobotsController extends ChangeNotifier {
+ WifiRobotsController({AutonomousDeviceCli? cli, this.onLocalNetworkBlocked})
+ : _injected = cli,
+ // Tests may inject a fake; without one under test nothing may reach a real CLI.
+ _inert = kUnderTest && cli == null;
+
+ final AutonomousDeviceCli? _injected;
+ late final AutonomousDeviceCli _cli = _injected ?? AutonomousDeviceCli();
+ final bool _inert;
+
+ /// Discovery found the local network refused: the app restarts a daemon it did not launch so it
+ /// gets the app's permission (AppNotifier.localNetworkBlocked).
+ final Future<void> Function()? onLocalNetworkBlocked;
+
+ Timer? _timer;
+ bool _started = false, _refreshing = false, _disposed = false;
+ int _generation = 0;
+
+ bool loading = true;
+ bool busy = false;
+ bool unsupported = false;
+ bool networkBlocked = false;
+
+ /// The last status read failed: why.
+ String? error;
+
+ /// The last pairing failed: why. Shown in the Wi-Fi code dialog.
+ String? pairError;
+
+ /// The last revoke failed: why. Shown beside the paired list.
+ String? revokeError;
+
+ Map<String, dynamic> status = const {};
+ List<Map<String, dynamic>> paired = const [];
+ List<Map<String, dynamic>> discovered = const [];
+
+ /// Nothing to press while a request is out, before the first answer, or with no CLI behind it.
+ bool get controlsDisabled => busy || loading || _inert;
+
+ /// Reads the CLI once and then every minute while somebody looks.
+ void start() {
+ if (_started) return;
+ _started = true;
+ if (_inert) {
+ loading = false;
+ notifyListeners();
+ return;
+ }
+ unawaited(refresh());
+ }
+
+ void _changed() {
+ if (!_disposed) notifyListeners();
+ }
+
+ void _scheduleRefresh() {
+ _timer?.cancel();
+ // Tests may inject a fake for the initial fetch and user actions, but must
+ // never start a background clock or invoke a real CLI.
+ if (_disposed || kUnderTest || unsupported || busy) return;
+ _timer = Timer(const Duration(seconds: 60), () => unawaited(refresh()));
+ }
+
+ String _message(Object error) => error is AutonomousDeviceCliException
+ ? error.userMessage
+ : 'Could not reach the Harness CLI.';
+
+ /// A refused local network loses discovery only: paired robots still list, and the dialog says
+ /// where to allow it instead of "no robots found".
+ Future<Map<String, dynamic>> _discoverOrBlocked() async {
+ try {
+ return await _cli.discover();
+ } on AutonomousDeviceCliException catch (error) {
+ if (!error.localNetworkBlocked) rethrow;
+ if (onLocalNetworkBlocked case final restart?) {
+ await restart();
+ try {
+ return await _cli.discover();
+ } on AutonomousDeviceCliException catch (again) {
+ if (!again.localNetworkBlocked) rethrow;
+ }
+ }
+ return {'devices': const [], 'localNetworkBlocked': true};
+ }
+ }
+
+ static List<Map<String, dynamic>> _rows(Object? raw) => [
+ for (final row in raw is List ? raw : const [])
+ if (row is Map<String, dynamic>) row,
+ ];
+
+ Future<void> refresh() async {
+ if (_refreshing || _inert || _disposed) return;
+ _refreshing = true;
+ final generation = _generation;
+ try {
+ final next = await _cli.status();
+ final results = await Future.wait([_cli.list(), _discoverOrBlocked()]);
+ if (_disposed || generation != _generation) return;
+ final devices = _rows(results[0]['devices']);
+ final found = [
+ for (final row in _rows(results[1]['devices']))
+ if (row['id'] is String && (row['id'] as String).isNotEmpty) row,
+ ];
+ final blocked = results[1]['localNetworkBlocked'] == true;
+ if (loading ||
+ unsupported ||
+ error != null ||
+ blocked != networkBlocked ||
+ jsonEncode([next, devices, found]) !=
+ jsonEncode([status, paired, discovered])) {
+ status = next;
+ paired = devices;
+ discovered = found;
+ networkBlocked = blocked;
+ loading = false;
+ unsupported = false;
+ error = null;
+ _changed();
+ }
+ } catch (failure) {
+ if (!_disposed && generation == _generation) {
+ error = _message(failure);
+ if (failure is AutonomousDeviceCliException && failure.unsupported) {
+ unsupported = true;
+ }
+ loading = false;
+ _changed();
+ }
+ } finally {
+ _refreshing = false;
+ _scheduleRefresh();
+ }
+ }
+
+ /// Runs one mutation: no poll begun before it may overwrite its newer answer.
+ Future<bool> _act(
+ Future<void> Function() action,
+ void Function(String message) failed,
+ ) async {
+ if (busy || _inert || _disposed) return false;
+ _timer?.cancel();
+ _generation++;
+ busy = true;
+ error = null;
+ pairError = null;
+ revokeError = null;
+ _changed();
+ var ok = false;
+ try {
+ await action();
+ ok = true;
+ } catch (failure) {
+ failed(_message(failure));
+ } finally {
+ busy = false;
+ _changed();
+ _scheduleRefresh();
+ }
+ return ok;
+ }
+
+ /// Why [deviceId] and [code] cannot be paired as typed, or null when they can.
+ String? pairProblem(String? deviceId, String code) {
+ if (deviceId == null || !discovered.any((d) => d['id'] == deviceId)) {
+ return 'Select your discovered Autonomous robot first.';
+ }
+ if (!RegExp(r'^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{6}$')
+ .hasMatch(normalizeAutonomousDeviceCode(code))) {
+ return 'Enter the six-character code shown on your Autonomous robot.';
+ }
+ return null;
+ }
+
+ /// Pairs the discovered robot [deviceId] with the [code] it shows. True once the CLI holds it.
+ Future<bool> pair({required String? deviceId, required String code}) async {
+ if (busy) return false;
+ if (pairProblem(deviceId, code) case final problem?) {
+ pairError = problem;
+ _changed();
+ return false;
+ }
+ return _act(() async {
+ // The daemon resolves this selected discovery identity, never a UI address.
+ await _cli.pair(
+ code: normalizeAutonomousDeviceCode(code),
+ deviceId: deviceId!,
+ );
+ // The pair response and the list row carry the same identity; reading the list keeps one
+ // source for what is paired.
+ final devices = await _cli.list();
+ if (!_disposed) paired = _rows(devices['devices']);
+ }, (message) => pairError = message);
+ }
+
+ Future<bool> revoke(String id) => _act(() async {
+ await _cli.revoke(id);
+ if (!_disposed) {
+ paired = [
+ for (final d in paired)
+ if (d['id'] != id) d,
+ ];
+ }
+ await refresh();
+ }, (message) => revokeError = message);
+
+ /// Clears a pairing message once the person changes what they typed or chose.
+ void clearPairError() {
+ if (pairError == null) return;
+ pairError = null;
+ _changed();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _timer?.cancel();
+ // Leaving the tab does not revoke trust or stop the daemon.
+ super.dispose();
+ }
+}
+
+/// Status of one paired robot, as its row says it.
+String wifiRobotDetail(Map<String, dynamic> device) => [
+ device['pendingFirstSession'] == true
+ ? 'Waiting for first connection'
+ : device['online'] == true
+ ? 'Connected'
+ : 'Paired · Offline',
+ ?device['fingerprint']?.toString(),
+].join(' · ');
+
+Future<bool> _confirmRevoke(
+ BuildContext context,
+ Map<String, dynamic> device,
+) async =>
+ await showAppDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Revoke Autonomous robot?'),
+ content: SizedBox(
+ width: 360,
+ child: Text(
+ 'Disconnect ${device['label'] ?? 'this Autonomous robot'} and remove its access to this computer. '
+ 'It will need to pair again.',
+ style: grid.AppType.body(height: 1.4),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ overlayColor: grid.AppSurface.hoverFill,
+ ),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('device-confirm'),
+ style: FilledButton.styleFrom(
+ backgroundColor: grid.AppPalette.dangerFill,
+ overlayColor: const Color(0x1FFFFFFF),
+ ),
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Revoke Autonomous robot'),
+ ),
+ ],
+ ),
+ ) ??
+ false;
+
+/// The Devices tab's robots paired over Wi-Fi: one row each, and Revoke… on it. Nothing at all while
+/// none is paired — Add device ▸ Wi-Fi code is where one is added.
+class WifiRobotsList extends StatelessWidget {
+ const WifiRobotsList({super.key, required this.controller, this.topGap = 0});
+
+ final WifiRobotsController controller;
+
+ /// Space above the list, taken only when there is a list.
+ final double topGap;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ final paired = controller.paired;
+ final problem = controller.revokeError;
+ if (paired.isEmpty && problem == null) return const SizedBox.shrink();
+ return Column(
+ key: const Key('wifi-robots'),
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(height: topGap),
+ Text('Paired over Wi-Fi', style: grid.AppType.title()),
+ const SizedBox(height: 5),
+ Text(
+ 'Harness CLI keeps the connection running when you close Desktop.',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(height: 14),
+ for (final device in paired) ...[
+ SettingRow(
+ key: ValueKey('wifi-robot-${device['id']}'),
+ title: device['label']?.toString() ?? 'Autonomous robot',
+ // The fingerprint belongs to the device it identifies, not to a row of its own.
+ detail: wifiRobotDetail(device),
+ control: SizedBox(
+ width: SettingRow.controlWidth,
+ child: OutlinedButton(
+ key: ValueKey('wifi-robot-revoke-${device['id']}'),
+ onPressed:
+ controller.controlsDisabled || device['id'] is! String
+ ? null
+ : () async {
+ if (!await _confirmRevoke(context, device)) return;
+ await controller.revoke(device['id'] as String);
+ },
+ child: const Text('Revoke…'),
+ ),
+ ),
+ ),
+ const SizedBox(height: 10),
+ ],
+ if (problem != null)
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ problem,
+ key: const Key('wifi-robots-error'),
+ style: DesktopChrome.metadata(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+}
+
+/// Add device ▸ Wi-Fi code: choose a robot the network shows and enter the six-character code it
+/// displays. True when it paired.
+Future<bool> showWifiPairDialog(
+ BuildContext context,
+ WifiRobotsController controller, {
+ void Function()? openLocalNetworkSettings,
+}) async =>
+ await showAppDialog<bool>(
+ context: context,
+ builder: (_) => WifiPairDialog(
+ controller: controller,
+ openLocalNetworkSettings: openLocalNetworkSettings,
+ ),
+ ) ??
+ false;
+
+class WifiPairDialog extends StatefulWidget {
+ const WifiPairDialog({
+ super.key,
+ required this.controller,
+ this.openLocalNetworkSettings,
+ });
+
+ final WifiRobotsController controller;
+
+ /// Replaces opening System Settings ▸ Privacy & Security ▸ Local Network (tests).
+ final void Function()? openLocalNetworkSettings;
+
+ @override
+ State<WifiPairDialog> createState() => _WifiPairDialogState();
+}
+
+class _WifiPairDialogState extends State<WifiPairDialog> {
+ final _code = TextEditingController();
+ String? _selected;
+
+ WifiRobotsController get _robots => widget.controller;
+
+ @override
+ void initState() {
+ super.initState();
+ _robots.addListener(_changed);
+ // A message from an earlier attempt belongs to that attempt.
+ _robots.pairError = null;
+ unawaited(_robots.refresh());
+ }
+
+ @override
+ void dispose() {
+ _robots.removeListener(_changed);
+ _code.dispose();
+ super.dispose();
+ }
+
+ void _changed() {
+ // A robot that left the network takes its selection with it, and the code typed for it: a
+ // code is never retargeted at another robot.
+ if (_selected != null &&
+ !_robots.discovered.any((device) => device['id'] == _selected)) {
+ _selected = null;
+ _code.clear();
+ }
+ if (mounted) setState(() {});
+ }
+
+ void _openLocalNetworkSettings() =>
+ (widget.openLocalNetworkSettings ??
+ () => unawaited(
+ launchUrl(
+ Uri.parse(
+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork',
+ ),
+ ),
+ ))();
+
+ Future<void> _submit() async {
+ if (_robots.busy) return;
+ final code = _code.text;
+ // A code that is sent is spent: the field empties. One refused before sending stays, to be
+ // corrected.
+ if (_robots.pairProblem(_selected, code) == null) _code.clear();
+ final paired = await _robots.pair(deviceId: _selected, code: code);
+ if (mounted && paired) Navigator.of(context).pop(true);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final robots = _robots;
+ final disabled = robots.controlsDisabled;
+ final message = robots.pairError ?? robots.error;
+ final refresh = AppIconButton(
+ icon: AppIcons.refreshCw,
+ tooltip: 'Refresh Autonomous robot status',
+ onPressed: disabled ? null : () => unawaited(robots.refresh()),
+ );
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 500),
+ child: DesktopDialogSurface(
+ child: SingleChildScrollView(
+ child: Padding(
+ padding: const EdgeInsets.all(28),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ DesktopDialogHeader(
+ title: 'Pair with a code',
+ padding: EdgeInsets.zero,
+ onClose: () => Navigator.of(context).pop(false),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Keep your Autonomous robot on the same network as this computer.',
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 20),
+ if (robots.loading)
+ const SkeletonBlock(child: SkeletonListTile(leading: 0))
+ else if (robots.unsupported) ...[
+ Text(
+ 'Update Harness CLI to use Autonomous robots.',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'Run this command in Terminal, then refresh.',
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ const Expanded(
+ child: SelectableText('harness update'),
+ ),
+ refresh,
+ ],
+ ),
+ ] else ...[
+ if (robots.networkBlocked) ...[
+ Column(
+ key: const Key('autonomous-device-network-blocked'),
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Allow Harness on your local network',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ 'macOS is blocking Harness from your local network, so it can’t find Autonomous robots. '
+ 'Turn on Harness in Privacy & Security › Local Network, then refresh.',
+ style: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
+ ),
+ if (Platform.isMacOS ||
+ widget.openLocalNetworkSettings != null) ...[
+ const SizedBox(height: 8),
+ OutlinedButton(
+ onPressed: disabled
+ ? null
+ : _openLocalNetworkSettings,
+ child: const Text('Open Settings'),
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 18),
+ ],
+ Text(
+ 'Device',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 6),
+ Row(
+ children: [
+ Expanded(
+ child: ExcludeFocus(
+ excluding: disabled,
+ child: IgnorePointer(
+ ignoring: disabled,
+ child: AppSelectField<String?>(
+ key: const Key('autonomous-device-selection'),
+ semanticLabel: 'Autonomous robot',
+ value: _selected,
+ options: [
+ const SelectOption<String?>(
+ value: null,
+ label: 'Select a device',
+ ),
+ for (final device in robots.discovered)
+ SelectOption<String?>(
+ value: device['id'] as String,
+ label:
+ device['name']?.toString() ??
+ 'Autonomous robot',
+ ),
+ ],
+ onChanged: (value) {
+ if (robots.controlsDisabled) return;
+ setState(() {
+ _selected = value;
+ _code.clear();
+ });
+ robots.clearPairError();
+ },
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ refresh,
+ ],
+ ),
+ const SizedBox(height: 6),
+ Text(
+ robots.networkBlocked
+ ? 'Allow local network access above to find your robot.'
+ : robots.discovered.isEmpty
+ ? 'No Autonomous robots found. Keep your device on the same network, then refresh.'
+ : 'Select your device and enter its six-character code. Separators are allowed, for example ABC-123.',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(height: 14),
+ TextField(
+ key: const Key('autonomous-device-code'),
+ controller: _code,
+ enabled: !disabled,
+ maxLength: 32,
+ obscureText: true,
+ autocorrect: false,
+ enableSuggestions: false,
+ style: grid.AppType.mono(
+ color: grid.AppPalette.textPrimary,
+ ),
+ decoration: labeledFieldDecoration(
+ 'Six-character code',
+ fill: grid.AppCard.inset,
+ ).copyWith(counterText: ''),
+ onSubmitted: (_) => unawaited(_submit()),
+ ),
+ ],
+ if (message != null && !robots.unsupported) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ message,
+ key: const Key('autonomous-device-error'),
+ style: DesktopChrome.text(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ],
+ const SizedBox(height: 12),
+ Text(
+ 'Harness CLI keeps the connection running when you close Desktop.',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(height: 24),
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 10,
+ runSpacing: 8,
+ children: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ key: const Key('autonomous-device-pair'),
+ onPressed: disabled || robots.unsupported
+ ? null
+ : () => unawaited(_submit()),
+ child: Text(robots.busy ? 'Pairing…' : 'Pair'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 5f7f66ced..ad130d9a1 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -32,7 +32,7 @@ import '../widgets/resting_section.dart'
show confirmStopInUse, confirmSwitchAnyway;
import '../widgets/session_close_dialog.dart';
import '../notify/system_notifications.dart';
-import '../settings/sections/account_device_detail.dart';
+import '../widgets/account_device_detail.dart';
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import 'login_screen.dart' show showSignInSheet;
@@ -114,7 +114,9 @@ import '../widgets/new_agent_dialog.dart';
import '../widgets/box_chrome.dart';
import '../widgets/new_harness_form.dart';
import '../widgets/desktop_chrome.dart';
+import '../widgets/account_device_history.dart';
import '../widgets/desktop_search_panel.dart';
+import '../widgets/machine_picker_extras.dart';
import '../widgets/desktop_workspace_tab.dart';
import '../widgets/open_harness_intent.dart';
import '../widgets/pane_grid.dart';
@@ -769,6 +771,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
_routeIsCurrent = current;
+ if (current) _maybeOpenMachinesRequest();
if (!current &&
(_search != null ||
_daemonOverlay != null ||
@@ -2590,6 +2593,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
await action();
} finally {
_dialogOpen = false;
+ _maybeOpenMachinesRequest();
if (mounted) {
_canvasFocus.descendantsAreFocusable = _search == null;
if (_search == null &&
@@ -3037,8 +3041,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
// (its "Sign in…") must not bring the card back once it closes, so the
// offer is dropped on the way out too.
app.dropPhoneOffer();
- // "Manage devices…" pops the dialog and asks for Settings, but this
- // [_dialog] is still open until the pop lands — a [_settings] made from
+ // "Manage devices…" pops the dialog and asks for Machines, but this
+ // [_dialog] is still open until the pop lands — a picker opened from
// the callback would be refused. So it is remembered, and opened after.
var manageDevices = false;
try {
@@ -3055,7 +3059,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.dropPhoneOffer();
}
if (manageDevices && mounted) {
- await _settings(SettingsSection.accountDevices);
+ await _openMachines(phones: true, toggle: false);
}
}
@@ -3076,18 +3080,131 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
- Future<void> _openMachines({String? initialMachineId}) async {
+ /// Machines: the account's computers, and its phones and apps.
+ ///
+ /// [devicePub] selects that device once the account's list has been read, [phones] the first
+ /// phone or app. [review] false is the picker opening on its own (a machine asking to be linked):
+ /// nobody chose to look at the list, so it marks no new device seen. [toggle] false keeps a
+ /// Machines picker that is already open rather than closing it, as a deep link wants.
+ Future<void> _openMachines({
+ String? initialMachineId,
+ String? devicePub,
+ bool phones = false,
+ bool review = true,
+ bool toggle = true,
+ }) async {
_browserMachineSetupHandled = true;
_onboarding.acknowledge(OnboardingStep.machines);
- _openResourcePicker('@');
- if (initialMachineId != null && _search?.isMachineMode == true) {
- final index = _search!.rows.indexWhere(
+ if (toggle || _search?.isMachineMode != true) _openResourcePicker('@');
+ final search = _search;
+ if (search == null || !search.isMachineMode) return;
+ if (!review) search.machineDevices?.markSeen = false;
+ if (initialMachineId != null) {
+ final index = search.rows.indexWhere(
(row) => row.machineId == initialMachineId,
);
- if (index >= 0) _search!.move(index - _search!.cursor);
+ if (index >= 0) search.move(index - search.cursor);
+ }
+ if (devicePub != null || phones) {
+ _selectDeviceWhenListed(search, pub: devicePub, phones: phones);
+ }
+ }
+
+ /// Selects a device in Machines as soon as the account's list has it: the list is read when
+ /// the picker opens, so a deep link usually arrives before its row does.
+ void _selectDeviceWhenListed(
+ SwarmSearchController search, {
+ String? pub,
+ bool phones = false,
+ }) {
+ var done = false, selecting = false;
+ bool attempt() {
+ // Selecting notifies this same listener: the second call is that, not news.
+ selecting = true;
+ try {
+ return pub != null
+ ? search.selectDevice(pub)
+ : search.selectFirstPhone();
+ } finally {
+ selecting = false;
+ }
+ }
+
+ if (attempt()) return;
+ late final VoidCallback listener;
+ listener = () {
+ if (done || selecting) return;
+ if (_search != search || !search.isMachineMode) {
+ done = true;
+ } else if (attempt() || search.machineDevices?.loaded == true) {
+ done = true;
+ }
+ if (done) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (_search == search) search.removeListener(listener);
+ });
+ }
+ };
+ search.addListener(listener);
+ }
+
+ /// A way in from outside the workspace (a device band, a review line under a password prompt)
+ /// asked for Machines ([AppNotifier.requestMachines]): opened once nothing else holds the window.
+ void _maybeOpenMachinesRequest() {
+ if (app.machinesRequest == null ||
+ !mounted ||
+ _dialogOpen ||
+ _spokenPaletteOpen ||
+ !_routeIsCurrent) {
+ return;
}
+ final request = app.takeMachinesRequest()!;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ unawaited(
+ _openMachines(
+ devicePub: request.devicePub,
+ phones: request.phones,
+ toggle: false,
+ ),
+ );
+ });
}
+ /// What the Machines picker needs from the workspace for its dialogs and Add Phone.
+ MachinePickerHooks get _machinePickerHooks => MachinePickerHooks(
+ confirm: (title, detail, action) async {
+ _pickerModalChanged(true);
+ try {
+ return await confirmDeviceAction(
+ context,
+ title,
+ detail,
+ action,
+ destructive: true,
+ );
+ } finally {
+ _pickerModalChanged(false);
+ if (mounted && _search != null) _focusSearch();
+ }
+ },
+ onHistory: () async {
+ _pickerModalChanged(true);
+ try {
+ await showAccountDeviceHistory(context, app);
+ } finally {
+ _pickerModalChanged(false);
+ if (mounted && _search != null) _focusSearch();
+ }
+ },
+ onAddPhone: kIsWeb
+ ? null
+ : () {
+ _closeSearch(restoreFocus: false);
+ unawaited(_addPhone());
+ },
+ );
+
void _openResourcePicker(String prefix) {
dismissTransientMenus();
if (_search?.scopePrefix == prefix) {
@@ -5974,7 +6091,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
if (choice.destination.isModel) return;
- if (_search!.setupLayout && choice.destination.isMachine) {
+ if (_search!.setupLayout &&
+ (choice.destination.isMachine || choice.destination.isAccountDevice)) {
final index = _search!.rows.indexWhere(
(row) => row.id == choice.destination.id,
);
@@ -6098,6 +6216,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
onRefocus: _focusSearch,
previewBuilder: preview,
showsBack: widget.chrome?.pickerShowsBack ?? false,
+ machineHooks: _machinePickerHooks,
);
final scoped = Semantics(
scopesRoute: true,
@@ -6510,7 +6629,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (mounted) {
app.acknowledgeMachineLinkRequest(machine.machine.machineId);
- await _openMachines(initialMachineId: machine.machine.machineId);
+ await _openMachines(
+ initialMachineId: machine.machine.machineId,
+ review: false,
+ );
}
// Keep the prompt's identity until the picker closes. Otherwise Escape
// would immediately reopen it on the next workspace update.
@@ -6625,6 +6747,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
initialMachineId: selected?.needsLink == true
? selected!.machine.machineId
: null,
+ review: false,
),
);
});
@@ -7044,6 +7167,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
builder: (context, _) {
grid.AppTheme.watch(context);
_maybeLink();
+ _maybeOpenMachinesRequest();
_scheduleWelcomeComposer();
if (app.panes.isEmpty) {
WidgetsBinding.instance.addPostFrameCallback(
diff --git a/desktop/lib/settings/agent_settings.dart b/desktop/lib/settings/agent_settings.dart
new file mode 100644
index 000000000..48c4ebe6f
--- /dev/null
+++ b/desktop/lib/settings/agent_settings.dart
@@ -0,0 +1,152 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../api/api_client.dart';
+
+/// What the person lets agents do with Harness on this computer — Settings ▸ Agents. This
+/// computer's daemon keeps them (`/api/agent-settings`, cli/src/lib/agentSettings.ts), not the
+/// account: each computer decides for the agents it runs.
+enum AgentSetting {
+ agentsStartAgents(
+ 'agentsStartAgents',
+ 'Agents can start other agents',
+ 'Claude Code and Codex can start, wait for and close harnesses of their own, and their '
+ 'instructions say how. Turn off to keep every agent working alone.',
+ ),
+ pullRequestLine(
+ 'pullRequestLine',
+ 'Mark pull requests from agent-started harnesses',
+ 'A harness another agent started adds one line to the pull requests it opens: '
+ '🤝 Started by another agent in Harness.',
+ );
+
+ const AgentSetting(this.key, this.label, this.description);
+
+ /// Its name in the daemon's settings.
+ final String key;
+ final String label, description;
+}
+
+/// Reads this computer's agent settings; null when its daemon predates them.
+typedef AgentSettingsRead = Future<Map<String, dynamic>?> Function();
+
+/// Changes one; answers the settings as they are afterwards.
+typedef AgentSettingsWrite = Future<Map<String, dynamic>> Function(
+ String key,
+ bool value,
+);
+
+/// Settings ▸ Agents, read from and written to this computer's daemon. A change shows once the
+/// daemon has answered with it, never before. A setting the daemon does not name is one it predates:
+/// it is not offered, rather than shown in a state nobody can vouch for.
+class AgentSettingsStore extends ChangeNotifier {
+ AgentSettingsStore({this.read, this.write, this.unavailable});
+
+ /// The settings through [api] — this computer's daemon.
+ factory AgentSettingsStore.api(ApiClient api) =>
+ AgentSettingsStore(read: api.agentSettings, write: api.setAgentSetting);
+
+ final AgentSettingsRead? read;
+ final AgentSettingsWrite? write;
+
+ /// Why these cannot be changed from here at all (a browser has no daemon of its own). Null where
+ /// they can.
+ final String? unavailable;
+
+ final _values = <AgentSetting, bool>{};
+ bool loaded = false, saving = false, _disposed = false;
+ int _generation = 0;
+
+ /// Why the last read or write failed, or why there is nothing to read.
+ String? error;
+
+ /// The read failed, or the daemon predates these settings: nothing can be changed until it answers.
+ bool get blocked => unavailable != null || (!loaded && error != null);
+ AgentSetting? savingSetting, errorSetting;
+
+ /// The value the daemon last answered for [setting]; null before it has, or when it does not keep it.
+ bool? value(AgentSetting setting) => _values[setting];
+
+ /// Whether this computer keeps [setting]. The first one is always offered, if only to say why it
+ /// cannot be changed here.
+ bool offered(AgentSetting setting) =>
+ setting == AgentSetting.agentsStartAgents || _values.containsKey(setting);
+
+ void _changed() {
+ if (!_disposed) notifyListeners();
+ }
+
+ void _take(Map<String, dynamic> answer) {
+ for (final setting in AgentSetting.values) {
+ final value = answer[setting.key];
+ if (value is bool) {
+ _values[setting] = value;
+ } else {
+ _values.remove(setting);
+ }
+ }
+ }
+
+ static String _message(Object failure) => failure is ApiException
+ ? failure.message
+ : 'Couldn’t reach Harness on this computer. Check that it is running, then refresh.';
+
+ Future<void> refresh() async {
+ final read = this.read;
+ // A read under way while a change is saved would drop the change's answer.
+ if (_disposed || saving || unavailable != null || read == null) return;
+ final generation = ++_generation;
+ error = null;
+ errorSetting = null;
+ _changed();
+ try {
+ final answer = await read();
+ if (_disposed || generation != _generation) return;
+ if (answer == null) {
+ loaded = false;
+ _values.clear();
+ error = 'Update Harness on this computer to change this.';
+ } else {
+ _take(answer);
+ loaded = true;
+ }
+ } catch (failure) {
+ if (_disposed || generation != _generation) return;
+ error = _message(failure);
+ }
+ _changed();
+ }
+
+ Future<void> set(AgentSetting setting, bool on) async {
+ final write = this.write;
+ if (_disposed || saving || blocked || write == null || !loaded) return;
+ final generation = ++_generation;
+ saving = true;
+ savingSetting = setting;
+ error = null;
+ errorSetting = null;
+ _changed();
+ try {
+ final answer = await write(setting.key, on);
+ if (_disposed || generation != _generation) return;
+ _take(answer);
+ } catch (failure) {
+ if (_disposed || generation != _generation) return;
+ error = _message(failure);
+ errorSetting = setting;
+ } finally {
+ if (!_disposed && generation == _generation) {
+ saving = false;
+ savingSetting = null;
+ }
+ }
+ _changed();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/settings/sections/account_devices_section.dart b/desktop/lib/settings/sections/account_devices_section.dart
deleted file mode 100644
index fd03742ae..000000000
--- a/desktop/lib/settings/sections/account_devices_section.dart
+++ /dev/null
@@ -1,466 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-
-import '../../core/relative_time.dart';
-import '../../shared/theme/app_theme.dart' as grid;
-import '../../shared/widgets/fingerprint_text.dart';
-import '../../shared/widgets/section_heading.dart';
-import '../../shared/widgets/section_scaffold.dart';
-import '../../shared/widgets/setting_row.dart';
-import '../../shared/widgets/skeleton.dart';
-import '../../state/account_devices.dart';
-import '../../state/app_state.dart';
-import '../../theme/app_theme.dart';
-import 'account_device_detail.dart';
-import 'account_device_history.dart';
-
-/// What "Trust again" says when the list it would trust is another account's than the one signed in to.
-const otherAccountMessage =
- 'The device list now belongs to a different account than the one you signed in with. '
- 'Sign in again to switch accounts.';
-
-/// Settings ▸ Your devices — every computer and app signed in to this account. Signing in on one is
-/// what makes the others trust it (the device key log), so this list is also the one place to see a
-/// device that is not yours, and to take it out.
-class AccountDevicesSection extends StatefulWidget {
- const AccountDevicesSection({super.key, required this.notifier});
-
- final AppNotifier notifier;
-
- @override
- State<AccountDevicesSection> createState() => _AccountDevicesSectionState();
-}
-
-class _AccountDevicesSectionState extends State<AccountDevicesSection> {
- AccountDevices? _devices;
- bool _loaded = false;
- int _revision = -1;
- final Set<String> _removing = {};
- String? _error;
-
- /// The error is a state to review again (another account, a list that changed), not a failure: amber.
- /// Every other error is red.
- bool _errorIsNotice = false;
-
- /// The devices that were new when this list opened: they keep their `New` badge for the visit, though
- /// opening the list clears the banner that announced them.
- late final Set<String> _newPubs;
-
- /// "Got it" was pressed on the baseline panel: hidden at once, whatever the write takes.
- bool _baselineDone = false;
-
- AppNotifier get _app => widget.notifier;
-
- @override
- void initState() {
- super.initState();
- _app.addListener(_changed);
- _newPubs = {for (final d in _app.newDevices) d.pub};
- unawaited(_load());
- }
-
- @override
- void dispose() {
- _app.removeListener(_changed);
- super.dispose();
- }
-
- void _changed() {
- if (_app.devicesRevision != _revision) unawaited(_load());
- }
-
- Future<void> _load() async {
- _revision = _app.devicesRevision;
- final first = !_loaded;
- List<String>? banner;
- final devices = await _app.loadDevices(onListed: (b) => banner = b);
- if (!mounted) return;
- setState(() {
- _devices = devices;
- _loaded = true;
- // What the log kept as new (it outlives the banner and a restart) badges alongside the banner's —
- // on every read, so a device that turns up while the list is open is badged too (it stays pending:
- // only the first read of a visit is marked seen below).
- if (devices != null) _newPubs.addAll(devices.pending);
- if (!first) _newPubs.addAll(_app.newDevices.map((d) => d.pub));
- });
- // Looking at the list IS reviewing the new devices: the banner that pointed here is done. After
- // the first read, so the pending keys are in [_newPubs] before they are marked seen.
- if (first) {
- _app.seenNewDevices(
- pending: devices?.pending ?? const [],
- shown: banner,
- departed: devices?.departed ?? const [],
- );
- }
- }
-
- Future<void> _gotIt() async {
- setState(() => _baselineDone = true);
- await _app.seeDeviceBaseline();
- }
-
- Future<void> _remove(AccountDevice device) async {
- final name = device.label.isEmpty ? 'this device' : device.label;
- final confirmed = await confirmDeviceAction(
- context,
- 'Remove $name?',
- removeDeviceDetail,
- 'Remove',
- destructive: true,
- );
- if (!confirmed || !mounted) return;
- setState(() {
- _removing.add(device.pub);
- _error = null;
- _errorIsNotice = false;
- });
- final error = await _app.removeDevice(device.pub);
- if (!mounted) return;
- setState(() {
- _removing.remove(device.pub);
- _error = error == null ? null : 'Couldn’t remove $name ($error). Try again.';
- _errorIsNotice = false;
- });
- }
-
- bool _removingUnused = false;
-
- Future<void> _removeUnused(List<AccountDevice> unused) async {
- final confirmed = await confirmDeviceAction(
- context,
- 'Remove ${unused.length} unused app${unused.length == 1 ? '' : 's'}?',
- [for (final d in unused) '${d.label.isEmpty ? 'Unnamed app' : d.label} — last active ${relativeAgo(d.lastSeen!, DateTime.now())}'].join('\n'),
- 'Remove',
- destructive: true,
- );
- if (!confirmed || !mounted) return;
- setState(() {
- _removingUnused = true;
- _error = null;
- _errorIsNotice = false;
- });
- final failed = <String>[];
- for (final d in unused) {
- if (await _app.removeDevice(d.pub) != null) failed.add(d.label.isEmpty ? 'an app' : d.label);
- }
- if (!mounted) return;
- setState(() {
- _removingUnused = false;
- _error = failed.isEmpty ? null : 'Couldn’t remove ${failed.join(', ')}. Try again.';
- _errorIsNotice = false;
- });
- }
-
- Future<void> _trustAgain() async {
- final preview = await _app.rebaselineDevices(confirm: false);
- if (!mounted) return;
- if (preview == null) {
- setState(() {
- _error = 'Couldn’t read a valid device list. Try again later.';
- _errorIsNotice = false;
- });
- return;
- }
- if (preview.otherAccount) {
- setState(() {
- _error = otherAccountMessage;
- _errorIsNotice = true;
- });
- return;
- }
- final lines = [
- for (final name in preview.added) '+ $name',
- for (final name in preview.removed) '− $name',
- ];
- final confirmed = await confirmDeviceAction(
- context,
- 'Trust this device list again?',
- lines.isEmpty
- ? 'It changes no device. Continue only if you expected this.'
- : 'Only if every device added below is yours:\n\n${lines.join('\n')}',
- 'Trust again',
- // Trusting a list the backend served is the cautionary action: the same red as Remove.
- destructive: true,
- );
- if (!confirmed || !mounted) return;
- final done = await _app.rebaselineDevices(confirm: true, head: preview.head);
- if (!mounted) return;
- if (done == null) {
- setState(() {
- _error = 'Couldn’t trust the device list again. Try again later.';
- _errorIsNotice = false;
- });
- } else if (done.otherAccount) {
- setState(() {
- _error = otherAccountMessage;
- _errorIsNotice = true;
- });
- } else if (!done.logChanged) {
- setState(() {
- _error = null;
- _errorIsNotice = false;
- });
- } else {
- // What was reviewed is no longer what the backend serves: nothing was trusted. Show it again.
- setState(() {
- _error = 'The device list changed while you were reviewing it. Review it again.';
- _errorIsNotice = true;
- });
- unawaited(_trustAgain());
- }
- }
-
- void _open(AccountDevice device) => unawaited(
- showAccountDeviceDetail(
- context,
- _app,
- pub: device.pub,
- device: device,
- isNew: _newPubs.contains(device.pub),
- onMine: () => setState(() => _newPubs.remove(device.pub)),
- ),
- );
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final devices = _devices;
- return SectionScaffold(
- title: 'Your devices',
- subtitle: 'Every computer and app signed in to your account. Each one reaches your machines '
- 'end to end encrypted. Remove one you do not recognise.',
- child: SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (devices != null && devices.frozen) _FrozenLine(devices: devices, onTrustAgain: _trustAgain),
- if (devices?.registerError case final code?) _RefusedLine(code: code),
- if (devices != null && !devices.baselineSeen && !_baselineDone && !_app.baselineSeenLocally && devices.baseline.isNotEmpty)
- _BaselinePanel(devices: devices.baseline, onGotIt: () => unawaited(_gotIt())),
- if (_error case final error?)
- Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: Text(
- error,
- key: const Key('account-devices-error'),
- style: grid.AppType.body(color: _errorIsNotice ? AppColors.warning : AppColors.danger),
- ),
- ),
- if (devices != null && devices.unused(DateTime.now()).isNotEmpty)
- Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: SettingRow(
- key: const Key('account-devices-unused'),
- title: '${devices.unused(DateTime.now()).length} app${devices.unused(DateTime.now()).length == 1 ? '' : 's'} not used in 90 days',
- detail: 'Most likely a browser whose data was cleared. Removing them changes nothing you use.',
- control: OutlinedButton(
- onPressed: _removingUnused ? null : () => unawaited(_removeUnused(devices.unused(DateTime.now()))),
- child: Text(_removingUnused ? 'Removing…' : 'Remove them'),
- ),
- ),
- ),
- if (!_loaded)
- const SkeletonList(rows: 3)
- else if (devices == null)
- Text(
- 'The device list is not available here yet.',
- style: grid.AppType.body(color: grid.AppPalette.textSecondary),
- )
- else ...[
- if (devices.self case final self?) ...[
- const SectionHeading('This device'),
- const SizedBox(height: 8),
- SettingRow(
- key: const Key('account-device-this'),
- title: self.label.trim().isEmpty ? 'Unnamed device' : self.label,
- detail: 'This is the code your other devices show for this device.',
- control: const SizedBox.shrink(),
- footer: FingerprintText(self.fingerprint, large: false, copyKey: const Key('this-device-copy')),
- ),
- const SizedBox(height: 16),
- ],
- for (final device in devices.listed(_newPubs))
- Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () => _open(device),
- child: SettingRow(
- key: ValueKey('account-device-${device.pub}'),
- title: device.label.trim().isEmpty ? 'Unnamed device' : device.label,
- badge: device.suspended
- ? 'Suspended'
- : _newPubs.contains(device.pub)
- ? 'New'
- : null,
- detail: deviceDetailLine(
- device,
- now: DateTime.now(),
- sameName: devices.sharedNames.contains(device.label.trim()),
- ),
- control: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- TextButton(
- key: ValueKey('account-device-details-${device.pub}'),
- onPressed: () => _open(device),
- child: const Text('Details'),
- ),
- const SizedBox(width: 6),
- OutlinedButton(
- onPressed: _removing.contains(device.pub) ? null : () => unawaited(_remove(device)),
- child: Text(_removing.contains(device.pub) ? 'Removing…' : 'Remove'),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: devices.historyAvailable
- ? Align(
- alignment: Alignment.centerLeft,
- child: OutlinedButton(
- key: const Key('account-devices-history'),
- onPressed: () => unawaited(showAccountDeviceHistory(context, _app)),
- child: const Text('History…'),
- ),
- )
- : Text(
- 'Update Harness on this computer to see history.',
- key: const Key('account-devices-history-hint'),
- style: grid.AppType.body(color: grid.AppPalette.textSecondary),
- ),
- ),
- ],
- ],
- ),
- ),
- );
- }
-}
-
-/// The devices that were already on the account when this one joined: never announced, so said once.
-class _BaselinePanel extends StatelessWidget {
- const _BaselinePanel({required this.devices, required this.onGotIt});
-
- final List<AccountDevice> devices;
- final VoidCallback onGotIt;
-
- @override
- Widget build(BuildContext context) => Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: DecoratedBox(
- key: const Key('account-devices-baseline'),
- decoration: BoxDecoration(
- color: grid.AppPalette.warn.withValues(alpha: 0.10),
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.28)),
- ),
- child: Padding(
- padding: const EdgeInsets.all(12),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text('Already on your account', style: Theme.of(context).textTheme.titleSmall),
- const SizedBox(height: 4),
- Text(
- 'These were on your account before this device joined. If one isn’t yours, remove it.',
- style: grid.AppType.body(color: grid.AppPalette.textPrimary),
- ),
- const SizedBox(height: 8),
- for (final d in devices)
- Text(
- '${d.label.trim().isEmpty ? 'A device' : d.label.trim()} · ${d.isMachine ? 'Computer' : 'App'} · ${d.fingerprint}',
- style: grid.AppType.caption(color: grid.AppPalette.textSecondary),
- ),
- const SizedBox(height: 8),
- Align(
- alignment: Alignment.centerRight,
- child: OutlinedButton(
- key: const Key('account-devices-baseline-gotit'),
- onPressed: onGotIt,
- child: const Text('Got it'),
- ),
- ),
- ],
- ),
- ),
- ),
- );
-}
-
-/// The backend refused this device a place on the account ([AccountDevices.registerError]).
-class _RefusedLine extends StatelessWidget {
- const _RefusedLine({required this.code});
-
- final String code;
-
- @override
- Widget build(BuildContext context) => Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: grid.AppPalette.warn.withValues(alpha: 0.10),
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.28)),
- ),
- child: Padding(
- padding: const EdgeInsets.all(12),
- child: Text(
- registerRefusalSentence(code),
- key: const Key('account-devices-refused'),
- style: grid.AppType.body(color: grid.AppPalette.textPrimary),
- ),
- ),
- ),
- );
-}
-
-class _FrozenLine extends StatelessWidget {
- const _FrozenLine({required this.devices, required this.onTrustAgain});
-
- final AccountDevices devices;
- final VoidCallback onTrustAgain;
-
- @override
- Widget build(BuildContext context) {
- final where = devices.frozenReason != null
- ? 'this device'
- : devices.frozenPeers.join(', ');
- return Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: grid.AppPalette.warn.withValues(alpha: 0.10),
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.28)),
- ),
- child: Padding(
- padding: const EdgeInsets.all(12),
- child: Row(
- children: [
- Expanded(
- child: Text(
- 'The device list froze on $where: Harness served a list that does not match what '
- 'was verified before. No device is added until you review it.',
- style: grid.AppType.body(color: grid.AppPalette.textPrimary),
- ),
- ),
- if (devices.frozenReason != null) ...[
- const SizedBox(width: 12),
- OutlinedButton(onPressed: onTrustAgain, child: const Text('Review…')),
- ],
- ],
- ),
- ),
- ),
- );
- }
-}
diff --git a/desktop/lib/settings/sections/agents_section.dart b/desktop/lib/settings/sections/agents_section.dart
new file mode 100644
index 000000000..d0a802b87
--- /dev/null
+++ b/desktop/lib/settings/sections/agents_section.dart
@@ -0,0 +1,109 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../../shared/widgets/section_scaffold.dart';
+import '../../shared/widgets/setting_row.dart';
+import '../agent_settings.dart';
+
+/// Settings ▸ Agents: what the agents on this computer may do with Harness itself.
+class AgentsSection extends StatefulWidget {
+ const AgentsSection({super.key, required this.store});
+
+ final AgentSettingsStore store;
+
+ @override
+ State<AgentsSection> createState() => _AgentsSectionState();
+}
+
+class _AgentsSectionState extends State<AgentsSection> {
+ @override
+ void initState() {
+ super.initState();
+ unawaited(widget.store.refresh());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final store = widget.store;
+ return SectionScaffold(
+ title: 'Agents',
+ subtitle: 'What the agents on this computer may do with Harness. Each computer keeps its own.',
+ child: SingleChildScrollView(
+ child: ListenableBuilder(
+ listenable: store,
+ builder: (context, _) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ spacing: 10,
+ children: [
+ for (final setting in AgentSetting.values)
+ if (store.offered(setting)) _row(store, setting),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _row(AgentSettingsStore store, AgentSetting setting) {
+ final first = setting == AgentSetting.values.first;
+ // Why nothing here can change: said once, under the first row.
+ final reason = first
+ ? store.unavailable ?? (store.errorSetting == null ? store.error : null)
+ : null;
+ final failed = store.errorSetting == setting ? store.error : null;
+ return SettingRow(
+ key: ValueKey('agent-setting-${setting.key}'),
+ title: setting.label,
+ detail: setting.description,
+ control: Semantics(
+ label: setting.label,
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Switch(
+ key: ValueKey('agent-setting-switch-${setting.key}'),
+ // Until the daemon answers, the default: agents may.
+ value: store.value(setting) ?? true,
+ onChanged: store.loaded && !store.saving && !store.blocked
+ ? (on) => unawaited(store.set(setting, on))
+ : null,
+ ),
+ ),
+ ),
+ footer: store.savingSetting == setting
+ ? Semantics(liveRegion: true, child: const Text('Saving…'))
+ : reason != null
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Semantics(
+ liveRegion: true,
+ child: Text(reason, key: const Key('agent-settings-reason')),
+ ),
+ if (store.unavailable == null)
+ TextButton(
+ onPressed: () => unawaited(store.refresh()),
+ child: const Text('Refresh setting'),
+ ),
+ ],
+ )
+ : failed != null
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Semantics(
+ liveRegion: true,
+ child: Text(failed, key: const Key('agent-settings-error')),
+ ),
+ TextButton(
+ onPressed: () => unawaited(store.refresh()),
+ child: const Text('Refresh setting'),
+ ),
+ ],
+ )
+ : first && !store.loaded && store.error == null
+ ? const Text('Loading…')
+ : null,
+ );
+ }
+}
diff --git a/desktop/lib/settings/sections/cabled_device_card.dart b/desktop/lib/settings/sections/cabled_device_card.dart
deleted file mode 100644
index de6b58bc9..000000000
--- a/desktop/lib/settings/sections/cabled_device_card.dart
+++ /dev/null
@@ -1,418 +0,0 @@
-import 'package:flutter/material.dart';
-
-import '../../shared/theme/app_theme.dart' as grid;
-import '../../shared/widgets/app_select_field.dart';
-import '../../shared/widgets/setting_row.dart';
-import '../../state/dial_status.dart';
-
-/// The robot on a cable at this desk, and everything it persists.
-///
-/// It lives in Settings ▸ Autonomous robots rather than in a section of its own because somebody
-/// looking for their robot's settings looks under "Autonomous robots"; what sits below it is a
-/// different thing wearing the same word — robots paired over the network, managed through the CLI.
-///
-/// **The pane says which robot it is changing, out loud and first.** That is not decoration. These
-/// rows look exactly like the app's own preferences — same [SettingRow], same controls, same column —
-/// and read as settings for *Harness* unless something says otherwise. So the first thing on the
-/// pane is "These settings apply to" and a card naming the robot, what it is running and whether it
-/// is here. With two on the desk that card is also the picker, because a setting belongs to one
-/// robot: reading them as account-wide would silently overwrite one device with the other's taste
-/// the first time somebody touched a row.
-///
-/// Two more rules it is built on:
-///
-/// * **The device owns the values.** Nothing is written here optimistically. A change is sent and the
-/// pane moves when the device answers with what it now holds, so a refusal corrects the window
-/// instead of leaving it showing its own hope.
-/// * **Read-only while unplugged.** The rows stay — a person should be able to read what their robot
-/// is set to with it in a drawer — but nothing can be changed, because there is nothing on the
-/// other end to agree.
-class CabledDeviceCard extends StatefulWidget {
- const CabledDeviceCard({
- super.key,
- required this.devices,
- required this.onChanged,
- this.showCompanion = false,
- });
-
- /// Every robot on this desk, plugged in or lately seen.
- final List<DialStatus> devices;
- final bool showCompanion;
-
- /// Send a patch to one robot. Only the named field travels.
- final void Function(String id, Map<String, Object?> patch) onChanged;
-
- @override
- State<CabledDeviceCard> createState() => _CabledDeviceCardState();
-}
-
-class _CabledDeviceCardState extends State<CabledDeviceCard> {
- /// Which robot the rows below are about. Held by identity rather than index so a device going away
- /// does not silently hand the rows to its neighbour.
- String? _selected;
-
- DialStatus? get _device {
- if (widget.devices.isEmpty) return null;
- for (final device in widget.devices) {
- if (device.id != null && device.id == _selected) return device;
- }
- // Prefer one that is actually here: a pane opening on the robot in the drawer while another is
- // plugged in would be read-only for no reason a person could see.
- for (final device in widget.devices) {
- if (device.attached) return device;
- }
- return widget.devices.first;
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final device = _device;
- if (device == null) return const SizedBox.shrink();
- final theme = Theme.of(context);
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.only(left: 2, bottom: 8),
- child: Text(
- 'These settings apply to',
- style: theme.textTheme.bodySmall,
- ),
- ),
- for (final each in widget.devices) ...[
- _DeviceChip(
- device: each,
- selected: each.id != null && each.id == device.id,
- // A single robot is a statement, not a choice: the card still names it, but tapping it
- // would suggest there is something else to tap.
- onTap: widget.devices.length > 1 && each.id != null
- ? () => setState(() => _selected = each.id)
- : null,
- ),
- const SizedBox(height: 8),
- ],
- const SizedBox(height: 6),
- _Rows(
- device: device,
- onChanged: widget.onChanged,
- showCompanion: widget.showCompanion,
- ),
- ],
- );
- }
-}
-
-/// One robot, named: what it is, what it runs, and whether it is here.
-class _DeviceChip extends StatelessWidget {
- const _DeviceChip({
- required this.device,
- required this.selected,
- required this.onTap,
- });
-
- final DialStatus device;
- final bool selected;
- final VoidCallback? onTap;
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final theme = Theme.of(context);
- final settings = device.settings;
- final detail = [
- if (settings != null)
- '${settings.face} ${settings.round ? 'round' : 'square'}',
- if (device.fw case final fw?) 'habitat $fw',
- ?device.mac,
- ].join(' · ');
- return Semantics(
- selected: selected,
- button: onTap != null,
- child: Material(
- type: MaterialType.transparency,
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(14),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
- decoration: BoxDecoration(
- color: grid.AppGlass.surfaceFill,
- borderRadius: BorderRadius.circular(14),
- boxShadow: grid.AppGlass.cardShadow,
- border: Border.all(
- color: selected
- ? theme.colorScheme.primary
- : theme.colorScheme.outlineVariant.withValues(alpha: 0.5),
- width: selected ? 1.6 : 1,
- ),
- ),
- child: Row(
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(device.name, style: theme.textTheme.titleSmall),
- if (detail.isNotEmpty) ...[
- const SizedBox(height: 2),
- Text(detail, style: theme.textTheme.bodySmall),
- ],
- ],
- ),
- ),
- const SizedBox(width: 12),
- Text(
- device.attached ? 'connected' : 'unplugged',
- style: theme.textTheme.bodySmall?.copyWith(
- color: device.attached
- ? theme.colorScheme.primary
- : theme.textTheme.bodySmall?.color,
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
-
-/// The settings themselves, grouped the way a person looks for them rather than the way the device
-/// stores them: what it looks like, how it answers a finger, and what it says out loud.
-class _Rows extends StatelessWidget {
- const _Rows({
- required this.device,
- required this.onChanged,
- required this.showCompanion,
- });
-
- final DialStatus device;
- final bool showCompanion;
- final void Function(String id, Map<String, Object?> patch) onChanged;
-
- /// The languages the microphone can be transcribed as, each named in itself. The codes are what
- /// the dial sends with every capture and what the backend accepts — VOICE_LANGS in
- /// backend/src/lib/deepgram.ts; edit the two together, or a language offered here is quietly
- /// transcribed as English there. The LVGL firmware offered the same six.
- static const _voiceLangs = [
- SelectOption(value: 'en', label: 'English'),
- SelectOption(value: 'vi', label: 'Tiếng Việt'),
- SelectOption(value: 'es', label: 'Español'),
- SelectOption(value: 'fr', label: 'Français'),
- SelectOption(value: 'ja', label: '日本語'),
- SelectOption(value: 'it', label: 'Italiano'),
- ];
-
- /// Whether the robot offers a choice of who is on the screen. Off while the companion skins are
- /// unfinished (owner, 2026-09-30): the firmware wears Focus whatever it is asked, so a Skin row or a
- /// companion switch would be a control that does nothing. Flip it with HABITAT_FOCUS_ONLY.
- static const _petSkins = false;
-
- /// The characters this firmware ships. Ids are the device's own, from character.h.
- static const _skins = [
- SelectOption(value: 0, label: 'Tim', note: 'The octopus'),
- SelectOption(value: 1, label: 'Tux', note: 'The penguin'),
- SelectOption(value: 2, label: 'Focus', note: 'No companion — the work'),
- ];
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final settings = device.settings;
- final id = device.id;
- if (settings == null) {
- return SettingRow(
- title: 'This robot has not said what it holds yet.',
- detail: device.fw == null
- ? 'It is still greeting the daemon.'
- : 'Its firmware (${device.fw}) keeps its settings on the glass.',
- control: const SizedBox(width: SettingRow.controlWidth),
- );
- }
- // No id means a daemon that predates per-device addressing: it can report, but nothing here can be
- // addressed to a particular robot, so the rows are readable and not writable.
- final live = device.attached && id != null;
- void set(Map<String, Object?> patch) {
- if (live) onChanged(id, patch);
- }
-
- Widget toggle(
- String key,
- bool value,
- String label, {
- bool invert = false,
- }) => Semantics(
- label: label,
- child: Align(
- alignment: Alignment.centerLeft,
- child: Switch(
- key: ValueKey('device-$key-${device.id ?? device.mac ?? ''}'),
- value: invert ? !value : value,
- onChanged: live ? (on) => set({key: invert ? !on : on}) : null,
- ),
- ),
- );
-
- Widget field<T>(
- T value,
- List<SelectOption<T>> options,
- void Function(T) apply,
- ) => SizedBox(
- width: SettingRow.controlWidth,
- child: AppSelectField<T>(
- value: value,
- options: options,
- onChanged: live ? apply : (_) {},
- ),
- );
-
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (!device.attached) ...[
- SettingRow(
- title: 'Unplugged',
- detail: 'These are the settings it last reported. Plug it in to change them.',
- control: const SizedBox(width: SettingRow.controlWidth),
- ),
- const SizedBox(height: 10),
- ],
- _Group(
- title: 'Appearance',
- children: [
- if (_petSkins && showCompanion && settings.followCompanion != null)
- SettingRow(
- title: 'Follow desktop companion',
- detail: settings.companion == null
- ? 'Show the companion paired in your Zoo.'
- : 'Showing ${settings.companion == 'gnu' ? 'GNU' : settings.companion!} from your Zoo.',
- control: toggle(
- 'followCompanion',
- settings.followCompanion!,
- 'Follow desktop companion',
- ),
- ),
- if (_petSkins)
- SettingRow(
- title: 'Skin',
- detail: settings.companion == null
- ? 'Who lives on the screen.'
- : 'Used when you stop following the desktop companion.',
- control: field(
- settings.character,
- _skins,
- (v) => set({'character': v}),
- ),
- ),
- SettingRow(
- title: 'Brightness',
- detail: '${settings.brightness}%',
- control: SizedBox(
- width: SettingRow.controlWidth,
- child: Slider(
- key: ValueKey('device-brightness-${device.id ?? ''}'),
- value: settings.brightness.toDouble(),
- min: 0,
- max: 100,
- divisions: 20,
- // On change END, not on every frame: each one is a frame over the cable and a write to
- // the device's flash, and a dragged slider would spend a thousand of both.
- onChanged: live ? (_) {} : null,
- onChangeEnd: live
- ? (v) => set({'brightness': v.round()})
- : null,
- ),
- ),
- ),
- SettingRow(
- title: 'Still companion',
- detail: 'Stops the artwork animating. Nothing else changes.',
- control: toggle('quiet', settings.quiet, 'Still companion'),
- ),
- // No Edge text row: the robot draws its titles straight across (owner, 2026-10-01), and
- // a Focus-only firmware ignores the field — a choice here would change nothing.
- ],
- ),
- _Group(
- title: 'Gestures',
- children: [
- SettingRow(
- title: 'Reverse scrolling',
- detail: 'Which way a drag moves the text under it.',
- control: field(settings.scrollReversed, const [
- SelectOption(
- value: false,
- label: 'Natural',
- note: 'The text follows your finger',
- ),
- SelectOption(
- value: true,
- label: 'Reversed',
- note: 'The view follows your finger',
- ),
- ], (v) => set({'scrollReversed': v})),
- ),
- ],
- ),
- _Group(
- title: 'Sound & voice',
- children: [
- SettingRow(
- title: 'Notification sound',
- detail: 'The chime when a turn finishes or a question arrives.',
- // Stated as "sound on", which is what the switch position means to a person; the wire
- // field is its opposite, and the flip belongs here rather than in anyone's head.
- control: toggle(
- 'muted',
- settings.muted,
- 'Notification sound',
- invert: true,
- ),
- ),
- SettingRow(
- title: 'Voice language',
- detail:
- 'What the microphone is transcribed as. The robot’s own choice, not this '
- 'computer’s.',
- control: field(
- _voiceLangs.any((o) => o.value == settings.voiceLang)
- ? settings.voiceLang
- : 'en',
- _voiceLangs,
- (v) => set({'voiceLang': v}),
- ),
- ),
- ],
- ),
- ],
- );
- }
-}
-
-/// A run of rows under a caption. The grouping is presentation only, but it says something true:
-/// what the robot looks like, how it answers a finger, and what it says out loud.
-class _Group extends StatelessWidget {
- const _Group({required this.title, required this.children});
-
- final String title;
- final List<Widget> children;
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- if (children.isEmpty) return const SizedBox.shrink();
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.only(left: 2, top: 10, bottom: 8),
- child: Text(title, style: Theme.of(context).textTheme.labelLarge),
- ),
- for (final child in children) ...[child, const SizedBox(height: 10)],
- ],
- );
- }
-}
diff --git a/desktop/lib/settings/sections/devices_section.dart b/desktop/lib/settings/sections/devices_section.dart
deleted file mode 100644
index 45e72d78c..000000000
--- a/desktop/lib/settings/sections/devices_section.dart
+++ /dev/null
@@ -1,516 +0,0 @@
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:harness/shared/theme/app_icons.dart';
-import 'package:flutter/material.dart';
-import 'package:url_launcher/url_launcher.dart';
-
-import '../../autonomous_device/autonomous_device_cli.dart';
-import '../../core/test_run.dart';
-import '../../shared/widgets/app_dialog.dart';
-import '../../shared/widgets/app_icon_button.dart';
-import '../../shared/widgets/app_select_field.dart';
-import '../../shared/widgets/labeled_field.dart';
-import '../../shared/widgets/setting_row.dart';
-import '../../shared/widgets/skeleton.dart';
-import '../../shared/theme/app_theme.dart' as grid;
-import '../../shared/widgets/section_scaffold.dart';
-import '../../state/dial_status.dart';
-import 'cabled_device_card.dart';
-
-class DevicesSection extends StatefulWidget {
- const DevicesSection({
- super.key,
- this.cli,
- this.dial,
- this.onDeviceSettings,
- this.onLocalNetworkBlocked,
- this.showCompanion = false,
- });
-
- /// Discovery found the local network refused: the app restarts a daemon it
- /// did not launch so it gets the app's permission (AppNotifier.localNetworkBlocked).
- final Future<void> Function()? onLocalNetworkBlocked;
- final bool showCompanion;
- final AutonomousDeviceCli? cli;
-
- /// The robots on a cable at THIS desk. Null in a build with no daemon behind it (and in the tests
- /// that drive only the paired half of this pane).
- final DialState? dial;
-
- /// Send one robot a settings patch. See AppNotifier.setDeviceSettings.
- final void Function(String id, Map<String, Object?> patch)? onDeviceSettings;
- @override
- State<DevicesSection> createState() => _DevicesSectionState();
-}
-
-class _DevicesSectionState extends State<DevicesSection> {
- late final AutonomousDeviceCli _cli = widget.cli ?? AutonomousDeviceCli();
- Timer? _timer;
- final _code = TextEditingController();
- bool _loading = true;
- bool _busy = false;
- bool _refreshing = false;
- int _generation = 0;
- bool _unsupported = false;
- bool _networkBlocked = false;
- String? _error;
- String? _actionError;
- String? _selectedDevice;
- List<Map<String, dynamic>> _discovered = [];
- Map<String, dynamic> _status = {};
- List<Map<String, dynamic>> _devices = [];
- bool get _controlsDisabled =>
- _busy || _loading || (kUnderTest && widget.cli == null);
-
- @override
- void initState() {
- super.initState();
- if (kUnderTest && widget.cli == null) {
- _loading = false;
- return;
- }
- unawaited(_refresh());
- }
-
- void _scheduleRefresh() {
- _timer?.cancel();
- // Tests may inject a fake for the initial fetch and user actions, but must
- // never start a background clock or invoke a real CLI.
- if (!mounted || kUnderTest || _unsupported || _busy) return;
- _timer = Timer(const Duration(seconds: 60), () {
- unawaited(_refresh());
- });
- }
-
- @override
- void dispose() {
- _timer?.cancel();
- _code.dispose();
- // Leaving the screen does not revoke trust or stop the daemon.
- super.dispose();
- }
-
- void _failed(Object error) {
- _error = error is AutonomousDeviceCliException
- ? error.userMessage
- : 'Could not reach the Harness CLI.';
- if (error is AutonomousDeviceCliException && error.unsupported) {
- _unsupported = true;
- }
- }
-
- /// A refused local network loses discovery only: paired robots still list, and the
- /// notice says where to allow it instead of "no robots found".
- Future<Map<String, dynamic>> _discoverOrBlocked() async {
- try {
- return await _cli.discover();
- } on AutonomousDeviceCliException catch (error) {
- if (!error.localNetworkBlocked) rethrow;
- if (widget.onLocalNetworkBlocked case final restart?) {
- await restart();
- try {
- return await _cli.discover();
- } on AutonomousDeviceCliException catch (again) {
- if (!again.localNetworkBlocked) rethrow;
- }
- }
- return {'devices': const [], 'localNetworkBlocked': true};
- }
- }
-
- void _openLocalNetworkSettings() => unawaited(
- launchUrl(
- Uri.parse(
- 'x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork',
- ),
- ),
- );
-
- Future<void> _refresh() async {
- if (_refreshing || (kUnderTest && widget.cli == null)) return;
- _refreshing = true;
- final generation = _generation;
- try {
- final status = await _cli.status();
- final results = await Future.wait([_cli.list(), _discoverOrBlocked()]);
- if (!mounted || generation != _generation) return;
- final devices = <Map<String, dynamic>>[
- for (final row in results[0]['devices'] as List? ?? [])
- if (row is Map<String, dynamic>) row,
- ];
- final discovered = <Map<String, dynamic>>[
- for (final row in results[1]['devices'] as List? ?? [])
- if (row is Map<String, dynamic> &&
- row['id'] is String &&
- (row['id'] as String).isNotEmpty)
- row,
- ];
- final networkBlocked = results[1]['localNetworkBlocked'] == true;
- if (_selectedDevice != null &&
- !discovered.any((device) => device['id'] == _selectedDevice)) {
- _selectedDevice = null;
- _code.clear();
- }
- if (_loading ||
- _unsupported ||
- _error != null ||
- networkBlocked != _networkBlocked ||
- jsonEncode([status, devices, discovered]) !=
- jsonEncode([_status, _devices, _discovered])) {
- setState(() {
- _status = status;
- _devices = devices;
- _discovered = discovered;
- _networkBlocked = networkBlocked;
- _loading = false;
- _unsupported = false;
- _error = null;
- });
- }
- } catch (error) {
- if (mounted && generation == _generation) {
- setState(() {
- _failed(error);
- _loading = false;
- });
- }
- } finally {
- _refreshing = false;
- _scheduleRefresh();
- }
- }
-
- Future<bool> _confirm(String title, String detail, String action) async =>
- await showAppDialog<bool>(
- context: context,
- builder: (context) => AlertDialog(
- title: Text(title),
- content: SizedBox(
- width: 360,
- child: Text(detail, style: grid.AppType.body(height: 1.4)),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context, false),
- style: TextButton.styleFrom(
- foregroundColor: grid.AppPalette.textSecondary,
- overlayColor: grid.AppSurface.hoverFill,
- ),
- child: const Text('Cancel'),
- ),
- FilledButton(
- key: const Key('device-confirm'),
- style: FilledButton.styleFrom(
- backgroundColor: grid.AppPalette.dangerFill,
- overlayColor: const Color(0x1FFFFFFF),
- ),
- onPressed: () => Navigator.pop(context, true),
- child: Text(action),
- ),
- ],
- ),
- ) ??
- false;
-
- Future<void> _act(Future<void> Function() action) async {
- if (_busy || (kUnderTest && widget.cli == null)) return;
- _timer?.cancel();
- // A poll begun before this mutation must not overwrite its newer response.
- _generation++;
- setState(() {
- _busy = true;
- _error = null;
- _actionError = null;
- });
- try {
- await action();
- } catch (error) {
- if (mounted) {
- setState(
- () => _actionError = error is AutonomousDeviceCliException
- ? error.userMessage
- : 'Could not reach the Harness CLI.',
- );
- }
- } finally {
- if (mounted) setState(() => _busy = false);
- _scheduleRefresh();
- }
- }
-
- Future<void> _submitCode() async {
- final deviceId = _selectedDevice;
- final code = normalizeAutonomousDeviceCode(_code.text);
- if (_busy) return;
- if (deviceId == null ||
- !_discovered.any((device) => device['id'] == deviceId)) {
- setState(
- () => _actionError = 'Select your discovered Autonomous robot first.',
- );
- return;
- }
- if (!RegExp(r'^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{6}$').hasMatch(code)) {
- setState(
- () => _actionError =
- 'Enter the six-character code shown on your Autonomous robot.',
- );
- return;
- }
- await _act(() async {
- _code.clear();
- // The daemon resolves this selected discovery identity, never a UI address.
- await _cli.pair(code: code, deviceId: deviceId);
- if (mounted) {
- setState(() => _selectedDevice = null);
- // The pair response and the list row carry the same identity; reading
- // the list keeps one source for what is paired.
- final devices = await _cli.list();
- if (mounted) {
- setState(
- () => _devices = [
- for (final row in devices['devices'] as List? ?? [])
- if (row is Map<String, dynamic>) row,
- ],
- );
- }
- }
- });
- }
-
- Future<void> _revoke(Map<String, dynamic> device) async {
- if (!await _confirm(
- 'Revoke Autonomous robot?',
- 'Disconnect ${device['label'] ?? 'this Autonomous robot'} and remove its access to this computer. '
- 'It will need to pair again.',
- 'Revoke Autonomous robot',
- )) {
- return;
- }
- if (!mounted) return;
- await _act(() async {
- await _cli.revoke(device['id'] as String);
- await _refresh();
- });
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final disabled = _controlsDisabled;
- Widget action(String label, VoidCallback? onPressed) => SizedBox(
- width: SettingRow.controlWidth,
- child: OutlinedButton(onPressed: onPressed, child: Text(label)),
- );
- return SectionScaffold(
- title: 'Autonomous robots',
- subtitle: 'Connect directly to your Autonomous robot.',
- child: SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- // The robot on the cable comes first: it is the one on the desk, and it is the only one
- // whose settings this pane owns. Everything below it is paired over the network.
- if (widget.dial case final dial?)
- ListenableBuilder(
- listenable: dial,
- builder: (context, _) => CabledDeviceCard(
- devices: dial.devices,
- showCompanion: widget.showCompanion,
- onChanged: widget.onDeviceSettings ?? (_, _) {},
- ),
- ),
- if (_loading)
- SkeletonBlock(
- child: Container(
- decoration: BoxDecoration(
- color: grid.AppGlass.surfaceFill,
- borderRadius: BorderRadius.circular(14),
- boxShadow: grid.AppGlass.cardShadow,
- ),
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 12,
- ),
- child: const SkeletonListTile(
- leading: 0,
- padding: EdgeInsets.zero,
- ),
- ),
- ),
- if (_unsupported)
- SettingRow(
- title: 'Update Harness CLI to use Autonomous robots.',
- detail: 'Run this command in Terminal, then refresh this page.',
- control: SizedBox(
- width: SettingRow.controlWidth,
- child: Row(
- children: [
- const Expanded(child: SelectableText('harness update')),
- AppIconButton(
- icon: AppIcons.refreshCw,
- tooltip: 'Refresh Autonomous robot status',
- onPressed: disabled
- ? null
- : () => unawaited(_refresh()),
- ),
- ],
- ),
- ),
- ),
- if ((_actionError != null || _error != null) && !_unsupported)
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 12),
- child: Text(
- _actionError ?? _error!,
- style: grid.AppType.body(
- color: Theme.of(context).colorScheme.error,
- ),
- ),
- ),
- if (!_unsupported && !_loading) ...[
- if (_networkBlocked) ...[
- SettingRow(
- key: const Key('autonomous-device-network-blocked'),
- title: 'Allow Harness on your local network',
- alignTop: true,
- detail:
- 'macOS is blocking Harness from your local network, so it can’t find Autonomous robots. '
- 'Turn on Harness in Privacy & Security › Local Network, then refresh.',
- control: Platform.isMacOS
- ? action(
- 'Open Settings',
- disabled ? null : _openLocalNetworkSettings,
- )
- : const SizedBox.shrink(),
- ),
- const SizedBox(height: 10),
- ],
- for (final device in _devices) ...[
- SettingRow(
- title: device['label']?.toString() ?? 'Autonomous robot',
- // The fingerprint belongs to the device it identifies, not to
- // a row of its own two lines below it.
- detail: [
- device['pendingFirstSession'] == true
- ? 'Waiting for first connection'
- : device['online'] == true
- ? 'Connected'
- : 'Paired · Offline',
- ?device['fingerprint']?.toString(),
- ].join(' · '),
- control: action(
- 'Revoke',
- disabled || device['id'] is! String
- ? null
- : () => _revoke(device),
- ),
- ),
- const SizedBox(height: 10),
- ],
- SettingRow(
- // The CLI's pair store is a map with no cap, so a paired device
- // is never replaced by the next one — say which act this is.
- title: _devices.isEmpty
- ? 'Pair a device'
- : 'Pair another device',
- alignTop: true,
- detail: _networkBlocked
- ? 'Allow local network access above to find your robot.'
- : _discovered.isEmpty
- ? 'No Autonomous robots found. Keep your device on the same network, then refresh.'
- : 'Select your device and enter its six-character code. Separators are allowed, for example ABC-123.',
- control: SizedBox(
- width: SettingRow.controlWidth,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Row(
- children: [
- Expanded(
- child: ExcludeFocus(
- excluding: disabled,
- child: IgnorePointer(
- ignoring: disabled,
- child: AppSelectField<String?>(
- key: const Key('autonomous-device-selection'),
- semanticLabel: 'Autonomous robot',
- value: _selectedDevice,
- options: [
- const SelectOption<String?>(
- value: null,
- label: 'Select a device',
- ),
- for (final device in _discovered)
- SelectOption<String?>(
- value: device['id'] as String,
- label:
- device['name']?.toString() ??
- 'Autonomous robot',
- ),
- ],
- onChanged: (value) {
- if (_controlsDisabled) return;
- setState(() {
- _selectedDevice = value;
- _code.clear();
- _actionError = null;
- });
- },
- ),
- ),
- ),
- ),
- const SizedBox(width: 8),
- AppIconButton(
- icon: AppIcons.refreshCw,
- tooltip: 'Refresh Autonomous robot status',
- onPressed: disabled
- ? null
- : () => unawaited(_refresh()),
- ),
- ],
- ),
- const SizedBox(height: 10),
- TextField(
- key: const Key('autonomous-device-code'),
- controller: _code,
- enabled: !disabled,
- maxLength: 32,
- obscureText: true,
- autocorrect: false,
- enableSuggestions: false,
- style: grid.AppType.mono(
- color: grid.AppPalette.textPrimary,
- ),
- decoration: labeledFieldDecoration(
- 'Six-character code',
- fill: grid.AppCard.inset,
- ).copyWith(counterText: ''),
- onSubmitted: (_) => unawaited(_submitCode()),
- ),
- const SizedBox(height: 10),
- action(
- _busy ? 'Pairing…' : 'Pair',
- disabled ? null : () => unawaited(_submitCode()),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 10),
- Text(
- 'Harness CLI keeps the connection running when you close Desktop.',
- style: grid.AppType.body(color: grid.AppPalette.textSecondary),
- ),
- const SizedBox(height: 10),
- ],
- const SizedBox(height: 8),
- ],
- ),
- ),
- );
- }
-}
diff --git a/desktop/lib/settings/sections/profiles_section.dart b/desktop/lib/settings/sections/profiles_section.dart
deleted file mode 100644
index 93cf8fd9e..000000000
--- a/desktop/lib/settings/sections/profiles_section.dart
+++ /dev/null
@@ -1,104 +0,0 @@
-import 'package:flutter/material.dart';
-
-import '../../core/models.dart';
-import '../../shared/widgets/section_scaffold.dart';
-import '../../shared/widgets/setting_row.dart';
-import '../../state/app_state.dart';
-
-/// One login, several computers. The account desk still holds every tab.
-/// This window draws all of them, or only the computer named here.
-class ProfilesSection extends StatelessWidget {
- const ProfilesSection({super.key, required this.notifier});
-
- final AppNotifier notifier;
-
- @override
- Widget build(BuildContext context) => ListenableBuilder(
- listenable: notifier,
- builder: (context, _) {
- final selected = notifier.machineProfileId;
- final localId = notifier.localMachineState?.machine.machineId;
- final machines = notifier.machines;
- final names = <String, int>{};
- for (final machine in machines) {
- names[machine.displayName] = (names[machine.displayName] ?? 0) + 1;
- }
- return SectionScaffold(
- title: 'Profiles',
- subtitle:
- 'One sign-in. Choose a computer to show only that computer\'s tabs. All machines keeps the shared desk.',
- child: SingleChildScrollView(
- child: Column(
- children: [
- SettingRow(
- title: 'All machines',
- detail: 'Every tab on this account, whichever computer it runs on.',
- control: _choice(
- selected: selected == null,
- onPressed: () => notifier.setMachineProfile(null),
- ),
- ),
- for (final machine in machines)
- SettingRow(
- title: machine.displayName,
- detail: _detail(
- machine,
- localId: localId,
- sharedName: (names[machine.displayName] ?? 0) > 1,
- unavailable: _unavailable(machine),
- ),
- control: _choice(
- selected: selected == machine.machineId,
- // A computer this window cannot reach has no live tabs to
- // narrow down to, so it cannot be chosen until it is back.
- // One already chosen stays shown.
- onPressed: _unavailable(machine) == null
- ? () => notifier.setMachineProfile(machine.machineId)
- : null,
- ),
- ),
- ],
- ),
- ),
- );
- },
- );
-
- /// Why [machine] cannot be chosen right now, or null when it can: this
- /// window has no live connection to it, it has to be linked again, or it
- /// reports itself offline.
- String? _unavailable(Machine machine) {
- final state = notifier.stateOf(machine.machineId);
- if (state == null || state.needsLink) return 'Not connected.';
- if (state.nodeOnline == false) return 'Offline.';
- if (state.connectionStatus != ConnectionStatus.connected) {
- return 'Not connected.';
- }
- return null;
- }
-
- String _detail(
- Machine machine, {
- String? localId,
- required bool sharedName,
- String? unavailable,
- }) {
- final where = machine.machineId == localId
- ? 'This computer. Tabs whose agents are all here.'
- : 'That computer. Tabs whose agents are all there.';
- final short = machine.machineId.length > 8
- ? machine.machineId.substring(0, 8)
- : machine.machineId;
- final named = sharedName ? '$where ($short)' : where;
- return unavailable == null ? named : '$unavailable $named';
- }
-
- /// [onPressed] null is a machine that cannot be chosen now: the button is
- /// disabled. A chosen one reads Showing, and is disabled for being chosen.
- Widget _choice({required bool selected, required VoidCallback? onPressed}) {
- return OutlinedButton(
- onPressed: selected ? null : onPressed,
- child: Text(selected ? 'Showing' : 'Show'),
- );
- }
-}
diff --git a/desktop/lib/settings/settings_body.dart b/desktop/lib/settings/settings_body.dart
index e1634a528..bc3b46869 100644
--- a/desktop/lib/settings/settings_body.dart
+++ b/desktop/lib/settings/settings_body.dart
@@ -1,14 +1,13 @@
import 'package:flutter/material.dart';
import '../state/app_state.dart';
+import 'agent_settings.dart';
import 'experimental_features.dart';
import 'sections/about_section.dart';
-import 'sections/account_devices_section.dart';
import 'sections/account_section.dart';
+import 'sections/agents_section.dart';
import 'sections/connectors_section.dart';
-import 'sections/profiles_section.dart';
import 'sections/debug_section.dart';
-import 'sections/devices_section.dart';
import 'sections/experimental_section.dart';
import 'sections/notifications_section.dart';
import 'sections/shortcuts_section.dart';
@@ -24,6 +23,7 @@ class SettingsBody extends StatelessWidget {
super.key,
required this.section,
required this.notifier,
+ required this.agentSettings,
this.experimentalFeatures,
});
@@ -31,14 +31,14 @@ class SettingsBody extends StatelessWidget {
final AppNotifier notifier;
final ExperimentalFeaturesStore? experimentalFeatures;
+ /// Settings ▸ Agents, held by the screen so leaving the page does not lose a save under way.
+ final AgentSettingsStore agentSettings;
+
@override
Widget build(BuildContext context) {
final screen = switch (section) {
SettingsSection.account => AccountSection(notifier: notifier),
- SettingsSection.accountDevices => AccountDevicesSection(
- notifier: notifier,
- ),
- SettingsSection.profiles => ProfilesSection(notifier: notifier),
+ SettingsSection.agents => AgentsSection(store: agentSettings),
SettingsSection.usage => const UsageSection(),
SettingsSection.connectors => ConnectorsSection(notifier: notifier),
SettingsSection.customize => throw StateError(
@@ -49,16 +49,6 @@ class SettingsBody extends StatelessWidget {
store: experimentalFeatures ?? notifier.experimentalFeatures,
openCodingMemory: notifier.openCodingMemoryConnection,
),
- SettingsSection.devices => ListenableBuilder(
- listenable: experimentalFeatures ?? notifier.experimentalFeatures,
- builder: (context, _) => DevicesSection(
- dial: notifier.dial,
- onDeviceSettings: notifier.setDeviceSettings,
- onLocalNetworkBlocked: notifier.localNetworkBlocked,
- showCompanion: (experimentalFeatures ?? notifier.experimentalFeatures)
- .enabled(ExperimentalFeature.focusBarCreature),
- ),
- ),
SettingsSection.shortcuts => const ShortcutsSection(),
SettingsSection.debug => const DebugSection(),
SettingsSection.about => AboutSection(notifier: notifier),
diff --git a/desktop/lib/settings/settings_nav.dart b/desktop/lib/settings/settings_nav.dart
index 582e93a64..ae2d01942 100644
--- a/desktop/lib/settings/settings_nav.dart
+++ b/desktop/lib/settings/settings_nav.dart
@@ -171,7 +171,10 @@ class _SettingsNavState extends State<SettingsNav> {
padding: const EdgeInsets.only(bottom: 10),
children: [
for (final group in visible) ...[
- RailSectionHeader(label: group.title),
+ if (group.title.isNotEmpty)
+ RailSectionHeader(label: group.title)
+ else if (group != visible.first)
+ const SizedBox(height: 8),
for (final target in group.sections)
SidebarItem(
icon: target.icon,
diff --git a/desktop/lib/settings/settings_screen.dart b/desktop/lib/settings/settings_screen.dart
index b4f96b75f..af8ac6c5e 100644
--- a/desktop/lib/settings/settings_screen.dart
+++ b/desktop/lib/settings/settings_screen.dart
@@ -3,7 +3,9 @@ import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
+import '../core/viewer_mode.dart';
import '../widgets/harness_customize_pane.dart';
+import 'agent_settings.dart';
import 'experimental_features.dart';
import 'settings_body.dart';
import 'settings_compact.dart';
@@ -69,6 +71,7 @@ class SettingsScreen extends StatefulWidget {
this.experimentalFeatures,
this.source = 'unknown',
this.compactBelow = 0,
+ this.agentSettings,
}) : assert(
initialSection != SettingsSection.customize,
'Open workspace actions through showSettingsScreen.',
@@ -91,6 +94,9 @@ class SettingsScreen extends StatefulWidget {
/// screen instead of sitting side by side.
final double compactBelow;
+ /// Settings ▸ Agents' store. Null reads this computer's daemon (tests pass a fake).
+ final AgentSettingsStore? agentSettings;
+
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
@@ -103,6 +109,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
/// a named section starts there; otherwise the list comes first.
late bool _sectionOpen = widget.initialSection != null;
+ /// A browser has no daemon of its own to keep what agents may do: that is each computer's.
+ late final AgentSettingsStore _agentSettings =
+ widget.agentSettings ??
+ (kViewerMode
+ ? AgentSettingsStore(
+ unavailable: 'Agents run on your computers: change this in the Harness app on each one.',
+ )
+ : AgentSettingsStore.api(widget.notifier.api));
+
+ @override
+ void dispose() {
+ if (widget.agentSettings == null) _agentSettings.dispose();
+ super.dispose();
+ }
+
bool get _compact => MediaQuery.sizeOf(context).width < widget.compactBelow;
KeyEventResult _key(FocusNode node, KeyEvent event) {
@@ -149,6 +170,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
section: _section,
notifier: widget.notifier,
experimentalFeatures: widget.experimentalFeatures,
+ agentSettings: _agentSettings,
);
if (_compact) {
return SettingsCompactScreen(
diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dart
index 0d7aa26ca..ca27fc61c 100644
--- a/desktop/lib/settings/settings_section.dart
+++ b/desktop/lib/settings/settings_section.dart
@@ -4,25 +4,28 @@ import 'package:flutter/foundation.dart' show kIsWeb;
import '../logging/debug_surface.dart';
-/// A Settings navigation entry. Customize returns to the workspace and opens
-/// its side panel; the other entries select a Settings page.
+/// A Settings navigation entry. Appearance ([customize]) returns to the workspace and opens its
+/// side panel, Customize Harness; the other entries select a Settings page.
+///
+/// Settings holds settings only. What is a thing rather than a setting lives where the thing is:
+/// the Autonomous robots in the Devices tab, the account's computers, phones and apps — and which
+/// of them this window shows — in Machines.
///
/// Declared once, like [ShortcutAction] in `shortcuts/app_shortcuts.dart`: the
/// rail, the search filter and the pane all read this list, so a section cannot
/// be listed without a screen behind it or reachable without a row.
enum SettingsSection {
account(AppIcons.user, 'Account'),
- accountDevices(AppIcons.shieldCheck, 'Your devices'),
- profiles(AppIcons.monitor, 'Profiles'),
- usage(AppIcons.chartNoAxesColumn, 'Usage'),
- connectors(AppIcons.plug, 'Connectors'),
- customize(AppIcons.palette, 'Customize'),
+ // Named `customize` still: the command palette remembers `settings:customize`.
+ customize(AppIcons.palette, 'Appearance'),
notifications(AppIcons.bell, 'Notifications'),
- experimental(AppIcons.flaskConical, 'Experimental'),
- devices(AppIcons.zap, 'Autonomous robots'),
shortcuts(AppIcons.keyboard, 'Keyboard shortcuts'),
- debug(AppIcons.bug, 'Debug'),
- about(AppIcons.info, 'About');
+ agents(AppIcons.bot, 'Agents'),
+ connectors(AppIcons.plug, 'Connectors'),
+ usage(AppIcons.chartNoAxesColumn, 'Usage'),
+ experimental(AppIcons.flaskConical, 'Experimental'),
+ about(AppIcons.info, 'About'),
+ debug(AppIcons.bug, 'Debug');
const SettingsSection(this.icon, this.label);
@@ -35,12 +38,13 @@ enum SettingsSection {
/// One labelled run of rows in the settings rail.
///
/// The grouping is presentation only — [settingsGroups] flattens back to every
-/// section — but it says something true: the first run is what you *change*,
-/// the second is what you *consult*.
+/// section — but it says something true: who is signed in, how the app behaves,
+/// what agents may do, what is still taking shape, and what to consult.
class SettingsGroup {
const SettingsGroup(this.title, this.sections);
- /// The caption over the run. A caption, not a sentence.
+ /// The caption over the run. A caption, not a sentence; empty for a run that needs none
+ /// (Account, alone at the top).
final String title;
final List<SettingsSection> sections;
}
@@ -65,8 +69,8 @@ List<SettingsGroup> get settingsGroups =>
@visibleForTesting
List<SettingsGroup> settingsGroupsFor({required bool debugSurface}) {
bool visible(SettingsSection section) =>
- // This computer's own: the Autonomous robots and the services its agents use.
- (!kIsWeb || (section != SettingsSection.devices && section != SettingsSection.connectors)) &&
+ // This computer's own: the services its agents use.
+ (!kIsWeb || section != SettingsSection.connectors) &&
(debugSurface || !_kDeveloperSections.contains(section));
return [
for (final group in _kSettingsGroups)
@@ -83,35 +87,27 @@ List<SettingsGroup> settingsGroupsFor({required bool debugSurface}) {
const _kDeveloperSections = {SettingsSection.debug};
const _kSettingsGroups = [
- // Usage sits with the preferences rather than with Debug, which it
- // otherwise resembles: that is developer furniture a shipped build
- // hides, and this is a screen anybody is meant to open. It earns its place in
- // a run titled "what you change" by carrying the three switches that decide
- // which logs are read at all — the pane is off until somebody sets it.
- SettingsGroup('Preferences', [
- SettingsSection.usage,
+ // Who is signed in, first and alone: Settings opens on it.
+ SettingsGroup('', [SettingsSection.account]),
+ SettingsGroup('General', [
SettingsSection.customize,
- // Beside Customize because it is the same kind of decision — how this Mac behaves while you
- // work — and NOT inside it, which is where the alert switch started. Customize is about how
- // the app looks; a sound is not a look, and somebody turning one off does not think to look
- // under Appearance for it.
+ // Beside Appearance because it is the same kind of decision — how this Mac behaves while you
+ // work — and NOT inside it, which is where the alert switch started. A sound is not a look,
+ // and somebody turning one off does not think to look under Appearance for it.
SettingsSection.notifications,
- SettingsSection.experimental,
- SettingsSection.devices,
+ SettingsSection.shortcuts,
+ ]),
+ SettingsGroup('Agents', [
+ SettingsSection.agents,
// The services this computer's agents use (Linear, Notion, GitHub…), connected once for all of them.
SettingsSection.connectors,
- SettingsSection.account,
- // Beside Account: the devices signed in to it, each trusted by the others because of that.
- SettingsSection.accountDevices,
- SettingsSection.profiles,
- ]),
- // Debug sits between the two things it is most often reached from: the keys
- // that open it, and the version a report has to name.
- SettingsGroup('Help', [
- SettingsSection.shortcuts,
- SettingsSection.debug,
- SettingsSection.about,
+ // What the agents on this machine have spent. It carries the switches that decide which logs
+ // are read at all — the pane is off until somebody sets it.
+ SettingsSection.usage,
]),
+ SettingsGroup('Labs', [SettingsSection.experimental]),
+ // Debug, in builds that have it, beside the version a report has to name.
+ SettingsGroup('Help', [SettingsSection.about, SettingsSection.debug]),
];
/// The section Settings opens on — the first row of the first group, so the
diff --git a/desktop/lib/shared/widgets/fingerprint_text.dart b/desktop/lib/shared/widgets/fingerprint_text.dart
index 52f6666d1..eb159e138 100644
--- a/desktop/lib/shared/widgets/fingerprint_text.dart
+++ b/desktop/lib/shared/widgets/fingerprint_text.dart
@@ -14,9 +14,10 @@ String fingerprintSpoken(String fingerprint) =>
/// How to check a key code, shown under it in a device's detail. [computer] adds the CLI route, which
/// only a computer has.
String fingerprintHowToCompare({required bool computer}) => computer
- ? 'This device’s own key code. Open Your devices on that computer — the code under “This device” '
+ ? 'This device’s own key code. Open Machines on that computer — the code shown for that computer '
'must match — or run harness status on it.'
- : 'This device’s own key code. Open Your devices on that device — the code under “This device” must match.';
+ : 'This device’s own key code. Open Your devices on a phone, or Machines in a browser — the code shown '
+ 'for “This device” must match.';
/// A key code (`E2FB·0DF5·5FD8·E6C7`) set in mono, selectable, with a Copy button.
///
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f018ae7fd..9ce00cf10 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -602,6 +602,10 @@ class _AgentStop {
/// machine answering its agent list, a push, the dial turning, a handoff.
enum AttachIntent { person, automatic }
+/// Machines asked for from outside the workspace ([AppNotifier.requestMachines]): the device to
+/// select there, or the first phone or app.
+typedef MachinesRequest = ({String? devicePub, bool phones});
+
class AppNotifier extends ChangeNotifier {
final AuthSession session;
@@ -4057,6 +4061,27 @@ class AppNotifier extends ChangeNotifier {
/// another connected machine and suppresses its automatic startup picker.
String? get requestedMachineLink => _requestedMachineLink;
+ MachinesRequest? _machinesRequest;
+
+ /// Machines was asked for from outside the workspace — a device band, the review line under a
+ /// password prompt — and the workspace has not opened it yet.
+ MachinesRequest? get machinesRequest => _machinesRequest;
+
+ /// Opens Machines, where the account's computers, phones and apps are listed: [devicePub] selects
+ /// that device, [phones] the first phone or app.
+ void requestMachines({String? devicePub, bool phones = false}) {
+ if (_disposed) return;
+ _machinesRequest = (devicePub: devicePub, phones: phones);
+ notifyListeners();
+ }
+
+ /// The workspace takes the request it is about to open.
+ MachinesRequest? takeMachinesRequest() {
+ final request = _machinesRequest;
+ _machinesRequest = null;
+ return request;
+ }
+
void acknowledgeMachineLinkRequest(String machineId) {
if (_requestedMachineLink == machineId) _requestedMachineLink = null;
}
@@ -7667,7 +7692,7 @@ class AppNotifier extends ChangeNotifier {
bool get baselineSeenLocally => _baselineSeenLocally;
/// Viewer builds only: this app's copy of the device log is frozen, so it pins no machine from it
- /// until someone reviews the list (Settings ▸ Your devices). A machine asking for its password says so.
+ /// until someone reviews the list (Machines). A machine asking for its password says so.
bool get deviceListNeedsReview => _deviceListFrozen;
bool _deviceListFrozen = false;
@@ -7850,8 +7875,7 @@ class AppNotifier extends ChangeNotifier {
systemNotifications.postNotice(
id: 'harness-device:${notice.pub}',
title: 'New device on your account',
- body:
- '${notice.sentence} Not yours? Remove it in Settings ▸ Your devices.',
+ body: '${notice.sentence} Not yours? Remove it in Machines.',
devicePub: notice.pub,
);
notifyListeners();
@@ -8164,6 +8188,11 @@ class AppNotifier extends ChangeNotifier {
await services.keys.forgetIdentity();
}
+ /// Whether the account's device list can be read from here: through this app's own copy of the
+ /// log (a viewer build), or through this computer's daemon once the app is connected to it. Not
+ /// before — and never from a test, which has neither and must not dial for one.
+ bool get accountDevicesReadable => _deviceLog != null || _pool != null;
+
/// The account's devices, from whichever end verified the log. Null when it cannot be read.
///
/// [onListed] hears the banner's devices the moment the listing is read — before the last-seen
diff --git a/desktop/lib/state/machine_devices.dart b/desktop/lib/state/machine_devices.dart
new file mode 100644
index 000000000..b3b26c0e4
--- /dev/null
+++ b/desktop/lib/state/machine_devices.dart
@@ -0,0 +1,338 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/relative_time.dart';
+import 'account_devices.dart';
+import 'app_state.dart';
+
+/// What "Trust again" says when the list it would trust is another account's than the one signed in to.
+const otherAccountMessage =
+ 'The device list now belongs to a different account than the one you signed in with. '
+ 'Sign in again to switch accounts.';
+
+/// Asks the person one yes/no question: [title], [detail], and the confirming [action]. True only on
+/// the confirming button.
+typedef DeviceConfirm = Future<bool> Function(
+ String title,
+ String detail,
+ String action,
+);
+
+/// The account's devices as the Machines picker lists them: every computer and app signed in to the
+/// account. Signing in on one is what makes the others trust it (the device key log), so this is also
+/// the one place to see a device that is not yours, and to take it out.
+///
+/// One per picker visit, read when it opens and again whenever the account's devices change
+/// ([AppNotifier.devicesRevision]). Computers are matched to the machines they are by machine id;
+/// phones, browsers and a signed-in computer with no machine record are rows of their own.
+class MachineDevices extends ChangeNotifier {
+ MachineDevices(this.app);
+
+ final AppNotifier app;
+
+ AccountDevices? devices;
+ bool loaded = false;
+
+ /// Bumped on every read that lands, so a row built from the last one knows it is stale.
+ int stamp = 0;
+ int _revision = -1;
+ bool _started = false, _disposed = false, _reading = false, _again = false;
+
+ /// Whether the first read marks the devices it shows as seen. True when the person opened
+ /// Machines; false when the picker opened on its own (a machine asking to be linked), which nobody
+ /// chose to look at.
+ bool markSeen = true;
+ bool _marked = false;
+
+ /// The devices that were new when the list opened: they keep their `New` mark for the visit, though
+ /// opening the list clears the banner that announced them.
+ final Set<String> newPubs = {};
+ final Set<String> removing = {};
+ bool removingUnused = false;
+ String? error;
+
+ /// The error is a state to review again (another account, a list that changed), not a failure: amber.
+ bool errorIsNotice = false;
+
+ /// "Got it" was pressed on the baseline notice: hidden at once, whatever the write takes.
+ bool baselineDone = false;
+
+ void start() {
+ if (_started || _disposed) return;
+ _started = true;
+ newPubs.addAll(app.newDevices.map((d) => d.pub));
+ app.addListener(_appChanged);
+ unawaited(load());
+ }
+
+ void _appChanged() {
+ if (app.devicesRevision != _revision) unawaited(load());
+ }
+
+ void _changed() {
+ if (!_disposed) notifyListeners();
+ }
+
+ Future<void> load() async {
+ if (_disposed) return;
+ if (_reading) {
+ _again = true;
+ return;
+ }
+ _reading = true;
+ _revision = app.devicesRevision;
+ List<String>? banner;
+ AccountDevices? next;
+ var read = false;
+ try {
+ if (app.accountDevicesReadable) {
+ next = await app.loadDevices(onListed: (b) => banner = b);
+ read = true;
+ }
+ } catch (_) {
+ next = null;
+ }
+ _reading = false;
+ if (_disposed) return;
+ devices = next;
+ loaded = true;
+ stamp++;
+ // What the log kept as new (it outlives the banner and a restart) is marked alongside the
+ // banner's — on every read, so a device that turns up while the list is open is marked too.
+ if (next != null) newPubs.addAll(next.pending);
+ newPubs.addAll(app.newDevices.map((d) => d.pub));
+ _changed();
+ // Looking at the list IS reviewing the new devices: the banner that pointed here is done. After
+ // the first read that answered, so the pending keys are in [newPubs] before they are marked seen.
+ if (read && next != null && markSeen && !_marked) {
+ _marked = true;
+ app.seenNewDevices(
+ pending: next.pending,
+ shown: banner,
+ departed: next.departed,
+ );
+ }
+ if (_again) {
+ _again = false;
+ unawaited(load());
+ }
+ }
+
+ AccountDevice? get self => devices?.self;
+
+ /// The account's key for the machine [machineId], when it has one.
+ AccountDevice? forMachine(String machineId) {
+ if (machineId.isEmpty) return null;
+ for (final d in devices?.devices ?? const <AccountDevice>[]) {
+ if (d.isMachine && d.machineId == machineId) return d;
+ }
+ return null;
+ }
+
+ AccountDevice? byPub(String pub) {
+ for (final d in devices?.devices ?? const <AccountDevice>[]) {
+ if (d.pub == pub) return d;
+ }
+ return null;
+ }
+
+ /// Every device the picker lists as a row of its own, in the list's order (new first, then by
+ /// activity): phones and browsers, and computers whose id is none of [machineIds] — signed in, but
+ /// with no machine record. This device first when it is one of them.
+ List<AccountDevice> rows(Set<String> machineIds) {
+ final list = devices;
+ if (list == null) return const [];
+ bool own(AccountDevice d) =>
+ !d.isMachine || !machineIds.contains(d.machineId);
+ return [
+ if (list.self case final self? when own(self)) self,
+ for (final d in list.listed(newPubs))
+ if (own(d)) d,
+ ];
+ }
+
+ bool isNew(AccountDevice d) => newPubs.contains(d.pub) || d.pending;
+
+ /// What the row under the device's name says: `App · active now`, `Computer · added 2 days ago`, and
+ /// whether it is this one, new or suspended.
+ String detail(AccountDevice d, {DateTime? now}) => [
+ deviceDetailLine(
+ d,
+ now: now ?? DateTime.now(),
+ sameName: devices?.sharedNames.contains(d.label.trim()) ?? false,
+ ),
+ if (d.self) 'This device',
+ if (d.suspended) 'Suspended' else if (isNew(d)) 'New',
+ ].join(' · ');
+
+ List<AccountDevice> unused([DateTime? now]) =>
+ devices?.unused(now ?? DateTime.now()) ?? const [];
+
+ /// The "Already on your account" notice is up: the devices that were on the account before this one
+ /// joined, which it never announced.
+ bool get baselineShowing {
+ final list = devices;
+ return list != null &&
+ !list.baselineSeen &&
+ !baselineDone &&
+ !app.baselineSeenLocally &&
+ list.baseline.isNotEmpty;
+ }
+
+ Future<void> gotIt() async {
+ baselineDone = true;
+ _changed();
+ await app.seeDeviceBaseline();
+ }
+
+ /// "It's mine" on a device that is new: it stops being announced. A suspension it shows is lifted.
+ void mine(AccountDevice d) {
+ app.dismissNewDevice(d.pub, liftSuspension: d.suspended);
+ newPubs.remove(d.pub);
+ _changed();
+ }
+
+ void _say(String? message, {bool notice = false}) {
+ error = message;
+ errorIsNotice = notice;
+ }
+
+ /// Signs [d] out of the account on every device. Null when done, else why not.
+ Future<String?> remove(AccountDevice d) async {
+ final name = d.label.trim().isEmpty ? 'this device' : d.label.trim();
+ removing.add(d.pub);
+ _say(null);
+ _changed();
+ String? failure;
+ try {
+ failure = await app.removeDevice(d.pub);
+ } catch (_) {
+ failure = 'UNREACHABLE';
+ }
+ removing.remove(d.pub);
+ if (failure != null) _say('Couldn’t remove $name ($failure). Try again.');
+ _changed();
+ return failure == null ? null : error;
+ }
+
+ /// A computer out of the account: signs [device] out when it is known, then deletes the machine
+ /// record [machineId]. Null when both are done, else why not. A sign-out that fails stops before the
+ /// record is touched.
+ Future<String?> removeComputer({
+ required String machineId,
+ required String name,
+ AccountDevice? device,
+ }) async {
+ if (device != null) {
+ removing.add(device.pub);
+ _changed();
+ String? failure;
+ try {
+ failure = await app.removeDevice(device.pub);
+ } catch (_) {
+ failure = 'UNREACHABLE';
+ }
+ removing.remove(device.pub);
+ _changed();
+ if (failure != null) {
+ return 'Couldn’t sign $name out ($failure). Try again.';
+ }
+ }
+ final failure = await app.deleteMachine(machineId);
+ if (failure == null) return null;
+ return device == null
+ ? failure
+ : '$name is signed out, but its machine record could not be deleted ($failure). Try again.';
+ }
+
+ /// Signs out every app unused for 90 days, after [confirm].
+ Future<void> removeUnused(DeviceConfirm confirm) async {
+ final list = unused();
+ if (list.isEmpty || removingUnused) return;
+ final confirmed = await confirm(
+ 'Remove ${list.length} unused app${list.length == 1 ? '' : 's'}?',
+ [
+ for (final d in list)
+ '${d.label.isEmpty ? 'Unnamed app' : d.label} — last active ${relativeAgo(d.lastSeen!, DateTime.now())}',
+ ].join('\n'),
+ 'Remove',
+ );
+ if (!confirmed || _disposed) return;
+ removingUnused = true;
+ _say(null);
+ _changed();
+ final failed = <String>[];
+ for (final d in list) {
+ String? failure;
+ try {
+ failure = await app.removeDevice(d.pub);
+ } catch (_) {
+ failure = 'UNREACHABLE';
+ }
+ if (failure != null) failed.add(d.label.isEmpty ? 'an app' : d.label);
+ }
+ removingUnused = false;
+ _say(
+ failed.isEmpty
+ ? null
+ : 'Couldn’t remove ${failed.join(', ')}. Try again.',
+ );
+ _changed();
+ }
+
+ /// Trusts the device list the account serves again, after the person reviews what it changes — the
+ /// one way out of a frozen list.
+ Future<void> trustAgain(DeviceConfirm confirm) async {
+ final preview = await app.rebaselineDevices(confirm: false);
+ if (_disposed) return;
+ if (preview == null) {
+ _say('Couldn’t read a valid device list. Try again later.');
+ _changed();
+ return;
+ }
+ if (preview.otherAccount) {
+ _say(otherAccountMessage, notice: true);
+ _changed();
+ return;
+ }
+ final lines = [
+ for (final name in preview.added) '+ $name',
+ for (final name in preview.removed) '− $name',
+ ];
+ final confirmed = await confirm(
+ 'Trust this device list again?',
+ lines.isEmpty
+ ? 'It changes no device. Continue only if you expected this.'
+ : 'Only if every device added below is yours:\n\n${lines.join('\n')}',
+ 'Trust again',
+ );
+ if (!confirmed || _disposed) return;
+ final done = await app.rebaselineDevices(confirm: true, head: preview.head);
+ if (_disposed) return;
+ if (done == null) {
+ _say('Couldn’t trust the device list again. Try again later.');
+ } else if (done.otherAccount) {
+ _say(otherAccountMessage, notice: true);
+ } else if (!done.logChanged) {
+ _say(null);
+ } else {
+ // What was reviewed is no longer what the account serves: nothing was trusted. Show it again.
+ _say(
+ 'The device list changed while you were reviewing it. Review it again.',
+ notice: true,
+ );
+ _changed();
+ await trustAgain(confirm);
+ return;
+ }
+ _changed();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ if (_started) app.removeListener(_appChanged);
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 0aff2c8a5..e7eaaf02f 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -333,6 +333,8 @@ class SwarmDestination {
this.isNote = false,
this.task,
this.external,
+ this.devicePub,
+ this.deviceIsComputer = false,
Iterable<String?> searchFields = const [],
int titleFields = 1,
}) : fields = [
@@ -399,6 +401,15 @@ class SwarmDestination {
/// A conversation Harness did not start; opening it resumes it as a harness.
final ExternalSessionRef? external;
+
+ /// A phone, browser or computer signed in to the account that is not one of its machines: the
+ /// Machines picker's Phones & apps, and a signed-in computer with no machine record. Its key in
+ /// the account's device list.
+ final String? devicePub;
+
+ /// [devicePub] is a computer rather than a phone or browser.
+ final bool deviceIsComputer;
+ bool get isAccountDevice => devicePub != null;
final bool current;
final List<String> fields;
bool get isProject => projectId != null;
@@ -419,7 +430,8 @@ class SwarmDestination {
!isStoreEntry &&
!isAgentChoice &&
pickerQuery == null &&
- external == null;
+ external == null &&
+ devicePub == null;
bool get hasView => swarmId != null;
}
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 7e2556a70..b0b834c53 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -14,7 +14,9 @@ import '../store/experimental_harnesses.dart';
import '../core/machine_resources.dart';
import '../core/models.dart'
show Agent, ConnectionStatus, GridModels, GridModel;
+import '../core/relative_time.dart';
+import 'account_devices.dart' show AccountDevice;
import 'app_state.dart';
import 'agent_switch_handoff.dart';
import 'harness_placement.dart';
@@ -22,6 +24,7 @@ import 'pane_arrangement.dart';
import 'swarm_catalog.dart';
import 'swarm_navigation.dart';
import 'harness_sessions.dart';
+import 'machine_devices.dart';
import 'search_when.dart';
import 'session_content_search.dart';
@@ -30,6 +33,15 @@ const kHarnessPickerHint = kSwarmSearchHint;
const kSwarmCreateRowId = 'create:harness';
+/// The Machines picker's two runs of rows: the account's computers, then its phones and apps.
+enum MachineSearchSection {
+ computers('Computers'),
+ phones('Phones & apps');
+
+ const MachineSearchSection(this.label);
+ final String label;
+}
+
typedef SwarmGroupScope = ({
String id,
String name,
@@ -1395,7 +1407,7 @@ class SwarmSearchController extends ChangeNotifier {
? 'Get'
: row?.isModel == true
? 'Unavailable'
- : setupLayout && row?.isMachine == true
+ : row?.isAccountDevice == true || (setupLayout && row?.isMachine == true)
? 'Manage'
: row?.isStoreEntry == true
? 'Open in Store'
@@ -1606,6 +1618,147 @@ class SwarmSearchController extends ChangeNotifier {
}
}
+ MachineDevices? _machineDevices;
+
+ /// The account's signed-in devices, while the picker lists machines: read the first time it does,
+ /// and kept for the rest of the visit.
+ MachineDevices? get machineDevices => _machineDevices;
+
+ MachineDevices? _ensureMachineDevices() {
+ if (_disposed || history != null) return _machineDevices;
+ if (_machineDevices case final devices?) return devices;
+ final devices = _machineDevices = MachineDevices(app)
+ ..addListener(_machineDevicesChanged);
+ // Read after this filter: an answer that is already there would otherwise filter again from
+ // inside it.
+ scheduleMicrotask(() {
+ if (!_disposed && identical(_machineDevices, devices)) devices.start();
+ });
+ return devices;
+ }
+
+ void _machineDevicesChanged() {
+ if (_disposed || !isMachineMode) return;
+ final previousSelection = selected?.id;
+ _filter(keepOrder: true);
+ if (previousSelection != null) {
+ final index = rows.indexWhere((row) => row.id == previousSelection);
+ if (index >= 0) {
+ cursor = index;
+ _selectedId = previousSelection;
+ }
+ }
+ notifyListeners();
+ }
+
+ /// Which run of the Machines picker [row] belongs to.
+ MachineSearchSection machineSection(SwarmDestination row) =>
+ row.isAccountDevice && !row.deviceIsComputer
+ ? MachineSearchSection.phones
+ : MachineSearchSection.computers;
+
+ /// Selects the device row for [pub] — a deep link to one device (a new one to review). False when
+ /// the list holds no such row (yet).
+ bool selectDevice(String pub) {
+ final index = rows.indexWhere(
+ (row) =>
+ row.devicePub == pub ||
+ (row.isMachine &&
+ _machineDevices?.forMachine(row.machineId!)?.pub == pub),
+ );
+ if (index < 0) return false;
+ if (index != cursor) move(index - cursor);
+ return true;
+ }
+
+ /// Selects the first phone or app, for a way in that is about them (Add Phone's Manage devices…).
+ bool selectFirstPhone() {
+ final index = rows.indexWhere(
+ (row) => machineSection(row) == MachineSearchSection.phones,
+ );
+ if (index < 0) return false;
+ if (index != cursor) move(index - cursor);
+ return true;
+ }
+
+ final _decoratedMachines =
+ <String, (SwarmDestination, int, SwarmDestination)>{};
+
+ /// The machines, and beside them every device signed in to the account that is not one: phones,
+ /// browsers, and a computer with no machine record. A machine's row adds what its key says — this
+ /// computer's code, when another was last active, whether it is new.
+ List<SwarmDestination> _machineCandidates() {
+ final machines = _catalog.where((row) => row.isMachine).toList();
+ final devices = _ensureMachineDevices();
+ if (devices == null || devices.devices == null) return machines;
+ final ids = {for (final row in machines) row.machineId!};
+ final now = DateTime.now();
+ return [
+ for (final row in machines) _machineRow(row, devices, now),
+ for (final device in devices.rows(ids)) _deviceRow(device, devices, now),
+ ];
+ }
+
+ SwarmDestination _machineRow(
+ SwarmDestination row,
+ MachineDevices devices,
+ DateTime now,
+ ) {
+ final device = devices.forMachine(row.machineId!);
+ if (device == null) return row;
+ final cached = _decoratedMachines[row.id];
+ if (cached != null &&
+ identical(cached.$1, row) &&
+ cached.$2 == devices.stamp) {
+ return cached.$3;
+ }
+ final local =
+ device.self || app.stateOf(row.machineId!)?.isLocalMachine == true;
+ final code = device.fingerprint.split('·').first;
+ final decorated = SwarmDestination(
+ id: row.id,
+ title: row.title,
+ detail: [
+ row.detail,
+ if (local) ...[
+ 'This computer',
+ if (code.isNotEmpty) 'code $code…',
+ ] else
+ activityPhrase(
+ lastSeen: device.lastSeen,
+ addedAt: device.addedAt,
+ now: now,
+ ),
+ if (device.suspended) 'Suspended' else if (devices.isNew(device)) 'New',
+ ].join(' · '),
+ machineId: row.machineId,
+ swarmId: row.swarmId,
+ current: row.current,
+ members: row.members,
+ searchFields: [...row.fields.skip(1), device.fingerprint, device.label],
+ );
+ _decoratedMachines[row.id] = (row, devices.stamp, decorated);
+ return decorated;
+ }
+
+ SwarmDestination _deviceRow(
+ AccountDevice device,
+ MachineDevices devices,
+ DateTime now,
+ ) => SwarmDestination(
+ id: 'device:${device.pub}',
+ devicePub: device.pub,
+ deviceIsComputer: device.isMachine,
+ title: device.label.trim().isEmpty ? 'Unnamed device' : device.label.trim(),
+ detail: devices.detail(device, now: now),
+ swarmId: null,
+ current: false,
+ searchFields: [
+ device.fingerprint,
+ device.isMachine ? 'computer' : 'app phone browser',
+ ],
+ );
+
void _filter({bool keepOrder = false}) {
final previous = rows;
if (isAgentMode) {
@@ -1698,7 +1851,7 @@ class SwarmSearchController extends ChangeNotifier {
: isProjectMode
? _catalog.where((row) => row.isProject).toList()
: isMachineMode
- ? _catalog.where((row) => row.isMachine).toList()
+ ? _machineCandidates()
: placement != null || _groupScope != null
? _catalog
.where(
@@ -1825,7 +1978,14 @@ class SwarmSearchController extends ChangeNotifier {
});
}
if (isMachineMode && matchQuery.trim().isEmpty) {
+ // Signed-in devices keep the order the account's list gives them (new first, then by activity),
+ // after the machines.
+ final deviceOrder = {
+ for (final (index, row) in rows.indexed)
+ if (row.isAccountDevice) row.id: index,
+ };
int priority(SwarmDestination row) {
+ if (row.isAccountDevice) return 4;
final machine = app.stateOf(row.machineId!);
if (machine == null) return 3;
if (machine.isLocalMachine) return 1;
@@ -1839,6 +1999,9 @@ class SwarmSearchController extends ChangeNotifier {
rows.sort((a, b) {
final group = priority(a).compareTo(priority(b));
if (group != 0) return group;
+ if (a.isAccountDevice && b.isAccountDevice) {
+ return deviceOrder[a.id]!.compareTo(deviceOrder[b.id]!);
+ }
final name = compareNatural(
a.title.toLowerCase(),
b.title.toLowerCase(),
@@ -1897,6 +2060,17 @@ class SwarmSearchController extends ChangeNotifier {
}
rows = [...available, ...unavailable];
}
+ // Computers, then phones and apps: the order the picker draws them in, so the arrows walk the
+ // rows in the order the eye does.
+ if (isMachineMode) {
+ rows = [
+ for (final section in MachineSearchSection.values)
+ for (final row in rows)
+ if (!row.isCreate && machineSection(row) == section) row,
+ for (final row in rows)
+ if (row.isCreate) row,
+ ];
+ }
// Creation has a stable place beside the prompt. Filtering changes the
// matches above it, never the position of the action itself.
if (offersCreate) {
@@ -2148,6 +2322,10 @@ class SwarmSearchController extends ChangeNotifier {
!canGetModel(destination)) {
return null;
}
+ if (destination.isAccountDevice) {
+ // A device is managed in the preview beside it; a click only chooses it.
+ return setupLayout ? SwarmSearchSelection(destination) : null;
+ }
if (setupLayout && (destination.isMachine || destination.isModel)) {
return SwarmSearchSelection(destination);
}
@@ -2224,6 +2402,8 @@ class SwarmSearchController extends ChangeNotifier {
bool canSubmit(SwarmDestination? row) => row?.agentEngine != null
? canSelectAgent(row!.agentEngine!)
+ : row?.devicePub != null
+ ? isMachineMode && _machineDevices?.byPub(row!.devicePub!) != null
: row?.isNote == true ||
sessionUnavailable(row) != null ||
sessionFilter == SessionFilter.needsInput &&
@@ -2337,6 +2517,8 @@ class SwarmSearchController extends ChangeNotifier {
models?.removeListener(_modelsChanged);
app.gridPictures.removeListener(_modelChoicesChanged);
app.sessionPreviews.removeListener(_previewChanged);
+ _machineDevices?.removeListener(_machineDevicesChanged);
+ _machineDevices?.dispose();
_previewPage.dispose();
_previewLine.dispose();
_resultPage.dispose();
diff --git a/desktop/lib/settings/sections/account_device_detail.dart b/desktop/lib/widgets/account_device_detail.dart
similarity index 97%
rename from desktop/lib/settings/sections/account_device_detail.dart
rename to desktop/lib/widgets/account_device_detail.dart
index ada0360de..d2f6c4602 100644
--- a/desktop/lib/settings/sections/account_device_detail.dart
+++ b/desktop/lib/widgets/account_device_detail.dart
@@ -2,13 +2,13 @@ import 'dart:async';
import 'package:flutter/material.dart';
-import '../../core/relative_time.dart';
-import '../../shared/theme/app_theme.dart' as grid;
-import '../../shared/widgets/app_dialog.dart';
-import '../../shared/widgets/fingerprint_text.dart';
-import '../../state/account_devices.dart';
-import '../../state/app_state.dart';
-import '../../theme/app_theme.dart';
+import '../core/relative_time.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/fingerprint_text.dart';
+import '../state/account_devices.dart';
+import '../state/app_state.dart';
+import '../theme/app_theme.dart';
/// What removing a device does, said in the confirm and nowhere else so the two entry points (the list
/// row and the detail) cannot word it differently.
diff --git a/desktop/lib/settings/sections/account_device_history.dart b/desktop/lib/widgets/account_device_history.dart
similarity index 95%
rename from desktop/lib/settings/sections/account_device_history.dart
rename to desktop/lib/widgets/account_device_history.dart
index e7ecc21ea..c2059d516 100644
--- a/desktop/lib/settings/sections/account_device_history.dart
+++ b/desktop/lib/widgets/account_device_history.dart
@@ -2,15 +2,15 @@ import 'dart:async';
import 'package:flutter/material.dart';
-import '../../core/relative_time.dart';
-import '../../shared/theme/app_theme.dart' as grid;
-import '../../shared/widgets/app_dialog.dart';
-import '../../state/app_state.dart';
-import '../../theme/app_theme.dart';
-import '../../viewer/device_history.dart';
+import '../core/relative_time.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../state/app_state.dart';
+import '../theme/app_theme.dart';
+import '../viewer/device_history.dart';
import 'account_device_detail.dart';
-/// Settings ▸ Your devices ▸ History… — every device added to or removed from the account, newest
+/// Machines ▸ History… — every device added to or removed from the account, newest
/// first, as this end verified the log. A device that was removed stays in it, named as it was.
Future<void> showAccountDeviceHistory(BuildContext context, AppNotifier app) =>
showAppDialog<void>(
diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dart
index fb4f0a350..a37d67b40 100644
--- a/desktop/lib/widgets/add_phone_dialog.dart
+++ b/desktop/lib/widgets/add_phone_dialog.dart
@@ -248,7 +248,7 @@ class AddPhoneDialog extends StatefulWidget {
final PhoneSignInCodeCall signInCode;
final VoidCallback? onConnectMachine;
- /// Opens Settings ▸ Your devices — where the account's devices are listed and
+ /// Opens Machines — where the account's computers, phones and apps are listed and
/// removed, on every device at once. Null shows no link.
final VoidCallback? onManageDevices;
diff --git a/desktop/lib/widgets/desktop_search_panel.dart b/desktop/lib/widgets/desktop_search_panel.dart
index 8f5170fa2..1276f9256 100644
--- a/desktop/lib/widgets/desktop_search_panel.dart
+++ b/desktop/lib/widgets/desktop_search_panel.dart
@@ -13,6 +13,7 @@ import 'box_chrome.dart' show ReadlineKeys;
import 'swarm_switcher.dart';
import 'swarm_search_input.dart';
import 'key_hints.dart';
+import 'machine_picker_extras.dart';
/// A desktop command palette over the existing search and activation pipeline.
/// Category buttons edit the same query as keyboard prefixes; no second index.
@@ -27,6 +28,7 @@ class DesktopSearchPanel extends StatelessWidget {
required this.onRefocus,
required this.previewBuilder,
this.showsBack = false,
+ this.machineHooks,
});
final SwarmSearchController search;
@@ -40,6 +42,27 @@ class DesktopSearchPanel extends StatelessWidget {
/// is open — the click for what Escape does.
final bool showsBack;
+ /// What Machines needs beyond its rows: which computer this window shows, the account's device
+ /// notices, and Add machine · Add phone · History… under the list. Null leaves Machines its rows.
+ final MachinePickerHooks? machineHooks;
+
+ /// The least height the window needs for Machines' extras above and below its list: a window
+ /// too short for both keeps the list, and the extras come back with the room.
+ static const machineExtrasMinHeight = 560.0;
+
+ MachinePickerHooks? _machineHooks(BuildContext context) =>
+ MediaQuery.sizeOf(context).height >=
+ MediaQuery.textScalerOf(context).scale(machineExtrasMinHeight)
+ ? machineHooks
+ : null;
+
+ void _addMachine() {
+ search.setQuery('@');
+ final index = search.rows.indexWhere((row) => row.isCreate);
+ if (index >= 0) search.move(index - search.cursor);
+ onRefocus();
+ }
+
static const maxWidth = 1120.0;
static const maxHeight = 680.0;
@@ -204,6 +227,13 @@ class DesktopSearchPanel extends StatelessWidget {
),
),
),
+ if (_machineHooks(context) case final hooks?)
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => search.isMachineMode
+ ? MachinePickerHeader(search: search, hooks: hooks)
+ : const SizedBox.shrink(),
+ ),
Flexible(
child: ListenableBuilder(
listenable: search,
@@ -222,6 +252,24 @@ class DesktopSearchPanel extends StatelessWidget {
),
),
),
+ if (_machineHooks(context) case final hooks?)
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => search.isMachineMode
+ ? Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Divider(height: 1, color: DesktopChrome.rim),
+ MachinePickerFooter(
+ search: search,
+ hooks: hooks,
+ onAddMachine: _addMachine,
+ ),
+ ],
+ )
+ : const SizedBox.shrink(),
+ ),
if (KeyHints.visibleOf(context)) ...[
Divider(height: 1, color: DesktopChrome.rim),
Padding(
diff --git a/desktop/lib/widgets/machine_picker_extras.dart b/desktop/lib/widgets/machine_picker_extras.dart
new file mode 100644
index 000000000..9dbfec2af
--- /dev/null
+++ b/desktop/lib/widgets/machine_picker_extras.dart
@@ -0,0 +1,359 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_select_field.dart';
+import '../state/account_devices.dart';
+import '../state/app_state.dart';
+import '../state/machine_devices.dart';
+import '../state/swarm_search.dart';
+import 'desktop_chrome.dart';
+
+/// What the Machines picker needs from the screen around it for the parts that are not rows: a
+/// dialog has to be shown with the picker stepped aside, and Add Phone belongs to the workspace.
+class MachinePickerHooks {
+ const MachinePickerHooks({
+ required this.confirm,
+ required this.onHistory,
+ this.onAddPhone,
+ });
+
+ /// Asks a yes/no question over the workspace (the picker steps aside while it is up).
+ final DeviceConfirm confirm;
+
+ /// Opens the account's device history.
+ final VoidCallback onHistory;
+
+ /// Opens Add Phone. Null where a phone cannot be added from here.
+ final VoidCallback? onAddPhone;
+}
+
+/// The top of the Machines picker: which computer's tabs this window shows, and what the account's
+/// device list needs looked at (a list that froze, a device refused, the devices already on the
+/// account when this one joined, apps nobody has used in months).
+class MachinePickerHeader extends StatelessWidget {
+ const MachinePickerHeader({
+ super.key,
+ required this.search,
+ required this.hooks,
+ });
+
+ final SwarmSearchController search;
+ final MachinePickerHooks hooks;
+
+ @override
+ Widget build(BuildContext context) {
+ final devices = search.machineDevices;
+ return ListenableBuilder(
+ listenable: Listenable.merge([search.app, ?devices]),
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 20, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ MachineWindowChoice(app: search.app),
+ if (devices != null)
+ _DeviceNotices(devices: devices, hooks: hooks),
+ ],
+ ),
+ );
+ },
+ );
+ }
+}
+
+/// Show in this window: every tab on the account, or only the tabs of one computer. One sign-in,
+/// several computers — the account's desk still holds every tab; this window draws all of them, or
+/// those whose agents all run on the computer chosen here.
+class MachineWindowChoice extends StatelessWidget {
+ const MachineWindowChoice({super.key, required this.app});
+
+ final AppNotifier app;
+
+ /// Why [machine] cannot be chosen right now, or null when it can: this window has no live
+ /// connection to it, it has to be linked again, or it reports itself offline.
+ String? _unavailable(Machine machine) {
+ final state = app.stateOf(machine.machineId);
+ if (state == null || state.needsLink) return 'Not connected';
+ if (state.nodeOnline == false) return 'Offline';
+ if (state.connectionStatus != ConnectionStatus.connected) {
+ return 'Not connected';
+ }
+ return null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final selected = app.machineProfileId;
+ final localId = app.localMachineState?.machine.machineId;
+ final machines = app.machines;
+ final names = <String, int>{};
+ for (final machine in machines) {
+ names[machine.displayName] = (names[machine.displayName] ?? 0) + 1;
+ }
+ String short(String id) => id.length > 8 ? id.substring(0, 8) : id;
+ final options = <SelectOption<String?>>[
+ const SelectOption<String?>(
+ value: null,
+ label: 'All machines',
+ detail: 'Every tab on this account, whichever computer it runs on.',
+ ),
+ for (final machine in machines)
+ // A computer this window cannot reach has no live tabs to narrow down to, so it cannot be
+ // chosen until it is back. One already chosen stays shown.
+ if (_unavailable(machine) == null || selected == machine.machineId)
+ SelectOption<String?>(
+ value: machine.machineId,
+ label: machine.displayName,
+ note: [
+ if (machine.machineId == localId) 'This computer',
+ if ((names[machine.displayName] ?? 0) > 1)
+ short(machine.machineId),
+ ?_unavailable(machine),
+ ].join(' · '),
+ detail: machine.machineId == localId
+ ? 'Tabs whose agents are all here.'
+ : 'Tabs whose agents are all there.',
+ ),
+ ];
+ return Wrap(
+ key: const Key('machine-window-choice'),
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 10,
+ runSpacing: 6,
+ children: [
+ Text('Show in this window', style: DesktopChrome.metadata()),
+ SizedBox(
+ width: 240,
+ child: AppSelectField<String?>(
+ key: const Key('machine-window-choice-field'),
+ semanticLabel: 'Show in this window',
+ value: selected,
+ options: options,
+ onChanged: (id) {
+ if (id != null &&
+ id != selected &&
+ machines
+ .where((m) => m.machineId == id)
+ .any((m) => _unavailable(m) != null)) {
+ return;
+ }
+ app.setMachineProfile(id);
+ },
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// A line the device list asks to be read, tinted like the device bands above the workspace, with
+/// the one button that answers it.
+class _Notice extends StatelessWidget {
+ const _Notice({
+ required this.text,
+ this.textKey,
+ this.children = const [],
+ this.action,
+ });
+
+ final String text;
+ final Key? textKey;
+ final List<String> children;
+ final Widget? action;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: grid.AppPalette.warn.withValues(alpha: 0.10),
+ borderRadius: BorderRadius.circular(8),
+ border: Border.all(color: grid.AppPalette.warn.withValues(alpha: 0.28)),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ text,
+ key: textKey,
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
+ for (final line in children)
+ Text(line, style: DesktopChrome.metadata()),
+ ],
+ ),
+ ),
+ if (action case final action?) ...[
+ const SizedBox(width: 10),
+ action,
+ ],
+ ],
+ ),
+ ),
+ ),
+ );
+}
+
+class _DeviceNotices extends StatelessWidget {
+ const _DeviceNotices({required this.devices, required this.hooks});
+
+ final MachineDevices devices;
+ final MachinePickerHooks hooks;
+
+ @override
+ Widget build(BuildContext context) {
+ final list = devices.devices;
+ final unused = devices.unused();
+ final notices = <Widget>[
+ if (list != null && list.frozen)
+ _Notice(
+ textKey: const Key('account-devices-frozen'),
+ text:
+ 'The device list froze on ${list.frozenReason != null ? 'this device' : list.frozenPeers.join(', ')}: '
+ 'Harness served a list that does not match what was verified before. No device is added '
+ 'until you review it.',
+ action: list.frozenReason == null
+ ? null
+ : DesktopPill(
+ key: const Key('account-devices-review'),
+ label: 'Review…',
+ compact: true,
+ onPressed: () => unawaited(devices.trustAgain(hooks.confirm)),
+ ),
+ ),
+ if (list?.registerError case final code?)
+ _Notice(
+ textKey: const Key('account-devices-refused'),
+ text: registerRefusalSentence(code),
+ ),
+ if (devices.baselineShowing)
+ _Notice(
+ textKey: const Key('account-devices-baseline'),
+ text: 'Already on your account: these were on it before this device joined. If one isn’t yours, remove it.',
+ children: [
+ for (final d in list!.baseline)
+ '${d.label.trim().isEmpty ? 'A device' : d.label.trim()} · ${d.isMachine ? 'Computer' : 'App'} · ${d.fingerprint}',
+ ],
+ action: DesktopPill(
+ key: const Key('account-devices-baseline-gotit'),
+ label: 'Got it',
+ compact: true,
+ onPressed: () => unawaited(devices.gotIt()),
+ ),
+ ),
+ if (unused.isNotEmpty)
+ _Notice(
+ textKey: const Key('account-devices-unused'),
+ text:
+ '${unused.length} app${unused.length == 1 ? '' : 's'} not used in 90 days. Most likely a '
+ 'browser whose data was cleared; removing them changes nothing you use.',
+ action: DesktopPill(
+ key: const Key('account-devices-remove-unused'),
+ label: devices.removingUnused ? 'Removing…' : 'Remove them',
+ compact: true,
+ onPressed: devices.removingUnused
+ ? null
+ : () => unawaited(devices.removeUnused(hooks.confirm)),
+ ),
+ ),
+ if (devices.error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ error,
+ key: const Key('account-devices-error'),
+ style: DesktopChrome.metadata(
+ color: devices.errorIsNotice
+ ? grid.AppPalette.warn
+ : Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ),
+ ),
+ ];
+ if (notices.isEmpty) return const SizedBox.shrink();
+ // A long baseline must not take the list's room: the notices scroll on their own.
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxHeight: 180),
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: notices,
+ ),
+ ),
+ );
+ }
+}
+
+/// The bottom of the Machines picker: the ways to add to the list, and its history.
+class MachinePickerFooter extends StatelessWidget {
+ const MachinePickerFooter({
+ super.key,
+ required this.search,
+ required this.hooks,
+ required this.onAddMachine,
+ });
+
+ final SwarmSearchController search;
+ final MachinePickerHooks hooks;
+ final VoidCallback onAddMachine;
+
+ @override
+ Widget build(BuildContext context) {
+ final devices = search.machineDevices;
+ return ListenableBuilder(
+ listenable: Listenable.merge([?devices]),
+ builder: (context, _) {
+ grid.AppTheme.watch(context);
+ final history = devices?.devices?.historyAvailable ?? false;
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
+ child: Wrap(
+ key: const Key('machine-picker-footer'),
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ DesktopPill(
+ key: const Key('machine-picker-add-machine'),
+ label: 'Add machine',
+ compact: true,
+ onPressed: onAddMachine,
+ ),
+ if (hooks.onAddPhone case final addPhone?)
+ DesktopPill(
+ key: const Key('machine-picker-add-phone'),
+ label: 'Add phone',
+ compact: true,
+ onPressed: addPhone,
+ ),
+ DesktopPill(
+ key: const Key('account-devices-history'),
+ label: 'History…',
+ compact: true,
+ tooltip: history || devices?.devices == null
+ ? null
+ : 'Update Harness on this computer to see history.',
+ onPressed: history ? hooks.onHistory : null,
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/desktop/lib/widgets/machine_picker_form.dart b/desktop/lib/widgets/machine_picker_form.dart
index 22d87085b..287725053 100644
--- a/desktop/lib/widgets/machine_picker_form.dart
+++ b/desktop/lib/widgets/machine_picker_form.dart
@@ -44,10 +44,19 @@ class MachinePickerForm extends StatefulWidget {
required this.onFocusChanged,
this.onSwitchPane,
this.machineId,
+ this.remove,
+ this.signsOut = false,
});
final AppNotifier app;
final MachinePickerFormKind kind;
final String? machineId;
+
+ /// What [MachinePickerFormKind.delete] does instead of deleting the machine record alone: the
+ /// Machines picker signs the computer out of the account as well ([signsOut]).
+ final Future<String?> Function()? remove;
+
+ /// The delete also signs the computer out of the account, and its confirmation says so.
+ final bool signsOut;
final ValueChanged<String?> onClose;
final ValueChanged<bool> onFocusChanged;
final VoidCallback? onSwitchPane;
@@ -313,7 +322,8 @@ class MachinePickerFormState extends State<MachinePickerForm> {
widget.machineId!,
_value.text.trim(),
),
- MachinePickerFormKind.delete => app.deleteMachine(widget.machineId!),
+ MachinePickerFormKind.delete =>
+ widget.remove?.call() ?? app.deleteMachine(widget.machineId!),
MachinePickerFormKind.password when machine!.isLocalMachine =>
_clearConfirmation
? app.clearRemotePassword()
@@ -451,7 +461,7 @@ class MachinePickerFormState extends State<MachinePickerForm> {
(
label: switch (widget.kind) {
MachinePickerFormKind.connect => 'Connect',
- MachinePickerFormKind.delete => 'Delete',
+ MachinePickerFormKind.delete => widget.signsOut ? 'Remove' : 'Delete',
_ => _clearConfirmation ? 'Clear' : 'Save',
},
run: _busy || _loading ? null : _submit,
@@ -472,7 +482,7 @@ class MachinePickerFormState extends State<MachinePickerForm> {
MachinePickerFormKind.connect => machineLinkProgress(
app.machineLinkStage(widget.machineId!),
),
- MachinePickerFormKind.delete => 'Deleting…',
+ MachinePickerFormKind.delete => widget.signsOut ? 'Removing…' : 'Deleting…',
_ => 'Saving…',
};
@@ -735,6 +745,13 @@ class MachinePickerFormState extends State<MachinePickerForm> {
gap,
// Signing in is what makes this app trust it (the device key log): no password to set.
line('It appears here and connects on its own.'),
+ ] else if (widget.kind == MachinePickerFormKind.delete &&
+ widget.signsOut) ...[
+ line('Remove this computer from your account?'),
+ line('It is signed out, and its machine record is deleted.'),
+ line(
+ 'Its panes in this window will close. Signing in on it again adds it back as a new device.',
+ ),
] else if (widget.kind == MachinePickerFormKind.delete) ...[
line('Delete this machine from your account?'),
line('Its panes in this window will close.'),
@@ -821,7 +838,9 @@ class MachinePickerFormState extends State<MachinePickerForm> {
() => FocusNode(debugLabel: action.label),
),
foregroundColor:
- action.label == 'Delete' || action.label == 'Clear'
+ action.label == 'Delete' ||
+ action.label == 'Remove' ||
+ action.label == 'Clear'
? Theme.of(context).colorScheme.error
: null,
onPressed: action.run,
diff --git a/desktop/lib/widgets/new_device_notice.dart b/desktop/lib/widgets/new_device_notice.dart
index 832389457..05ea1a635 100644
--- a/desktop/lib/widgets/new_device_notice.dart
+++ b/desktop/lib/widgets/new_device_notice.dart
@@ -3,10 +3,8 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:harness/shared/theme/app_icons.dart';
-import '../settings/sections/account_device_detail.dart';
-import '../settings/sections/account_device_history.dart';
-import '../settings/settings_screen.dart';
-import '../settings/settings_section.dart';
+import 'account_device_detail.dart';
+import 'account_device_history.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/account_devices.dart' show DeviceConflict, registerRefusalSentence;
import '../state/app_state.dart';
@@ -65,17 +63,10 @@ class NewDeviceNotice extends StatelessWidget {
const SizedBox(width: 6),
OutlinedButton(
key: const Key('new-device-review'),
- // One new device goes straight to its key code; several go to the list, where each is a row.
- onPressed: () => unawaited(
- more == 0
- ? showAccountDeviceDetail(context, notifier, pub: notice.pub, isNew: true)
- : showSettingsScreen(
- context,
- notifier,
- initialSection: SettingsSection.accountDevices,
- source: 'new-device-notice',
- ),
- ),
+ // One new device goes straight to its key code; several go to Machines, where each is a row.
+ onPressed: () => more == 0
+ ? unawaited(showAccountDeviceDetail(context, notifier, pub: notice.pub, isNew: true))
+ : openMachines(context, notifier, devicePub: notice.pub),
child: Text(more == 0 ? 'Review' : 'Review devices'),
),
],
@@ -249,9 +240,9 @@ class DeviceConflictNoticeBand extends StatelessWidget {
maxLines: null,
text: conflict.afterJoin
? 'Another key took this computer’s place on your account after it joined: $holder. '
- 'If you did not set up Harness here again, remove that key from another device now (Your devices).'
+ 'If you did not set up Harness here again, remove that key from another device now (Machines).'
: 'This computer is held by another key on your account: $holder. If that was an earlier '
- 'install of this computer, remove it from another device (Your devices) — this computer '
+ 'install of this computer, remove it from another device (Machines) — this computer '
'joins on its own once it is gone.',
actions: [
TextButton(
@@ -261,31 +252,31 @@ class DeviceConflictNoticeBand extends StatelessWidget {
),
OutlinedButton(
key: const Key('device-conflict-review'),
- onPressed: () => unawaited(
- showSettingsScreen(
- context,
- notifier,
- initialSection: SettingsSection.accountDevices,
- source: 'device-conflict-notice',
- ),
- ),
- child: const Text('Your devices'),
+ onPressed: () => openMachines(context, notifier, devicePub: conflict.pub),
+ child: const Text('Machines'),
),
],
);
}
}
-/// Settings ▸ Your devices, from a machine that asks for its password while this app's device list is
-/// frozen ([AppNotifier.deviceListNeedsReview]): the list pins no machine again until it is reviewed.
-void showDeviceListReview(BuildContext context, AppNotifier notifier) => unawaited(
- showSettingsScreen(
- context,
- notifier,
- initialSection: SettingsSection.accountDevices,
- source: 'needs-link',
- ),
-);
+/// Machines, where the account's computers, phones and apps are listed, from anywhere: it steps out
+/// of Settings and any dialog over the workspace, and the workspace opens the picker
+/// ([AppNotifier.requestMachines]). [devicePub] selects that device there.
+void openMachines(
+ BuildContext context,
+ AppNotifier notifier, {
+ String? devicePub,
+ bool phones = false,
+}) {
+ Navigator.of(context, rootNavigator: true).popUntil((route) => route.isFirst);
+ notifier.requestMachines(devicePub: devicePub, phones: phones);
+}
+
+/// Machines, from a machine that asks for its password while this app's device list is frozen
+/// ([AppNotifier.deviceListNeedsReview]): the list pins no machine again until it is reviewed.
+void showDeviceListReview(BuildContext context, AppNotifier notifier) =>
+ openMachines(context, notifier);
/// The line under a machine's password prompt while this app's device list is frozen — or the backend
/// refused this app a place on the account for having too many devices: the password is one way in,
@@ -322,7 +313,7 @@ class DeviceListReviewLine extends StatelessWidget {
TextButton(
key: const Key('device-list-review'),
onPressed: () => showDeviceListReview(context, notifier),
- child: const Text('Your devices'),
+ child: const Text('Machines'),
),
],
);
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 5499c1dfc..e45ebd62f 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1681,7 +1681,7 @@ class _PaneContent extends StatelessWidget {
notifier,
pane.machineId,
).ignore(),
- secondaryLabel: review ? 'Your devices' : null,
+ secondaryLabel: review ? 'Machines' : null,
onSecondary: review
? () => showDeviceListReview(context, notifier)
: null,
diff --git a/desktop/lib/widgets/swarm_resource_preview.dart b/desktop/lib/widgets/swarm_resource_preview.dart
index 2b9aff214..b920dbf00 100644
--- a/desktop/lib/widgets/swarm_resource_preview.dart
+++ b/desktop/lib/widgets/swarm_resource_preview.dart
@@ -12,8 +12,12 @@ import '../models/api_connections_controller.dart'
show ApiModels, contextWindowLabel;
import '../models/local_model.dart';
import '../models/model_search_catalog.dart';
+import '../core/relative_time.dart';
import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/fingerprint_text.dart';
+import '../state/account_devices.dart';
import '../state/app_state.dart';
+import '../state/machine_devices.dart';
import '../state/harness_sessions.dart';
import '../state/harness_placement.dart';
import '../state/swarm_navigation.dart';
@@ -21,6 +25,8 @@ import '../state/swarm_search.dart';
import '../terminal/terminal_text.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
+import 'account_device_detail.dart'
+ show confirmDeviceAction, removeDeviceDetail;
import 'machine_picker_form.dart';
import 'api_picker_form.dart';
import 'swarm_search_preview.dart';
@@ -129,7 +135,52 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
bool get _machineSetup =>
row?.isCreate == true && widget.search.isMachineMode;
bool get _isManagement =>
- row?.isMachine == true || row?.isModel == true || _machineSetup;
+ row?.isMachine == true ||
+ row?.isModel == true ||
+ row?.isAccountDevice == true ||
+ _machineSetup;
+
+ MachineDevices? get _devices => widget.search.machineDevices;
+
+ /// The account's key for the selected row: the device itself, or the key of the machine it is.
+ AccountDevice? get _device {
+ final selected = row;
+ final devices = _devices;
+ if (selected == null || devices == null) return null;
+ if (selected.devicePub case final pub?) return devices.byPub(pub);
+ if (selected.isMachine) return devices.forMachine(selected.machineId!);
+ return null;
+ }
+
+ /// A dialog over the workspace: the picker steps aside while it is up, and takes the keys back after.
+ Future<T> _modal<T>(Future<T> Function() dialog) async {
+ widget.onModalChanged(true);
+ try {
+ return await dialog();
+ } finally {
+ widget.onModalChanged(false);
+ if (mounted) widget.onRefocus();
+ }
+ }
+
+ Future<bool> _confirm(String title, String detail, String action) => _modal(
+ () =>
+ confirmDeviceAction(context, title, detail, action, destructive: true),
+ );
+
+ /// Signs a phone, browser or a computer with no machine record out of the account, after asking.
+ Future<void> _removeDevice(AccountDevice device) async {
+ final devices = _devices;
+ if (devices == null) return;
+ final name = device.label.trim().isEmpty
+ ? 'this device'
+ : device.label.trim();
+ if (!await _confirm('Remove $name?', removeDeviceDetail, 'Remove')) return;
+ if (!mounted) return;
+ await devices.remove(device);
+ }
+
+ void _mine(AccountDevice device) => _devices?.mine(device);
bool get _editingMachine => _machineForm != null && _formResource == row?.id;
void _editMachine(MachinePickerFormKind kind) {
@@ -928,6 +979,25 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
];
}
+ if (selected.isAccountDevice) {
+ final device = _device;
+ if (device == null) return const [];
+ final removing = _devices?.removing.contains(device.pub) == true;
+ return [
+ if (_devices?.isNew(device) == true && !device.self)
+ _ResourceAction(
+ 'It’s mine',
+ removing ? null : () => _mine(device),
+ command: 'picker.device_mine',
+ ),
+ if (!device.self)
+ _ResourceAction(
+ removing ? 'Removing…' : 'Remove',
+ removing ? null : () => unawaited(_removeDevice(device)),
+ command: 'picker.resource_remove',
+ ),
+ ];
+ }
if (selected.isMachine) {
final machine = app.stateOf(selected.machineId!);
if (machine == null) return [];
@@ -948,6 +1018,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
command: 'picker.resource_rename',
),
...secondary.where((a) => a.command == 'picker.resource_remove'),
+ ...secondary.where((a) => a.command == 'picker.device_mine'),
if (app.machineListError != null)
_ResourceAction(
'Retry',
@@ -1075,10 +1146,17 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
if (!machine.isLocalMachine && !machine.machine.isShared)
_ResourceAction(
- 'Delete',
+ 'Remove',
() => _editMachine(MachinePickerFormKind.delete),
command: 'picker.resource_remove',
),
+ if (_device case final device?
+ when _devices?.isNew(device) == true && !device.self)
+ _ResourceAction(
+ 'It’s mine',
+ () => _mine(device),
+ command: 'picker.device_mine',
+ ),
_ResourceAction(
'Add machine',
_addMachine,
@@ -1538,8 +1616,57 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
resources?.memoryTotalBytes != null)
'RAM ${(resources!.memoryUsedBytes! / (1024 * 1024 * 1024)).toStringAsFixed(1)} / ${(resources.memoryTotalBytes! / (1024 * 1024 * 1024)).toStringAsFixed(0)} GB',
'${machine.agents.length} ${machine.agents.length == 1 ? 'harness' : 'harnesses'}',
+ ..._deviceFacts(_device),
?app.machineListError,
?_messages[row!.id],
+ ?_devices?.error,
+ ], controls: true);
+ }
+
+ /// What the account's device list says about [device]: when it joined and was last active, and
+ /// its key code to compare on the device itself.
+ List<Object> _deviceFacts(AccountDevice? device) {
+ if (device == null) return const [];
+ final now = DateTime.now();
+ return [
+ '',
+ ('Added', fullDateTime(device.addedAt)),
+ if (device.lastSeen case final seen?)
+ ('Last active', device.self ? 'Now' : relativeAgo(seen, now)),
+ if (device.fingerprint.isNotEmpty) ...[
+ ('Code', ''),
+ FingerprintText(
+ device.fingerprint,
+ large: false,
+ copyKey: ValueKey('device-code-copy:${device.pub}'),
+ ),
+ device.self
+ ? 'This device’s code. Your other devices show the same code for it.'
+ : fingerprintHowToCompare(computer: device.isMachine),
+ ],
+ if (device.suspended)
+ 'Not trusted here: added after this device’s list and another’s split. '
+ 'Review the list to trust it again.',
+ ];
+ }
+
+ Widget _devicePreview() {
+ final device = _device;
+ if (device == null) {
+ return _details([row!.title, 'No longer on your account']);
+ }
+ return _details([
+ row!.title,
+ [
+ device.isMachine ? 'Computer' : 'App',
+ if (device.self) 'This device',
+ if (device.suspended)
+ 'Suspended'
+ else if (_devices?.isNew(device) == true)
+ 'New',
+ ].join(' · '),
+ ..._deviceFacts(device),
+ ?_devices?.error,
], controls: true);
}
@@ -1592,6 +1719,10 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
label,
value,
),
+ final Widget widget => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: widget,
+ ),
final line => Padding(
padding: EdgeInsets.only(bottom: i == 0 ? 5 : 3),
child: Text(
@@ -1640,6 +1771,7 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
),
],
),
+ final Widget widget => widget,
final line => Text(
'$line',
style: i == 0
@@ -1859,6 +1991,18 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
app: app,
kind: _machineForm!,
machineId: row?.machineId,
+ signsOut:
+ _machineForm == MachinePickerFormKind.delete &&
+ _device != null,
+ remove:
+ _machineForm == MachinePickerFormKind.delete &&
+ _devices != null
+ ? () => _devices!.removeComputer(
+ machineId: row!.machineId!,
+ name: row!.title,
+ device: _device,
+ )
+ : null,
onClose: _closeMachineForm,
onFocusChanged: widget.search.setManaging,
onSwitchPane: _switchPane,
@@ -1893,6 +2037,8 @@ class _SwarmResourcePreviewState extends State<SwarmResourcePreview> {
])
: row?.isMachine == true
? _machinePreview()
+ : row?.isAccountDevice == true
+ ? _devicePreview()
: widget.search.isModelMode
? _modelPreview()
: SwarmSearchPreview(
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index aa62f6c2d..5fa94c703 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -560,7 +560,49 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
/// The model list as drawn: each section's heading, then its rows. [key] is the section's own
/// label, which stays put while a heading such as `Get for this Mac · 64 GB` follows its machine.
+ /// The Machines picker as drawn once it lists signed-in devices beside the machines: Computers,
+ /// then Phones & apps, each under its heading, and Add machine after them. Empty — rows drawn as a
+ /// plain list — while there are only machines.
+ List<({int? index, String? heading, String? key})> get _machineRows {
+ if (!search.isMachineMode ||
+ !search.rows.any((row) => row.isAccountDevice)) {
+ return const [];
+ }
+ final items = <({int? index, String? heading, String? key})>[];
+ for (final section in MachineSearchSection.values) {
+ final indices = [
+ for (final (index, row) in search.rows.indexed)
+ if (!row.isCreate && search.machineSection(row) == section) index,
+ ];
+ if (indices.isEmpty) continue;
+ if (items.isNotEmpty) items.add((index: null, heading: null, key: null));
+ items.add((
+ index: null,
+ heading: section.label,
+ key: 'machine-section:${section.name}',
+ ));
+ items.addAll(
+ indices.map((index) => (index: index, heading: null, key: null)),
+ );
+ }
+ final create = [
+ for (final (index, row) in search.rows.indexed)
+ if (row.isCreate) index,
+ ];
+ if (create.isNotEmpty && items.isNotEmpty) {
+ items.add((index: null, heading: null, key: null));
+ }
+ items.addAll(
+ create.map((index) => (index: index, heading: null, key: null)),
+ );
+ return items;
+ }
+
+ /// The list is drawn in titled runs rather than as one list of rows.
+ bool get _sectioned => search.isModelMode || _machineRows.isNotEmpty;
+
List<({int? index, String? heading, String? key})> get _modelRows {
+ if (search.isMachineMode) return _machineRows;
if (!search.isModelMode) return const [];
final items = <({int? index, String? heading, String? key})>[];
for (final section in ModelSearchSection.values) {
@@ -582,7 +624,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
items.add((
index: null,
heading: search.modelSectionLabel(section),
- key: section.label,
+ key: 'model-section:${section.label}',
));
items.addAll(
indices.map((index) => (index: index, heading: null, key: null)),
@@ -752,18 +794,18 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
void _scrollToSelection() {
if (!_scroll.hasClients || search.rows.isEmpty) return;
final modelRows = _modelRows;
- final index = search.isModelMode
+ final sectioned = _sectioned;
+ final index = sectioned
? modelRows.indexWhere((item) => item.index == search.cursor)
: search.cursor - (_createPinned ? 1 : 0);
if (index < 0) return;
- final top = search.isModelMode
+ final top = sectioned
? modelRows
.take(index)
.fold(0.0, (height, item) => height + _modelItemHeight(item))
: index * _rowHeight;
final bottom =
- top +
- (search.isModelMode ? _modelItemHeight(modelRows[index]) : _rowHeight);
+ top + (sectioned ? _modelItemHeight(modelRows[index]) : _rowHeight);
final position = _scroll.position;
final offset = top < position.pixels
? top
@@ -894,6 +936,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
final pinCreate = _createPinned =
_pinsCreate && constraints.maxHeight >= _rowHeight + 16;
final modelRows = _modelRows;
+ final sectioned = _sectioned;
Widget buildRow(BuildContext context, int index) {
final row = search.rows[index];
final selected = index == search.cursor;
@@ -1035,8 +1078,10 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
: Icon(
row.isProject
? AppIcons.folder
- : row.isMachine
+ : row.isMachine || row.deviceIsComputer
? AppIcons.laptop
+ : row.isAccountDevice
+ ? AppIcons.smartphone
: row.isModel
? AppIcons.sparkles
: row.isCreate
@@ -1285,18 +1330,18 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
_rowHeight,
),
reverse: search.resultsFromBottom,
- itemCount: search.isModelMode
+ itemCount: sectioned
? modelRows.length
: search.rows.length - (pinCreate ? 1 : 0),
- itemExtent: desktop && search.isModelMode
+ itemExtent: desktop && sectioned
? null
: _rowHeight,
- itemExtentBuilder: desktop && search.isModelMode
+ itemExtentBuilder: desktop && sectioned
? (index, _) =>
_modelItemHeight(modelRows[index])
: null,
itemBuilder: (context, index) {
- if (!search.isModelMode) {
+ if (!sectioned) {
return buildRow(
context,
index + (pinCreate ? 1 : 0),
@@ -1312,7 +1357,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
return Semantics(
header: true,
child: Padding(
- key: ValueKey('model-section:${item.key}'),
+ key: ValueKey<String>(item.key!),
padding: EdgeInsets.symmetric(
horizontal: widget.bios
? cell.width * 3
@@ -1439,7 +1484,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
height * .45,
16 +
_rowHeight *
- (search.isModelMode
+ (sectioned
? modelRows.length
: search.rows.length)
.clamp(1, 4),
diff --git a/desktop/test/account_device_detail_test.dart b/desktop/test/account_device_detail_test.dart
index a0858ca90..41eb7114d 100644
--- a/desktop/test/account_device_detail_test.dart
+++ b/desktop/test/account_device_detail_test.dart
@@ -1,10 +1,10 @@
-// One device in full (Settings ▸ Your devices ▸ a row, the banner's Review, a notification click):
+// One device in full (a row in Machines, the banner's Review, a notification click):
// its facts, its whole key code, how to compare it, and what can be done about it.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/settings/sections/account_device_detail.dart';
+import 'package:harness/widgets/account_device_detail.dart';
import 'package:harness/shared/widgets/fingerprint_text.dart';
import 'package:harness/state/account_devices.dart';
import 'package:harness/theme/app_theme.dart' show AppColors;
diff --git a/desktop/test/account_device_history_test.dart b/desktop/test/account_device_history_test.dart
index 48e6174d8..f2f0f43ae 100644
--- a/desktop/test/account_device_history_test.dart
+++ b/desktop/test/account_device_history_test.dart
@@ -1,7 +1,7 @@
-// Settings ▸ Your devices ▸ History…: the log's adds and removes, newest first.
+// Machines ▸ History…: the log's adds and removes, newest first.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/settings/sections/account_device_history.dart';
+import 'package:harness/widgets/account_device_history.dart';
import 'package:harness/state/account_devices.dart';
import 'package:harness/theme/app_theme.dart' show AppColors;
import 'package:harness/viewer/device_history.dart';
diff --git a/desktop/test/account_devices_section_test.dart b/desktop/test/account_devices_section_test.dart
deleted file mode 100644
index 5f64683e6..000000000
--- a/desktop/test/account_devices_section_test.dart
+++ /dev/null
@@ -1,481 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/settings/sections/account_devices_section.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/state/account_devices.dart';
-import 'package:harness/theme/app_theme.dart' show AppColors;
-import 'package:harness/shared/widgets/fingerprint_text.dart';
-import 'package:harness/viewer/device_log.dart' show DevLogHead;
-import 'package:harness/viewer/device_log_sync.dart' show DeviceLogRebaseline;
-
-import 'support/devices_app.dart';
-
-/// Settings ▸ Your devices: opening it is reviewing the devices the banner announced.
-void main() {
- test('the daemon\'s OTHER_ACCOUNT answer and the viewer\'s are a refusal of another account\'s list', () {
- final daemon = DevicesRebaseline.fromDaemon({'error': 'OTHER_ACCOUNT'})!;
- expect([daemon.otherAccount, daemon.logChanged, daemon.refused], [true, false, true]);
- expect(DevicesRebaseline.fromDaemon({'error': 'LOG_CHANGED'})!.otherAccount, isFalse);
- final viewer = DevicesRebaseline.fromViewer(const DeviceLogRebaseline.otherAccount());
- expect([viewer.otherAccount, viewer.logChanged, viewer.head], [true, false, null]);
- });
- test('a listing carries its departed keys, from the daemon and from the viewer alike', () {
- final fromDaemon = AccountDevices.fromDaemon({
- 'members': <Object>[],
- 'pending': <Object>[],
- 'departed': [
- {
- 'pub': 'gone', 'label': 'Phone', 'kind': 'viewer', 'machineId': '', 'fingerprint': 'AAAA',
- 'addedAt': 1, 'removedAt': 2, 'removedBy': 'gone', 'removedByLabel': 'Phone', 'selfRemoved': true,
- },
- ],
- })!;
- expect(fromDaemon.departed, ['gone']);
- expect(AccountDevices.fromDaemon({'members': <Object>[], 'pending': <Object>[]})!.departed, isEmpty);
- expect(fromDaemon.withLastSeen(const {}).departed, ['gone']);
- });
- testWidgets('opening the devices list takes the new-device banner down', (tester) async {
- final app = FakeDevicesApp();
- addTearDown(app.dispose);
- app.newDevices.add(const NewDeviceNotice(pub: 'p1', label: 'Test iPad', kind: 'viewer'));
- app.newDevices.add(const NewDeviceNotice(pub: 'p2', label: 'box9', kind: 'machine'));
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
- await tester.pump();
- // Marking the devices seen waits for the list's read, so the pending keys it holds are badged first.
- await tester.pump();
- expect(app.newDevices, isEmpty);
- await tester.pumpWidget(const SizedBox());
- await tester.pump(const Duration(minutes: 1));
- });
- group('the list', () {
- final now = DateTime.now();
- late FakeDevicesApp app;
-
- setUp(() {
- app = FakeDevicesApp()
- ..devices = AccountDevices(devices: [
- fakeDevice('old', label: 'Old laptop', kind: 'machine', added: now.subtract(const Duration(days: 300)),
- seen: now.subtract(const Duration(days: 40)), fingerprint: 'AAAA·0001·0001·0001'),
- fakeDevice('me', label: 'MacBook', kind: 'machine', self: true, added: now.subtract(const Duration(days: 200)),
- seen: now, fingerprint: 'E2FB·0DF5·5FD8·E6C7'),
- fakeDevice('phone-a', label: 'iPhone', added: now.subtract(const Duration(days: 100)),
- seen: now.subtract(const Duration(minutes: 2)), fingerprint: 'BBBB·0002·0002·0002'),
- fakeDevice('phone-b', label: 'iPhone', added: now.subtract(const Duration(days: 50)), fingerprint: 'CCCC·0003·0003·0003'),
- fakeDevice('twin', label: 'MacBook', added: now.subtract(const Duration(days: 30)),
- seen: now.subtract(const Duration(days: 3)), fingerprint: 'DDDD·0004·0004·0004'),
- fakeDevice('new', label: 'Test iPad', added: now.subtract(const Duration(hours: 3)), fingerprint: 'EEEE·0005·0005·0005'),
- ]);
- app.newDevices.add(const NewDeviceNotice(pub: 'new', label: 'Test iPad', kind: 'viewer'));
- });
- tearDown(() => app.dispose());
-
- Future<void> openList(WidgetTester tester) async {
- tester.view.physicalSize = const Size(1200, 1600);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
- await tester.pump();
- await tester.pump();
- }
-
- String detailOf(WidgetTester tester, String pub) {
- final row = find.byKey(ValueKey('account-device-$pub'));
- return tester.widgetList<Text>(find.descendant(of: row, matching: find.byType(Text))).map((t) => t.data ?? '').join('\n');
- }
-
- testWidgets('this device is a card on top with its whole code, and is not a row again', (tester) async {
- await openList(tester);
- final card = find.byKey(const Key('account-device-this'));
- expect(card, findsOneWidget);
- expect(find.descendant(of: card, matching: find.text('MacBook')), findsOneWidget);
- expect(find.descendant(of: card, matching: find.text('This is the code your other devices show for this device.')), findsOneWidget);
- expect(find.descendant(of: card, matching: find.text('E2FB·0DF5·5FD8·E6C7')), findsOneWidget);
- expect(find.descendant(of: card, matching: find.byKey(const Key('this-device-copy'))), findsOneWidget);
- expect(find.byKey(const ValueKey('account-device-me')), findsNothing);
- expect(find.text('This device'), findsOneWidget);
- });
-
- testWidgets('rows: new first with a badge, then by activity; no whole code, the start of it only for a shared name', (tester) async {
- await openList(tester);
- double top(String pub) => tester.getTopLeft(find.byKey(ValueKey('account-device-$pub'))).dy;
- final order = ['new', 'phone-a', 'twin', 'old', 'phone-b'];
- for (var i = 1; i < order.length; i++) {
- expect(top(order[i - 1]), lessThan(top(order[i])), reason: '${order[i - 1]} above ${order[i]}');
- }
- expect(top('new'), greaterThan(tester.getTopLeft(find.byKey(const Key('account-device-this'))).dy));
- // Opening the list took the banner down, but this visit still shows which device was new.
- expect(app.newDevices, isEmpty);
- expect(find.descendant(of: find.byKey(const ValueKey('account-device-new')), matching: find.text('New')), findsOneWidget);
- expect(find.text('New'), findsOneWidget);
-
- expect(detailOf(tester, 'new'), contains('App · added 3 hours ago'));
- expect(detailOf(tester, 'phone-a'), contains('App · active now · BBBB…'));
- expect(detailOf(tester, 'phone-b'), contains('App · added 7 weeks ago · CCCC…'));
- // Shares its name with this device's card.
- expect(detailOf(tester, 'twin'), contains('App · last active 3 days ago · DDDD…'));
- expect(detailOf(tester, 'old'), contains('Computer · last active 5 weeks ago'));
- expect(detailOf(tester, 'old'), isNot(contains('AAAA')));
- expect(detailOf(tester, 'new'), isNot(contains('EEEE')));
- for (final pub in order) {
- expect(detailOf(tester, pub), isNot(matches(RegExp(r'[0-9A-F]{4}·[0-9A-F]{4}'))), reason: pub);
- }
- final everything = tester.widgetList<Text>(find.byType(Text)).map((t) => t.data ?? '').join('\n');
- expect(everything, isNot(matches(RegExp(r'\d{4}-\d{2}-\d{2}'))));
- });
-
- testWidgets('a row, or its Details button, opens that device with its whole code', (tester) async {
- await openList(tester);
- await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('Old laptop')));
- await tester.pump();
- await tester.pump();
- expect(find.text('AAAA·0001·0001·0001'), findsOneWidget);
- expect(find.text(fingerprintHowToCompare(computer: true)), findsOneWidget);
- expect(find.byKey(const Key('device-detail-mine')), findsNothing);
- await tester.tap(find.byKey(const Key('device-detail-close')));
- await tester.pump();
- expect(find.text('AAAA·0001·0001·0001'), findsNothing);
-
- await tester.tap(find.byKey(const ValueKey('account-device-details-phone-b')));
- await tester.pump();
- await tester.pump();
- expect(find.text('CCCC·0003·0003·0003'), findsOneWidget);
- expect(find.text(fingerprintHowToCompare(computer: false)), findsOneWidget);
- expect(app.loads, 1, reason: 'the detail uses the row, it does not read the list again');
- });
-
- testWidgets('It’s mine in a new device’s detail takes its badge off; closing without it does not', (tester) async {
- await openList(tester);
- final badge = find.descendant(of: find.byKey(const ValueKey('account-device-new')), matching: find.text('New'));
- await tester.tap(find.byKey(const ValueKey('account-device-details-new')));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('device-detail-close')));
- await tester.pump();
- expect(badge, findsOneWidget);
-
- await tester.tap(find.byKey(const ValueKey('account-device-details-new')));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('device-detail-mine')));
- await tester.pump();
- expect(find.text('EEEE·0005·0005·0005'), findsNothing);
- expect(badge, findsNothing);
- });
-
- testWidgets('Remove on a row still asks first, then takes the device out of the list', (tester) async {
- await openList(tester);
- await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('Remove')));
- await tester.pump();
- expect(find.text('Remove Old laptop?'), findsOneWidget);
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- await tester.pump();
- expect(app.removed, ['old']);
- expect(find.byKey(const ValueKey('account-device-old')), findsNothing);
- });
- });
-
- group('what the log kept', () {
- late FakeDevicesApp app;
- tearDown(() => app.dispose());
-
- Future<void> open(WidgetTester tester, AccountDevices devices) async {
- app = FakeDevicesApp()..devices = devices;
- tester.view.physicalSize = const Size(1200, 1600);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
- await tester.pump();
- await tester.pump();
- }
-
- testWidgets('a refusal to register is said: too many devices plainly, any other with its code', (tester) async {
- await open(tester, AccountDevices.fromDaemon({
- 'members': <Object>[],
- 'pending': <Object>[],
- 'registerError': 'TOO_MANY',
- })!);
- expect(
- find.text('This device couldn’t join: your account has too many devices. Remove ones you no longer use.'),
- findsOneWidget,
- );
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], registerError: 'FORBIDDEN'));
- expect(find.text('This device couldn’t join your account’s device list (FORBIDDEN).'), findsOneWidget);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- // A daemon that predates the field: nothing.
- await open(tester, AccountDevices.fromDaemon({'members': <Object>[], 'pending': <Object>[]})!);
- expect(find.byKey(const Key('account-devices-refused')), findsNothing);
- });
-
- testWidgets('a device the daemon kept as pending is badged New though no banner is up', (tester) async {
- await open(tester, AccountDevices(
- devices: [fakeDevice('me', self: true), fakeDevice('old'), fakeDevice('late', label: 'Late iPad')],
- pending: const ['late'],
- ));
- expect(find.descendant(of: find.byKey(const ValueKey('account-device-late')), matching: find.text('New')), findsOneWidget);
- expect(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('New')), findsNothing);
- // Looking at the list is seeing them: what it read as pending is written back, once.
- expect(app.seenPending, [['late']]);
- });
-
- testWidgets('a device that turns up while the list is open is badged New too (it is pending)', (tester) async {
- // E2E 2026-10-01: a forged key added while Your devices was open stayed pending (the banner came
- // back on leaving) but its row had no badge — `New` must follow `pending`, as on the phone.
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('old')], pending: const []));
- app.devices = AccountDevices(
- devices: [fakeDevice('me', self: true), fakeDevice('old'), fakeDevice('evil', label: 'Evil Chrome')],
- pending: const ['evil'],
- );
- app.devicesRevision++;
- app.notifyListeners();
- await tester.pump();
- await tester.pump();
- expect(find.descendant(of: find.byKey(const ValueKey('account-device-evil')), matching: find.text('New')), findsOneWidget);
- expect(find.descendant(of: find.byKey(const ValueKey('account-device-old')), matching: find.text('New')), findsNothing);
- // Only the first read of the visit is written back as seen.
- expect(app.seenPending, [<String>[]]);
- });
-
- testWidgets('the baseline panel names what was there before this device joined; Got it persists and hides it', (tester) async {
- await open(tester, AccountDevices(
- devices: [
- AccountDevice(pub: 'me', label: 'MacBook', kind: 'machine', machineId: 'm', addedAt: DateTime(2026, 9, 1), fingerprint: 'AAAA·1', self: true, seq: 1),
- AccountDevice(pub: 'old', label: 'Old iPad', kind: 'viewer', machineId: '', addedAt: DateTime(2026, 9, 1), fingerprint: 'BBBB·2', self: false, seq: 2),
- AccountDevice(pub: 'later', label: 'Later', kind: 'viewer', machineId: '', addedAt: DateTime(2026, 9, 2), fingerprint: 'CCCC·3', self: false, seq: 5),
- ],
- joinedSeq: 3,
- baselineSeen: false,
- ));
- final panel = find.byKey(const Key('account-devices-baseline'));
- expect(find.descendant(of: panel, matching: find.text('Already on your account')), findsOneWidget);
- expect(find.descendant(of: panel, matching: find.text('These were on your account before this device joined. If one isn’t yours, remove it.')), findsOneWidget);
- expect(find.descendant(of: panel, matching: find.text('Old iPad · App · BBBB·2')), findsOneWidget);
- expect(find.descendant(of: panel, matching: find.textContaining('Later')), findsNothing);
- await tester.tap(find.byKey(const Key('account-devices-baseline-gotit')));
- await tester.pump();
- expect(app.baselineSeenCalls, 1);
- expect(panel, findsNothing);
- });
-
- testWidgets('no panel once the baseline was seen, or when the daemon sends no joined point', (tester) async {
- await open(tester, AccountDevices(
- devices: [fakeDevice('me', self: true), fakeDevice('old')],
- joinedSeq: 3,
- ));
- expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('old')], baselineSeen: false));
- expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
- });
-
- testWidgets('a suspended device wears Suspended instead of New, and its detail says why', (tester) async {
- await open(tester, AccountDevices(
- devices: [
- fakeDevice('me', self: true),
- AccountDevice(pub: 'sus', label: 'Odd Mac', kind: 'machine', machineId: 'abcdef0123456789', addedAt: DateTime(2026, 9, 1), fingerprint: 'DDDD·4', self: false, suspended: true, pending: true),
- ],
- pending: const ['sus'],
- ));
- final row = find.byKey(const ValueKey('account-device-sus'));
- expect(find.descendant(of: row, matching: find.text('Suspended')), findsOneWidget);
- expect(find.descendant(of: row, matching: find.text('New')), findsNothing);
- await tester.tap(find.byKey(const ValueKey('account-device-details-sus')));
- await tester.pump();
- await tester.pump();
- expect(
- find.text('Not trusted here: added after this device’s list and another’s split. Review the list to trust it again.'),
- findsOneWidget,
- );
- });
-
- testWidgets('Trust again confirms the previewed head; a list that changed meanwhile says so and is previewed again', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
- app.previews
- ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
- ..add(const DevicesRebaseline(added: ['iPad', 'Mac'], removed: [], head: DevLogHead(8, 'h8')));
- app.confirmAnswer = const DevicesRebaseline.changed();
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(app.confirmedHeads.single?.seq, 7);
- expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsOneWidget);
- // The new preview is up, with the extra device.
- expect(find.textContaining('+ Mac'), findsOneWidget);
- });
-
- group('Trust again on another account\'s list says to sign in again', () {
- const message =
- 'The device list now belongs to a different account than the one you signed in with. Sign in again to switch accounts.';
-
- testWidgets('at the preview: nothing to confirm', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
- app.previews.add(const DevicesRebaseline.otherAccount());
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- expect(find.text(message), findsOneWidget);
- expect(find.byKey(const Key('account-device-confirm')), findsNothing);
- expect(app.confirmedHeads, isEmpty);
- });
-
- testWidgets('at the confirm: said once, not previewed again', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
- app.previews.add(const DevicesRebaseline(added: [], removed: [], head: DevLogHead(7, 'h7')));
- app.confirmAnswer = const DevicesRebaseline.otherAccount();
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(find.text(message), findsOneWidget);
- expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsNothing);
- expect(find.byKey(const Key('account-device-confirm')), findsNothing);
- expect(app.confirmedHeads, hasLength(1));
- });
- });
-
- // One convention: what is only a state to review again (another account's list, a list that changed
- // while it was reviewed) is the warning amber; every other failure is red.
- testWidgets('error colours: unreadable list, a failed trust and a failed remove are red; a list that changed is amber', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true), fakeDevice('b')], frozenReason: 'fork'));
- Color? colourOf(String text) => tester.widget<Text>(find.text(text)).style?.color;
- // The preview cannot be read.
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- expect(colourOf('Couldn’t read a valid device list. Try again later.'), AppColors.danger);
- // The trust is refused for another reason than the list changing.
- app.previews.add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
- app.confirmAnswer = null;
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(colourOf('Couldn’t trust the device list again. Try again later.'), AppColors.danger);
- // A removal that fails.
- app.removeError = 'UNAVAILABLE';
- await tester.tap(find.descendant(of: find.byKey(const ValueKey('account-device-b')), matching: find.text('Remove')));
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(colourOf('Couldn’t remove iPad (UNAVAILABLE). Try again.'), AppColors.danger);
- // LOG_CHANGED: amber, and the colour does not stick to the next error.
- app.previews
- ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
- ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(8, 'h8')));
- app.confirmAnswer = const DevicesRebaseline.changed();
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(colourOf('The device list changed while you were reviewing it. Review it again.'), AppColors.warning);
- });
-
- testWidgets('Trust again: an unreadable list says so; a later success clears the message', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
- app.previews
- ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')))
- ..add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
- app.confirmAnswer = null;
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(find.text('Couldn’t trust the device list again. Try again later.'), findsOneWidget);
- expect(find.text('The device list changed while you were reviewing it. Review it again.'), findsNothing);
-
- app.confirmAnswer = const DevicesRebaseline(added: [], removed: [], head: DevLogHead(7, 'h7'));
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- await tester.tap(find.byKey(const Key('account-device-confirm')));
- await tester.pump();
- await tester.pump();
- expect(find.text('Couldn’t trust the device list again. Try again later.'), findsNothing);
- });
-
- testWidgets('opening the list marks seen only the banner as it was when the list was read', (tester) async {
- final gate = Completer<void>();
- app = FakeDevicesApp()
- ..devices = AccountDevices(devices: [fakeDevice('me', self: true)])
- ..newDevices.add(const NewDeviceNotice(pub: 'new', label: 'N', kind: 'viewer'));
- app.loadGate = gate;
- // The banner holds `new` when the listing is read.
- app.bannerAtRead = () => ['new'];
- tester.view.physicalSize = const Size(1200, 1600);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
- await tester.pump();
- // A device announced while the read waits.
- app.newDevices.add(const NewDeviceNotice(pub: 'late', label: 'L', kind: 'viewer'));
- gate.complete();
- await tester.pump();
- await tester.pump();
- expect(app.seenShown.single, ['new']);
- expect(app.newDevices.map((d) => d.pub), ['late']);
- });
-
- testWidgets('the departed keys the listing read are handed over, so a banner that still names one does not mark it seen', (tester) async {
- app = FakeDevicesApp()
- ..devices = AccountDevices(devices: [fakeDevice('me', self: true)], departed: ['gone'])
- ..newDevices.add(const NewDeviceNotice(pub: 'gone', label: 'G', kind: 'viewer'));
- tester.view.physicalSize = const Size(1200, 1600);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: AccountDevicesSection(notifier: app))));
- await tester.pump();
- await tester.pump();
- expect(app.seenDeparted.single, ['gone']);
- });
-
- testWidgets('Trust again is confirmed with the destructive (red) button, like Remove', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'fork'));
- app.previews.add(const DevicesRebaseline(added: ['iPad'], removed: [], head: DevLogHead(7, 'h7')));
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- final confirm = tester.widget<FilledButton>(find.byKey(const Key('account-device-confirm')));
- expect(confirm.style?.backgroundColor?.resolve(const {}), grid.AppPalette.dangerFill);
- });
-
- testWidgets('the OTHER_ACCOUNT message is the warning amber', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], frozenReason: 'invalid'));
- app.previews.add(const DevicesRebaseline.otherAccount());
- await tester.tap(find.text('Review…'));
- await tester.pump();
- await tester.pump();
- final text = tester.widget<Text>(find.text(otherAccountMessage));
- expect(text.style?.color, grid.AppPalette.warn);
- });
-
- testWidgets('History… opens the history; a daemon that predates it gets the update hint instead', (tester) async {
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)]));
- expect(find.byKey(const Key('account-devices-history-hint')), findsNothing);
- expect(find.text('History…'), findsOneWidget);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- await open(tester, AccountDevices(devices: [fakeDevice('me', self: true)], historyAvailable: false));
- expect(find.text('History…'), findsNothing);
- expect(find.text('Update Harness on this computer to see history.'), findsOneWidget);
- });
- });
-}
diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dart
index 2d87d8fcc..840147365 100644
--- a/desktop/test/add_phone_dialog_test.dart
+++ b/desktop/test/add_phone_dialog_test.dart
@@ -16,6 +16,8 @@ import 'package:harness/shared/widgets/qr_code_view.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/add_phone_dialog.dart';
+import 'support/resource_picker.dart' show resourceScope;
+
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount;
import 'swarm_state_test.dart' show createApp, MemoryStore;
@@ -319,7 +321,7 @@ void main() {
group('the account\'s devices', () {
testWidgets(
- 'are one link away — Settings ▸ Your devices — not a list in here',
+ 'are one link away — Machines — not a list in here',
(tester) async {
final app = _signedInApp();
addTearDown(app.dispose);
@@ -336,7 +338,7 @@ void main() {
expect(find.text('Manage devices…'), findsOneWidget);
await tester.tap(link);
await tester.pump();
- // The dialog makes way for Settings: one is open at a time.
+ // The dialog makes way for Machines: one is open at a time.
expect(opened, 1);
expect(find.byType(AddPhoneDialog), findsNothing);
await tester.pump(const Duration(seconds: 10));
@@ -683,10 +685,10 @@ void main() {
});
testWidgets(
- 'Manage devices… makes way for Settings ▸ Your devices, which opens',
+ 'Manage devices… makes way for Machines, which opens',
(tester) async {
// The dialog is still this screen's open dialog while it pops, so a
- // Settings asked for from the link itself was silently refused.
+ // picker asked for from the link itself was silently refused.
final app = _signedInApp();
addTearDown(app.dispose);
await mount(tester, app);
@@ -706,7 +708,8 @@ void main() {
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.byType(AddPhoneDialog), findsNothing);
- expect(find.text('Your devices'), findsWidgets);
+ // Machines, where the account's phones and apps are listed now.
+ expect(resourceScope('@'), findsOneWidget);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(seconds: 10));
},
diff --git a/desktop/test/agents_section_test.dart b/desktop/test/agents_section_test.dart
new file mode 100644
index 000000000..f09169d8c
--- /dev/null
+++ b/desktop/test/agents_section_test.dart
@@ -0,0 +1,291 @@
+// Settings ▸ Agents: what the agents on this computer may do with Harness, kept by this computer's
+// daemon (`/api/agent-settings`). The page shows a change once the daemon answers with it; a setting
+// the daemon does not name (an older daemon) is not offered.
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/settings/agent_settings.dart';
+import 'package:harness/settings/sections/agents_section.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+/// This computer's daemon, as far as the page can tell.
+class _Daemon {
+ _Daemon([Map<String, dynamic>? settings])
+ : settings =
+ settings ?? {'agentsStartAgents': true, 'pullRequestLine': true};
+
+ Map<String, dynamic>? settings;
+ Object? readError;
+ Object? writeError;
+ Completer<void>? writeGate;
+ int reads = 0;
+ final writes = <(String, bool)>[];
+
+ Future<Map<String, dynamic>?> read() async {
+ reads++;
+ if (readError case final error?) throw error;
+ return settings == null ? null : Map.of(settings!);
+ }
+
+ Future<Map<String, dynamic>> write(String key, bool value) async {
+ writes.add((key, value));
+ await writeGate?.future;
+ if (writeError case final error?) throw error;
+ settings![key] = value;
+ return Map.of(settings!);
+ }
+
+ AgentSettingsStore store() => AgentSettingsStore(read: read, write: write);
+}
+
+void main() {
+ Future<AgentSettingsStore> open(
+ WidgetTester tester,
+ AgentSettingsStore store,
+ ) async {
+ addTearDown(store.dispose);
+ tester.view.physicalSize = const Size(1000, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(body: AgentsSection(store: store)),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return store;
+ }
+
+ Switch switchFor(WidgetTester tester, AgentSetting setting) =>
+ tester.widget<Switch>(
+ find.byKey(ValueKey('agent-setting-switch-${setting.key}')),
+ );
+
+ testWidgets('both rows load from the daemon, with their copy', (
+ tester,
+ ) async {
+ final daemon = _Daemon({
+ 'agentsStartAgents': false,
+ 'pullRequestLine': true,
+ });
+ await open(tester, daemon.store());
+ expect(find.text('Agents can start other agents'), findsOneWidget);
+ expect(
+ find.text(
+ 'Claude Code and Codex can start, wait for and close harnesses of their own, and their '
+ 'instructions say how. Turn off to keep every agent working alone.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text('Mark pull requests from agent-started harnesses'),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'A harness another agent started adds one line to the pull requests it opens: '
+ '🤝 Started by another agent in Harness.',
+ ),
+ findsOneWidget,
+ );
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).value, isFalse);
+ expect(switchFor(tester, AgentSetting.pullRequestLine).value, isTrue);
+ expect(daemon.reads, 1);
+ });
+
+ testWidgets(
+ 'a toggle sends only its key, and shows once the daemon says so',
+ (tester) async {
+ final daemon = _Daemon()..writeGate = Completer<void>();
+ await open(tester, daemon.store());
+ await tester.tap(
+ find.byKey(const ValueKey('agent-setting-switch-agentsStartAgents')),
+ );
+ await tester.pump();
+ expect(daemon.writes, [('agentsStartAgents', false)]);
+ expect(find.text('Saving…'), findsOneWidget);
+ // Not before the answer.
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).value, isTrue);
+ expect(
+ switchFor(tester, AgentSetting.pullRequestLine).onChanged,
+ isNull,
+ reason: 'one change at a time',
+ );
+ daemon.writeGate!.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Saving…'), findsNothing);
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).value, isFalse);
+
+ daemon.writeGate = null;
+ await tester.tap(
+ find.byKey(const ValueKey('agent-setting-switch-pullRequestLine')),
+ );
+ await tester.pumpAndSettle();
+ expect(daemon.writes.last, ('pullRequestLine', false));
+ expect(switchFor(tester, AgentSetting.pullRequestLine).value, isFalse);
+ },
+ );
+
+ testWidgets('a failed change says why, keeps the value, and offers Refresh', (
+ tester,
+ ) async {
+ final daemon = _Daemon()..writeError = ApiException('Nothing to change.');
+ await open(tester, daemon.store());
+ await tester.tap(
+ find.byKey(const ValueKey('agent-setting-switch-agentsStartAgents')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('agent-settings-error')), findsOneWidget);
+ expect(find.text('Nothing to change.'), findsOneWidget);
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).value, isTrue);
+ daemon.writeError = null;
+ await tester.tap(find.text('Refresh setting'));
+ await tester.pumpAndSettle();
+ expect(daemon.reads, 2);
+ expect(find.text('Nothing to change.'), findsNothing);
+ });
+
+ testWidgets(
+ 'a daemon that does not name pullRequestLine does not get its row',
+ (tester) async {
+ await open(tester, _Daemon({'agentsStartAgents': true}).store());
+ expect(find.text('Agents can start other agents'), findsOneWidget);
+ expect(
+ find.text('Mark pull requests from agent-started harnesses'),
+ findsNothing,
+ );
+ },
+ );
+
+ testWidgets('a daemon that predates the settings is told to update', (
+ tester,
+ ) async {
+ final daemon = _Daemon()..settings = null;
+ await open(tester, daemon.store());
+ expect(
+ find.text('Update Harness on this computer to change this.'),
+ findsOneWidget,
+ );
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).onChanged, isNull);
+ expect(
+ find.text('Mark pull requests from agent-started harnesses'),
+ findsNothing,
+ );
+ });
+
+ testWidgets('no daemon: disabled, with why and Refresh', (tester) async {
+ final daemon = _Daemon()..readError = StateError('no daemon');
+ await open(tester, daemon.store());
+ expect(find.byKey(const Key('agent-settings-reason')), findsOneWidget);
+ expect(find.textContaining('Couldn’t reach Harness'), findsOneWidget);
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).onChanged, isNull);
+ daemon.readError = null;
+ await tester.tap(find.text('Refresh setting'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('agent-settings-reason')), findsNothing);
+ expect(
+ switchFor(tester, AgentSetting.agentsStartAgents).onChanged,
+ isNotNull,
+ );
+ expect(
+ find.text('Mark pull requests from agent-started harnesses'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('in a browser: disabled, saying where it is changed', (
+ tester,
+ ) async {
+ await open(
+ tester,
+ AgentSettingsStore(unavailable: 'Change this in the Harness app.'),
+ );
+ expect(find.text('Change this in the Harness app.'), findsOneWidget);
+ expect(switchFor(tester, AgentSetting.agentsStartAgents).onChanged, isNull);
+ expect(find.text('Refresh setting'), findsNothing);
+ });
+
+ group('the client', () {
+ late HttpServer server;
+ late ApiClient api;
+ final requests = <(String, String, String?, String)>[];
+ var answer = <String, dynamic>{'agentsStartAgents': true};
+ var status = 200;
+
+ setUp(() async {
+ requests.clear();
+ answer = {'agentsStartAgents': true};
+ status = 200;
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) async {
+ final body = await utf8.decoder.bind(request).join();
+ requests.add((
+ request.method,
+ request.uri.path,
+ request.headers.value('x-adapter-local'),
+ body,
+ ));
+ request.response
+ ..statusCode = status
+ ..headers.contentType = ContentType.json
+ ..write(jsonEncode(answer));
+ await request.response.close();
+ });
+ api = ApiClient(
+ config: AppConfig(
+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',
+ apiBaseUrl: 'http://unused.invalid',
+ ),
+ session: AuthSession(storage: MemoryStore()),
+ );
+ });
+ tearDown(() => server.close(force: true));
+
+ test('reads the bare settings the daemon answers', () async {
+ expect(await api.agentSettings(), {'agentsStartAgents': true});
+ expect(requests.single.$1, 'GET');
+ expect(requests.single.$2, '/api/agent-settings');
+ });
+
+ test('writes one key with the local header', () async {
+ answer = {'agentsStartAgents': false, 'pullRequestLine': true};
+ expect(await api.setAgentSetting('agentsStartAgents', false), {
+ 'agentsStartAgents': false,
+ 'pullRequestLine': true,
+ });
+ final (method, path, local, body) = requests.single;
+ expect([method, path, local], ['PATCH', '/api/agent-settings', '1']);
+ expect(jsonDecode(body), {'agentsStartAgents': false});
+ });
+
+ test(
+ 'a daemon without the route reads as none; a refusal throws its message',
+ () async {
+ status = 404;
+ answer = {'error': 'NOT_FOUND'};
+ expect(await api.agentSettings(), isNull);
+ status = 400;
+ answer = {
+ 'error': {'code': 'BAD_REQUEST', 'message': 'Nothing to change.'},
+ };
+ await expectLater(
+ api.setAgentSetting('agentsStartAgents', true),
+ throwsA(
+ isA<ApiException>().having(
+ (e) => e.message,
+ 'message',
+ 'Nothing to change.',
+ ),
+ ),
+ );
+ },
+ );
+ });
+}
diff --git a/desktop/test/autonomous_device_pairing_test.dart b/desktop/test/autonomous_device_pairing_test.dart
deleted file mode 100644
index b1e866209..000000000
--- a/desktop/test/autonomous_device_pairing_test.dart
+++ /dev/null
@@ -1,566 +0,0 @@
-import 'dart:async';
-import 'dart:ui' show SemanticsAction;
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/autonomous_device/autonomous_device_cli.dart';
-import 'package:harness/shared/widgets/app_icon_button.dart';
-import 'package:harness/shared/widgets/app_select_field.dart';
-import 'package:harness/shared/widgets/skeleton.dart';
-import 'package:harness/shared/widgets/setting_row.dart';
-import 'package:harness/settings/sections/devices_section.dart';
-
-class FakeAutonomousDeviceCli extends AutonomousDeviceCli {
- bool unsupported = false;
- int statusCalls = 0;
- Completer<void>? statusWait;
- Completer<void>? pairWait;
- String? pairFailure;
- bool networkBlocked = false;
- List<Map<String, dynamic>> discovered = [
- {'id': 'device-1', 'name': 'Kitchen', 'host': '192.168.1.2', 'port': 5000},
- ];
- List<Map<String, dynamic>> devices = [];
- final submissions = <Map<String, dynamic>>[];
- final revoked = <String>[];
- @override
- Future<Map<String, dynamic>> status() async {
- statusCalls++;
- if (statusWait != null) await statusWait!.future;
- if (unsupported) {
- throw const AutonomousDeviceCliException('NOT_FOUND', 'Unsupported CLI');
- }
- return {'transport': 'direct', 'connected': true, 'paired': devices.length};
- }
-
- @override
- Future<Map<String, dynamic>> list() async => {'devices': devices};
- @override
- Future<Map<String, dynamic>> discover() async {
- if (networkBlocked) {
- throw const AutonomousDeviceCliException(
- 'LOCAL_NETWORK_BLOCKED',
- 'Harness is not allowed to use the local network.',
- );
- }
- return {'devices': discovered};
- }
-
- @override
- Future<Map<String, dynamic>> pair({
- required String code,
- required String deviceId,
- }) async {
- submissions.add({'code': code, 'deviceId': deviceId});
- if (pairWait != null) await pairWait!.future;
- if (pairFailure != null) {
- throw AutonomousDeviceCliException('CODE_MISMATCH', pairFailure!);
- }
- // The real CLI persists the trust, so the next `list` is what reports it.
- devices.add({
- 'id': 'fingerprint-$deviceId',
- 'fingerprint': 'fingerprint-$deviceId',
- 'label': 'Autonomous robot',
- 'online': true,
- });
- return {
- 'state': 'paired',
- 'label': 'Autonomous robot',
- 'fingerprint': 'fingerprint-$deviceId',
- };
- }
-
- @override
- Future<Map<String, dynamic>> revoke(String id) async {
- revoked.add(id);
- devices.removeWhere((device) => device['id'] == id);
- return {'revoked': 1};
- }
-}
-
-void main() {
- Future<void> open(WidgetTester tester, FakeAutonomousDeviceCli cli) async {
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(body: DevicesSection(cli: cli)),
- ),
- );
- await tester.pumpAndSettle();
- }
-
- final codeField = find.byKey(const Key('autonomous-device-code'));
- Future<void> select(WidgetTester tester, String id) async {
- tester
- .widget<AppSelectField<String?>>(
- find.byKey(const Key('autonomous-device-selection')),
- )
- .onChanged(id);
- await tester.pumpAndSettle();
- }
-
- Future<void> submit(WidgetTester tester, String code) async {
- await tester.enterText(codeField, code);
- await tester.testTextInput.receiveAction(TextInputAction.done);
- await tester.pumpAndSettle();
- }
-
- Future<void> refresh(WidgetTester tester) async {
- await tester.ensureVisible(find.byType(AppIconButton));
- await tester.tap(find.byType(AppIconButton));
- await tester.pumpAndSettle();
- }
-
- testWidgets(
- 'pairing controls keep separate accessible purposes and actions',
- (tester) async {
- final semantics = tester.ensureSemantics();
- try {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- final picker = find.bySemanticsLabel('Autonomous robot');
- final pickerNode = tester.getSemantics(picker);
- final codeNode = tester.getSemantics(
- find.bySemanticsLabel('Six-character code'),
- );
- final refreshNode = tester.getSemantics(
- find.byTooltip('Refresh Autonomous robot status'),
- );
- expect(pickerNode.getSemanticsData().label, 'Autonomous robot');
- expect(pickerNode.getSemanticsData().value, 'Select a device');
- expect(pickerNode.getSemanticsData().flagsCollection.isButton, isTrue);
- expect(codeNode.id, isNot(pickerNode.id));
- expect(codeNode.getSemanticsData().flagsCollection.isTextField, isTrue);
- expect(
- codeNode.getSemanticsData().hasAction(SemanticsAction.tap),
- isTrue,
- );
- expect(refreshNode.id, isNot(pickerNode.id));
- expect(
- refreshNode.getSemanticsData().tooltip,
- 'Refresh Autonomous robot status',
- );
- expect(
- refreshNode.getSemanticsData().hasAction(SemanticsAction.tap),
- isTrue,
- );
- await select(tester, 'device-1');
- expect(tester.getSemantics(picker).getSemanticsData().value, 'Kitchen');
- expect(cli.submissions, isEmpty);
- await tester.pumpWidget(const SizedBox());
- } finally {
- semantics.dispose();
- }
- },
- );
-
- testWidgets(
- 'code input and discovery are immediate without address or intent',
- (tester) async {
- await open(tester, FakeAutonomousDeviceCli());
- expect(codeField, findsOneWidget);
- expect(
- find.textContaining('Separators are allowed, for example ABC-123.'),
- findsOneWidget,
- );
- expect(
- find.byKey(const Key('autonomous-device-selection')),
- findsOneWidget,
- );
- expect(find.byType(SettingRow), findsOneWidget);
- expect(find.text('Pair'), findsOneWidget);
- expect(find.text('Refresh'), findsNothing);
- expect(find.text('Pair an Autonomous robot'), findsNothing);
- expect(find.text('Computer address'), findsNothing);
- expect(find.text('Cancel pairing'), findsNothing);
- },
- );
- testWidgets(
- 'a blocked local network says where to allow it and keeps paired robots listed',
- (tester) async {
- final cli = FakeAutonomousDeviceCli()
- ..networkBlocked = true
- ..devices = [
- {
- 'id': 'fingerprint-1',
- 'fingerprint': 'fingerprint-1',
- 'label': 'Desk lamp',
- 'online': false,
- },
- ];
- await open(tester, cli);
- final notice = find.byKey(const Key('autonomous-device-network-blocked'));
- expect(notice, findsOneWidget);
- expect(find.text('Allow Harness on your local network'), findsOneWidget);
- expect(find.text('Desk lamp'), findsOneWidget);
- expect(find.textContaining('No Autonomous robots found'), findsNothing);
-
- cli.networkBlocked = false;
- await refresh(tester);
- expect(notice, findsNothing);
- expect(find.text('Desk lamp'), findsOneWidget);
- },
- );
- testWidgets('pairing controls align with the title and explain persistence', (
- tester,
- ) async {
- await open(tester, FakeAutonomousDeviceCli());
- final title = find.text('Pair a device');
- final selection = find.byKey(const Key('autonomous-device-selection'));
- expect(
- tester.getTopLeft(selection).dy,
- closeTo(tester.getTopLeft(title).dy, 1),
- );
- expect(
- find.text(
- 'Harness CLI keeps the connection running when you close Desktop.',
- ),
- findsOneWidget,
- );
- expect(tester.takeException(), isNull);
- });
- testWidgets('an existing pairing makes the form an addition', (tester) async {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- expect(find.text('Pair a device'), findsOneWidget);
- // The CLI keeps every pairing, so the form adds rather than replaces.
- cli.devices = [
- {
- 'id': 'fingerprint-1',
- 'fingerprint': 'fingerprint-1',
- 'label': 'Kitchen',
- 'online': true,
- },
- ];
- await tester.tap(find.byType(AppIconButton));
- await tester.pumpAndSettle();
- expect(find.text('Pair another device'), findsOneWidget);
- expect(find.text('Pair a device'), findsNothing);
- });
-
- testWidgets('single discovered device still requires explicit selection', (
- tester,
- ) async {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- await submit(tester, 'ABC234');
- expect(cli.submissions, isEmpty);
- expect(
- find.text('Select your discovered Autonomous robot first.'),
- findsOneWidget,
- );
- });
- testWidgets(
- 'normalizes original Harness code and binds selected discovery identity',
- (tester) async {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- await select(tester, 'device-1');
- await submit(tester, 'o-i_l·u23');
- expect(cli.submissions, [
- {'code': '011V23', 'deviceId': 'device-1'},
- ]);
- expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
- expect(find.text('Connected · fingerprint-device-1'), findsOneWidget);
- },
- );
- testWidgets('changing selected device clears typed code', (tester) async {
- final cli = FakeAutonomousDeviceCli()
- ..discovered.add({'id': 'device-2', 'name': 'Desk'});
- await open(tester, cli);
- await select(tester, 'device-1');
- await tester.enterText(codeField, 'ABC234');
- await select(tester, 'device-2');
- expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
- });
-
- for (final (outcome, error) in [
- (
- 'failure',
- const AutonomousDeviceCliException('CODE_MISMATCH', 'Mismatch'),
- ),
- (
- 'cancellation',
- const AutonomousDeviceCliException('CANCELLED', 'Pairing was cancelled.'),
- ),
- ]) {
- testWidgets(
- 'pending device selection ignores keys and recovers after $outcome',
- (tester) async {
- tester.view.physicalSize = const Size(880, 560);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- final semantics = tester.ensureSemantics();
- try {
- final pending = Completer<void>();
- final cli = FakeAutonomousDeviceCli()
- ..pairWait = pending
- ..discovered.add({'id': 'device-2', 'name': 'Desk'});
- await open(tester, cli);
- final picker = find.byKey(const Key('autonomous-device-selection'));
- await tester.tap(picker);
- await tester.pumpAndSettle();
- await tester.tap(find.text('Kitchen').last);
- await tester.pumpAndSettle();
- final previousSelection = tester
- .widget<AppSelectField<String?>>(picker)
- .onChanged;
- await tester.enterText(codeField, 'ABC234');
- await tester.tap(find.text('Pair'));
- await tester.pump();
- expect(find.text('Pairing…'), findsOneWidget);
- final pendingPicker = tester
- .getSemantics(find.bySemanticsLabel('Autonomous robot'))
- .getSemanticsData();
- expect(pendingPicker.label, 'Autonomous robot');
- expect(pendingPicker.value, 'Kitchen');
- expect(pendingPicker.hasAction(SemanticsAction.tap), isFalse);
- expect(cli.submissions, [
- {'code': 'ABC234', 'deviceId': 'device-1'},
- ]);
-
- // The pending selector is unavailable to Tab/Enter just as it is to a
- // pointer, so the displayed device cannot diverge from this operation.
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(find.text('Desk'), findsNothing);
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- // A selection queued before the pending rebuild follows the same guard.
- previousSelection('device-2');
- await tester.pump();
- expect(
- tester.widget<AppSelectField<String?>>(picker).value,
- 'device-1',
- );
- expect(cli.submissions, hasLength(1));
-
- pending.completeError(error);
- await tester.pumpAndSettle();
- expect(find.text(error.userMessage), findsOneWidget);
- expect(tester.widget<TextField>(codeField).enabled, isTrue);
- final editablePicker = tester
- .getSemantics(find.bySemanticsLabel('Autonomous robot'))
- .getSemanticsData();
- expect(editablePicker.label, 'Autonomous robot');
- expect(editablePicker.value, 'Kitchen');
- expect(editablePicker.flagsCollection.isButton, isTrue);
- expect(editablePicker.hasAction(SemanticsAction.tap), isTrue);
- for (
- var i = 0;
- i < 4 && !Focus.of(tester.element(find.text('Kitchen'))).hasFocus;
- i++
- ) {
- await tester.sendKeyEvent(LogicalKeyboardKey.tab);
- await tester.pump();
- }
- expect(
- Focus.of(tester.element(find.text('Kitchen'))).hasFocus,
- isTrue,
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(find.text('Desk'), findsOneWidget);
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pumpAndSettle();
- expect(
- tester.widget<AppSelectField<String?>>(picker).value,
- 'device-2',
- );
- expect(find.text(error.userMessage), findsNothing);
- cli.pairWait = null;
- await submit(tester, 'DEF567');
- expect(cli.submissions.map((row) => row['deviceId']), [
- 'device-1',
- 'device-2',
- ]);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- } finally {
- semantics.dispose();
- }
- },
- );
- }
- testWidgets('lost discovery clears selection and never retargets code', (
- tester,
- ) async {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- await select(tester, 'device-1');
- await tester.enterText(codeField, 'ABC234');
- cli.discovered = [
- {'id': 'device-2', 'name': 'Desk'},
- ];
- await refresh(tester);
- expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
- expect(
- tester
- .widget<AppSelectField<String?>>(
- find.byKey(const Key('autonomous-device-selection')),
- )
- .value,
- isNull,
- );
- expect(cli.submissions, isEmpty);
- });
- testWidgets('code mismatch persists through successful status refresh', (
- tester,
- ) async {
- final cli = FakeAutonomousDeviceCli()..pairFailure = 'CODE_MISMATCH';
- await open(tester, cli);
- await select(tester, 'device-1');
- await submit(tester, 'ABC234');
- await refresh(tester);
- expect(
- find.text(
- 'That code did not match. Generate a new code on your Autonomous robot, then try again.',
- ),
- findsOneWidget,
- );
- });
-
- testWidgets(
- 'revocation confirms and targets the exact existing trust fingerprint',
- (tester) async {
- final cli = FakeAutonomousDeviceCli()
- ..devices = [
- {
- 'id': 'fingerprint-1',
- 'fingerprint': 'fingerprint-1',
- 'label': 'Kitchen',
- 'online': true,
- },
- {
- 'id': 'fingerprint-2',
- 'fingerprint': 'fingerprint-2',
- 'label': 'Desk',
- 'online': false,
- },
- ];
- await open(tester, cli);
- await tester.tap(find.text('Revoke').first);
- await tester.pumpAndSettle();
- expect(cli.revoked, isEmpty);
- await tester.tap(find.byKey(const Key('device-confirm')));
- await tester.pumpAndSettle();
- expect(cli.revoked, ['fingerprint-1']);
- expect(cli.devices.single['id'], 'fingerprint-2');
- },
- );
-
- testWidgets(
- 'empty discovery gives network guidance without implicit target',
- (tester) async {
- final cli = FakeAutonomousDeviceCli()..discovered = [];
- await open(tester, cli);
- expect(
- find.textContaining('No Autonomous robots found.'),
- findsOneWidget,
- );
- await submit(tester, 'ABC234');
- expect(cli.submissions, isEmpty);
- },
- );
- testWidgets(
- 'retry after mismatch pairs the same explicitly selected device',
- (tester) async {
- final cli = FakeAutonomousDeviceCli()..pairFailure = 'CODE_MISMATCH';
- await open(tester, cli);
- await select(tester, 'device-1');
- await submit(tester, 'ABC234');
- cli.pairFailure = null;
- await submit(tester, 'DEF567');
- expect(cli.submissions.map((row) => row['deviceId']), [
- 'device-1',
- 'device-1',
- ]);
- expect(
- find.text(
- 'That code did not match. Generate a new code on your Autonomous robot, then try again.',
- ),
- findsNothing,
- );
- expect(find.text('Connected · fingerprint-device-1'), findsOneWidget);
- },
- );
-
- testWidgets('unsupported CLI offers update guidance', (tester) async {
- await open(tester, FakeAutonomousDeviceCli()..unsupported = true);
- expect(
- find.text('Update Harness CLI to use Autonomous robots.'),
- findsOneWidget,
- );
- expect(codeField, findsNothing);
- });
-
- testWidgets('default construction never invokes a real CLI', (tester) async {
- await tester.pumpWidget(
- const MaterialApp(home: Scaffold(body: DevicesSection())),
- );
- await tester.pumpAndSettle();
- await tester.pump(const Duration(minutes: 2));
- expect(tester.takeException(), isNull);
- expect(
- tester.widget<AppIconButton>(find.byType(AppIconButton)).onPressed,
- isNull,
- );
- });
-
- testWidgets('injected CLI has no background polling in tests', (
- tester,
- ) async {
- final cli = FakeAutonomousDeviceCli();
- await open(tester, cli);
- await tester.pump(const Duration(minutes: 2));
- expect(cli.statusCalls, 1);
- });
-
- testWidgets('first status request has a skeleton', (tester) async {
- final pending = Completer<void>();
- final cli = FakeAutonomousDeviceCli()..statusWait = pending;
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(body: DevicesSection(cli: cli)),
- ),
- );
- await tester.pump();
- expect(find.byType(SkeletonBlock), findsOneWidget);
- pending.complete();
- await tester.pumpAndSettle();
- expect(find.byType(SkeletonBlock), findsNothing);
- });
-
- test('real CLI is unavailable under tests', () async {
- await expectLater(
- AutonomousDeviceCli().status(),
- throwsA(isA<AutonomousDeviceCliException>()),
- );
- });
-
- test('pair code travels only through stdin and selected discovery identity is bound', () async {
- final cli = RecordingAutonomousDeviceCli();
- await cli.pair(code: 'ABC234', deviceId: 'device-1');
- expect(cli.arguments, ['--code-stdin', '--device', 'device-1']);
- expect(cli.arguments.join(' '), isNot(contains('ABC234')));
- expect(cli.secret, 'ABC234');
- });
-}
-
-class RecordingAutonomousDeviceCli extends AutonomousDeviceCli {
- List<String> arguments = [];
- String? secret;
- @override
- Future<Map<String, dynamic>> command(
- String operation, {
- List<String> arguments = const [],
- String? secretStdin,
- }) async {
- this.arguments = arguments;
- secret = secretStdin;
- return {'state': 'paired'};
- }
-}
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index bc2a9bad8..df3f17e37 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -1082,8 +1082,8 @@ void main() {
await tester.pumpAndSettle();
await chord(tester, LogicalKeyboardKey.comma);
await tester.pumpAndSettle();
- await tester.tap(find.text('Account'));
- await tester.pumpAndSettle();
+ // Settings opens on Account: its row in the rail and its pane.
+ expect(find.text('Account'), findsNWidgets(2));
expect(find.text('Sam'), findsOneWidget);
expect(find.text('[email protected]'), findsOneWidget);
await tester.tap(find.byKey(const Key('settings-sign-out-button')));
diff --git a/desktop/test/cabled_device_card_test.dart b/desktop/test/cabled_device_card_test.dart
deleted file mode 100644
index dc3050bbc..000000000
--- a/desktop/test/cabled_device_card_test.dart
+++ /dev/null
@@ -1,248 +0,0 @@
-// The settings pane for the robot on the cable.
-//
-// Three rules, each of which the device made necessary: the device owns the values, a row that has
-// no meaning on this face is hidden rather than greyed, and an unplugged robot is readable but not
-// writable. Each gets a test, because each is a thing that looks fine when it is wrong.
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-
-import 'package:harness/settings/sections/cabled_device_card.dart';
-import 'package:harness/state/dial_status.dart';
-
-const _round = DeviceSettings(
- brightness: 60,
- character: 0,
- face: 466,
- muted: false,
- quiet: false,
- straightTitle: false,
- focusFace: false,
- scrollReversed: false,
- round: true,
- voiceLang: 'en',
-);
-
-const _square = DeviceSettings(
- brightness: 60,
- character: 1,
- face: 720,
- muted: true,
- quiet: true,
- straightTitle: true,
- focusFace: false,
- scrollReversed: true,
- round: false,
- voiceLang: 'vi',
-);
-
-/// The pane is taller than a test viewport, so a control below the fold has to be scrolled to before
-/// it can be tapped — otherwise the tap lands at a point outside the viewport and hits whatever is
-/// there instead, which looks exactly like a control that did nothing.
-Future<void> _tap(WidgetTester tester, Key key) async {
- await tester.ensureVisible(find.byKey(key));
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(key));
- await tester.pump();
-}
-
-Future<List<(String, Map<String, Object?>)>> _pump(
- WidgetTester tester,
- List<DialStatus> devices, {
- bool showCompanion = false,
-}) async {
- final sent = <(String, Map<String, Object?>)>[];
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: SingleChildScrollView(
- child: CabledDeviceCard(
- devices: devices,
- showCompanion: showCompanion,
- onChanged: (id, patch) => sent.add((id, patch)),
- ),
- ),
- ),
- ),
- );
- return sent;
-}
-
-void main() {
- testWidgets('while the robot wears Focus only, nothing offers another face', (
- tester,
- ) async {
- // The firmware ignores a skin or a companion until the companion skins are finished, so
- // neither row is drawn — even with the experimental companion switch on.
- const devices = [
- DialStatus(
- attached: true,
- id: 'dial',
- settings: DeviceSettings(
- brightness: 40,
- character: 2,
- face: 466,
- muted: true,
- quiet: false,
- straightTitle: false,
- focusFace: false,
- scrollReversed: false,
- round: true,
- voiceLang: 'en',
- followCompanion: true,
- companion: 'gnu',
- ),
- ),
- ];
- await _pump(tester, devices, showCompanion: true);
- expect(find.text('Follow desktop companion'), findsNothing);
- expect(find.text('Skin'), findsNothing);
- expect(find.text('Brightness'), findsOneWidget);
- });
-
- testWidgets('the pane names the robot it is changing, before any row', (
- tester,
- ) async {
- // These rows look exactly like the app's own preferences, so without this they read as settings
- // for Harness itself.
- await _pump(tester, const [
- DialStatus(
- attached: true,
- id: 'AA:01',
- mac: 'aa:bb',
- fw: '0.0.86',
- settings: _round,
- ),
- ]);
- expect(find.text('These settings apply to'), findsOneWidget);
- expect(find.text('Dial'), findsOneWidget);
- expect(find.text('connected'), findsOneWidget);
- expect(find.textContaining('466 round'), findsOneWidget);
- expect(find.textContaining('habitat 0.0.86'), findsOneWidget);
- });
-
- testWidgets('no robot offers Edge text: titles are straight across', (
- tester,
- ) async {
- await _pump(tester, const [
- DialStatus(attached: true, id: 'AA:01', settings: _round),
- ]);
- expect(find.text('Edge text'), findsNothing);
- expect(find.text('Voice language'), findsOneWidget);
- });
-
- testWidgets('the voice language shows what the robot holds, of all six', (
- tester,
- ) async {
- // The picker once knew only English and Vietnamese, and read a Japanese dial as English.
- await _pump(tester, const [
- DialStatus(
- attached: true,
- id: 'AA:01',
- settings: DeviceSettings(
- brightness: 60,
- character: 2,
- face: 466,
- muted: false,
- quiet: false,
- straightTitle: false,
- focusFace: false,
- scrollReversed: false,
- round: true,
- voiceLang: 'ja',
- ),
- ),
- ]);
- expect(find.text('日本語'), findsOneWidget);
- expect(find.text('English'), findsNothing);
- });
-
- testWidgets('a square face HIDES the row it has no meaning for', (
- tester,
- ) async {
- // Greying them out would still claim the settings exist there.
- await _pump(tester, const [
- DialStatus(attached: true, id: 'BB:02', settings: _square),
- ]);
- expect(find.text('Edge text'), findsNothing);
- expect(find.text('Rim scrolling'), findsNothing);
- expect(find.text('Reverse scrolling'), findsOneWidget);
- });
-
- testWidgets(
- 'one field at a time crosses, named the way the device names it',
- (tester) async {
- final sent = await _pump(tester, const [
- DialStatus(attached: true, id: 'AA:01', settings: _round),
- ]);
- await _tap(tester, const ValueKey('device-quiet-AA:01'));
- expect(sent, hasLength(1));
- expect(sent.single.$1, 'AA:01');
- expect(sent.single.$2, {'quiet': true});
-
- // The switch says "sound on"; the wire field is its opposite, and the flip belongs in the pane.
- await _tap(tester, const ValueKey('device-muted-AA:01'));
- expect(sent.last.$2, {'muted': true});
- },
- );
-
- testWidgets('an unplugged robot is readable and not writable', (
- tester,
- ) async {
- final sent = await _pump(tester, const [
- DialStatus(attached: false, id: 'AA:01', mac: 'aa:bb', settings: _round),
- ]);
- expect(find.text('Unplugged'), findsOneWidget);
- expect(
- find.text('Brightness'),
- findsOneWidget,
- reason: 'the values stay readable',
- );
- final toggle = tester.widget<Switch>(
- find.byKey(const ValueKey('device-quiet-AA:01')),
- );
- expect(toggle.onChanged, isNull);
- await _tap(tester, const ValueKey('device-quiet-AA:01'));
- expect(sent, isEmpty);
- });
-
- testWidgets('two robots on one desk get a picker, and the rows follow it', (
- tester,
- ) async {
- // Both are dials, so the name alone cannot separate them: the detail line carries the address.
- // And the rows belong to ONE of them — reading them as account-wide would overwrite one device
- // with the other's taste the first time somebody touched a row.
- final sent = await _pump(tester, const [
- DialStatus(attached: true, id: 'AA:01', mac: 'aa:bb', settings: _round),
- DialStatus(attached: true, id: 'BB:02', mac: 'cc:dd', settings: _square),
- ]);
- expect(find.text('These settings apply to'), findsOneWidget);
- expect(find.textContaining('aa:bb'), findsOneWidget);
- expect(find.textContaining('cc:dd'), findsOneWidget);
- // Opens on the first attached robot, whose voice is English; the second's is Vietnamese.
- expect(find.text('English'), findsOneWidget);
-
- await tester.tap(find.textContaining('cc:dd'));
- await tester.pumpAndSettle();
- expect(find.text('Tiếng Việt'), findsOneWidget);
- await _tap(tester, const ValueKey('device-quiet-BB:02'));
- expect(
- sent.single.$1,
- 'BB:02',
- reason: 'the change goes to the selected robot',
- );
- });
-
- testWidgets(
- 'a robot that has not reported says so instead of showing defaults',
- (tester) async {
- await _pump(tester, const [
- DialStatus(attached: true, id: 'AA:01', fw: '0.0.68'),
- ]);
- expect(
- find.textContaining('keeps its settings on the glass'),
- findsOneWidget,
- );
- expect(find.text('Brightness'), findsNothing);
- },
- );
-}
diff --git a/desktop/test/fingerprint_text_test.dart b/desktop/test/fingerprint_text_test.dart
index 98b7a77e3..716b968d0 100644
--- a/desktop/test/fingerprint_text_test.dart
+++ b/desktop/test/fingerprint_text_test.dart
@@ -82,11 +82,11 @@ void main() {
);
expect(
fingerprintHowToCompare(computer: false),
- 'This device’s own key code. Open Your devices on that device — the code under “This device” must match.',
+ 'This device’s own key code. Open Your devices on a phone, or Machines in a browser — the code shown for “This device” must match.',
);
expect(
fingerprintHowToCompare(computer: true),
- 'This device’s own key code. Open Your devices on that computer — the code under “This device” must match — or run harness status on it.',
+ 'This device’s own key code. Open Machines on that computer — the code shown for that computer must match — or run harness status on it.',
);
});
}
diff --git a/desktop/test/harness_customize_test.dart b/desktop/test/harness_customize_test.dart
index ca746a9c5..ed36c2e37 100644
--- a/desktop/test/harness_customize_test.dart
+++ b/desktop/test/harness_customize_test.dart
@@ -470,7 +470,8 @@ void main() {
await chord(tester, LogicalKeyboardKey.comma);
await tester.pumpAndSettle();
expect(find.byType(SettingsScreen), findsOneWidget);
- await tester.tap(find.text('Customize'));
+ // The rail's Appearance row (was Customize) opens the same panel.
+ await tester.tap(find.text('Appearance'));
} else {
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
await tester.enterText(
diff --git a/desktop/test/machine_devices_picker_test.dart b/desktop/test/machine_devices_picker_test.dart
new file mode 100644
index 000000000..f9be65b60
--- /dev/null
+++ b/desktop/test/machine_devices_picker_test.dart
@@ -0,0 +1,462 @@
+// Machines lists the account's signed-in devices beside its machines: COMPUTERS (each machine, with
+// this computer's code, and a signed-in computer that has no machine record), then PHONES & APPS.
+// These moved here from Settings ▸ Your devices and Settings ▸ Profiles. The device list and every
+// write are canned (support/devices_app.dart), so nothing reaches a daemon.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_select_field.dart';
+import 'package:harness/state/account_devices.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/machine_devices.dart';
+import 'package:harness/state/swarm_search.dart' show MachineSearchSection;
+import 'package:harness/viewer/device_history.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
+import 'package:harness/widgets/machine_picker_extras.dart';
+import 'package:harness/widgets/new_device_notice.dart' show openMachines;
+
+import 'support/devices_app.dart';
+import 'support/resource_picker.dart';
+import 'support/workspace_tools.dart';
+
+const _localId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+const _remoteId = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
+const _strayId = 'cccccccccccccccccccccccccccccccc';
+
+class _App extends FakeDevicesApp {
+ final deletes = <String>[];
+ String? deleteError;
+
+ @override
+ Future<String?> deleteMachine(String id) async {
+ deletes.add(id);
+ if (deleteError != null) return deleteError;
+ machineStates.remove(id);
+ machines = machineStates.values.map((s) => s.machine).toList();
+ notifyListeners();
+ return null;
+ }
+
+ void add(String id, String name, {bool local = false}) {
+ final machine = Machine(
+ machineId: id,
+ name: name,
+ authMode: MachineAuthMode.remote,
+ );
+ machineStates[id] = MachineState(machine)
+ ..localOnly = local
+ ..nodeOnline = true
+ ..needsLink = false
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..connectionStatus = ConnectionStatus.connected;
+ machines = machineStates.values.map((s) => s.machine).toList();
+ notifyListeners();
+ }
+}
+
+AccountDevice _device(
+ String pub, {
+ required String label,
+ String kind = 'viewer',
+ String machineId = '',
+ bool self = false,
+ Duration? seenAgo,
+ String fingerprint = fakeFingerprint,
+ bool pending = false,
+}) {
+ final now = DateTime.now();
+ return AccountDevice(
+ pub: pub,
+ label: label,
+ kind: kind,
+ machineId: machineId,
+ addedAt: now.subtract(const Duration(days: 30)),
+ fingerprint: fingerprint,
+ self: self,
+ lastSeen: seenAgo == null ? null : now.subtract(seenAgo),
+ pending: pending,
+ );
+}
+
+void main() {
+ late _App app;
+
+ setUp(() {
+ app = _App()
+ ..add(_localId, 'Studio Mac', local: true)
+ ..add(_remoteId, 'Build box');
+ app.devices = AccountDevices(
+ devices: [
+ _device(
+ 'self',
+ label: 'Studio Mac',
+ kind: 'machine',
+ machineId: _localId,
+ self: true,
+ fingerprint: 'D991·0A0B·0C0D·0E0F',
+ ),
+ _device(
+ 'remote',
+ label: 'Build box',
+ kind: 'machine',
+ machineId: _remoteId,
+ seenAgo: const Duration(minutes: 21),
+ ),
+ _device(
+ 'stray',
+ label: 'Lab computer',
+ kind: 'machine',
+ machineId: _strayId,
+ seenAgo: const Duration(hours: 3),
+ ),
+ _device(
+ 'phone',
+ label: 'Test iPhone',
+ seenAgo: const Duration(minutes: 27),
+ ),
+ ],
+ historyAvailable: true,
+ );
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> mount(WidgetTester tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 900);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ home: SwarmScreen(notifier: app, nativeTabs: false),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> openPicker(WidgetTester tester) async {
+ await openWorkspaceManagement(tester, 'machines');
+ await tester.pumpAndSettle();
+ expect(resourceScope('@'), findsOneWidget);
+ }
+
+ Finder pill(String label) => find.widgetWithText(DesktopPill, label);
+
+ testWidgets('computers, then phones and apps; this computer shows its code', (
+ tester,
+ ) async {
+ await mount(tester);
+ await openPicker(tester);
+ final search = resourceSearch(tester);
+ expect(search.rows.map((row) => row.title), [
+ 'Studio Mac',
+ 'Build box',
+ 'Lab computer',
+ 'Test iPhone',
+ 'Add machine',
+ ]);
+ expect(
+ find.byKey(const ValueKey('machine-section:computers')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('machine-section:phones')),
+ findsOneWidget,
+ );
+ expect(find.text('Computers'), findsOneWidget);
+ expect(find.text('Phones & apps'), findsOneWidget);
+ final local = search.rows.firstWhere((row) => row.title == 'Studio Mac');
+ expect(local.detail, contains('This computer · code D991…'));
+ final remote = search.rows.firstWhere((row) => row.title == 'Build box');
+ expect(remote.detail, contains('last active 21 minutes ago'));
+ // A computer signed in to the account with no machine record is still a computer.
+ final stray = search.rows.firstWhere((row) => row.title == 'Lab computer');
+ expect(stray.devicePub, 'stray');
+ expect(stray.deviceIsComputer, isTrue);
+ expect(search.machineSection(stray), MachineSearchSection.computers);
+
+ await selectResource(tester, 'machine:$_localId');
+ await tester.pumpAndSettle();
+ expect(find.text('D991·0A0B·0C0D·0E0F'), findsOneWidget);
+ expect(find.byKey(const ValueKey('device-code-copy:self')), findsOneWidget);
+ // This computer is never removed from here.
+ expect(pill('Remove'), findsNothing);
+ });
+
+ testWidgets('a phone: its facts and code; Remove signs it out after asking', (
+ tester,
+ ) async {
+ await mount(tester);
+ await openPicker(tester);
+ await selectResource(tester, 'device:phone');
+ await tester.pumpAndSettle();
+ expect(find.text('App'), findsOneWidget);
+ expect(find.text(fakeFingerprint), findsOneWidget);
+ await tester.tap(pill('Remove'));
+ await tester.pumpAndSettle();
+ expect(find.text('Remove Test iPhone?'), findsOneWidget);
+ expect(app.removed, isEmpty);
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pumpAndSettle();
+ expect(app.removed, ['phone']);
+ expect(
+ resourceSearch(tester).rows.any((row) => row.devicePub == 'phone'),
+ isFalse,
+ );
+ });
+
+ testWidgets(
+ 'Remove on a computer signs it out AND deletes its machine record, and says so first',
+ (tester) async {
+ await mount(tester);
+ await openPicker(tester);
+ await selectResource(tester, 'machine:$_remoteId');
+ await tester.pumpAndSettle();
+ expect(pill('Delete'), findsNothing);
+ await tester.tap(pill('Remove'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Remove this computer from your account?'),
+ findsOneWidget,
+ );
+ expect(
+ find.text('It is signed out, and its machine record is deleted.'),
+ findsOneWidget,
+ );
+ expect(app.removed, isEmpty);
+ expect(app.deletes, isEmpty);
+ await tester.tap(find.byKey(const ValueKey('machine-form:Remove')));
+ await tester.pumpAndSettle();
+ expect(app.removed, ['remote']);
+ expect(app.deletes, [_remoteId]);
+ },
+ );
+
+ testWidgets('a sign-out that fails leaves the machine record alone', (
+ tester,
+ ) async {
+ app.removeError = 'OFFLINE';
+ await mount(tester);
+ await openPicker(tester);
+ await selectResource(tester, 'machine:$_remoteId');
+ await tester.pumpAndSettle();
+ await tester.tap(pill('Remove'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('machine-form:Remove')));
+ await tester.pumpAndSettle();
+ expect(app.removed, ['remote']);
+ expect(app.deletes, isEmpty);
+ expect(find.textContaining('Couldn’t sign Build box out'), findsOneWidget);
+ });
+
+ testWidgets('a new phone offers It’s mine', (tester) async {
+ app.newDevices.add(
+ const NewDeviceNotice(pub: 'phone', label: 'Test iPhone', kind: 'viewer'),
+ );
+ await mount(tester);
+ await openPicker(tester);
+ final row = resourceSearch(tester).rows
+ .firstWhere((row) => row.devicePub == 'phone');
+ expect(row.detail, endsWith('New'));
+ await selectResource(tester, 'device:phone');
+ await tester.pumpAndSettle();
+ await tester.tap(pill('It’s mine'));
+ await tester.pumpAndSettle();
+ expect(app.dismissCalls, [('phone', false)]);
+ // Opening Machines was looking at the list: what was new is marked seen.
+ expect(app.seenPending, hasLength(1));
+ });
+
+ testWidgets('History… opens the account’s device history', (tester) async {
+ app.history = const DeviceLogHistory(rows: [], complete: true);
+ await mount(tester);
+ await openPicker(tester);
+ await tester.tap(find.byKey(const Key('account-devices-history')));
+ await tester.pumpAndSettle();
+ expect(find.text('Device history'), findsOneWidget);
+ });
+
+ testWidgets('Show in this window narrows the window to one computer', (
+ tester,
+ ) async {
+ await mount(tester);
+ await openPicker(tester);
+ final field = find.byKey(const Key('machine-window-choice-field'));
+ expect(field, findsOneWidget);
+ final select = tester.widget<AppSelectField<String?>>(field);
+ expect(select.value, isNull);
+ expect(select.options.map((o) => o.label), [
+ 'All machines',
+ 'Studio Mac',
+ 'Build box',
+ ]);
+ select.onChanged(_remoteId);
+ await tester.pumpAndSettle();
+ expect(app.machineProfileId, _remoteId);
+ tester.widget<AppSelectField<String?>>(field).onChanged(null);
+ await tester.pumpAndSettle();
+ expect(app.machineProfileId, isNull);
+ });
+
+ testWidgets(
+ 'a computer that is not connected or is offline cannot be chosen; one chosen stays',
+ (tester) async {
+ app.machineStates[_remoteId]!.connectionStatus =
+ ConnectionStatus.disconnected;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (context, _) => MachineWindowChoice(app: app),
+ ),
+ ),
+ ),
+ );
+ List<String> offered() => tester
+ .widget<AppSelectField<String?>>(
+ find.byKey(const Key('machine-window-choice-field')),
+ )
+ .options
+ .map((o) => o.label)
+ .toList();
+ expect(offered(), ['All machines', 'Studio Mac']);
+ app.machineStates[_remoteId]!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = false;
+ app.notifyListeners();
+ await tester.pump();
+ expect(offered(), ['All machines', 'Studio Mac']);
+ app.machineStates[_remoteId]!.nodeOnline = true;
+ app.notifyListeners();
+ await tester.pump();
+ expect(offered(), ['All machines', 'Studio Mac', 'Build box']);
+ app.setMachineProfile(_remoteId);
+ app.machineStates[_remoteId]!.nodeOnline = false;
+ app.notifyListeners();
+ await tester.pump();
+ final field = tester.widget<AppSelectField<String?>>(
+ find.byKey(const Key('machine-window-choice-field')),
+ );
+ expect(field.value, _remoteId);
+ expect(
+ field.options.firstWhere((o) => o.value == _remoteId).note,
+ contains('Offline'),
+ );
+ },
+ );
+
+ testWidgets('apps unused for 90 days are offered for removal together', (
+ tester,
+ ) async {
+ app.devices = AccountDevices(
+ devices: [
+ ...app.devices!.devices,
+ _device(
+ 'old',
+ label: 'Old browser',
+ seenAgo: const Duration(days: 120),
+ ),
+ ],
+ );
+ await mount(tester);
+ await openPicker(tester);
+ expect(find.byKey(const Key('account-devices-unused')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('account-devices-remove-unused')));
+ await tester.pumpAndSettle();
+ expect(find.text('Remove 1 unused app?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pumpAndSettle();
+ expect(app.removed, ['old']);
+ });
+
+ testWidgets('the devices already on the account are said once; Got it', (
+ tester,
+ ) async {
+ app.devices = AccountDevices(
+ devices: app.devices!.devices,
+ baselineSeen: false,
+ baselineKeys: const ['phone'],
+ );
+ await mount(tester);
+ await openPicker(tester);
+ expect(find.byKey(const Key('account-devices-baseline')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('account-devices-baseline-gotit')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('account-devices-baseline')), findsNothing);
+ expect(app.baselineSeenCalls, 1);
+ });
+
+ testWidgets(
+ 'a frozen list offers Review…, which trusts it again after asking',
+ (tester) async {
+ app.devices = AccountDevices(
+ devices: app.devices!.devices,
+ frozenReason: 'fork',
+ );
+ app.previews.add(
+ const DevicesRebaseline(added: ['Test iPhone'], removed: []),
+ );
+ app.confirmAnswer = const DevicesRebaseline(added: [], removed: []);
+ await mount(tester);
+ await openPicker(tester);
+ expect(find.byKey(const Key('account-devices-frozen')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('account-devices-review')));
+ await tester.pumpAndSettle();
+ expect(find.text('Trust this device list again?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('account-device-confirm')));
+ await tester.pumpAndSettle();
+ expect(app.confirmedHeads, hasLength(1));
+ },
+ );
+
+ testWidgets('a deep link opens Machines on that device', (tester) async {
+ await mount(tester);
+ final context = tester.element(find.byType(SwarmScreen));
+ openMachines(context, app, devicePub: 'phone');
+ await tester.pumpAndSettle();
+ expect(resourceScope('@'), findsOneWidget);
+ expect(resourceSearch(tester).selected?.devicePub, 'phone');
+ expect(app.machinesRequest, isNull);
+ });
+
+ testWidgets('a deep link to a computer selects its machine row', (
+ tester,
+ ) async {
+ await mount(tester);
+ app.requestMachines(devicePub: 'remote');
+ await tester.pumpAndSettle();
+ expect(resourceSearch(tester).selected?.id, 'machine:$_remoteId');
+ });
+
+ testWidgets('Add Phone’s way in selects the first phone', (tester) async {
+ await mount(tester);
+ app.requestMachines(phones: true);
+ await tester.pumpAndSettle();
+ expect(resourceSearch(tester).selected?.devicePub, 'phone');
+ });
+
+ test('a picker that opened on its own marks nothing seen', () async {
+ final devices = MachineDevices(app)..markSeen = false;
+ app.newDevices.add(
+ const NewDeviceNotice(pub: 'phone', label: 'Test iPhone', kind: 'viewer'),
+ );
+ devices.start();
+ await Future<void>.delayed(Duration.zero);
+ expect(devices.loaded, isTrue);
+ expect(app.seenPending, isEmpty);
+ devices.dispose();
+ });
+
+ test('without a device list there are only machines', () async {
+ app.loadError = StateError('daemon predates the list');
+ final devices = MachineDevices(app)..start();
+ await Future<void>.delayed(Duration.zero);
+ expect(devices.loaded, isTrue);
+ expect(devices.devices, isNull);
+ expect(devices.rows({_localId}), isEmpty);
+ expect(app.seenPending, isEmpty);
+ devices.dispose();
+ });
+}
diff --git a/desktop/test/machine_devices_test.dart b/desktop/test/machine_devices_test.dart
new file mode 100644
index 000000000..ec8efe487
--- /dev/null
+++ b/desktop/test/machine_devices_test.dart
@@ -0,0 +1,459 @@
+// The account's devices as Machines lists them (state/machine_devices.dart): opening the list is
+// reviewing the devices the banner announced, the rows' order and marks, and the acts on the list —
+// Remove, Remove unused apps, Got it, Trust again. Moved with the list from Settings ▸ Your devices.
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/account_devices.dart';
+import 'package:harness/state/machine_devices.dart';
+import 'package:harness/viewer/device_log.dart' show DevLogHead;
+import 'package:harness/viewer/device_log_sync.dart' show DeviceLogRebaseline;
+
+import 'support/devices_app.dart';
+
+/// A confirm that answers [answer] and records what it was asked.
+class _Confirm {
+ _Confirm([this.answer = true]);
+ bool answer;
+ final asked = <(String, String, String)>[];
+ Future<bool> call(String title, String detail, String action) async {
+ asked.add((title, detail, action));
+ return answer;
+ }
+}
+
+Future<void> _settle() async {
+ for (var i = 0; i < 4; i++) {
+ await Future<void>.delayed(Duration.zero);
+ }
+}
+
+void main() {
+ test('the daemon\'s OTHER_ACCOUNT answer and the viewer\'s are a refusal of another account\'s list', () {
+ final daemon = DevicesRebaseline.fromDaemon({'error': 'OTHER_ACCOUNT'})!;
+ expect(
+ [daemon.otherAccount, daemon.logChanged, daemon.refused],
+ [true, false, true],
+ );
+ expect(
+ DevicesRebaseline.fromDaemon({'error': 'LOG_CHANGED'})!.otherAccount,
+ isFalse,
+ );
+ final viewer = DevicesRebaseline.fromViewer(
+ const DeviceLogRebaseline.otherAccount(),
+ );
+ expect(
+ [viewer.otherAccount, viewer.logChanged, viewer.head],
+ [true, false, null],
+ );
+ });
+
+ test('a listing carries its departed keys, from the daemon and from the viewer alike', () {
+ final fromDaemon = AccountDevices.fromDaemon({
+ 'members': <Object>[],
+ 'pending': <Object>[],
+ 'departed': [
+ {
+ 'pub': 'gone',
+ 'label': 'Phone',
+ 'kind': 'viewer',
+ 'machineId': '',
+ 'fingerprint': 'AAAA',
+ 'addedAt': 1,
+ 'removedAt': 2,
+ 'removedBy': 'gone',
+ 'removedByLabel': 'Phone',
+ 'selfRemoved': true,
+ },
+ ],
+ })!;
+ expect(fromDaemon.departed, ['gone']);
+ expect(
+ AccountDevices.fromDaemon({'members': <Object>[], 'pending': <Object>[]})!
+ .departed,
+ isEmpty,
+ );
+ expect(fromDaemon.withLastSeen(const {}).departed, ['gone']);
+ });
+
+ group('the list', () {
+ final now = DateTime.now();
+ late FakeDevicesApp app;
+ late MachineDevices devices;
+
+ setUp(() {
+ app = FakeDevicesApp()
+ ..devices = AccountDevices(
+ devices: [
+ fakeDevice(
+ 'old',
+ label: 'Old laptop',
+ kind: 'machine',
+ added: now.subtract(const Duration(days: 300)),
+ seen: now.subtract(const Duration(days: 40)),
+ fingerprint: 'AAAA·0001·0001·0001',
+ ),
+ fakeDevice(
+ 'me',
+ label: 'Studio Mac',
+ kind: 'machine',
+ self: true,
+ added: now.subtract(const Duration(days: 200)),
+ seen: now,
+ fingerprint: 'E2FB·0DF5·5FD8·E6C7',
+ ),
+ fakeDevice(
+ 'phone-a',
+ label: 'Test iPhone',
+ added: now.subtract(const Duration(days: 100)),
+ seen: now.subtract(const Duration(minutes: 2)),
+ fingerprint: 'BBBB·0002·0002·0002',
+ ),
+ fakeDevice(
+ 'phone-b',
+ label: 'Test iPhone',
+ added: now.subtract(const Duration(days: 50)),
+ fingerprint: 'CCCC·0003·0003·0003',
+ ),
+ fakeDevice(
+ 'new',
+ label: 'Test iPad',
+ added: now.subtract(const Duration(hours: 3)),
+ fingerprint: 'EEEE·0005·0005·0005',
+ ),
+ ],
+ );
+ app.newDevices.add(
+ const NewDeviceNotice(pub: 'new', label: 'Test iPad', kind: 'viewer'),
+ );
+ devices = MachineDevices(app);
+ });
+ tearDown(() {
+ devices.dispose();
+ app.dispose();
+ });
+
+ Future<void> open([AccountDevices? list]) async {
+ if (list != null) app.devices = list;
+ devices.start();
+ await _settle();
+ }
+
+ test('opening the list takes the new-device banner down', () async {
+ await open();
+ expect(app.newDevices, isEmpty);
+ expect(app.seenPending, hasLength(1));
+ });
+
+ test('rows: new first, then by activity; this device is a machine row, not a device row', () async {
+ await open();
+ // `old` and `me` are machines with machine records; the rest are rows of their own.
+ expect(devices.rows({'abcdef0123456789'}).map((d) => d.pub), [
+ 'new',
+ 'phone-a',
+ 'phone-b',
+ ]);
+ // With no machine record, a computer is a row of its own too.
+ expect(devices.rows({}).map((d) => d.pub), [
+ 'me',
+ 'new',
+ 'phone-a',
+ 'old',
+ 'phone-b',
+ ]);
+ final phone = devices.byPub('phone-a')!;
+ // Two devices go by one name: the start of the code tells them apart.
+ expect(devices.detail(phone), 'App · active now · BBBB…');
+ expect(devices.detail(devices.byPub('new')!), endsWith('New'));
+ expect(devices.detail(devices.byPub('me')!), contains('This device'));
+ });
+
+ test('a device the daemon kept as pending is New though no banner is up, and so is one that turns up later', () async {
+ app.newDevices.clear();
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('kept')],
+ pending: const ['kept'],
+ ),
+ );
+ expect(devices.isNew(devices.byPub('kept')!), isTrue);
+ app.devices = AccountDevices(
+ devices: [
+ fakeDevice('me', self: true),
+ fakeDevice('kept'),
+ fakeDevice('late'),
+ ],
+ pending: const ['kept', 'late'],
+ );
+ app.devicesRevision++;
+ app.notifyListeners();
+ await _settle();
+ expect(devices.isNew(devices.byPub('late')!), isTrue);
+ });
+
+ test('a suspended device is marked Suspended instead of New', () async {
+ await open(
+ AccountDevices(
+ devices: [
+ fakeDevice('me', self: true),
+ fakeDevice('fork', label: 'Forked', suspended: true, pending: true),
+ ],
+ ),
+ );
+ final detail = devices.detail(devices.byPub('fork')!);
+ expect(detail, endsWith('Suspended'));
+ expect(detail, isNot(contains('New')));
+ });
+
+ test(
+ 'the baseline names what was there before; Got it hides it and persists',
+ () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('before')],
+ baselineSeen: false,
+ baselineKeys: const ['before'],
+ ),
+ );
+ expect(devices.baselineShowing, isTrue);
+ await devices.gotIt();
+ expect(devices.baselineShowing, isFalse);
+ expect(app.baselineSeenCalls, 1);
+ },
+ );
+
+ test('no baseline once seen', () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('before')],
+ baselineKeys: const ['before'],
+ ),
+ );
+ expect(devices.baselineShowing, isFalse);
+ });
+
+ test('Trust again confirms the previewed head; a list that changed meanwhile is previewed again', () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true)],
+ frozenReason: 'fork',
+ ),
+ );
+ app.previews
+ ..add(
+ const DevicesRebaseline(
+ added: ['iPad'],
+ removed: [],
+ head: DevLogHead(7, 'h7'),
+ ),
+ )
+ ..add(
+ const DevicesRebaseline(
+ added: ['iPad', 'Mac'],
+ removed: [],
+ head: DevLogHead(8, 'h8'),
+ ),
+ );
+ app.confirmAnswer = const DevicesRebaseline.changed();
+ final confirm = _Confirm();
+ var calls = 0;
+ await devices.trustAgain((title, detail, action) {
+ // The second preview is answered No, so this ends.
+ confirm.answer = ++calls == 1;
+ return confirm(title, detail, action);
+ });
+ expect(app.confirmedHeads.single?.seq, 7);
+ expect(confirm.asked, hasLength(2));
+ expect(confirm.asked.last.$2, contains('+ Mac'));
+ expect(
+ devices.error,
+ 'The device list changed while you were reviewing it. Review it again.',
+ );
+ expect(devices.errorIsNotice, isTrue);
+ });
+
+ test(
+ 'another account\'s list: at the preview, nothing to confirm',
+ () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true)],
+ frozenReason: 'invalid',
+ ),
+ );
+ app.previews.add(const DevicesRebaseline.otherAccount());
+ final confirm = _Confirm();
+ await devices.trustAgain(confirm.call);
+ expect(confirm.asked, isEmpty);
+ expect(devices.error, otherAccountMessage);
+ expect(devices.errorIsNotice, isTrue);
+ expect(app.confirmedHeads, isEmpty);
+ },
+ );
+
+ test(
+ 'another account\'s list at the confirm: said once, not previewed again',
+ () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true)],
+ frozenReason: 'invalid',
+ ),
+ );
+ app.previews.add(
+ const DevicesRebaseline(
+ added: [],
+ removed: [],
+ head: DevLogHead(7, 'h7'),
+ ),
+ );
+ app.confirmAnswer = const DevicesRebaseline.otherAccount();
+ final confirm = _Confirm();
+ await devices.trustAgain(confirm.call);
+ expect(confirm.asked, hasLength(1));
+ expect(devices.error, otherAccountMessage);
+ expect(app.confirmedHeads, hasLength(1));
+ },
+ );
+
+ test('failures: an unreadable list, a refused trust and a failed remove are errors, not notices', () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true), fakeDevice('b')],
+ frozenReason: 'fork',
+ ),
+ );
+ await devices.trustAgain(_Confirm().call);
+ expect(
+ devices.error,
+ 'Couldn’t read a valid device list. Try again later.',
+ );
+ expect(devices.errorIsNotice, isFalse);
+ app.previews.add(
+ const DevicesRebaseline(
+ added: ['iPad'],
+ removed: [],
+ head: DevLogHead(7, 'h7'),
+ ),
+ );
+ app.confirmAnswer = null;
+ await devices.trustAgain(_Confirm().call);
+ expect(
+ devices.error,
+ 'Couldn’t trust the device list again. Try again later.',
+ );
+ app.removeError = 'UNAVAILABLE';
+ await devices.remove(devices.byPub('b')!);
+ expect(devices.error, 'Couldn’t remove iPad (UNAVAILABLE). Try again.');
+ expect(devices.errorIsNotice, isFalse);
+ // A later success clears the message.
+ app.removeError = null;
+ app.previews.add(
+ const DevicesRebaseline(
+ added: [],
+ removed: [],
+ head: DevLogHead(7, 'h7'),
+ ),
+ );
+ app.confirmAnswer = const DevicesRebaseline(
+ added: [],
+ removed: [],
+ head: DevLogHead(7, 'h7'),
+ );
+ await devices.trustAgain(_Confirm().call);
+ expect(devices.error, isNull);
+ });
+
+ test(
+ 'opening marks seen only the banner as it was when the list was read',
+ () async {
+ final gate = Completer<void>();
+ app.devices = AccountDevices(devices: [fakeDevice('me', self: true)]);
+ app.newDevices
+ ..clear()
+ ..add(const NewDeviceNotice(pub: 'new', label: 'N', kind: 'viewer'));
+ app.loadGate = gate;
+ app.bannerAtRead = () => ['new'];
+ devices.start();
+ await _settle();
+ app.newDevices.add(
+ const NewDeviceNotice(pub: 'late', label: 'L', kind: 'viewer'),
+ );
+ gate.complete();
+ await _settle();
+ expect(app.seenShown.single, ['new']);
+ expect(app.newDevices.map((d) => d.pub), ['late']);
+ },
+ );
+
+ test('the departed keys the listing read are handed over', () async {
+ await open(
+ AccountDevices(
+ devices: [fakeDevice('me', self: true)],
+ departed: const ['gone'],
+ ),
+ );
+ expect(app.seenDeparted.single, ['gone']);
+ });
+
+ test(
+ 'apps unused for 90 days are removed together, after asking',
+ () async {
+ await open(
+ AccountDevices(
+ devices: [
+ fakeDevice('me', self: true),
+ fakeDevice(
+ 'stale',
+ label: 'Old browser',
+ seen: now.subtract(const Duration(days: 120)),
+ ),
+ fakeDevice(
+ 'stale-pc',
+ label: 'Old computer',
+ kind: 'machine',
+ seen: now.subtract(const Duration(days: 120)),
+ ),
+ ],
+ ),
+ );
+ // Never a computer: its absence is plain in the machine list.
+ expect(devices.unused().map((d) => d.pub), ['stale']);
+ final confirm = _Confirm(false);
+ await devices.removeUnused(confirm.call);
+ expect(app.removed, isEmpty);
+ confirm.answer = true;
+ await devices.removeUnused(confirm.call);
+ expect(confirm.asked.last.$1, 'Remove 1 unused app?');
+ expect(app.removed, ['stale']);
+ },
+ );
+
+ test(
+ 'a computer is signed out first; a record that cannot be deleted says so',
+ () async {
+ await open();
+ final remote = devices.byPub('old')!;
+ final failure = await devices.removeComputer(
+ machineId: 'abcdef0123456789',
+ name: 'Old laptop',
+ device: remote,
+ );
+ // FakeDevicesApp has no machine record to delete: the base app says so.
+ expect(app.removed, ['old']);
+ expect(failure, contains('Old laptop is signed out'));
+ },
+ );
+
+ test('a refused sign-out leaves the machine record alone', () async {
+ await open();
+ app.removeError = 'OFFLINE';
+ final failure = await devices.removeComputer(
+ machineId: 'abcdef0123456789',
+ name: 'Old laptop',
+ device: devices.byPub('old')!,
+ );
+ expect(failure, 'Couldn’t sign Old laptop out (OFFLINE). Try again.');
+ });
+ });
+}
diff --git a/desktop/test/new_device_notice_test.dart b/desktop/test/new_device_notice_test.dart
index bf466b57f..422376ec2 100644
--- a/desktop/test/new_device_notice_test.dart
+++ b/desktop/test/new_device_notice_test.dart
@@ -1,9 +1,8 @@
// The band a new device raises across the window: one device goes straight to its key code, several
-// go to Settings ▸ Your devices, where each is a row.
+// go to Machines, where each is a row.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show RenderParagraph;
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/settings/sections/account_devices_section.dart';
import 'package:harness/state/account_devices.dart' hide NewDeviceNotice;
import 'package:harness/viewer/device_history.dart'
show DevLogHistoryRow, DeviceLogHistory;
@@ -128,7 +127,7 @@ void main() {
await tester.pump();
expect(find.text('AAAA·BBBB·CCCC·DDDD'), findsOneWidget);
expect(find.byKey(const Key('device-detail-mine')), findsOneWidget);
- expect(find.byType(AccountDevicesSection), findsNothing);
+ expect(app.machinesRequest, isNull);
// It’s mine there is the banner's It’s mine.
await tester.tap(find.byKey(const Key('device-detail-mine')));
await tester.pump();
@@ -137,7 +136,7 @@ void main() {
});
testWidgets(
- 'two new devices: Review devices opens the list, the new ones on top',
+ 'two new devices: Review devices opens Machines on the first of them',
(tester) async {
final now = DateTime.now();
app.newDevices
@@ -184,16 +183,10 @@ void main() {
findsOneWidget,
);
await tester.tap(review);
- for (var i = 0; i < 5; i++) {
- await tester.pump(const Duration(milliseconds: 100));
- }
- expect(find.byType(AccountDevicesSection), findsOneWidget);
- double top(String pub) =>
- tester.getTopLeft(find.byKey(ValueKey('account-device-$pub'))).dy;
- expect(top('p2'), lessThan(top('p1')));
- expect(top('p1'), lessThan(top('old')));
- expect(find.text('New'), findsNWidgets(2));
- expect(app.newDevices, isEmpty);
+ await tester.pump();
+ // The workspace opens Machines with that device chosen (machine_devices_picker_test).
+ expect(app.machinesRequest, (devicePub: 'p1', phones: false));
+ expect(find.byType(AlertDialog), findsNothing);
},
);
@@ -516,7 +509,7 @@ void main() {
expect(
text,
contains(
- 'remove it from another device (Your devices) — this computer joins on its own once it is gone.',
+ 'remove it from another device (Machines) — this computer joins on its own once it is gone.',
),
);
},
@@ -578,15 +571,18 @@ void main() {
},
);
- testWidgets('Your devices opens the list', (tester) async {
+ testWidgets('Machines opens on the key that holds it', (tester) async {
app.deviceConflict = conflict(afterJoin: false);
app.devices = AccountDevices(devices: [fakeDevice('holder')]);
await mount(tester);
- await tester.tap(find.byKey(const Key('device-conflict-review')));
- for (var i = 0; i < 5; i++) {
- await tester.pump(const Duration(milliseconds: 100));
- }
- expect(find.byType(AccountDevicesSection), findsOneWidget);
+ final button = find.byKey(const Key('device-conflict-review'));
+ expect(
+ find.descendant(of: button, matching: find.text('Machines')),
+ findsOneWidget,
+ );
+ await tester.tap(button);
+ await tester.pump();
+ expect(app.machinesRequest, (devicePub: 'holder', phones: false));
});
testWidgets('dismissed, it stays down', (tester) async {
diff --git a/desktop/test/pane_needs_link_test.dart b/desktop/test/pane_needs_link_test.dart
index 4d0607d98..e33fde703 100644
--- a/desktop/test/pane_needs_link_test.dart
+++ b/desktop/test/pane_needs_link_test.dart
@@ -216,6 +216,10 @@ void main() {
expect(find.text('Your device list needs a review.'), findsOneWidget);
expect(find.byKey(const Key('device-list-review')), findsOneWidget);
expect(find.text('Link…'), findsOneWidget, reason: 'the password stays');
+ // The review is in Machines now, where the account's devices are listed.
+ await tester.tap(find.byKey(const Key('device-list-review')));
+ await tester.pump();
+ expect(app.machinesRequest, (devicePub: null, phones: false));
await finish(tester);
});
@@ -230,7 +234,7 @@ void main() {
find.textContaining('Your device list needs a review.'),
findsOneWidget,
);
- expect(find.text('Your devices'), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
expect(find.text('Link…'), findsOneWidget, reason: 'the password stays');
await finish(tester);
});
@@ -249,7 +253,7 @@ void main() {
findsOneWidget,
);
expect(find.textContaining('needs a review'), findsNothing);
- expect(find.text('Your devices'), findsOneWidget);
+ expect(find.text('Machines'), findsOneWidget);
await finish(tester);
});
diff --git a/desktop/test/profiles_section_test.dart b/desktop/test/profiles_section_test.dart
deleted file mode 100644
index 30ccf1c0e..000000000
--- a/desktop/test/profiles_section_test.dart
+++ /dev/null
@@ -1,65 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/models.dart';
-import 'package:harness/settings/sections/profiles_section.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/state/app_state.dart';
-
-import 'swarm_state_test.dart' show createApp;
-
-OutlinedButton _button(WidgetTester tester, int row) => tester
- .widgetList<OutlinedButton>(find.byType(OutlinedButton))
- .elementAt(row);
-
-void main() {
- testWidgets(
- 'a computer that is not connected or is offline cannot be chosen',
- (tester) async {
- tester.view.physicalSize = const Size(1200, 900);
- tester.view.devicePixelRatio = 1;
- addTearDown(tester.view.reset);
- final app = createApp(connected: true);
- addTearDown(app.dispose);
- const other = Machine(
- machineId: 'far',
- authMode: MachineAuthMode.remote,
- name: 'Far host',
- );
- app.machines = [...app.machines, other];
- app.machineStates['far'] = MachineState(other)
- ..connectionStatus = ConnectionStatus.disconnected;
-
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(body: ProfilesSection(notifier: app)),
- ),
- );
- // All machines is the default, and chosen.
- expect(_button(tester, 0).onPressed, isNull);
- expect(find.text('Showing'), findsOneWidget);
- // Connected and online: can be chosen.
- expect(_button(tester, 1).onPressed, isNotNull);
- // Not connected: cannot, and says why.
- expect(_button(tester, 2).onPressed, isNull);
- expect(find.textContaining('Not connected.'), findsOneWidget);
-
- // A connection that is up to a machine that reports itself offline.
- app.machineStates['far']!
- ..connectionStatus = ConnectionStatus.connected
- ..nodeOnline = false;
- app.notifyListeners();
- await tester.pump();
- expect(_button(tester, 2).onPressed, isNull);
- expect(find.textContaining('Offline.'), findsOneWidget);
-
- app.machineStates['far']!.nodeOnline = true;
- app.notifyListeners();
- await tester.pump();
- expect(_button(tester, 2).onPressed, isNotNull);
- await tester.tap(find.byType(OutlinedButton).at(2));
- await tester.pump();
- expect(app.machineProfileId, 'far');
- },
- );
-}
diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dart
index d923a96ae..8ae7c93f4 100644
--- a/desktop/test/settings_screen_test.dart
+++ b/desktop/test/settings_screen_test.dart
@@ -83,49 +83,84 @@ void main() {
return notifier;
}
- testWidgets('Settings lists customization under Preferences', (tester) async {
- await openSettings(tester);
- expect(find.text('PREFERENCES'), findsOneWidget);
- expect(find.text('HELP'), findsOneWidget);
- expect(find.text('Usage'), findsNWidgets(2));
- expect(find.text('Customize'), findsOneWidget);
- expect(find.text('Experimental'), findsOneWidget);
- expect(find.text('Keyboard shortcuts'), findsOneWidget);
- expect(find.text('About'), findsOneWidget);
- expect(find.text('Back to app'), findsOneWidget);
- expect(find.text('Appearance'), findsNothing);
- expect(find.text('Terminal'), findsNothing);
- expect(find.byKey(const Key('appearance-ui-size-field')), findsNothing);
- expect(
- find.byKey(const Key('terminal-font-family-dropdown')),
- findsNothing,
- );
- await tester.tap(find.text('Customize'));
- await tester.pumpAndSettle();
- expect(find.byType(SettingsScreen), findsNothing);
- expect(find.byType(Placeholder), findsOneWidget);
- expect(find.byType(HarnessCustomizePane), findsOneWidget);
- for (final label in ['Status', 'Appearance', 'Terminal']) {
- expect(find.text(label), findsOneWidget);
- }
- await tester.tap(find.byKey(const ValueKey('customize-appearance')));
- await tester.pumpAndSettle();
- expect(find.byKey(const Key('appearance-ui-size-field')), findsNothing);
- // Four tabs scroll at this window width; bring Terminal into view first.
- final terminalTab = find.byKey(const ValueKey('customize-terminal'));
- await tester.ensureVisible(terminalTab);
- await tester.tap(terminalTab);
- await tester.pumpAndSettle();
- expect(
- find.byKey(const Key('terminal-font-family-dropdown')),
- findsOneWidget,
- );
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pumpAndSettle();
- expect(find.byType(SettingsScreen), findsNothing);
- expect(find.byType(HarnessCustomizePane), findsNothing);
- expect(tester.takeException(), isNull);
- });
+ testWidgets(
+ 'Settings is settings only: Account, then General, Agents, Labs and Help',
+ (tester) async {
+ await openSettings(tester);
+ // Settings opens on Account, alone at the top with no caption over it.
+ expect(find.text('Account'), findsNWidgets(2));
+ for (final caption in ['GENERAL', 'AGENTS', 'LABS', 'HELP']) {
+ expect(find.text(caption), findsOneWidget, reason: caption);
+ }
+ expect(find.text('PREFERENCES'), findsNothing);
+ final rows = [
+ 'Account',
+ 'Appearance',
+ 'Notifications',
+ 'Keyboard shortcuts',
+ 'Agents',
+ 'Connectors',
+ 'Usage',
+ 'Experimental',
+ 'About',
+ 'Debug',
+ ];
+ final tops = [
+ for (final label in rows)
+ tester
+ .getTopLeft(
+ find.descendant(
+ of: find.byType(SettingsNav),
+ matching: find.text(label),
+ ),
+ )
+ .dy,
+ ];
+ expect(tops, [...tops]..sort(), reason: 'in this order');
+ // What moved out: robots to the Devices tab, devices and profiles to Machines.
+ for (final gone in [
+ 'Customize',
+ 'Your devices',
+ 'Profiles',
+ 'Autonomous robots',
+ ]) {
+ expect(find.text(gone), findsNothing, reason: gone);
+ }
+ expect(find.text('Back to app'), findsOneWidget);
+ expect(find.text('Terminal'), findsNothing);
+ expect(find.byKey(const Key('appearance-ui-size-field')), findsNothing);
+ expect(
+ find.byKey(const Key('terminal-font-family-dropdown')),
+ findsNothing,
+ );
+ // Appearance (was Customize) still opens the workspace's Customize Harness panel.
+ await tester.tap(find.text('Appearance'));
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsNothing);
+ expect(find.byType(Placeholder), findsOneWidget);
+ expect(find.byType(HarnessCustomizePane), findsOneWidget);
+ for (final label in ['Status', 'Appearance', 'Terminal']) {
+ expect(find.text(label), findsOneWidget);
+ }
+ await tester.tap(find.byKey(const ValueKey('customize-appearance')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('appearance-ui-size-field')), findsNothing);
+ // Four tabs scroll at this window width; bring Terminal into view first.
+ final terminalTab = find.byKey(const ValueKey('customize-terminal'));
+ await tester.ensureVisible(terminalTab);
+ await tester.tap(terminalTab);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const Key('terminal-font-family-dropdown')),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsNothing);
+ expect(find.byType(HarnessCustomizePane), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
testWidgets('settings navigation announces and changes its selected section', (
tester,
@@ -137,33 +172,33 @@ void main() {
of: find.byType(SettingsNav),
matching: find.widgetWithText(InkWell, label),
);
- final usage = tester.getSemantics(row('Usage'));
final account = tester.getSemantics(row('Account'));
- expect(usage.getSemanticsData().flagsCollection.isButton, isTrue);
+ final usage = tester.getSemantics(row('Usage'));
+ expect(account.getSemanticsData().flagsCollection.isButton, isTrue);
expect(
- usage.getSemanticsData().flagsCollection.isSelected,
+ account.getSemanticsData().flagsCollection.isSelected,
Tristate.isTrue,
);
expect(
- account.getSemanticsData().flagsCollection.isSelected,
+ usage.getSemanticsData().flagsCollection.isSelected,
Tristate.isFalse,
);
- expect(account.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
+ expect(usage.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);
// Assistive activation must take the same route as pointer/keyboard use.
tester
- .renderObject(row('Account'))
+ .renderObject(row('Usage'))
.owner!
.semanticsOwner!
- .performAction(account.id, SemanticsAction.tap);
+ .performAction(usage.id, SemanticsAction.tap);
await tester.pumpAndSettle();
expect(
tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
- SettingsSection.account,
+ SettingsSection.usage,
);
expect(
tester
- .getSemantics(row('Account'))
+ .getSemantics(row('Usage'))
.getSemanticsData()
.flagsCollection
.isSelected,
@@ -171,7 +206,7 @@ void main() {
);
expect(
tester
- .getSemantics(row('Usage'))
+ .getSemantics(row('Account'))
.getSemanticsData()
.flagsCollection
.isSelected,
@@ -345,9 +380,11 @@ void main() {
expect(find.text('Keyboard shortcuts'), findsOneWidget);
// Filtering the rail preserves the open pane.
- expect(find.text('Usage'), findsOneWidget);
+ expect(find.text('Account'), findsOneWidget);
expect(find.text('Terminal'), findsNothing);
- expect(find.text('PREFERENCES'), findsNothing);
+ // Its run's caption stays over it; the runs with no match go.
+ expect(find.text('GENERAL'), findsOneWidget);
+ expect(find.text('AGENTS'), findsNothing);
await tester.enterText(
find.byKey(const Key('settings-search-field')),
diff --git a/desktop/test/settings_section_test.dart b/desktop/test/settings_section_test.dart
index 2a7882550..68ff6d8c9 100644
--- a/desktop/test/settings_section_test.dart
+++ b/desktop/test/settings_section_test.dart
@@ -15,34 +15,71 @@ void main() {
test('a test build lists the developer sections', () {
expect(kDebugSurfaceEnabled, isTrue, reason: 'tests run in debug mode');
- expect(
- sectionsOf(settingsGroups),
- contains(SettingsSection.debug),
- );
+ expect(sectionsOf(settingsGroups), contains(SettingsSection.debug));
});
test('Settings opens on a row the rail actually shows', () {
expect(sectionsOf(settingsGroups), contains(kDefaultSettingsSection));
final shipped = settingsGroupsFor(debugSurface: false);
- expect(shipped.first.sections.first, SettingsSection.usage);
+ expect(shipped.first.sections.first, SettingsSection.account);
+ expect(kDefaultSettingsSection, SettingsSection.account);
});
test('everything outside the gate is always listed', () {
expect(sectionsOf(settingsGroupsFor(debugSurface: false)), [
+ SettingsSection.account,
+ SettingsSection.customize,
+ SettingsSection.notifications,
+ SettingsSection.shortcuts,
+ SettingsSection.agents,
+ if (!kIsWeb) SettingsSection.connectors,
// Usage carries no gate of its own: it reads only this machine's own
// files, and it reads nothing at all until a provider is switched on, so
// there is nothing here for a shipped build to hide.
SettingsSection.usage,
- SettingsSection.customize,
- SettingsSection.notifications,
SettingsSection.experimental,
- if (!kIsWeb) SettingsSection.devices,
- if (!kIsWeb) SettingsSection.connectors,
- SettingsSection.account,
- SettingsSection.accountDevices,
- SettingsSection.profiles,
- SettingsSection.shortcuts,
SettingsSection.about,
]);
});
+
+ test('the rail: Account alone, then General, Agents, Labs and Help', () {
+ final groups = settingsGroupsFor(debugSurface: true);
+ expect(groups.map((g) => g.title), [
+ '',
+ 'General',
+ 'Agents',
+ 'Labs',
+ 'Help',
+ ]);
+ expect(groups.map((g) => g.sections), [
+ [SettingsSection.account],
+ [
+ SettingsSection.customize,
+ SettingsSection.notifications,
+ SettingsSection.shortcuts,
+ ],
+ [
+ SettingsSection.agents,
+ if (!kIsWeb) SettingsSection.connectors,
+ SettingsSection.usage,
+ ],
+ [SettingsSection.experimental],
+ [SettingsSection.about, SettingsSection.debug],
+ ]);
+ // Customize keeps its name in the palette's memory; the rail calls it Appearance.
+ expect(SettingsSection.customize.label, 'Appearance');
+ });
+
+ test('nothing in Settings is a thing that lives elsewhere', () {
+ expect(
+ SettingsSection.values.map((s) => s.name),
+ isNot(
+ anyOf(
+ contains('accountDevices'),
+ contains('profiles'),
+ contains('devices'),
+ ),
+ ),
+ );
+ });
}
diff --git a/desktop/test/support/devices_app.dart b/desktop/test/support/devices_app.dart
index 6304c2374..fa55f2ae4 100644
--- a/desktop/test/support/devices_app.dart
+++ b/desktop/test/support/devices_app.dart
@@ -106,6 +106,10 @@ class FakeDevicesApp extends AppNotifier {
baselineSeenCalls++;
}
+ /// A canned list is always there to read.
+ @override
+ bool get accountDevicesReadable => true;
+
@override
Future<AccountDevices?> loadDevices({
void Function(List<String> banner)? onListed,
diff --git a/desktop/test/system_notifications_test.dart b/desktop/test/system_notifications_test.dart
index 129291deb..1d054952c 100644
--- a/desktop/test/system_notifications_test.dart
+++ b/desktop/test/system_notifications_test.dart
@@ -512,7 +512,7 @@ void main() {
expect(app.newDevices.single.fingerprint, 'AAAA·BBBB·CCCC·DDDD');
final shown = os.shown.single;
expect(shown.title, 'New device on your account');
- expect(shown.body, endsWith('Not yours? Remove it in Settings ▸ Your devices.'));
+ expect(shown.body, endsWith('Not yours? Remove it in Machines.'));
expect(shown.body, contains('Test iPad'));
expect((shown.machineId, shown.agentId), ('@device', 'pub-1'));
});
diff --git a/desktop/test/wifi_robots_test.dart b/desktop/test/wifi_robots_test.dart
new file mode 100644
index 000000000..81c812b4f
--- /dev/null
+++ b/desktop/test/wifi_robots_test.dart
@@ -0,0 +1,528 @@
+// The Devices tab's robots paired over Wi-Fi: Add device ▸ Wi-Fi code pairs one with the six-character
+// code it shows, and the tab lists what is paired with Revoke… beside each. These moved here from
+// Settings ▸ Autonomous robots; the CLI behind them is faked, so nothing reaches a real network.
+import 'dart:async';
+import 'dart:ui' show SemanticsAction;
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/autonomous_device/autonomous_device_cli.dart';
+import 'package:harness/devices/device_settings.dart';
+import 'package:harness/devices/devices_controller.dart';
+import 'package:harness/devices/devices_screen.dart';
+import 'package:harness/devices/wifi_robots.dart';
+import 'package:harness/shared/widgets/app_icon_button.dart';
+import 'package:harness/shared/widgets/app_select_field.dart';
+import 'package:harness/shared/widgets/skeleton.dart';
+import 'package:harness/state/dial_status.dart';
+
+import 'devices_controller_test.dart' show deviceStatus, report;
+
+class FakeAutonomousDeviceCli extends AutonomousDeviceCli {
+ bool unsupported = false;
+ int statusCalls = 0;
+ Completer<void>? statusWait;
+ Completer<void>? pairWait;
+ String? pairFailure;
+ bool networkBlocked = false;
+ List<Map<String, dynamic>> discovered = [
+ {'id': 'device-1', 'name': 'Kitchen', 'host': '192.0.2.2', 'port': 5000},
+ ];
+ List<Map<String, dynamic>> devices = [];
+ final submissions = <Map<String, dynamic>>[];
+ final revoked = <String>[];
+ @override
+ Future<Map<String, dynamic>> status() async {
+ statusCalls++;
+ if (statusWait != null) await statusWait!.future;
+ if (unsupported) {
+ throw const AutonomousDeviceCliException('NOT_FOUND', 'Unsupported CLI');
+ }
+ return {'transport': 'direct', 'connected': true, 'paired': devices.length};
+ }
+
+ @override
+ Future<Map<String, dynamic>> list() async => {'devices': devices};
+ @override
+ Future<Map<String, dynamic>> discover() async {
+ if (networkBlocked) {
+ throw const AutonomousDeviceCliException(
+ 'LOCAL_NETWORK_BLOCKED',
+ 'Harness is not allowed to use the local network.',
+ );
+ }
+ return {'devices': discovered};
+ }
+
+ @override
+ Future<Map<String, dynamic>> pair({
+ required String code,
+ required String deviceId,
+ }) async {
+ submissions.add({'code': code, 'deviceId': deviceId});
+ if (pairWait != null) await pairWait!.future;
+ if (pairFailure != null) {
+ throw AutonomousDeviceCliException('CODE_MISMATCH', pairFailure!);
+ }
+ // The real CLI persists the trust, so the next `list` is what reports it.
+ devices.add({
+ 'id': 'fingerprint-$deviceId',
+ 'fingerprint': 'fingerprint-$deviceId',
+ 'label': 'Autonomous robot',
+ 'online': true,
+ });
+ return {
+ 'state': 'paired',
+ 'label': 'Autonomous robot',
+ 'fingerprint': 'fingerprint-$deviceId',
+ };
+ }
+
+ @override
+ Future<Map<String, dynamic>> revoke(String id) async {
+ revoked.add(id);
+ devices.removeWhere((device) => device['id'] == id);
+ return {'revoked': 1};
+ }
+}
+
+void main() {
+ final codeField = find.byKey(const Key('autonomous-device-code'));
+ const mismatch =
+ 'That code did not match. Generate a new code on your Autonomous robot, then try again.';
+
+ /// The page as the Devices tab has it: the paired list, and a way into the Wi-Fi code dialog.
+ Future<WifiRobotsController> open(
+ WidgetTester tester,
+ FakeAutonomousDeviceCli cli, {
+ bool dialog = true,
+ void Function()? openLocalNetworkSettings,
+ }) async {
+ final robots = WifiRobotsController(cli: cli)..start();
+ addTearDown(robots.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => ListView(
+ children: [
+ TextButton(
+ key: const Key('open-wifi'),
+ onPressed: () => showWifiPairDialog(
+ context,
+ robots,
+ openLocalNetworkSettings: openLocalNetworkSettings,
+ ),
+ child: const Text('Wi-Fi code'),
+ ),
+ WifiRobotsList(controller: robots),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ if (dialog) {
+ await tester.tap(find.byKey(const Key('open-wifi')));
+ await tester.pumpAndSettle();
+ }
+ return robots;
+ }
+
+ Future<void> select(WidgetTester tester, String id) async {
+ tester
+ .widget<AppSelectField<String?>>(
+ find.byKey(const Key('autonomous-device-selection')),
+ )
+ .onChanged(id);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> submit(WidgetTester tester, String code) async {
+ await tester.enterText(codeField, code);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> refresh(WidgetTester tester) async {
+ final button = find.byType(AppIconButton);
+ await tester.ensureVisible(button);
+ await tester.tap(button);
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('the code dialog keeps separate accessible purposes', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ final picker = find.bySemanticsLabel('Autonomous robot');
+ final pickerNode = tester.getSemantics(picker);
+ final codeNode = tester.getSemantics(
+ find.bySemanticsLabel('Six-character code'),
+ );
+ final refreshNode = tester.getSemantics(
+ find.byTooltip('Refresh Autonomous robot status'),
+ );
+ expect(pickerNode.getSemanticsData().value, 'Select a device');
+ expect(pickerNode.getSemanticsData().flagsCollection.isButton, isTrue);
+ expect(codeNode.id, isNot(pickerNode.id));
+ expect(codeNode.getSemanticsData().flagsCollection.isTextField, isTrue);
+ expect(refreshNode.id, isNot(pickerNode.id));
+ expect(
+ refreshNode.getSemanticsData().hasAction(SemanticsAction.tap),
+ isTrue,
+ );
+ await select(tester, 'device-1');
+ expect(tester.getSemantics(picker).getSemanticsData().value, 'Kitchen');
+ expect(cli.submissions, isEmpty);
+ expect(
+ find.textContaining('Separators are allowed, for example ABC-123.'),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'Harness CLI keeps the connection running when you close Desktop.',
+ ),
+ findsOneWidget,
+ );
+ } finally {
+ semantics.dispose();
+ }
+ });
+
+ testWidgets(
+ 'pairing normalizes the code, binds the chosen robot, closes and lists it',
+ (tester) async {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ await select(tester, 'device-1');
+ await submit(tester, 'o-i_l·u23');
+ expect(cli.submissions, [
+ {'code': '011V23', 'deviceId': 'device-1'},
+ ]);
+ expect(find.byType(WifiPairDialog), findsNothing);
+ expect(find.text('Paired over Wi-Fi'), findsOneWidget);
+ expect(find.text('Connected · fingerprint-device-1'), findsOneWidget);
+ },
+ );
+
+ testWidgets('a single robot on the network still has to be chosen', (
+ tester,
+ ) async {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ await submit(tester, 'ABC234');
+ expect(cli.submissions, isEmpty);
+ expect(
+ find.text('Select your discovered Autonomous robot first.'),
+ findsOneWidget,
+ );
+ expect(
+ tester.widget<TextField>(codeField).controller!.text,
+ 'ABC234',
+ reason: 'a code refused before sending stays to be corrected',
+ );
+ });
+
+ testWidgets('choosing another robot clears the typed code', (tester) async {
+ final cli = FakeAutonomousDeviceCli()
+ ..discovered.add({'id': 'device-2', 'name': 'Desk'});
+ await open(tester, cli);
+ await select(tester, 'device-1');
+ await tester.enterText(codeField, 'ABC234');
+ await select(tester, 'device-2');
+ expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
+ });
+
+ testWidgets('a robot that leaves the network takes its code with it', (
+ tester,
+ ) async {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ await select(tester, 'device-1');
+ await tester.enterText(codeField, 'ABC234');
+ cli.discovered = [
+ {'id': 'device-2', 'name': 'Desk'},
+ ];
+ await refresh(tester);
+ expect(tester.widget<TextField>(codeField).controller!.text, isEmpty);
+ expect(
+ tester
+ .widget<AppSelectField<String?>>(
+ find.byKey(const Key('autonomous-device-selection')),
+ )
+ .value,
+ isNull,
+ );
+ expect(cli.submissions, isEmpty);
+ });
+
+ testWidgets(
+ 'while pairing the robot cannot be changed; a mismatch recovers',
+ (tester) async {
+ final pending = Completer<void>();
+ final cli = FakeAutonomousDeviceCli()
+ ..pairWait = pending
+ ..discovered.add({'id': 'device-2', 'name': 'Desk'});
+ await open(tester, cli);
+ final picker = find.byKey(const Key('autonomous-device-selection'));
+ await select(tester, 'device-1');
+ final previousSelection = tester
+ .widget<AppSelectField<String?>>(picker)
+ .onChanged;
+ await tester.enterText(codeField, 'ABC234');
+ await tester.tap(find.byKey(const Key('autonomous-device-pair')));
+ await tester.pump();
+ expect(find.text('Pairing…'), findsOneWidget);
+ previousSelection('device-2');
+ await tester.pump();
+ expect(tester.widget<AppSelectField<String?>>(picker).value, 'device-1');
+ pending.completeError(
+ const AutonomousDeviceCliException('CODE_MISMATCH', 'Mismatch'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(mismatch), findsOneWidget);
+ expect(tester.widget<TextField>(codeField).enabled, isTrue);
+ // The message stays through a refresh, and a retry pairs the same chosen robot.
+ await refresh(tester);
+ expect(find.text(mismatch), findsOneWidget);
+ cli.pairWait = null;
+ await submit(tester, 'DEF567');
+ expect(cli.submissions.map((row) => row['deviceId']), [
+ 'device-1',
+ 'device-1',
+ ]);
+ expect(find.text(mismatch), findsNothing);
+ expect(find.text('Connected · fingerprint-device-1'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'a blocked local network says where to allow it; paired robots stay listed',
+ (tester) async {
+ var opened = 0;
+ final cli = FakeAutonomousDeviceCli()
+ ..networkBlocked = true
+ ..devices = [
+ {
+ 'id': 'fingerprint-1',
+ 'fingerprint': 'fingerprint-1',
+ 'label': 'Desk lamp',
+ 'online': false,
+ },
+ ];
+ await open(tester, cli, openLocalNetworkSettings: () => opened++);
+ final notice = find.byKey(const Key('autonomous-device-network-blocked'));
+ expect(notice, findsOneWidget);
+ expect(find.text('Allow Harness on your local network'), findsOneWidget);
+ expect(find.textContaining('No Autonomous robots found'), findsNothing);
+ await tester.tap(find.text('Open Settings'));
+ expect(opened, 1);
+ cli.networkBlocked = false;
+ await refresh(tester);
+ expect(notice, findsNothing);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Desk lamp'), findsOneWidget);
+ expect(find.text('Paired · Offline · fingerprint-1'), findsOneWidget);
+ },
+ );
+
+ testWidgets('an empty network says so and pairs nothing', (tester) async {
+ final cli = FakeAutonomousDeviceCli()..discovered = [];
+ await open(tester, cli);
+ expect(find.textContaining('No Autonomous robots found.'), findsOneWidget);
+ await submit(tester, 'ABC234');
+ expect(cli.submissions, isEmpty);
+ });
+
+ testWidgets('an older CLI is told to update', (tester) async {
+ await open(tester, FakeAutonomousDeviceCli()..unsupported = true);
+ expect(
+ find.text('Update Harness CLI to use Autonomous robots.'),
+ findsOneWidget,
+ );
+ expect(find.text('harness update'), findsOneWidget);
+ expect(codeField, findsNothing);
+ });
+
+ testWidgets('Revoke… confirms and targets the exact paired fingerprint', (
+ tester,
+ ) async {
+ final cli = FakeAutonomousDeviceCli()
+ ..devices = [
+ {
+ 'id': 'fingerprint-1',
+ 'fingerprint': 'fingerprint-1',
+ 'label': 'Kitchen',
+ 'online': true,
+ },
+ {
+ 'id': 'fingerprint-2',
+ 'fingerprint': 'fingerprint-2',
+ 'label': 'Desk',
+ 'online': false,
+ },
+ ];
+ await open(tester, cli, dialog: false);
+ await tester.tap(
+ find.byKey(const ValueKey('wifi-robot-revoke-fingerprint-1')),
+ );
+ await tester.pumpAndSettle();
+ expect(cli.revoked, isEmpty);
+ expect(find.text('Revoke Autonomous robot?'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('device-confirm')));
+ await tester.pumpAndSettle();
+ expect(cli.revoked, ['fingerprint-1']);
+ expect(find.text('Kitchen'), findsNothing);
+ expect(find.text('Desk'), findsOneWidget);
+ });
+
+ testWidgets('nothing paired, no list', (tester) async {
+ await open(tester, FakeAutonomousDeviceCli(), dialog: false);
+ expect(find.byKey(const Key('wifi-robots')), findsNothing);
+ });
+
+ testWidgets('without an injected CLI nothing runs, under test or later', (
+ tester,
+ ) async {
+ final robots = WifiRobotsController()..start();
+ addTearDown(robots.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(body: WifiPairDialog(controller: robots)),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.pump(const Duration(minutes: 2));
+ expect(tester.takeException(), isNull);
+ expect(
+ tester.widget<AppIconButton>(find.byType(AppIconButton)).onPressed,
+ isNull,
+ );
+ });
+
+ testWidgets('an injected CLI is not polled in the background in tests', (
+ tester,
+ ) async {
+ final cli = FakeAutonomousDeviceCli();
+ await open(tester, cli);
+ final calls = cli.statusCalls;
+ await tester.pump(const Duration(minutes: 2));
+ expect(cli.statusCalls, calls);
+ });
+
+ testWidgets('the first status read waits in a skeleton', (tester) async {
+ final pending = Completer<void>();
+ final cli = FakeAutonomousDeviceCli()..statusWait = pending;
+ final robots = WifiRobotsController(cli: cli)..start();
+ addTearDown(robots.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(body: WifiPairDialog(controller: robots)),
+ ),
+ );
+ await tester.pump();
+ expect(find.byType(SkeletonBlock), findsOneWidget);
+ pending.complete();
+ await tester.pumpAndSettle();
+ expect(find.byType(SkeletonBlock), findsNothing);
+ });
+
+ group('the Devices tab', () {
+ Future<(DevicesController, DialState, List<Map<String, Object?>>)> pump(
+ WidgetTester tester, {
+ WifiRobotsController? wifi,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 940);
+ addTearDown(tester.view.reset);
+ final dial = DialState();
+ final sent = <Map<String, Object?>>[];
+ final controller = DevicesController(
+ dial: dial,
+ accountId: 'a',
+ sendSettings: (_, patch) async {
+ sent.add(patch);
+ return true;
+ },
+ );
+ await controller.load();
+ report(dial, [deviceStatus('desk')]);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: DevicesScreen(controller: controller, wifi: wifi),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(() {
+ controller.dispose();
+ dial.dispose();
+ });
+ return (controller, dial, sent);
+ }
+
+ testWidgets('Add device offers the USB cable and the Wi-Fi code', (
+ tester,
+ ) async {
+ final cli = FakeAutonomousDeviceCli();
+ final wifi = WifiRobotsController(cli: cli);
+ addTearDown(wifi.dispose);
+ await pump(tester, wifi: wifi);
+ await tester.tap(find.byKey(const Key('devices-add')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('devices-add-usb')), findsOneWidget);
+ expect(find.byKey(const Key('devices-add-wifi')), findsOneWidget);
+ await tester.tap(find.byKey(const Key('devices-add-wifi')));
+ await tester.pumpAndSettle();
+ expect(find.byType(WifiPairDialog), findsOneWidget);
+ await select(tester, 'device-1');
+ await submit(tester, 'ABC234');
+ expect(find.byType(WifiPairDialog), findsNothing);
+ expect(find.text('Paired over Wi-Fi'), findsOneWidget);
+ expect(find.text('Connected · fingerprint-device-1'), findsOneWidget);
+
+ await tester.tap(find.byKey(const Key('devices-add')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('devices-add-usb')));
+ await tester.pumpAndSettle();
+ expect(find.text('Add a device'), findsOneWidget);
+ });
+
+ testWidgets('without the network list, Add device is the cable alone', (
+ tester,
+ ) async {
+ await pump(tester);
+ await tester.tap(find.byKey(const Key('devices-add')));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const Key('devices-add-wifi')), findsNothing);
+ expect(find.text('Add a device'), findsOneWidget);
+ });
+
+ testWidgets('Still companion is on the robot card and writes quiet', (
+ tester,
+ ) async {
+ final (controller, _, sent) = await pump(tester);
+ final key = controller.devices.single.key;
+ final quiet = find.byKey(ValueKey('devices-quiet-$key'));
+ await tester.ensureVisible(quiet);
+ expect(find.text('Still companion'), findsOneWidget);
+ await tester.tap(quiet);
+ await tester.pump();
+ expect(sent, [
+ {'quiet': true},
+ ]);
+ // Unconfirmed, the change times out rather than holding a timer past the test.
+ await tester.pump(const Duration(seconds: 9));
+ // The companion skins are still off, so there is no switch to follow one.
+ expect(kDeviceCompanionSkins, isFalse);
+ expect(find.text('Follow desktop companion'), findsNothing);
+ });
+ });
+}
diff --git a/docs/app.md b/docs/app.md
index 42a585b67..cff2d21a0 100644
--- a/docs/app.md
+++ b/docs/app.md
@@ -86,8 +86,8 @@ Other machines are reached through that daemon: it links to them with a per-mach
terminates the encryption locally, and hands the app plaintext. Machines ▸ Link Machine… runs the
link flow; the CLI equivalent is under [The daemon and CLI](#the-daemon-and-cli).
-Settings ▸ Profiles keeps that one sign-in and chooses which computer's tabs
-this window draws. **All machines** is the shared desk. A computer's row hides
+**Show in this window**, at the top of Machines, keeps that one sign-in and chooses which
+computer's tabs this window draws. **All machines** is the shared desk. Choosing a computer hides
tabs whose agents run anywhere else. Those tabs stay on the account, so another
window, or **All machines** here, still has them. Closing the last visible tab
opens an empty tab on this computer; it does not reveal a hidden one. A tab
diff --git a/docs/cli.md b/docs/cli.md
index 05e5bb973..c79a142f4 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -109,7 +109,8 @@ it), a path looks like a path, the first other word is the agent and a second na
Signing in is what makes a device trusted: every computer and app signed in to the account adds its
key to the account's device key log, and the others trust it with no password. Nothing asks you to
confirm a device; instead every device shows you each one it did not know before.
-`harness devices` is this machine's view, the same one Settings ▸ Your devices shows in the app.
+`harness devices` is this machine's view, the same one Machines shows in the app (Computers, and
+Phones & apps).
- **New.** A device added after this machine joined the account is flagged `new` (an OS notification
in the apps) and stays flagged across restarts until you confirm it on one of your trusted devices,