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.

feat(mobile): clone a harness from its terminal menu, its folder and settings with a fresh conversation

tony8c6b692f1c8d
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index 4687444e0..9bddcbcaa 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -230,6 +230,14 @@ class Agent {
/// than the field — then [forkableEngines] decides. The desktop's `Agent.forkable`.
final bool? forkable;
+ /// Whether its permission prompts were bypassed at launch; null when unrecorded (see
+ /// [permissionMode]) — then a Clone uses the default. The desktop's `Agent.bypassPermission`.
+ final bool? bypassPermission;
+
+ /// The engine's own named agent it was opened as (`agent_create`'s `agent`, `namedAgent` on the
+ /// frame), or null for a general session. Read by Clone, so another opens as the same one.
+ final String? namedAgent;
+
const Agent({
required this.id,
this.sessionId,
@@ -263,6 +271,8 @@ class Agent {
this.closeSupported = false,
this.permissionMode,
this.forkable,
+ this.bypassPermission,
+ this.namedAgent,
});
factory Agent.fromJson(Map<String, dynamic> j) {
@@ -336,6 +346,10 @@ class Agent {
closeSupported: j['closeSupported'] == true,
permissionMode: _safePermissionMode(j['permissionMode']),
forkable: j['forkable'] is bool ? j['forkable'] as bool : null,
+ bypassPermission: j['bypassPermission'] is bool
+ ? j['bypassPermission'] as bool
+ : null,
+ namedAgent: _safeNamedAgent(j['namedAgent']),
);
}
@@ -372,6 +386,8 @@ class Agent {
closeSupported: closeSupported,
permissionMode: permissionMode,
forkable: forkable,
+ bypassPermission: bypassPermission,
+ namedAgent: namedAgent,
);
/// The engines whose sessions can be forked — natively (Claude Code's `--fork-session`,
@@ -384,6 +400,11 @@ class Agent {
/// drawn and refused.
bool get canFork => forkable ?? forkableEngines.contains(engine);
+ /// Whether Clone can open another of this one — any engine, but not one on a grid: the frame
+ /// carries the grid's model and never its launch key, so a clone would land on the engine's own
+ /// login instead. The desktop's `Agent.canClone`.
+ bool get canClone => engine != null && gridModel == null;
+
/// Saved work the daemon is no longer running, as the desktop's [Agent] reads
/// it. Its conversation is on disk; `agent_resume` brings it back.
///
@@ -447,6 +468,12 @@ class Agent {
static String? _safeResumeMode(Object? raw) =>
raw is String && _resumeModes.contains(raw) ? raw : null;
+ /// A named agent's id as the CLI accepts one (`AGENT_NAME_RE`) — the desktop's `_safeNamedAgent`.
+ static String? _safeNamedAgent(Object? raw) =>
+ raw is String && RegExp(r'^[A-Za-z0-9_-]{1,64}$').hasMatch(raw)
+ ? raw
+ : null;
+
/// A mode id as the CLI writes one — the desktop's `_safePermissionMode`, character for character.
static String? _safePermissionMode(Object? raw) =>
raw is String && RegExp(r'^[A-Za-z]{1,32}$').hasMatch(raw) ? raw : null;
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 1f516f97e..3fd340b76 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -3097,6 +3097,17 @@ class _TerminalPageState extends State<TerminalPage>
value: _forking ? 'forking…' : null,
onTap: () => unawaited(_fork()),
),
+ // Another of this one beside it — same folder and settings, a fresh conversation. The desktop's
+ // Clone Harness (⌘⇧N): no form, every answer is already on the agent. Not on a grid agent,
+ // whose launch key the frame never carries.
+ if (agent.canClone && !agent.isStopped)
+ PhoneSheetAction(
+ icon: LucideIcons.copyPlus300,
+ label: 'Clone',
+ value: _cloning ? 'cloning…' : null,
+ enabled: !_cloning,
+ onTap: () => unawaited(_clone()),
+ ),
PhoneSheetAction(
icon: LucideIcons.pencil300,
label: 'Rename…',
@@ -3134,6 +3145,33 @@ class _TerminalPageState extends State<TerminalPage>
bool get _forking =>
widget.notifier.agentForking(widget.machineId, widget.agentId);
+ /// Whether a Clone of this agent is on its way — see [AppNotifier.agentCloning].
+ bool get _cloning =>
+ widget.notifier.agentCloning(widget.machineId, widget.agentId);
+
+ /// Clone: the new harness opens once its machine confirms it, the source left as it is in the
+ /// same tab. What opens it is captured before the wait, as Change agent's is: the page can leave
+ /// on its own while the answer is out.
+ Future<void> _clone() async {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ final shell = PhoneShellScope.maybeOf(context);
+ final notifier = widget.notifier;
+ final machineId = widget.machineId;
+ final error = await notifier.cloneAgent(machineId, widget.agentId);
+ if (mounted) _putMenuAway();
+ if (error != null) {
+ messenger?.showSnackBar(SnackBar(content: Text(error)));
+ return;
+ }
+ final next = notifier.cloneAttempt(machineId, widget.agentId)?.agentId;
+ if (next == null) return;
+ if (mounted) {
+ openAgent(context, notifier, machineId, next);
+ } else {
+ shell?.onOpenAgent(machineId, next);
+ }
+ }
+
/// Fork: the form, then the fork opens — the source stays as it is, in the same tab.
///
/// ⚠️ **A fork outlives its form.** Closed while the fork is still out, the form says it carries
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 6b3923b5b..2f2237f93 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -198,6 +198,11 @@ class AgentCreationAttempt {
Map<String, dynamic>? _choices;
Future<String?>? _inFlight;
bool _awaitingConfirmation = false, _finished = false;
+
+ /// The Codex profile came off an agent the machine already runs on it (Clone), so the machine
+ /// is known to take one — the desktop's `_codexHomeTrusted`. The New form, which offers profiles
+ /// only from the machine's own engine list, leaves it false.
+ bool _codexHomeTrusted = false;
String? _outcome;
String? _agentId;
@@ -6286,6 +6291,117 @@ class AppNotifier extends ChangeNotifier {
);
}
+ /// Clones on their way or still to be confirmed, by machine and source agent — see [cloneAgent].
+ final Map<(String, String), AgentCreationAttempt> _agentClones = {};
+
+ /// Whether a Clone of this agent is on its way: the menu's row says so and takes no tap.
+ bool agentCloning(String machineId, String agentId) =>
+ _agentClones[(machineId, agentId)]?._inFlight != null;
+
+ /// Clone: another agent of the same kind as [agentId], with a fresh conversation — fork minus the
+ /// context. The desktop's `cloneAgent` (⌘⇧N): same machine, same project folder, same engine or
+ /// harness, Codex profile, named agent and permission mode, every one read off the agent's own
+ /// frame. Nothing of the source is touched, so a clone works while the source is busy or has no
+ /// conversation yet, where a fork would wait or refuse.
+ ///
+ /// A machine from before the frame carried the launch choices reports them null; the clone then
+ /// opens the way New Harness would by default. A terminal clones to a terminal in the same
+ /// folder, which the machine names itself.
+ ///
+ /// Null once the clone exists — its id is on [cloneAttempt] — else the sentence to show.
+ ///
+ /// ⚠️ **A lost reply is kept, receipt and all.** The machine may have started the clone, so the
+ /// next Clone of the same agent asks `agent_create_status` about the same receipt instead of
+ /// starting a second one; only a confirmed outcome lets it go.
+ Future<String?> cloneAgent(String machineId, String agentId) {
+ final key = (machineId, agentId);
+ final held = _agentClones[key];
+ if (held != null) {
+ if (held._inFlight case final inFlight?) return inFlight;
+ if (held.awaitingConfirmation) {
+ return _settleClone(key, checkAgentCreation(held), held);
+ }
+ _agentClones.remove(key);
+ }
+ final machine = machineStates[machineId];
+ if (machine == null) return Future.value('Machine not found');
+ final source = machine.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (source == null) {
+ return Future.value('The source harness is no longer available.');
+ }
+ final engine = source.engine;
+ if (engine == null) {
+ return Future.value('${source.displayName} has no engine to clone.');
+ }
+ if (!source.canClone) {
+ return Future.value(
+ '${source.displayName} runs on a grid; cloning a grid harness is not supported.',
+ );
+ }
+ final terminal = engine == 'terminal';
+ final cwd = source.project?.cwd;
+ if ((cwd == null || cwd.isEmpty) && !terminal) {
+ return Future.value(
+ '${source.displayName} has no project folder to clone into.',
+ );
+ }
+ final attempt = AgentCreationAttempt()
+ .._codexHomeTrusted = source.codexHome != null;
+ final work = _create(machineId, {
+ 'engine': engine,
+ if (cwd != null && cwd.isNotEmpty) 'cwd': cwd,
+ 'dsh': ?source.dsh,
+ if (engine == 'codex') 'codexHome': ?source.codexHome,
+ 'agent': ?source.namedAgent,
+ 'permissionMode': ?source.permissionMode,
+ // Unrecorded is not "off": an older machine's agent clones the way a new one would open. A
+ // terminal has no permissions to bypass. The desktop's rule.
+ 'bypassPermission': source.bypassPermission ?? !terminal,
+ // A terminal is named by the machine, as the desktop's ⌘⇧T is.
+ if (!terminal) 'name': cloneNameFor(source.displayName),
+ }, attempt: attempt);
+ _agentClones[key] = attempt;
+ return _settleClone(key, work, attempt);
+ }
+
+ /// The attempt behind the last Clone of [agentId], for the page to open what it started.
+ AgentCreationAttempt? cloneAttempt(String machineId, String agentId) =>
+ _agentClones[(machineId, agentId)];
+
+ /// Lets a clone's attempt go once its outcome is known — kept only while it is still to be
+ /// confirmed — and tells the menu it is no longer on its way.
+ Future<String?> _settleClone(
+ (String, String) key,
+ Future<String?> work,
+ AgentCreationAttempt attempt,
+ ) {
+ notifyListeners();
+ return work
+ .then(
+ // The New form's "Check status" is a button this menu does not have: here it is Clone
+ // again, which asks about the same receipt.
+ (error) => error != null && attempt.awaitingConfirmation
+ ? 'The clone is not confirmed yet. Tap Clone again to check '
+ 'before starting another.'
+ : error,
+ )
+ .whenComplete(() {
+ if (identical(_agentClones[key], attempt) &&
+ !attempt.awaitingConfirmation &&
+ attempt._inFlight == null &&
+ attempt.agentId == null) {
+ _agentClones.remove(key);
+ }
+ if (!_disposed) notifyListeners();
+ });
+ }
+
+ /// The name a clone is offered: the source's, marked as a clone — the desktop's `cloneNameFor`.
+ static String cloneNameFor(String name) =>
+ '${name.trim().isEmpty ? 'Harness' : name.trim()} - clone';
+
/// A Claude Code or Codex conversation Harness did not start, opened as a harness that resumes
/// it, in its own folder (Find's "not in Harness" rows, `ExternalSessionRef`) — the desktop's
/// `resumeConversation`. The machine refuses one open elsewhere, already a harness, or whose
@@ -6466,7 +6582,8 @@ class AppNotifier extends ChangeNotifier {
if (choices['engine'] != 'codex') {
return 'Choose a Codex profile only for Codex';
}
- if (machine.engines['codex']?.supportsCodexHome != true) {
+ if (!creation._codexHomeTrusted &&
+ machine.engines['codex']?.supportsCodexHome != true) {
return 'Update the harness CLI on this machine to choose a Codex profile';
}
}
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index 199a9d69c..be2184867 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -634,6 +634,44 @@ void main() {
},
)..handshaken = true;
+ testWidgets('Clone opens another of this one, in the same folder, and the '
+ 'source stays as it was', (tester) async {
+ final conn = EdgeConn(const {}, startsAgents)..handshaken = true;
+ final focus = await openMenu(tester, connection: conn);
+ await tapInView(tester, find.text('Clone'));
+ for (var i = 0; i < 40 && focus.opened.isEmpty; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ final [sent] = conn.payloads['agent_create']!;
+ expect(sent['engine'], 'claude');
+ expect(sent['cwd'], '/code/$longProject');
+ expect(sent['name'], 'a - clone');
+ expect(focus.opened, [('m', 'new-agent')]);
+ expect(conn.requests, isNot(contains('agent_close')));
+ await focus.close();
+ });
+
+ testWidgets('Clone, while it is out, says so and cannot be pressed '
+ 'again', (tester) async {
+ final reply = Completer<Map<String, dynamic>>();
+ final conn = _HeldCreateConn(reply.future)..handshaken = true;
+ final focus = await openMenu(tester, connection: conn);
+ await tapInView(tester, find.text('Clone'));
+ await frames(tester);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ expect(find.text('cloning…'), findsOneWidget);
+ await tapInView(tester, find.text('Clone'));
+ await frames(tester);
+ expect(conn.payloads['agent_create'], hasLength(1));
+
+ reply.complete({'error': 'BUSY'});
+ await frames(tester);
+ await focus.close();
+ });
+
testWidgets('Fork is offered where the machine can fork, and not on a '
'terminal', (tester) async {
var focus = await openMenu(tester);
@@ -2836,6 +2874,27 @@ class _PurgeConn extends EdgeConn {
}
}
+/// A machine whose `agent_create` answers only when [reply] does — a clone still on its way.
+class _HeldCreateConn extends EdgeConn {
+ _HeldCreateConn(this.reply);
+
+ final Future<Map<String, dynamic>> reply;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'agent_create') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ requests.add(type);
+ (payloads[type] ??= []).add(payload);
+ return reply;
+ }
+}
+
class _Pushes extends NavigatorObserver {
_Pushes(this.pushed);
diff --git a/mobile/test/state/clone_agent_test.dart b/mobile/test/state/clone_agent_test.dart
new file mode 100644
index 000000000..3bdbf1be0
--- /dev/null
+++ b/mobile/test/state/clone_agent_test.dart
@@ -0,0 +1,250 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+import '../viewer_app_fixture.dart';
+
+/// Clone from the phone: another harness of the same kind, in the same folder, with a fresh
+/// conversation — the desktop's Clone Harness (⌘⇧N). What the machine is asked for, read off the
+/// source's own frame, and that a lost reply is checked rather than answered with a second clone.
+void main() {
+ /// A signed-in phone whose machine `m` lists [agents] and creates what it is asked for as `c`.
+ Future<ViewerRig> rigWith(List<Map<String, dynamic>> agents) async {
+ final rig = viewerApp();
+ rig.api.onMachines = () async => [remoteMachine('m')];
+ final answers = rig.conn('m').answers;
+ answers['agents_list'] = (_) => {'agents': agents};
+ answers['terminal_capabilities'] = (_) => capabilities();
+ answers['agent_create'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('c', engine: p['engine'] as String),
+ };
+ await rig.app.bootstrap();
+ await settle();
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ await settle();
+ addTearDown(rig.app.dispose);
+ return rig;
+ }
+
+ List<String> listed(ViewerRig rig) => [
+ for (final agent in rig.app.stateOf('m')!.agents) agent.id,
+ ];
+
+ group('the frame', () {
+ test('carries what a clone is launched with', () {
+ final agent = Agent.fromJson(
+ agentJson(
+ 'a',
+ extra: {'bypassPermission': false, 'namedAgent': 'reviewer'},
+ ),
+ );
+ expect(agent.bypassPermission, isFalse);
+ expect(agent.namedAgent, 'reviewer');
+ expect(agent.canClone, isTrue);
+ });
+
+ test('a named agent that is not an id is not read as one', () {
+ final agent = Agent.fromJson(
+ agentJson('a', extra: {'namedAgent': '../etc/passwd'}),
+ );
+ expect(agent.namedAgent, isNull);
+ });
+
+ test('a grid agent cannot be cloned', () {
+ final agent = Agent.fromJson(
+ agentJson(
+ 'a',
+ extra: {
+ 'grid': {'model': 'qwen3-coder'},
+ },
+ ),
+ );
+ expect(agent.canClone, isFalse);
+ });
+ });
+
+ test('the same folder, engine, harness, profile, named agent and mode, '
+ 'under a fresh name — and the clone joins the list', () async {
+ final rig = await rigWith([
+ agentJson(
+ 'a',
+ name: 'api',
+ engine: 'codex',
+ extra: {
+ 'codexHome': '/Users/me/.codex-work',
+ 'dsh': 'autonomous/kicad',
+ 'namedAgent': 'reviewer',
+ 'permissionMode': 'plan',
+ 'bypassPermission': false,
+ },
+ ),
+ ]);
+
+ final error = await rig.app.cloneAgent('m', 'a');
+
+ expect(error, isNull);
+ final [sent] = rig.conn('m').payloadsOf('agent_create');
+ expect(Map.of(sent)..remove('creationId'), {
+ 'engine': 'codex',
+ 'cwd': '/work',
+ 'dsh': 'autonomous/kicad',
+ 'codexHome': '/Users/me/.codex-work',
+ 'agent': 'reviewer',
+ 'permissionMode': 'plan',
+ 'bypassPermission': false,
+ 'name': 'api - clone',
+ });
+ expect(rig.app.cloneAttempt('m', 'a')?.agentId, 'c');
+ expect(listed(rig), containsAll(['a', 'c']));
+ expect(rig.app.agentCloning('m', 'a'), isFalse);
+ });
+
+ test('a launch the machine never recorded clones the way a new one '
+ 'opens', () async {
+ final rig = await rigWith([agentJson('a')]);
+
+ await rig.app.cloneAgent('m', 'a');
+
+ final [sent] = rig.conn('m').payloadsOf('agent_create');
+ expect(sent['bypassPermission'], isTrue);
+ expect(sent.containsKey('permissionMode'), isFalse);
+ expect(sent.containsKey('agent'), isFalse);
+ expect(sent.containsKey('dsh'), isFalse);
+ });
+
+ test('a terminal clones to a terminal the machine names, with nothing to '
+ 'bypass', () async {
+ final rig = await rigWith([agentJson('t', engine: 'terminal')]);
+
+ expect(await rig.app.cloneAgent('m', 't'), isNull);
+
+ final [sent] = rig.conn('m').payloadsOf('agent_create');
+ expect(sent['engine'], 'terminal');
+ expect(sent['cwd'], '/work');
+ expect(sent['bypassPermission'], isFalse);
+ expect(sent.containsKey('name'), isFalse);
+ });
+
+ test('a profile outside Codex is not sent', () async {
+ final rig = await rigWith([
+ agentJson('a', extra: {'codexHome': '/Users/me/.codex-work'}),
+ ]);
+
+ await rig.app.cloneAgent('m', 'a');
+
+ expect(
+ rig.conn('m').payloadsOf('agent_create').single.containsKey('codexHome'),
+ isFalse,
+ );
+ });
+
+ test('what cannot be cloned says why and asks nothing', () async {
+ final rig = await rigWith([
+ agentJson(
+ 'g',
+ extra: {
+ 'grid': {'model': 'qwen3-coder'},
+ },
+ ),
+ {...agentJson('n'), 'project': null},
+ ]);
+
+ expect(
+ await rig.app.cloneAgent('m', 'g'),
+ 'g runs on a grid; cloning a grid harness is not supported.',
+ );
+ expect(
+ await rig.app.cloneAgent('m', 'n'),
+ 'n has no project folder to clone into.',
+ );
+ expect(
+ await rig.app.cloneAgent('m', 'gone'),
+ 'The source harness is no longer available.',
+ );
+ expect(rig.conn('m').payloadsOf('agent_create'), isEmpty);
+ });
+
+ test('pressed again while it is out joins the first', () async {
+ final rig = await rigWith([agentJson('a')]);
+ final reply = Completer<Map<String, dynamic>>();
+ rig.conn('m').answers['agent_create'] = (_) => reply.future;
+
+ final first = rig.app.cloneAgent('m', 'a');
+ final second = rig.app.cloneAgent('m', 'a');
+ expect(rig.app.agentCloning('m', 'a'), isTrue);
+ final [sent] = rig.conn('m').payloadsOf('agent_create');
+ reply.complete({
+ 'creationId': sent['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('c'),
+ });
+
+ expect(await first, isNull);
+ expect(await second, isNull);
+ expect(rig.conn('m').payloadsOf('agent_create'), hasLength(1));
+ expect(rig.app.agentCloning('m', 'a'), isFalse);
+ });
+
+ test('a lost reply is checked under the same receipt the next time, never '
+ 'cloned again', () async {
+ final rig = await rigWith([agentJson('a')]);
+ final conn = rig.conn('m');
+ conn.answers['agent_create'] = (_) =>
+ throw const WsRequestTimeout('agent_create');
+
+ expect(
+ await rig.app.cloneAgent('m', 'a'),
+ 'The clone is not confirmed yet. Tap Clone again to check before '
+ 'starting another.',
+ );
+
+ conn.answers['agent_create_status'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('c'),
+ };
+ expect(await rig.app.cloneAgent('m', 'a'), isNull);
+
+ final receipt = conn.payloadsOf('agent_create').single['creationId'];
+ expect(conn.payloadsOf('agent_create_status'), [
+ {'creationId': receipt},
+ ]);
+ expect(rig.app.cloneAttempt('m', 'a')?.agentId, 'c');
+
+ // Confirmed, it is let go: the next Clone is a new one.
+ conn.answers['agent_create'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('d'),
+ };
+ await rig.app.cloneAgent('m', 'a');
+ expect(conn.payloadsOf('agent_create'), hasLength(2));
+ expect(rig.app.cloneAttempt('m', 'a')?.agentId, 'd');
+ });
+
+ test('a refusal before anything started is said, and the next Clone is a '
+ 'new request', () async {
+ final rig = await rigWith([agentJson('a')]);
+ final conn = rig.conn('m');
+ conn.answers['agent_create'] = (_) => throw refusal('CWD_NOT_FOUND');
+
+ expect(
+ await rig.app.cloneAgent('m', 'a'),
+ 'The project folder is unavailable on Machine m. Choose another '
+ 'folder and try again.',
+ );
+
+ conn.answers['agent_create'] = (p) => {
+ 'creationId': p['creationId'],
+ 'state': 'created',
+ 'agent': agentJson('c'),
+ };
+ expect(await rig.app.cloneAgent('m', 'a'), isNull);
+ final [first, second] = conn.payloadsOf('agent_create');
+ expect(first['creationId'], isNot(second['creationId']));
+ });
+}