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.

Desktop: + New agent opens Cmd-N with Lead or Member (#4196) (#3463)

0xken154191333eb0c7
diff --git a/backend/src/superTabs/agentNew.test.ts b/backend/src/superTabs/agentNew.test.ts
index b56c26e30..2a7ac1d15 100644
--- a/backend/src/superTabs/agentNew.test.ts
+++ b/backend/src/superTabs/agentNew.test.ts
@@ -168,3 +168,57 @@ describe('a Regular agent\'s start on its computer', () => {
expect(f.state.starts ?? []).toEqual([])
})
})
+
+// Task #4196 (anh Dee 11-07): + New agent opens Cmd-N, which starts the agent on the person's own computer at once. A Member's
+// chat is opened first with no start, and the running session then joins it: a server start waited on its host (p50 18 s).
+describe('+ New agent, Member started on its own computer', () => {
+ const configuration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ const join = (chat: string, extra: Record<string, unknown> = {}) =>
+ ({ type: 'agent.add', conversationId: chat, machineId: 'mate-laptop', harnessId: 'h-ada', name: 'Ada', lead: false, configuration, ...extra }) as Command
+
+ it('opens its chat with no start, even on a computer the Swarm does not list', () => {
+ const f = swarm()
+ const made = f.add({ kind: 'regular', name: 'Ada', machineId: 'mate-laptop', local: true })
+ expect(f.state.conversations.find(c => c.id === made.result.conversationId))
+ .toMatchObject({ kind: 'agent-chat', title: 'Ada', agentIds: [], audience: { people: [{ id: 'mate' }] } })
+ expect(made.result.startId).toBeUndefined()
+ expect(f.state.starts ?? []).toEqual([])
+ })
+
+ it('takes the running session as a Regular agent in that chat, once', () => {
+ const f = swarm()
+ const chat = f.add({ kind: 'regular', name: 'Ada', machineId: 'mate-laptop', local: true }).result.conversationId as string
+ const added = f.run(join(chat, { initialMessage: 'Fix the docs' }), mate, own('mate'))
+ const agent = f.state.agents.find(a => a.id === added.result.agentId)!
+ expect(agent).toMatchObject({ machineId: 'mate-laptop', harnessId: 'h-ada', regular: true, contributorId: 'mate', machineOwnerId: 'mate' })
+ expect(agent.projectId).toBeUndefined()
+ expect(agentKind(f.state, agent)).toBe('regular')
+ expect(f.state.conversations.find(c => c.id === chat)!.agentIds).toEqual([agent.id])
+ expect(added.messages.map(m => m.text)).toContain('Fix the docs')
+ expect(code(() => f.run(join(chat, { harnessId: 'h-other' }), mate, own('mate')))).toBe('AGENT_CHAT_TAKEN')
+ })
+
+ it('leaves an unused chat for its person to archive, as Desktop\'s Discard does', () => {
+ const f = swarm()
+ const chat = f.add({ kind: 'regular', name: 'Ada', machineId: 'mate-laptop', local: true }).result.conversationId as string
+ expect(code(() => f.run({ type: 'conversation.archive', conversationId: chat, archived: true }, owner))).not.toBeNull()
+ f.run({ type: 'conversation.archive', conversationId: chat, archived: true }, mate)
+ expect(f.state.conversations.find(c => c.id === chat)!.archived).toBe(true)
+ })
+
+ it('is refused for a PM, another person\'s computer, another person\'s chat and a viewer', () => {
+ const f = swarm()
+ expect(code(() => f.add({ kind: 'pm', projectName: 'P', machineId: 'mate-laptop', local: true }))).not.toBeNull()
+ expect(code(() => f.add({ kind: 'regular', name: 'A', machineId: 'owner-mac', local: true }, mate,
+ { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }))).toBe('AGENT_OWN_MACHINE')
+ const chat = f.add({ kind: 'regular', name: 'Ada', machineId: 'mate-laptop', local: true }).result.conversationId as string
+ expect(code(() => f.run(join(chat, { machineId: 'owner-mac' }), mate, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })))
+ .toBe('AGENT_OWN_MACHINE')
+ expect(code(() => f.run(join(chat, { machineId: 'owner-laptop' }), owner, own('owner')))).toBe('NOT_FOUND')
+ expect(f.state.conversations.find(c => c.id === chat)!.agentIds).toEqual([])
+ const viewer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'viewer', email: '[email protected]' }
+ const invited = f.run({ type: 'invite.create', email: viewer.email, role: 'viewer', conversationId: 'lead' }, owner)
+ f.run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, viewer)
+ expect(code(() => f.add({ kind: 'regular', name: 'A', machineId: 'viewer-mac', local: true }, viewer))).toBe('READ_ONLY')
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 97361ffa0..caff8e65b 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -406,7 +406,9 @@ export const commandSchema = z.discriminatedUnion('type', [
// person's own listed computer and account.
z.object({ type: z.literal('agent.new'), kind: z.enum(['regular', 'pm']), machineId: id, engine: swarmEngine,
model: z.string().trim().min(1).max(200).optional(), name: z.string().trim().min(1).max(80).optional(), projectName: title.optional(),
- repositoryUrl: repositoryUrl.optional() }).strict(),
+ repositoryUrl: repositoryUrl.optional(),
+ // A Member its person's Desktop starts itself through Cmd-N (task #4196): only its chat opens here; agent.add brings in the session.
+ local: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration,
startedSession: z.object({ sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
@@ -1787,6 +1789,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
return project
}
+ /** A Regular agent's chat with its person, which nobody else reads (projects.ts readsAgentChat), for this command's agent. */
+ const openAgentChat = (me: { id: string; generation: string }, title: string): string => {
+ const chatId = stableId('agent-chat', me.id, me.generation, operationId)
+ state.conversations.push({ id: chatId, kind: 'agent-chat', title, leadId: null, agentIds: [], archived: false, brief: '', checks: [],
+ assignment: null, lastMessageSequence: 0, audience: { people: [{ id: me.id, generation: me.generation }] } })
+ return chatId
+ }
const addBuddyMachine = (machineId: string, setup: NonNullable<Extract<Command, { type: 'buddy.create' }>['setup']>, me: { id: string; generation: string }) => {
// Its last Buddy's folders are still being deleted there: a new one would lose its own (machine.contribute does the same).
if (state.machineCleanups?.some(c => c.machineId === machineId)) {
@@ -3230,6 +3239,29 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person adds a session already running. Start a new agent instead.', 403)
const addedName = addedAgentName(state, actor, command.name)
const group = open(state, command.conversationId)
+ // A Member's own chat (local agent.new, task #4196) takes the one session its person started for it on their own computer,
+ // in their own account, as a Regular agent in no project: as agent.started records a server-started one.
+ if (isAgentChat(group)) {
+ readConversation(state, actor, group.id)
+ const me = person(state, actor.userId)
+ if (me.role === 'viewer') fail('READ_ONLY', 'A viewer cannot contribute agents.', 403)
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'Choose your own computer.', 403)
+ if (grant.machineOwnerId !== me.id || grant.contributorId !== me.id || grant.hostGrant || grant.hostMachineId || grant.teamSession) {
+ fail('AGENT_OWN_MACHINE', 'A new agent runs only on your own computer, in your own account.', 403)
+ }
+ if (command.lead) fail('AGENT_CHAT_LEAD', 'An agent\'s own chat has no lead.', 400)
+ if (group.agentIds.length) fail('AGENT_CHAT_TAKEN', 'This chat already has its agent.', 409)
+ const agentId = stableId(command.machineId, command.harnessId)
+ if (state.agents.some(a => a.id === agentId)) fail('ALREADY_SHARED', 'This native harness is already in the tab.')
+ reserveHarnessSlot(state, command.machineId, command.harnessId, operationId)
+ state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId, regular: true,
+ machineOwnerId: me.id, contributorId: me.id, membershipGeneration: me.generation, hostGrant: null, name: addedName,
+ configuration: command.configuration, configurationVersion: operationId })
+ group.agentIds.push(agentId)
+ result.agentId = agentId
+ if (command.initialMessage) message(group.id, command.initialMessage)
+ break
+ }
const project = groupProject(state, group)
if (state.projects && group.id === project.leadConversationId && command.lead && command.project) {
project.repository ??= { machineId: command.machineId, ...command.project }
@@ -3692,6 +3724,15 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (grant.machineOwnerId !== me.id || grant.contributorId !== me.id || grant.hostGrant || grant.hostMachineId || grant.teamSession) {
fail('AGENT_OWN_MACHINE', 'A new agent runs only on your own computer, in your own account.', 403)
}
+ // A Member started through Cmd-N (task #4196, anh Dee 11-07): a server start waited on its host (p50 18 s, p95 4 min), so
+ // its person's Desktop starts it on their own computer at once. Only its chat opens here, with no start, so neither a listed
+ // computer nor a host that runs Regular starts is needed; agent.add then brings the running session into the chat.
+ if (command.local) {
+ if (command.kind !== 'regular') fail('LOCAL_MEMBER_ONLY', 'A Lead started on your computer starts its project with project.create.', 400)
+ const name = command.name ?? fail('AGENT_NAME_REQUIRED', 'Name your agent.', 400)
+ result.conversationId = openAgentChat(me, name)
+ break
+ }
// A Buddy-only record is not the computer in the Swarm: its person adds it first (Desktop does, with no screen).
const pool = state.machines?.find(m => m.machineId === command.machineId && m.contributorId === me.id && !m.buddyOnly && !m.removal)
?? fail('MACHINE_NOT_LISTED', 'Add this computer to the Swarm first.', 403)
@@ -3708,9 +3749,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const name = command.name ?? fail('AGENT_NAME_REQUIRED', 'Name your agent.', 400)
// Only a host that says it runs one gets its start (read/hostRows.ts regularStarts): an older one would leave it waiting.
if (!pool.observation?.capabilities?.includes(REGULAR_AGENT_CAPABILITY)) fail('HOST_OUTDATED', `Update Harness on ${pool.name ?? 'your computer'} to start this agent there.`, 409)
- const chatId = stableId('agent-chat', me.id, me.generation, operationId)
- state.conversations.push({ id: chatId, kind: 'agent-chat', title: name, leadId: null, agentIds: [], archived: false, brief: '', checks: [],
- assignment: null, lastMessageSequence: 0, audience: { people: [{ id: me.id, generation: me.generation }] } })
+ const chatId = openAgentChat(me, name)
const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,
...(command.model ? { model: command.model } : {}), name, cwd: buddyHomeFolder(pool, me), worktree: false, requirements: BUDDY_REQUIREMENTS, regular: true }
const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 4c454724c..c9fd449c2 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -3847,11 +3847,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? task,
String? superTabConversationId,
bool newSwarmProject = false,
+ bool newSwarmAgent = false,
HarnessPlacement? placement,
_NewHarnessSource source = _NewHarnessSource.workspace,
bool Function()? stillCurrent,
}) async {
if (!newSwarmProject &&
+ !newSwarmAgent &&
_newHarnessEmbedded &&
_newHarness != null &&
source == _NewHarnessSource.workspace &&
@@ -3962,8 +3964,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
integration = await SuperTabLaunch.open(
app,
superTab,
- newSwarmProject ? 'new-project' : conversation,
+ newSwarmProject
+ ? 'new-project'
+ : newSwarmAgent
+ ? 'new-agent'
+ : conversation,
newProject: newSwarmProject,
+ newAgent: newSwarmAgent,
);
} catch (failure) {
_showPaneActionHint(failure.toString());
@@ -8427,6 +8434,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
onNewProject: () => unawaited(
_newAgent(newSwarmProject: true),
),
+ // + New agent (task #4196): Cmd-N,
+ // with Member or Lead.
+ onNewAgent: () => unawaited(
+ _newAgent(newSwarmAgent: true),
+ ),
onNewSwarm: () =>
_newTab(superTab: true),
onAddAgent: (group) => unawaited(
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index 557b33bd5..e7233666f 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -44,6 +44,9 @@ class HarnessLaunchIntegration {
this.checkRepositoryOwner,
this.createRepository,
this.checkRepositoryAgain,
+ this.agentKind,
+ this.ownMachinesOnly = false,
+ this.startBuddy,
});
final String creationId, actionLabel;
String? swarmRole;
@@ -65,6 +68,22 @@ class HarnessLaunchIntegration {
String? projectVisibility;
bool projectVisibilityLocked;
+ /// + New agent in a Swarm (task #4196): whether it starts as a `lead`, which
+ /// names and starts a project, or a `member`. Null shows no such choice.
+ String? agentKind;
+
+ /// Set once the choice's first request is sent: it cannot change after.
+ bool agentKindLocked = false;
+
+ /// Only the person's own computers, never a shared, guest or Team one: an
+ /// agent they start runs in their own account.
+ final bool ownMachinesOnly;
+
+ /// Join's Buddy (task #4196): the Swarm starts it on [machineId] with
+ /// [engine], as before; the form only chooses them. Set, the form shows no
+ /// project and takes no first message.
+ final Future<void> Function(String machineId, String engine)? startBuddy;
+
/// A new project in a Swarm: the Swarm's machines its Product Manager may
/// start on, best first. The form then shows only the task, repo and
/// visibility, with the machine on a "Product Manager:" line. Null keeps
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 5ff425582..2b552feb4 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -1482,7 +1482,10 @@ class NewHarnessController extends ChangeNotifier {
_settingsModes.any((mode) => mode.id == _permissionFor(_settingsEngine))
? _permissionFor(_settingsEngine)
: kDefaultPermissionMode;
- bool get takesTask => isCloud || takesFirstTask(_base);
+ bool get takesTask => !bringsBuddy && (isCloud || takesFirstTask(_base));
+
+ /// Join's Buddy, which the Swarm starts (task #4196).
+ bool get bringsBuddy => integration?.startBuddy != null;
bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
List<PermissionMode> get _modes =>
_noAgentSetup || isCloud || leadThroughSwarm
@@ -1936,7 +1939,8 @@ class NewHarnessController extends ChangeNotifier {
/// A missing or ambiguous saved value stays visible until the person
/// replaces it. These checks never select a different launch target.
({NewHarnessField field, String message})? get requiredChoice {
- if (checking) return null;
+ // A Buddy needs only its agent and computer (task #4196).
+ if (checking || bringsBuddy) return null;
if (needsProject) {
return (field: NewHarnessField.projectMenu, message: 'Choose a project.');
}
@@ -2351,6 +2355,16 @@ class NewHarnessController extends ChangeNotifier {
/// lost has still to be checked on.
bool get locked => busy || checking || linkingProfile;
+ /// + New agent's Member or Lead (task #4196), or null outside one.
+ String? get agentKind => integration?.agentKind;
+
+ void setAgentKind(String kind) {
+ final destination = integration;
+ if (destination == null || locked || destination.agentKindLocked) return;
+ destination.agentKind = kind;
+ notifyListeners();
+ }
+
/// Lists always choose. The launch menu and optional task prompt start.
bool get returnCreates =>
checking ||
@@ -3682,7 +3696,10 @@ class NewHarnessController extends ChangeNotifier {
(m) => !m.isLocalMachine && !_machineUsable(m),
),
])
- if (!machine.machine.isShared)
+ if (!machine.machine.isShared &&
+ (integration?.ownMachinesOnly != true ||
+ !machine.belongsToOtherAccount &&
+ !machine.machine.isTeamAccount))
NewHarnessOption(
id: machine.machine.machineId,
title: machine.machine.displayName,
@@ -4592,6 +4609,7 @@ class NewHarnessController extends ChangeNotifier {
return _fail(failure.toString());
}
}
+ if (bringsBuddy) return _startBuddy();
if (!checking && usesProfile && _profile != null) {
if (loadingProfiles) {
return _fail(
@@ -4955,6 +4973,26 @@ class NewHarnessController extends ChangeNotifier {
/// services/cloud.ts), which starts it at its maker; no folder, no install.
/// New Project's Product Manager the Swarm starts
/// ([HarnessLaunchIntegration.startInSwarm]) on [leadSwarmMachine].
+ /// Join's Buddy (task #4196): the Swarm starts it on the chosen computer,
+ /// as before this form; the form chose only its engine and computer.
+ Future<NewHarnessOutcome> _startBuddy() async {
+ busy = true;
+ error = null;
+ status = 'Starting your Buddy on $machineLabel…';
+ notifyListeners();
+ try {
+ await integration!.startBuddy!(_machineId, _base);
+ } catch (failure) {
+ return _fail(failure.toString());
+ }
+ integration?.completed = true;
+ if (_disposed) return NewHarnessOutcome.created;
+ busy = false;
+ status = null;
+ notifyListeners();
+ return NewHarnessOutcome.created;
+ }
+
Future<NewHarnessOutcome> _startInSwarm() async {
final start = integration?.startInSwarm;
if (start == null) {
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 168de81b1..7e1402f6c 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -3501,7 +3501,7 @@ class SuperTabController extends ChangeNotifier {
/// PM (Ken, 10-29), so no private chat but a Buddy chat is listed or opened,
/// the reader's old Chat with PM that an older server still sends included.
bool hiddenByBuddies(SuperTabConversation group) =>
- group.audience != null && !group.isBuddyChat;
+ group.audience != null && !group.isBuddyChat && !group.isAgentChat;
/// Where opening conversation [id] lands: itself, unless the app hides it.
String landsOn(String id) => _shownFor(id);
diff --git a/desktop/lib/super_tabs/join/agent_dialog.dart b/desktop/lib/super_tabs/join/agent_dialog.dart
deleted file mode 100644
index 75e7f6624..000000000
--- a/desktop/lib/super_tabs/join/agent_dialog.dart
+++ /dev/null
@@ -1,214 +0,0 @@
-import 'package:flutter/material.dart';
-
-import '../../shared/widgets/app_select_field.dart';
-import '../../widgets/desktop_chrome.dart';
-import '../../widgets/desktop_prompt_surface.dart';
-import '../controller.dart' show superTabOperationId;
-import 'agent_launcher.dart';
-
-/// Starts only through the authenticated owner's daemon adapter. The dialog
-/// never reads CLI settings, credentials or another machine's login.
-typedef SwarmAgentCreate = Future<Map<String, dynamic>> Function(
- String engine,
- String kind,
- String? projectName,
- String operationId,
-);
-
-class SwarmAgentDialog extends StatefulWidget {
- const SwarmAgentDialog({
- super.key,
- required this.engines,
- required this.create,
- required this.isCurrent,
- this.bringing = false,
- });
- final List<String> engines;
- final SwarmAgentCreate create;
- final bool Function() isCurrent;
- final bool bringing;
-
- @override
- State<SwarmAgentDialog> createState() => _SwarmAgentDialogState();
-}
-
-class _SwarmAgentDialogState extends State<SwarmAgentDialog> {
- final _project = TextEditingController();
- final _operation = superTabOperationId();
- late String? _engine = widget.engines.firstOrNull;
- String _kind = 'regular';
- bool _busy = false, _submitted = false, _invalid = false;
- String? _error;
- String get _selectedKind => widget.bringing ? 'buddy' : _kind;
-
- Future<void> _submit() async {
- if (_busy || _invalid || _engine == null) return;
- if (!widget.isCurrent()) {
- setState(() {
- _invalid = true;
- _error = 'Your account changed. Close this dialog and try again.';
- });
- return;
- }
- setState(() {
- _busy = true;
- _submitted = true;
- _error = null;
- });
- try {
- final result = await widget
- .create(
- _engine!,
- _selectedKind,
- _selectedKind == 'pm' ? _project.text.trim() : null,
- _operation,
- )
- .timeout(const Duration(seconds: 80));
- if (!mounted) return;
- if (!widget.isCurrent()) {
- setState(() {
- _invalid = true;
- _error = 'Your account changed. Close this dialog and try again.';
- });
- return;
- }
- if (result['agentId'] is! String && result['startId'] is! String) {
- throw const FormatException('Agent start not acknowledged');
- }
- Navigator.pop(context, result);
- } catch (failure) {
- if (mounted) {
- setState(
- () => _error = failure is SwarmAgentLaunchFailure ? failure.message : 'Could not start your agent. Check this computer’s connection and try again.',
- );
- }
- } finally {
- if (mounted) setState(() => _busy = false);
- }
- }
-
- @override
- void dispose() {
- _project.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final enabled =
- !_busy &&
- !_invalid &&
- _engine != null &&
- (_selectedKind != 'pm' || _project.text.trim().isNotEmpty);
- return DesktopPromptSurface(
- body: DesktopPromptScrollBody(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- DesktopDialogHeader(
- title: widget.bringing ? 'Bring your agent' : 'New agent',
- padding: EdgeInsets.zero,
- onClose: () => Navigator.pop(context),
- ),
- const SizedBox(height: 16),
- Text(
- widget.bringing
- ? 'Choose the agent you use on this computer. It becomes your Buddy.'
- : 'Regular agents work across projects. A PM starts and leads a project.',
- style: DesktopChrome.text(),
- ),
- const SizedBox(height: 16),
- if (!widget.bringing) ...[
- SegmentedButton<String>(
- style: ButtonStyle(
- foregroundColor: WidgetStateProperty.resolveWith(
- (states) => states.contains(WidgetState.selected)
- ? DesktopChrome.onSelection
- : DesktopChrome.foreground,
- ),
- ),
- segments: const [
- ButtonSegment(value: 'regular', label: Text('Regular')),
- ButtonSegment(value: 'pm', label: Text('PM')),
- ],
- selected: {_kind},
- onSelectionChanged: _submitted
- ? null
- : (values) => setState(() => _kind = values.single),
- ),
- const SizedBox(height: 16),
- ],
- if (widget.engines.isEmpty)
- Text(
- 'Install Claude Code or Codex on this computer, then open this dialog again.',
- style: DesktopChrome.text(),
- )
- else
- AppSelectField<String>(
- key: const Key('swarm-agent-engine'),
- value: _engine!,
- semanticLabel: 'Engine',
- options: [
- for (final e in widget.engines)
- SelectOption(
- value: e,
- label: e == 'claude'
- ? 'Claude Code'
- : e == 'codex'
- ? 'Codex'
- : e,
- ),
- ],
- onChanged: (value) {
- if (!_submitted) setState(() => _engine = value);
- },
- ),
- if (_selectedKind == 'pm') ...[
- const SizedBox(height: 16),
- TextField(
- key: const Key('swarm-agent-project'),
- controller: _project,
- enabled: !_submitted,
- maxLength: 120,
- decoration: const InputDecoration(labelText: 'Project name'),
- onChanged: (_) => setState(() {}),
- onSubmitted: (_) {
- if (enabled) _submit();
- },
- ),
- ],
- const SizedBox(height: 8),
- Text(
- 'On this computer, with your own agent settings.',
- style: DesktopChrome.metadata(),
- ),
- if (_error != null) ...[
- const SizedBox(height: 12),
- Text(
- _error!,
- key: const Key('swarm-agent-error'),
- style: DesktopChrome.text(),
- ),
- ],
- ],
- ),
- ),
- actions: [
- FilledButton(
- key: const Key('swarm-agent-submit'),
- onPressed: enabled ? _submit : null,
- child: Text(
- _busy
- ? 'Starting…'
- : _error != null && !_invalid
- ? 'Retry'
- : widget.bringing
- ? 'Bring agent'
- : 'Create agent',
- ),
- ),
- ],
- );
- }
-}
diff --git a/desktop/lib/super_tabs/join/agent_launcher.dart b/desktop/lib/super_tabs/join/agent_launcher.dart
index aa731f307..bab3b9ee6 100644
--- a/desktop/lib/super_tabs/join/agent_launcher.dart
+++ b/desktop/lib/super_tabs/join/agent_launcher.dart
@@ -3,10 +3,14 @@
class SwarmAgentLaunchFailure implements Exception {
const SwarmAgentLaunchFailure(this.message);
final String message;
+
+ @override
+ String toString() => message;
}
-/// One dialog's start transaction. Preparation and machine admission are kept
-/// across retries; each server mutation has its own stable operation receipt.
+/// The Buddy a person brings as they join, on one of their own computers: the
+/// Swarm starts it there (buddy.create). Preparation is kept across retries,
+/// and the start keeps its operation receipt.
class SwarmAgentLauncher {
SwarmAgentLauncher({
required this.machineId,
@@ -15,7 +19,7 @@ class SwarmAgentLauncher {
required this.isCurrent,
required this.prepare,
required this.command,
- }) : _admitted = inSwarm;
+ }) : _listed = inSwarm;
final String machineId, machineName;
final bool Function() isCurrent;
@@ -25,31 +29,25 @@ class SwarmAgentLauncher {
String operationId,
)
command;
- bool _admitted;
+ final bool _listed;
Map<String, dynamic>? _prepared;
void _guard() {
if (!isCurrent()) {
throw const SwarmAgentLaunchFailure(
- 'Your account changed. Close this dialog and try again.',
+ 'Your account changed. Close this form and try again.',
);
}
}
- Future<Map<String, dynamic>> create(
- String engine,
- String kind,
- String? projectName,
- String operationId,
- ) async {
+ Future<Map<String, dynamic>> create(String engine, String operationId) async {
_guard();
- if (!const {'buddy', 'regular', 'pm'}.contains(kind) ||
- (kind == 'pm' && (projectName?.trim().isEmpty ?? true))) {
- throw const SwarmAgentLaunchFailure('Enter a project name for your PM.');
- }
- if (!_admitted) {
- _prepared ??= await prepare('$operationId-prepare')
- .timeout(const Duration(seconds: 25));
+ // A computer the Swarm does not list yet is recorded Buddy-only with its
+ // folder and engines (backend buddy.create setup).
+ if (!_listed) {
+ _prepared ??= await prepare(
+ '$operationId-prepare',
+ ).timeout(const Duration(seconds: 25));
_guard();
_prepared = {
..._prepared!,
@@ -58,35 +56,13 @@ class SwarmAgentLauncher {
if (engine == 'claude' || engine == 'codex') engine,
],
};
- if (kind != 'buddy') {
- await command({
- 'type': 'machine.contribute',
- 'machineId': machineId,
- 'name': machineName,
- 'cwd': _prepared!['cwd'],
- 'scope': 'swarm',
- 'engines': _prepared!['engines'],
- 'maxAgents': 16,
- 'agents': 'memory',
- // Listing this computer must never authorize a teammate to use
- // its person's login. Keep the existing owner-project restriction.
- 'teamAccountOnly': true,
- }, '$operationId-machine').timeout(const Duration(seconds: 25));
- _admitted = true;
- }
}
_guard();
final result = await command({
- 'type': kind == 'buddy' ? 'buddy.create' : 'agent.new',
+ 'type': 'buddy.create',
'machineId': machineId,
'engine': engine,
- if (kind == 'buddy' && !_admitted) 'setup': _prepared,
- if (kind != 'buddy') ...{
- 'kind': kind,
- if (kind == 'regular')
- 'name': engine == 'claude' ? 'Claude Code' : 'Codex',
- if (kind == 'pm') 'projectName': projectName!.trim(),
- },
+ if (!_listed) 'setup': _prepared,
}, '$operationId-start').timeout(const Duration(seconds: 25));
_guard();
return result;
diff --git a/desktop/lib/super_tabs/join/new_agent_dialog.dart b/desktop/lib/super_tabs/join/bring_agent.dart
similarity index 58%
rename from desktop/lib/super_tabs/join/new_agent_dialog.dart
rename to desktop/lib/super_tabs/join/bring_agent.dart
index aace083c1..3be0ea4c6 100644
--- a/desktop/lib/super_tabs/join/new_agent_dialog.dart
+++ b/desktop/lib/super_tabs/join/bring_agent.dart
@@ -2,20 +2,24 @@ import 'dart:convert';
import 'package:flutter/material.dart';
+import '../../logging/app_log.dart';
import '../../shared/widgets/app_dialog.dart';
import '../../state/app_state.dart';
-import '../../logging/app_log.dart';
+import '../../state/harness_launch_integration.dart';
+import '../../state/new_harness.dart';
+import '../../widgets/desktop_chrome.dart';
+import '../../widgets/new_harness_form.dart';
import '../controller.dart';
-import 'agent_dialog.dart';
import 'agent_launcher.dart';
-/// Shared entry for the left pane and the post-join Buddy prompt. The local
-/// transport's identity is used directly; a remote machine is never a fallback.
-Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
+/// Join's "bring your agent" (task #4196): the Cmd-N form, its agent and
+/// computer, for the person's Buddy, which the Swarm starts as before. The
+/// local transport's identity is used directly; a remote machine is never a
+/// fallback for this computer.
+Future<Map<String, dynamic>?> showBringAgentForm(
BuildContext context, {
required SuperTabController controller,
required AppNotifier app,
- bool bringing = false,
bool Function()? isCurrent,
}) async {
final accountId = app.currentUser?.id;
@@ -54,20 +58,11 @@ Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
);
return null;
}
- final machineId = here.machine.machineId;
- // Probe executables through the existing hidden native path; do not inspect
- // a sign-in or read settings here. Those belong to the owner's actual CLI.
- await app
- .probeEngines(machineId, force: true)
- .timeout(const Duration(seconds: 20), onTimeout: () {});
- if (!current()) return null;
- final engines = [
- for (final e in ['claude', 'codex'])
- if (here.engines[e]?.installed == true) e,
- ];
- final launcher = SwarmAgentLauncher(
+ // One start per computer chosen, each keeping its receipt across retries.
+ final launchers = <String, (SwarmAgentLauncher, String)>{};
+ SwarmAgentLauncher launcherFor(String machineId) => SwarmAgentLauncher(
machineId: machineId,
- machineName: here.machine.displayName,
+ machineName: app.stateOf(machineId)?.machine.displayName ?? machineId,
inSwarm:
controller.snapshot?.machines.any(
(m) => m['machineId'] == machineId && m['buddyOnly'] != true,
@@ -85,7 +80,7 @@ Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
.timeout(const Duration(seconds: 20));
if (prepared['state'] == 'preparing') {
throw const SwarmAgentLaunchFailure(
- 'Your agent’s folder is still being prepared. Retry to check it.',
+ 'Your agent’s folder is still being prepared. Try again to check it.',
);
}
if (prepared['state'] != 'ready' ||
@@ -96,7 +91,7 @@ Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
);
}
return {
- 'name': here.machine.displayName,
+ 'name': app.stateOf(machineId)?.machine.displayName ?? machineId,
'cwd': prepared['cwd'],
'engines': prepared['engines'],
};
@@ -118,24 +113,68 @@ Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
'UPDATE_REQUIRED',
}.contains(controller.operationErrorCode)) {
throw const SwarmAgentLaunchFailure(
- 'Update Harness to use this agent flow.',
+ 'Update Harness to bring your agent.',
);
}
throw const SwarmAgentLaunchFailure(
- 'The agent start is not confirmed. Retry to check it.',
+ 'Your agent’s start is not confirmed. Try again to check it.',
);
},
);
- if (!context.mounted || !current()) return null;
- final result = await showAppDialog<Map<String, dynamic>>(
- context: context,
- builder: (_) => SwarmAgentDialog(
- bringing: bringing,
- engines: engines,
- create: launcher.create,
- isCurrent: current,
- ),
+ Map<String, dynamic>? started;
+ String? startedOn;
+ final integration = HarnessLaunchIntegration(
+ creationId: superTabOperationId(),
+ actionLabel: 'Bring agent',
+ engines: const ['claude', 'codex'],
+ ownMachinesOnly: true,
+ prepare: (_, task, _) async => task,
+ complete: (_, _) async {},
+ beforeSubmit: (_, _) async {},
+ startBuddy: (machineId, engine) async {
+ final (launcher, operation) = launchers[machineId] ??= (
+ launcherFor(machineId),
+ superTabOperationId(),
+ );
+ final result = await launcher.create(engine, operation);
+ if (result['agentId'] is! String && result['startId'] is! String) {
+ throw const SwarmAgentLaunchFailure(
+ 'Your agent’s start is not confirmed. Try again to check it.',
+ );
+ }
+ started = result;
+ startedOn = machineId;
+ },
+ );
+ final box = NewHarnessController(
+ app,
+ machineId: here.machine.machineId,
+ integration: integration,
);
+ if (!context.mounted || !current()) {
+ box.dispose();
+ return null;
+ }
+ try {
+ // No transition: the form's controller is disposed as the route closes.
+ await showAppDialog<void>(
+ context: context,
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ builder: (dialog) => Padding(
+ padding: const EdgeInsets.all(DesktopChrome.panelPadding),
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onCreated: () => Navigator.pop(dialog),
+ onClose: () => Navigator.pop(dialog),
+ ),
+ ),
+ );
+ } finally {
+ box.dispose();
+ }
+ final result = started;
if (!current() || result == null) return null;
final conversation = result['conversationId'];
if (conversation is String) await controller.select(conversation);
@@ -144,7 +183,7 @@ Future<Map<String, dynamic>?> showSwarmNewAgentDialog(
// into a second start. Host liveness is still visible through existing UI.
try {
await app
- .wakeSuperTabHost(machineId)
+ .wakeSuperTabHost(startedOn!)
.timeout(const Duration(seconds: 10));
} catch (_) {
appLog.info(
diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dart
index 78a04ac9a..18915a9b5 100644
--- a/desktop/lib/super_tabs/join_dialog.dart
+++ b/desktop/lib/super_tabs/join_dialog.dart
@@ -8,7 +8,7 @@ import '../widgets/desktop_chrome.dart';
import '../widgets/desktop_prompt_surface.dart';
import 'controller.dart';
import 'join_link.dart';
-import 'join/new_agent_dialog.dart';
+import 'join/bring_agent.dart';
import 'join_machine.dart' show swarmNewMemberRole;
/// The native URL channel queues links before authentication. This host only
@@ -58,11 +58,10 @@ class _SwarmJoinHostState extends State<SwarmJoinHost> {
try {
final c = await app.superTabs.open(accountRequest.tabId);
if (!mounted || app.currentUser?.id != accountId) return;
- final started = await showSwarmNewAgentDialog(
+ final started = await showBringAgentForm(
context,
controller: c,
app: app,
- bringing: true,
isCurrent: () =>
app.currentUser?.id == accountId && !accountRequest.answered,
);
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 155b49a40..2a87fad8b 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -46,6 +46,9 @@ class SuperTabLaunch {
Swarm tab,
String conversationId, {
bool newProject = false,
+ // + New agent (task #4196): a Member in its own chat, or the Lead of a
+ // new project, chosen in the form.
+ bool newAgent = false,
}) async {
final account = app.currentUser?.id;
if (account == null) {
@@ -60,7 +63,7 @@ class SuperTabLaunch {
// in its chat, the person's first message going to it (River, 11-03,
// #2458: Tony's Personal project had none and joined a worker instead).
SuperTabSnapshot? snapshot;
- if (raw == null && tab.superTabId != null && !newProject) {
+ if (raw == null && tab.superTabId != null && !newProject && !newAgent) {
snapshot = await app.superTabs.readSnapshot(tab.superTabId!);
if (app.currentUser?.id != account) {
throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
@@ -71,7 +74,20 @@ class SuperTabLaunch {
unled != null &&
unled.leadConversationId == conversationId &&
snapshot!.leadOf(unled.id) == null;
- final saved = raw == null
+ final saved = raw == null && newAgent
+ ? <String, dynamic>{
+ 'operationId': superTabOperationId(),
+ 'joinId': superTabOperationId(),
+ 'tabId': tab.superTabId,
+ 'conversationId': conversationId,
+ 'newAgent': true,
+ 'agentKind': 'member',
+ 'lead': false,
+ 'newSwarm': false,
+ 'newProject': false,
+ 'visibility': 'public',
+ }
+ : raw == null
? <String, dynamic>{
'operationId': superTabOperationId(),
'joinId': superTabOperationId(),
@@ -97,7 +113,9 @@ class SuperTabLaunch {
// An agent joining a project with instructions names its role; an older
// Swarm (no coordinator name on the project) has no such field.
List<String>? roleSuggestions;
- if (saved['lead'] != true && tab.superTabId != null) {
+ if (saved['lead'] != true &&
+ saved['newAgent'] != true &&
+ tab.superTabId != null) {
final project =
(snapshot ?? await app.superTabs.readSnapshot(tab.superTabId!))
.projectFor(conversationId);
@@ -190,22 +208,41 @@ class SuperTabLaunch {
roleName: roleSuggestions == null
? null
: saved['roleName'] as String?,
- actionLabel: saved['newProject'] == true
+ actionLabel: saved['newAgent'] == true
+ ? 'New agent'
+ : saved['newProject'] == true
? 'New Project'
: saved['lead'] == true && saved['coordinator'] != true
? 'New Swarm'
: 'New Harness',
// Routing reads quota for Claude Code and Codex only, so a Lead is one
// of them; the agents it starts may be anything.
- engines: saved['lead'] == true ? const ['claude', 'codex'] : null,
+ engines: saved['lead'] == true || saved['newAgent'] == true
+ ? const ['claude', 'codex']
+ : null,
+ agentKind: saved['newAgent'] == true
+ ? saved['agentKind'] as String?
+ : null,
+ ownMachinesOnly: saved['newAgent'] == true,
projectVisibility:
- saved['lead'] == true && saved['coordinator'] != true
+ saved['newAgent'] != true &&
+ saved['lead'] == true &&
+ saved['coordinator'] != true
? saved['visibility'] as String? ?? 'public'
: null,
projectVisibilityLocked:
saved['projectPrepared'] == true ||
saved['creationRequest'] != null,
prepare: (machine, task, engine) async {
+ // The choice is what the first request is sent as, and stays.
+ if (saved['newAgent'] == true && !integration.agentKindLocked) {
+ final lead = integration.agentKind == 'lead';
+ saved['agentKind'] = lead ? 'lead' : 'member';
+ saved['lead'] = lead;
+ saved['newProject'] = lead;
+ saved['newAgentAt'] ??= DateTime.now().millisecondsSinceEpoch;
+ integration.agentKindLocked = true;
+ }
if (integration.leadMachines != null) {
await launch.recheckLeadMachine(
integration,
@@ -232,7 +269,7 @@ class SuperTabLaunch {
saved['visibility'] = integration.projectVisibility ?? 'public';
}
try {
- final prompt = await launch.prepare(machine, task);
+ final prompt = await launch.prepare(machine, task, engine);
integration.swarmSkillMode =
saved['skillMode'] as String? ?? 'orchestration';
integration.swarmRole = saved['lead'] == true ? 'lead' : 'dev';
@@ -310,6 +347,8 @@ class SuperTabLaunch {
: null,
)
..pending = recovering
+ ..agentKindLocked =
+ saved['newAgent'] == true && saved['newAgentAt'] != null
..leadMachines = leadMachines
..leadModels = leadModels
..newRepositoryOwners = newRepositoryOwners;
@@ -1042,7 +1081,7 @@ class SuperTabLaunch {
}
}
- Future<String> prepare(String machine, String task) async {
+ Future<String> prepare(String machine, String task, [String? engine]) async {
checkAccount();
refuseFullDesk();
if (app.stateOf(machine)?.belongsToOtherAccount == true) {
@@ -1072,6 +1111,7 @@ class SuperTabLaunch {
await persist();
}
await _createProject(task);
+ await _openMemberChat(machine, engine);
app.superTabs.deferTabDiscovery(saved['tabId'] as String);
// Revalidate a journal's destination before native submission. A project
// deleted on another computer must not leave an unattached native session.
@@ -1132,6 +1172,53 @@ class SuperTabLaunch {
}
}
+ /// A Member's own chat, once (task #4196): opened with no server start, as
+ /// this Desktop starts the agent itself. Its receipt stays in the journal.
+ Future<void> _openMemberChat(String machine, String? engine) async {
+ if (saved['newAgent'] != true ||
+ saved['lead'] == true ||
+ saved['chatPrepared'] == true) {
+ return;
+ }
+ final base = engine ?? saved['engine'] as String? ?? 'claude';
+ saved['chatRequest'] ??= {
+ 'operationId': '${saved['operationId']}-chat',
+ 'command': {
+ 'type': 'agent.new',
+ 'kind': 'regular',
+ 'machineId': machine,
+ 'engine': base,
+ 'name': base == 'codex' ? 'Codex' : 'Claude Code',
+ 'local': true,
+ },
+ };
+ await persist();
+ final Map<String, dynamic> created;
+ try {
+ created = await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${saved['tabId']}/commands',
+ body: superTabMap(saved['chatRequest']),
+ );
+ } on SuperTabFailure catch (failure) {
+ if (_refusedOutright(failure)) {
+ saved.remove('chatRequest');
+ await persist();
+ }
+ // A backend from before local Members refuses the field it does not know.
+ if (failure.code == 'VALIDATION_ERROR') {
+ throw const SuperTabFailure(
+ 'UPDATE_REQUIRED',
+ 'Update Harness to start a Member from here.',
+ );
+ }
+ rethrow;
+ }
+ saved['conversationId'] = superTabMap(created['result'])['conversationId'];
+ saved['chatPrepared'] = true;
+ await persist();
+ }
+
// A started request's journal stays until the person discards it.
static const projectUnavailable = SuperTabFailure(
'PROJECT_UNAVAILABLE',
@@ -1340,6 +1427,12 @@ class SuperTabLaunch {
}
}
controller.select(saved['conversationId'] as String);
+ // How long + New agent took to a running agent in its chat: the measure
+ // that warns first if it slows again (task #4196). No names or ids.
+ if (saved['newAgentAt'] case final int at) {
+ final ms = DateTime.now().millisecondsSinceEpoch - at;
+ appLog.info('super-tabs', 'New agent (${saved['agentKind']}) running in $ms ms');
+ }
await app.superTabs.storage.delete(key);
}
@@ -1461,12 +1554,39 @@ class SuperTabLaunch {
}
nothingWillJoin = true;
}
- if (nothingWillJoin) await _deleteEmptyProject();
+ if (nothingWillJoin) {
+ await _deleteEmptyProject();
+ await _archiveEmptyChat();
+ }
await app.superTabs.storage.delete(key);
checkAccount();
return null;
}
+ /// A Member's chat nothing joined is archived. Best effort, as below: the
+ /// person can still archive it from the chat.
+ Future<void> _archiveEmptyChat() async {
+ final chat = saved['conversationId'];
+ if (saved['chatPrepared'] != true || chat is! String) return;
+ try {
+ await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${saved['tabId']}/commands',
+ body: {
+ 'operationId': '${saved['operationId']}-discard',
+ 'command': {
+ 'type': 'conversation.archive',
+ 'conversationId': chat,
+ 'archived': true,
+ },
+ },
+ );
+ } catch (_) {
+ // Unreachable or refused: the chat stays.
+ }
+ checkAccount();
+ }
+
/// A new project nothing joined is only a name in the Swarm. Best effort:
/// a project left behind can still be deleted from its options, and must
/// not keep the person in this request.
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 97127863b..bc8fe0a72 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -63,7 +63,6 @@ import 'crew_panel.dart';
import 'instructions_panel.dart';
import 'project_rules.dart';
import 'model.dart';
-import 'join/new_agent_dialog.dart';
import 'agent_details.dart';
import 'identity.dart' show superTabMachineName;
import 'identity_card.dart';
@@ -140,6 +139,7 @@ class SuperTabView extends StatefulWidget {
this.terminalsVisible = false,
this.app,
this.onNewProject,
+ this.onNewAgent,
this.rightPane,
this.onNewSwarm,
this.onChooseAgentTerminal,
@@ -171,6 +171,10 @@ class SuperTabView extends StatefulWidget {
final AppNotifier? app;
final VoidCallback? onNewProject;
+ /// + New agent (task #4196): opens the workspace's Cmd-N form with Member or
+ /// Lead. Null shows no + New agent.
+ final VoidCallback? onNewAgent;
+
/// The Desktop's right pane (Swarm v3's Tasks, task #4119): always shown, never collapsing, in the pane layout's right
/// slot. Given, the chat of the selected agent or project is in the middle; without it the right pane keeps the Board's
/// chat as before.
@@ -2104,7 +2108,7 @@ class _SuperTabViewState extends State<SuperTabView>
compact: _phone,
app: widget.app,
onNewProject: widget.onNewProject,
- onNewAgent: widget.app == null ? null : _newAgent,
+ onNewAgent: widget.onNewAgent,
onOpenAgentChat: _openAgentChat,
onNewSwarm: widget.onNewSwarm,
page: _pageShown,
@@ -2136,15 +2140,6 @@ class _SuperTabViewState extends State<SuperTabView>
onOpenBuddyChat: (projectId) => unawaited(_openBuddyChat(projectId)),
);
- /// + New agent (Swarm v3, task #4118): the creation dialog, where Regular or PM is chosen and the agent starts on this
- /// computer. It needs the app: a view without one has no +.
- void _newAgent() {
- final app = widget.app;
- if (app != null) {
- unawaited(showSwarmNewAgentDialog(context, controller: c, app: app));
- }
- }
-
/// Opens the reader's Buddy chat in [projectId] in front of Notifications,
/// pull requests and a terminal, opening it on the server when they have
/// none yet: the sidebar's way in and ⇧⌘K's
@@ -5151,7 +5146,8 @@ class _SuperTabViewState extends State<SuperTabView>
if ((!widget.board || c.selected == null) &&
c.snapshot?.projects.isEmpty == true &&
!c.accessRevoked) {
- final newAgent = widget.board && widget.app != null ? _newAgent : null;
+ // The same + New agent as the left pane's: the Cmd-N form (task #4196).
+ final newAgent = widget.board ? widget.onNewAgent : null;
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
index 10e81b21a..a702ff4cc 100644
--- a/desktop/lib/super_tabs/workspace.dart
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -29,12 +29,16 @@ class SuperTabWorkspace extends StatefulWidget {
required this.canvas,
required this.onAddAgent,
this.onNewProject,
+ this.onNewAgent,
this.onNewSwarm,
});
final AppNotifier app;
final Widget canvas;
final ValueChanged<SuperTabConversation> onAddAgent;
final VoidCallback? onNewProject;
+
+ /// + New agent: the workspace's Cmd-N form, with Member or Lead (#4196).
+ final VoidCallback? onNewAgent;
final VoidCallback? onNewSwarm;
@override
@@ -665,6 +669,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
unawaited(showSuperTabPeople(context, controller)),
onAddAgent: widget.onAddAgent,
onNewProject: widget.onNewProject,
+ onNewAgent: widget.onNewAgent,
onNewSwarm: widget.onNewSwarm,
onOpenTerminal: (agent) => _focusAgent(
controller,
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index 9c9863747..42bc1de4b 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -90,6 +90,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
final _taskFocus = FocusNode(debugLabel: 'New harness task');
final _headerMachineMenu = MenuController();
final _headerMachineFocus = FocusNode(debugLabel: 'New harness computer');
+ final _kindMenu = MenuController();
+ final _kindFocus = FocusNode(debugLabel: 'New agent Member or Lead');
+ final _kindAnchor = GlobalKey();
final _leadRowFocus = <String, FocusNode>{};
final _headerMachineAnchor = GlobalKey();
bool get _desktopStartEnabled =>
@@ -234,6 +237,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
_taskText.dispose();
_taskFocus.dispose();
_headerMachineFocus.dispose();
+ _kindFocus.dispose();
for (final node in _leadRowFocus.values) {
node.dispose();
}
@@ -310,7 +314,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusScheduled = false;
if (!mounted) return;
- if (_headerMachineMenu.isOpen) return;
+ if (_headerMachineMenu.isOpen || _kindMenu.isOpen) return;
if (_picking) {
_inputFocus.requestFocus();
} else if (widget.desktop) {
@@ -337,8 +341,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
/// Escape and Close remain the explicit ways to discard an unfinished task.
void dismissFromOutside() {
if (widget.desktop) {
- if (_headerMachineMenu.isOpen) {
+ if (_headerMachineMenu.isOpen || _kindMenu.isOpen) {
_headerMachineMenu.close();
+ _kindMenu.close();
} else if (_picking && !box.locked) {
_closeDesktopChooser();
}
@@ -356,6 +361,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
void _closeDesktopChooser({bool? next}) {
_headerMachineMenu.close();
+ _kindMenu.close();
_folderAction = null;
box.setQuery('');
box.focusField(NewHarnessField.launch);
@@ -1087,8 +1093,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
}
void _cancel() {
- if (widget.desktop && _headerMachineMenu.isOpen) {
+ if (widget.desktop && (_headerMachineMenu.isOpen || _kindMenu.isOpen)) {
_headerMachineMenu.close();
+ _kindMenu.close();
return;
}
if (widget.desktop && !_picking) {
@@ -1148,6 +1155,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
void _openCreationRow(_Row row) {
_headerMachineMenu.close();
+ _kindMenu.close();
_folderAction = null;
// A direct shortcut enters the top-level chooser, even when another
// chooser currently owns a nested project or specialized-agent prompt.
@@ -1720,7 +1728,8 @@ class NewHarnessFormState extends State<NewHarnessForm> {
else ...[
_desktopTaskEditor(),
const SizedBox(height: 6),
- _desktopSettings(),
+ // A Buddy runs as the Swarm starts it.
+ if (!box.bringsBuddy) _desktopSettings(),
if (box.placesLead) _desktopLeadBlocked(),
if (box.requiredChoice
case final required?) ...[
@@ -1988,7 +1997,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
// Fo takes no repository; a cloud coding agent works on the chosen
// repository's GitHub copy, never on this computer's folder.
- if ((!box.isCloud || cloudAgentTakesRepository(box.engine)) &&
+ // A Buddy has a folder of its own (task #4196).
+ if (!box.bringsBuddy &&
+ (!box.isCloud || cloudAgentTakesRepository(box.engine)) &&
(!box.asGuest ||
box.fields.contains(NewHarnessField.projectMenu)))
_desktopField(
@@ -2020,6 +2031,33 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
),
),
+ if (box.agentKind case final kind?)
+ _desktopField(
+ order: 3.5,
+ finger: phone,
+ anchor: _kindAnchor,
+ child: _desktopKindMenu(
+ child: DesktopPill(
+ key: const ValueKey('new-harness-field-agent-kind'),
+ focusNode: _kindFocus,
+ label: kind == 'lead' ? 'Lead' : 'Member',
+ semanticLabel:
+ 'Starts as, ${kind == 'lead' ? 'Lead' : 'Member'}',
+ icon: kind == 'lead' ? AppIcons.crown : AppIcons.user,
+ menu: true,
+ capsule: true,
+ tooltip: 'Start as Lead or Member',
+ textSize: 13,
+ surfaceColor: DesktopChrome.surface,
+ onPressed:
+ box.locked || box.integration?.agentKindLocked == true
+ ? null
+ : () => _kindMenu.isOpen
+ ? _kindMenu.close()
+ : _kindMenu.open(),
+ ),
+ ),
+ ),
]),
),
if (!widget.embedded) ...[
@@ -2316,8 +2354,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {
controller: _taskText,
focusNode: _taskFocus,
canRequestFocus: box.takesTask,
- // As tall as what is typed, with the options under it.
- minLines: 1,
+ // Three rows to start, growing to seven as it is typed
+ // (anh Dee, 11-07, #4196; #2947 had cut it to one).
+ minLines: 3,
maxLines: 7,
textInputAction: TextInputAction.send,
readOnly: box.locked || !box.takesTask,
@@ -3804,6 +3843,41 @@ class NewHarnessFormState extends State<NewHarnessForm> {
}
// Computer selection belongs to the header, independently of repo search.
+ /// Member or Lead (task #4196): the one choice + New agent adds to Cmd-N.
+ Widget _desktopKindMenu({required Widget child}) {
+ final locked = box.locked || box.integration?.agentKindLocked == true;
+ return AppDropdown(
+ controller: _kindMenu,
+ childFocusNode: _kindFocus,
+ width: _machineMenuWidth,
+ onOpen: () => setState(() {}),
+ onClose: () {
+ if (!mounted) return;
+ setState(() {});
+ _chooserOrigin = _kindFocus;
+ _restoreChoiceFocus = true;
+ _chooserTraversal = null;
+ _focusEditor();
+ },
+ children: [
+ for (final (kind, label, detail, icon) in [
+ ('member', 'Member', 'Works with you in its own chat', AppIcons.user),
+ ('lead', 'Lead', 'Names and starts a project', AppIcons.crown),
+ ])
+ AppMenuItem(
+ key: ValueKey('new-harness-agent-kind-$kind'),
+ autofocus: kind == box.agentKind,
+ selected: kind == box.agentKind,
+ icon: icon,
+ label: label,
+ detail: detail,
+ onPressed: locked ? null : () => box.setAgentKind(kind),
+ ),
+ ],
+ child: child,
+ );
+ }
+
Widget _desktopMachineAnchor({required Widget child}) => AppDropdown(
controller: _headerMachineMenu,
childFocusNode: _headerMachineFocus,
diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dart
index 35a78d7b4..87cf8aa05 100644
--- a/desktop/test/desktop_composer_layout_test.dart
+++ b/desktop/test/desktop_composer_layout_test.dart
@@ -414,6 +414,34 @@ void main() {
);
}
+ // anh Dee, 11-07 (#4196): the task starts three rows tall and grows to seven
+ // as it is typed; #2947 had cut the empty box to one row.
+ testWidgets('the task opens three rows tall and grows to seven', (
+ tester,
+ ) async {
+ await _mount(tester);
+ Future<double> heightWith(int lines) async {
+ await tester.enterText(
+ _task,
+ List.generate(lines, (i) => 'line $i').join('\n'),
+ );
+ await tester.pumpAndSettle();
+ return tester.getSize(_task).height;
+ }
+
+ final empty = tester.getSize(_task).height;
+ final three = await heightWith(3);
+ final four = await heightWith(4);
+ final seven = await heightWith(7);
+ final ten = await heightWith(10);
+ final one = await heightWith(1);
+ expect(three, empty, reason: 'An empty task is three rows tall');
+ expect(one, empty, reason: 'One row typed keeps three rows');
+ expect(four, greaterThan(three), reason: 'It grows past three rows');
+ expect(ten, seven, reason: 'It stops growing at seven rows');
+ expect(seven - three, closeTo((four - three) * 4, 1));
+ });
+
testWidgets(
'footer controls show their purpose and keep stable focus geometry',
(tester) async {
diff --git a/desktop/test/new_harness_agent_kind_test.dart b/desktop/test/new_harness_agent_kind_test.dart
new file mode 100644
index 000000000..3eb2c9023
--- /dev/null
+++ b/desktop/test/new_harness_agent_kind_test.dart
@@ -0,0 +1,264 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_launch_integration.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+
+/// Four machines of the person's view: this computer, another of their own,
+/// one another account shares with them, and a Harness Team account.
+class _App extends AppNotifier {
+ _App()
+ : super(config: AppConfig.dev, authSession: AuthSession(), configStore: null) {
+ MachineState add(Machine machine, {bool local = false}) =>
+ machineStates[machine.machineId] = MachineState(machine)
+ ..localOnly = local
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..engines.replace(const [
+ EngineAvailability(engine: 'claude', installed: true),
+ EngineAvailability(engine: 'codex', installed: true),
+ ]);
+ machines = [
+ const Machine(
+ machineId: 'here',
+ name: 'This Mac',
+ authMode: MachineAuthMode.remote,
+ ),
+ const Machine(
+ machineId: 'studio',
+ name: 'Studio',
+ authMode: MachineAuthMode.remote,
+ ),
+ const Machine(
+ machineId: 'guest',
+ name: 'Ken’s Mac',
+ authMode: MachineAuthMode.remote,
+ machineShare: MachineShare(
+ ownerName: 'Ken',
+ ownerEmail: '[email protected]',
+ via: 'email',
+ added: true,
+ ),
+ ),
+ const Machine(
+ machineId: 'team',
+ name: 'Studio · Team',
+ authMode: MachineAuthMode.remote,
+ sessionKind: 'team',
+ ),
+ ];
+ add(machines[0], local: true);
+ for (final machine in machines.skip(1)) {
+ add(machine);
+ }
+ }
+
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {}
+
+ @override
+ Future<void> probeDsh(
+ String machineId, {
+ bool force = false,
+ bool userAction = false,
+ }) async {}
+
+ @override
+ Future<GridModels> refreshGridModels(
+ String machineId, {
+ bool userAction = false,
+ }) async => const GridModels.unreachable();
+
+ @override
+ Future<Map<String, dynamic>> readGitProject(
+ String machineId,
+ String path, {
+ bool refresh = false,
+ }) async => {'isGit': false};
+
+ @override
+ Future<Map<String, dynamic>> listCodexProfiles(
+ String machineId, {
+ Set<String> observedPaths = const {},
+ }) async => {'profiles': []};
+}
+
+HarnessLaunchIntegration _newAgent() => HarnessLaunchIntegration(
+ creationId: 'creation',
+ prepare: (machine, task, engine) async => task,
+ complete: (machine, harnessId) async {},
+ beforeSubmit: (machine, receipt) async {},
+ engines: const ['claude', 'codex'],
+ agentKind: 'member',
+ ownMachinesOnly: true,
+);
+
+final _kind = find.byKey(const ValueKey('new-harness-field-agent-kind'));
+final _machine = find.byKey(const ValueKey('new-harness-field-machine'));
+Finder _machineOption(String id) =>
+ find.byKey(ValueKey('new-harness-machine-option-$id'));
+
+Future<({NewHarnessController box, GlobalKey image})> _mount(
+ WidgetTester tester, {
+ HarnessLaunchIntegration? integration,
+ Brightness brightness = Brightness.dark,
+}) async {
+ final app = _App();
+ final box = NewHarnessController(
+ app,
+ machineId: 'here',
+ engine: 'claude',
+ folder: '/work/site',
+ integration: integration,
+ );
+ addTearDown(() {
+ box.dispose();
+ app.dispose();
+ });
+ tester.view.physicalSize = const Size(1200, 700);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final image = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid
+ .buildAppTheme(brightness: brightness)
+ .copyWith(platform: TargetPlatform.macOS),
+ home: RepaintBoundary(
+ key: image,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Padding(
+ padding: const EdgeInsets.all(24),
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () {},
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (box: box, image: image);
+}
+
+void main() {
+ final renderDir = Platform.environment['COMPOSER_LAYOUT_RENDER_DIR'];
+ setUpAll(() async {
+ if (renderDir != null) await loadPreviewFonts();
+ });
+
+ Future<void> capture(WidgetTester tester, GlobalKey key, String name) async {
+ if (renderDir == null) return;
+ final boundary =
+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ final directory = Directory(renderDir)..createSync(recursive: true);
+ await File(
+ '${directory.path}/$name.png',
+ ).writeAsBytes(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ // Task #4196 (anh Dee, 11-07): + New agent is Cmd-N with one more choice.
+ for (final brightness in Brightness.values) {
+ testWidgets('New agent adds a Member or Lead choice, ${brightness.name}', (
+ tester,
+ ) async {
+ final integration = _newAgent();
+ final mounted = await _mount(
+ tester,
+ integration: integration,
+ brightness: brightness,
+ );
+ final project = tester.getRect(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ expect(_kind, findsOneWidget);
+ expect(find.descendant(of: _kind, matching: find.text('Member')),
+ findsOneWidget);
+ final kind = tester.getRect(_kind);
+ expect(
+ kind.top >= project.bottom ||
+ (kind.center.dy - project.center.dy).abs() <= 1 &&
+ kind.left > project.right,
+ isTrue,
+ reason: 'The choice comes after the project, in reading order',
+ );
+ await capture(tester, mounted.image, 'new-agent-member-${brightness.name}');
+
+ await tester.tap(_kind);
+ await tester.pumpAndSettle();
+ expect(find.text('Names and starts a project'), findsOneWidget);
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-agent-kind-lead')),
+ );
+ await tester.pumpAndSettle();
+ expect(integration.agentKind, 'lead');
+ expect(find.descendant(of: _kind, matching: find.text('Lead')),
+ findsOneWidget);
+ await capture(tester, mounted.image, 'new-agent-lead-${brightness.name}');
+ });
+ }
+
+ testWidgets('New agent offers only the person’s own computers', (
+ tester,
+ ) async {
+ final mounted = await _mount(tester, integration: _newAgent());
+ expect(
+ mounted.box.machineChoices.map((m) => m.id),
+ ['here', 'studio'],
+ );
+ await tester.tap(_machine);
+ await tester.pumpAndSettle();
+ expect(_machineOption('here'), findsOneWidget);
+ expect(_machineOption('studio'), findsOneWidget);
+ expect(_machineOption('guest'), findsNothing);
+ expect(_machineOption('team'), findsNothing);
+ });
+
+ testWidgets('the choice is locked once its request is sent', (tester) async {
+ final integration = _newAgent()..agentKindLocked = true;
+ await _mount(tester, integration: integration);
+ await tester.tap(_kind);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('new-harness-agent-kind-lead')),
+ findsNothing,
+ );
+ expect(integration.agentKind, 'member');
+ });
+
+ testWidgets('plain Cmd-N has no choice and keeps every computer', (
+ tester,
+ ) async {
+ final mounted = await _mount(tester);
+ expect(_kind, findsNothing);
+ expect(
+ mounted.box.machineChoices.map((m) => m.id),
+ containsAll(['here', 'studio', 'guest', 'team']),
+ );
+ });
+}
diff --git a/desktop/test/super_tab_new_agent_launch_test.dart b/desktop/test/super_tab_new_agent_launch_test.dart
new file mode 100644
index 000000000..886dac81b
--- /dev/null
+++ b/desktop/test/super_tab_new_agent_launch_test.dart
@@ -0,0 +1,146 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/super_tabs/launch.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+/// + New agent (task #4196, anh Dee 11-07): Cmd-N starts the agent on the
+/// person's own computer, then it joins the Swarm as a Member in its own chat
+/// or as the Lead of a new project.
+Future<NewHarnessController> _newAgent(
+ SuperTabLaunchFixture f, {
+ String engine = 'claude',
+}) async {
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final integration = await SuperTabLaunch.open(
+ f.app,
+ f.app.activeSwarm,
+ 'new-agent',
+ newAgent: true,
+ );
+ final box = NewHarnessController(
+ f.app,
+ machineId: 'm',
+ engine: engine,
+ folder: '/work/project',
+ task: 'Tidy the docs.',
+ integration: integration,
+ );
+ addTearDown(box.dispose);
+ await Future<void>.delayed(Duration.zero);
+ return box;
+}
+
+List<Map> _commands(SuperTabLaunchFixture f) => [
+ for (final post in f.connection.server.posts) post['command'] as Map,
+];
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test('opens as a Member of Claude Code or Codex on own computers', () async {
+ final f = SuperTabLaunchFixture();
+ final box = await _newAgent(f);
+ final integration = box.integration!;
+ expect(integration.agentKind, 'member');
+ expect(integration.ownMachinesOnly, isTrue);
+ expect(integration.engines, ['claude', 'codex']);
+ expect(integration.leadMachines, isNull, reason: 'Every picker stays');
+ expect(box.actionLabel, 'New agent');
+ });
+
+ test('a Member opens its chat, starts here, then joins that chat', () async {
+ final f = SuperTabLaunchFixture();
+ final box = await _newAgent(f);
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+
+ final chat = _commands(f).firstWhere((c) => c['type'] == 'agent.new');
+ expect(chat, {
+ 'type': 'agent.new',
+ 'kind': 'regular',
+ 'machineId': 'm',
+ 'engine': 'claude',
+ 'name': 'Claude Code',
+ 'local': true,
+ });
+ final chatId = f.connection.server.state['conversations']
+ .cast<Map>()
+ .firstWhere((g) => g['kind'] == 'agent-chat')['id'] as String;
+ final create = f.connection.calls
+ .firstWhere((c) => c.$1 == 'agent_create')
+ .$2;
+ expect(create['prompt'], contains('messages $chatId'));
+ expect(create['swarmRole'], 'dev');
+ expect(create['cwd'] ?? create['folder'], '/work/project');
+ final join = f.connection.joins.single['command'] as Map;
+ expect(join, containsPair('conversationId', chatId));
+ expect(join, containsPair('lead', false));
+ expect(join['initialMessage'], 'Tidy the docs.');
+ expect(_commands(f).where((c) => c['type'] == 'project.create'), isEmpty);
+ expect(box.integration!.agentKindLocked, isTrue);
+ expect(f.app.superTabs.peek(tabId)!.selectedId, chatId);
+ });
+
+ test('a Lead creates its project, starts here, then leads it', () async {
+ final f = SuperTabLaunchFixture();
+ final box = await _newAgent(f, engine: 'codex');
+ box.setAgentKind('lead');
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+
+ final types = _commands(f).map((c) => c['type']).toList();
+ expect(types, containsAllInOrder(['project.create', 'agent.add']));
+ expect(types, contains('project.rename'));
+ expect(types, isNot(contains('agent.new')));
+ final create = f.connection.calls
+ .firstWhere((c) => c.$1 == 'agent_create')
+ .$2;
+ expect(create['swarmRole'], 'lead');
+ expect(f.connection.joins.single['command'], containsPair('lead', true));
+ });
+
+ test('a lost join reply is retried as the same request, once', () async {
+ final f = SuperTabLaunchFixture()..connection.loseJoin = true;
+ final box = await _newAgent(f);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(_commands(f).where((c) => c['type'] == 'agent.new'), hasLength(1));
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), hasLength(1));
+ final joins = f.connection.joins.map((j) => j['operationId']).toSet();
+ expect(joins, hasLength(1));
+ });
+
+ test('reopened after a failed start, it keeps the same chat', () async {
+ final f = SuperTabLaunchFixture()..connection.failCreation = true;
+ final box = await _newAgent(f);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ f.connection.failCreation = false;
+ final again = await _newAgent(f);
+ expect(await again.create(), NewHarnessOutcome.created, reason: again.error);
+ expect(_commands(f).where((c) => c['type'] == 'agent.new'), hasLength(1));
+ expect(f.connection.joins, hasLength(1));
+ });
+
+ test('Discard of a start that never ran archives the Member’s chat', () async {
+ final f = SuperTabLaunchFixture()..connection.loseCreate = true;
+ f.connection.creationRecovery = (type, payload) async => {
+ 'creationId': payload['creationId'],
+ 'state': type == 'agent_create_cancel' ? 'cancelled' : 'missing',
+ };
+ final box = await _newAgent(f);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ final chatId = f.connection.server.state['conversations']
+ .cast<Map>()
+ .firstWhere((g) => g['kind'] == 'agent-chat')['id'];
+ final recovered = await _newAgent(f);
+ expect(recovered.integration!.agentKindLocked, isTrue);
+ expect(await recovered.integration!.discard!(), isNull);
+ final archive = _commands(
+ f,
+ ).singleWhere((c) => c['type'] == 'conversation.archive');
+ expect(archive, {
+ 'type': 'conversation.archive',
+ 'conversationId': chatId,
+ 'archived': true,
+ });
+ });
+}
diff --git a/desktop/test/super_tab_v3_empty_org_test.dart b/desktop/test/super_tab_v3_empty_org_test.dart
index 85df77173..32abb81a6 100644
--- a/desktop/test/super_tab_v3_empty_org_test.dart
+++ b/desktop/test/super_tab_v3_empty_org_test.dart
@@ -64,6 +64,7 @@ void main() {
app: app,
onNewSwarm: () {},
onNewProject: onNewProject,
+ onNewAgent: () {},
onInvite: () {},
onAddAgent: (_) {},
onOpenTerminal: (_) {},
diff --git a/desktop/test/super_tab_v3_left_test.dart b/desktop/test/super_tab_v3_left_test.dart
index 36648d4f0..401cf460d 100644
--- a/desktop/test/super_tab_v3_left_test.dart
+++ b/desktop/test/super_tab_v3_left_test.dart
@@ -442,10 +442,13 @@ void main() {
});
});
- group('the view offers + New agent only with an app', () {
+ // Task #4196: + New agent opens the workspace's Cmd-N form, so the view
+ // offers it only when its workspace can open one.
+ group('the view offers + New agent only with Cmd-N to open', () {
Future<SuperTabController> view(
WidgetTester tester, {
required bool withApp,
+ VoidCallback? onNewAgent,
}) async {
final server = swarm()..state['agents'] = [_agent('kestrel', 'Kestrel')];
final c = server.controller(
@@ -471,6 +474,7 @@ void main() {
app: app,
onInvite: () {},
onAddAgent: (_) {},
+ onNewAgent: onNewAgent,
onOpenTerminal: (_) {},
machineName: (_) => 'Mac Studio',
board: true,
@@ -482,17 +486,22 @@ void main() {
return c;
}
- testWidgets('with an app the last row of My agents is + New agent', (
+ testWidgets('the last row of My agents is + New agent, which opens Cmd-N', (
tester,
) async {
- final c = await view(tester, withApp: true);
+ var opened = 0;
+ final c = await view(tester, withApp: true, onNewAgent: () => opened++);
expect(key('super-new-agent-row'), findsOneWidget);
+ await tester.tap(key('super-new-agent-row'));
+ await tester.pump();
+ expect(opened, 1);
+ expect(find.text('Create agent'), findsNothing);
await tester.pumpWidget(const SizedBox());
c.dispose();
});
- testWidgets('without one it has none', (tester) async {
- final c = await view(tester, withApp: false);
+ testWidgets('without Cmd-N to open it has none', (tester) async {
+ final c = await view(tester, withApp: true);
expect(key('super-new-agent-row'), findsNothing);
await tester.pumpWidget(const SizedBox());
c.dispose();
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 58a32ee05..4090ae9c1 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -1749,6 +1749,21 @@ class ConversationServer {
'machineId': ?machineId,
'requestedAt': revision,
};
+ } else if (command['type'] == 'agent.new' && command['local'] == true) {
+ // As backend agent.new with `local` (task #4196): a Member's own chat,
+ // and no start; its person's Desktop starts the agent itself.
+ revision++;
+ final id = 'agent-chat-$revision';
+ (state['conversations'] as List).add({
+ ...conversationFixture(id, command['name'] as String),
+ 'kind': 'agent-chat',
+ 'audience': {
+ 'people': [
+ {'id': 'owner', 'generation': 'g'},
+ ],
+ },
+ });
+ output['conversationId'] = id;
} else if (command['type'] == 'project.create') {
revision++;
final projects = state['projects'] ??= <dynamic>[
diff --git a/desktop/test/swarm_first_join_widget_test.dart b/desktop/test/swarm_first_join_widget_test.dart
index da6503ee6..7e19b8686 100644
--- a/desktop/test/swarm_first_join_widget_test.dart
+++ b/desktop/test/swarm_first_join_widget_test.dart
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/super_tabs/join/agent_dialog.dart';
+import 'package:harness/widgets/new_harness_form.dart';
import 'package:harness/super_tabs/join_dialog.dart';
import 'support/capture.dart';
@@ -37,30 +37,41 @@ void main() {
await tester.pump();
await tester.runAsync(() async => pumpEventQueue());
await tester.pumpAndSettle();
- expect(find.byType(SwarmAgentDialog), findsOneWidget);
- expect(find.text('Bring your agent'), findsOneWidget);
+ // Task #4196: the Cmd-N form, its agent and computer, for a Buddy.
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(find.text('Bring agent'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-agent-kind')),
+ findsNothing,
+ );
expect(find.text('Separate Harness Team account'), findsNothing);
expect(find.text('Add machine'), findsNothing);
await captureWindow(tester, shots, 'bring-agent-${brightness.name}');
if (brightness == Brightness.dark) {
- await tester.tap(find.byTooltip('Close').first);
+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));
await tester.pumpAndSettle();
await tester.runAsync(() => joining);
expectNoEnrollment(f);
} else {
await tester.runAsync(() async {
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
+ await tester.tap(find.text('Bring agent'));
await pumpEventQueue();
});
await tester.pumpAndSettle();
- if (find.text('Retry').evaluate().isNotEmpty) {
+ // The machine prepares its Buddy folder on the first ask, as a real
+ // one may; the person tries again.
+ if (find.textContaining('still being prepared').evaluate().isNotEmpty) {
await tester.runAsync(() async {
- await tester.tap(find.text('Retry'));
+ await tester.tap(find.text('Bring agent'));
await pumpEventQueue();
});
await tester.pumpAndSettle();
}
- expect(find.byType(SwarmAgentDialog), findsNothing);
+ expect(find.byType(NewHarnessForm), findsNothing);
await tester.runAsync(() => joining);
final starts = f.connection.server.posts.where(
(post) => (post['command'] as Map)['type'] == 'buddy.create',
diff --git a/desktop/test/swarm_v3_agent_dialog_test.dart b/desktop/test/swarm_v3_agent_dialog_test.dart
deleted file mode 100644
index 5e1bab453..000000000
--- a/desktop/test/swarm_v3_agent_dialog_test.dart
+++ /dev/null
@@ -1,204 +0,0 @@
-import 'dart:async';
-import 'dart:io';
-
-import 'support/capture.dart';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/app_theme.dart' as grid;
-import 'package:harness/super_tabs/join/agent_dialog.dart';
-import 'package:harness/widgets/desktop_chrome.dart';
-
-Future<void> mount(
- WidgetTester tester, {
- bool bringing = false,
- Brightness brightness = Brightness.light,
- List<String> engines = const ['claude', 'codex'],
- required SwarmAgentCreate create,
- bool Function()? current,
-}) async {
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
- await tester.pumpWidget(
- MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- home: Builder(
- builder: (context) => Scaffold(
- body: TextButton(
- onPressed: () => showDialog<Map<String, dynamic>>(
- context: context,
- builder: (_) => SwarmAgentDialog(
- bringing: bringing,
- engines: engines,
- create: create,
- isCurrent: current ?? () => true,
- ),
- ),
- child: const Text('Open'),
- ),
- ),
- ),
- ),
- );
- await tester.tap(find.text('Open'));
- await tester.pumpAndSettle();
-}
-
-void main() {
- final shots = Platform.environment['HARNESS_V3_JOIN_SHOTS'];
- setUpAll(() => loadCaptureFonts(shots));
- for (final brightness in Brightness.values) {
- testWidgets('new agent forms fit in ${brightness.name}', (tester) async {
- await tester.binding.setSurfaceSize(const Size(1000, 760));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- await mount(
- tester,
- brightness: brightness,
- create: (_, _, _, _) async => {'startId': 'one'},
- );
- final segments = tester.widget<SegmentedButton<String>>(find.byType(SegmentedButton<String>));
- expect(segments.style?.foregroundColor?.resolve({WidgetState.selected}), DesktopChrome.onSelection);
- expect(tester.takeException(), isNull);
- await captureWindow(tester, shots, 'new-regular-${brightness.name}');
- await tester.tap(find.text('PM'));
- await tester.pumpAndSettle();
- await tester.enterText(
- find.byKey(const Key('swarm-agent-project')),
- 'My project',
- );
- await tester.pumpAndSettle();
- expect(tester.takeException(), isNull);
- await captureWindow(tester, shots, 'new-pm-${brightness.name}');
- });
- }
-
- testWidgets('bringing an agent picks its engine and makes it the Buddy', (
- tester,
- ) async {
- final submitted = <(String, String, String?)>[];
- await mount(
- tester,
- bringing: true,
- create: (engine, kind, project, operation) async {
- submitted.add((engine, kind, project));
- return {'agentId': 'buddy'};
- },
- );
- expect(find.text('Bring your agent'), findsOneWidget);
- expect(find.textContaining('Team account'), findsNothing);
- expect(find.textContaining('Add machine'), findsNothing);
- expect(find.text('Regular'), findsNothing);
- await tester.tap(find.byKey(const Key('swarm-agent-engine')));
- await tester.pumpAndSettle();
- await tester.tap(find.text('Codex').last);
- await tester.pumpAndSettle();
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- await tester.pumpAndSettle();
- expect(submitted, [('codex', 'buddy', null)]);
- expect(find.text('Bring your agent'), findsNothing);
- });
-
- testWidgets('Regular has no project; PM requires a trimmed project name', (
- tester,
- ) async {
- final submitted = <(String, String, String?)>[];
- Future<Map<String, dynamic>> create(
- String e,
- String k,
- String? p,
- String op,
- ) async {
- submitted.add((e, k, p));
- return {'agentId': k};
- }
-
- await mount(tester, create: create);
- expect(find.byKey(const Key('swarm-agent-project')), findsNothing);
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- await tester.pumpAndSettle();
- expect(submitted.single, ('claude', 'regular', null));
- await mount(tester, create: create);
- await tester.tap(find.text('PM'));
- await tester.pumpAndSettle();
- expect(
- tester
- .widget<FilledButton>(find.byKey(const Key('swarm-agent-submit')))
- .onPressed,
- isNull,
- );
- await tester.enterText(
- find.byKey(const Key('swarm-agent-project')),
- ' Compiler ',
- );
- await tester.pump();
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- await tester.pumpAndSettle();
- expect(submitted.last, ('claude', 'pm', 'Compiler'));
- });
-
- testWidgets(
- 'lost response retries one operation and never shows raw failures',
- (tester) async {
- final operations = <String>[];
- await mount(
- tester,
- create: (e, k, p, op) async {
- operations.add(op);
- if (operations.length == 1) throw StateError('private-token-value');
- return {'agentId': 'one'};
- },
- );
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- await tester.pumpAndSettle();
- expect(find.textContaining('private-token-value'), findsNothing);
- expect(find.text('Retry'), findsOneWidget);
- await tester.tap(find.text('Retry'));
- await tester.pumpAndSettle();
- expect(operations, hasLength(2));
- expect(operations.toSet(), hasLength(1));
- },
- );
-
- testWidgets('no local engine cannot launch and explains how to recover', (
- tester,
- ) async {
- await mount(
- tester,
- engines: [],
- create: (e, k, p, op) async => throw StateError('must not launch'),
- );
- expect(find.textContaining('Install'), findsOneWidget);
- expect(
- tester
- .widget<FilledButton>(find.byKey(const Key('swarm-agent-submit')))
- .onPressed,
- isNull,
- );
- });
-
- testWidgets(
- 'pending submission is single and account changes invalidate it',
- (tester) async {
- final answer = Completer<Map<String, dynamic>>();
- var calls = 0, current = true;
- await mount(
- tester,
- current: () => current,
- create: (e, k, p, op) {
- calls++;
- return answer.future;
- },
- );
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- await tester.pump();
- await tester.tap(find.byKey(const Key('swarm-agent-submit')));
- expect(calls, 1);
- current = false;
- answer.complete({'agentId': 'old-account'});
- await tester.pumpAndSettle();
- expect(find.text('New agent'), findsOneWidget);
- expect(find.textContaining('account changed'), findsOneWidget);
- },
- );
-}
diff --git a/desktop/test/swarm_v3_agent_launcher_test.dart b/desktop/test/swarm_v3_agent_launcher_test.dart
index 7f9eecc80..df8a04a3f 100644
--- a/desktop/test/swarm_v3_agent_launcher_test.dart
+++ b/desktop/test/swarm_v3_agent_launcher_test.dart
@@ -1,100 +1,57 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/join/agent_launcher.dart';
+// The Buddy a person brings as they join starts through the Swarm on their own
+// computer (buddy.create), whichever form chose its engine (task #4196).
void main() {
- for (final kind in ['buddy', 'regular', 'pm']) {
- test(
- '$kind uses this computer and owner command without a login or Team setup',
- () async {
- final sent = <Map<String, dynamic>>[];
- final launcher = SwarmAgentLauncher(
- machineId: 'local',
- machineName: 'My computer',
- inSwarm: false,
- isCurrent: () => true,
- prepare: (operation) async => {
- 'name': 'My computer',
- 'cwd': '/work',
- 'engines': ['codex', 'pi'],
- },
- command: (command, operation) async {
- sent.add(command);
- return command['type'] == 'machine.contribute'
- ? {}
- : {'startId': 'start', 'conversationId': 'chat'};
- },
- );
- final result = await launcher.create(
- 'codex',
- kind,
- kind == 'pm' ? 'Compiler' : null,
- 'operation',
- );
- expect(result['startId'], 'start');
- final start = sent.last;
- expect(start['machineId'], 'local');
- if (kind == 'buddy') {
- expect(sent, hasLength(1));
- expect(start['type'], 'buddy.create');
- expect(start['setup'], containsPair('cwd', '/work'));
- expect((start['setup'] as Map)['engines'], ['codex']);
- } else {
- expect(sent.first['type'], 'machine.contribute');
- expect(sent.first['teamAccountOnly'], isTrue);
- expect(sent.first.containsKey('ifMissing'), isFalse);
- expect(start['type'], 'agent.new');
- expect(start['kind'], kind);
- if (kind == 'pm') expect(start.containsKey('name'), isFalse);
- expect(start['projectName'], kind == 'pm' ? 'Compiler' : null);
- }
- expect(sent.toString(), isNot(contains('teamSetup')));
- },
- );
- }
- for (final kind in ['regular', 'pm']) {
- test(
- 'a non-owner collaborator can create $kind without sharing their login',
- () async {
- final calls = <Map<String, dynamic>>[];
- final launcher = SwarmAgentLauncher(
- machineId: 'collaborator-computer',
- machineName: 'This computer',
- inSwarm: false,
- isCurrent: () => true,
- prepare: (_) async => {
- 'cwd': '/work',
- 'engines': ['claude'],
- },
- command: (command, operation) async {
- // This transport represents a collaborator, not the org owner. The
- // backend reserves automatic ifMissing admission for the owner.
- if (command['type'] == 'machine.contribute' &&
- command['ifMissing'] == true) {
- throw const SwarmAgentLaunchFailure(
- 'Only the org owner adds a machine automatically.',
- );
- }
- calls.add(command);
- return command['type'] == 'machine.contribute'
- ? <String, dynamic>{}
- : {'startId': 'started', 'conversationId': 'own-chat'};
- },
- );
- final result = await launcher.create(
- 'claude',
- kind,
- kind == 'pm' ? 'Compiler' : null,
- 'collaborator-operation',
- );
- expect(result['startId'], 'started');
- expect(calls, hasLength(2));
- expect(calls.first['teamAccountOnly'], isTrue);
- expect(calls.first.containsKey('ownAccountWork'), isFalse);
- expect(calls.last['type'], 'agent.new');
+ test(
+ 'a Buddy uses this computer and owner command without a login or Team setup',
+ () async {
+ final sent = <Map<String, dynamic>>[];
+ final launcher = SwarmAgentLauncher(
+ machineId: 'local',
+ machineName: 'My computer',
+ inSwarm: false,
+ isCurrent: () => true,
+ prepare: (operation) async => {
+ 'name': 'My computer',
+ 'cwd': '/work',
+ 'engines': ['codex', 'pi'],
+ },
+ command: (command, operation) async {
+ sent.add(command);
+ return {'startId': 'start', 'conversationId': 'chat'};
+ },
+ );
+ final result = await launcher.create('codex', 'operation');
+ expect(result['startId'], 'start');
+ expect(sent, hasLength(1));
+ expect(sent.single['type'], 'buddy.create');
+ expect(sent.single['machineId'], 'local');
+ expect(sent.single['setup'], containsPair('cwd', '/work'));
+ expect((sent.single['setup'] as Map)['engines'], ['codex']);
+ expect(sent.toString(), isNot(contains('teamSetup')));
+ },
+ );
+
+ test('a computer already in the Swarm sends no setup', () async {
+ final sent = <Map<String, dynamic>>[];
+ final launcher = SwarmAgentLauncher(
+ machineId: 'local',
+ machineName: 'Mac',
+ inSwarm: true,
+ isCurrent: () => true,
+ prepare: (op) async => throw StateError('must not prepare'),
+ command: (command, op) async {
+ sent.add(command);
+ return {'startId': 'one'};
},
);
- }
- test('a retry retains preparation and each command operation', () async {
+ await launcher.create('claude', 'op');
+ expect(sent.single.containsKey('setup'), isFalse);
+ });
+
+ test('a retry retains preparation and its operation', () async {
var prepares = 0, starts = 0;
final ops = <String>[];
final launcher = SwarmAgentLauncher(
@@ -111,20 +68,16 @@ void main() {
},
command: (cmd, op) async {
ops.add(op);
- if (cmd['type'] == 'agent.new' && starts++ == 0)
- throw StateError('lost');
+ if (starts++ == 0) throw StateError('lost');
return {'startId': 'one'};
},
);
- await expectLater(
- launcher.create('claude', 'regular', null, 'op'),
- throwsStateError,
- );
- await launcher.create('claude', 'regular', null, 'op');
+ await expectLater(launcher.create('claude', 'op'), throwsStateError);
+ await launcher.create('claude', 'op');
expect(prepares, 1);
- expect(ops.where((op) => op.endsWith('-start')).toSet(), hasLength(1));
- expect(ops.where((op) => op.endsWith('-machine')), hasLength(1));
+ expect(ops.toSet(), {'op-start'});
});
+
test('account invalidation after prepare never sends a command', () async {
var current = true;
final launcher = SwarmAgentLauncher(
@@ -142,7 +95,7 @@ void main() {
command: (cmd, op) async => throw StateError('must not send'),
);
await expectLater(
- launcher.create('claude', 'buddy', null, 'op'),
+ launcher.create('claude', 'op'),
throwsA(isA<SwarmAgentLaunchFailure>()),
);
});
diff --git a/desktop/test/swarm_v3_new_agent_entry_test.dart b/desktop/test/swarm_v3_new_agent_entry_test.dart
new file mode 100644
index 000000000..44eed6096
--- /dev/null
+++ b/desktop/test/swarm_v3_new_agent_entry_test.dart
@@ -0,0 +1,64 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.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/state/new_harness.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap;
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+// Task #4196 (anh Dee, 11-07): + New agent in My agents opens the workspace's
+// Cmd-N form, with every picker and one more choice, Member or Lead.
+void main() {
+ testWidgets('+ New agent opens Cmd-N as a Member', (tester) async {
+ final oldEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = oldEntry);
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final projects = SwarmProjectStore();
+ addTearDown(projects.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1500, 900);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) =>
+ KeymapProvider(keymap: map, child: child!),
+ home: SwarmScreen(
+ notifier: f.app,
+ nativeTabs: false,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final row = find.byKey(const ValueKey('super-new-agent-row'));
+ await tester.ensureVisible(row);
+ await tester.tap(row);
+ await tester.pumpAndSettle();
+
+ final form = find.byType(NewHarnessForm);
+ expect(form, findsOneWidget);
+ final kind = find.byKey(const ValueKey('new-harness-field-agent-kind'));
+ expect(find.descendant(of: kind, matching: find.text('Member')),
+ findsOneWidget);
+ for (final picker in ['agent', 'machine', 'project']) {
+ expect(find.byKey(ValueKey('new-harness-field-$picker')), findsOneWidget);
+ }
+ expect(tester.widget<NewHarnessForm>(form).controller.agentKind, 'member');
+ expect(find.text('Create agent'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ });
+}
diff --git a/docs/plans/2026-11-07-cmdn-new-agent-plan.md b/docs/plans/2026-11-07-cmdn-new-agent-plan.md
new file mode 100644
index 000000000..2c4a43071
--- /dev/null
+++ b/docs/plans/2026-11-07-cmdn-new-agent-plan.md
@@ -0,0 +1,147 @@
+# Cmd-N new agent (Lead or Member) implementation plan
+
+> Written by the writing-plans skill as the project's Engineer role uses it: implemented task by task in this session,
+> each failing test committed before its code, then one independent review of the pull request. No execution handoff.
+
+**Goal:** + New agent opens the existing Cmd-N form with every picker unchanged and one new choice, Lead or Member; the
+separate New agent dialog goes, and creating an agent stops waiting on a server start.
+
+**Architecture:** Cmd-N already reaches a Swarm through `HarnessLaunchIntegration` (`SuperTabLaunch.open`): the agent
+starts on the person's own machine through `AppNotifier.createAgent`, and the running session then joins the Swarm with
+`agent.add`. A Lead reuses its New Project path (`project.create`, then `agent.add` as lead). A Member gets its own chat
+from `agent.new` with `local: true` (no server start), and `agent.add` takes the running session into that chat as a
+Regular agent. The form gains one capsule for the choice and offers only the person's own machines.
+
+**Tech Stack:** Flutter/Dart (Desktop), TypeScript and Vitest (backend).
+
+**Spec:** Task #4196 (anh Dee, 2026-11-07 06:10 VN, by River), and its addition: the Cmd-N task box starts at 3 rows and
+grows to 7.
+
+## Global Constraints
+
+- Change only the delta to the existing Cmd-N form; no redesign. Every picker (agent, model, computer, project: GitHub,
+ new, folder) stays as it is.
+- One new choice: Lead (names and starts a project) or Member. Member is the default.
+- The machine picker offers only the person's own machines: no shared or guest machine, no Team account.
+- Agents run on the person's own account and settings. No login read.
+- The separate New agent dialog is removed; its entry points (left pane, join) open Cmd-N.
+- The backend ships first; the contract is only extended. A backend without it says "Update Harness", never falls back.
+- Ships in Desktop 1.3.88 with #4191 and #4192.
+
+## Design
+
+- Growth: a Member's chat is one conversation per agent, as `agent.new` makes today; a chat whose start failed is
+ archived by Discard. Bounded by the existing 32 pending starts only for server starts; a local chat holds one agent.
+- Concurrency: the Swarm's existing per-tab command transaction; each step keeps its own operation id in the launch
+ journal, so a retry repeats the same command.
+- Read cost: no new reads; the journal and the existing snapshot reads of the New Project path.
+- Scale: one command per step, no fan-out. Warning metric: the new-agent timing log (time to a running agent).
+- Compatibility: backend first. An older backend refuses `local` as VALIDATION_ERROR and the form says to update
+ Harness. Older Desktops keep `agent.new` server starts, which stay.
+- Migration and rollback: none; reverting Desktop restores the old dialog; reverting backend refuses `local`.
+- Audience: the server checks that the chat is the actor's own and the machine and account are theirs.
+- Identity: the session runs under the person's own CLI login on their own machine; never another person's.
+- Failure: every step's refusal is shown in the form with Retry or Discard; Discard archives an empty Member chat or
+ deletes an empty project, as New Project does.
+- Platforms: macOS, Linux, Windows Desktop (shared code; no new process launch).
+
+## Review Focus
+
+- A retried Member create after a lost reply makes one chat and one agent, not two.
+- A Member start on a machine that is not the person's own is refused by the server, whatever the client sends.
+- A second session added to a Member chat is refused: one agent per chat.
+- Switching Lead and Member after a request went out cannot change what was created (the choice locks).
+- The form never offers a shared, guest or Team machine in this mode, also after the machine list changes.
+
+---
+
+### Task 1: The task box starts three rows tall
+
+**Files:**
+- Modify: `desktop/lib/widgets/new_harness_form.dart` (`_desktopTaskBox`, `minLines`)
+- Test: `desktop/test/desktop_composer_layout_test.dart`
+
+- [x] Write `the task opens three rows tall and grows to seven`: heights of 0, 1, 3, 4, 7 and 10 typed lines; empty
+ equals 1 and 3 lines, 4 is taller, 10 equals 7.
+- [x] Run it: FAIL (empty 19 px, three lines 57 px).
+- [x] `minLines: 3`, `maxLines: 7`.
+- [x] Run the form's tests: PASS. Capture light and dark with `COMPOSER_LAYOUT_RENDER_DIR`.
+
+### Task 2: Backend: a Member's chat for a session running on its own machine
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (`agent.new` schema and case; `agent.add` case)
+- Test: `backend/src/superTabs/agentNew.test.ts`
+
+**Interfaces:**
+- Produces: `agent.new {kind: 'regular', machineId, engine, name, local: true}` → `{conversationId}`, no start.
+- Produces: `agent.add {conversationId: <agent chat>, machineId, harnessId, name, configuration, initialMessage?}` →
+ `{agentId}`; the agent has `regular: true` and no project.
+
+- [x] Tests, failing first: local `agent.new` opens the chat and queues no start; it is refused with `kind: 'pm'`, on
+ another person's machine and for a viewer; `agent.add` into the chat adds a Regular agent once (same operation again
+ adds nothing), refuses a second session, another person's chat and another person's machine.
+- [x] Implement: `local: z.literal(true).optional()`; the local case skips the listed-machine and host-capability
+ checks (nothing starts there) and keeps the own-machine grant check. `agent.add` on an agent chat checks the chat's
+ audience is the actor, the grant is their own machine and account, the chat has no agent, and pushes the agent as a
+ started Regular agent is pushed.
+- [x] Run `agentNew.test.ts` and the tests of `commands.ts` callers it touches: PASS.
+
+### Task 3: The form's Lead or Member choice and own machines
+
+**Files:**
+- Modify: `desktop/lib/state/harness_launch_integration.dart` (fields), `desktop/lib/state/new_harness.dart`
+ (`machineChoices`, `agentKind`), `desktop/lib/widgets/new_harness_form.dart` (`_desktopHeader`)
+- Test: `desktop/test/new_harness_agent_kind_test.dart`
+
+**Interfaces:**
+- Produces: `HarnessLaunchIntegration.agentKind` (`'lead' | 'member' | null`; null shows no choice),
+ `agentKindLocked`, `ownMachinesOnly`; `NewHarnessController.setAgentKind(String kind)`.
+
+- [x] Tests, failing first: with an integration whose `agentKind` is `member`, the header shows a `Member` capsule
+ after the project capsule; its menu offers Lead and Member and choosing Lead changes `integration.agentKind`; the
+ computer menu lists this computer and a remote own machine, not a shared, guest or Team one; without an integration
+ the header is unchanged. Light and dark pictures.
+- [x] Implement the capsule as the computer capsule is built (`DesktopPill` in an `AppDropdown`), locked with
+ `box.locked || agentKindLocked`.
+- [x] Run the test and the form's existing tests: PASS.
+
+### Task 4: New agent through Cmd-N, Lead or Member
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/launch.dart` (`SuperTabLaunch.open` `newAgent`, `prepare`, `complete`, `discard`)
+- Test: `desktop/test/super_tab_new_agent_launch_test.dart`
+
+**Interfaces:**
+- Consumes: Task 2's commands; Task 3's fields.
+- Produces: `SuperTabLaunch.open(app, tab, 'new-agent', newAgent: true)`.
+
+- [x] Tests, failing first, with recorded Swarm requests and a fake local create: Member sends `agent.new` with
+ `local: true`, then creates locally with a prompt naming the returned chat, then `agent.add` into it, then selects
+ the chat; Lead sends `project.create`, creates locally, then `agent.add` as lead and `project.rename`; a lost
+ `agent.add` reply retried sends the same operation id; reopened after a failed start it keeps its chat; Discard of a
+ start that never ran archives its chat; the choice locks once the first command is sent.
+- [x] Implement; the journal keeps `agentKind` beside the New Project keys.
+- [x] Run the test and `super_tab` launch tests: PASS.
+
+### Task 5: + New agent and join open Cmd-N; the old dialog goes
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/view.dart`, `desktop/lib/super_tabs/workspace.dart`,
+ `desktop/lib/screens/swarm_screen.dart` (`onNewAgent` → `_newAgent(swarmNewAgent: true)`),
+ `desktop/lib/super_tabs/join_dialog.dart`
+- Delete: `desktop/lib/super_tabs/join/new_agent_dialog.dart`, `agent_dialog.dart`; `agent_launcher.dart` unless the
+ join's Buddy still needs it; their tests.
+- Test: `desktop/test/swarm_v3_agent_entry_test.dart`
+
+- [x] Tests, failing first: the left pane's + New agent opens the Cmd-N form with the Member capsule; after a join,
+ the same form opens for the person's own agent; no `SwarmAgentDialog` exists.
+- [x] Implement. Join keeps its Buddy (River, 11-07: the Buddy starts as today; only its form is Cmd-N's).
+- [x] Run the entry, join and sidebar tests: PASS.
+
+### Task 6: Evidence
+
+- [x] Before: server starts in this Swarm (118 on record, 2026-11-07): dispatch p50 18 s, p95 233 s; engine session
+ p50 23 s, p95 91 s, max 375 s; plus the old dialog's waits before it (engine probe, machine preparation, contribute).
+- [x] After: local creates on this Mac (the Cmd-N path), from the daemon's receipts: p50 0.4 s; plus two Swarm commands. The timing log line measures the whole start once released.
+- [x] Light and dark pictures of the form with the choice; the 3-row task box.