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.

fix(desktop): one folder chooser at a time, and never behind something else

0xken150019047f4593
diff --git a/desktop/lib/core/desktop_window.dart b/desktop/lib/core/desktop_window.dart
index 3bd852d71..10af97564 100644
--- a/desktop/lib/core/desktop_window.dart
+++ b/desktop/lib/core/desktop_window.dart
@@ -49,6 +49,33 @@ Future<void> configureDesktopWindow({
await windowManager.focus();
}
+int _nativePickers = 0;
+
+/// Whether a native file chooser is on screen right now.
+///
+/// macOS draws `getDirectoryPath` as a SHEET attached to our window (the
+/// `file_selector_macos` plugin calls `beginSheetModal` whenever the registrar
+/// has a window). A sheet is modal to that window: nothing behind it takes a
+/// click, and no Flutter route pushed underneath it can be reached. So anything
+/// here that raises, re-orders or draws over the window has to ask first,
+/// rather than fighting a stack the person is already standing in.
+bool get nativePickerOpen => _nativePickers > 0;
+
+/// Runs [open] — a native chooser — with [nativePickerOpen] held.
+///
+/// The count is raised and lowered here rather than at the call sites because
+/// their own "already picking" flags live in `State` objects and stop being
+/// updated the moment the dialog unmounts; this one must come back down even
+/// then, or the app would believe a chooser was open forever.
+Future<T> whileNativePicker<T>(Future<T> Function() open) async {
+ _nativePickers++;
+ try {
+ return await open();
+ } finally {
+ _nativePickers--;
+ }
+}
+
/// Bring the window to the front, wherever it was.
///
/// For work that STARTS somewhere else. Speaking into the dial opens the task palette here, and a
@@ -60,8 +87,12 @@ Future<void> configureDesktopWindow({
/// backgrounded one needs the focus call, and which of the two applies is not knowable from here — so
/// both run, in that order. Failures are swallowed on purpose: the plugin throws on a platform without a
/// window server (a headless test host), and losing the palette is worse than losing the raise.
+///
+/// A raise is SKIPPED while [nativePickerOpen]: the person is already at this
+/// window, answering a modal sheet, and re-ordering the window under it buys
+/// nothing — whatever wanted the front has to wait for the answer anyway.
Future<void> revealWindow() async {
- if (!hasManagedWindow) return;
+ if (!hasManagedWindow || nativePickerOpen) return;
try {
if (await windowManager.isMinimized()) await windowManager.restore();
await windowManager.show();
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index c5f9d71c5..fcb34a6c1 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -207,6 +207,15 @@ class _SwarmScreenState extends State<SwarmScreen>
(String, bool)? _lastWorkspace;
bool _spokenPaletteOpen = false;
bool _dialogOpen = false;
+
+ /// A folder chooser opened from the new-harness box is still waiting.
+ ///
+ /// The box keeps its keyboard focus while the chooser is up, so Enter on the
+ /// Browse… row — or a second click — arrives here again. AppKit answers a
+ /// second `beginSheetModal` by QUEUEING it behind the first, which looks
+ /// exactly like a picker that refused to open.
+ bool _pickingFolder = false;
+ bool _newHarnessHidden = false;
bool _routeIsCurrent = true;
String? _linkDialogMachineId;
String? _nativeState;
@@ -1757,59 +1766,65 @@ class _SwarmScreenState extends State<SwarmScreen>
},
);
_newHarnessOverlay = OverlayEntry(
- builder: (context) => KeymapProvider(
- keymap: _keymap,
- child: ListenableBuilder(
- listenable: box,
- builder: (context, child) => LayoutBuilder(
- builder: (context, constraints) {
- final setupScale = terminalTextScaleOf(context).clamp(1.0, 1.25);
- return Stack(
- children: [
- Positioned.fill(
- child: BlockSemantics(
- child: GestureDetector(
- key: const ValueKey('new-harness-dismiss'),
- behavior: HitTestBehavior.opaque,
- onTap: () {
- if (box.requestDismiss()) {
- final target = box.swarmId ?? app.activeSwarmId;
- _closeNewHarness();
- app.cancelSwarmDraft(target);
- }
- },
- // The popup is the terminal's own colour, so the
- // screen behind it is dimmed rather than competed
- // with — that, and the light shadow, are what carry
- // the separation a different fill used to.
- child: ColoredBox(
- color: Colors.black.withValues(alpha: .94),
+ // Hidden, not removed, while a dialog ROUTE is up — see
+ // [_withNewHarnessHidden]. The form keeps its State and its draft.
+ builder: (context) => Offstage(
+ offstage: _newHarnessHidden,
+ child: KeymapProvider(
+ keymap: _keymap,
+ child: ListenableBuilder(
+ listenable: box,
+ builder: (context, child) => LayoutBuilder(
+ builder: (context, constraints) {
+ final setupScale = terminalTextScaleOf(context)
+ .clamp(1.0, 1.25);
+ return Stack(
+ children: [
+ Positioned.fill(
+ child: BlockSemantics(
+ child: GestureDetector(
+ key: const ValueKey('new-harness-dismiss'),
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ if (box.requestDismiss()) {
+ final target = box.swarmId ?? app.activeSwarmId;
+ _closeNewHarness();
+ app.cancelSwarmDraft(target);
+ }
+ },
+ // The popup is the terminal's own colour, so the
+ // screen behind it is dimmed rather than competed
+ // with — that, and the light shadow, are what carry
+ // the separation a different fill used to.
+ child: ColoredBox(
+ color: Colors.black.withValues(alpha: .94),
+ ),
),
),
),
- ),
- Positioned.fill(
- top: _native ? 0 : _tabBarHeight,
- child: Align(
- alignment: const Alignment(0, -0.12),
- // Sized for the setup fields rather than the session
- // catalog, with some extra room for larger terminal text.
- child: SizedBox(
- width: math.min(
- 960 * setupScale,
- constraints.maxWidth - 48,
- ),
- height: math.min(
- 480 * setupScale,
- constraints.maxHeight - 88,
+ Positioned.fill(
+ top: _native ? 0 : _tabBarHeight,
+ child: Align(
+ alignment: const Alignment(0, -0.12),
+ // Sized for the setup fields rather than the session
+ // catalog, with some extra room for larger terminal text.
+ child: SizedBox(
+ width: math.min(
+ 960 * setupScale,
+ constraints.maxWidth - 48,
+ ),
+ height: math.min(
+ 480 * setupScale,
+ constraints.maxHeight - 88,
+ ),
+ child: content,
),
- child: content,
),
),
- ),
- ],
- );
- },
+ ],
+ );
+ },
+ ),
),
),
),
@@ -1838,22 +1853,61 @@ class _SwarmScreenState extends State<SwarmScreen>
FocusManager.instance.applyFocusChangesIfNeeded();
}
+ /// Runs [show] — a dialog ROUTE — with the new-harness box out of the way.
+ ///
+ /// The box is an [OverlayEntry] this screen inserts itself, so it sits above
+ /// every route pushed AFTERWARDS: the navigator inserts a new route directly
+ /// above the previous ROUTE's entries, which is still below ours. The remote
+ /// folder browser is such a route, and it opened underneath the box — nothing
+ /// appeared until the box was dismissed, and then the chooser was sitting
+ /// there. The chooser on this computer is an AppKit sheet in its own window
+ /// and needs none of this.
+ ///
+ /// Hidden rather than removed: re-inserting the entry would build a second
+ /// [NewHarnessForm] and lose the row, the query and the focus the person left
+ /// behind.
+ Future<T?> _withNewHarnessHidden<T>(Future<T?> Function() show) async {
+ final entry = _newHarnessOverlay;
+ if (entry == null) return show();
+ _newHarnessHidden = true;
+ entry.markNeedsBuild();
+ try {
+ return await show();
+ } finally {
+ _newHarnessHidden = false;
+ // The box may have been closed under the dialog; the flag is reset
+ // either way so the next one does not open invisible.
+ _newHarnessOverlay?.markNeedsBuild();
+ }
+ }
+
/// The Browse… row: the system's folder chooser on this computer, the
/// folder browser on another. The box stays open behind it and takes the
/// answer when it comes back.
Future<void> _browseForNewHarness(NewHarnessController box) async {
+ if (_pickingFolder) return;
final previousFocus = FocusManager.instance.primaryFocus;
final machineId = box.machineId;
final machine = app.stateOf(machineId);
- final path = machine?.isLocalMachine == true
- ? await getDirectoryPath(initialDirectory: box.project.folder)
- : await showRemoteFolderPicker(
- context,
- notifier: app,
- machineId: machineId,
- initialPath: box.project.folder,
- terminal: true,
- );
+ _pickingFolder = true;
+ final String? path;
+ try {
+ path = machine?.isLocalMachine == true
+ ? await whileNativePicker(
+ () => getDirectoryPath(initialDirectory: box.project.folder),
+ )
+ : await _withNewHarnessHidden(
+ () => showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: machineId,
+ initialPath: box.project.folder,
+ terminal: true,
+ ),
+ );
+ } finally {
+ _pickingFolder = false;
+ }
if (mounted && identical(_newHarness, box) && box.machineId == machineId) {
if (path != null) box.setFolder(path);
if (previousFocus?.context?.mounted == true &&
@@ -1864,23 +1918,33 @@ class _SwarmScreenState extends State<SwarmScreen>
}
Future<void> _linkProfileForNewHarness(NewHarnessController box) async {
- if (box.locked || !box.supportsProfiles) return;
+ if (box.locked || !box.supportsProfiles || _pickingFolder) return;
final previousFocus = FocusManager.instance.primaryFocus;
final machineId = box.machineId;
final engine = box.engine;
final initialPath = box.draft.profile?.path;
final machine = app.stateOf(machineId);
- final path = machine?.isLocalMachine == true
- ? await getDirectoryPath(
- initialDirectory: initialPath,
- confirmButtonText: 'Link profile',
- )
- : await showRemoteFolderPicker(
- context,
- notifier: app,
- machineId: machineId,
- initialPath: initialPath,
- );
+ _pickingFolder = true;
+ final String? path;
+ try {
+ path = machine?.isLocalMachine == true
+ ? await whileNativePicker(
+ () => getDirectoryPath(
+ initialDirectory: initialPath,
+ confirmButtonText: 'Link profile',
+ ),
+ )
+ : await _withNewHarnessHidden(
+ () => showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: machineId,
+ initialPath: initialPath,
+ ),
+ );
+ } finally {
+ _pickingFolder = false;
+ }
if (!mounted ||
!identical(_newHarness, box) ||
box.machineId != machineId ||
@@ -2876,7 +2940,11 @@ class _SwarmScreenState extends State<SwarmScreen>
report: (voiceId, state, agentId) =>
app.reportVoiceRoute(request.machineId, voiceId, state, agentId),
);
- if (_spokenPaletteOpen || _dialogOpen || !mounted) {
+ // A native chooser is modal to this window, so the palette would open
+ // behind it and take neither a key nor a click. Reporting the task back as
+ // cancelled is the honest answer — the dial drops its sending overlay
+ // instead of leaving the words in a box nobody can reach.
+ if (_spokenPaletteOpen || _dialogOpen || nativePickerOpen || !mounted) {
spoken.cancelled();
return;
}
diff --git a/desktop/lib/widgets/clone_repository_dialog.dart b/desktop/lib/widgets/clone_repository_dialog.dart
index c28657ba0..9c3fb2ffc 100644
--- a/desktop/lib/widgets/clone_repository_dialog.dart
+++ b/desktop/lib/widgets/clone_repository_dialog.dart
@@ -2,6 +2,7 @@ import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
+import '../core/desktop_window.dart';
import '../core/repository_clone.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
@@ -49,13 +50,15 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
if (_busy || _picking || _closing) return;
setState(() => _picking = true);
try {
- final folder = await getDirectoryPath(
- initialDirectory:
- _parent ??
- (widget.initialFolder == null
- ? null
- : p.dirname(widget.initialFolder!)),
- confirmButtonText: 'Choose destination',
+ final folder = await whileNativePicker(
+ () => getDirectoryPath(
+ initialDirectory:
+ _parent ??
+ (widget.initialFolder == null
+ ? null
+ : p.dirname(widget.initialFolder!)),
+ confirmButtonText: 'Choose destination',
+ ),
);
if (mounted && folder != null) {
setState(() {
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index cf378d1b9..44b108a46 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -8,6 +8,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../analytics/analytics.dart';
import '../state/pane_arrangement.dart';
+import '../core/desktop_window.dart';
import '../core/engine_availability.dart';
import '../core/codex_profiles.dart';
import '../core/dsh_catalog.dart';
@@ -540,7 +541,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
final revision = _machineRevision;
try {
final picked = _machineIsThisComputer
- ? await getDirectoryPath(initialDirectory: _folder)
+ ? await whileNativePicker(
+ () => getDirectoryPath(initialDirectory: _folder),
+ )
: await showRemoteFolderPicker(
context,
notifier: widget.notifier,
diff --git a/desktop/lib/widgets/remote_folder_picker.dart b/desktop/lib/widgets/remote_folder_picker.dart
index c326764fe..adc60d5b8 100644
--- a/desktop/lib/widgets/remote_folder_picker.dart
+++ b/desktop/lib/widgets/remote_folder_picker.dart
@@ -343,6 +343,12 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
child: AlertDialog(
title: const Text('Choose a folder'),
scrollable: true,
+ // Material's 20 here left MORE air between the title and the
+ // machine line below it (16) than between that line and the next
+ // section (12), so the one line that belongs to the title floated
+ // between the two blocks instead of sitting under it. 10 groups it
+ // with its title and the section below starts a clear 16 later.
+ contentPadding: const EdgeInsets.fromLTRB(24, 10, 24, 24),
content: SizedBox(
width: 520,
child: Column(
@@ -353,11 +359,14 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {
'On ${machine ?? 'the remote machine'}',
style: Theme.of(context).textTheme.bodySmall,
),
- const SizedBox(height: 12),
+ const SizedBox(height: 16),
if (widget.terminal)
Text('Folder path', style: terminalTextStyle())
else
const FieldLabel('Folder path'),
+ // The label was flush against its field, while the Folders
+ // header gets ~8 from the icon buttons beside it centring.
+ const SizedBox(height: 6),
Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dart
index a23af8e3a..dae8fafd6 100644
--- a/desktop/lib/widgets/swarm_dialogs.dart
+++ b/desktop/lib/widgets/swarm_dialogs.dart
@@ -4,6 +4,7 @@ import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:harness/shared/theme/app_type.dart';
+import '../core/desktop_window.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
import '../state/app_state.dart';
@@ -79,7 +80,9 @@ class _ProjectDialogState extends State<_ProjectDialog> {
});
try {
final folder = widget.notifier.stateOf(id)?.isLocalMachine == true
- ? await getDirectoryPath(initialDirectory: path)
+ ? await whileNativePicker(
+ () => getDirectoryPath(initialDirectory: path),
+ )
: await showRemoteFolderPicker(
context,
notifier: widget.notifier,
diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dart
index 2f4afe141..5b33cf13d 100644
--- a/desktop/test/box_flows_test.dart
+++ b/desktop/test/box_flows_test.dart
@@ -15,11 +15,15 @@ import 'swarm_state_test.dart' show createApp;
class _CancelFolder extends FileSelectorPlatform {
final answer = Completer<String?>();
+ int opened = 0;
@override
Future<String?> getDirectoryPath({
String? initialDirectory,
String? confirmButtonText,
- }) => answer.future;
+ }) {
+ opened++;
+ return answer.future;
+ }
}
void main() {
@@ -100,6 +104,112 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ // The box keeps its keyboard focus while the sheet is up, so Enter on the
+ // Browse… row arrives again. AppKit answers a second `beginSheetModal` by
+ // queueing it behind the first: the screen does not change, and the person
+ // is left pressing a key that looks like it does nothing.
+ testWidgets('a second Browse… while the chooser is up opens nothing', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ final previous = FileSelectorPlatform.instance;
+ final picker = _CancelFolder();
+ FileSelectorPlatform.instance = picker;
+ addTearDown(() => FileSelectorPlatform.instance = previous);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await openLaunchRow(tester, 'project');
+ final controller = box(tester);
+ controller.move(
+ controller.options.indexWhere(
+ (row) => row.id == NewHarnessController.existingProjectId,
+ ) -
+ controller.cursor,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ controller.move(
+ controller.options.indexWhere(
+ (row) => row.id == NewHarnessController.browseId,
+ ) -
+ controller.cursor,
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(picker.opened, 1);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(picker.opened, 1, reason: 'one chooser, however often it is asked');
+ picker.answer.complete('/work/picked');
+ await tester.pumpAndSettle();
+ expect(controller.project.folder, '/work/picked');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ // A remote machine has no AppKit sheet to fall back on: the chooser is a
+ // DIALOG ROUTE, and the box is an overlay entry the screen inserted itself,
+ // so the route lands underneath it. It used to look like Browse… did nothing
+ // until the box was dismissed, and the chooser was waiting behind it.
+ testWidgets('the remote folder browser opens in front of the box', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = false;
+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await openLaunchRow(tester, 'project');
+ final controller = box(tester);
+ controller.move(
+ controller.options.indexWhere(
+ (row) => row.id == NewHarnessController.existingProjectId,
+ ) -
+ controller.cursor,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ controller.move(
+ controller.options.indexWhere(
+ (row) => row.id == NewHarnessController.browseId,
+ ) -
+ controller.cursor,
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Choose a folder'), findsOneWidget);
+ expect(
+ find.byType(NewHarnessForm),
+ findsNothing,
+ reason: 'the box steps aside while the chooser is up',
+ );
+ expect(
+ find.byType(NewHarnessForm, skipOffstage: false),
+ findsOneWidget,
+ reason: 'hidden, not rebuilt: the draft and the focused row survive',
+ );
+ await tester.tap(find.text('Cancel'));
+ await tester.pump();
+ await tester.pump();
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(identical(box(tester), controller), isTrue);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
testWidgets('different source panes retain separate setup drafts', (
tester,
) async {
diff --git a/desktop/test/native_picker_guard_test.dart b/desktop/test/native_picker_guard_test.dart
new file mode 100644
index 000000000..54e737471
--- /dev/null
+++ b/desktop/test/native_picker_guard_test.dart
@@ -0,0 +1,57 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/desktop_window.dart';
+
+/// A native folder chooser is a SHEET on this window, and the app has to know
+/// one is up: [revealWindow] must not re-order the window under it, and the
+/// dial's task palette must not open behind it.
+void main() {
+ test('starts closed', () {
+ expect(nativePickerOpen, isFalse);
+ });
+
+ test('held for as long as the chooser is up, and no longer', () async {
+ final answer = Completer<String?>();
+ final picked = whileNativePicker(() => answer.future);
+ expect(nativePickerOpen, isTrue);
+ answer.complete('/tmp/somewhere');
+ expect(await picked, '/tmp/somewhere');
+ expect(nativePickerOpen, isFalse);
+ });
+
+ test('released when the chooser throws', () async {
+ await expectLater(
+ whileNativePicker<String?>(() async => throw StateError('no window')),
+ throwsStateError,
+ );
+ expect(nativePickerOpen, isFalse);
+ });
+
+ // The dialog holding a chooser can be disposed while it is open — its own
+ // `mounted` guard then skips the flag reset. The count is not allowed to
+ // leak that way, and two panes may each be browsing at once.
+ test('counts, so one chooser closing does not clear another', () async {
+ final first = Completer<String?>();
+ final second = Completer<String?>();
+ final a = whileNativePicker(() => first.future);
+ final b = whileNativePicker(() => second.future);
+ expect(nativePickerOpen, isTrue);
+ first.complete(null);
+ await a;
+ expect(nativePickerOpen, isTrue, reason: 'the second one is still up');
+ second.complete(null);
+ await b;
+ expect(nativePickerOpen, isFalse);
+ });
+
+ test('revealWindow is a no-op while a chooser is up', () async {
+ final answer = Completer<String?>();
+ final picked = whileNativePicker(() => answer.future);
+ // On a headless test host `hasManagedWindow` is true on macOS/Linux and the
+ // plugin throws; the point is that this returns without raising anything.
+ await revealWindow();
+ answer.complete(null);
+ await picked;
+ });
+}