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.

New Harness: paste a folder path or GitHub link (#2525)

Kelvin048a9c1dc692
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index ddebbb9f7..2f05a4562 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -13,7 +13,7 @@ import type { AgentFrame } from '../../lib/agentFrame.js'
import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent, unsupportedLaunchModelFlag } from '../../lib/engineLaunch.js'
import { parseGridLaunchOverride } from '../../lib/gridLaunchWire.js'
import { parseNewAgentModel } from '../../lib/newAgentModel.js'
-import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'
+import { parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../../lib/projectFolder.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'
import * as pendingLaunches from './pendingLaunches.js'
@@ -690,6 +690,36 @@ describe('agent_create with a receipt', () => {
expect(create).not.toHaveBeenCalled()
})
+ it('lets the person\'s own clone try every way in, says which alias worked, and calls a refusal everywhere denied', async () => {
+ const { ask, status, replies } = setup()
+ const remote = { engine: 'claude', projectSource: 'remote', repositoryUrl: 'https://github.com/acme/app' }
+ vi.mocked(prepareProjectFolder).mockImplementationOnce(async (_project, options) => {
+ options?.onCloned?.({ url: 'git@gh-work:acme/app.git', alias: 'gh-work' })
+ return '/projects/prepared'
+ })
+ const answer = async (payload: Record<string, unknown>) => {
+ const before = replies.length
+ await ask(payload)
+ await vi.waitFor(() => expect(replies.length).toBeGreaterThan(before))
+ return replies.at(-1)!
+ }
+ expect(await answer({ ...remote, creationId: CREATION })).toMatchObject({ state: 'created', agent: { id: 'new-agent' }, clonedVia: { alias: 'gh-work' } })
+ expect(vi.mocked(prepareProjectFolder).mock.calls.at(-1)![1]).toMatchObject({ cloneFallback: true })
+ expect(await status({ creationId: CREATION })).toMatchObject({ clonedVia: { alias: 'gh-work' } })
+ // A transport switch is no news: the account is the same.
+ vi.mocked(prepareProjectFolder).mockImplementationOnce(async (_project, options) => {
+ options?.onCloned?.({ url: '[email protected]:acme/app.git' })
+ return '/projects/prepared'
+ })
+ expect(await answer({ ...remote, creationId: `${CREATION}-plain` })).not.toHaveProperty('clonedVia')
+ vi.mocked(prepareProjectFolder).mockRejectedValueOnce(new RepositoryAccessError('CLONE_FAILED', 'Could not access this repository.'))
+ expect(await answer({ ...remote, creationId: `${CREATION}-denied` })).toStrictEqual({ creationId: `${CREATION}-denied`, state: 'failed',
+ failure: { code: 'CLONE_FAILED', detail: 'Could not access this repository.', access: 'denied' } })
+ // A Swarm agent's repository was cloned by its start, one address per transport and never an alias.
+ await answer({ ...remote, swarmRole: 'lead', creationId: `${CREATION}-swarm` })
+ expect(vi.mocked(prepareProjectFolder).mock.calls.at(-1)![1]).toMatchObject({ cloneFallback: false })
+ })
+
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 c8d8bea33..875d93ec2 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -29,7 +29,7 @@ import {
import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridLaunchWire.js'
import { parseLaunchModel } from '../../lib/launchModel.js'
import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'
-import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, type ProjectFolder } from '../../lib/projectFolder.js'
+import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, RepositoryAccessError, type ProjectFolder } from '../../lib/projectFolder.js'
import type { ScmLaunchRecord } from '../../scm/types.js'
import { parentAgentIdOf, type RegisteredSession } from '../../lib/registry.js'
import { roleFromWire, wireRole } from '../../lib/savedSkill.js'
@@ -107,17 +107,25 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
/** A new project's folder, which this made empty: removed again if nothing starts in it. */
let made: string | undefined
let scmLaunchRecord: ScmLaunchRecord | null = null
+ /** The SSH alias a clone got in through, which the apps tell the person: it is the account later pushes go as. */
+ let clonedVia: { alias: string } | undefined
if (projectFolder) {
try {
preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),
- onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })
+ onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord },
+ // The person's own start may try every way this computer reaches GitHub. A Swarm agent's repository was cloned
+ // by its start (superTabs/projectFolder.ts), which keeps to one address per transport and never an alias.
+ ...(projectFolder.source === 'remote' ? { cloneFallback: !input.swarmRole,
+ onCloned: (clone: { alias?: string }) => { if (clone.alias) clonedVia = { alias: clone.alias } } } : {}) })
if (projectFolder.source === 'new') made = preparedFolder
}
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.',
// 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 } : {}) }
+ ...(error instanceof ProjectFolderError && error.folder ? { existingFolder: error.folder } : {}),
+ // GitHub refused every way in: the apps say "No access" in their own words rather than git's.
+ ...(error instanceof RepositoryAccessError ? { access: 'denied' as const } : {}) }
}
// 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
@@ -167,7 +175,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
} catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }
}
const result = await invoke(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)
- if (result.ok) return { state: 'created', agentId: result.session.agentId }
+ if (result.ok) return { state: 'created', agentId: result.session.agentId, ...(clonedVia ? { clonedVia } : {}) }
// 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' }
@@ -259,7 +267,8 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
if (status.state === 'created') {
const session = byAgent(status.agentId)
return session
- ? { state: 'created', agent: await toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }
+ ? { state: 'created', agent: await toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}),
+ ...(status.clonedVia ? { clonedVia: status.clonedVia } : {}) }
: { state: 'unavailable', createdAgentId: status.agentId }
}
// A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors
@@ -267,7 +276,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
if (status.state === 'failed') {
return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error,
...(status.reason ? { reason: status.reason } : {}), ...(status.detail ? { detail: status.detail } : {}),
- ...(status.existingFolder ? { existingFolder: status.existingFolder } : {}) } }
+ ...(status.existingFolder ? { existingFolder: status.existingFolder } : {}), ...(status.access ? { access: status.access } : {}) } }
}
return status
}
diff --git a/cli/src/lib/__fixtures__/github-repository-vectors.json b/cli/src/lib/__fixtures__/github-repository-vectors.json
new file mode 100644
index 000000000..061982349
--- /dev/null
+++ b/cli/src/lib/__fixtures__/github-repository-vectors.json
@@ -0,0 +1,290 @@
+{
+ "about": "What a pasted GitHub repository address means, held to by both cli/src/lib/githubRepository.spec.ts and desktop/test/github_repository_vectors_test.dart, so the daemon and the desktop app clone the same way. Hand-written: change it deliberately, then both implementations.",
+ "parse": [
+ {
+ "input": "https://github.com/autonomous-ai/openharness",
+ "expect": {
+ "url": "https://github.com/autonomous-ai/openharness.git",
+ "owner": "autonomous-ai",
+ "name": "openharness",
+ "transport": "https"
+ }
+ },
+ {
+ "input": " https://github.com/Org/Repo.git/ ",
+ "expect": {
+ "url": "https://github.com/Org/Repo.git",
+ "owner": "Org",
+ "name": "Repo",
+ "transport": "https"
+ }
+ },
+ {
+ "input": "github.com/org/repo",
+ "expect": {
+ "url": "https://github.com/org/repo.git",
+ "owner": "org",
+ "name": "repo",
+ "transport": "https"
+ }
+ },
+ {
+ "input": "org/repo",
+ "expect": {
+ "url": "https://github.com/org/repo.git",
+ "owner": "org",
+ "name": "repo",
+ "transport": "https"
+ }
+ },
+ {
+ "input": "[email protected]:org/repo.git",
+ "expect": {
+ "url": "[email protected]:org/repo.git",
+ "owner": "org",
+ "name": "repo",
+ "transport": "ssh"
+ }
+ },
+ {
+ "input": "[email protected]:org/repo",
+ "expect": {
+ "url": "[email protected]:org/repo.git",
+ "owner": "org",
+ "name": "repo",
+ "transport": "ssh"
+ }
+ },
+ {
+ "input": "git@gh-kelvin1295:autonomous-ai/autonomous-grid-be.git",
+ "expect": {
+ "url": "git@gh-kelvin1295:autonomous-ai/autonomous-grid-be.git",
+ "owner": "autonomous-ai",
+ "name": "autonomous-grid-be",
+ "transport": "alias",
+ "alias": "gh-kelvin1295"
+ }
+ },
+ {
+ "input": "[email protected]:org/repo",
+ "expect": {
+ "url": "[email protected]:org/repo.git",
+ "owner": "org",
+ "name": "repo",
+ "transport": "alias",
+ "alias": "work.github"
+ }
+ },
+ {
+ "input": "git@-oProxyCommand=evil:org/repo",
+ "expect": null
+ },
+ {
+ "input": "[email protected]:org/repo",
+ "expect": null
+ },
+ {
+ "input": "me@gh-kelvin1295:org/repo",
+ "expect": null
+ },
+ {
+ "input": "git@gh-kelvin1295:org",
+ "expect": null
+ },
+ {
+ "input": "git@gh-kelvin1295:org/repo/extra",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/autonomous-ai",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/repo/tree/main",
+ "expect": null
+ },
+ {
+ "input": "https://user:[email protected]/org/repo",
+ "expect": null
+ },
+ {
+ "input": "https://gitlab.com/org/repo",
+ "expect": null
+ },
+ {
+ "input": "http://github.com/org/repo",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/repo?tab=readme",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/..",
+ "expect": null
+ },
+ {
+ "input": "ssh://[email protected]/org/repo.git",
+ "expect": null
+ },
+ {
+ "input": "~/Projects/repo",
+ "expect": null
+ },
+ {
+ "input": "",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/repo?",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/repo#",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/re%70o",
+ "expect": null
+ },
+ {
+ "input": "https://github.com/org/re\tpo",
+ "expect": null
+ }
+ ],
+ "identity": [
+ {
+ "address": "https://github.com/Org/Repo.git",
+ "hosts": {},
+ "expect": "github.com/org/repo"
+ },
+ {
+ "address": "[email protected]:org/repo.git",
+ "hosts": {},
+ "expect": "github.com/org/repo"
+ },
+ {
+ "address": "git@gh-kelvin1295:Org/Repo.git",
+ "hosts": {
+ "gh-kelvin1295": "github.com"
+ },
+ "expect": "github.com/org/repo"
+ },
+ {
+ "address": "git@gh-kelvin1295:org/repo.git",
+ "hosts": {},
+ "expect": "gh-kelvin1295/org/repo"
+ },
+ {
+ "address": "git@gitlab-work:org/repo.git",
+ "hosts": {
+ "gitlab-work": "gitlab.com"
+ },
+ "expect": "gitlab.com/org/repo"
+ },
+ {
+ "address": "/Users/me/repo",
+ "hosts": {},
+ "expect": null
+ },
+ {
+ "address": "ssh://git@gh-kelvin1295/Org/Repo.git",
+ "hosts": {
+ "gh-kelvin1295": "github.com"
+ },
+ "expect": "github.com/org/repo"
+ },
+ {
+ "address": "git+ssh://git@gh-kelvin1295/org/repo",
+ "hosts": {
+ "gh-kelvin1295": "github.com"
+ },
+ "expect": "github.com/org/repo"
+ },
+ {
+ "about": "An https host is a real host name, never an SSH alias.",
+ "address": "https://gh-kelvin1295/org/repo",
+ "hosts": {
+ "gh-kelvin1295": "github.com"
+ },
+ "expect": "gh-kelvin1295/org/repo"
+ },
+ {
+ "about": "GitHub's SSH over port 443 is GitHub.",
+ "address": "git@gh-443:org/repo.git",
+ "hosts": {
+ "gh-443": "ssh.github.com"
+ },
+ "expect": "github.com/org/repo"
+ }
+ ],
+ "attempts": [
+ {
+ "about": "A browser link: the other transport, then the computer's GitHub aliases.",
+ "input": "https://github.com/org/repo",
+ "aliases": [
+ "gh-a",
+ "gh-b"
+ ],
+ "expect": [
+ "https://github.com/org/repo.git",
+ "[email protected]:org/repo.git",
+ "git@gh-a:org/repo.git",
+ "git@gh-b:org/repo.git"
+ ]
+ },
+ {
+ "input": "[email protected]:org/repo.git",
+ "aliases": [],
+ "expect": [
+ "[email protected]:org/repo.git",
+ "https://github.com/org/repo.git"
+ ]
+ },
+ {
+ "about": "A pasted alias goes first and is not tried twice.",
+ "input": "git@gh-b:org/repo.git",
+ "aliases": [
+ "gh-a",
+ "gh-b"
+ ],
+ "expect": [
+ "git@gh-b:org/repo.git",
+ "https://github.com/org/repo.git",
+ "[email protected]:org/repo.git",
+ "git@gh-a:org/repo.git"
+ ]
+ },
+ {
+ "about": "At most three aliases.",
+ "input": "https://github.com/org/repo",
+ "aliases": [
+ "a1",
+ "a2",
+ "a3",
+ "a4"
+ ],
+ "expect": [
+ "https://github.com/org/repo.git",
+ "[email protected]:org/repo.git",
+ "git@a1:org/repo.git",
+ "git@a2:org/repo.git",
+ "git@a3:org/repo.git"
+ ]
+ },
+ {
+ "about": "An alias list never holds github.com itself or an unsafe name.",
+ "input": "https://github.com/org/repo",
+ "aliases": [
+ "github.com",
+ "-oX",
+ "gh-a"
+ ],
+ "expect": [
+ "https://github.com/org/repo.git",
+ "[email protected]:org/repo.git",
+ "git@gh-a:org/repo.git"
+ ]
+ }
+ ]
+}
diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.ts
index cdddd86c9..371d1b9c2 100644
--- a/cli/src/lib/agentCreationReceipt.spec.ts
+++ b/cli/src/lib/agentCreationReceipt.spec.ts
@@ -117,6 +117,12 @@ it('retains a fork handoff level through a daemon restart', async () => {
expect(launch).not.toHaveBeenCalled()
})
+it('retains the alias a clone got in through across a daemon restart', async () => {
+ const { directory, receipts } = fixture()
+ await receipts.run(id, fingerprint, async () => ({ state: 'created', agentId: 'cloned', clonedVia: { alias: 'gh-work' } }))
+ expect(new AgentCreationReceipts(directory).status(id)).toEqual({ state: 'created', agentId: 'cloned', clonedVia: { alias: 'gh-work' } })
+})
+
it('retains a fresh restart outcome through a daemon restart', async () => {
const { directory, receipts } = fixture()
const restart = vi.fn(async () => ({ state: 'created' as const, agentId: 'agent-1', resumed: false }))
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 12fe923c6..606cbca28 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -6,9 +6,13 @@ import { readPrivateStateFile, secureStateDirectory, syncStateDirectory } from '
import type { LaunchModel } from './launchModel.js'
export type AgentCreationOutcome =
- | { state: 'created'; agentId: string; level?: 'native' | 'handoff'; resumed?: boolean }
+ | { state: 'created'; agentId: string; level?: 'native' | 'handoff'; resumed?: boolean
+ /** The SSH alias the project's clone got in through (lib/projectFolder.ts `onCloned`). */
+ clonedVia?: { alias: string } }
// `reason`: which check a refusal failed, where its code has several (a resume's RESUME_PREPARATION_FAILED).
- | { state: 'failed'; error: string; detail?: string; reason?: string; preparedFolder?: string; existingFolder?: string }
+ | { state: 'failed'; error: string; detail?: string; reason?: string; preparedFolder?: string; existingFolder?: string
+ /** GitHub refused every way this computer had in to the repository. */
+ access?: 'denied' }
| { state: 'unconfirmed' }
export type AgentCreationStatus = AgentCreationOutcome
@@ -50,7 +54,8 @@ function validOutcome(outcome: AgentCreationOutcome | undefined): outcome is Age
|| (outcome.state === 'failed' && typeof outcome.error === 'string')
|| (outcome.state === 'created' && typeof outcome.agentId === 'string' && !!outcome.agentId
&& (outcome.level === undefined || outcome.level === 'native' || outcome.level === 'handoff')
- && (outcome.resumed === undefined || typeof outcome.resumed === 'boolean')))
+ && (outcome.resumed === undefined || typeof outcome.resumed === 'boolean')
+ && (outcome.clonedVia === undefined || typeof outcome.clonedVia?.alias === 'string')))
}
export class AgentCreationReceiptError extends Error {
diff --git a/cli/src/lib/githubRepository.spec.ts b/cli/src/lib/githubRepository.spec.ts
new file mode 100644
index 000000000..6e46eace5
--- /dev/null
+++ b/cli/src/lib/githubRepository.spec.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { cloneAttempts, parseGitHubRepository, repositoryIdentity, resolvedRepositoryIdentity, safeSshAlias } from './githubRepository.js'
+
+// The same file the desktop app's github_repository_vectors_test.dart reads: the daemon and the app must clone alike.
+type Vectors = {
+ parse: { input: string; expect: Record<string, string> | null }[]
+ identity: { address: string; hosts: Record<string, string>; expect: string | null }[]
+ attempts: { input: string; aliases: string[]; expect: string[] }[]
+}
+const vectors = JSON.parse(readFileSync(join(__dirname, '__fixtures__', 'github-repository-vectors.json'), 'utf8')) as Vectors
+
+describe('a pasted GitHub repository address', () => {
+ it.each(vectors.parse)('parses $input', ({ input, expect: wanted }) => {
+ expect(parseGitHubRepository(input)).toStrictEqual(wanted)
+ })
+
+ it.each(vectors.identity)('names $address as one repository', async ({ address, hosts, expect: wanted }) => {
+ expect(await resolvedRepositoryIdentity(address, async (host) => hosts[host] ?? null)).toBe(wanted)
+ })
+
+ it.each(vectors.attempts)('tries $input in order', ({ input, aliases, expect: wanted }) => {
+ expect(cloneAttempts(parseGitHubRepository(input)!, aliases)).toStrictEqual(wanted)
+ })
+
+ it('resolves only the hosts an alias may name, and keeps github.com as it is', async () => {
+ const asked: string[] = []
+ const resolve = async (host: string) => { asked.push(host); return 'github.com' }
+ expect(await resolvedRepositoryIdentity('https://github.com/o/r', resolve)).toBe('github.com/o/r')
+ expect(await resolvedRepositoryIdentity('git@-oX:o/r', resolve)).toBe('-ox/o/r')
+ expect(asked).toStrictEqual([])
+ expect(repositoryIdentity('nonsense')).toBeNull()
+ })
+
+ it('takes a safe alias only', () => {
+ expect(['gh-a', 'work.github', 'A1'].map(safeSshAlias)).toStrictEqual([true, true, true])
+ expect(['-oX', '.a', '', 'a b', 'a'.repeat(64), 'a;b'].map(safeSshAlias)).toStrictEqual([false, false, false, false, false, false])
+ })
+})
diff --git a/cli/src/lib/githubRepository.ts b/cli/src/lib/githubRepository.ts
new file mode 100644
index 000000000..3bdaf578d
--- /dev/null
+++ b/cli/src/lib/githubRepository.ts
@@ -0,0 +1,107 @@
+/** A GitHub repository as a person pastes it: the browser's link, `[email protected]:`, or an SSH host alias from their own
+ * SSH configuration (`Host gh-work` / `HostName github.com`), which is how a computer with two GitHub accounts picks a
+ * key. The desktop app's repository_clone.dart parses the same way; both are held to
+ * __fixtures__/github-repository-vectors.json. */
+export interface GitHubRepository {
+ /** The address git clones, always ending `.git`. */
+ url: string
+ owner: string
+ name: string
+ transport: 'https' | 'ssh' | 'alias'
+ /** The SSH host alias, for `transport: 'alias'` only. */
+ alias?: string
+}
+
+const OWNER = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/
+const NAME = /^[A-Za-z0-9_.-]{1,100}$/
+/** A name that can never be read as an option by ssh or git: it starts with a letter or digit. */
+const ALIAS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/
+
+export function safeSshAlias(alias: string): boolean {
+ return ALIAS.test(alias)
+}
+
+/** Whether an SSH host name is GitHub: `ssh.github.com` is GitHub's SSH over port 443, which a second account's alias
+ * behind a firewall uses. */
+export function isGitHubHost(host: string | null): boolean {
+ return host === 'github.com' || host === 'ssh.github.com'
+}
+
+/** Null for anything that is not one GitHub repository: credentials, ports, queries, a page inside a repository, another
+ * host, a local path. A bare `owner/repo` is still one, for the GitHub prompt and older apps. */
+export function parseGitHubRepository(input: string): GitHubRepository | null {
+ const raw = input.trim()
+ // A query, a fragment, an escape or a space is never part of a repository's address, even an empty one: the URL parser
+ // would drop or decode it, and the app's parser must give the same answer (the shared vectors).
+ if (/[\s?#%]/.test(raw)) return null
+ let host = 'github.com', path: string
+ const scp = /^git@([^:/\s]+):(\S+)$/.exec(raw)
+ if (scp) {
+ host = scp[1]!
+ if (host !== 'github.com' && !safeSshAlias(host)) return null
+ path = scp[2]!
+ } else {
+ let url: URL
+ try { url = new URL(raw.includes('://') ? raw : raw.startsWith('github.com/') ? `https://${raw}` : `https://github.com/${raw}`) }
+ catch { return null }
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.username || url.password || url.port || url.search || url.hash) return null
+ path = url.pathname.replace(/^\//, '')
+ }
+ const parts = path.replace(/\/$/, '').replace(/\.git$/, '').split('/')
+ const [owner, name] = parts
+ if (parts.length !== 2 || !OWNER.test(owner!) || !NAME.test(name!) || name === '.' || name === '..') return null
+ if (!scp) return { url: `https://github.com/${owner}/${name}.git`, owner: owner!, name: name!, transport: 'https' }
+ if (host === 'github.com') return { url: `[email protected]:${owner}/${name}.git`, owner: owner!, name: name!, transport: 'ssh' }
+ return { url: `git@${host}:${owner}/${name}.git`, owner: owner!, name: name!, transport: 'alias', alias: host }
+}
+
+/**
+ * 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. 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
+}
+
+/** [repositoryIdentity] with an SSH alias read as the host it names (`ssh.github.com` as GitHub), so a checkout cloned as `git@gh-work:org/repo` is the
+ * repository a browser link `https://github.com/org/repo` asks for. Only a name that could be an alias is resolved. */
+export async function resolvedRepositoryIdentity(address: string, resolveHost: (alias: string) => Promise<string | null>): Promise<string | null> {
+ const identity = repositoryIdentity(address)
+ if (!identity) return null
+ const slash = identity.indexOf('/')
+ const host = identity.slice(0, slash)
+ // Only ssh reads ~/.ssh/config: an https or git:// host is a real name, never an alias.
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(address.trim())?.[1]?.toLowerCase()
+ const viaSsh = scheme === undefined || scheme === 'ssh' || scheme === 'git+ssh' || scheme === 'ssh+git'
+ const named = host === 'github.com' || !viaSsh || !safeSshAlias(host) ? host : (await resolveHost(host))?.toLowerCase() ?? host
+ return `${isGitHubHost(named) ? 'github.com' : named}${identity.slice(slash)}`
+}
+
+/** The most SSH aliases one clone tries: each refused attempt costs a round trip to GitHub, about a second. */
+export const MAX_CLONE_ALIASES = 3
+
+/** The addresses a clone tries, in order: what was pasted, the other transport, then [aliases] (the computer's own aliases
+ * for github.com, safe names only, at most three). A pasted alias is tried once. */
+export function cloneAttempts(repository: GitHubRepository, aliases: readonly string[]): string[] {
+ const { owner, name } = repository
+ const https = `https://github.com/${owner}/${name}.git`, ssh = `[email protected]:${owner}/${name}.git`
+ const others = repository.transport === 'https' ? [ssh] : repository.transport === 'ssh' ? [https] : [https, ssh]
+ const extra = aliases.filter(alias => alias !== 'github.com' && alias !== repository.alias && safeSshAlias(alias))
+ .slice(0, MAX_CLONE_ALIASES).map(alias => `git@${alias}:${owner}/${name}.git`)
+ return [...new Set([repository.url, ...others, ...extra])]
+}
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
index 7f8b741a2..f7151f57e 100644
--- a/cli/src/lib/projectFolder.spec.ts
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -179,7 +179,7 @@ describe('project folder preparation', () => {
.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 expect(prepareProjectFolder(project, { root, clone, resolveHost: async () => null })).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' })
@@ -221,6 +221,106 @@ describe('project folder preparation', () => {
})
})
+describe('a clone GitHub refuses', () => {
+ let root: string
+ beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'harness-clone-fallback-')) })
+ afterEach(async () => { await rm(root, { recursive: true, force: true }) })
+
+ const refused = () => new RepositoryAccessError('CLONE_FAILED', 'Could not access this repository.')
+ /** A git that clones only [reachable], refusing every other address, and records what it was asked. */
+ function git(reachable: string | null, failure: () => Error = refused) {
+ const tried: string[] = []
+ const clone = vi.fn(async (url: string, destination: string) => {
+ tried.push(url)
+ if (url !== reachable) throw failure()
+ await mkdir(destination)
+ })
+ return { clone, tried }
+ }
+ const remote = (url: string) => parseProjectFolder({ projectSource: 'remote', repositoryUrl: url })!
+
+ it('tries the other transport, then the computer\'s GitHub aliases, and says which alias worked', async () => {
+ const { clone, tried } = git('git@gh-b:owner/repo.git')
+ const aliases = vi.fn(async () => ['gh-a', 'gh-b'])
+ const onCloned = vi.fn()
+ const folder = await prepareProjectFolder(remote('https://github.com/owner/repo'), { root, clone, cloneFallback: true, githubAliases: aliases, onCloned })
+ expect(folder).toBe(join(root, 'repo'))
+ expect(tried).toStrictEqual(['https://github.com/owner/repo.git', '[email protected]:owner/repo.git', 'git@gh-a:owner/repo.git', 'git@gh-b:owner/repo.git'])
+ expect(aliases).toHaveBeenCalledOnce()
+ expect(onCloned).toHaveBeenCalledWith({ url: 'git@gh-b:owner/repo.git', alias: 'gh-b' })
+ expect(await readdir(root)).toStrictEqual(['repo'])
+ })
+
+ it('reads no aliases when the first address works, and names no alias for a transport switch', async () => {
+ const aliases = vi.fn(async () => ['gh-a'])
+ const first = git('https://github.com/owner/repo.git'), onCloned = vi.fn()
+ await prepareProjectFolder(remote('owner/repo'), { root, clone: first.clone, cloneFallback: true, githubAliases: aliases, onCloned })
+ expect(first.tried).toHaveLength(1)
+ expect(aliases).not.toHaveBeenCalled()
+ expect(onCloned).toHaveBeenCalledWith({ url: 'https://github.com/owner/repo.git' })
+ await rm(join(root, 'repo'), { recursive: true })
+ const second = git('https://github.com/owner/repo.git')
+ await prepareProjectFolder(remote('[email protected]:owner/repo'), { root, clone: second.clone, cloneFallback: true, githubAliases: async () => [], onCloned })
+ expect(onCloned).toHaveBeenLastCalledWith({ url: 'https://github.com/owner/repo.git' })
+ })
+
+ it('stays refused once every way in is, and leaves no staging behind', async () => {
+ const { clone, tried } = git(null)
+ await expect(prepareProjectFolder(remote('owner/repo'), { root, clone, cloneFallback: true, githubAliases: async () => ['gh-a'] }))
+ .rejects.toBeInstanceOf(RepositoryAccessError)
+ expect(tried).toHaveLength(3)
+ expect(await readdir(root)).toStrictEqual([])
+ })
+
+ it('stops at a failure other than a refusal: another way in would fail the same', async () => {
+ for (const failure of [() => new ProjectFolderError('CLONE_TIMEOUT', 'Cloning took too long.'), () => new ProjectFolderError('CLONE_FAILED', 'Could not resolve host'), () => new Error('disk full')]) {
+ const { clone, tried } = git(null, failure)
+ const aliases = vi.fn(async () => ['gh-a'])
+ await expect(prepareProjectFolder(remote('owner/repo'), { root, clone, cloneFallback: true, githubAliases: aliases })).rejects.toBeTruthy()
+ expect(tried).toHaveLength(1)
+ expect(aliases).not.toHaveBeenCalled()
+ }
+ })
+
+ it('tries one address only when not asked for more, as a Swarm start is', async () => {
+ const { clone, tried } = git('[email protected]:owner/repo.git')
+ await expect(prepareProjectFolder(remote('owner/repo'), { root, clone })).rejects.toBeInstanceOf(RepositoryAccessError)
+ expect(tried).toStrictEqual(['https://github.com/owner/repo.git'])
+ })
+
+ it('clones a pasted alias first, and refuses one that is not a GitHub host here', async () => {
+ const { clone, tried } = git('git@gh-work:owner/repo.git')
+ const resolveHost = vi.fn(async (alias: string) => alias === 'gh-work' ? 'github.com' : 'gitlab.com')
+ const project = remote('git@gh-work:owner/repo.git')
+ expect(project).toStrictEqual({ source: 'remote', repositoryUrl: 'git@gh-work:owner/repo.git', name: 'repo' })
+ await prepareProjectFolder(project, { root, clone, resolveHost, cloneFallback: true })
+ expect(tried).toStrictEqual(['git@gh-work:owner/repo.git'])
+ await expect(prepareProjectFolder(remote('git@gitlab-work:owner/repo'), { root, clone, resolveHost, cloneFallback: true }))
+ .rejects.toMatchObject({ code: 'INVALID_REPOSITORY', message: '“gitlab-work” isn\'t a GitHub host on this machine.' })
+ expect(clone).toHaveBeenCalledOnce()
+ })
+
+ it('refuses an alias in a start that is not the owner\'s own, without asking ssh which aliases exist', async () => {
+ // A Swarm Lead or a contribution names the address of a project that starts on someone else's computer.
+ const { clone } = git('git@gh-work:owner/repo.git')
+ const resolveHost = vi.fn(async () => 'github.com')
+ for (const url of ['git@gh-work:owner/repo.git', 'git@no-such-alias:owner/repo.git']) {
+ await expect(prepareProjectFolder(remote(url), { root, clone, resolveHost }))
+ .rejects.toMatchObject({ code: 'INVALID_REPOSITORY', message: 'Enter a GitHub HTTPS or SSH URL, or owner/repository.' })
+ }
+ expect(resolveHost).not.toHaveBeenCalled()
+ expect(clone).not.toHaveBeenCalled()
+ })
+
+ it('starts in a checkout cloned through an alias when the browser link asks for the same repository', async () => {
+ checkout(join(root, 'repo'), 'git@gh-work:Owner/repo.git')
+ const clone = vi.fn()
+ const folder = await prepareProjectFolder(remote('https://github.com/owner/repo'), { root, clone, resolveHost: async alias => alias === 'gh-work' ? 'github.com' : null })
+ expect(folder).toBe(join(root, 'repo'))
+ expect(clone).not.toHaveBeenCalled()
+ })
+})
+
// The OS chooses a familiar project root without changing other hn installations.
it('uses lowercase projects only in the explicit Harness OS environment', () => {
try {
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index 00843c76a..aa09beffe 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -5,6 +5,8 @@ import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { plausibleBranchName, projectFolderName, projectFolderSlug } from './agentNames.js'
import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'
+import { cloneAttempts, isGitHubHost, parseGitHubRepository, resolvedRepositoryIdentity } from './githubRepository.js'
+import { githubAliases, resolveHost } from './sshHosts.js'
import { scmByKind } from '../scm/scmProjects.js'
import type { ScmLaunchRecord } from '../scm/types.js'
@@ -29,8 +31,8 @@ export class ProjectFolderError extends Error {
constructor(readonly code: string, message: string, readonly folder?: string) { super(message) }
}
-// Same accepted forms as the existing desktop GitHub clone flow. Neither
-// credentials nor arbitrary local paths/remote helpers are repository URLs.
+// The desktop app's GitHub forms (githubRepository.ts, held to the same vectors). 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 === 'worktree' || payload.projectSource === 'branch') {
@@ -74,25 +76,12 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFol
throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a project.')
}
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(/^\//, '')
+ const repository = parseGitHubRepository(raw)
+ if (!repository) {
+ throw new ProjectFolderError('INVALID_REPOSITORY', raw.includes('://') || raw.startsWith('git@')
+ ? 'Enter a GitHub HTTPS or SSH URL, or owner/repository.' : 'Enter a GitHub URL or owner/repository.')
}
- 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]! }
+ return { source: 'remote', repositoryUrl: repository.url, name: repository.name }
}
async function exists(path: string): Promise<boolean> {
@@ -110,37 +99,19 @@ async function openableFolder(path: string): Promise<boolean> {
} 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
-}
+export { repositoryIdentity } from './githubRepository.js'
+
+type HostResolver = (alias: string) => Promise<string | 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.
+ * Anything else — no `.git`, another remote, an origin git cannot read — is not that repository. An SSH alias on either
+ * side is read as the host it names, so a checkout cloned as `git@gh-work:org/repo` is the browser link's repository.
*/
-async function holdsRepository(folder: string, repositoryUrl: string): Promise<boolean> {
- const wanted = repositoryIdentity(repositoryUrl)
+async function holdsRepository(folder: string, repositoryUrl: string, resolveAlias: HostResolver): Promise<boolean> {
+ const wanted = await resolvedRepositoryIdentity(repositoryUrl, resolveAlias)
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) }
@@ -150,7 +121,7 @@ async function holdsRepository(folder: string, repositoryUrl: string): Promise<b
{ env, timeout: 4000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 },
(error, stdout) => resolve(error ? null : stdout.trim()))
})
- return origin !== null && repositoryIdentity(origin) === wanted
+ return origin !== null && await resolvedRepositoryIdentity(origin, resolveAlias) === wanted
}
export async function prepareProjectFolder(
@@ -169,6 +140,16 @@ export async function prepareProjectFolder(
* branch reports nothing. A callback rather than a wider return so the folder stays the answer
* here, for every caller. */
onPrepared?: (prepared: { cwd: string; scmLaunchRecord: ScmLaunchRecord }) => void
+ /** A clone GitHub refuses tries the other transport, then this computer's SSH aliases for github.com
+ * (sshHosts.ts), stopping at the first that works: a person who reaches a private repository only over SSH, or
+ * only through a second account's key, can paste the browser's link. It is also what lets an address name an
+ * alias at all. Set only for the computer owner's own start (core/agents/launches.ts). Off, one attempt and no
+ * alias: a Swarm's or a contribution's start, whose address someone else chose, never picks the owner's accounts. */
+ cloneFallback?: boolean
+ /** Told which address a clone used, when it cloned; `alias` when that was an SSH alias. */
+ onCloned?: (clone: { url: string; alias?: string }) => void
+ resolveHost?: HostResolver
+ githubAliases?: () => Promise<string[]>
} = {},
): Promise<string> {
const root = options.root ?? projectsRoot()
@@ -228,23 +209,58 @@ export async function prepareProjectFolder(
}
}
}
+ const repository = parseGitHubRepository(project.repositoryUrl)
+ if (!repository) throw new ProjectFolderError('INVALID_REPOSITORY', 'Enter a GitHub URL or owner/repository.')
+ const resolve = options.resolveHost ?? resolveHost
+ // An alias picks one of this computer's GitHub accounts, so only its owner's own start may name one. A Swarm Lead or
+ // a contribution sets the address of a project that starts on someone else's computer: an alias there would choose
+ // that owner's second account, and "isn't a GitHub host" would tell the Lead which aliases exist. Such a start is
+ // refused in the same words as any other address, before ssh is asked anything.
+ if (repository.alias && !options.cloneFallback) {
+ throw new ProjectFolderError('INVALID_REPOSITORY', 'Enter a GitHub HTTPS or SSH URL, or owner/repository.')
+ }
+ // An alias names a host in THIS computer's SSH configuration, so it is checked here, where git will use it.
+ if (repository.alias && !isGitHubHost(await resolve(repository.alias))) {
+ throw new ProjectFolderError('INVALID_REPOSITORY', `“${repository.alias}” isn't a GitHub host on this machine.`)
+ }
const destination = join(root, project.name)
// 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
+ if (await holdsRepository(destination, project.repositoryUrl, resolve)) return destination
throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)
}
- staging = await mkdtemp(join(root, '.harness-clone-'))
+ // The aliases are read only once GitHub has refused: a computer that clones at once never runs ssh for them.
+ // cloneAttempts with them keeps the order it had without them, so the attempts so far stay a prefix.
+ let attempts = options.cloneFallback ? cloneAttempts(repository, []) : [repository.url]
+ let aliasesRead = !options.cloneFallback
+ let used = repository.url
+ for (let index = 0; ; index++) {
+ used = attempts[index]!
+ if (staging) await rm(staging, { force: true, recursive: true }).catch(() => {})
+ staging = await mkdtemp(join(root, '.harness-clone-'))
+ try {
+ await (options.clone ?? cloneRepository)(used, join(staging, 'checkout'), options.gitEnv)
+ if (index > 0) logAttempt(repository.owner, repository.name, used, 'cloned')
+ break
+ } catch (error) {
+ logAttempt(repository.owner, repository.name, used, error instanceof ProjectFolderError ? error instanceof RepositoryAccessError ? 'refused' : error.code : 'failed')
+ // Only a refusal is worth another way in: a network failure or a timeout would fail every one of them.
+ if (!(error instanceof RepositoryAccessError)) throw error
+ if (!aliasesRead) { aliasesRead = true; attempts = cloneAttempts(repository, await (options.githubAliases ?? githubAliases)()) }
+ if (index === attempts.length - 1) throw error
+ }
+ }
const checkout = join(staging, 'checkout')
- await (options.clone ?? cloneRepository)(project.repositoryUrl, checkout, options.gitEnv)
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
+ if (await holdsRepository(destination, project.repositoryUrl, resolve)) return destination
throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” was created while cloning. Select that folder from your projects.`)
}
await rename(checkout, destination)
+ const alias = parseGitHubRepository(used)?.alias
+ options.onCloned?.({ url: used, ...(alias ? { alias } : {}) })
return destination
} catch (error) {
if (error instanceof GitProjectError) throw new ProjectFolderError(error.code, error.message)
@@ -255,6 +271,13 @@ export async function prepareProjectFolder(
}
}
+/** One line per clone attempt that failed, or that worked after another had: which way in (https, ssh, or the alias) and
+ * how it ended. Never git's own words, which may quote a credential helper. */
+function logAttempt(owner: string, name: string, url: string, outcome: string): void {
+ const via = url.startsWith('https://') ? 'https' : url.startsWith('[email protected]:') ? 'ssh' : `ssh alias ${parseGitHubRepository(url)?.alias}`
+ console.info(`[project] clone ${owner}/${name} over ${via}: ${outcome}`)
+}
+
/** 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, gitEnv?: NodeJS.ProcessEnv): Promise<void> {
diff --git a/cli/src/lib/sshHosts.spec.ts b/cli/src/lib/sshHosts.spec.ts
new file mode 100644
index 000000000..8772bbad2
--- /dev/null
+++ b/cli/src/lib/sshHosts.spec.ts
@@ -0,0 +1,83 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { githubAliases, resolveHost, type SshRunner } from './sshHosts.js'
+
+/** An `ssh -G` that answers from a table, as the real one prints its resolved configuration. */
+function fakeSsh(hosts: Record<string, string>): SshRunner & { asked: string[] } {
+ const asked: string[] = []
+ return Object.assign(vi.fn(async (args: readonly string[]) => {
+ const alias = args.at(-1)!
+ asked.push(alias)
+ return `user git\nhostname ${hosts[alias] ?? alias}\nport 22\n`
+ }), { asked })
+}
+
+describe('SSH host aliases', () => {
+ let home: string
+ beforeEach(async () => { home = await mkdtemp(join(tmpdir(), 'harness-ssh-hosts-')); await mkdir(join(home, '.ssh')) })
+ afterEach(async () => { await rm(home, { recursive: true, force: true }) })
+
+ it('resolves an alias through ssh -G, and never runs ssh for an unsafe name', async () => {
+ const ssh = fakeSsh({ 'gh-work': 'GitHub.com' })
+ expect(await resolveHost('gh-work', ssh)).toBe('github.com')
+ expect(await resolveHost('-oProxyCommand=x', ssh)).toBeNull()
+ expect(ssh).toHaveBeenCalledOnce()
+ expect(vi.mocked(ssh).mock.calls[0]![0]).toStrictEqual(['-G', 'gh-work'])
+ })
+
+ it('reads nothing from an ssh that fails or prints no host name', async () => {
+ expect(await resolveHost('gh-work', async () => { throw new Error('timeout') })).toBeNull()
+ expect(await resolveHost('gh-work', async () => 'user git\n')).toBeNull()
+ })
+
+ it('lists the configuration\'s GitHub aliases in order, at most three, wildcards and other hosts left out', async () => {
+ await writeFile(join(home, '.ssh', 'config'), [
+ '# work and personal',
+ 'Host *',
+ ' AddKeysToAgent yes',
+ 'Host gh-work gh-*-x !gh-bad',
+ ' HostName github.com',
+ 'host=gitlab-work',
+ ' HostName gitlab.com',
+ 'Host "gh-personal"',
+ 'Include conf.d/*.conf',
+ 'Host gh-late gh-later',
+ ].join('\n'))
+ await mkdir(join(home, '.ssh', 'conf.d'))
+ await writeFile(join(home, '.ssh', 'conf.d', 'a.conf'), 'Host gh-included\nInclude ~/.ssh/deeper\n')
+ await writeFile(join(home, '.ssh', 'conf.d', 'skip.txt'), 'Host gh-skipped\n')
+ await writeFile(join(home, '.ssh', 'deeper'), 'Host gh-too-deep\n')
+ const ssh = fakeSsh({ 'gh-work': 'github.com', 'gitlab-work': 'gitlab.com', 'gh-personal': 'github.com', 'gh-included': 'github.com',
+ 'gh-late': 'github.com', 'gh-too-deep': 'github.com', 'gh-skipped': 'github.com' })
+ expect(await githubAliases({ home, ssh })).toStrictEqual(['gh-work', 'gh-personal', 'gh-included'])
+ // Stops asking once it has three.
+ expect(ssh.asked).toStrictEqual(['gh-work', 'gitlab-work', 'gh-personal', 'gh-included'])
+ })
+
+ it('counts an alias for GitHub\'s SSH over port 443 as GitHub', async () => {
+ await writeFile(join(home, '.ssh', 'config'), 'Host gh-443\n HostName ssh.github.com\n Port 443\n')
+ expect(await githubAliases({ home, ssh: fakeSsh({ 'gh-443': 'ssh.github.com' }) })).toStrictEqual(['gh-443'])
+ })
+
+ it('follows an absolute Include, and finds nothing without a configuration', async () => {
+ const ssh = fakeSsh({ 'gh-a': 'github.com' })
+ expect(await githubAliases({ home, ssh })).toStrictEqual([])
+ await writeFile(join(home, 'elsewhere'), 'Host gh-a\n')
+ await writeFile(join(home, '.ssh', 'config'), `Include ${join(home, 'elsewhere')} ${join(home, 'missing')}\nInclude ${join(home, 'nodir', '*.conf')}\n`)
+ expect(await githubAliases({ home, ssh })).toStrictEqual(['gh-a'])
+ })
+
+ it('ignores a configuration too large to be one person\'s', async () => {
+ await writeFile(join(home, '.ssh', 'config'), `Host gh-a\n${'#'.repeat(300 * 1024)}\n`)
+ expect(await githubAliases({ home, ssh: fakeSsh({ 'gh-a': 'github.com' }) })).toStrictEqual([])
+ })
+
+ it('asks ssh about a bounded number of hosts', async () => {
+ await writeFile(join(home, '.ssh', 'config'), Array.from({ length: 40 }, (_, i) => `Host h${i}`).join('\n'))
+ const ssh = fakeSsh({})
+ expect(await githubAliases({ home, ssh })).toStrictEqual([])
+ expect(ssh.asked).toHaveLength(20)
+ })
+})
diff --git a/cli/src/lib/sshHosts.ts b/cli/src/lib/sshHosts.ts
new file mode 100644
index 000000000..33e123094
--- /dev/null
+++ b/cli/src/lib/sshHosts.ts
@@ -0,0 +1,86 @@
+import { execFile } from 'node:child_process'
+import { readdir, readFile, stat } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { basename, dirname, isAbsolute, join } from 'node:path'
+import { isGitHubHost, MAX_CLONE_ALIASES, safeSshAlias } from './githubRepository.js'
+
+/** Runs `ssh` with [args] and gives its standard output. */
+export type SshRunner = (args: readonly string[]) => Promise<string>
+
+/** `ssh -G` prints the configuration it would use and connects to nothing. Bounded as the project readers are: four
+ * seconds, 64 KiB. */
+const runSsh: SshRunner = (args) => new Promise((resolve, reject) => {
+ execFile('ssh', [...args], { timeout: 4000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 },
+ (error, stdout) => error ? reject(error) : resolve(stdout))
+})
+
+/** The host name [alias] stands for in this computer's SSH configuration, lowercased; null when ssh cannot say. An unsafe
+ * name never reaches ssh: it could be read as an option. */
+export async function resolveHost(alias: string, ssh: SshRunner = runSsh): Promise<string | null> {
+ if (!safeSshAlias(alias)) return null
+ try {
+ const line = (await ssh(['-G', alias])).split('\n').find(l => l.startsWith('hostname '))
+ return line ? line.slice('hostname '.length).trim().toLowerCase() || null : null
+ } catch { return null }
+}
+
+/** A configuration bigger than this is not one a person wrote by hand, and is not read. */
+const MAX_CONFIG_BYTES = 256 * 1024
+/** The most `ssh -G` runs one listing makes, so a long configuration costs a clone a bounded wait. */
+const MAX_ASKED = 20
+
+async function readConfig(path: string): Promise<string | null> {
+ try {
+ if ((await stat(path)).size > MAX_CONFIG_BYTES) return null
+ return await readFile(path, 'utf8')
+ } catch { return null }
+}
+
+/** `keyword value…` or `keyword=value…`, as ssh_config(5) writes them; quotes taken off each value. */
+function directives(text: string): { keyword: string; values: string[] }[] {
+ return text.split('\n').flatMap((line) => {
+ const m = /^\s*([A-Za-z]+)(?:\s*=\s*|\s+)(.*)$/.exec(line)
+ return m ? [{ keyword: m[1]!.toLowerCase(), values: m[2]!.trim().split(/\s+/).map(v => v.replace(/^"(.*)"$/, '$1')) }] : []
+ })
+}
+
+/** The files an `Include` names: relative to ~/.ssh, `~` for [home], and a `*` or `?` in the file name only. */
+async function included(pattern: string, home: string): Promise<string[]> {
+ const path = pattern.startsWith('~/') ? join(home, pattern.slice(2)) : isAbsolute(pattern) ? pattern : join(home, '.ssh', pattern)
+ const name = basename(path)
+ if (!/[*?]/.test(name)) return [path]
+ const glob = new RegExp(`^${name.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`)
+ try { return (await readdir(dirname(path))).filter(n => glob.test(n)).sort().map(n => join(dirname(path), n)) }
+ catch { return [] }
+}
+
+/** The `Host` names of a configuration, in order, with its `Include`s read in place one level deep. Patterns and negations
+ * name no single host, so they are left out. */
+async function hostNames(path: string, home: string, depth: number): Promise<string[]> {
+ const text = await readConfig(path)
+ if (text === null) return []
+ const names: string[] = []
+ for (const { keyword, values } of directives(text)) {
+ if (keyword === 'host') names.push(...values.filter(v => !/[*?]/.test(v) && !v.startsWith('!')))
+ else if (keyword === 'include' && depth === 0) {
+ for (const pattern of values) for (const file of await included(pattern, home)) names.push(...await hostNames(file, home, 1))
+ }
+ }
+ return names
+}
+
+/**
+ * This computer's SSH aliases for github.com, in the order its configuration lists them, at most three: the keys of the
+ * other GitHub accounts a person signed in with (`Host gh-work` / `HostName github.com`). Read only after GitHub refused a
+ * clone, so a computer that clones fine never runs ssh for it.
+ */
+export async function githubAliases(options: { home?: string; ssh?: SshRunner } = {}): Promise<string[]> {
+ const home = options.home ?? homedir()
+ const candidates = [...new Set(await hostNames(join(home, '.ssh', 'config'), home, 0))].filter(safeSshAlias).filter(n => n !== 'github.com')
+ const found: string[] = []
+ for (const alias of candidates.slice(0, MAX_ASKED)) {
+ if (found.length >= MAX_CLONE_ALIASES) break
+ if (isGitHubHost(await resolveHost(alias, options.ssh))) found.push(alias)
+ }
+ return found
+}
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index 48a8cb2c9..c77df9e62 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -14,7 +14,7 @@ Agent, Computer, and Repo selectors sit above the message. The local computer is
**This Mac** on macOS and **This Computer** on Linux; remote computers retain their
names. Model, Approvals, applicable Account, Worktree, and Branch remain visible
below the message. Worktree and Branch stay on one line, without explanatory text
-underneath. **From main** identifies the base of a new worktree branch; a tooltip
+underneath. **From \<branch\>**, usually **From main**, identifies the base of a new worktree branch; a tooltip
explains the operation. Existing branches and worktrees retain their branch name.
The model control retains the provider/subscription picker and shared models.
@@ -182,10 +182,11 @@ person browses or types stays itself: the harness works in it on its current
branch, and Worktree is off and unavailable ("Already a worktree"). Worktrees
Start made are never offered as recent projects.
-**Branch** starts on `main` for a fresh desktop form. With Worktree on, local
-`main` or `origin/main` can supply the base. With Worktree off, it must be a local
-branch; a remote-only `main` requires an explicit local branch choice. Missing `main` requires
-an explicit branch choice; a failed worktree creation never silently turns
+**Branch** starts on the project's default branch (`origin/HEAD`) for a fresh desktop
+form; then `main`, for a project that names none; then the branch it is on. With
+Worktree on, a local or remote default can supply the base. With Worktree off, it must
+be a local branch; a remote-only default requires an explicit local branch choice. None
+of these requires an explicit branch choice; a failed worktree creation never silently turns
Worktree off. Branch does not follow the pane New Harness was opened from:
New Harness is new work, and another agent's branch is one pick away. The start
action reads **New Harness**, whatever the rows say.
@@ -282,6 +283,35 @@ 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.
+## Pasting a path or a GitHub link
+
+The project search reads what was typed
+(docs/plans/2026-10-30-new-harness-paste-path-or-repository.md). A path, or a
+GitHub link (`github.com/…` or `git@<host>:…`), gets one action row above the
+doors, highlighted, so Enter does it. Anything else, a bare `owner/repo`
+included, filters the recent projects as before.
+
+- A path naming a folder: **Open \<path\>**. Otherwise **Browse \<folder\>/**,
+ which moves to the Open Folder prompt with the typed text. A half-typed path
+ that a recent project matches shows no Browse row: the project keeps the
+ highlight.
+- A repository link: **Clone owner/repo**, the same row the GitHub prompt shows.
+ Its detail names the SSH alias it goes through, and, on another computer,
+ that it uses that computer's GitHub access. A GitHub link that is no
+ repository is a disabled **Not a repository link**. On this computer, an
+ alias whose `ssh -G` host is not github.com is a disabled **\<alias\> isn't a
+ GitHub host**. Another computer's daemon checks its own aliases at launch.
+- A terminal takes no project, so it clones nothing: a link shows a disabled **A terminal
+ can't clone**, and changing to Terminal with a clone chosen asks for a folder or an agent.
+- While it clones the line reads **Cloning owner/repo…**. A checkout of that
+ repository already in the projects folder is used, not cloned, and the line
+ stays **Starting harness…**, as it does when the computer cannot say. A clone refused
+ access tries the other transport, then up to three `~/.ssh/config` aliases
+ leading to github.com. It moves on only after a refusal, never after a network
+ failure or a timeout. Through an alias, the workspace says **Cloned via
+ \<alias\>** once. Refused everywhere: **No access to owner/repo on \<computer\>**,
+ with the task and choices kept.
+
## Regression coverage
`tool/check_new_harness_coverage.mjs` requires 100% executable-line coverage of
diff --git a/desktop/lib/core/github_repository.dart b/desktop/lib/core/github_repository.dart
new file mode 100644
index 000000000..0ae2dbde1
--- /dev/null
+++ b/desktop/lib/core/github_repository.dart
@@ -0,0 +1,194 @@
+/// How a repository address reaches GitHub: the browser's HTTPS link, plain
+/// SSH, or an SSH host alias from the computer's `~/.ssh/config` — a second
+/// GitHub account on one computer is reached only through its alias.
+enum GitHubTransport { https, ssh, alias }
+
+/// An SSH host alias as `ssh` and `git` may be given one: it can never begin
+/// with `-` and turn into an option. Mirrors cli/src/lib/githubRepository.ts.
+final _alias = RegExp(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$');
+final _owner = RegExp(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}$');
+final _name = RegExp(r'^[A-Za-z0-9_.-]{1,100}$');
+
+bool isSafeSshAlias(String alias) => _alias.hasMatch(alias);
+
+/// Whether an SSH host name is GitHub: `ssh.github.com` is GitHub's SSH over
+/// port 443, which a second account's alias behind a firewall uses.
+bool isGitHubHost(String? host) =>
+ host == 'github.com' || host == 'ssh.github.com';
+
+/// One GitHub repository somebody pasted. Held to the CLI's vectors
+/// (cli/src/lib/__fixtures__/github-repository-vectors.json): the daemon clones
+/// another computer's harness and this app clones this computer's.
+class GitHubRepository {
+ const GitHubRepository._(
+ this.url,
+ this.owner,
+ this.name,
+ this.transport, [
+ this.alias,
+ ]);
+ final String url, owner, name;
+ final GitHubTransport transport;
+
+ /// The `~/.ssh/config` host it goes through, for [GitHubTransport.alias].
+ final String? alias;
+
+ static GitHubRepository? parse(String input) {
+ final text = input.trim();
+ // A query, a fragment, an escape or a space is never part of a
+ // repository's address, even an empty one (the shared vectors).
+ if (RegExp(r'[\s?#%]').hasMatch(text)) return null;
+ final scp = RegExp(r'^git@([^:/\s]+):(\S+)$').firstMatch(text);
+ String path;
+ String? alias;
+ if (scp != null) {
+ final host = scp.group(1)!;
+ if (host != 'github.com') {
+ if (!isSafeSshAlias(host)) return null;
+ alias = host;
+ }
+ path = scp.group(2)!;
+ } else {
+ // `github.com/owner/repo` is a browser link without its scheme.
+ final withScheme = text.contains('://')
+ ? text
+ : text.startsWith('github.com/')
+ ? 'https://$text'
+ : 'https://github.com/$text';
+ final uri = Uri.tryParse(withScheme);
+ if (uri == null ||
+ uri.scheme != 'https' ||
+ uri.host != 'github.com' ||
+ uri.userInfo.isNotEmpty ||
+ uri.hasPort ||
+ uri.hasQuery ||
+ uri.hasFragment) {
+ return null;
+ }
+ path = uri.path.replaceFirst(RegExp(r'^/'), '');
+ }
+ path = path
+ .replaceFirst(RegExp(r'/$'), '')
+ .replaceFirst(RegExp(r'\.git$'), '');
+ final parts = path.split('/');
+ if (parts.length != 2 ||
+ !_owner.hasMatch(parts[0]) ||
+ !_name.hasMatch(parts[1]) ||
+ parts[1] == '.' ||
+ parts[1] == '..') {
+ return null;
+ }
+ if (scp == null) {
+ return GitHubRepository._(
+ 'https://github.com/$path.git',
+ parts[0],
+ parts[1],
+ GitHubTransport.https,
+ );
+ }
+ return GitHubRepository._(
+ 'git@${alias ?? 'github.com'}:$path.git',
+ parts[0],
+ parts[1],
+ alias == null ? GitHubTransport.ssh : GitHubTransport.alias,
+ alias,
+ );
+ }
+
+ /// `owner/repo`, as a person reads it.
+ String get slug => '$owner/$name';
+
+ /// The address to hand anyone but this computer's own git: an alias means
+ /// something only in this computer's `~/.ssh/config`, so a Swarm, a cloud
+ /// agent or a teammate gets the HTTPS link instead.
+ String get shareableUrl =>
+ alias == null ? url : 'https://github.com/$slug.git';
+}
+
+/// 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/githubRepository.ts.
+String? repositoryIdentity(String address) {
+ final parts = _hostAndPath(address);
+ return parts == null ? null : '${parts.$1}/${parts.$2}'.toLowerCase();
+}
+
+/// [repositoryIdentity] with an SSH alias read as the host it stands for, so
+/// a checkout cloned through `git@gh-work:org/repo` is the repository a
+/// browser link names. [resolveHost] answers null for a host it cannot read.
+Future<String?> resolvedRepositoryIdentity(
+ String address,
+ Future<String?> Function(String host) resolveHost,
+) async {
+ final parts = _hostAndPath(address);
+ if (parts == null) return null;
+ var host = parts.$1.toLowerCase();
+ // Only ssh reads ~/.ssh/config: an https or git:// host is a real name.
+ final scheme = RegExp(
+ r'^([a-z][a-z0-9+.-]*)://',
+ caseSensitive: false,
+ ).firstMatch(address.trim())?.group(1)?.toLowerCase();
+ final viaSsh =
+ scheme == null ||
+ scheme == 'ssh' ||
+ scheme == 'git+ssh' ||
+ scheme == 'ssh+git';
+ if (host != 'github.com' && viaSsh && isSafeSshAlias(host)) {
+ host = (await resolveHost(host))?.toLowerCase() ?? host;
+ }
+ if (isGitHubHost(host)) host = 'github.com';
+ return '$host/${parts.$2}'.toLowerCase();
+}
+
+(String, String)? _hostAndPath(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);
+}
+
+/// The most `~/.ssh/config` aliases a refused clone goes on to try: each is a
+/// round trip to GitHub, and three covers every multi-account setup seen.
+const maxCloneAliases = 3;
+
+/// The addresses a clone tries, in order: what was pasted, the same
+/// repository over the other transport, then the computer's GitHub [aliases].
+/// A clone moves to the next only when GitHub refused access.
+List<String> cloneAttempts(GitHubRepository repository, List<String> aliases) {
+ final path = repository.slug;
+ final https = 'https://github.com/$path.git';
+ final ssh = '[email protected]:$path.git';
+ final usable = aliases
+ .where((alias) => alias != 'github.com' && isSafeSshAlias(alias))
+ .take(maxCloneAliases);
+ // A set keeps the first of each: whatever was pasted, then the other.
+ return {
+ repository.url,
+ https,
+ ssh,
+ for (final alias in usable) 'git@$alias:$path.git',
+ }.toList();
+}
diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dart
index 1776190c5..987f0fb6e 100644
--- a/desktop/lib/core/project_folder.dart
+++ b/desktop/lib/core/project_folder.dart
@@ -213,6 +213,7 @@ class ProjectFolderRequest {
RepositoryClone Function()? createClone,
String label = 'harness',
DateTime Function()? now,
+ void Function(String alias)? onClonedVia,
}) async {
final home = maybeHomeDir();
if (projectHome == null && (home == null || !p.isAbsolute(home))) {
@@ -235,10 +236,10 @@ class ProjectFolderRequest {
}
await root.create(recursive: true);
if (repository case final repo?) {
- return await (createClone?.call() ?? RepositoryClone()).run(
- repo,
- root.path,
- );
+ final clone = createClone?.call() ?? RepositoryClone();
+ final folder = await clone.run(repo, root.path);
+ if (clone.clonedVia case final alias?) onClonedVia?.call(alias);
+ return folder;
}
if (folderName case final named?) {
// A name somebody chose is never quietly changed: an existing folder
diff --git a/desktop/lib/core/repository_clone.dart b/desktop/lib/core/repository_clone.dart
index accc3dbdb..c624f9c33 100644
--- a/desktop/lib/core/repository_clone.dart
+++ b/desktop/lib/core/repository_clone.dart
@@ -4,48 +4,10 @@ import 'dart:io';
import 'package:path/path.dart' as p;
-class GitHubRepository {
- const GitHubRepository._(this.url, this.name);
- final String url, name;
+import 'github_repository.dart';
+import 'ssh_hosts.dart';
- static GitHubRepository? parse(String input) {
- final text = input.trim();
- final ssh = text.startsWith('[email protected]:');
- String path;
- if (ssh) {
- path = text.substring('[email protected]:'.length);
- } else {
- final uri = Uri.tryParse(
- text.contains('://') ? text : 'https://github.com/$text',
- );
- if (uri == null ||
- uri.scheme != 'https' ||
- uri.host != 'github.com' ||
- uri.userInfo.isNotEmpty ||
- uri.hasPort ||
- uri.hasQuery ||
- uri.hasFragment) {
- return null;
- }
- path = uri.path.replaceFirst(RegExp(r'^/'), '');
- }
- path = path
- .replaceFirst(RegExp(r'/$'), '')
- .replaceFirst(RegExp(r'\.git$'), '');
- final parts = path.split('/');
- if (parts.length != 2 ||
- !RegExp(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}$').hasMatch(parts[0]) ||
- !RegExp(r'^[A-Za-z0-9_.-]{1,100}$').hasMatch(parts[1]) ||
- parts[1] == '.' ||
- parts[1] == '..') {
- return null;
- }
- return GitHubRepository._(
- ssh ? '[email protected]:$path.git' : 'https://github.com/$path.git',
- parts[1],
- );
- }
-}
+export 'github_repository.dart';
class RepositoryCloneException implements Exception {
const RepositoryCloneException(this.message);
@@ -54,39 +16,6 @@ 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,
@@ -101,12 +30,22 @@ typedef GitOriginReader = Future<String?> Function(String folder);
/// is already a checkout of the same repository is that project, and is used
/// rather than refused.
class RepositoryClone {
- RepositoryClone({GitCloneProcess? startProcess, GitOriginReader? readOrigin})
- : _startProcess = startProcess ?? _startGit,
- _readOrigin = readOrigin ?? readCheckoutOrigin;
+ RepositoryClone({
+ GitCloneProcess? startProcess,
+ GitOriginReader? readOrigin,
+ SshHosts? sshHosts,
+ }) : _startProcess = startProcess ?? _startGit,
+ _readOrigin = readOrigin ?? readCheckoutOrigin,
+ _sshHosts = sshHosts ?? SshHosts();
final GitCloneProcess _startProcess;
final GitOriginReader _readOrigin;
+ final SshHosts _sshHosts;
+ final _stagings = <Directory>[];
Process? _process;
+
+ /// The `~/.ssh/config` alias the clone went through, when it needed one: a
+ /// second GitHub account, which later pushes from the checkout use too.
+ String? clonedVia;
bool _cancelled = false;
bool _started = false;
@@ -166,12 +105,18 @@ class RepositoryClone {
}
/// Whether [folder] is a checkout of [repository]: anything else there
- /// (another repository, a folder of files) stays the person's, refused.
+ /// (another repository, a folder of files) stays the person's, refused. An
+ /// origin cloned through an SSH alias names the repository its host does.
Future<bool> _holds(String folder, GitHubRepository repository) async {
try {
final origin = await _readOrigin(folder);
- return origin != null &&
- repositoryIdentity(origin) == repositoryIdentity(repository.url);
+ if (origin == null) return false;
+ // Both sides: a pasted alias names the repository its host does too.
+ return await resolvedRepositoryIdentity(origin, _sshHosts.resolveHost) ==
+ await resolvedRepositoryIdentity(
+ repository.url,
+ _sshHosts.resolveHost,
+ );
} catch (_) {
return false;
}
@@ -185,9 +130,6 @@ class RepositoryClone {
Future<String> run(GitHubRepository repository, String parent) async {
if (_started) throw StateError('A clone can only be started once.');
_started = true;
- Directory? staging;
- Timer? deadline;
- var timedOut = false;
try {
if (!p.isAbsolute(parent) || !await Directory(parent).exists()) {
throw const RepositoryCloneException(
@@ -206,26 +148,109 @@ class RepositoryClone {
'“${repository.name}” already exists here. Choose another destination, or open that folder.',
);
}
- if (_cancelled) throw const RepositoryCloneException('Clone cancelled.');
- staging = await Directory(parent).createTemp('.harness-clone-');
- final checkout = p.join(staging.path, 'checkout');
- final process = _process = await _startProcess(
- ['clone', '--', repository.url, checkout],
- {
- 'GIT_TERMINAL_PROMPT': '0',
- 'GCM_INTERACTIVE': 'Never',
- if (!Platform.environment.containsKey('GIT_SSH_COMMAND'))
- 'GIT_SSH_COMMAND': 'ssh -oBatchMode=yes -oConnectTimeout=20',
- },
+ if (repository.alias case final alias?
+ when !isGitHubHost(await _sshHosts.resolveHost(alias))) {
+ throw RepositoryCloneException(
+ '$alias isn\'t a GitHub host on this computer.',
+ );
+ }
+ final checkout = await _cloneWithAccess(repository, parent);
+ 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.',
+ );
+ }
+ await Directory(checkout).rename(destination);
+ return destination;
+ } on ProcessException {
+ throw const RepositoryCloneException(
+ 'Git could not start. Install Git on this computer, then retry.',
);
- unawaited(process.stdin.close());
- if (_cancelled) process.kill();
- deadline = Timer(const Duration(minutes: 5), () {
- timedOut = true;
- process.kill();
- });
- // Drain both streams, retaining only a bounded diagnostic for classifying
- // failures. Git URLs/credential-helper output never enter the UI or logs.
+ } on FileSystemException {
+ throw const RepositoryCloneException(
+ 'Could not write to this destination. Choose a folder you can edit.',
+ );
+ } finally {
+ _process = null;
+ await _removeStagings();
+ }
+ }
+
+ /// A refused attempt's staging goes before the next one starts, so a quit
+ /// mid-run leaves at most one `.harness-clone-*` behind.
+ Future<void> _removeStagings() async {
+ for (final staging in [..._stagings]) {
+ _stagings.remove(staging);
+ try {
+ if (await staging.exists()) await staging.delete(recursive: true);
+ } on FileSystemException {
+ /* The checkout outcome remains authoritative. */
+ }
+ }
+ }
+
+ /// Clones through each way this computer may reach [repository] — what was
+ /// pasted, the other transport, then its `~/.ssh/config` GitHub aliases —
+ /// moving on only when GitHub refused access. On 2026-10-30 a developer Mac
+ /// with SSH keys and no HTTPS credential failed every browser link, and its
+ /// second account's repositories answered only through an alias.
+ Future<String> _cloneWithAccess(
+ GitHubRepository repository,
+ String parent,
+ ) async {
+ final tried = <String>{};
+ var attempts = cloneAttempts(repository, const []);
+ var aliasesRead = false;
+ for (var i = 0; i < attempts.length; i++) {
+ final url = attempts[i];
+ if (!tried.add(url)) continue;
+ final checkout = await _cloneOnce(url, parent);
+ if (checkout == null) await _removeStagings();
+ if (checkout != null) {
+ clonedVia = GitHubRepository.parse(url)?.alias;
+ return checkout;
+ }
+ // Refused: the aliases are read only now, when they may be needed.
+ if (!aliasesRead) {
+ aliasesRead = true;
+ attempts = cloneAttempts(repository, await _sshHosts.githubAliases());
+ i = -1;
+ }
+ }
+ throw RepositoryAccessDenied(repository);
+ }
+
+ /// One `git clone` of [url] into a fresh staging folder: the checkout, or
+ /// null when GitHub refused access. Any other failure ends the clone.
+ Future<String?> _cloneOnce(String url, String parent) async {
+ if (_cancelled) throw const RepositoryCloneException('Clone cancelled.');
+ final staging = await Directory(parent).createTemp('.harness-clone-');
+ _stagings.add(staging);
+ final checkout = p.join(staging.path, 'checkout');
+ var timedOut = false;
+ final process = _process = await _startProcess(
+ ['clone', '--', url, checkout],
+ {
+ 'GIT_TERMINAL_PROMPT': '0',
+ 'GCM_INTERACTIVE': 'Never',
+ if (!Platform.environment.containsKey('GIT_SSH_COMMAND'))
+ 'GIT_SSH_COMMAND': 'ssh -oBatchMode=yes -oConnectTimeout=20',
+ },
+ );
+ unawaited(process.stdin.close());
+ if (_cancelled) process.kill();
+ final deadline = Timer(const Duration(minutes: 5), () {
+ timedOut = true;
+ process.kill();
+ });
+ try {
+ // Drain both streams, retaining only a bounded diagnostic for
+ // classifying failures. Git URLs/credential-helper output never enter
+ // the UI or logs.
final output = process.stdout.drain<void>();
var diagnostic = '';
final errors = process.stderr
@@ -247,48 +272,29 @@ class RepositoryClone {
'Cloning took too long. Check the connection and retry.',
);
}
- if (code != 0) {
- if (RegExp(
- r'authentication|permission denied|could not read Username|repository not found',
- caseSensitive: false,
- ).hasMatch(diagnostic)) {
- throw const RepositoryCloneException(
- 'Could not access this repository. Check the URL and your GitHub access on this computer.',
- );
- }
- throw const RepositoryCloneException(
- 'Could not clone the repository. Check the URL and connection, then retry.',
- );
- }
- 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.',
- );
+ if (code == 0) return checkout;
+ // A private repository answers "not found" to whoever cannot see it.
+ if (RegExp(
+ r'authentication|permission denied|could not read Username|repository not found',
+ caseSensitive: false,
+ ).hasMatch(diagnostic)) {
+ return null;
}
- await Directory(checkout).rename(destination);
- return destination;
- } on ProcessException {
throw const RepositoryCloneException(
- 'Git could not start. Install Git on this computer, then retry.',
- );
- } on FileSystemException {
- throw const RepositoryCloneException(
- 'Could not write to this destination. Choose a folder you can edit.',
+ 'Could not clone the repository. Check the URL and connection, then retry.',
);
} finally {
- deadline?.cancel();
- _process = null;
- if (staging != null) {
- try {
- if (await staging.exists()) await staging.delete(recursive: true);
- } on FileSystemException {
- /* The checkout outcome remains authoritative. */
- }
- }
+ deadline.cancel();
}
}
}
+
+/// Every way this computer has to GitHub was refused: the repository is
+/// private to accounts it is not signed in as, or does not exist.
+class RepositoryAccessDenied extends RepositoryCloneException {
+ RepositoryAccessDenied(GitHubRepository repository)
+ : super(
+ 'No access to ${repository.slug} on '
+ '${Platform.isMacOS ? 'this Mac' : 'this computer'}.',
+ );
+}
diff --git a/desktop/lib/core/ssh_hosts.dart b/desktop/lib/core/ssh_hosts.dart
new file mode 100644
index 000000000..689a42b3b
--- /dev/null
+++ b/desktop/lib/core/ssh_hosts.dart
@@ -0,0 +1,155 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:path/path.dart' as p;
+
+import 'github_repository.dart';
+import 'home_dir.dart';
+
+/// `ssh -G <alias>`'s output, or null when ssh could not say.
+typedef SshRunner = Future<String?> Function(List<String> arguments);
+
+/// `ssh -G` prints a few KiB; more is not a configuration to trust.
+const _maxOutputBytes = 64 * 1024;
+
+/// The most of one config file read: a config is a few KiB, and a refused
+/// clone must not stall on a file somebody pointed at something huge. The
+/// daemon's sshHosts.ts reads the same.
+const _maxConfigBytes = 256 * 1024;
+
+/// The most host names asked about: each is an `ssh -G` run, as in the
+/// daemon's sshHosts.ts.
+const _maxAsked = 20;
+
+/// The SSH host aliases of the computer this app runs on, read only when a
+/// clone needs them. Mirrors cli/src/lib/sshHosts.ts, which answers the same
+/// for the daemon's computer.
+class SshHosts {
+ SshHosts({String? home, SshRunner? runSsh})
+ : _home = home ?? maybeHomeDir(),
+ _runSsh = runSsh ?? _sshG;
+ final String? _home;
+ final SshRunner _runSsh;
+
+ /// `ssh -G` prints the configuration an alias resolves to without
+ /// connecting, so reading it costs no network and asks for nothing.
+ static Future<String?> _sshG(List<String> arguments) async {
+ final Process process;
+ try {
+ process = await Process.start('ssh', arguments);
+ } on ProcessException {
+ return null;
+ }
+ unawaited(process.stdin.close());
+ unawaited(process.stderr.drain<void>());
+ final output = process.stdout
+ .transform(const Utf8Decoder(allowMalformed: true))
+ .join();
+ try {
+ final code = await process.exitCode.timeout(const Duration(seconds: 4));
+ final text = await output;
+ return code == 0 && text.length <= _maxOutputBytes ? text : null;
+ } on TimeoutException {
+ process.kill(ProcessSignal.sigkill);
+ return null;
+ }
+ }
+
+ /// The host name [alias] stands for, or null. A name that could be read as
+ /// an option never reaches ssh.
+ Future<String?> resolveHost(String alias) async {
+ if (!isSafeSshAlias(alias)) return null;
+ final output = await _runSsh(['-G', alias]);
+ if (output == null) return null;
+ for (final line in const LineSplitter().convert(output)) {
+ if (line.startsWith('hostname ')) {
+ return line.substring('hostname '.length).trim().toLowerCase();
+ }
+ }
+ return null;
+ }
+
+ /// The config's own host names that lead to github.com, in the order
+ /// written, at most [maxCloneAliases]: a second GitHub account on one
+ /// computer is reachable only through one of these.
+ Future<List<String>> githubAliases() async {
+ final home = _home;
+ if (home == null) return const [];
+ final found = <String>[];
+ final names = (await _hostNames(p.join(home, '.ssh', 'config'), 0))
+ .where((name) => name != 'github.com' && isSafeSshAlias(name))
+ .toSet()
+ .take(_maxAsked);
+ for (final alias in names) {
+ if (found.length == maxCloneAliases) break;
+ if (isGitHubHost(await resolveHost(alias))) found.add(alias);
+ }
+ return found;
+ }
+
+ /// The `Host` names in [file], with each `Include` read in place, one
+ /// level deep. Patterns (`*`, `?`, `!`) name no single host.
+ Future<List<String>> _hostNames(String file, int depth) async {
+ final String text;
+ try {
+ final handle = File(file);
+ if (await handle.length() > _maxConfigBytes) return const [];
+ text = await handle.readAsString();
+ } on FileSystemException {
+ return const [];
+ }
+ final names = <String>[];
+ for (final raw in const LineSplitter().convert(text)) {
+ final line = raw.trim();
+ final match = RegExp(
+ r'^(host|include)\s*(?:=\s*|\s)\s*(.+)$',
+ caseSensitive: false,
+ ).firstMatch(line);
+ if (match == null) continue;
+ // `Host "gh-personal"`: ssh takes a quoted name as the name.
+ final values = [
+ for (final value in match.group(2)!.split(RegExp(r'\s+')))
+ value.replaceAll('"', ''),
+ ];
+ if (match.group(1)!.toLowerCase() == 'host') {
+ names.addAll(values.where((v) => !RegExp(r'[*?!]').hasMatch(v)));
+ } else if (depth == 0) {
+ for (final pattern in values) {
+ for (final included in await _expand(pattern)) {
+ names.addAll(await _hostNames(included, depth + 1));
+ }
+ }
+ }
+ }
+ return names;
+ }
+
+ /// An `Include` argument as ssh reads it: `~` is home, a relative path is
+ /// under `~/.ssh`, and `*` or `?` in the last segment match its folder's
+ /// files.
+ Future<List<String>> _expand(String pattern) async {
+ final home = _home!;
+ final path = pattern.startsWith('~/')
+ ? p.join(home, pattern.substring(2))
+ : p.isAbsolute(pattern)
+ ? pattern
+ : p.join(home, '.ssh', pattern);
+ final name = p.basename(path);
+ if (!name.contains('*') && !name.contains('?')) return [path];
+ final glob = RegExp.escape(name)
+ .replaceAll(r'\*', '.*')
+ .replaceAll(r'\?', '.');
+ final matcher = RegExp('^$glob\$');
+ try {
+ final entries = await Directory(p.dirname(path)).list().toList();
+ return [
+ for (final entry in entries)
+ if (entry is File && matcher.hasMatch(p.basename(entry.path)))
+ entry.path,
+ ]..sort();
+ } on FileSystemException {
+ return const [];
+ }
+ }
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index fc5e8c463..1bb947847 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -14946,6 +14946,10 @@ class AppNotifier extends ChangeNotifier {
},
timeout: const Duration(seconds: 10),
);
+ } on WsRequestFailure catch (failure) {
+ // The machine answered. NOT_FOUND says a folder is not there, which a
+ // machine that could not be reached does not know.
+ return {'error': failure.code};
} catch (error) {
return {'error': 'UNREACHABLE'};
}
@@ -15154,7 +15158,31 @@ class AppNotifier extends ChangeNotifier {
Future<String> prepareLocalProjectFolder(
ProjectFolderRequest request, {
String label = 'harness',
- }) => request.prepareLocal(label: label);
+ }) async {
+ String? via;
+ final folder = await request.prepareLocal(
+ label: label,
+ onClonedVia: (alias) => via = alias,
+ );
+ if (via case final alias?) _clonedViaFolders[folder] = alias;
+ return folder;
+ }
+
+ /// A folder this computer's own clone reached through an SSH alias, until
+ /// its creation tells the person ([_announceClonedVia]).
+ final _clonedViaFolders = <String, String>{};
+
+ /// The alias a machine's own clone went through (cli launches.ts
+ /// `clonedVia`), when it names a safe one.
+ static String? _clonedViaOf(Map<String, dynamic> result) {
+ final via = result['clonedVia'];
+ final alias = via is Map ? via['alias'] : null;
+ return alias is String && isSafeSshAlias(alias) ? alias : null;
+ }
+
+ void _announceClonedVia(String? alias) {
+ if (alias != null) agentChangeNotice?.call('Cloned via $alias');
+ }
Future<String?> createAgent(
String machineId, {
@@ -15999,6 +16027,16 @@ class AppNotifier extends ChangeNotifier {
creation._existingFolder = folder;
return creation._complete(_projectExistsMessage(folder, machineName));
}
+ // Every way that machine has to GitHub was refused (cli launches.ts
+ // `access`): one short line, in the app's words, names the repository.
+ final denied = failure['access'] == 'denied'
+ ? GitHubRepository.parse('${choices['repositoryUrl'] ?? ''}')
+ : null;
+ if (denied != null) {
+ return creation._complete(
+ 'No access to ${denied.slug} on $machineName.',
+ );
+ }
return creation._complete(
_creationFailureMessage(
failure['code'] as String,
@@ -16025,6 +16063,10 @@ class AppNotifier extends ChangeNotifier {
creation._complete(null);
if (_disposed || machineStates[machineId] != machine) return null;
creation._agentId = agent.id;
+ _announceClonedVia(
+ _clonedViaFolders.remove(creation._preparedFolder) ??
+ _clonedViaOf(result),
+ );
if (choices['prompt'] case final String prompt
when prompt.trim().isNotEmpty) {
_firstMessages[(machineId, agent.id)] = prompt;
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index bad445a87..a8776d613 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -24,6 +24,7 @@ import '../core/git_worktree.dart';
import '../core/permission_modes.dart';
import '../core/project_folder.dart';
import '../core/repository_clone.dart';
+import '../core/ssh_hosts.dart';
import '../core/test_run.dart';
import '../finder/finder_availability.dart';
import '../widgets/engine_identity.dart';
@@ -161,14 +162,25 @@ String? currentBranchRef(GitProjectInfo info) =>
/// Git projects keep Worktree on; an empty repository asks for a choice.
bool worktreeByDefault(GitProjectInfo info) => info.isGit;
-/// New work starts from main. If it is absent, require an explicit choice.
+/// New work starts from the branch the project calls its default
+/// (`origin/HEAD`), preferring the local copy; then main, for a project that
+/// names none; then the branch it is on. octocat/Hello-World is on master, and
+/// reading only main refused it until a branch was chosen by hand. Null asks.
/// With Worktree off, show the branch the folder is actually on.
String? defaultBranchRef(GitProjectInfo info, {required bool worktree}) {
if (!worktree) return currentBranchRef(info);
- for (final ref in ['refs/heads/main', 'refs/remotes/origin/main']) {
+ final remote = info.defaultRef;
+ for (final ref in [
+ if (remote != null) ...[
+ 'refs/heads/${remote.split('/').skip(3).join('/')}',
+ remote,
+ ],
+ 'refs/heads/main',
+ 'refs/remotes/origin/main',
+ ]) {
if (info.branches.any((branch) => branch.ref == ref)) return ref;
}
- return null;
+ return currentBranchRef(info);
}
/// The branch a worktree started from [base] is on, unless [name] was typed:
@@ -886,17 +898,17 @@ class NewHarnessController extends ChangeNotifier {
: _recoveredWorktreePreference ??
(isGitProject && !inWorktree ? worktree : null);
- /// Fresh desktop work starts on main, with or without a worktree. A retry
+ /// Fresh desktop work starts on the default branch, with or without a worktree. A retry
/// must instead keep the branch of the folder its first attempt prepared.
- bool get _defaultsToMain =>
+ bool get _startsOnDefault =>
_desktopChoices && _attempt?.preparedFolder == null && !inWorktree;
String? get branchRef {
if (_branchRef != null) return _branchRef;
- if (_defaultsToMain) {
- final main = defaultBranchRef(_gitProject, worktree: true);
- return !worktree && main?.startsWith('refs/remotes/') == true
+ if (_startsOnDefault) {
+ final start = defaultBranchRef(_gitProject, worktree: true);
+ return !worktree && start?.startsWith('refs/remotes/') == true
? null
- : main;
+ : start;
}
return defaultBranchRef(_gitProject, worktree: worktree);
}
@@ -904,7 +916,9 @@ class NewHarnessController extends ChangeNotifier {
String? get gitError => _gitProject.error;
String get branchLabel =>
_refName(branchRef) ??
- (worktree || _defaultsToMain ? 'main · unavailable' : 'Detached HEAD');
+ (worktree || _startsOnDefault
+ ? 'default · unavailable'
+ : 'Detached HEAD');
String? _refName(String? ref) =>
_gitProject.branches
.where((branch) => branch.ref == ref)
@@ -1114,7 +1128,7 @@ class NewHarnessController extends ChangeNotifier {
// One the person picked stays itself ([inWorktree]).
if (info.mainFolder case final main?
when _project.folder == key.$2 && !_project.exact) {
- if (!_defaultsToMain &&
+ if (!_startsOnDefault &&
_worktree == false &&
_branchRef == null &&
info.branch != null) {
@@ -1790,7 +1804,9 @@ class NewHarnessController extends ChangeNotifier {
/// repository to clone, an agent that ran in that folder, or the Swarm's
/// own checkout there.
String? _remoteOf(String machineId, NewHarnessProject project) {
- if (project.repository case final repository?) return repository.url;
+ if (project.repository case final repository?) {
+ return repository.shareableUrl;
+ }
final folder = project.folder;
if (folder == null) return null;
final machine = app.stateOf(machineId);
@@ -1845,7 +1861,7 @@ class NewHarnessController extends ChangeNotifier {
/// The GitHub repository a cloud coding agent works on: the one chosen to
/// clone, else the chosen folder's own remote; null when neither is on GitHub.
String? get cloudRepository {
- final cloned = _project.repository?.url;
+ final cloned = _project.repository?.shareableUrl;
if (cloned != null) return cloned;
final folder = _project.folder;
final machine = _machine;
@@ -1886,6 +1902,14 @@ class NewHarnessController extends ChangeNotifier {
if (needsProject) {
return (field: NewHarnessField.projectMenu, message: 'Choose a project.');
}
+ // A terminal sends no project ([projectFolderRequest]): it would open at
+ // home under a chip that still names the repository.
+ if (isTerminal && _project.repository != null) {
+ return (
+ field: NewHarnessField.projectMenu,
+ message: "A terminal can't clone. Choose a folder or an agent.",
+ );
+ }
final machine = _machine;
if (machine == null || machine.isOffline || machine.needsLink) {
return (
@@ -1939,7 +1963,7 @@ class NewHarnessController extends ChangeNotifier {
}
if (!checkingGit &&
isGitProject &&
- (worktree || _defaultsToMain && _gitProject.branches.isNotEmpty) &&
+ (worktree || _startsOnDefault && _gitProject.branches.isNotEmpty) &&
branchRef == null) {
return (
field: _gitProject.branches.isEmpty
@@ -1947,7 +1971,7 @@ class NewHarnessController extends ChangeNotifier {
: NewHarnessField.branch,
message: _gitProject.branches.isEmpty
? 'This project has no commits. Choose a project or make an initial commit.'
- : 'This project has no main branch. Choose a branch.',
+ : 'This project has no default branch. Choose a branch.',
);
}
if (usesProfile &&
@@ -2326,6 +2350,19 @@ class NewHarnessController extends ChangeNotifier {
static const guestWorkspaceId = 'project:guest-workspace';
static const guestFolderId = 'project:guest-folder:';
static const repositoryId = 'project:repository';
+
+ /// The one action a pasted path or GitHub link gets at the top of the
+ /// project menu (docs/plans/2026-10-30-new-harness-paste-path-or-repository.md).
+ static const pasteOpenId = 'project:paste:open';
+ static const pasteBrowseId = 'project:paste:browse';
+ static const pasteInvalidId = 'project:paste:invalid';
+ static const cloneId = 'project:clone';
+ static const _pasteIds = {
+ pasteOpenId,
+ pasteBrowseId,
+ pasteInvalidId,
+ cloneId,
+ };
static const storeId = 'agent:store';
static const codingId = 'harness:coding';
static const defaultModelId = 'model:subscription';
@@ -2389,37 +2426,44 @@ class NewHarnessController extends ChangeNotifier {
}
}
- List<NewHarnessOption> _projectMenu() => asGuest
- ? _guestPlaces()
- : [
- if (!_desktopChoices)
- const NewHarnessOption(
- id: repositoryId,
- synthetic: true,
- title: 'Clone Repository',
- detail: 'Paste a GitHub repository URL',
- ),
- const NewHarnessOption(
- id: existingProjectId,
- synthetic: true,
- title: 'Open Folder',
- detail: 'Enter a path or browse folders',
- ),
- const NewHarnessOption(
- id: newProjectId,
- synthetic: true,
- title: 'New Folder',
- detail: 'Name a new folder',
- ),
- if (_desktopChoices)
- const NewHarnessOption(
- id: repositoryId,
- synthetic: true,
- title: 'GitHub',
- detail: 'Clone a GitHub repository',
- ),
- ..._ranked(_recentProjects()),
- ];
+ List<NewHarnessOption> _projectMenu() {
+ if (asGuest) return _guestPlaces();
+ final recent = _ranked(_recentProjects());
+ var pasted = _pasteAction();
+ // A half-typed path a recent project matches is that project: Browse
+ // would take the highlight from the answer already on screen.
+ if (pasted?.id == pasteBrowseId && recent.isNotEmpty) pasted = null;
+ return [
+ ?pasted,
+ if (!_desktopChoices)
+ const NewHarnessOption(
+ id: repositoryId,
+ synthetic: true,
+ title: 'Clone Repository',
+ detail: 'Paste a GitHub repository URL',
+ ),
+ const NewHarnessOption(
+ id: existingProjectId,
+ synthetic: true,
+ title: 'Open Folder',
+ detail: 'Enter a path or browse folders',
+ ),
+ const NewHarnessOption(
+ id: newProjectId,
+ synthetic: true,
+ title: 'New Folder',
+ detail: 'Name a new folder',
+ ),
+ if (_desktopChoices)
+ const NewHarnessOption(
+ id: repositoryId,
+ synthetic: true,
+ title: 'GitHub',
+ detail: 'Clone a GitHub repository',
+ ),
+ ...recent,
+ ];
+ }
/// Takes the highlighted row as this field's answer and moves along.
void accept([NewHarnessOption? row]) {
@@ -2461,6 +2505,12 @@ class NewHarnessController extends ChangeNotifier {
return;
}
if (option?.id == browseId) return;
+ if (option?.id == pasteBrowseId) {
+ final typed = query.trim();
+ focusField(NewHarnessField.project);
+ setQuery(typed);
+ return;
+ }
if (option == null) {
// Return is never silent: nothing matched, so say so and how to go on.
error = field == NewHarnessField.projectName && query.trim().isEmpty
@@ -3219,7 +3269,9 @@ class NewHarnessController extends ChangeNotifier {
: kept >= 0
? kept
: field == NewHarnessField.projectMenu
- ? (firstProject >= 0
+ ? (options.isNotEmpty && _pasteIds.contains(options.first.id)
+ ? 0
+ : firstProject >= 0
? firstProject
: options.indexWhere((option) => option.id == existingProjectId))
: query.isEmpty && now >= 0
@@ -3772,17 +3824,134 @@ class NewHarnessController extends ChangeNotifier {
List<NewHarnessOption> _repositoryOptions() {
final repository = GitHubRepository.parse(query.trim());
- return [
- if (repository != null)
- NewHarnessOption(
- id: 'project:clone',
+ return [?(repository == null ? null : _cloneRow(repository))];
+ }
+
+ /// What a pasted path or GitHub link offers, or null for a search. A bare
+ /// `owner/repo` is a search here: `team/api` is as likely a folder name.
+ NewHarnessOption? _pasteAction() {
+ final typed = query.trim();
+ if (typed.isEmpty) return null;
+ if (_isPath(typed)) return _pathAction(typed);
+ if (!typed.contains('github.com/') &&
+ !RegExp(r'^git@[^:/\s]+:').hasMatch(typed)) {
+ return null;
+ }
+ final repository = GitHubRepository.parse(typed);
+ if (repository == null) {
+ return const NewHarnessOption(
+ id: pasteInvalidId,
+ synthetic: true,
+ title: 'Not a repository link',
+ detail: 'Use github.com/owner/repo',
+ enabled: false,
+ why: 'Use a link to a repository, like github.com/owner/repo.',
+ );
+ }
+ return _cloneRow(repository);
+ }
+
+ /// Open for a path that names a folder, else Browse, which goes on in the
+ /// Open Folder prompt with what was typed.
+ NewHarnessOption _pathAction(String typed) {
+ final full = _expand(typed);
+ final paths = _pathsFor(_machineId, full);
+ final trailing =
+ full.endsWith('/') ||
+ paths.style == p.Style.windows && full.endsWith('\\');
+ final parent = !paths.isAbsolute(full)
+ ? null
+ : trailing
+ ? paths.normalize(full)
+ : paths.dirname(full);
+ final names = parent == null ? null : _listings[parent];
+ if (parent != null && names == null) _requestListing(parent);
+ if (!trailing && names != null && names.contains(paths.basename(full))) {
+ return NewHarnessOption(
+ id: pasteOpenId,
+ synthetic: true,
+ title: 'Open ${tildePath(full)}',
+ detail: 'Folder on $machineLabel',
+ project: NewHarnessProject.folder(full, exact: true),
+ machineId: _machineId,
+ );
+ }
+ final shown = parent == null ? typed : tildePath(parent);
+ return NewHarnessOption(
+ id: pasteBrowseId,
+ synthetic: true,
+ title:
+ 'Browse ${shown.endsWith(paths.separator) ? shown : '$shown${paths.separator}'}',
+ detail: 'Choose a folder on $machineLabel',
+ );
+ }
+
+ /// Reads this computer's `~/.ssh/config` for a pasted alias. A test gives
+ /// its own, so no suite reads the developer's.
+ @visibleForTesting
+ SshHosts sshHosts = SshHosts();
+
+ /// What each pasted alias stands for on this computer, '' when ssh could not
+ /// say; absent while it is being read.
+ final _aliasHosts = <String, String>{};
+
+ Future<void> _resolveAlias(String alias) async {
+ final host = await sshHosts.resolveHost(alias);
+ if (_disposed) return;
+ _aliasHosts[alias] = host ?? '';
+ if (field == NewHarnessField.projectMenu ||
+ field == NewHarnessField.projectRepository) {
+ _refresh();
+ }
+ }
+
+ /// Cloning [repository] where the harness will run, with the account it
+ /// goes through: an SSH alias, or the other computer's own GitHub access.
+ /// Another computer's aliases are its daemon's to check, at launch.
+ NewHarnessOption _cloneRow(GitHubRepository repository) {
+ if (isTerminal) {
+ return NewHarnessOption(
+ id: pasteInvalidId,
+ synthetic: true,
+ title: "A terminal can't clone",
+ detail: 'Choose an agent to clone ${repository.slug}',
+ enabled: false,
+ why: 'Choose an agent to clone ${repository.slug}.',
+ );
+ }
+ final alias = repository.alias;
+ final local = _machine?.isLocalMachine == true;
+ if (local && alias != null) {
+ final host = _aliasHosts[alias];
+ if (host == null) {
+ // Offered as GitHub until ssh says otherwise: no flicker for the
+ // usual alias, and a launch checks again before it clones.
+ _aliasHosts[alias] = 'github.com';
+ unawaited(_resolveAlias(alias));
+ } else if (!isGitHubHost(host)) {
+ return NewHarnessOption(
+ id: pasteInvalidId,
synthetic: true,
- title: 'Clone ${repository.name}',
- detail: location('~/harnesses/${repository.name}'),
- project: NewHarnessProject.clone(repository),
- machineId: _machineId,
- ),
- ];
+ title: "$alias isn't a GitHub host",
+ detail: 'Only GitHub repositories can be cloned here',
+ enabled: false,
+ why: '$alias does not lead to github.com on this computer.',
+ );
+ }
+ }
+ return NewHarnessOption(
+ id: cloneId,
+ synthetic: true,
+ title: 'Clone ${repository.slug}',
+ detail: [
+ if (alias != null) 'over SSH as $alias',
+ local
+ ? 'into ${location('~/harnesses/${repository.name}')}'
+ : 'on $machineLabel · uses that computer’s GitHub access',
+ ].join(' · '),
+ project: NewHarnessProject.clone(repository),
+ machineId: _machineId,
+ );
}
/// The most folders one listing offers. `node_modules` has five thousand; a
@@ -3899,6 +4068,57 @@ class NewHarnessController extends ChangeNotifier {
});
}
+ static const _startingLine = 'Starting harness…';
+
+ /// A repository whose checkout is already there is used, not cloned, and the
+ /// line said Cloning for that moment anyway. Only the preparation decides,
+ /// and on another computer it says nothing until it is done, so look at the
+ /// same place first and leave the creation itself waiting on nothing.
+ Future<void> _sayWhenCloning(
+ GitHubRepository repository,
+ AgentCreationAttempt attempt,
+ ) async {
+ final free = await _cloneDestinationIsFree(repository);
+ if (!free ||
+ _disposed ||
+ !busy ||
+ !identical(attempt, _attempt) ||
+ status != _startingLine) {
+ return;
+ }
+ status = 'Cloning ${repository.slug}…';
+ notifyListeners();
+ }
+
+ /// Whether nothing is at `~/harnesses/<name>` where the harness will run.
+ /// Saying nothing about a clone is less wrong than announcing one that is not
+ /// happening, so false also covers a computer that cannot say.
+ Future<bool> _cloneDestinationIsFree(GitHubRepository repository) async {
+ final id = _machineId;
+ final home = await _ensureHome(id);
+ if (home == null) return false;
+ final root = _pathsFor(id, home).join(home, 'harnesses');
+ if (app.stateOf(id)?.isLocalMachine == true) {
+ final kind = await FileSystemEntity.type(
+ p.join(root, repository.name),
+ followLinks: false,
+ );
+ return kind == FileSystemEntityType.notFound;
+ }
+ // fs_list_dir (cli fsBrowse.ts) leaves hidden folders out: `.github` would
+ // look free whether it is there or not.
+ if (repository.name.startsWith('.')) return false;
+ final answer = await app.listRemoteFolder(id, root);
+ // The first clone on that computer: ~/harnesses is made for it.
+ if (answer['error'] == 'NOT_FOUND') return true;
+ final entries = answer['entries'];
+ if (answer['error'] != null || entries is! List) return false;
+ final listed = entries.any(
+ (entry) => entry is Map && entry['name'] == repository.name,
+ );
+ return !listed && answer['truncated'] != true;
+ }
+
/// Ask for [folder]'s listing. A local folder is read at once, off this
/// isolate; another machine's is asked for only once the typing pauses — each
/// keystroke through `~/code/au` would otherwise be a round trip whose answer
@@ -3977,7 +4197,8 @@ class NewHarnessController extends ChangeNotifier {
}
if (current &&
(field == NewHarnessField.project ||
- field == NewHarnessField.projectName)) {
+ field == NewHarnessField.projectName ||
+ field == NewHarnessField.projectMenu)) {
_refresh();
}
}
@@ -4306,9 +4527,15 @@ class NewHarnessController extends ChangeNotifier {
busy = true;
if (!(quiet && recheck)) {
error = null;
- status = recheck ? 'Checking on the harness…' : 'Starting harness…';
+ status = recheck ? 'Checking on the harness…' : _startingLine;
notifyListeners();
}
+ if (!recheck && !asGuest) {
+ // What is sent, not what is shown: a terminal takes no project.
+ if (projectFolderRequest?.repository case final repository?) {
+ unawaited(_sayWhenCloning(repository, attempt));
+ }
+ }
if (model != null && !recheck) {
await refreshModels();
if (_disposed) return NewHarnessOutcome.failed;
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index f0d5548fb..b8106d38d 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -3002,7 +3002,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
return 'Open Folder…';
}
final folder = option.project?.folder;
- if (box.field == NewHarnessField.projectMenu && folder != null) {
+ if (box.field == NewHarnessField.projectMenu &&
+ folder != null &&
+ option.id != NewHarnessController.pasteOpenId) {
return folder
.split(RegExp(r'[/\\]'))
.where((part) => part.isNotEmpty)
@@ -3067,12 +3069,12 @@ class NewHarnessFormState extends State<NewHarnessForm> {
Widget _desktopOption(NewHarnessOption option) {
final title = _desktopOptionTitle(option);
final highlighted = identical(option, box.selected);
- final ink = highlighted
- ? DesktopChrome.onSelection
- : DesktopChrome.foreground;
- final muted = highlighted
- ? DesktopChrome.selectionDetail
- : DesktopChrome.muted;
+ // A refused paste is the answer to what was typed, not a choice: its two
+ // lines say why, and it keeps a quiet fill instead of the selection's.
+ final refused = option.id == NewHarnessController.pasteInvalidId;
+ final active = highlighted && !refused;
+ final ink = active ? DesktopChrome.onSelection : DesktopChrome.foreground;
+ final muted = active ? DesktopChrome.selectionDetail : DesktopChrome.muted;
final titleStyle = DesktopChrome.text(
size: _desktopTitleSize,
color: option.enabled ? ink : muted,
@@ -3086,7 +3088,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
: box.app.stateOf(option.id)?.isOffline == true
? 'Offline'
: null
- : !option.enabled
+ : !option.enabled && !refused
? option.why
: null;
return Semantics(
@@ -3103,8 +3105,10 @@ class NewHarnessFormState extends State<NewHarnessForm> {
if (!option.enabled) option.why else ?note,
].join('\n'),
child: Material(
- color: highlighted
+ color: active
? DesktopChrome.activeSelection
+ : highlighted
+ ? DesktopChrome.foreground.withValues(alpha: .06)
: Colors.transparent,
borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
child: InkWell(
diff --git a/desktop/test/desktop_compact_launch_test.dart b/desktop/test/desktop_compact_launch_test.dart
index ab061ac63..dffdda215 100644
--- a/desktop/test/desktop_compact_launch_test.dart
+++ b/desktop/test/desktop_compact_launch_test.dart
@@ -71,7 +71,8 @@ class _CompactApp extends AppNotifier {
bool refresh = false,
}) async => {
'isGit': true,
- 'branch': missingMain ? 'feature' : 'main',
+ // Detached: a current branch would itself be where new work starts.
+ 'branch': missingMain ? null : 'main',
'branches': [
if (!missingMain) {'ref': 'refs/heads/main', 'name': 'main'},
{'ref': 'refs/heads/feature', 'name': 'feature'},
diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dart
index 72e20face..920228c16 100644
--- a/desktop/test/desktop_composer_layout_test.dart
+++ b/desktop/test/desktop_composer_layout_test.dart
@@ -13,6 +13,7 @@ import 'package:harness/core/config.dart';
import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
+import 'package:harness/core/ssh_hosts.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/shortcuts/keymap_host.dart';
@@ -64,6 +65,7 @@ class _ReviewApp extends AppNotifier {
final bool git;
final List<String> branchNames;
final launches = <Map<String, Object?>>[];
+ final folders = <String, List<String>>{};
@override
Future<void> probeEngines(String machineId, {bool force = false}) async {}
@@ -111,7 +113,13 @@ class _ReviewApp extends AppNotifier {
Future<Map<String, dynamic>> listRemoteFolder(
String machineId,
String? path,
- ) async => {'path': path ?? '/work', 'entries': []};
+ ) async => {
+ 'path': path ?? '/work',
+ 'entries': [
+ for (final name in folders[path] ?? const <String>[])
+ {'name': name, 'isDir': true},
+ ],
+ };
@override
Future<String?> createAgent(
@@ -648,7 +656,10 @@ void main() {
await tester.enterText(_query, 'autonomous-ai/openharness');
await tester.pumpAndSettle();
- expect(find.text('Clone openharness').hitTestable(), findsOneWidget);
+ expect(
+ find.text('Clone autonomous-ai/openharness').hitTestable(),
+ findsOneWidget,
+ );
await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(fixture.box.field, NewHarnessField.projectMenu);
@@ -657,6 +668,94 @@ void main() {
expect(tester.takeException(), isNull);
});
}
+ testWidgets(
+ 'Esc leaves a pasted link without choosing it ${brightness.name}',
+ (tester) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ onBrowse: (_) {},
+ );
+ final before = fixture.box.project;
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, 'https://github.com/org/repo');
+ await tester.pumpAndSettle();
+ expect(find.text('Clone org/repo').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_query.hitTestable(), findsNothing);
+ expect(fixture.box.project, before);
+ expect(fixture.app.launches, isEmpty);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ testWidgets('A pasted folder path says Open ${brightness.name}', (
+ tester,
+ ) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ onBrowse: (_) {},
+ );
+ // Another computer's folders: a local listing reads the real disk.
+ fixture.app.machineStates['review']!.localOnly = false;
+ fixture.app.folders['/work'] = ['api'];
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, '/work/api');
+ await tester.pump(const Duration(milliseconds: 150));
+ await tester.pumpAndSettle();
+ expect(find.text('Open /work/api').hitTestable(), findsOneWidget);
+ expect(find.text('Folder on office').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+ for (final (typed, line, detail, why) in const [
+ (
+ 'https://github.com/autonomous-ai',
+ 'Not a repository link',
+ 'Use github.com/owner/repo',
+ 'Use a link to a repository, like github.com/owner/repo.',
+ ),
+ (
+ 'git@gitlab-work:org/repo.git',
+ "gitlab-work isn't a GitHub host",
+ 'Only GitHub repositories can be cloned here',
+ 'gitlab-work does not lead to github.com on this computer.',
+ ),
+ ]) {
+ testWidgets('A refused paste is two lines and does not read as a choice: '
+ '$line ${brightness.name}', (tester) async {
+ final fixture = await _mount(
+ tester,
+ brightness: brightness,
+ onBrowse: (_) {},
+ );
+ fixture.box.sshHosts = const _FixedSshHosts('gitlab.com');
+ await tester.tap(_field('project'));
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, typed);
+ await tester.pumpAndSettle();
+ await tester.enterText(_query, typed);
+ await tester.pumpAndSettle();
+ final row = find.byKey(
+ const ValueKey(
+ 'new-harness-option-${NewHarnessController.pasteInvalidId}',
+ ),
+ );
+ expect(find.text(line).hitTestable(), findsOneWidget);
+ expect(find.text(detail).hitTestable(), findsOneWidget);
+ expect(find.text(why), findsNothing);
+ final fill = tester
+ .widget<Material>(
+ find.descendant(of: row, matching: find.byType(Material)).first,
+ )
+ .color;
+ expect(fill, isNot(DesktopChrome.activeSelection));
+ expect(fixture.box.selected?.enabled, isFalse);
+ expect(tester.takeException(), isNull);
+ });
+ }
testWidgets(
'Repo search and header computer menus fit ${brightness.name}',
(tester) async {
@@ -1667,3 +1766,14 @@ void main() {
}
}
}
+
+class _FixedSshHosts implements SshHosts {
+ const _FixedSshHosts(this.host);
+ final String host;
+
+ @override
+ Future<String?> resolveHost(String alias) async => host;
+
+ @override
+ Future<List<String>> githubAliases() async => const [];
+}
diff --git a/desktop/test/github_repository_vectors_test.dart b/desktop/test/github_repository_vectors_test.dart
new file mode 100644
index 000000000..f3c576265
--- /dev/null
+++ b/desktop/test/github_repository_vectors_test.dart
@@ -0,0 +1,56 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/github_repository.dart';
+
+/// The CLI's vectors (cli/src/lib/__fixtures__/github-repository-vectors.json):
+/// the daemon clones another computer's harness and this app clones this
+/// computer's, so both must read a pasted address the same way.
+void main() {
+ final vectors = jsonDecode(
+ File('../cli/src/lib/__fixtures__/github-repository-vectors.json')
+ .readAsStringSync(),
+ ) as Map<String, dynamic>;
+
+ test('parses every vector as the daemon does', () {
+ for (final vector in vectors['parse'] as List) {
+ final input = vector['input'] as String;
+ final expected = vector['expect'] as Map<String, dynamic>?;
+ final parsed = GitHubRepository.parse(input);
+ if (expected == null) {
+ expect(parsed, isNull, reason: input);
+ continue;
+ }
+ expect(parsed, isNotNull, reason: input);
+ expect(parsed!.url, expected['url'], reason: input);
+ expect(parsed.owner, expected['owner'], reason: input);
+ expect(parsed.name, expected['name'], reason: input);
+ expect(parsed.transport.name, expected['transport'], reason: input);
+ expect(parsed.alias, expected['alias'], reason: input);
+ }
+ });
+
+ test('names one repository however its address is spelled', () async {
+ for (final vector in vectors['identity'] as List) {
+ final hosts = (vector['hosts'] as Map).cast<String, String>();
+ final address = vector['address'] as String;
+ expect(
+ await resolvedRepositoryIdentity(address, (host) async => hosts[host]),
+ vector['expect'],
+ reason: address,
+ );
+ }
+ });
+
+ test('tries the addresses in the daemon\'s order', () {
+ for (final vector in vectors['attempts'] as List) {
+ final repository = GitHubRepository.parse(vector['input'] as String)!;
+ expect(
+ cloneAttempts(repository, (vector['aliases'] as List).cast<String>()),
+ vector['expect'],
+ reason: vector['input'] as String,
+ );
+ }
+ });
+}
diff --git a/desktop/test/launch_preferences_test.dart b/desktop/test/launch_preferences_test.dart
index 194008be8..8c760f35a 100644
--- a/desktop/test/launch_preferences_test.dart
+++ b/desktop/test/launch_preferences_test.dart
@@ -259,7 +259,7 @@ void main() {
},
);
- test('desktop does not substitute a remote or different branch for missing local main', () async {
+ test('desktop does not substitute a remote or different branch for a default that is not local', () async {
final fixture = _Fixture();
await fixture.app.agentPreference.remember('codex', worktree: false);
final connection = fixture.connections.putIfAbsent(
@@ -281,7 +281,7 @@ void main() {
await _settle();
expect(box.branchRef, isNull);
expect(box.requiredChoice?.field, NewHarnessField.branch);
- expect(box.branchLabel, 'main · unavailable');
+ expect(box.branchLabel, 'default · unavailable');
box.toggleWorktree();
expect(box.branchRef, 'refs/remotes/origin/main');
});
diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dart
index a0318cbf3..6a1a145b2 100644
--- a/desktop/test/new_harness_box_test.dart
+++ b/desktop/test/new_harness_box_test.dart
@@ -274,7 +274,7 @@ void main() {
box.setQuery('acme/rocket');
// Repository input is dedicated to cloning, never creating a blank folder.
expect(box.options.any((row) => row.id == 'project:new'), isFalse);
- expect(box.options.first.title, 'Clone rocket');
+ expect(box.options.first.title, 'Clone acme/rocket');
box.accept(box.options.first);
expect(box.project.repository?.name, 'rocket');
expect(box.projectLabel, '~/harnesses/rocket');
diff --git a/desktop/test/new_harness_controller_edges_test.dart b/desktop/test/new_harness_controller_edges_test.dart
index 9b5ecaf5c..b8c378ee2 100644
--- a/desktop/test/new_harness_controller_edges_test.dart
+++ b/desktop/test/new_harness_controller_edges_test.dart
@@ -283,7 +283,7 @@ void main() {
);
test(
- 'main stays unavailable and a delayed Git read revalidates before creating',
+ 'no default stays unavailable and a delayed Git read revalidates before creating',
() async {
final fixture = _Fixture();
final pending = Completer<Map<String, dynamic>>();
@@ -293,14 +293,13 @@ void main() {
expect(box.busy, isTrue);
pending.complete({
'isGit': true,
- 'branch': 'trunk',
'branches': [
{'ref': 'refs/heads/trunk', 'name': 'trunk'},
],
'refreshed': true,
});
expect(await creating, NewHarnessOutcome.failed);
- expect(box.branchLabel, 'main · unavailable');
+ expect(box.branchLabel, 'default · unavailable');
expect(box.worktree, isTrue);
expect(box.field, NewHarnessField.branch);
expect(box.error, contains('Choose a branch'));
diff --git a/desktop/test/new_harness_default_branch_test.dart b/desktop/test/new_harness_default_branch_test.dart
new file mode 100644
index 000000000..930cfc26d
--- /dev/null
+++ b/desktop/test/new_harness_default_branch_test.dart
@@ -0,0 +1,146 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/git_worktree.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:path/path.dart' as p;
+
+import 'swarm_state_test.dart' show createApp;
+
+/// A fresh form starts from the branch the project itself calls its default:
+/// real Git repositories, read by the real reader, shown to the real form.
+/// octocat/Hello-World is on master: the form refused it until a branch was
+/// chosen by hand, and a repository on develop quietly started from main.
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ late Directory root;
+ late AppNotifier app;
+
+ Future<void> git(String at, List<String> arguments) async {
+ final result = await Process.run('git', [
+ '-c',
+ 'user.name=t',
+ '-c',
+ '-c',
+ 'commit.gpgsign=false',
+ '-C',
+ at,
+ ...arguments,
+ ]);
+ if (result.exitCode != 0) {
+ throw StateError('git $arguments: ${result.stderr}');
+ }
+ }
+
+ Future<String> repository(
+ String head, {
+ List<String> others = const [],
+ }) async {
+ final path = p.join(root.path, 'origin');
+ await Directory(path).create();
+ await git(path, ['init', '-b', head]);
+ await git(path, ['commit', '--allow-empty', '-m', 'first']);
+ for (final other in others) {
+ await git(path, ['branch', other]);
+ }
+ return path;
+ }
+
+ Future<String> cloneOf(String origin) async {
+ final clone = p.join(root.path, 'clone');
+ await git(root.path, ['clone', '--', origin, clone]);
+ return clone;
+ }
+
+ Future<NewHarnessController> form(String folder) async {
+ app.gitProjectReaderForTest = (_, path) => readLocalGitProject(path);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: folder,
+ )..useDesktopChoices(true);
+ addTearDown(box.dispose);
+ for (var i = 0; i < 400 && (box.checkingGit || !box.isGitProject); i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 10));
+ }
+ expect(box.isGitProject, isTrue, reason: 'the project was never read');
+ return box;
+ }
+
+ setUp(() async {
+ root = await Directory.systemTemp.createTemp('default-branch-');
+ root = Directory(await root.resolveSymbolicLinks());
+ app = createApp(connected: true);
+ addTearDown(app.dispose);
+ });
+ tearDown(() => root.delete(recursive: true));
+
+ void startsFrom(NewHarnessController box, String ref, String label) {
+ expect(box.branchRef, ref);
+ expect(box.branchLabel, label);
+ expect(box.requiredChoice, isNull);
+ }
+
+ test('a clone on main starts from main', () async {
+ final box = await form(await cloneOf(await repository('main')));
+ startsFrom(box, 'refs/heads/main', 'main');
+ });
+
+ test('a clone on master starts from master', () async {
+ final box = await form(await cloneOf(await repository('master')));
+ startsFrom(box, 'refs/heads/master', 'master');
+ });
+
+ test('so it does with Worktree off', () async {
+ final box = await form(await cloneOf(await repository('master')));
+ box.toggleWorktree();
+ expect(box.worktree, isFalse);
+ startsFrom(box, 'refs/heads/master', 'master');
+ });
+
+ test('a clone on an unusual default starts from it', () async {
+ final box = await form(await cloneOf(await repository('trunk')));
+ startsFrom(box, 'refs/heads/trunk', 'trunk');
+ });
+
+ test('the default wins over a main beside it', () async {
+ final clone = await cloneOf(await repository('develop', others: ['main']));
+ final box = await form(clone);
+ startsFrom(box, 'refs/heads/develop', 'develop');
+ });
+
+ test('a clone whose origin/HEAD is gone starts where it is', () async {
+ final clone = await cloneOf(await repository('master'));
+ await git(clone, ['remote', 'set-head', 'origin', '--delete']);
+ final box = await form(clone);
+ startsFrom(box, 'refs/heads/master', 'master');
+ });
+
+ test('a repository with no remote starts where it is', () async {
+ final box = await form(await repository('master'));
+ startsFrom(box, 'refs/heads/master', 'master');
+ });
+
+ test('main still leads when nothing names a default', () async {
+ final path = await repository('feature', others: ['main']);
+ final box = await form(path);
+ startsFrom(box, 'refs/heads/main', 'main');
+ });
+
+ test('a detached repository with no default still asks', () async {
+ final path = await repository('feature');
+ await git(path, ['checkout', '--detach']);
+ final box = await form(path);
+ expect(box.branchRef, isNull);
+ expect(box.branchLabel, 'default · unavailable');
+ expect(
+ box.requiredChoice?.message,
+ 'This project has no default branch. Choose a branch.',
+ );
+ expect(box.requiredChoice?.field, NewHarnessField.branch);
+ });
+}
diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dart
index 0c098ebf1..91d0d8eb1 100644
--- a/desktop/test/new_harness_git_test.dart
+++ b/desktop/test/new_harness_git_test.dart
@@ -123,13 +123,11 @@ void main() {
Future<void> settle() => Future<void>.delayed(Duration.zero);
test(
- 'missing main requires choosing a branch without changing Worktree',
+ 'no default, no main and no current branch asks without changing Worktree',
() async {
final connection = _Connection()
..answers['/repo'] = {
'isGit': true,
- 'branch': 'master',
- 'defaultRef': 'refs/remotes/origin/master',
'branches': [
{'ref': 'refs/heads/master', 'name': 'master'},
{'ref': 'refs/heads/feature', 'name': 'feature'},
diff --git a/desktop/test/new_harness_project_paste_test.dart b/desktop/test/new_harness_project_paste_test.dart
new file mode 100644
index 000000000..b24a34e4d
--- /dev/null
+++ b/desktop/test/new_harness_project_paste_test.dart
@@ -0,0 +1,477 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/ssh_hosts.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// Pasting a folder path or a GitHub link into the project search
+/// (docs/plans/2026-10-30-new-harness-paste-path-or-repository.md): one action
+/// row, above the doors and already selected, so Enter does it.
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creates = <Map<String, dynamic>>[];
+ Completer<Map<String, dynamic>>? createReply;
+
+ /// What this computer answers for `~/harnesses`, when it is asked.
+ Map<String, dynamic> harnesses = const {'error': 'NOT_FOUND'};
+ Completer<void>? harnessesHeld;
+
+ @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 'fs_list_dir':
+ final path = payload['path'] as String? ?? '/home/test';
+ if (path == '/home/test/harnesses') {
+ await harnessesHeld?.future;
+ // A refusal arrives as WsConn throws it, never as a value.
+ if (harnesses['error'] case final String code) {
+ throw WsRequestFailure(
+ responseType: 'fs_list_dir_result',
+ code: code,
+ );
+ }
+ return harnesses;
+ }
+ return {
+ 'path': path,
+ 'entries': [
+ if (path == '/work')
+ for (final name in ['api', 'repo']) {'name': name, 'isDir': true},
+ ],
+ };
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ return (createReply ??= Completer()).future;
+ }
+ return {};
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ late _Connection connection;
+ late AppNotifier app;
+
+ NewHarnessController search(
+ String typed, {
+ Map<String, String> hosts = const {},
+ }) {
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/repo',
+ )..useDesktopChoices(true);
+ // Never this developer's own ~/.ssh/config.
+ box.sshHosts = _Hosts(hosts);
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ box.setQuery(typed);
+ return box;
+ }
+
+ setUp(() {
+ connection = _Connection();
+ app = createApp(connectionForTest: (_) => connection, connected: true);
+ app.machineStates['m']!.agents = [];
+ addTearDown(app.dispose);
+ });
+
+ Future<void> listed() => Future<void>.delayed(
+ // A remote listing is debounced before it is asked for.
+ const Duration(milliseconds: 150),
+ );
+
+ test('a project name searches as it always did', () {
+ final box = search('repo');
+ expect(
+ box.options.where((row) => row.id.startsWith('project:paste')),
+ isEmpty,
+ );
+ });
+
+ test('a path to a folder opens it with one Enter', () async {
+ final box = search('/work/api');
+ await listed();
+ expect(box.selected!.title, 'Open /work/api');
+ box.accept();
+ expect(box.project.folder, '/work/api');
+ });
+
+ test('a path that names no folder yet goes on in the folder browser, '
+ 'keeping what was typed', () async {
+ final box = search('/work/ap');
+ await listed();
+ expect(box.selected!.title, 'Browse /work/');
+ box.accept();
+ expect(box.field, NewHarnessField.project);
+ expect(box.query, '/work/ap');
+ });
+
+ test('a half-typed path a recent project matches keeps that project '
+ 'highlighted', () async {
+ await app.projectHistory.select('m', '/work/team/payments-processing');
+ final box = search('/work/team/payments');
+ await listed();
+ expect(box.selected!.project!.folder, '/work/team/payments-processing');
+ expect(
+ box.options.map((row) => row.id),
+ isNot(contains(NewHarnessController.pasteBrowseId)),
+ );
+ });
+
+ test('a browser link clones with one Enter', () {
+ final box = search('https://github.com/autonomous-ai/openharness');
+ expect(box.selected!.title, 'Clone autonomous-ai/openharness');
+ expect(box.selected!.detail, contains('GitHub access'));
+ box.accept();
+ expect(box.project.repository!.slug, 'autonomous-ai/openharness');
+ });
+
+ test('an alias stays on this computer: others get the HTTPS link', () {
+ final box = search('git@gh-work:org/repo.git');
+ box.accept();
+ expect(box.project.repository!.url, 'git@gh-work:org/repo.git');
+ expect(box.cloudRepository, 'https://github.com/org/repo.git');
+ expect(box.leadRepositoryUrl, 'https://github.com/org/repo.git');
+ });
+
+ test('an SSH alias says which account clones', () {
+ final box = search('git@gh-work:org/repo.git');
+ expect(box.selected!.title, 'Clone org/repo');
+ expect(box.selected!.detail, contains('over SSH as gh-work'));
+ });
+
+ test('on this computer, an alias that is not GitHub is refused as it is '
+ 'typed', () async {
+ app.machineStates['m']!.localOnly = true;
+ final box = search(
+ 'git@gitlab-work:org/repo.git',
+ hosts: {'gitlab-work': 'gitlab.com', 'gh-work': 'github.com'},
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(box.selected!.title, "gitlab-work isn't a GitHub host");
+ expect(box.selected!.enabled, isFalse);
+ box.setQuery('git@gh-work:org/repo.git');
+ await Future<void>.delayed(Duration.zero);
+ expect(box.selected!.title, 'Clone org/repo');
+ expect(box.selected!.enabled, isTrue);
+ });
+
+ test('a path ending in a slash browses that folder', () async {
+ final box = search('/srv/');
+ await listed();
+ expect(box.selected!.title, 'Browse /srv/');
+ });
+
+ test('the GitHub prompt refuses the same alias', () async {
+ app.machineStates['m']!.localOnly = true;
+ final box = search('', hosts: {'gitlab-work': 'gitlab.com'});
+ box.focusField(NewHarnessField.projectRepository);
+ box.setQuery('git@gitlab-work:org/repo.git');
+ await Future<void>.delayed(Duration.zero);
+ expect(box.options.single.title, "gitlab-work isn't a GitHub host");
+ });
+
+ test('an alias read after the form closed changes nothing', () async {
+ app.machineStates['m']!.localOnly = true;
+ final answer = Completer<String?>();
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/repo',
+ )..useDesktopChoices(true);
+ box.sshHosts = _SlowHosts(answer.future);
+ box.focusField(NewHarnessField.projectMenu);
+ box.setQuery('git@gh-work:org/repo.git');
+ box.dispose();
+ answer.complete('gitlab.com');
+ await Future<void>.delayed(Duration.zero);
+ });
+
+ test('a GitHub link that is no repository says so', () {
+ final box = search('https://github.com/autonomous-ai');
+ expect(box.selected!.title, 'Not a repository link');
+ expect(box.selected!.enabled, isFalse);
+ });
+
+ test('owner/repo without a host is a search, never a clone', () {
+ final box = search('team/api');
+ expect(
+ box.options.map((row) => row.title),
+ isNot(contains(startsWith('Clone'))),
+ );
+ });
+
+ test('another computer refused everywhere says so in one line', () async {
+ final box = search('https://github.com/org/secret');
+ box.accept();
+ final outcome = box.create();
+ await Future<void>.delayed(Duration.zero);
+ connection.createReply!.complete({
+ 'creationId': connection.creates.single['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'CLONE_FAILED',
+ 'detail': 'Could not access this repository.',
+ 'access': 'denied',
+ },
+ });
+ expect(await outcome, NewHarnessOutcome.failed);
+ expect(box.error, 'No access to org/secret on Test host.');
+ });
+
+ test('a clone through an alias is told once', () async {
+ final told = <String>[];
+ app.agentChangeNotice = told.add;
+ final box = search('https://github.com/org/repo');
+ box.accept();
+ final outcome = box.create();
+ await Future<void>.delayed(Duration.zero);
+ connection.createReply!.complete({
+ 'creationId': connection.creates.single['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'a1', 'name': 'Repo', 'engine': 'codex'},
+ 'clonedVia': {'alias': 'gh-work'},
+ });
+ expect(await outcome, NewHarnessOutcome.created);
+ expect(told, ['Cloned via gh-work']);
+ });
+
+ test('a clone says so while it runs', () async {
+ final box = search('https://github.com/org/repo');
+ box.accept();
+ unawaited(box.create());
+ await Future<void>.delayed(Duration.zero);
+ expect(box.status, 'Cloning org/repo…');
+ });
+
+ group('a terminal opens in a folder and clones nothing', () {
+ NewHarnessController terminal(String typed) {
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'terminal',
+ folder: '/work/repo',
+ )..useDesktopChoices(true);
+ box.sshHosts = _Hosts(const {});
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ box.setQuery(typed);
+ return box;
+ }
+
+ test('a pasted link is refused, and says why', () {
+ final box = terminal('https://github.com/org/repo');
+ final row = box.options.first;
+ expect(row.id, NewHarnessController.pasteInvalidId);
+ expect(row.enabled, isFalse);
+ expect(row.title, "A terminal can't clone");
+ expect(row.detail, 'Choose an agent to clone org/repo');
+ box.accept();
+ expect(box.error, 'Choose an agent to clone org/repo.');
+ expect(box.requiredChoice, isNull);
+ });
+
+ test('a pasted path still opens', () async {
+ final box = terminal('/work');
+ await listed();
+ expect(box.options.first.id, isNot(NewHarnessController.pasteInvalidId));
+ expect(box.options.first.enabled, isTrue);
+ });
+
+ test('changing to Terminal after choosing a clone asks again', () async {
+ final box = search('https://github.com/org/repo');
+ box.accept();
+ expect(box.requiredChoice, isNull);
+ box.focusField(NewHarnessField.harness);
+ box.setQuery('Terminal');
+ box.accept();
+ expect(box.isTerminal, isTrue);
+ expect(box.requiredChoice?.field, NewHarnessField.projectMenu);
+ expect(
+ box.requiredChoice?.message,
+ "A terminal can't clone. Choose a folder or an agent.",
+ );
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(connection.creates, isEmpty);
+ });
+ });
+
+ group('the line only says Cloning when a clone will run', () {
+ Future<List<String?>> linesWhileCreating(NewHarnessController box) async {
+ final lines = <String?>[];
+ box.addListener(() => lines.add(box.status));
+ box.accept();
+ unawaited(box.create());
+ await Future<void>.delayed(Duration.zero);
+ return lines;
+ }
+
+ test(
+ 'a checkout already there is used, so it never says Cloning',
+ () async {
+ connection.harnesses = {
+ 'path': '/home/test/harnesses',
+ 'entries': [
+ {'name': 'repo', 'isDir': true},
+ ],
+ };
+ final box = search('https://github.com/org/repo');
+ final lines = await linesWhileCreating(box);
+ expect(box.status, 'Starting harness…');
+ expect(lines, isNot(contains('Cloning org/repo…')));
+ },
+ );
+
+ test('another folder in ~/harnesses does not stop it saying so', () async {
+ connection.harnesses = {
+ 'path': '/home/test/harnesses',
+ 'entries': [
+ {'name': 'other', 'isDir': true},
+ ],
+ };
+ final box = search('https://github.com/org/repo');
+ await linesWhileCreating(box);
+ expect(box.status, 'Cloning org/repo…');
+ });
+
+ test('a first clone on a computer with no ~/harnesses says so', () async {
+ final box = search('https://github.com/org/repo');
+ await linesWhileCreating(box);
+ expect(box.status, 'Cloning org/repo…');
+ });
+
+ test('a computer that cannot say is not told a clone is running', () async {
+ connection.harnesses = {'error': 'UNAVAILABLE'};
+ final box = search('https://github.com/org/repo');
+ final lines = await linesWhileCreating(box);
+ expect(box.status, 'Starting harness…');
+ expect(lines, isNot(contains('Cloning org/repo…')));
+ });
+
+ test(
+ 'a listing cut short that does not show the name cannot say',
+ () async {
+ connection.harnesses = {
+ 'path': '/home/test/harnesses',
+ 'entries': const <Object>[],
+ 'truncated': true,
+ };
+ final box = search('https://github.com/org/repo');
+ await linesWhileCreating(box);
+ expect(box.status, 'Starting harness…');
+ },
+ );
+
+ test('a hidden folder is never listed, so its name cannot say', () async {
+ connection.harnesses = {
+ 'path': '/home/test/harnesses',
+ 'entries': const <Object>[],
+ };
+ final box = search('https://github.com/org/.github');
+ await linesWhileCreating(box);
+ expect(box.status, 'Starting harness…');
+ });
+
+ test('this computer looks at its own folder', () async {
+ final home = Directory.systemTemp.createTempSync('harness-clone-line');
+ addTearDown(() => home.deleteSync(recursive: true));
+ Directory('${home.path}/harnesses/repo').createSync(recursive: true);
+ final held = Completer<String>();
+ final local = createApp(
+ connectionForTest: (_) => connection,
+ connected: true,
+ // Never a real clone into this developer's own home.
+ prepareFolder: (_) => held.future,
+ );
+ addTearDown(local.dispose);
+ local.machineStates['m']!
+ ..agents = []
+ ..localOnly = true;
+ NewHarnessController boxFor(String link) {
+ final box = NewHarnessController(
+ local,
+ machineId: 'm',
+ engine: 'codex',
+ folder: home.path,
+ home: home.path,
+ )..useDesktopChoices(true);
+ box.sshHosts = _Hosts(const {});
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ box.setQuery(link);
+ box.accept();
+ unawaited(box.create());
+ return box;
+ }
+
+ final reused = boxFor('https://github.com/org/repo');
+ final cloned = boxFor('https://github.com/org/fresh');
+ await pumpEventQueue();
+ expect(reused.status, 'Starting harness…');
+ expect(cloned.status, 'Cloning org/fresh…');
+ });
+
+ test('an answer after the creation failed changes nothing', () async {
+ connection.harnessesHeld = Completer();
+ final box = search('https://github.com/org/repo');
+ box.accept();
+ final outcome = box.create();
+ await Future<void>.delayed(Duration.zero);
+ expect(box.status, 'Starting harness…');
+ connection.createReply!.complete({'error': 'INVALID_CWD'});
+ await outcome;
+ final settled = box.status;
+ connection.harnessesHeld!.complete();
+ await Future<void>.delayed(Duration.zero);
+ expect(box.status, settled);
+ });
+ });
+}
+
+class _Hosts implements SshHosts {
+ _Hosts(this.hosts);
+ final Map<String, String> hosts;
+
+ @override
+ Future<String?> resolveHost(String alias) async => hosts[alias];
+
+ @override
+ Future<List<String>> githubAliases() async => const [];
+}
+
+class _SlowHosts extends _Hosts {
+ _SlowHosts(this.answer) : super(const {});
+ final Future<String?> answer;
+
+ @override
+ Future<String?> resolveHost(String alias) => answer;
+}
diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dart
index f6657c2d5..26d306035 100644
--- a/desktop/test/new_harness_scenarios_test.dart
+++ b/desktop/test/new_harness_scenarios_test.dart
@@ -1373,7 +1373,6 @@ void main() {
expect(scenario.box.busy, isTrue);
git.complete({
'isGit': true,
- 'branch': 'trunk',
'branches': [
{'ref': 'refs/heads/trunk', 'name': 'trunk'},
],
diff --git a/desktop/test/project_folder_test.dart b/desktop/test/project_folder_test.dart
index 93c51bfab..9540f04cb 100644
--- a/desktop/test/project_folder_test.dart
+++ b/desktop/test/project_folder_test.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/core/repository_clone.dart';
+import 'package:harness/core/ssh_hosts.dart';
import 'package:path/path.dart' as p;
void main() {
@@ -150,4 +151,38 @@ void main() {
});
},
);
+
+ test('a clone through an alias says which, for the person', () async {
+ final root = await Directory.systemTemp.createTemp(
+ 'harness-alias-project-test-',
+ );
+ addTearDown(() => root.delete(recursive: true));
+ final source = p.join(root.path, 'source.git');
+ expect((await Process.run('git', ['init', '--bare', source])).exitCode, 0);
+ final via = <String>[];
+ await ProjectFolderRequest.remote(
+ GitHubRepository.parse('git@gh-work:owner/repo.git')!,
+ ).prepareLocal(
+ projectHome: p.join(root.path, 'projects'),
+ onClonedVia: via.add,
+ createClone: () => RepositoryClone(
+ sshHosts: _GitHubAlias(),
+ startProcess: (args, environment) => Process.start('git', [
+ 'clone',
+ '--',
+ source,
+ args.last,
+ ], environment: environment),
+ ),
+ );
+ expect(via, ['gh-work']);
+ });
+}
+
+class _GitHubAlias implements SshHosts {
+ @override
+ Future<String?> resolveHost(String alias) async => 'github.com';
+
+ @override
+ Future<List<String>> githubAliases() async => const [];
}
diff --git a/desktop/test/repository_clone_test.dart b/desktop/test/repository_clone_test.dart
index 3e0caf3c9..acedca132 100644
--- a/desktop/test/repository_clone_test.dart
+++ b/desktop/test/repository_clone_test.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/repository_clone.dart';
+import 'package:harness/core/ssh_hosts.dart';
import 'package:path/path.dart' as p;
void main() {
@@ -268,4 +269,214 @@ void main() {
},
skip: Platform.isWindows ? 'Uses the POSIX sleep fixture.' : false,
);
+
+ group('a private repository', () {
+ late String source;
+ late List<String> tried;
+ late Directory parent;
+
+ setUp(() async {
+ source = p.join(root.path, 'fixture.git');
+ expect(
+ (await Process.run('git', ['init', '--bare', source])).exitCode,
+ 0,
+ );
+ parent = await Directory(p.join(root.path, 'projects')).create();
+ tried = [];
+ });
+
+ /// Git as GitHub answers: [refused] addresses are refused access, a
+ /// [broken] one fails the way a dead network does, anything else clones
+ /// the local fixture.
+ RepositoryClone cloner({
+ Set<String> refused = const {},
+ Set<String> broken = const {},
+ Map<String, String> hosts = const {'gh-work': 'github.com'},
+ List<String> aliases = const ['gh-work'],
+ }) => RepositoryClone(
+ sshHosts: _FakeSshHosts(hosts, aliases),
+ startProcess: (arguments, environment) {
+ final url = arguments[2];
+ tried.add(url);
+ if (refused.contains(url) || broken.contains(url)) {
+ final message = refused.contains(url)
+ ? 'fatal: could not read Username for https://github.com'
+ : 'fatal: unable to access: Could not resolve host: github.com';
+ return Process.start('sh', ['-c', 'echo "$message" >&2; exit 128']);
+ }
+ return Process.start('git', [
+ 'clone',
+ '--',
+ source,
+ arguments.last,
+ ], environment: environment);
+ },
+ );
+
+ Future<String?> origin(String folder) async => (await Process.run('git', [
+ '-C',
+ folder,
+ 'remote',
+ 'get-url',
+ 'origin',
+ ])).stdout.toString().trim();
+
+ test('a refused HTTPS link is cloned over SSH instead', () async {
+ final clone = cloner(refused: {'https://github.com/owner/project.git'});
+ final folder = await clone.run(
+ GitHubRepository.parse('https://github.com/owner/project')!,
+ parent.path,
+ );
+ expect(tried, [
+ 'https://github.com/owner/project.git',
+ '[email protected]:owner/project.git',
+ ]);
+ expect(clone.clonedVia, isNull);
+ // The fixture's own path stands in for the address that worked.
+ expect(await origin(folder), source);
+ expect((await parent.list().toList()).map((e) => p.basename(e.path)), [
+ 'project',
+ ]);
+ });
+
+ test('a second GitHub account is reached through its alias', () async {
+ final clone = cloner(
+ refused: {
+ 'https://github.com/owner/project.git',
+ '[email protected]:owner/project.git',
+ },
+ );
+ await clone.run(GitHubRepository.parse('owner/project')!, parent.path);
+ expect(tried.last, 'git@gh-work:owner/project.git');
+ expect(clone.clonedVia, 'gh-work');
+ });
+
+ test('a network failure stops at once', () async {
+ final clone = cloner(broken: {'https://github.com/owner/project.git'});
+ await expectLater(
+ clone.run(GitHubRepository.parse('owner/project')!, parent.path),
+ throwsA(isNot(isA<RepositoryAccessDenied>())),
+ );
+ expect(tried, ['https://github.com/owner/project.git']);
+ expect(await parent.list().toList(), isEmpty);
+ });
+
+ test('refused everywhere says so in one line', () async {
+ final clone = cloner(
+ refused: {
+ 'https://github.com/owner/project.git',
+ '[email protected]:owner/project.git',
+ 'git@gh-work:owner/project.git',
+ },
+ );
+ await expectLater(
+ clone.run(GitHubRepository.parse('owner/project')!, parent.path),
+ throwsA(
+ isA<RepositoryAccessDenied>().having(
+ (e) => e.message,
+ 'message',
+ startsWith('No access to owner/project on this '),
+ ),
+ ),
+ );
+ expect(tried, hasLength(3));
+ expect(await parent.list().toList(), isEmpty);
+ });
+
+ test('a pasted alias that is not GitHub never starts Git', () async {
+ final clone = cloner(hosts: {'gitlab-work': 'gitlab.com'});
+ await expectLater(
+ clone.run(
+ GitHubRepository.parse('git@gitlab-work:owner/project.git')!,
+ parent.path,
+ ),
+ throwsA(
+ isA<RepositoryCloneException>().having(
+ (e) => e.message,
+ 'message',
+ 'gitlab-work isn\'t a GitHub host on this computer.',
+ ),
+ ),
+ );
+ expect(tried, isEmpty);
+ });
+
+ test('a checkout made through an alias is the repository a browser link '
+ 'names', () async {
+ final checkout = p.join(parent.path, 'project');
+ expect((await Process.run('git', ['init', checkout])).exitCode, 0);
+ await Process.run('git', [
+ '-C',
+ checkout,
+ 'remote',
+ 'add',
+ 'origin',
+ 'git@gh-work:Owner/Project.git',
+ ]);
+ final folder = await cloner().run(
+ GitHubRepository.parse('https://github.com/owner/project')!,
+ parent.path,
+ );
+ expect(folder, checkout);
+ expect(tried, isEmpty);
+ });
+
+ test('a pasted alias again starts in the checkout it made', () async {
+ final checkout = p.join(parent.path, 'project');
+ expect((await Process.run('git', ['init', checkout])).exitCode, 0);
+ await Process.run('git', [
+ '-C',
+ checkout,
+ 'remote',
+ 'add',
+ 'origin',
+ 'git@gh-work:owner/project.git',
+ ]);
+ final folder = await cloner().run(
+ GitHubRepository.parse('git@gh-work:owner/project.git')!,
+ parent.path,
+ );
+ expect(folder, checkout);
+ expect(tried, isEmpty);
+ });
+
+ test('a refused attempt leaves no staging behind the next', () async {
+ final seen = <List<String>>[];
+ final clone = RepositoryClone(
+ sshHosts: _FakeSshHosts(const {}, const []),
+ startProcess: (arguments, environment) async {
+ seen.add([
+ for (final entry in parent.listSync()) p.basename(entry.path),
+ ]);
+ if (arguments[2].startsWith('https://')) {
+ return Process.start('sh', [
+ '-c',
+ 'echo "fatal: could not read Username" >&2; exit 128',
+ ]);
+ }
+ return Process.start('git', [
+ 'clone',
+ '--',
+ source,
+ arguments.last,
+ ], environment: environment);
+ },
+ );
+ await clone.run(GitHubRepository.parse('owner/project')!, parent.path);
+ // Each attempt sees only its own staging folder.
+ expect(seen.map((names) => names.length), [1, 1]);
+ });
+ });
+}
+
+class _FakeSshHosts implements SshHosts {
+ _FakeSshHosts(this.hosts, this.aliases);
+ final Map<String, String> hosts;
+ final List<String> aliases;
+
+ @override
+ Future<String?> resolveHost(String alias) async => hosts[alias];
+
+ @override
+ Future<List<String>> githubAliases() async => aliases;
}
diff --git a/desktop/test/ssh_hosts_test.dart b/desktop/test/ssh_hosts_test.dart
new file mode 100644
index 000000000..f517e0224
--- /dev/null
+++ b/desktop/test/ssh_hosts_test.dart
@@ -0,0 +1,90 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/ssh_hosts.dart';
+import 'package:path/path.dart' as p;
+
+void main() {
+ late Directory home;
+ late List<List<String>> ran;
+ late Map<String, String> hostnames;
+
+ setUp(() async {
+ home = await Directory.systemTemp.createTemp('harness-ssh-hosts-');
+ await Directory(p.join(home.path, '.ssh')).create();
+ ran = [];
+ hostnames = {};
+ });
+ tearDown(() => home.delete(recursive: true));
+
+ SshHosts hosts() => SshHosts(
+ home: home.path,
+ runSsh: (arguments) async {
+ ran.add(arguments);
+ final host = hostnames[arguments.last];
+ return host == null ? null : 'user git\nhostname $host\nport 22\n';
+ },
+ );
+
+ Future<void> config(String text, [String name = 'config']) =>
+ File(p.join(home.path, '.ssh', name)).writeAsString(text);
+
+ test('reads the host an alias stands for, from ssh -G', () async {
+ hostnames['gh-work'] = 'github.com';
+ expect(await hosts().resolveHost('gh-work'), 'github.com');
+ expect(ran.single, ['-G', 'gh-work']);
+ });
+
+ test('never hands ssh a name that could be an option', () async {
+ expect(await hosts().resolveHost('-oProxyCommand=evil'), isNull);
+ expect(ran, isEmpty);
+ });
+
+ test('lists the GitHub aliases in config order, at most three', () async {
+ await config('''
+Host gh-a
+ HostName github.com
+Host *.internal !bad
+ User me
+Host gitlab-work gh-b
+ HostName whatever
+Host="gh-c"
+Host gh-d gh-e
+''');
+ hostnames.addAll({
+ 'gh-a': 'github.com',
+ 'gitlab-work': 'gitlab.com',
+ 'gh-b': 'github.com',
+ 'gh-c': 'github.com',
+ 'gh-d': 'github.com',
+ });
+ expect(await hosts().githubAliases(), ['gh-a', 'gh-b', 'gh-c']);
+ // Wildcards and negations are patterns, never asked about.
+ expect(ran.map((a) => a.last), isNot(contains('*.internal')));
+ });
+
+ test('follows Include one level, relative to ~/.ssh', () async {
+ await Directory(p.join(home.path, '.ssh', 'config.d')).create();
+ await config('Include config.d/*\nHost gh-a\n');
+ await config('Host gh-included\nInclude deeper\n', 'config.d/work');
+ await config('Host gh-too-deep\n', 'deeper');
+ hostnames.addAll({
+ 'gh-a': 'github.com',
+ 'gh-included': 'github.com',
+ 'gh-too-deep': 'github.com',
+ });
+ expect(await hosts().githubAliases(), ['gh-included', 'gh-a']);
+ });
+
+ test('a computer without an SSH config has no aliases', () async {
+ expect(await hosts().githubAliases(), isEmpty);
+ });
+
+ test('GitHub over port 443 is GitHub, and ? globs an Include', () async {
+ await Directory(p.join(home.path, '.ssh', 'conf.d')).create();
+ await config('Include conf.d/work?\n');
+ await config('Host gh-443\n', 'conf.d/work1');
+ hostnames['gh-443'] = 'ssh.github.com';
+ expect(await hosts().githubAliases(), ['gh-443']);
+ });
+}
diff --git a/docs/plans/2026-10-30-new-harness-paste-path-or-repository.md b/docs/plans/2026-10-30-new-harness-paste-path-or-repository.md
new file mode 100644
index 000000000..7d85409c0
--- /dev/null
+++ b/docs/plans/2026-10-30-new-harness-paste-path-or-repository.md
@@ -0,0 +1,289 @@
+# New Harness: paste a folder path or a GitHub link into the project search
+
+Status: ready for implementation. UI decided 2026-10-30 (option B of the A/B mock-up).
+
+## Problem Statement
+
+When someone starts a harness, the project menu's search box ("Search repos") only filters the recent
+projects by folder name. Two things people naturally paste there do nothing useful:
+
+- **A folder path** (`~/Pro2/x4`, `/Users/me/work/api`). An absolute path shows "No matches". A `~` path
+ only matches when the folder is already recent, and then only by luck. To open a folder, the person has
+ to find **Open Folder…** first and type the path again there.
+- **A GitHub link copied from the browser** (`https://github.com/org/repo`) shows "No matches". To clone
+ it, the person has to find **GitHub ›** first and paste it again there.
+
+Even through the GitHub door, **private repositories often fail** although the person can reach them with
+git. A clone uses only the selected computer's own git credentials, with every prompt turned off, and it
+tries exactly the address that was pasted. Measured on a developer Mac on 2026-10-30 with `git ls-remote`
+(same environment as a clone):
+
+| Pasted | Repository A | Repository B |
+|---|---|---|
+| Browser HTTPS link | refused: no HTTPS credential stored | refused |
+| `[email protected]:` | works | "Repository not found" |
+
+Repository B is reachable only through an SSH host alias in `~/.ssh/config` (`Host gh-<account>`,
+`HostName github.com`, another key): the person has two GitHub accounts on that computer. Nothing in the
+browser link says which alias to use, and a pasted `git@gh-<account>:org/repo` is refused as "not a GitHub
+URL".
+
+## Solution
+
+The project search recognizes what was typed and offers one action for it, at the top of the list and
+already selected, so Enter does it:
+
+- A path that names a folder → **Open ~/Pro2/x4** ("Folder on This Mac"). A path that does not name a folder
+ yet (`~/Pro2/`, `~/Pro2/x9`) → **Browse ~/Pro2/ ›**, which moves to the Open Folder prompt and keeps what
+ was typed, so the person carries on there.
+- A GitHub repository link (HTTPS, `[email protected]:` or an SSH alias that points at github.com) → **Clone
+ org/repo** ("into ~/harnesses/repo"; "over SSH as gh-<account>" for an alias; "on Mac mini · uses that
+ computer's GitHub access" when the harness runs on another computer).
+- A GitHub link that is not a repository → a disabled **Not a repository link** row ("Use
+ github.com/owner/repo"). An SSH alias that does not point at github.com → a disabled **gh-x isn't a GitHub
+ host** row when the selected computer is this one.
+- Anything else filters the recent projects as today. Typing a bare `Pro2/x4` stays a search: it is never
+ read as `owner/repo`.
+
+Open Folder…, New Folder and GitHub › stay where they are.
+
+When the harness is launched, cloning a private repository tries the ways the computer may have access,
+stopping at the first that works:
+
+1. the address that was pasted;
+2. the same repository over the other transport (HTTPS ↔ SSH);
+3. up to three SSH host aliases from the computer's SSH configuration whose host name is github.com.
+
+It moves to the next only when GitHub **refused access**. A network failure or a timeout stops at once.
+While it runs, the composer shows the static line **Cloning org/repo…**. A checkout that is reused is no clone, so the line stays **Starting harness…**. When an alias was used, the person
+sees one short line, **Cloned via gh-<account>**. The new checkout's `origin` is the address that worked, so
+later pushes go through the same account. When every way is refused, the composer shows one line, **No
+access to org/repo on this Mac** (the computer's name for another computer), keeps the task and every
+choice, and Launch tries again.
+
+## User Stories
+
+1. As a person starting a harness, I want to paste a folder path into the project search, so that I don't
+ have to find Open Folder first.
+2. As a person starting a harness, I want Enter to open a pasted path that names a folder, so that opening a
+ known folder is one paste and one key.
+3. As a person typing a path that doesn't exist yet, I want the search to take me to the folder browser with
+ what I typed, so that I can carry on choosing without typing it again.
+4. As a person typing `~/`, I want the path understood on the selected computer, so that `~` means that
+ computer's home.
+5. As a person with a Windows computer selected, I want `C:\work\api` treated as a path, so that the search
+ works the same there.
+6. As a person typing a project name, I want search to behave exactly as today, so that nothing I rely on
+ changes.
+7. As a person typing `team/api`, I want it treated as a search, not as a GitHub repository, so that I'm
+ never offered a clone I didn't ask for.
+8. As a person who copied a GitHub link from the browser, I want to paste it into the project search, so that
+ I don't have to find the GitHub door first.
+9. As a person pasting a GitHub link, I want the Clone row selected, so that Enter clones.
+10. As a person pasting `[email protected]:org/repo.git`, I want it accepted like the HTTPS link, so that either
+ form works.
+11. As a person pasting a GitHub link to an organization or a file, I want a clear "Not a repository link"
+ row, so that I know why nothing happens.
+12. As a person who reaches GitHub through an SSH alias, I want to paste `git@<alias>:org/repo`, so that the
+ clone uses that account.
+13. As a person pasting an alias that doesn't point at GitHub, I want to be told so, so that I don't wait for
+ a clone that cannot happen.
+14. As a person cloning onto another computer, I want the row to say it uses that computer's GitHub access,
+ so that I understand whose credentials matter.
+15. As a person who has GitHub access only over SSH, I want a pasted HTTPS link to clone anyway, so that I
+ don't have to rewrite links.
+16. As a person who has GitHub access only over HTTPS, I want a pasted SSH link to clone anyway, for the same
+ reason.
+17. As a person with two GitHub accounts on one computer, I want a browser link to clone through the alias
+ that has access, so that I don't need to remember alias names.
+18. As a person whose clone used an alias, I want a short "Cloned via <alias>" line, so that I know which
+ account will push.
+19. As a person whose clone used an alias, I want `origin` to stay on that alias, so that later pushes and
+ pulls work without changes.
+20. As a person whose clone is running, I want a simple "Cloning org/repo…" line, so that I know it's working.
+21. As a person with no access to a repository, I want one short line, "No access to org/repo on this Mac", so
+ that I know what failed without reading a log.
+22. As a person who got "No access", I want my task and choices kept, so that I can fix my credentials and
+ launch again.
+23. As a person whose network is down, I want the clone to stop at the first network failure, so that I
+ don't wait for more attempts that cannot work.
+24. As a person who already cloned a repository through an alias, I want pasting its browser link to start in
+ the existing checkout, so that I'm not told the folder already exists.
+25. As a person launching on a computer that runs an older Harness, I want ordinary links to clone as before,
+ so that a mixed setup keeps working.
+26. As a person using the browser app, I want the same paste behaviour, so that the experience matches the
+ desktop app.
+27. As a keyboard user, I want the action row reachable and announced like any other row, so that I can use
+ it without a mouse.
+28. As a guest on a computer shared with me, I want clones to behave as they do today, so that my request
+ never tries the owner's other GitHub accounts.
+29. As a Swarm member, I want Swarm project clones to behave as they do today, so that this change does not
+ alter how shared projects get access.
+30. As a developer diagnosing a "No access" report, I want the attempts recorded in the log (which transport
+ or alias, and how each failed), so that I can tell the person what to fix.
+
+## Implementation Decisions
+
+**Two places clone, and they must agree.** A harness on this computer is cloned by the desktop app itself.
+A harness on another computer is cloned by that computer's daemon while it prepares the project folder.
+Each place gets the same parser, the same repository identity and the same attempt order, written once in
+Dart and once in TypeScript, and both held to one shared vector file (Testing Decisions).
+
+**Parser.** Accepted repository addresses are HTTPS `github.com/owner/repo`, `[email protected]:owner/repo`
+and, new, `git@<alias>:owner/repo`. An alias must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`. It never starts
+with `-`, so it can never become an option to `ssh` or `git`. Owner and repository rules are unchanged. A bare
+`owner/repo` is no longer offered as a clone from the project search. The GitHub prompt and the daemon still
+accept it, for older callers. The parsed value records the transport (`https`, `ssh`, `alias`) and, for an
+alias, its name.
+
+**SSH host resolution.** A small module answers two questions on the computer that clones:
+
+- `resolveHost(alias) → hostname | null`, by running `ssh -G <alias>`, which reads the configuration without
+ connecting. It is bounded to four seconds and to 64 KiB of output.
+- `githubAliases() → string[]`: the configuration's `Host` names, wildcards and negations left out,
+ `Include` followed one level deep, each kept when `resolveHost` says `github.com`. The result is ordered
+ as written and capped at 3.
+
+It runs only on demand. A pasted alias is checked at parse time on the cloning computer. The alias list is
+read only after access was refused. Nothing about SSH configuration is cached or sent anywhere except the
+alias name that succeeded.
+
+**Attempt order.** A pure function `cloneAttempts(parsed, aliases) → address[]` gives, without duplicates:
+the pasted address; the other transport (HTTPS ↔ `[email protected]:`); then each alias as
+`git@<alias>:owner/repo.git`. A pasted alias comes first and is followed by HTTPS and `[email protected]:`. The
+runner tries each address in a fresh staging folder. It moves on only on an access refusal (the existing
+classification: authentication, permission denied, could not read Username, repository not found). It stops
+on success, a timeout, a network failure or a cancel. The five-minute deadline applies to each attempt.
+Staging is removed after each attempt, as today.
+
+**Repository identity with aliases.** When an existing checkout is compared with the requested repository
+("already cloned here: start in it"), a host that is not github.com is resolved through `resolveHost` first.
+A checkout whose origin is `git@gh-<account>:org/repo` is then the same repository as
+`https://github.com/org/repo`.
+
+**Who gets the wider attempts.** The fallback and the alias attempts apply to an owner's own New Harness
+launch, on this computer or one of their own. A guest's launch on a shared computer keeps today's single
+attempt; that path never prepares a project folder at all. Swarm clones keep their current behaviour: the
+token path stays HTTPS only, and the non-token path keeps its own HTTPS ↔ SSH retry. A Swarm agent created
+through the owner path (it has a Swarm role) gets no fallback either. The wider attempts are opt-in on the
+daemon's project-folder preparation (`cloneFallback`), off by default. While building, the Swarm retry was
+left where it is rather than moved onto the shared runner: its specs pin the exact preparation calls. Folding
+the two together is a follow-up.
+
+**Launch result contract (daemon → apps).** A successful creation that cloned may carry an optional
+`clonedVia: { alias: string }`, present only when an alias was used. A failure after all attempts were
+refused keeps the code `CLONE_FAILED` and carries a new optional `access: "denied"` beside the existing
+`detail`. The apps word the short line themselves ("No access to org/repo on <computer>"). An older app shows
+`detail` as today. A pasted alias that is not a GitHub host is refused with `INVALID_REPOSITORY` and a detail
+naming the alias.
+
+**Project search (desktop/browser controller).** In the project menu field, the controller classifies the
+query:
+
+- path: the existing path test;
+- GitHub link: contains `github.com/` or matches `git@<host>:`;
+- search: anything else.
+
+For a path it requests the parent's listing through the existing listing request and builds one action
+row: Open (the folder exists) or Browse (anything else). Browse moves to the Open Folder field with the query
+carried over. A Browse row is left out when a recent project matches the half-typed path, so the matching
+project keeps the highlight. This decision was added while building, because an existing rule
+(`/work/team/payments` selects the recent `payments-processing`) would otherwise break. For a link it builds one Clone row from the parser, or one disabled row. The action row is
+synthetic, sits above the three doors and takes the cursor. A recent project never outranks it. The
+placeholder stays "Search repos".
+
+**Composer lines.** While a creation that clones is running: "Cloning org/repo…" (static, no per-attempt
+progress). On success with an alias: "Cloned via <alias>", shown once where the app reports a start's
+outcome. On denial: "No access to org/repo on <computer>". The task and choices stay, and Launch retries.
+
+**Logging.** Each attempt is logged with the transport or alias and the failure class, never the
+credential-helper output. Addresses carry no credentials: the parser refuses them.
+
+## Testing Decisions
+
+A good test here drives the feature from the outside: it sets a query and reads what the menu offers and
+what Enter does, or it asks for a clone and reads which addresses were tried and what came back. It never
+asserts on private fields or on the order of internal calls.
+
+1. **Project search, through the New Harness controller.** Set the query, then read the shown rows, the
+ selected row and the result of accept. Cases:
+ - name search unchanged;
+ - existing path → Open;
+ - partial or missing path → Browse, which carries the query into the Open Folder field;
+ - Windows path;
+ - HTTPS, `[email protected]:` and alias links → Clone with the right detail;
+ - organization link → disabled row;
+ - bare `owner/repo` → search only;
+ - another computer selected → the "uses that computer's GitHub access" detail;
+ - keyboard: cursor and Enter.
+
+ Prior art: the entry-rules, controller-edges and project-context tests for New Harness, which build the
+ controller over an in-memory app notifier.
+2. **Shared vectors, run by both languages.** One JSON file of cases, each an input address with:
+ - the expected parse (or the refusal);
+ - the expected identity;
+ - given a stated alias table, the expected attempt list.
+
+ The Dart test and the TypeScript spec both load it, so the two implementations cannot drift. Prior art:
+ the Windows pipe-auth vectors, which both the CLI and the desktop app hold to one fixture.
+3. **Clone runs, through the existing injection points.**
+ - Desktop: the repository clone with an injected process starter that refuses chosen addresses (access,
+ network, timeout).
+ - Daemon: project-folder preparation with an injected clone function, and an injected host resolver.
+
+ Assert:
+ - which addresses were tried, and that a network failure stops the run;
+ - the final `origin`;
+ - that an existing alias checkout is reused;
+ - staging cleanup;
+ - guest launches try exactly one address;
+ - Swarm's token path stays HTTPS only.
+
+ Prior art: the repository-clone test and the project-folder spec.
+4. **Launch result in the core.** An agent creation that clones reports `clonedVia` and `access: "denied"`
+ as specified. This runs under the core's 100 % coverage gate, which PR CI does not run: run it locally and
+ record it in the PR.
+5. **Windows.** One run of the Windows desktop workflow to confirm `ssh -G` from the Windows OpenSSH client.
+
+## Out of Scope
+
+- Detecting, before cloning, that a pasted link is already checked out somewhere on the computer (offering
+ "Open" instead of "Clone").
+- Using the Harness GitHub App's token for New Harness clones.
+- Hosts other than GitHub (GitLab, Bitbucket, GitHub Enterprise).
+- Live per-attempt progress while cloning.
+- Changing how Swarm projects get access.
+- Asking for credentials interactively (password, passphrase, device login).
+
+## Further Notes
+
+- Mock-up of the decided UI, with every state: the A/B page drawn for this decision (option B, private
+ repository states P1–P6), kept outside the repository.
+- Update the New Harness entry rules design note with the classification rules and the action row.
+
+## Design (docs/feature-design-rules.md)
+
+Reviewed revision: ______ Reviewer (another engine): ______
+
+1. Growth: N/A because nothing is stored; staging folders are removed after each attempt, as today.
+2. Concurrency: unchanged. Each attempt clones into its own staging folder and renames once. A destination
+ that appeared meanwhile is reused when it holds the same repository (alias-aware) and refused otherwise.
+3. Read cost: the SSH configuration is read only after an access refusal, bounded (64 KiB output per
+ `ssh -G`, at most 3 aliases kept, `Include` one level). The project search issues no request beyond the
+ listing path completion already makes.
+4. Scale: worst case per launch is 5 attempts, each refused in about 1–2 s. The first warning is clone time
+ in the creation logs.
+5. Compatibility: a new app with an old daemon gets today's single attempt and `INVALID_REPOSITORY` for a
+ pasted alias. An old app with a new daemon ignores `clonedVia` and `access` and shows `detail`. Existing
+ readers of the creation result were searched: the desktop failure wording and the creation-status payload.
+6. Migration and rollback: none. A previous release ignores the new optional fields.
+7. Audience: the alias name is returned only to the account that asked for the creation on its own computer.
+ Guests get no alias attempts.
+8. Identity: a clone runs with the cloning computer's own git credentials, as today. The wider attempts run
+ only for the computer owner's own launches, never for a guest, and never with the Harness GitHub App token.
+9. Failure: refused everywhere → "No access to org/repo on <computer>", task kept, Launch retries. Network or
+ timeout → today's messages. Every attempt is in the log.
+10. Platforms:
+ - macOS and Linux: `ssh -G` from OpenSSH.
+ - Windows: OpenSSH client, to be confirmed in the Windows workflow.
+ - Browser app: never clones locally, so the daemon does all of it.