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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: worktrees known by folder and branch; branches named after the session (#212)
Dee475d9b65e2b3
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0bdb7ecf1..e02b02bf5 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -44,7 +44,7 @@ import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseForimport { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'import { DeviceLink } from './device/deviceLink.js'import { DeviceFleet } from './device/deviceFleet.js'-import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'+import { registry, projectDisplayName, sessionDisplayTitle, type RegisteredSession } from './lib/registry.js'import { engineSessionTitle } from './lib/sessionTitle.js'import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'@@ -88,6 +88,9 @@ import { forkName, planFork } from './lib/forkAgent.js'import { restoreAgents } from './lib/restoreAgents.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'+import { sweepWorktrees } from './lib/worktreeSweep.js'+import { nameBranchAfterSession } from './lib/branchNaming.js'+import { forgetAgentProject } from './lib/agentProject.js'import { createStopAgentService } from './lib/stopAgentService.js'import { createResumeAgentService } from './lib/resumeAgentService.js'import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'@@ -1658,7 +1661,26 @@ async function runForeground(session: AuthSession): Promise<void> {dshFrames.delete(agentId)}+ // A worktree branch Harness made up at Start takes its session's name once it has one+ // (lib/branchNaming.ts). Each agent is looked at once per daemon; the git reads are the cost.+ const branchNamed = new Set<string>()+ const nameSessionBranches = (): void => {+ for (const session of registry.list()) {+ const title = sessionDisplayTitle(session)+ if (!title || !session.cwd || branchNamed.has(session.agentId)) continue+ branchNamed.add(session.agentId)+ const cwd = session.cwd+ void nameBranchAfterSession(cwd, title).then((renamed) => {+ if (!renamed) return+ console.log(`[worktrees] agent ${sid(session.agentId)} branch named ${renamed}`)+ forgetAgentProject(cwd)+ const current = registry.byAgent(session.agentId)+ if (current) syncSession(current)+ }).catch(() => {})+ }+ }const syncTerminalTitles = async (): Promise<void> => {+ nameSessionBranches()const titles = await terminals.titles()if (titles.size === 0) returnfor (const session of registry.list()) {@@ -5445,6 +5467,19 @@ async function runForeground(session: AuthSession): Promise<void> {backend.onDirectDeviceRevoked = fp => autonomousDeviceDirect?.revoked(fp)autonomousDeviceDirect.start()+ // Worktrees Harness made that no live or stopped harness uses and nothing would miss+ // (lib/worktreeSweep.ts): a few minutes after start, once restored agents are back in the+ // registry, then twice a day.+ const sweepUnusedWorktrees = () => {+ let inUse: Array<string | null>+ try { inUse = [...registry.list().map(s => s.cwd), ...stoppedAgents.list().map(s => s.cwd)] } catch { return }+ void sweepWorktrees({ root: join(homedir(), 'harnesses'), inUse })+ .then(removed => { if (removed.length) console.log(`[worktrees] removed ${removed.length} unused worktree(s)`) })+ .catch(() => {})+ }+ setTimeout(sweepUnusedWorktrees, 5 * 60_000).unref()+ setInterval(sweepUnusedWorktrees, 12 * 3600_000).unref()+// Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting// again at each call site: a new event kind reaches the dial the day it reaches the socket.diff --git a/cli/src/lib/agentNames.ts b/cli/src/lib/agentNames.tsindex 369462ac0..dbdf0e0b5 100644--- a/cli/src/lib/agentNames.ts+++ b/cli/src/lib/agentNames.ts@@ -63,13 +63,53 @@ 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+/** Two plain words for a branch nothing has named yet — plumbing, like the worktree's folder: the+ * agent or the person names the real branch when there is something to push. Mirrors* 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())}`+export const PLACEHOLDER_ADJECTIVES = [+ 'amber', 'bold', 'brave', 'brisk', 'calm', 'clever', 'cosmic', 'crisp', 'dapper', 'eager', 'fancy', 'gentle',+ 'glad', 'golden', 'happy', 'hidden', 'jolly', 'keen', 'kind', 'lively', 'lucky', 'merry', 'misty', 'noble',+ 'polite', 'proud', 'quick', 'quiet', 'rapid', 'rosy', 'royal', 'rustic', 'shiny', 'silent', 'silver', 'sleek',+ 'smart', 'snowy', 'solar', 'spry', 'steady', 'sunny', 'swift', 'tidy', 'vivid', 'warm', 'witty', 'zesty',+] as const+export const PLACEHOLDER_NOUNS = [+ 'badger', 'beacon', 'birch', 'bison', 'canyon', 'cedar', 'comet', 'coral', 'crane', 'delta', 'falcon', 'fern',+ 'finch', 'fjord', 'fox', 'gecko', 'glacier', 'harbor', 'hawk', 'heron', 'ibis', 'island', 'koala', 'lagoon',+ 'lark', 'lynx', 'maple', 'meadow', 'meteor', 'moose', 'nebula', 'otter', 'owl', 'panda', 'pebble', 'pine',+ 'puffin', 'quartz', 'raven', 'reef', 'river', 'robin', 'sparrow', 'spruce', 'tiger', 'walrus', 'willow', 'zebra',+] as const++/** `brave-otter`: the branch a new worktree starts on until its session has a name, one none of+ * `taken` (branch names, with or without `refs/heads/`) already uses. */+export function placeholderBranch(taken: Iterable<string>, pick = (n: number) => Math.floor(Math.random() * n)): string {+ const names = new Set([...taken].map(name => name.replace(/^refs\/heads\//, '')))+ const draw = () => `${PLACEHOLDER_ADJECTIVES[pick(PLACEHOLDER_ADJECTIVES.length)]}-${PLACEHOLDER_NOUNS[pick(PLACEHOLDER_NOUNS.length)]}`+ let name = draw()+ for (let tries = 0; tries < 16 && names.has(name); tries++) name = draw()+ const base = name+ for (let suffix = 2; names.has(name); suffix++) name = `${base}-${suffix}`+ return name+}++/** The folder a worktree on `branch` is checked out in, under its repository: the branch's last part.+ * Nobody needs to see it, and it keeps its name when the branch is renamed. */+export function worktreeFolderName(branch: string): string {+ const name = (branch.split('/').pop() ?? '').replace(/[^A-Za-z0-9._-]+/g, '').replace(/^[.-]+/, '')+ return name ? name.slice(0, 64) : 'worktree'+}++/** A session's name as a branch's last part: `Worktree and branches organization` →+ * `worktree-and-branches-organization`, cut at a word to 48 characters. Null when nothing is left. */+export function sessionBranchSlug(title: string | null | undefined): string | null {+ let slug = (title ?? '').normalize('NFKD').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')+ if (slug.length > 48) slug = slug.slice(0, 48).replace(/-[^-]*$/, '') || slug.slice(0, 48)+ return slug || null+}++/** A name Git might accept for a new branch, checked before Git is asked. */+export function plausibleBranchName(name: unknown): name is string {+ return typeof name === 'string' && name.length > 0 && name.length <= 255 && !name.startsWith('-')+ && !/[\x00-\x20\x7f~^:?*[\\]/.test(name)}/** The folder for a project somebody named: their words with spaces as dashes and nothing a path ordiff --git a/cli/src/lib/agentProject.spec.ts b/cli/src/lib/agentProject.spec.tsindex 02750f2b7..c0fe99ae0 100644--- a/cli/src/lib/agentProject.spec.ts+++ b/cli/src/lib/agentProject.spec.ts@@ -37,8 +37,14 @@ describe('owning-machine project metadata', () => {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(linked)).toMatchObject({ name: 'app', root: await realpath(linked), branch: 'harness/claude-0922-1136', worktree: true })expect(await agentProject(repo)).toMatchObject({ name: 'app', branch: 'main' })+ expect(await agentProject(repo)).not.toHaveProperty('worktree')+ expect(await agentProject(linked)).not.toHaveProperty('branchPending')+ git('config', 'branch.harness/claude-0922-1136.harness', 'placeholder')+ expect(await agentProject(linked, Date.now() + 20_000)).toMatchObject({ branchPending: true })+ git('checkout', '--quiet', '--detach')+ expect((await agentProject(repo, Date.now() + 20_000))?.branch).toMatch(/^Detached [0-9a-f]{7,}$/)})it('keeps a non-repository project branchless and rejects absent cwd', async () => {const root = await mkdtemp(join(tmpdir(), 'harness-v2-folder-')); roots.push(root)diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.tsindex 54ecf8740..cc2a2024d 100644--- a/cli/src/lib/agentProject.ts+++ b/cli/src/lib/agentProject.ts@@ -9,6 +9,10 @@ export type AgentProject = {root: string | nullremote: string | nullbranch: string | null+ /** Inside a linked worktree rather than the repository's own checkout. */+ worktree?: true+ /** The branch still has the name Harness made up at Start; the session's replaces it. */+ branchPending?: true}/** Compare remote repositories without publishing embedded credentials or transport syntax. */@@ -50,11 +54,19 @@ async function inspect(cwd: string): Promise<AgentProject> {const root = await git(cwd, ['rev-parse', '--show-toplevel'])if (!root) return { name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }const remote = await git(cwd, ['config', '--get', 'remote.origin.url'])+ // A checkout on no branch still says where it is, as the desktop's own reader does.const branch = await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD'])+ ?? await git(cwd, ['rev-parse', '--short', 'HEAD']).then(sha => sha && `Detached ${sha}`)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 }+ const pending = branch && !branch.startsWith('Detached ')+ ? await git(cwd, ['config', '--get', `branch.${branch}.harness`]) === 'placeholder'+ : false+ return {+ name: basename(main), cwd, root, remote: canonicalRepository(remote), branch,+ ...(main !== root ? { worktree: true as const } : {}), ...(pending ? { branchPending: true as const } : {}),+ }} finally {const next = waiting.shift()if (next) next()@@ -62,6 +74,11 @@ async function inspect(cwd: string): Promise<AgentProject> {}}+/** Forget what was read for `cwd`, as after renaming its branch. */+export function forgetAgentProject(cwd: string): void {+ cache.delete(cwd)+}+export function agentProject(cwd: string | null, now = Date.now()): Promise<AgentProject | null> {if (!cwd || !isAbsolute(cwd) || cwd.length > 4096 || /[\x00-\x1f\x7f]/.test(cwd)) return Promise.resolve(null)const found = cache.get(cwd)diff --git a/cli/src/lib/branchNaming.ts b/cli/src/lib/branchNaming.tsnew file mode 100644index 000000000..e601108d8--- /dev/null+++ b/cli/src/lib/branchNaming.ts@@ -0,0 +1,45 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { sessionBranchSlug } from './agentNames.js'+import { HARNESS_BRANCH_KEY } from './gitProject.js'++const exec = promisify(execFile)++async function git(cwd: string, args: string[]): Promise<string> {+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE']) delete (env as NodeJS.ProcessEnv)[key]+ return (await exec('git', ['-C', cwd, ...args], { timeout: 10_000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024, env }))+ .stdout.replace(/\r?\n$/, '')+}++/**+ * Names a worktree's branch after its session, once: `brave-otter`, made up at Start, becomes+ * `worktree-and-branches-organization` when the session first has a name. A name a local or remote+ * branch already has gets `-2`. Only a branch Harness+ * marked as a placeholder, with no upstream, is renamed; the mark goes with it, so a later session name,+ * a push, or a rename by the person or the agent is never overridden. Returns the new name, if any.+ */+export async function nameBranchAfterSession(cwd: string, title: string | null): Promise<string | null> {+ const slug = sessionBranchSlug(title)+ if (!slug) return null+ const branch = await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => null)+ if (!branch) return null+ const mark = await git(cwd, ['config', '--get', `branch.${branch}.${HARNESS_BRANCH_KEY}`]).catch(() => null)+ if (mark !== 'placeholder') return null+ if (await git(cwd, ['config', '--get', `branch.${branch}.remote`]).then(() => true, () => false)) return null+ const base = slug+ // Taken here, or on a remote: a name somebody else pushed is not one to push over.+ const known = new Set((await git(cwd, ['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes']).catch(() => ''))+ .split('\n').flatMap(ref => ref.startsWith('refs/heads/') ? [ref.slice(11)]+ : ref.startsWith('refs/remotes/') ? [ref.split('/').slice(3).join('/')] : []))+ for (let attempt = 1; attempt <= 50; attempt++) {+ const name = attempt === 1 ? base : `${base}-${attempt}`+ if (name === branch) return null+ if (known.has(name)) continue+ try { await git(cwd, ['check-ref-format', '--branch', name]) } catch { return null }+ await git(cwd, ['branch', '-m', branch, name])+ await git(cwd, ['config', `branch.${name}.${HARNESS_BRANCH_KEY}`, 'created']).catch(() => '')+ return name+ }+ return null+}diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.tsindex aee210680..a382d3520 100644--- a/cli/src/lib/gitProject.spec.ts+++ b/cli/src/lib/gitProject.spec.ts@@ -1,15 +1,18 @@import { execFile } from 'node:child_process'import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'-import { basename, join } from 'node:path'+import { 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'+import { placeholderBranch, sessionBranchSlug, worktreeFolderName } from './agentNames.js'+import { nameBranchAfterSession } from './branchNaming.js'import { prepareGitProject, readGitProject, validGitPath } from './gitProject.js'import { parseProjectFolder, prepareProjectFolder } from './projectFolder.js'const exec = promisify(execFile)-describe('launch Git preparation', () => {+// Real Git, several worktrees a test: slower than the default 5s under a full, parallel run.+describe('launch Git preparation', { timeout: 30_000 }, () => {let root: string, repo: stringconst git = async (...args: string[]) => (await exec('git', ['-C', repo, ...args])).stdout.trim()beforeEach(async () => {@@ -34,8 +37,10 @@ describe('launch Git preparation', () => {})afterEach(async () => { vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }) })const options = () => ({ root: join(root, 'harnesses'), label: 'Codex', now: () => new Date(2026, 8, 21, 12, 0) })- const prepare = (source: 'worktree' | 'branch', branchRef = 'refs/heads/feature', path = repo) =>- prepareProjectFolder(parseProjectFolder({ projectSource: source, gitSource: path, branchRef })!, options())+ const prepare = (source: 'worktree' | 'branch', branchRef = 'refs/heads/feature', path = repo, extra: Record<string, unknown> = {}) =>+ prepareProjectFolder(parseProjectFolder({ projectSource: source, gitSource: path, branchRef, ...extra })!, options())+ const worktrees = () => join(root, 'harnesses', 'worktrees', 'project with spaces')+ const current = async (path: string) => (await exec('git', ['-C', path, 'branch', '--show-current'])).stdout.trim()it('encrypts Git metadata requests and replies', () => {expect(encryptDownFrame('git_project_info')).toBe(true)@@ -62,7 +67,7 @@ describe('launch Git preparation', () => {for (const path of paths) {expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('feature')const branch = (await exec('git', ['-C', path, 'branch', '--show-current'])).stdout.trim()- expect(branch).toMatch(/^harness\//)+ expect(branch).toMatch(/^[a-z]+-[a-z]+(-\d+)?$/)branches.push(branch)}expect(new Set(branches).size).toBe(2)@@ -70,27 +75,135 @@ 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('makes up a two-word branch no branch uses, in a folder named for it, grouped by repository', async () => {+ expect(placeholderBranch([], () => 0)).toBe('amber-badger')+ expect(placeholderBranch(['refs/heads/amber-badger', 'amber-badger-2'], () => 0)).toBe('amber-badger-3')+ expect(worktreeFolderName('deehw/brave-otter')).toBe('brave-otter')+ expect(worktreeFolderName('fix/login page')).toBe('loginpage')+ expect(sessionBranchSlug('Worktree and branches organization')).toBe('worktree-and-branches-organization')+ expect(sessionBranchSlug('✳ Fix: the login page — redirects twice?')).toBe('fix-the-login-page-redirects-twice')+ expect(sessionBranchSlug('a'.repeat(30) + ' ' + 'b'.repeat(30))).toBe('a'.repeat(30))+ expect(sessionBranchSlug('✳ ✳')).toBeNull()+ const made = [await prepare('worktree'), await prepare('worktree')]+ expect(new Set(made).size).toBe(2)+ for (const path of made) {+ const branch = await current(path)+ expect(branch).toMatch(/^[a-z]+-[a-z]+(-\d+)?$/)+ expect(path).toBe(join(worktrees(), worktreeFolderName(branch)))+ expect(await git('config', '--get', `branch.${branch}.harness`)).toBe('placeholder')}})+ it('creates a named branch once, and refuses names Git would not take', async () => {+ const named = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'fix/login' })+ expect(named).toBe(join(worktrees(), 'login'))+ expect(await current(named)).toBe('fix/login')+ expect(await git('config', '--get', 'branch.fix/login.harness')).toBe('created')+ const made = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'quiet-owl', branchMode: 'placeholder' })+ expect(await current(made)).toBe('quiet-owl')+ expect(await git('config', '--get', 'branch.quiet-owl.harness')).toBe('placeholder')+ const info = await readGitProject(repo) as { branches: Array<{ name: string; harness?: true }> }+ expect(info.branches.filter(b => b.harness).map(b => b.name).sort()).toEqual(['fix/login', 'quiet-owl'])+ await expect(prepare('worktree', 'refs/heads/feature', repo, { branchName: 'fix/login' })).rejects.toMatchObject({ code: 'BRANCH_EXISTS' })+ await expect(prepare('worktree', 'refs/heads/feature', repo, { branchName: 'bad..name' })).rejects.toMatchObject({ code: 'INVALID_BRANCH' })+ for (const extra of [{ branchName: '-x' }, { branchName: 'a b' }, { branchName: 'ok', branchMode: 'other' }]) {+ expect(() => parseProjectFolder({ projectSource: 'worktree', gitSource: repo, ...extra })).toThrow()+ }+ })++ it('makes a new branch for the folder itself, keeping its uncommitted work, and refuses one that exists', async () => {+ await writeFile(join(repo, 'src', 'value'), 'in progress')+ expect(await prepare('branch', 'refs/heads/login-fix', repo, { branchName: 'login-fix' })).toBe(repo)+ expect(await git('branch', '--show-current')).toBe('login-fix')+ expect(await readFile(join(repo, 'src', 'value'), 'utf8')).toBe('in progress')+ await expect(prepare('branch', 'refs/heads/feature', repo, { branchName: 'feature' })).rejects.toMatchObject({ code: 'BRANCH_EXISTS' })+ expect(() => parseProjectFolder({ projectSource: 'branch', gitSource: repo, branchRef: 'refs/heads/other', branchName: 'login-fix' })).toThrow()+ })++ it('names a made-up worktree branch after its session once, and never a pushed or chosen one', async () => {+ const path = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'quiet-owl', branchMode: 'placeholder' })+ expect(await nameBranchAfterSession(path, null)).toBeNull()+ expect(await nameBranchAfterSession(path, 'Worktree and branches organization')).toBe('worktree-and-branches-organization')+ expect(await current(path)).toBe('worktree-and-branches-organization')+ expect(await git('config', '--get', 'branch.worktree-and-branches-organization.harness')).toBe('created')+ expect(await nameBranchAfterSession(path, 'A later name')).toBeNull()+ expect(await current(path)).toBe('worktree-and-branches-organization')+ const second = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'calm-fox', branchMode: 'placeholder' })+ expect(await nameBranchAfterSession(second, 'Worktree and branches organization')).toBe('worktree-and-branches-organization-2')+ // A name a remote has is taken too.+ const third = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'quiet-fox', branchMode: 'placeholder' })+ await git('update-ref', 'refs/remotes/origin/onboarding-experience', 'main')+ expect(await nameBranchAfterSession(third, 'Onboarding experience')).toBe('onboarding-experience-2')+ const chosen = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'fix/mine' })+ expect(await nameBranchAfterSession(chosen, 'Anything')).toBeNull()+ const pushed = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'sunny-owl', branchMode: 'placeholder' })+ await git('config', 'branch.sunny-owl.remote', 'origin')+ expect(await nameBranchAfterSession(pushed, 'Anything')).toBeNull()+ expect(await current(pushed)).toBe('sunny-owl')+ })++ it('checks out an existing branch as it is in a new worktree, once', async () => {+ await git('branch', 'topic', 'main')+ const path = await prepare('worktree', 'refs/heads/topic', repo, { branchName: 'topic', branchMode: 'existing' })+ expect(path).toBe(join(worktrees(), 'topic'))+ expect(await current(path)).toBe('topic')+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')+ await expect(prepare('worktree', 'refs/heads/topic', repo, { branchName: 'topic', branchMode: 'existing' }))+ .rejects.toMatchObject({ code: 'BRANCH_IN_USE' })+ })++ it('fetches a remote base first, reports the default, and tracks a remote branch under its own name', async () => {+ const origin = join(root, 'origin.git'), upstream = join(root, 'upstream')+ await exec('git', ['clone', '--quiet', '--bare', repo, origin])+ await git('remote', 'add', 'origin', origin)+ await git('fetch', '--quiet', 'origin')+ await git('remote', 'set-head', 'origin', 'main')+ expect(await readGitProject(repo)).toMatchObject({ defaultRef: 'refs/remotes/origin/main' })+ await exec('git', ['clone', '--quiet', origin, upstream])+ const up = (...args: string[]) => exec('git', ['-C', upstream, '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])+ await writeFile(join(upstream, 'src', 'value'), 'pushed')+ await up('commit', '-qam', 'pushed')+ await up('push', '--quiet', 'origin', 'main', 'main:fix/typo')+ await git('fetch', '--quiet', 'origin', 'fix/typo:refs/remotes/origin/fix/typo')+ const fresh = await prepare('worktree', 'refs/remotes/origin/main', repo, { branchName: 'harness/fresh' })+ expect(await readFile(join(fresh, 'src', 'value'), 'utf8')).toBe('pushed')+ await expect(exec('git', ['-C', fresh, 'rev-parse', '--abbrev-ref', '@{upstream}'])).rejects.toThrow()+ // A local branch starts from the newer of itself and its upstream.+ await git('branch', '--set-upstream-to=origin/main', 'main')+ await git('update-ref', 'refs/remotes/origin/main', 'main')+ const behind = await prepare('worktree', 'refs/heads/main', repo, { branchName: 'from-behind' })+ expect(await readFile(join(behind, 'src', 'value'), 'utf8')).toBe('pushed')+ await writeFile(join(repo, 'src', 'value'), 'local')+ await git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '-qam', 'local')+ const ahead = await prepare('worktree', 'refs/heads/main', repo, { branchName: 'from-ahead' })+ expect(await readFile(join(ahead, 'src', 'value'), 'utf8')).toBe('local')+ const tracking = await prepare('worktree', 'refs/remotes/origin/fix/typo', repo, { branchName: 'fix/typo' })+ expect((await exec('git', ['-C', tracking, 'rev-parse', '--abbrev-ref', '@{upstream}'])).stdout.trim()).toBe('origin/fix/typo')+ })++ it('copies ignored files named in .worktreeinclude into new worktrees', async () => {+ await writeFile(join(repo, '.gitignore'), '.env\n*.log\nlocal/\n')+ await writeFile(join(repo, '.worktreeinclude'), '.env\nlocal/\n')+ await writeFile(join(repo, '.env'), 'SECRET=1')+ await writeFile(join(repo, 'debug.log'), 'noise')+ await mkdir(join(repo, 'local'))+ await writeFile(join(repo, 'local', 'settings.json'), '{}')+ const path = await prepare('worktree')+ expect(await readFile(join(path, '.env'), 'utf8')).toBe('SECRET=1')+ expect(await readFile(join(path, 'local', 'settings.json'), 'utf8')).toBe('{}')+ await expect(readFile(join(path, 'debug.log'))).rejects.toThrow()+ })+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 linked = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'harness/linked' })const info = await readGitProject(join(linked, 'src'))- expect(info).toMatchObject({ isGit: true, branch: 'harness/codex-0921-1200', mainBranch: 'main' })+ expect(info).toMatchObject({ isGit: true, branch: 'harness/linked', 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 === 'harness/linked')!.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'))+ expect(await prepare('worktree', 'refs/heads/main', linked, { branchName: 'harness/second' })).toBe(join(worktrees(), 'second'))})it('keeps the selected subfolder in its new worktree', async () => {@@ -109,6 +222,10 @@ describe('launch Git preparation', () => {expect(await git('stash', 'list')).toBe('')// Selecting the current branch is a no-op even with dirty files.expect(await prepare('branch')).toBe(repo)+ await git('checkout', '--', '.')+ await writeFile(join(repo, 'notes.txt'), 'untracked')+ await expect(prepare('branch', 'refs/heads/main')).rejects.toMatchObject({ code: 'BRANCH_SWITCH_FAILED' })+ expect(await git('branch', '--show-current')).toBe('feature')})it('opens a branch checked out elsewhere in its worktree, and refuses missing refs, revision expressions, and untracked subfolders', async () => {@@ -159,7 +276,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).toMatch(/\/worktrees\/project with spaces\/harness-\d{4}-\d{4}$/)+ expect(path).toMatch(/\/worktrees\/project with spaces\/[a-z]+-[a-z]+(-\d+)?$/)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.tsindex 6a0c8ad37..47b9b233e 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, realpath, stat } from 'node:fs/promises'-import { basename, isAbsolute, join, normalize } from 'node:path'+import { cp, lstat, mkdir, realpath, stat, writeFile } from 'node:fs/promises'+import { basename, dirname, isAbsolute, join, normalize } from 'node:path'import { promisify } from 'node:util'-import { worktreeName } from './agentNames.js'+import { placeholderBranch, plausibleBranchName, worktreeFolderName } from './agentNames.js'const exec = promisify(execFile)@@ -38,6 +38,16 @@ function parseWorktrees(output: string): Worktree[] {}]})}+/** `branch.<name>.harness` in the repository's config marks a branch Harness made: `placeholder` while+ * its name waits for the session's, `created` once it has one or was named at Start. */+export const HARNESS_BRANCH_KEY = 'harness'+async function harnessBranches(path: string): Promise<Set<string>> {+ const out = await git(path, ['config', '--get-regexp', `^branch\\..*\\.${HARNESS_BRANCH_KEY}$`]).catch(() => '')+ return new Set(out.split('\n').flatMap(line => {+ const key = line.split(' ')[0] ?? ''+ return key.startsWith('branch.') && key.endsWith(`.${HARNESS_BRANCH_KEY}`) ? [key.slice(7, -(HARNESS_BRANCH_KEY.length + 1))] : []+ }))+}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)@@ -61,45 +71,93 @@ export async function readGitProject(path: string) {return !failure.killed && failure.code === 128 ? { isGit: false, branches: [] } : { error: 'GIT_UNAVAILABLE' }}try {- const [branch, refs, trees] = await Promise.all([+ const [branch, refs, trees, originHead, marked] = 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),+ git(path, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']).catch(() => null),+ harnessBranches(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')if (!ref || !name || symbolic) return []const worktree = checkedOut.get(ref)- return [{ ref, name, remote: ref.startsWith('refs/remotes/'), ...(worktree ? { worktree } : {}) }]+ const harness = !ref.startsWith('refs/remotes/') && (marked.has(name) || name.startsWith('harness/'))+ return [{ ref, name, remote: ref.startsWith('refs/remotes/'), ...(worktree ? { worktree } : {}), ...(harness ? { harness } : {}) }]})+ // Where new work starts by default: the remote's default branch, as a clone names it, else its+ // main or master.+ const known = new Set(branches.map(row => row.ref))+ const defaultRef = [originHead, 'refs/remotes/origin/main', 'refs/remotes/origin/master'].find(ref => ref && known.has(ref))+ const found = { isGit: true, root, branch, branches, ...(defaultRef ? { defaultRef } : {}) }// 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 }+ if (!main) return foundconst prefix = (await git(path, ['rev-parse', '--show-prefix']).catch(() => '')).replace(/\/$/, '')const mainFolder = prefix && await isDirectory(join(main, prefix)) ? join(main, prefix) : mainconst mainBranch = trees[0]!.ref?.replace(/^refs\/heads\//, '')- return { isGit: true, root, branch, branches, mainFolder, ...(mainBranch ? { mainBranch } : {}) }+ return { ...found, mainFolder, ...(mainBranch ? { mainBranch } : {}) }} catch { return { error: 'GIT_UNAVAILABLE' } }}-/** 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 },-): Promise<string> {- if (!validGitPath(source)) throw new GitProjectError('INVALID_PROJECT_SOURCE', 'Choose a Git project folder.')+/** `refs/remotes/origin/fix/typo` → origin, fix/typo, and a refspec updating exactly that ref. */+function remoteBranch(ref: string | undefined): { remote: string; branch: string; refspec: string } | null {+ const match = /^refs\/remotes\/([A-Za-z0-9._][A-Za-z0-9._-]*)\/([A-Za-z0-9._]\S*)$/.exec(ref ?? '')+ if (!match || match[2] === 'HEAD') return null+ return { remote: match[1]!, branch: match[2]!, refspec: `+refs/heads/${match[2]}:refs/remotes/${match[1]}/${match[2]}` }+}++export type GitProjectOptions = {+ root: string+ worktree: boolean+ /** Worktree on: what a new branch starts from. Worktree off: the branch the folder is on. */+ ref?: string+ /** The worktree's branch: created from `ref`, or with `existingBranch` checked out as it is. */+ branchName?: string+ existingBranch?: boolean+ /** `branchName` was made up (`brave-otter`): the session's name replaces it once there is one. */+ placeholder?: boolean+ pick?: (n: number) => number+}++/** Worktree on: a new worktree under `<root>/worktrees/<repository>`, on `branchName` — created from+ * `ref`, or with `existingBranch` an existing local branch checked out as it is. Without a name one+ * is made up (`harness/brave-otter`). A remote base is fetched first, briefly.+ *+ * Worktree off: the folder on the local `ref`. A branch that already has a worktree opens there; any+ * other is switched to, only in a folder with nothing uncommitted. With `branchName` the folder moves+ * to that new branch, made where it is now, uncommitted changes and all. */+export async function prepareGitProject(source: string, options: GitProjectOptions): Promise<string> {+ if (!validGitPath(source) || (options.branchName !== undefined && !plausibleBranchName(options.branchName))+ || (options.existingBranch && !options.branchName)) {+ throw new GitProjectError('INVALID_PROJECT_SOURCE', 'Choose a Git project folder.')+ }+ const existing = options.existingBranch === true+ // A new branch for the folder itself: `ref` names it and does not exist.+ const creating = !options.worktree && !!options.branchName && !existinglet root: string, head: string, prefix: stringtry {root = await git(source, ['rev-parse', '--show-toplevel'])- if (options.ref) {+ if (options.ref && !creating) {if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(options.ref)) throw new Error('Invalid branch')await git(source, ['show-ref', '--verify', '--hash', '--', options.ref])}- head = await git(source, ['rev-parse', '--verify', '--end-of-options', `${options.ref ?? 'HEAD'}^{commit}`])+ // New work starts from where its branch is now, not from the last fetch: a remote branch is+ // fetched; a local one is fetched against its upstream and the newer of the two taken, so nothing+ // only the local one has is lost. Offline, slow or refused, it starts from what is here.+ let start = existing ? `refs/heads/${options.branchName}` : creating ? 'HEAD' : options.ref ?? 'HEAD'+ const remote = options.worktree && !existing ? remoteBranch(options.ref) : null+ const upstream = options.worktree && !existing && !remote && options.ref+ ? await git(source, ['for-each-ref', '--format=%(upstream)', options.ref]).then(ref => remoteBranch(ref) ? ref : null, () => null)+ : null+ const fetch = remote ?? remoteBranch(upstream ?? undefined)+ if (fetch) await git(source, ['fetch', '--quiet', '--no-tags', fetch.remote, fetch.refspec], 10_000).catch(() => '')+ // Behind or level with its upstream: the upstream is the newer.+ if (upstream && options.ref && await git(source, ['merge-base', '--is-ancestor', options.ref, upstream]).then(() => true, () => false)) {+ start = upstream+ }+ head = await git(source, ['rev-parse', '--verify', '--end-of-options', `${start}^{commit}`])prefix = await git(source, ['rev-parse', '--show-prefix'])if (prefix && await git(source, ['cat-file', '-t', `${head}:${prefix.replace(/\/$/, '')}`]) !== 'tree') throw new Error('Missing folder')} catch {@@ -107,44 +165,109 @@ export async function prepareGitProject(}const inside = (folder: string) => prefix ? join(folder, prefix.replace(/\/$/, '')) : folderconst trees = await worktrees(source)+ if (creating) {+ const name = options.branchName!+ if (await git(source, ['show-ref', '--verify', '--quiet', '--', `refs/heads/${name}`]).then(() => true, () => false)) {+ throw new GitProjectError('BRANCH_EXISTS', `A branch named ${name} already exists. Choose it instead.`)+ }+ try { await git(source, ['check-ref-format', '--branch', name]) }+ catch { throw new GitProjectError('INVALID_BRANCH', `${name} is not a valid branch name.`) }+ try { await git(source, ['switch', '-c', name]) }+ catch { throw new GitProjectError('BRANCH_SWITCH_FAILED', `Could not create ${name} here.`) }+ return source+ }if (!options.worktree) {if (!options.ref?.startsWith('refs/heads/')) throw new GitProjectError('INVALID_BRANCH', 'Choose a local branch, or turn Worktree on.')+ 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)+ }+ const status = await git(source, ['status', '--porcelain']).catch(() => null)+ if (status !== '') {+ throw new GitProjectError('BRANCH_SWITCH_FAILED', 'This folder has uncommitted changes. Commit or stash them before switching branches, 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.')}}- // Grouped by repository, so the leaf only needs the harness and the time.+ // Grouped by repository, so the leaf only needs the branch.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 = ''+ const taken = new Set((await git(source, ['for-each-ref', '--format=%(refname)', 'refs/heads']).catch(() => '')).split('\n'))+ const branch = options.branchName ?? placeholderBranch(taken, options.pick)+ const placeholder = !options.branchName || options.placeholder === true+ if (existing) {+ if (!taken.has(`refs/heads/${branch}`)) throw new GitProjectError('GIT_PROJECT_UNAVAILABLE', 'That branch is no longer available. Choose another branch.')+ if (trees.some(tree => tree.ref === `refs/heads/${branch}`)) {+ throw new GitProjectError('BRANCH_IN_USE', `${branch} is checked out in another worktree. Turn Worktree off to open it there.`)+ }+ } else {+ if (taken.has(`refs/heads/${branch}`)) throw new GitProjectError('BRANCH_EXISTS', `A branch named ${branch} already exists. Choose another name.`)+ try { await git(source, ['check-ref-format', '--branch', branch]) }+ catch { throw new GitProjectError('INVALID_BRANCH', `${branch} is not a valid branch name.`) }+ }+ let destination: string | undefinedtry {- const parent = join(options.root, 'worktrees', repository)+ const home = join(options.root, 'worktrees')+ const parent = join(home, repository)await mkdir(parent, { recursive: true })+ // Spotlight would index every checkout again.+ if (process.platform === 'darwin') await writeFile(join(home, '.metadata_never_index'), '').catch(() => {})+ const leaf = worktreeFolderName(branch)// 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}` }+ const folder = join(parent, attempt === 1 ? leaf : `${leaf}-${attempt}`)+ try { await mkdir(folder); destination = folder }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.')+ const remote = remoteBranch(options.ref)try {- await git(source, ['worktree', 'add', '-b', branch, '--', destination, head], 120_000)- return inside(destination)+ await git(source, existing+ ? ['worktree', 'add', '--', destination, branch]+ // A remote branch checked out under its own name tracks it; a new branch from one must not,+ // or it would push onto the base.+ : remote && remote.branch === branch+ ? ['worktree', 'add', '--track', '-b', branch, '--', destination, options.ref!]+ : ['worktree', 'add', '--no-track', '-b', branch, '--', destination, head], 120_000)} 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.`)}+ // Harness made this branch: its cleanup may remove it, and a made-up name gives way to the session's.+ if (!existing) {+ await git(source, ['config', `branch.${branch}.${HARNESS_BRANCH_KEY}`, placeholder ? 'placeholder' : 'created']).catch(() => '')+ }+ await copyIncluded(root, destination)+ return inside(destination)+}++/** `.worktreeinclude` (gitignore syntax) in the repository names ignored files a new worktree needs+ * and Git will not bring: `.env`, local config. Only files both listed and ignored are copied, never+ * over one the checkout has. A copy that fails leaves the worktree as Git made it. */+async function copyIncluded(from: string, to: string): Promise<void> {+ const include = join(from, '.worktreeinclude')+ try {+ if (!(await stat(include)).isFile()) return+ } catch { return }+ const list = (exclude: string) => git(from, ['ls-files', '-z', '--others', '--ignored', '--directory', exclude])+ .then(out => out.split('\0').filter(Boolean), () => [] as string[])+ const [listed, ignored] = await Promise.all([list(`--exclude-from=${include}`), list('--exclude-standard')])+ const isIgnored = (entry: string) => ignored.some(path => path === entry || (path.endsWith('/') && entry.startsWith(path)))+ for (const entry of listed.filter(isIgnored).slice(0, 200)) {+ const relative = entry.replace(/\/$/, '')+ if (relative.split('/').includes('..')) continue+ const target = join(to, relative)+ try { await lstat(target); continue } catch { /* free */ }+ try {+ await mkdir(dirname(target), { recursive: true })+ await cp(join(from, relative), target, { recursive: true, errorOnExist: false, force: false, verbatimSymlinks: true, preserveTimestamps: true })+ } catch { /* the worktree stays as Git made it */ }+ }}diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.tsindex 607cfc225..8392bf0ad 100644--- a/cli/src/lib/projectFolder.ts+++ b/cli/src/lib/projectFolder.ts@@ -2,14 +2,14 @@ import { spawn } from 'node:child_process'import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'import { homedir } from 'node:os'import { join } from 'node:path'-import { projectFolderName, projectFolderSlug } from './agentNames.js'+import { plausibleBranchName, projectFolderName, projectFolderSlug } from './agentNames.js'import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'/** `name` on a new project is what the person called it; without one the folder is named after the* harness and the time. */export type ProjectFolder = { source: 'new'; name?: string } | { source: 'remote'; repositoryUrl: string; name: string }- | { source: 'worktree'; gitSource: string; branchRef?: string }- | { source: 'branch'; gitSource: string; branchRef?: string }+ | { source: 'worktree'; gitSource: string; branchRef?: string; branchName?: string; existingBranch?: boolean; placeholder?: boolean }+ | { source: 'branch'; gitSource: string; branchRef?: string; branchName?: string }export class ProjectFolderError extends Error {constructor(readonly code: string, message: string) { super(message) }@@ -26,6 +26,22 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFol(payload.projectSource === 'branch' && (typeof ref !== 'string' || !ref.startsWith('refs/heads/')))) {throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a Git project and branch.')}+ const name = payload.branchName+ if (payload.projectSource === 'worktree' && name !== undefined) {+ if (!plausibleBranchName(name) || (payload.branchMode !== undefined && payload.branchMode !== 'existing' && payload.branchMode !== 'placeholder')) {+ throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a Git project and branch.')+ }+ return { source: 'worktree', gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}),+ branchName: name, ...(payload.branchMode === 'existing' ? { existingBranch: true } : {}),+ ...(payload.branchMode === 'placeholder' ? { placeholder: true } : {}) }+ }+ // A new branch for the folder itself, named by `branchRef` too.+ if (payload.projectSource === 'branch' && name !== undefined) {+ if (!plausibleBranchName(name) || ref !== `refs/heads/${name}`) {+ throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a Git project and branch.')+ }+ return { source: 'branch', gitSource: payload.gitSource, branchRef: ref, branchName: name }+ }return { source: payload.projectSource, gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}) }}if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) {@@ -78,7 +94,11 @@ export async function prepareProjectFolder(try {if (project.source === 'worktree' || project.source === 'branch') {return await prepareGitProject(project.gitSource, {- root, worktree: project.source === 'worktree', ref: project.branchRef, label: options.label, now: options.now,+ root, worktree: project.source === 'worktree', ref: project.branchRef,+ ...(project.source === 'worktree' && project.branchName ? {+ branchName: project.branchName, existingBranch: project.existingBranch === true, placeholder: project.placeholder === true,+ } : {}),+ ...(project.source === 'branch' && project.branchName ? { branchName: project.branchName } : {}),})}await mkdir(root, { recursive: true })diff --git a/cli/src/lib/worktreeSweep.spec.ts b/cli/src/lib/worktreeSweep.spec.tsnew file mode 100644index 000000000..c66e44664--- /dev/null+++ b/cli/src/lib/worktreeSweep.spec.ts@@ -0,0 +1,95 @@+import { execFile } from 'node:child_process'+import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { sweepWorktrees } from './worktreeSweep.js'++const exec = promisify(execFile)+// Real Git, several worktrees a test: slower than the default 5s under a full, parallel run.+describe('sweeping unused worktrees', { timeout: 30_000 }, () => {+ let root: string, repo: string, home: string+ const git = async (cwd: string, ...args: string[]) => (await exec('git', ['-C', cwd,+ '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])).stdout.trim()+ const later = () => Date.now() + 8 * 24 * 3600_000+ const add = async (name: string, branch: string, from = 'main') => {+ const path = join(home, 'app', name)+ await git(repo, 'worktree', 'add', '--quiet', '-b', branch, path, from)+ return path+ }+ const exists = (path: string) => stat(path).then(() => true, () => false)+ const branches = async () => (await git(repo, 'branch', '--format=%(refname:short)')).split('\n')+ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'harness-sweep-'))+ repo = join(root, 'app')+ home = join(root, 'harnesses', 'worktrees')+ await mkdir(repo)+ await git(repo, 'init', '--quiet', '-b', 'main')+ await writeFile(join(repo, 'file'), 'one')+ await git(repo, 'add', '.')+ await git(repo, 'commit', '--quiet', '-m', 'initial')+ })+ afterEach(() => rm(root, { recursive: true, force: true }))++ it('removes a clean, idle, unused worktree and the harness branch that has nothing of its own', async () => {+ const path = await add('brave-otter', 'harness/brave-otter')+ expect(await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [], now: later() })).toEqual([path])+ expect(await exists(path)).toBe(false)+ expect(await exists(join(home, 'app')), 'the repository folder goes with its last worktree').toBe(false)+ expect(await exists(home), 'the worktrees folder stays').toBe(true)+ expect(await branches()).toEqual(['main'])+ })++ it('keeps worktrees a live or stopped harness uses, recently touched ones, and uncommitted work', async () => {+ const used = await add('used', 'harness/used')+ const recent = await add('recent', 'harness/recent')+ const dirty = await add('dirty', 'harness/dirty')+ await writeFile(join(dirty, 'draft'), 'not committed')+ const old = new Date(Date.now() - 30 * 24 * 3600_000)+ for (const path of [used, dirty]) await utimes(path, old, old)+ const removed = await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [join(used, 'src'), null], now: later() })+ expect(removed).toEqual([recent])+ expect(await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [used], now: Date.now() })).toEqual([])+ expect(await exists(used)).toBe(true)+ expect(await exists(dirty)).toBe(true)+ })++ it('removes a branch Harness marked in the config, whatever its name', async () => {+ const path = await add('quiet-owl', 'deehw/quiet-owl')+ await git(repo, 'config', 'branch.deehw/quiet-owl.harness', 'placeholder')+ expect(await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [], now: later() })).toEqual([path])+ expect(await branches()).toEqual(['main'])+ })++ it('keeps branches with commits of their own, and branches Harness did not name', async () => {+ const own = await add('own', 'harness/own')+ await writeFile(join(own, 'file'), 'two')+ await git(own, 'commit', '--quiet', '-am', 'work')+ await git(repo, 'branch', 'topic')+ const topic = join(home, 'app', 'topic')+ await git(repo, 'worktree', 'add', '--quiet', topic, 'topic')+ const removed = await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [], now: later() })+ expect(removed.sort()).toEqual([own, topic].sort())+ expect(await branches()).toEqual(expect.arrayContaining(['harness/own', 'topic', 'main']))+ })++ it('keeps a detached worktree holding a commit no branch has, and sweeps the flat layout older builds made', async () => {+ const detached = join(home, 'app', 'detached')+ await git(repo, 'worktree', 'add', '--quiet', '--detach', detached, 'main')+ await writeFile(join(detached, 'file'), 'lost?')+ await git(detached, 'commit', '--quiet', '-am', 'only here')+ const flat = join(home, 'app-claude-2026-09-22-11-36-13-abcdef')+ await git(repo, 'worktree', 'add', '--quiet', '-b', 'harness/app-claude-2026-09-22-11-36-13-abcdef', flat, 'main')+ expect(await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [], now: later() })).toEqual([flat])+ expect(await exists(detached)).toBe(true)+ expect(await exists(home)).toBe(true)+ })++ it('ignores a missing worktrees folder and checkouts that are not worktrees', async () => {+ expect(await sweepWorktrees({ root: join(root, 'nothing'), inUse: [] })).toEqual([])+ await mkdir(join(home, 'app', 'plain'), { recursive: true })+ await git(repo, 'clone', '--quiet', repo, join(home, 'clone'))+ expect(await sweepWorktrees({ root: join(root, 'harnesses'), inUse: [], now: later() })).toEqual([])+ })+})diff --git a/cli/src/lib/worktreeSweep.ts b/cli/src/lib/worktreeSweep.tsnew file mode 100644index 000000000..bd34483d5--- /dev/null+++ b/cli/src/lib/worktreeSweep.ts@@ -0,0 +1,93 @@+import { execFile } from 'node:child_process'+import { lstat, readdir, rmdir, stat } from 'node:fs/promises'+import { basename, dirname, join, normalize, resolve, sep } from 'node:path'+import { promisify } from 'node:util'++const exec = promisify(execFile)++/** A week without a commit, a checkout or an index write. */+export const WORKTREE_IDLE_MS = 7 * 24 * 3600_000++async function git(cwd: string, args: string[]): Promise<string> {+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE']) delete (env as NodeJS.ProcessEnv)[key]+ return (await exec('git', ['-C', cwd, ...args], { timeout: 30_000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024, env }))+ .stdout.replace(/\r?\n$/, '')+}++async function isLinkedCheckout(path: string): Promise<boolean> {+ try {+ const [folder, marker] = await Promise.all([lstat(path), lstat(join(path, '.git'))])+ return folder.isDirectory() && marker.isFile()+ } catch { return false }+}++/** Checkouts in Harness's worktrees folder: `<repo>/<name>`, and the flat `<name>` older builds made. */+async function candidates(home: string): Promise<string[]> {+ let entries: string[]+ try { entries = await readdir(home) } catch { return [] }+ const found: string[] = []+ for (const entry of entries.filter(name => !name.startsWith('.'))) {+ const path = join(home, entry)+ if (await isLinkedCheckout(path)) { found.push(path); continue }+ let children: string[] = []+ try { if ((await lstat(path)).isDirectory()) children = await readdir(path) } catch { continue }+ for (const child of children.filter(name => !name.startsWith('.'))) {+ if (await isLinkedCheckout(join(path, child))) found.push(join(path, child))+ }+ }+ return found+}++/**+ * Removes the worktrees Harness made that nothing uses and nothing would miss: under+ * `<root>/worktrees`, no live or stopped harness working in it (a stopped one can be resumed there),+ * nothing uncommitted, untouched for [idleMs], and — on no branch — no commit only it has. The+ * branch stays, unless Harness made it and its commits are all on other branches or the remote. Anything that does not pass is left exactly as it is.+ */+export async function sweepWorktrees(input: {+ root: string+ inUse: Iterable<string | null | undefined>+ now?: number+ idleMs?: number+}): Promise<string[]> {+ const home = join(input.root, 'worktrees')+ const used = [...input.inUse].filter((cwd): cwd is string => typeof cwd === 'string' && cwd.length > 0).map(cwd => normalize(cwd))+ const removed: string[] = []+ for (const path of await candidates(home)) {+ if (used.some(cwd => cwd === path || cwd.startsWith(path + sep))) continue+ try {+ if (!await sweepOne(path, input.now ?? Date.now(), input.idleMs ?? WORKTREE_IDLE_MS)) continue+ removed.push(path)+ // The repository's folder goes with its last worktree; the worktrees folder itself stays.+ if (dirname(path) !== home) await rmdir(dirname(path)).catch(() => {})+ } catch { /* left as it is */ }+ }+ return removed+}++async function sweepOne(path: string, now: number, idleMs: number): Promise<boolean> {+ const gitDir = resolve(path, await git(path, ['rev-parse', '--git-dir']))+ const common = resolve(path, await git(path, ['rev-parse', '--git-common-dir']))+ if (gitDir === common || basename(common) !== '.git') return false+ const main = dirname(common)+ const touched = await Promise.all(+ [path, join(gitDir, 'HEAD'), join(gitDir, 'index'), join(gitDir, 'logs', 'HEAD')]+ .map(file => stat(file).then(info => info.mtimeMs, () => 0)),+ )+ if (now - Math.max(...touched) < idleMs) return false+ if (await git(path, ['status', '--porcelain']) !== '') return false+ const branch = await git(path, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => null)+ if (!branch && await git(path, ['rev-list', '--count', 'HEAD', '--not', '--branches', '--remotes']) !== '0') return false+ await git(main, ['worktree', 'remove', '--', path])+ const name = branch?.slice('refs/heads/'.length)+ // Only a branch Harness made: marked in the repository's config, or named `harness/…` by older builds.+ const made = name !== undefined && (name.startsWith('harness/')+ || await git(main, ['config', '--get', `branch.${name}.harness`]).then(Boolean, () => false))+ if (branch && name && made) {+ // `--exclude` before `--branches` matches names without `refs/heads/`.+ const unique = await git(main, ['rev-list', '--count', branch, '--not', `--exclude=${name}`, '--branches', '--remotes']).catch(() => null)+ if (unique === '0') await git(main, ['branch', '-D', name]).catch(() => {})+ }+ return true+}diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.mdindex 4be689140..6f86fc87a 100644--- a/desktop/design/new-harness-entry-rules.md+++ b/desktop/design/new-harness-entry-rules.md@@ -32,28 +32,70 @@ while a pending start needs confirmation.## Git projects-Git projects show Branch and Worktree. Worktree defaults to `[x]` for each new-project context; Enter, Space, or a click toggles `[x]` and `[ ]`. Folders without-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 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.+Git projects show Branch, then Worktree. Worktree defaults to `[x]` for a+repository with a commit; Enter, Space, or a click toggles `[x]` and `[ ]`.+Folders without 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 the+folder it was started in and its repository's branch. Pane headers read+`folder › branch`, with the machine first only for another computer: the folder+the harness started in (a subfolder as itself, a checkout's root — a+worktree's too — as its repository), which does not follow the agent's shell,+and the branch with the same icon everywhere. Worktree folders are never shown;+the header's tooltip has the full path. Cut short, the folder shortens in the+middle before the branch does. 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, so Cmd-N from a worktree pane starts beside+it rather than inside it. Worktrees Start made are never offered as recent+projects.++**Branch** starts on the branch of the pane New Harness was opened from, and+otherwise on the default branch (Worktree on) or the folder's own branch (off).+The picker names local branches; a remote branch is listed only when no local+branch has its name.++With `[x]`, **Branch** is what the new worktree works from. At Start a new+branch starts from the newer of that branch and its upstream, fetched for at+most ten seconds: `main` behind `origin/main` starts from `origin/main`, and+`main` with commits of its own starts from `main`, so nothing is lost; offline,+it starts from the last fetch. The branch the harness works on follows from it, with no row of its+own: the default or current branch gets a new branch named after the session+(`onboarding-experience`);+another local branch is checked out as it is; a remote branch nobody has+locally becomes a local branch of the same name tracking it; a branch that+already has a worktree opens there, and Start reads **Start in Worktree**. The+project folder's own branch cannot be checked out twice. Typing a name no+branch has offers **Create branch**: a new branch in a new worktree, from the+default branch. Spaces become `-` and anything Git refuses in a name is+dropped.++A session has no name at Start, so that branch starts as a made-up+`<word>-<word>`, marked `branch.<name>.harness = placeholder` in the+repository's config and left out of the pane header. The daemon renames it once,+to the session's name (`-2` when a local or remote branch has it), when the+session first has a name, and never again:+not after a later session name, a push, or a rename by the person or the agent.+A picked or created branch keeps its name. The worktree is checked out in+`~/harnesses/worktrees/<repository>/<branch>`, and ignored files listed in the+repository's `.worktreeinclude` (gitignore syntax, e.g. `.env`) are copied in.++With `[ ]`, **Branch** is the branch the folder itself is on; only local+branches are selectable. A branch with a worktree of its own opens there+(**Start in Worktree**). Typing a name no branch has offers **Create branch**:+a new branch from the folder's branch, keeping its uncommitted changes.+Switching or creating needs no harness working in the folder, and switching+also needs nothing uncommitted. No changes are forced,+stashed, or discarded. A selected subfolder follows into a new worktree only if+it exists in that commit.++The picker tags branches `default`, `current`, `worktree` and `remote`, and+leaves out branches Harness made (marked `branch.<name>.harness`, or named+`harness/…` by older builds) whose worktree is gone. The daemon removes a+worktree it finds in `~/harnesses/worktrees` only when no live or stopped+harness uses it, nothing is uncommitted, and it has been idle for a week; the+branch stays unless Harness made it and its commits are all elsewhere.Drafts and advanced options preserve these choices. A lost start reply reusesits receipt, and retrying a confirmed launch failure reuses its prepared@@ -94,8 +136,11 @@ never silently renamed, and existing files are never overwritten.- `test/new_harness_git_test.dart`, `test/git_worktree_test.dart`, and`test/git_worktree_failures_test.dart`: Git defaults, hidden non-Git rows,- keyboard/click toggles, branch search, stale replies, retries, actual Git- worktrees and branch safety, process deadlines, and bounded output.+ keyboard/click toggles, branch search, branch resolution, stale+ replies, retries, actual Git worktrees and branch safety, fetching,+ tracking, `.worktreeinclude`, process deadlines, and bounded output.+ `cli/src/lib/gitProject.spec.ts` and `worktreeSweep.spec.ts` cover the same+ rules on a remote machine and the daemon's cleanup.- `test/new_harness_entry_rules_test.dart`: product changes with an open ordismissed dock, Open/Try, edited names, machine changes, explicit agentprecedence, search isolation, exact launch payloads, pending receipts, sourcediff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dartindex c72112d72..12817dcbf 100644--- a/desktop/lib/core/git_worktree.dart+++ b/desktop/lib/core/git_worktree.dart@@ -1,16 +1,26 @@import 'dart:async';import 'dart:convert';import 'dart:io';+import 'dart:math';import 'package:path/path.dart' as p;import 'repository_clone.dart';class GitBranch {- const GitBranch(this.ref, this.name, {this.remote = false, this.worktree});+ const GitBranch(+ this.ref,+ this.name, {+ this.remote = false,+ this.worktree,+ this.harness = false,+ });final String ref, name;final bool remote;+ /// Harness made this branch for a worktree.+ final bool harness;+/// Where this local branch is checked out, when it is.final String? worktree;}@@ -23,6 +33,8 @@ class GitProjectInfo {this.error,this.mainFolder,this.mainBranch,+ this.defaultRef,+ this.root,});factory GitProjectInfo.fromJson(Map<String, dynamic> data) => GitProjectInfo(isGit: data['isGit'] == true,@@ -32,6 +44,12 @@ class GitProjectInfo {? data['mainFolder'] as String: null,mainBranch: data['mainBranch'] as String?,+ defaultRef: data['defaultRef'] is String && validGitRef(data['defaultRef'])+ ? data['defaultRef'] as String+ : null,+ root: data['root'] is String && validGitPath(data['root'])+ ? data['root'] as String+ : null,branches: [for (final row in (data['branches'] as List? ?? const []))if (row is Map && row['ref'] is String && row['name'] is String)@@ -42,6 +60,7 @@ class GitProjectInfo {worktree: row['worktree'] is String? row['worktree'] as String: null,+ harness: row['harness'] == true,),],);@@ -52,6 +71,19 @@ class GitProjectInfo {/// 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;++ /// The remote branch new work starts from by default (`origin/HEAD`), and+ /// the checkout the folder belongs to.+ final String? defaultRef, root;++ GitProjectInfo copyWith({String? branch, String? root}) => GitProjectInfo(+ isGit: isGit,+ branch: branch ?? this.branch,+ branches: branches,+ error: error,+ defaultRef: defaultRef,+ root: root ?? this.root,+ );}/// One entry of `git worktree list --porcelain`. The main checkout is first.@@ -97,20 +129,96 @@ Future<String?> _mainCheckout(String root, List<_Worktree> trees) async {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'-+$'), '');+/// Two plain words for a branch nothing has named yet — plumbing, like the+/// worktree's folder: the agent or the person names the real branch when there+/// is something to push. Mirrors cli/src/lib/agentNames.ts.+const kPlaceholderAdjectives = [+ 'amber', 'bold', 'brave', 'brisk', 'calm', 'clever', 'cosmic', 'crisp', //+ 'dapper', 'eager', 'fancy', 'gentle', 'glad', 'golden', 'happy', 'hidden',+ 'jolly', 'keen', 'kind', 'lively', 'lucky', 'merry', 'misty', 'noble', //+ 'polite', 'proud', 'quick', 'quiet', 'rapid', 'rosy', 'royal', 'rustic',+ 'shiny', 'silent', 'silver', 'sleek', 'smart', 'snowy', 'solar', 'spry',+ 'steady', 'sunny', 'swift', 'tidy', 'vivid', 'warm', 'witty', 'zesty',+];+const kPlaceholderNouns = [+ 'badger', 'beacon', 'birch', 'bison', 'canyon', 'cedar', 'comet', 'coral',+ 'crane', 'delta', 'falcon', 'fern', 'finch', 'fjord', 'fox', 'gecko', //+ 'glacier', 'harbor', 'hawk', 'heron', 'ibis', 'island', 'koala', 'lagoon',+ 'lark', 'lynx', 'maple', 'meadow', 'meteor', 'moose', 'nebula', 'otter', //+ 'owl', 'panda', 'pebble', 'pine', 'puffin', 'quartz', 'raven', 'reef', //+ 'river', 'robin', 'sparrow', 'spruce', 'tiger', 'walrus', 'willow', 'zebra',+];++/// `brave-otter`: the branch a new worktree starts on until its session has a+/// name, one none of [taken] (branch names, with or without `refs/heads/`)+/// already uses.+String placeholderBranch(Iterable<String> taken, {Random? random}) {+ final names = {+ for (final name in taken) name.replaceFirst('refs/heads/', ''),+ };+ final pick = random ?? Random();+ String draw() =>+ '${kPlaceholderAdjectives[pick.nextInt(kPlaceholderAdjectives.length)]}'+ '-${kPlaceholderNouns[pick.nextInt(kPlaceholderNouns.length)]}';+ var name = draw();+ for (var tries = 0; tries < 16 && names.contains(name); tries++) {+ name = draw();}- return '${slug.isEmpty ? 'harness' : slug}-${two(at.month)}${two(at.day)}-${two(at.hour)}${two(at.minute)}';+ final base = name;+ for (var suffix = 2; names.contains(name); suffix++) {+ name = '$base-$suffix';+ }+ return name;+}++/// The folder a worktree on [branch] is checked out in, under its repository:+/// the branch's last part. Nobody needs to see it, and it keeps its name when+/// the branch is renamed.+String worktreeFolderName(String branch) {+ final name = branch+ .split('/')+ .last+ .replaceAll(RegExp(r'[^A-Za-z0-9._-]+'), '')+ .replaceAll(RegExp(r'^[.-]+'), '');+ return name.isEmpty+ ? 'worktree'+ : name.length > 64+ ? name.substring(0, 64)+ : name;}+/// What a typed name becomes as a branch, as editors do it: words joined by+/// `-`, and nothing `git check-ref-format` refuses. Empty when nothing is left.+String branchNameFrom(String typed) {+ var name = typed+ .trim()+ .replaceAll(RegExp(r'\s+'), '-')+ .replaceAll(RegExp(r'[\x00-\x1f\x7f~^:?*\[\\]+'), '')+ .replaceAll(RegExp(r'\.{2,}'), '.')+ .replaceAll('@{', '@')+ .replaceAll(RegExp(r'/{2,}'), '/')+ .replaceAll(RegExp(r'/[.]+'), '/')+ .replaceAll(RegExp(r'-{2,}'), '-')+ .replaceAll(RegExp(r'^[-./]+'), '');+ for (var trimmed = ''; trimmed != name;) {+ trimmed = name;+ name = name.replaceAll(RegExp(r'(\.lock|[./])$'), '');+ }+ return name == '@' ? '' : name;+}++/// A name Git accepts for a new branch, checked before Git is asked.+bool plausibleBranchName(String name) =>+ name.isNotEmpty &&+ name.length <= 255 &&+ !name.startsWith('-') &&+ !RegExp(r'[\x00-\x20\x7f~^:?*\[\\]').hasMatch(name);++/// `branch.<name>.harness` marks a branch Harness made: `placeholder` while its+/// name waits for the session's, `created` once it has one or was named at+/// Start. Mirrors cli/src/lib/gitProject.ts.+const kHarnessBranchKey = 'harness';+bool validGitPath(String path) =>p.isAbsolute(path) &&path.length <= 4096 &&@@ -146,8 +254,28 @@ Future<Map<String, dynamic>> readLocalGitProject('refs/remotes',]),git(['worktree', 'list', '--porcelain']),+ git(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']),+ git(['config', '--get-regexp', '^branch\\..*\\.$kHarnessBranchKey\$']),]);+ final marked = {+ for (final line in results[4].output.split('\n'))+ if (line.split(' ').first case final key+ when key.startsWith('branch.') &&+ key.endsWith('.$kHarnessBranchKey'))+ key.substring(7, key.length - kHarnessBranchKey.length - 1),+ };if (results[1].code != 0) return {'error': 'GIT_UNAVAILABLE'};+ final refs = {+ for (final line in results[1].output.split('\n'))+ if (line.split('\t') case [final ref, _, '']) ref,+ };+ // Where new work starts by default: the remote's default branch, as a+ // clone names it, else its main or master.+ final defaultRef = [+ if (results[3].code == 0) results[3].output,+ 'refs/remotes/origin/main',+ 'refs/remotes/origin/master',+ ].where(refs.contains).firstOrNull;final trees = results[2].code == 0? _parseWorktrees(results[2].output): const <_Worktree>[];@@ -177,6 +305,7 @@ Future<Map<String, dynamic>> readLocalGitProject(: null,'mainFolder': ?mainFolder,'mainBranch': ?mainBranch,+ 'defaultRef': ?defaultRef,'branches': [for (final line in results[1].output.split('\n'))if (line.split('\t') case [final ref, final name, ''])@@ -185,6 +314,9 @@ Future<Map<String, dynamic>> readLocalGitProject('name': name,'remote': ref.startsWith('refs/remotes/'),'worktree': ?checkedOut[ref],+ if (ref.startsWith('refs/heads/') &&+ (marked.contains(name) || name.startsWith('harness/')))+ 'harness': true,},],};@@ -193,31 +325,49 @@ Future<Map<String, dynamic>> readLocalGitProject(}}-/// 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.+/// Worktree on: a new worktree under `<projectHome>/worktrees/<repository>`,+/// on [branchName] — created from [branchRef], or with [existingBranch] an+/// existing local branch checked out as it is. Without a name one is made up+/// (`harness/brave-otter`). A remote base is fetched first, briefly.+///+/// Worktree off: the folder on the local [branchRef]. A branch that already+/// has a worktree opens there; any other is switched to, only in a folder with+/// nothing uncommitted. With [branchName] the folder moves to that new branch,+/// made where it is now, uncommitted changes and all.Future<String> prepareGitProject(String source,String projectHome, {required bool worktree,String? branchRef,- required String label,- DateTime Function()? now,+ String? branchName,+ bool existingBranch = false,+ bool placeholder = false,+ Random? random,GitProcessStarter? startProcess,}) async {Future<({int code, String output})> git(List<String> arguments, {Duration timeout = const Duration(seconds: 4),- }) => _git(source, arguments, timeout: timeout, startProcess: startProcess);- if (!validGitPath(source) || branchRef != null && !validGitRef(branchRef)) {+ String? at,+ }) => _git(+ at ?? source,+ arguments,+ timeout: timeout,+ startProcess: startProcess,+ );+ if (!validGitPath(source) ||+ branchRef != null && !validGitRef(branchRef) ||+ branchName != null && !plausibleBranchName(branchName) ||+ existingBranch && branchName == null) {throw const RepositoryCloneException('Choose a Git project and branch.');}final root = await git(['rev-parse', '--show-toplevel']);if (root.code != 0) {throw const RepositoryCloneException('Choose a Git working folder.');}- if (branchRef != null) {+ // A new branch for the folder itself: [branchRef] names it and does not exist.+ final creating = !worktree && branchName != null && !existingBranch;+ if (branchRef != null && !creating) {final ref = await git(['show-ref', '--verify', '--hash', '--', branchRef]);if (ref.code != 0) {throw const RepositoryCloneException(@@ -225,11 +375,56 @@ Future<String> prepareGitProject();}}+ // New work starts from where its branch is now, not from the last fetch: a+ // remote branch is fetched; a local one is fetched against its upstream and+ // the newer of the two taken, so nothing only the local one has is lost.+ // Offline, slow or refused, it starts from what is here.+ final remote = worktree && !existingBranch ? _remoteBranch(branchRef) : null;+ var start = existingBranch+ ? 'refs/heads/$branchName'+ : creating+ ? 'HEAD'+ : branchRef ?? 'HEAD';+ String? upstream;+ if (worktree && !existingBranch && branchRef != null && remote == null) {+ final tracked = await git([+ 'for-each-ref',+ '--format=%(upstream)',+ branchRef,+ ]);+ if (tracked.code == 0 && _remoteBranch(tracked.output) != null) {+ upstream = tracked.output;+ }+ }+ final fetch = remote ?? _remoteBranch(upstream);+ if (fetch != null) {+ try {+ await git([+ 'fetch',+ '--quiet',+ '--no-tags',+ fetch.remote,+ fetch.refspec,+ ], timeout: const Duration(seconds: 10));+ } on RepositoryCloneException {+ // Too slow: start from the last fetch.+ }+ }+ if (upstream != null && branchRef != null) {+ // Behind or level with its upstream: the upstream is the newer.+ final behind = await git([+ 'merge-base',+ '--is-ancestor',+ branchRef,+ upstream,+ ]);+ if (behind.code == 0) start = upstream;+ }final head = await git(['rev-parse','--verify','--end-of-options',- '${branchRef ?? 'HEAD'}^{commit}',+ '$start^{commit}',]);if (head.code != 0) {throw const RepositoryCloneException(@@ -260,6 +455,29 @@ Future<String> prepareGitProject(final trees = listed.code == 0? _parseWorktrees(listed.output): const <_Worktree>[];+ if (creating) {+ final exists = await git([+ 'show-ref',+ '--verify',+ '--quiet',+ '--',+ 'refs/heads/$branchName',+ ]);+ if (exists.code == 0) {+ throw RepositoryCloneException(+ 'A branch named $branchName already exists. Choose it instead.',+ );+ }+ final format = await git(['check-ref-format', '--branch', branchName]);+ if (format.code != 0) {+ throw RepositoryCloneException('$branchName is not a valid branch name.');+ }+ final made = await git(['switch', '-c', branchName]);+ if (made.code != 0) {+ throw RepositoryCloneException('Could not create $branchName here.');+ }+ return source;+ }if (!worktree) {if (branchRef == null || !branchRef.startsWith('refs/heads/')) {throw const RepositoryCloneException(@@ -277,6 +495,12 @@ Future<String> prepareGitProject(return inside(tree.path);}}+ final status = await git(['status', '--porcelain']);+ if (status.code != 0 || status.output.isNotEmpty) {+ throw const RepositoryCloneException(+ 'This folder has uncommitted changes. Commit or stash them before switching branches, or turn Worktree on.',+ );+ }final result = await git(['switch','--',@@ -289,34 +513,64 @@ Future<String> prepareGitProject(}return source;}- // Grouped by repository, so the leaf only needs the harness and the time.+ // Grouped by repository, so the leaf only needs the branch.final repository = trees.firstOrNull?.usable == true? p.basename(trees.first.path): p.basename(root.output);- final taken = await git([+ final locals = await git(['for-each-ref','--format=%(refname)',- 'refs/heads/harness/',+ 'refs/heads',]);- final base = worktreeName(label, (now ?? DateTime.now)());- late final String destination, branch;+ final taken = locals.output.split('\n').toSet();+ final branch = branchName ?? placeholderBranch(taken, random: random);+ final madeUp = branchName == null || placeholder;+ if (existingBranch) {+ if (!taken.contains('refs/heads/$branch')) {+ throw const RepositoryCloneException(+ 'That branch is no longer available. Choose another branch.',+ );+ }+ if (trees.any((tree) => tree.ref == 'refs/heads/$branch')) {+ throw RepositoryCloneException(+ '$branch is checked out in another worktree. Turn Worktree off to open it there.',+ );+ }+ } else {+ if (taken.contains('refs/heads/$branch')) {+ throw RepositoryCloneException(+ 'A branch named $branch already exists. Choose another name.',+ );+ }+ final format = await git(['check-ref-format', '--branch', branch]);+ if (format.code != 0) {+ throw RepositoryCloneException('$branch is not a valid branch name.');+ }+ }+ late final String destination;try {- final parent = Directory(p.join(projectHome, 'worktrees', repository));+ final home = Directory(p.join(projectHome, 'worktrees'));+ final parent = Directory(p.join(home.path, repository));await parent.create(recursive: true);+ // Spotlight would index every checkout again.+ if (Platform.isMacOS) {+ await File(p.join(home.path, '.metadata_never_index'))+ .writeAsString('', flush: true)+ .catchError((_) => File(''));+ }+ final leaf = worktreeFolderName(branch);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);+ final folder = p.join(+ parent.path,+ attempt == 1 ? leaf : '$leaf-$attempt',+ );// 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) ==@@ -333,24 +587,125 @@ Future<String> prepareGitProject('Could not create a worktree folder. Check folder permissions, then retry.',);}- final result = await git([- 'worktree',- 'add',- '-b',- branch,- '--',- destination,- head.output,- ], timeout: const Duration(minutes: 2));+ final result = await git(+ existingBranch+ ? ['worktree', 'add', '--', destination, branch]+ // A remote branch checked out under its own name tracks it; a new+ // branch from one must not, or it would push onto the base.+ : remote != null && remote.branch == branch+ ? [+ 'worktree',+ 'add',+ '--track',+ '-b',+ branch,+ '--',+ destination,+ branchRef!,+ ]+ : [+ 'worktree',+ 'add',+ '--no-track',+ '-b',+ branch,+ '--',+ 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. Check Git and folder permissions, then retry.',);}+ // Harness made this branch: its cleanup may remove it, and a made-up name+ // gives way to the session's.+ if (!existingBranch) {+ await git([+ 'config',+ 'branch.$branch.$kHarnessBranchKey',+ madeUp ? 'placeholder' : 'created',+ ]);+ }+ await _copyIncluded(root.output, destination, startProcess);return inside(destination);}+/// `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) {+ final match = RegExp(+ r'^refs/remotes/([A-Za-z0-9._][A-Za-z0-9._-]*)/([A-Za-z0-9._][^\s]*)$',+ ).firstMatch(ref ?? '');+ if (match == null || match.group(2) == 'HEAD') return null;+ final remote = match.group(1)!, branch = match.group(2)!;+ return (+ remote: remote,+ branch: branch,+ refspec: '+refs/heads/$branch:refs/remotes/$remote/$branch',+ );+}++/// `.worktreeinclude` (gitignore syntax) in the repository names ignored files+/// a new worktree needs and Git will not bring: `.env`, local config. Only+/// files that are both listed and ignored are copied, never over one the+/// checkout has. A copy that fails leaves the worktree as Git made it.+Future<void> _copyIncluded(+ String from,+ String to,+ GitProcessStarter? startProcess,+) async {+ final include = p.join(from, '.worktreeinclude');+ try {+ if (!await File(include).exists()) return;+ Future<List<String>> list(String exclude) async {+ final out = await _git(from, [+ 'ls-files',+ '-z',+ '--others',+ '--ignored',+ '--directory',+ exclude,+ ], startProcess: startProcess);+ return out.code == 0+ ? out.output.split('\u0000').where((e) => e.isNotEmpty).toList()+ : const [];+ }++ final listed = await list('--exclude-from=$include');+ final ignored = await list('--exclude-standard');+ bool isIgnored(String entry) => ignored.any(+ (path) => path == entry || path.endsWith('/') && entry.startsWith(path),+ );+ for (final entry in listed.where(isIgnored).take(200)) {+ final relative = entry.replaceFirst(RegExp(r'/$'), '');+ if (relative.split('/').contains('..')) continue;+ final target = p.join(to, relative);+ if (await FileSystemEntity.type(target, followLinks: false) !=+ FileSystemEntityType.notFound) {+ continue;+ }+ await Directory(p.dirname(target)).create(recursive: true);+ await Process.run('cp', [+ '-R',+ '-p',+ '--',+ p.join(from, relative),+ target,+ ]);+ }+ } on FileSystemException {+ return;+ } on ProcessException {+ return;+ } on RepositoryCloneException {+ return;+ }+}+Future<({int code, String output})> _git(String source,List<String> arguments, {diff --git a/desktop/lib/core/local_git_projects.dart b/desktop/lib/core/local_git_projects.dartindex 8ef0e01ad..b4cb08929 100644--- a/desktop/lib/core/local_git_projects.dart+++ b/desktop/lib/core/local_git_projects.dart@@ -129,6 +129,9 @@ class LocalGitProjects {'root': root,'remote': _origin(config),'branch': branch,+ 'worktree': shared != null,+ 'branchPending':+ branch != null && _placeholder(config, branch) == 'placeholder',});_publish(entry, project);} on FileSystemException {@@ -255,6 +258,26 @@ class LocalGitProjects {}}+ /// `branch.<name>.harness` from the repository's config: `placeholder`+ /// while Harness's made-up name waits for the session's.+ String? _placeholder(String? config, String branch) {+ if (config == null) return null;+ var inBranch = false;+ for (final line in config.split('\n')) {+ final text = line.trim();+ if (text.startsWith('[')) {+ inBranch = text == '[branch "$branch"]';+ } else if (inBranch) {+ final match = RegExp(+ r'^harness\s*=\s*(\S+)$',+ caseSensitive: false,+ ).firstMatch(text);+ if (match != null) return match.group(1);+ }+ }+ return null;+ }+String? _origin(String? config) {if (config == null) return null;var origin = false;diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex 61633643b..11322d881 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -781,6 +781,8 @@ class AgentProject {this.root,this.remote,this.branch,+ this.worktree = false,+ this.branchPending = false,});final String name;final String cwd;@@ -788,6 +790,29 @@ class AgentProject {final String? remote;final String? branch;+ /// In a linked worktree rather than the repository's own checkout.+ final bool worktree;++ /// [branch] still has the name Harness made up at Start; it is shown once+ /// the session's name replaces it.+ final bool branchPending;++ /// The folder as the person chose it: inside a Git checkout, a subfolder+ /// shows as itself and the checkout's root as its repository ([name]), even+ /// when the checkout is a temporary worktree. Outside Git it is [name], the+ /// folder itself. The branch beside it is the repository's.+ String get label {+ final checkout = root;+ if (checkout == null) return name;+ String trimmed(String path) => path.replaceFirst(RegExp(r'[/\\]+$'), '');+ if (trimmed(checkout) == trimmed(cwd)) return name;+ return cwd+ .split(RegExp(r'[/\\]'))+ .where((part) => part.isNotEmpty)+ .lastOrNull ??+ name;+ }+String identity(String machineId) =>remote != null ? 'repo:$remote' : 'folder:$machineId:${root ?? cwd}';@@ -798,9 +823,12 @@ class AgentProject {cwd == other.cwd &&root == other.root &&remote == other.remote &&- branch == other.branch;+ branch == other.branch &&+ worktree == other.worktree &&+ branchPending == other.branchPending;@override- int get hashCode => Object.hash(name, cwd, root, remote, branch);+ int get hashCode =>+ Object.hash(name, cwd, root, remote, branch, worktree, branchPending);static AgentProject? fromJson(Object? raw) {if (raw is! Map) return null;@@ -823,6 +851,8 @@ class AgentProject {root: field('root'),remote: field('remote'),branch: field('branch', 256),+ worktree: raw['worktree'] == true,+ branchPending: raw['branchPending'] == true,);}}diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dartindex 405e4e5d6..717cf3e30 100644--- a/desktop/lib/core/project_folder.dart+++ b/desktop/lib/core/project_folder.dart@@ -11,6 +11,9 @@ class ProjectFolderRequest {const ProjectFolderRequest.newProject({this.name}): gitSource = null,branchRef = null,+ branchName = null,+ existingBranch = false,+ placeholder = false,createsWorktree = false,repository = null,generatedLabel = null,@@ -21,6 +24,9 @@ class ProjectFolderRequest {String? name,}) : gitSource = null,branchRef = null,+ branchName = null,+ existingBranch = false,+ placeholder = false,createsWorktree = false,repository = null,generatedLabel = label,@@ -29,31 +35,53 @@ class ProjectFolderRequest {const ProjectFolderRequest.remote(GitHubRepository value): gitSource = null,branchRef = null,+ branchName = null,+ existingBranch = false,+ placeholder = false,createsWorktree = false,repository = value,name = null,generatedLabel = null,generatedAt = null;- const ProjectFolderRequest.worktree(String source, {this.branchRef})- : gitSource = source,- createsWorktree = true,- repository = null,- name = null,- generatedLabel = null,- generatedAt = null;+ /// A new worktree on [branchName]: created from [branchRef], or with+ /// [existingBranch] that local branch checked out as it is. Without a name+ /// the machine makes one up.+ const ProjectFolderRequest.worktree(+ String source, {+ this.branchRef,+ this.branchName,+ this.existingBranch = false,+ this.placeholder = false,+ }) : gitSource = source,+ createsWorktree = true,+ repository = null,+ name = null,+ generatedLabel = null,+ generatedAt = null;- const ProjectFolderRequest.branch(String source, String ref)- : gitSource = source,- branchRef = ref,- createsWorktree = false,- repository = null,- name = null,- generatedLabel = null,- generatedAt = null;+ /// The folder itself on [ref], or with [newBranch] on that new branch, made+ /// where the folder is now. [ref] then names the new branch, so a daemon that+ /// cannot make one refuses it rather than starting on the old one.+ const ProjectFolderRequest.branch(+ String source,+ String ref, {+ String? newBranch,+ }) : gitSource = source,+ branchRef = ref,+ branchName = newBranch,+ existingBranch = false,+ placeholder = false,+ createsWorktree = false,+ repository = null,+ name = null,+ generatedLabel = null,+ generatedAt = null;++ final String? gitSource, branchRef, branchName;- final String? gitSource, branchRef;- final bool createsWorktree;+ /// [branchName] was made up: the session's name replaces it once it has one.+ final bool createsWorktree, existingBranch, placeholder;final GitHubRepository? repository;@@ -113,6 +141,10 @@ class ProjectFolderRequest {: 'remote','gitSource': ?gitSource,'branchRef': ?branchRef,+ // A daemon that predates these names the worktree's branch itself.+ 'branchName': ?branchName,+ if (existingBranch) 'branchMode': 'existing',+ if (placeholder) 'branchMode': 'placeholder',if (repository != null) 'repositoryUrl': repository!.url,// A daemon that predates the field ignores it and names the folder itself.if (repository == null && folderName != null) 'projectName': folderName!,@@ -144,8 +176,9 @@ class ProjectFolderRequest {root.path,worktree: createsWorktree,branchRef: branchRef,- label: label,- now: now,+ branchName: branchName,+ existingBranch: existingBranch,+ placeholder: placeholder,);}await root.create(recursive: true);diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 7b33d90ed..5b2495b34 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -1299,11 +1299,13 @@ class _SwarmScreenState extends State<SwarmScreen> {?.machine.machineId ??app.machineStates.keys.firstOrNull;- final initialFolder =- folder ??- (projectName != null || agent == null || id != focused?.machineId- ? null- : machine?.projectOf(agent)?.cwd);+ final paneProject =+ projectName != null || agent == null || id != focused?.machineId+ ? null+ : machine?.projectOf(agent);+ final initialFolder = folder ?? paneProject?.cwd;+ // Another one of these: on the branch the pane is on, as well as its folder.+ final initialBranch = folder == null ? paneProject?.branch : null;if (id == null) {await _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap),@@ -1330,6 +1332,7 @@ class _SwarmScreenState extends State<SwarmScreen> {// ⌘⇧T is how a shell is made; New Harness from a shell means an agent.engine: engine ?? (isTerminalEngine(inherited) ? null : inherited),folder: initialFolder,+ branch: initialBranch,projectName: projectName,autoProject:projectName == null &&@@ -1414,6 +1417,7 @@ class _SwarmScreenState extends State<SwarmScreen> {required String machineId,String? engine,String? folder,+ String? branch,String? projectName,bool autoProject = false,String? task,@@ -1492,6 +1496,7 @@ class _SwarmScreenState extends State<SwarmScreen> {machineId: machineId,engine: engine,folder: folder,+ branch: branch,projectName: projectName,task: task,draft: resumed,diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex fb10922d2..3874054d2 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -1,6 +1,7 @@import 'dart:async';import 'dart:io';import 'dart:isolate';+import 'dart:math';import 'package:collection/collection.dart' show compareNatural;import 'package:flutter/foundation.dart';@@ -92,6 +93,173 @@ class NewHarnessProject {);}+/// What Start does with a Git project in a new worktree.+enum WorktreeStart {+ /// A new branch from the chosen base.+ newBranch,++ /// An existing local branch, checked out as it is.+ existingBranch,++ /// The branch already has a worktree: the harness starts in it.+ openWorktree,++ /// The branch is the project folder's own and cannot be checked out twice.+ unavailable,+}++@immutable+class WorktreePlan {+ const WorktreePlan(this.kind, this.branch, {this.base, this.worktree});+ final WorktreeStart kind;+ final String branch;++ /// What a new branch starts from; a remote branch of the same name is tracked.+ final String? base;++ /// Where an existing worktree is.+ final String? worktree;+ bool get tracks =>+ kind == WorktreeStart.newBranch &&+ base != null &&+ base!.startsWith('refs/remotes/') &&+ base!.split('/').skip(3).join('/') == branch;+}++/// The project folder's own branch, if it is on one.+String? currentBranchRef(GitProjectInfo info) =>+ info.branch != null &&+ info.branches.any((b) => b.ref == 'refs/heads/${info.branch}')+ ? 'refs/heads/${info.branch}'+ : null;++/// Worktree starts on for a Git project with a commit to start from.+bool worktreeByDefault(GitProjectInfo info) =>+ info.isGit && info.branches.any((branch) => !branch.remote);++/// Where Start begins when no branch was chosen: new work from the default+/// branch (the local one, which Start brings up to its remote), work in the+/// folder on the branch it is on.+String? defaultBranchRef(GitProjectInfo info, {required bool worktree}) {+ if (!worktree) return currentBranchRef(info);+ final remote = info.defaultRef;+ final local = remote == null+ ? null+ : 'refs/heads/${remote.split('/').skip(3).join('/')}';+ return info.branches.any((b) => b.ref == local)+ ? local+ : remote ?? currentBranchRef(info);+}++/// The branch a worktree started from [base] is on, unless [name] was typed:+/// the default or current branch gets a new [placeholder] branch; another+/// local branch is checked out as it is, or opened in its worktree; a remote+/// branch nobody has locally becomes a local branch tracking it.+WorktreePlan planWorktree(+ GitProjectInfo info, {+ required String? base,+ required String? name,+ required String placeholder,+}) {+ GitBranch? local(String branch) =>+ info.branches.where((b) => !b.remote && b.name == branch).firstOrNull;+ // The folder's own branch cannot be checked out again: typed, it is refused;+ // picked (itself or its remote), a new branch starts from what was picked.+ WorktreePlan onLocal(GitBranch branch, {required bool chosen}) =>+ branch.name == info.branch+ ? chosen+ ? WorktreePlan(WorktreeStart.unavailable, branch.name)+ : WorktreePlan(WorktreeStart.newBranch, placeholder, base: base)+ : branch.worktree != null+ ? WorktreePlan(+ WorktreeStart.openWorktree,+ branch.name,+ worktree: branch.worktree,+ )+ : WorktreePlan(WorktreeStart.existingBranch, branch.name);+ final typed = name?.trim();+ if (typed != null && typed.isNotEmpty) {+ final existing = local(typed);+ return existing == null+ ? WorktreePlan(WorktreeStart.newBranch, typed, base: base)+ : onLocal(existing, chosen: true);+ }+ final fresh = WorktreePlan(WorktreeStart.newBranch, placeholder, base: base);+ final defaultName = info.defaultRef?.split('/').skip(3).join('/');+ if (base == null ||+ base == info.defaultRef ||+ base == 'refs/heads/$defaultName') {+ return fresh;+ }+ if (base.startsWith('refs/heads/')) {+ final branch = local(base.substring('refs/heads/'.length));+ return branch == null ? fresh : onLocal(branch, chosen: false);+ }+ final short = base.split('/').skip(3).join('/');+ final branch = local(short);+ return branch != null+ ? onLocal(branch, chosen: false)+ : WorktreePlan(WorktreeStart.newBranch, short, base: base);+}++/// With Worktree off, the new branch the folder moves to: a typed name no+/// local branch has.+String? newBranchHere(GitProjectInfo info, String? name) {+ final typed = name?.trim();+ return typed == null ||+ typed.isEmpty ||+ info.branches.any((b) => !b.remote && b.name == typed)+ ? null+ : typed;+}++/// The preparation a Git project's folder gets at Start.+ProjectFolderRequest? gitFolderRequest(+ String folder,+ GitProjectInfo info, {+ required bool worktree,+ required String? branchRef,+ required String? branchName,+ required String placeholder,+}) {+ final ref = branchRef ?? defaultBranchRef(info, worktree: worktree);+ if (!worktree) {+ if (newBranchHere(info, branchName) case final name?) {+ return ProjectFolderRequest.branch(+ folder,+ 'refs/heads/$name',+ newBranch: name,+ );+ }+ return ref == null ? null : ProjectFolderRequest.branch(folder, ref);+ }+ final plan = planWorktree(+ info,+ base: ref,+ name: branchName,+ placeholder: placeholder,+ );+ return switch (plan.kind) {+ WorktreeStart.openWorktree => ProjectFolderRequest.branch(+ folder,+ 'refs/heads/${plan.branch}',+ ),+ WorktreeStart.existingBranch => ProjectFolderRequest.worktree(+ folder,+ branchRef: 'refs/heads/${plan.branch}',+ branchName: plan.branch,+ existingBranch: true,+ ),+ WorktreeStart.newBranch ||+ WorktreeStart.unavailable => ProjectFolderRequest.worktree(+ folder,+ branchRef: plan.base,+ branchName: plan.branch,+ placeholder: plan.branch == placeholder,+ ),+ };+}+/// A creation buffer shared by the prompt and advanced options. It includes/// the receipt of an unresolved request, so going back cannot start a duplicate.@immutable@@ -104,6 +272,8 @@ class NewHarnessDraft {required this.permissionMode,this.worktree,this.branchRef,+ this.branchName,+ this.placeholder,this.gitProject,this.profile,this.profileChosen = false,@@ -115,7 +285,10 @@ class NewHarnessDraft {final String machineId, engine, task, permissionMode;final bool? worktree;- final String? branchRef;++ /// The branch chosen in the launcher, and the name typed for a worktree's+ /// branch; null leaves either to [defaultBranchRef] and [placeholder].+ final String? branchRef, branchName, placeholder;final GitProjectInfo? gitProject;final NewHarnessProject project;final LocalCodexProfile? profile;@@ -127,19 +300,31 @@ class NewHarnessDraft {final bool dismissalWarningShown;final Map<String, NewHarnessProject> projectsByMachine;- ProjectFolderRequest? get projectFolderRequest =>- (worktree == true || worktree == null && gitProject?.isGit == true) &&- project.folder != null &&- !isTerminalEngine(engine)- ? ProjectFolderRequest.worktree(project.folder!, branchRef: branchRef)- : branchRef != null && project.folder != null && !isTerminalEngine(engine)- ? ProjectFolderRequest.branch(project.folder!, branchRef!)- : project.folder != null || isTerminalEngine(engine)- ? null- : project.repository != null- ? ProjectFolderRequest.remote(project.repository!)- : project.generated ??- ProjectFolderRequest.newProject(name: project.name);+ ProjectFolderRequest? get projectFolderRequest {+ final folder = project.folder;+ final terminal = isTerminalEngine(engine);+ final info = gitProject;+ if (folder != null && !terminal && info != null && info.isGit) {+ return gitFolderRequest(+ folder,+ info,+ worktree: worktree ?? worktreeByDefault(info),+ branchRef: branchRef,+ branchName: branchName,+ placeholder: placeholder ?? placeholderBranch(const []),+ );+ }+ return worktree == true && folder != null && !terminal+ ? ProjectFolderRequest.worktree(folder, branchRef: branchRef)+ : branchRef != null && folder != null && !terminal+ ? ProjectFolderRequest.branch(folder, branchRef!)+ : folder != null || terminal+ ? null+ : project.repository != null+ ? ProjectFolderRequest.remote(project.repository!)+ : project.generated ??+ ProjectFolderRequest.newProject(name: project.name);+ }}@immutable@@ -194,6 +379,7 @@ class NewHarnessController extends ChangeNotifier {required String machineId,String? engine,String? folder,+ String? branch,String? projectName,bool autoProject = false,DateTime Function()? now,@@ -204,7 +390,10 @@ class NewHarnessController extends ChangeNotifier {HarnessPlacement? placement,this.offersStore = false,String? home,- }) : placement =+ Random? random,+ }) : _random = random ?? Random(),+ _paneBranch = branch,+ placement =placement ?? (split == null ? HarnessPlacement.currentTab : null),_targetId = swarmId ?? app.activeSwarmId,_usesNewTabPage = app.swarms.any(@@ -231,6 +420,8 @@ class NewHarnessController extends ChangeNotifier {if (task != null) this.task = task;_worktree = draft?.worktree;_branchRef = draft?.branchRef;+ _branchName = draft?.branchName;+ _placeholder = draft?.placeholder;_gitProject = draft?.gitProject ?? const GitProjectInfo();if (draft != null) {_projectsByMachine.addAll(draft.projectsByMachine);@@ -303,8 +494,13 @@ class NewHarnessController extends ChangeNotifier {String get engine => _engine;String get machineId => _machineId;NewHarnessProject get project => _project;+ final Random _random;++ /// The branch the pane New Harness was opened from is on: Branch starts+ /// there, for that pane's project only.+ String? _paneBranch;bool? _worktree;- String? _branchRef;+ String? _branchRef, _branchName, _placeholder;GitProjectInfo _gitProject = const GitProjectInfo();(String, String?, bool)? _gitKey;Future<void>? _gitFuture;@@ -318,17 +514,92 @@ class NewHarnessController extends ChangeNotifier {bool get isGitProject => _gitProject.isGit && !isTerminal;bool get canUseWorktree => isGitProject && !checkingGit;- bool get worktree => isGitProject && _worktree != false;- String? get branchRef => _branchRef;+ bool get worktree =>+ isGitProject && (_worktree ?? worktreeByDefault(_gitProject));++ /// With Worktree on, what a new branch starts from; off, the branch the+ /// folder is on. Unchosen, the default for the mode.+ String? get branchRef =>+ _branchRef ?? defaultBranchRef(_gitProject, worktree: worktree);String? get gitError => _gitProject.error;- String get branchLabel =>+ String get branchLabel => _refName(branchRef) ?? 'Detached HEAD';+ String? _refName(String? ref) =>_gitProject.branches- .where((branch) => branch.ref == _branchRef)+ .where((branch) => branch.ref == ref).firstOrNull?.name ??- _branchRef?.replaceFirst(RegExp(r'^refs/(heads|remotes)/'), '') ??- _gitProject.branch ??- 'Detached HEAD';+ ref?.replaceFirst(RegExp(r'^refs/(heads|remotes)/'), '');++ /// The branch a new worktree is on until its session names it: two words+ /// the daemon replaces with the session's name.+ String get placeholder => _placeholder ??= placeholderBranch([+ for (final branch in _gitProject.branches) branch.name,+ ], random: _random);+ WorktreePlan? get worktreePlan => worktree+ ? planWorktree(+ _gitProject,+ base: branchRef,+ name: _branchName,+ placeholder: placeholder,+ )+ : null;++ /// A branch with a worktree of its own, other than the project folder's.+ String? _worktreeOf(String? ref) => _gitProject.branches+ .where(+ (branch) =>+ branch.ref == ref &&+ branch.worktree != null &&+ branch.name != _gitProject.branch,+ )+ .firstOrNull+ ?.worktree;++ /// With Worktree off, the new branch Start makes for the folder.+ String? get _branchHere =>+ worktree ? null : newBranchHere(_gitProject, _branchName);++ /// The Branch row: what was picked, or the new branch typed there.+ String get branchRowLabel {+ final plan = worktreePlan;+ if (plan != null &&+ plan.kind == WorktreeStart.newBranch &&+ _branchName != null &&+ plan.branch == _branchName) {+ return '${plan.branch} · new from ${_refName(plan.base) ?? 'HEAD'}';+ }+ final name = _branchHere;+ return name == null+ ? branchLabel+ : '$name · new from ${_refName(currentBranchRef(_gitProject)) ?? 'HEAD'}';+ }++ /// Start goes into a worktree that already exists.+ bool get opensWorktree => worktree+ ? worktreePlan?.kind == WorktreeStart.openWorktree+ : _branchHere == null && _worktreeOf(branchRef) != null;++ /// What Start does with Git, in words for the summary and screen readers.+ String get gitSummary {+ if (!isGitProject) return '';+ final plan = worktreePlan;+ if (plan == null) {+ final here = _branchHere;+ return here != null+ ? ', on a new branch $here'+ : opensWorktree+ ? ', in the worktree of $branchLabel'+ : ', on $branchLabel';+ }+ return switch (plan.kind) {+ WorktreeStart.newBranch =>+ ', in a new worktree on ${plan.branch == placeholder ? 'a branch named after the session' : plan.branch} from ${_refName(plan.base) ?? 'HEAD'}',+ WorktreeStart.existingBranch => ', in a new worktree on ${plan.branch}',+ WorktreeStart.openWorktree => ', in the worktree of ${plan.branch}',+ WorktreeStart.unavailable =>+ ', but ${plan.branch} is the project folder’s branch',+ };+ }void toggleWorktree() {if (locked || !canUseWorktree) return;@@ -350,6 +621,9 @@ class NewHarnessController extends ChangeNotifier {if (_gitKey != null) {_worktree = null;_branchRef = null;+ _branchName = null;+ _placeholder = null;+ _paneBranch = null;_gitProject = const GitProjectInfo();}_gitKey = key;@@ -385,16 +659,20 @@ class NewHarnessController extends ChangeNotifier {isGit: true,branch: info.mainBranch,branches: info.branches,+ defaultRef: info.defaultRef,);}_gitProject = info;- // Keep an explicit branch choice; a removed branch fails at Start.+ // Another one of the pane it came from: on that pane's branch, if it is+ // still a local branch here.if (_branchRef == null &&- info.branch != null &&- info.branches.any(- (branch) => branch.ref == 'refs/heads/${info.branch}',- )) {- _branchRef = 'refs/heads/${info.branch}';+ info.branches.any((b) => !b.remote && b.name == _paneBranch)) {+ _branchRef = 'refs/heads/$_paneBranch';+ }+ // A name made up before the branches were known may already be taken.+ if (_placeholder != null &&+ info.branches.any((branch) => branch.name == _placeholder)) {+ _placeholder = null;}_refresh();}@@ -414,6 +692,8 @@ class NewHarnessController extends ChangeNotifier {permissionMode: _mode,worktree: _worktree,branchRef: _branchRef,+ branchName: _branchName,+ placeholder: isGitProject ? placeholder : _placeholder,gitProject: _gitProject,profile: _profile,profileChosen: _profileChosen,@@ -427,10 +707,16 @@ class NewHarnessController extends ChangeNotifier {);/// The same preparation intent is used by the prompt and advanced options.- ProjectFolderRequest? get projectFolderRequest => worktree- ? ProjectFolderRequest.worktree(_project.folder!, branchRef: _branchRef)- : !isTerminal && _project.folder != null && _branchRef != null- ? ProjectFolderRequest.branch(_project.folder!, _branchRef!)+ ProjectFolderRequest? get projectFolderRequest =>+ isGitProject && _project.folder != null+ ? gitFolderRequest(+ _project.folder!,+ _gitProject,+ worktree: worktree,+ branchRef: _branchRef,+ branchName: _branchName,+ placeholder: placeholder,+ ): _project.folder != null || isTerminal? null: _project.repository != null@@ -584,7 +870,8 @@ class NewHarnessController extends ChangeNotifier {// ---- what the line says -------------------------------------------------- String get createLabel => 'Start Harness';+ String get createLabel =>+ opensWorktree ? 'Start in Worktree' : 'Start Harness';String get agentLabel => labelOf(_engine);String labelOf(String id) => currentHarnessName(@@ -790,7 +1077,7 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.launch || NewHarnessField.task => false,NewHarnessField.agent => option.id == _engine,NewHarnessField.machine => option.id == _machineId,- NewHarnessField.branch => option.id == _branchRef,+ NewHarnessField.branch => option.id == branchRef,NewHarnessField.project ||NewHarnessField.projectMenu ||NewHarnessField.projectName ||@@ -812,6 +1099,7 @@ class NewHarnessController extends ChangeNotifier {static const browseId = 'project:browse';static const changeMachineId = 'project:machine';static const newProjectId = 'project:name';+ static const createBranchId = 'branch:create:';static const existingProjectId = 'project:existing';static const repositoryId = 'project:repository';static const storeId = 'agent:store';@@ -1011,7 +1299,14 @@ class NewHarnessController extends ChangeNotifier {case NewHarnessField.machine:_selectMachine(option.id);case NewHarnessField.branch:- _branchRef = option.id;+ if (option.id.startsWith(createBranchId)) {+ _branchName = option.id.substring(createBranchId.length);+ _branchRef = null;+ } else {+ // A picked branch replaces a new one.+ _branchRef = option.id;+ _branchName = null;+ }case NewHarnessField.project:case NewHarnessField.projectMenu:case NewHarnessField.projectName:@@ -1498,18 +1793,10 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.task ||NewHarnessField.agent => const [],NewHarnessField.machine => _machineOptions(),- NewHarnessField.branch => _ranked([- for (final branch in _gitProject.branches)- NewHarnessOption(- id: branch.ref,- title: branch.name,- detail: branch.remote ? 'Remote' : '',- enabled: worktree || !branch.remote,- why: branch.remote- ? 'Turn Worktree on to start from a remote branch.'- : null,- ),- ]),+ NewHarnessField.branch => [+ ..._ranked(_branchOptions()),+ ?_createBranchRow(),+ ],NewHarnessField.projectMenu => _projectMenu(),NewHarnessField.project ||NewHarnessField.projectName => _projectOptions(),@@ -1603,6 +1890,81 @@ class NewHarnessController extends ChangeNotifier {notifyListeners();}+ /// Branches to start from (Worktree on) or to work on (off), tagged the way+ /// editors tag them. Branches Harness named for worktrees that are gone are+ /// left out: nobody chose them.+ List<NewHarnessOption> _branchOptions() {+ final info = _gitProject;+ final defaultName = info.defaultRef?.split('/').skip(3).join('/');+ bool isDefault(GitBranch b) =>+ b.ref == info.defaultRef || !b.remote && b.name == defaultName;+ bool isCurrent(GitBranch b) => !b.remote && b.name == info.branch;+ // A remote branch with a local one of its name is that branch: Start+ // brings the local one up to it.+ final locals = {+ for (final branch in info.branches)+ if (!branch.remote) branch.name,+ };+ bool hasLocal(GitBranch b) =>+ b.remote && locals.contains(b.name.split('/').skip(1).join('/'));+ final shown = [+ for (final branch in info.branches)+ if (!((branch.harness || branch.name.startsWith('harness/')) &&+ branch.worktree == null &&+ branch.ref != branchRef) &&+ !(hasLocal(branch) && branch.ref != branchRef))+ branch,+ ];+ int rank(GitBranch b) => isDefault(b)+ ? 0+ : isCurrent(b)+ ? 1+ : 2;+ final ordered = [+ for (final group in [0, 1, 2])+ for (final branch in shown)+ if (rank(branch) == group) branch,+ ];+ return [+ for (final branch in ordered)+ NewHarnessOption(+ id: branch.ref,+ title: branch.name,+ detail: [+ if (isDefault(branch)) 'default',+ if (isCurrent(branch)) 'current',+ if (_worktreeOf(branch.ref) != null) 'worktree',+ if (branch.remote) 'remote',+ ].join(' · '),+ enabled: worktree || !branch.remote,+ why: branch.remote+ ? 'Turn Worktree on to start from a remote branch.'+ : null,+ ),+ ];+ }++ /// A typed name no branch has can be made — the way an editor's branch+ /// picker offers "Create branch": with Worktree on in a new worktree from+ /// the default branch, off in the folder from the branch it is on. Spaces+ /// become `-`, and what Git refuses in a name is dropped.+ NewHarnessOption? _createBranchRow() {+ final name = branchNameFrom(query);+ if (!plausibleBranchName(name) ||+ newBranchHere(_gitProject, name) == null) {+ return null;+ }+ final base = worktree+ ? defaultBranchRef(_gitProject, worktree: true)+ : currentBranchRef(_gitProject);+ return NewHarnessOption(+ id: '$createBranchId$name',+ synthetic: true,+ title: 'Create branch $name',+ detail: 'New branch from ${_refName(base) ?? 'HEAD'}',+ );+ }+List<NewHarnessOption> _ranked(List<NewHarnessOption> all) {total = all.length;String normalize(String text) {@@ -2096,6 +2458,31 @@ class NewHarnessController extends ChangeNotifier {if (!worktree && _branchRef?.startsWith('refs/remotes/') == true) {return _fail('Choose a local branch, or turn Worktree on.');}+ if (worktreePlan case final plan?+ when plan.kind == WorktreeStart.unavailable) {+ return _fail(+ '${plan.branch} is the project folder’s branch. Turn Worktree off to work on it there, or name a new branch.',+ );+ }+ // Switching the folder's branch would move it under a harness at work.+ final folder = _project.folder;+ final ref = branchRef;+ if (!worktree &&+ folder != null &&+ (_branchHere != null ||+ ref != null &&+ ref != currentBranchRef(_gitProject) &&+ _worktreeOf(ref) == null) &&+ (_machine?.agents ?? const []).any((agent) {+ final cwd = _machine?.projectOf(agent)?.cwd;+ final root = _gitProject.root ?? folder;+ return cwd != null &&+ (p.equals(cwd, root) || p.isWithin(root, cwd));+ })) {+ return _fail(+ 'A harness is working in this folder, so its branch can’t be switched. Turn Worktree on, or stay on $branchLabel.',+ );+ }}// Shortened by the person, never cut by us: a machine refuses one longer.if (takesTask && taskTooLong && !checking) {diff --git a/desktop/lib/state/swarm_attention.dart b/desktop/lib/state/swarm_attention.dartindex 385dd706d..05ea84dcc 100644--- a/desktop/lib/state/swarm_attention.dart+++ b/desktop/lib/state/swarm_attention.dart@@ -64,7 +64,7 @@ SwarmAttentionEntry _entry(view?.detail ??[machine?.machine.displayName ?? question.machineId,- project?.name,+ project?.label,project?.branch,].whereType<String>().where((s) => s.isNotEmpty).join(' · '),swarmId: view?.swarmId,@@ -75,6 +75,7 @@ SwarmAttentionEntry _entry(searchFields: [...?view?.fields.skip(1),if (view == null) machine?.machine.displayName ?? question.machineId,+ project?.label,project?.name,project?.branch,project?.cwd,diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dartindex 435c2f085..b0b18c4aa 100644--- a/desktop/lib/state/swarm_catalog.dart+++ b/desktop/lib/state/swarm_catalog.dart@@ -17,6 +17,7 @@ class SwarmAgentRef {agent.displayName,agent.engine,machine.machine.displayName,+ project?.label,project?.name,project?.branch,project?.cwd,@@ -97,7 +98,7 @@ List<SwarmProjectGroup> swarmProjects(final id = project.identity(entry.machineId);final group = groups.putIfAbsent(id,- () => SwarmProjectGroup(id: id, name: project.name),+ () => SwarmProjectGroup(id: id, name: project.label),);group.agents.add(entry);folders['${entry.machineId}\u0000${project.cwd}'] = id;diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex 1173538be..b17686831 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -396,7 +396,7 @@ Future<void> _resumeStoppedDestination(}) {final prefix = [type,- project?.name,+ project?.label,].whereType<String>().where((part) => part.isNotEmpty).join(' · ');final branch = project?.branch;return (@@ -404,7 +404,7 @@ Future<void> _resumeStoppedDestination(agentLabel,machine,if (offline) 'Offline',- project?.name,+ project?.label,branch,].whereType<String>().where((part) => part.isNotEmpty).join(' · '),text: [@@ -654,8 +654,8 @@ class SwarmLocationCatalog {promptContext: PromptContext(harness: label,machine: machineLabel,- project: project?.name,- branch: project?.branch,+ project: project?.label,+ branch: project?.branchPending == true ? null : project?.branch,leading: machine?.nodeOnline == false ? 'Offline' : null,),swarmId: swarm.id,@@ -1103,6 +1103,7 @@ List<SwarmDestination> swarmDestinations(context.addAll([row?.$1.machine.displayName,row?.$2.name ?? pane.session?.agentName,+ project?.label,project?.name,project?.branch,project?.cwd,@@ -1193,8 +1194,8 @@ List<SwarmDestination> swarmDestinations(promptContext: PromptContext(harness: label,machine: machineName,- project: project?.name,- branch: project?.branch,+ project: project?.label,+ branch: project?.branchPending == true ? null : project?.branch,leading: machine?.nodeOnline == false ? 'Offline' : null,),swarmId: owner?.id,@@ -1212,6 +1213,7 @@ List<SwarmDestination> swarmDestinations(row?.$2.title,type,machineName,+ project?.label,project?.name,project?.branch,project?.cwd,diff --git a/desktop/lib/store/store_harness_actions.dart b/desktop/lib/store/store_harness_actions.dartindex 9efc2cb60..c7f1b3bba 100644--- a/desktop/lib/store/store_harness_actions.dart+++ b/desktop/lib/store/store_harness_actions.dart@@ -24,7 +24,7 @@ class StoreResumeTarget {String get title => agent.name;String get detail => [machine.machine.displayName,- if (agent.project case final project?) project.name,+ if (agent.project case final project?) project.label,].join(' · ');String get tooltip => [title,diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex abc913800..cf378d1b9 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -720,6 +720,8 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {? widget.initialDraft?.worktree: null,branchRef: _sameGitProject ? widget.initialDraft?.branchRef : null,+ branchName: _sameGitProject ? widget.initialDraft?.branchName : null,+ placeholder: _sameGitProject ? widget.initialDraft?.placeholder : null,gitProject: _sameGitProject ? widget.initialDraft?.gitProject : null,profile: _codexProfile,profileChosen: _codexProfileChosen,diff --git a/desktop/lib/widgets/new_harness_box.dart b/desktop/lib/widgets/new_harness_box.dartindex 2cf449c7b..5e985b018 100644--- a/desktop/lib/widgets/new_harness_box.dart+++ b/desktop/lib/widgets/new_harness_box.dart@@ -215,7 +215,8 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {box.canUseWorktree,box.checkingGit,box.gitError,- box.branchLabel,+ box.branchRowLabel,+ box.createLabel,box.placement,box.query.trim().isEmpty,box.matchCount,@@ -287,7 +288,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {? _summaryText(): _launchChoice == _LaunchChoice.worktree? 'Worktree ${box.worktree ? 'on' : 'off'}. Enter to toggle.'- : '${_launchChoice.name}. Enter to edit.'+ : '${_choiceTitle(_launchChoice)}. Enter to edit.': box.field == NewHarnessField.task// No row to read here: read what Return will do instead.? _summaryText()@@ -348,6 +349,10 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {NewHarnessField.project => 'Project',};+ /// What a launch row is called on screen.+ static String _choiceTitle(_LaunchChoice choice) =>+ '${choice.name[0].toUpperCase()}${choice.name.substring(1)}';+bool get _composing =>_hasInput &&_text.value.composing.isValid &&@@ -907,7 +912,15 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {],if (_launching) ...[if (box.isGitProject)- _segment(NewHarnessField.branch, box.branchLabel),+ _segment(+ NewHarnessField.branch,+ box.branchRowLabel,+ tooltip: box.worktree+ ? 'What the worktree works from, brought up to date with its remote at Start. The default branch gets a new branch named after the session; another is checked out as it is. Type a name to create one.'+ : box.opensWorktree+ ? '${box.branchLabel} has a worktree of its own: the harness starts there.'+ : 'The branch the project folder is on.',+ ),if (box.isGitProject || box.checkingGit || box.gitError != null)_default('worktree',@@ -922,7 +935,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {tooltip: box.gitError != null? 'Could not check Git on ${box.machineLabel}. Retry.': box.canUseWorktree- ? 'Start in a new Git worktree and branch from the selected branch. Uncommitted changes stay in the original folder.'+ ? 'Start in a new Git worktree: a folder of its own, so harnesses never share files. Uncommitted changes stay in the project folder.': 'Choose an existing Git project to use a worktree.',onTap: () {_selectLaunchChoice(_LaunchChoice.worktree);@@ -941,9 +954,16 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {),);- Widget _segment(NewHarnessField field, String label) => _default(+ Widget _segment(+ NewHarnessField field,+ String label, {+ String? title,+ String? tooltip,+ }) => _default(field.name,label,+ title: title,+ tooltip: tooltip,active:box.field == field ||(field == NewHarnessField.project &&@@ -968,13 +988,14 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {bool action = false,bool enabled = true,String? tooltip,+ String? title,}) {final choice = _launching? _LaunchChoice.values.where((item) => item.name == name).firstOrNull: null;final highlighted = choice != null && choice == _launchChoice;final disabled = !enabled || (name == 'create' ? box.busy : box.locked);- final fieldLabel = '${name[0].toUpperCase()}${name.substring(1)}';+ final fieldLabel = title ?? '${name[0].toUpperCase()}${name.substring(1)}';final checkbox =name == 'worktree' && !box.checkingGit && box.gitError == null;return MouseRegion(@@ -1051,8 +1072,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {? 'Choose a project before starting ${box.agentLabel}.': 'Return starts ${box.agentLabel} on ${box.machineLabel} in ''${box.projectLabel}'- '${box.isGitProject ? ', from ${box.branchLabel}' : ''}'- '${box.worktree ? ', in a new Git worktree' : ''}'+ '${box.gitSummary}''${box.hasModes ? ', ${box.modeLabel.toLowerCase()}' : ''}''${box.profileLabel == null ? '' : ', profile ${box.profileLabel}'}''${box.task.trim().isEmpty ? '' : ', and sends what you typed as its first message'}.';diff --git a/desktop/lib/widgets/prompt_context.dart b/desktop/lib/widgets/prompt_context.dartindex e88318376..3fa3b245d 100644--- a/desktop/lib/widgets/prompt_context.dart+++ b/desktop/lib/widgets/prompt_context.dart@@ -33,8 +33,13 @@ class PromptContextView extends StatelessWidget {store ?? appearancePrefsStore,terminalFontStore,]),- builder: (context, _) =>- _line(prefs ?? (store ?? appearancePrefsStore).value.prompt),+ builder: (context, _) => LayoutBuilder(+ builder: (context, constraints) => _line(+ prefs ?? (store ?? appearancePrefsStore).value.prompt,+ constraints.maxWidth,+ MediaQuery.textScalerOf(context),+ ),+ ),);}@@ -46,7 +51,7 @@ class PromptContextView extends StatelessWidget {height: 1.35,);- Widget _line(PromptPrefs prefs) {+ Widget _line(PromptPrefs prefs, double maxWidth, TextScaler scaler) {final data = contextData;final segments =<@@ -101,6 +106,7 @@ class PromptContextView extends StatelessWidget {];if (segments.isEmpty) return const SizedBox.shrink();final powerline = prefs.style == PromptStyle.powerline;+ final widths = _fit(segments, prefs, maxWidth, scaler);return Semantics(label: segments.map(@@ -109,63 +115,206 @@ class PromptContextView extends StatelessWidget {).join(', '),child: ExcludeSemantics(- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (var index = 0; index < segments.length; index++) ...[- if (index > 0 && !powerline) const SizedBox(width: 12),- Flexible(- child: Builder(- builder: (context) {- final part = segments[index];- final tone = prefs.color ? part.color : Colors.white60;- Widget segment = Row(- mainAxisSize: MainAxisSize.min,- children: [- if (part.ascii.isNotEmpty) ...[- if (prefs.style == PromptStyle.plain ||- part.icon == null)- Text(part.ascii, style: _style(tone))+ child: _Clipped(+ clip: widths != null,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (var index = 0; index < segments.length; index++) ...[+ if (index > 0 && !powerline) const SizedBox(width: 12),+ _Sized(+ fixed: widths != null,+ child: Builder(+ builder: (context) {+ final part = segments[index];+ final tone = prefs.color ? part.color : Colors.white60;+ final width = widths?[index];+ final style = _style(tone);+ // A folder cut short keeps both ends, the way editors+ // shorten paths; a branch keeps its start.+ final shown =+ width != null &&+ matches.isEmpty &&+ _middle(part.label) &&+ _measure(part.value, style, scaler) > width+ ? _middleEllipsis(part.value, width, style, scaler)+ : part.value;+ final text = SearchResultText(+ shown,+ matches: matches,+ style: style,+ );+ Widget segment = Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (part.ascii.isNotEmpty) ...[+ if (prefs.style == PromptStyle.plain ||+ part.icon == null)+ Text(part.ascii, style: _style(tone))+ else+ Icon(part.icon, size: size, color: tone),+ const SizedBox(width: 4),+ ],+ if (width != null)+ SizedBox(width: width, child: text)else- Icon(part.icon, size: size, color: tone),- const SizedBox(width: 4),+ Flexible(child: text),],- Flexible(- child: SearchResultText(- part.value,- matches: matches,- style: _style(tone),- ),- ),- ],- );- if (powerline) {- segment = ClipPath(- clipper: _PromptChevron(first: index == 0),- child: ColoredBox(- color: tone.withValues(alpha: .14),- child: Padding(- padding: EdgeInsets.fromLTRB(- index == 0 ? 6 : 12,- 2,- 12,- 2,+ );+ if (powerline) {+ segment = ClipPath(+ clipper: _PromptChevron(first: index == 0),+ child: ColoredBox(+ color: tone.withValues(alpha: .14),+ child: Padding(+ padding: EdgeInsets.fromLTRB(+ index == 0 ? 6 : 12,+ 2,+ 12,+ 2,+ ),+ child: segment,),- child: segment,),- ),- );- }- return segment;- },+ );+ }+ return segment;+ },+ ),),- ),+ ],],- ],+ ),),),);}++ /// Folders shorten in the middle; everything else at the end.+ static bool _middle(String label) => label == 'Project' || label.isEmpty;++ /// How much of the line each segment's text gets when it does not all fit:+ /// the project gives way first, then the machine, and the branch last, each keeping a few characters; narrower than that, all+ /// alike. Null when everything fits.+ List<double>? _fit(+ List<+ ({String label, String value, String ascii, IconData? icon, Color color})+ >+ segments,+ PromptPrefs prefs,+ double maxWidth,+ TextScaler scaler,+ ) {+ if (!maxWidth.isFinite) return null;+ final powerline = prefs.style == PromptStyle.powerline;+ final style = _style(Colors.white);+ final natural = [+ for (final part in segments) _measure(part.value, style, scaler) + 1,+ ];+ var chrome = 0.0;+ for (var index = 0; index < segments.length; index++) {+ final part = segments[index];+ if (part.ascii.isNotEmpty) {+ chrome +=+ (prefs.style == PromptStyle.plain || part.icon == null+ ? _measure(part.ascii, style, scaler)+ : size) ++ 4;+ }+ chrome += powerline ? (index == 0 ? 6 : 12) + 12 : (index > 0 ? 12 : 0);+ }+ var excess = natural.fold(chrome, (sum, width) => sum + width) - maxWidth;+ if (excess <= 0) return null;+ final widths = [...natural];+ final floor = _measure('mmmmmm…', style, scaler);+ const order = ['', 'Project', 'Machine', 'Branch', 'Harness'];+ // To a few characters each, in that order.+ for (final label in order) {+ for (var index = 0; index < segments.length && excess > 0; index++) {+ if (segments[index].label != label) continue;+ final cut = (widths[index] - floor).clamp(0.0, excess);+ widths[index] -= cut;+ excess -= cut;+ }+ }+ // Narrower still, all of them alike.+ final text = widths.fold(0.0, (sum, width) => sum + width);+ final scale = excess <= 0 || text <= 0+ ? 1.0+ : ((text - excess) / text).clamp(0.0, 1.0);+ return [for (final width in widths) (width * scale).floorToDouble()];+ }++ static final _widths = <(String, double, double), double>{};+ static double _measure(String text, TextStyle style, TextScaler scaler) {+ final key = (text, style.fontSize ?? 0, scaler.scale(100));+ final known = _widths[key];+ if (known != null) return known;+ if (_widths.length > 512) _widths.clear();+ final painter = TextPainter(+ text: TextSpan(text: text, style: style),+ textDirection: TextDirection.ltr,+ textScaler: scaler,+ maxLines: 1,+ )..layout();+ final width = painter.width;+ painter.dispose();+ return _widths[key] = width;+ }++ /// `claude-2026-…-uYONBE`: as much of both ends as fits in [width].+ static String _middleEllipsis(+ String text,+ double width,+ TextStyle style,+ TextScaler scaler,+ ) {+ String cut(int keep) => keep >= text.length+ ? text+ : '${text.substring(0, (keep + 1) ~/ 2)}…'+ '${text.substring(text.length - keep ~/ 2)}';+ var low = 0, high = text.length;+ while (low < high) {+ final mid = (low + high + 1) ~/ 2;+ if (_measure(cut(mid), style, scaler) <= width) {+ low = mid;+ } else {+ high = mid - 1;+ }+ }+ return cut(low);+ }+}++/// A line narrower than even its icons: laid out whole and clipped, rather+/// than overflowing.+class _Clipped extends StatelessWidget {+ const _Clipped({required this.clip, required this.child});++ /// Only with every segment at a fixed width; a line that fits is laid out+ /// as it always was.+ final bool clip;+ final Widget child;+ @override+ Widget build(BuildContext context) => clip+ ? ClipRect(+ child: SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ physics: const NeverScrollableScrollPhysics(),+ child: child,+ ),+ )+ : child;+}++/// A segment at the width [PromptContextView._fit] gave it, or sharing the+/// line's width with the others when it did not give one.+class _Sized extends StatelessWidget {+ const _Sized({required this.fixed, required this.child});+ final bool fixed;+ final Widget child;+ @override+ Widget build(BuildContext context) => fixed ? child : Flexible(child: child);}class _PromptChevron extends CustomClipper<Path> {diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dartindex a01bbb90c..edd917389 100644--- a/desktop/lib/widgets/swarm_search_preview.dart+++ b/desktop/lib/widgets/swarm_search_preview.dart@@ -427,11 +427,11 @@ class _AgentPreview extends StatelessWidget {overflow: TextOverflow.ellipsis,style: excerpt == null ? muted : body,),- if (project?.name != null)+ if (project != null)Padding(padding: const EdgeInsets.only(top: 8),child: Text(- [project!.name, project.branch].whereType<String>().join(' · '),+ [project.label, project.branch].whereType<String>().join(' · '),style: muted,),),diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex ff06979e6..aa70beefb 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -1895,12 +1895,6 @@ class _TerminalHeader extends StatelessWidget {pickerWidth +(onFork == null ? 0 : 30) +(agent?.viewerUrl == null && agent?.viewerError == null ? 0 : 30);- final folder =- project?.cwd- .split(RegExp(r'[/\\]'))- .where((part) => part.isNotEmpty)- .lastOrNull ??- project?.name;// A fork says so first: "forked from X" is the one fact about this pane// that the folder and the branch — shared with its source — cannot tell.final forkedFrom = agent?.forkedFrom;@@ -2139,9 +2133,18 @@ class _TerminalHeader extends StatelessWidget {].join('\n'),child: PromptContextView(contextData: PromptContext(- machine: machineName,- project: narrow ? null : folder,- branch: narrow ? null : project?.branch,+ // This computer goes without saying.+ machine: machine?.isLocalMachine == true+ ? null+ : machineName,+ // The folder as it was chosen and its repository's branch;+ // the full working folder is in the tooltip.+ project: narrow ? null : project?.label,+ // Waiting for the session's name, a branch Harness made+ // up at Start is not worth reading.+ branch: narrow || project?.branchPending == true+ ? null+ : project?.branch,leading: !narrow && forkedFrom != null? 'forked from ${forkedFrom.name}': null,diff --git a/desktop/test/git_worktree_failures_test.dart b/desktop/test/git_worktree_failures_test.dartindex 81053460d..996f38ff5 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(4));+ expect(calls, hasLength(6));expect(calls.any((args) => args.contains('switch') || args.contains('fetch')),false,@@ -148,7 +148,6 @@ void main() {'/repo',root.path,worktree: true,- label: 'Codex',startProcess: _commands(fail: 'worktree add'),),throwsA(@@ -182,7 +181,6 @@ void main() {'/unused',worktree: true,branchRef: ref,- label: 'Codex',startProcess: _commands(fail: failure),),throwsA(isA<RepositoryCloneException>()),@@ -193,7 +191,6 @@ void main() {'/repo/sub','/unused',worktree: true,- label: 'Codex',startProcess: _commands(prefix: 'sub/'),),throwsA(isA<RepositoryCloneException>()),@@ -203,7 +200,6 @@ void main() {'/repo','/unused',worktree: false,- label: 'Codex',startProcess: _commands(),),throwsA(isA<RepositoryCloneException>()),diff --git a/desktop/test/git_worktree_test.dart b/desktop/test/git_worktree_test.dartindex 6175427d8..be7f74f17 100644--- a/desktop/test/git_worktree_test.dart+++ b/desktop/test/git_worktree_test.dart@@ -1,4 +1,5 @@import 'dart:io';+import 'dart:math';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/git_worktree.dart';@@ -42,12 +43,16 @@ void main() {Future<String> worktree({String ref = 'refs/heads/feature',String? folder,- }) => ProjectFolderRequest.worktree(folder ?? repo, branchRef: ref)- .prepareLocal(- projectHome: p.join(root.path, 'harnesses'),- label: 'Codex',- now: () => DateTime(2026, 9, 21, 12),- );+ String? name,+ bool existing = false,+ }) => ProjectFolderRequest.worktree(+ folder ?? repo,+ branchRef: ref,+ branchName: name,+ existingBranch: existing,+ ).prepareLocal(projectHome: p.join(root.path, 'harnesses'));+ String worktrees() =>+ p.join(root.path, 'harnesses', 'worktrees', 'project with spaces');test('local Git discovery is read only and excludes symbolic remote refs',@@ -61,6 +66,7 @@ void main() {'origin/feature',]);expect(info.branches.last.remote, isTrue);+ expect(info.defaultRef, 'refs/remotes/origin/feature');expect(await git(['branch', '--show-current']), 'main');expect((await readLocalGitProject(root.path))['isGit'], false);expect((await readLocalGitProject('relative'))['error'], 'INVALID_PATH');@@ -81,7 +87,7 @@ void main() {'feature',);final branch = await git(['branch', '--show-current'], path);- expect(branch, startsWith('harness/'));+ expect(branch, matches(RegExp(r'^[a-z]+-[a-z]+(-\d+)?$')));branches.add(branch);}expect(branches, hasLength(2));@@ -123,8 +129,41 @@ void main() {expect(await git(['branch', '--show-current']), 'feature');expect(await git(['stash', 'list']), isEmpty);expect(await switchTo('feature'), repo);+ await git(['checkout', '--', '.']);+ await File(p.join(repo, 'notes.txt')).writeAsString('untracked');+ await expectLater(+ switchTo('main'),+ throwsA(isA<RepositoryCloneException>()),+ );+ expect(await git(['branch', '--show-current']), 'feature');});+ test(+ 'a new branch for the folder itself keeps its uncommitted work',+ () async {+ await File(p.join(repo, 'src', 'value')).writeAsString('in progress');+ final path = await ProjectFolderRequest.branch(+ repo,+ 'refs/heads/login-fix',+ newBranch: 'login-fix',+ ).prepareLocal(projectHome: root.path);+ expect(path, repo);+ expect(await git(['branch', '--show-current']), 'login-fix');+ expect(+ await File(p.join(repo, 'src', 'value')).readAsString(),+ 'in progress',+ );+ await expectLater(+ ProjectFolderRequest.branch(+ repo,+ 'refs/heads/feature',+ newBranch: 'feature',+ ).prepareLocal(projectHome: root.path),+ throwsA(isA<RepositoryCloneException>()),+ );+ },+ );+Future<String> real(String path) => Directory(path).resolveSymbolicLinks();test('a branch checked out in another worktree opens there', () async {@@ -138,43 +177,183 @@ void main() {expect(await git(['branch', '--show-current']), 'main');});+ test('placeholder branches are two words no branch uses yet', () {+ expect(placeholderBranch(const [], random: _First()), 'amber-badger');+ expect(+ placeholderBranch(const [+ 'refs/heads/amber-badger',+ 'amber-badger-2',+ ], random: _First()),+ 'amber-badger-3',+ );+ expect(worktreeFolderName('brave-otter'), 'brave-otter');+ expect(worktreeFolderName('fix/login page'), 'loginpage');+ });++ test('new worktrees are on a new branch, in a folder named for it, grouped by repository', () async {+ final made = [await worktree(), await worktree()];+ expect(made.toSet(), hasLength(2));+ for (final path in made) {+ final branch = await git(['branch', '--show-current'], path);+ expect(branch, matches(RegExp(r'^[a-z]+-[a-z]+(-\d+)?$')));+ expect(+ await git(['config', '--get', 'branch.$branch.harness']),+ 'placeholder',+ );+ expect(path, p.join(worktrees(), worktreeFolderName(branch)));+ expect(+ await git(['rev-parse', 'HEAD'], path),+ await git(['rev-parse', 'feature']),+ );+ }+ final named = await worktree(name: 'fix/login');+ expect(named, p.join(worktrees(), 'login'));+ expect(await git(['branch', '--show-current'], named), 'fix/login');+ expect(+ await git(['config', '--get', 'branch.fix/login.harness']),+ 'created',+ );+ final info = GitProjectInfo.fromJson(await readLocalGitProject(repo));+ expect(+ [+ for (final b in info.branches)+ if (b.harness) b.name,+ ]..sort(),+ [...made.map(p.basename), 'fix/login']..sort(),+ reason: 'Every branch Harness made, and only those.',+ );+ await expectLater(+ worktree(name: 'fix/login'),+ throwsA(isA<RepositoryCloneException>()),+ );+ await expectLater(+ worktree(name: 'bad..name'),+ throwsA(isA<RepositoryCloneException>()),+ );+ });+test(- 'worktrees are named for the harness and the time, grouped by repository',+ 'an existing branch is checked out as it is in a new worktree, once',() 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',+ await git(['branch', 'topic', 'main']);+ final path = await worktree(+ ref: 'refs/heads/topic',+ name: 'topic',+ existing: true,);- 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)}',- );- }+ expect(path, p.join(worktrees(), 'topic'));+ expect(await git(['branch', '--show-current'], path), 'topic');+ expect(await File(p.join(path, 'src', 'value')).readAsString(), 'main');+ await expectLater(+ worktree(ref: 'refs/heads/topic', name: 'topic', existing: true),+ throwsA(isA<RepositoryCloneException>()),+ );+ },+ );++ test('a remote base is fetched first; a remote branch is tracked under its own name', () async {+ final origin = p.join(root.path, 'origin.git');+ final upstream = p.join(root.path, 'upstream');+ await git(['clone', '--quiet', '--bare', repo, origin], root.path);+ await git(['remote', 'add', 'origin', origin]);+ await git(['fetch', '--quiet', 'origin']);+ await git(['clone', '--quiet', origin, upstream], root.path);+ for (final args in [+ ['config', 'user.name', 'Test'],+ ['config', 'user.email', '[email protected]'],+ ['config', 'commit.gpgsign', 'false'],+ ['config', 'core.hooksPath', '/dev/null'],+ ]) {+ await git(args, upstream);+ }+ await File(p.join(upstream, 'src', 'value')).writeAsString('pushed');+ await git(['commit', '-qam', 'pushed'], upstream);+ await git(['push', '--quiet', 'origin', 'main', 'main:fix/typo'], upstream);+ await git([+ 'fetch',+ '--quiet',+ 'origin',+ 'fix/typo:refs/remotes/origin/fix/typo',+ ]);+ final fresh = await worktree(+ ref: 'refs/remotes/origin/main',+ name: 'harness/fresh',+ );+ expect(+ await File(p.join(fresh, 'src', 'value')).readAsString(),+ 'pushed',+ reason: 'origin/main was fetched before the worktree started from it.',+ );+ final plain = await Process.run('git', [+ '-C',+ fresh,+ 'rev-parse',+ '--abbrev-ref',+ '@{upstream}',+ ]);+ expect(+ plain.exitCode,+ isNot(0),+ reason: 'A new branch never pushes onto its base.',+ );+ // A local branch starts from the newer of itself and its upstream.+ await git(['branch', '--set-upstream-to=origin/main', 'main']);+ await git(['update-ref', 'refs/remotes/origin/main', 'main']);+ final behind = await worktree(ref: 'refs/heads/main', name: 'from-behind');+ expect(+ await File(p.join(behind, 'src', 'value')).readAsString(),+ 'pushed',+ reason: 'main was behind origin/main, fetched at Start.',+ );+ await File(p.join(repo, 'src', 'value')).writeAsString('local');+ await git(['commit', '-qam', 'local']);+ final ahead = await worktree(ref: 'refs/heads/main', name: 'from-ahead');+ expect(+ await File(p.join(ahead, 'src', 'value')).readAsString(),+ 'local',+ reason: 'A commit only main has is never left behind.',+ );+ final tracking = await worktree(+ ref: 'refs/remotes/origin/fix/typo',+ name: 'fix/typo',+ );+ expect(+ await git(['rev-parse', '--abbrev-ref', '@{upstream}'], tracking),+ 'origin/fix/typo',+ );+ });++ test(+ 'ignored files named in .worktreeinclude are copied into new worktrees',+ () async {+ await File(p.join(repo, '.gitignore'))+ .writeAsString('.env\n*.log\nlocal/\n');+ await File(p.join(repo, '.worktreeinclude'))+ .writeAsString('.env\nlocal/\n');+ await File(p.join(repo, '.env')).writeAsString('SECRET=1');+ await File(p.join(repo, 'debug.log')).writeAsString('noise');+ await Directory(p.join(repo, 'local')).create();+ await File(p.join(repo, 'local', 'settings.json')).writeAsString('{}');+ final path = await worktree();+ expect(await File(p.join(path, '.env')).readAsString(), 'SECRET=1');+ expect(+ await File(p.join(path, 'local', 'settings.json')).readAsString(),+ '{}',+ );+ expect(await File(p.join(path, 'debug.log')).exists(), false);},);test('a linked worktree reads as its repository, and new worktrees from it join that repository', () async {- final linked = await worktree();+ final linked = await worktree(name: 'harness/linked');final info = GitProjectInfo.fromJson(await readLocalGitProject(p.join(linked, 'src')),);- expect(info.branch, 'harness/codex-0921-1200');+ expect(info.branch, 'harness/linked');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['harness/linked']!), await real(linked));expect(await real(branches['main']!), await real(repo));expect(branches['origin/feature'], isNull);expect(@@ -182,14 +361,8 @@ void main() {isNull,);expect(- await worktree(folder: linked),- p.join(- root.path,- 'harnesses',- 'worktrees',- 'project with spaces',- 'codex-0921-1200-2',- ),+ await worktree(folder: linked, name: 'harness/second'),+ p.join(worktrees(), 'second'),);});@@ -214,3 +387,13 @@ void main() {);});}++/// Always the first word of each list.+class _First implements Random {+ @override+ int nextInt(int max) => 0;+ @override+ double nextDouble() => 0;+ @override+ bool nextBool() => false;+}diff --git a/desktop/test/local_git_projects_test.dart b/desktop/test/local_git_projects_test.dartindex 138ac3fd8..36c859342 100644--- a/desktop/test/local_git_projects_test.dart+++ b/desktop/test/local_git_projects_test.dart@@ -390,9 +390,10 @@ void main() {final root = fixture.path;final main = Directory('$root/repo/.git');await main.create(recursive: true);- await File(- '${main.path}/config',- ).writeAsString('[remote "origin"]\n url = [email protected]:Team/Repo.git\n');+ await File('${main.path}/config').writeAsString(+ '[remote "origin"]\n url = [email protected]:Team/Repo.git\n'+ '[branch "feature/login"]\n\tharness = placeholder\n',+ );await File('${main.path}/HEAD').writeAsString('ref: refs/heads/main\n');await Directory('$root/repo/src').create();final tree = Directory('$root/feature');@@ -425,6 +426,12 @@ void main() {expect(reader.cached(tree.path)!.remote, project.remote);expect(reader.cached(tree.path)!.branch, 'feature/login');expect(project.name, 'repo');+ expect(project.branchPending, false);+ expect(+ reader.cached(tree.path)!.branchPending,+ true,+ reason: 'Harness made the name up; the session has not named it yet.',+ );expect(reader.cached(tree.path)!.name,'repo',diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dartindex 77109aa66..dafd5a94b 100644--- a/desktop/test/new_harness_git_test.dart+++ b/desktop/test/new_harness_git_test.dart@@ -1,10 +1,13 @@import 'dart:async';import 'dart:io';+import 'dart:math';import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/git_worktree.dart';+import 'package:harness/core/models.dart';import 'package:harness/e2ee/envelope.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/widgets/new_harness_box.dart';@@ -21,6 +24,11 @@ const _git = <String, dynamic>{{'ref': 'refs/heads/main', 'name': 'main'},{'ref': 'refs/heads/feature', 'name': 'feature'},{'ref': 'refs/remotes/origin/main', 'name': 'origin/main', 'remote': true},+ {+ 'ref': 'refs/remotes/origin/release',+ 'name': 'origin/release',+ 'remote': true,+ },],};@@ -116,10 +124,17 @@ void main() {await settle();expect(box.worktree, true);expect(box.branchRef, 'refs/heads/main');+ expect(+ box.placeholder,+ matches(RegExp(r'^[a-z]+-[a-z]+$')),+ reason: 'No login reported: the session name alone, later.',+ );expect(box.draft.projectFolderRequest!.payload, {'projectSource': 'worktree','gitSource': '/repo','branchRef': 'refs/heads/main',+ 'branchName': box.placeholder,+ 'branchMode': 'placeholder',});box.toggleWorktree();expect(box.worktree, false);@@ -250,6 +265,8 @@ void main() {'projectSource': 'worktree','gitSource': '/repo','branchRef': 'refs/heads/main',+ 'branchName': box.placeholder,+ 'branchMode': 'placeholder',});expect(connection.reads, [folder], reason: 'Branches are shared.');expect(await box.create(), NewHarnessOutcome.created);@@ -301,6 +318,303 @@ void main() {);});+ const rich = <String, dynamic>{+ 'isGit': true,+ 'root': '/repo',+ 'branch': 'main',+ 'defaultRef': 'refs/remotes/origin/main',+ 'branches': [+ {'ref': 'refs/heads/main', 'name': 'main', 'worktree': '/repo'},+ {'ref': 'refs/heads/feature', 'name': 'feature'},+ {+ 'ref': 'refs/heads/feature/pay',+ 'name': 'feature/pay',+ 'worktree': '/wt/pay',+ },+ {'ref': 'refs/heads/harness/old', 'name': 'harness/old'},+ {+ 'ref': 'refs/heads/harness/live',+ 'name': 'harness/live',+ 'worktree': '/wt/live',+ },+ {+ 'ref': 'refs/remotes/origin/main',+ 'name': 'origin/main',+ 'remote': true,+ },+ {+ 'ref': 'refs/remotes/origin/fix-typo',+ 'name': 'origin/fix-typo',+ 'remote': true,+ },+ ],+ };++ test(+ 'From is where new work starts; Branch is the branch it is on',+ () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ random: Random(7),+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ final placeholder = box.placeholder;+ expect(+ placeholder,+ matches(RegExp(r'^[a-z]+-[a-z]+$')),+ reason: 'Two words until the session names it.',+ );+ expect(box.worktree, true);+ expect(+ box.branchRowLabel,+ 'main',+ reason: 'The default branch; Start brings it up to origin/main.',+ );+ expect(box.worktreePlan!.branch, placeholder);+ expect(box.createLabel, 'Start Harness');+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'worktree',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/main',+ 'branchName': placeholder,+ 'branchMode': 'placeholder',+ });++ box.focusField(NewHarnessField.branch);+ final rows = {for (final row in box.options) row.title: row.detail};+ expect(rows.keys.first, 'main');+ expect(+ rows.containsKey('origin/main'),+ false,+ reason: 'The local main stands for it.',+ );+ expect(rows['origin/fix-typo'], 'remote');+ expect(rows['main'], 'default · current');+ expect(rows['feature/pay'], 'worktree');+ expect(rows['harness/live'], 'worktree');+ expect(+ rows.containsKey('harness/old'),+ false,+ reason: 'Nobody chose it.',+ );++ void pick(String title) {+ box.focusField(NewHarnessField.branch);+ box.accept(box.options.firstWhere((row) => row.title == title));+ }++ pick('feature');+ expect(box.branchRowLabel, 'feature');+ expect(box.worktreePlan!.kind, WorktreeStart.existingBranch);+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'worktree',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/feature',+ 'branchName': 'feature',+ 'branchMode': 'existing',+ });+ pick('feature/pay');+ expect(box.opensWorktree, true);+ expect(box.createLabel, 'Start in Worktree');+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'branch',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/feature/pay',+ });+ pick('origin/fix-typo');+ expect(box.worktreePlan!.tracks, true);+ expect(box.projectFolderRequest!.payload['branchName'], 'fix-typo');+ pick('main');+ expect(box.worktreePlan!.branch, placeholder);+ expect(box.projectFolderRequest!.payload['branchRef'], 'refs/heads/main');++ // A name no branch has: a new branch in a new worktree, from the default.+ box.focusField(NewHarnessField.branch);+ box.setQuery('my work');+ expect(box.options.last.title, 'Create branch my-work');+ expect(box.options.last.detail, 'New branch from main');+ box.accept(box.options.last);+ expect(box.branchRowLabel, 'my-work · new from main');+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'worktree',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/main',+ 'branchName': 'my-work',+ });+ box.focusField(NewHarnessField.branch);+ box.setQuery('main');+ expect(+ box.options.map((row) => row.title),+ isNot(contains('Create branch main')),+ );+ pick('main');+ expect(box.projectFolderRequest!.payload['branchMode'], 'placeholder');++ box.toggleWorktree();+ expect(box.worktree, false);+ expect(box.branchLabel, 'main');+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'branch',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/main',+ });+ pick('feature/pay');+ expect(box.createLabel, 'Start in Worktree');+ },+ );++ test(+ 'Worktree off can make a new branch for the folder, from its branch',+ () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.toggleWorktree();+ box.focusField(NewHarnessField.branch);+ box.setQuery('feature');+ expect(+ box.options.map((row) => row.title),+ isNot(contains('Create branch feature')),+ reason: 'It exists: pick it instead.',+ );+ box.setQuery('login fix');+ expect(box.options.last.title, 'Create branch login-fix');+ expect(box.options.last.detail, 'New branch from main');+ box.accept(box.options.last);+ expect(box.branchRowLabel, 'login-fix · new from main');+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'branch',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/login-fix',+ 'branchName': 'login-fix',+ });+ box.focusField(NewHarnessField.branch);+ box.accept(box.options.firstWhere((row) => row.title == 'feature'));+ expect(box.branchRowLabel, 'feature');+ expect(box.projectFolderRequest!.payload['branchName'], isNull);+ },+ );++ test('typed branch names become valid ones as they are typed', () {+ expect(branchNameFrom('john smith'), 'john-smith');+ expect(branchNameFrom(' fix: login~bug? '), 'fix-loginbug');+ expect(branchNameFrom('a..b//c/.d.lock'), 'a.b/c/d');+ expect(branchNameFrom('-.lead'), 'lead');+ expect(branchNameFrom('~^:'), '');+ });++ test('Branch starts on the branch of the pane it was opened from', () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ Future<NewHarnessController> from(String? branch) async {+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ branch: branch,+ );+ addTearDown(box.dispose);+ await settle();+ return box;+ }++ final feature = await from('feature');+ expect(feature.branchRef, 'refs/heads/feature');+ expect(feature.worktreePlan!.kind, WorktreeStart.existingBranch);+ final pay = await from('feature/pay');+ expect(pay.opensWorktree, true, reason: 'Another agent on that branch.');+ expect(pay.createLabel, 'Start in Worktree');+ final gone = await from('deleted-branch');+ expect(gone.branchRef, 'refs/heads/main', reason: 'The default instead.');+ final none = await from(null);+ expect(none.branchRef, 'refs/heads/main');+ });++ test('Create branch cleans up a typed name', () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ box.setQuery('john smith');+ expect(box.options.last.title, 'Create branch john-smith');+ box.setQuery('fix: it');+ box.accept(box.options.last);+ expect(box.projectFolderRequest!.payload['branchName'], 'fix-it');+ });++ test(+ 'Worktree off never switches a folder a harness is working in',+ () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ app.machineStates['m']!.agents = [+ const Agent(+ id: 'busy',+ name: 'Busy',+ engine: 'codex',+ project: AgentProject(name: 'repo', cwd: '/repo/cli', root: '/repo'),+ ),+ ];+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.toggleWorktree();+ box.focusField(NewHarnessField.branch);+ box.accept(box.options.firstWhere((row) => row.title == 'feature'));+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('A harness is working in this folder'));+ expect(connection.starts, isEmpty);+ },+ );++ test('a repository with no commit starts without a worktree', () async {+ final connection = _Connection()+ ..answers['/empty'] = {'isGit': true, 'branch': 'main', 'branches': []};+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/empty',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ expect(box.isGitProject, true);+ expect(box.worktree, false);+ });+testWidgets('compact launch, checkbox controls, hover selection, branch search and Cmd-Enter start',(tester) async {@@ -337,6 +651,7 @@ void main() {expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);}expect(find.text('[x]'), findsOneWidget);+ // Worktree sits just above Start.await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);await tester.sendKeyEvent(LogicalKeyboardKey.space);await tester.pump();@@ -362,7 +677,7 @@ void main() {await mouse.removePointer();expect(box.options.where(box.isCurrent).single.title, 'main');expect(- box.options.firstWhere((row) => row.title == 'origin/main').enabled,+ box.options.firstWhere((row) => row.title == 'origin/release').enabled,false,);final input = find.byKey(const ValueKey('new-harness-input'));@@ -374,14 +689,14 @@ void main() {await openLaunchRow(tester, 'worktree');expect(box.worktree, true);await openLaunchRow(tester, 'branch');- await tester.enterText(input, 'origin/main');+ await tester.enterText(input, 'origin/release');await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);await tester.pump();expect(connection.starts.single,- containsPair('branchRef', 'refs/remotes/origin/main'),+ containsPair('branchRef', 'refs/remotes/origin/release'),);expect(connection.starts.single['projectSource'], 'worktree');expect(connection.starts.single.containsKey('prompt'), false);@@ -448,7 +763,7 @@ void main() {await openLaunchRow(tester, 'branch');await tester.enterText(find.byKey(const ValueKey('new-harness-input')),- 'origin/main',+ 'origin/release',);await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();diff --git a/desktop/test/prompt_context_test.dart b/desktop/test/prompt_context_test.dartnew file mode 100644index 000000000..37cbd05bf--- /dev/null+++ b/desktop/test/prompt_context_test.dart@@ -0,0 +1,76 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/prompt_style.dart';+import 'package:harness/widgets/prompt_context.dart';++void main() {+ Future<void> line(+ WidgetTester tester,+ double width, {+ PromptStyle style = PromptStyle.symbols,+ }) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1600, 200);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Align(+ alignment: Alignment.topLeft,+ child: SizedBox(+ width: width,+ child: Align(+ alignment: Alignment.centerLeft,+ child: PromptContextView(+ prefs: PromptPrefs(style: style),+ contextData: const PromptContext(+ machine: 'mac-studio',+ project: 'autonomous-harness',+ branch: 'deehw/worktree-and-branches',+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ testWidgets(+ 'a crowded line keeps the branch and cuts the folder in the middle',+ (tester) async {+ for (final (width, style) in [+ (560.0, PromptStyle.symbols),+ (620.0, PromptStyle.powerline),+ ]) {+ await line(tester, width, style: style);+ expect(find.text('deehw/worktree-and-branches'), findsOneWidget);+ final folder = find.textContaining('…');+ expect(folder, findsOneWidget);+ final shown =+ tester.widget<Text>(folder).data ??+ tester.widget<Text>(folder).textSpan!.toPlainText();+ expect(shown, startsWith('aut'));+ expect(shown, endsWith('ess'));+ expect(tester.takeException(), isNull);+ }+ },+ );++ testWidgets('a line that fits is shown whole', (tester) async {+ await line(tester, 1590);+ expect(find.textContaining('…'), findsNothing);+ expect(find.text('autonomous-harness'), findsOneWidget);+ expect(tester.takeException(), isNull);+ });++ testWidgets('a line too narrow for every segment still lays out', (+ tester,+ ) async {+ for (final style in PromptStyle.values) {+ await line(tester, 120, style: style);+ expect(tester.takeException(), isNull);+ }+ });+}diff --git a/desktop/test/swarm_search_identity_test.dart b/desktop/test/swarm_search_identity_test.dartindex 001ec8a49..8a551155b 100644--- a/desktop/test/swarm_search_identity_test.dart+++ b/desktop/test/swarm_search_identity_test.dart@@ -355,6 +355,12 @@ void main() {expect(find.byType(ListTile), findsNWidgets(2));expect(find.byKey(const ValueKey(kSwarmCreateRowId)), findsOneWidget);// Context remains visible and searchable when drawn as separate segments.+ // A folder short of room keeps both ends; the line still reads it whole.+ bool shows(String text, String value) =>+ text == value ||+ text.contains('…') &&+ value.startsWith(text.split('…').first) &&+ value.endsWith(text.split('…').last);for (final value in ['Claude','Test host',@@ -363,10 +369,18 @@ void main() {]) {expect(find.byWidgetPredicate(- (widget) => widget is SearchResultText && widget.text == value,+ (widget) => widget is SearchResultText && shows(widget.text, value),),findsOneWidget,);+ expect(+ find.byWidgetPredicate(+ (widget) =>+ widget is Semantics &&+ (widget.properties.label ?? '').contains(value),+ ),+ findsWidgets,+ );}expect(find.textContaining('enter open', findRichText: true),diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dartindex e3948a299..36fe6df2c 100644--- a/desktop/test/terminal_panel_presentation_test.dart+++ b/desktop/test/terminal_panel_presentation_test.dart@@ -74,17 +74,76 @@ void main() {engine: 'codex',terminalAvailable: true,project: AgentProject(- name: 'Terminal project',- cwd: '/work/terminal',- branch: 'fast-focus',+ name: 'harness',+ cwd: '/work/worktrees/harness/codex-0922-1136/desktop',+ root: '/work/worktrees/harness/codex-0922-1136',+ branch: 'harness/codex-0922-1136',),),];revision.value = 2;await tester.pump();expect(find.text('Renamed terminal'), findsOneWidget);- expect(find.text('fast-focus'), findsOneWidget);- expect(find.text('terminal'), findsOneWidget);+ expect(find.text('harness/codex-0922-1136'), findsOneWidget);+ expect(+ find.text('desktop'),+ findsOneWidget,+ reason: 'A subfolder shows as itself, beside its repository branch.',+ );+ expect(find.text('codex-0922-1136'), findsNothing);+ app.machineStates['m']!.agents = [+ const Agent(+ id: 'a0',+ name: 'Renamed terminal',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(+ name: 'harness',+ cwd: '/work/worktrees/harness/codex-0922-1136',+ root: '/work/worktrees/harness/codex-0922-1136',+ branch: 'harness/codex-0922-1136',+ worktree: true,+ ),+ ),+ ];+ revision.value = 3;+ await tester.pump();+ expect(+ find.text('harness'),+ findsOneWidget,+ reason: 'A worktree root shows as its repository, never its folder.',+ );+ expect(+ find.text('codex-0922-1136'),+ findsNothing,+ reason: 'Its folder is named after the branch already shown.',+ );+ app.machineStates['m']!.agents = [+ const Agent(+ id: 'a0',+ name: 'Renamed terminal',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(+ name: 'harness',+ cwd: '/work/worktrees/harness/brave-otter',+ root: '/work/worktrees/harness/brave-otter',+ branch: 'tester/brave-otter',+ worktree: true,+ branchPending: true,+ ),+ ),+ ];+ revision.value = 4;+ await tester.pump();+ expect(find.text('harness'), findsOneWidget);+ expect(+ find.text('tester/brave-otter'),+ findsNothing,+ reason: 'A made-up branch waits for the session to name it.',+ );+ revision.value = 2;+ await tester.pump();expect(find.byTooltip('Zoom Pane'), findsOneWidget);session.status = TerminalSessionStatus.takenOver;revision.value = 3;@@ -129,7 +188,7 @@ void main() {engine: 'codex',terminalAvailable: true,project: AgentProject(- name: 'Harness project',+ name: 'harness',cwd: '/work/harness',branch: 'main',),@@ -165,14 +224,23 @@ void main() {expect(tester.widget<AnimatedOpacity>(details).opacity, 1);expect(find.text('harness'), findsOneWidget);expect(find.text('main'), findsOneWidget);- expect(- tester.getRect(find.text('Test host')).left,- greaterThan(titleBounds.right),- );- expect(- tester.getRect(find.text('harness')).left,- greaterThan(tester.getRect(find.text('Test host')).right),- );+ if (local) {+ // This computer goes without saying.+ expect(find.text('Test host'), findsNothing);+ expect(+ tester.getRect(find.text('harness')).left,+ greaterThan(titleBounds.right),+ );+ } else {+ expect(+ tester.getRect(find.text('Test host')).left,+ greaterThan(titleBounds.right),+ );+ expect(+ tester.getRect(find.text('harness')).left,+ greaterThan(tester.getRect(find.text('Test host')).right),+ );+ }expect(tester.getRect(find.text('main')).left,greaterThan(tester.getRect(find.text('harness')).right),