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.

Recover delayed agent creation without launching duplicates

deec3db329c9a9c
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 3443d0ce6..b7e2ec2a1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:io' show exit, pid;
+import 'dart:math' show Random;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
@@ -64,6 +65,34 @@ class RestartAgentResult {
const RestartAgentResult({this.error, this.resumed = true});
}
+/// One deliberate creation, retained by the form if its reply is lost. Reusing
+/// it checks the original request; opening New agent starts a fresh intent.
+class AgentCreationAttempt {
+ AgentCreationAttempt() {
+ final random = Random.secure();
+ _id = List.generate(
+ 16,
+ (_) => random.nextInt(256),
+ ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
+ }
+
+ late final String _id;
+ String? _machineId, _targetId;
+ Map<String, dynamic>? _choices;
+ PaneSplitRequest? _split;
+ Future<String?>? _inFlight;
+ bool _awaitingConfirmation = false, _finished = false;
+ String? _outcome;
+
+ bool get awaitingConfirmation => _awaitingConfirmation;
+
+ String? _complete(String? error) {
+ _finished = true;
+ _awaitingConfirmation = false;
+ return _outcome = error;
+ }
+}
+
String? _normalizeComputerId(String? raw) {
if (raw == null) return null;
final value = raw.trim().toLowerCase().replaceAll('-', '');
@@ -3579,8 +3608,9 @@ class AppNotifier extends ChangeNotifier {
}
}
- /// Spawns a new engine session on [machineId] via the harness CLI, then jumps into its terminal.
- /// Returns null on success, or an error message to show inline in the New Agent dialog.
+ /// Starts an agent, or recovers this form's earlier request after a lost reply.
+ /// Returns null on success, or an inline message; [attempt] tells the form
+ /// whether to offer Check status instead of inviting another creation.
Future<String?> createAgent(
String machineId, {
required String engine,
@@ -3589,76 +3619,198 @@ class AppNotifier extends ChangeNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
- }) async {
+ AgentCreationAttempt? attempt,
+ }) {
+ final creation = attempt ?? AgentCreationAttempt();
+ final choices = <String, dynamic>{
+ 'engine': engine,
+ 'cwd': folder,
+ 'bypassPermission': bypassPermission,
+ 'codexHome': ?codexHome,
+ };
+ if (creation._choices != null &&
+ (creation._machineId != machineId ||
+ !mapEquals(creation._choices, choices))) {
+ return Future.value(
+ 'Check the original request before changing its choices.',
+ );
+ }
+ if (creation._finished) return Future.value(creation._outcome);
+ if (creation._inFlight case final inFlight?) return inFlight;
+ if (creation._choices == null) {
+ creation._choices = choices;
+ creation._machineId = machineId;
+ creation._targetId = split?.swarmId ?? swarmId ?? activeSwarmId;
+ creation._split = split;
+ }
+ final work = _createAgentWithReceipt(creation);
+ creation._inFlight = work;
+ return work.whenComplete(() => creation._inFlight = null);
+ }
+
+ String? _creationPlacementError(String targetId, PaneSplitRequest? split) {
if (split != null && !isPaneSplitCurrent(split)) {
return 'The layout changed. Close this dialog and split the agent again.';
}
- final targetId = split?.swarmId ?? swarmId ?? activeSwarmId;
- if (!swarms.any((s) => s.id == targetId)) return 'This swarm was closed';
- final target = swarms.firstWhere((s) => s.id == targetId);
+ final target = swarms.where((s) => s.id == targetId).firstOrNull;
+ if (target == null) return 'This swarm was closed';
if (target.panes.length >= maxPanes) {
return 'This swarm is full. Open a new swarm to create an agent.';
}
+ return null;
+ }
+
+ String _creationFailureMessage(String code, String? detail, String machine) =>
+ switch (code) {
+ 'CWD_NOT_FOUND' || 'INVALID_CWD' =>
+ 'The project folder is unavailable on $machine. '
+ 'Choose another folder and try again.',
+ 'TMUX_UNAVAILABLE' =>
+ 'Harness needs tmux to start agents on $machine. '
+ 'Install tmux there, then try again.',
+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
+ 'Update the harness CLI on this machine to use New Agent',
+ _ => 'Create agent failed: ${detail ?? code}',
+ };
+
+ Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {
+ final machineId = creation._machineId!;
+ final targetId = creation._targetId!;
+ final split = creation._split;
+ final choices = creation._choices!;
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
- if (codexHome != null) {
- if (engine != 'codex') {
- return 'Choose a Codex profile only for Codex';
- }
- if (machine.engines['codex']?.supportsCodexHome != true) {
- return 'Update the harness CLI on this machine to choose a Codex profile';
+ final machineName = machine.machine.displayName;
+ // A status check must remain possible even if the destination closed or a
+ // capability probe changed while the first create was already in flight.
+ if (!creation.awaitingConfirmation) {
+ final placementError = _creationPlacementError(targetId, split);
+ if (placementError != null) return placementError;
+ if (choices['codexHome'] != null) {
+ if (choices['engine'] != 'codex') {
+ return 'Choose a Codex profile only for Codex';
+ }
+ if (machine.engines['codex']?.supportsCodexHome != true) {
+ return 'Update the harness CLI on this machine to choose a Codex profile';
+ }
}
}
final connection = _conn(machineId);
+ final operation = creation.awaitingConfirmation
+ ? 'agent_create_status'
+ : 'agent_create';
+ final unconfirmed =
+ '$machineName has not confirmed the new agent yet. '
+ 'Check status before creating another.';
Map<String, dynamic> result;
+ creation._awaitingConfirmation = true;
try {
- result = await connection.request(
- 'agent_create',
- payload: {
- 'engine': engine,
- 'cwd': folder,
- 'bypassPermission': bypassPermission,
- 'codexHome': ?codexHome,
- },
- timeout: const Duration(seconds: 20),
- );
+ if (operation == 'agent_create_status') {
+ result = await connection.request(
+ operation,
+ payload: {'creationId': creation._id},
+ timeout: const Duration(seconds: 10),
+ );
+ if (result['creationId'] != creation._id) return unconfirmed;
+ } else {
+ result = await connection.request(
+ operation,
+ payload: {...choices, 'creationId': creation._id},
+ timeout: const Duration(seconds: 20),
+ );
+ }
} on WsRequestFailure catch (failure) {
- // A refusal the CLI MEANT arrives as a thrown WsRequestFailure, never as an `error` key on a
- // reply that was returned — see that class. This used to be a branch on `result['error']`
- // below, which could not run, so the user got the wire code in place of the sentence.
- return switch (failure.code) {
- 'CWD_NOT_FOUND' || 'INVALID_CWD' =>
- 'The project folder is unavailable on ${machine.machine.displayName}. '
- 'Choose another folder and try again.',
- 'TMUX_UNAVAILABLE' =>
- 'Harness needs tmux to start agents on ${machine.machine.displayName}. '
- 'Install tmux there, then try again.',
- 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
- 'Update the harness CLI on this machine to use New Agent',
- _ => 'Create agent failed: ${failure.detail ?? failure.code}',
+ if (operation == 'agent_create_status') {
+ if (failure.code == 'UNSUPPORTED' ||
+ failure.code == 'UNSUPPORTED_ON_REMOTE' ||
+ failure.code == 'E2EE_REQUIRED') {
+ return '$machineName cannot check this creation. '
+ 'Use Add agent to look for it before creating another.';
+ }
+ return unconfirmed;
+ }
+ // Refusals that happen before a launch are safe to correct. INTERNAL,
+ // spawn timeouts and connection failures cannot prove nothing started.
+ const refusedBeforeLaunch = {
+ 'CWD_NOT_FOUND',
+ 'INVALID_CWD',
+ 'INVALID_ENGINE',
+ 'INVALID_GRID',
+ 'INVALID_CODEX_HOME',
+ 'TMUX_UNAVAILABLE',
+ 'TMUX_TOO_OLD_FOR_GRID',
+ 'GRID_CONFIG_FAILED',
+ 'UNSUPPORTED_ON_REMOTE',
+ 'UNSUPPORTED',
};
- } on WsRequestTimeout {
- // The request may have succeeded while its reply was lost. Do not call
- // that a definite failure or encourage blindly creating a duplicate.
- return '${machine.machine.displayName} has not confirmed the new agent yet. '
- 'Check Search before creating another.';
- } catch (error) {
- return 'Create agent failed: $error';
+ if (refusedBeforeLaunch.contains(failure.code)) {
+ return creation._complete(
+ _creationFailureMessage(failure.code, failure.detail, machineName),
+ );
+ }
+ return unconfirmed;
+ } catch (_) {
+ // Includes disconnects, malformed replies and timeouts. A transport error
+ // is not evidence that the machine did not execute the request.
+ return unconfirmed;
+ }
+ if ((result.containsKey('creationId') || result['state'] != null) &&
+ result['creationId'] != creation._id) {
+ return unconfirmed;
+ }
+ switch (result['state']) {
+ case 'missing':
+ // An old CLI may have created the agent before being updated to a
+ // receipt-aware version. Missing is not proof that nothing started.
+ // Check status stays read-only, even across upgrades and reconnects.
+ return '$machineName has no record of this request. '
+ 'Use Add agent to look for it before creating another.';
+ case 'pending':
+ return '$machineName is still starting your agent. Check again in a moment.';
+ case 'unconfirmed':
+ return '$machineName could not confirm whether this agent started. '
+ 'Use Add agent to look for it before creating another.';
+ case 'unavailable':
+ return creation._complete(
+ 'This agent was created but is no longer available. '
+ 'You can create a new one.',
+ );
+ case 'failed':
+ final failure = result['failure'];
+ if (failure is! Map || failure['code'] is! String) return unconfirmed;
+ return creation._complete(
+ _creationFailureMessage(
+ failure['code'] as String,
+ failure['detail'] is String ? failure['detail'] as String : null,
+ machineName,
+ ),
+ );
+ case 'created':
+ case null: // A successful first response from a CLI predating receipts.
+ break;
+ default:
+ return unconfirmed;
}
final raw = result['agent'];
- if (raw is! Map) return 'Create agent failed: malformed response';
+ if (raw is! Map || raw['id'] is! String || (raw['id'] as String).isEmpty) {
+ return unconfirmed;
+ }
+ final Agent agent;
+ try {
+ agent = Agent.fromJson(Map<String, dynamic>.from(raw));
+ } catch (_) {
+ return unconfirmed;
+ }
+ creation._complete(null);
if (_disposed || machineStates[machineId] != machine) return null;
- final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
- // Idempotent on agent.id — safe even if the CLI's own agent_synced push for this session
- // arrives separately (it's fire-and-forget on the CLI side and unordered relative to this reply).
_upsertAgent(machine, agent);
- // Counted HERE and not on the `agent_created` push, which also fires for
- // agents another client made on the same machine. "Agents spawned" is a
- // count of what this app launched.
+ // Apply each creation receipt once, even if its transport result is replayed.
harnessStats.onAgentSpawned();
notifyListeners();
- if (split != null && !isPaneSplitCurrent(split)) {
- _lastError = 'The agent was created, but the original layout changed. Find it in Search.';
+ if (_creationPlacementError(targetId, split) != null) {
+ _lastError =
+ 'The agent was created, but its original swarm or layout changed. '
+ 'Find it with Add agent.';
_lastErrorRetryable = false;
notifyListeners();
return null;
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index 3b1a3e14a..36026ab7f 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -89,6 +89,11 @@ class _NewAgentDialog extends StatefulWidget {
class _NewAgentDialogState extends State<_NewAgentDialog> {
final _folderFocus = FocusNode(debugLabel: 'Working folder');
+ final _actionFocus = FocusNode(debugLabel: 'Create or check agent');
+ AgentCreationAttempt? _creation;
+ bool _checkingCreation = false;
+ bool get _confirmationPending => _creation?.awaitingConfirmation == true;
+ bool get _choicesLocked => _submitting || _confirmationPending;
late String _engine = allEngines.first.id;
bool _engineChosenByUser = false;
late String _machineId = widget.machineId;
@@ -107,6 +112,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
@override
void dispose() {
_folderFocus.dispose();
+ _actionFocus.dispose();
super.dispose();
}
@@ -142,7 +148,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Future<void> _loadAgentPreference() async {
await widget.notifier.agentPreference.load();
- if (!mounted || _submitting || _engineChosenByUser) return;
+ if (!mounted || _choicesLocked || _engineChosenByUser) return;
final remembered = widget.notifier.agentPreference.value;
if (allEngines.any((identity) => identity.id == remembered)) {
setState(() {
@@ -173,7 +179,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
widget.notifier.probeEngines(machineId, force: true));
if (!mounted ||
revision != _machineRevision ||
- _submitting ||
+ _choicesLocked ||
_engineChosenByUser) {
return;
}
@@ -252,7 +258,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
widget.notifier.stateOf(_machineId)?.engines.inFlight != null;
void _retryEngineCheck() {
- if (_submitting || _checkingEngines) return;
+ if (_choicesLocked || _checkingEngines) return;
unawaited(_probeEngines());
}
@@ -320,7 +326,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
].join(' — ');
Future<void> _browse() async {
- if (_picking) return;
+ if (_picking || _choicesLocked) return;
final restoreFocus = _folderFocus.hasFocus;
// The agent runs on the MACHINE, so the folder has to exist on the machine
// — which is the whole reason this branches.
@@ -352,7 +358,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
if (!mounted) return;
setState(() {
_picking = false;
- if (picked != null && pickingRevision == _machineRevision) {
+ if (picked != null &&
+ !_choicesLocked &&
+ pickingRevision == _machineRevision) {
_folder = picked;
_error = null;
}
@@ -368,7 +376,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
} finally {
if (mounted && restoreFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && !_submitting && pickingRevision == _machineRevision) {
+ if (mounted &&
+ !_choicesLocked &&
+ pickingRevision == _machineRevision) {
_folderFocus.requestFocus();
}
});
@@ -378,12 +388,18 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Future<void> _submit() async {
final folder = _folder;
- if (folder == null || _submitting || _waitingForCodexProfile) return;
+ if (folder == null ||
+ _submitting ||
+ (!_confirmationPending && _waitingForCodexProfile)) {
+ return;
+ }
final engine = _engine;
final profile = _codexProfile;
final bypassPermission =
_bypassPermission && kEngineBypassPermissionFlag.containsKey(engine);
+ if (!_confirmationPending) _creation = AgentCreationAttempt();
setState(() {
+ _checkingCreation = _confirmationPending;
_submitting = true;
_error = null;
});
@@ -397,6 +413,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// Keep the explicit choice even if machine discovery changes mid-submit.
// The notifier must reject a now-remote target, never use its default login.
codexHome: engine == 'codex' ? profile?.path : null,
+ attempt: _creation,
);
if (!mounted) return;
if (error != null) {
@@ -404,6 +421,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_submitting = false;
_error = error;
});
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _actionFocus.requestFocus();
+ });
return;
}
analytics.agentCreated(engine: engine, bypassPermission: bypassPermission);
@@ -411,7 +431,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
}
Future<void> _cloneRepository() async {
- if (_picking || !_machineIsThisComputer) return;
+ if (_picking || _choicesLocked || !_machineIsThisComputer) return;
final revision = _machineRevision;
setState(() => _picking = true);
final folder = await showCloneRepositoryDialog(
@@ -421,7 +441,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
if (!mounted) return;
setState(() {
_picking = false;
- if (folder != null && revision == _machineRevision) {
+ if (folder != null && !_choicesLocked && revision == _machineRevision) {
_folder = folder;
_error = null;
}
@@ -448,7 +468,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Widget _buildDialog(BuildContext context) {
final bypassFlag = kEngineBypassPermissionFlag[_engine];
final canCreate =
- _folder != null && !_submitting && !_waitingForCodexProfile;
+ _folder != null &&
+ !_picking &&
+ !_submitting &&
+ (_confirmationPending || !_waitingForCodexProfile);
return AlertDialog(
title: Text(switch (widget.split?.axis) {
@@ -479,9 +502,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// thing on the screen was setting the size of the window for
// everybody who never turns it on.
AbsorbPointer(
- absorbing: _submitting,
+ absorbing: _choicesLocked,
child: ExcludeFocus(
- excluding: _submitting,
+ excluding: _choicesLocked,
child: _choices(bypassFlag),
),
),
@@ -491,8 +514,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
liveRegion: true,
child: Text(
_error!,
- style: Theme.of(context).textTheme.bodySmall
- ?.copyWith(color: Theme.of(context).colorScheme.error),
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: _confirmationPending
+ ? grid.AppPalette.textSecondary
+ : Theme.of(context).colorScheme.error,
+ ),
),
),
],
@@ -506,9 +532,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
style: TextButton.styleFrom(
foregroundColor: grid.AppPalette.textSecondary,
),
- child: const Text('Cancel'),
+ child: Text(_confirmationPending ? 'Close' : 'Cancel'),
),
FilledButton(
+ focusNode: _actionFocus,
onPressed: canCreate ? _submit : null,
style: FilledButton.styleFrom(
disabledForegroundColor: _submitting
@@ -518,21 +545,27 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
child: _submitting
? Semantics(
liveRegion: true,
- child: const Row(
+ child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- SizedBox(
+ const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2),
),
- SizedBox(width: 8),
- Text('Creating agent…'),
+ const SizedBox(width: 8),
+ Text(
+ _checkingCreation
+ ? 'Checking status…'
+ : 'Creating agent…',
+ ),
],
),
)
: Text(
- _machineIsThisComputer
+ _confirmationPending
+ ? 'Check status'
+ : _machineIsThisComputer
? 'Create agent'
: 'Create on $_machineName',
),
@@ -654,7 +687,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// folder" is the Create button being disabled. These two had nowhere
// else, and losing them would have made a machine that Harness has not
// managed to reach look exactly like one it has.
- if (_willInstall || _engineCheckFailed) ...[
+ if (!_confirmationPending && (_willInstall || _engineCheckFailed)) ...[
const SizedBox(height: 6),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -718,8 +751,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
if (agent.engine == 'codex' && agent.codexHome != null)
agent.codexHome!,
},
- onChanged: (profile) =>
- setState(() => _codexProfile = profile),
+ onChanged: (profile) {
+ if (!_choicesLocked) {
+ setState(() => _codexProfile = profile);
+ }
+ },
onBusyChanged: (busy) {
if (_codexProfilesBusy != busy) {
setState(() => _codexProfilesBusy = busy);
diff --git a/desktop/test/agent_creation_recovery_test.dart b/desktop/test/agent_creation_recovery_test.dart
new file mode 100644
index 000000000..6116475f2
--- /dev/null
+++ b/desktop/test/agent_creation_recovery_test.dart
@@ -0,0 +1,350 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/stats/harness_stats.dart';
+import 'package:harness/widgets/new_agent_dialog.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+class _Request {
+ _Request(this.type, this.payload);
+ final String type;
+ final Map<String, dynamic> payload;
+ final reply = Completer<Map<String, dynamic>>();
+ String get creationId => payload['creationId'] as String;
+ void status(String state, {Map<String, dynamic>? agent}) => reply.complete({
+ 'creationId': creationId,
+ 'state': state,
+ 'agent': ?agent,
+ });
+ void created([String id = 'created']) => status(
+ 'created',
+ agent: {'id': id, 'name': 'Recovered agent', 'engine': 'claude'},
+ );
+}
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final calls = <_Request>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'engines_probe') return Future.value({'engines': []});
+ if (type == 'codex_profiles_list') return Future.value({'profiles': []});
+ final request = _Request(type, Map.of(payload));
+ calls.add(request);
+ return request.reply.future;
+ }
+}
+
+Future<void> _timeOut(
+ AppNotifier app,
+ _Connection connection,
+ AgentCreationAttempt attempt,
+) async {
+ final create = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ connection.calls.last.reply.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ expect(await create, contains('Check status'));
+ expect(attempt.awaitingConfirmation, isTrue);
+}
+
+void main() {
+ test(
+ 'lost creation reply recovers into the original swarm and counts once',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final destination = app.activeSwarm;
+ final attempt = AgentCreationAttempt();
+ final before = harnessStats.summary.agentsSpawned;
+ await _timeOut(app, connection, attempt);
+ app.newSwarm(name: 'Another task');
+ final recover = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ expect(connection.calls.last.type, 'agent_create_status');
+ expect(
+ connection.calls.last.creationId,
+ connection.calls.first.creationId,
+ );
+ connection.calls.last.created();
+ expect(await recover, isNull);
+ expect(attempt.awaitingConfirmation, isFalse);
+ expect(destination.panes.single.agentId, 'created');
+ expect(app.activeSwarm.panes, isEmpty);
+ expect(harnessStats.summary.agentsSpawned, before + 1);
+ // Reusing the completed intent does not count or apply it a second time.
+ expect(
+ await app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ ),
+ isNull,
+ );
+ expect(connection.calls, hasLength(2));
+ expect(harnessStats.summary.agentsSpawned, before + 1);
+ },
+ );
+
+ test('concurrent submits share one request; a deliberate fresh intent gets a new id', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final attempt = AgentCreationAttempt();
+ final first = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ final duplicate = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ expect(connection.calls, hasLength(1));
+ connection.calls.single.created();
+ expect(await first, isNull);
+ expect(await duplicate, isNull);
+ final fresh = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: AgentCreationAttempt(),
+ );
+ expect(
+ connection.calls.last.creationId,
+ isNot(connection.calls.first.creationId),
+ );
+ connection.calls.last.created('new-intent');
+ expect(await fresh, isNull);
+ });
+
+ for (final result in [
+ 'unsupported',
+ 'timeout',
+ 'disconnect',
+ 'pending',
+ 'unconfirmed',
+ 'missing',
+ 'wrong receipt',
+ 'malformed',
+ ]) {
+ test('$result never turns a status check into another launch', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final attempt = AgentCreationAttempt();
+ await _timeOut(app, connection, attempt);
+ final recover = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ final check = connection.calls.last;
+ switch (result) {
+ case 'unsupported':
+ check.reply.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_create_status_result',
+ code: 'UNSUPPORTED',
+ ),
+ );
+ case 'timeout':
+ check.reply.completeError(
+ const WsRequestTimeout('agent_create_status'),
+ );
+ case 'disconnect':
+ check.reply.completeError(StateError('fixture disconnected'));
+ case 'wrong receipt':
+ check.reply.complete({
+ 'creationId': 'not-this-creation',
+ 'state': 'missing',
+ });
+ case 'malformed':
+ check.status('created', agent: {});
+ default:
+ check.status(result);
+ }
+ expect(await recover, isNotNull);
+ expect(attempt.awaitingConfirmation, isTrue);
+ expect(connection.calls.map((c) => c.type), [
+ 'agent_create',
+ 'agent_create_status',
+ ]);
+ expect(app.panes, isEmpty);
+ });
+ }
+
+ test(
+ 'changing launch choices cannot redirect an uncertain request',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final attempt = AgentCreationAttempt();
+ await _timeOut(app, connection, attempt);
+ expect(
+ await app.createAgent(
+ 'm',
+ engine: 'codex',
+ folder: '/different',
+ attempt: attempt,
+ ),
+ contains('original request'),
+ );
+ expect(connection.calls, hasLength(1));
+ expect(attempt.awaitingConfirmation, isTrue);
+ },
+ );
+
+ for (final state in ['failed', 'unavailable']) {
+ test(
+ 'a recorded $state outcome ends recovery without another launch',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final attempt = AgentCreationAttempt();
+ await _timeOut(app, connection, attempt);
+ final recover = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ final request = connection.calls.last;
+ request.reply.complete({
+ 'creationId': request.creationId,
+ 'state': state,
+ 'failure': {'code': 'CWD_NOT_FOUND'},
+ });
+ expect(
+ await recover,
+ contains(
+ state == 'failed' ? 'Choose another folder' : 'no longer available',
+ ),
+ );
+ expect(attempt.awaitingConfirmation, isFalse);
+ expect(connection.calls, hasLength(2));
+ },
+ );
+ }
+
+ test('closing the original swarm does not block recovery or add into a different swarm', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final original = app.activeSwarmId;
+ final attempt = AgentCreationAttempt();
+ await _timeOut(app, connection, attempt);
+ app.newSwarm(name: 'Other');
+ await app.closeSwarm(original);
+ final recover = app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ attempt: attempt,
+ );
+ connection.calls.last.created();
+ expect(await recover, isNull);
+ expect(app.panes, isEmpty);
+ expect(
+ app.stateOf('m')!.agents.any((agent) => agent.id == 'created'),
+ isTrue,
+ );
+ expect(app.lastError, contains('Find it with Add agent'));
+ });
+
+ testWidgets(
+ 'timeout keeps choices and keyboard focus on Check status, then opens the recovered agent',
+ (tester) async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.localOnly = true;
+ await tester.binding.setSurfaceSize(const Size(960, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'm',
+ source: 'test',
+ initialFolder: '/work',
+ initialEngineProbe: Future.value(),
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Create agent'));
+ await tester.pump();
+ connection.calls.last.reply.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('/work'), findsOneWidget);
+ expect(find.widgetWithText(FilledButton, 'Create agent'), findsNothing);
+ final action = tester.widget<FilledButton>(
+ find.widgetWithText(FilledButton, 'Check status'),
+ );
+ expect(action.focusNode!.hasFocus, isTrue);
+ expect(find.text('Close'), findsOneWidget);
+ // The original settings remain locked while the request is uncertain.
+ await tester.tap(find.text('Codex'), warnIfMissed: false);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(connection.calls.map((c) => c.type), [
+ 'agent_create',
+ 'agent_create_status',
+ ]);
+ connection.calls.last.created();
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(app.panes.single.agentId, 'created');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+}
diff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dart
index 29ee685ab..d4c74cf24 100644
--- a/desktop/test/agent_events_test.dart
+++ b/desktop/test/agent_events_test.dart
@@ -62,6 +62,7 @@ class FakeCreateAgentNotifier extends AppNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
}) async => null;
}
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 7c9546a64..1db255c9f 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -72,6 +72,7 @@ class _FirstUseApp extends AppNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
}) async {
launches.add((
machine: machineId,
diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dart
index a2df96095..7bb7982c9 100644
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@ -99,6 +99,7 @@ class _Notifier extends AppNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
}) async {
calls.add({'engine': engine, 'codexHome': codexHome, 'folder': folder});
return null;
diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dart
index 01408a6f8..36ff760f9 100644
--- a/desktop/test/new_agent_engine_check_test.dart
+++ b/desktop/test/new_agent_engine_check_test.dart
@@ -299,6 +299,7 @@ class _RetryNotifier extends AppNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
}) async {
launches.add({
'machine': machineId,
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
index adb381449..4cef1a534 100644
--- a/desktop/test/remote_folder_picker_test.dart
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -47,6 +47,7 @@ class _Folders extends AppNotifier {
String? codexHome,
String? swarmId,
PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
}) async {
launches.add((machine: machineId, engine: engine, folder: folder));
return null;
diff --git a/desktop/test/swarm_async_test.dart b/desktop/test/swarm_async_test.dart
index 014250f3e..8092ae7c2 100644
--- a/desktop/test/swarm_async_test.dart
+++ b/desktop/test/swarm_async_test.dart
@@ -102,7 +102,7 @@ void main() {
(
'SPAWN_FAILED',
'The machine could not allocate an agent process.',
- 'Create agent failed: The machine could not allocate an agent process.',
+ 'Test host has not confirmed the new agent yet. Check status before creating another.',
),
]) {
test(
@@ -140,7 +140,7 @@ void main() {
connection.reply.completeError(const WsRequestTimeout('agent_create'));
expect(
await creation,
- 'Test host has not confirmed the new agent yet. Check Search before creating another.',
+ 'Test host has not confirmed the new agent yet. Check status before creating another.',
);
expect(connection.calls, ['agent_create']);
expect(app.panes, isEmpty);
diff --git a/docs/harness-agent-creation.md b/docs/harness-agent-creation.md
index dba023dcc..e3a7816e9 100644
--- a/docs/harness-agent-creation.md
+++ b/docs/harness-agent-creation.md
@@ -15,8 +15,9 @@ separate from the proposed Archive/Resume lifecycle; it stops no existing agent.
report `missing`, `pending`, `created`, `failed`, `unconfirmed` or `unavailable`.
`created` includes the current agent frame. `failed` carries `failure.code`
and optional `failure.detail`, separate from RPC/transport errors.
-- A missing receipt reported by a supporting CLI permits retry with the same
- id. An unsupported request, malformed reply or transport failure does not.
+- A missing receipt does not prove that nothing started: an older CLI may have
+ launched the agent before being upgraded. Desktop status checks never resend
+ creation, including for missing/unsupported receipts and transport failures.
Do not use a `checkOnly` flag on `agent_create`: old CLIs would launch it.
- Receipt-aware creation is detached from the connection's ordered request
chain, so a status request can be answered while creation is still pending.
@@ -40,8 +41,9 @@ separate from the proposed Archive/Resume lifecycle; it stops no existing agent.
Legacy callers without `creationId` keep the existing create response. An older
CLI can also handle a new desktop's first create, ignoring the additional field.
-The desktop must check status before resending an uncertain request, including
-on old CLIs where status may be unsupported or time out.
+The desktop keeps an uncertain request on **Check status**. On old CLIs where
+status is unsupported or times out, it directs the user to **Add agent** to look
+for the existing runtime. It does not guess from a title or folder match.
September 14 CLI checkpoint: 150 affected checks pass (receipt storage,
BackendSocket creation, existing launch helper, E2EE and relay fixtures), along
@@ -49,7 +51,37 @@ with TypeScript checking and CLI bundling. The new BackendSocket recovery tests
failed before integration. All launch callbacks use fakes and all state/sockets
are disposable. The CLI bundle was not installed or restarted.
-The desktop recovery UI is the next part of this checkpoint. Real process
-creation across a remote disconnect remains to be verified. A crash between
-launch and receipt completion is conservatively unconfirmed, not automatically
-reconciled with the runtime registry. Native benchmarking remains deferred.
+## Desktop behavior
+
+The form keeps the same creation intent and original machine, folder, engine,
+profile, swarm and split. After an ambiguous reply, its choices stay visible and
+locked and the primary action becomes **Check status**. Keyboard focus returns
+to that action. Closing an uncertain request is labeled **Close**, not Cancel.
+A confirmed refusal unlocks the choices for correction; the next deliberate
+submission uses a new intent. Opening New agent also starts a fresh intent.
+
+Recovery opens the returned agent in the original swarm/position and counts the
+creation once. If that destination changed or closed, the runtime remains in
+the catalog for Add agent without opening a different tab or deleting anything.
+Concurrent submits for the same intent share one pending request. Late engine,
+profile and folder results cannot change the original launch choices.
+
+The receipt is durable on the CLI; the desktop form's intent is in memory. Closing
+the form or restarting the app currently ends that form's recovery path. A future
+pending-creations list could retain it across those boundaries. Do not describe
+this as automatic recovery across a desktop restart or an Archive/Resume feature.
+
+Desktop validation: 127 affected checks pass, including 15 creation-recovery
+regressions and the team's concurrent Option-Enter input tests. A separate
+real-font render check passes at 880×560 with normal and 2× text. Static analysis
+has no errors/warnings and the same 14 existing infos. The normal arm64 Release
+build succeeds at
+`/private/tmp/harness-creation-release/Build/Products/Release/Harness.app` with
+the production `lib/main.dart` entry point. It was not launched. Logs:
+`/private/tmp/harness-creation-{desktop-tests,final-recovery,analyze,release}.log`.
+The fixtures never create, stop or send input to a real agent.
+
+Real process creation across a remote disconnect remains to be verified. A crash
+between launch and receipt completion is conservatively unconfirmed, not
+automatically reconciled with the runtime registry. Native benchmarking remains
+deferred.
diff --git a/docs/harness-v2-appearance-onboarding.md b/docs/harness-v2-appearance-onboarding.md
index 11c269d1d..1135aa2ff 100644
--- a/docs/harness-v2-appearance-onboarding.md
+++ b/docs/harness-v2-appearance-onboarding.md
@@ -141,7 +141,7 @@ Rechecked the primary-source guidance on 2026-09-13: [Zed's welcome page](https:
The audit reproduced a pending-launch bug: Escape dismissed New agent despite its disabled Cancel button, leaving the request running without its outcome visible. The form now keeps the pending request visible with a readable “Creating agent…” state. It permits dismissal again when the request completes. A failed request retains the machine, folder and coding agent; selecting another folder or agent clears the obsolete error. Completion still opens the requested agent, with no automatic task input.
-Known missing/invalid-folder failures now name the target machine and ask the user to choose another folder. Missing tmux gets its required recovery instead of a wire code. Other server details remain visible. A request timeout is described as an unconfirmed outcome and directs the user to Search before creating another agent; it is never automatically retried. Protocol-level creation idempotency and late-reply reconciliation remain separate future reliability work.
+Known missing/invalid-folder failures name the target machine and ask the user to choose another folder. Missing tmux gets its required recovery instead of a wire code. The September 14 continuation adds [creation receipts and recovery](harness-agent-creation.md): after a timeout/disconnect, the form preserves and locks its choices and changes its primary action to **Check status**. Checking is read-only, even if an older CLI was upgraded after creation and has no receipt. A confirmed result opens the original agent in its intended swarm and counts once. If its destination changed, the agent remains discoverable in **Add agent**. Unknown results on older CLIs direct the user there as well. Form closure/app restart recovery and a real remote-disconnect exercise remain unfinished.
Validation: the new pending-launch regression failed before the fix and passed afterward. Forty-six focused onboarding/profile/split/async checks passed, plus isolated 880×560 renders of pending, invalid-folder and timeout states. These checks use synthetic state and requests; they do not install software, launch a provider, or send a task to a real agent.
diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.md
index ccf419ebe..ff0ff1573 100644
--- a/docs/harness-v2-handoff.md
+++ b/docs/harness-v2-handoff.md
@@ -27,6 +27,14 @@ with in-place retry and latest-request ownership. A pending or failed hop cannot
select the previous folder. These changes apply wherever the shared remote
chooser is used: agent working folders, saved projects and profile folders.
+[Creation recovery](harness-agent-creation.md) now distinguishes a delayed reply
+from a refused launch. The form retains its choices and offers **Check status**
+after a timeout/disconnect. That action only reads the original creation receipt;
+it never creates another agent. A confirmed agent returns to the original swarm
+or stays discoverable in Add if that destination changed. Older CLIs can still
+create normally, but cannot recover a lost result through this new status RPC.
+Form intents currently last for that open dialog; do not claim app-restart recovery.
+
## Goal
Build the best everyday workspace for people directing persistent AI agents:
@@ -51,6 +59,15 @@ Research must lead to justified improvements, not feature accumulation.
- Continue on **`main`**, tracking `origin/main`. The user's latest instruction
is to work, commit, and push directly on main from now on. This supersedes
the earlier preference for creating a fresh feature branch after each merge.
+- **`3585051`** records CLI creation receipts and encrypted status recovery.
+ **`7ae2cba`** preserves the team's main through PR #37 (`012c171`, Option-Enter
+ inserts a line break). The corresponding desktop continuation keeps unknown
+ outcomes on Check status, preserves the original destination and counts a
+ recovered creation once. The affected desktop checks include that incoming
+ terminal change: 127 checks pass, plus one real-font render check. Analysis
+ has zero errors/warnings and 14 existing infos. The normal arm64 Release
+ build succeeds at `/private/tmp/harness-creation-release/Build/Products/Release/Harness.app`;
+ it was not launched. CLI typechecking, bundling and 150 related checks pass.
- **`e73eb6e`** adds keyboard remote-folder selection and reliable asynchronous
browsing. The affected workflow/render checks (58 total), analysis and normal
Release build pass. **`8800c35`** preserves the team's concurrent main through
@@ -469,6 +486,11 @@ that its isolated window can become active/key.
machine/project starters are implemented. Check fresh dependencies, provider sign-in, cloning,
first task and adding a second agent; improve what the observation exposes.
Preserve choices on failure and the distinction between Navigate and Add.
+ Creation recovery is implemented and tested with isolated replies. Verify a
+ deliberately delayed remote create on a disposable agent, including an older
+ CLI and a changed original swarm. A status check must remain read-only. A
+ durable desktop pending-creations list and crash-window registry reconciliation
+ are still future work; the current dialog cannot resume its intent after closure.
3. **Recheck fresh terminal positioning and real workflows** on disposable
local/remote agents: startup, delayed snapshots, resizing, returning to a
scrolled view, reconnect, paste, selection, and IME.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 268a8aeb2..361939dd4 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -6,6 +6,23 @@ Updated 2026-09-14 after integrating the continuation into main. This is a worki
## Continue directly on main
+- Added [creation receipts and recovery](harness-agent-creation.md). A lost
+ creation reply now leaves the original choices visible and changes Create to
+ **Check status**, with keyboard focus on that action. Checking never launches
+ another agent, including on older/upgraded CLIs with no matching receipt.
+ Confirmed creation returns to the original swarm/position and counts once;
+ stale destinations leave it available in Add. The CLI retains completed and
+ uncertain outcomes across daemon restarts and rejects conflicting retries.
+ This does not implement Archive/Resume or restore closed desktop forms.
+ CLI typechecking, bundling and 150 affected checks pass; 127 desktop checks
+ pass, plus one real-font render check at 880×560 and normal/2× text. Analysis
+ has no errors/warnings and the same 14 existing infos. The normal arm64
+ Release build succeeds at
+ `/private/tmp/harness-creation-release/Build/Products/Release/Harness.app`.
+ Logs: `/private/tmp/harness-creation-{desktop-tests,final-recovery,analyze,release}.log`.
+ CLI code is saved in `3585051`; `7ae2cba` preserves the team's concurrent
+ Option-Enter fix from main (`012c171`). No real agent or running app was
+ started/stopped, and no benchmark ran. Live remote recovery remains unverified.
- Made the shared remote folder chooser work by keyboard: enter a full path,
browse with arrows/Enter, go up with Alt-Up, and select the loaded folder with
Cmd-Enter (Ctrl-Enter elsewhere). It names the target machine and keeps Home