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): New Harness asks the Git questions a window asks
bubu-dudu88dded414fd7
diff --git a/mobile/lib/core/git_project.dart b/mobile/lib/core/git_project.dartnew file mode 100644index 000000000..60ce9fcfb--- /dev/null+++ b/mobile/lib/core/git_project.dart@@ -0,0 +1,352 @@+/// The Git choices a project folder offers, and what Start would do with them.+///+/// ⚠️ **This is the phone's HALF of the desktop's `core/git_worktree.dart`**, the+/// same split `core/project_folder.dart` already makes. That file carries a+/// second half built on `dart:io` — it runs `git` itself, which is right for a+/// folder on the machine the desktop is running ON. Every machine a phone talks+/// to is remote, so the machine reads its own repository (`git_project_info`,+/// served by `cli/src/lib/gitProject.ts`) and this only parses the answer and+/// works out what to ask for. Nothing here touches a filesystem or a process.+///+/// The planning rules below ([planWorktree] and its neighbours) are ported from+/// `state/new_harness.dart` unchanged, because they decide what is SENT: a+/// phone that planned differently would make a different branch from a desktop+/// asked the same question.+library;++import 'dart:math';++import 'package:path/path.dart' as p;++import 'project_folder.dart';++class GitBranch {+ const GitBranch(+ this.ref,+ this.name, {+ this.remote = false,+ this.worktree,+ this.harness = false,+ });++ final String ref, name;+ final bool remote;++ /// Harness made this branch for a worktree.+ final bool harness;++ /// Where this local branch is checked out, when it is.+ final String? worktree;+}++class GitProjectInfo {+ const GitProjectInfo({+ this.isGit = false,+ this.branch,+ this.branches = const [],+ this.error,+ this.mainFolder,+ this.mainBranch,+ this.defaultRef,+ this.root,+ });++ factory GitProjectInfo.fromJson(Map<String, dynamic> data) => GitProjectInfo(+ isGit: data['isGit'] == true,+ branch: data['branch'] as String?,+ error: data['error'] as String?,+ mainFolder: data['mainFolder'] is String && validGitPath(data['mainFolder'])+ ? data['mainFolder'] as String+ : null,+ mainBranch: data['mainBranch'] as String?,+ defaultRef: data['defaultRef'] is String && validGitRef(data['defaultRef'])+ ? data['defaultRef'] as String+ : null,+ root: data['root'] is String && validGitPath(data['root'])+ ? data['root'] as String+ : null,+ branches: [+ for (final row in (data['branches'] as List? ?? const []))+ if (row is Map && row['ref'] is String && row['name'] is String)+ GitBranch(+ row['ref'] as String,+ row['name'] as String,+ remote: row['remote'] == true,+ worktree: row['worktree'] is String+ ? row['worktree'] as String+ : null,+ harness: row['harness'] == true,+ ),+ ],+ );++ final bool isGit;+ final String? branch, error;+ final List<GitBranch> branches;++ /// Set only for a folder inside a linked worktree: the same folder in the+ /// repository's main checkout, and the branch that checkout is on.+ final String? mainFolder, mainBranch;++ /// The remote branch new work starts from by default (`origin/HEAD`), and+ /// the checkout the folder belongs to.+ final String? defaultRef, root;++ /// Whether the machine could not answer at all, as opposed to answering+ /// "not a repository". The difference decides whether the screen offers+ /// nothing or says why.+ bool get unavailable => error != null;+}++/// What Start does with a Git project in a new worktree.+enum WorktreeStart {+ /// A new branch from the chosen base.+ newBranch,++ /// An existing local branch, checked out as it is.+ existingBranch,++ /// The branch already has a worktree: the harness starts in it.+ openWorktree,++ /// The branch is the project folder's own and cannot be checked out twice.+ unavailable,+}++class WorktreePlan {+ const WorktreePlan(this.kind, this.branch, {this.base, this.worktree});++ final WorktreeStart kind;+ final String branch;++ /// What a new branch starts from; a remote branch of the same name is tracked.+ final String? base;++ /// Where an existing worktree is.+ final String? worktree;++ bool get tracks =>+ kind == WorktreeStart.newBranch &&+ base != null &&+ base!.startsWith('refs/remotes/') &&+ base!.split('/').skip(3).join('/') == branch;+}++/// The project folder's own branch, if it is on one.+String? currentBranchRef(GitProjectInfo info) =>+ info.branch != null &&+ info.branches.any((b) => b.ref == 'refs/heads/${info.branch}')+ ? 'refs/heads/${info.branch}'+ : null;++/// Worktree starts on for a Git project with a commit to start from.+bool worktreeByDefault(GitProjectInfo info) =>+ info.isGit && info.branches.any((branch) => !branch.remote);++/// Where Start begins when no branch was chosen: new work from the default+/// branch (the local one, which Start brings up to its remote), work in the+/// folder on the branch it is on.+String? defaultBranchRef(GitProjectInfo info, {required bool worktree}) {+ if (!worktree) return currentBranchRef(info);+ final remote = info.defaultRef;+ final local = remote == null+ ? null+ : 'refs/heads/${remote.split('/').skip(3).join('/')}';+ return info.branches.any((b) => b.ref == local)+ ? local+ : remote ?? currentBranchRef(info);+}++/// The branch a worktree started from [base] is on, unless [name] was typed:+/// the default or current branch gets a new [placeholder] branch; another+/// local branch is checked out as it is, or opened in its worktree; a remote+/// branch nobody has locally becomes a local branch tracking it.+WorktreePlan planWorktree(+ GitProjectInfo info, {+ required String? base,+ required String? name,+ required String placeholder,+}) {+ GitBranch? local(String branch) =>+ info.branches.where((b) => !b.remote && b.name == branch).firstOrNull;+ // The folder's own branch cannot be checked out again: typed, it is refused;+ // picked (itself or its remote), a new branch starts from what was picked.+ WorktreePlan onLocal(GitBranch branch, {required bool chosen}) =>+ branch.name == info.branch+ ? chosen+ ? WorktreePlan(WorktreeStart.unavailable, branch.name)+ : WorktreePlan(WorktreeStart.newBranch, placeholder, base: base)+ : branch.worktree != null+ ? WorktreePlan(+ WorktreeStart.openWorktree,+ branch.name,+ worktree: branch.worktree,+ )+ : WorktreePlan(WorktreeStart.existingBranch, branch.name);+ final typed = name?.trim();+ if (typed != null && typed.isNotEmpty) {+ final existing = local(typed);+ return existing == null+ ? WorktreePlan(WorktreeStart.newBranch, typed, base: base)+ : onLocal(existing, chosen: true);+ }+ final fresh = WorktreePlan(WorktreeStart.newBranch, placeholder, base: base);+ final defaultName = info.defaultRef?.split('/').skip(3).join('/');+ if (base == null ||+ base == info.defaultRef ||+ base == 'refs/heads/$defaultName') {+ return fresh;+ }+ if (base.startsWith('refs/heads/')) {+ final branch = local(base.substring('refs/heads/'.length));+ return branch == null ? fresh : onLocal(branch, chosen: false);+ }+ final short = base.split('/').skip(3).join('/');+ final branch = local(short);+ return branch != null+ ? onLocal(branch, chosen: false)+ : WorktreePlan(WorktreeStart.newBranch, short, base: base);+}++/// With Worktree off, the new branch the folder moves to: a typed name no+/// local branch has.+String? newBranchHere(GitProjectInfo info, String? name) {+ final typed = name?.trim();+ return typed == null ||+ typed.isEmpty ||+ info.branches.any((b) => !b.remote && b.name == typed)+ ? null+ : typed;+}++/// The preparation a Git project's folder gets at Start.+///+/// ⚠️ **Ported from the desktop's `state/new_harness.dart` line for line, and+/// that is the point of it.** This is the function that decides what the+/// machine is ASKED to do — make a branch, check one out, open a worktree — and+/// a phone that decided differently would answer the same question with a+/// different repository. Change it here only by changing it there too.+ProjectFolderRequest? gitFolderRequest(+ String folder,+ GitProjectInfo info, {+ required bool worktree,+ required String? branchRef,+ required String? branchName,+ required String placeholder,+}) {+ final ref = branchRef ?? defaultBranchRef(info, worktree: worktree);+ if (!worktree) {+ if (newBranchHere(info, branchName) case final name?) {+ return ProjectFolderRequest.branch(+ folder,+ 'refs/heads/$name',+ newBranch: name,+ );+ }+ return ref == null ? null : ProjectFolderRequest.branch(folder, ref);+ }+ final plan = planWorktree(+ info,+ base: ref,+ name: branchName,+ placeholder: placeholder,+ );+ return switch (plan.kind) {+ WorktreeStart.openWorktree => ProjectFolderRequest.branch(+ folder,+ 'refs/heads/${plan.branch}',+ ),+ WorktreeStart.existingBranch => ProjectFolderRequest.worktree(+ folder,+ branchRef: 'refs/heads/${plan.branch}',+ branchName: plan.branch,+ existingBranch: true,+ ),+ WorktreeStart.newBranch ||+ WorktreeStart.unavailable => ProjectFolderRequest.worktree(+ folder,+ branchRef: plan.base,+ branchName: plan.branch,+ placeholder: plan.branch == placeholder,+ ),+ };+}++/// Two plain words for a branch nothing has named yet — plumbing, like the+/// worktree's folder: the harness or the person names the real branch when+/// there is something to push. Mirrors cli/src/lib/agentNames.ts.+const kPlaceholderAdjectives = [+ 'amber', 'bold', 'brave', 'brisk', 'calm', 'clever', 'cosmic', 'crisp', //+ 'dapper', 'eager', 'fancy', 'gentle', 'glad', 'golden', 'happy', 'hidden',+ 'jolly', 'keen', 'kind', 'lively', 'lucky', 'merry', 'misty', 'noble', //+ 'polite', 'proud', 'quick', 'quiet', 'rapid', 'rosy', 'royal', 'rustic',+ 'shiny', 'silent', 'silver', 'sleek', 'smart', 'snowy', 'solar', 'spry',+ 'steady', 'sunny', 'swift', 'tidy', 'vivid', 'warm', 'witty', 'zesty',+];++const kPlaceholderNouns = [+ 'badger', 'beacon', 'birch', 'bison', 'canyon', 'cedar', 'comet', 'coral',+ 'crane', 'delta', 'falcon', 'fern', 'finch', 'fjord', 'fox', 'gecko', //+ 'glacier', 'harbor', 'hawk', 'heron', 'ibis', 'island', 'koala', 'lagoon',+ 'lark', 'lynx', 'maple', 'meadow', 'meteor', 'moose', 'nebula', 'otter', //+ 'owl', 'panda', 'pebble', 'pine', 'puffin', 'quartz', 'raven', 'reef', //+ 'river', 'robin', 'sparrow', 'spruce', 'tiger', 'walrus', 'willow', 'zebra',+];++/// `brave-otter`: the branch a new worktree starts on until its session has a+/// name, one none of [taken] (branch names, with or without `refs/heads/`)+/// already uses.+String placeholderBranch(Iterable<String> taken, {Random? random}) {+ final names = {+ for (final name in taken) name.replaceFirst('refs/heads/', ''),+ };+ final pick = random ?? Random();+ String draw() =>+ '${kPlaceholderAdjectives[pick.nextInt(kPlaceholderAdjectives.length)]}'+ '-${kPlaceholderNouns[pick.nextInt(kPlaceholderNouns.length)]}';+ var name = draw();+ for (var tries = 0; tries < 16 && names.contains(name); tries++) {+ name = draw();+ }+ final base = name;+ for (var suffix = 2; names.contains(name); suffix++) {+ name = '$base-$suffix';+ }+ return name;+}++/// What a typed name becomes as a branch, as editors do it: words joined by+/// `-`, and nothing `git check-ref-format` refuses. Empty when nothing is left.+String branchNameFrom(String typed) {+ var name = typed+ .trim()+ .replaceAll(RegExp(r'\s+'), '-')+ .replaceAll(RegExp(r'[\x00-\x1f\x7f~^:?*\[\\]+'), '')+ .replaceAll(RegExp(r'\.{2,}'), '.')+ .replaceAll('@{', '@')+ .replaceAll(RegExp(r'/{2,}'), '/')+ .replaceAll(RegExp(r'/[.]+'), '/')+ .replaceAll(RegExp(r'-{2,}'), '-')+ .replaceAll(RegExp(r'^[-./]+'), '');+ for (var trimmed = ''; trimmed != name;) {+ trimmed = name;+ name = name.replaceAll(RegExp(r'(\.lock|[./])$'), '');+ }+ return name == '@' ? '' : name;+}++/// A name Git accepts for a new branch, checked before Git is asked.+bool plausibleBranchName(String name) =>+ name.isNotEmpty &&+ name.length <= 255 &&+ !name.startsWith('-') &&+ !RegExp(r'[\x00-\x20\x7f~^:?*\[\\]').hasMatch(name);++bool validGitPath(String path) =>+ p.isAbsolute(path) &&+ path.length <= 4096 &&+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(path);++bool validGitRef(String ref) =>+ ref.length <= 1024 &&+ RegExp(r'^refs/(heads|remotes)/[^\s\x00-\x1f\x7f]+$').hasMatch(ref);diff --git a/mobile/lib/core/project_folder.dart b/mobile/lib/core/project_folder.dartindex b751512a8..9e38a0df8 100644--- a/mobile/lib/core/project_folder.dart+++ b/mobile/lib/core/project_folder.dart@@ -11,17 +11,89 @@/// 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;+ const ProjectFolderRequest.newProject()+ : repository = null,+ gitSource = null,+ branchRef = null,+ branchName = null,+ existingBranch = false,+ placeholder = false,+ createsWorktree = false;/// Let the machine clone [value] and work in the checkout.- const ProjectFolderRequest.remote(GitHubRepository value) : repository = value;+ const ProjectFolderRequest.remote(GitHubRepository value)+ : repository = value,+ gitSource = null,+ branchRef = null,+ branchName = null,+ existingBranch = false,+ placeholder = false,+ createsWorktree = false;++ /// A new worktree of the repository at [source], on [branchName]: created+ /// from [branchRef], or with [existingBranch] that local branch checked out+ /// as it is. Without a name the machine makes one up.+ ///+ /// ⚠️ [placeholder] says the name was MADE UP here rather than typed, so the+ /// machine may replace it with the session's own name once the engine reports+ /// one. A name a person typed is theirs and is never replaced.+ const ProjectFolderRequest.worktree(+ String source, {+ this.branchRef,+ this.branchName,+ this.existingBranch = false,+ this.placeholder = false,+ }) : gitSource = source,+ createsWorktree = true,+ repository = null;++ /// The folder at [source] itself on [ref], or with [newBranch] on that new+ /// branch, made where the folder is now.+ ///+ /// ⚠️ [ref] then names the NEW branch, so a daemon too old to make one+ /// refuses the request rather than quietly starting the harness on the old+ /// branch — which is the one outcome nobody could see had happened.+ const ProjectFolderRequest.branch(+ String source,+ String ref, {+ String? newBranch,+ }) : gitSource = source,+ branchRef = ref,+ branchName = newBranch,+ existingBranch = false,+ placeholder = false,+ createsWorktree = false,+ repository = null;final GitHubRepository? repository;+ /// The existing checkout a branch or worktree is taken from. Null for the two+ /// sources that have no repository yet.+ final String? gitSource;++ /// What to start from, and what to call the branch that starts there.+ final String? branchRef, branchName;++ final bool createsWorktree, existingBranch, placeholder;+/// ⚠️ 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.+ ///+ /// The keys are the desktop's, byte for byte (`core/project_folder.dart`+ /// there): the same CLI parses both, and a phone inventing its own spelling+ /// would be a second dialect to keep in step.Map<String, String> get payload => {- 'projectSource': repository == null ? 'new' : 'remote',+ 'projectSource': gitSource != null+ ? (createsWorktree ? 'worktree' : 'branch')+ : repository == null+ ? 'new'+ : 'remote',+ 'gitSource': ?gitSource,+ 'branchRef': ?branchRef,+ // A daemon that predates these names the worktree's branch itself.+ 'branchName': ?branchName,+ if (existingBranch) 'branchMode': 'existing',+ if (placeholder) 'branchMode': 'placeholder',if (repository != null) 'repositoryUrl': repository!.url,};}diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex b2e36099c..c547cd943 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -35,6 +35,15 @@ const Set<String> encryptedDownTypes = {'agent_read_file','fs_list_dir','project_preview',+ // The branches of a folder on that machine, for the New Harness form+ // (`AppNotifier.readGitProject`).+ //+ // ⚠️ **Not in the CLI's `ENCRYPTED_DOWN_TYPES`, and still required.** The+ // machine's real rule is `encryptDownFrame` in `cli/src/lib/e2ee/+ // applicationFrames.ts`, which is that set OR a handful of types named+ // outright beside it — this one among them. Sent in the clear it came back+ // `E2EE_REQUIRED`, which on this screen read as a folder with no branches.+ 'git_project_info','codex_profiles_list','codex_profile_link',// Asks the machine to read its OWN agent accounts' usage (cli/src/lib/accountUsage.ts). Missingdiff --git a/mobile/lib/phone/branch_picker_sheet.dart b/mobile/lib/phone/branch_picker_sheet.dartnew file mode 100644index 000000000..680bb2991--- /dev/null+++ b/mobile/lib/phone/branch_picker_sheet.dart@@ -0,0 +1,270 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/core/git_project.dart';+import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'phone_search_field.dart';+import 'sheet_list.dart';++/// The branches of a project, to start a harness on.+///+/// ```+/// ───────────────────────────────+/// ⌕ Search branches+/// + New branch…+/// main default · current+/// feat/tabs in a worktree+/// origin/main remote+/// ```+///+/// ⚠️ **A sheet with a field in it, not the rows folded into the form.** A+/// repository with six branches fits under a row; the ones people actually work+/// in have dozens, and a fold turns the New Harness form into a list to scroll+/// past. The desktop asks the same question in its own box with `Search+/// branches` at the foot of it — this is that box.+///+/// ⚠️ **`default · current` is copied from the desktop's picker word for word.**+/// They answer two different questions that look alike: *default* is where new+/// work starts from on this repository, *current* is where the folder is+/// standing right now. A person who has both in front of them can tell whether+/// picking `main` means "branch from the usual place" or "carry on where I am".+///+/// Returns what was chosen — a ref to start from, or a name to create — or null+/// where the sheet was dismissed.+Future<BranchChoice?> showBranchPickerSheet(+ BuildContext context, {+ required GitProjectInfo info,+ required String? selectedRef,+ required String? typedName,+}) => showModalBottomSheet<BranchChoice>(+ context: context,+ useRootNavigator: true,+ showDragHandle: true,+ backgroundColor: AppPalette.panelBg,+ isScrollControlled: true,+ builder: (_) =>+ _BranchPicker(info: info, selectedRef: selectedRef, typedName: typedName),+);++/// What came back: [ref] to start from an existing branch, or [name] to make+/// one. Exactly one is set.+class BranchChoice {+ const BranchChoice.ref(String this.ref) : name = null;+ const BranchChoice.name(String this.name) : ref = null;++ final String? ref, name;+}++class _BranchPicker extends StatefulWidget {+ const _BranchPicker({+ required this.info,+ required this.selectedRef,+ required this.typedName,+ });++ final GitProjectInfo info;+ final String? selectedRef, typedName;++ @override+ State<_BranchPicker> createState() => _BranchPickerState();+}++class _BranchPickerState extends State<_BranchPicker> {+ final _controller = TextEditingController();+ final _focus = FocusNode();+ String _query = '';++ @override+ void dispose() {+ _controller.dispose();+ _focus.dispose();+ super.dispose();+ }++ /// The default branch's short name, for the note beside it.+ String? get _defaultName =>+ widget.info.defaultRef?.split('/').skip(3).join('/');++ /// Local first, then remote — the order the desktop lists them in, and the+ /// order of how likely each is to be the answer.+ List<GitBranch> get _matches {+ final query = _query.trim().toLowerCase();+ bool hit(GitBranch branch) =>+ query.isEmpty || branch.name.toLowerCase().contains(query);+ return [+ for (final branch in widget.info.branches)+ if (!branch.remote && hit(branch)) branch,+ for (final branch in widget.info.branches)+ if (branch.remote && hit(branch)) branch,+ ];+ }++ /// What a branch is, in the words the desktop uses.+ ///+ /// ⚠️ **The folder's OWN branch is `current`, never "in a worktree".** Git+ /// records a checkout for it like any other — the project folder is itself a+ /// checkout — so the raw answer says `main` is in a worktree, which is true+ /// and useless: it is in THIS one. Read that way the row said "in a worktree"+ /// where the desktop says `default · current`, and the two facts that tell+ /// those words apart were nowhere on screen.+ ///+ /// The note is otherwise about OTHER checkouts, and that one outranks the+ /// marks because it changes what Start does: a branch already checked out+ /// elsewhere cannot be checked out again, and the harness opens that worktree+ /// instead.+ String? _note(GitBranch branch) {+ if (branch.remote) return 'remote';+ final marks = [+ if (branch.name == _defaultName) 'default',+ if (branch.name == widget.info.branch) 'current',+ ];+ if (marks.isNotEmpty) return marks.join(' · ');+ return branch.worktree == null ? null : 'in a worktree';+ }++ Widget? _noteRow(GitBranch branch) {+ final note = _note(branch);+ return note == null ? null : SheetRowNote(note);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final matches = _matches;+ final typed = widget.typedName;+ return SafeArea(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(kSheetInset, 0, kSheetInset, 10),+ child: PhoneSearchField(+ controller: _controller,+ focus: _focus,+ // ⚠️ Not autofocused. The list is worth reading first — most+ // repositories have a handful of branches and the answer is on+ // screen already; the keyboard would bury it.+ autofocus: false,+ hintText: 'Search branches',+ onChanged: (value) => setState(() => _query = value),+ onClear: () => setState(() {+ _controller.clear();+ _query = '';+ }),+ ),+ ),+ Flexible(+ child: ListView.builder(+ padding: EdgeInsets.fromLTRB(+ kSheetInset,+ 0,+ kSheetInset,+ MediaQuery.paddingOf(context).bottom + 16,+ ),+ itemCount: matches.length + 1,+ itemBuilder: (context, index) {+ if (index == 0) {+ // First, because a branch nobody has yet is what most new+ // work starts on and it cannot be found by searching.+ return SheetRow(+ first: true,+ last: matches.isEmpty,+ leading: SheetTile(+ child: Icon(+ LucideIcons.plus,+ size: 18,+ color: AppPalette.accentOnSurface,+ ),+ ),+ title: Text(+ typed == null ? 'New branch…' : 'New branch: $typed',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: sheetRowTitleStyle().copyWith(+ color: AppPalette.accentOnSurface,+ ),+ ),+ onTap: () {+ HapticFeedback.selectionClick();+ Navigator.of(context).pop(const BranchChoice.name(''));+ },+ );+ }+ final branch = matches[index - 1];+ final chosen =+ widget.typedName == null &&+ branch.ref == widget.selectedRef;+ return SheetRow(+ first: false,+ last: index == matches.length,+ leading: SheetTile(+ child: Icon(+ LucideIcons.gitBranch,+ size: 18,+ color: chosen+ ? AppPalette.accentOnSurface+ : AppPalette.textSecondary,+ ),+ ),+ title: Text(+ branch.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: sheetRowTitleStyle(),+ ),+ chevron: false,+ selected: chosen,+ // The note goes where a status would: `default · current` is+ // what this branch IS, the same kind of fact.+ // ⚠️ **The note and the tick sit side by side, and the note+ // is never given up for it.** They were one slot, so the+ // branch most likely to carry `default · current` — the one+ // the form starts on — was also the one wearing the tick,+ // and the two facts a person needs to tell those words apart+ // were exactly the ones never shown.+ trailing: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ ?_noteRow(branch),+ if (chosen) ...[+ const SizedBox(width: 8),+ Icon(+ LucideIcons.check300,+ size: 18,+ color: AppPalette.accent,+ ),+ ],+ ],+ ),+ onTap: () {+ HapticFeedback.selectionClick();+ Navigator.of(context).pop(BranchChoice.ref(branch.ref));+ },+ );+ },+ ),+ ),+ if (matches.isEmpty && _query.trim().isNotEmpty)+ Padding(+ padding: const EdgeInsets.fromLTRB(+ kSheetCaptionInset,+ 0,+ kSheetInset,+ 12,+ ),+ child: Text(+ 'No branch matches “${_query.trim()}”. New branch… makes one.',+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: 13.5,+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex e50b69730..ef63affb6 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -7,10 +7,12 @@ import 'package:harness_mobile/core/codex_profiles.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/git_project.dart';import 'package:harness_mobile/core/project_folder.dart';import 'package:harness_mobile/widgets/remote_folder_picker.dart';import 'agent_index.dart';+import 'branch_picker_sheet.dart';import 'phone_header.dart';import 'phone_navigation.dart';import 'phone_status.dart';@@ -52,6 +54,19 @@ class _NewAgentPageState extends State<NewAgentPage> {/// Whether the engines past [_primaryEngines] are shown.bool _moreEnginesOpen = false;+ /// Whether PROJECT and ENGINE are folded open onto their choices. BRANCH+ /// opens a sheet of its own instead — see [showBranchPickerSheet] — because+ /// its list is the one that needs searching.+ ///+ /// ⚠️ **Shut by default, and that is what makes this a form rather than a+ /// list of everything.** Laid out flat it ran to ten rows with four sources+ /// and five engines always on screen, so the two rows that matter — where the+ /// work is and what runs it — read as items in a catalogue, and Branch had+ /// nowhere to go. Folded, the page says what is chosen; opening a section is+ /// how it is changed. It is the idiom MACHINE above already uses.+ bool _projectOpen = false;+ bool _engineOpen = false;+String? _folder;/// Set when the MACHINE is to produce the folder — a fresh project, or a clone — instead of one@@ -84,6 +99,43 @@ class _NewAgentPageState extends State<NewAgentPage> {/// taken the list has nothing left to say.bool _recentOpen = false;+ /// What the machine said about [_folder]'s repository, and which folder it+ /// answered about.+ ///+ /// ⚠️ **The path is kept beside the answer on purpose.** The read is a round+ /// trip to somebody's laptop and the folder can change twice while one is in+ /// flight; without it, a slow answer about the folder before last would draw+ /// that repository's branches under this one's name.+ GitProjectInfo? _git;+ String? _gitFolder;+ bool _gitLoading = false;++ /// Set when the machine could not answer at all, as opposed to answering+ /// "not a repository".+ ///+ /// ⚠️ **Kept apart from [_git] because the two used to look identical, and+ /// that hid a real fault.** `git_project_info` was missing from this app's+ /// end-to-end encrypted frame list, so every machine refused it with+ /// `E2EE_REQUIRED` — and since a folder that is not a checkout also offers+ /// nothing, the section simply never appeared and there was nothing on screen+ /// to say why. A refusal says so now.+ bool _gitFailed = false;++ /// Start puts the harness in a worktree of its own rather than in the folder+ /// itself. Set from [worktreeByDefault] each time a repository is read, which+ /// is what the desktop's box does with the same answer.+ bool _worktree = false;++ /// What the new branch starts FROM (a ref), and what to call it. Null base+ /// means [defaultBranchRef]; null name means a made-up one.+ String? _branchRef;+ String? _branchName;++ /// Held for the length of the form rather than drawn fresh on every build:+ /// the name is random, and one that changed under the person between the row+ /// they read and the harness they started would be a different branch.+ String? _placeholder;+@overridevoid initState() {super.initState();@@ -129,6 +181,13 @@ class _NewAgentPageState extends State<NewAgentPage> {_project = null;_projectLabel = null;_recentOpen = false;+ _git = null;+ _gitFolder = null;+ _gitLoading = false;+ _gitFailed = false;+ _worktree = false;+ _branchRef = null;+ _branchName = null;_codexProfiles = const [];_codexProfile = null;_codexProfilesLoaded = false;@@ -147,6 +206,124 @@ class _NewAgentPageState extends State<NewAgentPage> {machine,];+ /// Reads [folder]'s repository on its machine, and starts the Git choices+ /// where the desktop starts them.+ ///+ /// Silent about failure. A folder that is not a repository and a machine that+ /// could not answer both come back with nothing to offer, and neither is+ /// something to interrupt a half-filled form about — the section simply does+ /// not appear, and everything else on the page still works.+ Future<void> _loadGit(String folder) async {+ final machineId = _machineId;+ setState(() {+ _gitLoading = true;+ _gitFailed = false;+ _gitFolder = folder;+ _git = null;+ _branchRef = null;+ _branchName = null;+ _worktree = false;+ });+ final raw = await widget.notifier.readGitProject(machineId, folder);+ // A late answer about a folder the form has since left belongs to nobody —+ // see the note on [_gitFolder].+ if (!mounted || machineId != _machineId || folder != _folder) return;+ final info = GitProjectInfo.fromJson(raw);+ setState(() {+ _gitLoading = false;+ _gitFailed = info.unavailable;+ _git = info.isGit ? info : null;+ if (!info.isGit) return;+ _worktree = worktreeByDefault(info);+ _branchRef = defaultBranchRef(info, worktree: _worktree);+ _placeholder ??= placeholderBranch([+ for (final branch in info.branches)+ if (!branch.remote) branch.name,+ ]);+ });+ }++ /// The repository the Git rows are about, or null when there is none to show.+ GitProjectInfo? get _repository =>+ _folder != null && _folder == _gitFolder ? _git : null;++ /// What Start would do, so the rows can say it before it is done. Null when+ /// there is no repository, or when Worktree is off — the folder simply moves+ /// to the branch then, and the row already names it.+ WorktreePlan? get _plan {+ final info = _repository;+ if (info == null || !_worktree) return null;+ return planWorktree(+ info,+ base: _branchRef ?? defaultBranchRef(info, worktree: true),+ name: _branchName,+ placeholder: _placeholder ?? 'new-branch',+ );+ }++ /// The PROJECT row's own line: the folder's last segment, or the name of the+ /// source that will make one.+ String get _projectTitle => _folder != null+ ? _basename(_folder!)+ : (_projectLabel ?? 'Choose a folder');++ /// Under it: the whole path, or why there is none yet.+ String? get _projectDetail =>+ _folder ??+ (_project?.repository != null+ ? 'Cloned on the machine'+ : _project != null+ ? 'A fresh folder, made on the machine'+ : null);++ String get _engineLabel => _engine == null+ ? 'Choose an agent'+ : allEngines+ .where((identity) => identity.id == _engine)+ .firstOrNull+ ?.label ??+ _engine!;++ /// What the BRANCH row says is about to happen, in the words of the thing it+ /// will do. Null leaves the row showing the branch alone.+ ///+ /// ⚠️ The four answers are not decoration: with Worktree on, the same branch+ /// name means make one, check one out, or walk into a worktree that already+ /// exists — and the last two are surprises if the row said only "main".+ String? get _branchNote => switch (_plan?.kind) {+ WorktreeStart.newBranch => 'A new branch from here, in its own worktree',+ WorktreeStart.existingBranch => 'Checked out in a new worktree',+ WorktreeStart.openWorktree => 'Opens the worktree it already has',+ WorktreeStart.unavailable =>+ 'The folder is on this branch — pick another, or turn Worktree off',+ null =>+ _repository == null || _branchName == null ? null : 'New branch here',+ };++ /// The branch the row names: the one Start begins FROM.+ ///+ /// ⚠️ **Never the made-up name a new worktree's branch gets.** With Worktree+ /// on, [planWorktree] answers with a two-word placeholder — `brave-otter` —+ /// that the daemon replaces with the session's own name later. Shown as the+ /// title it read as the app picking a branch at random, and the branch the+ /// person actually chose was nowhere on the row. The desktop's field shows+ /// `branchLabel`, which is the name of `branchRef` and nothing else; this is+ /// that. What the placeholder is FOR belongs in the note under it.+ String get _branchTitle {+ final typed = _branchName?.trim();+ if (typed != null && typed.isNotEmpty) return typed;+ final info = _repository;+ final ref =+ _branchRef ??+ (info == null ? null : defaultBranchRef(info, worktree: _worktree));+ if (ref == null) return info?.branch ?? 'Default';+ final named = info?.branches+ .where((branch) => branch.ref == ref)+ .firstOrNull+ ?.name;+ return named ?? ref.replaceFirst(RegExp(r'^refs/(heads|remotes)/'), '');+ }+/// Discovery runs on the MACHINE, never on this device — the phone has no/// Codex config of its own and the agent will not run here anyway.Future<void> _loadCodexProfiles() async {@@ -292,6 +469,8 @@ class _NewAgentPageState extends State<NewAgentPage> {_project = ProjectFolderRequest.remote(repository);_projectLabel = repository.name;_folder = null;+ _git = null;+ _gitFolder = null;_error = null;});}@@ -310,6 +489,7 @@ class _NewAgentPageState extends State<NewAgentPage> {_projectLabel = null;_error = null;});+ unawaited(_loadGit(chosen));}Future<void> _create() async {@@ -325,13 +505,30 @@ class _NewAgentPageState extends State<NewAgentPage> {// [AgentCreationAttempt.agentId]. A fresh one per submit, which is what the// call made on its own before: a retry after a refusal is a new request.final creation = AgentCreationAttempt();+ // A folder in a repository is not sent as a bare `cwd`: the branch and the+ // worktree travel with it, and [gitFolderRequest] is the desktop's own rule+ // for turning the rows above into what the machine is asked to do. A folder+ // that is not a repository, or one this form never read, falls through to+ // the plain path — and `New project` / `Git…` keep the request they made.+ final request =+ project ??+ (folder == null || _repository == null+ ? null+ : gitFolderRequest(+ folder,+ _repository!,+ worktree: _worktree,+ branchRef: _branchRef,+ branchName: _branchName,+ placeholder: _placeholder ?? 'new-branch',+ ));final error = await widget.notifier.createAgent(_machineId,engine: engine,// 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,+ projectFolder: request,// Only for Codex, and only when chosen: omitted, the machine launches// with its own default CODEX_HOME.codexHome: _showsCodexProfile ? _codexProfile?.path : null,@@ -443,158 +640,233 @@ class _NewAgentPageState extends State<NewAgentPage> {),],),- const SettingsCaption('FOLDER'),+ const SettingsCaption('PROJECT'),SettingsGroup(children: [+ // What is chosen, and the way into changing it. Its+ // detail is the full path: the title is only the last+ // segment, and two machines' `mobile` folders are told+ // apart by everything before it.SettingsRow(- title: 'New project',- detail:- _projectSourceNote ??- 'A fresh folder, made on the machine',+ title: _projectTitle,+ detail: _projectDetail,leading: Icon(- LucideIcons.folderPlus300,+ LucideIcons.folder300,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: _browsed ? _folder : null,- leading: Icon(- LucideIcons.folderSearch300,+ trailing: Icon(+ _projectOpen+ ? LucideIcons.chevronUp300+ : LucideIcons.chevronDown300,size: 18,- color: AppPalette.textSecondary,+ color: AppPalette.textFaint,),- trailing: _check(_browsed),- onTap: () => unawaited(_browse()),+ onTap: () =>+ setState(() => _projectOpen = !_projectOpen),),- 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)+ if (_projectOpen) ...[SettingsRow(- title: 'Recent',- detail: _recentOpen+ title: 'New project',+ nested: true,+ 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- : (_pickedRecent ?? _recentCount),+ : () => setState(() {+ _project =+ const ProjectFolderRequest.newProject();+ _projectLabel = 'New project';+ _folder = null;+ _git = null;+ _gitFolder = 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…',+ nested: true,+ detail: _browsed ? _folder : null,leading: Icon(- LucideIcons.history300,+ LucideIcons.folderSearch300,size: 18,color: AppPalette.textSecondary,),- trailing: Icon(- _recentOpen- ? LucideIcons.chevronUp300- : LucideIcons.chevronDown300,+ trailing: _check(_browsed),+ onTap: () => unawaited(_browse()),+ ),+ SettingsRow(+ title: 'Git…',+ nested: true,+ detail:+ _projectSourceNote ??+ (_project?.repository == null+ ? 'Clone a GitHub repository'+ : _projectLabel),+ leading: Icon(+ LucideIcons.gitBranch300,size: 18,- color: AppPalette.textFaint,+ color: AppPalette.textSecondary,),- onTap: () =>- setState(() => _recentOpen = !_recentOpen),+ trailing: _check(_project?.repository != null),+ onTap: !_canMakeProject+ ? null+ : () => unawaited(_pickRepository()),),- if (_recentOpen)- for (final path in _recent)+ // 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: _basename(path),- detail: path,+ title: 'Recent',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;- }),+ 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;+ });+ unawaited(_loadGit(path));+ },+ ),+ ],],),- const SettingsCaption('ENGINE'),+ ..._branchSection(),+ // ⚠️ **"Agent" here means the ENGINE — Claude Code, Codex —+ // and that is the desktop's word, not a slip back into the+ // one this app spent a rename getting rid of.** The desktop+ // calls a running instance a HARNESS and the program it+ // runs an AGENT (`NewHarnessField.agent => 'Agent'`), so on+ // this form the two words sit one above the other meaning+ // two different things. Anywhere else in this app, a+ // harness is a harness.+ const SettingsCaption('AGENT'),SettingsGroup(children: [- for (final identity in _shownEngines) ...[- SettingsRow(- title: identity.label,- detail: _engineNote(identity.id),- leading: EngineMark(engine: identity.id, size: 18),- trailing: _check(_engine == identity.id),- onTap: () => setState(() {- _engine = identity.id;- _error = null;- }),+ // The engine in one row, the rest behind it — see+ // [_projectOpen] for why nothing here is laid out flat.+ SettingsRow(+ title: _engineLabel,+ detail: _engine == null+ ? null+ : _engineNote(_engine!),+ leading: _engine == null+ ? Icon(+ LucideIcons.cpu300,+ size: 18,+ color: AppPalette.textSecondary,+ )+ : EngineMark(engine: _engine!, size: 18),+ trailing: Icon(+ _engineOpen+ ? LucideIcons.chevronUp300+ : LucideIcons.chevronDown300,+ size: 18,+ color: AppPalette.textFaint,),- // 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) ...[+ onTap: () =>+ setState(() => _engineOpen = !_engineOpen),+ ),+ if (_engineOpen)+ for (final identity in _shownEngines) ...[SettingsRow(- title: 'Default profile',+ title: identity.label,nested: true,- detail: _codexProfilesLoaded- ? null- : 'Looking for others…',- trailing: _check(_codexProfile == null),- onTap: () => setState(() => _codexProfile = null),+ detail: _engineNote(identity.id),+ leading: EngineMark(+ engine: identity.id,+ size: 18,+ ),+ trailing: _check(_engine == identity.id),+ onTap: () => setState(() {+ _engine = identity.id;+ _error = 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,+ title: 'Default profile',nested: true,- trailing: _check(_codexProfile == profile),+ detail: _codexProfilesLoaded+ ? null+ : 'Looking for others…',+ trailing: _check(_codexProfile == null),onTap: () =>- setState(() => _codexProfile = profile),+ 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),+ ),+ ],],- ],// The rest of the engines, behind one row. It stays once opened: there is// nothing to fold back to that the person would want.- if (!_moreEnginesOpen && _hiddenEngineCount > 0)+ if (_engineOpen &&+ !_moreEnginesOpen &&+ _hiddenEngineCount > 0)SettingsRow(title: '$_hiddenEngineCount more',leading: Icon(@@ -640,11 +912,221 @@ class _NewAgentPageState extends State<NewAgentPage> {},);+ /// BRANCH and Worktree, or nothing at all.+ ///+ /// ⚠️ **Absent rather than empty for a folder with no repository.** Most of+ /// what a phone starts is a fresh project or a clone, and a Branch row that+ /// could never be tapped would be two thirds of this form saying "not+ /// applicable". It appears the moment a folder turns out to be a checkout,+ /// which is also the moment it has something to offer.+ ///+ /// While the machine is still answering, the section is drawn with the row+ /// dimmed instead of appearing late under the thumb — a form that grows a+ /// section between reading it and pressing Create is how people press the+ /// wrong thing.+ List<Widget> _branchSection() {+ final info = _repository;+ if (info == null && !_gitLoading && !_gitFailed) return const [];+ if (info == null && _gitFailed) {+ return [+ const SettingsCaption('BRANCH'),+ SettingsGroup(+ children: [+ SettingsRow(+ title: 'Could not read the repository',+ detail:+ 'The machine did not answer. The harness still starts in '+ 'the folder, on the branch it is on.',+ leading: Icon(+ LucideIcons.gitBranch300,+ size: 18,+ color: AppPalette.textFaint,+ ),+ ),+ ],+ ),+ ];+ }+ return [+ const SettingsCaption('BRANCH'),+ SettingsGroup(+ children: [+ SettingsRow(+ title: _gitLoading ? 'Reading the repository…' : _branchTitle,+ detail: _gitLoading ? null : _branchNote,+ leading: Icon(+ LucideIcons.gitBranch300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ // A chevron pointing RIGHT, not a fold arrow: this row opens a+ // sheet rather than unfolding under itself.+ trailing: _gitLoading+ ? null+ : Icon(+ LucideIcons.chevronRight300,+ size: 18,+ color: AppPalette.textFaint,+ ),+ onTap: _gitLoading || info == null+ ? null+ : () => unawaited(_pickBranch(info)),+ ),+ // ⚠️ Beside the branch row, never inside what opens from it. It+ // changes what that row MEANS — with it off the folder itself moves+ // to the branch, with it on the harness gets a checkout of its own —+ // so it has to be readable at the same time as the answer it+ // qualifies.+ if (info != null)+ SettingsRow(+ title: 'Worktree',+ detail: _worktree+ ? 'A checkout of its own, beside the folder'+ : 'Work in the folder itself',+ leading: Icon(+ LucideIcons.gitFork300,+ size: 18,+ color: AppPalette.textSecondary,+ ),+ trailing: Switch.adaptive(+ value: _worktree,+ onChanged: (value) => setState(() {+ _worktree = value;+ // The base a branch starts from is read differently by each+ // — see [defaultBranchRef] — so a ref chosen for one is not+ // an answer to the other.+ _branchRef = defaultBranchRef(info, worktree: value);+ _error = null;+ }),+ ),+ onTap: () => setState(() {+ _worktree = !_worktree;+ _branchRef = defaultBranchRef(info, worktree: _worktree);+ _error = null;+ }),+ ),+ ],+ ),+ ];+ }++ /// The branch row: the picker, and the name dialog behind its first entry.+ ///+ /// ⚠️ **Two sheets, one after the other, rather than a field in the list.**+ /// The picker is a list to search; naming a branch is a keyboard and a rule+ /// about what Git accepts. Put together, the keyboard covered the list the+ /// moment the field took focus.+ Future<void> _pickBranch(GitProjectInfo info) async {+ final choice = await showBranchPickerSheet(+ context,+ info: info,+ selectedRef: _branchRef ?? defaultBranchRef(info, worktree: _worktree),+ typedName: _branchName,+ );+ if (choice == null || !mounted) return;+ if (choice.ref case final ref?) {+ setState(() {+ _branchRef = ref;+ _branchName = null;+ _error = null;+ });+ return;+ }+ await _typeBranch();+ }++ /// Asks for a branch name, and keeps only what Git would take.+ Future<void> _typeBranch() async {+ final typed = await showDialog<String>(+ context: context,+ useRootNavigator: true,+ builder: (_) => _BranchDialog(initial: _branchName),+ );+ if (typed == null || !mounted) return;+ setState(() {+ _branchName = typed.isEmpty ? null : typed;+ _error = null;+ });+ }+Widget? _check(bool selected) => selected? Icon(LucideIcons.check300, size: 18, color: AppPalette.accent): null;}+/// A branch name, cleaned the way Git would take it.+///+/// ⚠️ **Cleaned as it is typed, not on submit.** `branchNameFrom` turns spaces+/// into dashes and drops what `git check-ref-format` refuses, and a person who+/// only finds that out after starting a harness has a branch they did not name.+/// Shown live, the field IS the answer.+class _BranchDialog extends StatefulWidget {+ const _BranchDialog({this.initial});++ final String? initial;++ @override+ State<_BranchDialog> createState() => _BranchDialogState();+}++class _BranchDialogState extends State<_BranchDialog> {+ late final _controller = TextEditingController(text: widget.initial ?? '');++ String get _clean => branchNameFrom(_controller.text);+ bool get _ok => _clean.isEmpty || plausibleBranchName(_clean);++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ void _submit() {+ if (!_ok) return;+ Navigator.of(context).pop(_clean);+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ final clean = _clean;+ return AlertDialog(+ title: const Text('New branch'),+ content: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ TextField(+ controller: _controller,+ autofocus: true,+ autocorrect: false,+ style: kFieldTextStyle,+ textInputAction: TextInputAction.done,+ onChanged: (_) => setState(() {}),+ onSubmitted: (_) => _submit(),+ ),+ // Only when it differs: repeating back exactly what was typed is+ // noise, and the line is here to warn.+ if (clean.isNotEmpty && clean != _controller.text.trim()) ...[+ const SizedBox(height: 10),+ Text(+ 'Git will call it $clean',+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 12.5),+ ),+ ],+ ],+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(),+ child: const Text('Cancel'),+ ),+ FilledButton(onPressed: _ok ? _submit : null, child: const Text('Use')),+ ],+ );+ }+}+/// 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 {diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 3c12ece25..c6f2ec474 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -4705,6 +4705,38 @@ class AppNotifier extends ChangeNotifier {}}+ /// The Git choices [path] offers, read ON the machine that owns it.+ ///+ /// ⚠️ **The phone never looks at a repository itself, and could not.** The+ /// folder is on somebody's laptop; `git` runs there. The desktop has a local+ /// branch of this same call for its own machine — see `readGitProject` there+ /// — and this is the half that is always remote.+ ///+ /// Answers `{isGit, branch, branches: [...], defaultRef, root, ...}`, parsed+ /// by [GitProjectInfo.fromJson], or `{error}` — which the form draws as "no+ /// Git choices here" rather than as a failure, because a folder that is not a+ /// repository answers the same way.+ ///+ /// A short timeout on purpose: this runs while somebody is looking at a form+ /// they have already half filled in, and a machine that cannot answer in six+ /// seconds should leave the rest of the form working.+ Future<Map<String, dynamic>> readGitProject(+ String machineId,+ String path,+ ) async {+ final machine = machineStates[machineId];+ if (machine == null) return {'error': 'UNAVAILABLE'};+ try {+ return await _conn(machineId).request(+ 'git_project_info',+ payload: {'path': path},+ timeout: const Duration(seconds: 6),+ );+ } 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 remotediff --git a/mobile/test/encrypted_down_types_test.dart b/mobile/test/encrypted_down_types_test.dartindex 41bc89d9a..cd6a0d477 100644--- a/mobile/test/encrypted_down_types_test.dart+++ b/mobile/test/encrypted_down_types_test.dart@@ -16,21 +16,72 @@ void main() {final from = source.indexOf(start);expect(from, isNonNegative, reason: 'could not find $start');final body = source.substring(from, source.indexOf(end, from));- final code = body.split('\n').map((line) => line.split('//').first).join('\n');+ final code = body+ .split('\n')+ .map((line) => line.split('//').first)+ .join('\n');return {for (final match in RegExp(r"'([a-z0-9_]+)'").allMatches(code)) match[1]!,};}- test('matches the CLI\'s ENCRYPTED_DOWN_TYPES', () {+ test('seals every type the CLI insists on', () {final core = File('../cli/src/lib/e2ee/core.ts');- expect(core.existsSync(), isTrue, reason: 'run from mobile/ in the monorepo');+ expect(+ core.existsSync(),+ isTrue,+ reason: 'run from mobile/ in the monorepo',+ );final cli = namesIn(core.readAsStringSync(),'ENCRYPTED_DOWN_TYPES = new Set<string>([','])',);expect(cli, isNotEmpty);- expect(encryptedDownTypes, cli);+ expect(+ encryptedDownTypes,+ containsAll(cli),+ reason:+ 'a type the machine requires and the phone sends in the clear '+ 'comes back E2EE_REQUIRED',+ );+ });++ /// ⚠️ **`ENCRYPTED_DOWN_TYPES` is NOT the machine's whole rule**, and reading+ /// it as though it were cost an afternoon: `git_project_info` is required by+ /// `encryptDownFrame` in `lib/e2ee/applicationFrames.ts`, which is that set+ /// OR several types named outright beside it. Sealing it looked wrong against+ /// the narrow list, the entry was taken back out, and the machine went on+ /// answering E2EE_REQUIRED.+ ///+ /// So the two halves are tested apart: everything the set names must be+ /// sealed (above), and anything sealed BEYOND it must be something the+ /// machine will actually unwrap (here). Sealing a type the CLI does not+ /// unwrap is the quieter fault of the two — the envelope is never opened, the+ /// payload reads back as undefined fields, and the caller waits out its+ /// timeout.+ test('seals nothing the CLI would refuse to unwrap', () {+ final frames = File('../cli/src/lib/e2ee/applicationFrames.ts');+ expect(+ frames.existsSync(),+ isTrue,+ reason: 'run from mobile/ in the monorepo',+ );+ final source = frames.readAsStringSync();+ final rule = source.substring(+ source.indexOf('encryptDownFrame'),+ source.indexOf('encryptRpcResult'),+ );+ final core = namesIn(+ File('../cli/src/lib/e2ee/core.ts').readAsStringSync(),+ 'ENCRYPTED_DOWN_TYPES = new Set<string>([',+ '])',+ );+ // The types the rule names outright, beside the set it starts from.+ final named = {+ for (final match in RegExp(r"'([a-z0-9_]+)'").allMatches(rule)) match[1]!,+ };+ expect(named, contains('git_project_info'));+ expect(encryptedDownTypes.difference(core.union(named)), isEmpty);});}diff --git a/mobile/test/phone_new_agent_opens_test.dart b/mobile/test/phone_new_agent_opens_test.dartindex 02874045b..13b08c9e3 100644--- a/mobile/test/phone_new_agent_opens_test.dart+++ b/mobile/test/phone_new_agent_opens_test.dart@@ -95,12 +95,16 @@ void main() {);await tester.pump();- // Recent is folded shut, so its entries are not on screen until it is opened.+ // PROJECT and ENGINE are folded shut — the page says what is chosen and+ // opens onto the choices. Recent is a second fold inside PROJECT.+ await tester.tap(find.text('Choose a folder'));+ await tester.pump();await tester.tap(find.text('Recent'));await tester.pump();await tester.tap(find.text('grid'));await tester.pump();- await tester.tap(find.text('Claude'));+ // Claude is the engine the form starts on, and the ENGINE row now shows+ // it rather than offering it — so there is nothing to tap.await tester.pump();await tester.tap(find.text('Create Harness'));// The create resolves on a microtask, then the route it pushes has to slide in — and only once