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.

Make remote folder selection keyboard friendly and reliable

deee73eb6eef44c
diff --git a/desktop/lib/widgets/remote_folder_picker.dart b/desktop/lib/widgets/remote_folder_picker.dart
index 3eeee782d..3512f8a8e 100644
--- a/desktop/lib/widgets/remote_folder_picker.dart
+++ b/desktop/lib/widgets/remote_folder_picker.dart
@@ -1,4 +1,8 @@
+import 'dart:math' as math;
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:path/path.dart' as p;
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
@@ -6,274 +10,547 @@ import '../theme/app_theme.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/skeleton.dart';
-/// Lets the user browse folders ON THE REMOTE MACHINE (via the `fs_list_dir` RPC) and returns the
-/// chosen absolute path, or null if cancelled. Desktop-app and the harness CLI usually run on two
-/// different computers, so this deliberately does not use a local native file picker.
+/// Browses the selected machine through fs_list_dir. The native folder chooser
+/// would return a path on this computer instead of the agent's machine.
Future<String?> showRemoteFolderPicker(
BuildContext context, {
required AppNotifier notifier,
required String machineId,
String? initialPath,
-}) {
- return showAppDialog<String>(
- context: context,
- builder: (context) => _RemoteFolderPickerDialog(
- notifier: notifier,
- machineId: machineId,
- initialPath: initialPath,
- ),
- );
-}
+}) => showAppDialog<String>(
+ context: context,
+ builder: (context) => _RemoteFolderPickerDialog(
+ notifier: notifier,
+ machineId: machineId,
+ initialPath: initialPath,
+ ),
+);
class _RemoteFolderPickerDialog extends StatefulWidget {
- final AppNotifier notifier;
- final String machineId;
- final String? initialPath;
-
const _RemoteFolderPickerDialog({
required this.notifier,
required this.machineId,
this.initialPath,
});
+ final AppNotifier notifier;
+ final String machineId;
+ final String? initialPath;
+
@override
State<_RemoteFolderPickerDialog> createState() =>
_RemoteFolderPickerDialogState();
}
class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
- String? _path;
- List<Map<String, dynamic>> _entries = [];
- bool _loading = true;
- String? _error;
+ final _location = TextEditingController();
+ final _locationFocus = FocusNode(debugLabel: 'Remote folder path');
+ final _foldersFocus = FocusNode(debugLabel: 'Remote folders');
+ final _scroll = ScrollController();
+ String? _path, _requestedPath, _error;
+ List<String> _entries = [];
+ bool _loading = true, _truncated = false;
+ int _request = 0, _edit = 0, _selected = -1;
+ double _rowHeight = 36;
+
+ bool get _canSelect =>
+ !_loading &&
+ _error == null &&
+ _path != null &&
+ _location.text.trim() == _path;
+
+ // The remote machine may use different path separators than this desktop.
+ p.Context get _paths => p.Context(
+ style:
+ (_path?.startsWith(r'\\') ?? false) ||
+ RegExp(r'^[A-Za-z]:[/\\]').hasMatch(_path ?? '')
+ ? p.Style.windows
+ : p.Style.posix,
+ );
+
+ String? get _parentPath {
+ if (_path == null) return null;
+ final parent = _paths.dirname(_path!);
+ return parent == _path ? null : parent;
+ }
@override
void initState() {
super.initState();
_load(widget.initialPath);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _locationFocus.requestFocus();
+ });
}
- Future<void> _load(String? path) async {
+ @override
+ void dispose() {
+ _location.dispose();
+ _locationFocus.dispose();
+ _foldersFocus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ Future<void> _load(String? path, {String? highlight}) async {
+ if (_loading && _request > 0 && path == _requestedPath) return;
+ final request = ++_request;
+ final edit = _edit;
setState(() {
_loading = true;
_error = null;
+ _requestedPath = path;
+ if (_location.text != (path ?? '')) {
+ _location.text = path ?? '';
+ _location.selection = TextSelection.collapsed(
+ offset: _location.text.length,
+ );
+ }
});
- final result = await widget.notifier.listRemoteFolder(
- widget.machineId,
- path,
- );
- if (!mounted) return;
+ Map<String, dynamic> result;
+ try {
+ result = await widget.notifier.listRemoteFolder(widget.machineId, path);
+ } catch (_) {
+ result = {'error': 'UNREACHABLE'};
+ }
+ if (!mounted || request != _request) return;
+ final resolved = result['path'];
final error = result['error'];
- if (error is String) {
- // Keep whatever `_path`/`_entries` was showing before the failed hop, so a bad click (e.g. a
- // restricted folder) leaves the browser where the user was instead of collapsing to blank.
+ if (error != null || resolved is! String || resolved.isEmpty) {
setState(() {
_loading = false;
- _error = error;
+ _error = edit != _edit
+ ? null
+ : error is String
+ ? error
+ : 'UNAVAILABLE';
});
return;
}
setState(() {
_loading = false;
- _path = result['path'] as String?;
- _entries = (result['entries'] as List<dynamic>? ?? [])
- .map((e) => Map<String, dynamic>.from(e as Map))
- .toList();
+ _path = resolved;
+ _entries = [
+ for (final entry in result['entries'] as List? ?? const [])
+ if (entry is Map &&
+ entry['isDir'] != false &&
+ entry['name'] is String &&
+ (entry['name'] as String).isNotEmpty)
+ entry['name'] as String,
+ ];
+ _truncated = result['truncated'] == true;
+ _selected = _entries.isEmpty
+ ? -1
+ : math.max(0, _entries.indexOf(highlight ?? ''));
+ // A reply may canonicalize a path, but must not replace a newer draft or
+ // disturb a selection/caret when the field already contains that path.
+ if (edit == _edit && _location.text != resolved) {
+ _location.value = TextEditingValue(
+ text: resolved,
+ selection: TextSelection(
+ baseOffset: 0,
+ extentOffset: resolved.length,
+ ),
+ );
+ }
+ });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && request == _request) _revealSelection();
});
}
- List<String> get _segments =>
- (_path ?? '').split('/').where((s) => s.isNotEmpty).toList();
+ void _openPath() {
+ final path = _location.text.trim();
+ if (path.isEmpty || (_loading && path == _requestedPath)) return;
+ _load(path);
+ }
- String _pathUpTo(int index) {
- final prefix = (_path ?? '').startsWith('/') ? '/' : '';
- return prefix + _segments.sublist(0, index + 1).join('/');
+ void _up() {
+ if (_loading) return;
+ final parent = _parentPath;
+ if (parent != null) _load(parent, highlight: _paths.basename(_path!));
}
- String? get _parentPath {
- if (_segments.length <= 1) return null;
- final prefix = (_path ?? '').startsWith('/') ? '/' : '';
- return prefix + _segments.sublist(0, _segments.length - 1).join('/');
+ void _select() {
+ if (_canSelect) Navigator.of(context).pop(_path);
}
- String _errorMessage(String code) {
- switch (code) {
- case 'FORBIDDEN':
- return "Can't browse outside the home directory on this machine.";
- case 'PERMISSION_DENIED':
- return "Can't open this folder — permission denied.";
- case 'NOT_A_DIRECTORY':
- return 'That path is not a folder.';
- case 'UNREACHABLE':
- return 'Machine is unreachable.';
- default:
- return "Can't open this folder.";
+ void _openSelected() {
+ if (!_loading && _selected >= 0 && _selected < _entries.length) {
+ _load(_paths.join(_path!, _entries[_selected]));
+ }
+ }
+
+ void _revealSelection() {
+ if (!_scroll.hasClients || _selected < 0) return;
+ final top = _selected * _rowHeight;
+ final bottom = top + _rowHeight;
+ final position = _scroll.position;
+ final target = top < position.pixels
+ ? top
+ : bottom > position.pixels + position.viewportDimension
+ ? bottom - position.viewportDimension
+ : position.pixels;
+ _scroll.jumpTo(target.clamp(0.0, position.maxScrollExtent));
+ }
+
+ KeyEventResult _folderKey(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final keyboard = HardwareKeyboard.instance;
+ if (keyboard.isControlPressed ||
+ keyboard.isMetaPressed ||
+ keyboard.isAltPressed ||
+ keyboard.isShiftPressed) {
+ return KeyEventResult.ignored;
}
+ final key = event.logicalKey;
+ if (key == LogicalKeyboardKey.arrowLeft) {
+ _up();
+ } else if (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter ||
+ key == LogicalKeyboardKey.arrowRight) {
+ _openSelected();
+ } else if (key == LogicalKeyboardKey.arrowDown ||
+ key == LogicalKeyboardKey.arrowUp ||
+ key == LogicalKeyboardKey.home ||
+ key == LogicalKeyboardKey.end) {
+ if (!_loading && _entries.isNotEmpty) {
+ setState(() {
+ _selected = switch (key) {
+ LogicalKeyboardKey.home => 0,
+ LogicalKeyboardKey.end => _entries.length - 1,
+ LogicalKeyboardKey.arrowUp => (_selected - 1).clamp(
+ 0,
+ _entries.length - 1,
+ ),
+ _ => (_selected + 1).clamp(0, _entries.length - 1),
+ };
+ });
+ _revealSelection();
+ }
+ } else {
+ return KeyEventResult.ignored;
+ }
+ return KeyEventResult.handled;
}
+ String _errorMessage(String code) => switch (code) {
+ 'FORBIDDEN' =>
+ 'Choose a folder inside your home directory on this machine.',
+ 'PERMISSION_DENIED' => 'You don’t have permission to open this folder.',
+ 'NOT_A_DIRECTORY' => 'That path is not a folder.',
+ 'NOT_FOUND' =>
+ 'This folder could not be found. Check the path and try again.',
+ 'INVALID_PATH' => 'Enter a full folder path on this machine.',
+ 'UNREACHABLE' =>
+ 'Couldn’t reach this machine. Check its connection and retry.',
+ _ => 'Couldn’t open this folder. Try again.',
+ };
+
@override
Widget build(BuildContext context) {
- return AlertDialog(
- title: const Text('Choose a folder'),
- content: SizedBox(
- width: 440,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _Breadcrumbs(
- segments: _segments,
- onTap: (i) => _load(_pathUpTo(i)),
- ),
- const SizedBox(height: 10),
- SizedBox(height: 260, child: _buildBody(context)),
- ],
+ grid.AppTheme.watch(context);
+ final scale = MediaQuery.textScalerOf(context);
+ _rowHeight = math.max(36, scale.scale(14) * 1.35 + 16);
+ final listHeight =
+ (MediaQuery.sizeOf(context).height - 320 - scale.scale(50)).clamp(
+ 120.0,
+ 280.0,
+ );
+ final machine = widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName;
+ final mac = Theme.of(context).platform == TargetPlatform.macOS;
+ final actionStyle = ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(
+ Size(
+ 0,
+ math.max(
+ grid.AppControl.heightScaled,
+ scale.scale(grid.AppControl.fontSize) * 1.25 + 16,
+ ),
),
),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('Cancel'),
- ),
- FilledButton(
- onPressed: _path == null
- ? null
- : () => Navigator.of(context).pop(_path),
- child: const Text('Select this folder'),
- ),
- ],
);
- }
-
- Widget _buildBody(BuildContext context) {
- return DecoratedBox(
- decoration: BoxDecoration(
- color: AppColors.background,
- border: Border.all(color: AppColors.border),
- borderRadius: BorderRadius.circular(6),
+ return IconButtonTheme(
+ data: IconButtonThemeData(
+ style: ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size(32, 32)),
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(6)),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(grid.AppControl.radius),
+ ),
+ ),
+ overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? AppColors.muted
+ : states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused)
+ ? AppColors.text
+ : AppColors.textSoft,
+ ),
+ ),
),
- child: _loading
- // Every click into a folder passes through here, so the rows are
- // drawn where rows will be rather than a spinner in the middle of
- // a well that empties and refills on each step.
- ? const _FolderRowsSkeleton(key: Key('folders-skeleton'))
- : _error != null
- ? Center(
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: Text(
- _errorMessage(_error!),
- textAlign: TextAlign.center,
- style: TextStyle(
- color: AppColors.danger,
- fontFamily: AppFonts.sans,
- fontSize: 11.2,
+ child: CallbackShortcuts(
+ bindings: {
+ SingleActivator(
+ LogicalKeyboardKey.enter,
+ meta: mac,
+ control: !mac,
+ includeRepeats: false,
+ ): _select,
+ const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up,
+ },
+ child: AlertDialog(
+ title: const Text('Choose a folder'),
+ scrollable: true,
+ content: SizedBox(
+ width: 520,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'On ${machine ?? 'the remote machine'}',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ const SizedBox(height: 12),
+ Focus(
+ onKeyEvent: (node, event) {
+ if (event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.arrowDown &&
+ !HardwareKeyboard.instance.isAltPressed &&
+ !HardwareKeyboard.instance.isControlPressed &&
+ !HardwareKeyboard.instance.isMetaPressed &&
+ !HardwareKeyboard.instance.isShiftPressed &&
+ _location.value.composing.isCollapsed &&
+ !_loading &&
+ _entries.isNotEmpty) {
+ _foldersFocus.requestFocus();
+ _revealSelection();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: TextField(
+ key: const Key('remote-folder-path'),
+ controller: _location,
+ focusNode: _locationFocus,
+ autofocus: true,
+ style: grid.kFieldTextStyle,
+ decoration: InputDecoration(
+ labelText: 'Folder path',
+ hintText: 'Enter a full folder path…',
+ suffixIcon: IconButton(
+ tooltip: 'Open path',
+ onPressed:
+ _location.text.trim().isEmpty ||
+ (_loading &&
+ _location.text.trim() == _requestedPath)
+ ? null
+ : _openPath,
+ icon: const Icon(Icons.arrow_forward, size: 18),
+ ),
+ ),
+ onChanged: (_) => setState(() {
+ _edit++;
+ _error = null;
+ }),
+ onEditingComplete: () {},
+ onSubmitted: (_) => _openPath(),
),
),
- ),
- )
- : _entries.isEmpty && _parentPath == null
- ? Center(
- child: Text(
- 'No subfolders here.',
- style: TextStyle(
- color: AppColors.muted,
- fontFamily: AppFonts.sans,
- fontSize: 11.2,
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ _path != null && _location.text.trim() != _path
+ ? 'Showing $_path'
+ : 'Folders',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.labelMedium,
+ ),
+ ),
+ IconButton(
+ key: const Key('remote-folder-home'),
+ tooltip: 'Home folder on this machine',
+ onPressed: () => _load(null),
+ icon: const Icon(Icons.home_outlined, size: 18),
+ ),
+ IconButton(
+ tooltip: mac
+ ? 'Up one folder (⌥↑)'
+ : 'Up one folder (Alt+↑)',
+ onPressed: _loading || _parentPath == null ? null : _up,
+ icon: const Icon(Icons.arrow_upward, size: 18),
+ ),
+ ],
),
- ),
- )
- : ListView(
- children: [
- if (_parentPath != null)
- _FolderRow(
- icon: Icons.arrow_upward,
- label: '.. (up one level)',
- onTap: () => _load(_parentPath),
+ Focus(
+ focusNode: _foldersFocus,
+ onKeyEvent: _folderKey,
+ onFocusChange: (_) => setState(() {}),
+ child: Container(
+ key: const Key('remote-folder-list'),
+ height: listHeight,
+ decoration: BoxDecoration(
+ color: AppColors.background,
+ border: Border.all(
+ color: _foldersFocus.hasFocus
+ ? AppColors.accent
+ : AppColors.border,
+ ),
+ borderRadius: BorderRadius.circular(
+ grid.AppCard.insetRadius,
+ ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: _loading
+ ? const _FolderRowsSkeleton()
+ : _entries.isEmpty
+ ? Center(
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Text(
+ _path == null
+ ? 'Enter a path or open your home folder.'
+ : 'No subfolders here.',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ ),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ itemExtent: _rowHeight,
+ itemCount: _entries.length,
+ itemBuilder: (context, index) => Semantics(
+ selected: index == _selected,
+ child: Material(
+ color:
+ index == _selected && _foldersFocus.hasFocus
+ ? AppColors.selected
+ : Colors.transparent,
+ child: InkWell(
+ canRequestFocus: false,
+ onTap: () {
+ _foldersFocus.requestFocus();
+ setState(() => _selected = index);
+ _openSelected();
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ ),
+ child: Row(
+ children: [
+ Icon(
+ Icons.folder_outlined,
+ size: 18,
+ color: AppColors.mutedStrong,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ _entries[index],
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ Icon(
+ Icons.chevron_right,
+ size: 16,
+ color: AppColors.mutedStrong,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
),
- for (final entry in _entries)
- _FolderRow(
- icon: Icons.folder_outlined,
- label: entry['name'] as String? ?? '',
- onTap: () => _load('${_path ?? ''}/${entry['name']}'),
+ ),
+ if (_error != null) ...[
+ const SizedBox(height: 8),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Semantics(
+ liveRegion: true,
+ child: Text(
+ _errorMessage(_error!),
+ style: Theme.of(context).textTheme.bodySmall
+ ?.copyWith(color: AppColors.danger),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ TextButton(
+ onPressed: () => _load(_requestedPath),
+ child: const Text('Retry'),
+ ),
+ ],
),
+ ] else if (_truncated && !_loading) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'More folders are available. Enter their full path to open them.',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ ],
],
),
- );
- }
-}
-
-class _Breadcrumbs extends StatelessWidget {
- final List<String> segments;
- final ValueChanged<int> onTap;
-
- const _Breadcrumbs({required this.segments, required this.onTap});
-
- @override
- Widget build(BuildContext context) {
- return Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
- decoration: BoxDecoration(
- color: AppColors.background,
- border: Border.all(color: AppColors.border),
- borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),
- ),
- child: Wrap(
- crossAxisAlignment: WrapCrossAlignment.center,
- children: [
- for (var i = 0; i < segments.length; i++) ...[
- if (i > 0)
- Padding(
- padding: EdgeInsets.symmetric(horizontal: 2),
- child: Text(
- '/',
- style: TextStyle(color: AppColors.borderStrong),
- ),
- ),
- InkWell(
- onTap: () => onTap(i),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 2),
- child: Text(
- segments[i],
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontSize: 13.5,
- color: i == segments.length - 1
- ? AppColors.text
- : AppColors.mutedStrong,
- ),
- ),
+ ),
+ actions: [
+ TextButton(
+ style: actionStyle,
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ Tooltip(
+ message: mac
+ ? 'Select this folder (⌘↩)'
+ : 'Select this folder (Ctrl+Enter)',
+ child: FilledButton(
+ style: actionStyle,
+ onPressed: _canSelect ? _select : null,
+ child: const Text('Select this folder'),
),
),
],
- ],
+ ),
),
);
}
}
-/// Five [_FolderRow]s with nothing in them: the glyph's square and a name of
-/// varying length, at the row's own padding.
class _FolderRowsSkeleton extends StatelessWidget {
- const _FolderRowsSkeleton({super.key});
-
- static const _widths = [0.42, 0.28, 0.56, 0.34, 0.48];
+ const _FolderRowsSkeleton();
@override
Widget build(BuildContext context) => SkeletonList(
- rows: _widths.length,
+ rows: 5,
semanticsLabel: 'Loading folders',
itemBuilder: (context, i) => Padding(
- padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
- const Skeleton(width: 14, height: 14, radius: 3),
- const SizedBox(width: 9),
+ const Skeleton(width: 18, height: 18, radius: 3),
+ const SizedBox(width: 10),
Expanded(
child: SkeletonText(
- style: TextStyle(fontFamily: AppFonts.sans, fontSize: 13.5),
- widthFactor: _widths[i],
+ style: Theme.of(context).textTheme.bodyMedium!,
+ widthFactor: const [0.42, 0.28, 0.56, 0.34, 0.48][i],
),
),
],
@@ -281,42 +558,3 @@ class _FolderRowsSkeleton extends StatelessWidget {
),
);
}
-
-class _FolderRow extends StatelessWidget {
- final IconData icon;
- final String label;
- final VoidCallback onTap;
-
- const _FolderRow({
- required this.icon,
- required this.label,
- required this.onTap,
- });
-
- @override
- Widget build(BuildContext context) {
- return InkWell(
- onTap: onTap,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 8),
- child: Row(
- children: [
- Icon(icon, size: 14, color: AppColors.mutedStrong),
- const SizedBox(width: 9),
- Expanded(
- child: Text(
- label,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppColors.textSoft,
- fontFamily: AppFonts.sans,
- fontSize: 13.5,
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-}
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
new file mode 100644
index 000000000..adb381449
--- /dev/null
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -0,0 +1,452 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/new_agent_dialog.dart';
+import 'package:harness/widgets/remote_folder_picker.dart';
+
+class _Folders extends AppNotifier {
+ _Folders()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ name: 'Studio Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ );
+ }
+
+ final requests =
+ <
+ ({String machine, String? path, Completer<Map<String, dynamic>> reply})
+ >[];
+
+ final launches = <({String machine, String engine, String folder})>[];
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String folder,
+ bool bypassPermission = false,
+ String? codexHome,
+ String? swarmId,
+ PaneSplitRequest? split,
+ }) async {
+ launches.add((machine: machineId, engine: engine, folder: folder));
+ return null;
+ }
+
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) {
+ final reply = Completer<Map<String, dynamic>>();
+ requests.add((machine: machineId, path: path, reply: reply));
+ return reply.future;
+ }
+}
+
+Map<String, dynamic> _listing(String path, [List<String> names = const []]) => {
+ 'path': path,
+ 'entries': [
+ for (final name in names) {'name': name, 'isDir': true},
+ ],
+};
+
+Future<void> _open(
+ WidgetTester tester,
+ _Folders app, {
+ ValueChanged<String?>? onResult,
+ TargetPlatform platform = TargetPlatform.macOS,
+ double textScale = 1,
+}) async {
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: Brightness.dark)
+ .copyWith(platform: platform),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: child!,
+ ),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () async {
+ final result = await showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: 'remote',
+ );
+ onResult?.call(result);
+ },
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+}
+
+void main() {
+ testWidgets('cannot select the old folder while opening another folder', (
+ tester,
+ ) async {
+ final app = _Folders();
+ String? selected;
+ await _open(tester, app, onResult: (value) => selected = value);
+ app.requests.single.reply.complete(_listing('/home/dev', ['code']));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('code'));
+ await tester.pump();
+ expect(app.requests.last.path, '/home/dev/code');
+ final select = find.widgetWithText(FilledButton, 'Select this folder');
+ expect(tester.widget<FilledButton>(select).onPressed, isNull);
+ expect(selected, isNull);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ expect(
+ app.requests,
+ hasLength(2),
+ reason: 'Up cannot use the old folder while another is loading.',
+ );
+ app.requests.last.reply.complete(_listing('/home/dev/code'));
+ await tester.pumpAndSettle();
+ await tester.tap(select);
+ await tester.pumpAndSettle();
+ expect(selected, '/home/dev/code');
+ });
+
+ testWidgets('a newer path wins over an older reply and stays editable', (
+ tester,
+ ) async {
+ final app = _Folders();
+ String? selected;
+ await _open(tester, app, onResult: (value) => selected = value);
+ final input = find.byKey(const Key('remote-folder-path'));
+ await tester.enterText(input, '/home/dev/new-project');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(app.requests.map((request) => request.path), [
+ null,
+ '/home/dev/new-project',
+ ]);
+ expect(
+ app.requests.every((request) => request.machine == 'remote'),
+ isTrue,
+ );
+ app.requests.last.reply.complete(
+ _listing('/home/dev/new-project', ['src']),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ app.requests.first.reply.complete(_listing('/home/dev', ['old']));
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(input).controller!.text,
+ '/home/dev/new-project',
+ );
+ expect(find.text('src'), findsOneWidget);
+ expect(find.text('old'), findsNothing);
+ await tester.tap(find.text('Select this folder'));
+ await tester.pumpAndSettle();
+ expect(selected, '/home/dev/new-project');
+ });
+
+ testWidgets(
+ 'a late reply preserves a path draft, selection and composition',
+ (tester) async {
+ final app = _Folders();
+ await _open(tester, app);
+ final input = find.byKey(const Key('remote-folder-path'));
+ const draft = TextEditingValue(
+ text: '/home/dev/日本語',
+ selection: TextSelection.collapsed(offset: 13),
+ composing: TextRange(start: 10, end: 13),
+ );
+ tester.testTextInput.updateEditingValue(draft);
+ await tester.pump();
+ app.requests.single.reply.complete(_listing('/home/dev', ['code']));
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(input).controller!.value, draft);
+ expect(
+ tester
+ .widget<FilledButton>(
+ find.widgetWithText(FilledButton, 'Select this folder'),
+ )
+ .onPressed,
+ isNull,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(app.requests, hasLength(1));
+ },
+ );
+
+ testWidgets(
+ 'failed browsing preserves the last folder and retries in place',
+ (tester) async {
+ final app = _Folders();
+ await _open(tester, app);
+ app.requests.single.reply.complete(
+ _listing('/home/dev', ['code', 'notes']),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('code'));
+ await tester.pump();
+ app.requests.last.reply.complete({'error': 'PERMISSION_DENIED'});
+ await tester.pumpAndSettle();
+ expect(find.text('notes'), findsOneWidget);
+ expect(find.text('Showing /home/dev'), findsOneWidget);
+ expect(
+ find.text('You don’t have permission to open this folder.'),
+ findsOneWidget,
+ );
+ final input = tester.widget<TextField>(
+ find.byKey(const Key('remote-folder-path')),
+ );
+ expect(input.controller!.text, '/home/dev/code');
+ expect(
+ tester
+ .widget<FilledButton>(
+ find.widgetWithText(FilledButton, 'Select this folder'),
+ )
+ .onPressed,
+ isNull,
+ );
+ await tester.tap(find.text('Retry'));
+ await tester.tap(find.text('Retry'));
+ await tester.pump();
+ expect(app.requests.map((request) => request.path), [
+ null,
+ '/home/dev/code',
+ '/home/dev/code',
+ ]);
+ app.requests.last.reply.complete(_listing('/home/dev/code', ['project']));
+ await tester.pumpAndSettle();
+ expect(find.text('project'), findsOneWidget);
+ expect(find.text('Retry'), findsNothing);
+ expect(
+ tester
+ .widget<FilledButton>(
+ find.widgetWithText(FilledButton, 'Select this folder'),
+ )
+ .onPressed,
+ isNotNull,
+ );
+ },
+ );
+
+ for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {
+ testWidgets(
+ 'keyboard path, long-list browsing and selection on $platform',
+ (tester) async {
+ final app = _Folders();
+ String? selected;
+ await _open(
+ tester,
+ app,
+ platform: platform,
+ onResult: (value) => selected = value,
+ );
+ final entries = [for (var i = 0; i < 60; i++) 'project-$i'];
+ app.requests.single.reply.complete(_listing('/home/dev', entries));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(
+ FocusManager.instance.primaryFocus!.debugLabel,
+ 'Remote folders',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.end);
+ await tester.pump();
+ expect(find.text('project-59').hitTestable(), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.requests.last.path, '/home/dev/project-58');
+ app.requests.last.reply.complete(
+ _listing('/home/dev/project-58', ['src']),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ FocusManager.instance.primaryFocus!.debugLabel,
+ 'Remote folders',
+ );
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ await tester.pump();
+ expect(app.requests.last.path, '/home/dev');
+ app.requests.last.reply.complete(_listing('/home/dev', entries));
+ await tester.pumpAndSettle();
+ expect(find.text('project-58').hitTestable(), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.requests.last.path, '/home/dev/project-58');
+ app.requests.last.reply.complete(_listing('/home/dev/project-58'));
+ await tester.pumpAndSettle();
+ final modifier = platform == TargetPlatform.macOS
+ ? LogicalKeyboardKey.metaLeft
+ : LogicalKeyboardKey.controlLeft;
+ await tester.sendKeyDownEvent(modifier);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(modifier);
+ await tester.pumpAndSettle();
+ expect(selected, '/home/dev/project-58');
+ },
+ );
+ }
+
+ testWidgets(
+ 'home recovers an initial failure; cancelling ignores late replies',
+ (tester) async {
+ final app = _Folders();
+ var returned = false;
+ String? selected;
+ await _open(
+ tester,
+ app,
+ onResult: (value) {
+ returned = true;
+ selected = value;
+ },
+ );
+ app.requests.single.reply.complete({'error': 'UNREACHABLE'});
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'Couldn’t reach this machine. Check its connection and retry.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('remote-folder-home')));
+ await tester.pump();
+ expect(app.requests.last.path, isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ app.requests.last.reply.complete(_listing('/home/dev', ['code']));
+ await tester.pumpAndSettle();
+ expect(returned, isTrue);
+ expect(selected, isNull);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'remote selection returns to New agent without launching or losing choices',
+ (tester) async {
+ final app = _Folders();
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: Brightness.dark)
+ .copyWith(platform: TargetPlatform.macOS),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'remote',
+ source: 'test',
+ initialFolder: '/home/dev/old',
+ ),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-agent-quick-codex')));
+ await tester.tap(find.text('Change'));
+ await tester.pump();
+ app.requests.single.reply.complete(_listing('/home/dev/old'));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('/home/dev/old'), findsOneWidget);
+ expect(app.launches, isEmpty);
+ await tester.tap(find.text('Change'));
+ await tester.pump();
+ app.requests.last.reply.complete(_listing('/home/dev/old'));
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('remote-folder-path')),
+ '/home/dev/target',
+ );
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ app.requests.last.reply.complete(_listing('/home/dev/target'));
+ await tester.pumpAndSettle();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.text('/home/dev/target'), findsOneWidget);
+ expect(app.launches, isEmpty);
+ await tester.tap(find.text('Create on Studio Mac'));
+ await tester.pumpAndSettle();
+ expect(app.launches, [
+ (machine: 'remote', engine: 'codex', folder: '/home/dev/target'),
+ ]);
+ expect(find.byType(AlertDialog), findsNothing);
+ },
+ );
+
+ testWidgets('large text keeps actions reachable at the minimum window size', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 560);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final app = _Folders();
+ await _open(tester, app, textScale: 2);
+ app.requests.single.reply.complete(_listing('/home/dev', ['code']));
+ await tester.pumpAndSettle();
+ expect(find.text('Select this folder').hitTestable(), findsOneWidget);
+ final input = find.byKey(const Key('remote-folder-path'));
+ await tester.ensureVisible(input);
+ await tester.enterText(input, '/home/dev/missing');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ app.requests.last.reply.complete({'error': 'NOT_FOUND'});
+ await tester.pumpAndSettle();
+ await tester.ensureVisible(find.text('Retry'));
+ await tester.tap(find.text('Retry'));
+ await tester.pump();
+ app.requests.last.reply.complete(_listing('/home/dev/missing'));
+ await tester.pumpAndSettle();
+ expect(find.text('Select this folder').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/docs/harness-v2-appearance-onboarding.md b/docs/harness-v2-appearance-onboarding.md
index 87ce31a3a..11c269d1d 100644
--- a/docs/harness-v2-appearance-onboarding.md
+++ b/docs/harness-v2-appearance-onboarding.md
@@ -156,3 +156,29 @@ A later full-screen probe found that first launch focused the shell, while arriv
The [W3C combobox pattern](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) documents a collapsed default and several possible expansion triggers, including Down Arrow, focus and typing. Our choice is to keep the welcome useful while making search immediately available. This is a Harness interaction decision, not a claim of complete ARIA or native accessibility conformance. Keymap overrides, composition ownership, explicit command mode and both search locations retain their existing behavior.
The full Flutter screen was rendered at 880×560 for fresh welcome, prefilled creation, New swarm after work and inline results. Regression checks cover first arrival, close-last-swarm, keyboard opening, retained query/selection/composition, native-search cancellation and the first folder action. The render uses Flutter's fallback titlebar; native field behavior is checked separately in a hidden AppKit window. Live first-install observation and native input-to-display timing remain unmeasured.
+
+## Remote folder selection
+
+The shared remote folder chooser now names the machine and offers an editable
+full path. Enter opens the path; Down moves into the list, arrows browse, Enter
+opens a folder, Alt-Up returns to the parent, and Cmd-Enter (Ctrl-Enter on other
+platforms) selects the currently loaded folder. Home remains available when an
+initial folder no longer exists. The list also explains when the remote server's
+bounded reply omits more folders, which can still be opened by their full paths.
+
+A regression reproduced Select returning the previous folder while the next one
+was still loading. Selection now requires a successfully loaded path matching
+the editor. Late replies cannot replace a newer request or path draft; IME and
+selection survive a reply. A failed hop keeps the last usable list visible,
+names the directory still shown, and offers Retry without leaving the dialog.
+Cancel returns to the same New agent form; selecting a folder preserves the
+chosen agent and does not create a runtime by itself.
+
+Nine new folder regressions and the surrounding onboarding, project, profile
+and creation checks pass (57 total), plus real-font renders at 880×560 with
+normal and 2× text. The visual pass adjusted icon controls and button height for
+large text. Analysis has zero errors/warnings and 14 existing infos. Artifacts:
+`/private/tmp/harness-remote-folder-{final-tests,final-analyze}.log` and
+`/private/tmp/harness-remote-folder-{ready,error,large-text}.png`. The checks use
+isolated remote replies and creation calls, not real remote agents; native
+input timing and observed first-install flows remain unverified.
diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.md
index d149fdaaf..fc3e43151 100644
--- a/docs/harness-v2-handoff.md
+++ b/docs/harness-v2-handoff.md
@@ -22,6 +22,11 @@ History recovery also reuses a partially restored swarm: reopening an agent and
then its original swarm adds the missing views to the same tab, retaining newer
choices and live sessions. No runtime cleanup was introduced.
+The remote folder chooser now accepts a full path and supports keyboard browsing,
+with in-place retry and latest-request ownership. A pending or failed hop cannot
+select the previous folder. These changes apply wherever the shared remote
+chooser is used: agent working folders, saved projects and profile folders.
+
## Goal
Build the best everyday workspace for people directing persistent AI agents:
@@ -286,10 +291,31 @@ darker modal veil. See [first-use details](harness-v2-appearance-onboarding.md).
Observed first-install/provider flows and onboarding conversion/time remain
unverified; do not infer them from these UI changes.
+**Remote folder selection:** the chosen machine is named above an editable path.
+Enter opens that path; Down enters the folder list, arrows move, Enter opens a
+folder, Alt-Up goes to its parent, and Cmd-Enter (Ctrl-Enter on other platforms)
+selects the loaded folder. Home and Retry recover from inaccessible paths.
+Delayed replies cannot replace a newer request, path draft or composition.
+Failures retain the last usable listing and identify which directory it shows.
+Folder selection returns to the same New agent choices and starts no agent.
+
**Archived drafts:** both are superseded. The onboarding ideas were adapted into
the common page, without adding another first-tab-only component.
-**Latest verification:** the History recovery and viewport-focus continuation,
+**Latest verification:** the remote-folder continuation passes 57 affected
+workflow checks, including nine new folder regressions, plus a real-font render
+check at 880×560 with normal and 2× text (58 total). Analysis reports no errors
+or warnings and the same 14 existing informational diagnostics. Logs:
+`/private/tmp/harness-remote-folder-{final-tests,final-analyze}.log`.
+The normal macOS Release build also succeeds with `FLUTTER_TARGET=lib/main.dart`:
+`/private/tmp/harness-remote-folder-release/Build/Products/Release/Harness.app`;
+log: `/private/tmp/harness-remote-folder-release.log`. The running app was not
+replaced or restarted.
+The tested folder replies and creation calls are isolated fixtures; no real
+agent was started or given input. Live remote and first-install qualification
+remain outstanding, and benchmarking remains deferred.
+
+**Previous verification:** the History recovery and viewport-focus continuation,
including the team's default-machine update in `eef17f6`, passes **1,317 desktop
tests**, one existing skip. The analyzer reports
zero errors/warnings and the same 14 informational diagnostics. The isolated
@@ -528,6 +554,7 @@ that its isolated window can become active/key.
| Area | Start here |
| --- | --- |
| Workspace orchestration, picker routes, split/new-agent context | `desktop/lib/screens/swarm_screen.dart` |
+| Shared remote folder browsing and request ownership | `desktop/lib/widgets/remote_folder_picker.dart`, `desktop/test/remote_folder_picker_test.dart` |
| Search data, actions, destinations | `desktop/lib/state/swarm_search.dart`, `swarm_navigation.dart`, `swarm_catalog.dart` |
| Distinct Navigate and shared Add/welcome UI | `desktop/lib/widgets/swarm_navigator.dart`, `swarm_switcher.dart`, `swarm_inline_search.dart`, `swarm_search_input.dart`, `swarm_welcome.dart` |
| Preview extraction | `desktop/lib/terminal/search_output_preview.dart` |
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index d369cff1a..268a8aeb2 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -6,6 +6,23 @@ Updated 2026-09-14 after integrating the continuation into main. This is a worki
## Continue directly on main
+- Made the shared remote folder chooser work by keyboard: enter a full path,
+ browse with arrows/Enter, go up with Alt-Up, and select the loaded folder with
+ Cmd-Enter (Ctrl-Enter elsewhere). It names the target machine and keeps Home
+ and Retry available. Failed navigation preserves the last usable listing;
+ pending navigation cannot accidentally select the previous folder. Older
+ replies cannot replace a newer path, text selection or composition. Selecting
+ a folder returns to the existing agent choices without starting a runtime.
+ The affected onboarding/project/profile/creation checks pass (57 tests), plus
+ a real-font render check at 880×560 with normal/2× text. Analysis has zero
+ errors/warnings and 14 existing infos. Logs:
+ `/private/tmp/harness-remote-folder-{final-tests,final-analyze}.log`.
+ The normal macOS Release build succeeds with the production `lib/main.dart`
+ entry point at `/private/tmp/harness-remote-folder-release/Build/Products/Release/Harness.app`;
+ log: `/private/tmp/harness-remote-folder-release.log`. It was not launched and
+ the user's running app was not replaced or restarted.
+ These are isolated UI/transport checks; live remote and first-install
+ qualification remain open. Benchmarking remains deferred.
- Clarified **Remove from swarm** in the pane/native menus and keyboard help.
The action still removes only a view. Fixed History recovery that created a
second same-named swarm after one of its agents had already been reopened: