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): a cancelled New Harness no longer blocks the next one with its placeholder branch (#2320)

Kelvinf3352d36d9bc
diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dart
index 25878800e..4eb660964 100644
--- a/desktop/lib/core/git_worktree.dart
+++ b/desktop/lib/core/git_worktree.dart
@@ -646,8 +646,17 @@ Future<String> prepareGitProject(
'refs/heads',
]);
final taken = locals.output.split('\n').toSet();
- final branch = branchName ?? placeholderBranch(taken, random: random);
+ var branch = branchName ?? placeholderBranch(taken, random: random);
final madeUp = branchName == null || placeholder;
+ // The composer keeps the placeholder it drew, so a start that made it and
+ // was then cancelled leaves it taken for the next press. Nobody chose that
+ // name: take the next free number, as the CLI does (gitProject.ts).
+ if (madeUp && !existingBranch) {
+ final base = branch;
+ for (var suffix = 2; taken.contains('refs/heads/$branch'); suffix++) {
+ branch = '$base-$suffix';
+ }
+ }
if (existingBranch) {
if (!taken.contains('refs/heads/$branch')) {
throw const RepositoryCloneException(
@@ -784,6 +793,80 @@ Future<String> prepareGitProject(
return inside(destination);
}
+/// Takes back a worktree [prepareGitProject] made for a start that was then
+/// cancelled: its folder, and the branch Harness made for it. A cancelled
+/// start left both behind, and the next press was refused for the branch
+/// (desktop 1.3.41, 2026-10-30). [folder] is what [prepareGitProject]
+/// returned, a subfolder of the worktree for a subfolder project.
+///
+/// True once the worktree is gone. Anything that may be somebody's work stays:
+/// a repository's own checkout, a worktree with changes in it, a branch that
+/// cannot be shown to have no commits of its own. With [keepBranch] (a branch
+/// that was there before the start) only the folder goes; a branch without
+/// Harness's mark keeps its branch too.
+Future<bool> discardPreparedWorktree(
+ String folder, {
+ bool keepBranch = false,
+ GitProcessStarter? startProcess,
+}) async {
+ Future<({int code, String output, String errorOutput})> git(
+ String at,
+ List<String> arguments, {
+ Duration timeout = const Duration(seconds: 4),
+ }) => _git(at, arguments, timeout: timeout, startProcess: startProcess);
+ final dirs = await git(folder, [
+ 'rev-parse',
+ '--path-format=absolute',
+ '--show-toplevel',
+ '--git-dir',
+ '--git-common-dir',
+ ]);
+ final lines = dirs.code == 0 ? dirs.output.split('\n') : const <String>[];
+ if (lines.length != 3 || lines.any((line) => line.isEmpty)) return false;
+ final [top, gitDir, common] = lines;
+ // The repository's own checkout has its git directory as the common one.
+ if (gitDir == common) return false;
+ final current = await git(folder, ['symbolic-ref', '--quiet', 'HEAD']);
+ final head = await git(folder, ['rev-parse', '--verify', 'HEAD']);
+ if (head.code != 0) return false;
+ final ref = current.code == 0 ? current.output : null;
+ final branch = ref?.replaceFirst('refs/heads/', '');
+ final mark = branch == null
+ ? null
+ : await git(folder, [
+ 'config',
+ '--get',
+ 'branch.$branch.$kHarnessBranchKey',
+ ]);
+ final made =
+ !keepBranch && mark != null && mark.code == 0 && mark.output.isNotEmpty;
+ if (made) {
+ // Proof, not absence of evidence: one entry ("branch: Created from …")
+ // that is still the tip. No reflog at all (core.logAllRefUpdates=false)
+ // proves nothing, and a branch with a commit there was lost in review.
+ final log = await git(folder, ['reflog', 'show', '--format=%H', ref!]);
+ if (log.code != 0 || log.output != head.output) return false;
+ }
+ // Without --force: a worktree with changes in it refuses. Ignored files
+ // (what `.worktreeinclude` copied in) do not count as changes. As long as
+ // `worktree add` may take: a deadline mid-delete leaves half a folder.
+ final removed = await git(folder, [
+ 'worktree',
+ 'remove',
+ '--',
+ top,
+ ], timeout: const Duration(minutes: 2));
+ if (removed.code != 0) return false;
+ if (made) {
+ // The tip proven above; one that moved since is kept.
+ final deleted = await git(common, ['update-ref', '-d', ref!, head.output]);
+ if (deleted.code == 0) {
+ await git(common, ['config', '--remove-section', 'branch.$branch']);
+ }
+ }
+ return true;
+}
+
/// `refs/remotes/origin/fix/typo` → origin, fix/typo, and a refspec that
/// updates exactly that remote-tracking branch.
({String remote, String branch, String refspec})? _remoteBranch(String? ref) {
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 2ef88cb46..a4e0ac60d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -338,6 +338,11 @@ class AgentCreationAttempt {
String? _outcome;
String? _preparedFolder;
ProjectFolderRequest? _projectFolder;
+
+ /// The worktree this computer made for this attempt, set only where it is
+ /// made: [_preparedFolder] is also what a machine's refusal names. A
+ /// confirmed cancel takes it back ([AppNotifier._discardCancelledWorktree]).
+ ({String folder, bool keepBranch})? _worktreeMadeHere;
String? _remoteProjectName;
int _projectNameRetries = 0;
@@ -15344,6 +15349,7 @@ class AppNotifier extends ChangeNotifier {
result['state'] == 'cancelled') {
creation._complete('Creation cancelled.');
_activeAgentCreations.remove(creation);
+ await _discardCancelledWorktree(creation);
return null;
}
return 'The request may already be starting. Check status before starting another.';
@@ -15354,6 +15360,30 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Takes back the worktree this computer made for [creation], once its
+ /// cancel is confirmed and nothing will start in it. Kept, it held its
+ /// branch, and the next press was refused for that name (desktop 1.3.41,
+ /// 2026-10-30). One it cannot take back stays and is logged: the cancel
+ /// itself is done either way.
+ Future<void> _discardCancelledWorktree(AgentCreationAttempt creation) async {
+ final made = creation._worktreeMadeHere;
+ if (made == null) return;
+ creation._worktreeMadeHere = null;
+ if (creation._preparedFolder == made.folder) creation._preparedFolder = null;
+ try {
+ if (!await discardLocalWorktree(made.folder, keepBranch: made.keepBranch)) {
+ appLog.info('worktree', 'kept after cancel: ${made.folder}');
+ }
+ } catch (error) {
+ appLog.warn('worktree', 'not removed after cancel: ${made.folder}', error: error);
+ }
+ }
+
+ /// The local half of [_discardCancelledWorktree]; a test's seam, as
+ /// [prepareLocalProjectFolder] is.
+ Future<bool> discardLocalWorktree(String folder, {bool keepBranch = false}) =>
+ discardPreparedWorktree(folder, keepBranch: keepBranch);
+
Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {
// Only this answer says whether it is starting; one that never reaches
// the machine (it went offline) must not be followed as if it were.
@@ -15431,6 +15461,7 @@ class AppNotifier extends ChangeNotifier {
name: projectName is String ? projectName : null,
));
final dshId = choices['dsh'];
+ final preparedBefore = creation._preparedFolder;
creation._preparedFolder ??= await prepareLocalProjectFolder(
project,
// The folder is named after who the harness is: the harness's own name, else the engine's.
@@ -15442,6 +15473,12 @@ class AppNotifier extends ChangeNotifier {
engineIdentity(dshId).label)
: engineIdentity(choices['engine'] as String?).label,
);
+ if (preparedBefore == null && project.createsWorktree) {
+ creation._worktreeMadeHere = (
+ folder: creation._preparedFolder!,
+ keepBranch: project.existingBranch,
+ );
+ }
} on ProjectExistsException catch (error) {
// This computer's own folder refuses a typed name as the machine
// does, so the form offers the folder the same way.
diff --git a/desktop/test/cancel_discards_worktree_test.dart b/desktop/test/cancel_discards_worktree_test.dart
new file mode 100644
index 000000000..3adb707f9
--- /dev/null
+++ b/desktop/test/cancel_discards_worktree_test.dart
@@ -0,0 +1,341 @@
+import 'dart:async';
+import 'dart:io';
+
+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/core/project_folder.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:path/path.dart' as p;
+
+import 'swarm_state_test.dart' show createApp;
+
+class _Request {
+ _Request(this.type, this.payload);
+ final String type;
+ final Map<String, dynamic> payload;
+ final reply = Completer<Map<String, dynamic>>();
+ void held() => reply.complete({
+ 'creationId': payload['creationId'],
+ 'state': 'pending',
+ 'held': {
+ 'service': 'native',
+ 'detail': 'Waiting to confirm the engine search path and its aliases.',
+ },
+ });
+}
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final calls = <_Request>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'engines_probe') return Future.value({'engines': []});
+ if (type == 'dsh_list') return Future.value({'dsh': []});
+ final request = _Request(type, Map.of(payload));
+ calls.add(request);
+ return request.reply.future;
+ }
+}
+
+class _App extends AppNotifier {
+ _App(_Connection connection, {required bool local, this.discardFails = false})
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ connectionForTest: (_) => connection,
+ ) {
+ const machine = Machine(
+ machineId: 'm',
+ name: 'Studio',
+ authMode: MachineAuthMode.remote,
+ );
+ machineStates['m'] = MachineState(machine)..localOnly = local;
+ }
+ final bool discardFails;
+ final discarded = <(String, bool)>[];
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+ @override
+ Future<String> prepareLocalProjectFolder(
+ ProjectFolderRequest request, {
+ String label = 'harness',
+ }) async => '/harnesses/worktrees/x4/witty-finch';
+ @override
+ Future<bool> discardLocalWorktree(
+ String folder, {
+ bool keepBranch = false,
+ }) async {
+ if (discardFails) throw StateError('git went away');
+ discarded.add((folder, keepBranch));
+ return true;
+ }
+}
+
+const _worktree = ProjectFolderRequest.worktree(
+ '/repo/x4',
+ branchRef: 'refs/heads/main',
+ branchName: 'witty-finch',
+ placeholder: true,
+);
+
+/// Starts [project] on [app], has the machine hold it, then cancels it with
+/// the machine answering [receipt].
+Future<String?> _holdThenCancel(
+ _App app,
+ _Connection connection, {
+ ProjectFolderRequest? project = _worktree,
+ String receipt = 'cancelled',
+}) async {
+ final attempt = AgentCreationAttempt();
+ final create = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: project == null ? '/repo/x4' : null,
+ projectFolder: project,
+ attempt: attempt,
+ );
+ await pumpEventQueue();
+ connection.calls.last.held();
+ await create;
+ expect(attempt.canCancelPending, isTrue);
+ final cancel = app.cancelAgentCreation(attempt);
+ await pumpEventQueue();
+ final request = connection.calls.last;
+ expect(request.type, 'agent_create_cancel');
+ request.reply.complete({
+ 'creationId': request.payload['creationId'],
+ 'state': receipt,
+ });
+ return cancel;
+}
+
+void main() {
+ // Desktop 1.3.41, 2026-10-30: New Harness made witty-finch's worktree and
+ // branch here, the machine held the start, Cancel request was confirmed, and
+ // both stayed behind; the next press was refused for the branch they kept.
+ test(
+ 'a confirmed cancel removes the worktree this computer made for it',
+ () async {
+ final connection = _Connection();
+ final app = _App(connection, local: true);
+ addTearDown(app.dispose);
+ expect(await _holdThenCancel(app, connection), isNull);
+ expect(app.discarded, [('/harnesses/worktrees/x4/witty-finch', false)]);
+ },
+ );
+
+ test('a branch that was there before the start keeps its branch', () async {
+ final connection = _Connection();
+ final app = _App(connection, local: true);
+ addTearDown(app.dispose);
+ const existing = ProjectFolderRequest.worktree(
+ '/repo/x4',
+ branchRef: 'refs/heads/topic',
+ branchName: 'topic',
+ existingBranch: true,
+ );
+ expect(await _holdThenCancel(app, connection, project: existing), isNull);
+ expect(app.discarded, [('/harnesses/worktrees/x4/witty-finch', true)]);
+ });
+
+ test('a cancel the machine did not confirm keeps the worktree', () async {
+ final connection = _Connection();
+ final app = _App(connection, local: true);
+ addTearDown(app.dispose);
+ expect(
+ await _holdThenCancel(app, connection, receipt: 'created'),
+ contains('Check status'),
+ );
+ expect(app.discarded, isEmpty);
+ });
+
+ test('a folder that is not a new worktree is never removed', () async {
+ final connection = _Connection();
+ final app = _App(connection, local: true);
+ addTearDown(app.dispose);
+ expect(await _holdThenCancel(app, connection, project: null), isNull);
+ expect(app.discarded, isEmpty);
+ });
+
+ test(
+ 'another machine removes its own worktree; this computer does not',
+ () async {
+ final connection = _Connection();
+ final app = _App(connection, local: false);
+ addTearDown(app.dispose);
+ expect(await _holdThenCancel(app, connection), isNull);
+ expect(app.discarded, isEmpty);
+ },
+ );
+
+ test(
+ 'a worktree that cannot be removed still leaves the cancel confirmed',
+ () async {
+ final connection = _Connection();
+ final app = _App(connection, local: true, discardFails: true);
+ addTearDown(app.dispose);
+ expect(await _holdThenCancel(app, connection), isNull);
+ },
+ );
+
+ group('New Harness on this computer', () {
+ late Directory root;
+ late String repo;
+ Future<String> git(List<String> args, [String? at]) async {
+ final result = await Process.run('git', ['-C', at ?? repo, ...args]);
+ expect(result.exitCode, 0, reason: '${args.join(' ')}: ${result.stderr}');
+ return (result.stdout as String).trim();
+ }
+
+ setUp(() async {
+ root = await Directory.systemTemp.createTemp('harness-cancel-');
+ repo = p.join(root.path, 'x4');
+ await Directory(repo).create();
+ await git(['init', '-b', 'main']);
+ await git(['config', 'user.name', 'Test']);
+ await git(['config', 'user.email', '[email protected]']);
+ await git(['config', 'commit.gpgsign', 'false']);
+ await git(['commit', '--allow-empty', '-m', 'initial']);
+ });
+ tearDown(() => root.delete(recursive: true));
+
+ // The whole of the 2026-10-30 report: press, the machine holds the start,
+ // Cancel request, press again.
+ test('starts again after a cancelled held start, from main, with nothing left behind', () async {
+ final connection = _Machine();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ prepareFolder: (request) =>
+ request.prepareLocal(projectHome: p.join(root.path, 'harnesses')),
+ );
+ app.machineStates['m']!.localOnly = true;
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: repo,
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await _gitRead(box);
+ expect(box.isGitProject, isTrue);
+ expect(box.worktree, isTrue);
+
+ connection.hold = true;
+ expect(await box.create(), NewHarnessOutcome.failed);
+ final first = connection.starts.single['cwd'] as String;
+ expect(await Directory(first).exists(), isTrue);
+ expect(box.canCancelPending, isTrue);
+
+ await box.cancelPending();
+ await _gitRead(box);
+ expect(box.status, 'Creation cancelled.');
+ expect(await Directory(first).exists(), isFalse);
+ expect(await git(['branch', '--format=%(refname:short)']), 'main');
+
+ connection.hold = false;
+ expect(
+ await box.create(),
+ NewHarnessOutcome.created,
+ reason: '${box.error}',
+ );
+ final second = connection.starts.last['cwd'] as String;
+ expect(await Directory(second).exists(), isTrue);
+ expect(
+ await git(['rev-parse', 'HEAD'], second),
+ await git(['rev-parse', 'main']),
+ );
+ expect(
+ await git([
+ 'config',
+ '--get',
+ 'branch.${await git(['branch', '--show-current'], second)}.harness',
+ ]),
+ 'placeholder',
+ );
+ });
+ });
+}
+
+/// The box reads Git with real processes: waits until it has an answer.
+Future<void> _gitRead(NewHarnessController box) async {
+ for (var i = 0; i < 200; i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ if (!box.checkingGit) return;
+ }
+}
+
+/// A machine that holds a start while [hold], confirms a cancel, and
+/// otherwise makes the harness.
+class _Machine extends WsConn {
+ _Machine()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ bool hold = false;
+ final starts = <Map<String, dynamic>>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ final id = payload['creationId'];
+ switch (type) {
+ case 'agent_create':
+ starts.add(Map.of(payload));
+ if (hold) {
+ return {
+ 'creationId': id,
+ 'state': 'pending',
+ 'held': {
+ 'service': 'native',
+ 'detail':
+ 'Waiting to confirm the engine search path and its aliases.',
+ },
+ };
+ }
+ return {
+ 'creationId': id,
+ 'state': 'created',
+ 'agent': {
+ 'id': 'made',
+ 'name': 'Made',
+ 'engine': 'claude',
+ 'project': {'name': 'x4', 'cwd': payload['cwd']},
+ },
+ };
+ case 'agent_create_cancel':
+ return {'creationId': id, 'state': 'cancelled'};
+ case 'engines_probe':
+ return {'engines': []};
+ case 'dsh_list':
+ return {'dsh': []};
+ }
+ return {};
+ }
+}
diff --git a/desktop/test/git_worktree_test.dart b/desktop/test/git_worktree_test.dart
index 61dffda15..56cb73b40 100644
--- a/desktop/test/git_worktree_test.dart
+++ b/desktop/test/git_worktree_test.dart
@@ -353,6 +353,144 @@ void main() {
);
});
+ // The composer draws its placeholder once and keeps it. A start that made
+ // the branch and was then cancelled left it behind, and the next press asked
+ // for the same name: "A branch named witty-finch already exists. Choose
+ // another name." about a name nobody chose (desktop 1.3.41, 2026-10-30).
+ test('a kept placeholder taken since takes the next free number; a typed name is still refused', () async {
+ Future<String> placeholder() => ProjectFolderRequest.worktree(
+ repo,
+ branchRef: 'refs/heads/feature',
+ branchName: 'witty-finch',
+ placeholder: true,
+ ).prepareLocal(projectHome: p.join(root.path, 'harnesses'));
+ final first = await placeholder();
+ final second = await placeholder();
+ expect(await git(['branch', '--show-current'], first), 'witty-finch');
+ expect(await git(['branch', '--show-current'], second), 'witty-finch-2');
+ expect(second, p.join(worktrees(), 'witty-finch-2'));
+ expect(
+ await git(['config', '--get', 'branch.witty-finch-2.harness']),
+ 'placeholder',
+ );
+ await expectLater(
+ worktree(name: 'witty-finch'),
+ throwsA(isA<RepositoryCloneException>()),
+ );
+ });
+
+ group('discarding a prepared worktree', () {
+ Future<String> placeholder() => ProjectFolderRequest.worktree(
+ repo,
+ branchRef: 'refs/heads/feature',
+ branchName: 'witty-finch',
+ placeholder: true,
+ ).prepareLocal(projectHome: p.join(root.path, 'harnesses'));
+ Future<bool> branchExists(String name) async =>
+ (await Process.run('git', [
+ '-C',
+ repo,
+ 'show-ref',
+ '--verify',
+ '--quiet',
+ 'refs/heads/$name',
+ ])).exitCode ==
+ 0;
+
+ test('removes the folder, the branch Harness made, and its mark', () async {
+ await File(p.join(repo, '.git', 'info', 'exclude'))
+ .writeAsString('.env\n');
+ final path = await placeholder();
+ // `.worktreeinclude` copies ignored files in; they are the start's own.
+ await File(p.join(path, '.env')).writeAsString('KEY=1');
+ expect(await discardPreparedWorktree(path), isTrue);
+ expect(await Directory(path).exists(), isFalse);
+ expect(await branchExists('witty-finch'), isFalse);
+ final mark = await Process.run('git', [
+ '-C',
+ repo,
+ 'config',
+ '--get',
+ 'branch.witty-finch.harness',
+ ]);
+ expect(mark.exitCode, isNot(0));
+ // The name is free again for the next press.
+ expect(await placeholder(), p.join(worktrees(), 'witty-finch'));
+ });
+
+ test('a subfolder project removes the whole worktree', () async {
+ final sub = await ProjectFolderRequest.worktree(
+ p.join(repo, 'src'),
+ branchRef: 'refs/heads/feature',
+ branchName: 'witty-finch',
+ placeholder: true,
+ ).prepareLocal(projectHome: p.join(root.path, 'harnesses'));
+ expect(p.basename(sub), 'src');
+ expect(await discardPreparedWorktree(sub), isTrue);
+ expect(await Directory(p.dirname(sub)).exists(), isFalse);
+ expect(await branchExists('witty-finch'), isFalse);
+ });
+
+ test('keeps a worktree with changes in it, and its branch', () async {
+ final path = await placeholder();
+ await File(p.join(path, 'src', 'value')).writeAsString('edited');
+ await File(p.join(path, 'notes.txt')).writeAsString('new');
+ expect(await discardPreparedWorktree(path), isFalse);
+ expect(await Directory(path).exists(), isTrue);
+ expect(await branchExists('witty-finch'), isTrue);
+ });
+
+ test('keeps a branch with commits of its own', () async {
+ final path = await placeholder();
+ await File(p.join(path, 'src', 'value')).writeAsString('work');
+ await git(['commit', '-am', 'work'], path);
+ expect(await discardPreparedWorktree(path), isFalse);
+ expect(await Directory(path).exists(), isTrue);
+ expect(await branchExists('witty-finch'), isTrue);
+ });
+
+ // Review of this change: with no reflog, "one entry or fewer" read as
+ // unused, and a committed branch was deleted with its commit.
+ test(
+ 'without reflogs a branch is never proven unused, so it stays',
+ () async {
+ await git(['config', 'core.logAllRefUpdates', 'false']);
+ final path = await placeholder();
+ await File(p.join(path, 'src', 'value')).writeAsString('work');
+ await git(['commit', '-am', 'work'], path);
+ final tip = await git(['rev-parse', 'witty-finch']);
+ expect(await discardPreparedWorktree(path), isFalse);
+ expect(await git(['rev-parse', 'witty-finch']), tip);
+ expect(await Directory(path).exists(), isTrue);
+ },
+ );
+
+ test('a marked branch the person chose keeps its branch', () async {
+ final path = await placeholder();
+ expect(await discardPreparedWorktree(path, keepBranch: true), isTrue);
+ expect(await Directory(path).exists(), isFalse);
+ expect(await branchExists('witty-finch'), isTrue);
+ });
+
+ test('an existing branch loses only the worktree made for it', () async {
+ await git(['branch', 'topic', 'main']);
+ final path = await worktree(
+ ref: 'refs/heads/topic',
+ name: 'topic',
+ existing: true,
+ );
+ expect(await discardPreparedWorktree(path), isTrue);
+ expect(await Directory(path).exists(), isFalse);
+ expect(await branchExists('topic'), isTrue);
+ });
+
+ test('never removes a repository\'s own checkout', () async {
+ expect(await discardPreparedWorktree(repo), isFalse);
+ expect(await Directory(repo).exists(), isTrue);
+ expect(await branchExists('main'), isTrue);
+ });
+ });
+
test(
'an existing branch is checked out as it is in a new worktree, once',
() async {