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
Simplify agent creation and add GitHub cloning
dee06ba77c2f3ec
diff --git a/desktop/lib/core/agent_preference.dart b/desktop/lib/core/agent_preference.dartnew file mode 100644index 000000000..7f0cf9585--- /dev/null+++ b/desktop/lib/core/agent_preference.dart@@ -0,0 +1,35 @@+import 'local_key_value_store.dart';++/// Remembers an agent choice, independently of a machine, profile or permission.+class AgentPreference {+ AgentPreference(this.storage);+ final LocalKeyValueStore? storage;+ static const _key = 'new_agent_engine';+ String? value;+ Future<void>? _loading;+ Future<void> _writes = Future.value();+ int _revision = 0;++ Future<void> load() => _loading ??= _read();+ Future<void> _read() async {+ final revision = _revision;+ try {+ final stored = await storage?.read(_key);+ if (revision == _revision && revision == 0) value = stored;+ } catch (_) {+ /* A missing preference never blocks a new agent. */+ }+ }++ Future<void> select(String engine) {+ _revision++;+ value = engine;+ return _writes = _writes.then((_) async {+ try {+ await storage?.write(_key, engine);+ } catch (_) {+ /* Keep the current choice usable if persistence fails. */+ }+ });+ }+}diff --git a/desktop/lib/core/repository_clone.dart b/desktop/lib/core/repository_clone.dartnew file mode 100644index 000000000..5424d3b74--- /dev/null+++ b/desktop/lib/core/repository_clone.dart@@ -0,0 +1,179 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:path/path.dart' as p;++class GitHubRepository {+ const GitHubRepository._(this.url, this.name);+ final String url, name;++ static GitHubRepository? parse(String input) {+ final text = input.trim();+ final ssh = text.startsWith('[email protected]:');+ String path;+ if (ssh) {+ path = text.substring('[email protected]:'.length);+ } else {+ final uri = Uri.tryParse(+ text.contains('://') ? text : 'https://github.com/$text',+ );+ if (uri == null ||+ uri.scheme != 'https' ||+ uri.host != 'github.com' ||+ uri.userInfo.isNotEmpty ||+ uri.hasPort ||+ uri.hasQuery ||+ uri.hasFragment)+ return null;+ path = uri.path.replaceFirst(RegExp(r'^/'), '');+ }+ path = path+ .replaceFirst(RegExp(r'/$'), '')+ .replaceFirst(RegExp(r'\.git$'), '');+ final parts = path.split('/');+ if (parts.length != 2 ||+ !RegExp(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}$').hasMatch(parts[0]) ||+ !RegExp(r'^[A-Za-z0-9_.-]{1,100}$').hasMatch(parts[1]) ||+ parts[1] == '.' ||+ parts[1] == '..')+ return null;+ return GitHubRepository._(+ ssh ? '[email protected]:$path.git' : 'https://github.com/$path.git',+ parts[1],+ );+ }+}++class RepositoryCloneException implements Exception {+ const RepositoryCloneException(this.message);+ final String message;+ @override+ String toString() => message;+}++typedef GitCloneProcess = Future<Process> Function(+ List<String> arguments,+ Map<String, String> environment,+);++/// Clones into a private staging directory. Existing working folders are never+/// reused or removed, and a failed/cancelled clone leaves no partial project.+class RepositoryClone {+ RepositoryClone({GitCloneProcess? startProcess})+ : _startProcess = startProcess ?? _startGit;+ final GitCloneProcess _startProcess;+ Process? _process;+ bool _cancelled = false;+ bool _started = false;++ static Future<Process> _startGit(+ List<String> arguments,+ Map<String, String> environment,+ ) => Process.start('git', arguments, environment: environment);++ void cancel() {+ _cancelled = true;+ _process?.kill();+ }++ Future<String> run(GitHubRepository repository, String parent) async {+ if (_started) throw StateError('A clone can only be started once.');+ _started = true;+ Directory? staging;+ Timer? deadline;+ var timedOut = false;+ try {+ if (!p.isAbsolute(parent) || !await Directory(parent).exists()) {+ throw const RepositoryCloneException(+ 'Choose an existing destination folder.',+ );+ }+ final destination = p.join(parent, repository.name);+ if (await FileSystemEntity.type(destination, followLinks: false) !=+ FileSystemEntityType.notFound) {+ throw RepositoryCloneException(+ '“${repository.name}” already exists here. Choose another destination, or open that folder.',+ );+ }+ if (_cancelled) throw const RepositoryCloneException('Clone cancelled.');+ staging = await Directory(parent).createTemp('.harness-clone-');+ final checkout = p.join(staging.path, 'checkout');+ final process = _process = await _startProcess(+ ['clone', '--', repository.url, checkout],+ {+ 'GIT_TERMINAL_PROMPT': '0',+ 'GCM_INTERACTIVE': 'Never',+ if (!Platform.environment.containsKey('GIT_SSH_COMMAND'))+ 'GIT_SSH_COMMAND': 'ssh -oBatchMode=yes -oConnectTimeout=20',+ },+ );+ unawaited(process.stdin.close());+ if (_cancelled) process.kill();+ deadline = Timer(const Duration(minutes: 5), () {+ timedOut = true;+ process.kill();+ });+ // Drain both streams, retaining only a bounded diagnostic for classifying+ // failures. Git URLs/credential-helper output never enter the UI or logs.+ final output = process.stdout.drain<void>();+ var diagnostic = '';+ final errors = process.stderr+ .transform(const Utf8Decoder(allowMalformed: true))+ .forEach((chunk) {+ if (diagnostic.length < 8192)+ diagnostic += chunk.substring(+ 0,+ chunk.length.clamp(0, 8192 - diagnostic.length),+ );+ });+ final code = await process.exitCode;+ await output;+ await errors;+ if (_cancelled) throw const RepositoryCloneException('Clone cancelled.');+ if (timedOut)+ throw const RepositoryCloneException(+ 'Cloning took too long. Check the connection and retry.',+ );+ if (code != 0) {+ if (RegExp(+ r'authentication|permission denied|could not read Username|repository not found',+ caseSensitive: false,+ ).hasMatch(diagnostic)) {+ throw const RepositoryCloneException(+ 'Could not access this repository. Check the URL and your GitHub access on this computer.',+ );+ }+ throw const RepositoryCloneException(+ 'Could not clone the repository. Check the URL and connection, then retry.',+ );+ }+ if (await FileSystemEntity.type(destination, followLinks: false) !=+ FileSystemEntityType.notFound) {+ throw RepositoryCloneException(+ '“${repository.name}” was created while cloning. Choose another destination.',+ );+ }+ await Directory(checkout).rename(destination);+ return destination;+ } on ProcessException {+ throw const RepositoryCloneException(+ 'Git could not start. Install Git on this computer, then retry.',+ );+ } on FileSystemException {+ throw const RepositoryCloneException(+ 'Could not write to this destination. Choose a folder you can edit.',+ );+ } finally {+ deadline?.cancel();+ _process = null;+ if (staging != null) {+ try {+ if (await staging.exists()) await staging.delete(recursive: true);+ } on FileSystemException {+ /* The checkout outcome remains authoritative. */+ }+ }+ }+ }+}diff --git a/desktop/lib/shared/widgets/app_select_field.dart b/desktop/lib/shared/widgets/app_select_field.dartindex 055ccd3ff..332d685b7 100644--- a/desktop/lib/shared/widgets/app_select_field.dart+++ b/desktop/lib/shared/widgets/app_select_field.dart@@ -72,6 +72,7 @@ class AppSelectField<T> extends StatefulWidget {required this.options,required this.onChanged,this.width,+ this.trigger,});final T value;@@ -82,6 +83,10 @@ class AppSelectField<T> extends StatefulWidget {/// take whatever its parent gives.final double? width;+ /// An alternate compact trigger, such as the agent picker's More button.+ /// Selection, keyboard navigation and menu rows remain shared.+ final Widget? trigger;+@overrideState<AppSelectField<T>> createState() => _AppSelectFieldState<T>();}@@ -251,61 +256,63 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {: Colors.transparent,),),- child: Row(- children: [- Expanded(- child: Row(- children: [- if (current?.leading != null) ...[- current!.leading!(),- const SizedBox(width: 8),- ],- Flexible(- child: Text(- current?.label ?? '—',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontFamily: AppFont.sans,- fontFamilyFallback: AppFont.sansFallback,- fontSize: AppControl.fontSize,- fontWeight: AppControl.fontWeight,- letterSpacing: AppFont.trackingFor(- AppControl.fontSize,+ child:+ widget.trigger ??+ Row(+ children: [+ Expanded(+ child: Row(+ children: [+ if (current?.leading != null) ...[+ current!.leading!(),+ const SizedBox(width: 8),+ ],+ Flexible(+ child: Text(+ current?.label ?? '—',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: AppControl.fontSize,+ fontWeight: AppControl.fontWeight,+ letterSpacing: AppFont.trackingFor(+ AppControl.fontSize,+ ),+ color: AppPalette.textPrimary,+ ),),- color: AppPalette.textPrimary,),- ),- ),- if (current?.note != null) ...[- const SizedBox(width: 8),- Flexible(- child: Text(- current!.note!,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontFamily: AppFont.sans,- fontFamilyFallback: AppFont.sansFallback,- fontSize: 11.5,- color: AppPalette.textFaint,+ if (current?.note != null) ...[+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ current!.note!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontFamily: AppFont.sans,+ fontFamilyFallback: AppFont.sansFallback,+ fontSize: 11.5,+ color: AppPalette.textFaint,+ ),+ ),),- ),- ),- ],- ],- ),- ),- const SizedBox(width: 6),- Icon(- Icons.expand_more_rounded,- size: AppControl.iconSize,- color: _hovered || controller.isOpen- ? AppPalette.textPrimary- : AppPalette.textSecondary,+ ],+ ],+ ),+ ),+ const SizedBox(width: 6),+ Icon(+ Icons.expand_more_rounded,+ size: AppControl.iconSize,+ color: _hovered || controller.isOpen+ ? AppPalette.textPrimary+ : AppPalette.textSecondary,+ ),+ ],),- ],- ),),),),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 1b0b94805..6b4b61b7d 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -13,6 +13,7 @@ import '../auth/cli_link.dart';import '../auth/cli_login.dart';import '../bootstrap/environment_provisioner.dart';import '../core/config.dart';+import '../core/agent_preference.dart';import '../core/build_identity.dart';import '../core/engine_availability.dart';import '../core/local_hostname.dart';@@ -846,6 +847,7 @@ class AppNotifier extends ChangeNotifier {// layout is remembered: with a layout store there is a state file, and// without one (the tests) nothing is written anywhere.dial = DialState(paneLayoutStore?.storage),+ agentPreference = AgentPreference(paneLayoutStore?.storage),session = authSession,_store = configStore,cliLogin = cliLogin ?? CliLogin(),@@ -889,6 +891,7 @@ class AppNotifier extends ChangeNotifier {/// frames from the local daemon; its own notifier, so the row rebuilds/// without dragging the whole rail through a machine-list rebuild.final DialState dial;+ final AgentPreference agentPreference;TerminalPane? get focusedPane {final id = focusedPaneId;diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dartindex c488ba65b..694562a08 100644--- a/desktop/lib/state/swarm_catalog.dart+++ b/desktop/lib/state/swarm_catalog.dart@@ -67,9 +67,13 @@ class SavedSwarmProject {}class SwarmProjectGroup {- SwarmProjectGroup({required this.id, required this.name, this.saved});+ SwarmProjectGroup({required this.id, required String name, this.saved})+ : _discoveredName = name;final String id;- final String name;+ final String _discoveredName;+ // An explicitly saved folder is the user's choice of project identity/name.+ // Discovery order across checkouts must not hide it under another folder name.+ String get name => saved?.name ?? _discoveredName;SavedSwarmProject? saved;final List<SwarmAgentRef> agents = [];}diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dartnew file mode 100644index 000000000..1df250c20--- /dev/null+++ b/desktop/lib/widgets/agent_picker.dart@@ -0,0 +1,109 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_select_field.dart';+import 'engine_identity.dart';++class AgentPicker extends StatelessWidget {+ const AgentPicker({+ super.key,+ required this.value,+ required this.options,+ required this.onChanged,+ });+ final String value;+ final List<SelectOption<String>> options;+ final ValueChanged<String> onChanged;+ static const quickAgents = ['codex', 'claude', 'cursor'];++ @override+ Widget build(BuildContext context) {+ final other = !quickAgents.contains(value);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ for (final id in quickAgents) ...[+ Expanded(+ child: Semantics(+ selected: value == id,+ child: TextButton.icon(+ key: ValueKey('new-agent-quick-$id'),+ onPressed: () => onChanged(id),+ icon: EngineMark(engine: id, size: 18),+ label: Text(+ id == 'claude' ? 'Claude Code' : engineIdentity(id).label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textPrimary,+ backgroundColor: value == id+ ? grid.AppSurface.recessHover+ : grid.AppSurface.recess,+ minimumSize: const Size(0, 38),+ padding: const EdgeInsets.symmetric(horizontal: 8),+ textStyle: const TextStyle(+ fontSize: 13,+ fontWeight: FontWeight.w500,+ ),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(8),+ side: BorderSide(+ color: value == id+ ? grid.AppPalette.accentOnSurface+ : Colors.transparent,+ ),+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 8),+ ],+ Tooltip(+ message: other+ ? '${engineIdentity(value).label} selected · More agents'+ : 'More agents',+ child: AppSelectField<String>(+ key: const Key('new-agent-engine-field'),+ value: value,+ options: options,+ onChanged: onChanged,+ width: 42,+ trigger: Icon(+ Icons.more_horiz,+ size: 20,+ color: other+ ? grid.AppPalette.accentOnSurface+ : grid.AppPalette.textSecondary,+ ),+ ),+ ),+ ],+ ),+ if (other)+ Padding(+ padding: const EdgeInsets.only(top: 10),+ child: Row(+ children: [+ EngineMark(engine: value, size: 18),+ const SizedBox(width: 8),+ Text(+ engineIdentity(value).label,+ style: const TextStyle(fontSize: 13),+ ),+ const SizedBox(width: 6),+ Icon(+ Icons.check,+ size: 14,+ color: grid.AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/widgets/clone_repository_dialog.dart b/desktop/lib/widgets/clone_repository_dialog.dartnew file mode 100644index 000000000..4df54957a--- /dev/null+++ b/desktop/lib/widgets/clone_repository_dialog.dart@@ -0,0 +1,203 @@+import 'package:file_selector/file_selector.dart';+import 'package:flutter/material.dart';+import 'package:path/path.dart' as p;++import '../core/repository_clone.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/labeled_field.dart';++Future<String?> showCloneRepositoryDialog(+ BuildContext context, {+ String? initialFolder,+}) => showAppDialog<String>(+ context: context,+ builder: (_) => CloneRepositoryDialog(initialFolder: initialFolder),+);++class CloneRepositoryDialog extends StatefulWidget {+ const CloneRepositoryDialog({+ super.key,+ this.initialFolder,+ this.createClone,+ });+ final String? initialFolder;+ final RepositoryClone Function()? createClone;+ @override+ State<CloneRepositoryDialog> createState() => _CloneRepositoryDialogState();+}++class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {+ final _url = TextEditingController();+ String? _parent, _error;+ RepositoryClone? _clone;+ bool _picking = false, _closing = false;+ bool get _busy => _clone != null;+ GitHubRepository? get _repository => GitHubRepository.parse(_url.text);++ @override+ void dispose() {+ _clone?.cancel();+ _url.dispose();+ super.dispose();+ }++ Future<void> _chooseDestination() async {+ setState(() => _picking = true);+ try {+ final folder = await getDirectoryPath(+ initialDirectory:+ _parent ??+ (widget.initialFolder == null+ ? null+ : p.dirname(widget.initialFolder!)),+ confirmButtonText: 'Choose destination',+ );+ if (mounted && folder != null)+ setState(() {+ _parent = folder;+ _error = null;+ });+ } catch (_) {+ if (mounted)+ setState(() => _error = 'Could not open the folder picker. Try again.');+ } finally {+ if (mounted) setState(() => _picking = false);+ }+ }++ Future<void> _submit() async {+ final repository = _repository, parent = _parent;+ if (repository == null || parent == null || _busy) return;+ final clone = widget.createClone?.call() ?? RepositoryClone();+ setState(() {+ _clone = clone;+ _error = null;+ });+ String? result;+ try {+ result = await clone.run(repository, parent);+ } on RepositoryCloneException catch (error) {+ if (mounted && !_closing) setState(() => _error = error.message);+ } catch (_) {+ if (mounted && !_closing)+ setState(+ () => _error = 'Could not clone the repository. Please retry.',+ );+ } finally {+ if (mounted) {+ setState(() => _clone = null);+ if (result != null || _closing) Navigator.pop(context, result);+ }+ }+ }++ void _cancel() {+ if (_busy) {+ setState(() => _closing = true);+ _clone!.cancel();+ } else {+ Navigator.pop(context);+ }+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final repository = _repository;+ return PopScope(+ canPop: !_busy,+ child: AlertDialog(+ title: const Text('Clone repository'),+ content: SizedBox(+ width: 520,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const FieldLabel('GitHub repository'),+ TextField(+ key: const ValueKey('clone-repository-url'),+ controller: _url,+ autofocus: true,+ readOnly: _busy,+ decoration: const InputDecoration(+ hintText: 'https://github.com/owner/repository',+ ),+ onChanged: (_) => setState(() => _error = null),+ onSubmitted: (_) => _submit(),+ ),+ const SizedBox(height: 6),+ Text(+ 'Use an HTTPS or SSH URL, or owner/repository.',+ style: Theme.of(context).textTheme.bodySmall,+ ),+ const SizedBox(height: 20),+ const FieldLabel('Destination on this computer'),+ OutlinedButton.icon(+ onPressed: _busy || _picking ? null : _chooseDestination,+ icon: const Icon(Icons.folder_open_outlined, size: 18),+ label: Text(+ _parent ?? 'Choose folder…',+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),+ style: OutlinedButton.styleFrom(+ alignment: Alignment.centerLeft,+ padding: const EdgeInsets.symmetric(+ horizontal: 12,+ vertical: 14,+ ),+ foregroundColor: grid.AppPalette.textPrimary,+ ),+ ),+ if (_parent != null && repository != null) ...[+ const SizedBox(height: 8),+ Text(+ 'Creates ${p.join(_parent!, repository.name)}',+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ if (_busy) ...[+ const SizedBox(height: 20),+ const LinearProgressIndicator(minHeight: 2),+ const SizedBox(height: 8),+ Text(+ _closing ? 'Cancelling…' : 'Cloning ${repository!.name}…',+ style: Theme.of(context).textTheme.bodySmall,+ ),+ ],+ if (_error != null) ...[+ const SizedBox(height: 16),+ Semantics(+ liveRegion: true,+ child: Text(+ _error!,+ style: TextStyle(+ color: Theme.of(context).colorScheme.error,+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ onPressed: _closing ? null : _cancel,+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed:+ _busy || _picking || repository == null || _parent == null+ ? null+ : _submit,+ child: const Text('Clone repository'),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/widgets/codex_profile_field.dart b/desktop/lib/widgets/codex_profile_field.dartindex c28643b50..8acbdd60e 100644--- a/desktop/lib/widgets/codex_profile_field.dart+++ b/desktop/lib/widgets/codex_profile_field.dart@@ -5,6 +5,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import '../core/codex_profiles.dart';import '../state/app_state.dart';+import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_select_field.dart';import '../shared/widgets/labeled_field.dart';import 'remote_folder_picker.dart';@@ -179,13 +180,6 @@ class _CodexProfileFieldState extends State<CodexProfileField> {@overrideWidget build(BuildContext context) {// Default is launch behavior, not another discovered account folder.- final showPicker = _profiles.length >= 2;- final remainingProfile = _profiles.length == 1 ? _profiles.single : null;- final canChooseRemaining =- !showPicker &&- !_loading &&- _error == null &&- widget.value?.path != remainingProfile?.path;final choices = {for (final profile in _profiles) profile.path: profile,if (widget.value != null) widget.value!.path: widget.value!,@@ -194,37 +188,41 @@ class _CodexProfileFieldState extends State<CodexProfileField> {crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,children: [- if (showPicker) ...[- const FieldLabel('Codex profile'),- AppSelectField<String>(- key: const Key('new-agent-codex-profile-field'),- value: widget.value?.path ?? '',- options: [- SelectOption(- value: '',- label: 'Default',- note: _loading ? 'loading profiles…' : null,- detail: 'Use this machine’s normal Codex launch.',+ Row(+ children: [+ const Expanded(child: FieldLabel('Codex profile')),+ Tooltip(+ message:+ 'A profile is the Codex folder containing your account and settings '+ '(CODEX_HOME). Profiles stay on the selected machine.',+ child: Icon(+ LucideIcons.info,+ size: 14,+ color: grid.AppPalette.textSecondary,),- for (final profile in choices.values)- SelectOption(- value: profile.path,- label: profile.label,- detail: profile.path,- ),- ],- onChanged: (value) => _select(choices[value]),- ),- ],- if (canChooseRemaining)- TextButton(- onPressed: _linking ? null : () => _select(remainingProfile),- child: Text(- remainingProfile == null- ? 'Use default profile'- : 'Use ${remainingProfile.label}',),- ),+ ],+ ),+ AppSelectField<String>(+ key: const Key('new-agent-codex-profile-field'),+ value: widget.value?.path ?? '',+ options: [+ SelectOption(+ value: '',+ label: 'Default profile',+ note: _loading ? 'loading profiles…' : null,+ detail: 'Use this machine’s normal Codex launch.',+ ),+ for (final profile in choices.values)+ SelectOption(+ value: profile.path,+ label: profile.label,+ detail: profile.path,+ ),+ ],+ onChanged: (value) => _select(choices[value]),+ ),+ const SizedBox(height: 4),Row(children: [Expanded(@@ -232,6 +230,14 @@ class _CodexProfileFieldState extends State<CodexProfileField> {alignment: Alignment.centerLeft,child: TextButton(onPressed: _linking ? null : _link,+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ padding: const EdgeInsets.symmetric(+ horizontal: 0,+ vertical: 6,+ ),+ minimumSize: const Size(0, 32),+ ),child: Text(_linking ? 'Linking profile…' : 'Link a profile folder…',),@@ -245,10 +251,6 @@ class _CodexProfileFieldState extends State<CodexProfileField> {),],),- Text(- 'Use the folder your Codex shortcut points to (CODEX_HOME).',- style: Theme.of(context).textTheme.bodySmall,- ),if (_error != null)Text(_error!,diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex aae765326..aeb937946 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -16,6 +16,8 @@ import '../shared/widgets/labeled_field.dart';import '../state/app_state.dart';import 'engine_identity.dart';import 'codex_profile_field.dart';+import 'clone_repository_dialog.dart';+import 'agent_picker.dart';import 'remote_folder_picker.dart';/// Mirrors the harness CLI's `BYPASS_PERMISSION_FLAGS`@@ -112,7 +114,13 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {@overridevoid initState() {super.initState();- _engine = _preferredInstalledEngine();+ final remembered = widget.notifier.agentPreference.value;+ if (allEngines.any((identity) => identity.id == remembered)) {+ _engine = remembered!;+ _engineChosenByUser = true;+ } else {+ _engine = _preferredInstalledEngine();+ }// Which engines this machine actually has. Asked here rather than at// connect because the answer costs the far side one interactive shell per// engine and is only ever read on this screen. Deferred a frame so the@@ -128,10 +136,25 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted) {unawaited(_probeEngines(initialProbe: widget.initialEngineProbe));+ unawaited(_loadAgentPreference());}});}+ Future<void> _loadAgentPreference() async {+ await widget.notifier.agentPreference.load();+ if (!mounted || _submitting || _engineChosenByUser) return;+ final remembered = widget.notifier.agentPreference.value;+ if (allEngines.any((identity) => identity.id == remembered)) {+ setState(() {+ _engine = remembered!;+ _engineChosenByUser = true;+ _codexProfile = null;+ _codexProfilesBusy = true;+ });+ }+ }+String _preferredInstalledEngine() {final engines = widget.notifier.stateOf(_machineId)?.engines;if (engines?.loaded != true || engines?[_engine]?.installed == true) {@@ -371,6 +394,24 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {Navigator.of(context).pop();}+ Future<void> _cloneRepository() async {+ if (_picking || !_machineIsThisComputer) return;+ final revision = _machineRevision;+ setState(() => _picking = true);+ final folder = await showCloneRepositoryDialog(+ context,+ initialFolder: _folder,+ );+ if (!mounted) return;+ setState(() {+ _picking = false;+ if (folder != null && revision == _machineRevision) {+ _folder = folder;+ _error = null;+ }+ });+ }+@overrideWidget build(BuildContext context) {// Reads colour tokens, and lives in an Overlay — a top-down rebuild never@@ -517,7 +558,22 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {},),const SizedBox(height: _gapField),- const FieldLabel('Project folder'),+ Row(+ children: [+ const Expanded(child: FieldLabel('Working folder')),+ if (_machineIsThisComputer)+ TextButton(+ onPressed: _picking ? null : _cloneRepository,+ style: TextButton.styleFrom(+ foregroundColor: grid.AppPalette.textSecondary,+ padding: const EdgeInsets.only(bottom: 6),+ minimumSize: Size.zero,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ child: const Text('Clone repository…'),+ ),+ ],+ ),_FolderControl(folder: _folder,machineName: _machineName,@@ -531,7 +587,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {onPressed: _browse,),const SizedBox(height: _gapField),- const FieldLabel('Coding agent'),+ const FieldLabel('Agent'),// The app's own picker, not `DropdownButtonFormField`.//// Material's dropdown renders its own popup, anchors it OVER the field@@ -539,8 +595,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {// out square-cornered and edge-to-edge whatever you pass it — while// ignoring both `menuTheme` and `popupMenuTheme`, so it could not be// made to match any other menu in this app.- AppSelectField<String>(- key: const Key('new-agent-engine-field'),+ AgentPicker(value: _engine,options: [for (final identity in allEngines)@@ -560,6 +615,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {),],onChanged: (value) => setState(() {+ unawaited(widget.notifier.agentPreference.select(value));_engineChosenByUser = true;_engine = value;_error = null;@@ -647,9 +703,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {style: Theme.of(context).textTheme.bodySmall,),],- // No 'Permissions' heading. It sat over a single checkbox whose own- // label already says what it does, so it was a section title for a- // section of one.+ if (_engine == 'codex') ...[+ const SizedBox(height: 12),+ Divider(height: 1, color: grid.AppGlass.hair),+ const SizedBox(height: 16),+ ],+ const FieldLabel('Permissions'),if (bypassFlag != null)_BypassCheck(value: _bypassPermission,@@ -662,8 +721,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {// Not silence: an engine with no checkbox looks identical to one whose// checkbox the user simply missed.Text(- '${engineIdentity(_engine).label} has no permission flag this app '- 'can pass — it asks in the terminal.',+ 'Managed by ${engineIdentity(_engine).label}.',style: Theme.of(context).textTheme.bodySmall,),],@@ -832,17 +890,19 @@ class _Advanced extends StatelessWidget {),),const Spacer(),- Flexible(- child: Text(- key: const Key('new-agent-advanced-state'),- state,- maxLines: 1,- overflow: TextOverflow.ellipsis,- textAlign: TextAlign.right,- style: _mono(color: grid.AppPalette.textFaint)- .copyWith(fontSize: 11.5),+ 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,+ ),+ ),),- ),],),),@@ -863,8 +923,13 @@ class _Advanced extends StatelessWidget {offstage: !open,child: ExcludeFocus(excluding: !open,- child: Padding(- padding: const EdgeInsets.only(top: 4, bottom: 2),+ 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,@@ -1091,14 +1156,33 @@ class _BypassCheck extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,children: [+ Row(+ children: [+ Expanded(+ child: Text(+ 'Bypass permission prompts',+ style: theme.textTheme.labelMedium?.copyWith(+ color: grid.AppPalette.textPrimary,+ ),+ ),+ ),+ Tooltip(+ message: flag,+ child: Icon(+ LucideIcons.info,+ size: 14,+ color: grid.AppPalette.textSecondary,+ ),+ ),+ ],+ ),+ const SizedBox(height: _gapTight),Text(- 'Bypass permission prompts',- style: theme.textTheme.labelMedium?.copyWith(- color: grid.AppPalette.textPrimary,+ 'Allow this agent to act without asking for approval.',+ style: theme.textTheme.bodySmall?.copyWith(+ color: grid.AppPalette.textSecondary,),),- const SizedBox(height: _gapTight),- Text(flag, style: _mono(color: grid.AppPalette.textFaint)),],),),diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dartindex 71bbbe89a..e5d3d0e8c 100644--- a/desktop/lib/widgets/swarm_dialogs.dart+++ b/desktop/lib/widgets/swarm_dialogs.dart@@ -10,6 +10,7 @@ import '../state/swarm_catalog.dart';import 'link_machine_dialog.dart';import 'link_machine_screen.dart';import 'remote_folder_picker.dart';+import 'clone_repository_dialog.dart';Future<String?> showSwarmRenameDialog(BuildContext context, String name) =>showAppDialog<String>(@@ -98,16 +99,20 @@ class _ProjectDialogState extends State<_ProjectDialog> {widget.notifier.machineStates.values.firstOrNull)?.machine.machineId;- final name = TextEditingController();String? path;String? error;bool picking = false;int _machineRevision = 0;- @override- void dispose() {- name.dispose();- super.dispose();- }+ String get folderName =>+ (path+ ?.split(RegExp(r'[/\\]'))+ .where((part) => part.isNotEmpty)+ .lastOrNull ??+ path ??+ '')+ .characters+ .take(80)+ .join();Future<void> browse() async {final id = machineId;@@ -129,17 +134,6 @@ class _ProjectDialogState extends State<_ProjectDialog> {if (!mounted || revision != _machineRevision) return;setState(() {path = folder ?? path;- if (folder != null && name.text.trim().isEmpty) {- name.text =- (folder- .split(RegExp(r'[/\\]'))- .where((s) => s.isNotEmpty)- .lastOrNull ??- folder)- .characters- .take(80)- .join();- }});} catch (_) {if (mounted && revision == _machineRevision) {@@ -153,6 +147,24 @@ class _ProjectDialogState extends State<_ProjectDialog> {}}+ Future<void> clone() async {+ if (picking) return;+ final revision = _machineRevision;+ setState(() => picking = true);+ final folder = await showCloneRepositoryDialog(+ context,+ initialFolder: path,+ );+ if (!mounted) return;+ setState(() {+ picking = false;+ if (folder != null && revision == _machineRevision) {+ path = folder;+ error = null;+ }+ });+ }+@overrideWidget build(BuildContext context) => AlertDialog(title: const Text('Add project'),@@ -175,7 +187,7 @@ class _ProjectDialogState extends State<_ProjectDialog> {SelectOption(value: machine.machine.machineId,label: machine.isLocalMachine- ? 'Local'+ ? 'This computer': machine.machine.displayName,),],@@ -197,13 +209,12 @@ class _ProjectDialogState extends State<_ProjectDialog> {overflow: TextOverflow.ellipsis,),),- const SizedBox(height: 16),- TextField(- controller: name,- maxLength: 80,- decoration: const InputDecoration(labelText: 'Project name'),- onChanged: (_) => setState(() {}),- ),+ if (widget.notifier.stateOf(machineId ?? '')?.isLocalMachine == true)+ TextButton(+ onPressed: picking ? null : clone,+ style: TextButton.styleFrom(foregroundColor: Colors.white70),+ child: const Text('Clone repository…'),+ ),if (error != null)Text(error!,@@ -218,14 +229,14 @@ class _ProjectDialogState extends State<_ProjectDialog> {child: const Text('Cancel'),),FilledButton(- onPressed: path == null || name.text.trim().isEmpty || picking+ onPressed: path == null || folderName.isEmpty || picking? null: () => Navigator.pop(context,SavedSwarmProject(machineId: machineId!,path: path!,- name: name.text.trim(),+ name: folderName,),),child: const Text('Add project'),diff --git a/desktop/test/agent_picker_test.dart b/desktop/test/agent_picker_test.dartnew file mode 100644index 000000000..f2e9d6bb6--- /dev/null+++ b/desktop/test/agent_picker_test.dart@@ -0,0 +1,86 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/agent_preference.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/shared/widgets/app_select_field.dart';+import 'package:harness/widgets/agent_picker.dart';++import 'swarm_state_test.dart' show MemoryStore;++class _SlowStore implements LocalKeyValueStore {+ final pending = Completer<String?>();+ @override+ Future<String?> read(String key) => pending.future;+ @override+ Future<void> write(String key, String value) async {}+ @override+ Future<void> delete(String key) async {}+}++void main() {+ test(+ 'remembers the agent across launches without replacing a newer choice',+ () async {+ final store = MemoryStore();+ final preferences = AgentPreference(store);+ await preferences.select('codex');+ final restored = AgentPreference(store);+ await restored.load();+ expect(restored.value, 'codex');+ final slow = _SlowStore();+ final racing = AgentPreference(slow);+ final loading = racing.load();+ await racing.select('hermes');+ slow.pending.complete('claude');+ await loading;+ expect(racing.value, 'hermes');+ },+ );++ testWidgets('popular agents take one click and More contains every option', (+ tester,+ ) async {+ var selected = 'claude';+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 520,+ child: StatefulBuilder(+ builder: (_, setState) => AgentPicker(+ value: selected,+ options: const [+ SelectOption(value: 'codex', label: 'Codex'),+ SelectOption(value: 'claude', label: 'Claude Code'),+ SelectOption(value: 'cursor', label: 'Cursor'),+ SelectOption(value: 'hermes', label: 'Hermes'),+ ],+ onChanged: (value) => setState(() => selected = value),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.byKey(const ValueKey('new-agent-quick-codex')));+ await tester.pump();+ expect(selected, 'codex');+ expect(find.text('Hermes'), findsNothing);+ await tester.tap(find.byTooltip('More agents'));+ await tester.pumpAndSettle();+ expect(find.text('Codex'), findsNWidgets(2));+ await tester.tap(find.text('Hermes'));+ await tester.pumpAndSettle();+ expect(selected, 'hermes');+ expect(+ find.text('Hermes'),+ findsOneWidget,+ reason: 'The less common selection stays visible after closing the menu.',+ );+ expect(tester.takeException(), isNull);+ });+}diff --git a/desktop/test/clone_repository_dialog_test.dart b/desktop/test/clone_repository_dialog_test.dartnew file mode 100644index 000000000..f879871a5--- /dev/null+++ b/desktop/test/clone_repository_dialog_test.dart@@ -0,0 +1,82 @@+import 'dart:async';++import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/repository_clone.dart';+import 'package:harness/widgets/clone_repository_dialog.dart';++class _Folders extends FileSelectorPlatform {+ @override+ Future<String?> getDirectoryPath({+ String? initialDirectory,+ String? confirmButtonText,+ }) async => '/work';+}++class _Clone extends RepositoryClone {+ final pending = Completer<String>();+ bool cancelled = false;+ @override+ Future<String> run(GitHubRepository repository, String parent) =>+ pending.future;+ @override+ void cancel() {+ cancelled = true;+ }+}++void main() {+ testWidgets(+ 'clone failure preserves inputs; retry returns the new working folder',+ (tester) async {+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Folders();+ addTearDown(() => FileSelectorPlatform.instance = original);+ var clone = _Clone();+ String? result;+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () async {+ result = await showDialog<String>(+ context: context,+ builder: (_) =>+ CloneRepositoryDialog(createClone: () => clone),+ );+ },+ child: const Text('Open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ final submit = find.widgetWithText(FilledButton, 'Clone repository');+ final input = find.byKey(const ValueKey('clone-repository-url'));+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);+ await tester.enterText(input, 'owner/project');+ await tester.tap(find.text('Choose folder…'));+ await tester.pumpAndSettle();+ await tester.tap(submit);+ await tester.pump();+ expect(tester.widget<TextField>(input).readOnly, isTrue);+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);+ clone.pending.completeError(+ const RepositoryCloneException('Please check your GitHub access.'),+ );+ await tester.pumpAndSettle();+ expect(tester.widget<TextField>(input).controller!.text, 'owner/project');+ expect(find.text('/work'), findsOneWidget);+ expect(find.text('Please check your GitHub access.'), findsOneWidget);+ clone = _Clone();+ await tester.tap(submit);+ await tester.pump();+ clone.pending.complete('/work/project');+ await tester.pumpAndSettle();+ expect(result, '/work/project');+ expect(input, findsNothing);+ },+ );+}diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dartindex 0f692ce2c..b99a6a804 100644--- a/desktop/test/new_agent_codex_profile_test.dart+++ b/desktop/test/new_agent_codex_profile_test.dart@@ -10,6 +10,7 @@ import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/pane_arrangement.dart';import 'package:harness/widgets/new_agent_dialog.dart';+import 'package:harness/shared/widgets/app_select_field.dart';class _Folders extends FileSelectorPlatform {@override@@ -19,17 +20,15 @@ class _Folders extends FileSelectorPlatform {}) async => '/work';}-/// The profile the dialog says it will use, read off the Advanced row.-///-/// That row is the only place reporting it now: the summary card that used to-/// print a `Profile` fact is gone with the rest of the second column, and the-/// row carries the same answer by LABEL rather than by full path — which is what-/// a person reading a folded drawer actually needs.+/// The visible profile field reports the account used for the next launch.void expectProfile(WidgetTester tester, String label) {- final state = tester.widget<Text>(- find.byKey(const Key('new-agent-advanced-state')),+ final field = tester.widget<AppSelectField<String>>(+ find.byKey(const Key('new-agent-codex-profile-field')),+ );+ expect(+ field.options.firstWhere((option) => option.value == field.value).label,+ contains(label),);- expect(state.data, contains(label), reason: 'Advanced should name $label');}String _labelFor(String path) =>@@ -175,16 +174,6 @@ void main() {// opens it.await tester.tap(find.byKey(const Key('new-agent-advanced')));await tester.pumpAndSettle();- for (final t in [- 'Permissions',- 'Codex profile',- 'Link a profile folder…',- '/custom/work-login',- 'Checking whether this computer supports Codex profiles…',- ]) {- // ignore: avoid_print- print('PROBE $t -> ${tester.widgetList(find.text(t)).length}');- }return n;}@@ -195,15 +184,15 @@ void main() {await tester.pumpAndSettle();}- testWidgets('no profiles hides the picker and keeps a default launch', (+ testWidgets('no profiles shows the default launch explicitly', (tester,) async {final notifier = await open(tester, initialPaths: const []);expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);- expect(find.text('Codex profile'), findsNothing);+ expect(find.text('Codex profile'), findsOneWidget);expect(find.text('Link a profile folder…'), findsOneWidget);await tester.tap(find.text('Browse…'));await tester.pumpAndSettle();@@ -212,7 +201,7 @@ void main() {expect(notifier.calls.single['codexHome'], isNull);});- testWidgets('one profile is used automatically without a picker', (+ testWidgets('one profile is selected automatically and remains visible', (tester,) async {final notifier = await open(@@ -221,9 +210,9 @@ void main() {);expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);- expect(find.text('Codex profile'), findsNothing);+ expect(find.text('Codex profile'), findsOneWidget);expectProfile(tester, 'work-login');expect(find.text('Link a profile folder…'), findsOneWidget);await tester.tap(find.text('Browse…'));@@ -244,14 +233,14 @@ void main() {);expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);expectProfile(tester, 'work-login');expect(find.text('Link a profile folder…'), findsOneWidget);},);- testWidgets('the picker appears at two profiles and hides again at one', (+ testWidgets('refresh keeps the selected profile visible as accounts change', (tester,) async {final notifier = await open(@@ -260,7 +249,7 @@ void main() {);expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);notifier.paths.add('/accounts/codex2');await tester.tap(find.byTooltip('Refresh profiles'));@@ -276,7 +265,7 @@ void main() {await tester.pumpAndSettle();expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);expectProfile(tester, 'codex2');});@@ -311,10 +300,12 @@ void main() {await tester.pumpAndSettle();expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,+ findsOneWidget,);expectProfile(tester, 'codex2');- await tester.tap(find.text('Use codex1'));+ await tester.tap(find.byKey(const Key('new-agent-codex-profile-field')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('codex1').last);await tester.pumpAndSettle();expectProfile(tester, 'codex1');await tester.tap(find.text('Browse…'));@@ -331,21 +322,16 @@ void main() {await selectSecond(tester);await tester.tap(find.byKey(const Key('new-agent-codex-profile-field')));await tester.pumpAndSettle();- await tester.tap(find.text('Default').last);+ await tester.tap(find.text('Default profile').last);await tester.pumpAndSettle();notifier.paths.remove('/accounts/codex2');await tester.tap(find.byTooltip('Refresh profiles'));await tester.pumpAndSettle();expect(find.byKey(const Key('new-agent-codex-profile-field')),- findsNothing,- );- expect(- tester- .widget<Text>(find.byKey(const Key('new-agent-advanced-state')))- .data,- isNot(contains('codex1')),+ findsOneWidget,);+ expectProfile(tester, 'Default profile');await tester.tap(find.text('Browse…'));await tester.pumpAndSettle();await tester.tap(find.widgetWithText(FilledButton, 'Create agent'));diff --git a/desktop/test/repository_clone_test.dart b/desktop/test/repository_clone_test.dartnew file mode 100644index 000000000..71ac91e41--- /dev/null+++ b/desktop/test/repository_clone_test.dart@@ -0,0 +1,159 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/repository_clone.dart';+import 'package:path/path.dart' as p;++void main() {+ test(+ 'accepts GitHub URLs and shorthand without shell syntax or credentials',+ () {+ for (final input in [+ 'owner/project',+ 'https://github.com/owner/project/',+ 'https://github.com/owner/project.git',+ ]) {+ final repository = GitHubRepository.parse(input)!;+ expect(repository.url, 'https://github.com/owner/project.git');+ expect(repository.name, 'project');+ }+ expect(+ GitHubRepository.parse('[email protected]:owner/project.git')!.url,+ '[email protected]:owner/project.git',+ );+ for (final input in [+ '',+ '/tmp/repo',+ '--upload-pack=bad',+ 'https://user:[email protected]/owner/repo',+ 'https://github.com/owner/..',+ 'https://github.com/owner/repo?token=secret',+ 'https://github.com/owner/repo/tree/main',+ 'ext::bad',+ 'owner/repo;command',+ ]) {+ expect(GitHubRepository.parse(input), isNull, reason: input);+ }+ },+ );++ late Directory root;+ setUp(+ () async =>+ root = await Directory.systemTemp.createTemp('harness-clone-test-'),+ );+ tearDown(() async => root.delete(recursive: true));++ test('clones a real fixture and publishes a complete checkout, without network access', () async {+ final source = p.join(root.path, 'fixture.git');+ expect((await Process.run('git', ['init', '--bare', source])).exitCode, 0);+ final parent = await Directory(p.join(root.path, 'projects')).create();+ final clone = RepositoryClone(+ startProcess: (arguments, environment) {+ expect(arguments.take(3), [+ 'clone',+ '--',+ 'https://github.com/owner/project.git',+ ]);+ expect(environment['GIT_TERMINAL_PROMPT'], '0');+ // Substitute only the synthetic source; run the real Git clone, staging,+ // rename and cleanup logic without reaching GitHub or real credentials.+ return Process.start('git', [+ 'clone',+ '--',+ source,+ arguments.last,+ ], environment: environment);+ },+ );+ final destination = await clone.run(+ GitHubRepository.parse('owner/project')!,+ parent.path,+ );+ expect(destination, p.join(parent.path, 'project'));+ expect(await Directory(p.join(destination, '.git')).exists(), isTrue);+ expect(+ (await parent.list().toList()).map((entry) => p.basename(entry.path)),+ ['project'],+ );+ });++ test('an existing destination is preserved and never starts Git', () async {+ final existing = await Directory(p.join(root.path, 'project')).create();+ final draft = File(p.join(existing.path, 'draft.txt'));+ await draft.writeAsString('keep this');+ final clone = RepositoryClone(+ startProcess: (_, _) => throw StateError('Must not start'),+ );+ await expectLater(+ clone.run(GitHubRepository.parse('owner/project')!, root.path),+ throwsA(+ isA<RepositoryCloneException>().having(+ (e) => e.message,+ 'message',+ contains('already exists'),+ ),+ ),+ );+ expect(await draft.readAsString(), 'keep this');+ });++ test(+ 'failed Git does not leave a partial project or expose diagnostics',+ () async {+ final clone = RepositoryClone(+ startProcess: (arguments, environment) => Process.start('git', [+ 'clone',+ '--',+ p.join(root.path, 'missing-secret-source'),+ arguments.last,+ ], environment: environment),+ );+ await expectLater(+ clone.run(GitHubRepository.parse('owner/project')!, root.path),+ throwsA(+ isA<RepositoryCloneException>().having(+ (e) => e.message,+ 'message',+ isNot(contains('missing-secret-source')),+ ),+ ),+ );+ expect(await root.list().toList(), isEmpty);+ },+ );++ test(+ 'cancelling an in-flight clone stops its process and removes staging',+ () async {+ final started = Completer<void>();+ final clone = RepositoryClone(+ startProcess: (_, _) async {+ final process = await Process.start('sleep', ['30']);+ started.complete();+ return process;+ },+ );+ final result = clone.run(+ GitHubRepository.parse('owner/project')!,+ root.path,+ );+ final expectation = expectLater(+ result,+ throwsA(+ isA<RepositoryCloneException>().having(+ (e) => e.message,+ 'message',+ 'Clone cancelled.',+ ),+ ),+ );+ await started.future;+ clone.cancel();+ await expectation;+ expect(await root.list().toList(), isEmpty);+ },+ skip: Platform.isWindows ? 'Uses the POSIX sleep fixture.' : false,+ );+}diff --git a/desktop/test/swarm_saved_project_test.dart b/desktop/test/swarm_saved_project_test.dartnew file mode 100644index 000000000..53f52e486--- /dev/null+++ b/desktop/test/swarm_saved_project_test.dart@@ -0,0 +1,94 @@+import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/widgets/swarm_dialogs.dart';+import 'package:harness/ws/local_cli_discovery.dart';++import 'swarm_state_test.dart' show createApp;++class _Folders extends FileSelectorPlatform {+ @override+ Future<String?> getDirectoryPath({+ String? initialDirectory,+ String? confirmButtonText,+ }) async => '/work/autonomous-harness/';+}++void main() {+ test(+ 'an explicitly added folder names the group across aliased checkouts',+ () {+ final app = createApp();+ app.machineStates['m']!.localEndpoint = LocalCliEndpoint(+ computerId: 'local',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ agentProjects: const {+ 'a0': AgentProject(+ name: 'harness-app-v2',+ cwd: '/work/harness-app-v2',+ remote: 'https://github.com/autonomous-ai/autonomous-harness.git',+ ),+ 'a1': AgentProject(+ name: 'autonomous-harness',+ cwd: '/work/autonomous-harness',+ remote: 'https://github.com/autonomous-ai/autonomous-harness.git',+ ),+ },+ );+ final groups = swarmProjects(app, const [+ SavedSwarmProject(+ machineId: 'm',+ path: '/work/autonomous-harness',+ name: 'autonomous-harness',+ ),+ ]);+ expect(groups, hasLength(1));+ expect(groups.single.name, 'autonomous-harness');+ expect(groups.single.agents.map((a) => a.agent.id), ['a0', 'a1']);+ app.dispose();+ },+ );++ testWidgets('adding a project derives its name from the selected folder', (+ tester,+ ) async {+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Folders();+ addTearDown(() => FileSelectorPlatform.instance = original);+ final app = createApp();+ app.machineStates['m']!.localEndpoint = LocalCliEndpoint(+ computerId: 'local',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ );+ SavedSwarmProject? saved;+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () async {+ saved = await showSwarmProjectDialog(context, app);+ },+ child: const Text('Open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ expect(find.byType(TextField), findsNothing);+ await tester.tap(find.text('Choose folder'));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Add project'));+ await tester.pumpAndSettle();+ expect(saved!.name, 'autonomous-harness');+ expect(saved!.path, '/work/autonomous-harness/');+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+}