Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

A project that already exists: reuse the same repository's checkout; offer Use the existing folder for a typed name (#1402)

Dee081645962351
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 502ef8559..ae36b4477 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -533,6 +533,17 @@ describe('agent_create with a receipt', () => {
expect(create).not.toHaveBeenCalled()
})
+ it('records the folder a typed name found already there, so the apps can offer to start in it', async () => {
+ const { ask, status, create, replies } = setup()
+ vi.mocked(prepareProjectFolder).mockRejectedValueOnce(new ProjectFolderError('PROJECT_EXISTS', '“payments” already exists.', '/projects/payments'))
+ await ask({ engine: 'claude', projectSource: 'new', projectName: 'payments', creationId: CREATION })
+ const refused = { creationId: CREATION, state: 'failed', failure: { code: 'PROJECT_EXISTS', detail: '“payments” already exists.', existingFolder: '/projects/payments' } }
+ await vi.waitFor(() => expect(replies).toStrictEqual([refused]))
+ // Kept with the receipt: asked again, the answer is the same.
+ expect(await status({ creationId: CREATION })).toStrictEqual(refused)
+ expect(create).not.toHaveBeenCalled()
+ })
+
it('records the prepared folder of a launch that then failed, so the person can open it', async () => {
const { ask, replies } = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })
await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index e8938e126..d932ad88f 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -107,7 +107,9 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
}
catch (error) {
return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',
- detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }
+ detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.',
+ // The folder a typed name found already there: the apps offer to start in it, and `harness new` names it.
+ ...(error instanceof ProjectFolderError && error.folder ? { existingFolder: error.folder } : {}) }
}
// Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or
// the person's own repo is theirs to answer for (engines/kit/folderTrust.ts); a worktree gets only
@@ -239,7 +241,8 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors
// so clients can distinguish "safe to correct the choices" from "outcome still unknown".
if (status.state === 'failed') {
- return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error, ...(status.detail ? { detail: status.detail } : {}) } }
+ return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error,
+ ...(status.detail ? { detail: status.detail } : {}), ...(status.existingFolder ? { existingFolder: status.existingFolder } : {}) } }
}
return status
}
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 496661483..6743f108a 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -6,7 +6,7 @@ import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
export type AgentCreationOutcome =
| { state: 'created'; agentId: string; level?: 'native' | 'handoff'; resumed?: boolean }
- | { state: 'failed'; error: string; detail?: string; preparedFolder?: string }
+ | { state: 'failed'; error: string; detail?: string; preparedFolder?: string; existingFolder?: string }
| { state: 'unconfirmed' }
export type AgentCreationStatus = AgentCreationOutcome
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index a878b9cda..2f1291e8b 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -421,6 +421,30 @@ describe('harness new: the daemon', () => {
expect(claimed.err.at(-1)).toBe('Harness could not confirm the harness started (unconfirmed). Check with `harness ps --machine "Mac mini"` before starting another.')
})
+ // PROJECT_EXISTS was 4 of 7 failed starts on Oct 18: "Name its folder instead" said neither where nor how.
+ it('says where a typed project already is and the command that starts in it, or to choose another name', async () => {
+ const exists = (existingFolder?: string) => new FakeSocket((frame) => frame.type === 'agent_create' ? { creationId: 'c1', state: 'failed',
+ failure: { code: 'PROJECT_EXISTS', detail: '“payments” already exists. Select that folder from your projects.', ...(existingFolder ? { existingFolder } : {}) } } : null)
+ const here = deps(['codex', 'payments', '--name', 'pay', '--', 'add refunds'], exists('/home/me/harnesses/payments'))
+ expect(await newCommand(here)).toBe(1)
+ expect(here.err).toEqual(['“payments” already exists on this computer: ~/harnesses/payments. Choose another name for the new project, '
+ + 'or start in that folder: harness new codex ~/harnesses/payments --name pay -- …'])
+ // On another machine its path is that machine's, named as it is.
+ const there = deps(['codex', '--machine', 'Mac mini', 'payments'], exists('/home/lee/Harness Projects/payments'))
+ expect(await newCommand(there)).toBe(1)
+ expect(there.err).toEqual(['“payments” already exists on Mac mini: /home/lee/Harness Projects/payments. Choose another name for the new project, '
+ + 'or start in that folder: harness new codex --machine "Mac mini" "/home/lee/Harness Projects/payments"'])
+ const mcp = deps(['codex', '--new', 'payments', '--name', 'pay', '--task', 'add refunds'], exists('/home/me/harnesses/payments'),
+ { env: { HARNESS_VIA_MCP: '1', HOME: '/nonexistent/home', CODEX_HOME: '/nonexistent/codex' } })
+ expect(await newCommand(mcp)).toBe(1)
+ expect(mcp.err.at(-1)).toBe('“payments” already exists on this computer: ~/harnesses/payments. Choose another name for the new project, '
+ + 'or start in that folder: harness_start (folder: "~/harnesses/payments", …)')
+ // A file has that name, or the machine predates naming the folder: only another name helps.
+ const file = deps(['codex', 'payments', '--json'], exists())
+ expect(await newCommand(file)).toBe(1)
+ expect(JSON.parse(file.out[0]!)).toEqual({ ok: false, error: '“payments” already exists on this computer. Choose another name for the new project.' })
+ })
+
it('says why the machine refused an engine that cannot run, in the machine\'s words', async () => {
const d = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create' ? { creationId: 'c1', state: 'failed',
failure: { code: 'ENGINE_CANNOT_RUN', detail: 'Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory' } } : null))
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 93045e46d..4beb8ffc2 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -336,7 +336,7 @@ const ERRORS: Record<string, string> = {
INVALID_CWD: 'That folder does not exist on the machine.',
INVALID_ENGINE: 'That agent is not one this machine knows.',
INVALID_DSH: 'That harness is not in the machine\'s catalog, or does not run on that engine.',
- PROJECT_EXISTS: 'A project with that name already exists. Name its folder instead.',
+ PROJECT_EXISTS: 'A project with that name already exists. Choose another name, or name its folder to start in it.',
PROMPT_UNSUPPORTED: 'That agent cannot be started with a first message.',
PROMPT_TOO_LONG: 'A first message holds at most 2,000 characters. Put the rest in a file and name the file in it.',
SPAWN_FAILED: 'The agent could not be started.',
@@ -404,6 +404,30 @@ function projectStep(args: NewArgs, project: string, env: NodeJS.ProcessEnv): st
return `harness new ${args.agent} ${project}${name} -- …`
}
+/** How the caller starts [args] in the existing [folder] instead: the shell's words, or the tool `harness mcp` offers. */
+function folderStep(args: NewArgs, folder: string, env: NodeJS.ProcessEnv): string {
+ if (env[VIA_MCP_ENV] === '1') return `harness_start (folder: "${folder}"${args.machine === null ? '' : `, machine: "${args.machine}"`}, …)`
+ const name = args.name === null ? '' : ` --name ${/^[\w.-]+$/.test(args.name) ? args.name : JSON.stringify(args.name)}`
+ const machine = args.machine === null ? '' : ` ${machineOption(args.machine)}`
+ // Quoted, `~/` still means the home: parseNewArgs reads it, not the shell.
+ return `harness new ${args.agent}${machine} ${/^[\w./~-]+$/.test(folder) ? folder : JSON.stringify(folder)}${name}${args.prompt ? ' -- …' : ''}`
+}
+
+/**
+ * What `harness new` says when the new project it was to make is already there. A name the person chose is never quietly
+ * changed (lib/projectFolder.ts), so the ways on are that folder or another name. "Name its folder instead", followed by
+ * the app's "Select that folder from your projects", left out where the folder was and how to name one (PROJECT_EXISTS
+ * was 4 of 7 failed starts on Oct 18). The machine names the folder when it is one to start in (`existingFolder`).
+ */
+function projectExists(args: NewArgs, folder: string | null, at: { local: boolean; machine: string; home: string }, env: NodeJS.ProcessEnv): string {
+ const slug = args.projectName ? projectFolderSlug(args.projectName) : null
+ const called = slug ? `“${slug}”` : 'A project with that name'
+ if (!folder) return `${called} already exists on ${at.machine}. Choose another name for the new project.`
+ const shown = at.local ? tildeOf(folder, at.home) : folder
+ return `${called} already exists on ${at.machine}: ${shown}. Choose another name for the new project, or start in that folder: `
+ + folderStep(args, shown, env)
+}
+
/** One loopback session with the daemon: select the machine, then ask, one request at a time. */
export function daemonSession(deps: Pick<NewCommandDeps, 'port' | 'connect' | 'timeoutMs'>, machineId: string): Promise<{
request: (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>
@@ -638,9 +662,11 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
const failure = (result.failure ?? {}) as Record<string, unknown>
const code = typeof failure.code === 'string' ? failure.code : ''
const detail = typeof failure.detail === 'string' && failure.detail ? failure.detail : ''
+ const existing = typeof failure.existingFolder === 'string' && failure.existingFolder ? failure.existingFolder : null
throw new Error(result.state === 'failed'
+ ? code === 'PROJECT_EXISTS' ? projectExists(args, existing, { local, machine: machineLabel, home: deps.home }, env)
// A code this has no words for is shown by the daemon's own detail, which names the engine and why.
- ? (ERRORS[code] ? `${ERRORS[code]}${detail ? ` (${detail})` : ''}` : detail || code || 'The harness could not be started.')
+ : ERRORS[code] ? `${ERRORS[code]}${detail ? ` (${detail})` : ''}` : detail || code || 'The harness could not be started.'
: `Harness could not confirm the harness started (${String(result.state)}). Check with \`${psThere}\` before starting another.`)
}
const agent = (result.agent ?? {}) as Record<string, unknown>
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
index 381f54ea2..0b37ab0df 100644
--- a/cli/src/lib/projectFolder.spec.ts
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -1,8 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'node:child_process'
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { parseProjectFolder, prepareProjectFolder, ProjectFolderError, projectsRoot } from './projectFolder.js'
+import { parseProjectFolder, prepareProjectFolder, ProjectFolderError, projectsRoot, repositoryIdentity } from './projectFolder.js'
+
+/** A checkout at [folder] whose origin is [origin] (none when null), made by the real git, with no network. */
+function checkout(folder: string, origin: string | null): void {
+ execFileSync('git', ['init', '-q', folder])
+ if (origin !== null) execFileSync('git', ['-C', folder, 'remote', 'add', 'origin', origin])
+}
describe('project folder preparation', () => {
let root: string
@@ -43,6 +50,17 @@ describe('project folder preparation', () => {
expect(await readdir(root)).toEqual(['My-Game-v2'])
})
+ it('names the folder a typed name found, so an app can offer it, and no folder when what is there is a file', async () => {
+ await mkdir(join(root, 'payments'))
+ await expect(prepareProjectFolder({ source: 'new', name: 'payments' }, { root, label: 'Codex', now }))
+ .rejects.toMatchObject({ code: 'PROJECT_EXISTS', folder: join(root, 'payments') })
+ await writeFile(join(root, 'notes'), 'a file, not a project')
+ const refusal = await prepareProjectFolder({ source: 'new', name: 'notes' }, { root, label: 'Codex', now }).catch((error: unknown) => error)
+ expect(refusal).toMatchObject({ code: 'PROJECT_EXISTS' })
+ expect((refusal as ProjectFolderError).folder).toBeUndefined()
+ expect(await readFile(join(root, 'notes'), 'utf8')).toBe('a file, not a project')
+ })
+
it('numbers a suggested name past a folder that exists, instead of refusing it', async () => {
expect(parseProjectFolder({ projectSource: 'new', projectName: 'robot-noi-chuyen', projectNameMode: 'suggested' }))
.toEqual({ source: 'new', name: 'robot-noi-chuyen', suggested: true })
@@ -86,6 +104,69 @@ describe('project folder preparation', () => {
expect(await readFile(join(folder, 'README.md'), 'utf8')).toBe('saved checkout')
})
+ it('knows one repository however git spells it, and nothing that names no host', () => {
+ for (const address of ['https://github.com/owner/repo.git', 'https://github.com/owner/repo', 'https://github.com/owner/repo/',
+ 'https://GitHub.com/Owner/Repo.git', 'http://github.com/owner/repo', 'https://x-access-token:[email protected]/owner/repo.git',
+ '[email protected]:owner/repo.git', '[email protected]:Owner/repo', 'ssh://[email protected]/owner/repo.git', 'ssh://[email protected]:22/owner/repo',
+ 'git://github.com/owner/repo.git', ' https://github.com/owner/repo.git\n']) {
+ expect(repositoryIdentity(address), address).toBe('github.com/owner/repo')
+ }
+ expect(repositoryIdentity('https://github.com/owner/other.git')).toBe('github.com/owner/other')
+ expect(repositoryIdentity('https://gitlab.com/owner/repo.git')).toBe('gitlab.com/owner/repo')
+ for (const address of ['/srv/git/repo.git', './repo', 'file:///srv/git/repo.git', 'not a url', '', 'https://github.com/']) {
+ expect(repositoryIdentity(address), address).toBeNull()
+ }
+ })
+
+ it('starts in a checkout of the same repository already at the destination, and never clones it again', async () => {
+ const clone = vi.fn(async () => { throw new Error('must not clone') })
+ // The address asked for and the origin git keeps, in each other's spellings.
+ for (const [asked, origin] of [['owner/repo', 'https://github.com/owner/repo.git'], ['https://github.com/Owner/repo/','[email protected]:owner/repo.git'],
+ ['[email protected]:owner/repo', 'https://github.com/owner/repo'], ['https://github.com/owner/repo.git', 'ssh://[email protected]/owner/repo/']] as const) {
+ const at = await mkdtemp(join(root, 'root-'))
+ checkout(join(at, 'repo'), origin)
+ await writeFile(join(at, 'repo', 'work.txt'), 'local changes')
+ const project = parseProjectFolder({ projectSource: 'remote', repositoryUrl: asked })!
+ expect(await prepareProjectFolder(project, { root: at, clone }), asked).toBe(join(at, 'repo'))
+ expect(await readFile(join(at, 'repo', 'work.txt'), 'utf8')).toBe('local changes')
+ expect(await readdir(at)).toEqual(['repo'])
+ }
+ expect(clone).not.toHaveBeenCalled()
+ })
+
+ it('still refuses a destination holding another repository, a checkout without origin, or a folder inside a checkout', async () => {
+ const clone = vi.fn(async () => { throw new Error('must not clone') })
+ const project = parseProjectFolder({ projectSource: 'remote', repositoryUrl: 'owner/repo' })!
+ checkout(join(root, 'repo'), 'https://github.com/owner/other.git')
+ await expect(prepareProjectFolder(project, { root, clone }))
+ .rejects.toMatchObject({ code: 'PROJECT_EXISTS', message: '“repo” already exists. Select that folder from your projects.' })
+ await rm(join(root, 'repo'), { recursive: true })
+ checkout(join(root, 'repo'), 'https://gitlab.com/owner/repo.git')
+ await expect(prepareProjectFolder(project, { root, clone })).rejects.toMatchObject({ code: 'PROJECT_EXISTS' })
+ await rm(join(root, 'repo'), { recursive: true })
+ checkout(join(root, 'repo'), null)
+ await expect(prepareProjectFolder(project, { root, clone })).rejects.toMatchObject({ code: 'PROJECT_EXISTS' })
+ await rm(join(root, 'repo'), { recursive: true })
+ // The projects folder is itself that repository's checkout: `repo` inside it is a plain folder, not the checkout.
+ checkout(root, 'https://github.com/owner/repo.git')
+ await mkdir(join(root, 'repo'))
+ const refusal = await prepareProjectFolder(project, { root, clone }).catch((error: unknown) => error)
+ expect(refusal).toMatchObject({ code: 'PROJECT_EXISTS' })
+ // A clone's refusal names no folder to start in: only a typed name's does.
+ expect((refusal as ProjectFolderError).folder).toBeUndefined()
+ expect(clone).not.toHaveBeenCalled()
+ })
+
+ it('takes the checkout of the same repository another start made while this one cloned, and leaves no staging', async () => {
+ const project = parseProjectFolder({ projectSource: 'remote', repositoryUrl: 'owner/repo' })!
+ const folder = await prepareProjectFolder(project, { root, clone: async (_, destination) => {
+ await mkdir(destination)
+ checkout(join(root, 'repo'), '[email protected]:owner/repo.git')
+ } })
+ expect(folder).toBe(join(root, 'repo'))
+ expect(await readdir(root)).toEqual(['repo'])
+ })
+
it('cleans only its private staging on failure and preserves a concurrently created destination', async () => {
const project = parseProjectFolder({ projectSource: 'remote', repositoryUrl: 'owner/repo' })!
await expect(prepareProjectFolder(project, { root, clone: async (_, destination) => {
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index 40d635d2c..d7cd6f2cf 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -1,7 +1,8 @@
-import { spawn } from 'node:child_process'
-import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'
+import { execFile, spawn } from 'node:child_process'
+import { constants } from 'node:fs'
+import { access, lstat, mkdir, mkdtemp, rename, rm, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { plausibleBranchName, projectFolderName, projectFolderSlug } from './agentNames.js'
import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'
import { scmByKind } from '../scm/scmProjects.js'
@@ -21,7 +22,9 @@ export function projectsRoot(home = homedir()): string {
}
export class ProjectFolderError extends Error {
- constructor(readonly code: string, message: string) { super(message) }
+ /** [folder]: on PROJECT_EXISTS for a name the person typed, the folder already there when it is one this daemon can
+ * open, so an app can offer to start in it once the person chooses that. Never set for anything else. */
+ constructor(readonly code: string, message: string, readonly folder?: string) { super(message) }
}
// Same accepted forms as the existing desktop GitHub clone flow. Neither
@@ -89,6 +92,59 @@ async function exists(path: string): Promise<boolean> {
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error }
}
+/** A folder somebody can work in: a directory (a link to one counts) this daemon may list and enter. A file, or a folder
+ * it cannot read, is no project to offer. */
+async function openableFolder(path: string): Promise<boolean> {
+ try {
+ if (!(await stat(path)).isDirectory()) return false
+ await access(path, constants.R_OK | constants.X_OK)
+ return true
+ } catch { return false }
+}
+
+/**
+ * One repository however git spells its address: `github.com/owner/repo` for `https://github.com/Owner/Repo.git/`,
+ * `[email protected]:owner/repo`, `ssh://[email protected]:22/owner/repo.git` and `git://github.com/owner/repo`, credentials and
+ * ports left out. Lowercased: host names are case-insensitive, and so are GitHub's owner and repository names, the only
+ * host a clone is asked for (parseProjectFolder). Null for a local path or anything else that names no host.
+ */
+export function repositoryIdentity(address: string): string | null {
+ const raw = address.trim()
+ let host: string, path: string
+ // scp-like `[user@]host:path`, which has no scheme and no slash before its colon.
+ const scp = raw.includes('://') ? null : /^(?:[^@/\s]+@)?([^:/\s]+):([^\s]+)$/.exec(raw)
+ if (scp) { host = scp[1]!; path = scp[2]! }
+ else {
+ let url: URL
+ try { url = new URL(raw) } catch { return null }
+ if (!['https:', 'http:', 'ssh:', 'git:', 'git+ssh:', 'ssh+git:'].includes(url.protocol)) return null
+ host = url.hostname
+ path = url.pathname
+ }
+ path = path.replace(/^\/+/, '').replace(/\/+$/, '').replace(/\.git$/i, '')
+ return host && path ? `${host}/${path}`.toLowerCase() : null
+}
+
+/**
+ * Whether [folder] is itself a checkout whose `origin` is [repositoryUrl]. Bounded and local: `.git` is looked for before
+ * git runs (on a Mac without the Command Line Tools, `git` is Apple's stub, which opens an install dialog), git may not
+ * look above [folder] for a repository (GIT_CEILING_DIRECTORIES), and it gets four seconds, as gitProject.ts's reads do.
+ * Anything else — no `.git`, another remote, an origin git cannot read — is not that repository.
+ */
+async function holdsRepository(folder: string, repositoryUrl: string): Promise<boolean> {
+ const wanted = repositoryIdentity(repositoryUrl)
+ if (!wanted || !await exists(join(folder, '.git')).catch(() => false)) return false
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0',
+ GIT_CEILING_DIRECTORIES: dirname(folder) }
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete env[key]
+ const origin = await new Promise<string | null>((resolve) => {
+ execFile('git', ['-c', 'core.fsmonitor=false', '-C', folder, 'remote', 'get-url', 'origin'],
+ { env, timeout: 4000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 },
+ (error, stdout) => resolve(error ? null : stdout.trim()))
+ })
+ return origin !== null && repositoryIdentity(origin) === wanted
+}
+
export async function prepareProjectFolder(
project: ProjectFolder,
options: {
@@ -136,7 +192,11 @@ export async function prepareProjectFolder(
catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
if (!project.suggested) {
- throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)
+ // Refused, and the folder told, so an app can offer "Use the existing folder" (used only once the person
+ // picks it). PROJECT_EXISTS was 4 of 7 failed starts on Oct 18 (CLI 0.4.18), all from the apps, which
+ // had nothing to offer but retyping the name as a path.
+ throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`,
+ await openableFolder(folder) ? folder : undefined)
}
}
}
@@ -158,11 +218,21 @@ export async function prepareProjectFolder(
}
}
const destination = join(root, project.name)
- if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)
+ // A checkout of the very repository asked for is that project, already there: started in, never cloned again. It
+ // was refused as PROJECT_EXISTS (4 of 7 failed starts on Oct 18, CLI 0.4.18), a failed start for asking twice.
+ // Anything else there (another repository, a folder of files) is still the person's, and still refused.
+ if (await exists(destination)) {
+ if (await holdsRepository(destination, project.repositoryUrl)) return destination
+ throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)
+ }
staging = await mkdtemp(join(root, '.harness-clone-'))
const checkout = join(staging, 'checkout')
await (options.clone ?? cloneRepository)(project.repositoryUrl, checkout)
- if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” was created while cloning. Select that folder from your projects.`)
+ if (await exists(destination)) {
+ // Another start cloned the same repository meanwhile: that one is kept and this staging goes (below).
+ if (await holdsRepository(destination, project.repositoryUrl)) return destination
+ throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” was created while cloning. Select that folder from your projects.`)
+ }
await rename(checkout, destination)
return destination
} catch (error) {
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index 16e2f3cb0..b10e3a946 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -274,6 +274,14 @@ silently reused on another. Generated folders use exclusive reservation and
advance to seconds/a suffix only on a confirmed collision. Explicit names are
never silently renamed, and existing files are never overwritten.
+An explicit name whose folder already exists is refused (`PROJECT_EXISTS`).
+When what is there is a folder, the refusal names it and the form offers
+**Use the existing folder**, which switches Project to that folder on the same
+machine and starts there only when pressed; a file of that name, or another
+name or machine, offers nothing. A clone whose destination is already a
+checkout of the same repository (its `origin`, however git spells it) starts in
+that checkout instead of cloning; anything else there is still refused.
+
## Regression coverage
`tool/check_new_harness_coverage.mjs` requires 100% executable-line coverage of
@@ -318,6 +326,10 @@ not a guarantee about every possible external machine or agent failure.
- `test/generated_project_launch_test.dart` and
`test/new_harness_project_context_test.dart`: generated versus edited names,
collisions, delayed replies, and machine-specific project choices.
+- `test/project_exists_test.dart` and `test/repository_clone_test.dart`: an
+ explicit name's existing folder offered and used only when chosen, on this
+ computer and another machine, and a clone reusing a checkout of the same
+ repository. `cli/src/lib/projectFolder.spec.ts` covers the daemon's side.
- `integration_test/native_workspace_e2e_test.dart`: native onboarding,
Cmd-T/Cmd-Shift-P creation, edited defaults, Store product switching for Open/Try,
the Models menu, and terminal input immediately after starting without a
diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dart
index fc05cb740..1c527c14e 100644
--- a/desktop/lib/core/project_folder.dart
+++ b/desktop/lib/core/project_folder.dart
@@ -5,6 +5,15 @@ import 'package:path/path.dart' as p;
import 'repository_clone.dart';
import 'git_worktree.dart';
+/// A new project's name the person typed whose folder is already there. Its
+/// name is never quietly changed, so it is refused like the machine's
+/// `PROJECT_EXISTS`, with [folder] when what is there is a folder to start in
+/// — offered as "Use the existing folder", used only once they choose it.
+class ProjectExistsException extends RepositoryCloneException {
+ const ProjectExistsException(super.message, {this.folder});
+ final String? folder;
+}
+
/// Folder preparation is explicit and runs only when New Agent is submitted.
/// Existing folders continue to use the ordinary agent_create cwd payload.
class ProjectFolderRequest {
@@ -243,8 +252,13 @@ class ProjectFolderRequest {
candidate = nextGeneratedName(candidate);
continue;
}
- throw RepositoryCloneException(
+ throw ProjectExistsException(
'“$named” already exists. Choose it as an existing project.',
+ folder:
+ await FileSystemEntity.type(folder) ==
+ FileSystemEntityType.directory
+ ? folder
+ : null,
);
}
throw FileSystemException('Could not create folder', folder);
diff --git a/desktop/lib/core/repository_clone.dart b/desktop/lib/core/repository_clone.dart
index de4531138..accc3dbdb 100644
--- a/desktop/lib/core/repository_clone.dart
+++ b/desktop/lib/core/repository_clone.dart
@@ -54,17 +54,58 @@ class RepositoryCloneException implements Exception {
String toString() => message;
}
+/// One repository however git spells its address: `github.com/owner/repo`
+/// for `https://github.com/Owner/Repo.git/`, `[email protected]:owner/repo`,
+/// `ssh://[email protected]:22/owner/repo.git` and `git://…`, credentials and
+/// ports left out. Lowercased: host names are case-insensitive, and so are
+/// GitHub's owner and repository names, the only host a clone is asked for.
+/// Null for a local path or anything else that names no host. Mirrors
+/// `repositoryIdentity` in cli/src/lib/projectFolder.ts.
+String? repositoryIdentity(String address) {
+ final raw = address.trim();
+ String host, path;
+ // scp-like `[user@]host:path`: no scheme, and no slash before its colon.
+ final scp = raw.contains('://')
+ ? null
+ : RegExp(r'^(?:[^@/\s]+@)?([^:/\s]+):(\S+)$').firstMatch(raw);
+ if (scp != null) {
+ host = scp.group(1)!;
+ path = scp.group(2)!;
+ } else {
+ final uri = Uri.tryParse(raw);
+ const schemes = {'https', 'http', 'ssh', 'git', 'git+ssh', 'ssh+git'};
+ if (uri == null || !schemes.contains(uri.scheme.toLowerCase())) {
+ return null;
+ }
+ host = uri.host;
+ path = uri.path;
+ }
+ path = path
+ .replaceFirst(RegExp(r'^/+'), '')
+ .replaceFirst(RegExp(r'/+$'), '')
+ .replaceFirst(RegExp(r'\.git$', caseSensitive: false), '');
+ return host.isEmpty || path.isEmpty ? null : '$host/$path'.toLowerCase();
+}
+
typedef GitCloneProcess = Future<Process> Function(
List<String> arguments,
Map<String, String> environment,
);
+/// The `origin` of the checkout at a folder, or null when the folder is not
+/// itself one or git cannot say.
+typedef GitOriginReader = Future<String?> Function(String folder);
+
/// Clones into a private staging directory. Existing working folders are never
-/// reused or removed, and a failed/cancelled clone leaves no partial project.
+/// removed, and a failed/cancelled clone leaves no partial project. One that
+/// is already a checkout of the same repository is that project, and is used
+/// rather than refused.
class RepositoryClone {
- RepositoryClone({GitCloneProcess? startProcess})
- : _startProcess = startProcess ?? _startGit;
+ RepositoryClone({GitCloneProcess? startProcess, GitOriginReader? readOrigin})
+ : _startProcess = startProcess ?? _startGit,
+ _readOrigin = readOrigin ?? readCheckoutOrigin;
final GitCloneProcess _startProcess;
+ final GitOriginReader _readOrigin;
Process? _process;
bool _cancelled = false;
bool _started = false;
@@ -74,6 +115,68 @@ class RepositoryClone {
Map<String, String> environment,
) => Process.start('git', arguments, environment: environment);
+ /// `git remote get-url origin` in [folder], bounded: `.git` is looked for
+ /// before git runs (on a Mac without the Command Line Tools `git` is Apple's
+ /// stub, which opens an install dialog), git may not look above [folder]
+ /// (GIT_CEILING_DIRECTORIES), and it gets four seconds, as the CLI's do.
+ static Future<String?> readCheckoutOrigin(String folder) async {
+ if (await FileSystemEntity.type(
+ p.join(folder, '.git'),
+ followLinks: false,
+ ) ==
+ FileSystemEntityType.notFound) {
+ return null;
+ }
+ final Process process;
+ try {
+ process = await Process.start(
+ 'git',
+ [
+ '-c',
+ 'core.fsmonitor=false',
+ '-C',
+ folder,
+ 'remote',
+ 'get-url',
+ 'origin',
+ ],
+ environment: {
+ 'GIT_TERMINAL_PROMPT': '0',
+ 'GCM_INTERACTIVE': 'Never',
+ 'GIT_OPTIONAL_LOCKS': '0',
+ 'GIT_CEILING_DIRECTORIES': p.dirname(folder),
+ },
+ );
+ } on ProcessException {
+ return null;
+ }
+ unawaited(process.stdin.close());
+ final output = process.stdout
+ .transform(const Utf8Decoder(allowMalformed: true))
+ .join();
+ unawaited(process.stderr.drain<void>());
+ try {
+ final code = await process.exitCode.timeout(const Duration(seconds: 4));
+ final origin = (await output).trim();
+ return code == 0 && origin.isNotEmpty ? origin : null;
+ } on TimeoutException {
+ process.kill(ProcessSignal.sigkill);
+ return null;
+ }
+ }
+
+ /// Whether [folder] is a checkout of [repository]: anything else there
+ /// (another repository, a folder of files) stays the person's, refused.
+ Future<bool> _holds(String folder, GitHubRepository repository) async {
+ try {
+ final origin = await _readOrigin(folder);
+ return origin != null &&
+ repositoryIdentity(origin) == repositoryIdentity(repository.url);
+ } catch (_) {
+ return false;
+ }
+ }
+
void cancel() {
_cancelled = true;
_process?.kill();
@@ -94,6 +197,11 @@ class RepositoryClone {
final destination = p.join(parent, repository.name);
if (await FileSystemEntity.type(destination, followLinks: false) !=
FileSystemEntityType.notFound) {
+ // The repository asked for, already checked out there: started in,
+ // never cloned again, as a machine's own clone now is
+ // (cli/src/lib/projectFolder.ts). Refusing it failed the start for
+ // asking twice; PROJECT_EXISTS was 4 of 7 failed starts on Oct 18.
+ if (await _holds(destination, repository)) return destination;
throw RepositoryCloneException(
'“${repository.name}” already exists here. Choose another destination, or open that folder.',
);
@@ -154,6 +262,9 @@ class RepositoryClone {
}
if (await FileSystemEntity.type(destination, followLinks: false) !=
FileSystemEntityType.notFound) {
+ // Another start cloned the same repository meanwhile: that one is
+ // kept and this staging goes (below).
+ if (await _holds(destination, repository)) return destination;
throw RepositoryCloneException(
'“${repository.name}” was created while cloning. Choose another destination.',
);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 32d84a3bb..010b76b74 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -330,6 +330,13 @@ class AgentCreationAttempt {
/// agent choice does not clone or create the same project again.
String? get preparedFolder => _preparedFolder;
+ /// On `PROJECT_EXISTS` for a new project's name the person typed: the
+ /// folder already there, when it is one to start in. Unlike
+ /// [preparedFolder] it is only offered ("Use the existing folder"), never
+ /// used until the person chooses it.
+ String? _existingFolder;
+ String? get existingFolder => _existingFolder;
+
String? _complete(String? error) {
_finished = true;
_awaitingConfirmation = false;
@@ -13245,6 +13252,18 @@ class AppNotifier extends ChangeNotifier {
_ => 'Could not start harness: ${detail ?? code}',
};
+ /// A typed new project's name that [folder] on [machine] already has. The
+ /// machine's own words ("Select that folder from your projects") left
+ /// nothing to press: PROJECT_EXISTS was 4 of 7 failed starts on Oct 18, all
+ /// from the apps. The form offers "Use the existing folder" beside this.
+ String _projectExistsMessage(String folder, String machine) {
+ final name = folder
+ .split('/')
+ .lastWhere((part) => part.isNotEmpty, orElse: () => folder);
+ return '“$name” already exists on $machine. '
+ 'Choose another name, or use the existing folder.';
+ }
+
/// A confirmed name collision happens before any process starts. Only then
/// may an automatic suggestion advance to another name with a fresh receipt.
/// Uncertain replies always keep their original receipt and never retry.
@@ -13296,6 +13315,7 @@ class AppNotifier extends ChangeNotifier {
// Only this answer says whether it is starting; one that never reaches
// the machine (it went offline) must not be followed as if it were.
creation._starting = false;
+ creation._existingFolder = null;
final machineId = creation._machineId!;
var targetId = creation._targetId!;
final split = creation._split;
@@ -13379,6 +13399,15 @@ class AppNotifier extends ChangeNotifier {
engineIdentity(dshId).label)
: engineIdentity(choices['engine'] as String?).label,
);
+ } on ProjectExistsException catch (error) {
+ // This computer's own folder refuses a typed name as the machine
+ // does, so the form offers the folder the same way.
+ creation._refusal = 'PROJECT_EXISTS';
+ if (error.folder case final folder?) {
+ creation._existingFolder = folder;
+ return creation._complete(_projectExistsMessage(folder, machineName));
+ }
+ return creation._complete(error.message);
} on RepositoryCloneException catch (error) {
return creation._complete(error.message);
} catch (_) {
@@ -13609,6 +13638,14 @@ class AppNotifier extends ChangeNotifier {
creation._preparedFolder = folder;
}
creation._refusal = failure['code'] as String;
+ // A typed name the machine found already there, as a folder it can
+ // open (CLI `existingFolder`): said so, and offered to the person.
+ if (failure['existingFolder'] case final String folder
+ when failure['code'] == 'PROJECT_EXISTS' &&
+ folder.startsWith('/')) {
+ creation._existingFolder = folder;
+ return creation._complete(_projectExistsMessage(folder, machineName));
+ }
return creation._complete(
_creationFailureMessage(
failure['code'] as String,
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index d830f025d..1e524b000 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -3464,6 +3464,35 @@ class NewHarnessController extends ChangeNotifier {
_attempt?.awaitingConfirmation == true || integration?.pending == true;
bool get canCancelPending => _attempt?.canCancelPending == true;
+ /// The folder a new project's typed name found already there
+ /// (`PROJECT_EXISTS`), with the project and machine it was refused for.
+ (String, NewHarnessProject, String)? _existing;
+
+ /// That folder, while the same name on the same machine is still the
+ /// choice: what "Use the existing folder" starts in ([useExistingFolder]).
+ /// A name somebody chose is never quietly changed, so nothing starts there
+ /// until they press it; the refusal alone left them to retype the name as
+ /// a path (PROJECT_EXISTS was 4 of 7 failed starts on Oct 18).
+ String? get existingFolder => switch (_existing) {
+ (final folder, final project, final machine)
+ when !busy && project == _project && machine == _machineId =>
+ folder,
+ _ => null,
+ };
+
+ /// Switches Project to [existingFolder] on the same machine and starts the
+ /// harness there, as if the person had picked that folder.
+ Future<NewHarnessOutcome> useExistingFolder({bool? resendAttachments}) {
+ final folder = existingFolder;
+ if (folder == null || locked) return Future.value(NewHarnessOutcome.failed);
+ _existing = null;
+ _project = NewHarnessProject.folder(folder, exact: true);
+ if (_desktopChoices) _syncGitProject();
+ error = null;
+ notifyListeners();
+ return create(resendAttachments: resendAttachments);
+ }
+
/// The check [followHeld] is making. Nobody pressed for it, so it shows
/// nothing until it has an answer.
Future<NewHarnessOutcome>? _following;
@@ -3678,6 +3707,7 @@ class NewHarnessController extends ChangeNotifier {
background: integration != null,
beforeSubmit: integration?.beforeSubmit,
);
+ _existing = null;
_warnedAboutClosing = false;
_installing = null;
}
@@ -3862,6 +3892,18 @@ class NewHarnessController extends ChangeNotifier {
_gitProject = const GitProjectInfo();
_gitFuture = _readGitProject(_gitKey!);
}
+ final project = _project;
+ _existing =
+ attempt.refusal == 'PROJECT_EXISTS' &&
+ project.isNew &&
+ project.repository == null &&
+ project.generated == null &&
+ project.name != null
+ ? switch (attempt.existingFolder) {
+ final folder? => (folder, project, _machineId),
+ null => null,
+ }
+ : null;
return _fail(failure);
}
busy = false;
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 3865206cd..83ccc9bb4 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -897,7 +897,10 @@ class NewHarnessFormState extends State<NewHarnessForm> {
bool _checkingLaunch = false;
- Future<void> _start() async {
+ /// [existingFolder]: "Use the existing folder" was pressed, so the harness
+ /// starts in the folder the typed project name found
+ /// ([NewHarnessController.useExistingFolder]).
+ Future<void> _start({bool existingFolder = false}) async {
if (box.busy) return;
bool? resendAttachments;
if (box.needsAttachmentReview) {
@@ -936,7 +939,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
return;
}
_checkingLaunch = box.checking;
- final outcome = await box.create(resendAttachments: resendAttachments);
+ final outcome = existingFolder
+ ? await box.useExistingFolder(resendAttachments: resendAttachments)
+ : await box.create(resendAttachments: resendAttachments);
if (!mounted) return;
switch (outcome) {
case NewHarnessOutcome.created:
@@ -2213,11 +2218,20 @@ class NewHarnessFormState extends State<NewHarnessForm> {
child: const Text('Cancel request'),
);
+ /// Offered beside the refusal of a typed project name whose folder is
+ /// already there: starts in that folder, only once pressed.
+ Widget _useExistingFolderButton() => TextButton(
+ key: const ValueKey('use-existing-folder'),
+ onPressed: box.busy ? null : () => unawaited(_start(existingFolder: true)),
+ child: const Text('Use the existing folder'),
+ );
+
Widget _desktopLaunchActions() => Wrap(
spacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (box.canCancelPending) _cancelPendingButton(),
+ if (box.existingFolder != null) _useExistingFolderButton(),
_desktopStartButton(),
],
);
@@ -2987,6 +3001,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
_buildButton(),
if (box.canCancelPending) _cancelPendingButton(),
+ if (box.existingFolder != null) _useExistingFolderButton(),
if (!_picking && box.requiredChoice != null) ...[
SizedBox(height: _rowHeight),
Padding(
diff --git a/desktop/test/cloud_agents_test.dart b/desktop/test/cloud_agents_test.dart
index a3a955075..0c46b6f42 100644
--- a/desktop/test/cloud_agents_test.dart
+++ b/desktop/test/cloud_agents_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/state/new_harness.dart';
import 'package:harness/state/workspace_status.dart';
import 'package:harness/widgets/cloud_chat_pane.dart';
import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/ws/ws_conn.dart';
import 'support/rename_connection.dart';
@@ -424,6 +425,86 @@ void main() {
);
});
+ test('New Harness sends a coding cloud agent its repository, and a box closed mid-create says nothing', () async {
+ final connection = CreateConnection();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ final devin = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'devin-cloud',
+ );
+ addTearDown(devin.dispose);
+ devin.focusField(NewHarnessField.projectRepository);
+ devin.setQuery('acme/api');
+ devin.accept();
+ expect(devin.cloudRepository, 'https://github.com/acme/api.git');
+ devin.setTask('fix the flaky login test');
+ expect(devin.requiredChoice, isNull);
+ expect(await devin.create(), NewHarnessOutcome.created);
+ expect(
+ connection.creates.single,
+ containsPair('repositoryUrl', 'https://github.com/acme/api.git'),
+ );
+ expect(connection.creates.single, containsPair('acuLimit', 5));
+
+ // Closed while the cloud service makes it: nothing is said to a box
+ // that is gone.
+ final fo = NewHarnessController(app, machineId: 'm', engine: 'fo');
+ fo.setTask('book a haircut');
+ final made = fo.create();
+ fo.dispose();
+ expect(await made, NewHarnessOutcome.failed);
+ expect(connection.creates, hasLength(2));
+ });
+
+ testWidgets(
+ 'each press of Devin Cloud\'s limit steps to the next, round to the first',
+ (tester) async {
+ final connection = CreateConnection();
+ final app = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ addTearDown(app.dispose);
+ final devin = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'devin-cloud',
+ );
+ addTearDown(devin.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 1000,
+ height: 600,
+ child: NewHarnessForm(
+ controller: devin,
+ onClose: () {},
+ onCreated: () {},
+ desktop: true,
+ embedded: true,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final limit = find.byKey(const ValueKey('new-harness-field-acu'));
+ expect(devin.acuLimit, 5);
+ for (final next in [10, 20, 2, 5]) {
+ await tester.tap(limit);
+ await tester.pumpAndSettle();
+ expect(devin.acuLimit, next);
+ }
+ expect(find.text('Up to 5 ACUs'), findsOneWidget);
+ },
+ );
+
testWidgets('the dial scrolls a focused cloud conversation', (tester) async {
final (app, connection) = await setUp(tester, cloudFrame());
connection.extraMessages = 60;
diff --git a/desktop/test/new_harness_attachments_test.dart b/desktop/test/new_harness_attachments_test.dart
index ea4e280c5..ee0d0813e 100644
--- a/desktop/test/new_harness_attachments_test.dart
+++ b/desktop/test/new_harness_attachments_test.dart
@@ -9,10 +9,56 @@ import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/attached_task_delivery.dart';
import 'package:harness/state/harness_attachments.dart';
import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// A machine that makes the harness asked for, and never opens its terminal.
+class _Machine extends WsConn {
+ _Machine()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final creates = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'engines_probe':
+ return {
+ 'engines': [
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ case 'git_project_info':
+ return {'isGit': false};
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'made', 'name': 'Made', 'engine': 'claude'},
+ };
+ default:
+ return {};
+ }
+ }
+}
class _Notifier extends AppNotifier {
_Notifier()
@@ -121,6 +167,43 @@ void main() {
expect(problems.single, contains('without its files'));
});
+ testWidgets(
+ 'a created harness is handed its files, and one whose pane never opens is said',
+ (tester) async {
+ final machine = _Machine();
+ final notifier = createApp(
+ connectionForTest: (_) => machine,
+ connected: true,
+ );
+ addTearDown(notifier.dispose);
+ notifier.machineStates['m']!
+ ..terminalPasteFileAvailable = true
+ ..terminalPasteRawAvailable = true;
+ final problems = <String>[];
+ final files = HarnessAttachments(onDeliveryProblem: problems.add)
+ ..add([HarnessAttachment('shot.png', Uint8List(4))]);
+ final box = NewHarnessController(
+ notifier,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work/desk',
+ task: 'đọc ảnh',
+ attachments: files,
+ );
+ addTearDown(box.dispose);
+ expect(await box.create(), NewHarnessOutcome.created);
+ // Created without its task, which waits for the files.
+ expect(machine.creates.single.containsKey('prompt'), isFalse);
+ expect(files.files, isEmpty);
+ await tester.pump(kAttachedTaskOpenTimeout - const Duration(seconds: 1));
+ expect(problems, isEmpty);
+ await tester.pump(const Duration(seconds: 2));
+ expect(problems, [
+ 'The harness did not open in time. Attach the files in its pane.',
+ ]);
+ },
+ );
+
test('without files the task still launches with the engine', () async {
final notifier = app();
final box = NewHarnessController(
diff --git a/desktop/test/new_harness_controller_edges_test.dart b/desktop/test/new_harness_controller_edges_test.dart
index 7f0507e65..9b5ecaf5c 100644
--- a/desktop/test/new_harness_controller_edges_test.dart
+++ b/desktop/test/new_harness_controller_edges_test.dart
@@ -792,6 +792,25 @@ void main() {
expect((await open(fixture)).engine, 'codex');
});
+ test('a suggested project is renamed for that agent', () async {
+ final fixture = _Fixture();
+ fixture.connection.replies['engines_probe'] = (_) => probe();
+ final box = NewHarnessController(
+ fixture.app,
+ machineId: 'm',
+ autoProject: true,
+ now: () => DateTime(2026, 9, 25, 9, 10, 11),
+ );
+ addTearDown(box.dispose);
+ // Named after the product default until the machine says otherwise.
+ expect(box.engine, 'opencode');
+ expect(box.project.name, 'opencode-2026-09-25-09-10');
+ await _settle();
+ expect(box.engine, 'claude');
+ expect(box.project.name, 'claude-2026-09-25-09-10');
+ expect(box.projectFolderRequest!.isGenerated, isTrue);
+ });
+
test('a remembered choice still wins', () async {
final fixture = _Fixture();
fixture.connection.replies['engines_probe'] = (_) => probe();
diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dart
index f55355138..5acbcb2a5 100644
--- a/desktop/test/new_harness_form_test.dart
+++ b/desktop/test/new_harness_form_test.dart
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/terminal/terminal_theme.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
@@ -53,6 +55,18 @@ class _Git extends WsConn {
}
}
+/// A controller whose list is what the test gives it: the form draws whatever
+/// a controller lists, including shapes today's lists do not have (headings
+/// outside Model, a folder on another machine in the desktop chooser).
+class _Listed extends NewHarnessController {
+ _Listed(super.app, {required super.machineId, super.folder});
+
+ List<NewHarnessOption>? listed;
+
+ @override
+ List<NewHarnessOption> get options => listed ?? super.options;
+}
+
void main() {
Future<NewHarnessController> mount(
WidgetTester tester, {
@@ -895,4 +909,85 @@ void main() {
expect(harnessChoicesActive(tester), isTrue);
expect(find.text('Select Item'), findsNothing);
});
+
+ testWidgets(
+ 'the desktop chooser heads any grouped list in small type, and names another machine\'s folder',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1100, 800);
+ addTearDown(tester.view.reset);
+ final app = createApp(connectionForTest: (_) => _Git(), connected: true);
+ app.machineStates['other'] = MachineState(
+ const Machine(
+ machineId: 'other',
+ name: 'Other Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ );
+ addTearDown(app.dispose);
+ final box = _Listed(app, machineId: 'm', folder: '/work/repo');
+ addTearDown(box.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ desktop: true,
+ embedded: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-project')));
+ await tester.pumpAndSettle();
+ expect(box.field, isNot(NewHarnessField.model));
+ box.listed = const [
+ NewHarnessOption(
+ id: 'project:here',
+ title: 'repo',
+ detail: 'Test host:~/work/repo',
+ group: 'This computer',
+ project: NewHarnessProject.folder('/work/repo'),
+ machineId: 'm',
+ ),
+ NewHarnessOption(
+ id: 'project:other',
+ title: 'site',
+ detail: 'Other Mac:~/site',
+ group: 'Other Mac',
+ project: NewHarnessProject.folder('/Users/lee/site'),
+ machineId: 'other',
+ ),
+ ];
+ // A search redraws the list; this one lists the same two whatever is typed.
+ box.setQuery('s');
+ await tester.pumpAndSettle();
+ for (final heading in ['This computer', 'Other Mac']) {
+ final text = tester.widget<Text>(find.text(heading));
+ expect(text.style?.fontSize, 11);
+ }
+ // This machine's folder by its path; another's with that machine's name.
+ expect(find.text('~/work/repo'), findsOneWidget);
+ expect(find.text('Other Mac · ~/site'), findsOneWidget);
+ },
+ );
+
+ testWidgets('a dismiss sent to the query field does what Escape does', (
+ tester,
+ ) async {
+ final box = await mount(tester, engine: 'codex');
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectMenu);
+ final query = find.byKey(const ValueKey('new-harness-query'));
+ Actions.invoke(tester.element(query), const DismissIntent());
+ await tester.pumpAndSettle();
+ final dismissed = box.field;
+ await press(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectMenu);
+ await press(tester, LogicalKeyboardKey.escape);
+ expect(box.field, dismissed);
+ });
}
diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dart
index 423ca4722..416863bb2 100644
--- a/desktop/test/new_harness_models_test.dart
+++ b/desktop/test/new_harness_models_test.dart
@@ -385,6 +385,49 @@ void main() {
expect(connections['m']!.creates.single.keys, isNot(contains('gridModel')));
expect(connections['m']!.creates.single.keys, isNot(contains('gridName')));
});
+ testWidgets(
+ 'the desktop Model chooser heads each list, a line above every list after the first',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1100, 800);
+ addTearDown(tester.view.reset);
+ final box = controller();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: NewHarnessForm(
+ controller: box,
+ onClose: () {},
+ onCreated: () {},
+ desktop: true,
+ embedded: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-model')));
+ await tester.pumpAndSettle();
+ expect(box.field, NewHarnessField.model);
+ Border? lineAbove(String heading) =>
+ (tester
+ .widget<Container>(
+ find
+ .ancestor(
+ of: find.text(heading),
+ matching: find.byType(Container),
+ )
+ .first,
+ )
+ .decoration
+ as BoxDecoration?)
+ ?.border
+ as Border?;
+ expect(lineAbove('Subscription'), isNull);
+ expect(lineAbove('Your models')?.top.width, greaterThan(0));
+ expect(lineAbove('Shared with you')?.top.width, greaterThan(0));
+ },
+ );
testWidgets(
'switching from a model to Terminal clears routing and still opens a shell',
(tester) async {
diff --git a/desktop/test/project_exists_test.dart b/desktop/test/project_exists_test.dart
new file mode 100644
index 000000000..9c2dfdd4e
--- /dev/null
+++ b/desktop/test/project_exists_test.dart
@@ -0,0 +1,323 @@
+// A new project's name the person typed whose folder is already there is
+// refused, never quietly changed (PROJECT_EXISTS). That refusal was 4 of 7
+// failed starts on Oct 18 (CLI 0.4.18), all from the apps, and it left only
+// retyping the name as a path. The form now offers "Use the existing folder",
+// which starts there only once it is pressed.
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:path/path.dart' as p;
+
+const _folder = '/home/lee/harnesses/payments';
+
+/// A machine whose `agent_create` refuses a new project with [refusal].
+class _Machine extends WsConn {
+ _Machine(String id)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: id,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final creates = <Map<String, dynamic>>[];
+
+ /// The failure a create with `projectSource` gets; null starts it.
+ Map<String, dynamic>? refusal = {
+ 'code': 'PROJECT_EXISTS',
+ 'detail':
+ '“payments” already exists. Select that folder from your projects.',
+ 'existingFolder': _folder,
+ };
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'engines_probe':
+ return {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ ],
+ };
+ case 'dsh_list':
+ return {'dsh': []};
+ case 'fs_list_dir':
+ return {'path': payload['path'] ?? '/home/lee', 'entries': []};
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ if (payload['projectSource'] != null && refusal != null) {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': refusal,
+ };
+ }
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'made-${creates.length}',
+ 'name': 'Payments',
+ 'engine': 'codex',
+ },
+ };
+ default:
+ return {};
+ }
+ }
+}
+
+class _App extends AppNotifier {
+ _App(this.root, Map<String, _Machine> connections)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => connections[id]!,
+ ) {
+ machines = [
+ for (final id in connections.keys)
+ Machine(machineId: id, name: id, authMode: MachineAuthMode.remote),
+ ];
+ for (final machine in machines) {
+ machineStates[machine.machineId] = MachineState(machine)
+ ..localOnly = machine.machineId == 'local'
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ }
+ gitProjectReaderForTest = (_, _) async => {'isGit': false};
+ status = AppStatus.authenticated;
+ }
+ final String root;
+ @override
+ Future<String> prepareLocalProjectFolder(
+ ProjectFolderRequest request, {
+ String label = 'harness',
+ }) => request.prepareLocal(projectHome: root, label: label);
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory home;
+ late _App app;
+ late Map<String, _Machine> machines;
+ setUp(() async {
+ home = await Directory.systemTemp.createTemp('harness-project-exists-');
+ machines = {
+ for (final id in ['local', 'office']) id: _Machine(id),
+ };
+ app = _App(p.join(home.path, 'harnesses'), machines);
+ });
+ tearDown(() async {
+ app.dispose();
+ for (final machine in machines.values) {
+ await machine.close();
+ }
+ await home.delete(recursive: true);
+ });
+
+ NewHarnessController box(String machine, {String? name = 'payments'}) {
+ final box = NewHarnessController(
+ app,
+ machineId: machine,
+ engine: 'codex',
+ projectName: name,
+ home: home.path,
+ placement: HarnessPlacement.newTab,
+ );
+ addTearDown(box.dispose);
+ return box;
+ }
+
+ test('a typed name another machine already has offers its folder, and starts there only once chosen', () async {
+ final draft = box('office');
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(
+ draft.error,
+ '“payments” already exists on office. '
+ 'Choose another name, or use the existing folder.',
+ );
+ expect(draft.existingFolder, _folder);
+ // Offered, not taken: nothing else was asked of the machine.
+ expect(machines['office']!.creates, hasLength(1));
+ expect(draft.project.name, 'payments');
+
+ expect(await draft.useExistingFolder(), NewHarnessOutcome.created);
+ final started = machines['office']!.creates.last;
+ expect(started['cwd'], _folder);
+ expect(started.containsKey('projectSource'), isFalse);
+ expect(started.containsKey('projectName'), isFalse);
+ expect(machines['office']!.creates, hasLength(2));
+ expect(draft.project.folder, _folder);
+ expect(draft.existingFolder, isNull);
+ });
+
+ test('nothing is offered for a refusal with no folder to start in, or any other refusal', () async {
+ // What is there is a file, or the machine predates naming the folder.
+ machines['office']!.refusal = {
+ 'code': 'PROJECT_EXISTS',
+ 'detail':
+ '“payments” already exists. Select that folder from your projects.',
+ };
+ final file = box('office');
+ expect(await file.create(), NewHarnessOutcome.failed);
+ expect(file.error, contains('already exists'));
+ expect(file.existingFolder, isNull);
+ expect(await file.useExistingFolder(), NewHarnessOutcome.failed);
+ expect(machines['office']!.creates, hasLength(1));
+
+ machines['office']!.refusal = {
+ 'code': 'INVALID_DSH',
+ 'detail': 'Install it first.',
+ 'existingFolder': _folder,
+ };
+ final other = box('office');
+ expect(await other.create(), NewHarnessOutcome.failed);
+ expect(other.existingFolder, isNull);
+ });
+
+ test('a clone refused for its destination offers nothing: only a typed name does', () async {
+ final draft = box('office', name: null);
+ draft.focusField(NewHarnessField.projectRepository);
+ draft.setQuery('owner/payments');
+ draft.accept();
+ expect(draft.project.repository?.name, 'payments');
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(machines['office']!.creates.single['repositoryUrl'], isNotNull);
+ expect(draft.existingFolder, isNull);
+ });
+
+ test('another name, or another machine, takes the offer away', () async {
+ final draft = box('office');
+ await draft.create();
+ expect(draft.existingFolder, _folder);
+ draft.focusField(NewHarnessField.machine);
+ draft.setQuery('local');
+ draft.accept();
+ expect(draft.machineId, 'local');
+ expect(draft.existingFolder, isNull);
+ draft.focusField(NewHarnessField.machine);
+ draft.setQuery('office');
+ draft.accept();
+ expect(draft.machineId, 'office');
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('refunds');
+ draft.accept();
+ expect(draft.project.name, 'refunds');
+ expect(draft.existingFolder, isNull);
+ expect(await draft.useExistingFolder(), NewHarnessOutcome.failed);
+ expect(machines['office']!.creates, hasLength(1));
+ });
+
+ test('this computer refuses a typed name the same way, and starts in that folder once chosen', () async {
+ final existing = Directory(p.join(app.root, 'payments'));
+ await existing.create(recursive: true);
+ final keep = File(p.join(existing.path, 'keep.txt'));
+ await keep.writeAsString('untouched');
+ final draft = box('local');
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(draft.error, contains('“payments” already exists on local.'));
+ expect(draft.existingFolder, existing.path);
+ expect(machines['local']!.creates, isEmpty);
+
+ expect(await draft.useExistingFolder(), NewHarnessOutcome.created);
+ expect(machines['local']!.creates.single['cwd'], existing.path);
+ expect(await keep.readAsString(), 'untouched');
+ expect(
+ await Directory(app.root).list().map((e) => p.basename(e.path)).toList(),
+ ['payments'],
+ );
+ });
+
+ test(
+ 'on this computer a file with that name is no folder to offer',
+ () async {
+ await Directory(app.root).create(recursive: true);
+ await File(p.join(app.root, 'payments')).writeAsString('notes');
+ final draft = box('local');
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(
+ draft.error,
+ '“payments” already exists. Choose it as an existing project.',
+ );
+ expect(draft.existingFolder, isNull);
+ expect(machines['local']!.creates, isEmpty);
+ },
+ );
+
+ for (final desktop in [true, false]) {
+ testWidgets(
+ 'the ${desktop ? 'desktop' : 'line'} form shows Use the existing folder after the refusal, and pressing it starts there',
+ (tester) async {
+ final draft = box('office');
+ var created = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 1000,
+ height: 700,
+ child: NewHarnessForm(
+ controller: draft,
+ onClose: () {},
+ onCreated: () => created++,
+ desktop: desktop,
+ embedded: desktop,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final offer = find.byKey(const ValueKey('use-existing-folder'));
+ expect(offer, findsNothing);
+
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ '“payments” already exists on office. '
+ 'Choose another name, or use the existing folder.',
+ ),
+ findsOneWidget,
+ );
+ expect(offer, findsOneWidget);
+ expect(
+ find.descendant(
+ of: offer,
+ matching: find.text('Use the existing folder'),
+ ),
+ findsOneWidget,
+ );
+ expect(created, 0);
+
+ await tester.ensureVisible(offer);
+ await tester.tap(offer);
+ await tester.pumpAndSettle();
+ expect(created, 1);
+ expect(machines['office']!.creates.last['cwd'], _folder);
+ expect(machines['office']!.creates, hasLength(2));
+ },
+ );
+ }
+}
diff --git a/desktop/test/repository_clone_test.dart b/desktop/test/repository_clone_test.dart
index 71ac91e41..3e0caf3c9 100644
--- a/desktop/test/repository_clone_test.dart
+++ b/desktop/test/repository_clone_test.dart
@@ -99,6 +99,118 @@ void main() {
expect(await draft.readAsString(), 'keep this');
});
+ test('knows one repository however git spells it', () {
+ for (final address in [
+ 'https://github.com/owner/project.git',
+ 'https://github.com/owner/project/',
+ 'https://GitHub.com/Owner/Project',
+ 'https://x-access-token:[email protected]/owner/project.git',
+ '[email protected]:owner/project.git',
+ 'ssh://[email protected]:22/owner/project',
+ 'git://github.com/owner/project.git',
+ ]) {
+ expect(
+ repositoryIdentity(address),
+ 'github.com/owner/project',
+ reason: address,
+ );
+ }
+ for (final address in ['/srv/git/project.git', 'file:///srv/project', '']) {
+ expect(repositoryIdentity(address), isNull, reason: address);
+ }
+ });
+
+ // PROJECT_EXISTS was 4 of 7 failed starts on Oct 18: a clone of a
+ // repository already checked out where it would go was refused.
+ test('a checkout of the same repository at the destination is used, never cloned again', () async {
+ for (final (asked, origin) in [
+ ('owner/project', 'https://github.com/owner/project.git'),
+ ('[email protected]:owner/project.git', 'https://github.com/owner/project'),
+ ('https://github.com/Owner/project/', '[email protected]:owner/project.git'),
+ ]) {
+ final parent = await root.createTemp('parent-');
+ final existing = p.join(parent.path, 'project');
+ expect((await Process.run('git', ['init', '-q', existing])).exitCode, 0);
+ expect(
+ (await Process.run('git', [
+ '-C',
+ existing,
+ 'remote',
+ 'add',
+ 'origin',
+ origin,
+ ])).exitCode,
+ 0,
+ );
+ final draft = File(p.join(existing, 'draft.txt'));
+ await draft.writeAsString('keep this');
+ final clone = RepositoryClone(
+ startProcess: (_, _) => throw StateError('Must not start'),
+ );
+ expect(
+ await clone.run(GitHubRepository.parse(asked)!, parent.path),
+ existing,
+ reason: asked,
+ );
+ expect(await draft.readAsString(), 'keep this');
+ expect(
+ (await parent.list().toList()).map((entry) => p.basename(entry.path)),
+ ['project'],
+ );
+ }
+ });
+
+ test('the same repository checked out there while cloning is used, and staging goes', () async {
+ final parent = await Directory(p.join(root.path, 'projects')).create();
+ final existing = p.join(parent.path, 'project');
+ final clone = RepositoryClone(
+ startProcess: (arguments, environment) async {
+ // Another start finishes its clone of the same repository first.
+ await Process.run('git', ['init', '-q', existing]);
+ await Process.run('git', [
+ '-C',
+ existing,
+ 'remote',
+ 'add',
+ 'origin',
+ '[email protected]:owner/project.git',
+ ]);
+ return Process.start('git', ['init', '-q', arguments.last]);
+ },
+ );
+ expect(
+ await clone.run(GitHubRepository.parse('owner/project')!, parent.path),
+ existing,
+ );
+ expect(
+ (await parent.list().toList()).map((entry) => p.basename(entry.path)),
+ ['project'],
+ );
+ });
+
+ test(
+ 'a checkout of another repository at the destination is still refused',
+ () async {
+ final existing = p.join(root.path, 'project');
+ final clone = RepositoryClone(
+ startProcess: (_, _) => throw StateError('Must not start'),
+ readOrigin: (folder) async =>
+ folder == existing ? 'https://github.com/owner/other.git' : null,
+ );
+ await Directory(existing).create();
+ await expectLater(
+ clone.run(GitHubRepository.parse('owner/project')!, root.path),
+ throwsA(
+ isA<RepositoryCloneException>().having(
+ (e) => e.message,
+ 'message',
+ contains('already exists'),
+ ),
+ ),
+ );
+ },
+ );
+
test(
'failed Git does not leave a partial project or expose diagnostics',
() async {