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
import '../core/harness_defaults.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'package:collection/collection.dart' show compareNatural;
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../core/home_dir.dart';
import '../core/codex_profiles.dart';
import '../core/launch_setup.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/first_task.dart';
import '../core/guest_folders.dart';
import '../core/models.dart';
import '../usage/models_menu_controller.dart';
import '../core/fuzzy_match.dart';
import '../core/git_worktree.dart';
import '../core/permission_modes.dart';
import '../core/project_folder.dart';
import '../core/repository_clone.dart';
import '../super_tabs/new_repository.dart';
import '../core/ssh_hosts.dart';
import '../core/test_run.dart';
import '../finder/finder_availability.dart';
import '../widgets/engine_identity.dart';
import '../widgets/resting_model_words.dart';
import 'app_state.dart';
import 'attached_task_delivery.dart';
import 'harness_placement.dart';
import 'harness_attachments.dart';
import 'harness_launch_integration.dart';
import 'lead_placement.dart';
import 'pane_arrangement.dart';
/// Whether New Harness opens as a line in the box, or as the full form.
///
/// The app, including Store Open/Try, uses the box with inline advanced options.
/// Legacy form tests leave this off; dock
/// journeys enable it explicitly.
bool newHarnessOpensInBox =
!kUnderTest || const bool.fromEnvironment('HARNESS_CURRENT_WORKSPACE');
/// A launch command with inherited arguments. Arrows select a launch argument;
/// a focused prompt edits one argument at a time. Enter
/// accepts a choice, Tab completes text, and Escape returns to the menu.
enum NewHarnessField {
launch,
task,
harness,
agent,
model,
machine,
branch,
projectMenu,
project,
projectName,
projectRepository,
mode,
profile,
}
/// What Project holds: a folder that exists, a project to make, a GitHub
/// repository to clone, or one to create on GitHub first (New Project).
@immutable
class NewHarnessProject {
/// A new project, named by the person or (null) after the agent and the time.
const NewHarnessProject.fresh([this.name])
: folder = null,
repository = null,
generated = null,
newRepository = null,
exact = false;
NewHarnessProject.generated(ProjectFolderRequest request)
: name = request.name,
generated = request,
folder = null,
repository = null,
newRepository = null,
exact = false;
const NewHarnessProject.folder(String this.folder, {this.exact = false})
: name = null,
repository = null,
generated = null,
newRepository = null;
const NewHarnessProject.clone(GitHubRepository this.repository)
: name = null,
folder = null,
generated = null,
newRepository = null,
exact = false;
/// New Project's New Repository (task #3374): created on GitHub at Start,
/// then cloned as [NewHarnessProject.clone] is.
const NewHarnessProject.newRepository(NewRepositoryAsk this.newRepository)
: name = null,
folder = null,
repository = null,
generated = null,
exact = false;
final String? name;
final String? folder;
final GitHubRepository? repository;
final ProjectFolderRequest? generated;
final NewRepositoryAsk? newRepository;
/// The person picked this very folder (browsed or typed): a worktree stays
/// itself instead of showing as its repository.
final bool exact;
bool get isNew => folder == null;
@override
bool operator ==(Object other) =>
other is NewHarnessProject &&
other.name == name &&
other.generated?.generatedAt == generated?.generatedAt &&
other.generated?.generatedLabel == generated?.generatedLabel &&
other.folder == folder &&
other.exact == exact &&
other.repository?.url == repository?.url &&
other.newRepository == newRepository;
@override
int get hashCode => Object.hash(
name,
folder,
exact,
repository?.url,
newRepository,
generated?.generatedAt,
generated?.generatedLabel,
);
}
/// 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,
}
@immutable
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;
/// A repository with nothing to branch from: `git init` and no commit yet, or
/// a folder inside one (a `git init` in the home folder makes ~/Downloads
/// one). As in Claude Code, work starts in the folder itself, with no Worktree
/// or Branch to choose, until the first commit gives Git something to branch.
bool hasNoCommits(GitProjectInfo info) => info.isGit && info.branches.isEmpty;
/// Git projects keep Worktree on, once there is a commit to start it from.
bool worktreeByDefault(GitProjectInfo info) =>
info.isGit && !hasNoCommits(info);
/// New work starts from the branch the project calls its default
/// (`origin/HEAD`), preferring the local copy; then main, for a project that
/// names none; then the branch it is on. octocat/Hello-World is on master, and
/// reading only main refused it until a branch was chosen by hand. Null asks.
/// With Worktree off, show the branch the folder is actually on.
String? defaultBranchRef(GitProjectInfo info, {required bool worktree}) {
if (!worktree) return currentBranchRef(info);
final remote = info.defaultRef;
for (final ref in [
if (remote != null) ...[
'refs/heads/${remote.split('/').skip(3).join('/')}',
remote,
],
'refs/heads/main',
'refs/remotes/origin/main',
]) {
if (info.branches.any((branch) => branch.ref == ref)) return ref;
}
return 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 == 'refs/heads/main' ||
base == 'refs/remotes/origin/main' ||
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.
ProjectFolderRequest? gitFolderRequest(
String folder,
GitProjectInfo info, {
required bool worktree,
required String? branchRef,
required String? branchName,
required String placeholder,
}) {
// Nothing to branch from: the folder is used as it is ([hasNoCommits]).
if (hasNoCommits(info)) return null;
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,
),
};
}
/// A creation buffer shared by the prompt and advanced options. It includes
/// the receipt of an unresolved request, so going back cannot start a duplicate.
@immutable
class NewHarnessDraft {
const NewHarnessDraft({
required this.machineId,
required this.engine,
this.harnessId,
this.model,
this.advancedOpen = false,
required this.project,
required this.task,
required this.permissionMode,
this.worktree,
this.worktreePreference,
this.branchRef,
this.branchName,
this.placeholder,
this.gitProject,
this.profile,
this.profileChosen = false,
this.attempt,
this.integration,
this.error,
this.dismissalWarningShown = false,
this.projectsByMachine = const {},
});
final String machineId, engine, task, permissionMode;
final String? harnessId;
final GridModel? model;
final bool advancedOpen;
final bool? worktree;
// The reviewed choice when recovery reuses an already prepared worktree.
final bool? worktreePreference;
/// The branch chosen in the launcher, and the name typed for a worktree's
/// branch; null leaves either to [defaultBranchRef] and [placeholder].
final String? branchRef, branchName, placeholder;
final GitProjectInfo? gitProject;
final NewHarnessProject project;
final LocalCodexProfile? profile;
final bool profileChosen;
final AgentCreationAttempt? attempt;
final HarnessLaunchIntegration? integration;
final String? error;
// The visible "Escape again" message must keep the same meaning if the
// unresolved prompt is dismissed and then restored.
final bool dismissalWarningShown;
final Map<String, NewHarnessProject> projectsByMachine;
ProjectFolderRequest? get projectFolderRequest {
final folder = project.folder;
final terminal = isTerminalEngine(engine);
final info = gitProject;
if (folder != null && !terminal && info != null && info.isGit) {
return gitFolderRequest(
folder,
info,
worktree: worktree ?? worktreeByDefault(info),
branchRef: branchRef,
branchName: branchName,
placeholder: placeholder ?? placeholderBranch(const []),
);
}
return worktree == true && folder != null && !terminal
? ProjectFolderRequest.worktree(folder, branchRef: branchRef)
: branchRef != null && folder != null && !terminal
? ProjectFolderRequest.branch(folder, branchRef!)
: folder != null || terminal
? null
: project.repository != null
? ProjectFolderRequest.remote(project.repository!)
: project.generated ??
ProjectFolderRequest.newProject(name: project.name);
}
}
@immutable
class NewHarnessOption {
const NewHarnessOption({
required this.id,
required this.title,
this.detail = '',
this.engine,
this.project,
this.profile,
this.model,
this.group,
this.machineId,
this.enabled = true,
this.synthetic = false,
this.risky = false,
this.why,
this.meta,
});
/// What the row says of itself at its end — a subscription's allowance left ("79% remaining"),
/// where the Models picker shows it too, rather than run on after the account in its detail.
final String? meta;
/// A row the box adds rather than finds — "New project", "Use this folder".
/// It is never a match, so it is in neither half of the `2 of 14`.
final bool synthetic;
/// A permission mode that disables the engine's safety checks.
final bool risky;
/// Why the row cannot be chosen, said when somebody tries.
final String? why;
/// An engine or harness id, a machine id, or a project token.
final String id;
final String title, detail;
/// Whose mark the row wears, on the agent field.
final String? engine;
/// What choosing the row sets, on the project field.
final NewHarnessProject? project;
/// A profile folder on [machineId], never on an implicitly different host.
final LocalCodexProfile? profile;
final GridModel? model;
final String? group;
/// A recent project chooses its machine and folder together.
final String? machineId;
final bool enabled;
}
enum NewHarnessOutcome { created, failed }
class NewHarnessController extends ChangeNotifier {
NewHarnessController(
this.app, {
required String machineId,
String? engine,
String? harnessId,
String? folder,
String? projectName,
bool autoProject = false,
DateTime Function()? now,
String? task,
NewHarnessDraft? draft,
this.swarmId,
this.split,
HarnessPlacement? placement,
this.offersStore = false,
String? home,
ModelsMenuController? modelUsage,
Random? random,
this.attachments,
HarnessLaunchIntegration? integration,
}) : _random = random ?? Random(),
integration = draft?.integration ?? integration,
placement =
placement ?? (split == null ? HarnessPlacement.currentTab : null),
_targetId = swarmId ?? app.activeSwarmId,
_usesNewTabPage = app.swarms.any(
(tab) => tab.id == (swarmId ?? app.activeSwarmId) && tab.isBlankNewTab,
),
_machineId = draft?.machineId ?? machineId,
_autoProject = autoProject || draft?.project.generated != null,
_initialAgentExplicit =
draft != null || engine != null || harnessId != null,
_restoringDraft = draft != null,
_now = now ?? DateTime.now,
_home = home ?? maybeHomeDir() {
final explicitSelection =
draft != null || engine != null || harnessId != null;
_rememberedAgent = !explicitSelection;
engine = draft?.engine ?? engine;
// A Finder is chosen as a harness is: by itself, or with its chat's agent.
_finder =
_allowedEngines == null &&
(isFinderEngine(draft?.harnessId ?? harnessId) ||
isFinderEngine(engine));
if (isFinderEngine(engine)) engine = null;
_harnessId = _finder
? null
: draft?.harnessId ??
harnessId ??
(isHarnessId(engine)
? engine
: explicitSelection
? null
: app.agentPreference.harness);
_engine = draft != null && engine != null && !isHarnessId(engine)
? engine
: harnessId != null && engine != null && !isHarnessId(engine)
? engine
: _initialEngine(isHarnessId(engine) ? null : engine);
if (_finder) _engine = _finderChat(_engine);
// A new Lead opened beside another pane inherits its agent, which may be
// one a Lead cannot run (OpenCode); it gives way as a guest's does.
if (_allowedEngines != null && !compatibleEngines.contains(_engine)) {
_engine = compatibleEngines.first;
}
_restorePermissionMode();
_model = _noAgentSetup ? null : draft?.model;
_modelUsage = modelUsage;
_ownsModelUsage = modelUsage == null;
_modelUsage?.addListener(_refresh);
advancedOpen = draft?.advancedOpen ?? false;
_project = projectName != null
? NewHarnessProject.fresh(projectName)
: folder != null
? NewHarnessProject.folder(folder)
: _autoProject
? _generatedProject()
: const NewHarnessProject.fresh();
this.task = this.integration?.initialTask ?? task ?? '';
_worktree = draft?.worktree;
_recoveredWorktreePreference = draft?.worktreePreference;
_branchRef = draft?.branchRef;
_branchName = draft?.branchName;
_placeholder = draft?.placeholder;
_gitProject = draft?.gitProject ?? const GitProjectInfo();
if (draft != null) {
_projectsByMachine.addAll(draft.projectsByMachine);
_project = draft.project;
this.task = draft.task;
_mode = draft.permissionMode;
_chosenModes[_engine] = _mode;
_profile = draft.profile;
_profileChosen = draft.profileChosen;
_attempt = draft.attempt;
error = draft.error;
_warnedAboutClosing = draft.dismissalWarningShown;
}
// A recovering request shows what it was sent with: Check status asks
// its machine, whatever machine this form was opened on.
if (this.integration case final request? when request.pending) {
_machineId = request.machineId ?? _machineId;
// Its person chose that machine when it was sent.
_leadPicked = request.machineId != null;
if (request.engine case final engine?) {
_engine = engine;
_harnessId = null;
}
if (request.folder case final folder?) {
_project = NewHarnessProject.folder(folder);
}
status = request.pendingNote;
}
if ((projectName != null || _autoProject) &&
!checking &&
_project.folder == null &&
_project.repository == null &&
(_project.name?.isEmpty ?? true)) {
_project = projectName != null
? NewHarnessProject.fresh(projectName)
: _generatedProject();
}
// Start at the missing project when there is no saved one. Any other
// unavailable value is explained by requiredChoice before launching.
field = needsProject && !checking
? NewHarnessField.projectMenu
: NewHarnessField.launch;
query = field == NewHarnessField.task ? this.task : '';
if (!takesTask && this.task.trim().isNotEmpty && !checking) {
error =
'$agentLabel cannot start on a first message, so '
'“${_short(this.task)}” will not be sent. Choose another agent to send it.';
}
app.addListener(_onApp);
_refresh();
unawaited(
app.agentPreference.load().then((_) {
if (_disposed || locked) return;
if (!_selectionTouched && !explicitSelection) {
_harnessId = app.agentPreference.harness;
_engine = _initialEngine(null);
if (_project.generated != null) _project = _generatedProject();
} else if (!_selectionTouched && draft == null && isHarnessId(engine)) {
_engine = _initialEngine(null);
}
_restorePermissionMode();
if (_desktopChoices) _applySuccessfulLaunch();
_refresh();
}),
);
unawaited(
app.projectHistory.load().then((_) {
if (!_disposed && !locked) _refresh();
}),
);
// What the machine has is asked when the box opens, as the form does: an
// engine installed in a terminal a minute ago is otherwise still "missing".
unawaited(
app
.probeEngines(_machineId, force: true)
.then((_) => _adoptAccountAgent()),
);
final initialMachine = _machineId;
// A guest is listed no harnesses or folders there (asGuest): nothing to ask.
if (!asGuest) {
unawaited(
app.probeDsh(initialMachine, force: true).then((_) {
// Store and remembered choices can open before the machine's catalog
// arrives. Resolve their preferred engine once compatibility is known.
// An inherited session, draft, or explicit user choice keeps its engine.
if (_disposed ||
locked ||
_selectionTouched ||
draft != null ||
(engine != null && !isHarnessId(engine)) ||
_machineId != initialMachine ||
_harnessId == null) {
return;
}
_engine = _initialEngine(null);
_restorePermissionMode();
_refresh();
}),
);
unawaited(_ensureHome(_machineId));
unawaited(_refreshGeneratedProject());
} else {
_startAsGuest();
}
}
final AppNotifier app;
final String? swarmId;
final PaneSplitRequest? split;
final HarnessPlacement? placement;
final String _targetId;
final bool _usesNewTabPage;
HarnessPlacement? get effectivePlacement =>
placement == HarnessPlacement.newTab && _usesNewTabPage
? HarnessPlacement.currentTab
: placement;
final bool _autoProject;
final bool _initialAgentExplicit;
final bool _restoringDraft;
final DateTime Function() _now;
final String? _home;
late String _engine;
String? _chosenHarness;
/// A destination that allows only some agents (integration.engines, a new
/// Lead) starts the agent itself, never a Store harness, as a guest does.
String? get _harnessId => _allowedEngines == null ? _chosenHarness : null;
set _harnessId(String? id) => _chosenHarness = id;
List<String>? get _allowedEngines => integration?.engines;
/// What the Harness row answers: a Store harness, the Finder, or null for
/// an agent on its own. Both of the first two run on [engine].
String? get harnessId => _finder ? kFinderEngine : _harnessId;
/// The harness this form is installing, or failed to install, on its way to
/// starting — so the form can show the machine's own narration of it.
String? _installing;
/// The install that start is waiting on, while it runs and after it fails.
/// Cleared by choosing another harness or machine, or by starting again.
DshInstallRun? get installRun =>
_installing == null ? null : _machine?.dsh.runs[_installing];
/// Whether [id] can be offered on the selected machine: anything, until its
/// catalog has answered; afterwards only a launchable package it lists. A
/// harness removed from the Store stays in the recents file, and must not
/// be offered — or opened on — as though it could still start.
bool _offered(String id) {
final machine = _machine;
if (machine == null || !machine.dsh.loaded) return true;
final entry = harnessForOperation(machine.dsh.entries, id);
return entry != null && !entry.isViewerPackage;
}
String get harnessLabel => harnessId == null ? 'Code' : labelOf(harnessId!);
bool advancedOpen = false;
bool _selectionTouched = false;
bool _rememberedAgent = false;
void toggleAdvanced() {
if (locked) return;
advancedOpen = !advancedOpen;
if (!advancedOpen &&
[
NewHarnessField.branch,
NewHarnessField.mode,
NewHarnessField.profile,
].contains(field)) {
field = NewHarnessField.launch;
query = '';
}
_refresh();
}
DshEntry? get selectedHarness => _harnessId == null
? null
: harnessForOperation(
_machine?.dsh.entries ?? const <DshEntry>[],
_harnessId!,
);
/// A machine shared with this account: this person is a guest there, with a space of
/// their own (docs/plans/2026-10-19-guest-machine-sharing-plan.md). Its daemon starts
/// Claude Code or Codex in that space, on its owner's plans, and lists a guest no
/// folders, harnesses, models or profiles, so none are asked for or offered.
bool get asGuest => _machine?.machine.isSharedMachine == true;
/// Where a guest may start there (asGuest): its workspace and the folders the owner shares, as the
/// machine last said; null until it has.
GuestFolders? _guestFolders;
/// A guest starts in its workspace until it picks a folder the owner shares.
void _startAsGuest() {
_project = const NewHarnessProject.fresh();
// An agent a guest cannot start there (OpenCode, a Store harness) gives way to Claude Code.
if (_harnessId != null || _finder || !compatibleEngines.contains(_engine)) {
_harnessId = null;
_finder = false;
_engine = compatibleEngines.first;
_restorePermissionMode();
}
_guestFolders = null;
final id = _machineId;
unawaited(
app.guestFolders(id).then((folders) {
if (_disposed || id != _machineId) return;
_guestFolders = folders;
_refresh();
}),
);
}
/// A guest's Project: its workspace, or one of the folders the owner shares.
List<NewHarnessOption> _guestPlaces() => [
NewHarnessOption(
id: guestWorkspaceId,
title: 'My workspace',
detail: 'Your own folder on $machineLabel',
project: const NewHarnessProject.fresh(),
),
for (final folder in _guestFolders?.folders ?? const <GuestFolder>[])
NewHarnessOption(
id: '$guestFolderId${folder.path}',
title: p.basename(folder.path),
detail:
'${folder.path} · ${folder.write ? 'you can edit it' : 'read only'}',
project: NewHarnessProject.folder(folder.path, exact: true),
),
];
List<String> get compatibleEngines => asGuest
? const ['claude', 'codex']
: _allowedEngines != null
? _allowedEngines!
// A Finder's chat runs beside it on this computer: an agent, never
// the cloud or a bare shell.
: _finder
? [for (final engine in allEngines) engine.id]
: _harnessId == null
? [
for (final engine in allEngines) engine.id,
for (final agent in cloudAgents) agent.id,
kTerminalEngine,
]
: selectedHarness?.supportedEngines ??
[knownHarnessBase[canonicalHarnessId(_harnessId!)] ?? 'claude'];
/// The agent this person chose before, as stored, for the current harness;
/// null when nothing is remembered.
String? get _rememberedChoice => _desktopChoices
? app.agentPreference.successfulLaunch?.engine
: app.agentPreference.engineFor(_harnessId) ??
(_harnessId == null || _harnessId == app.agentPreference.harness
? app.agentPreference.value
: null);
/// Whether [_engine] is this person's own earlier choice rather than the
/// product default. Only a remembered agent that is gone asks for a
/// replacement: the default is installed in its pane on Create, and asking a
/// brand-new user to replace it stopped every first harness on a fresh Mac
/// (2026-10-08, "OpenCode is unavailable. Choose an agent."). Read from the
/// stored choice where it is used, so it always describes [_engine].
bool get _engineRemembered =>
!_initialAgentExplicit && _rememberedChoice == _engine;
String _initialEngine(String? requested) {
final allowed = compatibleEngines;
final remembered = requested ?? _rememberedChoice;
if (remembered != null &&
(allowed.contains(remembered) ||
_allowedEngines == null &&
(requested != null ||
!_desktopChoices ||
_harnessId ==
app.agentPreference.successfulLaunch?.harnessId))) {
return remembered;
}
// Nothing remembered: the agent this person already uses, when the
// machine says it is installed and signed in, before the product default.
// Everyone opened on OpenCode's free model, including people who
// installed Harness to run the Claude Code or Codex they pay for.
if (_harnessId == null) {
final account = _accountAgent();
if (account != null && allowed.contains(account)) return account;
}
final preferred = allowed.contains(defaultHarnessEngine)
? defaultHarnessEngine
: selectedHarness?.engine;
if (preferred != null && allowed.contains(preferred)) return preferred;
return allowed.first;
}
/// Claude Code or Codex, installed and signed in on the chosen machine; the
/// one used most recently when both are. Null until the machine has said.
String? _accountAgent() {
final engines = _machine?.engines;
if (engines == null || !engines.loaded) return null;
String? best;
var bestAt = -1;
for (final id in const ['claude', 'codex']) {
final engine = engines[id];
if (engine == null || !engine.installed || engine.signedIn != true) {
continue;
}
final at = engine.lastUsedAt ?? 0;
if (best == null || at > bestAt) {
best = id;
bestAt = at;
}
}
return best;
}
/// The machine's engines answered after the box opened. While the person
/// has not chosen and nothing was remembered, open on the agent they use.
void _adoptAccountAgent() {
if (_disposed ||
locked ||
_selectionTouched ||
_initialAgentExplicit ||
_engineRemembered ||
_harnessId != null) {
return;
}
final next = _initialEngine(null);
if (next == _engine) return;
_engine = next;
_restorePermissionMode();
if (_project.generated != null) {
_project = _generatedProject();
unawaited(_refreshGeneratedProject());
}
_refresh();
}
String _machineId;
late NewHarnessProject _project;
final _projectsByMachine = <String, NewHarnessProject>{};
final _homes = <String, String>{};
final _homeRequests = <String, Future<String?>>{};
int _machineRevision = 0;
String get engine => _engine;
String get machineId => _machineId;
NewHarnessProject get project => _project;
final Random _random;
bool? _worktree;
String? _branchRef, _branchName, _placeholder;
GitProjectInfo _gitProject = const GitProjectInfo();
(String, String?, bool)? _gitKey;
Future<void>? _gitFuture;
int _gitRevision = 0;
bool checkingGit = false;
bool refreshingBranches = false;
String? branchRefreshError;
DateTime? _branchesCheckedAt;
bool get isGitProject => _gitProject.isGit && !_noGitSetup && !isCloud;
/// A Git project with no commit yet starts in its folder ([hasNoCommits]).
bool get noCommitsYet => isGitProject && hasNoCommits(_gitProject);
/// Whether Branch is offered: a Git project with something to branch from.
bool get choosesBranch => isGitProject && !noCommitsYet;
/// A worktree the person picked: the harness works in it, on its branch.
bool get inWorktree => _project.exact && _gitProject.mainFolder != null;
bool get canUseWorktree => choosesBranch && !checkingGit && !inWorktree;
bool get worktree =>
choosesBranch &&
!inWorktree &&
// A Swarm's Product Manager never edits the person's checkout.
(placesLead ||
(_worktree ??
(_desktopChoices
? app.agentPreference.successfulWorktree ?? true
: app.projectHistory.worktreeFor(
_machineId,
_project.folder ?? '',
) ??
worktreeByDefault(_gitProject))));
bool? _recoveredWorktreePreference;
/// The Worktree setting a successful start saves for the next New Harness,
/// or null to leave it: a Swarm's Product Manager always gets a worktree,
/// which is not the person's choice.
bool? get worktreeToRemember => placesLead
? null
: _recoveredWorktreePreference ??
(choosesBranch && !inWorktree ? worktree : null);
/// Fresh desktop work starts on the default branch, with or without a worktree. A retry
/// must instead keep the branch of the folder its first attempt prepared.
bool get _startsOnDefault =>
_desktopChoices && _attempt?.preparedFolder == null && !inWorktree;
String? get branchRef {
if (_branchRef != null) return _branchRef;
if (_startsOnDefault) {
final start = defaultBranchRef(_gitProject, worktree: true);
return !worktree && start?.startsWith('refs/remotes/') == true
? null
: start;
}
return defaultBranchRef(_gitProject, worktree: worktree);
}
String? get gitError => _gitProject.error;
String get branchLabel =>
_refName(branchRef) ??
(worktree || _startsOnDefault
? 'default · unavailable'
: 'Detached HEAD');
String? _refName(String? ref) =>
_gitProject.branches
.where((branch) => branch.ref == ref)
.firstOrNull
?.name ??
ref?.replaceFirst(RegExp(r'^refs/(heads|remotes)/'), '');
/// The branch a new worktree is on until its session names it: two words
/// the daemon replaces with the session's name.
String get placeholder => _placeholder ??= placeholderBranch([
for (final branch in _gitProject.branches) branch.name,
], random: _random);
WorktreePlan? get worktreePlan => worktree
? planWorktree(
_gitProject,
base: branchRef,
name: _branchName,
placeholder: placeholder,
)
: null;
/// A branch with a worktree of its own, other than the project folder's.
String? _worktreeOf(String? ref) => _gitProject.branches
.where(
(branch) =>
branch.ref == ref &&
branch.worktree != null &&
branch.name != _gitProject.branch,
)
.firstOrNull
?.worktree;
/// With Worktree off, the new branch Start makes for the folder.
String? get _branchHere =>
worktree ? null : newBranchHere(_gitProject, _branchName);
/// The Branch row: what was picked, or the new branch typed there.
String get branchRowLabel {
// Its worktree is where the harness starts, not the project folder.
if (opensWorktree) return '$branchLabel · in its worktree';
final plan = worktreePlan;
if (plan != null &&
plan.kind == WorktreeStart.newBranch &&
_branchName != null &&
plan.branch == _branchName) {
return '${plan.branch} · new from ${_refName(plan.base) ?? 'HEAD'}';
}
final name = _branchHere;
return name == null
? branchLabel
: '$name · new from ${_refName(currentBranchRef(_gitProject)) ?? 'HEAD'}';
}
/// A new worktree names its base instead of implying it opens that branch.
String get compactBranchLabel =>
worktree &&
worktreePlan?.kind == WorktreeStart.newBranch &&
_branchName == null
? 'From $branchLabel'
: branchRowLabel.split(' · ').first;
String get branchTooltip {
final plan = worktreePlan;
if (worktree && plan?.kind == WorktreeStart.newBranch) {
return 'New branch from ${_refName(plan!.base) ?? 'HEAD'} in a separate folder';
}
if (opensWorktree) return 'Open $branchLabel in its existing worktree';
if (worktree) return 'Open $branchLabel in a separate folder';
return 'Use $branchRowLabel in the project folder';
}
/// Start goes into a worktree that already exists.
bool get opensWorktree => worktree
? worktreePlan?.kind == WorktreeStart.openWorktree
: _branchHere == null && _worktreeOf(branchRef) != null;
void toggleWorktree() {
if (locked || !canUseWorktree || placesLead) return;
_worktree = !worktree;
_recoveredWorktreePreference = null;
if (_project.folder case final folder? when !_desktopChoices) {
unawaited(
app.projectHistory.selectWorktree(_machineId, folder, _worktree!),
);
}
error = null;
_refresh();
}
void retryGitProject() {
if (locked || checkingGit || _project.folder == null || _noGitSetup) {
return;
}
error = null;
_gitFuture = _readGitProject(_gitKey!);
notifyListeners();
}
/// Cached matches stay usable while Git discovers branches pushed elsewhere.
/// Typing only filters; entering Branch refreshes at most once per ten seconds.
Future<void> refreshBranches({bool force = true}) async {
if (_disposed ||
locked ||
checkingGit ||
refreshingBranches ||
!choosesBranch ||
_gitKey == null) {
return;
}
if (!force &&
_branchesCheckedAt != null &&
_now().difference(_branchesCheckedAt!) < const Duration(seconds: 10)) {
return;
}
_branchesCheckedAt = _now();
await _readGitProject(_gitKey!, refresh: true);
}
bool get canRefreshChoices => switch (field) {
NewHarnessField.branch => choosesBranch,
NewHarnessField.project ||
NewHarnessField.projectName => _visibleFolder != null,
_ => false,
};
bool get refreshingChoices =>
field == NewHarnessField.branch ? refreshingBranches : listing;
String? get choicesStatus => field == NewHarnessField.branch
? refreshingBranches
? 'Checking remote branches…'
: branchRefreshError
: canRefreshChoices
? listing
? 'Checking folders…'
: folderRefreshError
: null;
void refreshChoices() {
if (locked || !canRefreshChoices) return;
if (field == NewHarnessField.branch) {
unawaited(refreshBranches());
} else if (_visibleFolder case final folder?) {
_requestListing(folder);
notifyListeners();
}
}
void _syncGitProject() {
final key = (_machineId, _project.folder, _noGitSetup);
if (_gitKey == key) return;
if (_gitKey != null) {
_worktree = null;
_recoveredWorktreePreference = null;
_branchRef = null;
_branchName = null;
_placeholder = null;
_gitProject = const GitProjectInfo();
}
_gitKey = key;
_gitRevision++;
checkingGit = false;
refreshingBranches = false;
branchRefreshError = null;
_branchesCheckedAt = null;
_gitFuture = null;
// A guest's harness starts in its own space: no folder of theirs to read Git in (asGuest).
if (key.$2 != null && !key.$3 && !checking && !asGuest) {
_gitFuture = _readGitProject(key);
}
}
Future<void> _readGitProject(
(String, String?, bool) key, {
bool refresh = false,
}) async {
if (refresh) {
refreshingBranches = true;
branchRefreshError = null;
_refresh();
} else {
checkingGit = true;
}
final revision = ++_gitRevision;
GitProjectInfo info;
try {
final data = await app.readGitProject(key.$1, key.$2!, refresh: refresh);
if (_disposed || _gitKey != key || revision != _gitRevision) return;
info = GitProjectInfo.fromJson(data);
if (refresh && data['refreshed'] != true) {
branchRefreshError =
'Couldn’t refresh remote branches. Showing saved branches.';
}
} catch (_) {
info = const GitProjectInfo(error: 'UNAVAILABLE');
}
if (_disposed || _gitKey != key || revision != _gitRevision) return;
checkingGit = false;
refreshingBranches = false;
if (refresh && info.error != null) {
branchRefreshError =
'Couldn’t refresh remote branches. Showing saved branches.';
_refresh();
return;
}
// A worktree is a temporary folder, so the launcher shows its repository.
// With Worktree off its branch stays chosen and Start reopens that
// worktree; otherwise new work starts from the repository's own branch.
// One the person picked stays itself ([inWorktree]).
if (info.mainFolder case final main?
when _project.folder == key.$2 && !_project.exact) {
if (!_startsOnDefault &&
_worktree == false &&
_branchRef == null &&
info.branch != null) {
_branchRef = 'refs/heads/${info.branch}';
}
_project = NewHarnessProject.folder(main);
_gitKey = (key.$1, main, key.$3);
info = GitProjectInfo(
isGit: true,
branch: info.mainBranch,
branches: info.branches,
defaultRef: info.defaultRef,
);
}
_gitProject = info;
// A name made up before the branches were known may already be taken.
if (_placeholder != null &&
info.branches.any((branch) => branch.name == _placeholder)) {
_placeholder = null;
}
_refresh();
if (!refresh && field == NewHarnessField.branch) {
unawaited(refreshBranches(force: false));
}
}
GridModel? _model;
bool _modelTouched = false;
GridModel? get model => _model;
GridModels? _modelCatalog;
ModelsMenuController? _modelUsage;
bool _ownsModelUsage = true;
bool _loadingModels = false;
int _modelRequest = 0;
String get subscriptionLabel => switch (_engine) {
'codex' => 'OpenAI',
'claude' => 'Anthropic',
'opencode' => defaultHarnessModelLabel,
_ => agentLabel,
};
String get modelLabel => _model == null
? subscriptionLabel
: [_model!.id, if (_model!.node.isNotEmpty) _model!.node].join(' · ');
static String _modelId(GridModel model) =>
'model:${jsonEncode([model.grid, model.id])}';
bool _modelAvailable(GridModel model) =>
!_noAgentSetup &&
_modelCatalog?.supportsModelLaunch == true &&
_modelCatalog!.reachable &&
_modelCatalog!.canRunLocally(_engine) &&
_modelCatalog!.sections.any(
(section) =>
section.name == model.grid &&
section.models.any((candidate) => candidate.id == model.id),
);
String? get modelNotice {
if (_loadingModels) return 'Loading models…';
final catalog = _modelCatalog;
if (catalog == null) return null;
if (!catalog.reachable) {
return 'Could not load models from $machineLabel. Refresh to retry.';
}
if (!catalog.supportsModelLaunch) {
return 'Update Harness CLI on $machineLabel to choose a model before starting.';
}
if (!catalog.canRunLocally(_engine)) {
return '$agentLabel uses its own login.';
}
if (_model != null && !_modelAvailable(_model!)) {
return 'The selected model is unavailable. Choose another model or your subscription.';
}
if (catalog.sections.every((section) => section.models.isEmpty)) {
return 'No models are running on your machines. Open Your models to start one.';
}
return null;
}
Future<void> refreshModels() async {
// A guest's harness runs on its owner's plans: no grid or saved API to pick.
if (_disposed || asGuest) return;
final request = ++_modelRequest;
final machine = _machineId;
_loadingModels = true;
if (_modelUsage == null) {
// The app's shared readings, the same the Models menu and pane pickers show. Owned by the
// app, so this form never disposes it.
_modelUsage = app.modelsMenu;
_ownsModelUsage = false;
_modelUsage!.addListener(_refresh);
}
// Native credential reads stay out of fixture tests, as in the session picker.
if (!kUnderTest) unawaited(_modelUsage!.refresh());
_refresh();
final answer = await app.refreshGridModels(machine);
if (_disposed || request != _modelRequest || machine != _machineId) return;
_modelCatalog = answer;
_loadingModels = false;
_refresh();
}
List<NewHarnessOption> _modelOptions() {
final catalog = _modelCatalog;
final subscription = _profile == null
? _modelUsage?.subscriptionFor(
_engine,
local: _machine?.isLocalMachine == true,
machineName: machineLabel,
)
: null;
final groups = <NewHarnessOption>[
..._ranked([
NewHarnessOption(
id: defaultModelId,
title: subscriptionLabel,
detail: '${_profile?.label ?? 'Default account'} on $machineLabel',
meta: switch (subscription?['status']) {
final String status => status,
_ => null,
},
group: 'Subscription',
engine: _engine,
machineId: _machineId,
enabled: _leadModelRefusal(null) == null,
why: _leadModelRefusal(null),
),
]),
if (catalog?.supportsModelLaunch == true &&
catalog!.canRunLocally(_engine))
for (final section in catalog.sections)
..._ranked([
for (final model in section.models)
NewHarnessOption(
id: _modelId(
GridModel(id: model.id, node: model.node, grid: section.name),
),
title: model.id,
// Every read now asks for row state, so the daemon no longer folds "seems
// offline" into the node — this row puts back what an older build showed.
detail: switch (model.unavailable) {
final offline? => offlineNodeLabel(offline.machine),
null => model.node,
},
// The Models picker's names for the same two lists. Its machine on the row's second
// line tells two grids' copies of a model apart, as it does there.
group: section.own ? 'Your models' : 'Shared with you',
model: GridModel(
id: model.id,
node: model.node,
grid: section.name,
),
machineId: _machineId,
enabled: _leadModelRefusal(model.id, grid: true) == null,
why: _leadModelRefusal(model.id, grid: true),
),
]),
NewHarnessOption(
id: refreshModelsId,
title: _loadingModels ? 'Loading models…' : 'Refresh models',
synthetic: true,
enabled: !_loadingModels,
),
const NewHarnessOption(
id: manageModelsId,
title: 'Your models…',
synthetic: true,
),
];
total =
1 +
(catalog?.supportsModelLaunch == true && catalog!.canRunLocally(_engine)
? catalog.sections.fold<int>(
0,
(count, section) => count + section.models.length,
)
: 0);
return groups;
}
LocalCodexProfile? _profile;
bool _profileChosen = false;
String? get profileLabel =>
_base == 'codex' && (_profileChosen || _profile != null)
? _profile?.label ?? (_desktopChoices ? 'Default account' : 'Default')
: null;
NewHarnessDraft get draft => NewHarnessDraft(
machineId: _machineId,
engine: _engine,
harnessId: harnessId,
model: _model,
advancedOpen: advancedOpen,
project: _project,
task: task,
permissionMode: _mode,
worktree: isGitProject ? worktree : _worktree,
worktreePreference: _recoveredWorktreePreference,
branchRef: _branchRef,
branchName: _branchName,
placeholder: isGitProject ? placeholder : _placeholder,
gitProject: _gitProject,
profile: _profile,
profileChosen: _profileChosen,
attempt: _attempt,
// A discarded request's launch is spent; the next form gets a fresh one.
integration: _discarded ? null : integration,
error: error,
dismissalWarningShown: _warnedAboutClosing,
projectsByMachine: Map.unmodifiable({
..._projectsByMachine,
_machineId: _project,
}),
);
/// The same preparation intent is used by the prompt and advanced options.
ProjectFolderRequest? get projectFolderRequest =>
isGitProject && _project.folder != null
? gitFolderRequest(
_project.folder!,
_gitProject,
worktree: worktree,
branchRef: branchRef,
branchName: _branchName,
placeholder: placeholder,
)
: _project.folder != null || _noAgentSetup
? null
: _project.repository != null
? ProjectFolderRequest.remote(_project.repository!)
: _project.generated ??
ProjectFolderRequest.newProject(name: _project.name);
NewHarnessField field = NewHarnessField.agent;
final bool offersStore;
/// Files for the harness's prompt, when the host lets New Harness attach
/// them (the browser). Null leaves the box as desktop has it.
final HarnessAttachments? attachments;
String query = '';
/// The harness's first message, sent exactly as written as it starts. Empty
/// starts it with nothing sent. Kept while the other answers are changed.
String task = '';
/// The desktop composer edits the first message independently of whichever
/// configuration chooser is open. It never repurposes that chooser's query.
void setTask(String value) {
if (locked || task == value) return;
task = value;
error = taskTooLong
? 'A first message can be $kFirstTaskMaxLength characters; '
'this is ${value.trim().length}.'
: null;
// The desktop composer is where almost every first task is typed. Without
// this its harnesses kept the clock name (`opencode-2026-10-08-13-24`,
// "Untitled Pane") unless something else happened to rebuild the project.
_followTask(debounce: true);
notifyListeners();
}
Timer? _projectRefresh;
/// A suggested project follows the task it will be named after; a name the
/// person typed is theirs and stays. Typed in the composer, the check for a
/// taken folder name (a directory listing, or a request to a remote machine)
/// waits for a pause rather than running on every keystroke; Start reserves
/// the folder itself either way.
void _followTask({bool debounce = false}) {
if (_project.generated case final suggested?) {
final next = _generatedProject();
if (next.generated?.generatedTask != suggested.generatedTask) {
_project = next;
_projectRefresh?.cancel();
if (debounce) {
_projectRefresh = Timer(
const Duration(milliseconds: 300),
() => unawaited(_refreshGeneratedProject()),
);
} else {
unawaited(_refreshGeneratedProject());
}
}
}
}
/// The permission mode picked, by id; an engine without it uses its default.
String _mode = kDefaultPermissionMode;
final _chosenModes = <String, String>{};
String _permissionFor(String engine) =>
_chosenModes[engine] ??
(_desktopChoices
? app.agentPreference.successfulLaunch?.engine == engine
? app.agentPreference.successfulLaunch?.permissionMode
: null
: app.agentPreference.permissionModeFor(_baseOf(engine))) ??
kDefaultPermissionMode;
void _restorePermissionMode() => _mode = _permissionFor(_engine);
/// The engine a choice launches: a store harness runs ON one of them.
String _baseOf(String engine) => isHarnessId(engine)
? _machine?.dsh[engine]?.engine ??
knownHarnessBase[canonicalHarnessId(engine)] ??
'claude'
: engine;
String get _base => _engine;
// Browsing previews an engine without changing the launch draft. Keep that
// engine while its settings are open in a child picker.
String? _agentPreview;
String get _settingsEngine => _agentPreview ?? _engine;
LocalCodexProfile? get _settingsProfile =>
_settingsEngine == _engine ? _profile : null;
// A Product Manager the Swarm starts on another machine starts there with
// its owner's own permission settings (task #4215): no choice to offer.
List<PermissionMode> get _settingsModes =>
leadThroughSwarm ? const [] : permissionModesOf(_baseOf(_settingsEngine));
String get _settingsMode =>
_settingsModes.any((mode) => mode.id == _permissionFor(_settingsEngine))
? _permissionFor(_settingsEngine)
: kDefaultPermissionMode;
bool get takesTask => !bringsBuddy && (isCloud || takesFirstTask(_base));
/// Join's Buddy, which the Swarm starts (task #4196).
bool get bringsBuddy => integration?.startBuddy != null;
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
List<PermissionMode> get _modes =>
_noAgentSetup || isCloud || leadThroughSwarm
? const []
: permissionModesOf(_base);
bool get hasModes => _modes.isNotEmpty;
String get mode =>
_modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;
String get modeLabel =>
_modes.where((m) => m.id == mode).firstOrNull?.label ?? mode;
// A guest's Codex runs on its owner's subscription, through the relay: no CODEX_HOME of its own to pick (asGuest).
bool get usesProfile => !asGuest && _base == 'codex' && _model == null;
bool get hasProfile => !asGuest && _baseOf(_settingsEngine) == 'codex';
bool get supportsProfiles =>
hasProfile && _machine?.engines['codex']?.supportsCodexHome == true;
String? get profileHelp => supportsProfiles
? null
: _machine?.engines.loaded == true
? 'Update Harness CLI on $machineLabel to choose a Codex profile.'
: 'Checking Codex profile support on $machineLabel…';
/// Settings are offered separately so browsing never inserts list rows.
List<NewHarnessOption> agentSettingsFor(String engine) {
final modes = leadThroughSwarm
? const <PermissionMode>[]
: permissionModesOf(_baseOf(engine));
final mode =
modes.where((mode) => mode.id == _permissionFor(engine)).firstOrNull ??
modes.where((mode) => mode.id == kDefaultPermissionMode).firstOrNull;
return [
if (mode != null)
NewHarnessOption(
id: permissionsId,
title: 'Permissions',
detail: mode.label,
synthetic: true,
),
if (_baseOf(engine) == 'codex')
NewHarnessOption(
id: profileId,
title: 'Codex Profile',
detail: engine == _engine ? profileLabel ?? 'Default' : 'Default',
synthetic: true,
),
];
}
void openAgentSetting(String engine, String setting) {
if (locked ||
field != NewHarnessField.agent ||
!options.any((row) => row.engine == engine) ||
!agentSettingsFor(engine).any((row) => row.id == setting)) {
return;
}
_agentPreview = engine;
focusField(
setting == profileId ? NewHarnessField.profile : NewHarnessField.mode,
previewAgent: true,
);
}
void openLaunchSetting(NewHarnessField setting) {
if (locked) return;
_agentPreview = null;
focusField(setting);
}
/// The arguments exposed by the launch menu. Machine sets the context;
/// permissions and profiles belong to the selected agent's picker.
List<NewHarnessField> get fields => [
NewHarnessField.harness,
NewHarnessField.agent,
if (!_noAgentSetup && !asGuest) NewHarnessField.model,
NewHarnessField.machine,
// A guest picks only among the folders the owner shares, when there are any.
if (!asGuest || (_guestFolders?.folders.isNotEmpty ?? false))
NewHarnessField.projectMenu,
if (advancedOpen) ...[
if (choosesBranch && !asGuest) NewHarnessField.branch,
if (hasModes) NewHarnessField.mode,
if (usesProfile) NewHarnessField.profile,
],
];
bool _supportsField(NewHarnessField value) =>
fields.contains(value) ||
value == NewHarnessField.launch ||
(value == NewHarnessField.task && takesTask) ||
value == NewHarnessField.project ||
value == NewHarnessField.projectName ||
value == NewHarnessField.projectRepository ||
value == NewHarnessField.machine ||
(value == NewHarnessField.branch && choosesBranch) ||
(value == NewHarnessField.mode && _settingsModes.isNotEmpty) ||
(value == NewHarnessField.profile && hasProfile);
int cursor = 0;
List<NewHarnessOption> options = const [];
/// How many things the field has before what was typed narrowed them, and
/// how many are left: the `2 of 14` beside the input. Rows the box adds
/// itself are in neither number — "1 of 0" was the count lying.
int total = 0;
int matchCount = 0;
/// A folder's listing has been asked for and has not come back: the list is
/// not empty, it is not here yet, and the two must not read the same.
bool get listing => _visibleFolder != null && _listing == _visibleFolder;
bool busy = false;
String? status;
String? error;
bool _disposed = false;
/// Folder listings for path completion, by the folder that was listed.
final _listings = <String, List<String>>{};
final _loadingFolders = <String>{};
String? _visibleFolder, folderRefreshError;
String? _listing;
MachineState? get _machine => app.stateOf(_machineId);
bool get isTerminal => isTerminalEngine(_engine);
/// A Finder: the folder to browse, with a chat on [engine] beside it.
bool _finder = false;
bool get isFinder => _finder;
/// The plain shell: no model or permission mode to set up.
bool get _noAgentSetup => isTerminal;
/// No branch or worktree: the plain shell, and a Finder, whose chat works
/// in exactly the folder the Finder shows.
bool get _noGitSetup => isTerminal || isFinder;
/// A cloud agent (Fo, Devin Cloud, Cursor Cloud): it runs on its maker's
/// servers, so it takes no folder, model, approvals or branch here — a coding
/// one takes a GitHub repository, and Devin Cloud an ACU limit.
bool get isCloud => _harnessId == null && isCloudAgentId(_engine);
/// New Project in a Swarm: the Swarm places the Product Manager on one of
/// [HarnessLaunchIntegration.leadMachines], and the form asks only the
/// task, repo and visibility.
bool get placesLead => integration?.leadMachines != null;
/// The machine the Swarm starts the Product Manager on, rather than this
/// Desktop: a teammate's Team account, or a machine of the person's this
/// Desktop is not connected to. The repo stays the one chosen on
/// [machineId]; that machine clones it. Null when this Desktop starts it on
/// [machineId].
String? _swarmLeadMachine;
String? get leadSwarmMachine => _swarmLeadMachine;
/// The person chose the Product Manager's machine: none is chosen for them,
/// since only they know which one stays on (Ken, 10-29).
bool _leadPicked = false;
bool get leadPicked => _leadPicked;
/// The machine the Product Manager starts on, as the Swarm lists it; null
/// until the person chooses one.
LeadMachine? get leadMachine => !_leadPicked
? null
: integration?.leadMachines
?.where((m) => m.id == (_swarmLeadMachine ?? _machineId))
.firstOrNull;
bool _paused(List<LeadMachine> machines) =>
machines.isNotEmpty &&
machines.every((m) => m.unavailable == kLeadSwarmPaused);
/// No machine could start the Product Manager now: each is paused, offline,
/// full, another person's that cannot take it, or runs no engine it can
/// start with. Its list says why for each.
bool get leadNone {
final machines = integration?.leadMachines;
return machines != null &&
!_paused(machines) &&
!machines.any((m) => m.startable);
}
/// The Swarm starts the Product Manager, on [leadSwarmMachine]; this
/// Desktop does not.
bool get leadThroughSwarm => placesLead && _swarmLeadMachine != null;
/// The address the Swarm clones the chosen repo from, or null when it is
/// not known.
String? get leadRepositoryUrl {
// Not made yet: its address once it is, never a remote to keep.
if (_project.newRepository case final ask?) {
return 'https://github.com/${ask.slug}';
}
return switch (_remoteOf(_machineId, _project)) {
final String remote when remote.startsWith('github.com/') =>
'https://$remote',
final remote => remote,
};
}
String? get _leadRepositoryName =>
_project.repository?.name ??
_project.newRepository?.name ??
switch (_project.folder) {
final String folder => _pathsFor(_machineId, folder).basename(folder),
null => null,
};
/// The Product Manager line: where it starts, its engine and model.
String get leadLine {
final target = leadMachine;
// Never a Team account's: the Swarm starts a PM only on its person's own
// computer (backend leadStart.ts leadHost, #4120).
final name = target?.name ?? machineLabel;
return ['Product Manager on $name', agentLabel, leadModelLabel].join(' · ');
}
/// Under [leadLine]: the repo that machine clones first, or null.
String? get leadCloneNote {
if (_leadRepositoryName == null) return null;
final target = leadMachine;
final clones = leadThroughSwarm
? target != null && !target.has(leadRepositoryUrl)
: _project.repository != null;
return clones ? 'Clones $_leadRepositoryName there first' : null;
}
/// Why New Project cannot start its Product Manager now, or null.
String? get leadBlocked {
final machines = integration?.leadMachines;
if (machines == null) return null;
if (_paused(machines)) {
return '$kLeadSwarmPaused. New Project can start once it resumes.';
}
if (leadNone) return 'No machine can run the Product Manager now.';
if (!_leadPicked) return kLeadChooseMachine;
if (leadMachine?.startable != true) {
final name = leadMachine?.name ?? machineLabel;
return '$name cannot start the Product Manager. Choose another machine.';
}
final refusal = leadMachine?.engineRefusals[_engine];
if (refusal != null) {
return '${leadMachine!.name} can’t run $agentLabel: $refusal. '
'Choose another engine.';
}
if (leadThroughSwarm) {
if (leadRepositoryUrl == null) {
return 'Choose a repo with a remote, so the Swarm can clone it for '
'the Product Manager.';
}
if (_model != null) {
return 'Models on the grid run only where this Desktop starts the '
'Product Manager. Choose the default model.';
}
}
return _leadModelListRefusal;
}
/// The engine a chosen machine runs, as a choice the person did not make.
void _placeLeadEngine(String engine) {
final touched = _selectionTouched;
_selectEngine(engine);
_selectionTouched = touched;
}
/// Starts the Product Manager on [id], a machine the list can start it on
/// now: this Desktop starts it on one of the person's it is connected to,
/// the Swarm on any other. Anything else is refused with its reason.
void chooseLeadMachine(String id) {
if (locked) return;
final listed = integration?.leadMachines
?.where((m) => m.id == id)
.firstOrNull;
// The machine chosen last wins over an engine it cannot run.
if (listed != null && listed.startable && !listed.runs(_engine)) {
_placeLeadEngine(listed.leadEngines.first);
}
if (listed != null && listed.startable && !listed.native) {
error = null;
_swarmLeadMachine = id;
_leadPicked = true;
notifyListeners();
return;
}
final choice = machineChoices.where((m) => m.id == id).firstOrNull;
if (listed == null ||
!listed.startable ||
choice == null ||
!choice.enabled) {
warn(
listed?.unavailable ??
choice?.why ??
'${listed?.name ?? 'This machine'} cannot start the Product Manager.',
);
return;
}
error = null;
_swarmLeadMachine = null;
_leadPicked = true;
final remote = _remoteOf(_machineId, _project);
_selectMachine(id);
if (remote != null) _keepRepository(id, remote, listed.name);
// That machine's branches: a branch chosen on the other one is not here.
if (_desktopChoices) _syncGitProject();
notifyListeners();
}
/// The model the Product Manager runs: the one chosen; else its role's
/// default, Claude Opus 5.5 at xhigh (Scholes's roadmap, piece 1); else its
/// engine's own, which nothing knows before it starts.
String get leadModelLabel => _model != null
? modelLabel
: leadLaunchModel != null
? '${kLeadModel.label} · ${kLeadModel.effort}'
: 'Default model';
/// The model and effort a Claude Product Manager is launched with when its
/// person chose no model and the Swarm's model list leaves Opus on: on this
/// Mac as flags. Through the Swarm its start names none, and the Swarm
/// fills the same default under the owner's list and rules (backend
/// commands.ts). A machine that cannot take them starts it on the engine's
/// own (AppNotifier.createAgent).
({String model, String effort})? get leadLaunchModel =>
integration?.swarmRole == 'lead' &&
_engine == 'claude' &&
_model == null &&
!asGuest &&
(integration?.leadModels?.modelOn(
'claude',
kLeadModel.model,
kLeadModel.effort,
) ??
true)
? (model: kLeadModel.model, effort: kLeadModel.effort)
: null;
/// Why the Swarm's model list rules out [model] (null for the engine's
/// default) for a new project's Product Manager, or null.
String? _leadModelRefusal(String? model, {bool grid = false}) {
final list = integration?.leadModels;
if (!placesLead || list == null) return null;
if (grid && !list.gridModels) {
return 'The Swarm’s model list turns off models on its grid.';
}
return list.refusal(_engine, model);
}
/// Why the Swarm's model list rules out the engine or model chosen, or
/// null.
String? get _leadModelListRefusal {
final list = integration?.leadModels;
if (!placesLead || list == null) return null;
if (list.engineRefusal(_engine) case final why?) {
return '$why Choose another engine.';
}
final why = _leadModelRefusal(_model?.id, grid: _model != null);
return why == null ? null : '$why Choose another model.';
}
/// The remote [project] on [machineId] has, when anything says so: a
/// repository to clone, an agent that ran in that folder, or the Swarm's
/// own checkout there.
String? _remoteOf(String machineId, NewHarnessProject project) {
if (project.repository case final repository?) {
return repository.shareableUrl;
}
final folder = project.folder;
if (folder == null) return null;
final machine = app.stateOf(machineId);
for (final agent in machine?.agents ?? const <Agent>[]) {
final known = machine!.projectOf(agent);
if (known?.remote case final remote?
when known!.root == folder || known.cwd == folder) {
return remote;
}
}
final listed = integration?.leadMachines
?.where((m) => m.id == machineId)
.firstOrNull;
for (final MapEntry(:key, :value) in listed?.folders.entries ?? const []) {
if (value == folder) return key;
}
return null;
}
/// Keeps the repo [remote] names on [machineId]: its folder there, found by
/// its remote, or else the repository to clone there.
void _keepRepository(String machineId, String remote, String machineName) {
final key = leadRepositoryKey(remote);
String? folder;
final machine = app.stateOf(machineId);
for (final agent in machine?.agents ?? const <Agent>[]) {
final known = machine!.projectOf(agent);
if (known != null &&
!known.worktree &&
leadRepositoryKey(known.remote) == key) {
folder = known.root ?? known.cwd;
break;
}
}
folder ??= integration?.leadMachines
?.where((m) => m.id == machineId)
.firstOrNull
?.folders[key];
final clone = GitHubRepository.parse(
remote.startsWith('github.com/') ? 'https://$remote' : remote,
);
if (folder != null) {
_project = NewHarnessProject.folder(folder);
} else if (clone != null) {
_project = NewHarnessProject.clone(clone);
} else {
warn('$machineName has no copy of $remote. Choose its folder there.');
return;
}
}
/// The GitHub repository a cloud coding agent works on: the one chosen to
/// clone, else the chosen folder's own remote; null when neither is on GitHub.
String? get cloudRepository {
final cloned = _project.repository?.shareableUrl;
if (cloned != null) return cloned;
final folder = _project.folder;
final machine = _machine;
if (folder == null || machine == null) return null;
for (final agent in machine.agents) {
final project = machine.projectOf(agent);
final remote = project?.remote;
if (remote != null &&
remote.contains('github.com') &&
(project!.cwd == folder || project.root == folder)) {
return remote;
}
}
return null;
}
/// Devin Cloud's ACU limit for the session: low by default, since it bills
/// while it works.
int acuLimit = 5;
static const acuLimits = [2, 5, 10, 20];
void setAcuLimit(int value) {
acuLimit = value;
notifyListeners();
}
bool get needsProject =>
!asGuest &&
!isTerminal &&
!isCloud &&
_project.folder == null &&
_project.repository == null &&
_project.newRepository == null &&
projectFolderSlug(_project.name ?? '') == null;
/// A missing or ambiguous saved value stays visible until the person
/// replaces it. These checks never select a different launch target.
({NewHarnessField field, String message})? get requiredChoice {
// A Buddy needs only its agent and computer (task #4196).
if (checking || bringsBuddy) return null;
if (needsProject) {
return (field: NewHarnessField.projectMenu, message: 'Choose a project.');
}
// A terminal sends no project ([projectFolderRequest]): it would open at
// home under a chip that still names the repository.
if (isTerminal && _project.repository != null) {
return (
field: NewHarnessField.projectMenu,
message: "A terminal can't clone. Choose a folder or an agent.",
);
}
final machine = _machine;
if (machine == null || machine.isOffline || machine.needsLink) {
return (
field: NewHarnessField.machine,
message: 'This machine is unavailable. Choose a machine.',
);
}
if (isCloud) {
if (cloudAgentTakesRepository(_engine) && cloudRepository == null) {
return (
field: NewHarnessField.projectMenu,
message: 'Choose a GitHub repository for $agentLabel.',
);
}
if (task.trim().isEmpty) {
return (
field: NewHarnessField.task,
message: 'Tell $agentLabel what to do.',
);
}
return null;
}
if (_harnessId != null && !_offered(_harnessId!)) {
return (
field: NewHarnessField.harness,
message: '$harnessLabel is unavailable. Choose an agent or harness.',
);
}
final engineState = machine.engines[_engine];
if (!compatibleEngines.contains(_engine) ||
(_rememberedAgent &&
!asGuest &&
!_selectionTouched &&
engineState?.installed == false &&
// The product default installs on Create; one that cannot be
// installed here (a custom path that is gone, an ambiguous
// binary) is as unavailable as a remembered one.
(_engineRemembered || !engineState!.installable))) {
return (
field: harnessId == null
? NewHarnessField.harness
: NewHarnessField.agent,
message: '$agentLabel is unavailable. Choose an agent.',
);
}
if (gitError == 'PROJECT_UNAVAILABLE') {
return (
field: NewHarnessField.projectMenu,
message: 'This project is unavailable. Choose a project.',
);
}
// A harness starts in the folder of a project with no commit
// ([noCommitsYet]), but a Product Manager never works in the person's
// checkout, and its worktree needs a commit to start from.
if (!checkingGit && placesLead && noCommitsYet) {
return (
field: NewHarnessField.projectMenu,
message: 'This project has no commits, and a Product Manager works in its own worktree. Choose a project with a commit.',
);
}
if (!checkingGit &&
choosesBranch &&
(worktree || _startsOnDefault) &&
branchRef == null) {
return (
field: NewHarnessField.branch,
message: 'This project has no default branch. Choose a branch.',
);
}
if (usesProfile &&
_profile != null &&
_profilesLoaded &&
!_profiles.any((profile) => profile.path == _profile!.path)) {
return (
field: NewHarnessField.profile,
message: 'This profile is unavailable. Choose a profile.',
);
}
return null;
}
// ---- what the line says -------------------------------------------------
/// The same on every New Harness: where Start goes is said by the Branch row,
/// not by a button that changes its name.
String get createLabel => 'Start Harness';
String get agentLabel => labelOf(_engine);
String get launchAgentLabel =>
harnessId == null ? agentLabel : '$harnessLabel · $agentLabel';
String get launchProjectLabel =>
'$machineLabel:${needsProject ? "Choose project" : projectLabel}';
String labelOf(String id) => currentHarnessName(
id,
_machine?.dsh[id]?.name ??
(id == 'claude' ? 'Claude Code' : engineIdentity(id).label),
);
String get machineLabel => _machineLabel(_machineId);
String _machineLabel(String id) =>
app.stateOf(id)?.machine.displayName ?? 'No machine';
String get projectLabel {
final project = _project;
if (asGuest) return project.folder ?? 'My workspace';
if (project.folder case final folder?) return tildePath(folder);
if (project.repository case final repo?) return '~/harnesses/${repo.name}';
if (isTerminal) return '~';
final name = project.name == null ? null : projectFolderSlug(project.name!);
return name == null ? '~/harnesses' : '~/harnesses/$name';
}
String get projectLocation => needsProject
? 'Choose a project on $machineLabel'
: '$machineLabel:$projectLabel';
String location(String path, [String? machineId]) {
final id = machineId ?? _machineId;
return '${_machineLabel(id)}:${tildePath(path, id)}';
}
String? _homeOf(String id) =>
app.stateOf(id)?.isLocalMachine == true ? _home : _homes[id];
p.Context _pathsFor(String id, [String? hint]) {
if (app.stateOf(id)?.isLocalMachine == true) return p.context;
// The machine model has no OS field. Its own home response (or a known
// project path before that response) owns the syntax, never this host.
// A relative query carries no style evidence over the committed project.
final absoluteHint =
hint != null &&
(p.posix.isAbsolute(hint) ||
p.windows.isAbsolute(hint) && !p.windows.isRootRelative(hint))
? hint
: null;
final ownerPath =
_homes[id] ??
absoluteHint ??
(id == _machineId ? _project.folder : _projectsByMachine[id]?.folder);
return ownerPath != null &&
p.windows.isAbsolute(ownerPath) &&
!p.windows.isRootRelative(ownerPath)
? p.windows
: p.posix;
}
String tildePath(String path, [String? machineId]) {
final id = machineId ?? _machineId;
final home = _homeOf(id);
if (home == null) return path;
final paths = _pathsFor(id, path);
if (paths.style == p.Style.windows) {
if (paths.equals(path, home)) return '~';
if (paths.isWithin(home, path)) {
return '~/${paths.relative(path, from: home).replaceAll('\\', '/')}';
}
return path;
}
return path == home
? '~'
: path.startsWith('$home/')
? '~${path.substring(home.length)}'
: path;
}
String get hint => switch (field) {
NewHarnessField.launch => '',
NewHarnessField.projectMenu => 'Search projects',
NewHarnessField.task => 'What should this harness work on? (optional)',
NewHarnessField.harness => 'Search agents and harnesses',
NewHarnessField.agent => 'Search agents',
NewHarnessField.model => 'Search subscriptions and models',
NewHarnessField.machine => 'Search machines',
NewHarnessField.branch => 'Search branches',
NewHarnessField.project => 'Folder path',
NewHarnessField.projectName => 'Project name',
NewHarnessField.projectRepository => 'GitHub URL',
NewHarnessField.mode => 'How much it may do without asking',
NewHarnessField.profile => 'Find a Codex profile',
};
// ---- moving along the line ----------------------------------------------
({NewHarnessField field, String query, String? agentPreview}) _machineOrigin =
(field: NewHarnessField.launch, query: '', agentPreview: null);
void focusField(NewHarnessField next, {bool previewAgent = false}) {
if (locked) return;
// Form fields edit the saved agent. Only an explicit nested setting may
// use the agent currently being previewed in the choices list.
if (!previewAgent) _agentPreview = null;
if (field == next || !_supportsField(next)) return;
_visibleFolder = folderRefreshError = null;
if (next == NewHarnessField.machine) {
_machineOrigin = (
field: field,
query: query,
agentPreview: _agentPreview,
);
}
if (next == NewHarnessField.mode || next == NewHarnessField.profile) {
if (field != NewHarnessField.agent) _agentPreview = null;
_agentSettingsOrigin = (
field: field == NewHarnessField.agent
? NewHarnessField.agent
: NewHarnessField.launch,
query: field == NewHarnessField.agent ? query : '',
);
} else {
_agentPreview = null;
}
if (field == NewHarnessField.projectMenu) _projectFilter = query;
if (next == NewHarnessField.projectMenu &&
field == NewHarnessField.launch) {
_projectFilter = '';
}
field = next;
_editingSuggestedProject =
next == NewHarnessField.projectName && _project.generated != null;
_cycle = null;
_steered = false;
// Keep the task and a Project filter when returning from a child prompt.
// A fresh visit from the launch menu starts with all recent projects.
query = next == NewHarnessField.task
? task
: next == NewHarnessField.projectName
? _project.name ?? ''
: next == NewHarnessField.projectMenu
? _projectFilter
: '';
error = null;
_refresh();
if (next == NewHarnessField.branch) {
unawaited(refreshBranches(force: false));
}
if (next == NewHarnessField.model) unawaited(refreshModels());
}
void nextField([int step = 1]) {
if (field == NewHarnessField.machine) {
_returnToProject();
return;
}
final line = fields;
final at = line.indexOf(field);
focusField(line[((at < 0 ? 0 : at) + step) % line.length]);
}
void setQuery(String value) {
if (locked || field == NewHarnessField.launch || query == value) {
return;
}
if (field == NewHarnessField.projectName) _editingSuggestedProject = false;
if (field == NewHarnessField.task) {
task = query = value;
error = taskTooLong
? 'A first message can be $kFirstTaskMaxLength characters; '
'this is ${value.trim().length}.'
: null;
_followTask();
notifyListeners();
return;
}
// A completion menu's `/`: with a folder highlighted, typing a slash takes
// that folder and goes into it, rather than the half-typed stem before it.
if (field == NewHarnessField.project &&
_isPath(query) &&
value == '$query/' &&
!query.endsWith('/')) {
final folder = selected?.project?.folder;
final slash = query.lastIndexOf('/');
if (folder != null &&
slash >= 0 &&
selected!.detail.startsWith('Use ') == false) {
value = '${query.substring(0, slash + 1)}${selected!.title}/';
}
}
// Typing ends a Tab walk: the list goes back to following what is typed.
_cycle = null;
query = value;
error = null;
_refresh(resetCursor: true);
// A filter's top row is the person's: they typed what put it there.
_steered = value.trim().isNotEmpty;
}
/// Only an explicitly highlighted result may override a launch argument
/// when using the quick-start shortcut from a picker.
bool _steered = false;
/// The arrows end a Tab walk: the line goes back to what was typed and the
/// highlight is the arrows' again. Left set, the walk outranked them — the
/// next app tick or folder listing yanked the highlight back to its row.
void _endCycle() {
final cycle = _cycle;
if (cycle == null) return;
_cycle = null;
query = '${cycle.typedParent}${cycle.stem}';
}
/// Escape during a Tab walk gives back what was typed, as vim's wildmenu
/// does, before it closes anything. Whether there was a walk to end.
bool endCompletion() {
if (_cycle == null || locked) return false;
_endCycle();
_refresh();
return true;
}
void move(int delta) {
if (options.isEmpty || locked) return;
_endCycle();
cursor = (cursor + delta) % options.length;
_steered = true;
if (field == NewHarnessField.agent) {
_refresh();
return;
}
notifyListeners();
}
/// ← and → change the focused field's value where it stands, as a BIOS
/// settings screen does, rather than opening a list to choose from. Unlike
/// [accept] the line keeps its field, so the next arrow steps again, and
/// the rows the box adds for itself — Browse, New project, Permissions —
/// are skipped: they are doors, not values.
/// The values a field can be stepped through, in a stable order. The
/// displayed list is NOT that order: it re-ranks so the chosen row floats
/// to the front, which makes stepping by index walk in circles — right
/// always took the second row and left always wrapped to the last.
List<NewHarnessOption> stepValues() => [
for (final option in options)
if (!option.synthetic && option.enabled) option,
];
/// Take [option] as this field's value without moving off the field.
/// Synthetic rows are allowed here even though [stepValues] leaves them
/// out: "Create branch x" is a real answer to the Branch row, it is only
/// not one the arrows should cycle onto.
void applyOption(NewHarnessOption option) {
if (locked || !option.enabled || !_optionIsCurrent(option)) return;
error = null;
_steered = true;
_apply(option);
_refresh();
}
/// Take what the field is highlighting as its value, where it stands.
/// Typing narrows a field and lands on a row; this is what makes that row
/// the answer, so the value on screen is always the one Return acts on.
void takeSelection() {
final option = selected;
if (locked || option == null || option.synthetic || !option.enabled) {
return;
}
applyOption(option);
}
bool _optionIsCurrent(NewHarnessOption option) {
if (field == NewHarnessField.model &&
(option.machineId != _machineId ||
option.model != null && !_modelAvailable(option.model!))) {
warn(
'This model choice is no longer available. Refresh models and choose again.',
);
return false;
}
if (field == NewHarnessField.agent &&
!compatibleEngines.contains(option.id)) {
warn('Choose an agent compatible with $harnessLabel on $machineLabel.');
return false;
}
if (field == NewHarnessField.profile && option.machineId != _machineId) {
warn('Choose a Codex profile on $machineLabel. The machine has changed.');
return false;
}
if (field == NewHarnessField.projectMenu && option.machineId != null) {
final machine = app.stateOf(option.machineId!);
if (machine == null ||
machine.machine.isShared ||
!_machineUsable(machine)) {
warn('This project is unavailable. Choose a connected machine.');
return false;
}
}
if ((field == NewHarnessField.project ||
field == NewHarnessField.projectName ||
field == NewHarnessField.projectRepository) &&
option.machineId != null &&
option.machineId != _machineId) {
warn('Choose a project on $machineLabel. The machine has changed.');
return false;
}
return true;
}
NewHarnessOption? get selected =>
cursor < 0 || cursor >= options.length ? null : options[cursor];
/// The answers cannot change: a create is running, or one whose reply was
/// lost has still to be checked on.
bool get locked => busy || checking || linkingProfile;
/// + New agent's Agent (`member`) or Product Manager (`lead`) (task #4196),
/// or null outside one.
String? get agentKind => integration?.agentKind;
void setAgentKind(String kind) {
final destination = integration;
if (destination == null || locked || destination.agentKindLocked) return;
destination.agentKind = kind;
notifyListeners();
}
/// Lists always choose. The launch menu and optional task prompt start.
bool get returnCreates =>
checking ||
field == NewHarnessField.launch ||
field == NewHarnessField.task;
/// Whether [option] is the answer the line already gives — the row that
/// wears the ✓, as the current folder and branch do in an editor's pickers.
bool isCurrent(NewHarnessOption option) => switch (field) {
NewHarnessField.launch || NewHarnessField.task => false,
NewHarnessField.harness => option.id == (harnessId ?? _engine),
NewHarnessField.agent => option.id == _engine,
NewHarnessField.model =>
option.id == (_model == null ? defaultModelId : _modelId(_model!)),
NewHarnessField.machine => option.id == _machineId,
NewHarnessField.branch => option.id == branchRef,
NewHarnessField.project ||
NewHarnessField.projectMenu ||
NewHarnessField.projectName ||
NewHarnessField.projectRepository =>
option.project != null &&
(option.machineId ?? _machineId) == _machineId &&
option.project == _project,
NewHarnessField.mode => option.id == _settingsMode,
NewHarnessField.profile =>
option.id ==
(_settingsProfile == null
? defaultProfileId
: 'profile:${_settingsProfile!.path}'),
};
bool _isCurrent(NewHarnessOption option) => isCurrent(option);
/// The project row that opens the system's folder chooser: the way in for
/// anyone who would rather point at a folder than type its path.
static const browseId = 'project:browse';
static const changeMachineId = 'project:machine';
static const newProjectId = 'project:name';
static const createBranchId = 'branch:create:';
static const existingProjectId = 'project:existing';
static const guestWorkspaceId = 'project:guest-workspace';
static const guestFolderId = 'project:guest-folder:';
static const repositoryId = 'project:repository';
/// The one action a pasted path or GitHub link gets at the top of the
/// project menu (docs/plans/2026-10-30-new-harness-paste-path-or-repository.md).
static const pasteOpenId = 'project:paste:open';
static const pasteBrowseId = 'project:paste:browse';
static const pasteInvalidId = 'project:paste:invalid';
static const cloneId = 'project:clone';
static const newRepositoryId = 'project:new-repository';
static const _pasteIds = {
pasteOpenId,
pasteBrowseId,
pasteInvalidId,
cloneId,
};
static const storeId = 'agent:store';
static const codingId = 'harness:coding';
static const defaultModelId = 'model:subscription';
static const manageModelsId = 'model:manage';
static const refreshModelsId = 'model:refresh';
static const permissionsId = 'agent:permissions';
static const profileId = 'agent:profile';
static const defaultProfileId = 'profile:default';
static const refreshProfilesId = 'profile:refresh';
static const linkProfileId = 'profile:link';
static const _store = NewHarnessOption(
id: storeId,
synthetic: true,
title: 'Browse Harness Store',
);
// For anyone who would rather point at a folder than type its path. It stays
// under whatever is typed: the way out must not vanish on the first key.
NewHarnessOption get _browse =>
NewHarnessOption(id: browseId, synthetic: true, title: 'Browse Folder');
NewHarnessOption get _changeMachine => NewHarnessOption(
id: changeMachineId,
synthetic: true,
title: 'Change Machine',
detail: machineLabel,
);
bool _desktopChoices = false;
/// Desktop menus scope folders to the selected machine and keep coding
/// agents ahead of recent and featured specialized harnesses.
void useDesktopChoices(bool desktop) {
if (_desktopChoices == desktop) return;
_desktopChoices = desktop;
if (desktop) _applySuccessfulLaunch();
_refresh(resetCursor: true);
}
void _applySuccessfulLaunch() {
if (_restoringDraft || locked) return;
final saved = app.agentPreference.successfulLaunch;
if (!_initialAgentExplicit && !_selectionTouched) {
_harnessId = saved?.harnessId;
_engine = _initialEngine(null);
if (_project.generated != null) _project = _generatedProject();
}
_restorePermissionMode();
if (saved == null || saved.engine != _engine || _noAgentSetup) return;
if (!_modelTouched) {
_model = saved.model;
if (_model != null) unawaited(refreshModels());
}
if (!_profileChosen &&
saved.profileMachineId == _machineId &&
_engine == 'codex' &&
_model == null) {
_profile = saved.profile;
_profileChosen = true;
if (_profile != null) unawaited(refreshProfiles());
}
}
List<NewHarnessOption> _projectMenu() {
if (asGuest) return _guestPlaces();
final recent = _ranked(_recentProjects());
var pasted = _pasteAction();
// A half-typed path a recent project matches is that project: Browse
// would take the highlight from the answer already on screen.
if (pasted?.id == pasteBrowseId && recent.isNotEmpty) pasted = null;
return [
?pasted,
if (!_desktopChoices)
const NewHarnessOption(
id: repositoryId,
synthetic: true,
title: 'Clone Repository',
detail: 'Paste a GitHub repository URL',
),
const NewHarnessOption(
id: existingProjectId,
synthetic: true,
title: 'Open Folder',
detail: 'Enter a path or browse folders',
),
const NewHarnessOption(
id: newProjectId,
synthetic: true,
title: 'New Folder',
detail: 'Name a new folder',
),
if (_desktopChoices)
const NewHarnessOption(
id: repositoryId,
synthetic: true,
title: 'GitHub',
detail: 'Clone a GitHub repository',
),
if (_desktopChoices && offersNewRepository)
const NewHarnessOption(
id: newRepositoryId,
synthetic: true,
title: 'New Repository',
detail: 'Create one on GitHub',
),
...recent,
];
}
/// Takes the highlighted row as this field's answer and moves along.
void accept([NewHarnessOption? row]) {
final option = row ?? selected;
if (locked || option?.id == storeId) return;
if (field == NewHarnessField.agent &&
option != null &&
!compatibleEngines.contains(option.id)) {
warn('Choose an agent compatible with $harnessLabel on $machineLabel.');
return;
}
if (option?.id == permissionsId) {
focusField(NewHarnessField.mode, previewAgent: true);
return;
}
if (option?.id == profileId) {
focusField(NewHarnessField.profile, previewAgent: true);
return;
}
if (option?.id == refreshProfilesId) {
unawaited(refreshProfiles());
return;
}
if (option?.id == linkProfileId) return;
if (option?.id == changeMachineId) {
focusField(NewHarnessField.machine);
return;
}
if (option?.id == newProjectId) {
focusField(NewHarnessField.projectName);
return;
}
if (option?.id == existingProjectId) {
focusField(NewHarnessField.project);
return;
}
if (option?.id == repositoryId) {
focusField(NewHarnessField.projectRepository);
return;
}
if (option?.id == newRepositoryId) {
field = NewHarnessField.launch;
query = '';
_refresh(resetCursor: true);
onNewRepository?.call();
return;
}
if (option?.id == browseId) return;
if (option?.id == pasteBrowseId) {
final typed = query.trim();
focusField(NewHarnessField.project);
setQuery(typed);
return;
}
if (option == null) {
// Return is never silent: nothing matched, so say so and how to go on.
error = field == NewHarnessField.projectName && query.trim().isEmpty
? 'Type a project name.'
: field == NewHarnessField.projectRepository
? 'Enter a GitHub URL or a short name like openai/codex.'
: listing
? 'Still reading that folder…'
: field == NewHarnessField.project && _isPath(query)
? 'No folder matches “${query.trim()}”.'
: 'Nothing matches “${query.trim()}”. Edit it, or press Escape to go back.';
notifyListeners();
return;
}
if (!option.enabled) {
// A key that silently does nothing is the worst answer: say why.
error = option.why ?? '${option.title} cannot be chosen.';
notifyListeners();
return;
}
if (!_optionIsCurrent(option)) return;
final from = field;
final previousMachine = _machineId;
_apply(option);
_cycle = null;
if (from == NewHarnessField.machine) {
_returnFromMachine(changed: previousMachine != _machineId);
return;
}
if (from == NewHarnessField.mode || from == NewHarnessField.profile) {
_returnFromAgentSettings(accepted: true);
return;
}
_agentPreview = null;
field = needsProject ? NewHarnessField.projectMenu : NewHarnessField.launch;
query = '';
_refresh(resetCursor: true);
}
/// The folder the system chooser (or the remote browser) came back with.
void setFolder(String folder) {
if (locked) return;
_project = NewHarnessProject.folder(folder, exact: true);
field = NewHarnessField.launch;
_cycle = null;
query = field == NewHarnessField.task ? task : '';
error = null;
_refresh(resetCursor: true);
}
/// ⌘↵: make it now — WITH the row under the highlight. Creating with the
/// old answer while a different one was lit threw away the one thing the
/// person had just done.
Future<NewHarnessOutcome> createNow() {
if (!locked &&
(field == NewHarnessField.projectMenu ||
field == NewHarnessField.machine ||
field == NewHarnessField.mode ||
field == NewHarnessField.profile ||
selected?.id == permissionsId ||
selected?.id == profileId ||
selected?.id == changeMachineId ||
selected?.id == newProjectId ||
selected?.id == newRepositoryId)) {
accept();
return Future.value(NewHarnessOutcome.failed);
}
if (!locked && !returnCreates && selected == null) {
accept();
return Future.value(NewHarnessOutcome.failed);
}
if (!locked && selected?.id == browseId) {
return Future.value(_fail('Choose a folder to continue.'));
}
if (selected?.id == storeId && !locked) {
return Future.value(_fail('Choose a harness from the Store first.'));
}
// Only a row the person went to: see [_steered].
final option = _steered ? selected : null;
if (!checking && !busy && option != null && !option.enabled) {
// Never make it with the OLD answer while a different one is lit.
if (!returnCreates) {
return Future.value(
_fail(option.why ?? '${option.title} cannot be chosen.'),
);
}
}
if (!checking && !busy && option != null && option.enabled) {
if (!returnCreates) {
_apply(option);
_cycle = null;
query = '';
_refresh(resetCursor: true);
}
}
return create();
}
void _apply(NewHarnessOption option) {
switch (field) {
case NewHarnessField.harness:
if (isFinderEngine(option.id)) {
_selectFinder();
} else if (isHarnessId(option.id) && option.id != codingId) {
_selectHarness(option.id);
} else {
_selectHarness(null);
if (option.id != codingId) _selectEngine(option.id);
}
case NewHarnessField.agent:
// A machine that cannot run it says so (leadBlocked); the person
// chooses again, nothing moves on its own.
_selectEngine(option.id);
case NewHarnessField.model:
_model = option.model;
_modelTouched = true;
case NewHarnessField.machine:
_selectMachine(option.id);
case NewHarnessField.branch:
if (option.id.startsWith(createBranchId)) {
_branchName = option.id.substring(createBranchId.length);
_branchRef = null;
} else {
// A picked branch replaces a new one.
_branchRef = option.id;
_branchName = null;
}
case NewHarnessField.project:
case NewHarnessField.projectMenu:
case NewHarnessField.projectName:
case NewHarnessField.projectRepository:
if (option.machineId case final id?) _selectMachine(id);
_project = option.project ?? _project;
if (_desktopChoices) {
_syncGitProject();
}
case NewHarnessField.mode:
_selectEngine(_settingsEngine);
_mode = option.id;
_chosenModes[_engine] = _mode;
if (!_desktopChoices) {
unawaited(app.agentPreference.selectPermissionMode(_base, _mode));
}
case NewHarnessField.profile:
_selectEngine(_settingsEngine);
_profile = option.profile;
_profileChosen = true;
case NewHarnessField.task:
case NewHarnessField.launch:
break;
}
}
void _selectEngine(String engine) {
if (!compatibleEngines.contains(engine)) return;
_selectionTouched = true;
final changed = engine != _engine;
if (_engine != engine) {
_profile = null;
_profileChosen = false;
_resetProfiles();
}
_engine = engine;
if (changed && _desktopChoices && !_modelTouched) _model = null;
if (changed) _restorePermissionMode();
if (_noAgentSetup) _model = null;
if (changed &&
_harnessId == null &&
_project.generated != null &&
field != NewHarnessField.projectName) {
_project = _generatedProject();
unawaited(_refreshGeneratedProject());
}
_dropAccepted = false;
if (!takesTask && task.trim().isNotEmpty) {
error =
'${labelOf(engine)} cannot start on a first message, so '
'“${_short(task)}” will not be sent. Type it once it is open.';
}
}
void _selectHarness(String? id) {
_selectionTouched = true;
_harnessId = id;
_finder = false;
_installing = null;
_selectEngine(
_desktopChoices
? _initialEngine(null)
: _initialEngine(app.agentPreference.engineFor(id) ?? _engine),
);
if (_project.generated != null) {
_project = _generatedProject();
unawaited(_refreshGeneratedProject());
}
}
/// The Finder keeps the agent already chosen as its chat when it can run
/// one; otherwise the box's own first choice.
void _selectFinder() {
_selectionTouched = true;
_harnessId = null;
_installing = null;
_finder = true;
if (!compatibleEngines.contains(_engine)) {
_selectEngine(_finderChat(_initialEngine(null)));
}
}
/// [candidate] when a Finder's chat can run it — an agent, not the cloud or
/// a bare shell — else the agent signed in here, else the product default.
String _finderChat(String candidate) => compatibleEngines.contains(candidate)
? candidate
: _accountAgent() ?? defaultHarnessEngine;
void _selectMachine(String id) {
_installing = null;
if (_machineId == id) return;
_projectsByMachine[_machineId] = _project;
_machineId = id;
_modelCatalog = null;
_loadingModels = false;
_modelRequest++;
_projectFilter = '';
_project =
_projectsByMachine[id] ??
(_autoProject ? _generatedProject() : const NewHarnessProject.fresh());
_profile = null;
_profileChosen = false;
_agentPreview = null;
_resetProfiles();
_machineRevision++;
_listDebounce?.cancel();
_hiddenFolderDebounce?.cancel();
_hiddenFolders.clear();
_hiddenFolderAsked = null;
_listings.clear();
_loadingFolders.clear();
_visibleFolder = folderRefreshError = null;
_listing = null;
_pathKey = null;
unawaited(app.probeEngines(id, force: true));
// A guest is listed no harnesses or folders there, only where it may start (asGuest).
if (app.stateOf(id)?.machine.isSharedMachine == true) {
return _startAsGuest();
}
unawaited(app.probeDsh(id, force: true));
unawaited(_ensureHome(id));
unawaited(_refreshGeneratedProject());
}
NewHarnessProject _generatedProject() => NewHarnessProject.generated(
ProjectFolderRequest.generated(
label: harnessId == null ? engineIdentity(_engine).label : harnessLabel,
at: _now(),
// Only a task the agent will actually be sent names the project.
task: takesTask ? task : null,
),
);
/// Offer an unused name without creating anything. Start still reserves the
/// folder atomically, including when two previews saw the same free name.
Future<void> _refreshGeneratedProject() async {
final project = _project;
final request = project.generated;
if (request == null) return;
final id = _machineId;
final revision = _machineRevision;
try {
final home = await _ensureHome(id);
if (home == null) return;
final root = _pathsFor(id, home).join(home, 'harnesses');
final List<String> names;
if (app.stateOf(id)?.isLocalMachine == true) {
names = await Isolate.run(
() =>
Directory(root)
.listSync(followLinks: false)
.map((entry) => p.basename(entry.path))
.toList(),
);
} else {
final answer = await app.listRemoteFolder(id, root);
final entries = answer['entries'];
if (entries is! List) return;
names = [
for (final entry in entries)
if (entry is Map && entry['name'] is String)
entry['name'] as String,
];
}
if (_disposed ||
locked ||
id != _machineId ||
revision != _machineRevision ||
field == NewHarnessField.projectName ||
!identical(project, _project)) {
return;
}
final name = request.availableGeneratedName(names);
if (name == project.name) return;
_project = NewHarnessProject.generated(request.withGeneratedName(name));
_refresh();
} catch (_) {
// Missing or unreadable listings are not permission to reuse a folder.
// The exclusive reservation at Start remains authoritative.
}
}
({NewHarnessField field, String query}) _agentSettingsOrigin = (
field: NewHarnessField.launch,
query: '',
);
void _returnFromAgentSettings({bool accepted = false}) {
final engine = _settingsEngine;
field = _agentSettingsOrigin.field;
query = _agentSettingsOrigin.query;
if (accepted && field == NewHarnessField.launch && needsProject) {
field = NewHarnessField.projectMenu;
query = '';
}
_cycle = null;
error = null;
_refresh(resetCursor: true, agentSelection: engine);
}
List<LocalCodexProfile> _profiles = const [];
bool _profilesLoaded = false;
String? _profilesMachine;
int _profileRevision = 0;
int _profileRequest = 0;
bool loadingProfiles = false;
bool linkingProfile = false;
void _resetProfiles() {
_profiles = const [];
_profilesLoaded = false;
_profilesMachine = null;
_profileRevision++;
_profileRequest++;
loadingProfiles = linkingProfile = false;
}
Future<void> refreshProfiles() async {
if (_disposed || locked || loadingProfiles || !supportsProfiles) return;
final machine = _machineId;
final revision = _profileRevision;
final request = ++_profileRequest;
bool current() =>
!_disposed &&
revision == _profileRevision &&
request == _profileRequest;
_profilesMachine = machine;
loadingProfiles = true;
_profilesLoaded = false;
error = null;
_refresh();
try {
final result = await app.listCodexProfiles(
machine,
observedPaths: {
for (final agent in _machine?.agents ?? const [])
if (agent.engine == 'codex' && agent.codexHome != null)
agent.codexHome!,
},
);
if (!current()) return;
if (result['error'] != null) throw StateError('Profiles unavailable');
_profiles = [
for (final raw in result['profiles'] as List? ?? const [])
LocalCodexProfile.fromJson(Map<String, dynamic>.from(raw as Map)),
];
_profilesLoaded = true;
} catch (_) {
if (current() && field == NewHarnessField.profile) {
error =
'Could not load Codex profiles on $machineLabel. Choose Refresh profiles to retry.';
}
} finally {
if (current()) {
loadingProfiles = false;
_refresh();
}
}
}
Future<void> linkProfile(String path) async {
if (_disposed ||
locked ||
!supportsProfiles ||
field != NewHarnessField.profile) {
return;
}
final revision = _profileRevision;
bool current() => !_disposed && revision == _profileRevision;
linkingProfile = true;
error = null;
_refresh();
try {
final result = await app.linkCodexProfile(_machineId, path);
if (!current()) return;
if (result['error'] != null || result['profile'] is! Map) {
throw StateError('Profile unavailable');
}
_selectEngine(_settingsEngine);
_profile = LocalCodexProfile.fromJson(
Map<String, dynamic>.from(result['profile'] as Map),
);
_profileChosen = true;
_profiles = [..._profiles, _profile!];
linkingProfile = false;
_returnFromAgentSettings(accepted: true);
} catch (_) {
if (current()) {
error =
'Could not link this Codex profile folder on $machineLabel. Try another folder.';
}
} finally {
if (current()) {
linkingProfile = false;
_refresh();
}
}
}
List<NewHarnessOption> _profileOptions() {
final choices = <String, LocalCodexProfile>{
if (supportsProfiles) ...{
for (final profile in [..._profiles, ?_settingsProfile])
profile.path: profile,
},
};
return [
if (supportsProfiles) ...[
const NewHarnessOption(
id: linkProfileId,
title: 'Link profile folder…',
synthetic: true,
),
NewHarnessOption(
id: refreshProfilesId,
title: loadingProfiles ? 'Loading profiles…' : 'Refresh profiles',
synthetic: true,
enabled: !loadingProfiles,
),
],
..._ranked([
NewHarnessOption(
id: defaultProfileId,
title: 'Default profile',
detail: 'Use Codex’s default account on $machineLabel',
machineId: _machineId,
),
for (final profile in choices.values)
NewHarnessOption(
id: 'profile:${profile.path}',
title: profile.label,
detail: profile.path,
profile: profile,
machineId: _machineId,
enabled:
!_profilesLoaded ||
_profiles.any((available) => available.path == profile.path),
why: 'This profile is unavailable. Choose a profile.',
),
]),
];
}
String _projectFilter = '';
bool _editingSuggestedProject = false;
void _returnToProject() {
field = NewHarnessField.projectMenu;
query = _projectFilter;
_cycle = null;
error = null;
_refresh(resetCursor: true);
}
void _returnFromMachine({bool changed = false}) {
field = _machineOrigin.field;
_agentPreview = _machineOrigin.agentPreview;
// A path filter belongs to its machine; a task, name, or URL can travel.
query =
changed &&
(field == NewHarnessField.project ||
field == NewHarnessField.projectMenu)
? ''
: _machineOrigin.query;
_cycle = null;
error = null;
_refresh(resetCursor: true, agentSelection: _agentPreview);
}
/// Escape closes a nested machine chooser before it closes the agent draft.
bool backToProject() {
if (locked ||
(field != NewHarnessField.machine &&
field != NewHarnessField.project &&
field != NewHarnessField.projectName &&
field != NewHarnessField.projectRepository)) {
return false;
}
_returnToProject();
return true;
}
/// Escape leaves the focused prompt before dismissing the launch command.
/// Uncommitted filters are discarded; the task and accepted arguments stay.
bool back() {
if (locked) return false;
if (field == NewHarnessField.machine) {
_returnFromMachine();
return true;
}
if (field == NewHarnessField.mode || field == NewHarnessField.profile) {
_returnFromAgentSettings();
return true;
}
if (endCompletion() || backToProject()) return true;
if (field == NewHarnessField.launch) return false;
focusField(NewHarnessField.launch);
return true;
}
static String _short(String text) {
final one = text.trim().replaceAll(RegExp(r'\s+'), ' ');
return one.length <= 40 ? one : '${one.substring(0, 39)}…';
}
/// Tab is walking a completion menu: the stem that was typed, and the
/// candidate the line currently holds. Typing anything ends it.
({String typedParent, String stem, String name})? _cycle;
/// Tab completes the current argument without accepting it or changing
/// prompts. Paths retain common-prefix expansion and reversible cycling.
String? complete([int step = 1]) {
if (locked) return null;
if (!isPathQuery) {
if (field == NewHarnessField.task ||
field == NewHarnessField.launch ||
field == NewHarnessField.projectName ||
field == NewHarnessField.projectRepository) {
return null;
}
final option = selected;
if (option != null && !option.synthetic) {
setQuery(option.title);
_steered = true;
}
return query;
}
final paths = _pathsFor(_machineId, query);
final slash = paths.style == p.Style.windows
? max(query.lastIndexOf('/'), query.lastIndexOf('\\'))
: query.lastIndexOf('/');
final typedParent =
_cycle?.typedParent ?? (slash < 0 ? '' : query.substring(0, slash + 1));
final stem =
_cycle?.stem ?? (slash < 0 ? query : query.substring(slash + 1));
// The folders under what was typed; "Use this folder" is not a candidate.
final names = [
for (final option in options)
if (!option.synthetic) option.title,
];
if (names.isEmpty) return query;
if (_cycle case final cycle?) {
final at = names.indexOf(cycle.name);
final next = names[(at + step) % names.length];
return _showCandidate(typedParent, stem, next);
}
var common = names.first;
for (final name in names.skip(1)) {
var i = 0;
while (i < common.length &&
i < name.length &&
common[i].toLowerCase() == name[i].toLowerCase()) {
i++;
}
common = common.substring(0, i);
}
if (names.length == 1) {
final separator = paths.style == p.Style.windows && slash >= 0
? query[slash]
: '/';
final text = '$typedParent${names.single}$separator';
setQuery(text);
return text;
}
if (common.length > stem.length) {
final text = '$typedParent$common';
setQuery(text);
return text;
}
return _showCandidate(
typedParent,
stem,
step < 0 ? names.last : names.first,
);
}
String _showCandidate(String typedParent, String stem, String name) {
_cycle = (typedParent: typedParent, stem: stem, name: name);
query = '$typedParent$name';
error = null;
_refresh();
_steered = true;
return query;
}
// ---- the lists ----------------------------------------------------------
/// What of the app this box shows, and nothing else. The app notifies on
/// every turn heartbeat and every terminal byte; none of that is on this
/// screen, and rebuilding each list — and the panel with it — for each was
/// work done many times a second for nothing. Same idea as the search
/// catalog's presentation key.
List<Object?>? _seen;
List<Object?> _signature() {
final machine = _machine;
return [
for (final state in app.machineStates.values) ...[
state.machine.machineId,
state.machine.displayName,
state.machine.isShared,
state.isLocalMachine,
state.needsLink,
state.nodeOnline,
// The machine list's own word, which moves without `nodeOnline` ever
// changing — a machine that goes offline while nothing has been heard
// from it would otherwise keep its old row.
state.isOffline,
],
machine?.engines.loaded,
for (final identity in allEngines)
machine?.engines[identity.id]?.installed,
machine?.engines['codex']?.supportsCodexHome,
machine?.dsh.loaded,
machine?.dsh.error,
for (final entry in machine?.dsh.entries ?? const <DshEntry>[]) ...[
entry.id,
entry.name,
entry.installed,
entry.engine,
...entry.supportedEngines,
null,
],
...app.agentPreference.recent,
null,
...app.agentPreference.recentHarnesses,
null,
...app.agentPreference.recentChoices,
null,
// An install narrates through pushes that change no catalog row.
if (installRun case final run?) ...[
run.phase,
run.line,
run.detail,
run.log.length,
null,
],
// Projects can arrive after the box opens, including metadata recovered
// by the local CLI. Terminal output alone must not reorder this list.
for (final id in app.machineStates.keys) ..._recentProjectFolders(id),
null,
for (final id in app.machineStates.keys) ...[
id,
...app.projectHistory.recent(id),
null,
],
];
}
Timer? _appTick;
void _onApp() {
if (_disposed || _appTick != null) return;
// Coalesced: the app notifies on every terminal byte batch, and building
// even a small signature for each is work nobody sees. Ten looks a second
// is more often than any of this changes.
_appTick = Timer(const Duration(milliseconds: 100), () {
_appTick = null;
if (_disposed) return;
if (listEquals(_seen, _signature())) return;
_refresh();
});
}
void _refresh({bool resetCursor = false, String? agentSelection}) {
if (_disposed) return;
_syncGitProject();
_seen = _signature();
final current = resetCursor ? null : selected?.id;
// An agent picked from another field may have no task or no modes.
if (!_supportsField(field)) {
field = fields.first;
query = field == NewHarnessField.task ? task : '';
}
if (field == NewHarnessField.agent) {
_refreshAgents(agentSelection ?? current, resetCursor: resetCursor);
return;
}
options = switch (field) {
NewHarnessField.harness => [
..._harnessOptions(),
// A guest starts nothing from the Store there (asGuest).
if (offersStore && !asGuest && _allowedEngines == null) _store,
],
NewHarnessField.launch ||
NewHarnessField.task ||
NewHarnessField.agent => const [],
NewHarnessField.model => _modelOptions(),
NewHarnessField.machine => _machineOptions(),
NewHarnessField.branch => [
..._ranked(_branchOptions()),
?_createBranchRow(),
],
NewHarnessField.projectMenu => _projectMenu(),
NewHarnessField.project ||
NewHarnessField.projectName => _projectOptions(),
NewHarnessField.projectRepository => _repositoryOptions(),
NewHarnessField.mode => _ranked([
for (final mode in _settingsModes)
NewHarnessOption(
id: mode.id,
title: mode.label,
detail: mode.detail,
risky: mode.risky,
),
]),
NewHarnessField.profile => _profileOptions(),
};
// A path list is capped; its count is of every match, not of the rows.
matchCount =
_pathMatched ?? options.where((option) => !option.synthetic).length;
_pathMatched = null;
final kept = current == null
? -1
: options.indexWhere((option) => option.id == current);
final selectedBranch = field == NewHarnessField.branch ? branchRef : null;
final now = query.isNotEmpty
? -1
: options.indexWhere(
field == NewHarnessField.branch
? (option) => option.id == selectedBranch
: _isCurrent,
);
final pathChoice = isPathQuery
? options.indexWhere((option) => option.project?.folder != null)
: -1;
final cycling = _cycle == null
? -1
: options.indexWhere(
(option) => !option.synthetic && option.title == _cycle!.name,
);
final firstProject = options.indexWhere((option) => !option.synthetic);
cursor = cycling >= 0
? cycling
: kept >= 0
? kept
: field == NewHarnessField.projectMenu
? (options.isNotEmpty && _pasteIds.contains(options.first.id)
? 0
: firstProject >= 0
? firstProject
: options.indexWhere((option) => option.id == existingProjectId))
: query.isEmpty && now >= 0
? now
: field == NewHarnessField.profile
? options.indexWhere((row) => !row.synthetic).clamp(0, options.length)
: pathChoice >= 0
? pathChoice
: 0;
// A row we put the highlight on is not one the person chose.
if (resetCursor || (cycling < 0 && kept < 0)) _steered = false;
notifyListeners();
if (field == NewHarnessField.profile &&
supportsProfiles &&
_profilesMachine != _machineId) {
unawaited(refreshProfiles());
}
}
/// A page of the list, for PgUp/PgDn: [rows] is how many fit on screen.
void page(int direction, int rows) {
if (options.isEmpty || locked) return;
_endCycle();
cursor = (cursor + direction * rows.clamp(1, options.length)).clamp(
0,
options.length - 1,
);
_steered = true;
if (field == NewHarnessField.agent) {
_refresh();
return;
}
notifyListeners();
}
void _refreshAgents(String? current, {required bool resetCursor}) {
final agents = _agentOptions();
final target =
agents.where((row) => row.id == current).firstOrNull ??
(query.isEmpty
? agents.where((row) => row.id == _engine).firstOrNull
: null) ??
agents.firstOrNull;
_agentPreview = target?.id;
options = agents;
matchCount = agents.length;
final kept = options.indexWhere((row) => row.id == current);
cursor = kept >= 0
? kept
: target == null
? (options.isEmpty ? -1 : 0)
: options.indexWhere(
(row) => row.engine == _agentPreview && row.engine != null,
);
if (resetCursor || kept < 0) _steered = false;
notifyListeners();
}
/// Branches to start from (Worktree on) or to work on (off), tagged the way
/// editors tag them. The default list hides duplicate remote names and old
/// Harness branches; typing can find every branch.
List<NewHarnessOption> _branchOptions() {
final info = _gitProject;
final selectedRef = branchRef;
final usesWorktree = worktree;
final searching = query.trim().isNotEmpty;
final defaultName = info.defaultRef?.split('/').skip(3).join('/');
bool isDefault(GitBranch b) =>
b.ref == info.defaultRef || !b.remote && b.name == defaultName;
bool isCurrent(GitBranch b) => !b.remote && b.name == info.branch;
// A remote branch with a local one of its name is that branch: Start
// brings the local one up to it.
final candidates = [
for (final branch in info.branches)
if (searching ||
!((branch.harness || branch.name.startsWith('harness/')) &&
branch.worktree == null &&
branch.ref != selectedRef))
branch,
];
final locals = {
for (final branch in candidates)
if (!branch.remote) branch.name,
};
bool hasLocal(GitBranch b) =>
b.remote && locals.contains(b.name.split('/').skip(1).join('/'));
final shown = [
for (final branch in candidates)
if (searching || !(hasLocal(branch) && branch.ref != selectedRef))
branch,
];
int rank(GitBranch b) => isDefault(b)
? 0
: isCurrent(b)
? 1
: 2;
final ordered = [
for (final group in [0, 1, 2])
for (final branch in shown)
if (rank(branch) == group) branch,
];
return [
for (final branch in ordered)
NewHarnessOption(
id: branch.ref,
title: branch.name,
detail: [
if (isDefault(branch)) 'default',
if (isCurrent(branch)) 'current',
if (branch.worktree != null && branch.name != info.branch)
'worktree',
if (branch.remote) 'remote',
].join(' · '),
enabled: usesWorktree || !branch.remote,
why: branch.remote
? 'Turn Worktree on to start from a remote branch.'
: null,
),
];
}
/// A typed name no branch has can be made — the way an editor's branch
/// picker offers "Create branch": with Worktree on in a new worktree from
/// the default branch, off in the folder from the branch it is on. Spaces
/// become `-`, and what Git refuses in a name is dropped.
NewHarnessOption? _createBranchRow() {
if (refreshingBranches) return null;
final name = branchNameFrom(query);
if (!plausibleBranchName(name) ||
newBranchHere(_gitProject, name) == null ||
_gitProject.branches.any((branch) => branch.name == name)) {
return null;
}
final base = worktree
? defaultBranchRef(_gitProject, worktree: true)
: currentBranchRef(_gitProject);
return NewHarnessOption(
id: '$createBranchId$name',
synthetic: true,
title: 'Create branch $name',
detail: 'New branch from ${_refName(base) ?? 'HEAD'}',
);
}
List<NewHarnessOption> _ranked(List<NewHarnessOption> all) {
total = all.length;
String normalize(String text) {
final lower = text.toLowerCase();
if (field != NewHarnessField.project &&
field != NewHarnessField.projectMenu) {
return lower;
}
final normalized = lower.replaceAll(RegExp(r'[\s._:-]+'), ' ').trim();
return normalized.isEmpty ? lower : normalized;
}
final needle = normalize(query.trim());
if (needle.isEmpty) return all;
final scored = <(int, int, NewHarnessOption)>[];
for (var i = 0; i < all.length; i++) {
final option = all[i];
final name = normalize(option.title);
final spread = subsequenceSpread(name, needle);
final detail = subsequenceSpread(normalize(option.detail), needle);
// The start of the name, then the start of a word in it, then anywhere
// in it, then scattered through it, then the description. `co` is
// Codex and Claude Code before it is MuJoCo.
final score = name.startsWith(needle)
? 0
: name.split(RegExp(r'[\s/._-]+')).any((w) => w.startsWith(needle))
? 100
: name.contains(needle)
? 200
: spread != null
? 300 + spread
// A description is long; two letters scattered through one match
// nearly everything. It counts from three letters on.
: detail == null || needle.length < 3
? null
: 1000 + detail;
if (score != null) scored.add((score, i, option));
}
scored.sort((a, b) {
final by = a.$1.compareTo(b.$1);
return by != 0 ? by : a.$2.compareTo(b.$2);
});
return [for (final entry in scored) entry.$3];
}
List<NewHarnessOption> _harnessOptions() {
// A guest there starts Claude Code or Codex, nothing from the Store (asGuest);
// so does a new Lead.
if (asGuest || _allowedEngines != null) {
return _ranked([
for (final id in compatibleEngines)
NewHarnessOption(id: id, title: labelOf(id), engine: id),
]);
}
final machine = _machine;
final harnesses = machine != null && machine.dsh.loaded
? [
for (final entry in machine.dsh.entries)
if (!entry.isViewerPackage) entry.id,
]
: [for (final identity in knownHarnesses) identity.id];
String operationId(String id) =>
harnessForOperation(
machine?.dsh.entries ?? const <DshEntry>[],
id,
)?.id ??
canonicalHarnessId(id);
// Recent specialized harnesses, direct coding agents, then the catalog.
// A specialized harness that is not installed yet installs when it starts.
final recents = <String>{
for (final id in app.agentPreference.recentHarnesses.where(isHarnessId))
if (_offered(id)) operationId(id),
};
final rest = <String>{
for (final id in [?_harnessId, ...harnesses]) operationId(id),
}.difference(recents);
bool installed(String id) => machine?.dsh[id]?.installed != false;
NewHarnessOption row(String id) => NewHarnessOption(
id: id,
title: labelOf(id),
engine: id,
// Specialized harnesses carry their catalog description.
detail: [
machine?.dsh[id]?.tagline ??
engineIdentity(id).tagline ??
machine?.dsh[id]?.category ??
engineIdentity(id).category,
if (machine?.dsh[id]?.installed == false) 'installs first',
].whereType<String>().where((part) => part.isNotEmpty).join(' · '),
);
if (_desktopChoices) {
final engines = {for (final engine in allEngines) engine.id};
return _ranked([
for (final id in <String>{
for (final id in [
// Keep coding agents together in a stable, familiar-first order.
// Recency can reorder specialized harnesses, never this group.
'claude',
'codex',
'cursor',
'copilot',
'grok',
'opencode',
'agy',
'amp',
'kilo',
'devin',
'devin-cloud',
'cursor-cloud',
'fo',
'pi',
'hermes',
'commandcode',
'muse',
...engines,
...app.agentPreference.recentChoices.where(isHarnessId),
'autonomous/blender',
'autonomous/circuitjs',
'autonomous/godogen',
'autonomous/mujoco',
'autonomous/rdkit',
'autonomous/strudel',
'autonomous/typst',
...harnesses,
kFinderEngine,
kTerminalEngine,
])
if (isHarnessId(id)
? _offered(id)
: engines.contains(id) ||
isCloudAgentId(id) ||
id == kFinderEngine ||
id == kTerminalEngine)
isHarnessId(id) ? operationId(id) : id,
})
isHarnessId(id) ? row(id) : _engineOption(id),
]);
}
return _ranked([
for (final id in recents) row(id),
for (final id in <String>{
_engine,
...app.agentPreference.recent.where((id) => !isHarnessId(id)),
for (final engine in allEngines) engine.id,
kFinderEngine,
kTerminalEngine,
})
_engineOption(id),
for (final id in rest.where(installed)) row(id),
for (final id in rest.where((id) => !installed(id))) row(id),
]);
}
List<NewHarnessOption> _agentOptions() => _ranked([
for (final id in <String>{
_engine,
...app.agentPreference.recent,
for (final identity in allEngines) identity.id,
kFinderEngine,
kTerminalEngine,
})
if (!isHarnessId(id) && compatibleEngines.contains(id)) _engineOption(id),
]);
/// An agent's row. The Finder reads this computer's disk, so on any other
/// machine its row says so instead of opening.
NewHarnessOption _engineOption(String id) {
final finderElsewhere = isFinderEngine(id) && !canOpenFinderOn(_machine);
final ruledOut = placesLead
? integration?.leadModels?.engineRefusal(id)
: null;
return NewHarnessOption(
id: id,
title: labelOf(id),
engine: id,
enabled: !finderElsewhere && ruledOut == null,
why: finderElsewhere ? kFinderElsewhere : ruledOut,
);
}
/// Whether [machine] can be given work now — the same test that enables
/// its row below.
bool _machineUsable(MachineState machine) =>
!machine.needsLink && !machine.isOffline;
// Before any query ranks the list: this computer, then the machines that
// can take work now, then the ones that cannot (unlinked or offline). The
// local one is the choice most launches want, and an unusable machine in
// the middle of the usable ones made the list read as a jumble. Within
// each group the inventory's own order holds.
List<NewHarnessOption> _machineOptions() => _ranked(machineChoices);
/// Unfiltered choices for the Repo menu's separate machine picker. The
/// folder search must never filter the machine inventory.
List<NewHarnessOption> get machineChoices => [
for (final machine in [
...app.machineStates.values.where((m) => m.isLocalMachine),
...app.machineStates.values.where(
(m) => !m.isLocalMachine && _machineUsable(m),
),
...app.machineStates.values.where(
(m) => !m.isLocalMachine && !_machineUsable(m),
),
])
if (!machine.machine.isShared &&
(integration?.ownMachinesOnly != true ||
!machine.belongsToOtherAccount && !machine.machine.isTeamAccount))
NewHarnessOption(
id: machine.machine.machineId,
title: machine.machine.displayName,
detail: [
machine.isLocalMachine ? 'This computer' : 'Remote',
if (machine.needsLink)
'link required'
else if (machine.isOffline)
'offline',
].join(' · '),
// `isOffline`, not `nodeOnline == false`: a machine nothing has been
// heard from yet still has the machine list's word for it, and a
// computer the list calls offline cannot start an agent — offering
// it is offering a failure a minute from now.
enabled: !machine.needsLink && !machine.isOffline,
why: machine.needsLink
? '${machine.machine.displayName} is not linked to this '
'computer yet. Link it from the Machines menu.'
: '${machine.machine.displayName} is offline.',
),
];
/// Whether what is typed in the project field is a path being completed.
bool get isPathQuery => field == NewHarnessField.project && _isPath(query);
/// A notice in the box's bottom line that is not a failed create.
void warn(String message) {
error = message;
notifyListeners();
}
bool _isPath(String text) =>
text.startsWith('/') ||
text.startsWith('~') ||
text.startsWith('./') ||
text.startsWith('../') ||
text == '.' ||
text == '..' ||
(_pathsFor(_machineId, text).style == p.Style.windows &&
(p.windows.isAbsolute(text) ||
text.startsWith('.\\') ||
text.startsWith('..\\')));
String _expand(String text) {
final home = _homeOf(_machineId);
final paths = _pathsFor(_machineId, text);
if (home != null) {
if (text == '~') return home;
// `~/` keeps its slash: joined with nothing it came back as the home
// folder itself, which then read as "the folder `me` under /home" — the
// list showed one row, your own home, and Tab completed to `~/me/`.
if (text == '~/' || paths.style == p.Style.windows && text == '~\\') {
return '$home${text.substring(1)}';
}
if (text.startsWith('~/') ||
paths.style == p.Style.windows && text.startsWith('~\\')) {
return paths.join(home, text.substring(2));
}
}
// `./x` and `../x` are relative to the project the line already names —
// the box's only "here" — and to home when it names none.
if (text.startsWith('.')) {
final here = _project.folder ?? home;
if (here != null) {
final trailing = text.endsWith('/')
? '/'
: paths.style == p.Style.windows && text.endsWith('\\')
? '\\'
: '';
return '${paths.normalize(paths.join(here, text))}$trailing';
}
}
return text;
}
Iterable<String> _recentProjectFolders(String id) sync* {
final machine = app.stateOf(id);
final seen = <String>{};
// Worktrees Start made are temporary: their repository is the project.
final home = _homeOf(id);
final worktrees = home == null
? null
: _pathsFor(id, home).join(home, 'harnesses/worktrees');
for (final folder in [
if (id == _machineId) ?_project.folder,
...app.projectHistory.recent(id),
// Match the full form: explicit choices first, then known agent folders
// on this machine. Older projects need not be picked again to appear.
if (machine != null)
for (final agent in machine.agents.reversed)
if (!isInternalLaunchHarness(agent.dsh))
?machine.projectOf(agent)?.cwd,
]) {
final paths = _pathsFor(id, folder);
if (!paths.isAbsolute(folder) ||
isInternalLaunchFolder(folder) ||
folder.length > 4096 ||
RegExp(r'[\x00-\x1f\x7f]').hasMatch(folder) ||
folder != _project.folder &&
(worktrees != null && paths.isWithin(worktrees, folder) ||
folder.contains('/harnesses/worktrees/'))) {
continue;
}
if (seen.add(paths.normalize(folder))) yield folder;
}
}
List<NewHarnessOption> _recentProjects() {
final result = <NewHarnessOption>[];
for (final machine in [
...app.machineStates.values.where((m) => m.isLocalMachine),
...app.machineStates.values.where((m) => !m.isLocalMachine),
].where((m) => !m.machine.isShared)) {
final id = machine.machine.machineId;
if (_desktopChoices && id != _machineId) continue;
final folders = _recentProjectFolders(id).toList();
final names = <String, int>{};
for (final folder in folders) {
names.update(
_pathsFor(id, folder).basename(folder),
(n) => n + 1,
ifAbsent: () => 1,
);
}
for (final folder in folders) {
final name = _pathsFor(id, folder).basename(folder);
result.add(
NewHarnessOption(
id: 'project:$id:$folder',
title:
'${machine.machine.displayName}:${names[name]! > 1 ? tildePath(folder, id) : name}',
detail: location(folder, id),
project: NewHarnessProject.folder(
folder,
exact: folder == _project.folder && _project.exact,
),
machineId: id,
enabled: _machineUsable(machine),
why: machine.needsLink ? 'Link required' : 'Offline',
),
);
}
}
return result;
}
List<NewHarnessOption> _projectOptions() {
final typed = query.trim();
if (field == NewHarnessField.project) {
if (_isPath(typed)) return _pathOptions(typed);
_visibleFolder = folderRefreshError = null;
// Recent projects live in the project menu. This prompt only opens a
// folder by path or browser, so it cannot look like a second history.
total = 0;
return [_browse];
}
final slug = typed.contains('/') ? null : projectFolderSlug(typed);
final keepSuggestion = _editingSuggestedProject && typed == _project.name;
// Resolve the owning machine's home before offering an existing name.
// The daemon still reserves a fresh name atomically on submission.
final root = _expand('~/harnesses');
final paths = _pathsFor(_machineId, root);
if (slug != null && paths.isAbsolute(root)) {
if (_visibleFolder != root) {
_visibleFolder = root;
_requestListing(root);
}
} else {
_visibleFolder = folderRefreshError = null;
}
final existingName = _listings[root]
?.where((name) => name == slug)
.firstOrNull;
final existingFolder = existingName == null || keepSuggestion
? null
: paths.join(root, existingName);
return [
if (typed.isNotEmpty)
NewHarnessOption(
id: 'project:new',
synthetic: true,
title: slug == null
? 'Enter a project name'
: '${existingFolder == null ? 'Create' : 'Open existing'} $slug',
detail: slug == null
? 'Use letters or numbers, like payments'
: location('~/harnesses/$slug'),
project: existingFolder != null
? NewHarnessProject.folder(existingFolder)
: keepSuggestion
? _project
: slug == null
? null
: NewHarnessProject.fresh(typed),
machineId: _machineId,
enabled: slug != null,
why: 'Use a project name with letters or numbers. Choose Existing for a folder path.',
),
];
}
List<NewHarnessOption> _repositoryOptions() {
final repository = GitHubRepository.parse(query.trim());
return [?(repository == null ? null : _cloneRow(repository))];
}
/// What a pasted path or GitHub link offers, or null for a search. A bare
/// `owner/repo` is a search here: `team/api` is as likely a folder name.
NewHarnessOption? _pasteAction() {
final typed = query.trim();
if (typed.isEmpty) return null;
if (_isPath(typed)) return _pathAction(typed);
if (!typed.contains('github.com/') &&
!RegExp(r'^git@[^:/\s]+:').hasMatch(typed)) {
return null;
}
final repository = GitHubRepository.parse(typed);
if (repository == null) {
return const NewHarnessOption(
id: pasteInvalidId,
synthetic: true,
title: 'Not a repository link',
detail: 'Use github.com/owner/repo',
enabled: false,
why: 'Use a link to a repository, like github.com/owner/repo.',
);
}
return _cloneRow(repository);
}
/// Open for a path that names a folder, else Browse, which goes on in the
/// Open Folder prompt with what was typed.
NewHarnessOption _pathAction(String typed) {
final full = _expand(typed);
final paths = _pathsFor(_machineId, full);
final trailing =
full.endsWith('/') ||
paths.style == p.Style.windows && full.endsWith('\\');
final parent = !paths.isAbsolute(full)
? null
: trailing
? paths.normalize(full)
: paths.dirname(full);
final names = parent == null ? null : _listings[parent];
if (parent != null && names == null) _requestListing(parent);
final name = paths.basename(full);
final hidden =
!trailing &&
parent != null &&
_machine?.isLocalMachine != true &&
name.startsWith('.') &&
name != '.' &&
name != '..';
if (hidden && !_hiddenFolders.contains(full)) _askAboutHiddenFolder(full);
if (!trailing &&
(_hiddenFolders.contains(full) || names?.contains(name) == true)) {
return NewHarnessOption(
id: pasteOpenId,
synthetic: true,
title: 'Open ${tildePath(full)}',
detail: 'Folder on $machineLabel',
project: NewHarnessProject.folder(full, exact: true),
machineId: _machineId,
);
}
final shown = parent == null ? typed : tildePath(parent);
return NewHarnessOption(
id: pasteBrowseId,
synthetic: true,
title:
'Browse ${shown.endsWith(paths.separator) ? shown : '$shown${paths.separator}'}',
detail: 'Choose a folder on $machineLabel',
);
}
/// Reads this computer's `~/.ssh/config` for a pasted alias. A test gives
/// its own, so no suite reads the developer's.
@visibleForTesting
SshHosts sshHosts = SshHosts();
/// What each pasted alias stands for on this computer; absent until it is
/// asked about.
final _aliasHosts = <String, String>{};
Future<void> _resolveAlias(String alias) async {
final host = await sshHosts.resolveHost(alias);
if (_disposed) return;
// ssh that cannot say (a timeout, no ssh) has not called it another host:
// it stays offered, and the launch reads it again and says what went wrong.
if (host != null) _aliasHosts[alias] = host;
if (field == NewHarnessField.projectMenu ||
field == NewHarnessField.projectRepository) {
_refresh();
}
}
/// Cloning [repository] where the harness will run, with the account it
/// goes through: an SSH alias, or the other computer's own GitHub access.
/// Another computer's aliases are its daemon's to check, at launch.
NewHarnessOption _cloneRow(GitHubRepository repository) {
if (isTerminal) {
return NewHarnessOption(
id: pasteInvalidId,
synthetic: true,
title: "A terminal can't clone",
detail: 'Choose an agent to clone ${repository.slug}',
enabled: false,
why: 'Choose an agent to clone ${repository.slug}.',
);
}
final alias = repository.alias;
final local = _machine?.isLocalMachine == true;
if (local && alias != null) {
final host = _aliasHosts[alias];
if (host == null) {
// Offered as GitHub until ssh says otherwise: no flicker for the
// usual alias, and a launch checks again before it clones.
_aliasHosts[alias] = 'github.com';
unawaited(_resolveAlias(alias));
} else if (!isGitHubHost(host)) {
return NewHarnessOption(
id: pasteInvalidId,
synthetic: true,
title: "$alias isn't a GitHub host",
detail: 'Only GitHub repositories can be cloned here',
enabled: false,
why: '$alias does not lead to github.com on this computer.',
);
}
}
return NewHarnessOption(
id: cloneId,
synthetic: true,
title: 'Clone ${repository.slug}',
detail: [
if (alias != null) 'over SSH as $alias',
local
? 'into ${location('~/harnesses/${repository.name}')}'
: 'on $machineLabel · uses that computer’s GitHub access',
].join(' · '),
project: NewHarnessProject.clone(repository),
machineId: _machineId,
);
}
/// The most folders one listing offers. `node_modules` has five thousand; a
/// list nobody scrolls that far costs a row object each, every keystroke.
/// Typing narrows it, and the count still says how many there really are.
static const maxPathRows = 200;
/// The last path list built, and what it was built from: a keystroke that
/// changes neither the folder nor the stem (or a tick that changes nothing)
/// gets the same list back instead of thousands of new rows.
(String, String, List<String>)? _pathKey;
List<NewHarnessOption> _pathRows = const [];
int _pathTotal = 0;
int _pathHits = 0;
int? _pathMatched;
/// zsh's path completion: the folders under what has been typed so far.
List<NewHarnessOption> _pathOptions(String typed) {
final full = _expand(typed);
final paths = _pathsFor(_machineId, full);
if (!paths.isAbsolute(full)) {
_visibleFolder = folderRefreshError = null;
total = 0;
return [_browse, _changeMachine];
}
final trailing =
full.endsWith('/') ||
paths.style == p.Style.windows && full.endsWith('\\');
final parent = trailing ? paths.normalize(full) : paths.dirname(full);
// While Tab is cycling the candidates, the line holds one of them but the
// list stays the list of the stem that was typed — a completion menu.
final stem = (_cycle?.stem ?? (trailing ? '' : paths.basename(full)))
.toLowerCase();
final names = _listings[parent];
if (_visibleFolder != parent) {
_visibleFolder = parent;
_requestListing(parent);
}
if (names == null) {
total = 0;
return const [];
}
final key = (parent, stem, names);
if (_pathKey != null &&
_pathKey!.$1 == parent &&
_pathKey!.$2 == stem &&
identical(_pathKey!.$3, names)) {
total = _pathTotal;
_pathMatched = _pathHits;
return _pathRows;
}
// Dot-folders are offered only once a dot is typed, as `ls` hides them; the
// count is of what is on offer.
final dots = stem.startsWith('.');
var offered = 0;
final rows = <NewHarnessOption>[
_browse,
if (stem.isEmpty && parent != '/')
NewHarnessOption(
id: 'project:$parent',
title: paths.basename(parent),
detail: 'Use ${location(parent)}',
project: NewHarnessProject.folder(parent, exact: true),
synthetic: true,
),
];
var matched = 0;
for (final name in names) {
if (!dots && name.startsWith('.')) continue;
offered++;
if (!name.toLowerCase().startsWith(stem)) continue;
if (++matched > maxPathRows) continue;
final folder = paths.join(parent, name);
rows.add(
NewHarnessOption(
id: 'project:$folder',
title: name,
detail: location(folder),
project: NewHarnessProject.folder(folder, exact: true),
),
);
}
rows.add(_changeMachine);
_pathKey = key;
_pathRows = rows;
total = _pathTotal = offered;
_pathMatched = _pathHits = matched;
return rows;
}
Timer? _listDebounce;
static const _maxListings = 16;
/// ~ always means the home of the selected machine's account. The browser
/// protocol resolves an omitted path to that home; no local path is guessed.
Future<String?> _ensureHome(String id) {
if (app.stateOf(id)?.isLocalMachine == true) return Future.value(_home);
return _homeRequests.putIfAbsent(id, () async {
try {
final answer = await app.listRemoteFolder(id, null);
final home = answer['path'];
if (_disposed ||
home is! String ||
!_pathsFor(id, home).isAbsolute(home)) {
return null;
}
_homes[id] = home;
if (id == _machineId) _refresh();
return home;
} catch (_) {
// Display the full path until this machine can resolve its home.
return null;
}
});
}
static const _startingLine = 'Starting harness…';
/// A repository whose checkout is already there is used, not cloned, and the
/// line said Cloning for that moment anyway. Only the preparation decides,
/// and on another computer it says nothing until it is done, so look at the
/// same place first and leave the creation itself waiting on nothing.
Future<void> _sayWhenCloning(
GitHubRepository repository,
AgentCreationAttempt attempt,
) async {
final free = await _cloneDestinationIsFree(repository);
if (!free ||
_disposed ||
!busy ||
!identical(attempt, _attempt) ||
status != _startingLine) {
return;
}
status = 'Cloning ${repository.slug}…';
notifyListeners();
}
/// Whether nothing is at `<projects folder>/<name>` where the harness will
/// run. Saying nothing about a clone is less wrong than announcing one that
/// is not happening, so false also covers a computer that cannot say.
Future<bool> _cloneDestinationIsFree(GitHubRepository repository) async {
final id = _machineId;
final home = await _ensureHome(id);
if (home == null) return false;
final root = _pathsFor(id, home).join(home, 'harnesses');
if (app.stateOf(id)?.isLocalMachine == true) {
final kind = await FileSystemEntity.type(
p.join(root, repository.name),
followLinks: false,
);
return kind == FileSystemEntityType.notFound;
}
// fs_list_dir (cli fsBrowse.ts) leaves hidden folders out: `.github` would
// look free whether it is there or not.
if (repository.name.startsWith('.')) return false;
// This app is not told which folder that computer's daemon uses: Harness OS
// keeps its projects in ~/projects (cli projectsRoot). A case-insensitive
// disk holds `Repo` as `repo`, so any spelling may be the same folder.
final name = repository.name.toLowerCase();
for (final folder in [root, _pathsFor(id, home).join(home, 'projects')]) {
final answer = await app.listRemoteFolder(id, folder);
// The first clone on that computer: the folder is made for it.
if (answer['error'] == 'NOT_FOUND') continue;
final entries = answer['entries'];
if (answer['error'] != null ||
entries is! List ||
answer['truncated'] == true) {
return false;
}
final listed = entries.any(
(entry) =>
entry is Map &&
entry['name'] is String &&
(entry['name'] as String).toLowerCase() == name,
);
if (listed) return false;
}
return true;
}
/// Folders another computer has said are there though their parent's listing
/// leaves them out: fs_list_dir (cli fsBrowse.ts) hides dot folders, so each
/// is asked about by its own path. Not a [_listings] entry: a failed listing
/// is kept there as empty, and here that would read as a folder.
final _hiddenFolders = <String>{};
Timer? _hiddenFolderDebounce;
/// The folder last asked about. A refresh runs the path row again, and the
/// parent's listing arriving is one: without this each pushed the question
/// back, or asked it twice.
String? _hiddenFolderAsked;
void _askAboutHiddenFolder(String folder) {
if (_hiddenFolderAsked == folder) return;
_hiddenFolderAsked = folder;
_hiddenFolderDebounce?.cancel();
_hiddenFolderDebounce = Timer(
const Duration(milliseconds: 80),
() => unawaited(_readHiddenFolder(folder)),
);
}
Future<void> _readHiddenFolder(String folder) async {
final id = _machineId;
final revision = _machineRevision;
final answer = await app.listRemoteFolder(id, folder);
if (_disposed || id != _machineId || revision != _machineRevision) return;
if (answer['error'] != null || answer['entries'] is! List) return;
_hiddenFolders.add(folder);
if (field == NewHarnessField.project ||
field == NewHarnessField.projectMenu) {
_refresh();
}
}
/// Ask for [folder]'s listing. A local folder is read at once, off this
/// isolate; another machine's is asked for only once the typing pauses — each
/// keystroke through `~/code/au` would otherwise be a round trip whose answer
/// nobody is waiting for any more.
void _requestListing(String folder) {
if (_listing == folder) return;
_listing = folder;
folderRefreshError = null;
_listDebounce?.cancel();
if (_loadingFolders.contains(folder)) return;
if (_machine?.isLocalMachine == true) {
unawaited(_list(folder));
} else {
_listDebounce = Timer(
const Duration(milliseconds: 80),
() => unawaited(_list(folder)),
);
}
}
Future<void> _list(String folder) async {
if (_disposed || !_loadingFolders.add(folder)) return;
final machineId = _machineId;
final revision = _machineRevision;
var names = <String>[];
var failed = false;
try {
if (_machine?.isLocalMachine == true) {
// Five thousand entries streamed through the UI isolate's event loop
// is five thousand events between two frames; read them elsewhere.
names = await Isolate.run(() {
final found = <String>[];
for (final entry in Directory(folder).listSync(followLinks: true)) {
if (entry is Directory) found.add(p.basename(entry.path));
}
return found;
});
} else {
final answer = await app.listRemoteFolder(_machineId, folder);
final entries = answer['entries'];
if (answer['error'] == null && entries is List) {
names = [
for (final entry in entries)
if (entry is Map &&
entry['isDir'] == true &&
entry['name'] is String)
entry['name'] as String,
];
} else {
failed = true;
}
}
} catch (_) {
failed = true;
}
if (_disposed || machineId != _machineId || revision != _machineRevision) {
return;
}
_loadingFolders.remove(folder);
names.sort((a, b) => compareNatural(a.toLowerCase(), b.toLowerCase()));
if (!failed || !_listings.containsKey(folder)) {
_listings.remove(folder);
_listings[folder] = names;
}
// Recently listed folders stay; a long walk does not keep every one.
while (_listings.length > _maxListings) {
_listings.remove(_listings.keys.first);
}
// An answer for a folder the line has already left is kept, not shown.
final current = _listing == folder;
if (current) {
_listing = null;
folderRefreshError = failed
? 'Couldn’t refresh folders. Try again.'
: null;
}
if (current &&
(field == NewHarnessField.project ||
field == NewHarnessField.projectName ||
field == NewHarnessField.projectMenu)) {
_refresh();
}
}
// ---- making it ----------------------------------------------------------
/// One attempt per harness, kept across a lost reply: a create whose answer
/// never came back may have worked, and asking again must ask the machine
/// what happened to THAT request rather than start a second harness.
AgentCreationAttempt? _attempt;
final HarnessLaunchIntegration? integration;
String get actionLabel => _project.newRepository == null
? integration?.actionLabel ?? 'New Harness'
: _repositoryFailed
? 'Try again'
: 'Create and continue in GitHub';
// ---- New Repository (task #3374) ---------------------------------------
/// New Project in a Swarm whose server can create repositories.
bool get offersNewRepository =>
placesLead &&
integration?.createRepository != null &&
integration?.newRepositoryOwners != null;
/// Opens New Repository's prompt; the form sets it.
VoidCallback? onNewRepository;
/// The last create made nothing: Start reads Try again.
bool _repositoryFailed = false;
/// GitHub's sign-in is out in the browser: Check again reads the Swarm.
bool repositoryWaiting = false;
/// The repository named in New Repository's prompt, to create at Start.
void chooseNewRepository(NewRepositoryAsk ask) {
if (locked) return;
_project = NewHarnessProject.newRepository(ask);
_repositoryFailed = false;
error = null;
field = NewHarnessField.launch;
query = '';
_cycle = null;
_refresh(resetCursor: true);
}
/// Under the composer: what Start does with a repository to create.
String? get newRepositoryNote => switch (_project.newRepository) {
final ask? =>
'Creates ${ask.slug} on GitHub, then clones it on '
'${leadMachine?.name ?? machineLabel}',
null => null,
};
/// Creates [ask] through the person's GitHub sign-in, then starts as for
/// the repository it made; nothing starts when nothing was made.
Future<NewHarnessOutcome> _createRepository(NewRepositoryAsk ask) async {
final make = integration?.createRepository;
if (make == null) {
return _fail('Update Harness to create a repository here.');
}
busy = true;
error = null;
repositoryWaiting = true;
status = 'Creating ${ask.slug}…';
notifyListeners();
final NewRepositoryCreated made;
try {
made = await make(ask, task.trim());
} catch (failure) {
repositoryWaiting = false;
_repositoryFailed = true;
return _fail(failure.toString());
}
repositoryWaiting = false;
if (_disposed) return NewHarnessOutcome.failed;
final repository = GitHubRepository.parse(made.repositoryUrl);
if (repository == null) {
_repositoryFailed = true;
return _fail('GitHub gave an address Harness can’t read.');
}
busy = false;
status = null;
_repositoryFailed = false;
_project = NewHarnessProject.clone(repository);
notifyListeners();
return create();
}
bool get needsAttachmentReview =>
integration?.needsAttachmentReview?.call() == true;
String get pendingActionLabel =>
needsAttachmentReview ? 'Review files' : 'Check status';
/// The person has been told a typed task will not be sent, and pressed again.
bool _dropAccepted = false;
/// A reply was lost; Return now checks on it instead of creating again.
bool get checking =>
_attempt?.awaitingConfirmation == true || integration?.pending == true;
bool get canCancelPending => _attempt?.canCancelPending == true;
bool get canFollowPending => _attempt?.canFollowPending == true;
/// The folder a new project's typed name found already there
/// (`PROJECT_EXISTS`), with the project and machine it was refused for.
(String, NewHarnessProject, String)? _existing;
/// That folder, while the same name on the same machine is still the
/// choice: what "Use the existing folder" starts in ([useExistingFolder]).
/// A name somebody chose is never quietly changed, so nothing starts there
/// until they press it; the refusal alone left them to retype the name as
/// a path (PROJECT_EXISTS was 4 of 7 failed starts on Oct 18).
String? get existingFolder => switch (_existing) {
(final folder, final project, final machine)
when !busy && project == _project && machine == _machineId =>
folder,
_ => null,
};
/// Switches Project to [existingFolder] on the same machine and starts the
/// harness there, as if the person had picked that folder.
Future<NewHarnessOutcome> useExistingFolder({bool? resendAttachments}) {
final folder = existingFolder;
if (folder == null || locked) return Future.value(NewHarnessOutcome.failed);
_existing = null;
_project = NewHarnessProject.folder(folder, exact: true);
if (_desktopChoices) _syncGitProject();
error = null;
notifyListeners();
return create(resendAttachments: resendAttachments);
}
/// The check [followHeld] is making. Nobody pressed for it, so it shows
/// nothing until it has an answer.
Future<NewHarnessOutcome>? _following;
/// Asks after a request the machine holds or is starting, without pressing
/// Check status. The machine starts a held harness by itself (an agent it is
/// installing, a model waking). The line said "Installing Kilo. The harness
/// starts once it is installed." and stayed after Kilo had started, with no
/// pane, until Check status was pressed (desktop 1.2.65, a fresh Ubuntu VM,
/// 2026-10-12). Created once it has started; failed while it still waits,
/// or when it was refused, which the line then says.
Future<NewHarnessOutcome> followHeld() {
if (_following case final check?) return check;
if (_disposed || busy || !canFollowPending) {
return Future.value(NewHarnessOutcome.failed);
}
final check = create(quiet: true);
_following = check;
return check.whenComplete(() => _following = null);
}
Future<void> cancelPending() async {
// A check nobody pressed for is let finish: it holds `busy` for a moment
// without saying so, and a Cancel pressed just then must still count.
if (_following case final check?) {
await check;
if (_disposed) return;
}
if (busy || !canCancelPending) return;
busy = true;
notifyListeners();
final problem = await app.cancelAgentCreation(_attempt!);
if (_disposed) return;
busy = false;
if (problem == null) {
_attempt = null;
error = null;
status = 'Creation cancelled.';
} else {
error = problem;
}
notifyListeners();
}
/// Only while a request is being recovered: once its creation failed, the
/// form is the person's again and Discard would delete what they retry.
bool get canDiscardPending =>
integration?.pending == true && integration?.discard != null;
/// The destination dropped its request; the form is closed, not reused.
bool get discarded => _discarded;
bool _discarded = false;
/// Drops a request the destination cannot finish. Null once it is gone or
/// kept (which the line then says), else the question to confirm before
/// dropping it anyway.
Future<String?> discardPending({bool anyway = false}) async {
final discard = integration?.discard;
if (busy || discard == null) return null;
busy = true;
error = null;
status = 'Discarding the request…';
notifyListeners();
try {
final question = await discard(anyway: anyway);
if (_disposed) return null;
busy = false;
status = null;
if (question == null) {
_discarded = true;
_attempt = null;
integration!
..pending = false
..resume = null
..discard = null;
}
notifyListeners();
return question;
} catch (failure) {
_fail(failure.toString());
return null;
}
}
bool _warnedAboutClosing = false;
/// Every dismissal path observes the same in-flight receipt and completion.
/// A second explicit dismissal acknowledges an unresolved creation.
bool requestDismiss() {
if (linkingProfile) {
warn('Linking the profile. You can close once it is done.');
return false;
}
if (busy && integration?.stopBuddy?.call() != true) {
warn('Still working on it. You can close once it is done.');
return false;
}
if (checking && !_warnedAboutClosing) {
_warnedAboutClosing = true;
warn(
canCancelPending
? 'Your request is saved and will continue when the model is available. Cancel request to prevent that, or close again to leave it waiting.'
: _desktopChoices
? 'The harness may already exist. Check status to find it, or click Close again to leave this form.'
: 'The harness may already exist. Return checks on it; Escape again '
'closes without knowing.',
);
return false;
}
return !endCompletion();
}
/// [quiet] is [followHeld]'s: a check on a held request that changes
/// nothing on screen until it has an answer.
Future<NewHarnessOutcome> create({
bool quiet = false,
bool? resendAttachments,
}) async {
if (busy || linkingProfile) {
return NewHarnessOutcome.failed;
}
final resume =
resendAttachments != null && integration?.resolveAttachments != null
? () => integration!.resolveAttachments!(resendAttachments)
: integration?.resume;
if (resume != null) {
busy = true;
status = 'Checking on the harness…';
notifyListeners();
try {
await resume();
busy = false;
integration!.pending = false;
return NewHarnessOutcome.created;
} catch (failure) {
return _fail(failure.toString());
}
}
if (bringsBuddy) return _startBuddy();
if (!checking && usesProfile && _profile != null) {
if (loadingProfiles) {
return _fail(
'Profiles are still loading. Try again when they are ready.',
);
}
final validation = refreshProfiles();
busy = true;
status = 'Checking profile…';
notifyListeners();
await validation;
if (_disposed) return NewHarnessOutcome.failed;
busy = false;
status = null;
if (!_profilesLoaded) {
focusField(NewHarnessField.profile);
return _fail(
'Could not verify this profile. Choose a profile or refresh to retry.',
);
}
}
if (requiredChoice case final choice?) {
focusField(choice.field);
return _fail(choice.message);
}
if (integration != null && (isCloud || !takesTask)) {
return _fail(
'Choose an agent that runs on a machine, such as Claude Code or Codex.',
);
}
if (isCloud) return _createCloud();
// Whoever starts it, New Project never starts a Product Manager on a
// machine the person did not choose, or one that cannot run it.
if (placesLead) {
if (leadBlocked case final why?) return _fail(why);
}
if (_project.newRepository case final ask?) return _createRepository(ask);
if (leadThroughSwarm) return _startInSwarm();
if (!checking) {
_syncGitProject();
if (gitError != null) retryGitProject();
if (checkingGit) {
busy = true;
status = 'Checking project…';
notifyListeners();
await _gitFuture;
if (_disposed) return NewHarnessOutcome.failed;
busy = false;
status = null;
}
if (requiredChoice case final choice?) {
focusField(choice.field);
return _fail(choice.message);
}
if (gitError != null) {
return _fail(
'Could not check Git on $machineLabel. Check the connection and Harness CLI, then retry.',
);
}
if (!worktree && _branchRef?.startsWith('refs/remotes/') == true) {
return _fail('Choose a local branch, or turn Worktree on.');
}
if (worktreePlan case final plan?
when plan.kind == WorktreeStart.unavailable) {
return _fail(
'${plan.branch} is the project folder’s branch. Turn Worktree off to work on it there, or name a new branch.',
);
}
// Switching the folder's branch would move it under a harness at work.
final folder = _project.folder;
final ref = branchRef;
if (!worktree &&
folder != null &&
(_branchHere != null ||
ref != null &&
ref != currentBranchRef(_gitProject) &&
_worktreeOf(ref) == null) &&
(_machine?.agents ?? const []).any((agent) {
final cwd = _machine?.projectOf(agent)?.cwd;
final root = _gitProject.root ?? folder;
final paths = _pathsFor(_machineId, root);
return cwd != null &&
(paths.equals(cwd, root) || paths.isWithin(root, cwd));
})) {
return _fail(
'A harness is working in this folder, so its branch can’t be switched. Turn Worktree on, or stay on $branchLabel.',
);
}
}
// Shortened by the person, never cut by us: a machine refuses one longer.
if (takesTask && taskTooLong && !checking) {
return _fail(
'A first message can be $kFirstTaskMaxLength characters; '
'this is ${task.trim().length}.',
);
}
// A task typed for an agent that cannot take one is said BEFORE the
// harness is made, on every path — ⌘↵ from the agent field went straight
// past the notice that choosing the agent shows. The second press means it.
if (!takesTask && task.trim().isNotEmpty && !checking && !_dropAccepted) {
_dropAccepted = true;
return _fail(
'$agentLabel cannot start on a first message, so “${_short(task)}” '
'will not be sent. Press again to make it anyway.',
);
}
if (isFinder && !canOpenFinderOn(_machine)) return _fail(kFinderElsewhere);
final machine = _machine;
if (machine == null) {
error = 'Choose a machine.';
notifyListeners();
return NewHarnessOutcome.failed;
}
final choice = _engine;
// A guest starts the engine itself, in its own space, on the owner's plans (asGuest).
var harness = asGuest ? null : _harnessId;
final model = asGuest ? null : _model;
final terminal = isTerminalEngine(choice);
final base = _base;
// The daemon's launch installs a missing engine inside its new terminal.
// A cached availability probe must not block that first launch.
final recheck = checking;
if (!recheck) {
_attempt = AgentCreationAttempt(
background: integration != null,
beforeSubmit: integration?.beforeSubmit,
launchModel: leadLaunchModel,
);
_existing = null;
_warnedAboutClosing = false;
_installing = null;
}
final attempt = _attempt!;
busy = true;
if (!(quiet && recheck)) {
error = null;
status = recheck ? 'Checking on the harness…' : _startingLine;
notifyListeners();
}
if (!recheck && !asGuest) {
// What is sent, not what is shown: a terminal takes no project.
if (projectFolderRequest?.repository case final repository?) {
unawaited(_sayWhenCloning(repository, attempt));
}
}
if (model != null && !recheck) {
await refreshModels();
if (_disposed) return NewHarnessOutcome.failed;
if (!_modelAvailable(model)) {
return _fail(
'The selected model is unavailable for $agentLabel on $machineLabel. Choose a model or use your subscription.',
);
}
}
if (harness != null && !recheck) {
await app.probeDsh(_machineId, force: true);
if (_disposed) return NewHarnessOutcome.failed;
if (!machine.dsh.loaded && machine.dsh.error != null) {
return _fail(
'Update Harness CLI on ${machine.machine.displayName} to create a '
'${labelOf(harness)} harness.',
);
}
if (!_offered(harness)) {
busy = false;
focusField(NewHarnessField.harness);
return _fail(
'$harnessLabel is unavailable. Choose an agent or harness.',
);
}
harness =
harnessForOperation(machine.dsh.entries, harness)?.id ?? harness;
if (machine.dsh[harness]?.installed == false) {
status = 'Installing ${labelOf(harness)}… this can take a few minutes';
_installing = harness;
notifyListeners();
final failure = await app.installDsh(_machineId, harness);
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) return _fail(failure);
_installing = null;
await app.probeDsh(_machineId, force: true);
if (_disposed) return NewHarnessOutcome.failed;
status = 'Starting harness…';
notifyListeners();
}
final compatible =
machine.dsh[harness]?.supportedEngines ?? compatibleEngines;
if (!compatible.contains(base)) {
return _fail(
'$harnessLabel does not support ${labelOf(base)} on $machineLabel. Choose a compatible agent.',
);
}
}
final permissionMode = hasModes ? mode : null;
final bypass =
permissionMode != null && permissionModeApproves(permissionMode);
final folder = _project.folder;
final firstMessage = task.trim();
String launchMessage = firstMessage;
if (integration case final destination?) {
try {
launchMessage = destination.preparedPrompt ??= await destination
.prepare(_machineId, firstMessage, base);
} catch (failure) {
return _fail(failure.toString());
}
}
// Files ride into the live terminal after creation, and the task follows
// them there (see deliverAttachedTask), so neither is a launch argument.
final files = takesTask
? attachments?.files ?? const <HarnessAttachment>[]
: const <HarnessAttachment>[];
if (files.isNotEmpty && !canAttachFiles(app, _machineId)) {
return _fail(
'Update Harness CLI on $machineLabel to attach files, or remove them.',
);
}
if (integration?.stageAttachments case final stage? when !recheck) {
try {
await stage(files, launchMessage);
} catch (failure) {
return _fail(failure.toString());
}
}
final launchSetup = LaunchSetup(
engine: base,
harnessId: harness,
permissionMode: permissionMode ?? kDefaultPermissionMode,
model: model,
profile: base == 'codex' && model == null && !asGuest ? _profile : null,
profileMachineId: _machineId,
);
// Working in a picked worktree says nothing about the next harness's.
final launchedWorktree =
_recoveredWorktreePreference ??
(choosesBranch && !inWorktree ? worktree : null);
// A destination's journal keeps them for a later recovery's form.
// Only a real folder: a new project's or a clone's label is no path, and a
// recovery that unlocks the form after a failure would send it as one.
integration
?..engine = base
..folder = folder;
final failure = await app.createAgent(
_machineId,
engine: base,
// A guest's harness starts in its workspace, or a folder the owner shares (asGuest).
folder: asGuest
? (_project.folder ?? '')
: (terminal ? folder : folder ?? ''),
projectFolder: asGuest ? null : projectFolderRequest,
swarmId: _targetId,
split: split,
placement: effectivePlacement,
bypassPermission: bypass,
permissionMode: permissionMode,
codexHome: base == 'codex' && model == null && !asGuest
? _profile?.path
: null,
model: model,
dsh: harness,
swarmRole: integration?.swarmRole,
swarmSkillMode: integration?.swarmSkillMode,
// Sent exactly as written; an agent that cannot take one is never sent it.
prompt: takesTask && files.isEmpty && launchMessage.isNotEmpty
? launchMessage
: null,
// A new project named by the person, or after its task, names the agent
// too — until the engine titles the session. So does a first message
// sent into an existing folder: a returning user's second harness in
// their project read "Untitled Pane" until the engine titled it (fresh
// macOS VM, 2026-10-08). Only a harness started with nothing to say is
// left to the machine ("Solder harness 9-18 13:02").
name:
projectFolderRequest?.agentName ??
(takesTask && firstMessage.isNotEmpty
? taskProjectTitle(firstMessage)
: null),
attempt: attempt,
);
// Before the disposed check: on an empty tab the new pane replaces this
// box as soon as it opens, disposing it while createAgent returns — and
// the files still have to follow the harness there.
final destination = integration;
if (failure == null && attempt.agentId != null && destination != null) {
destination.pending = true;
try {
if (!destination.completed) {
destination.launchModelRefused = attempt.launchModelRefused;
await destination.complete(_machineId, attempt.agentId!);
destination.completed = true;
}
destination.pending = false;
} catch (problem) {
// The destination says what started and what did not.
return _fail(problem.toString());
}
}
if (failure == null &&
files.isNotEmpty &&
destination?.stageAttachments == null) {
_deliverFiles(attempt.agentId, files, launchMessage);
}
if (failure == null && isFinder && attempt.agentId != null) {
final root = attempt.preparedFolder ?? folder;
final problem = root == null
? 'The chat has no folder for the Finder to show.'
: app.openFinderBeside(_machineId, attempt.agentId!, root);
if (problem != null) return _fail('Chat started. $problem');
}
// Creation can replace an embedded form before this future returns. Save
// the confirmed choices even if that form has already been disposed. A
// Finder's chat is remembered as its agent; the Finder itself is not.
if (failure == null && attempt.agentId != null) {
unawaited(
app.agentPreference.remember(
choice,
harnessId: harness,
setup: launchSetup,
worktree: worktreeToRemember,
),
);
}
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) {
if (!checking) integration?.preparedPrompt = null;
// A folder already made for this attempt is the project now: a retry
// goes into it rather than making a second one beside it.
if (!checking && attempt.preparedFolder != null) {
_recoveredWorktreePreference = launchedWorktree;
_project = NewHarnessProject.folder(
attempt.preparedFolder!,
// A picked worktree prepared in place is still the one picked.
exact: _project.exact && attempt.preparedFolder == _project.folder,
);
_gitKey = (_machineId, _project.folder, _noGitSetup);
_worktree = false;
_branchRef = null;
_gitProject = const GitProjectInfo();
_gitFuture = _readGitProject(_gitKey!);
}
final project = _project;
_existing =
attempt.refusal == 'PROJECT_EXISTS' &&
project.isNew &&
project.repository == null &&
project.generated == null &&
project.name != null
? switch (attempt.existingFolder) {
final folder? => (folder, project, _machineId),
null => null,
}
: null;
return _fail(failure);
}
busy = false;
status = null;
return NewHarnessOutcome.created;
}
/// A cloud harness: made by the cloud service on this machine (CLI
/// services/cloud.ts), which starts it at its maker; no folder, no install.
/// New Project's Product Manager the Swarm starts
/// ([HarnessLaunchIntegration.startInSwarm]) on [leadSwarmMachine].
/// Join's Buddy (task #4196): the Swarm starts it on the chosen computer,
/// as before this form; the form chose only its engine and computer.
Future<NewHarnessOutcome> _startBuddy() async {
busy = true;
error = null;
status = 'Starting your Buddy on $machineLabel…';
notifyListeners();
try {
await integration!.startBuddy!(_machineId, _base);
} catch (failure) {
return _fail(failure.toString());
}
integration?.completed = true;
if (_disposed) return NewHarnessOutcome.created;
busy = false;
status = null;
notifyListeners();
return NewHarnessOutcome.created;
}
Future<NewHarnessOutcome> _startInSwarm() async {
final start = integration?.startInSwarm;
if (start == null) {
return _fail(
'Update Harness to start a Product Manager on another machine.',
);
}
if (leadBlocked case final why?) return _fail(why);
busy = true;
error = null;
status =
'Asking ${leadMachine?.name ?? 'the machine'} to start the Product Manager…';
notifyListeners();
try {
await start(
LeadSwarmStart(
machineId: _swarmLeadMachine!,
engine: _engine,
repositoryUrl: leadRepositoryUrl,
title: _leadRepositoryName,
task: task.trim(),
files: attachments?.files ?? const [],
),
);
} catch (failure) {
return _fail(failure.toString());
}
integration?.completed = true;
if (_disposed) return NewHarnessOutcome.created;
busy = false;
status = null;
attachments?.clear();
notifyListeners();
return NewHarnessOutcome.created;
}
Future<NewHarnessOutcome> _createCloud() async {
busy = true;
error = null;
status = 'Starting $agentLabel…';
notifyListeners();
final failure = await app.createCloudHarness(
_machineId,
engine: _engine,
prompt: task.trim(),
repositoryUrl: cloudAgentTakesRepository(_engine)
? cloudRepository
: null,
acuLimit: _engine == 'devin-cloud' ? acuLimit : null,
swarmId: _targetId,
split: split,
placement: effectivePlacement,
);
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) return _fail(failure);
busy = false;
status = null;
return NewHarnessOutcome.created;
}
/// Hands a created harness its files and then its task, detached from this
/// box, which may already be gone ([deliverAttachedTask]).
void _deliverFiles(
String? agentId,
List<HarnessAttachment> files,
String task,
) {
final report = attachments?.onDeliveryProblem;
if (!_disposed) attachments?.clear();
if (agentId == null) {
report?.call(
'The harness started without its files. Attach them in its pane.',
);
return;
}
unawaited(
deliverAttachedTask(
app,
machineId: _machineId,
agentId: agentId,
files: files,
task: task,
).then((problem) {
if (problem != null) report?.call(problem);
}),
);
}
NewHarnessOutcome _fail(String message) {
busy = false;
status = null;
error = message;
if (!_disposed) notifyListeners();
return NewHarnessOutcome.failed;
}
@override
void dispose() {
_disposed = true;
// Its files were copied out for delivery; only the list goes.
attachments?.dispose();
_appTick?.cancel();
_projectRefresh?.cancel();
_listDebounce?.cancel();
_hiddenFolderDebounce?.cancel();
app.removeListener(_onApp);
_modelUsage?.removeListener(_refresh);
if (_ownsModelUsage) _modelUsage?.dispose();
super.dispose();
}
}
/// The Product Manager's default (backend projects.ts BUILT_IN_ROLE_DEFAULTS):
/// `opus` is Claude Code's name for its newest Opus, Opus 5.5.
const kLeadModel = (model: 'opus', label: 'Opus 5.5', effort: 'xhigh');