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
Redesign New Agent around a searchable project picker
dee2b332f27f0e5
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 98cffe110..42a8498ff 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -9,6 +9,7 @@ import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.jsimport { registry, type RegisteredSession } from './lib/registry.js'import * as mediaPreview from './lib/mediaPreview.js'import * as projectFolder from './lib/projectFolder.js'+import * as projectPreview from './lib/projectPreview.js'import { randomUUID } from 'node:crypto'const wsMock = vi.hoisted(() => {@@ -435,6 +436,33 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('returns project previews only to the requesting encrypted connection', async () => {+ vi.spyOn(registry, 'list').mockReturnValue([{ cwd: '/remote/workspace' }] as RegisteredSession[])+ const preview = { path: '/remote/workspace', readme: 'Private project README', branch: 'main', files: ['README.md'], contributors: [] }+ const read = vi.spyOn(projectPreview, 'projectPreview').mockResolvedValue(preview)+ const socket = new BackendSocket('token')+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'project_preview', payload: {+ requestId: 'preview-1', path: '/remote/workspace',+ } })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'project_preview_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ })+ ws.message({ t: 'down', connId: 'viewer-a', frame: {+ type: 'project_preview', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },+ } })+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'project_preview_result', 'preview-1', preview))+ expect(read).toHaveBeenCalledWith('/remote/workspace', ['/remote/workspace'])+ expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {+ type: 'project_preview_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ } }))+ expect(JSON.stringify(parseSent(ws))).not.toContain('Private project README')+ 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,diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex f2d5653a7..1572205fc 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -33,6 +33,7 @@ import { probeEngines } from './lib/engineProbe.js'import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'import { engineInstallRecipe } from './lib/engineInstall.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'+import { projectPreview } from './lib/projectPreview.js'import { agentFrame, type AgentFrame } from './lib/agentFrame.js'import { routeVoiceTask } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'@@ -1008,7 +1009,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 !== 'agent_read_file') logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })+ if (env.LOG_FRAMES && type !== 'agent_read_file' && type !== 'project_preview') 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@@ -1082,7 +1083,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 !== 'agent_read_file') {+ if (env.LOG_FRAMES && !type.startsWith('terminal_') && type !== 'agent_read_file' && type !== 'project_preview') {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)@@ -1735,6 +1736,15 @@ export class BackendSocket {return}+ case 'project_preview': {+ const path = typeof payload.path === 'string' ? payload.path : ''+ // Preview work is detached so typing and other RPCs stay responsive.+ void projectPreview(path, registry.list().flatMap(agent => agent.cwd ? [agent.cwd] : []))+ .then(result => reply(type, requestId, result))+ .catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))+ return+ }+case 'fs_list_dir': {// One-level remote directory listing for the New Agent folder browser.const path = typeof payload.path === 'string' ? payload.path : ''diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex 148df488e..dedefe55a 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -351,7 +351,7 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.'agent_recent_result', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result',// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.- 'fs_list_dir_result',+ 'fs_list_dir_result', 'project_preview_result',// Same reasoning as fs_list_dir_result: reveals Codex profile folder names/paths on this machine.'codex_profiles_list_result', 'codex_profile_link_result',// This machine's Claude/Codex rate limits and a key naming the account — what the person is@@ -372,7 +372,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>(['question_response','agents_list', 'sessions_list', 'session_get', 'models_list','agent_create', 'agent_create_status', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',- 'fs_list_dir', 'codex_profiles_list', 'codex_profile_link',+ 'fs_list_dir', 'project_preview', 'codex_profiles_list', 'codex_profile_link',// Asks this machine to read its own agent accounts' usage (lib/accountUsage.ts). ⚠️ Missing here it// would not fail loudly — the same trap `question_response` once fell into: the payload would stay// an {__e2e} envelope, requestId would read back undefined, and the requester would wait out itsdiff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.tsindex e0955dbbc..8185d8b4e 100644--- a/cli/src/lib/projectFolder.ts+++ b/cli/src/lib/projectFolder.ts@@ -15,7 +15,7 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFolif (payload.projectSource === undefined) return nullif (payload.projectSource === 'new' && payload.repositoryUrl === undefined) return { source: 'new' }if (payload.projectSource !== 'remote' || typeof payload.repositoryUrl !== 'string') {- throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose New, Local, or Remote for the project folder.')+ throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a project.')}const raw = payload.repositoryUrl.trim()let path: string@@ -66,16 +66,16 @@ export async function prepareProjectFolder(}}const destination = join(root, project.name)- if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Choose Local to open that folder.`)+ if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)staging = await mkdtemp(join(root, '.harness-clone-'))const checkout = join(staging, 'checkout')await (options.clone ?? cloneRepository)(project.repositoryUrl, checkout)- if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” was created while cloning. Choose Local to open that folder.`)+ if (await exists(destination)) throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” was created while cloning. Select that folder from your projects.`)await rename(checkout, destination)return destination} catch (error) {if (error instanceof ProjectFolderError) throw error- throw new ProjectFolderError('PROJECT_PREPARATION_FAILED', 'Could not create a project folder on this machine. Choose Local to select a folder you can edit.')+ throw new ProjectFolderError('PROJECT_PREPARATION_FAILED', 'Could not create a project folder on this machine. Browse for a folder you can edit.')} finally {if (staging) await rm(staging, { force: true, recursive: true }).catch(() => {})}diff --git a/cli/src/lib/projectPreview.spec.ts b/cli/src/lib/projectPreview.spec.tsnew file mode 100644index 000000000..c1889afae--- /dev/null+++ b/cli/src/lib/projectPreview.spec.ts@@ -0,0 +1,55 @@+import { execFile } from 'node:child_process'+import { mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { afterEach, beforeEach, expect, it } from 'vitest'+import { env } from '../config/env.js'+import { ENCRYPTED_DOWN_TYPES, ENCRYPTED_RPC_RESULT_TYPES } from './e2ee/core.js'+import { projectPreview } from './projectPreview.js'++const exec = promisify(execFile)+let root: string+const unrestricted = env.HARNESS_FS_BROWSE_UNRESTRICTED+beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'harness-preview-'))+ env.HARNESS_FS_BROWSE_UNRESTRICTED = undefined+})+afterEach(async () => {+ await rm(root, { recursive: true, force: true })+ env.HARNESS_FS_BROWSE_UNRESTRICTED = unrestricted+})+const git = (args: string[]) => exec('git', ['-C', root, ...args])++it('previews existing Git content without running a configured fsmonitor hook', async () => {+ await git(['init', '-b', 'preview'])+ await writeFile(join(root, 'README.md'), '# Project\nExisting content')+ await git(['add', 'README.md'])+ await git(['-c', 'user.name=Preview Author', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-m', 'First commit'])+ await writeFile(join(root, 'README.md'), '# Project\nUpdated content')+ await git(['config', 'core.fsmonitor', `touch ${join(root, 'monitor-ran')}`])+ expect(await projectPreview(root, [root])).toMatchObject({+ readme: '# Project\nUpdated content', branch: 'preview', changedFiles: 1,+ commit: { subject: 'First commit', author: 'Preview Author' }, contributors: ['Preview Author'],+ })+ await expect(readFile(join(root, 'monitor-ran'))).rejects.toMatchObject({ code: 'ENOENT' })+})++it('bounds README reads and does not follow README symlinks', async () => {+ const readme = join(root, 'README.md')+ await writeFile(readme, 'a'.repeat(40000))+ const preview = await projectPreview(root, [root])+ expect('readme' in preview && preview.readme?.length).toBe(32768)+ await rm(readme)+ await writeFile(join(root, 'private.txt'), 'private')+ await symlink(join(root, 'private.txt'), readme)+ expect(await projectPreview(root, [root])).not.toHaveProperty('readme', 'private')+})++it('rejects unscoped paths and keeps remote content inside the encrypted RPC', async () => {+ expect(await projectPreview(root)).toEqual({ error: 'FORBIDDEN' })+ expect(await projectPreview('relative')).toEqual({ error: 'INVALID_PATH' })+ expect(await projectPreview(`${root}\n`, [root])).toEqual({ error: 'INVALID_PATH' })+ expect(ENCRYPTED_DOWN_TYPES.has('project_preview')).toBe(true)+ expect(ENCRYPTED_RPC_RESULT_TYPES.has('project_preview_result')).toBe(true)+})diff --git a/cli/src/lib/projectPreview.ts b/cli/src/lib/projectPreview.tsnew file mode 100644index 000000000..79f585ed4--- /dev/null+++ b/cli/src/lib/projectPreview.ts@@ -0,0 +1,62 @@+import { execFile } from 'node:child_process'+import { open, opendir, realpath, stat } from 'node:fs/promises'+import { constants } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute, join, relative } from 'node:path'+import { promisify } from 'node:util'+import { env } from '../config/env.js'++const exec = promisify(execFile)+const within = (root: string, path: string) => {+ const rel = relative(root, path)+ return rel === '' || (rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel))+}++/** Existing local content only. Paths/README symlinks stay inside the browsable+ * home or an agent's known workspace; all Git commands are read-only/bounded. */+export async function projectPreview(path: string, knownRoots: string[] = []) {+ if (!isAbsolute(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path)) return { error: 'INVALID_PATH' }+ try {+ const target = await realpath(path)+ const roots = await Promise.all([homedir(), ...knownRoots].map(root => realpath(root).catch(() => '')))+ if (env.HARNESS_FS_BROWSE_UNRESTRICTED !== '1' && !roots.some(root => root && within(root, target))) return { error: 'FORBIDDEN' }+ if (!(await stat(target)).isDirectory()) return { error: 'NOT_FOUND' }+ const files: string[] = []+ let readme: string | undefined+ const directory = await opendir(target)+ let seen = 0+ for await (const entry of directory) {+ if (!entry.name.startsWith('.')) files.push(entry.name)+ if (!readme && entry.isFile() && /^readme(?:\.(?:md|markdown|txt))?$/i.test(entry.name)) {+ const file = await open(join(target, entry.name), constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ const buffer = Buffer.alloc(32 * 1024)+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0)+ const bytes = buffer.subarray(0, bytesRead)+ if (!bytes.includes(0)) readme = bytes.toString('utf8')+ } finally { await file.close() }+ }+ if (++seen >= 200) break+ }+ const git = async (args: string[]) => {+ try {+ return (await exec('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', target, ...args], {+ timeout: 2000, maxBuffer: 32 * 1024,+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },+ })).stdout.trim()+ } catch { return undefined }+ }+ const [branch, status, last, authors] = await Promise.all([+ git(['symbolic-ref', '--quiet', '--short', 'HEAD']),+ git(['status', '--porcelain=v1', '--untracked-files=no']),+ git(['log', '-1', '--format=%s%n%an%n%aI']),+ git(['log', '-100', '--format=%an']),+ ])+ const commit = last?.split('\n')+ return { path: target, readme, files: files.sort().slice(0, 12), branch,+ ...(status !== undefined ? { changedFiles: status ? status.split('\n').length : 0 } : {}),+ ...(commit && commit.length >= 3 ? { commit: { subject: commit[0], author: commit[1], date: commit[2] } } : {}),+ contributors: authors ? [...new Set(authors.split('\n'))].slice(0, 5) : [],+ }+ } catch { return { error: 'UNREADABLE' } }+}diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dartindex 8a1801518..026680ee7 100644--- a/desktop/lib/core/project_folder.dart+++ b/desktop/lib/core/project_folder.dart@@ -26,7 +26,7 @@ class ProjectFolderRequest {Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];if (projectHome == null && (home == null || !p.isAbsolute(home))) {throw const RepositoryCloneException(- 'Could not find your home folder. Choose Local to select a folder.',+ 'Could not find your home folder. Browse for a folder.',);}final root = Directory(projectHome ?? p.join(home!, 'harnesses'));@@ -61,11 +61,11 @@ class ProjectFolderRequest {}} on FileSystemException {throw const RepositoryCloneException(- 'Could not create a project folder. Choose Local to select a folder you can edit.',+ 'Could not create a project folder. Browse for a folder you can edit.',);} on ProcessException {throw const RepositoryCloneException(- 'Could not create a project folder. Choose Local to select a folder you can edit.',+ 'Could not create a project folder. Browse for a folder you can edit.',);}}diff --git a/desktop/lib/core/project_history.dart b/desktop/lib/core/project_history.dartnew file mode 100644index 000000000..f8ec6adeb--- /dev/null+++ b/desktop/lib/core/project_history.dart@@ -0,0 +1,78 @@+import 'dart:convert';++import 'local_key_value_store.dart';++/// Recent choices are scoped to the machine that owns their paths.+class ProjectHistory {+ ProjectHistory(this._storage);+ final LocalKeyValueStore? _storage;+ static const _key = 'new_agent_projects_v1';+ final _recent = <String, List<String>>{};+ final _selected = <String, String?>{};+ Future<void>? _loading;+ Future<void> _saving = Future.value();+ int _revision = 0;++ List<String> recent(String machine) =>+ List.unmodifiable(_recent[machine] ?? []);+ bool hasSelection(String machine) => _selected.containsKey(machine);+ String? selected(String machine) => _selected[machine];++ Future<void> load() => _loading ??= _load();+ Future<void> _load() async {+ final revision = _revision;+ try {+ final raw = await _storage?.read(_key);+ if (raw == null || _revision != revision) return;+ final decoded = jsonDecode(raw);+ if (decoded is! Map) return;+ for (final entry in decoded.entries.take(64)) {+ if (entry.key is! String || entry.value is! Map) continue;+ final value = entry.value as Map;+ final paths = value['recent'];+ if (paths is List) {+ _recent[entry.key] = paths+ .whereType<String>()+ .where(_valid)+ .take(40)+ .toSet()+ .toList();+ }+ if (value['selected'] == null ||+ value['selected'] is String && _valid(value['selected'])) {+ _selected[entry.key] = value['selected'];+ }+ }+ } catch (_) {+ // A missing preference never blocks creation.+ }+ }++ static bool _valid(String path) =>+ path.startsWith('/') &&+ path.length <= 4096 &&+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(path);++ Future<void> select(String machine, String? path) async {+ await load();+ if (path != null && !_valid(path)) return;+ _revision++;+ _selected[machine] = path;+ if (path != null) {+ _recent[machine] = [+ path,+ ...?_recent[machine]?.where((item) => item != path),+ ].take(40).toList();+ }+ final snapshot = jsonEncode({+ for (final id in _selected.keys.toList().reversed.take(64))+ id: {'selected': _selected[id], 'recent': _recent[id] ?? []},+ });+ _saving = _saving.then((_) async {+ try {+ await _storage?.write(_key, snapshot);+ } catch (_) {}+ });+ await _saving;+ }+}diff --git a/desktop/lib/core/project_preview.dart b/desktop/lib/core/project_preview.dartnew file mode 100644index 000000000..35d534d8d--- /dev/null+++ b/desktop/lib/core/project_preview.dart@@ -0,0 +1,118 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:path/path.dart' as p;++/// Read-only, bounded source material for a project preview. Never executes+/// project code, hooks, Markdown images or a Git network operation.+Future<Map<String, dynamic>> readLocalProjectPreview(String path) async {+ if (!p.isAbsolute(path) || path.length > 4096 || path.contains('\u0000')) {+ return {'error': 'INVALID_PATH'};+ }+ try {+ if (!await Directory(path).exists()) return {'error': 'NOT_FOUND'};+ final files = <String>[];+ String? readme;+ var seen = 0;+ await for (final entity in Directory(path).list(followLinks: false)) {+ final name = p.basename(entity.path);+ if (!name.startsWith('.')) files.add(name);+ if (readme == null &&+ RegExp(+ r'^readme(?:\.(?:md|markdown|txt))?$',+ caseSensitive: false,+ ).hasMatch(name) &&+ entity is File) {+ final file = await entity.open();+ try {+ final bytes = await file.read(32 * 1024);+ if (!bytes.contains(0)) {+ readme = utf8.decode(bytes, allowMalformed: true);+ }+ } finally {+ await file.close();+ }+ }+ if (++seen >= 200) break;+ }+ files.sort();+ final git = await Future.wait([+ _git(path, ['symbolic-ref', '--quiet', '--short', 'HEAD']),+ _git(path, ['status', '--porcelain=v1', '--untracked-files=no']),+ _git(path, ['log', '-1', '--format=%s%n%an%n%aI']),+ _git(path, ['log', '-100', '--format=%an']),+ ]);+ final commit = git[2]?.split('\n');+ return {+ 'path': path,+ 'readme': ?readme,+ 'files': files.take(12).toList(),+ 'branch': ?git[0],+ if (git[1] != null)+ 'changedFiles': git[1]!.isEmpty ? 0 : git[1]!.split('\n').length,+ if (commit != null && commit.length >= 3)+ 'commit': {+ 'subject': commit[0],+ 'author': commit[1],+ 'date': commit[2],+ },+ if (git[3] != null)+ 'contributors': git[3]!+ .split('\n')+ .where((name) => name.isNotEmpty)+ .toSet()+ .take(5)+ .toList(),+ };+ } on FileSystemException {+ return {'error': 'UNREADABLE'};+ }+}++Future<String?> _git(String path, List<String> args) async {+ Process? process;+ Timer? timer;+ var expired = false;+ try {+ process = await Process.start(+ 'git',+ [+ '--no-optional-locks',+ '-c',+ 'core.fsmonitor=false',+ '-C',+ path,+ ...args,+ ],+ environment: {'GIT_TERMINAL_PROMPT': '0', 'GIT_OPTIONAL_LOCKS': '0'},+ );+ timer = Timer(const Duration(seconds: 2), () {+ expired = true;+ process?.kill(ProcessSignal.sigkill);+ });+ var length = 0;+ final bytes = <int>[];+ final stdout = process.stdout.listen((chunk) {+ length += chunk.length;+ if (length > 32 * 1024) {+ expired = true;+ process?.kill(ProcessSignal.sigkill);+ } else {+ bytes.addAll(chunk);+ }+ });+ final outputDone = stdout.asFuture<void>();+ final stderr = process.stderr.drain<void>();+ final code = await process.exitCode;+ await outputDone;+ await stderr;+ return code == 0 && !expired+ ? utf8.decode(bytes, allowMalformed: true).trim()+ : null;+ } on ProcessException {+ return null;+ } finally {+ timer?.cancel();+ }+}diff --git a/desktop/lib/shared/widgets/app_choice_picker.dart b/desktop/lib/shared/widgets/app_choice_picker.dartindex 13b02b183..a6db8e41c 100644--- a/desktop/lib/shared/widgets/app_choice_picker.dart+++ b/desktop/lib/shared/widgets/app_choice_picker.dart@@ -20,6 +20,8 @@ class AppChoicePicker<T> extends StatefulWidget {this.showDetails = false,this.wrap = true,this.compact = false,+ this.quiet = false,+ this.allVisible = false,});final T value;@@ -32,6 +34,8 @@ class AppChoicePicker<T> extends StatefulWidget {final bool showDetails;final bool wrap;final bool compact;+ final bool quiet;+ final bool allVisible;@overrideState<AppChoicePicker<T>> createState() => _AppChoicePickerState<T>();@@ -87,6 +91,7 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {@overrideWidget build(BuildContext context) {AppTheme.watch(context);+ if (widget.quiet) return _quietChoices();final candidates = _visibleOptions;if (candidates.isEmpty) return const SizedBox.shrink();final textStyle = TextStyle(@@ -213,6 +218,117 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {);}+ Widget _quietChoices() {+ final visible = widget.allVisible+ ? _orderedOptions+ : [+ ..._orderedOptions.take(3),+ ..._orderedOptions+ .skip(3)+ .where((option) => option.value == widget.value),+ ];+ return Wrap(+ spacing: 8,+ runSpacing: 8,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ for (final option in visible)+ Semantics(+ selected: widget.value == option.value,+ inMutuallyExclusiveGroup: true,+ child: TextButton(+ key: widget.optionKey(option.value),+ onPressed: () => _choose(option.value),+ style: TextButton.styleFrom(+ foregroundColor: widget.value == option.value+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ backgroundColor: widget.value == option.value+ ? AppPalette.swarmAccent.withValues(alpha: .13)+ : Colors.transparent,+ minimumSize: const Size(0, 44),+ padding: const EdgeInsets.symmetric(+ horizontal: 15,+ vertical: 12,+ ),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (option.leading != null) ...[+ option.leading!(),+ const SizedBox(width: 9),+ ],+ Flexible(+ child: Text(+ option.label,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 14,+ fontWeight: FontWeight.w500,+ ),+ ),+ ),+ if (option.note != null) ...[+ const SizedBox(width: 8),+ Text(+ option.note!,+ style: TextStyle(+ fontSize: 12,+ color: AppPalette.textFaint,+ ),+ ),+ ],+ const SizedBox(width: 10),+ Visibility(+ visible: widget.value == option.value,+ maintainSize: true,+ maintainState: true,+ maintainAnimation: true,+ child: const Icon(Icons.check, size: 16),+ ),+ ],+ ),+ ),+ ),+ if (!widget.allVisible && widget.options.length > visible.length)+ AppSelectField<T>(+ key: widget.moreKey,+ value: widget.value,+ options: widget.options,+ onChanged: _choose,+ width: math.max(+ 104,+ MediaQuery.textScalerOf(context).scale(14) * 4.2 + 32,+ ),+ height: math.max(+ 44,+ MediaQuery.textScalerOf(context).scale(14) * 1.5 + 24,+ ),+ fillColor: Colors.transparent,+ trigger: Padding(+ padding: const EdgeInsets.only(left: 5),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Text(+ 'More…',+ maxLines: 1,+ style: TextStyle(+ fontSize: 14,+ color: AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ ),+ ],+ );+ }+Widget _choice(SelectOption<T> option,TextStyle textStyle,diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex f8e78567c..fb7f75297 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -24,6 +24,8 @@ import '../core/local_git_projects.dart';import '../core/test_run.dart';import '../core/models.dart';import '../core/project_folder.dart';+import '../core/project_history.dart';+import '../core/project_preview.dart';import '../core/repository_clone.dart';import '../core/retry.dart';import '../settings/config_store.dart';@@ -1084,6 +1086,7 @@ class AppNotifier extends ChangeNotifier {// without one (the tests) nothing is written anywhere.dial = DialState(paneLayoutStore?.storage),agentPreference = AgentPreference(paneLayoutStore?.storage),+ projectHistory = ProjectHistory(paneLayoutStore?.storage),session = authSession,_store = configStore,cliLogin = cliLogin ?? CliLogin(),@@ -1146,6 +1149,7 @@ class AppNotifier extends ChangeNotifier {/// without dragging the whole rail through a machine-list rebuild.final DialState dial;final AgentPreference agentPreference;+ final ProjectHistory projectHistory;TerminalPane? get focusedPane {final id = focusedPaneId;@@ -4022,6 +4026,36 @@ class AppNotifier extends ChangeNotifier {}}+ /// Reads source material only on the machine that owns the selected path.+ Future<Map<String, dynamic>> readProjectPreview(+ String machineId,+ String path,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) return {'error': 'UNAVAILABLE'};+ if (machine.isLocalMachine) {+ return readLocalProjectPreview(path).timeout(+ const Duration(seconds: 4),+ onTimeout: () => {'error': 'UNAVAILABLE'},+ );+ }+ if (machine.nodeOnline == false ||+ machine.needsLink ||+ machine.connectionStatus != ConnectionStatus.connected &&+ connectionForTest == null) {+ return {'error': 'UNAVAILABLE'};+ }+ try {+ return await _conn(machineId).request(+ 'project_preview',+ payload: {'path': path},+ timeout: const Duration(seconds: 4),+ );+ } catch (_) {+ return {'error': 'UNAVAILABLE'};+ }+ }+/// Every Codex profile folder the CLI on [machineId] can offer, merged with [observedPaths]/// (Codex homes already known from this same machine's other Codex agents). Runs entirely on that/// machine — this app never touches a filesystem itself, which is what makes it work for a remote@@ -4175,7 +4209,7 @@ class AppNotifier extends ChangeNotifier {return creation._complete(error.message);} catch (_) {return creation._complete(- 'Could not prepare the project folder. Choose Local to select an existing folder.',+ 'Could not prepare the project folder. Browse for an existing folder.',);}// Preparation may be slow. Revalidate before starting a process, using@@ -4314,6 +4348,11 @@ class AppNotifier extends ChangeNotifier {if (_disposed || machineStates[machineId] != machine) return null;_upsertAgent(machine, agent);// Apply each creation receipt once, even if its transport result is replayed.+ final projectPath =+ agent.project?.cwd ?? creation.preparedFolder ?? choices['cwd'];+ if (projectPath is String && projectPath.isNotEmpty) {+ unawaited(projectHistory.select(machineId, projectPath));+ }harnessStats.onAgentSpawned();notifyListeners();if (_creationPlacementError(targetId, split) != null) {diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dartindex bb274a0a2..ca7ef3489 100644--- a/desktop/lib/widgets/agent_picker.dart+++ b/desktop/lib/widgets/agent_picker.dart@@ -11,17 +11,20 @@ class AgentPicker extends StatelessWidget {required this.options,required this.onChanged,this.compact = false,+ this.quiet = false,});final String value;final List<SelectOption<String>> options;final ValueChanged<String> onChanged;final bool compact;+ final bool quiet;static const quickAgents = ['codex', 'claude', 'cursor'];@overrideWidget build(BuildContext context) => AppChoicePicker<String>(value: value,compact: compact,+ quiet: quiet,options: [for (final option in options)SelectOption(@@ -33,7 +36,9 @@ class AgentPicker extends StatelessWidget {trailing: option.trailing,),],- preferredValues: quickAgents,+ preferredValues: quiet+ ? const ['codex', 'claude', 'opencode']+ : quickAgents,onChanged: onChanged,optionKey: (id) => ValueKey('new-agent-quick-$id'),moreKey: const Key('new-agent-engine-field'),diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex d37b75059..143b77ff6 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -1,7 +1,9 @@import 'dart:async';+import 'dart:math' as math;import 'package:file_selector/file_selector.dart';import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import '../analytics/analytics.dart';@@ -21,6 +23,7 @@ import 'engine_identity.dart';import 'codex_profile_field.dart';import 'agent_picker.dart';import 'remote_folder_picker.dart';+import 'new_agent_project_picker.dart';/// Mirrors the harness CLI's `BYPASS_PERMISSION_FLAGS`/// (autonomous-harness/cli/src/lib/engineLaunch.ts) 1:1 — this is UI-only display + gating, the CLI@@ -107,11 +110,12 @@ class _NewAgentDialog extends StatefulWidget {class _NewAgentDialogState extends State<_NewAgentDialog> {final _folderFocus = FocusNode(debugLabel: 'Working folder');final _actionFocus = FocusNode(debugLabel: 'Create or check agent');- final _repositoryFocus = FocusNode(debugLabel: 'Repository URL');- final _repository = TextEditingController();+ GitHubRepository? _repository;final _advancedKey = GlobalKey();final _choicesScroll = ScrollController();- _FolderSource _folderSource = _FolderSource.local;+ late _FolderSource _folderSource = widget.initialFolder == null+ ? _FolderSource.newProject+ : _FolderSource.local;String? _preparedFolder;AgentCreationAttempt? _creation;bool _checkingCreation = false;@@ -130,15 +134,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {/// it is shut for the case it exists to serve, and a drawer that remembers/// being open is a drawer that is open for somebody who never asked.bool _advancedOpen = false;- bool _machineChoicesOpen = false;bool _submitting = false;@overridevoid dispose() {_folderFocus.dispose();_actionFocus.dispose();- _repositoryFocus.dispose();- _repository.dispose();_choicesScroll.dispose();super.dispose();}@@ -252,12 +253,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {unawaited(_probeEngines());}- /// Surface a changed permission setting without repeating the default profile.- String _advancedState() => _bypassPermission ? 'Approvals off' : '';-bool _picking = false;- bool _folderHovered = false;- bool _folderFocused = false;bool _bypassHovered = false;String? _error;@@ -282,36 +278,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {widget.notifier.stateOf(_machineId)?.machine.displayName ??'this machine';- String _machineDetail(MachineState machine) => [- machine.isLocalMachine ? 'This computer' : 'Remote',- if (machine.nodeOnline == false)- 'Offline'- else if (machine.needsLink)- 'Link required',- ].join(' · ');-- Future<void> _browse() async {- if (_picking || _choicesLocked) return;- final restoreFocus = _folderFocus.hasFocus;- // The agent runs on the MACHINE, so the folder has to exist on the machine- // — which is the whole reason this branches.- //- // On this computer that is the OS's own panel (`getDirectoryPath` is- // NSOpenPanel on macOS, IFileDialog on Windows, the desktop's file-chooser- // portal on Linux): it is the picker the user already knows, it can reach- // sidebar favourites, iCloud and network mounts that `fs_list_dir` never- // enumerates, and the app is not sandboxed (`macos/Runner/*.entitlements`- // declares no `com.apple.security.app-sandbox`) so the path it returns is- // one the CLI can actually open — no security-scoped bookmark to hand over.- //- // On any other machine a native panel is not merely wrong but actively- // misleading: it browses THIS Mac and hands back a path that does not exist- // over there, so the agent would fail to start in a folder the user watched- // themselves select. That case keeps the in-app browser, which walks the- // remote filesystem over the `fs_list_dir` RPC.- var acceptedFolder = false;+ Future<String?> _browse() async {+ if (_picking || _choicesLocked) return null;setState(() => _picking = true);- final pickingRevision = _machineRevision;+ final revision = _machineRevision;try {final picked = _machineIsThisComputer? await getDirectoryPath(initialDirectory: _folder)@@ -321,43 +291,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {machineId: _machineId,initialPath: _folder,);- if (!mounted) return;- setState(() {- _picking = false;- if (picked != null &&- !_choicesLocked &&- pickingRevision == _machineRevision) {- _folder = picked;- _error = null;- acceptedFolder = true;- }- });- } catch (error) {- if (!mounted) return;- setState(() {- _picking = false;- if (pickingRevision == _machineRevision) {- _error = 'Could not open the folder picker: $error';- }- });- } finally {- if (mounted && restoreFocus) {- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted &&- !_choicesLocked &&- !_picking &&- pickingRevision == _machineRevision) {- // A confirmed folder makes the primary action the next step.- // Cancellation/failure keeps Enter on browsing, and a pending- // account choice must not focus a disabled submit button.- if (acceptedFolder && !_waitingForCodexProfile) {- _actionFocus.requestFocus();- } else {- _folderFocus.requestFocus();- }- }- });+ return mounted && !_choicesLocked && revision == _machineRevision+ ? picked+ : null;+ } catch (_) {+ if (mounted && revision == _machineRevision) {+ setState(() => _error = 'Could not open the folder picker. Try again.');}+ return null;+ } finally {+ if (mounted) setState(() => _picking = false);}}@@ -399,6 +342,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {setState(() {if (!_confirmationPending) {_preparedFolder = _creation?.preparedFolder;+ if (_preparedFolder != null) {+ _folder = _preparedFolder;+ _repository = null;+ _folderSource = _FolderSource.local;+ }}_submitting = false;_error = error;@@ -415,32 +363,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {ProjectFolderRequest? get _projectFolder => switch (_folderSource) {_FolderSource.newProject => const ProjectFolderRequest.newProject(),_FolderSource.local => null,- _FolderSource.remote => switch (GitHubRepository.parse(_repository.text)) {+ _FolderSource.remote => switch (_repository) {final repository? => ProjectFolderRequest.remote(repository),null => null,},};- void _selectFolderSource(_FolderSource source) {- if (_folderSource == source || _choicesLocked || _picking) return;- setState(() {- _folderSource = source;- _preparedFolder = null;- _error = null;- });- WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted) return;- switch (source) {- case _FolderSource.local:- _folderFocus.requestFocus();- case _FolderSource.remote:- _repositoryFocus.requestFocus();- case _FolderSource.newProject:- if (!_waitingForCodexProfile) _actionFocus.requestFocus();- }- });- }-void _toggleAdvanced() {setState(() => _advancedOpen = !_advancedOpen);if (!_advancedOpen) return;@@ -488,166 +416,266 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {!_submitting &&(_confirmationPending || !_waitingForCodexProfile);- return AlertDialog(- title: Text(switch (widget.split?.axis) {- PaneResizeAxis.x => 'New Agent to the right',- PaneResizeAxis.y => 'New Agent below',- null => 'New Agent',- }),- titleTextStyle: Theme.of(context).textTheme.headlineSmall?.copyWith(- fontSize: 24,- fontWeight: grid.AppFont.semibold,- color: grid.AppPalette.textPrimary,- ),- titlePadding: const EdgeInsets.fromLTRB(28, 28, 28, 0),- contentPadding: const EdgeInsets.fromLTRB(28, 24, 28, 16),- actionsPadding: const EdgeInsets.fromLTRB(28, 0, 28, 24),- actionsOverflowButtonSpacing: 8,- content: SizedBox(- width: _dialogWidth,- child: Scrollbar(- controller: _choicesScroll,- thumbVisibility: true,- thickness: 4,- radius: const Radius.circular(2),- child: SingleChildScrollView(- controller: _choicesScroll,- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- AbsorbPointer(- absorbing: _choicesLocked,- child: ExcludeFocus(- excluding: _choicesLocked,- child: _choices(bypassFlag),- ),- ),- if (_error != null) ...[- const SizedBox(height: _gapBlock),- Semantics(- liveRegion: true,- child: Text(- _error!,- style: Theme.of(context).textTheme.bodySmall?.copyWith(- color: _confirmationPending- ? grid.AppPalette.textSecondary- : Theme.of(context).colorScheme.error,+ return CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.enter, meta: true): () {+ if (canCreate) _submit();+ },+ const SingleActivator(LogicalKeyboardKey.enter, control: true): () {+ if (canCreate) _submit();+ },+ },+ child: AlertDialog(+ constraints: const BoxConstraints(maxWidth: 1160),+ backgroundColor: grid.AppPalette.swarmField,+ surfaceTintColor: Colors.transparent,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),+ title: Text(switch (widget.split?.axis) {+ PaneResizeAxis.x => 'New Agent to the right',+ PaneResizeAxis.y => 'New Agent below',+ null => 'New Agent',+ }),+ titleTextStyle: Theme.of(context).textTheme.headlineSmall?.copyWith(+ fontSize: 24,+ fontWeight: grid.AppFont.semibold,+ color: grid.AppPalette.textPrimary,+ ),+ titlePadding: const EdgeInsets.fromLTRB(28, 28, 28, 0),+ contentPadding: const EdgeInsets.fromLTRB(28, 24, 28, 16),+ actionsPadding: const EdgeInsets.fromLTRB(28, 0, 28, 24),+ actionsOverflowButtonSpacing: 8,+ content: SizedBox(+ width: _dialogWidth,+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: math.min(+ 650,+ math.max(220, MediaQuery.sizeOf(context).height - 230),+ ),+ ),+ child: Scrollbar(+ controller: _choicesScroll,+ thickness: 4,+ radius: const Radius.circular(2),+ child: SingleChildScrollView(+ controller: _choicesScroll,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ AbsorbPointer(+ absorbing: _choicesLocked,+ child: ExcludeFocus(+ excluding: _choicesLocked,+ child: _choices(bypassFlag),),),- ),- ],- ],+ if (_error != null) ...[+ const SizedBox(height: _gapBlock),+ Semantics(+ liveRegion: true,+ child: Text(+ _error!,+ style: Theme.of(context).textTheme.bodySmall+ ?.copyWith(+ color: _confirmationPending+ ? grid.AppPalette.textSecondary+ : Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ ],+ ),+ ),),),),- ),- actions: [- if (!_confirmationPending && !widget.offerBackToSearch)- TextButton(- onPressed: _submitting ? null : () => Navigator.of(context).pop(),- style: TextButton.styleFrom(- foregroundColor: grid.AppPalette.textSecondary,- ),- child: const Text('Cancel'),- ),- if (_confirmationPending || widget.offerBackToSearch)- TextButton(- onPressed: _submitting- ? null- : () => Navigator.of(context).pop(- widget.offerBackToSearch && !_confirmationPending- ? NewAgentDialogResult.backToSearch- : null,- ),- style: TextButton.styleFrom(- foregroundColor: grid.AppPalette.textSecondary,- ),- child: Text(_confirmationPending ? 'Close' : 'Back to Search'),- ),- if (widget.offerFindExisting &&- _confirmationPending &&- (!_submitting || _checkingCreation))- TextButton.icon(- onPressed: _submitting- ? null- : () =>- Navigator.of(context)- .pop(NewAgentDialogResult.findExisting),- icon: const Icon(LucideIcons.search, size: 16),- label: const Text('Find an agent'),- ),- FilledButton(- key: const ValueKey('create-agent-submit'),- focusNode: _actionFocus,- onPressed: canCreate ? _submit : null,- style: FilledButton.styleFrom(- minimumSize: const Size(136, 42),- padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 12),- backgroundColor: grid.AppPalette.swarmAccent,- foregroundColor: grid.AppPalette.swarmTabBar,- shape: const StadiumBorder(),- disabledForegroundColor: _submitting- ? grid.AppPalette.textPrimary- : null,- ),- child: _submitting- ? Semantics(- liveRegion: true,- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- const SizedBox(- width: 14,- height: 14,- child: CircularProgressIndicator(strokeWidth: 2),+ actions: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ TextButton(+ key: const Key('new-agent-advanced'),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ onPressed: _choicesLocked ? null : _toggleAdvanced,+ child: Text(+ _bypassPermission ? 'Options · Approvals off' : 'Options',+ ),+ ),+ const SizedBox(width: 16),+ Expanded(+ child: OverflowBar(+ alignment: MainAxisAlignment.end,+ spacing: 8,+ overflowSpacing: 8,+ children: [+ if (!_confirmationPending && !widget.offerBackToSearch)+ TextButton(+ onPressed: _submitting+ ? null+ : () => Navigator.of(context).pop(),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ child: const Text('Cancel'),),- const SizedBox(width: 8),- Text(- _checkingCreation- ? 'Checking status…'- : _folderSource == _FolderSource.remote &&- _preparedFolder == null- ? 'Cloning and starting…'- : 'Creating agent…',+ if (_confirmationPending || widget.offerBackToSearch)+ TextButton(+ onPressed: _submitting+ ? null+ : () => Navigator.of(context).pop(+ widget.offerBackToSearch &&+ !_confirmationPending+ ? NewAgentDialogResult.backToSearch+ : null,+ ),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ child: Text(+ _confirmationPending ? 'Close' : 'Back to Search',+ ),),- ],- ),- )- : Text(_confirmationPending ? 'Check status' : 'Create Agent'),- ),- ],+ if (widget.offerFindExisting &&+ _confirmationPending &&+ (!_submitting || _checkingCreation))+ TextButton.icon(+ onPressed: _submitting+ ? null+ : () =>+ Navigator.of(context)+ .pop(NewAgentDialogResult.findExisting),+ icon: const Icon(LucideIcons.search, size: 16),+ label: const Text('Find an agent'),+ ),+ FilledButton(+ key: const ValueKey('create-agent-submit'),+ focusNode: _actionFocus,+ onPressed: canCreate ? _submit : null,+ style: FilledButton.styleFrom(+ minimumSize: const Size(136, 42),+ padding: const EdgeInsets.symmetric(+ horizontal: 22,+ vertical: 12,+ ),+ backgroundColor: grid.AppPalette.swarmAccent,+ foregroundColor: grid.AppPalette.swarmTabBar,+ shape: const StadiumBorder(),+ disabledForegroundColor: _submitting+ ? grid.AppPalette.textPrimary+ : null,+ ),+ child: _submitting+ ? Semantics(+ liveRegion: true,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ const SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ ),+ ),+ const SizedBox(width: 8),+ Text(+ _checkingCreation+ ? 'Checking status…'+ : _folderSource ==+ _FolderSource.remote &&+ _preparedFolder == null+ ? 'Cloning and starting…'+ : 'Creating agent…',+ ),+ ],+ ),+ )+ : Text(+ _confirmationPending+ ? 'Check status'+ : 'Create Agent',+ ),+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),);}+ Widget _choiceRow(String label, Widget choices) => LayoutBuilder(+ builder: (context, constraints) {+ if (constraints.maxWidth <+ 700 *+ math.min(1.3, MediaQuery.textScalerOf(context).scale(14) / 14)) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [FieldLabel(label), choices],+ );+ }+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: 76,+ child: Padding(+ padding: const EdgeInsets.only(top: 13),+ child: Text(+ label,+ style: TextStyle(+ fontSize: 13,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ),+ ),+ Expanded(child: choices),+ ],+ );+ },+ );+Widget _choices(String? bypassFlag) {return Column(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: [- const FieldLabel('Agent'),- AgentPicker(- compact: true,- value: _engine,- options: [- for (final identity in allEngines)- SelectOption(- value: identity.id,- label: identity.label,- leading: () => EngineMark(engine: identity.id, size: 14),- ),- ],- onChanged: (value) => setState(() {- unawaited(widget.notifier.agentPreference.select(value));- _engineChosenByUser = true;- _engine = value;- _error = null;- _codexProfile = null;- _codexProfilesBusy = true;- if (!kEngineBypassPermissionFlag.containsKey(value)) {- _bypassPermission = false;- }- }),+ _choiceRow(+ 'Agent',+ AgentPicker(+ compact: true,+ quiet: true,+ value: _engine,+ options: [+ for (final identity in allEngines)+ SelectOption(+ value: identity.id,+ label: identity.label,+ leading: () => EngineMark(engine: identity.id, size: 14),+ ),+ ],+ onChanged: (value) {+ if (_choicesLocked) return;+ setState(() {+ unawaited(widget.notifier.agentPreference.select(value));+ _engineChosenByUser = true;+ _engine = value;+ _error = null;+ _codexProfile = null;+ _codexProfilesBusy = true;+ if (!kEngineBypassPermissionFlag.containsKey(value)) {+ _bypassPermission = false;+ }+ });+ },+ ),),if (!_confirmationPending && _engineCheckFailed) ...[const SizedBox(height: 6),@@ -672,77 +700,39 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {),],const SizedBox(height: _gapField),- _projectHeader(),- const SizedBox(height: 10),- if (_folderSource == _FolderSource.local)- _FolderControl(- folder: _folder,- machineName: _machineName,- machineIsThisComputer: _machineIsThisComputer,- picking: _picking,- focusNode: _folderFocus,- hovered: _folderHovered,- focused: _folderFocused,- onHover: (value) => setState(() => _folderHovered = value),- onFocusChange: (value) => setState(() => _folderFocused = value),- onPressed: _browse,- ),- if (_folderSource == _FolderSource.newProject)- ConstrainedBox(- constraints: const BoxConstraints(minHeight: 52),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- 'Creates a new folder in ~/harnesses.',- style: Theme.of(context).textTheme.bodySmall- ?.copyWith(color: grid.AppPalette.textSecondary),- ),- ),- ),- if (_folderSource == _FolderSource.remote) ...[- TextField(- key: const ValueKey('new-agent-repository'),- controller: _repository,- focusNode: _repositoryFocus,- decoration: InputDecoration(- hintText: 'GitHub URL or owner/repository',- filled: true,- fillColor: grid.AppSurface.recess,- contentPadding: const EdgeInsets.symmetric(- horizontal: 14,- vertical: 16,- ),- enabledBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(grid.AppControl.radius),- borderSide: BorderSide.none,- ),- focusedBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(grid.AppControl.radius),- borderSide: BorderSide(color: grid.AppPalette.accentOnSurface),- ),- ),- onChanged: (_) => setState(() {+ _choiceRow('Machine', _machineOptions()),+ const SizedBox(height: _gapField),+ const FieldLabel('Project'),+ NewAgentProjectPicker(+ key: ValueKey('new-agent-projects-$_machineId'),+ notifier: widget.notifier,+ machineId: _machineId,+ initialFolder: _folder,+ focusNode: _folderFocus,+ locked: _choicesLocked,+ onCreate: _picking || _waitingForCodexProfile || _choicesLocked+ ? null+ : _submit,+ onBrowse: _browse,+ onSelected: (folder, repository) {+ if (_choicesLocked) return;+ setState(() {+ _folder = folder;+ _repository = repository;+ _folderSource = repository != null+ ? _FolderSource.remote+ : folder != null+ ? _FolderSource.local+ : _FolderSource.newProject;_preparedFolder = null;_error = null;- }),- onSubmitted: (_) => _submit(),- ),- const SizedBox(height: 6),- Text(- 'Clone into ~/harnesses on $_machineName.',- style: Theme.of(context).textTheme.bodySmall- ?.copyWith(color: grid.AppPalette.textSecondary),- ),- ],- const SizedBox(height: _gapField),- _machineSelector(),- // Profiles keep loading while collapsed; creation still waits for them.- const SizedBox(height: _gapBlock),+ });+ },+ ),+ const SizedBox(height: 16),_Advanced(key: _advancedKey,open: _advancedOpen,- state: _advancedState(),- onToggle: _toggleAdvanced,children: [if (_engineCheckFailed) ...[Text(@@ -813,147 +803,6 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {);}- Widget _projectHeader() => SizedBox(- width: double.infinity,- child: Wrap(- alignment: WrapAlignment.spaceBetween,- crossAxisAlignment: WrapCrossAlignment.center,- runSpacing: 8,- children: [- Text(- 'Project',- style: Theme.of(context).textTheme.labelMedium- ?.copyWith(color: grid.AppPalette.textSecondary),- ),- DecoratedBox(- decoration: BoxDecoration(- color: grid.AppSurface.recess,- borderRadius: BorderRadius.circular(10),- ),- child: Padding(- padding: const EdgeInsets.all(3),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (final (source, label) in [- (_FolderSource.newProject, 'New'),- (_FolderSource.local, 'Local'),- (_FolderSource.remote, 'Remote'),- ])- Semantics(- selected: _folderSource == source,- inMutuallyExclusiveGroup: true,- child: TextButton(- key: ValueKey('new-agent-folder-${source.name}'),- onPressed: () => _selectFolderSource(source),- style: TextButton.styleFrom(- minimumSize: const Size(60, 30),- padding: const EdgeInsets.symmetric(- horizontal: 12,- vertical: 7,- ),- foregroundColor: _folderSource == source- ? grid.AppPalette.textPrimary- : grid.AppPalette.textSecondary,- backgroundColor: _folderSource == source- ? grid.AppSurface.recessHover- : Colors.transparent,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(7),- ),- ),- child: Text(label),- ),- ),- ],- ),- ),- ),- ],- ),- );-- Widget _machineSelector() {- final machine = widget.notifier.stateOf(_machineId);- final status = machine?.nodeOnline == false- ? 'Offline'- : machine?.needsLink == true- ? 'Link required'- : null;- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- Text(- 'Run on',- style: Theme.of(context).textTheme.bodySmall- ?.copyWith(color: grid.AppPalette.textSecondary),- ),- const SizedBox(width: 10),- Flexible(- child: Tooltip(- message: 'Choose machine',- child: TextButton(- key: const Key('new-agent-machine-toggle'),- onPressed: () => setState(- () => _machineChoicesOpen = !_machineChoicesOpen,- ),- style: TextButton.styleFrom(- foregroundColor: grid.AppPalette.textPrimary,- padding: const EdgeInsets.symmetric(- horizontal: 8,- vertical: 6,- ),- minimumSize: const Size(0, 32),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(- _machineIsThisComputer- ? LucideIcons.laptop- : LucideIcons.monitor,- size: 16,- ),- const SizedBox(width: 8),- Flexible(- child: Text(- _machineName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- ),- ),- if (status != null) ...[- const SizedBox(width: 8),- Text(- status,- style: Theme.of(context).textTheme.bodySmall- ?.copyWith(color: grid.AppPalette.textSecondary),- ),- ],- const SizedBox(width: 6),- Icon(- _machineChoicesOpen- ? Icons.expand_less- : Icons.expand_more,- size: 16,- ),- ],- ),- ),- ),- ),- ],- ),- if (_machineChoicesOpen) ...[- const SizedBox(height: 8),- _machineOptions(),- ],- ],- );- }-Widget _machineOptions() => AppChoicePicker<String>(key: const Key('new-agent-machine-field'),value: _machineId,@@ -962,7 +811,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {optionKey: (id) => ValueKey('new-agent-machine-$id'),showDetails: true,compact: true,- wrap: false,+ wrap: true,+ quiet: true,+ allVisible: true,preferredValues: [for (final machine in widget.notifier.machineStates.values)if (machine.isLocalMachine) machine.machine.machineId,@@ -972,7 +823,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {SelectOption(value: machine.machine.machineId,label: machine.machine.displayName,- detail: _machineDetail(machine),+ note: machine.nodeOnline == false+ ? 'Offline'+ : machine.needsLink+ ? 'Link required'+ : null,leading: () => Icon(machine.isLocalMachine ? LucideIcons.laptop : LucideIcons.monitor,size: 18,@@ -983,8 +838,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {if (id == _machineId || _choicesLocked) return;setState(() {_machineRevision++;+ _engineChosenByUser = true;_machineId = id;_folder = null;+ _repository = null;+ _folderSource = _FolderSource.newProject;_preparedFolder = null;_codexProfile = null;_codexProfilesBusy = true;@@ -995,356 +853,47 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {);}-/// A focused creation form; machine details expand only when requested.-const double _dialogWidth = 600;--/// A path shortened from its HEAD, so the leaf survives.-///-/// `/Users/macbookpro/Desktop/A` truncated the ordinary way keeps the part-/// every path on the machine shares and drops the only part that identifies it.-/// This drops whole leading segments instead and marks the cut with `…/`, the-/// same shorthand a shell prompt uses:-///-/// ```-/// /Users/macbookpro/work/harness/autonomous-harness-desktop-/// …/harness/autonomous-harness-desktop-/// ```-///-/// Segment-wise rather than character-wise: cutting mid-name reads as a typo,-/// while a dropped segment reads as a path someone abbreviated. Windows paths-/// come back untouched — they are separated by `\`, and a wrong guess about the-/// separator would mangle the string rather than shorten it.-/// The advance of one character at the 12pt mono the path control sets — the-/// face is 0.6em wide, like every monospaced face in this family.-///-/// Arithmetic rather than a `TextPainter`: this runs on every rebuild, and a-/// layout pass to answer a question this cheap is a poor trade.-const double _monoAdvance = 12 * 0.6;--String _ellipsizeHead(String path, double maxWidth) {- final fits = path.length * _monoAdvance <= maxWidth;- if (fits || !path.contains('/')) return path;- final segments = path.split('/').where((s) => s.isNotEmpty).toList();- // Never below the leaf: a control too narrow for even that shows the leaf and- // lets the Text's own ellipsis take the rest.- for (var drop = 1; drop < segments.length; drop++) {- final candidate = '…/${segments.skip(drop).join('/')}';- if (candidate.length * _monoAdvance <= maxWidth) return candidate;- }- return '…/${segments.last}';-}--/// A path or a flag, in the face the user chose for code.-///-/// Built from [grid.AppFont] rather than a literal family so it follows Settings-/// ▸ Terminal, and carries `monoFallback` — without it a user whose chosen face-/// lacks a glyph gets Roboto for that one character.-///-/// One size for every mono string here, taken off the ramp rather than picked-/// per call: the path, the flag under the checkbox and the flag in the command-/// are the same kind of text, and three hand-set sizes is how they stop looking-/// like it. `labelSmall`'s 12 is a step under the 13 of the controls around-/// them, which is where a monospaced face has to sit to read at the same size.-TextStyle _mono({required Color color}) => TextStyle(- fontFamily: grid.AppFont.mono,- fontFamilyFallback: grid.AppFont.monoFallback,- fontSize: 12,- color: color,-);--// The dialog's spacing scale. Four steps, named, rather than the run of-// 3/6/7/8/10/12/14/16/18 this file grew — a column whose gaps are all slightly-// different is what "the padding feels off" actually is.-//-// `FieldLabel` already carries its own 6px gap to the control it names, so a-// caption never takes a step from here; these are the gaps BETWEEN things.+/// The project picker shares Open Agent’s generous reading space.+const double _dialogWidth = 1080;-/// A label and the line it belongs to — the flag under its title.const double _gapTight = 4;/// Blocks inside one card: the command, the facts, the reason.const double _gapBlock = 12;/// One field and the next, down the choices column.-const double _gapField = 24;+const double _gapField = 20;-/// The folder control: one target, not a text box with a button beside it.-///-/// The old shape put a read-only `InputDecorator` next to a `Browse…` button,-/// which read as a field you could type in and as the loudest control in the-/// dialog. Here the whole row is the button — the path is what it displays, and-/// the trailing word says what clicking does.-/// The fold that holds what most people never touch.-///-/// A ROW THAT REPORTS ITSELF. Everything about this is ordinary — a twisty, a-/// label, some children — except the state printed on the right, and that is the-/// part doing the work. Two settings were moved out of sight here; a drawer that-/// hides what it is set to is one people open every time to check, which costs-/// more than leaving the controls where they were.-///-/// AMBER, NOT RED, when the prompts are off. Red on this desktop means destroy,-/// and it was tried: a red "Create without prompts" button read as though the-/// button itself were dangerous rather than the setting behind it. Amber is-/// already what this app gives that flag wherever else it appears.class _Advanced extends StatelessWidget {- const _Advanced({- super.key,- required this.open,- required this.state,- required this.onToggle,- required this.children,- });-+ const _Advanced({super.key, required this.open, required this.children});final bool open;-- /// What is set, in a few words — see `_advancedState`. Empty says nothing.- final String state;-- final VoidCallback onToggle;final List<Widget> children;@override- Widget build(BuildContext context) {- final theme = Theme.of(context);- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- mainAxisSize: MainAxisSize.min,- children: [- InkWell(- key: const Key('new-agent-advanced'),- onTap: onToggle,- borderRadius: BorderRadius.circular(6),- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 9),- child: Row(- children: [- // Rotated rather than swapped for a second glyph: one shape- // turning reads as the same control in two positions, which is- // what it is.- AnimatedRotation(- turns: open ? 0 : -0.25,- duration: const Duration(milliseconds: 120),- child: Icon(- Icons.expand_more,- size: 16,- color: grid.AppPalette.textFaint,- ),- ),- const SizedBox(width: 6),- Text(- 'Advanced',- style: theme.textTheme.bodyMedium?.copyWith(- color: grid.AppPalette.textSecondary,- ),- ),- const Spacer(),- if (!open)- Flexible(- child: Text(- key: const Key('new-agent-advanced-state'),- state,- maxLines: 1,- overflow: TextOverflow.ellipsis,- textAlign: TextAlign.right,- style: theme.textTheme.bodySmall?.copyWith(- color: grid.AppPalette.textSecondary,- ),- ),- ),- ],- ),+ Widget build(BuildContext context) => Offstage(+ offstage: !open,+ child: ExcludeFocus(+ excluding: !open,+ child: Align(+ alignment: Alignment.centerLeft,+ child: Container(+ constraints: const BoxConstraints(maxWidth: 560),+ padding: const EdgeInsets.all(20),+ decoration: BoxDecoration(+ color: grid.AppSurface.hoverFill,+ borderRadius: BorderRadius.circular(16),),- ),- // HIDDEN, NOT UNMOUNTED, and that is not a preference — it is what the- // dialog needs to work at all.- //- // It was `if (open)` first, on the reasoning that a shut drawer should- // not pay for a question nobody asked. The Codex profile field is the- // thing that asks the machine for its profiles, and TWO things downstream- // depend on its having asked: it clears `_codexProfilesBusy`, which gates- // the Create button, and it auto-selects when there is exactly one- // profile. Unmounted, neither ever happens — so Create stayed disabled- // forever on Codex, with nothing on screen saying why.- //- // Offstage builds and runs it, and merely declines to paint it.- Offstage(- offstage: !open,- child: ExcludeFocus(- excluding: !open,- child: Container(- margin: const EdgeInsets.only(top: 4),- padding: const EdgeInsets.all(16),- decoration: BoxDecoration(- color: grid.AppSurface.hoverFill,- borderRadius: BorderRadius.circular(10),- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- mainAxisSize: MainAxisSize.min,- children: children,- ),- ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ mainAxisSize: MainAxisSize.min,+ children: children,),),- ],- );- }-}--class _FolderControl extends StatelessWidget {- const _FolderControl({- required this.folder,- required this.machineName,- required this.machineIsThisComputer,- required this.picking,- required this.focusNode,- required this.hovered,- required this.focused,- required this.onHover,- required this.onFocusChange,- required this.onPressed,- });-- final String? folder;- final String machineName;- final bool machineIsThisComputer;- final bool picking;- final FocusNode focusNode;- final bool hovered;- final bool focused;- final ValueChanged<bool> onHover;- final ValueChanged<bool> onFocusChange;- final VoidCallback onPressed;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final theme = Theme.of(context);- final chosen = folder;- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- mainAxisSize: MainAxisSize.min,- children: [- MouseRegion(- cursor: picking- ? SystemMouseCursors.progress- : SystemMouseCursors.click,- onEnter: (_) => onHover(true),- onExit: (_) => onHover(false),- child: InkWell(- key: const Key('new-agent-folder'),- focusNode: focusNode,- onTap: picking ? null : onPressed,- canRequestFocus: !picking,- onFocusChange: onFocusChange,- splashFactory: NoSplash.splashFactory,- hoverColor: Colors.transparent,- focusColor: Colors.transparent,- borderRadius: BorderRadius.circular(grid.AppControl.radius),- child: AnimatedContainer(- duration: grid.AppMotion.hover,- curve: grid.AppMotion.curve,- constraints: BoxConstraints(- minHeight: grid.AppControl.heightFieldScaled.clamp(- 52.0,- double.infinity,- ),- ),- // The select field's own padding, so the two controls stacked in- // this column share one left edge and one right edge.- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),- decoration: BoxDecoration(- color: (hovered || focused) && !picking- ? grid.AppSurface.recessHover- : grid.AppSurface.recess,- borderRadius: BorderRadius.circular(grid.AppControl.radius),- border: Border.all(- color: focused- ? grid.AppPalette.accentOnSurface- : Colors.transparent,- ),- ),- child: Row(- children: [- Icon(- Icons.folder_outlined,- size: 20,- color: grid.AppPalette.textSecondary,- ),- const SizedBox(width: 8),- Expanded(- key: const Key('new-agent-folder-text'),- // Aligned left like every other control's content.- //- // This used to set `TextDirection.rtl` to make a long path- // ellipsize from its head, keeping the leaf visible. But- // direction drives ALIGNMENT too, so the whole string was- // shoved to the trailing edge and left a hole after the- // folder glyph — wider the shorter the path, which is why a- // remote `/home/node/work` looked worst of all.- //- // Truncation is a job for the string, not the layout, so the- // head is now trimmed in [_ellipsizeHead] and the Text stays- // plain LTR.- child: LayoutBuilder(- builder: (context, constraints) => Align(- alignment: AlignmentDirectional.centerStart,- child: Text(- picking- ? 'Waiting for the folder picker…'- // Not "on $machineName": the title says which- // machine and so does the summary, and a hostname- // like `MacBooks-MacBook-Pro.local` spent the- // whole control repeating it, then truncated.- : chosen == null- ? 'Choose a folder…'- : _ellipsizeHead(chosen, constraints.maxWidth),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: chosen != null && !picking- ? _mono(color: grid.AppPalette.textPrimary)- : theme.textTheme.labelMedium?.copyWith(- color: grid.AppPalette.textSecondary,- ),- ),- ),- ),- ),- if (!picking) ...[- const SizedBox(width: 8),- Text(- chosen == null ? 'Browse…' : 'Change',- style: theme.textTheme.labelSmall?.copyWith(- color: grid.AppPalette.accentOnSurface,- ),- ),- ],- ],- ),- ),- ),- ),- // Only the case that needs explaining gets a line. On this computer the- // OS panel is what everyone expects and saying so is noise; on another- // machine the in-app browser is the surprising half, so that is the half- // that speaks.- if (!machineIsThisComputer) ...[- const SizedBox(height: _gapTight),- Text(- 'Choose a folder on $machineName.',- style: theme.textTheme.bodySmall,- ),- ],- ],- );- }+ ),+ ),+ );}-/// The bypass checkbox, in the app's own row shape.-///-/// Not `CheckboxListTile`: that was the only Material list tile left in the app,-/// and its `dense`/`contentPadding` combination left the box floating well clear-/// of the text it labels and out of line with the fields above it.class _BypassCheck extends StatelessWidget {const _BypassCheck({required this.value,diff --git a/desktop/lib/widgets/new_agent_project_picker.dart b/desktop/lib/widgets/new_agent_project_picker.dartnew file mode 100644index 000000000..e48c42c44--- /dev/null+++ b/desktop/lib/widgets/new_agent_project_picker.dart@@ -0,0 +1,701 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:path/path.dart' as p;++import '../core/repository_clone.dart';+import '../core/models.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../state/app_state.dart';++class NewAgentProjectPicker extends StatefulWidget {+ const NewAgentProjectPicker({+ super.key,+ required this.notifier,+ required this.machineId,+ required this.focusNode,+ required this.onSelected,+ required this.onBrowse,+ this.onCreate,+ this.initialFolder,+ this.locked = false,+ });+ final AppNotifier notifier;+ final String machineId;+ final String? initialFolder;+ final FocusNode focusNode;+ final bool locked;+ final VoidCallback? onCreate;+ final void Function(String? folder, GitHubRepository? repository) onSelected;+ final Future<String?> Function() onBrowse;++ @override+ State<NewAgentProjectPicker> createState() => _NewAgentProjectPickerState();+}++class _ProjectRow {+ const _ProjectRow(this.name, {this.path, this.repository});+ final String name;+ final String? path;+ final GitHubRepository? repository;+ bool get isNew => path == null && repository == null;+}++class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {+ final _query = TextEditingController();+ final _searchFocus = FocusNode(debugLabel: 'Search projects');+ final _listScroll = ScrollController();+ final _cache = <String, Map<String, dynamic>>{};+ late _ProjectRow _selection = widget.initialFolder == null+ ? const _ProjectRow('New project')+ : _ProjectRow(+ p.basename(widget.initialFolder!),+ path: widget.initialFolder,+ );+ bool _open = false, _chosen = false, _browsing = false;+ int _index = 0, _previewRevision = 0;+ Timer? _debounce;+ Map<String, dynamic>? _preview;++ @override+ void initState() {+ super.initState();+ unawaited(_restore());+ }++ @override+ void didUpdateWidget(covariant NewAgentProjectPicker oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (widget.initialFolder != oldWidget.initialFolder &&+ widget.initialFolder != null &&+ widget.initialFolder != _selection.path) {+ _selection = _ProjectRow(+ p.basename(widget.initialFolder!),+ path: widget.initialFolder,+ );+ }+ }++ Future<void> _restore() async {+ final history = widget.notifier.projectHistory;+ await history.load();+ if (!mounted || widget.locked || _chosen || widget.initialFolder != null) {+ return;+ }+ final path = history.selected(widget.machineId);+ if (path != null) {+ setState(() => _selection = _ProjectRow(p.basename(path), path: path));+ widget.onSelected(path, null);+ } else {+ setState(() {});+ }+ }++ @override+ void dispose() {+ _previewRevision++;+ _debounce?.cancel();+ _query.dispose();+ _searchFocus.dispose();+ _listScroll.dispose();+ super.dispose();+ }++ List<_ProjectRow> get _rows {+ final machine = widget.notifier.stateOf(widget.machineId);+ final projects = <String, String>{};+ for (final path in widget.notifier.projectHistory.recent(+ widget.machineId,+ )) {+ projects[path] = p.basename(path);+ }+ for (final agent in machine?.agents.reversed ?? const <Agent>[]) {+ final project = machine?.projectOf(agent);+ if (project != null) {+ projects.putIfAbsent(project.cwd, () => project.name);+ }+ }+ if (_selection.path != null) {+ projects.putIfAbsent(_selection.path!, () => _selection.name);+ }+ final query = _query.text.trim();+ final repository = query.isEmpty ? null : GitHubRepository.parse(query);+ final terms = query.toLowerCase().split(RegExp(r'\s+'));+ return [+ const _ProjectRow('New project'),+ if (repository != null)+ _ProjectRow(repository.name, repository: repository),+ for (final entry in projects.entries)+ if (query.isEmpty ||+ terms.every(+ (term) =>+ '${entry.value} ${entry.key}'.toLowerCase().contains(term),+ ))+ _ProjectRow(entry.value, path: entry.key),+ ];+ }++ void _openSearch() {+ if (widget.locked) return;+ _chosen = true;+ _query.text = _selection.repository?.url ?? '';+ final index = _rows.indexWhere(+ (row) =>+ row.path == _selection.path &&+ row.repository?.url == _selection.repository?.url,+ );+ setState(() {+ _open = true;+ _index = math.max(0, index);+ });+ _loadPreview();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && _open) _searchFocus.requestFocus();+ });+ }++ void _closeSearch() {+ setState(() => _open = false);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) widget.focusNode.requestFocus();+ });+ }++ void _select(_ProjectRow row) {+ if (widget.locked) return;+ _chosen = true;+ setState(() {+ _selection = row;+ _open = false;+ });+ widget.onSelected(row.path, row.repository);+ if (row.repository == null) {+ unawaited(+ widget.notifier.projectHistory.select(widget.machineId, row.path),+ );+ }+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) widget.focusNode.requestFocus();+ });+ }++ bool get _hasSearchMatch => _query.text.trim().isEmpty || _rows.length > 1;++ void _confirm({bool create = false}) {+ if (!_hasSearchMatch || widget.locked) return;+ _select(_rows[_index]);+ if (create) widget.onCreate?.call();+ }++ void _highlight(int index) {+ final next = index.clamp(0, _rows.length - 1);+ if (_index == next) return;+ setState(() => _index = next);+ _loadPreview();+ if (_listScroll.hasClients) {+ final offset = math.max(0, _index - 1) * _rowHeight;+ final bottom =+ offset + _rowHeight - _listScroll.position.viewportDimension;+ if (offset < _listScroll.offset) {+ _listScroll.jumpTo(offset);+ } else if (bottom > _listScroll.offset) {+ _listScroll.jumpTo(+ bottom.clamp(0, _listScroll.position.maxScrollExtent),+ );+ }+ }+ }++ double get _rowHeight =>+ math.max(62, MediaQuery.textScalerOf(context).scale(13) * 3.6);++ void _loadPreview() {+ _debounce?.cancel();+ final revision = ++_previewRevision;+ final rows = _rows;+ final row = rows[_index.clamp(0, rows.length - 1)];+ _preview = row.path == null ? null : _cache[row.path];+ if (row.path == null || _preview != null) return;+ _debounce = Timer(const Duration(milliseconds: 160), () async {+ final result = await widget.notifier.readProjectPreview(+ widget.machineId,+ row.path!,+ );+ if (!mounted || revision != _previewRevision) return;+ if (_cache.length >= 24) _cache.remove(_cache.keys.first);+ _cache[row.path!] = result;+ setState(() => _preview = result);+ });+ }++ Future<void> _browse() async {+ if (_browsing || widget.locked) return;+ setState(() => _browsing = true);+ try {+ final path = await widget.onBrowse();+ if (mounted && path != null && !widget.locked) {+ _select(_ProjectRow(p.basename(path), path: path));+ }+ } finally {+ if (mounted) setState(() => _browsing = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final rows = _rows;+ _index = _index.clamp(0, rows.length - 1);+ return Material(+ color: grid.AppPalette.swarmSearchSurface,+ surfaceTintColor: Colors.transparent,+ borderRadius: BorderRadius.circular(24),+ clipBehavior: Clip.antiAlias,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (_open)+ Focus(+ onKeyEvent: (_, event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ if (event.logicalKey == LogicalKeyboardKey.enter &&+ (HardwareKeyboard.instance.isMetaPressed ||+ HardwareKeyboard.instance.isControlPressed)) {+ _confirm(create: true);+ return KeyEventResult.handled;+ }+ if (event.logicalKey == LogicalKeyboardKey.arrowDown ||+ event.logicalKey == LogicalKeyboardKey.arrowUp) {+ _highlight(+ _index ++ (event.logicalKey == LogicalKeyboardKey.arrowDown+ ? 1+ : -1),+ );+ return KeyEventResult.handled;+ }+ if (event.logicalKey == LogicalKeyboardKey.escape) {+ _closeSearch();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: TextField(+ key: const Key('new-agent-project-search'),+ controller: _query,+ style: const TextStyle(fontSize: 16),+ focusNode: _searchFocus,+ decoration: InputDecoration(+ hintText: 'Search projects or paste a Git URL',+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ filled: true,+ fillColor: Colors.transparent,+ hoverColor: Colors.transparent,+ prefixIcon: const Padding(+ padding: EdgeInsets.symmetric(horizontal: 20),+ child: Icon(LucideIcons.search, size: 20),+ ),+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 20,+ vertical: 20,+ ),+ suffixIcon: TextButton(+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ onPressed: _closeSearch,+ child: const Text('esc'),+ ),+ ),+ onChanged: (_) {+ setState(() => _index = _rows.length > 1 ? 1 : 0);+ _loadPreview();+ },+ onSubmitted: (_) => _confirm(),+ ),+ )+ else+ InkWell(+ key: const Key('new-agent-project-bar'),+ focusNode: widget.focusNode,+ onTap: widget.locked ? null : _openSearch,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 22,+ vertical: 20,+ ),+ child: Row(+ children: [+ Icon(+ _selection.isNew+ ? LucideIcons.folderPlus+ : _selection.repository != null+ ? LucideIcons.gitBranch+ : LucideIcons.folder,+ size: 21,+ color: grid.AppPalette.textSecondary,+ ),+ const SizedBox(width: 14),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ _selection.name,+ style: const TextStyle(+ fontSize: 16,+ fontWeight: FontWeight.w500,+ ),+ ),+ if (_selection.path != null)+ Text(+ _selection.path!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 12,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 12),+ Icon(+ LucideIcons.search,+ size: 18,+ color: grid.AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ if (_open)+ LayoutBuilder(+ builder: (context, constraints) {+ final wide =+ constraints.maxWidth >=+ 640 *+ math.min(+ 1.3,+ MediaQuery.textScalerOf(context).scale(14) / 14,+ );+ Widget projectRow(int index) {+ final row = rows[index];+ return MouseRegion(+ onEnter: (_) => _highlight(index),+ child: Semantics(+ selected: _hasSearchMatch && _index == index,+ child: Material(+ color: _hasSearchMatch && _index == index+ ? Colors.white.withValues(alpha: .065)+ : Colors.transparent,+ borderRadius: BorderRadius.circular(12),+ child: InkWell(+ key: ValueKey(+ row.isNew+ ? 'new-agent-folder-newProject'+ : row.repository != null+ ? 'new-agent-clone-project'+ : 'project-${row.path}',+ ),+ borderRadius: BorderRadius.circular(12),+ onTap: () => _select(row),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 14),+ child: Row(+ children: [+ Icon(+ row.isNew+ ? LucideIcons.plus+ : row.repository != null+ ? LucideIcons.gitBranch+ : LucideIcons.folder,+ size: 18,+ color: grid.AppPalette.textSecondary,+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ crossAxisAlignment:+ CrossAxisAlignment.start,+ children: [+ Text(+ row.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ if (row.path != null ||+ row.repository != null)+ Text(+ row.path ?? 'Clone repository',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 12,+ color:+ grid.AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ ),+ if (_hasSearchMatch && _index == index)+ Padding(+ padding: const EdgeInsets.only(left: 8),+ child: Icon(+ Icons.keyboard_return,+ size: 16,+ color: grid.AppPalette.textFaint,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }++ final list = Column(+ children: [+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: SizedBox(height: _rowHeight, child: projectRow(0)),+ ),+ Expanded(+ child: ListView.builder(+ controller: _listScroll,+ padding: const EdgeInsets.symmetric(horizontal: 8),+ itemCount: rows.length - 1,+ itemExtent: _rowHeight,+ itemBuilder: (context, index) => projectRow(index + 1),+ ),+ ),+ Align(+ alignment: Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.all(10),+ child: TextButton.icon(+ key: const Key('new-agent-project-browse'),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ ),+ onPressed: _browsing ? null : _browse,+ icon: const Icon(LucideIcons.folderOpen, size: 16),+ label: Text(+ _browsing ? 'Opening…' : 'Browse folders…',+ ),+ ),+ ),+ ),+ ],+ );+ final preview = !_hasSearchMatch+ ? Center(+ child: Text(+ 'No matching projects',+ style: TextStyle(+ color: grid.AppPalette.textSecondary,+ ),+ ),+ )+ : _ProjectPreview(row: rows[_index], data: _preview);+ return SizedBox(+ height: wide+ ? math.min(+ 330,+ math.max(+ 260,+ MediaQuery.sizeOf(context).height - 520,+ ),+ )+ : 430,+ child: wide+ ? Row(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Expanded(child: list),+ const SizedBox(width: 16),+ Expanded(child: preview),+ ],+ )+ : Column(+ children: [+ SizedBox(height: 230, child: list),+ Expanded(child: preview),+ ],+ ),+ );+ },+ ),+ if (_open) const SizedBox(height: 12),+ ],+ ),+ );+ }+}++class _ProjectPreview extends StatelessWidget {+ const _ProjectPreview({required this.row, required this.data});+ final _ProjectRow row;+ final Map<String, dynamic>? data;++ @override+ Widget build(BuildContext context) {+ final secondary = TextStyle(+ fontSize: 12,+ color: grid.AppPalette.textSecondary,+ height: 1.5,+ );+ final readme = data?['readme'];+ final commit = data?['commit'];+ final contributors = data?['contributors'];+ final files = data?['files'];+ return SingleChildScrollView(+ key: ValueKey('project-preview-${row.path ?? row.name}'),+ padding: const EdgeInsets.fromLTRB(16, 18, 28, 20),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ row.name,+ style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w600),+ ),+ const SizedBox(height: 6),+ Text(+ row.path ?? (row.repository?.url ?? '~/harnesses'),+ style: secondary,+ ),+ if (row.repository != null) ...[+ const SizedBox(height: 24),+ Text('Cloned when you create the agent.', style: secondary),+ ],+ if (row.path != null && data == null) ...[+ const SizedBox(height: 24),+ const SizedBox(+ width: 16,+ height: 16,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),+ ],+ if (data?['error'] != null) ...[+ const SizedBox(height: 24),+ Text(+ data?['error'] == 'NOT_FOUND'+ ? 'Folder unavailable'+ : 'Preview unavailable',+ style: secondary,+ ),+ ],+ if (data?['branch'] is String || data?['changedFiles'] is int) ...[+ const SizedBox(height: 16),+ Text(+ [+ if (data?['branch'] is String) data!['branch'],+ if (data?['changedFiles'] is int && data!['changedFiles'] > 0)+ '${data!['changedFiles']} changed files',+ ].join(' · '),+ style: secondary,+ ),+ ],+ if (readme is String && readme.trim().isNotEmpty) ...[+ const SizedBox(height: 24),+ ..._readme(context, readme),+ ] else if (files is List && files.isNotEmpty) ...[+ const SizedBox(height: 24),+ for (final file in files.whereType<String>())+ Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Text(file, style: secondary),+ ),+ ],+ if (commit is Map && commit['subject'] is String) ...[+ const SizedBox(height: 24),+ Text('Latest commit', style: secondary),+ const SizedBox(height: 5),+ Text(+ commit['subject'],+ style: const TextStyle(fontSize: 13, height: 1.5),+ ),+ if (commit['author'] is String)+ Text(+ [+ commit['author'],+ if (commit['date'] is String)+ (commit['date'] as String).split('T').first,+ ].join(' · '),+ style: secondary,+ ),+ ],+ if (contributors is List && contributors.isNotEmpty) ...[+ const SizedBox(height: 20),+ Text('Contributors', style: secondary),+ const SizedBox(height: 5),+ Text(+ contributors.whereType<String>().join(' · '),+ style: const TextStyle(fontSize: 13, height: 1.5),+ ),+ ],+ ],+ ),+ );+ }++ /// A restrained excerpt: headings, paragraphs and code remain readable.+ /// Links are text; Markdown never fetches remote images or runs HTML.+ List<Widget> _readme(BuildContext context, String text) {+ final result = <Widget>[];+ var code = false;+ for (final raw+ in text+ .substring(0, math.min(text.length, 5000))+ .split('\n')+ .take(70)) {+ if (raw.trim().startsWith('```')) {+ code = !code;+ continue;+ }+ if (raw.trim().startsWith('<') || raw.trim().startsWith('![')) continue;+ final heading = RegExp(r'^#{1,6}\s+').hasMatch(raw);+ final line = raw+ .replaceFirst(RegExp(r'^#{1,6}\s+'), '')+ .replaceAllMapped(+ RegExp(r'!?\[([^\]]*)\]\([^)]*\)'),+ (match) => match.group(1)!,+ )+ .replaceAll('**', '')+ .replaceAll('`', '');+ result.add(+ Padding(+ padding: EdgeInsets.only(+ bottom: line.isEmpty ? 4 : 6,+ top: heading ? 8 : 0,+ ),+ child: Text(+ line,+ style: TextStyle(+ fontSize: heading ? 17 : 13,+ height: 1.55,+ fontWeight: heading ? FontWeight.w600 : FontWeight.normal,+ fontFamily: code ? grid.AppFont.mono : null,+ color: grid.AppPalette.textPrimary.withValues(+ alpha: heading ? 1 : .85,+ ),+ ),+ ),+ ),+ );+ }+ return result;+ }+}diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 255dc4c20..b1c0842d1 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -314,6 +314,8 @@ class WsConn {// File paths and media contents are user data, not frame diagnostics.'agent_read_file','agent_read_file_result',+ 'project_preview',+ 'project_preview_result','terminal_output','terminal_input','terminal_resize',diff --git a/desktop/test/agent_creation_recovery_test.dart b/desktop/test/agent_creation_recovery_test.dartindex 92041dcfb..a3ce46959 100644--- a/desktop/test/agent_creation_recovery_test.dart+++ b/desktop/test/agent_creation_recovery_test.dart@@ -1,3 +1,5 @@+import 'support/new_agent_project.dart';+import 'dart:async';import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';@@ -219,7 +221,7 @@ void main() {}),findsWidgets,);- await tester.tap(find.byKey(const Key('new-agent-folder')));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('create-agent-submit')));await tester.pump();@@ -269,7 +271,7 @@ void main() {}await chord(tester, LogicalKeyboardKey.keyN);await tester.pumpAndSettle();- await tester.tap(find.byKey(const Key('new-agent-folder')));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('create-agent-submit')));await tester.pump();@@ -345,7 +347,7 @@ void main() {await chord(tester, LogicalKeyboardKey.keyO);await chord(tester, LogicalKeyboardKey.keyN);await tester.pumpAndSettle();- await tester.tap(find.byKey(const Key('new-agent-folder')));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('create-agent-submit')));await tester.pump();diff --git a/desktop/test/new_agent_choices_layout_test.dart b/desktop/test/new_agent_choices_layout_test.dartindex 738465c55..5daa1be5f 100644--- a/desktop/test/new_agent_choices_layout_test.dart+++ b/desktop/test/new_agent_choices_layout_test.dart@@ -46,6 +46,23 @@ class _ChoicesApp extends AppNotifier {}}+ @override+ Future<Map<String, dynamic>> readProjectPreview(+ String machineId,+ String path,+ ) async => {+ 'path': path,+ 'branch': 'main',+ 'changedFiles': 2,+ 'readme': '# Harness\nOne window for your coding agents.\n\n## Development\nRun agents on your machines and keep every project within reach.',+ 'commit': {+ 'subject': 'Simplify the project picker',+ 'author': 'Alex',+ 'date': '2026-09-15T10:00:00Z',+ },+ 'contributors': ['Alex', 'Dee', 'Sam'],+ };+@overrideFuture<void> probeEngines(String machineId, {bool force = false}) async {}@@ -73,6 +90,7 @@ void main() {});for (final (size, scale) in [+ (const Size(1280, 1000), 1.0),(const Size(900, 720), 1.0),(const Size(880, 560), 1.0),(const Size(600, 700), 2.0),@@ -85,6 +103,14 @@ void main() {addTearDown(tester.view.reset);final app = _ChoicesApp();await app.agentPreference.select('codex');+ for (final path in [+ '/Users/example/code/workshop',+ '/Users/example/code/website',+ '/Users/example/code/harness',+ ]) {+ await app.projectHistory.select('local', path);+ }+ await app.projectHistory.select('local', null);addTearDown(() async {await tester.pumpWidget(const SizedBox());app.dispose();@@ -142,79 +168,35 @@ void main() {}await capture('initial');- await tester.tap(- find.byKey(const ValueKey('new-agent-folder-newProject')),- );- await tester.pumpAndSettle();- await capture('new-project');- await tester.tap(find.byKey(const ValueKey('new-agent-folder-remote')));- await tester.pumpAndSettle();- await capture('repository');- await tester.tap(find.byKey(const ValueKey('new-agent-folder-local')));- await tester.pumpAndSettle();- expect(find.byKey(const Key('new-agent-machine-field')), findsNothing);- await tester.tap(find.byKey(const Key('new-agent-machine-toggle')));- await tester.pumpAndSettle();- await capture('machines');- for (final label in [- 'iMac - Office',- if (scale == 1) ...['M2', 'T480 - Omarchy'],- 'Codex',- 'Claude Code',- 'Cursor',- ]) {- expect(- tester- .renderObject<RenderParagraph>(find.text(label).last)- .didExceedMaxLines,- isFalse,- reason: label,- );- }- if (scale == 1) {- final machineTop = tester- .getTopLeft(find.byKey(const ValueKey('new-agent-machine-local')))- .dy;- for (final id in ['office', 'home']) {- expect(- tester.getTopLeft(find.byKey(ValueKey('new-agent-machine-$id'))).dy,- machineTop,- );- }- final agentTop = tester- .getTopLeft(find.byKey(const ValueKey('new-agent-quick-codex')))- .dy;- expect(- tester- .getTopLeft(find.byKey(const ValueKey('new-agent-quick-cursor')))- .dy,- agentTop,- );+ for (final id in ['local', 'office', 'home', 'studio']) {+ expect(find.byKey(ValueKey('new-agent-machine-$id')), findsOneWidget);}- final visibleMachines = ['local', 'office', 'home']- .map((id) => find.byKey(ValueKey('new-agent-machine-$id')))- .where((finder) => finder.evaluate().isNotEmpty);- final top = tester.getTopLeft(visibleMachines.first).dy;- for (final choice in visibleMachines) {- expect(tester.getTopLeft(choice).dy, top);+ for (final id in ['codex', 'claude', 'opencode']) {+ expect(find.byKey(ValueKey('new-agent-quick-$id')), findsOneWidget);}- expect(- tester.getTopLeft(find.byKey(const Key('new-agent-machine-more'))).dy,- top,- );- await tester.tap(find.byKey(const Key('new-agent-machine-more')));+ final bar = find.byKey(const Key('new-agent-project-bar'));+ await tester.ensureVisible(bar);+ await tester.tap(bar);+ await tester.pumpAndSettle();+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);await tester.pumpAndSettle();- await tester.ensureVisible(find.text('Studio'));+ await capture('projects');+ await tester.enterText(+ find.byKey(const Key('new-agent-project-search')),+ 'owner/repo',+ );await tester.pumpAndSettle();- await tester.tap(find.text('Studio'));+ await capture('repository');+ await tester.testTextInput.receiveAction(TextInputAction.done);await tester.pumpAndSettle();- expect(+ await tester.ensureVisible(find.byKey(const ValueKey('new-agent-machine-studio')),- findsOneWidget,);+ await tester.tap(find.byKey(const ValueKey('new-agent-machine-studio')));+ await tester.pumpAndSettle();expect(find.byKey(const ValueKey('new-agent-machine-home')),- findsNothing,+ findsOneWidget,);final moreAgents = find.byKey(const Key('new-agent-engine-field'));await tester.ensureVisible(moreAgents);@@ -229,8 +211,8 @@ void main() {findsOneWidget,);expect(- find.byKey(const ValueKey('new-agent-quick-cursor')),- findsNothing,+ find.byKey(const ValueKey('new-agent-quick-opencode')),+ findsOneWidget,);expect(find.text('Kilo'), findsOneWidget);expect(diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dartindex 4e8b0e81e..5659e9886 100644--- a/desktop/test/new_agent_codex_profile_test.dart+++ b/desktop/test/new_agent_codex_profile_test.dart@@ -1,3 +1,5 @@+import 'support/new_agent_project.dart';+import 'dart:async';import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';@@ -250,8 +252,7 @@ void main() {);expect(find.text('Codex profile'), findsOneWidget);expect(find.text('Link a profile folder…'), findsOneWidget);- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -272,8 +273,7 @@ void main() {expect(find.text('Codex profile'), findsOneWidget);expectProfile(tester, 'work-login');expect(find.text('Link a profile folder…'), findsOneWidget);- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -289,15 +289,14 @@ void main() {local: false,initialPaths: const ['/custom/work-login'],);- await tester.tap(find.byKey(const Key('new-agent-machine-toggle')));await tester.pump();final machineField = tester.widget<AppChoicePicker<String>>(find.byKey(const Key('new-agent-machine-field')),);expect(machineField.options.single.label, 'This Mac');- expect(machineField.options.single.detail, 'Remote');+ expect(machineField.options.single.detail, isNull);expect(find.widgetWithText(FilledButton, 'Create Agent'), findsOneWidget);- expect(find.text('Choose a folder on This Mac.'), findsOneWidget);+ expect(find.byKey(const Key('new-agent-project-bar')), findsOneWidget);expect(find.byKey(const Key('new-agent-codex-profile-field')),findsOneWidget,@@ -344,21 +343,24 @@ void main() {..pending = Completer<void>();await open(tester, notifier: notifier);final folderFocus = tester- .widget<InkWell>(find.byKey(const Key('new-agent-folder')))+ .widget<InkWell>(find.byKey(const Key('new-agent-project-bar'))).focusNode!;folderFocus.requestFocus();await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pumpAndSettle();+ final searchFocus = tester+ .widget<TextField>(find.byKey(const Key('new-agent-project-search')))+ .focusNode!;final createButton = find.widgetWithText(FilledButton, 'Create Agent');expect(tester.widget<FilledButton>(createButton).onPressed, isNull);- expect(folderFocus.hasPrimaryFocus, isTrue);+ expect(searchFocus.hasPrimaryFocus, isTrue);expect(notifier.calls, isEmpty);notifier.pending!.complete();await tester.pumpAndSettle();expect(tester.widget<FilledButton>(createButton).onPressed, isNotNull);expect(- folderFocus.hasPrimaryFocus,+ searchFocus.hasPrimaryFocus,isTrue,reason: 'A late account lookup must not steal keyboard focus',);@@ -386,8 +388,7 @@ void main() {await tester.tap(find.text('codex1').last);await tester.pumpAndSettle();expectProfile(tester, 'codex1');- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -411,8 +412,7 @@ void main() {findsOneWidget,);expectProfile(tester, 'Default profile');- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -425,8 +425,7 @@ void main() {final notifier = await open(tester);await selectSecond(tester);expectProfile(tester, 'codex2');- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -507,8 +506,7 @@ void main() {find.byKey(const Key('new-agent-codex-profile-field')),findsNothing,);- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();@@ -528,8 +526,7 @@ void main() {find.text('Update Harness CLI on This Mac to choose a Codex profile.'),findsOneWidget,);- await tester.ensureVisible(find.byKey(const Key('new-agent-folder')));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create Agent'));await tester.pumpAndSettle();diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dartindex 2b3ac0239..778380cd5 100644--- a/desktop/test/new_agent_engine_check_test.dart+++ b/desktop/test/new_agent_engine_check_test.dart@@ -7,6 +7,8 @@// does not refuse it either — the frame goes out over the relay and nothing ever comes back, so the// app waits out its 30s timeout and then knows nothing. Meanwhile the panel had already promised a// launch, and the create failed at the far end with `exec: opencode: not found`.+import 'support/new_agent_project.dart';+import 'dart:async';import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';@@ -75,7 +77,7 @@ void main() {await tester.tap(find.text('open'));await tester.pumpAndSettle();// 'Browse…' until a folder is chosen; 'Change' after.- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pumpAndSettle();return notifier;}@@ -218,7 +220,6 @@ void main() {final pending = app.pending['machine-1'] = Completer<void>();await tester.tap(find.byKey(const Key('new-agent-retry-check')));await tester.pump();- await tester.tap(find.byKey(const Key('new-agent-machine-toggle')));await tester.pump();await tester.tap(find.byKey(const ValueKey('new-agent-machine-machine-2')));await tester.pumpAndSettle();diff --git a/desktop/test/new_agent_project_folder_test.dart b/desktop/test/new_agent_project_folder_test.dartindex 5d8b413ab..b490962a5 100644--- a/desktop/test/new_agent_project_folder_test.dart+++ b/desktop/test/new_agent_project_folder_test.dart@@ -104,6 +104,8 @@ void main() {await _mount(tester, app);expect(app.prepared, isEmpty);expect(connection.calls, isEmpty);+ await tester.tap(find.byKey(const Key('new-agent-project-bar')));+ await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('new-agent-folder-newProject')),);@@ -160,9 +162,9 @@ void main() {app.dispose();});await _mount(tester, app);- await tester.tap(find.byKey(const ValueKey('new-agent-folder-remote')));+ await tester.tap(find.byKey(const Key('new-agent-project-bar')));await tester.pumpAndSettle();- final field = find.byKey(const ValueKey('new-agent-repository'));+ final field = find.byKey(const Key('new-agent-project-search'));expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);expect(tester@@ -170,10 +172,12 @@ void main() {find.byKey(const ValueKey('create-agent-submit')),).onPressed,- isNull,+ isNotNull,);await tester.enterText(field, 'owner/repo');await tester.pump();+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();await tester.tap(find.byKey(const ValueKey('create-agent-submit')));await tester.pump();final (_, payload, result) = connection.calls.single;diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dartnew file mode 100644index 000000000..24612548f--- /dev/null+++ b/desktop/test/new_agent_project_picker_test.dart@@ -0,0 +1,251 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/project_folder.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_arrangement.dart';+import 'package:harness/widgets/new_agent_dialog.dart';++class _App extends AppNotifier {+ _App() : super(config: AppConfig.dev, authSession: AuthSession()) {+ for (final id in ['local', 'remote']) {+ machineStates[id] =+ MachineState(+ Machine(+ machineId: id,+ name: id,+ authMode: MachineAuthMode.remote,+ ),+ )+ ..localOnly = id == 'local'+ ..nodeOnline = true+ ..agents = [+ for (final name in ['alpha', 'beta'])+ Agent(+ id: '$id-$name',+ name: name,+ project: AgentProject(name: name, cwd: '/$id/$name'),+ ),+ ];+ }+ }+ final calls = <Map<String, Object?>>[];+ final previews = <String>[];+ final pending = <String, Completer<Map<String, dynamic>>>{};+ @override+ Future<void> probeEngines(String machineId, {bool force = false}) async {}+ @override+ Future<Map<String, dynamic>> listCodexProfiles(+ String machineId, {+ Set<String> observedPaths = const {},+ }) async => {'profiles': []};+ @override+ Future<Map<String, dynamic>> readProjectPreview(+ String machineId,+ String path,+ ) async {+ previews.add('$machineId:$path');+ return pending[path]?.future ??+ Future.value({'readme': 'README for $path', 'branch': 'main'});+ }++ @override+ Future<String?> createAgent(+ String machineId, {+ required String engine,+ required String folder,+ ProjectFolderRequest? projectFolder,+ bool bypassPermission = false,+ String? codexHome,+ String? swarmId,+ PaneSplitRequest? split,+ AgentCreationAttempt? attempt,+ }) async {+ calls.add({+ 'machine': machineId,+ 'engine': engine,+ 'folder': folder,+ 'project': projectFolder?.payload,+ });+ return null;+ }+}++void main() {+ late _App app;+ Future<void> mount(WidgetTester tester) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 1000);+ addTearDown(tester.view.reset);+ app = _App();+ await app.agentPreference.select('claude');+ addTearDown(() async {+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () =>+ showNewAgentDialog(context, app, 'local', source: 'test'),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ }++ Future<void> search(WidgetTester tester) async {+ final bar = find.byKey(const Key('new-agent-project-bar'));+ await tester.ensureVisible(bar);+ await tester.tap(bar);+ await tester.pumpAndSettle();+ }++ Future<void> type(WidgetTester tester, String value) async {+ await tester.enterText(+ find.byKey(const Key('new-agent-project-search')),+ value,+ );+ await tester.pumpAndSettle();+ }++ Future<void> enter(WidgetTester tester) async {+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'arrows preview, Enter selects, and reopening restores that project',+ (tester) async {+ await mount(tester);+ await search(tester);+ expect(+ find.byKey(const Key('new-agent-folder-newProject')),+ findsOneWidget,+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pumpAndSettle();+ expect(find.text('README for /local/beta'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pumpAndSettle();+ expect(find.text('README for /local/alpha'), findsOneWidget);+ await enter(tester);+ expect(find.byKey(const Key('new-agent-project-search')), findsNothing);+ expect(find.text('/local/alpha'), findsOneWidget);+ expect(app.calls, isEmpty);+ await search(tester);+ expect(find.text('README for /local/alpha'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.text('/local/alpha'), findsOneWidget);+ },+ );++ testWidgets(+ 'agent switching keeps the project; each machine restores its own choice',+ (tester) async {+ await mount(tester);+ await search(tester);+ await type(tester, 'alpha');+ await enter(tester);+ await tester.tap(find.byKey(const ValueKey('new-agent-quick-opencode')));+ await tester.pumpAndSettle();+ expect(find.text('/local/alpha'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('new-agent-machine-remote')));+ await tester.pumpAndSettle();+ expect(find.text('New project'), findsOneWidget);+ await search(tester);+ expect(find.byKey(const ValueKey('project-/local/alpha')), findsNothing);+ await type(tester, 'beta');+ await enter(tester);+ await tester.tap(find.byKey(const ValueKey('new-agent-machine-local')));+ await tester.pumpAndSettle();+ expect(find.text('/local/alpha'), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('new-agent-machine-remote')));+ await tester.pumpAndSettle();+ expect(find.text('/remote/beta'), findsOneWidget);+ await tester.tap(find.byKey(const Key('create-agent-submit')));+ await tester.pumpAndSettle();+ expect(app.calls.single, containsPair('folder', '/remote/beta'));+ expect(app.calls.single, containsPair('machine', 'remote'));+ expect(app.calls.single, containsPair('engine', 'opencode'));+ },+ );++ testWidgets(+ 'Git URL becomes the selected project; unknown searches do not choose New',+ (tester) async {+ await mount(tester);+ await search(tester);+ await type(tester, 'no such project');+ await enter(tester);+ expect(find.text('No matching projects'), findsOneWidget);+ expect(find.byKey(const Key('new-agent-project-search')), findsOneWidget);+ await type(tester, 'owner/repo');+ await enter(tester);+ expect(find.text('repo'), findsOneWidget);+ await search(tester);+ expect(+ tester+ .widget<TextField>(+ find.byKey(const Key('new-agent-project-search')),+ )+ .controller!+ .text,+ 'https://github.com/owner/repo.git',+ );+ await enter(tester);+ await tester.tap(find.byKey(const Key('create-agent-submit')));+ await tester.pumpAndSettle();+ expect(app.calls.single['project'], {+ 'projectSource': 'remote',+ 'repositoryUrl': 'https://github.com/owner/repo.git',+ });+ },+ );++ testWidgets(+ 'Command Enter creates the highlighted project, not the old selection',+ (tester) async {+ await mount(tester);+ await search(tester);+ await type(tester, 'alpha');+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();+ expect(app.calls.single['folder'], '/local/alpha');+ expect(find.byType(AlertDialog), findsNothing);+ },+ );++ testWidgets('a late preview never replaces the newly highlighted project', (+ tester,+ ) async {+ await mount(tester);+ app.pending['/local/alpha'] = Completer();+ await search(tester);+ await tester.enterText(+ find.byKey(const Key('new-agent-project-search')),+ 'alpha',+ );+ await tester.pump(const Duration(milliseconds: 200));+ expect(app.previews, contains('local:/local/alpha'));+ await type(tester, 'beta');+ app.pending['/local/alpha']!.complete({'readme': 'STALE README'});+ await tester.pumpAndSettle();+ expect(find.text('README for /local/beta'), findsOneWidget);+ expect(find.text('STALE README'), findsNothing);+ });+}diff --git a/desktop/test/project_history_test.dart b/desktop/test/project_history_test.dartnew file mode 100644index 000000000..a46a00979--- /dev/null+++ b/desktop/test/project_history_test.dart@@ -0,0 +1,84 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/core/project_history.dart';++class _Store implements LocalKeyValueStore {+ String? value;+ Completer<String?>? pending;+ bool failWrites = false;+ @override+ Future<String?> read(String key) async =>+ pending == null ? value : pending!.future;+ @override+ Future<void> write(String key, String value) async {+ if (failWrites) throw StateError('unavailable');+ this.value = value;+ }++ @override+ Future<void> delete(String key) async => value = null;+}++void main() {+ test(+ 'remembers projects separately on each machine, including New',+ () async {+ final store = _Store();+ final history = ProjectHistory(store);+ await history.select('local', '/code/first');+ await history.select('remote', '/srv/other');+ await history.select('local', '/code/second');+ await history.select('local', '/code/first');+ await history.select('remote', null);+ final restored = ProjectHistory(store);+ await restored.load();+ expect(restored.selected('local'), '/code/first');+ expect(restored.recent('local'), ['/code/first', '/code/second']);+ expect(restored.hasSelection('remote'), isTrue);+ expect(restored.selected('remote'), isNull);+ expect(restored.recent('remote'), ['/srv/other']);+ expect(restored.hasSelection('unknown'), isFalse);+ },+ );++ test(+ 'a selection made while loading wins over the saved selection',+ () async {+ final store = _Store()..pending = Completer<String?>();+ final history = ProjectHistory(store);+ final selecting = history.select('local', '/code/new');+ store.pending!.complete(+ jsonEncode({+ 'local': {+ 'selected': '/code/old',+ 'recent': ['/code/old'],+ },+ }),+ );+ await selecting;+ expect(history.selected('local'), '/code/new');+ expect(history.recent('local'), ['/code/new', '/code/old']);+ expect(jsonDecode(store.value!)['local']['selected'], '/code/new');+ },+ );++ test(+ 'bad state and unavailable storage never prevent an in-memory choice',+ () async {+ final store = _Store()+ ..value = 'not json'+ ..failWrites = true;+ final history = ProjectHistory(store);+ await history.select('local', '/code/project');+ await history.select('local', 'relative/path');+ await history.select('local', '/code/invalid\npath');+ expect(history.selected('local'), '/code/project');+ store.failWrites = false;+ await history.select('local', null);+ expect(history.recent('local'), ['/code/project']);+ },+ );+}diff --git a/desktop/test/project_preview_test.dart b/desktop/test/project_preview_test.dartnew file mode 100644index 000000000..dd3b685a4--- /dev/null+++ b/desktop/test/project_preview_test.dart@@ -0,0 +1,75 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/project_preview.dart';++void main() {+ late Directory root;+ setUp(+ () async =>+ root = await Directory.systemTemp.createTemp('harness-preview-'),+ );+ tearDown(() => root.delete(recursive: true));++ Future<void> git(List<String> args) async {+ final result = await Process.run('git', ['-C', root.path, ...args]);+ expect(result.exitCode, 0, reason: '${result.stderr}');+ }++ test('previews README, branch, commit and authors without running a fsmonitor hook', () async {+ await git(['init', '-b', 'preview']);+ await File('${root.path}/README.md')+ .writeAsString('# Project\nExisting content');+ await git(['add', 'README.md']);+ await git([+ '-c',+ 'user.name=Preview Author',+ '-c',+ '[email protected]',+ '-c',+ 'commit.gpgsign=false',+ '-c',+ 'core.hooksPath=/dev/null',+ 'commit',+ '-m',+ 'First commit',+ ]);+ await File('${root.path}/README.md')+ .writeAsString('# Project\nUpdated content');+ await git(['config', 'core.fsmonitor', 'touch ${root.path}/monitor-ran']);+ final preview = await readLocalProjectPreview(root.path);+ expect(preview['readme'], '# Project\nUpdated content');+ expect(preview['branch'], 'preview');+ expect(preview['changedFiles'], 1);+ expect(preview['commit'], containsPair('subject', 'First commit'));+ expect(preview['contributors'], ['Preview Author']);+ expect(await File('${root.path}/monitor-ran').exists(), isFalse);+ });++ test(+ 'ordinary folders work, README reads are bounded, symlinks stay unread',+ () async {+ final readme = File('${root.path}/README.md');+ await readme.writeAsString('a' * 40000);+ expect(+ (await readLocalProjectPreview(root.path))['readme'].length,+ 32768,+ );+ await readme.delete();+ await File('${root.path}/private.txt').writeAsString('private');+ await Link(readme.path).create('${root.path}/private.txt');+ final preview = await readLocalProjectPreview(root.path);+ expect(preview['readme'], isNull);+ expect(preview['files'], contains('private.txt'));+ expect(preview['commit'], isNull);+ expect(+ (await readLocalProjectPreview('${root.path}/missing'))['error'],+ 'NOT_FOUND',+ );+ expect(+ (await readLocalProjectPreview('relative'))['error'],+ 'INVALID_PATH',+ );+ },+ );+}diff --git a/desktop/test/support/new_agent_project.dart b/desktop/test/support/new_agent_project.dartnew file mode 100644index 000000000..ca6700321--- /dev/null+++ b/desktop/test/support/new_agent_project.dart@@ -0,0 +1,14 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++Future<void> browseNewAgentProject(WidgetTester tester) async {+ final bar = find.byKey(const Key('new-agent-project-bar'));+ if (bar.evaluate().isNotEmpty) {+ await tester.ensureVisible(bar);+ await tester.tap(bar);+ await tester.pumpAndSettle();+ }+ final browse = find.byKey(const Key('new-agent-project-browse'));+ await tester.ensureVisible(browse);+ await tester.tap(browse);+}diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dartindex 144ff57c1..128818f8b 100644--- a/desktop/test/swarm_interactions_test.dart+++ b/desktop/test/swarm_interactions_test.dart@@ -1,3 +1,5 @@+import 'support/new_agent_project.dart';+import 'dart:async';import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';@@ -593,9 +595,8 @@ void main() {);await tester.tap(find.text('Open'));await tester.pump(const Duration(milliseconds: 300));- await tester.tap(find.text('Browse…'));+ await browseNewAgentProject(tester);await tester.pump();- await tester.tap(find.byKey(const Key('new-agent-machine-toggle')));await tester.pump();final field = find.byKey(const Key('new-agent-machine-field'));tester.widget<AppChoicePicker<String>>(field).onChanged('b');@@ -605,7 +606,7 @@ void main() {folder.answer.complete('/old-machine-folder');await tester.pump();expect(find.textContaining('/old-machine-folder'), findsNothing);- expect(find.text('Browse…'), findsOneWidget);+ expect(find.text('New project'), findsOneWidget);await tester.pumpWidget(const SizedBox());app.dispose();},diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.mdindex d816317ca..4ed495a79 100644--- a/docs/harness-v2-handoff.md+++ b/docs/harness-v2-handoff.md@@ -45,20 +45,38 @@ Fifty Flutter checks, 69 CLI checks, static analysis and CLI typechecking pass.Logs: `/private/tmp/harness-friendly-names-tests.log` and`/private/tmp/harness-friendly-names-cli-tests.log`.-### Approved next: project picker in New Agent--Build Agent → Machine → Project in a dialog as spacious as Open Agent. Keep-Codex, Claude Code and OpenCode visible in stable order; show all machines.-Project combines a pinned New project, recent folders, search, Git URL and-Browse. Arrow selection updates a preview from README, Git history, contributors-and files. Enter selects and collapses into a project bar; clicking it searches-again. Remember the last project per machine; first use selects New project.-Profiles and permissions stay in Options. Cmd-Return creates the agent.-The user has renewed authorization to push each completed feature separately.+### Project picker in New Agent++Agent → Machine → Project now replaces the old New / Local / Remote form.+Codex, Claude Code and OpenCode stay visible in stable order; all machines are+visible. Wide windows use quiet horizontal choice rows; small windows and large+text wrap and scroll. Options retains Codex profiles and permission controls.++Project combines a pinned New project, machine-scoped recent folders, search,+existing GitHub HTTPS/SSH/owner-repo cloning, and Browse. Arrows update the+README/Git/files preview, Enter selects into a compact project bar, and clicking+it reopens search. Cmd-Return creates from the highlighted project. Unmatched+searches never implicitly select New. Each machine remembers its last choice;+first use selects New. Switching engines preserves the project. Prepared-folder+recovery and uncertain-create status checks remain intact.++Local previews read bounded existing files and Git metadata. Remote previews use+the new encrypted `project_preview` RPC, requiring this CLI on the local relay+and remote machine; older CLIs show an unavailable preview without blocking+project selection. No live CLI daemon has been upgraded or restarted.++81 desktop tests and 60 CLI tests pass, plus the final affected layout/keyboard+rerun. Full desktop analysis has only 12 existing vendored xterm info messages;+CLI typechecking passes. Logs: `/private/tmp/harness-launcher-final-tests.log`,+`/private/tmp/harness-launcher-row-tests.log`,+`/private/tmp/harness-launcher-final-cli-tests.log`, and+`/private/tmp/harness-launcher-full-analyze.log`. Render captures:+`/private/tmp/harness-project-launcher-captures`.-The latest installed preview is **0c764cf** (receipt-`/private/tmp/harness-minimal-preview-install.json`); later search/device/chooser-refinements have not been installed yet.+The user has renewed authorization to push each completed feature separately.+The latest installed preview is still **0c764cf** (receipt+`/private/tmp/harness-minimal-preview-install.json`); the new launcher and later+search/device/chooser refinements are awaiting the next verified install.### Quiet agent choices