Skip to content

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.

Use working project and successful launch settings for Cmd-N (#607)

Dee8e862aa964dd
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index 5df450f95..9c4a40ef3 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -489,4 +489,15 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
expect(await readFile(join(linked, 'src', 'value'), 'utf8')).toBe('feature')
expect(await git('branch', '--show-current')).toBe('main')
})
+
+ it.each(['No space left on device', 'Disk quota exceeded'])('explains worktree disk exhaustion: %s', async (message) => {
+ const hooks = join(root, 'hooks')
+ await mkdir(hooks)
+ await writeFile(join(hooks, 'post-checkout'), `#!/bin/sh\necho 'private-file: ${message}' >&2\nexit 1\n`, { mode: 0o755 })
+ await git('config', 'core.hooksPath', hooks)
+ await expect(prepare('worktree')).rejects.toMatchObject({
+ code: 'WORKTREE_FAILED',
+ message: 'Not enough disk space to create the worktree. Free space on this machine, then retry.',
+ })
+ })
})
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index 2a8d028ad..03c3666e0 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -12,6 +12,13 @@ export class GitProjectError extends Error {
constructor(readonly code: string, message: string) { super(message) }
}
+const worktreeDiskFull = 'Not enough disk space to create the worktree. Free space on this machine, then retry.'
+function diskFull(error: unknown): boolean {
+ const failure = error as { code?: string; stderr?: string }
+ return failure?.code === 'ENOSPC' || failure?.code === 'EDQUOT' ||
+ /no space left on device|disk quota exceeded/i.test(failure?.stderr ?? '')
+}
+
export function validGitPath(path: unknown): path is string {
return typeof path === 'string' && isAbsolute(path) && path.length <= 4096 && !/[\x00-\x1f\x7f]/.test(path)
}
@@ -281,7 +288,10 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
try { await mkdir(folder); destination = folder }
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
}
- } catch { destination = undefined }
+ } catch (error) {
+ if (diskFull(error)) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)
+ destination = undefined
+ }
if (!destination) throw new GitProjectError('WORKTREE_FAILED', 'Could not create a worktree folder. Check folder permissions, then retry.')
const remote = remoteBranch(options.ref)
try {
@@ -303,8 +313,9 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
: remote && remote.branch === branch
? ['worktree', 'add', '--track', '-b', branch, '--', destination, options.ref!]
: ['worktree', 'add', '--no-track', '-b', branch, '--', destination, head], 120_000)
- } catch {
+ } catch (error) {
// Keep any partial checkout and branch available for recovery.
+ if (diskFull(error)) throw new GitProjectError('WORKTREE_FAILED', worktreeDiskFull)
throw new GitProjectError('WORKTREE_FAILED', `Could not create the worktree at ${destination}. Check Git and folder permissions, then retry.`)
}
// Harness made this branch: its cleanup may remove it, and a made-up name gives way to the session's.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index 1e5d5eb60..d36422966 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -24,4 +24,5 @@ and [new-harness-entry-rules.md](design/new-harness-entry-rules.md).
The full visual migration is tracked in
[desktop-ui-migration.md](design/desktop-ui-migration.md). Preserve core UX,
-controller reuse, keyboard/IME behavior, drafts, pending receipts, and scope.
+controller reuse, keyboard/IME behavior, pending receipts, and scope. Ordinary
+Cmd-N forms start fresh after dismissal; see the entry rules above.
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index 0d34cd5fa..9f2e1bb83 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -64,9 +64,9 @@ from the control that owns it.
| What should happen? | Prompt, then the terminal's work | The task remains the focal point |
| Where is the project? | Project selector; machine inside its search row | A folder belongs to a machine; its path is not globally interchangeable |
| Which agent or specialized harness? | Agent selector, with its real mark | A specialized harness can run with an agent framework: “Run Blender with” |
-| Which model and effort? | Model control and its options | Available models belong to the selected agent and connection |
+| Which model? | Model control and its options | Available models belong to the selected agent and connection |
| What may it do? | Visible approvals control | Preserve the explicit setting; never hide a permission change behind styling |
-| How is the work isolated? | Worktree and branch together | Fresh main default, remembered worktree choice, reviewed draft kept intact |
+| How is the work isolated? | Worktree and branch together | Fresh main default, worktree remembered after a successful Git launch |
| Which work am I returning to? | Session name in tabs/search, with machine/project context when useful | Session identity stays stable when its model or activity changes |
The footer describes the focused work. Creation controls describe the next
@@ -304,11 +304,12 @@ while finding machines. While saved defaults load, show “Preparing your harnes
in the same quiet hierarchy, then hand focus to the existing composer. Startup
must not leave a blank page or imply that a harness has already started.
-Fresh forms focus the prompt and use the last explicit agent, project,
-approvals and worktree choices. Fresh branches default to main; reopening a
-draft preserves its selected branch. Enter submits except during composition.
-Escape and outside click dismiss the innermost picker first, then the dialog;
-they preserve its draft. Pending operations retain their existing close guards.
+Fresh forms focus an empty prompt. The last focused real project supplies its
+machine and folder; the global last successful launch supplies agent, model,
+approvals, account and worktree choice. Fresh branches default to main. Enter
+submits even with an empty prompt, except during composition. Escape and outside
+click dismiss the innermost picker first, then the dialog. Closing discards ordinary
+edits; pending operations retain their close guards and exact recovery values.
Opening any form or preview must never start work.
The GitHub entry starts with only “Enter GitHub URL”; a valid address reveals
its clone action and an invalid submission reveals inline validation. Do not
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
index ac1bc08d2..0a4eaf966 100644
--- a/desktop/design/new-harness-entry-rules.md
+++ b/desktop/design/new-harness-entry-rules.md
@@ -8,26 +8,25 @@ composer and picker interactions. Earlier terminal-cell form styling is retired.
Startup and New Tab embed the same `NewHarnessForm` and controller used by
Cmd-N, at the same 680-point maximum width. The page has Recent harnesses below
the composer, without a modal frame or Close button. Opening the page or dialog
-never starts a harness; New Harness submits the reviewed draft.
+never starts a harness; Enter or New Harness starts it, with or without a prompt.
Agent and Repo selectors sit above the message. Model, Approvals, applicable
-Profile, Worktree, and Branch remain visible below it. Fresh and restored task
-drafts focus the prompt. Terminal, which takes no task, focuses New Harness. In the message,
+Profile, Worktree, and Branch remain visible below it. Fresh forms and recovered
+launches focus the prompt. Terminal, which takes no task, focuses New Harness. In the message,
Enter submits and Shift-Enter inserts a newline, respecting composition and the
active keymap. Tab/Shift-Tab traverse the visible controls. Arrow keys navigate
an open chooser. Accepting or cancelling returns focus to its originating control.
Outside clicks and Escape close the innermost child picker first, then the main
-popup. The X directly closes the popup. Dismissal preserves its draft; unresolved
-launch receipts retain their close guards. The popup's 95% dark backdrop
-covers the native footer. The full-page entry retains its per-tab draft when
-switching tabs. Choosers use system typography, normal controls, a search field,
+popup. The X directly closes the popup. Closing cancels an ordinary unfinished
+form; unresolved launch receipts retain their close guards and recovery values.
+The popup's 95% dark backdrop covers the native footer. Reopening starts fresh. Choosers use system typography, normal controls, a search field,
natural row heights, and bounded scrolling.
Agent combines direct coding agents and specialized harnesses in one searchable
list. A specialized harness then offers compatible coding agents. Repo searches
recent folders on the selected machine; its search row contains the machine
-picker, with local preselected for a fresh context. Open Folder, New Folder,
+picker, using the working project's machine, or local for a first launch. Open Folder, New Folder,
and GitHub operate on that selected machine. Open invokes the native local
folder dialog or remote browser; New and Clone offer Change machine inside
their prompts. Escape retraces child steps. A remote machine appears in the
@@ -37,14 +36,14 @@ Opening, searching, and cancelling never send input to an existing harness.
| Entry | Initial values | Destination after a successful start |
| --- | --- | --- |
-| Cmd-T, then Cmd-N | Last explicit agent, local machine, last selected project on that machine | The blank tab opened by Cmd-T |
-| Cmd-Shift-P → New Harness | Last explicit agent, local machine, last selected project on that machine | Current tab |
-| Cmd-N or the New Harness command | Last explicit agent, local machine, last selected project on that machine; retain explicit task and destination | Current tab unless its source requests a new tab |
+| Cmd-T, then Cmd-N | Last successful setup and last focused real project with its machine | The blank tab opened by Cmd-T |
+| Cmd-Shift-P → New Harness | Last successful setup and last focused real project with its machine | Current tab |
+| Cmd-N or the New Harness command | Last successful setup and last focused real project with its machine; retain explicit task and destination | Current tab unless its source requests a new tab |
| Pane-edge split, Split Right/Down command, menu, or shortcut | Opens creation directly with the clicked/focused pane's agent, machine, and project | Requested split in that tab after submission |
| Store New Harness, or a product's Open action in the pane or native Models menu | Explicit product and machine; suggested project named for that product | New tab |
| Store Resume Harness | Existing harness and its machine; choose from a menu when several match | Focus its existing tab or reopen a view of the same harness |
| Store Try this prompt | Same as Open, with the example as the editable task | New tab |
-| First empty workspace / New Tab | Same launch defaults, with a draft owned by that empty tab | That tab when the user submits New Harness |
+| First empty workspace / New Tab | Same successful setup and working project; a suggested local folder on first launch | That tab when the user submits New Harness |
The Store and orchestration tabs cannot host a terminal pane. Generic creation
from either uses a new tab. Command-bar requests keep the workspace context and
@@ -70,7 +69,7 @@ desktop experiment. Specialized harnesses follow with recent choices, the tuned
set, and the remaining catalog. Terminal comes last. All are searchable and
the saved default selection does not move specialized harnesses above coding
agents. There is no separate Coding category. A specialized harness asks which compatible
-coding agent should run it, preselecting its remembered choice. The form's value
+coding agent should run it, using the last successful agent when compatible. The form's value
then reads `Blender · Codex`. Choosing a direct agent removes the package choice
and sends no `dsh`; it does not remove project instructions or skills.
@@ -97,17 +96,23 @@ Machine changes re-evaluate compatibility and never silently substitute at
launch. The installed package's compatibility takes precedence over a newer
catalog listing.
-The existing local state store retains separate engine and harness use recents.
-Explicit desktop agent/harness choices become defaults immediately without
-pretending a launch happened or changing use-recency order. The compatible
-agent chosen for a harness is remembered too. Explicit folder choices are saved
-after Git discovery canonicalizes linked worktrees to their repository. Legacy
-preference keys and the app data directory stay in place.
-On the desktop experiment, approvals separately remember the last explicit
-selection for each agent. Worktree remembers the last explicit toggle for each
-project on each machine, even when the form is later dismissed. Unsupported
-saved modes are ignored; drafts and pending receipts retain their reviewed
-values. Automatic retry recovery never changes these remembered preferences.
+The existing local state store remembers one global **last successful launch**:
+agent and specialized harness, model route, approvals, and account/profile.
+A profile path is only reusable on its original machine. Worktree is a global
+choice from the last successful Git launch; plain folders leave that choice alone.
+Choosing options, cancelling, or a failed start never changes these defaults.
+A confirmed start saves them even when creation has already replaced the form.
+Legacy preference keys and the app data directory stay in place; migration uses
+actual launch history instead of previously persisted dropdown edits.
+
+The working project is the last focused real work pane in this window, including
+its machine. Monitor, Grid, Store, and Settings do not replace it. Without a working
+pane, use the last successfully launched user project. Without either, suggest a
+new local folder so Enter can launch immediately. Normalize linked worktrees back
+to their repository. Utility launches never update this project history or the
+successful setup. Task text, attachments, branch names, and worktree folder names
+are never global preferences. There is no extra Draft, Save as default, or
+reasoning-effort control.
## Model selection
@@ -127,17 +132,17 @@ updates the choices; Manage Models opens the existing Models panel for lifecycle
management and preserves the launch draft. Choosing Terminal clears model routing;
its Model row is omitted.
-An explicit model survives draft dismissal/restoration and uncertain creation
-receipts. A new OpenCode session starts with Muse Spark 1.3; other engines use their default subscription;
-model routing is not persisted as a global preference. Start refreshes availability
+An explicit model survives an uncertain creation receipt. A successful launch
+remembers its model route globally with its agent. A first OpenCode session starts
+with Muse Spark 1.3; other engines use their default subscription. Start refreshes availability
and sends only `gridModel` and `gridName`; the selected machine resolves the endpoint
and credentials. Older daemons without `supportsModelLaunch` explain that an update
is needed while continuing to allow ordinary subscription launches.
## Git projects
-Git projects enable Branch and Worktree. Worktree defaults to **Yes** when the
-project has no saved worktree preference;
+Git projects enable Branch and Worktree. Worktree defaults to **Yes** until a
+successful Git launch remembers another global choice.
The checkbox supports pointer and keyboard activation through the form's active
keymap. Its label and branch icon remain together as the form narrows.
An empty repository explains that a commit is required for a worktree and asks
@@ -219,35 +224,26 @@ worktree it finds in `~/harnesses/worktrees` only when no live or stopped
harness uses it, nothing is uncommitted, and it has been idle for a week; the
branch stays unless Harness made it and its commits are all elsewhere.
-Drafts preserve these choices. A lost start reply reuses
+An open form preserves these choices. A lost start reply reuses
its receipt, and retrying a confirmed launch failure reuses its prepared
worktree: the retry selects that worktree's branch with Worktree off.
-## Draft ownership
-
-- Workspace drafts belong to their original machine, focused source harness,
- and project context. A different focused harness does not inherit their edits.
-- Fresh Cmd-N and Cmd-Shift-P creation use the same remembered explicit choices.
- The current tab controls placement; a saved draft cannot redirect it to an old destination.
-- Draft identity uses the original source context, not the remembered project
- subsequently changed by editing that draft. Reopening cannot lose the task
- because the person's latest choice became a new default.
-- Store drafts belong to the explicitly requested product and machine. Opening
- Blender cannot restore Workshop's agent, task, or generated project name.
-- Closing Cmd-N keeps its draft for that context. Explicit Store entries can
- resume their compatible draft, including the selected agent. Store Open still
- wins if the harness or machine was changed inside that saved draft.
-- Cmd-N from search resumes the same-context draft, including its task and
- selected options. Search text seeds the task only when no compatible draft
- resumes; browsing search must not replace an interrupted composer.
-- Explicitly choosing a new-task search result or a Store example starts the
- requested task from that entry's defaults. Repeating the same request while
- its draft is already open keeps its edits.
-- A request awaiting confirmation is an exception: restore its exact values and
+## Fresh forms and launch recovery
+
+- Every newly opened Cmd-N starts with an empty prompt and the successful setup.
+ Closing discards ordinary edits. Repeating Cmd-N while the same form is still
+ open simply focuses it.
+- Browsing search does not become a new task. An explicit create action or Store
+ example supplies its requested prompt. Explicit product, machine, split and
+ destination choices take precedence over inferred defaults.
+- The current tab controls placement. Store entries start fresh on their requested
+ machine, with a suggested project named for that product.
+- A request awaiting confirmation is the exception: restore its exact values and
receipt. A new task must not silently turn an uncertain start into a duplicate.
- An in-flight or uncertain draft cannot be replaced while it is open.
-- Closing the dock does not discard unresolved receipts. Advanced options and
- return-to-dock preserve the same draft ownership and placement.
+ In-flight and uncertain requests cannot be replaced while open.
+- Pending receipts belong to their original source context. Closing keeps them
+ recoverable. Opening a nested picker or returning from advanced options keeps
+ the currently open form and its destination.
## Project names
@@ -257,7 +253,7 @@ does not. The suggestion is frozen while reviewed. Project → New Folder
opens the name prompt on the selected machine, with Change machine available;
accepting a name returns to the Repo control.
-Each machine retains its own project choice. A folder on one machine is never
+Project paths retain their owning machine. A folder on one machine is never
silently reused on another. Generated folders use exclusive reservation and
advance to seconds/a suffix only on a confirmed collision. Explicit names are
never silently renamed, and existing files are never overwritten.
diff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.md
index 03668cbc3..7883baa52 100644
--- a/desktop/design/terminal-dialogs.md
+++ b/desktop/design/terminal-dialogs.md
@@ -8,14 +8,14 @@ are retired for app UI. Older screenshots are historical evidence only.
## Shared ownership
-Reuse the existing controllers, launch paths, and draft stores. Cmd-N and the
+Reuse the existing controllers, launch paths, and receipt recovery. Cmd-N and the
full-page welcome use the same form. Cmd-P scopes use the same query editor,
result selection, and resource preview. Styling must not fork their behavior.
The detailed creation contract is [new-harness-entry-rules.md](new-harness-entry-rules.md).
-Fresh creation uses saved successful choices on the local machine. Explicit
-Store/split requests and restored drafts retain their own destination and
-reviewed values. Never substitute another branch, folder, agent, or profile,
+Fresh creation combines the last successful setup with the last focused real
+project and its machine. Explicit Store/split requests and pending launch receipts
+retain their destination and reviewed values. Closing cancels an ordinary form. Never substitute another branch, folder, agent, or profile,
or disable Worktree after a failure. Browsing options does not commit them.
Searching and highlighting never creates a folder or launches a harness.
A held Return cannot accept a choice and launch in the same keypress.
diff --git a/desktop/lib/core/agent_preference.dart b/desktop/lib/core/agent_preference.dart
index 598fe7dc9..e98c84f26 100644
--- a/desktop/lib/core/agent_preference.dart
+++ b/desktop/lib/core/agent_preference.dart
@@ -1,9 +1,10 @@
import 'dart:convert';
import 'local_key_value_store.dart';
+import 'launch_setup.dart';
import 'permission_modes.dart';
-/// Remembers agent choices and each agent's last explicit approval mode.
+/// Confirmed launch setup and use history, alongside legacy picker preferences.
class AgentPreference {
AgentPreference(this.storage);
final LocalKeyValueStore? storage;
@@ -17,6 +18,9 @@ class AgentPreference {
String? value;
String? harness;
+ LaunchSetup? successfulLaunch;
+ // A non-Git launch leaves the last Git preference alone.
+ bool? successfulWorktree;
bool advancedOpen = false;
List<String> recentHarnesses = const [];
final _enginesByHarness = <String, String>{};
@@ -44,10 +48,12 @@ class AgentPreference {
}.take(recentCapacity).toList(growable: false);
Future<void>? _loading;
+ bool _loaded = false;
Future<void> _writes = Future.value();
int _revision = 0;
- Future<void> load() => _loading ??= _read();
+ Future<void> load() =>
+ _loading ??= _read().whenComplete(() => _loaded = true);
Future<void> _read() async {
final revision = _revision;
try {
@@ -133,8 +139,36 @@ class AgentPreference {
}
}
}
+ successfulLaunch = LaunchSetup.fromJson(data['successfulLaunch']);
+ if (data['successfulWorktree'] case final bool worktree) {
+ successfulWorktree = worktree;
+ }
} catch (_) {
/* A malformed preference never blocks launch. */
+ } finally {
+ // Older versions persisted dropdown edits as defaults. Only actual
+ // launch history is suitable for migrating a successful setup.
+ if (successfulLaunch == null && revision == _revision && revision == 0) {
+ final choice = _recentChoices
+ ?.where(
+ (id) =>
+ id != 'terminal' &&
+ !isInternalLaunchHarness(id) &&
+ (id.contains('/')
+ ? recentHarnesses.contains(id)
+ : recent.contains(id)),
+ )
+ .firstOrNull;
+ final engine = choice != null && !choice.contains('/')
+ ? choice
+ : recent.where((id) => id != 'terminal').firstOrNull;
+ if (engine != null) {
+ successfulLaunch = LaunchSetup(
+ engine: engine,
+ harnessId: choice?.contains('/') == true ? choice : null,
+ );
+ }
+ }
}
}
@@ -149,8 +183,8 @@ class AgentPreference {
return _save();
}
- /// Explicit composer selections become the next form's defaults without
- /// recording an agent launch or changing the recent-use order.
+ /// Legacy picker defaults. Cmd-N uses [successfulLaunch] instead; selecting
+ /// an option is not a successful launch.
Future<void> selectLaunch(String engine, {String? harnessId}) async {
await load();
_revision++;
@@ -162,13 +196,24 @@ class AgentPreference {
/// [agent] was just used to create a harness: it moves to the front of
/// [recent].
- Future<void> remember(String agent, {String? harnessId}) async {
- await load();
- _revision++;
+ Future<void> remember(
+ String agent, {
+ String? harnessId,
+ LaunchSetup? setup,
+ bool? worktree,
+ }) async {
+ if (!_loaded) await load();
if (agent.contains('/')) {
harnessId = agent;
agent = value ?? '';
}
+ if (isInternalLaunchHarness(harnessId)) return;
+ _revision++;
+ if (agent.isNotEmpty && agent != 'terminal') {
+ successfulLaunch =
+ setup ?? LaunchSetup(engine: agent, harnessId: harnessId);
+ if (worktree != null) successfulWorktree = worktree;
+ }
final choice = harnessId ?? agent;
_recentChoices = <String>{
if (choice.isNotEmpty) choice,
@@ -217,6 +262,9 @@ class AgentPreference {
'enginesByHarness': _enginesByHarness,
'advancedOpen': advancedOpen,
'permissionsByEngine': _permissionsByEngine,
+ if (successfulLaunch != null)
+ 'successfulLaunch': successfulLaunch!.toJson(),
+ if (successfulWorktree != null) 'successfulWorktree': successfulWorktree,
});
return _writes = _writes.then((_) async {
try {
diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dart
index 34fa080e9..8ef836844 100644
--- a/desktop/lib/core/git_worktree.dart
+++ b/desktop/lib/core/git_worktree.dart
@@ -300,8 +300,9 @@ Future<Map<String, dynamic>> readLocalGitProject(
bool refresh = false,
GitProcessStarter? startProcess,
}) async {
- Future<({int code, String output})> git(List<String> arguments) =>
- _git(source, arguments, startProcess: startProcess);
+ Future<({int code, String output, String errorOutput})> git(
+ List<String> arguments,
+ ) => _git(source, arguments, startProcess: startProcess);
if (!validGitPath(source)) return {'error': 'INVALID_PATH'};
try {
final root = await git(['rev-parse', '--show-toplevel']);
@@ -436,7 +437,7 @@ Future<String> prepareGitProject(
Random? random,
GitProcessStarter? startProcess,
}) async {
- Future<({int code, String output})> git(
+ Future<({int code, String output, String errorOutput})> git(
List<String> arguments, {
Duration timeout = const Duration(seconds: 4),
String? at,
@@ -660,16 +661,23 @@ Future<String> prepareGitProject(
);
// Directory.create accepts an existing directory; mkdir reserves the
// name exclusively, so concurrent starts never share a worktree.
- if ((await Process.run('mkdir', [folder])).exitCode == 0) {
+ final reservation = await Process.run('mkdir', [folder]);
+ if (reservation.exitCode == 0) {
destination = folder;
break;
}
+ if (_diskFullMessage(reservation.stderr.toString())) {
+ throw const RepositoryCloneException(_worktreeDiskFull);
+ }
if (await FileSystemEntity.type(folder, followLinks: false) ==
FileSystemEntityType.notFound) {
throw FileSystemException('Could not create folder', folder);
}
}
- } on FileSystemException {
+ } on FileSystemException catch (error) {
+ if ([28, 69, 122].contains(error.osError?.errorCode)) {
+ throw const RepositoryCloneException(_worktreeDiskFull);
+ }
throw const RepositoryCloneException(
'Could not create a worktree folder. Check folder permissions, then retry.',
);
@@ -727,7 +735,9 @@ Future<String> prepareGitProject(
if (result.code != 0) {
// A partial checkout or branch stays available for recovery.
throw RepositoryCloneException(
- 'Could not create the worktree at $destination. Check Git and folder permissions, then retry.',
+ _diskFullMessage(result.errorOutput)
+ ? _worktreeDiskFull
+ : 'Could not create the worktree at $destination. Check Git and folder permissions, then retry.',
);
}
// Harness made this branch: its cleanup may remove it, and a made-up name
@@ -815,7 +825,15 @@ Future<void> _copyIncluded(
}
}
-Future<({int code, String output})> _git(
+const _worktreeDiskFull =
+ 'Not enough disk space to create the worktree. Free space on this machine, then retry.';
+
+bool _diskFullMessage(String message) => RegExp(
+ r'no space left on device|disk quota exceeded',
+ caseSensitive: false,
+).hasMatch(message);
+
+Future<({int code, String output, String errorOutput})> _git(
String source,
List<String> arguments, {
Duration timeout = const Duration(seconds: 4),
@@ -855,6 +873,7 @@ Future<({int code, String output})> _git(
}
unawaited(process.stdin.close());
final output = StringBuffer();
+ var errorOutput = '';
var overflow = false;
final outDone = Completer<void>(), errDone = Completer<void>();
final stdout = process.stdout
@@ -871,11 +890,20 @@ Future<({int code, String output})> _git(
onDone: outDone.complete,
onError: outDone.completeError,
);
- final stderr = process.stderr.listen(
- (_) {},
- onDone: errDone.complete,
- onError: errDone.completeError,
- );
+ final stderr = process.stderr
+ .transform(const Utf8Decoder(allowMalformed: true))
+ .listen(
+ (chunk) {
+ errorOutput += chunk;
+ // Keep a bounded tail for failure classification; never show raw Git
+ // output, which can contain credentials or repository contents.
+ if (errorOutput.length > 8192) {
+ errorOutput = errorOutput.substring(errorOutput.length - 8192);
+ }
+ },
+ onDone: errDone.complete,
+ onError: errDone.completeError,
+ );
try {
final results = await Future.wait<dynamic>([
process.exitCode,
@@ -890,6 +918,7 @@ Future<({int code, String output})> _git(
return (
code: results.first as int,
output: output.toString().replaceFirst(RegExp(r'\r?\n$'), ''),
+ errorOutput: errorOutput,
);
} on TimeoutException {
process.kill(ProcessSignal.sigkill);
diff --git a/desktop/lib/core/launch_setup.dart b/desktop/lib/core/launch_setup.dart
new file mode 100644
index 000000000..04c730e06
--- /dev/null
+++ b/desktop/lib/core/launch_setup.dart
@@ -0,0 +1,98 @@
+import 'codex_profiles.dart';
+import 'models.dart';
+import 'permission_modes.dart';
+
+/// Management tools are never a person's next coding setup or working project.
+bool isInternalLaunchHarness(String? id) => const {
+ 'autonomous/harness-monitor',
+ 'autonomous/machine-monitor',
+ 'autonomous/autonomous-grid',
+}.contains(id);
+
+/// Discard generated management folders left in project history by older apps.
+/// A user repository simply named "harness-monitor" remains an ordinary project.
+bool isInternalLaunchFolder(String folder) => RegExp(
+ r'(?:^|/)(?:harness-monitor|machine-monitor|autonomous-grid)-\d{4}-\d{2}-\d{2}(?:-|$)',
+).hasMatch(folder);
+
+/// One confirmed user launch. Model routes and account references stay paired
+/// with their agent; an account path only applies on the machine that owns it.
+/// Task text, files, branches and temporary worktree folders are not preferences.
+class LaunchSetup {
+ const LaunchSetup({
+ required this.engine,
+ this.harnessId,
+ this.permissionMode = kDefaultPermissionMode,
+ this.model,
+ this.profile,
+ this.profileMachineId,
+ });
+
+ final String engine;
+ final String? harnessId;
+ final String permissionMode;
+ final GridModel? model;
+ final LocalCodexProfile? profile;
+ final String? profileMachineId;
+
+ Map<String, dynamic> toJson() => {
+ 'engine': engine,
+ if (harnessId != null) 'harness': harnessId,
+ 'permissionMode': permissionMode,
+ if (model case final value?)
+ 'model': {'id': value.id, 'node': value.node, 'grid': value.grid},
+ if (profile case final value?)
+ 'profile': {
+ 'path': value.path,
+ 'label': value.label,
+ 'machineId': profileMachineId,
+ },
+ };
+
+ static LaunchSetup? fromJson(Object? raw) {
+ if (raw is! Map || raw['engine'] is! String) return null;
+ final engine = raw['engine'] as String;
+ final harness = raw['harness'] is String ? raw['harness'] as String : null;
+ if (engine.isEmpty ||
+ engine.contains('/') ||
+ engine == 'terminal' ||
+ isInternalLaunchHarness(harness)) {
+ return null;
+ }
+ final mode = raw['permissionMode'];
+ final model = raw['model'];
+ final profile = raw['profile'];
+ return LaunchSetup(
+ engine: engine,
+ harnessId: harness,
+ permissionMode: permissionModesOf(engine).any((item) => item.id == mode)
+ ? mode as String
+ : kDefaultPermissionMode,
+ model:
+ model is Map &&
+ model['id'] is String &&
+ (model['id'] as String).isNotEmpty
+ ? GridModel(
+ id: model['id'] as String,
+ node: model['node'] is String ? model['node'] as String : '',
+ grid: model['grid'] is String ? model['grid'] as String : null,
+ )
+ : null,
+ profile:
+ engine == 'codex' &&
+ profile is Map &&
+ profile['path'] is String &&
+ profile['machineId'] is String
+ ? LocalCodexProfile(
+ profile['path'] as String,
+ profile['label'] is String
+ ? profile['label'] as String
+ : 'Profile',
+ )
+ : null,
+ profileMachineId: profile is Map && profile['machineId'] is String
+ ? profile['machineId'] as String
+ : null,
+ );
+ }
+}
diff --git a/desktop/lib/core/project_history.dart b/desktop/lib/core/project_history.dart
index 3892b8c40..2b58fec62 100644
--- a/desktop/lib/core/project_history.dart
+++ b/desktop/lib/core/project_history.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'local_key_value_store.dart';
+import 'launch_setup.dart';
/// Recent choices are scoped to the machine that owns their paths.
class ProjectHistory {
@@ -13,6 +14,7 @@ class ProjectHistory {
Future<void>? _loading;
Future<void> _saving = Future.value();
int _revision = 0;
+ ({String machineId, String folder})? lastLaunched;
List<String> recent(String machine) =>
List.unmodifiable(_recent[machine] ?? []);
@@ -28,7 +30,18 @@ class ProjectHistory {
if (raw == null || _revision != revision) return;
final decoded = jsonDecode(raw);
if (decoded is! Map) return;
+ final last = decoded['_lastLaunch'];
+ if (last is Map &&
+ last['machine'] is String &&
+ last['folder'] is String &&
+ _valid(last['folder'])) {
+ lastLaunched = (
+ machineId: last['machine'] as String,
+ folder: last['folder'] as String,
+ );
+ }
for (final entry in decoded.entries.take(64)) {
+ if (entry.key == '_lastLaunch') continue;
if (entry.key is! String || entry.value is! Map) continue;
final value = entry.value as Map;
final paths = value['recent'];
@@ -62,14 +75,22 @@ class ProjectHistory {
static bool _valid(String path) =>
path.startsWith('/') &&
+ !isInternalLaunchFolder(path) &&
path.length <= 4096 &&
!RegExp(r'[\x00-\x1f\x7f]').hasMatch(path);
- Future<void> select(String machine, String? path) async {
+ Future<void> select(
+ String machine,
+ String? path, {
+ bool launched = false,
+ }) async {
await load();
if (path != null && !_valid(path)) return;
_revision++;
_selected[machine] = path;
+ if (launched && path != null) {
+ lastLaunched = (machineId: machine, folder: path);
+ }
if (path != null) {
_recent[machine] = [
path,
@@ -98,6 +119,8 @@ class ProjectHistory {
Future<void> _save() async {
final snapshot = jsonEncode({
+ if (lastLaunched case final last?)
+ '_lastLaunch': {'machine': last.machineId, 'folder': last.folder},
for (final id in {
..._worktrees.keys,
..._selected.keys,
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 03cb91704..dec6561ee 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -18,6 +18,7 @@ import '../api/api_client.dart';
import '../core/desktop_window.dart';
import '../core/harness_file_store.dart';
import '../core/project_folder.dart';
+import '../core/launch_setup.dart';
import '../core/test_run.dart';
import '../logging/debug_surface.dart';
import '../models/api_connections_controller.dart' show agentOnApiModel;
@@ -428,10 +429,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
OverlayEntry? _newHarnessOverlay;
var _newHarnessFormKey = GlobalKey<NewHarnessFormState>();
- /// Escape keeps unfinished work with the machine/project/agent it started
- /// from. Switching context must not carry a task into the wrong project or
- /// silently reset its edited permissions. These buffers live for this window.
+ /// Only unconfirmed launches survive closing. Ordinary forms start fresh.
final _newHarnessDrafts = <_NewHarnessContext, NewHarnessDraft>{};
+ ({String machineId, String folder})? _workingProject;
_NewHarnessContext? _newHarnessContext;
(String, bool, String, HarnessPlacement?)? _searchHeaderState;
FocusNode? _searchReturnFocus;
@@ -1057,7 +1057,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
final target = _search!.targetId;
final split = _search!.split;
final placement = _search!.placement;
- final fallbackTask = _search!.createTask;
final selected = _search!.selected;
final machineId =
_search!.scopedMachineId ??
@@ -1069,7 +1068,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: target,
split: split,
placement: placement,
- fallbackTask: fallbackTask,
),
);
return;
@@ -1091,6 +1089,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
void _recordNavigation() {
+ _rememberWorkingProject();
_scheduleCompanionWorkspace();
_navigation.record(app);
if (_hasCommandBar && _commandBarOpen) {
@@ -2871,6 +2870,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
placement: HarnessPlacement.newTab,
);
+ void _rememberWorkingProject() {
+ if (app.activeSwarm.isUtility || app.activeSwarm.isOrchestrator) return;
+ final pane = app.focusedPane;
+ if (pane == null) return;
+ final machine = app.stateOf(pane.machineId);
+ final agentId = pane.agentId ?? pane.ownerAgentId;
+ final agent = machine?.agents
+ .where((item) => item.id == agentId)
+ .firstOrNull;
+ if (agent == null || isInternalLaunchHarness(agent.dsh)) return;
+ final folder = machine?.projectOf(agent)?.cwd;
+ if (folder == null || folder.isEmpty || isInternalLaunchFolder(folder)) {
+ return;
+ }
+ _workingProject = (machineId: pane.machineId, folder: folder);
+ }
+
Future<void> _newAgent({
String? machineId,
String? folder,
@@ -2879,7 +2895,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? engine,
String? projectName,
String? task,
- String? fallbackTask,
HarnessPlacement? placement,
_NewHarnessSource source = _NewHarnessSource.workspace,
bool Function()? stillCurrent,
@@ -2904,13 +2919,26 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
final target = swarmId ?? search?.targetId ?? app.activeSwarmId;
final requestedSplit = split ?? search?.split;
- // Search text seeds a fresh composer, but switching back with ⌘N must not
- // replace a draft. Explicit create rows and Store examples pass task.
- if (newHarnessOpensInBox) fallbackTask ??= search?.createTask;
if (app.activeSwarmId != target) return;
- // A fresh launcher uses saved choices on this computer. Only an explicit
- // split inherits its source pane; changing focus never changes Cmd-N's
- // defaults.
+ _rememberWorkingProject();
+ await Future.wait([app.agentPreference.load(), app.projectHistory.load()]);
+ if (!mounted ||
+ app.activeSwarmId != target ||
+ stillCurrent?.call() == false) {
+ return;
+ }
+ final rememberedProject = [_workingProject, app.projectHistory.lastLaunched]
+ .nonNulls
+ .where((project) => app.stateOf(project.machineId) != null)
+ .firstOrNull;
+ final working =
+ source == _NewHarnessSource.workspace &&
+ newHarnessOpensInBox &&
+ rememberedProject != null
+ ? rememberedProject
+ : null;
+ // Only a split inherits the source agent. Cmd-N combines the working
+ // project's location with the one global successful launch setup.
final draftSource = source == _NewHarnessSource.workspace
? app.focusedPane ?? _newTabSources[target]
: null;
@@ -2922,6 +2950,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
final id =
machineId ??
machine?.machine.machineId ??
+ working?.machineId ??
app.machineStates.values
.where((machine) => machine.isLocalMachine)
.firstOrNull
@@ -2937,19 +2966,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
await _openMachines();
return;
}
- await Future.wait([app.agentPreference.load(), app.projectHistory.load()]);
- if (!mounted ||
- app.activeSwarmId != target ||
- stillCurrent?.call() == false) {
- return;
- }
final initialFolder =
folder ??
paneProject?.cwd ??
- (newHarnessOpensInBox && source == _NewHarnessSource.workspace
- ? app.projectHistory.selected(id) ??
- app.projectHistory.recent(id).firstOrNull
- : null);
+ (working?.machineId == id ? working?.folder : null);
final inherited = agent?.engine;
if (!newHarnessOpensInBox) {
await _newAgentForm(
@@ -2959,7 +2979,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
split: requestedSplit,
engine: engine ?? (isTerminalEngine(inherited) ? null : inherited),
placement: placement,
- task: task ?? fallbackTask,
+ task: task,
);
return;
}
@@ -2982,12 +3002,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
harnessId: engine == null ? agent?.dsh : null,
folder: initialFolder,
projectName: projectName,
- autoProject:
- projectName == null &&
- initialFolder == null &&
- source == _NewHarnessSource.product,
+ autoProject: projectName == null && initialFolder == null,
task: task,
- fallbackTask: fallbackTask,
embedded: embedded,
draftContext:
welcomeOrigin ??
@@ -3077,7 +3093,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? projectName,
bool autoProject = false,
String? task,
- String? fallbackTask,
NewHarnessDraft? draft,
_NewHarnessContext? draftContext,
required String swarmId,
@@ -3140,8 +3155,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_newHarnessEmbedded = embedded;
_canvasFocus.descendantsAreFocusable = embedded;
_newHarnessContext = origin;
- // Consume once. ⌘N resumes this context's whole draft, even after typing
- // in search. Only an explicit new-task action replaces ordinary edits.
+ // Consume an unresolved receipt once. Ordinary dismissed forms are fresh.
final savedDraft = _newHarnessDrafts[origin];
// A lost reply always restores its exact receipt. Otherwise explicit
// product/machine choices and explicit task requests win over old defaults.
@@ -3160,7 +3174,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
harnessId: harnessId,
folder: folder,
projectName: projectName,
- task: task ?? (resumed == null ? fallbackTask : null),
+ task: task,
draft: resumed,
autoProject: autoProject,
offersStore: true,
@@ -3399,7 +3413,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
_NewHarnessContext origin,
NewHarnessDraft draft,
) {
- // Choosing defaults is useful work even before the first task is typed.
+ // An uncertain reply must retain its receipt to avoid duplicate creation.
+ // Closing an ordinary composer cancels that task and its choices.
+ if (draft.attempt?.awaitingConfirmation != true) return;
_newHarnessDrafts.remove(origin);
_newHarnessDrafts[origin] = draft;
while (_newHarnessDrafts.length > 32) {
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 44b34915b..56b119024 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -40,6 +40,7 @@ import '../core/sleep_aware.dart';
import '../core/agent_git_context.dart';
import '../core/agent_names.dart';
import '../core/agent_preference.dart';
+import '../core/launch_setup.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/engine_availability.dart';
@@ -7410,7 +7411,9 @@ class AppNotifier extends ChangeNotifier {
if (!connection.isReady) return null;
final reply = await connection.request(
'machine_resources',
- payload: harnesses ? const {'harnesses': true, 'storage': true} : const {},
+ payload: harnesses
+ ? const {'harnesses': true, 'storage': true}
+ : const {},
timeout: const Duration(seconds: 3),
);
if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision) ||
@@ -10096,8 +10099,11 @@ class AppNotifier extends ChangeNotifier {
agent.project?.cwd ??
creation.preparedFolder ??
choices['cwd'];
- if (projectPath is String && projectPath.isNotEmpty) {
- unawaited(projectHistory.select(machineId, projectPath));
+ if (!creation.background &&
+ !isInternalLaunchHarness(agent.dsh ?? choices['dsh'] as String?) &&
+ projectPath is String &&
+ projectPath.isNotEmpty) {
+ unawaited(projectHistory.select(machineId, projectPath, launched: true));
}
harnessStats.onAgentSpawned();
notifyListeners();
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 1fa52f364..1f8dfb6fc 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -12,6 +12,7 @@ import 'package:path/path.dart' as p;
import '../core/runtime_platform.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';
@@ -282,6 +283,7 @@ class NewHarnessDraft {
required this.task,
required this.permissionMode,
this.worktree,
+ this.worktreePreference,
this.branchRef,
this.branchName,
this.placeholder,
@@ -299,6 +301,8 @@ class NewHarnessDraft {
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].
@@ -420,6 +424,9 @@ class NewHarnessController extends ChangeNotifier {
),
_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 ?? RuntimePlatform.environment['HOME'] {
final explicitSelection =
@@ -454,6 +461,7 @@ class NewHarnessController extends ChangeNotifier {
: const NewHarnessProject.fresh();
if (task != null) this.task = task;
_worktree = draft?.worktree;
+ _recoveredWorktreePreference = draft?.worktreePreference;
_branchRef = draft?.branchRef;
_branchName = draft?.branchName;
_placeholder = draft?.placeholder;
@@ -503,6 +511,7 @@ class NewHarnessController extends ChangeNotifier {
_engine = _initialEngine(null);
}
_restorePermissionMode();
+ if (_desktopChoices) _applySuccessfulLaunch();
_refresh();
}),
);
@@ -550,6 +559,8 @@ class NewHarnessController extends ChangeNotifier {
: placement;
final bool _autoProject;
+ final bool _initialAgentExplicit;
+ final bool _restoringDraft;
final DateTime Function() _now;
final String? _home;
@@ -610,11 +621,20 @@ class NewHarnessController extends ChangeNotifier {
final allowed = compatibleEngines;
final remembered =
requested ??
- app.agentPreference.engineFor(_harnessId) ??
- (_harnessId == null || _harnessId == app.agentPreference.harness
- ? app.agentPreference.value
- : null);
- if (remembered != null) return remembered;
+ (_desktopChoices
+ ? app.agentPreference.successfulLaunch?.engine
+ : app.agentPreference.engineFor(_harnessId) ??
+ (_harnessId == null ||
+ _harnessId == app.agentPreference.harness
+ ? app.agentPreference.value
+ : null));
+ if (remembered != null &&
+ (requested != null ||
+ !_desktopChoices ||
+ allowed.contains(remembered) ||
+ _harnessId == app.agentPreference.successfulLaunch?.harnessId)) {
+ return remembered;
+ }
final preferred = allowed.contains(defaultHarnessEngine)
? defaultHarnessEngine
: selectedHarness?.engine;
@@ -648,8 +668,15 @@ class NewHarnessController extends ChangeNotifier {
bool get worktree =>
isGitProject &&
(_worktree ??
- app.projectHistory.worktreeFor(_machineId, _project.folder ?? '') ??
- worktreeByDefault(_gitProject));
+ (_desktopChoices
+ ? app.agentPreference.successfulWorktree ?? true
+ : app.projectHistory.worktreeFor(
+ _machineId,
+ _project.folder ?? '',
+ ) ??
+ worktreeByDefault(_gitProject)));
+
+ bool? _recoveredWorktreePreference;
/// Fresh desktop work starts on main, with or without a worktree. A retry
/// must instead keep the branch of the folder its first attempt prepared.
@@ -731,7 +758,8 @@ class NewHarnessController extends ChangeNotifier {
void toggleWorktree() {
if (locked || !canUseWorktree) return;
_worktree = !worktree;
- if (_project.folder case final folder?) {
+ _recoveredWorktreePreference = null;
+ if (_project.folder case final folder? when !_desktopChoices) {
unawaited(
app.projectHistory.selectWorktree(_machineId, folder, _worktree!),
);
@@ -800,6 +828,7 @@ class NewHarnessController extends ChangeNotifier {
if (_gitKey == key) return;
if (_gitKey != null) {
_worktree = null;
+ _recoveredWorktreePreference = null;
_branchRef = null;
_branchName = null;
_placeholder = null;
@@ -882,6 +911,7 @@ class NewHarnessController extends ChangeNotifier {
}
GridModel? _model;
+ bool _modelTouched = false;
GridModel? get model => _model;
GridModels? _modelCatalog;
ModelsMenuController? _modelUsage;
@@ -1045,6 +1075,7 @@ class NewHarnessController extends ChangeNotifier {
task: task,
permissionMode: _mode,
worktree: isGitProject ? worktree : _worktree,
+ worktreePreference: _recoveredWorktreePreference,
branchRef: _branchRef,
branchName: _branchName,
placeholder: isGitProject ? placeholder : _placeholder,
@@ -1107,7 +1138,11 @@ class NewHarnessController extends ChangeNotifier {
final _chosenModes = <String, String>{};
String _permissionFor(String engine) =>
_chosenModes[engine] ??
- app.agentPreference.permissionModeFor(_baseOf(engine)) ??
+ (_desktopChoices
+ ? app.agentPreference.successfulLaunch?.engine == engine
+ ? app.agentPreference.successfulLaunch?.permissionMode
+ : null
+ : app.agentPreference.permissionModeFor(_baseOf(engine))) ??
kDefaultPermissionMode;
void _restorePermissionMode() => _mode = _permissionFor(_engine);
@@ -1686,9 +1721,34 @@ class NewHarnessController extends ChangeNotifier {
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 || isTerminal) 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 (!_desktopChoices)
const NewHarnessOption(
@@ -1807,25 +1867,6 @@ class NewHarnessController extends ChangeNotifier {
query = field == NewHarnessField.task ? task : '';
error = null;
_refresh(resetCursor: true);
- _rememberProjectSelection();
- }
-
- void _rememberProjectSelection() {
- if (!_desktopChoices || _project.folder == null) return;
- final machine = _machineId;
- final revision = _gitRevision;
- // Git discovery normalizes a chosen worktree back to its repository.
- // Do not persist the temporary checkout or an obsolete async selection.
- unawaited(() async {
- await _gitFuture;
- if (_disposed || machine != _machineId || revision != _gitRevision) {
- return;
- }
- final folder = _project.folder;
- if (folder != null && gitError != 'PROJECT_UNAVAILABLE') {
- await app.projectHistory.select(machine, folder);
- }
- }());
}
/// ⌘↵: make it now — WITH the row under the highlight. Creating with the
@@ -1888,6 +1929,7 @@ class NewHarnessController extends ChangeNotifier {
_selectEngine(option.id);
case NewHarnessField.model:
_model = option.model;
+ _modelTouched = true;
case NewHarnessField.machine:
_selectMachine(option.id);
case NewHarnessField.branch:
@@ -1907,13 +1949,14 @@ class NewHarnessController extends ChangeNotifier {
_project = option.project ?? _project;
if (_desktopChoices) {
_syncGitProject();
- _rememberProjectSelection();
}
case NewHarnessField.mode:
_selectEngine(_settingsEngine);
_mode = option.id;
_chosenModes[_engine] = _mode;
- unawaited(app.agentPreference.selectPermissionMode(_base, _mode));
+ if (!_desktopChoices) {
+ unawaited(app.agentPreference.selectPermissionMode(_base, _mode));
+ }
case NewHarnessField.profile:
_selectEngine(_settingsEngine);
_profile = option.profile;
@@ -1922,12 +1965,6 @@ class NewHarnessController extends ChangeNotifier {
case NewHarnessField.launch:
break;
}
- if (_desktopChoices &&
- (field == NewHarnessField.harness || field == NewHarnessField.agent)) {
- unawaited(
- app.agentPreference.selectLaunch(_engine, harnessId: _harnessId),
- );
- }
}
void _selectEngine(String engine) {
@@ -1940,6 +1977,7 @@ class NewHarnessController extends ChangeNotifier {
_resetProfiles();
}
_engine = engine;
+ if (changed && _desktopChoices && !_modelTouched) _model = null;
if (changed) _restorePermissionMode();
if (isTerminal) _model = null;
if (changed &&
@@ -1961,7 +1999,11 @@ class NewHarnessController extends ChangeNotifier {
_selectionTouched = true;
_harnessId = id;
_installing = null;
- _selectEngine(_initialEngine(app.agentPreference.engineFor(id) ?? _engine));
+ _selectEngine(
+ _desktopChoices
+ ? _initialEngine(null)
+ : _initialEngine(app.agentPreference.engineFor(id) ?? _engine),
+ );
if (_project.generated != null) {
_project = _generatedProject();
unawaited(_refreshGeneratedProject());
@@ -2895,9 +2937,11 @@ class NewHarnessController extends ChangeNotifier {
// on this machine. Older projects need not be picked again to appear.
if (machine != null)
for (final agent in machine.agents.reversed)
- ?machine.projectOf(agent)?.cwd,
+ if (!isInternalLaunchHarness(agent.dsh))
+ ?machine.projectOf(agent)?.cwd,
]) {
if (!p.isAbsolute(folder) ||
+ isInternalLaunchFolder(folder) ||
folder.length > 4096 ||
RegExp(r'[\x00-\x1f\x7f]').hasMatch(folder) ||
folder != _project.folder &&
@@ -3420,6 +3464,16 @@ class NewHarnessController extends ChangeNotifier {
'Update Harness CLI on $machineLabel to attach files, or remove them.',
);
}
+ final launchSetup = LaunchSetup(
+ engine: base,
+ harnessId: harness,
+ permissionMode: permissionMode ?? kDefaultPermissionMode,
+ model: _model,
+ profile: base == 'codex' && _model == null ? _profile : null,
+ profileMachineId: _machineId,
+ );
+ final launchedWorktree =
+ _recoveredWorktreePreference ?? (isGitProject ? worktree : null);
final failure = await app.createAgent(
_machineId,
engine: base,
@@ -3449,11 +3503,24 @@ class NewHarnessController extends ChangeNotifier {
if (failure == null && files.isNotEmpty) {
_deliverFiles(attempt.agentId, files, firstMessage);
}
+ // Creation can replace an embedded form before this future returns. Save
+ // the confirmed choices even if that form has already been disposed.
+ if (failure == null && attempt.agentId != null) {
+ unawaited(
+ app.agentPreference.remember(
+ choice,
+ harnessId: harness,
+ setup: launchSetup,
+ worktree: launchedWorktree,
+ ),
+ );
+ }
if (_disposed) return NewHarnessOutcome.failed;
if (failure != 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!);
_gitKey = (_machineId, _project.folder, isTerminal);
_worktree = false;
@@ -3463,7 +3530,6 @@ class NewHarnessController extends ChangeNotifier {
}
return _fail(failure);
}
- unawaited(app.agentPreference.remember(choice, harnessId: _harnessId));
busy = false;
status = null;
return NewHarnessOutcome.created;
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index 91922728b..9c7d19661 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -13,6 +13,7 @@ import '../core/codex_profiles.dart';
import '../core/dsh_catalog.dart';
import '../core/harness_catalog.dart';
import '../core/first_task.dart';
+import '../core/launch_setup.dart';
import '../core/permission_modes.dart';
import '../core/project_folder.dart';
import '../core/repository_clone.dart';
@@ -745,6 +746,30 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
prompt: _firstPrompt,
attempt: _creation,
);
+ if (error == null && _creation?.agentId != null) {
+ unawaited(
+ widget.notifier.agentPreference.remember(
+ choice,
+ harnessId: harness,
+ setup: LaunchSetup(
+ engine: engine,
+ harnessId: harness,
+ permissionMode: permissionMode ?? kDefaultPermissionMode,
+ model: terminal ? null : widget.initialDraft?.model,
+ profile: engine == 'codex' && widget.initialDraft?.model == null
+ ? profile
+ : null,
+ profileMachineId: _machineId,
+ ),
+ worktree:
+ _sameGitProject && widget.initialDraft?.worktreePreference != null
+ ? widget.initialDraft!.worktreePreference
+ : project?.gitSource != null
+ ? project!.createsWorktree
+ : null,
+ ),
+ );
+ }
if (!mounted) return;
if (error != null) {
setState(() {
@@ -764,10 +789,6 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
});
return;
}
- // What New Harness lists first next time, before anything is typed.
- unawaited(
- widget.notifier.agentPreference.remember(choice, harnessId: _harnessId),
- );
Navigator.of(context).pop(NewAgentDialogResult.created);
}
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 2c7cb47cd..0051c1f6a 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -1920,7 +1920,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
onTapOutside: (_) {},
decoration: InputDecoration(
hintText: box.takesTask
- ? 'Harness anything'
+ ? 'What would you like to work on?'
: 'Open a terminal in this repo',
hintStyle: DesktopChrome.text(
size: 15,
diff --git a/desktop/test/desktop_compact_launch_test.dart b/desktop/test/desktop_compact_launch_test.dart
index 4625e79c1..0b7ef8b9a 100644
--- a/desktop/test/desktop_compact_launch_test.dart
+++ b/desktop/test/desktop_compact_launch_test.dart
@@ -313,7 +313,7 @@ void main({bool nativeSmoke = false}) {
expect(_task, findsOneWidget);
expect(
tester.widget<TextField>(_task).decoration?.hintText,
- 'Harness anything',
+ 'What would you like to work on?',
);
expect(find.byKey(const ValueKey('new-harness-settings')), findsNothing);
expect(find.byKey(const ValueKey('new-harness-task-toggle')), findsNothing);
diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dart
index 4dc7f2be1..319b03a27 100644
--- a/desktop/test/desktop_composer_layout_test.dart
+++ b/desktop/test/desktop_composer_layout_test.dart
@@ -384,7 +384,7 @@ void main() {
expect(find.text('New Harness'), findsOneWidget);
expect(
tester.widget<TextField>(_task).decoration!.hintText,
- 'Harness anything',
+ 'What would you like to work on?',
);
expect(find.text('Options'), findsNothing);
expect(find.text('Add task'), findsNothing);
diff --git a/desktop/test/git_worktree_failures_test.dart b/desktop/test/git_worktree_failures_test.dart
index 0c8072bd4..c971359e4 100644
--- a/desktop/test/git_worktree_failures_test.dart
+++ b/desktop/test/git_worktree_failures_test.dart
@@ -15,8 +15,13 @@ class _DiscardInput implements StreamConsumer<List<int>> {
}
class _GitProcess implements Process {
- _GitProcess({String output = '', int? code = 0, List<int>? bytes})
- : stdout = Stream.value(bytes ?? utf8.encode(output)) {
+ _GitProcess({
+ String output = '',
+ String error = '',
+ int? code = 0,
+ List<int>? bytes,
+ }) : stdout = Stream.value(bytes ?? utf8.encode(output)),
+ stderr = Stream.value(utf8.encode(error)) {
if (code != null) ended.complete(code);
}
final ended = Completer<int>();
@@ -24,7 +29,7 @@ class _GitProcess implements Process {
@override
final Stream<List<int>> stdout;
@override
- Stream<List<int>> get stderr => const Stream.empty();
+ final Stream<List<int>> stderr;
@override
final stdin = IOSink(_DiscardInput());
@override
@@ -39,21 +44,24 @@ class _GitProcess implements Process {
}
}
-GitProcessStarter _commands({String? fail, String prefix = ''}) =>
- (arguments, environment) async {
- final command = arguments.skip(3).join(' ');
- if (fail != null && command.startsWith(fail)) {
- return _GitProcess(code: 1);
- }
- return _GitProcess(
- output: switch (command) {
- 'rev-parse --show-toplevel' => '/repo\n',
- 'rev-parse --show-prefix' => prefix,
- 'symbolic-ref --quiet HEAD' => 'refs/heads/main\n',
- _ => '0123456789\n',
- },
- );
- };
+GitProcessStarter _commands({
+ String? fail,
+ String prefix = '',
+ String error = '',
+}) => (arguments, environment) async {
+ final command = arguments.skip(3).join(' ');
+ if (fail != null && command.startsWith(fail)) {
+ return _GitProcess(code: 1, error: error);
+ }
+ return _GitProcess(
+ output: switch (command) {
+ 'rev-parse --show-toplevel' => '/repo\n',
+ 'rev-parse --show-prefix' => prefix,
+ 'symbolic-ref --quiet HEAD' => 'refs/heads/main\n',
+ _ => '0123456789\n',
+ },
+ );
+};
void main() {
test('Git command failures stay distinct from folders without Git', () async {
@@ -194,6 +202,34 @@ void main() {
},
);
+ for (final message in ['No space left on device', 'Disk quota exceeded']) {
+ test(
+ 'worktree failure explains $message without exposing Git output',
+ () async {
+ final root = await Directory.systemTemp.createTemp('git-space-test-');
+ addTearDown(() => root.delete(recursive: true));
+ await expectLater(
+ prepareGitProject(
+ '/repo',
+ root.path,
+ worktree: true,
+ startProcess: _commands(
+ fail: 'worktree add',
+ error: '${'progress ' * 2000}\nfatal: private-file: $message\n',
+ ),
+ ),
+ throwsA(
+ isA<RepositoryCloneException>().having(
+ (error) => error.message,
+ 'message',
+ 'Not enough disk space to create the worktree. Free space on this machine, then retry.',
+ ),
+ ),
+ );
+ },
+ );
+ }
+
test('preparation rejects invalid sources, stale refs and unreadable project paths', () async {
for (final (source, ref, failure) in [
('relative', null, null),
diff --git a/desktop/test/launch_preferences_test.dart b/desktop/test/launch_preferences_test.dart
index 3d3e803c2..5bdfe29c5 100644
--- a/desktop/test/launch_preferences_test.dart
+++ b/desktop/test/launch_preferences_test.dart
@@ -3,8 +3,11 @@ import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/agent_preference.dart';
+import 'package:harness/core/codex_profiles.dart';
import 'package:harness/core/dsh_catalog.dart';
import 'package:harness/core/git_worktree.dart';
+import 'package:harness/core/launch_setup.dart';
+import 'package:harness/core/models.dart';
import 'package:harness/core/permission_modes.dart';
import 'package:harness/core/project_history.dart';
import 'package:harness/state/app_state.dart';
@@ -210,27 +213,30 @@ void main() {
},
);
- test('desktop remembers selected agent and repo before launching', () async {
- final storage = _Store();
- final fixture = _Fixture(storage: storage);
- final box = fixture.open(desktop: true);
- await _settle();
- _engine(box, 'claude');
- box.setFolder('/chosen/project');
- await _settle();
- expect(fixture.app.agentPreference.value, 'claude');
- expect(fixture.app.projectHistory.selected('m'), '/chosen/project');
- expect(fixture.connections.values.expand((c) => c.creates), isEmpty);
- final next = fixture.open(engine: null, desktop: true);
- await _settle();
- expect(next.engine, 'claude');
- });
+ test(
+ 'desktop ignores cancelled choices when opening the next form',
+ () async {
+ final storage = _Store();
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(desktop: true);
+ await _settle();
+ _engine(box, 'claude');
+ box.setFolder('/chosen/project');
+ await _settle();
+ expect(fixture.app.agentPreference.successfulLaunch, isNull);
+ expect(fixture.app.projectHistory.lastLaunched, isNull);
+ expect(fixture.connections.values.expand((c) => c.creates), isEmpty);
+ final next = fixture.open(engine: null, desktop: true);
+ await _settle();
+ expect(next.engine, 'opencode');
+ },
+ );
test(
'desktop defaults to main with saved worktree off and sends that branch',
() async {
final fixture = _Fixture();
- await fixture.app.projectHistory.selectWorktree('m', '/repo', false);
+ await fixture.app.agentPreference.remember('codex', worktree: false);
final box = fixture.open(desktop: true);
await _settle();
expect(box.worktree, isFalse);
@@ -255,7 +261,7 @@ void main() {
test('desktop does not substitute a remote or different branch for missing local main', () async {
final fixture = _Fixture();
- await fixture.app.projectHistory.selectWorktree('m', '/repo', false);
+ await fixture.app.agentPreference.remember('codex', worktree: false);
final connection = fixture.connections.putIfAbsent(
'm',
() => _Connection('m'),
@@ -280,6 +286,233 @@ void main() {
expect(box.branchRef, 'refs/remotes/origin/main');
});
+ test(
+ 'successful desktop choices apply globally after launch and reload',
+ () async {
+ final storage = _Store();
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(desktop: true);
+ await _settle();
+ _engine(box, 'claude');
+ _mode(box, 'plan');
+ box.toggleWorktree();
+ expect(fixture.app.agentPreference.successfulLaunch, isNull);
+ expect(fixture.app.agentPreference.successfulWorktree, isNull);
+ expect(await box.create(), NewHarnessOutcome.created);
+ final preferences = AgentPreference(storage);
+ await preferences.load();
+ expect(preferences.successfulLaunch?.engine, 'claude');
+ expect(preferences.successfulLaunch?.permissionMode, 'plan');
+ expect(preferences.successfulWorktree, isFalse);
+ final other = fixture.open(
+ engine: null,
+ folder: '/another',
+ desktop: true,
+ );
+ await _settle();
+ expect(other.engine, 'claude');
+ expect(other.mode, 'plan');
+ expect(other.worktree, isFalse);
+ expect(other.branchRef, 'refs/heads/main');
+ expect(other.task, isEmpty);
+ final history = ProjectHistory(storage);
+ await history.load();
+ expect(history.lastLaunched, (machineId: 'm', folder: '/repo'));
+ },
+ );
+
+ test(
+ 'a non-Git launch preserves the last successful worktree preference',
+ () async {
+ final fixture = _Fixture();
+ await fixture.app.agentPreference.remember('codex', worktree: false);
+ final box = fixture.open(
+ engine: 'claude',
+ folder: '/plain',
+ desktop: true,
+ );
+ await _settle();
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(fixture.app.agentPreference.successfulLaunch?.engine, 'claude');
+ final next = fixture.open(engine: null, desktop: true);
+ await _settle();
+ expect(next.worktree, isFalse);
+ },
+ );
+
+ test(
+ 'failed desktop launches leave the last successful setup intact',
+ () async {
+ final fixture = _Fixture();
+ await fixture.app.agentPreference.remember('codex', worktree: true);
+ final box = fixture.open(desktop: true);
+ await _settle();
+ _engine(box, 'claude');
+ _mode(box, 'plan');
+ box.toggleWorktree();
+ fixture.connections['m']!.failure = {
+ 'failure': {'code': 'WORKTREE_FAILED', 'detail': 'Fixture failure'},
+ };
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(fixture.app.agentPreference.successfulLaunch?.engine, 'codex');
+ expect(fixture.app.agentPreference.successfulWorktree, isTrue);
+ expect(fixture.app.projectHistory.lastLaunched, isNull);
+ },
+ );
+
+ test(
+ 'retrying a prepared worktree remembers the original isolation choice',
+ () async {
+ final fixture = _Fixture();
+ await fixture.app.agentPreference.remember('codex', worktree: false);
+ final connection = fixture.connections.putIfAbsent(
+ 'm',
+ () => _Connection('m'),
+ );
+ connection.gitAnswers['/worktrees/repo/task'] = {
+ ..._git,
+ 'branch': 'task',
+ 'mainFolder': '/repo',
+ 'mainBranch': 'feature',
+ };
+ connection.failure = {
+ 'preparedFolder': '/worktrees/repo/task',
+ 'failure': {'code': 'TMUX_UNAVAILABLE'},
+ };
+ final box = fixture.open(desktop: true);
+ await _settle();
+ box.toggleWorktree();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ await _settle();
+ expect(box.worktree, isFalse);
+ expect(fixture.app.agentPreference.successfulWorktree, isFalse);
+ final retry = fixture.open(draft: box.draft, desktop: true);
+ await _settle();
+ connection.failure = null;
+ expect(await retry.create(), NewHarnessOutcome.created);
+ await _settle();
+ expect(fixture.app.agentPreference.successfulWorktree, isTrue);
+ expect(connection.creates.last['projectSource'], 'branch');
+ },
+ );
+
+ test(
+ 'model routes and machine-scoped account references survive reload',
+ () async {
+ final storage = _Store();
+ final preferences = AgentPreference(storage);
+ const model = GridModel(
+ id: 'Qwen-35B',
+ node: 'Studio',
+ grid: 'team-grid',
+ );
+ await preferences.remember(
+ 'codex',
+ setup: const LaunchSetup(
+ engine: 'codex',
+ model: model,
+ permissionMode: 'readOnly',
+ ),
+ );
+ var restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.successfulLaunch?.model?.id, model.id);
+ expect(restored.successfulLaunch?.model?.node, model.node);
+ expect(restored.successfulLaunch?.model?.grid, model.grid);
+ await preferences.remember(
+ 'codex',
+ setup: const LaunchSetup(
+ engine: 'codex',
+ profile: LocalCodexProfile('/accounts/work', 'Work'),
+ profileMachineId: 'm',
+ ),
+ );
+ restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.successfulLaunch?.model, isNull);
+ final fixture = _Fixture(storage: storage, machines: true);
+ final local = fixture.open(engine: null, desktop: true);
+ final remote = fixture.open(
+ engine: null,
+ machine: 'studio',
+ desktop: true,
+ );
+ await _settle();
+ expect(local.draft.profile?.path, '/accounts/work');
+ expect(remote.draft.profile, isNull);
+ },
+ );
+
+ test(
+ 'internal utilities cannot replace launch defaults or user projects',
+ () async {
+ final storage = _Store();
+ final preferences = AgentPreference(storage);
+ await preferences.remember('codex', worktree: false);
+ await preferences.remember(
+ 'opencode',
+ harnessId: 'autonomous/harness-monitor',
+ worktree: true,
+ );
+ expect(preferences.successfulLaunch?.engine, 'codex');
+ expect(preferences.successfulWorktree, isFalse);
+ expect(preferences.recentChoices, ['codex']);
+ final history = ProjectHistory(storage);
+ await history.select('m', '/repo', launched: true);
+ await history.select(
+ 'm',
+ '/harnesses/harness-monitor-2026-09-21-18-41',
+ launched: true,
+ );
+ await history.select('studio', '/just-browsing');
+ expect(history.lastLaunched, (machineId: 'm', folder: '/repo'));
+ expect(history.recent('m'), ['/repo']);
+ // A normal repository with this name remains selectable.
+ await history.select('m', '/projects/harness-monitor', launched: true);
+ expect(history.lastLaunched?.folder, '/projects/harness-monitor');
+ },
+ );
+
+ test(
+ 'legacy successful history migrates without using cancelled defaults',
+ () async {
+ final storage = _Store()
+ ..values['new_agent_engine'] = 'claude'
+ ..values['new_agent_recent'] = 'codex';
+ final preferences = AgentPreference(storage);
+ await preferences.load();
+ expect(preferences.successfulLaunch?.engine, 'codex');
+ expect(LaunchSetup.fromJson({'engine': 'terminal'}), isNull);
+ expect(
+ LaunchSetup.fromJson({
+ 'engine': 'opencode',
+ 'harness': 'autonomous/harness-monitor',
+ }),
+ isNull,
+ );
+ expect(
+ LaunchSetup.fromJson({'engine': 'codex', 'permissionMode': 'plan'})
+ ?.permissionMode,
+ kDefaultPermissionMode,
+ );
+ },
+ );
+
+ test(
+ 'migration ignores dropdown-only defaults with no successful launch',
+ () async {
+ final storage = _Store();
+ await AgentPreference(storage).selectLaunch('claude');
+ final restored = AgentPreference(storage);
+ await restored.load();
+ expect(restored.successfulLaunch, isNull);
+ final fixture = _Fixture(storage: storage);
+ final box = fixture.open(engine: null, desktop: true);
+ await _settle();
+ expect(box.engine, 'opencode');
+ },
+ );
+
test(
'launch recency interleaves harnesses and agents across reloads',
() async {
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 8807a0c8e..961ce9d2d 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -7,6 +7,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/models.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/harness_placement.dart';
@@ -14,6 +15,7 @@ import 'package:harness/state/new_harness.dart';
import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/state/swarm_search.dart';
import 'package:harness/store/store_screen.dart';
+import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/desktop_search_panel.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/widgets/swarm_search_input.dart';
@@ -91,6 +93,7 @@ class _Connection extends WsConn {
'engine': starts.last['engine'],
'dsh': starts.last['dsh'],
'project': {
+ 'name': 'Created project',
'cwd':
starts.last['cwd'] ??
'/home/$machineId/harnesses/${starts.last['projectName']}',
@@ -116,7 +119,13 @@ void main() {
newHarnessOpensInBox = false;
});
- Future<void> mount(WidgetTester tester, {bool store = true}) async {
+ Future<void> mount(
+ WidgetTester tester, {
+ bool store = true,
+ bool workingPane = true,
+ bool history = true,
+ bool remotePane = false,
+ }) async {
connections = {
for (final id in ['m', 'studio', 'build']) id: _Connection(id),
};
@@ -128,9 +137,26 @@ void main() {
machine.dsh.replace(_products.map((json) => DshEntry.fromJson(json)!));
}
map = MemoryKeymap();
- await app.agentPreference.remember('codex');
- await app.projectHistory.select('m', '/work/openharness');
- app.adoptSessionForTest(terminal('a0', []));
+ if (history) {
+ await app.agentPreference.remember('codex');
+ await app.projectHistory.select('m', '/work/openharness', launched: true);
+ }
+ if (workingPane) {
+ app.adoptSessionForTest(
+ remotePane
+ ? (TerminalSession(
+ machineId: 'studio',
+ agentId: 'helmet',
+ agentName: 'Helmet',
+ engineId: 'claude',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'remote-stream')
+ : terminal('a0', []),
+ );
+ }
if (store) app.openStore();
await configured.mount(tester, app, map);
}
@@ -232,6 +258,87 @@ void main() {
);
}
+ testWidgets(
+ 'Monitor and Store preserve the last focused real project and machine',
+ (tester) async {
+ await mount(tester, store: false, remotePane: true);
+ // Observe the real work pane before focusing a utility terminal.
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.folder, '/work/helmet');
+ expect(box(tester).engine, 'codex');
+ await dismiss(tester);
+ app.machineStates['m']!.agents = [
+ ...app.machineStates['m']!.agents,
+ const Agent(
+ id: 'monitor',
+ name: 'Harness Monitor',
+ engine: 'opencode',
+ dsh: 'autonomous/harness-monitor',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Monitor',
+ cwd: '/harnesses/harness-monitor-2026-09-21-18-41',
+ ),
+ ),
+ ];
+ app.newSwarm(name: 'Monitor');
+ app.adoptSessionForTest(terminal('monitor', []));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.folder, '/work/helmet');
+ expect(box(tester).engine, 'codex');
+ await dismiss(tester);
+ app.openStore();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.folder, '/work/helmet');
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).task, isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'without a focused work pane Cmd-N uses the last successful project',
+ (tester) async {
+ await mount(tester, workingPane: false);
+ await app.projectHistory.select('studio', '/work/helmet', launched: true);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.folder, '/work/helmet');
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'first launch needs only Enter and saves choices when the embedded form closes',
+ (tester) async {
+ await mount(tester, store: false, workingPane: false, history: false);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).project.generated, isNotNull);
+ expect(box(tester).engine, 'opencode');
+ expect(box(tester).task, isEmpty);
+ app.machineStates['m']!.localOnly = false;
+ await acceptSetupOrSearch(tester);
+ final connection = connections['m']!;
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['projectName'], isNotEmpty);
+ expect(connection.starts.single['prompt'], isNull);
+ connection.created();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byType(NewHarnessForm), findsNothing);
+ expect(app.agentPreference.successfulLaunch?.engine, 'opencode');
+ expect(app.projectHistory.lastLaunched?.folder, contains('/harnesses/'));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
for (final closeFirst in [false, true]) {
for (final task in [null, 'Model a reading nook']) {
testWidgets(
@@ -255,8 +362,8 @@ void main() {
await dismiss(tester);
await product(tester, 'autonomous/workshop');
expect(box(tester).harnessId, 'autonomous/workshop');
- expect(box(tester).projectLabel, '~/harnesses/workshop-design');
- expect(box(tester).task, 'Workshop task');
+ expect(box(tester).project.generated, isNotNull);
+ expect(box(tester).task, isEmpty);
expect(connections.values.expand((c) => c.starts), isEmpty);
await dismiss(tester);
await tester.pumpWidget(const SizedBox());
@@ -289,36 +396,35 @@ void main() {
},
);
- testWidgets(
- 'Store machine choices have separate drafts and override edited defaults',
- (tester) async {
- await mount(tester);
- await product(tester, 'autonomous/blender');
- await nameProject(tester, 'local-scene');
- await product(tester, 'autonomous/blender', machine: 'studio');
- expect(box(tester).machineId, 'studio');
- expect(box(tester).project.generated, isNotNull);
- await nameProject(tester, 'remote-scene');
- await product(tester, 'autonomous/blender');
- expect(box(tester).machineId, 'm');
- expect(box(tester).project.name, 'local-scene');
- box(tester).focusField(NewHarnessField.machine);
- box(tester).accept(const NewHarnessOption(id: 'studio', title: 'Studio'));
- await dismiss(tester);
- await product(tester, 'autonomous/blender');
- expect(
- box(tester).machineId,
- 'm',
- reason: 'The Store explicitly requested this machine',
- );
- expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
- await dismiss(tester);
- await product(tester, 'autonomous/blender', machine: 'studio');
- expect(box(tester).project.name, 'remote-scene');
- await dismiss(tester);
- await tester.pumpWidget(const SizedBox());
- },
- );
+ testWidgets('Store requests start fresh on their explicitly chosen machine', (
+ tester,
+ ) async {
+ await mount(tester);
+ await product(tester, 'autonomous/blender');
+ await nameProject(tester, 'local-scene');
+ await product(tester, 'autonomous/blender', machine: 'studio');
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.generated, isNotNull);
+ await nameProject(tester, 'remote-scene');
+ await product(tester, 'autonomous/blender');
+ expect(box(tester).machineId, 'm');
+ expect(box(tester).project.generated, isNotNull);
+ box(tester).focusField(NewHarnessField.machine);
+ box(tester).accept(const NewHarnessOption(id: 'studio', title: 'Studio'));
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender');
+ expect(
+ box(tester).machineId,
+ 'm',
+ reason: 'The Store explicitly requested this machine',
+ );
+ expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender', machine: 'studio');
+ expect(box(tester).project.generated, isNotNull);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
testWidgets(
'product entry from a pane does not inherit workspace projects or search tasks',
@@ -400,7 +506,7 @@ void main() {
});
testWidgets(
- 'an explicit coding engine reopens its draft and overrides a different harness',
+ 'an explicit coding engine opens fresh and overrides a different harness',
(tester) async {
await mount(tester);
await product(tester, 'codex');
@@ -409,7 +515,7 @@ void main() {
box(tester).setFolder('/work/explicit-code');
await dismiss(tester);
await product(tester, 'codex');
- expect(box(tester).project.folder, '/work/explicit-code');
+ expect(box(tester).project.generated, isNotNull);
box(tester).focusField(NewHarnessField.harness);
box(tester).applyOption(
box(tester).options
@@ -530,13 +636,10 @@ void main() {
expect(updated.search!.rows, isEmpty);
expect(connections.values.expand((c) => c.starts), isEmpty);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
- expect(box(tester).task, 'Check the keyboard workflow');
+ expect(box(tester).task, isEmpty);
expect(box(tester).placement, HarnessPlacement.currentTab);
await acceptSetupOrSearch(tester);
- expect(
- connections['m']!.starts.single['prompt'],
- 'Check the keyboard workflow',
- );
+ expect(connections['m']!.starts.single['prompt'], isNull);
connections['m']!.created();
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
@@ -620,7 +723,7 @@ void main() {
});
testWidgets(
- 'Cmd-N keeps drafts with their source pane and uses defaults in another',
+ 'Cmd-N follows the focused project and discards cancelled task edits',
(tester) async {
await mount(tester, store: false);
final first = app.focusedPane!;
@@ -638,15 +741,15 @@ void main() {
expect(box(tester).harnessId, isNull);
expect(box(tester).engine, 'codex');
expect(box(tester).machineId, 'm');
- expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).project.folder, '/work/release-notes');
expect(box(tester).task, isEmpty);
await dismiss(tester);
app.focusPane(first.id);
await tester.pump();
await key(tester, shortcut, cmd: true);
expect(box(tester).engine, 'codex');
- expect(box(tester).project.name, 'keyboard-review');
- expect(box(tester).task, 'Review this project');
+ expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).task, isEmpty);
expect(connections.values.expand((c) => c.starts), isEmpty);
await dismiss(tester);
await tester.pumpWidget(const SizedBox());
@@ -655,7 +758,7 @@ void main() {
);
testWidgets(
- 'reopened Cmd-N restores reviewed edits and starts in the current tab',
+ 'reopened Cmd-N starts fresh in the current tab even after searching',
(tester) async {
await mount(tester, store: false);
final origin = app.activeSwarm;
@@ -682,8 +785,8 @@ void main() {
);
await key(tester, LogicalKeyboardKey.keyN, cmd: true);
draft = box(tester);
- expect(draft.task, 'Check keyboard focus');
- expect(draft.project.name, 'keyboard-review');
+ expect(draft.task, isEmpty);
+ expect(draft.project.folder, '/work/openharness');
expect(draft.placement, HarnessPlacement.currentTab);
// Keep the launch on the fake daemon; no local project is created.
app.machineStates['m']!.localOnly = false;
@@ -691,8 +794,8 @@ void main() {
final connection = connections['m']!;
expect(connection.starts, hasLength(1));
expect(connection.starts.single['engine'], 'codex');
- expect(connection.starts.single['projectName'], 'keyboard-review');
- expect(connection.starts.single['prompt'], 'Check keyboard focus');
+ expect(connection.starts.single['cwd'], '/work/openharness');
+ expect(connection.starts.single['prompt'], isNull);
expect(connection.starts.single['dsh'], isNull);
connection.created();
await tester.pump();
diff --git a/desktop/test/new_harness_models_test.dart b/desktop/test/new_harness_models_test.dart
index dc7108e65..4b48c28e4 100644
--- a/desktop/test/new_harness_models_test.dart
+++ b/desktop/test/new_harness_models_test.dart
@@ -168,6 +168,25 @@ void main() {
app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
addTearDown(app.dispose);
});
+ test(
+ 'desktop reuses the model route only after a successful launch',
+ () async {
+ final box = controller()..useDesktopChoices(true);
+ await load(box);
+ box.accept(localChoice(box, 'team-grid'));
+ expect(app.agentPreference.successfulLaunch, isNull);
+ expect(await box.create(), NewHarnessOutcome.created);
+ final next = controller()..useDesktopChoices(true);
+ await Future<void>.delayed(Duration.zero);
+ expect(next.model?.id, 'Qwen-35B');
+ expect(next.model?.grid, 'team-grid');
+ expect(next.model?.node, 'GPU Server');
+ expect(await next.create(), NewHarnessOutcome.created);
+ expect(connections['m']!.creates.last['gridModel'], 'Qwen-35B');
+ expect(connections['m']!.creates.last['gridName'], 'team-grid');
+ },
+ );
+
test('creation rejects an old daemon, lost connection, unsupported engine and missing model before launching', () async {
final connection = connections.putIfAbsent('m', _Connection.new);
const model = GridModel(