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(desktop): Clone Agent (⌘⇧N) — another of the focused agent, fresh conversation (#174)

0xken150fbf5723bfe8
diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.ts
index 8cea8fddb..a214af6fa 100644
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@ -68,6 +68,25 @@ describe('agentFrame', () => {
expect(await agentFrame(session(null), { selectedModel: null, terminalAvailable: true })).toHaveProperty('viewerName', null)
})
+ // What the desktop's Clone (⌘⇧N) sends back through `agent_create`: the choices only the registry
+ // row holds. Without them a clone of a Plan-mode reviewer would come up as an auto-mode general.
+ it('carries the launch choices a clone needs', async () => {
+ const row = session(null)
+ row.permissionMode = 'plan'
+ row.bypassPermission = false
+ row.agent = 'reviewer'
+ expect(await agentFrame(row, { selectedModel: null, terminalAvailable: true }))
+ .toMatchObject({ permissionMode: 'plan', bypassPermission: false, namedAgent: 'reviewer' })
+ })
+
+ it('reports unrecorded launch choices as null rather than omitting them', async () => {
+ const frame = await agentFrame(session(null), { selectedModel: null, terminalAvailable: true })
+ expect(frame).toHaveProperty('permissionMode', null)
+ expect(frame).toHaveProperty('bypassPermission', null)
+ expect(frame).toHaveProperty('namedAgent', null)
+ expect(frame).not.toHaveProperty('agent')
+ })
+
it('reports launch state and defaults legacy agents to ready', async () => {
const legacy = session(null)
expect(await agentFrame(legacy, { selectedModel: null, terminalAvailable: true }))
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index b64b87165..a634853cd 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -78,6 +78,18 @@ export type AgentFrame = {
/** Whether `agent_fork` can do anything for this engine (lib/forkAgent.ts) — natively, or by a
* handoff. A client hides the Fork action on a false rather than offering a button that refuses. */
forkable: boolean
+ /**
+ * The launch choices a client needs to open ANOTHER agent like this one — the desktop's Clone
+ * (`agent_create` with the same `permissionMode`, `bypassPermission` and `agent`). Read off the
+ * registry row, never off the live process. Each null is a real answer: a row from before the
+ * choice existed, or an agent Harness did not launch, has none to report — and a clone of one
+ * falls back to the client's own defaults rather than to a guess made here.
+ */
+ permissionMode: string | null
+ bypassPermission: boolean | null
+ /** The engine's named agent (`agent_create`'s `agent`); `namedAgent` on the wire so an agent
+ * object never carries a key called `agent`. */
+ namedAgent: string | null
}
/** What the daemon knows about an agent's DSH — looked up by the caller, never here. */
@@ -152,5 +164,8 @@ export async function agentFrame(
verdict: dsh?.verdict ?? null,
forkedFrom: s.forkedFrom ? { agentId: s.forkedFrom.agentId, name: s.forkedFrom.name } : null,
forkable: engineCanFork(s.engine),
+ permissionMode: s.permissionMode ?? null,
+ bypassPermission: s.bypassPermission ?? null,
+ namedAgent: s.agent ?? null,
}
}
diff --git a/desktop/design/super-terminal-interaction.md b/desktop/design/super-terminal-interaction.md
index a445f7fb0..62dacceeb 100644
--- a/desktop/design/super-terminal-interaction.md
+++ b/desktop/design/super-terminal-interaction.md
@@ -489,6 +489,25 @@ legacy response requires checking existing agents before explicitly starting
another. The desktop draft and receipt reference last for the current window,
not across app restarts.
+## Cloning an agent
+
+“Clone Agent” (⇧⌘N, File menu, pane command search) is fork minus the
+context: another agent of the focused pane's kind with a fresh conversation.
+There is no prompt, as with ⇧⌘T — every answer is already on the agent's
+frame: its machine (its own or a relayed one), project folder, engine or
+harness, Codex profile, named agent, and permission mode. The clone is named
+`<source> - clone`, opens as another tile in the current tab, and takes
+focus; the source is not touched, so a clone works while the source is busy
+or has no session yet, where a fork would wait or refuse. A terminal clones
+to a terminal in the same folder. An agent on a grid is refused before asking,
+since the frame carries the grid's model and never its key.
+
+The launch choices come from the CLI's agent frame (`permissionMode`,
+`bypassPermission`, `namedAgent`). A daemon that predates them reports none,
+and the clone then opens the way New Harness would by default — folder,
+harness and profile still carry. Errors surface as a snackbar; there is no
+receipt to reopen, and a second ⇧⌘N is a second clone.
+
A confirmed fork opens in its original tab without stealing focus if the user
has moved elsewhere. If that tab closed, or filled while the user moved away,
the agent stays available through New Pane/New Tab. A full tab still in focus
diff --git a/desktop/design/terminal-review-checklist.md b/desktop/design/terminal-review-checklist.md
index cafb3ea9a..852589875 100644
--- a/desktop/design/terminal-review-checklist.md
+++ b/desktop/design/terminal-review-checklist.md
@@ -224,28 +224,35 @@ Escape or Cmd-Shift-J closes the experimental prompt.
and reopen to check its draft, then fork. The source should stay intact;
the new agent should open at the original destination. The prompt explains
conversation continuation versus a handoff when supported by the engine.
-25. **Restart Agent / Restart Terminal.** This starts immediately. Check the
+25. **Clone Agent (⇧⌘N).** On an owned agent in Plan or Read-only mode, with a
+ Codex profile or a named agent if one is at hand. A new tile opens beside
+ it at once, named `<source> - clone`, in the same folder with the same mode
+ (check the launch argv) and an empty conversation; the source is untouched
+ and the tab count does not change. Works the same on a linked remote
+ machine; a remote CLI too old to report modes clones in auto mode. A
+ terminal pane clones to a terminal; a grid agent is refused with a message.
+26. **Restart Agent / Restart Terminal.** This starts immediately. Check the
compact pending prompt; close/reopen it while pending if timing permits.
Existing views should remain. A fresh agent conversation should be clearly
reported; a shell restart simply starts a fresh shell.
-26. **Stop Agent / Stop Terminal.** The confirmation names the target and
+27. **Stop Agent / Stop Terminal.** The confirmation names the target and
initially focuses Cancel. Enter should cancel; Tab then Enter should stop.
A confirmed stop should close that agent's views across tabs and leave
unrelated terminals usable.
## Machines and keyboard customization
-27. **Open Machines Manager.** Filter by name or status, Enter into actions,
+28. **Open Machines Manager.** Filter by name or status, Enter into actions,
and Escape back twice. Queries and selection should survive nested
prompts and refresh. Try keyboard-only machine renaming if desired.
-28. **Link machine.** Search existing machines or open desktop/SSH setup.
+29. **Link machine.** Search existing machines or open desktop/SSH setup.
Copy controls, links, refresh, and back navigation should work without a
mouse. A machine's password prompt should accept typing immediately.
-29. **This computer's password / Links from this computer.** Open these via
+30. **This computer's password / Links from this computer.** Open these via
Machines Manager. Review the wording and keyboard navigation; setting or
clearing a password and unlinking make real changes. Clear/unlink
confirmations start on Cancel and explain their scope.
-30. **Keyboard shortcuts and Edit keybindings.** Find both through command
+31. **Keyboard shortcuts and Edit keybindings.** Find both through command
search. Try a custom binding in `~/.config/harness/keybindings.jsonc`
(or the shown XDG config path). Live hints and prompt behavior should follow
the change; invalid config should keep the last working bindings.
diff --git a/desktop/lib/core/agent_names.dart b/desktop/lib/core/agent_names.dart
new file mode 100644
index 000000000..769f07475
--- /dev/null
+++ b/desktop/lib/core/agent_names.dart
@@ -0,0 +1,11 @@
+/// The names a derived agent starts with, before the engine reports a title.
+/// One place so a fork and a clone read as siblings in the rail: `<source> - fork`,
+/// `<source> - clone`. A blank source name falls back to "Agent".
+library;
+
+String forkNameFor(String name) => '${_baseName(name)} - fork';
+
+/// Clone (⌘⇧N): another agent of the same kind with a fresh conversation.
+String cloneNameFor(String name) => '${_baseName(name)} - clone';
+
+String _baseName(String name) => name.trim().isEmpty ? 'Agent' : name.trim();
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 5d3e10359..27e4edcc7 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -280,6 +280,20 @@ class Agent {
/// decides (see [canFork]).
final bool? forkable;
+ /// The permission mode this agent was launched in (`plan`, `readOnly`, …),
+ /// as the daemon recorded it; null from a daemon that predates the field, a
+ /// row from before the choice existed, or an agent Harness did not launch.
+ /// Read for Clone (⌘⇧N), so another of this one opens in the same mode.
+ final String? permissionMode;
+
+ /// Whether its permission prompts were bypassed at launch; null when
+ /// unrecorded (see [permissionMode]) — then a clone uses the default.
+ final bool? bypassPermission;
+
+ /// The engine's own named agent it was opened as (`agent_create`'s `agent`),
+ /// or null for a general session.
+ final String? namedAgent;
+
const Agent({
required this.id,
this.sessionId,
@@ -307,6 +321,9 @@ class Agent {
this.verdict,
this.forkedFrom,
this.forkable,
+ this.permissionMode,
+ this.bypassPermission,
+ this.namedAgent,
});
/// Explicit names win. An automatic CLI label gives way to its session title.
@@ -325,6 +342,11 @@ class Agent {
/// rather than drawn and refused.
bool get canFork => forkable ?? forkableEngines.contains(engine);
+ /// Whether Clone (⌘⇧N) can open another of this agent — any engine, but not
+ /// one on a grid: the frame carries the grid's model and never its launch
+ /// key, so a clone would silently land on the engine's own login instead.
+ bool get canClone => engine != null && gridModel == null;
+
/// What to draw this agent AS: its harness when it has one, else its engine.
String? get identityEngine => dsh ?? engine;
@@ -388,6 +410,11 @@ class Agent {
verdict: AgentVerdict.fromJson(j['verdict']),
forkedFrom: ForkedFrom.fromJson(j['forkedFrom']),
forkable: j['forkable'] is bool ? j['forkable'] as bool : null,
+ permissionMode: _safePermissionMode(j['permissionMode']),
+ bypassPermission: j['bypassPermission'] is bool
+ ? j['bypassPermission'] as bool
+ : null,
+ namedAgent: _safeNamedAgent(j['namedAgent']),
);
}
@@ -418,8 +445,24 @@ class Agent {
verdict: verdict,
forkedFrom: forkedFrom,
forkable: forkable,
+ permissionMode: permissionMode,
+ bypassPermission: bypassPermission,
+ namedAgent: namedAgent,
);
+ /// A mode id as `PERMISSION_MODES` spells them (`acceptEdits`, `readOnly`):
+ /// one word. Not checked against this build's own list — the daemon that
+ /// launched the agent is the authority, and it is the one that will read the
+ /// id back on a clone.
+ static String? _safePermissionMode(Object? raw) =>
+ raw is String && RegExp(r'^[A-Za-z]{1,32}$').hasMatch(raw) ? raw : null;
+
+ /// The daemon's `AGENT_NAME_RE` (engineLaunch.ts): a flag value, never a path.
+ static String? _safeNamedAgent(Object? raw) =>
+ raw is String && RegExp(r'^[A-Za-z0-9_-]{1,64}$').hasMatch(raw)
+ ? raw
+ : null;
+
/// `owner/name`, exactly the shape the DSH manifest schema allows and nothing else — the
/// id names an install directory on the far machine and a picker tile here.
static String? _safeDsh(Object? raw) {
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 1524b622b..cb9f99701 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -897,6 +897,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'commands' => 'navigation.commands',
'newAgent' => 'agent.new',
'newTerminal' => 'terminal.new',
+ 'cloneAgent' => 'agent.clone',
_ => null,
};
if (nativeCommand != null) {
@@ -999,6 +1000,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
unawaited(_newAgent(swarmId: app.activeSwarmId));
case 'newTerminal':
unawaited(_newTerminal());
+ case 'cloneAgent':
+ unawaited(_cloneAgent());
case 'runLocalModel':
// Native commands arrive above the Actions subtree. Use the same
// product entry directly; a dialog guard would block the dock.
@@ -1124,6 +1127,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'addAgent',
'newAgent',
'newTerminal',
+ 'cloneAgent',
'runLocalModel',
'manageMachines',
'machineList',
@@ -1760,6 +1764,32 @@ class _SwarmScreenState extends State<SwarmScreen> {
unawaited(_ensureEmptyEntry());
}
+ /// ⌘⇧N — another agent of the focused pane's kind, fresh conversation.
+ /// No dialog, like ⌘⇧T: the answer to every question a dialog would ask is
+ /// already on the source agent's frame (`AppNotifier.cloneAgent`). The
+ /// chord is gated by `_canExecuteCommand`; the File menu is not, so a click
+ /// with nothing to clone from says so instead of doing nothing.
+ Future<void> _cloneAgent() async {
+ final pane = app.focusedPane;
+ final agent = _focusedAgent;
+ final String? error;
+ if (pane == null || agent == null) {
+ error = 'Focus an agent pane to clone it.';
+ } else if (app.stateOf(pane.machineId)?.machine.isShared != false) {
+ error = 'Shared agents are view-only.';
+ } else {
+ error = await app.cloneAgent(
+ pane.machineId,
+ agent.id,
+ swarmId: app.activeSwarmId,
+ );
+ }
+ if (error != null && mounted) {
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text(error)));
+ }
+ }
+
/// ⌘⇧T: a shell in a new tile, no dialog — the way a terminal app opens a
/// tab. It lands on the machine the focused tile is on (this computer when
/// nothing is focused), in the folder that tile's harness works in, else
@@ -2358,6 +2388,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
ShortcutAction.newAgent: _newAgent,
ShortcutAction.newTerminal: _newTerminal,
+ ShortcutAction.cloneAgent: _cloneAgent,
ShortcutAction.routeTask: () =>
_dialog(() => showTaskPalette(context, app)),
ShortcutAction.orchestrate: () =>
@@ -2431,13 +2462,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (id == 'agent.rename' ||
id == 'agent.stop' ||
id == 'agent.fork' ||
+ id == 'agent.clone' ||
id == 'agent.restart') {
final pane = app.focusedPane;
final machine = pane == null ? null : app.stateOf(pane.machineId);
+ // Clone and restart both ask the daemon for a launch, so both need it
+ // reachable; clone is not gated on `canFork` — any engine can be opened
+ // again, only a fork needs the engine to carry a conversation over.
return machine != null &&
!machine.machine.isShared &&
(id != 'agent.fork' || _focusedAgent?.canFork == true) &&
- (id != 'agent.restart' ||
+ (id != 'agent.clone' || _focusedAgent?.canClone == true) &&
+ ((id != 'agent.restart' && id != 'agent.clone') ||
(machine.nodeOnline != false && !machine.needsLink)) &&
machine.agents.any((agent) => agent.id == pane!.agentId);
}
@@ -2522,6 +2558,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
?mode('agent.new', 'New Harness', 'agent · machine · project'),
?mode('app.store', 'Harness Store', 'Browse and install harnesses'),
?mode('terminal.new', 'New terminal', 'A shell where you are'),
+ ?mode(
+ 'agent.clone',
+ 'Clone Agent',
+ 'Another of this one, fresh conversation',
+ ),
?mode('navigation.needs_input', 'Agents needing input', 'Who is waiting'),
?mode('navigation.history', 'History', 'Where you have been'),
?mode('task.route', 'Boss mode', 'Describe a task, it picks the agent'),
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 4d11bc602..69c8675ec 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -58,6 +58,11 @@ enum ShortcutAction {
/// A plain shell in a pane, like a native terminal's new tab — the daemon
/// treats whatever engine is later typed into it as the pane's agent.
newTerminal,
+
+ /// Another agent of the focused pane's kind — same machine, folder, harness,
+ /// profile and permission mode — with a fresh conversation: fork minus the
+ /// context. No dialog, like [newTerminal].
+ cloneAgent,
routeTask,
orchestrate,
reload,
@@ -379,6 +384,18 @@ const kSwarmShortcuts = [
label: 'New Terminal',
group: ShortcutGroup.actions,
),
+ // ⌘⇧N was Create Agent until ⌘N became New Harness (01989f5a); reclaimed
+ // for its shifted sibling: ⌘N starts a new one, ⌘⇧N another of this one.
+ AppShortcut(
+ action: ShortcutAction.cloneAgent,
+ activator: SingleActivator(
+ LogicalKeyboardKey.keyN,
+ meta: true,
+ shift: true,
+ ),
+ label: 'Clone Agent',
+ group: ShortcutGroup.actions,
+ ),
AppShortcut(
action: ShortcutAction.closeSwarm,
activator: SingleActivator(LogicalKeyboardKey.keyW, meta: true),
diff --git a/desktop/lib/shortcuts/keyboard_practice.dart b/desktop/lib/shortcuts/keyboard_practice.dart
index 2b191a6c6..c47016144 100644
--- a/desktop/lib/shortcuts/keyboard_practice.dart
+++ b/desktop/lib/shortcuts/keyboard_practice.dart
@@ -74,6 +74,7 @@ class KeyboardLesson {
'Restart Agent\nA fresh conversation starts in the same project.',
'agent.fork' =>
'Fork Agent\nChoose a name and first task. The source stays open.',
+ 'agent.clone' => 'Clone Agent\nAnother of this one opens beside it: same folder and settings, fresh conversation.',
'app.store' =>
'[Harness Store]\nFind a harness for the kind of work you want to do.',
'pane.focus_left' ||
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 9a72d87ba..65a4d205d 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -302,6 +302,14 @@ final harnessCommands = <HarnessCommand>[
const HarnessCommand('agent.rename', 'Rename Agent', ShortcutGroup.actions),
const HarnessCommand('agent.stop', 'Stop Agent', ShortcutGroup.actions),
const HarnessCommand('agent.fork', 'Fork Agent', ShortcutGroup.actions),
+ const HarnessCommand(
+ 'agent.clone',
+ 'Clone Agent',
+ ShortcutGroup.actions,
+ action: ShortcutAction.cloneAgent,
+ nativeAction: 'cloneAgent',
+ keywords: ['duplicate', 'another', 'fresh'],
+ ),
const HarnessCommand('agent.restart', 'Restart Agent', ShortcutGroup.actions),
const HarnessCommand(
'terminal.new',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c1b5fa2d2..ce61e4991 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -22,6 +22,7 @@ import '../auth/cli_login.dart';
import '../bootstrap/environment_provisioner.dart';
import '../core/viewer_mode.dart';
import '../core/config.dart';
+import '../core/agent_names.dart';
import '../core/agent_preference.dart';
import '../core/dsh_catalog.dart';
import '../core/engine_availability.dart';
@@ -184,6 +185,11 @@ class AgentCreationAttempt {
String? _remoteProjectName;
int _projectNameRetries = 0;
+ /// The `codexHome` came off this machine's own agent frame (a clone), so the
+ /// daemon there evidently supports it — the capability probe, which only
+ /// New Harness runs, is not needed to prove it.
+ bool _codexHomeTrusted = false;
+
bool get awaitingConfirmation => _awaitingConfirmation;
/// A completed folder survives a refused agent launch, so correcting the
@@ -6061,6 +6067,10 @@ class AppNotifier extends ChangeNotifier {
'This first task is too long for $machine. Shorten it and try again.',
'AGENT_UNSUPPORTED' =>
'This engine cannot be opened as a named agent on $machine.',
+ 'INVALID_AGENT' =>
+ 'This engine cannot be opened as that named agent on $machine.',
+ 'INVALID_PERMISSION_MODE' =>
+ 'This engine has no such permission mode on $machine.',
// A daemon that predates the terminal engine refuses it by name; the
// fix is the same one the other UNSUPPORTED codes ask for.
'INVALID_ENGINE' =>
@@ -6104,7 +6114,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';
}
}
@@ -6233,6 +6244,8 @@ class AppNotifier extends ChangeNotifier {
'PROMPT_TOO_LONG',
'INVALID_PROMPT',
'AGENT_UNSUPPORTED',
+ 'INVALID_AGENT',
+ 'INVALID_PERMISSION_MODE',
'TMUX_UNAVAILABLE',
'CODEX_CLI_TOO_OLD',
'TMUX_TOO_OLD_FOR_GRID',
@@ -6983,6 +6996,75 @@ class AppNotifier extends ChangeNotifier {
return true;
}
+ /// Clone (⌘⇧N): another agent of the same kind as [agentId], with a fresh
+ /// conversation — fork minus the context. Same machine (its own or a relayed
+ /// one: `agent_create` takes the same road either way), 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 — no session to bind, so a clone works while the source is busy
+ /// or has no session yet, where a fork would wait or refuse.
+ ///
+ /// A daemon from before the frame carried the launch choices reports them
+ /// null; the clone then opens the way New Harness would by default — auto
+ /// mode, no named agent — while folder, harness and profile still carry. So
+ /// does an agent Harness did not launch.
+ ///
+ /// Returns null once the agent exists, else the sentence to show. A terminal
+ /// pane clones to a terminal in the same folder, exactly what ⌘⇧T opens; the
+ /// daemon names those itself.
+ Future<String?> cloneAgent(
+ String machineId,
+ String agentId, {
+ String? swarmId,
+ }) {
+ final machine = machineStates[machineId];
+ if (machine == null) return Future.value('Machine not found');
+ if (machine.machine.isShared) {
+ return Future.value('Shared agents are view-only.');
+ }
+ final source = machine.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (source == null) {
+ return Future.value('The source agent 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 agent is not supported.',
+ );
+ }
+ final terminal = isTerminalEngine(engine);
+ final cwd = machine.projectOf(source)?.cwd;
+ if (cwd == null && !terminal) {
+ return Future.value(
+ '${source.displayName} has no project folder to clone into.',
+ );
+ }
+ return createAgent(
+ machineId,
+ engine: engine,
+ folder: cwd,
+ dsh: source.dsh,
+ codexHome: source.codexHome,
+ attempt: AgentCreationAttempt().._codexHomeTrusted = true,
+ agent: source.namedAgent,
+ permissionMode: source.permissionMode,
+ // Unrecorded is not "off": an older daemon's agent clones the way a new
+ // one would open. A terminal has no permissions to bypass (⌘⇧T's choice).
+ bypassPermission: source.bypassPermission ?? !terminal,
+ name: terminal ? null : cloneNameFor(source.displayName),
+ swarmId: swarmId ?? activeSwarmId,
+ // The current tab, said out loud: without a placement a harness clone
+ // would open a tab of its own (see `createAgent`), and the point of a
+ // clone is another tile beside the one it came from.
+ placement: HarnessPlacement.currentTab,
+ );
+ }
+
/// A fork keeps the originating tab and creation receipt while its prompt is
/// closed. Reopening joins the request; checking an uncertain result never
/// sends a second agent_fork. Old daemons can still return their legacy reply.
diff --git a/desktop/lib/widgets/fork_agent_dialog.dart b/desktop/lib/widgets/fork_agent_dialog.dart
index 3e101ee5f..63e157226 100644
--- a/desktop/lib/widgets/fork_agent_dialog.dart
+++ b/desktop/lib/widgets/fork_agent_dialog.dart
@@ -3,14 +3,14 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../core/agent_names.dart';
import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
import '../terminal/terminal_font_store.dart';
import 'box_chrome.dart';
import 'terminal_prompt.dart';
-String forkNameFor(String name) =>
- '${name.trim().isEmpty ? 'Agent' : name.trim()} - fork';
+export '../core/agent_names.dart' show forkNameFor;
/// The model retains the draft, receipt and destination across dismissal.
Future<void> forkHarness(
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index b96629b50..8ed029ff8 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -100,7 +100,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["select", "close", "new", "rename", "commands", "notifications", "store", "addAgent", "newAgent", "newTerminal", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["select", "close", "new", "rename", "commands", "notifications", "store", "addAgent", "newAgent", "newTerminal", "cloneAgent", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -237,6 +237,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)
let symbols = [
"new": "plus.square", "newAgent": "plus", "addAgent": "plus", "newTerminal": "terminal",
+ "cloneAgent": "plus.square.on.square",
"renameActive": "pencil", "closeActive": "xmark",
"splitRight": "rectangle.split.2x1", "splitDown": "rectangle.split.1x2",
"zoomPane": "viewfinder", "closePane": "xmark",
@@ -260,6 +261,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// row and loses its default chord — the Dart keymap (`swarm.reopen`) is where both are decided,
// and applyMenuKeys rewrites every equivalent here from it.
add(file, "New Terminal", "t", "newTerminal", [.command, .shift])
+ // ⌘⇧N: another agent like the focused pane's, fresh conversation (Dart: `agent.clone`).
+ add(file, "Clone Agent", "n", "cloneAgent", [.command, .shift])
add(file, "Rename Tab…", "r", "renameActive", [.command, .shift])
add(file, "Close Tab", "w", "closeActive")
file.addItem(.separator())
diff --git a/desktop/test/agent_model_test.dart b/desktop/test/agent_model_test.dart
index 421c87c98..e76cd2043 100644
--- a/desktop/test/agent_model_test.dart
+++ b/desktop/test/agent_model_test.dart
@@ -3,6 +3,7 @@ import 'package:harness/core/models.dart';
void main() {
_dshTests();
+ _cloneTests();
test('uses explicit terminal availability from a new CLI', () {
final dormantPane = Agent.fromJson({
'id': 'agent-1',
@@ -70,7 +71,10 @@ void main() {
});
test('reads the status off the grid block', () {
- expect(onGrid({'model': 'qwen', 'webSearch': 'on'}).gridWebSearch, GridWebSearch.on);
+ expect(
+ onGrid({'model': 'qwen', 'webSearch': 'on'}).gridWebSearch,
+ GridWebSearch.on,
+ );
expect(
onGrid({'model': 'qwen', 'webSearch': 'unavailable'}).gridWebSearch,
GridWebSearch.unavailable,
@@ -85,12 +89,19 @@ void main() {
// An older daemon, or a grid agent the daemon merely discovered: no field at all.
expect(onGrid({'model': 'qwen'}).gridWebSearch, isNull);
// A newer daemon with a fourth word: not printed verbatim, not guessed at.
- expect(onGrid({'model': 'qwen', 'webSearch': 'throttled'}).gridWebSearch, isNull);
+ expect(
+ onGrid({'model': 'qwen', 'webSearch': 'throttled'}).gridWebSearch,
+ isNull,
+ );
expect(onGrid({'model': 'qwen', 'webSearch': 7}).gridWebSearch, isNull);
});
test('has nothing to say off a grid', () {
- final own = Agent.fromJson({'id': 'agent-2', 'name': 'Own', 'grid': null});
+ final own = Agent.fromJson({
+ 'id': 'agent-2',
+ 'name': 'Own',
+ 'grid': null,
+ });
expect(own.gridModel, isNull);
expect(own.gridWebSearch, isNull);
});
@@ -140,7 +151,10 @@ void _dshTests() {
expect(verdict.artifact, 'boards/main.board.json');
expect(verdict.updatedAt, DateTime.utc(2026, 9, 14, 20));
expect(agent.copyWith(name: 'Renamed').verdict, verdict);
- expect(agent.copyWith(name: 'Renamed').dsh, 'autonomous/autonomous-circuit');
+ expect(
+ agent.copyWith(name: 'Renamed').dsh,
+ 'autonomous/autonomous-circuit',
+ );
});
test('a plain engine agent has none of them and draws as its engine', () {
@@ -200,3 +214,60 @@ void _dshTests() {
},
);
}
+
+/// What Clone (⌘⇧N) reads off the frame to open another of the same agent.
+void _cloneTests() {
+ test('parses the launch choices off an agent frame', () {
+ final agent = Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'a',
+ 'engine': 'claude',
+ 'permissionMode': 'readOnly',
+ 'bypassPermission': false,
+ 'namedAgent': 'reviewer',
+ });
+ expect(agent.permissionMode, 'readOnly');
+ expect(agent.bypassPermission, isFalse);
+ expect(agent.namedAgent, 'reviewer');
+ expect(agent.canClone, isTrue);
+ });
+
+ test('an older daemon leaves them null, which is not the same as false', () {
+ final agent = Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'a',
+ 'engine': 'claude',
+ });
+ expect(agent.permissionMode, isNull);
+ expect(agent.bypassPermission, isNull);
+ expect(agent.namedAgent, isNull);
+ expect(agent.canClone, isTrue);
+ });
+
+ test('refuses a mode or named agent outside the flag-value shape', () {
+ Agent parse(Map<String, dynamic> extra) => Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'a',
+ 'engine': 'claude',
+ ...extra,
+ });
+ expect(parse({'permissionMode': 'read only'}).permissionMode, isNull);
+ expect(parse({'permissionMode': '--dangerous'}).permissionMode, isNull);
+ expect(parse({'namedAgent': '../etc/passwd'}).namedAgent, isNull);
+ expect(parse({'namedAgent': 'a b'}).namedAgent, isNull);
+ expect(parse({'bypassPermission': 'true'}).bypassPermission, isNull);
+ });
+
+ test('a grid agent, or one with no engine, cannot be cloned', () {
+ expect(
+ Agent.fromJson({
+ 'id': 'agent-1',
+ 'name': 'a',
+ 'engine': 'claude',
+ 'grid': {'model': 'DeepSeek-V4'},
+ }).canClone,
+ isFalse,
+ );
+ expect(Agent.fromJson({'id': 'agent-1', 'name': 'a'}).canClone, isFalse);
+ });
+}
diff --git a/desktop/test/clone_agent_test.dart b/desktop/test/clone_agent_test.dart
new file mode 100644
index 000000000..7b12058d9
--- /dev/null
+++ b/desktop/test/clone_agent_test.dart
@@ -0,0 +1,292 @@
+// Clone Agent (⌘⇧N): another agent of the focused pane's kind with a fresh
+// conversation — fork minus the context. Everything a dialog would ask is read
+// off the source agent's frame, so the chord goes straight to `agent_create`
+// on the source's machine; a relayed machine takes the same road as this one.
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/agent_names.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/app_shortcuts.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final creates = <Map<String, dynamic>>[];
+ final replies = <Completer<Map<String, dynamic>>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'agent_create') return Future.value({});
+ creates.add(payload);
+ final reply = Completer<Map<String, dynamic>>();
+ replies.add(reply);
+ return reply.future;
+ }
+
+ void created(Map<String, dynamic> agent) {
+ replies.last.complete({
+ 'creationId': creates.last['creationId'],
+ 'state': 'created',
+ 'agent': agent,
+ });
+ }
+}
+
+void main() {
+ late _Connection connection;
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late SwarmProjectStore projects;
+ setUp(() {
+ connection = _Connection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.nodeOnline = true;
+ map = MemoryKeymap();
+ projects = SwarmProjectStore();
+ });
+ tearDown(() {
+ app.dispose();
+ map.dispose();
+ projects.dispose();
+ });
+
+ /// The source: what a daemon that knows the launch choices reports.
+ Agent source(Map<String, dynamic> extra) => Agent.fromJson({
+ 'id': 'a0',
+ 'name': 'Reviewer',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ 'project': {'name': 'work', 'cwd': '/work'},
+ ...extra,
+ });
+
+ Future<void> mount(WidgetTester tester, Agent agent) async {
+ app.stateOf('m')!.agents = [agent];
+ app.adoptSessionForTest(terminal('a0', []));
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ projectStore: projects,
+ nativeTabs: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> clone(WidgetTester tester) async {
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true, shift: true);
+ await tester.pump();
+ }
+
+ Map<String, dynamic> withoutId(Map<String, dynamic> payload) =>
+ {...payload}..remove('creationId');
+
+ test('⌘⇧N is Clone Agent in the live table and reaches the native menu', () {
+ final shiftN = kSwarmShortcuts.where(
+ (s) =>
+ s.activator.trigger == LogicalKeyboardKey.keyN &&
+ s.activator.meta &&
+ s.activator.shift,
+ );
+ expect(shiftN.single.action, ShortcutAction.cloneAgent);
+ expect(harnessCommandById['agent.clone']!.keys, ['cmd+shift+n']);
+ expect(harnessCommandById['agent.clone']!.nativeAction, 'cloneAgent');
+ // Fork keeps no default chord; the two are siblings, not a pair.
+ expect(harnessCommandById['agent.fork']!.keys, isEmpty);
+ });
+
+ test('a clone is named after its source the way a fork is', () {
+ expect(cloneNameFor('Reviewer'), 'Reviewer - clone');
+ expect(cloneNameFor(' '), 'Agent - clone');
+ expect(forkNameFor('Reviewer'), 'Reviewer - fork');
+ });
+
+ testWidgets('sends every launch choice off the frame, and never a prompt', (
+ tester,
+ ) async {
+ await mount(
+ tester,
+ source({
+ 'codexHome': '/Users/x/.codex-work',
+ 'namedAgent': 'reviewer',
+ 'permissionMode': 'readOnly',
+ 'bypassPermission': false,
+ }),
+ );
+ // No `engines_probe` ever ran: the profile came off this machine's own
+ // frame, which is proof enough that its daemon takes one.
+ expect(app.stateOf('m')!.engines['codex'], isNull);
+ final tabs = app.swarms.length;
+ await clone(tester);
+ expect(withoutId(connection.creates.single), {
+ 'engine': 'codex',
+ 'cwd': '/work',
+ 'bypassPermission': false,
+ 'permissionMode': 'readOnly',
+ 'codexHome': '/Users/x/.codex-work',
+ 'name': 'Reviewer - clone',
+ 'agent': 'reviewer',
+ });
+ connection.created({
+ 'id': 'made',
+ 'name': 'Reviewer - clone',
+ 'engine': 'codex',
+ });
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'made']);
+ expect(app.focusedPane!.agentId, 'made');
+ expect(app.swarms.length, tabs);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a harness clone stays in the current tab', (tester) async {
+ await mount(
+ tester,
+ source({'engine': 'claude', 'dsh': 'autonomous/blender'}),
+ );
+ final tabs = app.swarms.length;
+ final tab = app.activeSwarmId;
+ await clone(tester);
+ expect(connection.creates.single['dsh'], 'autonomous/blender');
+ expect(connection.creates.single['engine'], 'claude');
+ connection.created({
+ 'id': 'made',
+ 'name': 'Reviewer - clone',
+ 'engine': 'claude',
+ 'dsh': 'autonomous/blender',
+ });
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(app.swarms.length, tabs);
+ expect(app.activeSwarmId, tab);
+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'made']);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'an older daemon reports no choices, and the clone opens by default',
+ (tester) async {
+ await mount(tester, source({}));
+ await clone(tester);
+ expect(withoutId(connection.creates.single), {
+ 'engine': 'codex',
+ 'cwd': '/work',
+ 'bypassPermission': true,
+ 'name': 'Reviewer - clone',
+ });
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('a terminal clones to a terminal in the same folder', (
+ tester,
+ ) async {
+ await mount(tester, source({'engine': 'terminal'}));
+ await clone(tester);
+ expect(withoutId(connection.creates.single), {
+ 'engine': 'terminal',
+ 'cwd': '/work',
+ 'bypassPermission': false,
+ });
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('refuses a grid agent, and one with no folder, before asking', (
+ tester,
+ ) async {
+ await mount(
+ tester,
+ source({
+ 'grid': {'model': 'DeepSeek-V4'},
+ }),
+ );
+ expect(find.byKey(const ValueKey('command:agent.clone')), findsNothing);
+ await clone(tester);
+ expect(connection.creates, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('with no project folder the chord says so', (tester) async {
+ await mount(
+ tester,
+ Agent.fromJson({
+ 'id': 'a0',
+ 'name': 'Reviewer',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ }),
+ );
+ await clone(tester);
+ expect(connection.creates, isEmpty);
+ expect(
+ find.text('Reviewer has no project folder to clone into.'),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a machine that cannot launch keeps the chord a no-op', (
+ tester,
+ ) async {
+ app.stateOf('m')!.nodeOnline = false;
+ await mount(tester, source({}));
+ await clone(tester);
+ expect(connection.creates, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a daemon too old to create says to update', (tester) async {
+ await mount(tester, source({}));
+ await clone(tester);
+ connection.replies.single.completeError(
+ const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'UNSUPPORTED',
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(
+ find.text('Update the harness CLI on this machine to start a harness'),
+ findsOneWidget,
+ );
+ expect(app.panes.map((pane) => pane.agentId), ['a0']);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index a187da724..01c266971 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -62,6 +62,7 @@ void main() {
('cmd+p', 'agent.add'),
('cmd+r', 'pane.split_right'),
('cmd+d', 'pane.split_down'),
+ ('cmd+shift+n', 'agent.clone'),
('cmd+h', 'pane.focus_left'),
('cmd+j', 'pane.focus_below'),
('cmd+k', 'pane.focus_above'),
@@ -95,7 +96,7 @@ void main() {
final id = command(stroke.toString());
expect(harnessCommandById[id]?.action, shortcut.action);
}
- for (final retired in ['cmd+shift+n', 'cmd+shift+h', 'cmd+shift+k']) {
+ for (final retired in ['cmd+shift+h', 'cmd+shift+k']) {
expect(command(retired), isNull, reason: retired);
}
expect(command('cmd+alt+left'), isNull);
diff --git a/docs/keyboard.md b/docs/keyboard.md
index 5df7e0d7b..b7669b1ad 100644
--- a/docs/keyboard.md
+++ b/docs/keyboard.md
@@ -14,6 +14,7 @@ The defaults, in the workspace:
| ⌘B | Boss mode: describe a task, it picks the agent |
| ⌘W · ⇧⌘R | Close tab · rename tab |
| ⇧⌘T | New terminal in the current project |
+| ⇧⌘N | Clone Agent — another agent like the focused pane's (same machine, project, harness, Codex profile, permission mode, named agent) with a fresh conversation. No dialog; fork minus the context |
| ⌘1 … ⌘9 | Select tab by position |
| ⇧⌘] · ⇧⌘[ · ⌃Tab · ⌃⇧Tab | Next · previous tab |
| ⌘] · ⌘[ · ⌘Y | Forward · back through visited agents · full history |