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(mobile): wait for the Git read before starting a harness

tonyfb051726cb53
diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dart
index e24e9db9d..865f9ee26 100644
--- a/mobile/lib/phone/new_agent_page.dart
+++ b/mobile/lib/phone/new_agent_page.dart
@@ -126,6 +126,10 @@ class _NewAgentPageState extends State<NewAgentPage> {
String? _gitFolder;
bool _gitLoading = false;
+ /// The read [_gitLoading] is about, held so a Start pressed during it can wait for the same
+ /// answer — see [_gitSettled].
+ Future<void>? _gitRead;
+
/// Set when the machine could not answer at all, as opposed to answering
/// "not a repository".
///
@@ -297,7 +301,9 @@ class _NewAgentPageState extends State<NewAgentPage> {
branchName: _branchName,
placeholder: _placeholder,
git: _git,
- gitFolder: _gitFolder,
+ // Only an answer is kept. A read still out, or one that failed, comes back as no read at
+ // all, so Start asks again instead of taking "not a repository" from it — see [_gitSettled].
+ gitFolder: _gitLoading || _gitFailed ? null : _gitFolder,
codexProfile: _codexProfile,
model: _model,
task: _task.text,
@@ -365,8 +371,12 @@ class _NewAgentPageState extends State<NewAgentPage> {
/// Silent about failure. A folder that is not a repository and a machine that
/// could not answer both come back with nothing to offer, and neither is
/// something to interrupt a half-filled form about — the section simply does
- /// not appear, and everything else on the page still works.
- Future<void> _loadGit(String folder) async {
+ /// not appear, and everything else on the page still works. Start is where
+ /// it matters, and Start waits for this answer: see [_gitSettled].
+ Future<void> _loadGit(String folder) => _gitRead = _readGit(folder);
+
+ /// [_loadGit]'s read, which it keeps in [_gitRead].
+ Future<void> _readGit(String folder) async {
final machineId = _machineId;
setState(() {
_gitLoading = true;
@@ -615,9 +625,62 @@ class _NewAgentPageState extends State<NewAgentPage> {
unawaited(_loadGit(chosen));
}
+ /// Waits for the Git answer about the folder Start is about to use, and says whether Start may go
+ /// on. False has already put the form back, with the reason on it.
+ ///
+ /// ⚠️ **Start does not go without the answer**, as the desktop's `create` does not
+ /// (`state/new_harness.dart`). The request is built from it: with no answer there is no
+ /// repository on hand, [_create] takes the plain path, and the harness starts on a bare `cwd` with
+ /// no worktree and no branch. The form reads Git after its first frame, so a Start pressed as it
+ /// opened used to land in exactly that gap.
+ ///
+ /// A machine that could not answer is asked again, once per Start, as the desktop asks; failing
+ /// again refuses rather than starting in the folder anyway, because whether the folder is a
+ /// repository is exactly what is not known. A folder that is simply NOT one was answered, and
+ /// starts there as it always has.
+ Future<bool> _gitSettled() async {
+ final folder = _folder;
+ if (folder == null || _project != null) return true;
+ // Never read for this folder — a draft left while its read was out — counts as unread.
+ if (!_gitLoading && (_gitFailed || _gitFolder != folder)) {
+ unawaited(_loadGit(folder));
+ }
+ // The newest read, not the first: one about a folder the form has since left ends without an
+ // answer (see [_gitFolder]), and the folder only changes by starting another.
+ Future<void>? waited;
+ while (_gitLoading &&
+ _folder != null &&
+ _project == null &&
+ !identical(waited, _gitRead)) {
+ waited = _gitRead;
+ try {
+ await waited;
+ } catch (_) {
+ // A read that threw has no answer either; it is refused below like one that failed.
+ }
+ if (!mounted) return false;
+ }
+ if (_folder == null && _project == null) {
+ setState(() => _creating = false);
+ return false;
+ }
+ if (_project == null && (_gitLoading || _gitFailed)) {
+ final machine = _machine?.machine.displayName ?? 'the computer';
+ setState(() {
+ _creating = false;
+ // The desktop's words, so the two say the same thing about the same machine.
+ _error =
+ 'Could not check Git on $machine. Check the connection and Harness '
+ 'CLI, then retry.';
+ });
+ return false;
+ }
+ return true;
+ }
+
Future<void> _create() async {
- final folder = _folder, engine = _engine, project = _project;
- if ((folder == null && project == null) || engine == null || _creating) {
+ final engine = _engine;
+ if ((_folder == null && _project == null) || engine == null || _creating) {
return;
}
// A request still waiting on its answer is asked about, never made again — see [_creation].
@@ -635,6 +698,10 @@ class _NewAgentPageState extends State<NewAgentPage> {
);
return;
}
+ if (!await _gitSettled()) return;
+ // Taken after the wait, not before it: the answer can move the form to the folder's own
+ // repository (a worktree's main checkout), and Start goes where the form says now.
+ final folder = _folder, project = _project;
// Held so the id of what it starts comes back here — see
// [AgentCreationAttempt.agentId] — and kept as [_creation] for as long as
// its answer is outstanding.
diff --git a/mobile/test/phone_edge/new_git_wait_test.dart b/mobile/test/phone_edge/new_git_wait_test.dart
new file mode 100644
index 000000000..f1709d287
--- /dev/null
+++ b/mobile/test/phone_edge/new_git_wait_test.dart
@@ -0,0 +1,272 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/new_agent_draft.dart';
+import 'package:harness_mobile/phone/new_agent_page.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'edge_fixture.dart';
+
+/// A machine that holds every Git read until the test answers it — a laptop slow to say what its
+/// folder is, which is what a Start pressed as New opens runs into.
+class _SlowGitConn extends EdgeConn {
+ _SlowGitConn() : super(const {}, startsAgents);
+
+ /// Every Git read asked for, in order: the folder, and the answer the test gives it.
+ final reads = <({String path, Completer<Map<String, dynamic>> answer})>[];
+
+ /// Every `agent_create` sent.
+ List<Map<String, dynamic>> get created =>
+ payloads['agent_create'] ?? const [];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'git_project_info') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ requests.add(type);
+ (payloads[type] ??= []).add(payload);
+ final answer = Completer<Map<String, dynamic>>();
+ reads.add((path: payload['path'] as String, answer: answer));
+ return answer.future;
+ }
+}
+
+/// A checkout on `main`, with `origin/main` to start new work from.
+Map<String, dynamic> _repository(String root) => {
+ 'isGit': true,
+ 'branch': 'main',
+ 'root': root,
+ 'defaultRef': 'refs/remotes/origin/main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/remotes/origin/main', 'name': 'origin/main', 'remote': true},
+ ],
+};
+
+/// What the machine says about a folder that is not a repository: an answer, not a failure.
+const _notARepository = {'isGit': false, 'branches': <Object>[]};
+
+const _refusal =
+ '✗ Could not check Git on studio. Check the connection and Harness CLI, '
+ 'then retry.';
+
+/// Start pressed while the form is still reading its folder's Git: it waits for the answer and
+/// starts from it, the desktop's `create`. Before, it went without — a bare `cwd`, no worktree.
+void main() {
+ setUp(() => newAgentDraft = null);
+ tearDown(() => newAgentDraft = null);
+
+ /// New, pushed over a page the way Focus pushes it, with its default folder's Git read still
+ /// out. `/code/web` is the default: the folder of the machine's latest harness.
+ Future<({AppNotifier app, _SlowGitConn conn})> openNew(
+ WidgetTester tester, {
+ String? folder,
+ List<Agent>? agents,
+ }) async {
+ setPhone(tester, largePhone);
+ final conn = _SlowGitConn();
+ final app = edgeApp(conn: conn, agents: agents ?? [edgeAgent('a')]);
+ await tester.pumpWidget(
+ phoneApp(
+ Builder(
+ builder: (context) => TextButton(
+ onPressed: () => Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (_) => NewAgentPage(
+ notifier: app,
+ machineId: 'm',
+ folder: folder,
+ voice: edgeVoice().voice,
+ ),
+ ),
+ ),
+ child: const Text('focus'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('focus'));
+ await frames(tester);
+ return (app: app, conn: conn);
+ }
+
+ Future<void> close(WidgetTester tester, AppNotifier app) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 3));
+ app.dispose();
+ await tester.pump(const Duration(seconds: 30));
+ }
+
+ testWidgets('Start during the read waits for it and starts in a worktree, '
+ 'once', (tester) async {
+ final (:app, :conn) = await openNew(tester);
+ expect(conn.reads.single.path, '/code/web');
+ expect(conn.reads.single.answer.isCompleted, isFalse);
+
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ // Waiting, in the form's own busy state: nothing sent yet, and no second Start to press.
+ expect(find.text('Starting…'), findsOneWidget);
+ await tester.tap(find.text('Starting…'), warnIfMissed: false);
+ await frames(tester);
+ expect(conn.created, isEmpty);
+ expect(conn.reads, hasLength(1));
+
+ conn.reads.single.answer.complete(_repository('/code/web'));
+ await frames(tester, count: 20);
+
+ final payload = conn.created.single;
+ expect(payload['projectSource'], 'worktree');
+ expect(payload['gitSource'], '/code/web');
+ expect(payload['branchRef'], 'refs/heads/main');
+ expect(payload.containsKey('cwd'), isFalse);
+ await close(tester, app);
+ });
+
+ testWidgets('a read the computer could not answer refuses Start; the next '
+ 'Start asks again', (tester) async {
+ final (:app, :conn) = await openNew(tester);
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ conn.reads.single.answer.complete({'error': 'UNAVAILABLE'});
+ await frames(tester, count: 20);
+
+ expect(find.text(_refusal), findsOneWidget);
+ expect(conn.created, isEmpty);
+ expect(find.text('Start'), findsOneWidget);
+
+ // Try again: the machine is asked again rather than the failure being taken as an answer.
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ expect(conn.reads, hasLength(2));
+ expect(conn.created, isEmpty);
+ conn.reads.last.answer.complete(_repository('/code/web'));
+ await frames(tester, count: 20);
+
+ expect(find.text(_refusal), findsNothing);
+ final payload = conn.created.single;
+ expect(payload['projectSource'], 'worktree');
+ expect(payload.containsKey('cwd'), isFalse);
+ await close(tester, app);
+ });
+
+ testWidgets('a folder that is not a repository still starts in it, plainly', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(tester);
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ expect(conn.created, isEmpty);
+ conn.reads.single.answer.complete(_notARepository);
+ await frames(tester, count: 20);
+
+ expect(find.text(_refusal), findsNothing);
+ final payload = conn.created.single;
+ expect(payload['cwd'], '/code/web');
+ expect(payload.containsKey('projectSource'), isFalse);
+ await close(tester, app);
+ });
+
+ testWidgets('an answer that moves the folder to its repository starts '
+ 'there', (tester) async {
+ const worktree = '/home/u/harnesses/worktrees/web/silent-beacon';
+ const main = '/home/u/code/web';
+ final (:app, :conn) = await openNew(tester, folder: worktree);
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ expect(conn.reads.single.path, worktree);
+ conn.reads.single.answer.complete({
+ ..._repository(worktree),
+ 'branch': 'silent-beacon',
+ 'mainFolder': main,
+ 'mainBranch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main', 'worktree': main},
+ {
+ 'ref': 'refs/heads/silent-beacon',
+ 'name': 'silent-beacon',
+ 'worktree': worktree,
+ 'harness': true,
+ },
+ {
+ 'ref': 'refs/remotes/origin/main',
+ 'name': 'origin/main',
+ 'remote': true,
+ },
+ ],
+ });
+ await frames(tester, count: 20);
+
+ final payload = conn.created.single;
+ expect(payload['gitSource'], main);
+ expect(payload['projectSource'], 'worktree');
+ expect(payload['branchRef'], 'refs/heads/main');
+ await close(tester, app);
+ });
+
+ testWidgets('another folder chosen while the first read is out: Start '
+ 'waits for that folder, and the late answer is not used', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [
+ edgeAgent('a'),
+ edgeAgent('b', project: 'api', minutesAgo: 10),
+ ],
+ );
+ expect(conn.reads.single.path, '/code/web');
+ await tapInView(tester, find.text('project'));
+ await frames(tester);
+ await tapInView(tester, find.text('api', findRichText: true).last);
+ await frames(tester);
+ expect(conn.reads.map((read) => read.path), ['/code/web', '/code/api']);
+
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ // The folder the form has left answers late, as a repository: not the answer Start waits for.
+ conn.reads.first.answer.complete(_repository('/code/web'));
+ await frames(tester);
+ expect(conn.created, isEmpty);
+
+ conn.reads.last.answer.complete(_notARepository);
+ await frames(tester, count: 20);
+ final payload = conn.created.single;
+ expect(payload['cwd'], '/code/api');
+ expect(payload.containsKey('projectSource'), isFalse);
+ expect(payload.containsKey('gitSource'), isFalse);
+ await close(tester, app);
+ });
+
+ testWidgets('a form left before its read answered asks again on Start', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(tester);
+ await tester.binding.handlePopRoute();
+ await frames(tester, count: 6);
+ expect(newAgentDraft?.folder, '/code/web');
+ expect(newAgentDraft?.gitFolder, isNull);
+ // The answer arrives with nobody left to take it.
+ conn.reads.single.answer.complete(_repository('/code/web'));
+ await frames(tester);
+
+ await tester.tap(find.text('focus'));
+ await frames(tester);
+ await tapInView(tester, find.text('Start'));
+ await frames(tester);
+ expect(conn.reads, hasLength(2));
+ expect(conn.created, isEmpty);
+ conn.reads.last.answer.complete(_repository('/code/web'));
+ await frames(tester, count: 20);
+
+ final payload = conn.created.single;
+ expect(payload['projectSource'], 'worktree');
+ expect(payload.containsKey('cwd'), isFalse);
+ await close(tester, app);
+ });
+}