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.

Prepare remote project folders within agent creation receipts

dee9d0150d15ce7
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 206578a05..5e2e7621e 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -7,6 +7,7 @@ import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
import * as mediaPreview from './lib/mediaPreview.js'
+import * as projectFolder from './lib/projectFolder.js'
import { randomUUID } from 'node:crypto'
const wsMock = vi.hoisted(() => {
@@ -606,6 +607,42 @@ describe('BackendSocket outbound queue', () => {
}
})
+ it('prepares a remote project once under its creation receipt and retains its folder after a refused launch', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ let finish!: (folder: string) => void
+ const prepare = vi.spyOn(projectFolder, 'prepareProjectFolder').mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const create = vi.fn(async () => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))
+ socket.onCreateAgent = create
+ const creationId = randomUUID()
+ const payload = { creationId, engine: 'claude', projectSource: 'remote', repositoryUrl: 'owner/repo' }
+ const ask = (type: string, requestId: string, choices = payload) => socket.handleLocalFrame('local:project', { type, payload: { requestId, ...choices } })
+ try {
+ ask('agent_create', 'first')
+ await vi.waitFor(() => expect(prepare).toHaveBeenCalledTimes(1))
+ ask('agent_create', 'retry')
+ ask('agent_create_status', 'pending')
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'pending', state: 'pending' }) })))
+ expect(create).not.toHaveBeenCalled()
+ finish('/remote/Harness Projects/repo')
+ for (const requestId of ['first', 'retry']) {
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId, state: 'failed', preparedFolder: '/remote/Harness Projects/repo', failure: { code: 'TMUX_UNAVAILABLE' } }) })))
+ }
+ expect(create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ cwd: '/remote/Harness Projects/repo' }))
+ expect(prepare).toHaveBeenCalledTimes(1)
+ ask('agent_create', 'changed', { ...payload, repositoryUrl: 'owner/different' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'changed', error: 'CREATION_CONFLICT' }) })))
+ expect(prepare).toHaveBeenCalledTimes(1)
+ ask('agent_create_status', 'saved')
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'saved', preparedFolder: '/remote/Harness Projects/repo' }) })))
+ } finally {
+ finish?.('/remote/Harness Projects/repo')
+ await socket.unregisterLocalClient('local:project')
+ await socket.stop()
+ }
+ })
+
it('checks an unknown creation without spawning and rejects malformed creation ids before launch', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 59946e6bb..6510ff46b 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -32,6 +32,7 @@ import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.j
import { probeEngines } from './lib/engineProbe.js'
import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
+import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
@@ -1556,12 +1557,20 @@ export class BackendSocket {
const engine = payload.engine as AgentEngine | undefined
const cwd = payload.cwd
if (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }
- if (typeof cwd !== 'string' || !isAbsolute(cwd)) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
+ let projectFolder
+ try { projectFolder = parseProjectFolder(payload) }
+ catch (error) {
+ reply(type, requestId, { error: error instanceof ProjectFolderError ? error.code : 'INVALID_PROJECT_SOURCE' }); return
+ }
+ if (!projectFolder && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
if (!this.onCreateAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
const creationId = payload.creationId
if (creationId !== undefined && !validCreationId(creationId)) {
reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return
}
+ if (projectFolder && (!validCreationId(creationId) || cwd !== undefined)) {
+ reply(type, requestId, { error: 'INVALID_PROJECT_SOURCE' }); return
+ }
// Absent is the ordinary case and stays indistinguishable from a client that predates grids;
// present-but-malformed is refused here rather than half-applied at launch, because an agent
// that quietly ran on the engine's own login would look like it worked.
@@ -1581,7 +1590,7 @@ export class BackendSocket {
}
const input = {
engine,
- cwd,
+ cwd: typeof cwd === 'string' ? cwd : '',
bypassPermission: payload.bypassPermission === true,
grid: grid.state === 'ok' ? grid.override : null,
codexHome,
@@ -1592,13 +1601,21 @@ export class BackendSocket {
// on this connection, just as engines_probe is detached above.
const create = this.onCreateAgent
try {
- void this.agentCreations.run(creationId, creationFingerprint(input), async () => {
- const result = await create(input)
+ void this.agentCreations.run(creationId, creationFingerprint(projectFolder ? { ...input, projectFolder } : input), async () => {
+ let preparedFolder: string | undefined
+ if (projectFolder) {
+ try { preparedFolder = await prepareProjectFolder(projectFolder) }
+ 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.' }
+ }
+ }
+ const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)
if (result.ok) return { state: 'created', agentId: result.session.agentId }
// tmux may have executed before a timeout; registration cleanup is best-effort.
// Neither can prove that no process started, so never encourage another launch.
if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }
- return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
}).then(async (status) => {
reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })
}).catch(() => reply(type, requestId, { error: 'INTERNAL' }))
@@ -1828,7 +1845,7 @@ export class BackendSocket {
// 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', 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 } : {}) } }
}
return status
}
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index ebde79314..384292b14 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -5,7 +5,7 @@ import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
export type AgentCreationOutcome =
| { state: 'created'; agentId: string }
- | { state: 'failed'; error: string; detail?: string }
+ | { state: 'failed'; error: string; detail?: string; preparedFolder?: string }
| { state: 'unconfirmed' }
export type AgentCreationStatus = AgentCreationOutcome
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
new file mode 100644
index 000000000..44587739d
--- /dev/null
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+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 } from './projectFolder.js'
+
+describe('project folder preparation', () => {
+ let root: string
+ beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'harness-project-test-')) })
+ afterEach(async () => { await rm(root, { recursive: true, force: true }) })
+
+ it('accepts the existing GitHub forms and rejects credentials, helpers and ambiguous source choices', () => {
+ expect(parseProjectFolder({})).toBeNull()
+ expect(parseProjectFolder({ projectSource: 'new' })).toEqual({ source: 'new' })
+ for (const url of ['owner/repo', 'https://github.com/owner/repo.git', '[email protected]:owner/repo']) {
+ expect(parseProjectFolder({ projectSource: 'remote', repositoryUrl: url })).toMatchObject({ source: 'remote', name: 'repo' })
+ }
+ for (const url of ['ext::bad', '/tmp/repo', '--upload-pack=bad', 'https://user:[email protected]/owner/repo', 'owner/repo;command', 'https://github.com/owner/repo?token=secret']) {
+ expect(() => parseProjectFolder({ projectSource: 'remote', repositoryUrl: url })).toThrow(ProjectFolderError)
+ }
+ expect(() => parseProjectFolder({ projectSource: 'new', repositoryUrl: 'owner/repo' })).toThrow(ProjectFolderError)
+ })
+
+ it('creates different folders for two deliberate new projects', async () => {
+ const folders = await Promise.all([prepareProjectFolder({ source: 'new' }, { root }), prepareProjectFolder({ source: 'new' }, { root })])
+ expect(new Set(folders).size).toBe(2)
+ expect(folders.every(folder => folder.startsWith(join(root, 'project-')))).toBe(true)
+ expect(await readdir(root)).toHaveLength(2)
+ })
+
+ it('publishes a complete clone and never replaces existing files or starts a second clone', async () => {
+ const project = parseProjectFolder({ projectSource: 'remote', repositoryUrl: 'owner/repo' })!
+ const clone = vi.fn(async (url: string, destination: string) => {
+ expect(url).toBe('https://github.com/owner/repo.git')
+ await mkdir(destination)
+ await writeFile(join(destination, 'README.md'), 'saved checkout')
+ })
+ const folder = await prepareProjectFolder(project, { root, clone })
+ expect(folder).toBe(join(root, 'repo'))
+ expect(await readFile(join(folder, 'README.md'), 'utf8')).toBe('saved checkout')
+ expect(await readdir(root)).toEqual(['repo'])
+ await expect(prepareProjectFolder(project, { root, clone })).rejects.toMatchObject({ code: 'PROJECT_EXISTS' })
+ expect(clone).toHaveBeenCalledTimes(1)
+ expect(await readFile(join(folder, 'README.md'), 'utf8')).toBe('saved checkout')
+ })
+
+ 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) => {
+ await mkdir(destination)
+ throw new ProjectFolderError('CLONE_FAILED', 'Could not clone')
+ } })).rejects.toMatchObject({ code: 'CLONE_FAILED' })
+ expect(await readdir(root)).toEqual([])
+ await expect(prepareProjectFolder(project, { root, clone: async (_, destination) => {
+ await mkdir(destination)
+ await mkdir(join(root, 'repo'))
+ await writeFile(join(root, 'repo', 'draft'), 'keep me')
+ } })).rejects.toMatchObject({ code: 'PROJECT_EXISTS' })
+ expect(await readFile(join(root, 'repo', 'draft'), 'utf8')).toBe('keep me')
+ expect(await readdir(root)).toEqual(['repo'])
+ })
+})
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
new file mode 100644
index 000000000..6f46c240b
--- /dev/null
+++ b/cli/src/lib/projectFolder.ts
@@ -0,0 +1,105 @@
+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'
+
+export type ProjectFolder = { source: 'new' } | { source: 'remote'; repositoryUrl: string; name: string }
+
+export class ProjectFolderError extends Error {
+ constructor(readonly code: string, message: string) { super(message) }
+}
+
+// Same accepted forms as the existing desktop GitHub clone flow. Neither
+// credentials nor arbitrary local paths/remote helpers are repository URLs.
+export function parseProjectFolder(payload: Record<string, unknown>): ProjectFolder | null {
+ if (payload.projectSource === undefined) return null
+ if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) return { source: 'new' }
+ if (payload.projectSource !== 'remote' || typeof payload.repositoryUrl !== 'string') {
+ throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose New, Local, or Remote for the project folder.')
+ }
+ const raw = payload.repositoryUrl.trim()
+ let path: string
+ const ssh = raw.startsWith('[email protected]:')
+ if (ssh) path = raw.slice('[email protected]:'.length)
+ else {
+ let url: URL
+ try { url = new URL(raw.includes('://') ? raw : `https://github.com/${raw}`) }
+ catch { throw new ProjectFolderError('INVALID_REPOSITORY', 'Enter a GitHub URL or owner/repository.') }
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.username || url.password || url.port || url.search || url.hash) {
+ throw new ProjectFolderError('INVALID_REPOSITORY', 'Enter a GitHub HTTPS or SSH URL, or owner/repository.')
+ }
+ path = url.pathname.replace(/^\//, '')
+ }
+ path = path.replace(/\/$/, '').replace(/\.git$/, '')
+ const parts = path.split('/')
+ if (parts.length !== 2 || !/^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(parts[0]!) ||
+ !/^[A-Za-z0-9_.-]{1,100}$/.test(parts[1]!) || parts[1] === '.' || parts[1] === '..') {
+ throw new ProjectFolderError('INVALID_REPOSITORY', 'Enter a GitHub URL or owner/repository.')
+ }
+ return { source: 'remote', repositoryUrl: ssh ? `[email protected]:${path}.git` : `https://github.com/${path}.git`, name: parts[1]! }
+}
+
+async function exists(path: string): Promise<boolean> {
+ try { await lstat(path); return true }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error }
+}
+
+export async function prepareProjectFolder(
+ project: ProjectFolder,
+ options: { root?: string; clone?: (url: string, destination: string) => Promise<void> } = {},
+): Promise<string> {
+ const root = options.root ?? join(homedir(), 'Harness Projects')
+ let staging: string | undefined
+ try {
+ await mkdir(root, { recursive: true })
+ if (project.source === 'new') return await mkdtemp(join(root, 'project-'))
+ const destination = join(root, project.name)
+ if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Choose Local to open that folder.`)
+ 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. Choose Local to open that folder.`)
+ await rename(checkout, destination)
+ return destination
+ } catch (error) {
+ if (error instanceof ProjectFolderError) throw error
+ throw new ProjectFolderError('PROJECT_PREPARATION_FAILED', 'Could not create a project folder on this machine. Choose Local to select a folder you can edit.')
+ } finally {
+ if (staging) await rm(staging, { force: true, recursive: true }).catch(() => {})
+ }
+}
+
+/** No shell interpolation or interactive password prompt. Diagnostics stay
+ * bounded and private; only actionable, credential-free messages reach the UI. */
+function cloneRepository(url: string, destination: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = spawn('git', ['clone', '--', url, destination], {
+ stdio: ['ignore', 'ignore', 'pipe'],
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never',
+ GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' },
+ })
+ let diagnostic = '', timedOut = false
+ let forceKill: ReturnType<typeof setTimeout> | undefined
+ const deadline = setTimeout(() => {
+ timedOut = true
+ child.kill()
+ forceKill = setTimeout(() => child.kill('SIGKILL'), 2000)
+ forceKill.unref()
+ }, 300_000)
+ deadline.unref()
+ child.stderr?.on('data', (chunk: Buffer) => { diagnostic = (diagnostic + chunk.toString()).slice(0, 8192) })
+ child.on('error', () => {
+ clearTimeout(deadline)
+ reject(new ProjectFolderError('GIT_UNAVAILABLE', 'Git could not start. Install Git on the selected machine, then retry.'))
+ })
+ child.on('close', (code) => {
+ clearTimeout(deadline)
+ clearTimeout(forceKill)
+ if (timedOut) reject(new ProjectFolderError('CLONE_TIMEOUT', 'Cloning took too long. Check the connection and retry.'))
+ else if (code === 0) resolve()
+ else reject(new ProjectFolderError('CLONE_FAILED', /authentication|permission denied|could not read username|repository not found/i.test(diagnostic)
+ ? 'Could not access this repository. Check the URL and GitHub access on the selected machine.'
+ : 'Could not clone the repository. Check the URL and connection, then retry.'))
+ })
+ })
+}