The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: simplify harness launch and add Git worktree choices (#193)
Deeafded9aa2f60
diff --git a/.github/assets/harness-launch/new-harness.png b/.github/assets/harness-launch/new-harness.pngnew file mode 100644index 000000000..e9b8a9745Binary files /dev/null and b/.github/assets/harness-launch/new-harness.png differdiff --git a/.github/assets/harness-launch/new-pane.png b/.github/assets/harness-launch/new-pane.pngnew file mode 100644index 000000000..59667ba99Binary files /dev/null and b/.github/assets/harness-launch/new-pane.png differdiff --git a/.github/assets/harness-launch/new-tab.png b/.github/assets/harness-launch/new-tab.pngnew file mode 100644index 000000000..0d7e53f96Binary files /dev/null and b/.github/assets/harness-launch/new-tab.png differdiff --git a/.github/assets/harness-launch/non-git.png b/.github/assets/harness-launch/non-git.pngnew file mode 100644index 000000000..dbc645402Binary files /dev/null and b/.github/assets/harness-launch/non-git.png differdiff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 19c821de0..e4f7437e0 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -10,6 +10,7 @@ import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.jsimport { registry, type RegisteredSession } from './lib/registry.js'import { stoppedAgents } from './lib/stoppedAgents.js'import * as mediaPreview from './lib/mediaPreview.js'+import * as gitProject from './lib/gitProject.js'import * as projectFolder from './lib/projectFolder.js'import * as projectPreview from './lib/projectPreview.js'import * as storeCatalog from './dsh/catalog.js'@@ -497,6 +498,53 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('returns Git branch choices only to the requesting encrypted connection', async () => {+ const preview = { isGit: true, root: '/remote/workspace', branch: 'main', branches: [{ ref: 'refs/heads/private-branch', name: 'private-branch', remote: false }] }+ const read = vi.spyOn(gitProject, 'readGitProject').mockResolvedValue(preview)+ const socket = new BackendSocket('token')+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {+ requestId: 'preview-1', path: '/remote/workspace',+ } })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ })+ ws.message({ t: 'down', connId: 'viewer-a', frame: {+ type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },+ } })+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'preview-1', preview))+ expect(read).toHaveBeenCalledWith('/remote/workspace')+ expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {+ type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ } }))+ expect(JSON.stringify(parseSent(ws))).not.toContain('private-branch')+ await socket.stop()+ })++ it('returns a correlated Git error when discovery rejects or the path is malformed', async () => {+ const read = vi.spyOn(gitProject, 'readGitProject').mockRejectedValue(new Error('unavailable'))+ const socket = new BackendSocket('token')+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {+ requestId: 'git-error', path: 42,+ } })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-error' } },+ })+ ws.message({ t: 'down', connId: 'viewer-a', frame: {+ type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },+ } })+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'git-error', { error: 'UNAVAILABLE' }))+ expect(read).toHaveBeenCalledWith('')+ await socket.stop()+ })+it('serves media only to the requesting encrypted connection', async () => {vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)const media = { media: true as const, filename: 'preview.png', offset: 0, totalBytes: 3,@@ -909,7 +957,11 @@ describe('BackendSocket outbound queue', () => {}})- it('prepares a remote project once under its creation receipt and retains its folder after a refused launch', async () => {+ it.each([+ { projectSource: 'remote', repositoryUrl: 'owner/repo' },+ { projectSource: 'worktree', gitSource: '/remote/repo', branchRef: 'refs/heads/main' },+ { projectSource: 'branch', gitSource: '/remote/repo', branchRef: 'refs/heads/feature' },+ ])('prepares $projectSource once under its creation receipt and retains its folder after a refused launch', async (project) => {const socket = new BackendSocket('token')const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -918,7 +970,7 @@ describe('BackendSocket outbound queue', () => {const create = vi.fn(async () => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))socket.onCreateAgent = createconst creationId = randomUUID()- const payload = { creationId, engine: 'claude', projectSource: 'remote', repositoryUrl: 'owner/repo' }+ const payload = { creationId, engine: 'claude', ...project }const ask = (type: string, requestId: string, choices = payload) => socket.handleLocalFrame('local:project', { type, payload: { requestId, ...choices } })try {ask('agent_create', 'first')@@ -933,7 +985,7 @@ describe('BackendSocket outbound queue', () => {}expect(create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ cwd: '/remote/Harness Projects/repo' }))expect(prepare).toHaveBeenCalledTimes(1)- ask('agent_create', 'changed', { ...payload, repositoryUrl: 'owner/different' })+ ask('agent_create', 'changed', { ...payload, engine: 'codex' })await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'changed', error: 'CREATION_CONFLICT' }) })))expect(prepare).toHaveBeenCalledTimes(1)ask('agent_create_status', 'saved')diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex cf3ea0a67..9a207c203 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -42,6 +42,7 @@ import { engineInstallRecipe } from './lib/engineInstall.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'import { projectPreview } from './lib/projectPreview.js'+import { readGitProject } from './lib/gitProject.js'import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { installedDsh, listInstalledDsh } from './dsh/installed.js'import { OrchestratorService } from './orchestrator/service.js'@@ -1280,7 +1281,7 @@ export class BackendSocket {private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {const resultType = `${type}_result`// Before the E2EE wrap: an RPC reply is only readable here.- if (env.LOG_FRAMES && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && !SHARE_REQUEST_TYPES.has(type)) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })+ if (env.LOG_FRAMES && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && !SHARE_REQUEST_TYPES.has(type)) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })if (this.localClients.has(connId)) {this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })return@@ -1383,7 +1384,7 @@ export class BackendSocket {// than as an opaque __e2e envelope.// Terminal frames contain raw keystrokes, paste text and screen bytes after// unwrap. Never pass them to the frame logger, even in diagnostic mode.- if (env.LOG_FRAMES && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'orchestrator' && !SHARE_REQUEST_TYPES.has(type)) {+ if (env.LOG_FRAMES && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'orchestrator' && !SHARE_REQUEST_TYPES.has(type)) {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)@@ -2389,6 +2390,14 @@ export class BackendSocket {return}+ case 'git_project_info': {+ const path = typeof payload.path === 'string' ? payload.path : ''+ void readGitProject(path)+ .then(result => reply(type, requestId, result))+ .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))+ return+ }+case 'project_preview': {const path = typeof payload.path === 'string' ? payload.path : ''// Preview work is detached so typing and other RPCs stay responsive.diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex a9cea490d..057fbc047 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -14,6 +14,6 @@ import { VIEWER_DOWN_TYPES } from '../viewerWire.js'const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))export const encryptDownFrame = (type: string): boolean =>- isEncryptedDownType(type) || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)+ isEncryptedDownType(type) || type === 'git_project_info' || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)export const encryptRpcResult = (type: string): boolean =>- ENCRYPTED_RPC_RESULT_TYPES.has(type) || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)+ ENCRYPTED_RPC_RESULT_TYPES.has(type) || type === 'git_project_info_result' || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.tsnew file mode 100644index 000000000..11d13efa9--- /dev/null+++ b/cli/src/lib/gitProject.spec.ts@@ -0,0 +1,174 @@+import { execFile } from 'node:child_process'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { encryptDownFrame, encryptRpcResult } from './e2ee/applicationFrames.js'+import { prepareGitProject, readGitProject, validGitPath } from './gitProject.js'+import { parseProjectFolder, prepareProjectFolder } from './projectFolder.js'++const exec = promisify(execFile)+describe('launch Git preparation', () => {+ let root: string, repo: string+ const git = async (...args: string[]) => (await exec('git', ['-C', repo, ...args])).stdout.trim()+ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'harness-git-test-'))+ repo = join(root, 'project with spaces')+ await mkdir(repo)+ await git('init', '-b', 'main')+ await git('config', 'user.name', 'Test')+ await git('config', 'user.email', '[email protected]')+ await git('config', 'commit.gpgsign', 'false')+ await git('config', 'core.hooksPath', '/dev/null')+ await mkdir(join(repo, 'src'))+ await writeFile(join(repo, 'src', 'value'), 'main')+ await git('add', '.')+ await git('commit', '-m', 'initial')+ await git('switch', '-c', 'feature')+ await writeFile(join(repo, 'src', 'value'), 'feature')+ await git('commit', '-am', 'feature')+ await git('update-ref', 'refs/remotes/origin/feature', 'HEAD')+ await git('symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/feature')+ await git('switch', 'main')+ })+ afterEach(async () => { vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }) })+ const options = () => ({ root: join(root, 'harnesses'), label: 'Codex', now: () => new Date(2026, 8, 21, 12, 0) })+ const prepare = (source: 'worktree' | 'branch', branchRef = 'refs/heads/feature', path = repo) =>+ prepareProjectFolder(parseProjectFolder({ projectSource: source, gitSource: path, branchRef })!, options())++ it('encrypts Git metadata requests and replies', () => {+ expect(encryptDownFrame('git_project_info')).toBe(true)+ expect(encryptRpcResult('git_project_info_result')).toBe(true)+ })++ it('reads local and remote branches without switching or creating anything', async () => {+ expect(await readGitProject(repo)).toMatchObject({ isGit: true, branch: 'main', branches: [+ { ref: 'refs/heads/feature', name: 'feature', remote: false },+ { ref: 'refs/heads/main', name: 'main', remote: false },+ { ref: 'refs/remotes/origin/feature', name: 'origin/feature', remote: true },+ ] })+ expect(await git('branch', '--show-current')).toBe('main')+ expect(await git('worktree', 'list', '--porcelain')).not.toContain('harness/')+ expect(await readGitProject(root)).toMatchObject({ isGit: false })+ expect(await readGitProject('relative/path')).toEqual({ error: 'INVALID_PATH' })+ })++ it('starts concurrent worktrees on distinct branches from the chosen ref and preserves dirty source files', async () => {+ await writeFile(join(repo, 'src', 'value'), 'my uncommitted work')+ const paths = await Promise.all([prepare('worktree'), prepare('worktree', 'refs/remotes/origin/feature')])+ expect(new Set(paths).size).toBe(2)+ const branches = []+ for (const path of paths) {+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('feature')+ const branch = (await exec('git', ['-C', path, 'branch', '--show-current'])).stdout.trim()+ expect(branch).toMatch(/^harness\//)+ branches.push(branch)+ }+ expect(new Set(branches).size).toBe(2)+ expect(await readFile(join(repo, 'src', 'value'), 'utf8')).toBe('my uncommitted work')+ expect(await git('branch', '--show-current')).toBe('main')+ })++ it('keeps the selected subfolder in its new worktree', async () => {+ const path = await prepare('worktree', 'refs/heads/feature', join(repo, 'src'))+ expect(await readFile(join(path, 'value'), 'utf8')).toBe('feature')+ expect(path.endsWith('/src/')).toBe(false)+ })++ it('switches the shared folder only when requested, without forcing conflicting changes', async () => {+ expect(await prepare('branch')).toBe(repo)+ expect(await git('branch', '--show-current')).toBe('feature')+ await writeFile(join(repo, 'src', 'value'), 'keep this')+ await expect(prepare('branch', 'refs/heads/main')).rejects.toMatchObject({ code: 'BRANCH_SWITCH_FAILED' })+ expect(await git('branch', '--show-current')).toBe('feature')+ expect(await readFile(join(repo, 'src', 'value'), 'utf8')).toBe('keep this')+ expect(await git('stash', 'list')).toBe('')+ // Selecting the current branch is a no-op even with dirty files.+ expect(await prepare('branch')).toBe(repo)+ })++ it('refuses a branch checked out elsewhere, missing refs, revision expressions, and untracked subfolders', async () => {+ await git('worktree', 'add', join(root, 'other'), 'feature')+ await expect(prepare('branch')).rejects.toMatchObject({ code: 'BRANCH_SWITCH_FAILED' })+ for (const ref of ['refs/heads/missing', 'refs/heads/main~0', 'refs/heads/main^{commit}']) {+ await expect(prepare('worktree', ref)).rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })+ }+ await mkdir(join(repo, 'untracked'))+ await expect(prepare('worktree', 'refs/heads/main', join(repo, 'untracked'))).rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })+ expect(() => parseProjectFolder({ projectSource: 'branch', gitSource: repo, branchRef: 'refs/remotes/origin/feature' })).toThrow()+ })++ it('detects an empty repository but refuses a worktree until its first commit', async () => {+ const empty = join(root, 'empty')+ await mkdir(empty)+ await exec('git', ['-C', empty, 'init', '-b', 'main'])+ expect(await readGitProject(empty)).toMatchObject({ isGit: true, branch: 'main', branches: [] })+ await expect(prepareProjectFolder({ source: 'worktree', gitSource: empty }, options()))+ .rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })+ })++ it('validates source paths and requires an exact local branch when isolation is disabled', async () => {+ for (const path of [null, 7, '', 'relative', '/bad\npath', '/bad\0path', `/${'x'.repeat(4096)}`]) {+ expect(validGitPath(path)).toBe(false)+ expect(() => parseProjectFolder({ projectSource: 'worktree', gitSource: path })).toThrow()+ }+ await expect(prepareGitProject('relative', { ...options(), worktree: true }))+ .rejects.toMatchObject({ code: 'INVALID_PROJECT_SOURCE' })+ await expect(prepareGitProject(repo, { ...options(), worktree: true, ref: '--help' }))+ .rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })+ for (const ref of [undefined, 'refs/remotes/origin/feature']) {+ await expect(prepareGitProject(repo, { ...options(), worktree: false, ref }))+ .rejects.toMatchObject({ code: 'INVALID_BRANCH' })+ }+ for (const payload of [+ { branchRef: 7 }, { branchRef: 'refs/heads/bad name' },+ { branchRef: `refs/heads/${'x'.repeat(1024)}` }, { repositoryUrl: 'https://github.com/a/b' },+ ]) {+ expect(() => parseProjectFolder({ projectSource: 'worktree', gitSource: repo, ...payload })).toThrow()+ }+ })++ it('supports detached HEAD, default worktree names, and switching back to a local branch', async () => {+ await git('checkout', '--detach', 'HEAD')+ expect(await readGitProject(repo)).toMatchObject({ isGit: true, branch: null })+ const path = await prepareGitProject(repo, { root, worktree: true })+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')+ expect(path).toContain('project-with-spaces-harness-')+ expect(await prepare('branch')).toBe(repo)+ expect(await git('branch', '--show-current')).toBe('feature')+ })++ it('distinguishes an unavailable Git executable from a non-Git folder', async () => {+ vi.stubEnv('PATH', join(root, 'missing-binaries'))+ expect(await readGitProject(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })+ })++ it('reports unreadable refs instead of silently treating the repository as non-Git', async () => {+ await writeFile(join(repo, '.git', 'packed-refs'), 'invalid packed refs\n')+ expect(await readGitProject(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })+ })++ it('rejects a subfolder that became a file on the selected branch', async () => {+ await git('switch', 'feature')+ await git('rm', '-r', 'src')+ await writeFile(join(repo, 'src'), 'a file now')+ await git('add', 'src')+ await git('commit', '-m', 'replace folder with file')+ await git('switch', 'main')+ await expect(prepare('worktree', 'refs/heads/feature', join(repo, 'src')))+ .rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })+ })++ it('keeps a worktree created before a checkout hook fails so the user can recover it', async () => {+ const hooks = join(root, 'hooks')+ await mkdir(hooks)+ await writeFile(join(hooks, 'post-checkout'), '#!/bin/sh\nexit 1\n', { mode: 0o755 })+ await git('config', 'core.hooksPath', hooks)+ await expect(prepare('worktree')).rejects.toMatchObject({ code: 'WORKTREE_FAILED' })+ const linked = (await git('worktree', 'list', '--porcelain')).split('\n')+ .find(line => line.startsWith('worktree ') && line.includes('/worktrees/'))!.slice(9)+ expect(await readFile(join(linked, 'src', 'value'), 'utf8')).toBe('feature')+ expect(await git('branch', '--show-current')).toBe('main')+ })+})diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.tsnew file mode 100644index 000000000..43a382963--- /dev/null+++ b/cli/src/lib/gitProject.ts@@ -0,0 +1,91 @@+import { execFile } from 'node:child_process'+import { mkdir, mkdtemp } from 'node:fs/promises'+import { basename, isAbsolute, join } from 'node:path'+import { promisify } from 'node:util'+import { projectFolderName } from './agentNames.js'++const exec = promisify(execFile)++export class GitProjectError extends Error {+ constructor(readonly code: string, message: string) { super(message) }+}++export function validGitPath(path: unknown): path is string {+ return typeof path === 'string' && isAbsolute(path) && path.length <= 4096 && !/[\x00-\x1f\x7f]/.test(path)+}++async function git(path: string, args: string[], timeout = 4000): Promise<string> {+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_OPTIONAL_LOCKS: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]+ return (await exec('git', ['--no-optional-locks', '-C', path, ...args], {+ timeout, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,+ env,+ })).stdout.replace(/\r?\n$/, '')+}++/** Read only: listing a branch never checks it out or fetches from a remote. */+export async function readGitProject(path: string) {+ if (!validGitPath(path)) return { error: 'INVALID_PATH' }+ let root: string+ try { root = await git(path, ['rev-parse', '--show-toplevel']) }+ catch (error) {+ const failure = error as { code?: number | string; killed?: boolean }+ return !failure.killed && failure.code === 128 ? { isGit: false, branches: [] } : { error: 'GIT_UNAVAILABLE' }+ }+ try {+ const [branch, refs] = await Promise.all([+ git(path, ['symbolic-ref', '--quiet', 'HEAD']).then(ref => ref.replace(/^refs\/heads\//, '')).catch(() => null),+ git(path, ['for-each-ref', '--format=%(refname)%09%(refname:short)%09%(symref)', 'refs/heads', 'refs/remotes']),+ ])+ const branches = refs.split('\n').filter(Boolean).flatMap(line => {+ const [ref, name, symbolic] = line.split('\t')+ return ref && name && !symbolic ? [{ ref, name, remote: ref.startsWith('refs/remotes/') }] : []+ })+ return { isGit: true, root, branch, branches }+ } catch { return { error: 'GIT_UNAVAILABLE' } }+}++/** Start uses a fresh branch for worktrees; the shared folder is only switched+ * when the user explicitly chooses a different local branch with Worktree off. */+export async function prepareGitProject(+ source: string,+ options: { root: string; worktree: boolean; ref?: string; label?: string | null; now?: () => Date },+): Promise<string> {+ if (!validGitPath(source)) throw new GitProjectError('INVALID_PROJECT_SOURCE', 'Choose a Git project folder.')+ let root: string, head: string, prefix: string+ try {+ root = await git(source, ['rev-parse', '--show-toplevel'])+ if (options.ref) {+ if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(options.ref)) throw new Error('Invalid branch')+ await git(source, ['show-ref', '--verify', '--hash', '--', options.ref])+ }+ head = await git(source, ['rev-parse', '--verify', '--end-of-options', `${options.ref ?? 'HEAD'}^{commit}`])+ prefix = await git(source, ['rev-parse', '--show-prefix'])+ if (prefix && await git(source, ['cat-file', '-t', `${head}:${prefix.replace(/\/$/, '')}`]) !== 'tree') throw new Error('Missing folder')+ } catch {+ throw new GitProjectError('GIT_PROJECT_UNAVAILABLE', 'Choose a Git project and branch with at least one commit. For a new folder, turn Worktree off.')+ }+ if (!options.worktree) {+ if (!options.ref?.startsWith('refs/heads/')) throw new GitProjectError('INVALID_BRANCH', 'Choose a local branch, or turn Worktree on.')+ try {+ const current = await git(source, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => null)+ if (current === options.ref) return source+ await git(source, ['switch', '--', options.ref.slice('refs/heads/'.length)], 120_000)+ return source+ } catch {+ throw new GitProjectError('BRANCH_SWITCH_FAILED', 'Could not switch branches. Commit or stash conflicting changes, or turn Worktree on.')+ }+ }+ const parent = join(options.root, 'worktrees')+ await mkdir(parent, { recursive: true })+ const name = projectFolderName(`${basename(root)}-${options.label?.trim() || 'harness'}`, (options.now ?? (() => new Date()))(), true)+ const destination = await mkdtemp(join(parent, `${name}-`))+ const branch = `harness/${basename(destination)}`+ try {+ await git(source, ['worktree', 'add', '-b', branch, '--', destination, head], 120_000)+ return prefix ? join(destination, prefix.replace(/\/$/, '')) : destination+ } catch {+ // Keep any partial checkout and branch available for recovery.+ throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)+ }+}diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.tsindex f10b2600d..607cfc225 100644--- a/cli/src/lib/projectFolder.ts+++ b/cli/src/lib/projectFolder.ts@@ -3,10 +3,13 @@ import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'import { homedir } from 'node:os'import { join } from 'node:path'import { projectFolderName, projectFolderSlug } from './agentNames.js'+import { GitProjectError, prepareGitProject, validGitPath } from './gitProject.js'/** `name` on a new project is what the person called it; without one the folder is named after the* harness and the time. */export type ProjectFolder = { source: 'new'; name?: string } | { source: 'remote'; repositoryUrl: string; name: string }+ | { source: 'worktree'; gitSource: string; branchRef?: string }+ | { source: 'branch'; gitSource: string; branchRef?: string }export class ProjectFolderError extends Error {constructor(readonly code: string, message: string) { super(message) }@@ -16,6 +19,15 @@ export class ProjectFolderError extends Error {// 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') {+ const ref = payload.branchRef+ if (!validGitPath(payload.gitSource) || payload.repositoryUrl !== undefined ||+ (ref !== undefined && (typeof ref !== 'string' || ref.length > 1024 || !/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(ref))) ||+ (payload.projectSource === 'branch' && (typeof ref !== 'string' || !ref.startsWith('refs/heads/')))) {+ throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a Git project and branch.')+ }+ return { source: payload.projectSource, gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}) }+ }if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) {// Slugged again here: the name becomes a path segment, so it is never taken on trust.const name = typeof payload.projectName === 'string' ? projectFolderSlug(payload.projectName) : null@@ -64,6 +76,11 @@ export async function prepareProjectFolder(const root = options.root ?? join(homedir(), 'harnesses')let staging: string | undefinedtry {+ if (project.source === 'worktree' || project.source === 'branch') {+ return await prepareGitProject(project.gitSource, {+ root, worktree: project.source === 'worktree', ref: project.branchRef, label: options.label, now: options.now,+ })+ }await mkdir(root, { recursive: true })if (project.source === 'new' && project.name) {// A name somebody chose is never quietly changed: an existing folder is theirs to pick as an@@ -100,6 +117,7 @@ export async function prepareProjectFolder(await rename(checkout, destination)return destination} catch (error) {+ if (error instanceof GitProjectError) throw new ProjectFolderError(error.code, error.message)if (error instanceof ProjectFolderError) throw errorthrow new ProjectFolderError('PROJECT_PREPARATION_FAILED', 'Could not create a project folder on this machine. Browse for a folder you can edit.')} finally {diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.mdindex a03bbc5a0..57fb94007 100644--- a/desktop/design/new-harness-entry-rules.md+++ b/desktop/design/new-harness-entry-rules.md@@ -1,8 +1,13 @@# New Harness entry rules-All workspace entry points use the command dock. Start submits the values in-the reviewed draft. Merely opening or cancelling it never starts a harness or-allocates a tab.+All workspace entry points use the command dock. Start Harness submits the+reviewed draft. Opening or cancelling it never starts a harness. Cmd-T allocates+a temporary tab that is removed on cancellation if it remains untouched.++The launch form starts with Agent, Machine, and Project, followed by Start+Harness, which is selected initially. There is no heading, Task row, or Open In+row. Cmd-T and Cmd-P pickers also omit their heading and result-count row.+Tasks carried from search or Store examples remain part of the draft.| Entry | Initial values | Destination after a successful start || --- | --- | --- |@@ -21,10 +26,28 @@ apply any agent or machine explicitly named by the request.While the harness picker is open, Cmd-T and Cmd-P change only the destination.They preserve the query, text selection, highlighted result, and project or-machine filter. Repeating either shortcut refocuses the same input. The heading,-Enter action, and available capacity update together. Cancelling still leaves+machine filter. Repeating either shortcut refocuses the same input. The Enter+action and available capacity update together. Cancelling still leavesthe workspace unchanged.+## Git projects++Git projects show Branch and Worktree. Worktree defaults to `[x]` for each new+project context; Enter, Space, or a click toggles `[x]` and `[ ]`. Folders without+Git show neither row. Discovery runs on the selected machine without fetching,+switching branches, or creating a worktree. A failed discovery offers Retry and+blocks starting until the result is known.++Branch selects the starting local or remote ref. With `[x]`, Start Harness+creates a unique worktree and branch under `~/harnesses/worktrees`, keeping+uncommitted source files intact. With `[ ]`, only local branches are selectable;+Start Harness switches the existing folder using Git's normal protections.+No changes are forced, stashed, or discarded. A selected subfolder follows into+the new worktree only if it exists in that commit.++Drafts and advanced options preserve these choices. A lost start reply reuses+its receipt, and retrying a confirmed launch failure reuses its prepared folder.+## Draft ownership- Workspace drafts belong to their original machine, focused source harness,@@ -58,6 +81,10 @@ never silently renamed, and existing files are never overwritten.## Regression coverage+- `test/new_harness_git_test.dart`, `test/git_worktree_test.dart`, and+ `test/git_worktree_failures_test.dart`: Git defaults, hidden non-Git rows,+ keyboard/click toggles, branch search, stale replies, retries, actual Git+ worktrees and branch safety, process deadlines, and bounded output.- `test/new_harness_entry_rules_test.dart`: product changes with an open ordismissed dock, Open/Try, edited names, machine changes, explicit agentprecedence, search isolation, exact launch payloads, pending receipts, sourcediff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dartindex c9f8726ac..c8ae58e0e 100644--- a/desktop/integration_test/native_workspace_e2e_test.dart+++ b/desktop/integration_test/native_workspace_e2e_test.dart@@ -1297,6 +1297,7 @@ void main() {) async {final connection = _CreationConnection();final app = createApp(connectionForTest: (_) => connection);+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};seedMixedAgents(app);app.machineStates['m']!..localOnly = true@@ -1324,8 +1325,9 @@ void main() {await tester.enterText(search, 'Check retargeted keyboard input');await key(tester, shortcut, cmd: true);await key(tester, shortcut, cmd: true);+ final destination = app.activeSwarm;expect(find.text('Check retargeted keyboard input'), findsWidgets);- expect(find.text(label), findsOneWidget);+ expect(find.text(label), findsNothing);await key(tester, LogicalKeyboardKey.enter);expect(find.byType(NewHarnessBox), findsOneWidget);expect(@@ -1339,7 +1341,8 @@ void main() {await tester.pump(const Duration(milliseconds: 200));await tester.pump();expect(find.byType(NewHarnessBox), findsNothing);- expect(app.activeSwarm == source, label == 'New Pane');+ expect(app.activeSwarm, same(destination));+ expect(app.activeSwarm, isNot(same(source)));final session = app.focusedPane!.session!;final view = tester.widget<TerminalView>(find.byWidgetPredicate(@@ -1517,7 +1520,9 @@ void main() {expect(prompt().engine, 'codex');expect(prompt().machineId, 'm');expect(prompt().project.folder, '/work/openharness');- expect(app.swarms, [source]);+ expect(app.swarms, hasLength(2));+ expect(app.swarms.first, same(source));+ expect(app.activeSwarm.isBlankNewTab, true);expect(prompt().field, NewHarnessField.launch);await key(tester, LogicalKeyboardKey.arrowDown);await key(tester, LogicalKeyboardKey.arrowDown);@@ -1530,7 +1535,7 @@ void main() {await key(tester, LogicalKeyboardKey.enter);expect(prompt().project.folder, '/work/openharness');expect(prompt().field, NewHarnessField.launch);- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.enterText(line, 'Refine terminal workspace');await key(tester, LogicalKeyboardKey.enter, alt: true);expect(@@ -1596,7 +1601,7 @@ void main() {expect(connection.creates, isEmpty);// Reopen from the same source, this time choosing a pane. Escape kept- // both the task and edited defaults without allocating an empty tab.+ // both the task and edited defaults after removing the temporary tab.await key(tester, LogicalKeyboardKey.keyP, cmd: true);await key(tester, LogicalKeyboardKey.enter);await tester.pump(const Duration(milliseconds: 80));diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dartnew file mode 100644index 000000000..ee34ed0b3--- /dev/null+++ b/desktop/lib/core/git_worktree.dart@@ -0,0 +1,291 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:path/path.dart' as p;++import 'project_folder.dart';+import 'repository_clone.dart';++class GitBranch {+ const GitBranch(this.ref, this.name, {this.remote = false});+ final String ref, name;+ final bool remote;+}++class GitProjectInfo {+ const GitProjectInfo({+ this.isGit = false,+ this.branch,+ this.branches = const [],+ this.error,+ });+ factory GitProjectInfo.fromJson(Map<String, dynamic> data) => GitProjectInfo(+ isGit: data['isGit'] == true,+ branch: data['branch'] as String?,+ error: data['error'] as String?,+ branches: [+ for (final row in (data['branches'] as List? ?? const []))+ if (row is Map && row['ref'] is String && row['name'] is String)+ GitBranch(+ row['ref'] as String,+ row['name'] as String,+ remote: row['remote'] == true,+ ),+ ],+ );+ final bool isGit;+ final String? branch, error;+ final List<GitBranch> branches;+}++bool validGitPath(String path) =>+ p.isAbsolute(path) &&+ path.length <= 4096 &&+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(path);+bool validGitRef(String ref) =>+ ref.length <= 1024 &&+ RegExp(r'^refs/(heads|remotes)/[^\s\x00-\x1f\x7f]+$').hasMatch(ref);++typedef GitProcessStarter = Future<Process> Function(+ List<String> arguments,+ Map<String, String> environment,+);++/// Listing choices never checks out a branch or fetches from a remote.+Future<Map<String, dynamic>> readLocalGitProject(+ String source, {+ GitProcessStarter? startProcess,+}) async {+ Future<({int code, String output})> git(List<String> arguments) =>+ _git(source, arguments, startProcess: startProcess);+ if (!validGitPath(source)) return {'error': 'INVALID_PATH'};+ try {+ final root = await git(['rev-parse', '--show-toplevel']);+ if (root.code != 0) {+ return root.code == 128 ? {'isGit': false} : {'error': 'GIT_UNAVAILABLE'};+ }+ final results = await Future.wait([+ git(['symbolic-ref', '--quiet', 'HEAD']),+ git([+ 'for-each-ref',+ '--format=%(refname)%09%(refname:short)%09%(symref)',+ 'refs/heads',+ 'refs/remotes',+ ]),+ ]);+ if (results[1].code != 0) return {'error': 'GIT_UNAVAILABLE'};+ return {+ 'isGit': true,+ 'root': root.output,+ 'branch': results[0].code == 0+ ? results[0].output.replaceFirst('refs/heads/', '')+ : null,+ 'branches': [+ for (final line in results[1].output.split('\n'))+ if (line.split('\t') case [final ref, final name, ''])+ {+ 'ref': ref,+ 'name': name,+ 'remote': ref.startsWith('refs/remotes/'),+ },+ ],+ };+ } on RepositoryCloneException {+ return {'error': 'GIT_UNAVAILABLE'};+ }+}++/// Worktrees get a fresh branch. With Worktree off, only an explicitly chosen+/// local branch can switch the shared folder, using Git's normal protections.+Future<String> prepareGitProject(+ String source,+ String projectHome, {+ required bool worktree,+ String? branchRef,+ required String label,+ DateTime Function()? now,+ GitProcessStarter? startProcess,+}) async {+ Future<({int code, String output})> git(+ List<String> arguments, {+ Duration timeout = const Duration(seconds: 4),+ }) => _git(source, arguments, timeout: timeout, startProcess: startProcess);+ if (!validGitPath(source) || branchRef != null && !validGitRef(branchRef)) {+ throw const RepositoryCloneException('Choose a Git project and branch.');+ }+ final root = await git(['rev-parse', '--show-toplevel']);+ if (root.code != 0) {+ throw const RepositoryCloneException('Choose a Git working folder.');+ }+ if (branchRef != null) {+ final ref = await git(['show-ref', '--verify', '--hash', '--', branchRef]);+ if (ref.code != 0) {+ throw const RepositoryCloneException(+ 'That branch is no longer available. Choose another branch.',+ );+ }+ }+ final head = await git([+ 'rev-parse',+ '--verify',+ '--end-of-options',+ '${branchRef ?? 'HEAD'}^{commit}',+ ]);+ if (head.code != 0) {+ throw const RepositoryCloneException(+ 'Worktree needs a branch with at least one commit. Turn Worktree off for an empty repository.',+ );+ }+ final prefix = await git(['rev-parse', '--show-prefix']);+ if (prefix.code != 0) {+ throw const RepositoryCloneException('Could not read the project folder.');+ }+ final relative = prefix.output;+ if (relative.isNotEmpty) {+ final tree = await git([+ 'cat-file',+ '-t',+ '${head.output}:${relative.replaceFirst(RegExp(r'/$'), '')}',+ ]);+ if (tree.code != 0 || tree.output != 'tree') {+ throw const RepositoryCloneException(+ 'This folder is not in the selected branch. Choose the repository root.',+ );+ }+ }+ if (!worktree) {+ if (branchRef == null || !branchRef.startsWith('refs/heads/')) {+ throw const RepositoryCloneException(+ 'Choose a local branch, or turn Worktree on.',+ );+ }+ final current = await git(['symbolic-ref', '--quiet', 'HEAD']);+ if (current.code == 0 && current.output == branchRef) return source;+ final result = await git([+ 'switch',+ '--',+ branchRef.substring('refs/heads/'.length),+ ], timeout: const Duration(minutes: 2));+ if (result.code != 0) {+ throw const RepositoryCloneException(+ 'Could not switch branches. Commit or stash conflicting changes, or turn Worktree on.',+ );+ }+ return source;+ }+ final parent = Directory(p.join(projectHome, 'worktrees'));+ await parent.create(recursive: true);+ final name = projectFolderName(+ '${p.basename(root.output)}-$label',+ (now ?? DateTime.now)(),+ withSeconds: true,+ );+ final destination = await parent.createTemp('$name-');+ final branch = 'harness/${p.basename(destination.path)}';+ final result = await git([+ 'worktree',+ 'add',+ '-b',+ branch,+ '--',+ destination.path,+ head.output,+ ], timeout: const Duration(minutes: 2));+ if (result.code != 0) {+ // A partial checkout or branch stays available for recovery.+ throw RepositoryCloneException(+ 'Could not create the worktree at ${destination.path}. Check Git and folder permissions, then retry.',+ );+ }+ return relative.isEmpty+ ? destination.path+ : p.join(destination.path, relative);+}++Future<({int code, String output})> _git(+ String source,+ List<String> arguments, {+ Duration timeout = const Duration(seconds: 4),+ GitProcessStarter? startProcess,+}) async {+ final environment = Map<String, String>.of(Platform.environment)+ ..removeWhere(+ (key, _) => const [+ 'GIT_DIR',+ 'GIT_WORK_TREE',+ 'GIT_COMMON_DIR',+ 'GIT_INDEX_FILE',+ 'GIT_NAMESPACE',+ 'GIT_PREFIX',+ ].contains(key),+ )+ ..addAll({+ 'GIT_TERMINAL_PROMPT': '0',+ 'GCM_INTERACTIVE': 'Never',+ 'GIT_OPTIONAL_LOCKS': '0',+ });+ Process process;+ final argv = ['--no-optional-locks', '-C', source, ...arguments];+ try {+ process =+ await (startProcess?.call(argv, environment) ??+ Process.start(+ 'git',+ argv,+ environment: environment,+ includeParentEnvironment: false,+ ));+ } on ProcessException {+ throw const RepositoryCloneException(+ 'Git could not start. Install Git, then retry.',+ );+ }+ unawaited(process.stdin.close());+ final output = StringBuffer();+ var overflow = false;+ final outDone = Completer<void>(), errDone = Completer<void>();+ final stdout = process.stdout+ .transform(const Utf8Decoder(allowMalformed: true))+ .listen(+ (chunk) {+ if (output.length + chunk.length <= 1024 * 1024) {+ output.write(chunk);+ } else {+ overflow = true;+ process.kill(ProcessSignal.sigkill);+ }+ },+ onDone: outDone.complete,+ onError: outDone.completeError,+ );+ final stderr = process.stderr.listen(+ (_) {},+ onDone: errDone.complete,+ onError: errDone.completeError,+ );+ try {+ final results = await Future.wait<dynamic>([+ process.exitCode,+ outDone.future,+ errDone.future,+ ]).timeout(timeout);+ if (overflow) {+ throw const RepositoryCloneException(+ 'This repository has too many branches to read.',+ );+ }+ return (+ code: results.first as int,+ output: output.toString().replaceFirst(RegExp(r'\r?\n$'), ''),+ );+ } on TimeoutException {+ process.kill(ProcessSignal.sigkill);+ throw const RepositoryCloneException(+ 'Git took too long. Check this machine, then retry.',+ );+ } finally {+ await stdout.cancel();+ await stderr.cancel();+ }+}diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dartindex 864c9deed..405e4e5d6 100644--- a/desktop/lib/core/project_folder.dart+++ b/desktop/lib/core/project_folder.dart@@ -3,28 +3,58 @@ import 'dart:io';import 'package:path/path.dart' as p;import 'repository_clone.dart';+import 'git_worktree.dart';/// Folder preparation is explicit and runs only when New Agent is submitted./// Existing folders continue to use the ordinary agent_create cwd payload.class ProjectFolderRequest {const ProjectFolderRequest.newProject({this.name})- : repository = null,+ : gitSource = null,+ branchRef = null,+ createsWorktree = false,+ repository = null,generatedLabel = null,generatedAt = null;ProjectFolderRequest.generated({required String label,required DateTime at,String? name,- }) : repository = null,+ }) : gitSource = null,+ branchRef = null,+ createsWorktree = false,+ repository = null,generatedLabel = label,generatedAt = at,name = name ?? _suggestedFolderName(label, at);const ProjectFolderRequest.remote(GitHubRepository value)- : repository = value,+ : gitSource = null,+ branchRef = null,+ createsWorktree = false,+ repository = value,name = null,generatedLabel = null,generatedAt = null;+ const ProjectFolderRequest.worktree(String source, {this.branchRef})+ : gitSource = source,+ createsWorktree = true,+ repository = null,+ name = null,+ generatedLabel = null,+ generatedAt = null;++ const ProjectFolderRequest.branch(String source, String ref)+ : gitSource = source,+ branchRef = ref,+ createsWorktree = false,+ repository = null,+ name = null,+ generatedLabel = null,+ generatedAt = null;++ final String? gitSource, branchRef;+ final bool createsWorktree;+final GitHubRepository? repository;/// What the person called the new project, or null to name it after the@@ -76,7 +106,13 @@ class ProjectFolderRequest {String? get folderName => name == null ? null : projectFolderSlug(name!);Map<String, String> get payload => {- 'projectSource': repository == null ? 'new' : 'remote',+ 'projectSource': gitSource != null+ ? (createsWorktree ? 'worktree' : 'branch')+ : repository == null+ ? 'new'+ : 'remote',+ 'gitSource': ?gitSource,+ 'branchRef': ?branchRef,if (repository != null) 'repositoryUrl': repository!.url,// A daemon that predates the field ignores it and names the folder itself.if (repository == null && folderName != null) 'projectName': folderName!,@@ -102,6 +138,16 @@ class ProjectFolderRequest {}final root = Directory(projectHome ?? p.join(home!, 'harnesses'));try {+ if (gitSource case final source?) {+ return await prepareGitProject(+ source,+ root.path,+ worktree: createsWorktree,+ branchRef: branchRef,+ label: label,+ now: now,+ );+ }await root.create(recursive: true);if (repository case final repo?) {return await (createClone?.call() ?? RepositoryClone()).run(diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex d541a6444..6a5976dc3 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -33,6 +33,7 @@ const Set<String> encryptedDownTypes = {'agent_read_file','fs_list_dir','project_preview',+ 'git_project_info','codex_profiles_list','codex_profile_link',// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missingdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 340b7a731..13bbe13e1 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -2150,34 +2150,35 @@ class _SwarmScreenState extends State<SwarmScreen> {child: Column(mainAxisSize: MainAxisSize.min,children: [- Padding(- padding: const EdgeInsets.fromLTRB(14, 9, 14, 2),- child: Row(- children: [- Text(- search.title,- style: boxMonoStyle(size: 12, color: kBoxFaint),- ),- if (search.placement == HarnessPlacement.currentTab ||- search.split != null)- Expanded(- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 8),- child: Text(- '· ${search.targetName}',- key: const ValueKey('swarm-search-target'),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: boxMonoStyle(size: 12, color: kBoxFaint),+ if (search.title != search.placement?.title)+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 9, 14, 2),+ child: Row(+ children: [+ Text(+ search.title,+ style: boxMonoStyle(size: 12, color: kBoxFaint),+ ),+ if (search.placement == HarnessPlacement.currentTab ||+ search.split != null)+ Expanded(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: Text(+ '· ${search.targetName}',+ key: const ValueKey('swarm-search-target'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: boxMonoStyle(size: 12, color: kBoxFaint),+ ),),- ),- )- else- const Spacer(),- SwarmSearchCount(search: search, terminal: true),- ],+ )+ else+ const Spacer(),+ SwarmSearchCount(search: search, terminal: true),+ ],+ ),),- ),Flexible(child: ordered(2,diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 8c7789954..a09921f4a 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -31,6 +31,7 @@ import '../core/local_git_projects.dart';import '../core/test_run.dart';import '../core/models.dart';import '../core/project_folder.dart';+import '../core/git_worktree.dart';import '../core/project_history.dart';import '../core/project_preview.dart';import '../core/repository_clone.dart';@@ -6034,6 +6035,37 @@ class AppNotifier extends ChangeNotifier {}}+ @visibleForTesting+ Future<Map<String, dynamic>> Function(String machineId, String path)?+ gitProjectReaderForTest;++ /// Git choices are read on the machine that owns this project.+ Future<Map<String, dynamic>> readGitProject(+ String machineId,+ String path,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) return {'error': 'UNAVAILABLE'};+ final reader = gitProjectReaderForTest;+ if (reader != null) return reader(machineId, path);+ if (machine.isLocalMachine) return readLocalGitProject(path);+ if (connectionForTest == null &&+ (machine.nodeOnline == false ||+ machine.needsLink ||+ machine.connectionStatus != ConnectionStatus.connected)) {+ return {'error': 'UNAVAILABLE'};+ }+ try {+ return await _conn(machineId).request(+ 'git_project_info',+ payload: {'path': path},+ timeout: const Duration(seconds: 6),+ );+ } catch (_) {+ return {'error': 'UNAVAILABLE'};+ }+ }+/// Reads source material only on the machine that owns the selected path.Future<Map<String, dynamic>> readProjectPreview(String machineId,@@ -6239,6 +6271,10 @@ class AppNotifier extends ChangeNotifier {'PROJECT_EXISTS' ||'CLONE_FAILED' ||'CLONE_TIMEOUT' ||+ 'GIT_PROJECT_UNAVAILABLE' ||+ 'INVALID_BRANCH' ||+ 'BRANCH_SWITCH_FAILED' ||+ 'WORKTREE_FAILED' ||'GIT_UNAVAILABLE' =>detail ?? 'Could not prepare the project folder on $machine.','CWD_NOT_FOUND' || 'INVALID_CWD' =>@@ -6376,6 +6412,8 @@ class AppNotifier extends ChangeNotifier {..remove('projectSource')..remove('repositoryUrl')..remove('projectName')+ ..remove('gitSource')+ ..remove('branchRef')..['cwd'] = creation._preparedFolder;}if (!machine.isLocalMachine && creation._remoteProjectName != null) {diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex c6157dcab..2197b67b1 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -12,6 +12,7 @@ import '../core/dsh_catalog.dart';import '../core/harness_catalog.dart';import '../core/first_task.dart';import '../core/fuzzy_match.dart';+import '../core/git_worktree.dart';import '../core/permission_modes.dart';import '../core/project_folder.dart';import '../core/repository_clone.dart';@@ -36,6 +37,7 @@ enum NewHarnessField {task,agent,machine,+ branch,projectMenu,project,projectName,@@ -100,6 +102,9 @@ class NewHarnessDraft {required this.project,required this.task,required this.permissionMode,+ this.worktree,+ this.branchRef,+ this.gitProject,this.profile,this.profileChosen = false,this.attempt,@@ -109,6 +114,9 @@ class NewHarnessDraft {});final String machineId, engine, task, permissionMode;+ final bool? worktree;+ final String? branchRef;+ final GitProjectInfo? gitProject;final NewHarnessProject project;final LocalCodexProfile? profile;final bool profileChosen;@@ -120,7 +128,13 @@ class NewHarnessDraft {final Map<String, NewHarnessProject> projectsByMachine;ProjectFolderRequest? get projectFolderRequest =>- project.folder != null || isTerminalEngine(engine)+ (worktree == true || worktree == null && gitProject?.isGit == true) &&+ project.folder != null &&+ !isTerminalEngine(engine)+ ? ProjectFolderRequest.worktree(project.folder!, branchRef: branchRef)+ : branchRef != null && project.folder != null && !isTerminalEngine(engine)+ ? ProjectFolderRequest.branch(project.folder!, branchRef!)+ : project.folder != null || isTerminalEngine(engine)? null: project.repository != null? ProjectFolderRequest.remote(project.repository!)@@ -216,6 +230,9 @@ class NewHarnessController extends ChangeNotifier {? _generatedProject(): const NewHarnessProject.fresh();if (task != null) this.task = task;+ _worktree = draft?.worktree;+ _branchRef = draft?.branchRef;+ _gitProject = draft?.gitProject ?? const GitProjectInfo();if (draft != null) {_projectsByMachine.addAll(draft.projectsByMachine);_project = draft.project;@@ -236,8 +253,8 @@ class NewHarnessController extends ChangeNotifier {? NewHarnessProject.fresh(projectName): _generatedProject();}- // A missing destination is the only required question. A carried task is- // shown in the launch summary and remains editable, including after Escape.+ // A missing project is the only required question. Carried tasks remain+ // part of the draft for Store examples and advanced options.field = needsProject && !checking? NewHarnessField.projectMenu: NewHarnessField.launch;@@ -269,7 +286,7 @@ class NewHarnessController extends ChangeNotifier {final AppNotifier app;final String? swarmId;final PaneSplitRequest? split;- HarnessPlacement? placement;+ final HarnessPlacement? placement;final String _targetId;final bool _usesNewTabPage;HarnessPlacement? get effectivePlacement =>@@ -277,12 +294,6 @@ class NewHarnessController extends ChangeNotifier {? HarnessPlacement.currentTab: placement;- void changePlacement(HarnessPlacement value) {- if (locked || split != null || placement == value) return;- placement = value;- notifyListeners();- }-final bool firstRun;final bool _autoProject;final DateTime Function() _now;@@ -300,6 +311,86 @@ class NewHarnessController extends ChangeNotifier {String get engine => _engine;String get machineId => _machineId;NewHarnessProject get project => _project;+ bool? _worktree;+ String? _branchRef;+ GitProjectInfo _gitProject = const GitProjectInfo();+ (String, String?, bool)? _gitKey;+ Future<void>? _gitFuture;+ int _gitRevision = 0;+ bool checkingGit = false;+ Future<void> waitForGitProject() async {+ while (checkingGit && !_disposed) {+ await _gitFuture;+ }+ }+ bool get isGitProject => _gitProject.isGit && !isTerminal;+ bool get canUseWorktree => isGitProject && !checkingGit;+ bool get worktree => isGitProject && _worktree != false;+ String? get branchRef => _branchRef;+ String? get gitError => _gitProject.error;+ String get branchLabel =>+ _gitProject.branches+ .where((branch) => branch.ref == _branchRef)+ .firstOrNull+ ?.name ??+ _branchRef?.replaceFirst(RegExp(r'^refs/(heads|remotes)/'), '') ??+ _gitProject.branch ??+ 'Detached HEAD';++ void toggleWorktree() {+ if (locked || !canUseWorktree) return;+ _worktree = !worktree;+ error = null;+ _refresh();+ }++ void retryGitProject() {+ if (locked || checkingGit || _project.folder == null || isTerminal) return;+ error = null;+ _gitFuture = _readGitProject(_gitKey!);+ notifyListeners();+ }++ void _syncGitProject() {+ final key = (_machineId, _project.folder, isTerminal);+ if (_gitKey == key) return;+ if (_gitKey != null) {+ _worktree = null;+ _branchRef = null;+ _gitProject = const GitProjectInfo();+ }+ _gitKey = key;+ _gitRevision++;+ checkingGit = false;+ _gitFuture = null;+ if (key.$2 != null && !key.$3 && !checking) {+ _gitFuture = _readGitProject(key);+ }+ }++ Future<void> _readGitProject((String, String?, bool) key) async {+ checkingGit = true;+ final revision = ++_gitRevision;+ GitProjectInfo info;+ try {+ info = GitProjectInfo.fromJson(await app.readGitProject(key.$1, key.$2!));+ } catch (_) {+ info = const GitProjectInfo(error: 'UNAVAILABLE');+ }+ if (_disposed || _gitKey != key || revision != _gitRevision) return;+ checkingGit = false;+ _gitProject = info;+ // Keep an explicit branch choice; a removed branch fails at Start.+ if (_branchRef == null &&+ info.branch != null &&+ info.branches.any(+ (branch) => branch.ref == 'refs/heads/${info.branch}',+ )) {+ _branchRef = 'refs/heads/${info.branch}';+ }+ _refresh();+ }+LocalCodexProfile? _profile;bool _profileChosen = false;String? get profileLabel =>@@ -313,6 +404,9 @@ class NewHarnessController extends ChangeNotifier {project: _project,task: task,permissionMode: _mode,+ worktree: _worktree,+ branchRef: _branchRef,+ gitProject: _gitProject,profile: _profile,profileChosen: _profileChosen,attempt: _attempt,@@ -325,8 +419,11 @@ class NewHarnessController extends ChangeNotifier {);/// The same preparation intent is used by the prompt and advanced options.- ProjectFolderRequest? get projectFolderRequest =>- _project.folder != null || isTerminal+ ProjectFolderRequest? get projectFolderRequest => worktree+ ? ProjectFolderRequest.worktree(_project.folder!, branchRef: _branchRef)+ : !isTerminal && _project.folder != null && _branchRef != null+ ? ProjectFolderRequest.branch(_project.folder!, _branchRef!)+ : _project.folder != null || isTerminal? null: _project.repository != null? ProjectFolderRequest.remote(_project.repository!)@@ -365,9 +462,6 @@ class NewHarnessController extends ChangeNotifier {? _mode: kDefaultPermissionMode;bool get takesTask => takesFirstTask(_base);- String get taskAvailability => takesTask- ? 'Add a task (optional)'- : 'Enter a task in $agentLabel after launch';bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;List<PermissionMode> get _modes =>isTerminal ? const [] : permissionModesOf(_base);@@ -429,11 +523,12 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.agent,NewHarnessField.machine,NewHarnessField.projectMenu,- if (takesTask) NewHarnessField.task,+ if (isGitProject) NewHarnessField.branch,];bool _supportsField(NewHarnessField value) =>fields.contains(value) ||value == NewHarnessField.launch ||+ (value == NewHarnessField.task && takesTask) ||value == NewHarnessField.project ||value == NewHarnessField.projectName ||value == NewHarnessField.projectRepository ||@@ -481,7 +576,7 @@ class NewHarnessController extends ChangeNotifier {// ---- what the line says -------------------------------------------------- String get createLabel => 'Start';+ String get createLabel => 'Start Harness';Future<void> _detectInitialAgent({required bool allowSelection}) async {detectingAgent = true;@@ -554,6 +649,7 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.task => 'What should this agent work on? (optional)',NewHarnessField.agent => 'Choose an agent',NewHarnessField.machine => 'Choose a machine',+ NewHarnessField.branch => 'Search branches',NewHarnessField.project => 'Enter a folder path, or press Enter to browse',NewHarnessField.projectName => 'Type a project name',NewHarnessField.projectRepository => 'Paste a GitHub repository URL',@@ -714,6 +810,7 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.launch || NewHarnessField.task => false,NewHarnessField.agent => option.id == _engine,NewHarnessField.machine => option.id == _machineId,+ NewHarnessField.branch => option.id == _branchRef,NewHarnessField.project ||NewHarnessField.projectMenu ||NewHarnessField.projectName ||@@ -933,6 +1030,8 @@ class NewHarnessController extends ChangeNotifier {_selectEngine(option.id);case NewHarnessField.machine:_selectMachine(option.id);+ case NewHarnessField.branch:+ _branchRef = option.id;case NewHarnessField.project:case NewHarnessField.projectMenu:case NewHarnessField.projectName:@@ -1402,6 +1501,7 @@ class NewHarnessController extends ChangeNotifier {void _refresh({bool resetCursor = false, String? agentSelection}) {if (_disposed) return;+ _syncGitProject();_seen = _signature();final current = resetCursor ? null : selected?.id;// An agent picked from another field may have no task or no modes.@@ -1418,6 +1518,18 @@ class NewHarnessController extends ChangeNotifier {NewHarnessField.task ||NewHarnessField.agent => const [],NewHarnessField.machine => _machineOptions(),+ NewHarnessField.branch => _ranked([+ for (final branch in _gitProject.branches)+ NewHarnessOption(+ id: branch.ref,+ title: branch.name,+ detail: branch.remote ? 'Remote' : '',+ enabled: worktree || !branch.remote,+ why: branch.remote+ ? 'Turn Worktree on to start from a remote branch.'+ : null,+ ),+ ]),NewHarnessField.projectMenu => _projectMenu(),NewHarnessField.project ||NewHarnessField.projectName => _projectOptions(),@@ -1981,6 +2093,27 @@ class NewHarnessController extends ChangeNotifier {focusField(NewHarnessField.projectMenu);return _fail('Choose a project, or create a new one.');}+ if (!checking) {+ _syncGitProject();+ if (gitError != null) retryGitProject();+ if (checkingGit) {+ busy = true;+ status = 'Checking project…';+ notifyListeners();+ await _gitFuture;+ if (_disposed) return NewHarnessOutcome.failed;+ busy = false;+ status = null;+ }+ if (gitError != null) {+ return _fail(+ 'Could not check Git on $machineLabel. Check the connection and Harness CLI, then retry.',+ );+ }+ if (!worktree && _branchRef?.startsWith('refs/remotes/') == true) {+ return _fail('Choose a local branch, or turn Worktree on.');+ }+ }// Shortened by the person, never cut by us: a machine refuses one longer.if (takesTask && taskTooLong && !checking) {return _fail(@@ -2070,6 +2203,11 @@ class NewHarnessController extends ChangeNotifier {// goes into it rather than making a second one beside it.if (!checking && attempt.preparedFolder != null) {_project = NewHarnessProject.folder(attempt.preparedFolder!);+ _gitKey = (_machineId, _project.folder, isTerminal);+ _worktree = false;+ _branchRef = null;+ _gitProject = const GitProjectInfo();+ _gitFuture = _readGitProject(_gitKey!);}return _fail(failure);}diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex 869ddfa86..928d17135 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -680,10 +680,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {Navigator.of(context).pop(NewAgentDialogResult.created);}+ bool get _sameGitProject =>+ _machineId == widget.initialDraft?.machineId &&+ _folder == widget.initialDraft?.project.folder &&+ _preparedFolder == null;+ProjectFolderRequest? get _projectFolder => switch (_folderSource) {_FolderSource.newProject =>_generatedProject ?? ProjectFolderRequest.newProject(name: _projectName),- _FolderSource.local => null,+ _FolderSource.local =>+ _sameGitProject ? widget.initialDraft?.projectFolderRequest : null,_FolderSource.remote => switch (_repository) {final repository? => ProjectFolderRequest.remote(repository),null => null,@@ -708,6 +714,13 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {: NewHarnessProject.fresh(_projectName),task: _task.text,permissionMode: _permissionMode,+ worktree: _preparedFolder != null+ ? false+ : _sameGitProject+ ? widget.initialDraft?.worktree+ : null,+ branchRef: _sameGitProject ? widget.initialDraft?.branchRef : null,+ gitProject: _sameGitProject ? widget.initialDraft?.gitProject : null,profile: _codexProfile,profileChosen: _codexProfileChosen,attempt: _creation,diff --git a/desktop/lib/widgets/new_harness_box.dart b/desktop/lib/widgets/new_harness_box.dartindex 6dc7e7b71..57cd568d9 100644--- a/desktop/lib/widgets/new_harness_box.dart+++ b/desktop/lib/widgets/new_harness_box.dart@@ -9,12 +9,11 @@ import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';import '../state/new_harness.dart';-import '../state/harness_placement.dart';import 'box_chrome.dart';import 'pane_menu.dart';import 'terminal_prompt.dart';-enum _LaunchChoice { agent, machine, project, task, placement, create }+enum _LaunchChoice { agent, machine, project, branch, worktree, create }/// A launch menu and focused completion prompts with shared arrow navigation./// Create is selected initially; arrows and Enter edit a displayed default.@@ -73,8 +72,8 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {_LaunchChoice.agent,_LaunchChoice.machine,_LaunchChoice.project,- _LaunchChoice.task,- if (box.split == null) _LaunchChoice.placement,+ if (box.isGitProject) _LaunchChoice.branch,+ if (box.canUseWorktree || box.gitError != null) _LaunchChoice.worktree,_LaunchChoice.create,];String get _launchCreateLabel => box.checking@@ -98,27 +97,16 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {box.focusField(NewHarnessField.machine);case _LaunchChoice.project:box.focusField(NewHarnessField.projectMenu);- case _LaunchChoice.task:- _editTask();- case _LaunchChoice.placement:- _togglePlacement();+ case _LaunchChoice.branch:+ box.focusField(NewHarnessField.branch);+ case _LaunchChoice.worktree:+ box.gitError != null ? box.retryGitProject() : box.toggleWorktree();case _LaunchChoice.create:unawaited(_finish(box.create()));}_requestFocus();}- void _togglePlacement() {- if (box.locked || box.split != null) return;- _selectLaunchChoice(_LaunchChoice.placement);- box.changePlacement(- box.placement == HarnessPlacement.newTab- ? HarnessPlacement.currentTab- : HarnessPlacement.newTab,- );- _requestFocus();- }-void _requestFocus() => (_hasInput ? _focus : _launchFocus).requestFocus();final _scroll = ScrollController();final _announcer = BoxAnnouncer();@@ -223,6 +211,11 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {box.status,box.error,box.task,+ box.worktree,+ box.canUseWorktree,+ box.checkingGit,+ box.gitError,+ box.branchLabel,box.placement,box.query.trim().isEmpty,box.matchCount,@@ -292,8 +285,8 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {(_launching? _launchChoice == _LaunchChoice.create? _summaryText()- : _launchChoice == _LaunchChoice.placement- ? 'Open in ${box.placement!.title}. Enter to switch.'+ : _launchChoice == _LaunchChoice.worktree+ ? 'Worktree ${box.worktree ? 'on' : 'off'}. Enter to toggle.': '${_launchChoice.name}. Enter to edit.': box.field == NewHarnessField.task// No row to read here: read what Return will do instead.@@ -351,6 +344,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {NewHarnessField.profile => 'Codex profile',NewHarnessField.agent => 'Agent',NewHarnessField.machine => 'Machine',+ NewHarnessField.branch => 'Branch',NewHarnessField.project => 'Project',};@@ -368,8 +362,23 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {}}- void _moreOptions() {- if (!box.locked && !_composing) widget.onNeedsForm();+ bool _openingOptions = false;+ Future<void> _moreOptions() async {+ if (box.locked || _composing || _openingOptions) return;+ _openingOptions = true;+ try {+ await box.waitForGitProject();+ if (!mounted || box.locked) return;+ if (box.gitError != null) {+ box.warn(+ 'Could not check Git on ${box.machineLabel}. Retry Worktree before opening advanced options.',+ );+ return;+ }+ widget.onNeedsForm();+ } finally {+ _openingOptions = false;+ }}Future<void> _agentSettings(@@ -662,6 +671,12 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {);final extra = CallbackShortcuts(bindings: {+ if (_launching)+ const SingleActivator(LogicalKeyboardKey.space): () {+ if (_launchChoice == _LaunchChoice.worktree) {+ _activateLaunchChoice(_LaunchChoice.worktree);+ }+ },// ⌥↵ is the pane's own chord for "break the line"; it is not a command.const SingleActivator(LogicalKeyboardKey.enter, alt: true): _newline,if (KeymapTheme.of(context) == null) ...{@@ -849,25 +864,30 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- Padding(- padding: const EdgeInsets.symmetric(horizontal: 8),- child: Text(- box.checking- ? 'pending harness'- : _agentPicker- ? 'Choose an agent'- : _machinePicker- ? 'Choose a machine'- : _profilePicker- ? 'Codex profile on ${box.machineLabel}'- : box.field == NewHarnessField.mode- ? 'Permissions for ${box.agentSettingsLabel}'- : 'New Harness',- style: boxMonoStyle(size: 12, color: kBoxFaint),+ if (!_launching)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: Text(+ box.checking+ ? 'pending harness'+ : _agentPicker+ ? 'Choose an agent'+ : _machinePicker+ ? 'Choose a machine'+ : box.field == NewHarnessField.branch+ ? 'Choose a branch'+ : _profilePicker+ ? 'Codex profile on ${box.machineLabel}'+ : box.field == NewHarnessField.mode+ ? 'Permissions for ${box.agentSettingsLabel}'+ : 'New Harness',+ style: boxMonoStyle(size: 12, color: kBoxFaint),+ ),),- ),- if (!_agentPicker && !_machinePicker) ...[- const SizedBox(height: 8),+ if (!_agentPicker &&+ !_machinePicker &&+ box.field != NewHarnessField.branch) ...[+ if (!_launching) const SizedBox(height: 8),_segment(NewHarnessField.agent,_launching@@ -884,22 +904,30 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {_ => box.needsProject ? 'Choose a project' : box.projectLabel,}),],- if (_launching)- _default(- 'task',- box.task.trim().isEmpty- ? box.taskAvailability- : box.task.trim().replaceAll(RegExp(r'\s+'), ' '),- muted: !box.takesTask,- onTap: _editTask,- ),- if (_launching && box.split == null)- _default(- 'placement',- box.placement!.title,- onTap: _togglePlacement,- ),if (_launching) ...[+ if (box.isGitProject)+ _segment(NewHarnessField.branch, box.branchLabel),+ if (box.isGitProject || box.checkingGit || box.gitError != null)+ _default(+ 'worktree',+ box.checkingGit+ ? 'Checking…'+ : box.gitError != null+ ? 'Retry'+ : box.worktree+ ? '[x]'+ : '[ ]',+ enabled: box.canUseWorktree || box.gitError != null,+ tooltip: box.gitError != null+ ? 'Could not check Git on ${box.machineLabel}. Retry.'+ : box.canUseWorktree+ ? 'Start in a new Git worktree and branch from the selected branch. Uncommitted changes stay in the original folder.'+ : 'Choose an existing Git project to use a worktree.',+ onTap: () {+ _selectLaunchChoice(_LaunchChoice.worktree);+ _activateLaunchChoice(_LaunchChoice.worktree);+ },+ ),const SizedBox(height: 8),_default('create',@@ -936,37 +964,43 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {required VoidCallback onTap,bool active = false,bool risky = false,- bool muted = false,bool action = false,+ bool enabled = true,+ String? tooltip,}) {final choice = _launching? _LaunchChoice.values.where((item) => item.name == name).firstOrNull: null;final highlighted = choice != null && choice == _launchChoice;- final disabled = name == 'create'- ? box.busy || box.detectingAgent- : box.locked;- final fieldLabel = name == 'placement'- ? 'Open in'- : '${name[0].toUpperCase()}${name.substring(1)}';+ final disabled =+ !enabled ||+ (name == 'create' ? box.busy || box.detectingAgent : box.locked);+ final fieldLabel = '${name[0].toUpperCase()}${name.substring(1)}';+ final checkbox =+ name == 'worktree' && !box.checkingGit && box.gitError == null;return MouseRegion(onHover: (event) {- if (choice != null && _pointer.moved(event)) {+ if (!disabled && choice != null && _pointer.moved(event)) {_selectLaunchChoice(choice);}},child: Semantics(- button: true,+ button: !checkbox,+ checked: checkbox ? box.worktree : null,enabled: !disabled,selected: highlighted || active,- label: action ? label : '$fieldLabel, $label',+ label: checkbox+ ? fieldLabel+ : action+ ? label+ : '$fieldLabel, $label',excludeSemantics: true,child: BoxRowHighlight(terminal: true,highlighted: highlighted,accent: grid.AppPalette.swarmAccent,child: Tooltip(- message: label,+ message: tooltip ?? label,child: InkWell(key: ValueKey('new-harness-field-$name'),onTap: disabled ? null : onTap,@@ -994,7 +1028,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {size: 12,color: risky? grid.AppPalette.warn- : muted || disabled+ : disabled? kBoxFaint: Colors.white,weight: active || action@@ -1020,6 +1054,8 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {? 'Choose a project before starting ${box.agentLabel}.': 'Return starts ${box.agentLabel} on ${box.machineLabel} in ''${box.projectLabel}'+ '${box.isGitProject ? ', from ${box.branchLabel}' : ''}'+ '${box.worktree ? ', in a new Git worktree' : ''}''${box.hasModes ? ', ${box.modeLabel.toLowerCase()}' : ''}''${box.profileLabel == null ? '' : ', profile ${box.profileLabel}'}''${box.task.trim().isEmpty ? '' : ', and sends what you typed as its first message'}.';@@ -1492,13 +1528,13 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {_ => 'use project',}: _launching && _launchChoice != _LaunchChoice.create- ? _launchChoice == _LaunchChoice.placement- ? 'switch'+ ? _launchChoice == _LaunchChoice.worktree+ ? 'toggle': 'edit ${_launchChoice.name}': _launching && box.needsProject? 'choose project': box.returnCreates- ? box.createLabel.toLowerCase()+ ? 'start': box.selected?.id == NewHarnessController.storeId? 'open store': box.selected?.id == NewHarnessController.permissionsId@@ -1530,11 +1566,7 @@ class _NewHarnessBoxState extends State<NewHarnessBox> {if (_launching &&!box.checking &&_launchChoice != _LaunchChoice.create)- BoxHint(- key('picker.add_here', '⌘↵'),- box.createLabel.toLowerCase(),- onTap: _createNow,- ),+ BoxHint(key('picker.add_here', '⌘↵'), 'start', onTap: _createNow),if (!box.checking &&!_launching &&!_projectMenu &&diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex cb6c7e88e..7101bb6d1 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -1142,9 +1142,8 @@ class SwarmSearchHints extends StatelessWidget {accept,selected?.isCreate == true? 'new harness'- // The dock title already names the destination. Keep this- // hint short so filtering does not wrap the footer and move- // the input above it on narrow windows.+ // Keep this hint short so filtering does not wrap the+ // footer and move the input above it on narrow windows.: search.placement != null && action == search.primaryAction? 'open': action.toLowerCase(),diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 0eddbef8f..a9e9e8433 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -450,6 +450,8 @@ class WsConn {'agent_read_file_result','project_preview','project_preview_result',+ 'git_project_info',+ 'git_project_info_result','terminal_output','terminal_input','terminal_resize',diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dartindex 6313202de..6e8c7a5b7 100644--- a/desktop/test/box_flows_test.dart+++ b/desktop/test/box_flows_test.dart@@ -99,6 +99,7 @@ void main() {final app = createApp();seedMixedAgents(app);app.machineStates['m']!.localOnly = true;+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};app.adoptSessionForTest(terminal('a0', []));addTearDown(app.dispose);final previous = FileSelectorPlatform.instance;diff --git a/desktop/test/box_render_preview_test.dart b/desktop/test/box_render_preview_test.dartindex bf47c0946..0fe193fcb 100644--- a/desktop/test/box_render_preview_test.dart+++ b/desktop/test/box_render_preview_test.dart@@ -118,7 +118,7 @@ class _PreviewConnection extends WsConn {////// BOX_RENDER_DIR=/tmp/box flutter test --update-goldens \\/// test/box_render_preview_test.dart-Future<void> _loadFonts() async {+Future<void> loadPreviewFonts() async {Future<void> load(String family, List<String> files) async {final loader = FontLoader(family);var any = false;@@ -178,7 +178,7 @@ void main() {skip: dir == null,variant: TargetPlatformVariant.only(TargetPlatform.macOS),(tester) async {- await tester.runAsync(_loadFonts);+ await tester.runAsync(loadPreviewFonts);// Tests draw shadows as solid black slabs; a picture wants the real thing.debugDisableShadows = false;newHarnessOpensInBox = true;@@ -246,7 +246,7 @@ void main() {await shot('06-launch-large-text');tester.view.physicalSize = const Size(1280, 800);tester.platformDispatcher.clearTextScaleFactorTestValue();- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.pump();await type(line, '');await shot('07-new-tab-task-empty');@@ -411,7 +411,7 @@ void main() {.controller;largeBox.setFolder('/work/payments');await shot('15-create-large-text');- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.pump();await shot('15-task-large-text');await tester.sendKeyEvent(LogicalKeyboardKey.escape);diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dartindex 61041a7d8..e01f2df3f 100644--- a/desktop/test/command_dock_interaction_test.dart+++ b/desktop/test/command_dock_interaction_test.dart@@ -63,7 +63,6 @@ void main() {(1, 'agent', NewHarnessField.agent),(2, 'machine', NewHarnessField.machine),(3, 'project', NewHarnessField.projectMenu),- (4, 'task', NewHarnessField.task),]) {for (var i = 0; i < steps; i++) {await key(tester, LogicalKeyboardKey.arrowDown);@@ -75,9 +74,9 @@ void main() {highlighted('create');}await key(tester, LogicalKeyboardKey.arrowUp);- highlighted('placement');+ highlighted('worktree');await key(tester, LogicalKeyboardKey.arrowUp);- highlighted('task');+ highlighted('project');expect(find.byKey(const ValueKey('new-harness-field-options')),findsNothing,@@ -139,7 +138,7 @@ void main() {.controller;final original = box.project;final input = find.byKey(const ValueKey('new-harness-input'));- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.enterText(input, 'Inspect the project');await key(tester, LogicalKeyboardKey.escape);await openLaunchRow(tester, 'machine');@@ -401,9 +400,7 @@ void main() {},);- testWidgets('Pi keeps a task row and explains its launch limitation', (- tester,- ) async {+ testWidgets('Pi and Codex both use the compact launch form', (tester) async {final app = createApp();seedMixedAgents(app);addTearDown(app.dispose);@@ -416,26 +413,21 @@ void main() {.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;final input = find.byKey(const ValueKey('new-harness-input'));- await openLaunchRow(tester, 'agent');- await tester.enterText(input, 'Pi');- box.accept(box.options.firstWhere((row) => row.id == 'pi'));- await tester.pump();- expect(- find.byKey(const ValueKey('new-harness-field-task')),- findsOneWidget,- );- expect(find.text('Enter a task in Pi after launch'), findsOneWidget);- await openLaunchRow(tester, 'task');- expect(box.error, contains('not supported yet'));- expect(box.field, NewHarnessField.launch);- await openLaunchRow(tester, 'agent');- await tester.enterText(input, 'Codex');- await key(tester, LogicalKeyboardKey.enter);- await openLaunchRow(tester, 'task');- expect(box.field, NewHarnessField.task);- await tester.enterText(input, 'Make a product video');- await key(tester, LogicalKeyboardKey.escape);- expect(box.task, 'Make a product video');+ for (final agent in ['pi', 'codex']) {+ await openLaunchRow(tester, 'agent');+ await tester.enterText(input, agent);+ box.accept(box.options.firstWhere((row) => row.id == agent));+ await tester.pump();+ expect(+ find.byKey(const ValueKey('new-harness-field-task')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('new-harness-field-placement')),+ findsNothing,+ );+ expect(find.text('Start Harness'), findsOneWidget);+ }await tester.pumpWidget(const SizedBox());});@@ -473,7 +465,7 @@ void main() {await key(tester, LogicalKeyboardKey.enter);expect(box.engine, 'opencode');expect(box.field, NewHarnessField.launch);- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.enterText(input, 'a project to open');await key(tester, LogicalKeyboardKey.escape);expect(box.task, 'a project to open');@@ -553,7 +545,7 @@ void main() {await key(tester, LogicalKeyboardKey.keyP, cmd: true);final input = find.byKey(const ValueKey('swarm-search-input'));final preview = find.byKey(const ValueKey('swarm-search-preview'));- expect(find.text('· Feature work'), findsOneWidget);+ expect(find.text('· Feature work'), findsNothing);// The create row already explains itself; only real agents need preview.expect(preview, findsNothing);await tester.enterText(input, 'Agent 1');diff --git a/desktop/test/git_worktree_failures_test.dart b/desktop/test/git_worktree_failures_test.dartnew file mode 100644index 000000000..11ca18214--- /dev/null+++ b/desktop/test/git_worktree_failures_test.dart@@ -0,0 +1,212 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/git_worktree.dart';+import 'package:harness/core/repository_clone.dart';++class _DiscardInput implements StreamConsumer<List<int>> {+ @override+ Future<void> addStream(Stream<List<int>> stream) => stream.drain<void>();+ @override+ Future<void> close() async {}+}++class _GitProcess implements Process {+ _GitProcess({String output = '', int? code = 0, List<int>? bytes})+ : stdout = Stream.value(bytes ?? utf8.encode(output)) {+ if (code != null) ended.complete(code);+ }+ final ended = Completer<int>();+ final signals = <ProcessSignal>[];+ @override+ final Stream<List<int>> stdout;+ @override+ Stream<List<int>> get stderr => const Stream.empty();+ @override+ final stdin = IOSink(_DiscardInput());+ @override+ Future<int> get exitCode => ended.future;+ @override+ int get pid => 1;+ @override+ bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {+ signals.add(signal);+ if (!ended.isCompleted) ended.complete(-9);+ return true;+ }+}++GitProcessStarter _commands({String? fail, String prefix = ''}) =>+ (arguments, environment) async {+ final command = arguments.skip(3).join(' ');+ if (fail != null && command.startsWith(fail)) {+ return _GitProcess(code: 1);+ }+ return _GitProcess(+ output: switch (command) {+ 'rev-parse --show-toplevel' => '/repo\n',+ 'rev-parse --show-prefix' => prefix,+ 'symbolic-ref --quiet HEAD' => 'refs/heads/main\n',+ _ => '0123456789\n',+ },+ );+ };++void main() {+ test('Git command failures stay distinct from folders without Git', () async {+ for (final code in [1, 128]) {+ expect(+ await readLocalGitProject(+ '/repo',+ startProcess: (_, _) async => _GitProcess(code: code),+ ),+ code == 128 ? {'isGit': false} : {'error': 'GIT_UNAVAILABLE'},+ );+ }+ expect(+ await readLocalGitProject(+ '/repo',+ startProcess: (_, _) => throw const ProcessException('git', []),+ ),+ {'error': 'GIT_UNAVAILABLE'},+ );+ expect(+ await readLocalGitProject(+ '/repo',+ startProcess: _commands(fail: 'for-each-ref'),+ ),+ {'error': 'GIT_UNAVAILABLE'},+ );+ });++ test(+ 'Git reads receive one literal path and a noninteractive environment',+ () async {+ final calls = <List<String>>[];+ await readLocalGitProject(+ '/repo with spaces',+ startProcess: (arguments, environment) async {+ calls.add(arguments);+ expect(arguments.take(3), [+ '--no-optional-locks',+ '-C',+ '/repo with spaces',+ ]);+ expect(environment['GIT_TERMINAL_PROMPT'], '0');+ expect(environment['GIT_OPTIONAL_LOCKS'], '0');+ expect(environment['GCM_INTERACTIVE'], 'Never');+ for (final key in [+ 'GIT_DIR',+ 'GIT_WORK_TREE',+ 'GIT_COMMON_DIR',+ 'GIT_INDEX_FILE',+ 'GIT_NAMESPACE',+ 'GIT_PREFIX',+ ]) {+ expect(environment.containsKey(key), false);+ }+ return _GitProcess(output: '/repo with spaces\n');+ },+ );+ expect(calls, hasLength(3));+ expect(+ calls.any((args) => args.contains('switch') || args.contains('fetch')),+ false,+ );+ },+ );++ test('excessive Git output is bounded and the process is killed', () async {+ final process = _GitProcess(bytes: Uint8List(1024 * 1024 + 1));+ expect(+ await readLocalGitProject('/repo', startProcess: (_, _) async => process),+ {'error': 'GIT_UNAVAILABLE'},+ );+ expect(process.signals, [ProcessSignal.sigkill]);+ });++ test('a stalled Git read is killed at its deadline', () async {+ final process = _GitProcess(code: null);+ final result = readLocalGitProject(+ '/repo',+ startProcess: (_, _) async => process,+ );+ expect(await result, {'error': 'GIT_UNAVAILABLE'});+ expect(process.signals, [ProcessSignal.sigkill]);+ });++ test(+ 'failed worktree creation leaves its allocated folder for recovery',+ () async {+ final root = await Directory.systemTemp.createTemp('git-recovery-test-');+ addTearDown(() => root.delete(recursive: true));+ await expectLater(+ prepareGitProject(+ '/repo',+ root.path,+ worktree: true,+ label: 'Codex',+ startProcess: _commands(fail: 'worktree add'),+ ),+ throwsA(+ isA<RepositoryCloneException>().having(+ (e) => e.message,+ 'message',+ contains('Could not create the worktree at'),+ ),+ ),+ );+ final parent = Directory('${root.path}/worktrees');+ expect(+ await parent.list().where((entity) => entity is Directory).length,+ 1,+ );+ },+ );++ test('preparation rejects invalid sources, stale refs and unreadable project paths', () async {+ for (final (source, ref, failure) in [+ ('relative', null, null),+ ('/repo', '--help', null),+ ('/repo', null, 'rev-parse --show-toplevel'),+ ('/repo', 'refs/heads/missing', 'show-ref'),+ ('/repo', null, 'rev-parse --verify'),+ ('/repo', null, 'rev-parse --show-prefix'),+ ]) {+ await expectLater(+ prepareGitProject(+ source,+ '/unused',+ worktree: true,+ branchRef: ref,+ label: 'Codex',+ startProcess: _commands(fail: failure),+ ),+ throwsA(isA<RepositoryCloneException>()),+ );+ }+ await expectLater(+ prepareGitProject(+ '/repo/sub',+ '/unused',+ worktree: true,+ label: 'Codex',+ startProcess: _commands(prefix: 'sub/'),+ ),+ throwsA(isA<RepositoryCloneException>()),+ );+ await expectLater(+ prepareGitProject(+ '/repo',+ '/unused',+ worktree: false,+ label: 'Codex',+ startProcess: _commands(),+ ),+ throwsA(isA<RepositoryCloneException>()),+ );+ });+}diff --git a/desktop/test/git_worktree_test.dart b/desktop/test/git_worktree_test.dartnew file mode 100644index 000000000..b82e847b9--- /dev/null+++ b/desktop/test/git_worktree_test.dart@@ -0,0 +1,153 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/git_worktree.dart';+import 'package:harness/core/project_folder.dart';+import 'package:harness/core/repository_clone.dart';+import 'package:path/path.dart' as p;++void main() {+ late Directory root;+ late String repo;+ Future<String> git(List<String> args, [String? folder]) async {+ final result = await Process.run('git', ['-C', folder ?? repo, ...args]);+ expect(result.exitCode, 0, reason: '${args.join(' ')}: ${result.stderr}');+ return (result.stdout as String).trim();+ }++ setUp(() async {+ root = await Directory.systemTemp.createTemp('harness-git-test-');+ repo = p.join(root.path, 'project with spaces');+ await Directory(p.join(repo, 'src')).create(recursive: true);+ await git(['init', '-b', 'main']);+ await git(['config', 'user.name', 'Test']);+ await git(['config', 'user.email', '[email protected]']);+ await git(['config', 'commit.gpgsign', 'false']);+ await git(['config', 'core.hooksPath', '/dev/null']);+ await File(p.join(repo, 'src', 'value')).writeAsString('main');+ await git(['add', '.']);+ await git(['commit', '-m', 'initial']);+ await git(['switch', '-c', 'feature']);+ await File(p.join(repo, 'src', 'value')).writeAsString('feature');+ await git(['commit', '-am', 'feature']);+ await git(['update-ref', 'refs/remotes/origin/feature', 'HEAD']);+ await git([+ 'symbolic-ref',+ 'refs/remotes/origin/HEAD',+ 'refs/remotes/origin/feature',+ ]);+ await git(['switch', 'main']);+ });+ tearDown(() => root.delete(recursive: true));+ Future<String> worktree({+ String ref = 'refs/heads/feature',+ String? folder,+ }) => ProjectFolderRequest.worktree(folder ?? repo, branchRef: ref)+ .prepareLocal(+ projectHome: p.join(root.path, 'harnesses'),+ label: 'Codex',+ now: () => DateTime(2026, 9, 21, 12),+ );++ test(+ 'local Git discovery is read only and excludes symbolic remote refs',+ () async {+ final info = GitProjectInfo.fromJson(await readLocalGitProject(repo));+ expect(info.isGit, isTrue);+ expect(info.branch, 'main');+ expect(info.branches.map((branch) => branch.name), [+ 'feature',+ 'main',+ 'origin/feature',+ ]);+ expect(info.branches.last.remote, isTrue);+ expect(await git(['branch', '--show-current']), 'main');+ expect((await readLocalGitProject(root.path))['isGit'], false);+ expect((await readLocalGitProject('relative'))['error'], 'INVALID_PATH');+ },+ );++ test('concurrent worktrees use the selected ref, new branches, and preserve dirty source files', () async {+ await File(p.join(repo, 'src', 'value')).writeAsString('keep my work');+ final paths = await Future.wait([+ worktree(),+ worktree(ref: 'refs/remotes/origin/feature'),+ ]);+ expect(paths.toSet(), hasLength(2));+ final branches = <String>{};+ for (final path in paths) {+ expect(+ await File(p.join(path, 'src', 'value')).readAsString(),+ 'feature',+ );+ final branch = await git(['branch', '--show-current'], path);+ expect(branch, startsWith('harness/'));+ branches.add(branch);+ }+ expect(branches, hasLength(2));+ expect(+ await File(p.join(repo, 'src', 'value')).readAsString(),+ 'keep my work',+ );+ expect(await git(['branch', '--show-current']), 'main');+ });++ test(+ 'a subfolder follows the selected branch into its new worktree',+ () async {+ final path = await worktree(folder: p.join(repo, 'src'));+ expect(await File(p.join(path, 'value')).readAsString(), 'feature');+ await Directory(p.join(repo, 'untracked')).create();+ await expectLater(+ worktree(folder: p.join(repo, 'untracked')),+ throwsA(isA<RepositoryCloneException>()),+ );+ },+ );++ test('branch switching protects dirty changes and branches checked out elsewhere', () async {+ Future<String> switchTo(String branch) => ProjectFolderRequest.branch(+ repo,+ 'refs/heads/$branch',+ ).prepareLocal(projectHome: root.path);+ expect(await switchTo('feature'), repo);+ await File(p.join(repo, 'src', 'value')).writeAsString('keep this');+ await expectLater(+ switchTo('main'),+ throwsA(isA<RepositoryCloneException>()),+ );+ expect(+ await File(p.join(repo, 'src', 'value')).readAsString(),+ 'keep this',+ );+ expect(await git(['branch', '--show-current']), 'feature');+ expect(await git(['stash', 'list']), isEmpty);+ expect(await switchTo('feature'), repo);+ await git(['worktree', 'add', p.join(root.path, 'other'), 'main']);+ await expectLater(+ switchTo('main'),+ throwsA(isA<RepositoryCloneException>()),+ );+ });++ test('missing branches and revision expressions cannot silently select another commit', () async {+ for (final ref in [+ 'refs/heads/missing',+ 'refs/heads/main~0',+ 'refs/heads/main^{commit}',+ ]) {+ await expectLater(+ worktree(ref: ref),+ throwsA(isA<RepositoryCloneException>()),+ );+ }+ final empty = await Directory(p.join(root.path, 'empty')).create();+ await git(['init', '-b', 'main'], empty.path);+ expect((await readLocalGitProject(empty.path))['isGit'], true);+ await expectLater(+ ProjectFolderRequest.worktree(empty.path)+ .prepareLocal(projectHome: root.path),+ throwsA(isA<RepositoryCloneException>()),+ );+ });+}diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dartindex dde7aa399..9ab51bdde 100644--- a/desktop/test/harness_placement_test.dart+++ b/desktop/test/harness_placement_test.dart@@ -887,7 +887,7 @@ void main() {.controller;expect(box.task, isEmpty);expect(box.checking, isTrue);- expect(find.text('pending harness'), findsOneWidget);+ expect(find.text('pending harness'), findsNothing);expect(find.textContaining('check status', findRichText: true),findsOneWidget,@@ -945,7 +945,7 @@ void main() {await tester.pump();expect(app.swarms, contains(original));expect(app.swarms.length, placement == HarnessPlacement.newTab ? 2 : 1);- expect(find.text(placement.title), findsWidgets);+ expect(find.text(placement.title), findsNothing);await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();expect(app.swarms, [original]);diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dartindex d9bce598b..e354ad480 100644--- a/desktop/test/harness_store_entry_test.dart+++ b/desktop/test/harness_store_entry_test.dart@@ -171,7 +171,7 @@ void main() {.controller;box.setFolder('/work/project');await tester.pump();- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.enterText(input, 'Finish the login feature');await tester.pump();final draft = box.draft;diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dartindex 42b6f00a9..2c44d5e83 100644--- a/desktop/test/new_harness_box_test.dart+++ b/desktop/test/new_harness_box_test.dart@@ -63,6 +63,7 @@ class _Connection extends WsConn {if (type == 'engines_probe') return {'engines': []};if (type == 'dsh_list') return {'dsh': []};if (type == 'fs_list_dir') return {};+ if (type == 'git_project_info') return {'isGit': false};calls.add(_Request(type, Map.of(payload)));if (type == 'agent_create' && createFailure != null) {return {@@ -211,8 +212,8 @@ void main() {box.setQuery('fix the flaky login test');expect(box.task, 'fix the flaky login test');expect(box.returnCreates, isTrue);- // Tab steps out to who; the task is kept, and is back on the way round.- box.nextField();+ // Carried tasks survive navigation without appearing in the launch loop.+ box.focusField(NewHarnessField.agent);expect(box.field, NewHarnessField.agent);expect(box.query, isEmpty);// The highlight opens on the line's own answer, which wears the ✓. In a@@ -221,11 +222,11 @@ void main() {expect(box.isCurrent(box.selected!), isTrue);expect(box.returnCreates, isFalse);box.nextField(-1);- expect(box.field, NewHarnessField.task);- expect(box.query, 'fix the flaky login test');+ expect(box.field, NewHarnessField.projectMenu);+ expect(box.task, 'fix the flaky login test');});- test('the main loop follows Agent, Project, Task and modes remain available to advanced drafts', () {+ test('the main loop follows Agent, Machine, Project and modes remain available to advanced drafts', () {final app = createApp();final box = NewHarnessController(app, machineId: 'm', engine: 'claude');addTearDown(box.dispose);@@ -233,7 +234,6 @@ void main() {NewHarnessField.agent,NewHarnessField.machine,NewHarnessField.projectMenu,- NewHarnessField.task,]);box.focusField(NewHarnessField.mode);expect(box.options.where(box.isCurrent).single.id, 'auto');@@ -820,7 +820,7 @@ void main() {await tester.pump();expect(box.engine, 'claude');expect(box.field, NewHarnessField.launch);- await openLaunchRow(tester, 'task');+ await openLegacyTaskEditor(tester);await tester.pump();await tester.enterText(input, 'a project to test');await tester.sendKeyEvent(LogicalKeyboardKey.escape);diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dartindex bbdad77a5..a07d9de71 100644--- a/desktop/test/new_harness_entry_rules_test.dart+++ b/desktop/test/new_harness_entry_rules_test.dart@@ -173,7 +173,7 @@ void main() {LogicalKeyboardKey.keyT,]) {testWidgets(- '${shortcut.keyLabel} defaults Open in correctly and lets users change it',+ '${shortcut.keyLabel} starts a pane with no extra launch controls',(tester) async {await mount(tester, store: false);final origin = app.activeSwarm;@@ -186,59 +186,28 @@ void main() {? HarnessPlacement.newTab: HarnessPlacement.currentTab;expect(controller.placement, initial);- final placement = find.byKey(- const ValueKey('new-harness-field-placement'),- );- expect(placement.hitTestable(), findsOneWidget);- expect(- tester.getTopLeft(placement).dy,- greaterThan(- tester- .getTopLeft(- find.byKey(const ValueKey('new-harness-field-task')),- )- .dy,- ),- );- expect(- tester.getTopLeft(placement).dy,- lessThan(- tester- .getTopLeft(- find.byKey(const ValueKey('new-harness-field-create')),- )- .dy,- ),- );- final choice = initial == HarnessPlacement.newTab- ? HarnessPlacement.currentTab- : HarnessPlacement.newTab;- await key(tester, LogicalKeyboardKey.arrowUp);- await key(tester, LogicalKeyboardKey.enter);- expect(controller.placement, choice);- expect(- find.descendant(of: placement, matching: find.text(choice.title)),- findsOneWidget,- );- await key(tester, LogicalKeyboardKey.enter);- expect(controller.placement, initial);- await tester.tap(placement);- await tester.pump();- expect(controller.placement, choice);- expect(- find.descendant(of: placement, matching: find.text(choice.title)),- findsOneWidget,- );+ for (final removed in ['task', 'placement']) {+ expect(+ find.byKey(ValueKey('new-harness-field-$removed')),+ findsNothing,+ );+ }+ expect(find.text('New Harness'), findsNothing);+ expect(find.text('Start Harness'), findsOneWidget);expect(connections['m']!.starts, isEmpty);- await key(tester, LogicalKeyboardKey.arrowDown);await key(tester, LogicalKeyboardKey.enter);expect(connections['m']!.starts, hasLength(1));connections['m']!.created();await tester.pump();await tester.pump(const Duration(milliseconds: 200));- expect(app.swarms.length, 2);- expect(origin.panes.single.agentId, 'a0');- expect(app.activeSwarm.panes.single.agentId, 'created-1');+ if (shortcut == LogicalKeyboardKey.keyT) {+ expect(app.swarms.length, 2);+ expect(origin.panes.single.agentId, 'a0');+ expect(app.activeSwarm.panes.single.agentId, 'created-1');+ } else {+ expect(app.activeSwarm, same(origin));+ expect(origin.panes.map((pane) => pane.agentId), ['a0', 'created-1']);+ }await tester.pumpWidget(const SizedBox());},);@@ -495,7 +464,7 @@ void main() {const TextSelection(baseOffset: 6, extentOffset: 18),);expect(updated.focusNode.hasFocus, isTrue);- expect(find.text(nextTab ? 'New Tab' : 'New Pane'), findsOneWidget);+ expect(find.text(nextTab ? 'New Tab' : 'New Pane'), findsNothing);expect(app.swarms.first, same(origin));expect(app.swarms.length, newTab || nextTab ? 2 : 1);await key(tester, LogicalKeyboardKey.enter);diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dartnew file mode 100644index 000000000..e01ff03e7--- /dev/null+++ b/desktop/test/new_harness_git_test.dart@@ -0,0 +1,469 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/e2ee/envelope.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/widgets/new_harness_box.dart';+import 'package:harness/ws/ws_conn.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/launch_menu.dart';+import 'swarm_state_test.dart' show createApp;++const _git = <String, dynamic>{+ 'isGit': true,+ 'branch': 'main',+ 'branches': [+ {'ref': 'refs/heads/main', 'name': 'main'},+ {'ref': 'refs/heads/feature', 'name': 'feature'},+ {'ref': 'refs/remotes/origin/main', 'name': 'origin/main', 'remote': true},+ ],+};++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final starts = <Map<String, dynamic>>[];+ final reads = <String>[];+ final pending = <String, Completer<Map<String, dynamic>>>{};+ Map<String, dynamic>? failure;+ bool loseReply = false;+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type == 'git_project_info') {+ final path = payload['path'] as String;+ reads.add(path);+ return pending[path]?.future ??+ Future.value(path == '/plain' ? {'isGit': false} : _git);+ }+ if (type == 'engines_probe') return {'engines': []};+ if (type == 'dsh_list') return {'dsh': []};+ if (type == 'fs_list_dir') return {'path': '/home/user', 'entries': []};+ if (type == 'agent_create') {+ starts.add(Map.of(payload));+ if (loseReply) {+ loseReply = false;+ throw const WsRequestTimeout('agent_create');+ }+ if (failure != null) {+ return {+ 'creationId': payload['creationId'],+ 'state': 'failed',+ ...failure!,+ };+ }+ }+ if (type == 'agent_create' || type == 'agent_create_status') {+ return {+ 'creationId': payload['creationId'],+ 'state': 'created',+ 'agent': {+ 'id': 'created',+ 'name': 'Created',+ 'engine': 'codex',+ 'project': {'cwd': payload['cwd'] ?? '/worktrees/new'},+ },+ };+ }+ return {};+ }+}++void main() {+ test(+ 'Git metadata uses encrypted requests on clients without a local CLI',+ () {+ expect(encryptedDownTypes, contains('git_project_info'));+ },+ );++ Future<void> settle() => Future<void>.delayed(Duration.zero);+ test('Git defaults follow the project, late replies are ignored, and draft choices survive', () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ expect(box.worktree, true);+ expect(box.branchRef, 'refs/heads/main');+ expect(box.draft.projectFolderRequest!.payload, {+ 'projectSource': 'worktree',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/main',+ });+ box.toggleWorktree();+ expect(box.worktree, false);+ box.focusField(NewHarnessField.branch);+ box.setQuery('feature');+ box.accept();+ expect(box.projectFolderRequest!.payload, {+ 'projectSource': 'branch',+ 'gitSource': '/repo',+ 'branchRef': 'refs/heads/feature',+ });+ final restored = NewHarnessController(+ app,+ machineId: 'm',+ draft: box.draft,+ );+ addTearDown(restored.dispose);+ await settle();+ expect(restored.worktree, false);+ expect(restored.branchLabel, 'feature');+ expect(+ restored.projectFolderRequest!.payload,+ box.draft.projectFolderRequest!.payload,+ );+ final slow = connection.pending['/slow'] = Completer();+ box.setFolder('/slow');+ box.setFolder('/plain');+ await settle();+ expect(box.worktree, false);+ expect(box.isGitProject, false);+ slow.complete(_git);+ await settle();+ expect(box.isGitProject, false);+ box.setFolder('/repo');+ await settle();+ expect(+ box.worktree,+ true,+ reason: 'Each Git project starts with Worktree on.',+ );+ expect(box.branchRef, 'refs/heads/main');+ });++ test('one Start waits for Git detection and lost replies reuse the original receipt', () async {+ final connection = _Connection()..loseReply = true;+ final ready = connection.pending['/repo'] = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ final starting = box.create();+ expect(box.busy, true);+ expect(connection.starts, isEmpty);+ ready.complete(_git);+ expect(await starting, NewHarnessOutcome.failed);+ expect(box.checking, true);+ expect(connection.starts.single, containsPair('projectSource', 'worktree'));+ final restored = NewHarnessController(+ app,+ machineId: 'm',+ draft: box.draft,+ );+ addTearDown(restored.dispose);+ expect(await restored.create(), NewHarnessOutcome.created);+ expect(connection.starts, hasLength(1));+ expect(connection.reads, ['/repo']);+ });++ test('a refused launch reuses its prepared worktree on retry', () async {+ final connection = _Connection()+ ..failure = {+ 'preparedFolder': '/prepared',+ 'failure': {'code': 'TMUX_UNAVAILABLE'},+ };+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ expect(await box.create(), NewHarnessOutcome.failed);+ await settle();+ expect(box.project.folder, '/prepared');+ expect(box.worktree, false);+ connection.failure = null;+ expect(await box.create(), NewHarnessOutcome.created);+ expect(connection.starts, hasLength(2));+ expect(connection.starts.last['projectSource'], 'branch');+ expect(connection.starts.last['gitSource'], '/prepared');+ });++ testWidgets(+ 'compact launch, checkbox controls, hover selection, branch search and Cmd-Enter start',+ (tester) async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/home/user/code/autonomous-harness',+ );+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 680,+ height: 440,+ child: NewHarnessBox(+ controller: box,+ onClose: () {},+ onCreated: () {},+ onNeedsForm: () {},+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(find.text('New Harness'), findsNothing);+ expect(find.text('Start Harness'), findsOneWidget);+ for (final name in ['task', 'placement']) {+ expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);+ }+ expect(find.text('[x]'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);+ await tester.sendKeyEvent(LogicalKeyboardKey.space);+ await tester.pump();+ expect(box.worktree, false);+ expect(find.text('[ ]'), findsOneWidget);+ await tester.tap(+ find.byKey(const ValueKey('new-harness-field-worktree')),+ );+ await tester.pump();+ expect(find.text('[x]'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(box.worktree, false);+ final branchRow = find.byKey(const ValueKey('new-harness-field-branch'));+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(branchRow));+ await mouse.moveBy(const Offset(4, 0));+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(box.field, NewHarnessField.branch);+ await mouse.removePointer();+ expect(box.options.where(box.isCurrent).single.title, 'main');+ expect(+ box.options.firstWhere((row) => row.title == 'origin/main').enabled,+ false,+ );+ final input = find.byKey(const ValueKey('new-harness-input'));+ await tester.enterText(input, 'feature');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(box.branchLabel, 'feature');+ expect(connection.starts, isEmpty);+ await openLaunchRow(tester, 'worktree');+ expect(box.worktree, true);+ await openLaunchRow(tester, 'branch');+ await tester.enterText(input, 'origin/main');+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pump();+ expect(+ connection.starts.single,+ containsPair('branchRef', 'refs/remotes/origin/main'),+ );+ expect(connection.starts.single['projectSource'], 'worktree');+ expect(connection.starts.single.containsKey('prompt'), false);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ box.dispose();+ app.dispose();+ await tester.pump(const Duration(milliseconds: 200));+ },+ );+ testWidgets(+ 'Git errors retry without losing isolation, and advanced options wait for detection',+ (tester) async {+ final connection = _Connection();+ final ready = connection.pending['/repo'] = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ var advanced = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessBox(+ controller: box,+ onClose: () {},+ onCreated: () {},+ onNeedsForm: () => advanced++,+ ),+ ),+ ),+ );+ Future<void> options() async {+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.period);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pump();+ }++ await options();+ expect(advanced, 0);+ ready.complete({'error': 'GIT_UNAVAILABLE'});+ await tester.pump();+ expect(advanced, 0);+ expect(box.error, contains('Retry Worktree'));+ final start = find.byKey(const ValueKey('new-harness-field-create'));+ await tester.tap(start);+ await tester.pump();+ expect(box.error, contains('Could not check Git'));+ expect(connection.starts, isEmpty);+ connection.pending.remove('/repo');+ await tester.tap(+ find.byKey(const ValueKey('new-harness-field-worktree')),+ );+ await tester.pump();+ expect(box.error, isNull);+ expect(box.worktree, true);+ expect(find.text('[x]'), findsOneWidget);+ await options();+ expect(advanced, 1);+ await openLaunchRow(tester, 'branch');+ await tester.enterText(+ find.byKey(const ValueKey('new-harness-input')),+ 'origin/main',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.tap(+ find.byKey(const ValueKey('new-harness-field-worktree')),+ );+ await tester.pump();+ expect(box.worktree, false);+ await tester.tap(start);+ await tester.pump();+ expect(box.error, contains('Choose a local branch'));+ expect(connection.starts, isEmpty);+ await tester.pumpWidget(const SizedBox());+ box.dispose();+ app.dispose();+ await tester.pump(const Duration(milliseconds: 200));+ },+ );++ testWidgets('Git and non-Git launch layouts fit at large text sizes', (+ tester,+ ) async {+ final renderDir = Platform.environment['HARNESS_LAUNCH_RENDER_DIR'];+ if (renderDir != null) await tester.runAsync(loadPreviewFonts);+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/home/user/code/autonomous-harness',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ tester.view.physicalSize = const Size(760, 520);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ for (final scale in [1.0, 1.7]) {+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: ThemeData.dark(),+ home: MediaQuery(+ data: MediaQueryData(textScaler: TextScaler.linear(scale)),+ child: Scaffold(+ backgroundColor: const Color(0xff252525),+ body: Align(+ alignment: Alignment.bottomCenter,+ child: SizedBox(+ width: 720,+ child: NewHarnessBox(+ docked: true,+ controller: box,+ onClose: () {},+ onCreated: () {},+ onNeedsForm: () {},+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(find.text('Start Harness').hitTestable(), findsOneWidget);+ expect(tester.takeException(), isNull);+ if (renderDir != null) {+ await expectLater(+ find.byType(MaterialApp),+ matchesGoldenFile(Uri.file('$renderDir/launch-$scale.png')),+ );+ }+ }+ await openLaunchRow(tester, 'branch');+ expect(+ find.byKey(const ValueKey('new-harness-input')).hitTestable(),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ if (renderDir != null) {+ await expectLater(+ find.byType(MaterialApp),+ matchesGoldenFile(Uri.file('$renderDir/branches.png')),+ );+ }+ box.setFolder('/plain');+ await tester.pump();+ expect(+ find.byKey(const ValueKey('new-harness-field-branch')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('new-harness-field-worktree')),+ findsNothing,+ );+ if (renderDir != null) {+ await expectLater(+ find.byType(MaterialApp),+ matchesGoldenFile(Uri.file('$renderDir/non-git.png')),+ );+ }+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(milliseconds: 200));+ });+}diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dartindex 5ab1f5d83..8e6742176 100644--- a/desktop/test/new_harness_project_context_test.dart+++ b/desktop/test/new_harness_project_context_test.dart@@ -455,7 +455,6 @@ void main() {('agent', NewHarnessField.agent),('machine', NewHarnessField.machine),('project', NewHarnessField.projectMenu),- ('task', NewHarnessField.task),]) {await openLaunchRow(tester, name);await tester.pump();diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dartindex 6c737af04..12891e5f9 100644--- a/desktop/test/support/launch_menu.dart+++ b/desktop/test/support/launch_menu.dart@@ -11,7 +11,13 @@ Future<void> openLaunchRow(WidgetTester tester, String name) async {.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;expect(box.field, NewHarnessField.launch);- final index = ['agent', 'machine', 'project', 'task'].indexOf(name);+ final index = [+ 'agent',+ 'machine',+ 'project',+ if (box.isGitProject) 'branch',+ if (box.canUseWorktree || box.gitError != null) 'worktree',+ ].indexOf(name);expect(index, greaterThanOrEqualTo(0));await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);await tester.pump();@@ -48,3 +54,13 @@ Future<void> openAgentSetting(await tester.pump();await mouse.removePointer();}++/// Exercises compatibility for carried tasks and advanced drafts. Task is no+/// longer a visible launch row.+Future<void> openLegacyTaskEditor(WidgetTester tester) async {+ tester+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))+ .controller+ .focusField(NewHarnessField.task);+ await tester.pump();+}diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dartindex 6101acf4b..17d29e259 100644--- a/desktop/test/swarm_split_test.dart+++ b/desktop/test/swarm_split_test.dart@@ -383,6 +383,7 @@ void main() {addTearDown(() => newHarnessOpensInBox = false);final connection = _Creation();final app = createApp(connectionForTest: (_) => connection);+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};final machine = app.machineStates['m']!;machine.nodeOnline = true;machine.localOnly = true;diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dartindex ad362b49e..30b5690cf 100644--- a/desktop/test/workspace_start_guide_test.dart+++ b/desktop/test/workspace_start_guide_test.dart@@ -170,7 +170,7 @@ void main() {.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;expect(box.detectingAgent, isTrue);- expect(find.text('Start'), findsOneWidget);+ expect(find.text('Start Harness'), findsOneWidget);expect(find.text('Detecting installed agents…'), findsOneWidget);final start = find.byKey(const ValueKey('new-harness-field-create'));expect(tester.widget<InkWell>(start).onTap, isNull);@@ -186,9 +186,12 @@ void main() {await tester.pump();await tester.pump(const Duration(milliseconds: 150));expect(box.engine, 'codex');- expect(find.text('Start'), findsOneWidget);- expect(find.text('New Harness'), findsOneWidget);- expect(find.text('New Tab'), findsOneWidget);+ expect(find.text('Start Harness'), findsOneWidget);+ expect(find.text('New Harness'), findsNothing);+ expect(+ find.byKey(const ValueKey('new-harness-field-placement')),+ findsNothing,+ );await key(tester, LogicalKeyboardKey.enter);await tester.pump();expect(app.launches, hasLength(1));