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.

feat: treat worktrees as temporary folders, known by repo and branch (#199)

Dee5a1ff70d2b33
diff --git a/cli/src/lib/agentNames.ts b/cli/src/lib/agentNames.ts
index 151c6a001..369462ac0 100644
--- a/cli/src/lib/agentNames.ts
+++ b/cli/src/lib/agentNames.ts
@@ -63,6 +63,15 @@ export function projectFolderName(label: string, at: Date, withSeconds = false):
return `${slug}-${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}-${time}`
}
+/** `claude-0922-1136`: the harness and the local time, short enough to read as a branch. The
+ * worktree's folder is named the same and nobody needs to see it. Mirrors `worktreeName` in
+ * desktop/lib/core/git_worktree.dart. */
+export function worktreeName(label: string, at: Date): string {
+ const slug = label.normalize('NFKD').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
+ .slice(0, 40).replace(/-+$/, '') || 'harness'
+ return `${slug}-${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}`
+}
+
/** The folder for a project somebody named: their words with spaces as dashes and nothing a path or
* a shell reads specially. Null when nothing usable is left. Mirrors `projectFolderSlug` in
* desktop/lib/core/project_folder.dart. */
diff --git a/cli/src/lib/agentProject.spec.ts b/cli/src/lib/agentProject.spec.ts
index f7f8e0a9b..02750f2b7 100644
--- a/cli/src/lib/agentProject.spec.ts
+++ b/cli/src/lib/agentProject.spec.ts
@@ -28,6 +28,18 @@ describe('owning-machine project metadata', () => {
git('symbolic-ref', 'HEAD', 'refs/heads/feature/real-branch')
expect(await agentProject(cwd, 20_000)).toMatchObject({ branch: 'feature/real-branch' })
})
+ it('names a linked worktree for its repository rather than its folder', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'harness-v2-worktree-')); roots.push(root)
+ const repo = join(root, 'app')
+ const git = (...args: string[]) => execFileSync('git', ['-C', repo, ...args], { stdio: 'pipe' })
+ await mkdir(repo)
+ git('init', '-b', 'main')
+ git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'initial')
+ const linked = join(root, 'worktrees', 'app', 'claude-0922-1136')
+ git('worktree', 'add', '-b', 'harness/claude-0922-1136', linked)
+ expect(await agentProject(linked)).toMatchObject({ name: 'app', root: await realpath(linked), branch: 'harness/claude-0922-1136' })
+ expect(await agentProject(repo)).toMatchObject({ name: 'app', branch: 'main' })
+ })
it('keeps a non-repository project branchless and rejects absent cwd', async () => {
const root = await mkdtemp(join(tmpdir(), 'harness-v2-folder-')); roots.push(root)
expect(await agentProject(root)).toMatchObject({ cwd: root, root: null, remote: null, branch: null })
diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.ts
index 1baeda12e..54ecf8740 100644
--- a/cli/src/lib/agentProject.ts
+++ b/cli/src/lib/agentProject.ts
@@ -1,5 +1,5 @@
import { execFile } from 'node:child_process'
-import { basename, isAbsolute } from 'node:path'
+import { basename, dirname, isAbsolute, resolve } from 'node:path'
import { promisify } from 'node:util'
const exec = promisify(execFile)
@@ -51,7 +51,10 @@ async function inspect(cwd: string): Promise<AgentProject> {
if (!root) return { name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }
const remote = await git(cwd, ['config', '--get', 'remote.origin.url'])
const branch = await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD'])
- return { name: basename(root), cwd, root, remote: canonicalRepository(remote), branch }
+ const common = await git(root, ['rev-parse', '--git-common-dir'])
+ // A linked worktree is named for its repository, not its folder.
+ const main = common && basename(common) === '.git' ? dirname(resolve(root, common)) : root
+ return { name: basename(main), cwd, root, remote: canonicalRepository(remote), branch }
} finally {
const next = waiting.shift()
if (next) next()
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index 11d13efa9..aee210680 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -1,7 +1,7 @@
import { execFile } from 'node:child_process'
-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { basename, join } from 'node:path'
import { promisify } from 'node:util'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'
@@ -70,6 +70,29 @@ describe('launch Git preparation', () => {
expect(await git('branch', '--show-current')).toBe('main')
})
+ it('names worktrees for the harness and the time, grouped by repository, skipping names already taken', async () => {
+ await git('branch', 'harness/codex-0921-1200-2', 'main')
+ const paths = [await prepare('worktree'), await prepare('worktree')]
+ const folder = join(root, 'harnesses', 'worktrees', 'project with spaces')
+ expect(paths).toEqual([join(folder, 'codex-0921-1200'), join(folder, 'codex-0921-1200-3')])
+ for (const path of paths) {
+ expect((await exec('git', ['-C', path, 'branch', '--show-current'])).stdout.trim()).toBe(`harness/${basename(path)}`)
+ }
+ })
+
+ it('reads a linked worktree as its repository, and a worktree started from one joins the same repository', async () => {
+ const linked = await prepare('worktree')
+ const info = await readGitProject(join(linked, 'src'))
+ expect(info).toMatchObject({ isGit: true, branch: 'harness/codex-0921-1200', mainBranch: 'main' })
+ expect(await realpath((info as { mainFolder: string }).mainFolder)).toBe(await realpath(join(repo, 'src')))
+ const branches = (info as { branches: Array<{ name: string; worktree?: string }> }).branches
+ expect(await realpath(branches.find(branch => branch.name === 'harness/codex-0921-1200')!.worktree!)).toBe(await realpath(linked))
+ expect(await realpath(branches.find(branch => branch.name === 'main')!.worktree!)).toBe(await realpath(repo))
+ expect(await readGitProject(repo)).not.toHaveProperty('mainFolder')
+ const second = await prepare('worktree', 'refs/heads/main', linked)
+ expect(second).toBe(join(root, 'harnesses', 'worktrees', 'project with spaces', 'codex-0921-1200-2'))
+ })
+
it('keeps the selected subfolder in its new worktree', async () => {
const path = await prepare('worktree', 'refs/heads/feature', join(repo, 'src'))
expect(await readFile(join(path, 'value'), 'utf8')).toBe('feature')
@@ -88,9 +111,11 @@ describe('launch Git preparation', () => {
expect(await prepare('branch')).toBe(repo)
})
- it('refuses a branch checked out elsewhere, missing refs, revision expressions, and untracked subfolders', async () => {
+ it('opens a branch checked out elsewhere in its worktree, and refuses missing refs, revision expressions, and untracked subfolders', async () => {
await git('worktree', 'add', join(root, 'other'), 'feature')
- await expect(prepare('branch')).rejects.toMatchObject({ code: 'BRANCH_SWITCH_FAILED' })
+ expect(await realpath(await prepare('branch'))).toBe(await realpath(join(root, 'other')))
+ expect(await realpath(await prepare('branch', 'refs/heads/feature', join(repo, 'src')))).toBe(await realpath(join(root, 'other', 'src')))
+ expect(await git('branch', '--show-current')).toBe('main')
for (const ref of ['refs/heads/missing', 'refs/heads/main~0', 'refs/heads/main^{commit}']) {
await expect(prepare('worktree', ref)).rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })
}
@@ -134,7 +159,7 @@ describe('launch Git preparation', () => {
expect(await readGitProject(repo)).toMatchObject({ isGit: true, branch: null })
const path = await prepareGitProject(repo, { root, worktree: true })
expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')
- expect(path).toContain('project-with-spaces-harness-')
+ expect(path).toMatch(/\/worktrees\/project with spaces\/harness-\d{4}-\d{4}$/)
expect(await prepare('branch')).toBe(repo)
expect(await git('branch', '--show-current')).toBe('feature')
})
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index 43a382963..6a0c8ad37 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -1,8 +1,8 @@
import { execFile } from 'node:child_process'
-import { mkdir, mkdtemp } from 'node:fs/promises'
-import { basename, isAbsolute, join } from 'node:path'
+import { mkdir, realpath, stat } from 'node:fs/promises'
+import { basename, isAbsolute, join, normalize } from 'node:path'
import { promisify } from 'node:util'
-import { projectFolderName } from './agentNames.js'
+import { worktreeName } from './agentNames.js'
const exec = promisify(execFile)
@@ -23,6 +23,34 @@ async function git(path: string, args: string[], timeout = 4000): Promise<string
})).stdout.replace(/\r?\n$/, '')
}
+/** `git worktree list --porcelain`, main checkout first. A bare repository has no files and a
+ * prunable entry lost its folder, so neither is somewhere to work. */
+type Worktree = { path: string; ref: string | null; usable: boolean }
+function parseWorktrees(output: string): Worktree[] {
+ return output.split(/\n\s*\n/).flatMap(block => {
+ const lines = block.split('\n')
+ const path = lines.find(line => line.startsWith('worktree '))?.slice('worktree '.length)
+ if (!path) return []
+ return [{
+ path,
+ ref: lines.find(line => line.startsWith('branch '))?.slice('branch '.length) ?? null,
+ usable: !lines.some(line => line === 'bare' || line.startsWith('prunable')),
+ }]
+ })
+}
+const worktrees = (path: string) => git(path, ['worktree', 'list', '--porcelain']).then(parseWorktrees, () => [])
+const real = (path: string) => realpath(path).catch(() => normalize(path))
+const isDirectory = (path: string) => stat(path).then(info => info.isDirectory(), () => false)
+
+/** The main checkout, when `root` is one of its linked worktrees. */
+async function mainCheckout(root: string, trees: Worktree[]): Promise<string | null> {
+ if (trees.length < 2 || !trees[0]!.usable) return null
+ const here = await real(root)
+ if (await real(trees[0]!.path) === here) return null
+ for (const tree of trees.slice(1)) if (await real(tree.path) === here) return trees[0]!.path
+ return null
+}
+
/** Read only: listing a branch never checks it out or fetches from a remote. */
export async function readGitProject(path: string) {
if (!validGitPath(path)) return { error: 'INVALID_PATH' }
@@ -33,20 +61,32 @@ export async function readGitProject(path: string) {
return !failure.killed && failure.code === 128 ? { isGit: false, branches: [] } : { error: 'GIT_UNAVAILABLE' }
}
try {
- const [branch, refs] = await Promise.all([
+ const [branch, refs, trees] = await Promise.all([
git(path, ['symbolic-ref', '--quiet', 'HEAD']).then(ref => ref.replace(/^refs\/heads\//, '')).catch(() => null),
git(path, ['for-each-ref', '--format=%(refname)%09%(refname:short)%09%(symref)', 'refs/heads', 'refs/remotes']),
+ worktrees(path),
])
+ const checkedOut = new Map(trees.flatMap(tree => tree.usable && tree.ref ? [[tree.ref, tree.path] as const] : []))
const branches = refs.split('\n').filter(Boolean).flatMap(line => {
const [ref, name, symbolic] = line.split('\t')
- return ref && name && !symbolic ? [{ ref, name, remote: ref.startsWith('refs/remotes/') }] : []
+ if (!ref || !name || symbolic) return []
+ const worktree = checkedOut.get(ref)
+ return [{ ref, name, remote: ref.startsWith('refs/remotes/'), ...(worktree ? { worktree } : {}) }]
})
- return { isGit: true, root, branch, branches }
+ // A worktree is a temporary folder. The launcher shows its repository.
+ const main = await mainCheckout(root, trees)
+ if (!main) return { isGit: true, root, branch, branches }
+ const prefix = (await git(path, ['rev-parse', '--show-prefix']).catch(() => '')).replace(/\/$/, '')
+ const mainFolder = prefix && await isDirectory(join(main, prefix)) ? join(main, prefix) : main
+ const mainBranch = trees[0]!.ref?.replace(/^refs\/heads\//, '')
+ return { isGit: true, root, branch, branches, mainFolder, ...(mainBranch ? { mainBranch } : {}) }
} catch { return { error: 'GIT_UNAVAILABLE' } }
}
-/** Start uses a fresh branch for worktrees; the shared folder is only switched
- * when the user explicitly chooses a different local branch with Worktree off. */
+/** Start uses a fresh `harness/<name>` branch for worktrees, in a folder under
+ * `<root>/worktrees/<repository>`. With Worktree off, a branch that already has a worktree opens
+ * there; otherwise the shared folder is only switched when the user explicitly chooses a different
+ * local branch. */
export async function prepareGitProject(
source: string,
options: { root: string; worktree: boolean; ref?: string; label?: string | null; now?: () => Date },
@@ -65,25 +105,44 @@ export async function prepareGitProject(
} catch {
throw new GitProjectError('GIT_PROJECT_UNAVAILABLE', 'Choose a Git project and branch with at least one commit. For a new folder, turn Worktree off.')
}
+ const inside = (folder: string) => prefix ? join(folder, prefix.replace(/\/$/, '')) : folder
+ const trees = await worktrees(source)
if (!options.worktree) {
if (!options.ref?.startsWith('refs/heads/')) throw new GitProjectError('INVALID_BRANCH', 'Choose a local branch, or turn Worktree on.')
try {
const current = await git(source, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => null)
if (current === options.ref) return source
+ // A branch that already has a worktree is worked on there: Git would refuse to check it out
+ // twice, and the folder is not the person's concern.
+ for (const tree of trees) {
+ if (tree.usable && tree.ref === options.ref && await isDirectory(tree.path)) return inside(tree.path)
+ }
await git(source, ['switch', '--', options.ref.slice('refs/heads/'.length)], 120_000)
return source
} catch {
throw new GitProjectError('BRANCH_SWITCH_FAILED', 'Could not switch branches. Commit or stash conflicting changes, or turn Worktree on.')
}
}
- const parent = join(options.root, 'worktrees')
- await mkdir(parent, { recursive: true })
- const name = projectFolderName(`${basename(root)}-${options.label?.trim() || 'harness'}`, (options.now ?? (() => new Date()))(), true)
- const destination = await mkdtemp(join(parent, `${name}-`))
- const branch = `harness/${basename(destination)}`
+ // Grouped by repository, so the leaf only needs the harness and the time.
+ const repository = trees[0]?.usable ? basename(trees[0].path) : basename(root)
+ const taken = new Set((await git(source, ['for-each-ref', '--format=%(refname)', 'refs/heads/harness/']).catch(() => '')).split('\n'))
+ const base = worktreeName(options.label?.trim() || 'harness', (options.now ?? (() => new Date()))())
+ let destination: string | undefined, branch = ''
+ try {
+ const parent = join(options.root, 'worktrees', repository)
+ await mkdir(parent, { recursive: true })
+ // mkdir reserves the name atomically, so simultaneous starts never share a worktree.
+ for (let attempt = 1; attempt <= 100 && !destination; attempt++) {
+ const name = attempt === 1 ? base : `${base}-${attempt}`
+ if (taken.has(`refs/heads/harness/${name}`)) continue
+ try { await mkdir(join(parent, name)); destination = join(parent, name); branch = `harness/${name}` }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
+ }
+ } catch { destination = undefined }
+ if (!destination) throw new GitProjectError('WORKTREE_FAILED', 'Could not create a worktree folder. Check folder permissions, then retry.')
try {
await git(source, ['worktree', 'add', '-b', branch, '--', destination, head], 120_000)
- return prefix ? join(destination, prefix.replace(/\/$/, '')) : destination
+ return inside(destination)
} catch {
// Keep any partial checkout and branch available for recovery.
throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index f898ec9a0..4be689140 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -38,15 +38,26 @@ Git show neither row. Discovery runs on the selected machine without fetching,
switching branches, or creating a worktree. A failed discovery offers Retry and
blocks starting until the result is known.
+A worktree is a temporary folder, never a project: a harness is known by its
+repository and branch. A folder inside a linked worktree (the focused pane's,
+or one typed or browsed) shows as the same folder in the repository's main
+checkout, on that checkout's branch, so Cmd-N from a worktree pane starts
+beside it rather than inside it. Pane headers name the repository, and
+worktrees Start made are never offered as recent projects.
+
Branch selects the starting local or remote ref. With `[x]`, Start Harness
-creates a unique worktree and branch under `~/harnesses/worktrees`, keeping
-uncommitted source files intact. With `[ ]`, only local branches are selectable;
-Start Harness switches the existing folder using Git's normal protections.
-No changes are forced, stashed, or discarded. A selected subfolder follows into
-the new worktree only if it exists in that commit.
+creates branch `harness/<agent>-MMDD-HHMM` checked out in
+`~/harnesses/worktrees/<repository>/<agent>-MMDD-HHMM`, adding `-2`, `-3` only
+when that branch or folder is taken, and keeping uncommitted source files
+intact. With `[ ]`, only local branches are selectable; a branch that already
+has a worktree opens there, and any other branch switches the existing folder
+using Git's normal protections. No changes are forced, stashed, or discarded.
+A selected subfolder follows into the new worktree only if it exists in that
+commit.
Drafts and advanced options preserve these choices. A lost start reply reuses
-its receipt, and retrying a confirmed launch failure reuses its prepared folder.
+its receipt, and retrying a confirmed launch failure reuses its prepared
+worktree: the retry selects that worktree's branch with Worktree off.
## Draft ownership
diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dart
index ee34ed0b3..c72112d72 100644
--- a/desktop/lib/core/git_worktree.dart
+++ b/desktop/lib/core/git_worktree.dart
@@ -4,13 +4,15 @@ import 'dart:io';
import 'package:path/path.dart' as p;
-import 'project_folder.dart';
import 'repository_clone.dart';
class GitBranch {
- const GitBranch(this.ref, this.name, {this.remote = false});
+ const GitBranch(this.ref, this.name, {this.remote = false, this.worktree});
final String ref, name;
final bool remote;
+
+ /// Where this local branch is checked out, when it is.
+ final String? worktree;
}
class GitProjectInfo {
@@ -19,11 +21,17 @@ class GitProjectInfo {
this.branch,
this.branches = const [],
this.error,
+ this.mainFolder,
+ this.mainBranch,
});
factory GitProjectInfo.fromJson(Map<String, dynamic> data) => GitProjectInfo(
isGit: data['isGit'] == true,
branch: data['branch'] as String?,
error: data['error'] as String?,
+ mainFolder: data['mainFolder'] is String && validGitPath(data['mainFolder'])
+ ? data['mainFolder'] as String
+ : null,
+ mainBranch: data['mainBranch'] as String?,
branches: [
for (final row in (data['branches'] as List? ?? const []))
if (row is Map && row['ref'] is String && row['name'] is String)
@@ -31,12 +39,76 @@ class GitProjectInfo {
row['ref'] as String,
row['name'] as String,
remote: row['remote'] == true,
+ worktree: row['worktree'] is String
+ ? row['worktree'] as String
+ : null,
),
],
);
final bool isGit;
final String? branch, error;
final List<GitBranch> branches;
+
+ /// Set only for a folder inside a linked worktree: the same folder in the
+ /// repository's main checkout, and the branch that checkout is on.
+ final String? mainFolder, mainBranch;
+}
+
+/// One entry of `git worktree list --porcelain`. The main checkout is first.
+typedef _Worktree = ({String path, String? ref, bool usable});
+
+List<_Worktree> _parseWorktrees(String output) => [
+ for (final block in output.split(RegExp(r'\n\s*\n')))
+ if (block
+ .split('\n')
+ .where((line) => line.startsWith('worktree '))
+ .firstOrNull
+ case final line?)
+ (
+ path: line.substring('worktree '.length),
+ ref: block
+ .split('\n')
+ .where((line) => line.startsWith('branch '))
+ .firstOrNull
+ ?.substring('branch '.length),
+ // A bare repository has no files, and a prunable entry lost its folder.
+ usable: !block
+ .split('\n')
+ .any((line) => line == 'bare' || line.startsWith('prunable')),
+ ),
+];
+
+Future<String> _realPath(String path) async {
+ try {
+ return await Directory(path).resolveSymbolicLinks();
+ } on FileSystemException {
+ return p.normalize(path);
+ }
+}
+
+/// The main checkout, when [root] is one of its linked worktrees.
+Future<String?> _mainCheckout(String root, List<_Worktree> trees) async {
+ if (trees.length < 2 || !trees.first.usable) return null;
+ final here = await _realPath(root);
+ if (await _realPath(trees.first.path) == here) return null;
+ for (final tree in trees.skip(1)) {
+ if (await _realPath(tree.path) == here) return trees.first.path;
+ }
+ return null;
+}
+
+/// `claude-0922-1136`: the harness and the local time, short enough to read as
+/// a branch. The worktree's folder is named the same and nobody needs to see it.
+String worktreeName(String label, DateTime at) {
+ String two(int n) => n.toString().padLeft(2, '0');
+ var slug = label
+ .toLowerCase()
+ .replaceAll(RegExp(r'[^a-z0-9]+'), '-')
+ .replaceAll(RegExp(r'^-+|-+$'), '');
+ if (slug.length > 40) {
+ slug = slug.substring(0, 40).replaceAll(RegExp(r'-+$'), '');
+ }
+ return '${slug.isEmpty ? 'harness' : slug}-${two(at.month)}${two(at.day)}-${two(at.hour)}${two(at.minute)}';
}
bool validGitPath(String path) =>
@@ -73,14 +145,38 @@ Future<Map<String, dynamic>> readLocalGitProject(
'refs/heads',
'refs/remotes',
]),
+ git(['worktree', 'list', '--porcelain']),
]);
if (results[1].code != 0) return {'error': 'GIT_UNAVAILABLE'};
+ final trees = results[2].code == 0
+ ? _parseWorktrees(results[2].output)
+ : const <_Worktree>[];
+ final checkedOut = {
+ for (final tree in trees)
+ if (tree.usable && tree.ref != null) tree.ref!: tree.path,
+ };
+ // A worktree is a temporary folder. The launcher shows its repository.
+ String? mainFolder, mainBranch;
+ if (await _mainCheckout(root.output, trees) case final main?) {
+ final prefix = await git(['rev-parse', '--show-prefix']);
+ final relative = prefix.code == 0
+ ? prefix.output.replaceFirst(RegExp(r'/$'), '')
+ : '';
+ mainFolder =
+ relative.isNotEmpty &&
+ await Directory(p.join(main, relative)).exists()
+ ? p.join(main, relative)
+ : main;
+ mainBranch = trees.first.ref?.replaceFirst('refs/heads/', '');
+ }
return {
'isGit': true,
'root': root.output,
'branch': results[0].code == 0
? results[0].output.replaceFirst('refs/heads/', '')
: null,
+ 'mainFolder': ?mainFolder,
+ 'mainBranch': ?mainBranch,
'branches': [
for (final line in results[1].output.split('\n'))
if (line.split('\t') case [final ref, final name, ''])
@@ -88,6 +184,7 @@ Future<Map<String, dynamic>> readLocalGitProject(
'ref': ref,
'name': name,
'remote': ref.startsWith('refs/remotes/'),
+ 'worktree': ?checkedOut[ref],
},
],
};
@@ -96,7 +193,9 @@ Future<Map<String, dynamic>> readLocalGitProject(
}
}
-/// Worktrees get a fresh branch. With Worktree off, only an explicitly chosen
+/// Worktrees get a fresh `harness/<name>` branch, in a folder under
+/// `<projectHome>/worktrees/<repository>`. With Worktree off, a branch that
+/// already has a worktree opens there; otherwise only an explicitly chosen
/// local branch can switch the shared folder, using Git's normal protections.
Future<String> prepareGitProject(
String source,
@@ -154,6 +253,13 @@ Future<String> prepareGitProject(
);
}
}
+ String inside(String folder) => relative.isEmpty
+ ? folder
+ : p.join(folder, relative.replaceFirst(RegExp(r'/$'), ''));
+ final listed = await git(['worktree', 'list', '--porcelain']);
+ final trees = listed.code == 0
+ ? _parseWorktrees(listed.output)
+ : const <_Worktree>[];
if (!worktree) {
if (branchRef == null || !branchRef.startsWith('refs/heads/')) {
throw const RepositoryCloneException(
@@ -162,6 +268,15 @@ Future<String> prepareGitProject(
}
final current = await git(['symbolic-ref', '--quiet', 'HEAD']);
if (current.code == 0 && current.output == branchRef) return source;
+ // A branch that already has a worktree is worked on there: Git would
+ // refuse to check it out twice, and the folder is not the person's concern.
+ for (final tree in trees) {
+ if (tree.usable &&
+ tree.ref == branchRef &&
+ await Directory(tree.path).exists()) {
+ return inside(tree.path);
+ }
+ }
final result = await git([
'switch',
'--',
@@ -174,33 +289,66 @@ Future<String> prepareGitProject(
}
return source;
}
- final parent = Directory(p.join(projectHome, 'worktrees'));
- await parent.create(recursive: true);
- final name = projectFolderName(
- '${p.basename(root.output)}-$label',
- (now ?? DateTime.now)(),
- withSeconds: true,
- );
- final destination = await parent.createTemp('$name-');
- final branch = 'harness/${p.basename(destination.path)}';
+ // Grouped by repository, so the leaf only needs the harness and the time.
+ final repository = trees.firstOrNull?.usable == true
+ ? p.basename(trees.first.path)
+ : p.basename(root.output);
+ final taken = await git([
+ 'for-each-ref',
+ '--format=%(refname)',
+ 'refs/heads/harness/',
+ ]);
+ final base = worktreeName(label, (now ?? DateTime.now)());
+ late final String destination, branch;
+ try {
+ final parent = Directory(p.join(projectHome, 'worktrees', repository));
+ await parent.create(recursive: true);
+ for (var attempt = 1; ; attempt++) {
+ if (attempt > 100) {
+ throw FileSystemException('No free worktree name', parent.path);
+ }
+ final name = attempt == 1 ? base : '$base-$attempt';
+ if (taken.output.split('\n').contains('refs/heads/harness/$name')) {
+ continue;
+ }
+ final folder = p.join(parent.path, name);
+ // Directory.create accepts an existing directory; mkdir reserves the
+ // name exclusively, so concurrent starts never share a worktree.
+ if ((await Process.run('mkdir', [folder])).exitCode == 0) {
+ destination = folder;
+ branch = 'harness/$name';
+ break;
+ }
+ if (await FileSystemEntity.type(folder, followLinks: false) ==
+ FileSystemEntityType.notFound) {
+ throw FileSystemException('Could not create folder', folder);
+ }
+ }
+ } on FileSystemException {
+ throw const RepositoryCloneException(
+ 'Could not create a worktree folder. Check folder permissions, then retry.',
+ );
+ } on ProcessException {
+ throw const RepositoryCloneException(
+ 'Could not create a worktree folder. Check folder permissions, then retry.',
+ );
+ }
final result = await git([
'worktree',
'add',
'-b',
branch,
'--',
- destination.path,
+ destination,
head.output,
], timeout: const Duration(minutes: 2));
if (result.code != 0) {
// A partial checkout or branch stays available for recovery.
throw RepositoryCloneException(
- 'Could not create the worktree at ${destination.path}. Check Git and folder permissions, then retry.',
+ 'Could not create the worktree at $destination. Check Git and folder permissions, then retry.',
);
}
- return relative.isEmpty
- ? destination.path
- : p.join(destination.path, relative);
+ return inside(destination);
}
Future<({int code, String output})> _git(
diff --git a/desktop/lib/core/local_git_projects.dart b/desktop/lib/core/local_git_projects.dart
index d3e4d010b..8ef0e01ad 100644
--- a/desktop/lib/core/local_git_projects.dart
+++ b/desktop/lib/core/local_git_projects.dart
@@ -121,7 +121,10 @@ class LocalGitProjects {
? 'Detached ${head.substring(0, 7)}'
: null;
final project = AgentProject.fromJson({
- 'name': p.basename(root),
+ // A linked worktree is named for its repository, not its folder.
+ 'name': p.basename(common) == '.git'
+ ? p.basename(p.dirname(common))
+ : p.basename(root),
'cwd': cwd,
'root': root,
'remote': _origin(config),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index b30e97313..5c3868c1d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -6563,8 +6563,12 @@ class AppNotifier extends ChangeNotifier {
if (_disposed || machineStates[machineId] != machine) return null;
_upsertAgent(machine, agent);
// Apply each creation receipt once, even if its transport result is replayed.
+ // A Git start remembers its repository, never the worktree it made.
final projectPath =
- agent.project?.cwd ?? creation.preparedFolder ?? choices['cwd'];
+ choices['gitSource'] ??
+ agent.project?.cwd ??
+ creation.preparedFolder ??
+ choices['cwd'];
if (projectPath is String && projectPath.isNotEmpty) {
unawaited(projectHistory.select(machineId, projectPath));
}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 626f7ae9a..fb10922d2 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -372,6 +372,21 @@ class NewHarnessController extends ChangeNotifier {
}
if (_disposed || _gitKey != key || revision != _gitRevision) return;
checkingGit = false;
+ // A worktree is a temporary folder, so the launcher shows its repository.
+ // With Worktree off its branch stays chosen and Start reopens that
+ // worktree; otherwise new work starts from the repository's own branch.
+ if (info.mainFolder case final main? when _project.folder == key.$2) {
+ if (_worktree == false && _branchRef == null && info.branch != null) {
+ _branchRef = 'refs/heads/${info.branch}';
+ }
+ _project = NewHarnessProject.folder(main);
+ _gitKey = (key.$1, main, key.$3);
+ info = GitProjectInfo(
+ isGit: true,
+ branch: info.mainBranch,
+ branches: info.branches,
+ );
+ }
_gitProject = info;
// Keep an explicit branch choice; a removed branch fails at Start.
if (_branchRef == null &&
@@ -1746,6 +1761,8 @@ class NewHarnessController extends ChangeNotifier {
Iterable<String> _recentProjectFolders() sync* {
final machine = _machine;
final seen = <String>{};
+ // Worktrees Start made are temporary: their repository is the project.
+ final worktrees = _expand('~/harnesses/worktrees');
for (final folder in [
?_project.folder,
...app.projectHistory.recent(_machineId),
@@ -1757,7 +1774,8 @@ class NewHarnessController extends ChangeNotifier {
]) {
if (!p.isAbsolute(folder) ||
folder.length > 4096 ||
- RegExp(r'[\x00-\x1f\x7f]').hasMatch(folder)) {
+ RegExp(r'[\x00-\x1f\x7f]').hasMatch(folder) ||
+ folder != _project.folder && p.isWithin(worktrees, folder)) {
continue;
}
if (seen.add(p.normalize(folder))) yield folder;
diff --git a/desktop/test/git_worktree_failures_test.dart b/desktop/test/git_worktree_failures_test.dart
index 11ca18214..81053460d 100644
--- a/desktop/test/git_worktree_failures_test.dart
+++ b/desktop/test/git_worktree_failures_test.dart
@@ -111,7 +111,7 @@ void main() {
return _GitProcess(output: '/repo with spaces\n');
},
);
- expect(calls, hasLength(3));
+ expect(calls, hasLength(4));
expect(
calls.any((args) => args.contains('switch') || args.contains('fetch')),
false,
@@ -159,7 +159,7 @@ void main() {
),
),
);
- final parent = Directory('${root.path}/worktrees');
+ final parent = Directory('${root.path}/worktrees/repo');
expect(
await parent.list().where((entity) => entity is Directory).length,
1,
diff --git a/desktop/test/git_worktree_test.dart b/desktop/test/git_worktree_test.dart
index b82e847b9..6175427d8 100644
--- a/desktop/test/git_worktree_test.dart
+++ b/desktop/test/git_worktree_test.dart
@@ -105,7 +105,7 @@ void main() {
},
);
- test('branch switching protects dirty changes and branches checked out elsewhere', () async {
+ test('branch switching protects dirty changes', () async {
Future<String> switchTo(String branch) => ProjectFolderRequest.branch(
repo,
'refs/heads/$branch',
@@ -123,10 +123,73 @@ void main() {
expect(await git(['branch', '--show-current']), 'feature');
expect(await git(['stash', 'list']), isEmpty);
expect(await switchTo('feature'), repo);
- await git(['worktree', 'add', p.join(root.path, 'other'), 'main']);
- await expectLater(
- switchTo('main'),
- throwsA(isA<RepositoryCloneException>()),
+ });
+
+ Future<String> real(String path) => Directory(path).resolveSymbolicLinks();
+
+ test('a branch checked out in another worktree opens there', () async {
+ final other = p.join(root.path, 'other');
+ await git(['worktree', 'add', other, 'feature']);
+ final path = await ProjectFolderRequest.branch(
+ p.join(repo, 'src'),
+ 'refs/heads/feature',
+ ).prepareLocal(projectHome: root.path);
+ expect(await real(path), await real(p.join(other, 'src')));
+ expect(await git(['branch', '--show-current']), 'main');
+ });
+
+ test(
+ 'worktrees are named for the harness and the time, grouped by repository',
+ () async {
+ await git(['branch', 'harness/codex-0921-1200-2', 'main']);
+ final paths = [await worktree(), await worktree()];
+ final folder = p.join(
+ root.path,
+ 'harnesses',
+ 'worktrees',
+ 'project with spaces',
+ );
+ expect(paths, [
+ p.join(folder, 'codex-0921-1200'),
+ p.join(folder, 'codex-0921-1200-3'),
+ ]);
+ for (final path in paths) {
+ expect(
+ await git(['branch', '--show-current'], path),
+ 'harness/${p.basename(path)}',
+ );
+ }
+ },
+ );
+
+ test('a linked worktree reads as its repository, and new worktrees from it join that repository', () async {
+ final linked = await worktree();
+ final info = GitProjectInfo.fromJson(
+ await readLocalGitProject(p.join(linked, 'src')),
+ );
+ expect(info.branch, 'harness/codex-0921-1200');
+ expect(info.mainBranch, 'main');
+ expect(await real(info.mainFolder!), await real(p.join(repo, 'src')));
+ final branches = {for (final b in info.branches) b.name: b.worktree};
+ expect(
+ await real(branches['harness/codex-0921-1200']!),
+ await real(linked),
+ );
+ expect(await real(branches['main']!), await real(repo));
+ expect(branches['origin/feature'], isNull);
+ expect(
+ GitProjectInfo.fromJson(await readLocalGitProject(repo)).mainFolder,
+ isNull,
+ );
+ expect(
+ await worktree(folder: linked),
+ p.join(
+ root.path,
+ 'harnesses',
+ 'worktrees',
+ 'project with spaces',
+ 'codex-0921-1200-2',
+ ),
);
});
diff --git a/desktop/test/local_git_projects_test.dart b/desktop/test/local_git_projects_test.dart
index 5665de880..138ac3fd8 100644
--- a/desktop/test/local_git_projects_test.dart
+++ b/desktop/test/local_git_projects_test.dart
@@ -424,6 +424,12 @@ void main() {
expect(project.remote, 'github.com/team/repo');
expect(reader.cached(tree.path)!.remote, project.remote);
expect(reader.cached(tree.path)!.branch, 'feature/login');
+ expect(project.name, 'repo');
+ expect(
+ reader.cached(tree.path)!.name,
+ 'repo',
+ reason: 'A linked worktree is named for its repository.',
+ );
await reader.read(tree.path);
expect(reader.cached('$root/repo/src'), same(project));
await File('${meta.path}/HEAD')
diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dart
index e01ff03e7..77109aa66 100644
--- a/desktop/test/new_harness_git_test.dart
+++ b/desktop/test/new_harness_git_test.dart
@@ -38,6 +38,7 @@ class _Connection extends WsConn {
final starts = <Map<String, dynamic>>[];
final reads = <String>[];
final pending = <String, Completer<Map<String, dynamic>>>{};
+ final answers = <String, Map<String, dynamic>>{};
Map<String, dynamic>? failure;
bool loseReply = false;
@override
@@ -50,7 +51,9 @@ class _Connection extends WsConn {
final path = payload['path'] as String;
reads.add(path);
return pending[path]?.future ??
- Future.value(path == '/plain' ? {'isGit': false} : _git);
+ Future.value(
+ answers[path] ?? (path == '/plain' ? {'isGit': false} : _git),
+ );
}
if (type == 'engines_probe') return {'engines': []};
if (type == 'dsh_list') return {'dsh': []};
@@ -77,7 +80,12 @@ class _Connection extends WsConn {
'id': 'created',
'name': 'Created',
'engine': 'codex',
- 'project': {'cwd': payload['cwd'] ?? '/worktrees/new'},
+ 'project': {
+ 'name': 'repo',
+ 'cwd':
+ payload['cwd'] ??
+ '/home/user/harnesses/worktrees/repo/codex-0922-1136',
+ },
},
};
}
@@ -212,6 +220,87 @@ void main() {
expect(connection.starts.last['gitSource'], '/prepared');
});
+ Map<String, dynamic> linked(String branch) => {
+ ..._git,
+ 'branch': branch,
+ 'mainFolder': '/repo',
+ 'mainBranch': 'main',
+ };
+
+ test(
+ 'a worktree folder opens as its repository, on the repository branch',
+ () async {
+ const folder = '/harnesses/worktrees/repo/claude-0922-1136';
+ final connection = _Connection()
+ ..answers[folder] = linked('harness/claude-0922-1136');
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: folder,
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await settle();
+ expect(box.project.folder, '/repo');
+ expect(box.worktree, true);
+ expect(box.branchLabel, 'main');
+ expect(box.projectFolderRequest!.payload, {
+ 'projectSource': 'worktree',
+ 'gitSource': '/repo',
+ 'branchRef': 'refs/heads/main',
+ });
+ expect(connection.reads, [folder], reason: 'Branches are shared.');
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(app.projectHistory.recent('m'), ['/repo']);
+ final next = NewHarnessController(app, machineId: 'm', engine: 'codex');
+ addTearDown(next.dispose);
+ await settle();
+ next.focusField(NewHarnessField.projectMenu);
+ final folders = [for (final row in next.options) ?row.project?.folder];
+ expect(folders, contains('/repo'));
+ expect(
+ folders.where((folder) => folder.contains('/harnesses/worktrees/')),
+ isEmpty,
+ reason: 'A worktree Start made is not a project to pick again.',
+ );
+ },
+ );
+
+ test('a refused launch in a new worktree retries on its branch', () async {
+ const prepared = '/harnesses/worktrees/repo/codex-0922-1136';
+ final connection = _Connection()
+ ..answers[prepared] = linked('harness/codex-0922-1136')
+ ..failure = {
+ 'preparedFolder': prepared,
+ 'failure': {'code': 'TMUX_UNAVAILABLE'},
+ };
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/repo',
+ );
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await settle();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ await settle();
+ expect(box.project.folder, '/repo');
+ expect(box.worktree, false);
+ expect(box.branchLabel, 'harness/codex-0922-1136');
+ connection.failure = null;
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.starts.last, containsPair('projectSource', 'branch'));
+ expect(connection.starts.last, containsPair('gitSource', '/repo'));
+ expect(
+ connection.starts.last,
+ containsPair('branchRef', 'refs/heads/harness/codex-0922-1136'),
+ );
+ });
+
testWidgets(
'compact launch, checkbox controls, hover selection, branch search and Cmd-Enter start',
(tester) async {