The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(mobile): give New agent the project sources the desktop has
bubu-dudu44294c95d72d
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex a965ef6ba..b3d890b19 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -258,6 +258,15 @@ export class TerminalStreamManager {pasteFile: true,// Bounded media reads through the already encrypted agent_read_file RPC.mediaPreview: true,+ // `agent_create` understands `projectSource` — a folder this machine makes or clones for+ // itself — rather than only a `cwd` the client already knows. A client old enough to+ // predate `lib/projectFolder.ts` never sends it, and one NEWER than the machine has no way+ // to tell without this: the keys are simply ignored, `cwd` comes up missing, and the+ // refusal arrives as INVALID_CWD — "the project folder is unavailable", about a folder+ // nobody named. Advertised here, beside the other "what this CLI can do" answers, even+ // though creating an agent is not terminal streaming; this is the message a client already+ // asks every machine.+ projectFolder: true,},engines: terminalEngineCapabilities(this.deps.streamingAvailable),})diff --git a/mobile/lib/core/project_folder.dart b/mobile/lib/core/project_folder.dartnew file mode 100644index 000000000..b751512a8--- /dev/null+++ b/mobile/lib/core/project_folder.dart@@ -0,0 +1,79 @@+/// Where a new agent's project comes from, when it is not a folder that already exists.+///+/// ⚠️ This is the phone's HALF of the desktop's `core/project_folder.dart`. That one carries a+/// second half, `prepareLocal`, which makes the folder or clones the repository with `dart:io` and+/// hands over a real path — right for a machine the desktop is running ON, and meaningless here.+/// Every machine a phone talks to is remote, so the machine does the work and this only has to say+/// what to do. Nothing in this file touches a filesystem.+///+/// The keys travel to `cli/src/lib/projectFolder.ts`, which parses them and clones. The CLI parses+/// the URL again at its end; [GitHubRepository.parse] runs here anyway so a typo is answered on the+/// screen it was typed on rather than after a round trip.+class ProjectFolderRequest {+ /// Let the machine make a fresh project folder of its own.+ const ProjectFolderRequest.newProject() : repository = null;++ /// Let the machine clone [value] and work in the checkout.+ const ProjectFolderRequest.remote(GitHubRepository value) : repository = value;++ final GitHubRepository? repository;++ /// ⚠️ Sent INSTEAD of `cwd`, never beside it — see `AppNotifier.createAgent`. The two answer the+ /// same question, and a machine given both would have to guess which one was meant.+ Map<String, String> get payload => {+ 'projectSource': repository == null ? 'new' : 'remote',+ if (repository != null) 'repositoryUrl': repository!.url,+ };+}++/// A GitHub repository named by URL — `owner/repo`, an https link, or an ssh remote.+///+/// Ported from the desktop's `core/repository_clone.dart` without the cloning it sits beside there.+class GitHubRepository {+ const GitHubRepository._(this.url, this.name);++ final String url, name;++ /// Null when [input] does not name a GitHub repository.+ ///+ /// ⚠️ Strict on purpose. The result is handed to a machine that will run `git clone` with it, so+ /// everything that could smuggle something else into that command — a userinfo, a port, a query,+ /// a fragment, a host that is not github.com — is refused rather than trimmed off and accepted.+ 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],+ );+ }+}diff --git a/mobile/lib/core/project_history.dart b/mobile/lib/core/project_history.dartnew file mode 100644index 000000000..f8ec6adeb--- /dev/null+++ b/mobile/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/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex 137662aa6..e4f32f1b8 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -4,10 +4,10 @@ import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/core/codex_profiles.dart';-import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/widgets/engine_identity.dart';+import 'package:harness_mobile/core/project_folder.dart';import 'package:harness_mobile/widgets/remote_folder_picker.dart';import 'phone_header.dart';@@ -41,6 +41,19 @@ class NewAgentPage extends StatefulWidget {class _NewAgentPageState extends State<NewAgentPage> {String? _folder;++ /// Set when the MACHINE is to produce the folder — a fresh project, or a clone — instead of one+ /// being picked here.+ ///+ /// ⚠️ Exclusive with [_folder], and the two are cleared against each other everywhere they are+ /// set. They answer the same question, and both being live would leave the button's `ready` true+ /// with no way to tell which answer it meant.+ ProjectFolderRequest? _project;++ /// What the FOLDER rows show as chosen for [_project], since a request carries no path to show:+ /// "New project", or the repository's name.+ String? _projectLabel;+String? _engine;String? _error;bool _creating = false;@@ -52,6 +65,12 @@ class _NewAgentPageState extends State<NewAgentPage> {LocalCodexProfile? _codexProfile;bool _codexProfilesLoaded = false;+ /// Whether the Recent row is folded open.+ ///+ /// Starts shut every time, and closes again on a pick: what it lists are answers, and once one is+ /// taken the list has nothing left to say.+ bool _recentOpen = false;+@overridevoid initState() {super.initState();@@ -60,6 +79,13 @@ class _NewAgentPageState extends State<NewAgentPage> {// machine with neither still gets the browse-and-create path.unawaited(widget.notifier.probeEngines(widget.machineId));unawaited(_loadCodexProfiles());+ // Read from disk once. `recent` answers from memory after this, so the rows below need no+ // await — but the first build happens before it lands, hence the rebuild.+ unawaited(+ widget.notifier.projectHistory.load().then((_) {+ if (mounted) setState(() {});+ }),+ );}/// Discovery runs on the MACHINE, never on this device — the phone has no@@ -91,17 +117,60 @@ class _NewAgentPageState extends State<NewAgentPage> {MachineState? get _machine => widget.notifier.stateOf(widget.machineId);- /// The folders this machine's agents already work in, most recently seen- /// first — on a machine with agents, the answer is nearly always one of them.- List<AgentProject> get _knownProjects {+ /// Whether this machine can make a folder of its own — a fresh project, or a clone.+ ///+ /// ⚠️ Gated because an older CLI fails in a way that BLAMES THE PERSON. It ignores+ /// `projectSource`, finds no `cwd`, and refuses with INVALID_CWD, which the app renders as "the+ /// project folder is unavailable on this machine, choose another folder and try again" — advice+ /// about a folder they never chose, for a problem that is not theirs to fix.+ ///+ /// ⚠️ The desktop offers both unconditionally and has the same hole. Worth carrying over there.+ bool get _canMakeProject => _machine?.projectFolderAvailable ?? false;++ /// Why the two rows are unavailable, or null while they are not.+ ///+ /// Printed rather than left to a disabled row: "Update Harness on that machine" is something the+ /// person can act on, and a row that simply does nothing teaches them nothing.+ String? get _projectSourceNote {final machine = _machine;- if (machine == null) return const [];- final byPath = <String, AgentProject>{};- for (final agent in machine.agents) {- final project = machine.projectOf(agent);- if (project != null) byPath.putIfAbsent(project.cwd, () => project);- }- return byPath.values.toList();+ if (machine == null || _canMakeProject) return null;+ // Said only once the machine has actually answered. Before that, silence — a row must not call+ // a machine out of date on the strength of an answer that has not arrived.+ if (!machine.terminalCapabilityLoaded) return null;+ return 'Update Harness on ${machine.machine.displayName} to create a '+ 'project or clone one there.';+ }++ /// Folders agents have been started in on THIS machine, newest first.+ ///+ /// ⚠️ A stored history, not a reading of what exists now. It survives the agent that put it+ /// there, which is what makes "recent" honest — the list that came from `machine.agents` emptied+ /// itself when an agent was deleted, and called that "recent" too.+ ///+ /// Scoped per machine because the paths are: a folder on one computer means nothing on another.+ List<String> get _recent =>+ widget.notifier.projectHistory.recent(widget.machineId);++ /// Whether the chosen folder came from the browser rather than from Recent.+ bool get _browsed => _folder != null && !_recent.contains(_folder);++ /// The recent folder currently chosen, for the folded row to show, or null.+ String? get _pickedRecent =>+ _folder != null && _recent.contains(_folder) ? _folder : null;++ String get _recentCount =>+ _recent.length == 1 ? '1 folder' : '${_recent.length} folders';++ /// The last segment of a path, for the row's title. No `package:path` here — these are the remote+ /// machine's paths, and its separator is not this device's to assume.+ String _basename(String path) {+ final trimmed = path.endsWith('/') && path.length > 1+ ? path.substring(0, path.length - 1)+ : path;+ final cut = trimmed.lastIndexOf('/');+ return cut < 0 || cut == trimmed.length - 1+ ? trimmed+ : trimmed.substring(cut + 1);}/// Every engine Harness knows, the way the desktop dialog offers them.@@ -126,6 +195,31 @@ class _NewAgentPageState extends State<NewAgentPage> {return 'not installed';}+ /// Asks for a GitHub repository by URL — the desktop's "Git" button, which is also just a field+ /// to paste into. Neither end lists repositories or talks to GitHub.+ ///+ /// ⚠️ Refuses in the dialog rather than on submit. `cli/src/lib/projectFolder.ts` parses the URL+ /// again at its end and would refuse too, but that answer arrives after a round trip and lands as+ /// a failed creation; [GitHubRepository.parse] is the same rule applied where it was typed.+ Future<void> _pickRepository() async {+ final repository = await showDialog<GitHubRepository>(+ context: context,+ useRootNavigator: true,+ // ⚠️ The dialog owns its controller. Holding one out here and disposing it when `showDialog`+ // returns disposes it while the route is still animating OUT, with the field still attached —+ // "A TextEditingController was used after being disposed", and the frame after it takes the+ // whole screen down.+ builder: (_) => _RepositoryDialog(initialUrl: _project?.repository?.url),+ );+ if (repository == null || !mounted) return;+ setState(() {+ _project = ProjectFolderRequest.remote(repository);+ _projectLabel = repository.name;+ _folder = null;+ _error = null;+ });+ }+Future<void> _browse() async {final chosen = await showRemoteFolderPicker(context,@@ -136,13 +230,17 @@ class _NewAgentPageState extends State<NewAgentPage> {if (chosen == null || !mounted) return;setState(() {_folder = chosen;+ _project = null;+ _projectLabel = null;_error = null;});}Future<void> _create() async {- final folder = _folder, engine = _engine;- if (folder == null || engine == null || _creating) return;+ final folder = _folder, engine = _engine, project = _project;+ if ((folder == null && project == null) || engine == null || _creating) {+ return;+ }setState(() {_creating = true;_error = null;@@ -154,7 +252,10 @@ class _NewAgentPageState extends State<NewAgentPage> {final error = await widget.notifier.createAgent(widget.machineId,engine: engine,- folder: folder,+ // Empty only in the branch that drops `cwd` from the payload entirely — `createAgent` keeps+ // this required so the ordinary case cannot be left out by accident.+ folder: folder ?? '',+ projectFolder: project,// Only for Codex, and only when chosen: omitted, the machine launches// with its own default CODEX_HOME.codexHome: _showsCodexProfile ? _codexProfile?.path : null,@@ -201,7 +302,10 @@ class _NewAgentPageState extends State<NewAgentPage> {builder: (context, _) {AppTheme.watch(context);final machine = _machine;- final ready = _folder != null && _engine != null && !_creating;+ final ready =+ (_folder != null || _project != null) &&+ _engine != null &&+ !_creating;return Scaffold(backgroundColor: AppPalette.windowBg,body: SafeArea(@@ -224,39 +328,112 @@ class _NewAgentPageState extends State<NewAgentPage> {const SettingsCaption('FOLDER'),SettingsGroup(children: [- for (final project in _knownProjects)- SettingsRow(- title: project.name,- detail: project.cwd,- leading: Icon(- LucideIcons.folder300,- size: 18,- color: AppPalette.textSecondary,- ),- trailing: _check(_folder == project.cwd),- onTap: () => setState(() {- _folder = project.cwd;- _error = null;- }),+ SettingsRow(+ title: 'New project',+ detail:+ _projectSourceNote ??+ 'A fresh folder, made on the machine',+ leading: Icon(+ LucideIcons.folderPlus300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ trailing: _check(+ _project != null && _project!.repository == null,),+ onTap: !_canMakeProject+ ? null+ : () => setState(() {+ _project =+ const ProjectFolderRequest.newProject();+ _projectLabel = 'New project';+ _folder = null;+ _error = null;+ }),+ ),+ // Shows its path only when the choice is this row's own. A folder picked+ // from RECENT below is already named there, and printing it here too would+ // put one answer under two ticks.SettingsRow(title: 'Browse…',- detail: _knownProjects.any((p) => p.cwd == _folder)- ? null- : _folder,+ detail: _browsed ? _folder : null,leading: Icon(LucideIcons.folderSearch300,size: 18,color: AppPalette.textSecondary,),+ trailing: _check(_browsed),onTap: () => unawaited(_browse()),),+ SettingsRow(+ title: 'Git…',+ detail:+ _projectSourceNote ??+ (_project?.repository == null+ ? 'Clone a GitHub repository'+ : _projectLabel),+ leading: Icon(+ LucideIcons.gitBranch300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ trailing: _check(_project?.repository != null),+ onTap: !_canMakeProject+ ? null+ : () => unawaited(_pickRepository()),+ ),+ // The fourth source, folded shut. Its entries are answers already given+ // rather than a way of choosing, so they stay out of sight until asked+ // for — a machine used for months would otherwise bury the three rows+ // above under its own history.+ //+ // ⚠️ Absent entirely when there is no history, rather than opening onto+ // nothing. Nobody's first agent has a recent folder.+ if (_recent.isNotEmpty)+ SettingsRow(+ title: 'Recent',+ detail: _recentOpen+ ? null+ : (_pickedRecent ?? _recentCount),+ leading: Icon(+ LucideIcons.history300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ trailing: Icon(+ _recentOpen+ ? LucideIcons.chevronUp300+ : LucideIcons.chevronDown300,+ size: 18,+ color: AppPalette.textFaint,+ ),+ onTap: () =>+ setState(() => _recentOpen = !_recentOpen),+ ),+ if (_recentOpen)+ for (final path in _recent)+ SettingsRow(+ title: _basename(path),+ detail: path,+ nested: true,+ // No leading glyph: the indent under an open Recent is what says+ // these belong to it, and a second icon column would put them back+ // level with the sources above.+ trailing: _check(_folder == path),+ onTap: () => setState(() {+ _folder = path;+ _project = null;+ _projectLabel = null;+ _recentOpen = false;+ _error = null;+ }),+ ),],),const SettingsCaption('ENGINE'),SettingsGroup(children: [- for (final identity in _engines)+ for (final identity in _engines) ...[SettingsRow(title: identity.label,detail: _engineNote(identity.id),@@ -267,45 +444,54 @@ class _NewAgentPageState extends State<NewAgentPage> {_error = null;}),),- ],- ),- if (_showsCodexProfile) ...[- const SettingsCaption('CODEX PROFILE'),- SettingsGroup(- children: [- SettingsRow(- title: 'Default profile',- detail: _codexProfilesLoaded- ? null- : 'Looking for others…',- trailing: _check(_codexProfile == null),- onTap: () => setState(() => _codexProfile = null),- ),- for (final profile in _codexProfiles)+ // Codex's profiles belong UNDER Codex, not in a section of their own at+ // the foot of the page. They are a detail of one engine — a section+ // separated from the row that summons it reads as a second question,+ // and appearing at the bottom of a long list is how it went unnoticed.+ //+ // ⚠️ Only for the engine that has them, and only once the machine has+ // said it understands CODEX_HOME. Every other engine shows nothing here,+ // which is why this is a list inside the loop rather than a block after+ // it.+ if (identity.id == 'codex' && _showsCodexProfile) ...[SettingsRow(- title: profile.label,- detail: profile.path,- trailing: _check(_codexProfile == profile),- onTap: () =>- setState(() => _codexProfile = profile),+ title: 'Default profile',+ nested: true,+ detail: _codexProfilesLoaded+ ? null+ : 'Looking for others…',+ trailing: _check(_codexProfile == null),+ onTap: () => setState(() => _codexProfile = null),),+ for (final profile in _codexProfiles)+ SettingsRow(+ title: profile.label,+ detail: profile.path,+ nested: true,+ trailing: _check(_codexProfile == profile),+ onTap: () =>+ setState(() => _codexProfile = profile),+ ),+ ],],- ),- ],- if (_error != null)- Padding(- padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),- child: Text(- _error!,- style: TextStyle(- color: AppPalette.offline,- fontSize: 13,- ),- ),- ),+ ],+ ),],),),+ // ⚠️ The refusal belongs BESIDE the button, not at the end of the list above it.+ // It used to sit after the engines and the Codex profile — past nine rows and well+ // below the fold — while the button is pinned here. Pressing Create and being+ // refused looked exactly like pressing Create and nothing happening, because the+ // answer rendered somewhere nobody was looking.+ if (_error != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),+ child: Text(+ _error!,+ style: TextStyle(color: AppPalette.offline, fontSize: 13),+ ),+ ),Padding(padding: const EdgeInsets.fromLTRB(20, 8, 20, 12),child: SizedBox(@@ -327,3 +513,70 @@ class _NewAgentPageState extends State<NewAgentPage> {? Icon(LucideIcons.check300, size: 18, color: AppPalette.accent): null;}++/// The Git field, as its own widget so the text it holds survives the parent's rebuilds — a+/// `StatefulBuilder` inside the dialog would lose the error the moment anything above repainted.+class _RepositoryDialog extends StatefulWidget {+ const _RepositoryDialog({this.initialUrl});++ final String? initialUrl;++ @override+ State<_RepositoryDialog> createState() => _RepositoryDialogState();+}++class _RepositoryDialogState extends State<_RepositoryDialog> {+ late final _controller = TextEditingController(text: widget.initialUrl ?? '');+ String? _error;++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ void _submit() {+ final repository = GitHubRepository.parse(_controller.text);+ if (repository == null) {+ setState(() => _error = 'That is not a GitHub repository.');+ return;+ }+ Navigator.of(context).pop(repository);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return AlertDialog(+ backgroundColor: AppPalette.panelBg,+ title: Text(+ 'Git repository',+ style: TextStyle(color: AppPalette.textPrimary, fontSize: 18),+ ),+ content: TextField(+ controller: _controller,+ autofocus: true,+ autocorrect: false,+ enableSuggestions: false,+ keyboardType: TextInputType.url,+ textInputAction: TextInputAction.go,+ style: TextStyle(color: AppPalette.textPrimary, fontSize: 15),+ decoration: InputDecoration(+ hintText: 'owner/repo, or a GitHub URL',+ errorText: _error,+ ),+ onChanged: (_) {+ if (_error != null) setState(() => _error = null);+ },+ onSubmitted: (_) => _submit(),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(onPressed: _submit, child: const Text('Select')),+ ],+ );+ }+}diff --git a/mobile/lib/phone/settings_row.dart b/mobile/lib/phone/settings_row.dartindex 72709a506..c76cafde0 100644--- a/mobile/lib/phone/settings_row.dart+++ b/mobile/lib/phone/settings_row.dart@@ -31,6 +31,16 @@ const double kSettingsRowHeight = 50;/// Re-measure if the icon size or the icon pack changes; this number belongs to both.const double _chevronInk = 6.68;+/// A row's own left padding, and the step a [SettingsRow.nested] child takes beyond it.+///+/// The step is the glyph's box plus the gap after it, so a child's TITLE begins exactly where its+/// parent's title does. Written as the sum rather than as the number it comes to, because the three+/// parts are set independently below and a hand-rounded total would drift away from them.+const double _rowPadding = 13;+const double _rowGlyph = 18;+const double _rowGlyphGap = 12;+const double _nestedPadding = _rowPadding + _rowGlyph + _rowGlyphGap;+/// A caption over a run of rows.class SettingsCaption extends StatelessWidget {const SettingsCaption(this.text, {super.key});@@ -140,6 +150,7 @@ class SettingsRow extends StatelessWidget {this.trailing,this.onTap,this.destructive = false,+ this.nested = false,});final String title;@@ -157,6 +168,15 @@ class SettingsRow extends StatelessWidget {final VoidCallback? onTap;final bool destructive;+ /// Draws this row as a CHILD of the one above it — the Codex profiles under Codex, the folders+ /// under Recent.+ ///+ /// ⚠️ Indent, not a nested group. A group of its own would draw its own card edge and read as a+ /// separate question; the whole point is that these rows belong to the row above. The step is the+ /// width [leading] occupies plus its gap, so a child without a glyph lines up under its parent's+ /// TEXT rather than under the parent's icon.+ final bool nested;+@overrideWidget build(BuildContext context) {AppTheme.watch(context);@@ -168,10 +188,18 @@ class SettingsRow extends StatelessWidget {// in a group clears the same bar — without it a row carrying a stepper (34pt tall) stands// visibly taller than one carrying only a value, and a group of four reads as ragged.constraints: const BoxConstraints(minHeight: kSettingsRowHeight),- padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 8),+ padding: EdgeInsets.fromLTRB(+ nested ? _nestedPadding : _rowPadding,+ 8,+ _rowPadding,+ 8,+ ),child: Row(children: [- if (leading != null) ...[leading!, const SizedBox(width: 12)],+ if (leading != null) ...[+ leading!,+ const SizedBox(width: _rowGlyphGap),+ ],Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start,diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 265ad0e79..589e123ac 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -24,6 +24,8 @@ import '../core/local_hostname.dart';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/retry.dart';import '../settings/config_store.dart';import '../stats/harness_stats.dart';@@ -178,6 +180,14 @@ class MachineState {// Only consulted for a REMOTE pane; a local one pastes its own path directly and never needs this.bool terminalPasteFileAvailable = false;bool mediaPreviewAvailable = false;+ // Whether this machine's CLI understands `projectSource` on agent_create — a folder it makes or+ // clones for itself, rather than one the client names with `cwd`.+ //+ // ⚠️ False is not "the feature is off", it is "this machine would MISREPORT the failure". An+ // older CLI ignores the keys, finds no `cwd`, and refuses with INVALID_CWD — which reaches the+ // person as "the project folder is unavailable, choose another folder", advice about a folder+ // they never chose and that has nothing to do with what went wrong.+ bool projectFolderAvailable = false;// Which engines this machine actually has, as this machine answered it. Kept// on MachineState rather than globally because that is the whole point: two// machines on one account hold different engines, and the Docker rig holds@@ -1058,6 +1068,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,cliLink = cliLink ?? CliLink(),@@ -1116,6 +1127,13 @@ class AppNotifier extends ChangeNotifier {final DialState dial;final AgentPreference agentPreference;+ /// Folders agents have been started in, per machine, kept across launches.+ ///+ /// ⚠️ Not the same list as the folders this machine's agents are using right now. That one comes+ /// from `machine.agents` and a deleted agent takes its folder off it; this one is a HISTORY and+ /// outlives the agent — which is what "recent" has to mean for the word to be true.+ final ProjectHistory projectHistory;+TerminalPane? get focusedPane {final id = focusedPaneId;if (id == null) return null;@@ -3456,6 +3474,8 @@ class AppNotifier extends ChangeNotifier {features is Map && features['pasteFile'] == true;machine.mediaPreviewAvailable =features is Map && features['mediaPreview'] == true;+ machine.projectFolderAvailable =+ features is Map && features['projectFolder'] == true;} catch (_) {if (!_machineWorkCurrent(machine, revision)) return;machine.terminalCapabilityLoaded = true;@@ -3465,6 +3485,7 @@ class AppNotifier extends ChangeNotifier {machine.terminalImagePasteAvailable = false;machine.terminalPasteFileAvailable = false;machine.mediaPreviewAvailable = false;+ machine.projectFolderAvailable = false;}if (!_machineWorkCurrent(machine, revision)) return;if (machine.agentLoadStatus != AgentLoadStatus.loading &&@@ -3893,10 +3914,19 @@ class AppNotifier extends ChangeNotifier {/// Starts an agent, or recovers this form's earlier request after a lost reply./// Returns null on success, or an inline message; [attempt] tells the form/// whether to offer Check status instead of inviting another creation.+ /// [projectFolder] asks the MACHINE to produce the folder — a fresh project of its own, or a+ /// clone of a repository — instead of being handed one that already exists.+ ///+ /// ⚠️ It replaces [folder] rather than joining it: `cwd` leaves the payload entirely when a+ /// request is present. Both answer "which directory", and a machine given a path AND an+ /// instruction to make one would have to guess which was meant. `cli/src/lib/projectFolder.ts`+ /// reads the pair, and `[folder]` stays required so the ordinary case — a folder the person+ /// picked — cannot be forgotten.Future<String?> createAgent(String machineId, {required String engine,required String folder,+ ProjectFolderRequest? projectFolder,bool bypassPermission = false,String? codexHome,String? swarmId,@@ -3906,7 +3936,8 @@ class AppNotifier extends ChangeNotifier {final creation = attempt ?? AgentCreationAttempt();final choices = <String, dynamic>{'engine': engine,- 'cwd': folder,+ if (projectFolder == null) 'cwd': folder,+ ...?projectFolder?.payload,'bypassPermission': bypassPermission,'codexHome': ?codexHome,};@@ -4087,6 +4118,14 @@ class AppNotifier extends ChangeNotifier {creation._complete(null);if (_disposed || machineStates[machineId] != machine) return null;_upsertAgent(machine, agent);+ // ⚠️ Read from the AGENT the machine answered with, not from what was asked for. "New project"+ // and a clone send no `cwd` at all — the folder is whatever the machine made — so taking it+ // from the request would record nothing for exactly the two sources that produce a folder+ // worth remembering.+ final projectPath = agent.project?.cwd ?? choices['cwd'];+ if (projectPath is String && projectPath.isNotEmpty) {+ unawaited(projectHistory.select(machineId, projectPath));+ }// Apply each creation receipt once, even if its transport result is replayed.harnessStats.onAgentSpawned();notifyListeners();diff --git a/mobile/test/phone_new_agent_opens_test.dart b/mobile/test/phone_new_agent_opens_test.dartindex d6c4d81ca..1f9d5e98b 100644--- a/mobile/test/phone_new_agent_opens_test.dart+++ b/mobile/test/phone_new_agent_opens_test.dart@@ -44,8 +44,12 @@ class _Conn extends WsConn {}}-/// A machine answering, with one agent already in a folder — which is what puts a tappable folder-/// on the form. Browsing for one instead would open the remote picker, a screen of its own.+/// A machine answering, with one agent already in a folder.+///+/// ⚠️ The agent is no longer what puts a tappable folder on the form — RECENT does, and RECENT is+/// the stored history rather than a reading of the machine's agents. The caller seeds that history;+/// this agent is here so the machine is not empty. Browsing for a folder instead would open the+/// remote picker, a screen of its own.AppNotifier _app(_Conn conn) {final app = AppNotifier(config: AppConfig.dev,@@ -76,37 +80,46 @@ AppNotifier _app(_Conn conn) {}void main() {- testWidgets('creating an agent opens it, and leaves no form to come back to', (- tester,- ) async {- final app = _app(_Conn());- addTearDown(app.dispose);- await tester.pumpWidget(- MaterialApp(home: NewAgentPage(notifier: app, machineId: 'm')),- );- await tester.pump();+ testWidgets(+ 'creating an agent opens it, and leaves no form to come back to',+ (tester) async {+ final app = _app(_Conn());+ addTearDown(app.dispose);+ // A folder this machine has been used with before. Its row is titled by the path's last+ // segment, so this is the 'grid' tapped below.+ await app.projectHistory.select('m', '/src/grid');+ await tester.pumpWidget(+ MaterialApp(+ home: NewAgentPage(notifier: app, machineId: 'm'),+ ),+ );+ await tester.pump();- await tester.tap(find.text('grid'));- await tester.pump();- await tester.tap(find.text('Claude'));- await tester.pump();- await tester.tap(find.text('Create agent'));- // The create resolves on a microtask, then the route it pushes has to slide in — and only once- // that transition ends does the form's own route come off the stack.- await tester.pump();- for (var i = 0; i < 4; i++) {- await tester.pump(const Duration(milliseconds: 400));- }+ // Recent is folded shut, so its entries are not on screen until it is opened.+ await tester.tap(find.text('Recent'));+ await tester.pump();+ await tester.tap(find.text('grid'));+ await tester.pump();+ await tester.tap(find.text('Claude'));+ await tester.pump();+ await tester.tap(find.text('Create agent'));+ // The create resolves on a microtask, then the route it pushes has to slide in — and only once+ // that transition ends does the form's own route come off the stack.+ await tester.pump();+ for (var i = 0; i < 4; i++) {+ await tester.pump(const Duration(milliseconds: 400));+ }- expect(- find.byType(AgentSwipeHost),- findsOneWidget,- reason: 'the agent just asked for is what the form opens',- );- expect(- find.byType(NewAgentPage),- findsNothing,- reason: 'the form is replaced, so back from the agent is the list behind it',- );- });+ expect(+ find.byType(AgentSwipeHost),+ findsOneWidget,+ reason: 'the agent just asked for is what the form opens',+ );+ expect(+ find.byType(NewAgentPage),+ findsNothing,+ reason: 'the form is replaced, so back from the agent is the list behind it',+ );+ },+ );}diff --git a/mobile/test/project_folder_test.dart b/mobile/test/project_folder_test.dartnew file mode 100644index 000000000..311774559--- /dev/null+++ b/mobile/test/project_folder_test.dart@@ -0,0 +1,73 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/project_folder.dart';++void main() {+ group('what the machine is told', () {+ test('a new project asks for one and names nothing', () {+ expect(const ProjectFolderRequest.newProject().payload, {+ 'projectSource': 'new',+ });+ });++ test('a repository travels as its canonical clone URL', () {+ final repo = GitHubRepository.parse('owner/repo')!;+ expect(ProjectFolderRequest.remote(repo).payload, {+ 'projectSource': 'remote',+ 'repositoryUrl': 'https://github.com/owner/repo.git',+ });+ });++ test('neither payload carries a cwd', () {+ // ⚠️ `createAgent` drops `cwd` when a request is present, so a stray path here would be the+ // second answer to a question that takes one — and the machine would have to guess.+ final repo = GitHubRepository.parse('owner/repo')!;+ for (final request in [+ const ProjectFolderRequest.newProject(),+ ProjectFolderRequest.remote(repo),+ ]) {+ expect(request.payload.containsKey('cwd'), isFalse);+ }+ });+ });++ group('parsing what someone pasted', () {+ test('the three shapes a person actually pastes', () {+ for (final input in [+ 'owner/repo',+ 'https://github.com/owner/repo',+ 'https://github.com/owner/repo.git',+ ' owner/repo/ ',+ ]) {+ final repo = GitHubRepository.parse(input);+ expect(repo?.url, 'https://github.com/owner/repo.git', reason: input);+ expect(repo?.name, 'repo', reason: input);+ }+ });++ test('an ssh remote stays ssh', () {+ final repo = GitHubRepository.parse('[email protected]:owner/repo.git');+ expect(repo?.url, '[email protected]:owner/repo.git');+ expect(repo?.name, 'repo');+ });++ test('anything that could smuggle something into git clone is refused', () {+ // ⚠️ The result is handed to a machine that runs `git clone` with it. Each of these is a way+ // to make that command reach somewhere other than the repository it appears to name, so they+ // are refused whole rather than trimmed and accepted.+ for (final input in [+ 'https://evil.com/owner/repo',+ 'https://user:[email protected]/owner/repo',+ 'https://github.com:22/owner/repo',+ 'https://github.com/owner/repo?x=1',+ 'https://github.com/owner/repo#frag',+ 'http://github.com/owner/repo',+ 'owner',+ 'owner/repo/extra',+ 'owner/..',+ '',+ ]) {+ expect(GitHubRepository.parse(input), isNull, reason: input);+ }+ });+ });+}