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): refuse a branch switch under a working harness

tony0187b95bd09a
diff --git a/mobile/lib/core/git_project.dart b/mobile/lib/core/git_project.dart
index 60ce9fcfb..24094e22c 100644
--- a/mobile/lib/core/git_project.dart
+++ b/mobile/lib/core/git_project.dart
@@ -219,6 +219,47 @@ String? newBranchHere(GitProjectInfo info, String? name) {
: typed;
}
+/// With Worktree off, whether Start moves the folder ITSELF onto another branch — the one choice
+/// that reaches every harness already working in its checkout.
+///
+/// ⚠️ **The desktop's condition (`state/new_harness.dart`, `create`), kept in step with it.** With
+/// Worktree off the machine (`cli/src/lib/gitProject.ts`, `prepareGitProject`) makes a typed new
+/// branch where the folder is and moves the folder onto it, and checks any other local branch out
+/// in the folder with `git switch` once nothing there is uncommitted. Three choices move nothing,
+/// so they are not counted: the branch the folder is already on; a branch with a worktree of its
+/// own, which the machine opens instead, since Git will not check a branch out twice; and a remote
+/// branch, which the machine refuses with Worktree off, in its own words ("Choose a local branch,
+/// or turn Worktree on."). The desktop refuses that last one before its own check, so the two never
+/// say different things about it.
+bool switchesFolderBranch(
+ GitProjectInfo info, {
+ required bool worktree,
+ required String? branchRef,
+ required String? branchName,
+}) {
+ if (worktree) return false;
+ if (newBranchHere(info, branchName) != null) return true;
+ final ref = branchRef ?? defaultBranchRef(info, worktree: false);
+ return ref != null &&
+ ref.startsWith('refs/heads/') &&
+ ref != currentBranchRef(info) &&
+ // The desktop's `_worktreeOf`: checked out somewhere other than this folder.
+ !info.branches.any(
+ (branch) =>
+ branch.ref == ref &&
+ branch.worktree != null &&
+ branch.name != info.branch,
+ );
+}
+
+/// Whether [path] is the checkout at [root] or a folder inside it — what moves with the checkout
+/// when its branch is switched.
+///
+/// Both are the machine's paths, so they are compared by POSIX rules whatever this device's own
+/// are; `/code/web` holds `/code/web/api` and not `/code/website`.
+bool withinCheckout(String root, String path) =>
+ p.posix.equals(path, root) || p.posix.isWithin(root, path);
+
/// The preparation a Git project's folder gets at Start.
///
/// ⚠️ **Ported from the desktop's `state/new_harness.dart` line for line, and
diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dart
index cd76a9ae6..15f3d9ad1 100644
--- a/mobile/lib/phone/new_agent_page.dart
+++ b/mobile/lib/phone/new_agent_page.dart
@@ -424,6 +424,17 @@ class _NewAgentPageState extends State<NewAgentPage> {
// machine names the main checkout, and new work starts from the branch that is on. One the
// person browsed to stays itself, mainFolder and all ([_inWorktree]).
if (info.mainFolder case final main? when !exact) {
+ // The main checkout itself, which is where its branch is checked out: [main] when the
+ // worktree was opened at its top, the checkout above it when opened on a subfolder. That
+ // whole checkout moves if Start switches its branch, so a harness anywhere in it must count
+ // — see [_branchSwitchRefusal]. [main] when the checkout is on no branch to find it by.
+ final mainBranch = info.mainBranch;
+ final checkout =
+ info.branches
+ .where((branch) => !branch.remote && branch.name == mainBranch)
+ .firstOrNull
+ ?.worktree ??
+ main;
_folder = main;
_gitFolder = main;
info = GitProjectInfo(
@@ -431,7 +442,7 @@ class _NewAgentPageState extends State<NewAgentPage> {
branch: info.mainBranch,
branches: info.branches,
defaultRef: info.defaultRef,
- root: main,
+ root: checkout,
);
}
setState(() {
@@ -709,6 +720,53 @@ class _NewAgentPageState extends State<NewAgentPage> {
return true;
}
+ /// Why Start may not move [folder] onto another branch, or null when nothing stops it. [info] is
+ /// [folder]'s repository, as the machine answered for it.
+ ///
+ /// ⚠️ **With Worktree off the machine switches the folder's own branch, and nothing there asks
+ /// what else is working in it.** `cli/src/lib/gitProject.ts` runs `git switch` in a folder with
+ /// nothing uncommitted, or makes a typed new branch there — and a harness already at work in that
+ /// checkout had its files change branch under it, then went on editing and committing on a branch
+ /// nobody chose for it. The easy way in was the branch row's default: Worktree starts on with the
+ /// default branch picked, turning it off kept that pick, and Start moved a folder on another
+ /// branch to `main`. The desktop refuses before sending (`state/new_harness.dart`, `create`); this
+ /// is its check, in its words. Like the Git-read refusal in [_gitSettled], it leaves the button
+ /// saying Start: nothing was sent, so there is nothing to try again.
+ ///
+ /// What counts, and why:
+ /// - Only a choice that moves the folder ([switchesFolderBranch]). The branch it is already on, a
+ /// branch with a worktree of its own (opened there instead) and Worktree on all start as before.
+ /// - Only harnesses on THIS machine. The same path on another computer is another folder.
+ /// - Every harness the machine lists, a stopped one included, as the desktop counts them:
+ /// resumed, it would carry on in a checkout that changed branch while it was away.
+ /// - A harness anywhere in the checkout ([GitProjectInfo.root]), a subfolder as much as the root,
+ /// because the switch moves every file in it. A machine that names no root leaves the folder
+ /// itself, as the desktop does.
+ /// - Where a harness works is read as the desktop reads it: where its machine last saw it working
+ /// ([Agent.displayProject]), which is where it was started until it is seen anywhere else.
+ ///
+ /// "Stay on" names the branch the folder is on now, since that is what keeping it there means; a
+ /// folder on no branch is called what the desktop's branch row calls it, Detached HEAD.
+ String? _branchSwitchRefusal(String folder, GitProjectInfo info) {
+ if (!switchesFolderBranch(
+ info,
+ worktree: _worktree,
+ branchRef: _branchRef,
+ branchName: _branchName,
+ )) {
+ return null;
+ }
+ final root = info.root ?? folder;
+ final busy = (_machine?.agents ?? const <Agent>[]).any((agent) {
+ final cwd = agent.displayProject?.cwd;
+ return cwd != null && withinCheckout(root, cwd);
+ });
+ if (!busy) return null;
+ return 'A harness is working in this folder, so its branch can’t be '
+ 'switched. Turn Worktree on, or stay on '
+ '${info.branch ?? 'Detached HEAD'}.';
+ }
+
Future<void> _create() async {
final engine = _engine;
if ((_folder == null && _project == null) || engine == null || _creating) {
@@ -733,6 +791,20 @@ class _NewAgentPageState extends State<NewAgentPage> {
// 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;
+ // Read after the wait for the same reason, and before the first task is looked at — the
+ // desktop's order. Only a folder sent with its repository can be switched; `New project` and
+ // `Git…` make a folder nothing is working in yet.
+ final switchRefusal =
+ project == null && folder != null && _repository != null
+ ? _branchSwitchRefusal(folder, _repository!)
+ : null;
+ if (switchRefusal != null) {
+ setState(() {
+ _creating = false;
+ _error = switchRefusal;
+ });
+ return;
+ }
// The first task as it is sent, read after the wait too: the field stays open through it. An
// engine that cannot take one is sent none.
final task = takesFirstTask(engine) ? _task.text.trim() : '';
diff --git a/mobile/test/core_units_test.dart b/mobile/test/core_units_test.dart
index d60bf6013..51fe3d9fd 100644
--- a/mobile/test/core_units_test.dart
+++ b/mobile/test/core_units_test.dart
@@ -206,6 +206,74 @@ void main() {
expect(newBranchHere(info, ' fresh '), 'fresh');
});
+ test('with Worktree off, which choices move the folder onto another '
+ 'branch', () {
+ final info = repo();
+ bool switches(
+ GitProjectInfo info, {
+ bool worktree = false,
+ String? ref,
+ String? name,
+ }) => switchesFolderBranch(
+ info,
+ worktree: worktree,
+ branchRef: ref,
+ branchName: name,
+ );
+
+ // Moved: another local branch with no worktree, or a new branch made here.
+ expect(switches(info, ref: 'refs/heads/feature'), isTrue);
+ expect(switches(info, name: 'fresh'), isTrue);
+ expect(
+ switches(info, ref: 'refs/heads/main', name: ' fresh '),
+ isTrue,
+ reason: 'a typed new name wins over the picked branch',
+ );
+ // A folder on no branch is moved by any local branch.
+ expect(switches(repo(branch: null), ref: 'refs/heads/main'), isTrue);
+
+ // Left where it is.
+ expect(switches(info), isFalse, reason: 'nothing picked: where it is');
+ expect(switches(info, ref: 'refs/heads/main'), isFalse);
+ expect(
+ switches(info, ref: 'refs/heads/main', name: 'feature'),
+ isFalse,
+ reason: 'a typed name an existing branch has is not a new one',
+ );
+ expect(
+ switches(info, ref: 'refs/heads/busy'),
+ isFalse,
+ reason: 'opened in its own worktree instead',
+ );
+ expect(
+ switches(info, ref: 'refs/remotes/origin/main'),
+ isFalse,
+ reason: 'the machine refuses a remote branch with Worktree off',
+ );
+ expect(switches(repo(branch: null)), isFalse);
+ expect(
+ switches(info, worktree: true, ref: 'refs/heads/feature'),
+ isFalse,
+ );
+ expect(switches(info, worktree: true, name: 'fresh'), isFalse);
+ });
+
+ test('a checkout holds itself and every folder inside it, nothing '
+ 'else', () {
+ expect(withinCheckout('/w/app', '/w/app'), isTrue);
+ expect(withinCheckout('/w/app', '/w/app/'), isTrue);
+ expect(withinCheckout('/w/app/', '/w/app'), isTrue);
+ expect(withinCheckout('/w/app', '/w/app/cli'), isTrue);
+ expect(withinCheckout('/w/app', '/w/app/cli/src/lib'), isTrue);
+ expect(withinCheckout('/w/app', '/w/app/cli/../desktop'), isTrue);
+
+ expect(withinCheckout('/w/app', '/w/application'), isFalse);
+ expect(withinCheckout('/w/app', '/w/app-2'), isFalse);
+ expect(withinCheckout('/w/app', '/w'), isFalse);
+ expect(withinCheckout('/w/app', '/w/other'), isFalse);
+ expect(withinCheckout('/w/app', '/w/app/../other'), isFalse);
+ });
+
test('a placeholder branch is two words none of the taken ones use', () {
final taken = <String>{};
final random = Random(1);
diff --git a/mobile/test/phone_edge/new_behavior_test.dart b/mobile/test/phone_edge/new_behavior_test.dart
index 9e4a41fd3..7e498713d 100644
--- a/mobile/test/phone_edge/new_behavior_test.dart
+++ b/mobile/test/phone_edge/new_behavior_test.dart
@@ -77,6 +77,7 @@ void main() {
String? folder,
List<Agent>? agents,
Map<String, Map<String, dynamic>> overrides = const {},
+ String? remembered,
}) async {
setPhone(tester, largePhone);
final conn = EdgeConn({...answers, ...overrides}, startsAgents);
@@ -84,6 +85,9 @@ void main() {
conn.capabilities = {...conn.capabilities, 'features': {}};
}
final app = edgeApp(conn: conn, agents: agents ?? [edgeAgent('a')]);
+ // The folder this phone last started in on `m`: the project row's default, ahead of the
+ // latest harness's folder.
+ if (remembered != null) await app.projectHistory.select('m', remembered);
app.stateOf('m')!
..projectFolderAvailable = makesProjects
..terminalCapabilityLoaded = true;
@@ -242,11 +246,21 @@ void main() {
),
);
+ /// The machine's harness, working in another folder than `/code/web` (the folder these tests
+ /// remember): Start may switch `/code/web`'s branch with Worktree off.
+ final elsewhere = [edgeAgent('a', project: 'api')];
+
for (final worktree in [false, true]) {
testWidgets(
'branch and worktree are independent; create with worktree $worktree',
(tester) async {
- final (:app, :conn) = await openNew(tester);
+ // Worktree off moves the folder to fix/login, so nothing may be working in it — a harness
+ // there is refused (`new_branch_guard_test.dart`). Worktree on leaves the folder alone.
+ final (:app, :conn) = await openNew(
+ tester,
+ remembered: worktree ? null : '/code/web',
+ agents: worktree ? null : elsewhere,
+ );
expect(find.text('branch'), findsNothing);
expect(find.text('worktree'), findsNothing);
await tapInView(tester, find.text('options'));
@@ -272,6 +286,7 @@ void main() {
await frames(tester, count: 20);
final payload = conn.payloads['agent_create']!.single;
expect(payload['projectSource'], worktree ? 'worktree' : 'branch');
+ expect(payload['gitSource'], '/code/web');
expect(payload['branchRef'], 'refs/heads/fix/login');
expect(payload.containsKey('cwd'), isFalse);
expect(payload.containsKey('gridModel'), isFalse);
@@ -281,7 +296,12 @@ void main() {
}
testWidgets('a new branch name works with Worktree off', (tester) async {
- final (:app, :conn) = await openNew(tester);
+ // The folder moves to the new branch, so nothing may be working in it.
+ final (:app, :conn) = await openNew(
+ tester,
+ remembered: '/code/web',
+ agents: elsewhere,
+ );
await tapInView(tester, find.text('options'));
await frames(tester);
await tapInView(tester, find.text('worktree'));
@@ -298,6 +318,7 @@ void main() {
await frames(tester, count: 20);
final payload = conn.payloads['agent_create']!.single;
expect(payload['projectSource'], 'branch');
+ expect(payload['gitSource'], '/code/web');
expect(payload['branchName'], 'fix-the-login');
await close(tester, app);
});
@@ -341,7 +362,12 @@ void main() {
testWidgets(
'model, branch and Worktree survive Cancel; subscription restores profile',
(tester) async {
- final (:app, :conn) = await openNew(tester);
+ // Worktree off moves the folder to fix/login, so nothing may be working in it.
+ final (:app, :conn) = await openNew(
+ tester,
+ remembered: '/code/web',
+ agents: elsewhere,
+ );
await choose(tester, 'agent', 'Codex');
await tapInView(tester, find.text('options'));
await frames(tester);
@@ -369,6 +395,8 @@ void main() {
final payload = conn.payloads['agent_create']!.single;
expect(payload['codexHome'], '/home/ada/.codex-work');
expect(payload.containsKey('gridModel'), isFalse);
+ expect(payload['projectSource'], 'branch');
+ expect(payload['gitSource'], '/code/web');
await close(tester, app);
},
);
diff --git a/mobile/test/phone_edge/new_branch_guard_test.dart b/mobile/test/phone_edge/new_branch_guard_test.dart
new file mode 100644
index 000000000..b83b49b9d
--- /dev/null
+++ b/mobile/test/phone_edge/new_branch_guard_test.dart
@@ -0,0 +1,482 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/agent_git_context.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/phone/tty_controls.dart' show TtyFormRow;
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'edge_fixture.dart';
+
+/// `/code/web` as its machine reads it: on `fix/login`, with `main` to start new work from — the
+/// branch row's default while Worktree is on — `feature` to switch to, and `docs`, which already
+/// has a worktree of its own.
+Map<String, dynamic> _repository({
+ String root = '/code/web',
+ String? branch = 'fix/login',
+}) => {
+ 'isGit': true,
+ 'branch': branch,
+ 'root': root,
+ 'defaultRef': 'refs/remotes/origin/main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main'},
+ {'ref': 'refs/heads/fix/login', 'name': 'fix/login'},
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ {
+ 'ref': 'refs/heads/docs',
+ 'name': 'docs',
+ 'worktree': '/home/u/harnesses/worktrees/web/docs',
+ },
+ {'ref': 'refs/remotes/origin/main', 'name': 'origin/main', 'remote': true},
+ ],
+};
+
+/// The desktop's words (`state/new_harness.dart`), naming the branch the folder stays on.
+String _refusal([String branch = 'fix/login']) =>
+ '✗ A harness is working in this folder, so its branch can’t be switched. '
+ 'Turn Worktree on, or stay on $branch.';
+
+/// A harness started in [cwd] — and, with [seenIn], one its machine has since seen working in
+/// [seenIn] instead.
+Agent _harness(String id, String cwd, {String? seenIn}) => Agent(
+ id: id,
+ name: id,
+ engine: 'claude',
+ sessionId: 'session-$id',
+ status: 'active',
+ project: AgentProject(name: cwd.split('/').last, cwd: cwd),
+ gitContext: seenIn == null
+ ? null
+ : AgentGitContext(
+ state: 'observed',
+ current: AgentProject(name: seenIn.split('/').last, cwd: seenIn),
+ ),
+ updatedAt: DateTime.now().subtract(const Duration(minutes: 5)),
+ terminalAvailable: true,
+);
+
+/// With Worktree off, Start switches the folder's own branch: the machine runs `git switch` there
+/// (`cli/src/lib/gitProject.ts`) and does not look at what else is working in it. A harness already
+/// at work in that checkout had its files change branch under it. New refuses before sending
+/// anything, as the desktop does — and every choice that moves nothing still starts as before.
+void main() {
+ setUp(() => newAgentDraft = null);
+ tearDown(() => newAgentDraft = null);
+
+ /// New for [folder] on `m`, pushed over a page the way Focus pushes it, with [agents] running on
+ /// `m` — and [elsewhere] on a second computer, `mini`.
+ Future<({AppNotifier app, EdgeConn conn})> openNew(
+ WidgetTester tester, {
+ String folder = '/code/web',
+ required List<Agent> agents,
+ List<Agent> elsewhere = const [],
+ Map<String, dynamic>? repository,
+ }) async {
+ setPhone(tester, largePhone);
+ final conn = EdgeConn({
+ 'git_project_info': repository ?? _repository(),
+ }, startsAgents);
+ final app = edgeApp(conn: conn, agents: agents);
+ app.stateOf('m')!
+ ..projectFolderAvailable = true
+ ..terminalCapabilityLoaded = true;
+ if (elsewhere.isNotEmpty) {
+ const other = Machine(
+ machineId: 'mini',
+ authMode: MachineAuthMode.remote,
+ name: 'mini',
+ );
+ app.machines = [...app.machines, other];
+ app.machineStates['mini'] = MachineState(other)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = elsewhere;
+ }
+ 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));
+ }
+
+ TtyFormRow formRow(WidgetTester tester, String label) =>
+ tester.widget<TtyFormRow>(
+ find.byWidgetPredicate(
+ (widget) => widget is TtyFormRow && widget.label == label,
+ ),
+ );
+
+ Future<void> choose(WidgetTester tester, String row, String item) async {
+ await tapInView(tester, find.text(row));
+ await frames(tester);
+ await tapInView(tester, find.text(item, findRichText: true).last);
+ await frames(tester);
+ }
+
+ /// Options open, Worktree turned off — and, with [branch], that branch picked.
+ Future<void> worktreeOff(WidgetTester tester, {String? branch}) async {
+ await tapInView(tester, find.text('options'));
+ await frames(tester);
+ // Below the fold when nothing is running yet: the first-task suggestions take the room.
+ if (find.text('worktree').evaluate().isEmpty) {
+ await tester.scrollUntilVisible(
+ find.text('worktree'),
+ 200,
+ scrollable: find.byType(Scrollable).first,
+ );
+ }
+ expect(formRow(tester, 'worktree').value, '[x]');
+ await tapInView(tester, find.text('worktree'));
+ await frames(tester);
+ expect(formRow(tester, 'worktree').value, '[ ]');
+ if (branch != null) await choose(tester, 'branch', branch);
+ }
+
+ Future<void> start(WidgetTester tester) async {
+ await tapInView(tester, find.text('Start'));
+ await frames(tester, count: 20);
+ }
+
+ List<Map<String, dynamic>> created(EdgeConn conn) =>
+ conn.payloads['agent_create'] ?? const [];
+
+ /// Refused on the form: the reason under the task, nothing sent, and the button still saying
+ /// Start — nothing went out, so there is nothing to try again.
+ void expectRefused(EdgeConn conn, [String branch = 'fix/login']) {
+ expect(find.text(_refusal(branch)), findsOneWidget);
+ expect(created(conn), isEmpty);
+ expect(find.text('Start'), findsOneWidget);
+ expect(find.text('Try Again'), findsNothing);
+ }
+
+ group('Worktree off, a harness at work in the checkout: Start refuses', () {
+ testWidgets('the default branch Worktree on chose, kept when it is turned '
+ 'off; Worktree back on then starts', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester);
+ // The trigger: the row still says the default it had with Worktree on, and Start would
+ // have switched a folder on fix/login to main under the harness there.
+ expect(formRow(tester, 'branch').value, 'main');
+ await start(tester);
+ expectRefused(conn);
+
+ // The advice works: with Worktree on the folder is left alone, and the harness starts.
+ await tapInView(tester, find.text('worktree'));
+ await frames(tester);
+ expect(find.text(_refusal()), findsNothing);
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'worktree');
+ expect(payload['gitSource'], '/code/web');
+ expect(payload['branchRef'], 'refs/heads/main');
+ await close(tester, app);
+ });
+
+ testWidgets('another existing branch picked', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ expect(formRow(tester, 'branch').value, 'feature');
+ await start(tester);
+ expectRefused(conn);
+ await close(tester, app);
+ });
+
+ testWidgets('a new branch name typed for the folder', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'New branch…');
+ await tester.enterText(find.byType(TextField).last, 'try it');
+ await tester.pump();
+ await tester.tap(find.text('Use'));
+ await frames(tester);
+ expect(formRow(tester, 'branch').value, 'try-it');
+ await start(tester);
+ expectRefused(conn);
+ await close(tester, app);
+ });
+
+ testWidgets('the harness is in a subfolder of the checkout', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web/api')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ expectRefused(conn);
+ await close(tester, app);
+ });
+
+ testWidgets('the folder is a subfolder, and the harness is at the top of '
+ 'its checkout', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ folder: '/code/web/api',
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ expectRefused(conn);
+ await close(tester, app);
+ });
+
+ testWidgets('a harness started elsewhere that its machine has seen working '
+ 'in the checkout', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/api', seenIn: '/code/web/cli')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ expectRefused(conn);
+ await close(tester, app);
+ });
+
+ testWidgets('a folder on no branch is said to be on Detached HEAD', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ repository: _repository(branch: null),
+ );
+ await worktreeOff(tester);
+ await start(tester);
+ expectRefused(conn, 'Detached HEAD');
+ await close(tester, app);
+ });
+
+ testWidgets(
+ 'opened on a worktree\'s subfolder: its main checkout counts as '
+ 'a whole, top included',
+ (tester) async {
+ const worktree = '/home/u/harnesses/worktrees/web/silent-beacon';
+ final (:app, :conn) = await openNew(
+ tester,
+ folder: '$worktree/api',
+ // Working at the top of the main checkout, above the folder New moves to.
+ agents: [_harness('a', '/code/web')],
+ repository: {
+ ..._repository(root: worktree, branch: 'silent-beacon'),
+ 'mainFolder': '/code/web/api',
+ 'mainBranch': 'main',
+ 'branches': [
+ {
+ 'ref': 'refs/heads/main',
+ 'name': 'main',
+ 'worktree': '/code/web',
+ },
+ {
+ 'ref': 'refs/heads/silent-beacon',
+ 'name': 'silent-beacon',
+ 'worktree': worktree,
+ 'harness': true,
+ },
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ },
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ expectRefused(conn, 'main');
+ await close(tester, app);
+ },
+ );
+ });
+
+ group('everything that moves nothing starts as before', () {
+ testWidgets('harnesses in other folders, one whose path only begins like '
+ 'the checkout\'s', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/api'), _harness('b', '/code/website')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ expect(find.text(_refusal()), findsNothing);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['gitSource'], '/code/web');
+ expect(payload['branchRef'], 'refs/heads/feature');
+ expect(payload.containsKey('cwd'), isFalse);
+ await close(tester, app);
+ });
+
+ testWidgets('the branch the folder is already on', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'fix/login');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['branchRef'], 'refs/heads/fix/login');
+ await close(tester, app);
+ });
+
+ testWidgets('a branch with a worktree of its own, which opens there', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'docs');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['branchRef'], 'refs/heads/docs');
+ await close(tester, app);
+ });
+
+ testWidgets('Worktree on', (tester) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await tapInView(tester, find.text('options'));
+ await frames(tester);
+ await choose(tester, 'branch', 'feature');
+ expect(formRow(tester, 'worktree').value, '[x]');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'worktree');
+ expect(payload['branchRef'], 'refs/heads/feature');
+ await close(tester, app);
+ });
+
+ testWidgets('a New Folder chosen after the switch was set up', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await choose(tester, 'project', '+ New Folder');
+ await start(tester);
+ expect(find.text(_refusal()), findsNothing);
+ expect(created(conn).single['projectSource'], 'new');
+ await close(tester, app);
+ });
+
+ testWidgets('a repository to clone chosen after the switch was set up', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await choose(tester, 'project', '+ Clone Repository');
+ await tester.enterText(
+ find.byType(TextField).last,
+ 'https://github.com/ada/engine',
+ );
+ await tester.tap(find.text('Select'));
+ await frames(tester);
+ await start(tester);
+ expect(find.text(_refusal()), findsNothing);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'remote');
+ expect(payload['repositoryUrl'], 'https://github.com/ada/engine.git');
+ await close(tester, app);
+ });
+
+ testWidgets('no harness running on the computer', (tester) async {
+ final (:app, :conn) = await openNew(tester, agents: []);
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['branchRef'], 'refs/heads/feature');
+ await close(tester, app);
+ });
+
+ testWidgets('a harness at the same path on another computer', (
+ tester,
+ ) async {
+ final (:app, :conn) = await openNew(
+ tester,
+ agents: [_harness('a', '/code/api')],
+ elsewhere: [_harness('x', '/code/web')],
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['gitSource'], '/code/web');
+ expect(payload['branchRef'], 'refs/heads/feature');
+ await close(tester, app);
+ });
+
+ testWidgets('opened on a worktree\'s subfolder: a harness in that worktree '
+ 'is not in the main checkout', (tester) async {
+ const worktree = '/home/u/harnesses/worktrees/web/silent-beacon';
+ final (:app, :conn) = await openNew(
+ tester,
+ folder: '$worktree/api',
+ agents: [_harness('a', '$worktree/api')],
+ repository: {
+ ..._repository(root: worktree, branch: 'silent-beacon'),
+ 'mainFolder': '/code/web/api',
+ 'mainBranch': 'main',
+ 'branches': [
+ {'ref': 'refs/heads/main', 'name': 'main', 'worktree': '/code/web'},
+ {
+ 'ref': 'refs/heads/silent-beacon',
+ 'name': 'silent-beacon',
+ 'worktree': worktree,
+ 'harness': true,
+ },
+ {'ref': 'refs/heads/feature', 'name': 'feature'},
+ ],
+ },
+ );
+ await worktreeOff(tester, branch: 'feature');
+ await start(tester);
+ final payload = created(conn).single;
+ expect(payload['projectSource'], 'branch');
+ expect(payload['gitSource'], '/code/web/api');
+ expect(payload['branchRef'], 'refs/heads/feature');
+ await close(tester, app);
+ });
+ });
+}