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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(desktop): preserve Swarms app v2 preview and development handoff
deecd877653f795
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex 821843191..fd409e35c 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -19,6 +19,7 @@*/import { stat } from 'node:fs/promises'+import { agentProject, type AgentProject } from './agentProject.js'import type { GridAssignment } from './gridAssignment.js'import { projectDisplayName, type RegisteredSession } from './registry.js'@@ -43,6 +44,7 @@ export type AgentFrame = {selectedModel: string | nullgrid: GridAssignment | nullcodexHome: string | null+ project: AgentProject | null}/** What the caller knows and this module deliberately does not look up for itself. */@@ -87,5 +89,6 @@ export async function agentFrame(// engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason// `grid: null` is above.codexHome: s.codexHome ?? null,+ project: await agentProject(s.cwd),}}diff --git a/cli/src/lib/agentProject.spec.ts b/cli/src/lib/agentProject.spec.tsnew file mode 100644index 000000000..a6ff3f558--- /dev/null+++ b/cli/src/lib/agentProject.spec.ts@@ -0,0 +1,36 @@+import { execFileSync } from 'node:child_process'+import { mkdtemp, mkdir, rm, realpath } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { agentProject, canonicalRepository } from './agentProject.js'++const roots: string[] = []+afterEach(async () => { await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))) })+describe('owning-machine project metadata', () => {+ it('canonicalizes transports and strips credentials and URL tokens', () => {+ expect(canonicalRepository('[email protected]:Org/App.git')).toBe('github.com/org/app')+ expect(canonicalRepository('https://user:[email protected]/Org/App.git?token=secret')).toBe('github.com/org/app')+ expect(canonicalRepository('/private/checkouts/app')).toBeNull()+ expect(canonicalRepository('file:///private/checkouts/app')).toBeNull()+ expect(canonicalRepository('ssh://[email protected]/CaseSensitive.git')).toBe('example.com/CaseSensitive')+ })+ it('reads the current checkout and branch, including branch changes after cache expiry', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-v2-project-')); roots.push(root)+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: 'pipe' })+ git('init', '-b', 'main')+ git('remote', 'add', 'origin', '[email protected]:Org/App.git')+ await mkdir(join(root, 'nested'))+ const cwd = join(root, 'nested')+ expect(await agentProject(cwd, 100)).toMatchObject({ cwd, root: await realpath(root), remote: 'github.com/org/app', branch: 'main' })+ git('symbolic-ref', 'HEAD', 'refs/heads/feature/real-branch')+ expect(await agentProject(cwd, 20_000)).toMatchObject({ branch: 'feature/real-branch' })+ })+ it('keeps a non-repository project branchless and rejects absent cwd', async () => {+ const root = await mkdtemp(join(tmpdir(), 'harness-v2-folder-')); roots.push(root)+ expect(await agentProject(root)).toMatchObject({ cwd: root, root: null, remote: null, branch: null })+ expect(await agentProject(null)).toBeNull()+ expect(await agentProject('relative')).toBeNull()+ expect(await agentProject('/tmp/unsafe\n')).toBeNull()+ })+})diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.tsnew file mode 100644index 000000000..fbc0f0b1b--- /dev/null+++ b/cli/src/lib/agentProject.ts@@ -0,0 +1,68 @@+import { execFile } from 'node:child_process'+import { basename, isAbsolute } from 'node:path'+import { promisify } from 'node:util'++const exec = promisify(execFile)+export type AgentProject = {+ name: string+ cwd: string+ root: string | null+ remote: string | null+ branch: string | null+}++/** Compare remote repositories without publishing embedded credentials or transport syntax. */+export function canonicalRepository(raw: string | null): string | null {+ if (!raw) return null+ const scp = /^(?:[^@/\s]+@)?([^:/\s]+):([^\s]+)$/.exec(raw)+ try {+ const url = new URL(scp && !raw.includes('://') ? `ssh://${scp[1]}/${scp[2]}` : raw)+ if (!['ssh:', 'https:', 'http:', 'git:'].includes(url.protocol) || !url.hostname) return null+ let path = url.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')+ if (!path || /[\x00-\x20]/.test(path)) return null+ const host = url.hostname.toLowerCase()+ if (host === 'github.com' || host === 'bitbucket.org') path = path.toLowerCase()+ return `${host}${url.port ? `:${url.port}` : ''}/${path}`+ } catch { return null }+}++/** Bounded subprocesses, no shell, network, or repository mutation. */+async function git(cwd: string, args: string[]): Promise<string | null> {+ try {+ const { stdout } = await exec('git', ['-C', cwd, ...args], {+ timeout: 1500, maxBuffer: 16 * 1024, encoding: 'utf8',+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },+ })+ return stdout.trim() || null+ } catch { return null }+}++// Agent list and push frames share this cache. Only four folders run Git at once.+const cache = new Map<string, { at: number; value: Promise<AgentProject> }>()+let running = 0+const waiting: Array<() => void> = []+async function inspect(cwd: string): Promise<AgentProject> {+ if (running >= 4) await new Promise<void>(resolve => waiting.push(resolve))+ else running+++ try {+ const root = await git(cwd, ['rev-parse', '--show-toplevel'])+ if (!root) return { name: basename(cwd) || cwd, cwd, root: null, remote: null, branch: null }+ const remote = await git(cwd, ['config', '--get', 'remote.origin.url'])+ const branch = await git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD'])+ return { name: basename(root), cwd, root, remote: canonicalRepository(remote), branch }+ } finally {+ const next = waiting.shift()+ if (next) next()+ else running--+ }+}++export function agentProject(cwd: string | null, now = Date.now()): Promise<AgentProject | null> {+ if (!cwd || !isAbsolute(cwd) || cwd.length > 4096 || /[\x00-\x1f\x7f]/.test(cwd)) return Promise.resolve(null)+ const found = cache.get(cwd)+ if (found && now - found.at < 15_000) return found.value+ if (cache.size >= 256) cache.delete(cache.keys().next().value!)+ const value = inspect(cwd)+ cache.set(cwd, { at: now, value })+ return value+}diff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-abstract.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-abstract.jpgnew file mode 100644index 000000000..0c86f7a2fBinary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-abstract.jpg differdiff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-ai.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-ai.jpgnew file mode 100644index 000000000..ff251b0c8Binary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-ai.jpg differdiff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-ant-colony.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-ant-colony.jpgnew file mode 100644index 000000000..6683b21e7Binary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-ant-colony.jpg differdiff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-associative-memory.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-associative-memory.jpgnew file mode 100644index 000000000..dd3f520e4Binary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-associative-memory.jpg differdiff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-dusk.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-dusk.jpgnew file mode 100644index 000000000..35e6edf1bBinary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-dusk.jpg differdiff --git a/desktop/assets/swarm-wallpapers/swarm-welcome-robots.jpg b/desktop/assets/swarm-wallpapers/swarm-welcome-robots.jpgnew file mode 100644index 000000000..6e7874852Binary files /dev/null and b/desktop/assets/swarm-wallpapers/swarm-welcome-robots.jpg differdiff --git a/desktop/lib/analytics/analytics_config.dart b/desktop/lib/analytics/analytics_config.dartindex 6fb530efe..84187c6c9 100644--- a/desktop/lib/analytics/analytics_config.dart+++ b/desktop/lib/analytics/analytics_config.dart@@ -56,7 +56,7 @@ class AnalyticsConfig {/// Stamped on every event, so this app's stream stays separable from Grid's/// and the website's inside the shared project. Grid sends `grid-app`.- static const String category = 'harness-desktop';+ static const String category = 'harness-desktop-v2';/// Env var / `--dart-define` names. The URL and key overrides are dev-only so/// a shipped build always reports to production; [disableEnvKey] is honoureddiff --git a/desktop/lib/bootstrap/environment_provisioner.dart b/desktop/lib/bootstrap/environment_provisioner.dartindex d980f35fa..9dda63396 100644--- a/desktop/lib/bootstrap/environment_provisioner.dart+++ b/desktop/lib/bootstrap/environment_provisioner.dart@@ -1372,7 +1372,7 @@ fi''';List<String> linuxPackages = const [],}) async {final directory = Directory(- '${harnessHome.path}/desktop-app/setup-runs/${DateTime.now().millisecondsSinceEpoch}',+ '${harnessHome.path}/desktop-app-v2/setup-runs/${DateTime.now().millisecondsSinceEpoch}',);await directory.create(recursive: true);await _run('/bin/chmod', ['700', directory.path]);diff --git a/desktop/lib/core/build_identity.dart b/desktop/lib/core/build_identity.dartnew file mode 100644index 000000000..796c48a1f--- /dev/null+++ b/desktop/lib/core/build_identity.dart@@ -0,0 +1,3 @@+/// This checkout builds the separate V2 review app. CLI identity stays shared.+const isHarnessV2 = true;+const desktopAppName = 'Harness V2';diff --git a/desktop/lib/core/crash_log.dart b/desktop/lib/core/crash_log.dartindex 672b76bdc..6a132e394 100644--- a/desktop/lib/core/crash_log.dart+++ b/desktop/lib/core/crash_log.dart@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';import '../logging/app_log.dart';import 'harness_file_store.dart';+import 'test_run.dart';/// Where a released build writes the errors nobody would otherwise see.///@@ -18,7 +19,11 @@ import 'harness_file_store.dart';class CrashLog {static const _maxBytes = 256 * 1024;+ @visibleForTesting+ static File? testFile;+static File get _file =>+ testFile ??File('${HarnessFileStore.defaultDirectoryPath()}/errors.log');static void record(Object error, StackTrace? stackTrace, {String? context}) {@@ -36,6 +41,7 @@ class CrashLog {error: error,stackTrace: stackTrace,);+ if (kUnderTest && testFile == null) return;try {final file = _file;// The directory may not exist yet, and the first run is exactly when thisdiff --git a/desktop/lib/core/desktop_window.dart b/desktop/lib/core/desktop_window.dartindex e28c403b5..debbd34d4 100644--- a/desktop/lib/core/desktop_window.dart+++ b/desktop/lib/core/desktop_window.dart@@ -2,6 +2,9 @@ import 'dart:io' show Platform;import 'dart:ui' show Size;import 'package:window_manager/window_manager.dart';+import 'package:flutter/services.dart';++import 'build_identity.dart';/// Puts the window into the same shape Grid's uses, before the first frame.///@@ -18,13 +21,14 @@ Future<void> configureDesktopWindow() async {final options = WindowOptions(size: const Size(1280, 800),minimumSize: const Size(880, 560),- title: 'Harness',+ title: desktopAppName,center: true,- titleBarStyle: Platform.isMacOS- ? TitleBarStyle.hidden- : TitleBarStyle.normal,+ titleBarStyle: TitleBarStyle.normal,);await windowManager.waitUntilReadyToShow(options, () async {+ if (Platform.isMacOS) {+ await const MethodChannel('harness/swarm_tabs').invokeMethod('configure');+ }await windowManager.show();await windowManager.focus();});diff --git a/desktop/lib/core/harness_file_store.dart b/desktop/lib/core/harness_file_store.dartindex 550a08fc8..c5bd7ffc5 100644--- a/desktop/lib/core/harness_file_store.dart+++ b/desktop/lib/core/harness_file_store.dart@@ -11,9 +11,8 @@ import 'local_key_value_store.dart';/// POSIX platforms. Values are never logged.class HarnessFileStore implements LocalKeyValueStore {static const schemaVersion = 1;- // Keep this legacy namespace stable across the product rename so existing- // credentials and E2EE pairing state remain available after upgrading.- static const directoryName = 'desktop-app';+ // Separate from production; the CLI still owns shared authentication and links.+ static const directoryName = 'desktop-app-v2';static const fileName = 'state.json';static const lockFileName = 'state.lock';diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex f91e1aa16..4136aed2a 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -124,6 +124,7 @@ class Agent {final String? engineIconHint;final String? codexHome;final String? parentAgentId;+ final AgentProject? project;final String status;final String launchState;final String? launchError;@@ -140,6 +141,7 @@ class Agent {this.engineIconHint,this.codexHome,this.parentAgentId,+ this.project,this.status = 'active',this.launchState = 'ready',this.launchError,@@ -181,6 +183,7 @@ class Agent {engineIconHint: _safeLabel(j['engineIconHint']),codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),+ project: AgentProject.fromJson(j['project']),status: (j['status'] as String?) ?? 'active',launchState: launchState,launchError: launchState == 'failed' ? _safeLabel(launch['error']) : null,@@ -204,6 +207,7 @@ class Agent {engineIconHint: engineIconHint,codexHome: codexHome,parentAgentId: parentAgentId,+ project: project,status: status,launchState: launchState,launchError: launchError,@@ -365,3 +369,52 @@ class RouteCandidate {}String _str(Object? value) => value is String ? value : '';++/// Context reported by the owning daemon. Missing on older daemons.+class AgentProject {+ const AgentProject({+ required this.name,+ required this.cwd,+ this.root,+ this.remote,+ this.branch,+ });+ final String name;+ final String cwd;+ final String? root;+ final String? remote;+ final String? branch;++ String identity(String machineId) =>+ remote != null ? 'repo:$remote' : 'folder:$machineId:${root ?? cwd}';++ @override+ bool operator ==(Object other) => other is AgentProject && name == other.name &&+ cwd == other.cwd && root == other.root && remote == other.remote && branch == other.branch;+ @override+ int get hashCode => Object.hash(name, cwd, root, remote, branch);++ static AgentProject? fromJson(Object? raw) {+ if (raw is! Map) return null;+ String? field(String key, [int max = 4096]) {+ final v = raw[key];+ return v is String &&+ v.isNotEmpty &&+ v.length <= max &&+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(v)+ ? v+ : null;+ }++ final name = field('name', 256);+ final cwd = field('cwd');+ if (name == null || cwd == null) return null;+ return AgentProject(+ name: name,+ cwd: cwd,+ root: field('root'),+ remote: field('remote'),+ branch: field('branch', 256),+ );+ }+}diff --git a/desktop/lib/main.dart b/desktop/lib/main.dartindex 35f581b3e..928f85240 100644--- a/desktop/lib/main.dart+++ b/desktop/lib/main.dart@@ -7,7 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';import 'analytics/analytics_lifecycle.dart';import 'core/crash_log.dart';import 'core/desktop_window.dart';-import 'screens/home_screen.dart';+import 'screens/swarm_screen.dart';import 'screens/login_screen.dart';import 'state/app_state.dart';import 'shared/theme/app_theme.dart' as grid;@@ -76,7 +76,8 @@ class DesktopApp extends StatelessWidget {codeSize: grid.AppFont.codeSize,);return MaterialApp(- title: 'Harness',+ title: 'Harness V2',+ debugShowCheckedModeBanner: false,// The design system's own `buildAppTheme` — see the note where a second,// hand-written `ThemeData` used to shadow it, in `lib/theme/app_theme.dart`.// Harness Desktop is dark-only: one theme, no `darkTheme`/`themeMode` to@@ -216,7 +217,7 @@ class _RootShellState extends ConsumerState<RootShell> {case AppStatus.unauthenticated:screen = LoginScreen(notifier: app);case AppStatus.authenticated:- screen = HomeScreen(notifier: app);+ screen = SwarmScreen(notifier: app);}// Only the home shell carries its own drag handle and traffic-light// clearance (the rail's head). Every other screen fills the windowdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartnew file mode 100644index 000000000..27a41d6df--- /dev/null+++ b/desktop/lib/screens/swarm_screen.dart@@ -0,0 +1,686 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io' show Platform;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../core/desktop_window.dart';+import '../core/harness_file_store.dart';+import '../core/test_run.dart';+import '../settings/settings_screen.dart';+import '../settings/settings_section.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_dialog.dart';+import '../shortcuts/app_shortcuts.dart';+import '../state/app_state.dart';+import '../state/swarm_catalog.dart';+import '../widgets/engine_identity.dart';+import '../widgets/layout_palette.dart';+import '../widgets/link_machine_screen.dart';+import '../widgets/new_agent_dialog.dart';+import '../widgets/pane_grid.dart';+import '../widgets/shortcuts_sheet.dart';+import '../widgets/swarm_dialogs.dart';+import '../widgets/swarm_welcome.dart';+import '../widgets/task_palette.dart';++class SwarmScreen extends StatefulWidget {+ const SwarmScreen({+ super.key,+ required this.notifier,+ this.nativeTabs,+ this.projectStore,+ });+ final AppNotifier notifier;+ final bool? nativeTabs;+ final SwarmProjectStore? projectStore;+ @override+ State<SwarmScreen> createState() => _SwarmScreenState();+}++class _SwarmScreenState extends State<SwarmScreen> {+ static const _channel = MethodChannel('harness/swarm_tabs');+ late final bool _native =+ widget.nativeTabs ?? (Platform.isMacOS && !kUnderTest);+ late final SwarmProjectStore _projects =+ widget.projectStore ??+ SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);+ StreamSubscription<SpokenTaskRequest>? _spokenTasks;+ bool _spokenPaletteOpen = false;+ bool _dialogOpen = false;+ String? _linkDialogMachineId;+ String? _nativeState;+ AppNotifier get app => widget.notifier;++ @override+ void initState() {+ super.initState();+ app.hasNavigationRail = false;+ app.railFocused = false;+ unawaited(_projects.load());+ _spokenTasks = app.spokenTasks.listen(_openSpokenTask);+ if (_native) {+ _channel.setMethodCallHandler(_onNative);+ app.addListener(_syncNative);+ _syncNative();+ }+ }++ @override+ void dispose() {+ unawaited(_spokenTasks?.cancel());+ if (_native) {+ app.removeListener(_syncNative);+ _channel.setMethodCallHandler(null);+ unawaited(+ _channel.invokeMethod<void>('update', {'tabs': [], 'enabled': false}),+ );+ }+ if (widget.projectStore == null) _projects.dispose();+ super.dispose();+ }++ int get _attention =>+ app.machineStates.values.fold(0, (n, m) => n + m.blockedAgents.length);+ void _syncNative() {+ final payload = {+ 'enabled': true,+ 'activeId': app.activeSwarmId,+ 'attention': _attention,+ 'tabs': [+ for (final swarm in app.swarms)+ {+ 'id': swarm.id,+ 'name': swarm.name,+ 'attention': swarm.panes+ .where(+ (p) =>+ p.agentId != null &&+ app.questionFor(p.machineId, p.agentId!) != null,+ )+ .length,+ },+ ],+ };+ final encoded = jsonEncode(payload);+ if (encoded == _nativeState) return;+ _nativeState = encoded;+ unawaited(_channel.invokeMethod<void>('update', payload));+ }++ Future<void> _onNative(MethodCall call) async {+ if (!mounted) return;+ final args = call.arguments is Map ? call.arguments as Map : const {};+ switch (call.method) {+ case 'new':+ app.newSwarm();+ case 'select':+ if (args['id'] is String) app.selectSwarm(args['id']);+ case 'close':+ if (args['id'] is String) await app.closeSwarm(args['id']);+ case 'closeActive':+ await app.closeSwarm(app.activeSwarmId);+ case 'rename':+ if (args['id'] is String) await _rename(args['id']);+ case 'renameActive':+ await _rename(app.activeSwarmId);+ case 'next':+ app.stepSwarm(1);+ case 'previous':+ app.stepSwarm(-1);+ case 'reorder':+ if (args['id'] is String && args['index'] is int)+ app.reorderSwarm(args['id'], args['index']);+ case 'addAgent':+ await _addAgent();+ case 'closePane':+ if (app.focusedPaneId != null) await app.closePane(app.focusedPaneId!);+ case 'notifications':+ await _notifications();+ case 'settings':+ await _settings();+ }+ }++ Future<void> _dialog(Future<void> Function() action) async {+ if (_dialogOpen || !mounted) return;+ _dialogOpen = true;+ try {+ await action();+ } finally {+ _dialogOpen = false;+ }+ }++ Future<void> _rename(String id) => _dialog(() async {+ final swarm = app.swarms.where((s) => s.id == id).firstOrNull;+ if (swarm == null) return;+ final name = await showSwarmRenameDialog(context, swarm.name);+ if (name != null) app.renameSwarm(id, name);+ });+ Future<void> _settings() =>+ _dialog(() => showSettingsScreen(context, app, source: 'swarm'));+ Future<void> _newAgent({+ String? machineId,+ String? folder,+ String? swarmId,+ }) => _dialog(() async {+ final local = app.machineStates.values+ .where((m) => m.isLocalMachine)+ .firstOrNull;+ final id =+ machineId ??+ local?.machine.machineId ??+ app.machineStates.keys.firstOrNull;+ if (id == null) {+ await showSwarmLinkDialog(context, app);+ return;+ }+ await showNewAgentDialog(+ context,+ app,+ id,+ source: 'swarm',+ initialFolder: folder,+ swarmId: swarmId,+ );+ });+ Future<void> _addAgent() async {+ final target = app.activeSwarmId;+ bool create = false;+ SwarmAgentRef? selected;+ await _dialog(() async {+ selected = await showSwarmAgentPicker(context, app, () => create = true);+ });+ if (!mounted) return;+ if (create) {+ await _newAgent(swarmId: target);+ } else if (selected != null) {+ await app.addAgentToSwarm(+ selected!.machineId,+ selected!.agent.id,+ swarmId: target,+ );+ }+ }++ Future<void> _addProject() => _dialog(() async {+ final project = await showSwarmProjectDialog(context, app);+ if (project != null) await _projects.add(project);+ });+ Future<void> _machine(MachineState machine) async {+ if (machine.needsLink) {+ await _dialog(+ () => showLinkMachineScreenDialog(+ context,+ app,+ machine.machine.machineId,+ ),+ );+ return;+ }+ if (machine.agents.isEmpty) {+ if (machine.nodeOnline == false) {+ await _dialog(() => showSwarmLinkDialog(context, app));+ } else {+ await _newAgent(machineId: machine.machine.machineId);+ }+ return;+ }+ await app.seedSwarm(machine.machine.displayName, [+ for (final a in machine.agents)+ (machineId: machine.machine.machineId, agentId: a.id),+ ]);+ }++ Future<void> _project(SwarmProjectGroup group) async {+ if (group.agents.isEmpty) {+ final saved = group.saved;+ await _newAgent(machineId: saved?.machineId, folder: saved?.path);+ } else {+ await app.seedSwarm(group.name, [+ for (final a in group.agents)+ (machineId: a.machineId, agentId: a.agent.id),+ ]);+ }+ }++ Future<void> _goToAgent(String machineId, String agentId) async {+ if (app.paneOfAgent(machineId, agentId) == null) {+ final owner = app.swarms+ .where(+ (s) => s.panes.any(+ (p) => p.machineId == machineId && p.agentId == agentId,+ ),+ )+ .firstOrNull;+ if (owner != null) app.selectSwarm(owner.id);+ }+ await app.selectAgent(machineId, agentId);+ }++ Future<void> _notifications() => _dialog(() async {+ final selected = await showAppDialog<({String machineId, String agentId})>(+ context: context,+ builder: (context) => Dialog(+ child: SizedBox(+ width: 520,+ height: 400,+ child: Padding(+ padding: const EdgeInsets.all(22),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ const Text('Notifications', style: TextStyle(fontSize: 20)),+ const Spacer(),+ IconButton(+ tooltip: 'Close notifications',+ onPressed: () => Navigator.pop(context),+ icon: const Icon(Icons.close, size: 18),+ ),+ ],+ ),+ const SizedBox(height: 14),+ Expanded(+ child: ListenableBuilder(+ listenable: app,+ builder: (context, _) {+ final questions =+ app.machineStates.values+ .expand((m) => m.blockedAgents.values)+ .toList()+ ..sort((a, b) => a.since.compareTo(b.since));+ if (questions.isEmpty)+ return const Center(+ child: Text(+ 'No agents need your input',+ style: TextStyle(color: Colors.white60),+ ),+ );+ return ListView(+ children: [+ for (final q in questions)+ ListTile(+ leading: EngineMark(+ engine: app+ .stateOf(q.machineId)+ ?.agents+ .where((a) => a.id == q.agentId)+ .firstOrNull+ ?.engine,+ size: 22,+ ),+ title: Text(+ q.prompt,+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 13),+ ),+ subtitle: Text(+ '${app.stateOf(q.machineId)?.agents.where((a) => a.id == q.agentId).firstOrNull?.name ?? q.agentId} · ${app.stateOf(q.machineId)?.machine.displayName ?? q.machineId}',+ style: const TextStyle(+ fontSize: 11,+ color: Colors.white54,+ ),+ ),+ onTap: () => Navigator.pop(context, (+ machineId: q.machineId,+ agentId: q.agentId,+ )),+ ),+ ],+ );+ },+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ if (selected != null)+ await _goToAgent(selected.machineId, selected.agentId);+ });++ Future<void> _openSpokenTask(SpokenTaskRequest request) async {+ final spoken = SpokenTask(+ voiceId: request.voiceId,+ text: request.text,+ cmd: request.cmd,+ report: (voiceId, state, agentId) =>+ app.reportVoiceRoute(request.machineId, voiceId, state, agentId),+ );+ if (_spokenPaletteOpen || _dialogOpen || !mounted) {+ spoken.cancelled();+ return;+ }+ _spokenPaletteOpen = true;+ try {+ await revealWindow();+ if (!mounted) {+ spoken.cancelled();+ return;+ }+ await showTaskPalette(context, app, spoken: spoken);+ } finally {+ _spokenPaletteOpen = false;+ spoken.cancelled();+ }+ }++ void _maybeLink() {+ final machine = app.stateOf(app.selectedMachineId ?? '');+ if (machine == null ||+ !machine.needsLink ||+ machine.isLocalMachine ||+ _dialogOpen ||+ app.isLinkPromptDismissed(machine.machine.machineId) ||+ _linkDialogMachineId != null)+ return;+ _linkDialogMachineId = machine.machine.machineId;+ WidgetsBinding.instance.addPostFrameCallback((_) async {+ if (mounted)+ await _dialog(+ () => showLinkMachineScreenDialog(+ context,+ app,+ machine.machine.machineId,+ ),+ );+ _linkDialogMachineId = null;+ });+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: Listenable.merge([app, _projects]),+ builder: (context, _) {+ grid.AppTheme.watch(context);+ _maybeLink();+ return CallbackShortcuts(+ bindings: {+ ...buildShortcutBindings(+ handlers: {+ ShortcutAction.focusPaneLeft: () => app.focusPaneHorizontally(-1),+ ShortcutAction.focusPaneRight: () => app.focusPaneHorizontally(1),+ ShortcutAction.focusPaneAbove: () => app.focusPaneVertically(-1),+ ShortcutAction.focusPaneBelow: () => app.focusPaneVertically(1),+ ShortcutAction.movePaneLeft: () =>+ app.movePaneDirection(dx: -1, dy: 0),+ ShortcutAction.movePaneRight: () =>+ app.movePaneDirection(dx: 1, dy: 0),+ ShortcutAction.movePaneUp: () =>+ app.movePaneDirection(dx: 0, dy: -1),+ ShortcutAction.movePaneDown: () =>+ app.movePaneDirection(dx: 0, dy: 1),+ ShortcutAction.nextAgent: () => app.focusPaneBy(1),+ ShortcutAction.previousAgent: () => app.focusPaneBy(-1),+ ShortcutAction.lastPane: app.focusLastPane,+ ShortcutAction.zoomPane: app.toggleZoomPane,+ ShortcutAction.switchAgent: _addAgent,+ ShortcutAction.closePane: () {+ if (app.focusedPaneId != null)+ app.closePane(app.focusedPaneId!);+ },+ ShortcutAction.newAgent: _newAgent,+ ShortcutAction.routeTask: () =>+ _dialog(() => showTaskPalette(context, app)),+ ShortcutAction.reload: app.retryMachines,+ ShortcutAction.showLayout: () =>+ _dialog(() => showLayoutPalette(context, app)),+ ShortcutAction.pinPane: () {+ if (app.focusedPaneId != null)+ app.togglePinPane(app.focusedPaneId!);+ },+ ShortcutAction.showShortcuts: () =>+ _dialog(() => showShortcutsSheet(context)),+ ShortcutAction.showDebug: () => _dialog(+ () => showSettingsScreen(+ context,+ app,+ source: 'shortcut',+ initialSection: SettingsSection.debug,+ ),+ ),+ },+ onSelectPaneIndex: app.focusPaneByIndex,+ ),+ const SingleActivator(LogicalKeyboardKey.keyT, meta: true):+ app.newSwarm,+ const SingleActivator(LogicalKeyboardKey.keyW, meta: true): () =>+ app.closeSwarm(app.activeSwarmId),+ const SingleActivator(+ LogicalKeyboardKey.keyF,+ meta: true,+ shift: true,+ ): _addAgent,+ const SingleActivator(+ LogicalKeyboardKey.keyR,+ meta: true,+ shift: true,+ ): () =>+ _rename(app.activeSwarmId),+ const SingleActivator(+ LogicalKeyboardKey.bracketRight,+ meta: true,+ shift: true,+ ): () =>+ app.stepSwarm(1),+ const SingleActivator(+ LogicalKeyboardKey.bracketLeft,+ meta: true,+ shift: true,+ ): () =>+ app.stepSwarm(-1),+ const SingleActivator(LogicalKeyboardKey.tab, control: true): () =>+ app.stepSwarm(1),+ const SingleActivator(+ LogicalKeyboardKey.tab,+ control: true,+ shift: true,+ ): () =>+ app.stepSwarm(-1),+ const SingleActivator(LogicalKeyboardKey.comma, meta: true):+ _settings,+ },+ child: Focus(+ autofocus: true,+ child: Scaffold(+ backgroundColor: grid.AppPalette.swarmField,+ body: Column(+ children: [+ if (!_native) _tabStrip(),+ if (app.lastError != null)+ Material(+ color: grid.AppPalette.panelBg,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Row(+ children: [+ const Icon(+ Icons.info_outline,+ size: 16,+ color: Colors.orangeAccent,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(+ app.lastError!,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 12),+ ),+ ),+ if (app.lastErrorRetryable)+ TextButton(+ onPressed: app.retryMachines,+ child: const Text('Retry'),+ ),+ IconButton(+ onPressed: app.dismissError,+ tooltip: 'Dismiss',+ icon: const Icon(Icons.close, size: 16),+ ),+ ],+ ),+ ),+ ),+ Expanded(+ child: Padding(+ padding: const EdgeInsets.all(10),+ child: Stack(+ children: [+ Positioned.fill(+ child: PaneGrid(+ notifier: app,+ swarmMode: true,+ empty: SwarmWelcome(+ key: ValueKey(app.activeSwarmId),+ notifier: app,+ projects: _projects.projects,+ onNewAgent: _newAgent,+ onAddProject: _addProject,+ onLinkMachine: () => _dialog(+ () => showSwarmLinkDialog(context, app),+ ),+ onMachine: _machine,+ onProject: _project,+ onAgent: (entry) => app.addAgentToSwarm(+ entry.machineId,+ entry.agent.id,+ ),+ ),+ ),+ ),+ if (app.panes.isNotEmpty)+ Positioned(+ right: 10,+ bottom: 10,+ child: Material(+ color: grid.AppPalette.swarmTabBar,+ elevation: 6,+ borderRadius: BorderRadius.circular(8),+ child: IconButton(+ tooltip: 'Add agent (⌘⇧F)',+ onPressed: _addAgent,+ constraints: const BoxConstraints.tightFor(+ width: 34,+ height: 34,+ ),+ padding: EdgeInsets.zero,+ icon: Icon(+ Icons.add,+ size: 21,+ color: grid.AppPalette.swarmAccent,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ },+ );++ Widget _tabStrip() => Container(+ height: 44,+ color: grid.AppPalette.swarmTabBar,+ child: Row(+ children: [+ const SizedBox(width: 10),+ Flexible(+ child: ReorderableListView.builder(+ scrollDirection: Axis.horizontal,+ shrinkWrap: true,+ buildDefaultDragHandles: false,+ itemCount: app.swarms.length,+ onReorder: (old, to) =>+ app.reorderSwarm(app.swarms[old].id, to > old ? to - 1 : to),+ itemBuilder: (context, index) {+ final swarm = app.swarms[index];+ return ReorderableDragStartListener(+ key: ValueKey(swarm.id),+ index: index,+ child: GestureDetector(+ onDoubleTap: () => _rename(swarm.id),+ child: Container(+ width: 186,+ margin: const EdgeInsets.only(top: 6, right: 2),+ decoration: BoxDecoration(+ color: app.activeSwarmId == swarm.id+ ? grid.AppPalette.swarmField+ : Colors.transparent,+ borderRadius: const BorderRadius.vertical(+ top: Radius.circular(9),+ ),+ ),+ child: Row(+ children: [+ Expanded(+ child: TextButton(+ onPressed: () => app.selectSwarm(swarm.id),+ child: Text(+ swarm.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 12),+ ),+ ),+ ),+ IconButton(+ tooltip: 'Close ${swarm.name}',+ onPressed: () => app.closeSwarm(swarm.id),+ icon: const Icon(Icons.close, size: 13),+ constraints: const BoxConstraints.tightFor(+ width: 30,+ height: 30,+ ),+ padding: EdgeInsets.zero,+ ),+ ],+ ),+ ),+ ),+ );+ },+ ),+ ),+ IconButton(+ tooltip: 'New swarm (⌘T)',+ onPressed: app.swarms.length < AppNotifier.maxSwarms+ ? app.newSwarm+ : null,+ icon: const Icon(Icons.add, size: 18),+ ),+ const Spacer(),+ IconButton(+ tooltip: _attention == 0+ ? 'Notifications'+ : '$_attention agents need input',+ onPressed: _notifications,+ icon: Badge(+ isLabelVisible: _attention > 0,+ label: Text('$_attention'),+ child: const Icon(Icons.notifications_none, size: 19),+ ),+ ),+ IconButton(+ tooltip: 'Settings',+ onPressed: _settings,+ icon: const Icon(Icons.settings_outlined, size: 18),+ ),+ const SizedBox(width: 6),+ ],+ ),+ );+}diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dartindex 4423a5601..46264a038 100644--- a/desktop/lib/shared/theme/app_theme.dart+++ b/desktop/lib/shared/theme/app_theme.dart@@ -176,6 +176,11 @@ class _FontScope extends InheritedNotifier<FontNotifier> {/// Centralized so every pane reads the same surfaces/accents instead of re-typing/// hex literals, and resolves per [AppTheme.brightness].abstract final class AppPalette {+ // Approved Swarms canvas and native tab-strip palette.+ static Color get swarmField => const Color(0xff463746);+ static Color get swarmTabBar => const Color(0xff332936);+ static Color get swarmAccent => const Color(0xffd8cce1);+// the conversation / content area — pure white in light, like Codex.//// Dark is a charcoal page rather than the near-black it was (#0A0A0A). Thatdiff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 407778db4..818e7037c 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -13,6 +13,7 @@ import '../auth/cli_link.dart';import '../auth/cli_login.dart';import '../bootstrap/environment_provisioner.dart';import '../core/config.dart';+import '../core/build_identity.dart';import '../core/engine_availability.dart';import '../core/local_hostname.dart';import '../core/models.dart';@@ -26,6 +27,7 @@ import '../core/harness_file_store.dart';import 'dial_status.dart';import 'pane_layout_store.dart';import 'terminal_pane.dart';+import 'swarm.dart';import '../terminal/terminal_binary.dart';import '../update/desktop_updater.dart';import '../update/manual_update_check.dart';@@ -330,8 +332,129 @@ class AppNotifier extends ChangeNotifier {final Set<String> expandedMachines = {};String? selectedMachineId;- /// The grid, in reading order. At most [maxPanes].- final List<TerminalPane> panes = [];+ /// Swarms own arrangements; a shared pane owns one live terminal controller.+ final List<Swarm> swarms = [Swarm(id: 'swarm-1')];+ String _activeSwarmId = 'swarm-1';+ int _nextSwarmId = 2;+ int _nextWallpaper = 1;+ static const maxSwarms = 24;+ Swarm get activeSwarm => swarms.firstWhere(+ (s) => s.id == _activeSwarmId,+ orElse: () => swarms.first,+ );+ List<TerminalPane> get panes => activeSwarm.panes;+ Iterable<TerminalPane> get allPanes => swarms.expand((s) => s.panes).toSet();+ String get activeSwarmId => activeSwarm.id;++ void newSwarm({String name = 'New swarm'}) {+ if (swarms.length >= maxSwarms) return;+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ final swarm = Swarm(+ id: 'swarm-${_nextSwarmId++}',+ name: name,+ wallpaper: _nextWallpaper++ % swarmWallpapers.length,+ );+ swarms.add(swarm);+ selectSwarm(swarm.id);+ }++ void selectSwarm(String id) {+ if (!swarms.any((s) => s.id == id)) return;+ _activeSwarmId = id;+ railFocused = false;+ final pane = focusedPane;+ selectedMachineId = pane?.machineId;+ _persistLayout();+ _announceFocusToDial();+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ notifyListeners();+ }++ void stepSwarm(int delta) {+ final index = swarms.indexOf(activeSwarm);+ selectSwarm(swarms[(index + delta) % swarms.length].id);+ }++ void renameSwarm(String id, String name) {+ final clean = name.trim();+ if (clean.isEmpty) return;+ final swarm = swarms.where((s) => s.id == id).firstOrNull;+ if (swarm == null) return;+ swarm.name = clean.length > 80 ? clean.substring(0, 80) : clean;+ _persistLayout();+ notifyListeners();+ }++ void reorderSwarm(String id, int destination) {+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ final swarm = swarms.removeAt(index);+ swarms.insert(destination.clamp(0, swarms.length), swarm);+ _persistLayout();+ notifyListeners();+ }++ void nextSwarmWallpaper() {+ activeSwarm.wallpaper =+ (activeSwarm.wallpaper + 1) % swarmWallpapers.length;+ _persistLayout();+ notifyListeners();+ }++ Future<void> closeSwarm(String id) async {+ final index = swarms.indexWhere((s) => s.id == id);+ if (index < 0) return;+ final removed = swarms.removeAt(index);+ if (swarms.isEmpty) {+ swarms.add(+ Swarm(+ id: 'swarm-${_nextSwarmId++}',+ wallpaper: _nextWallpaper++ % swarmWallpapers.length,+ ),+ );+ }+ if (_activeSwarmId == id) {+ _activeSwarmId = swarms[index.clamp(0, swarms.length - 1)].id;+ }+ _persistLayout();+ notifyListeners();+ selectedMachineId = focusedPane?.machineId;+ _announceFocusToDial();+ for (final machine in machineStates.values) {+ _attachPendingPanes(machine);+ }+ for (final pane in removed.panes) {+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);+ }+ }++ /// Capture the destination before any network wait or tab change.+ Future<void> addAgentToSwarm(+ String machineId,+ String agentId, {+ String? swarmId,+ }) => assignAgentToPane(null, machineId, agentId, swarmId: swarmId);++ Future<void> seedSwarm(+ String name,+ List<({String machineId, String agentId})> agents,+ ) async {+ final target = activeSwarm;+ renameSwarm(target.id, name);+ // Each call records membership synchronously, before its attachment waits.+ // A slow/offline host must not hold back the other panes or retarget a tab.+ final attachments = <Future<void>>[];+ for (final agent in agents) {+ attachments.add(+ addAgentToSwarm(agent.machineId, agent.agentId, swarmId: target.id),+ );+ }+ await Future.wait(attachments);+ }/// Which tile the keyboard, the dial and the rail's highlight all mean.///@@ -340,10 +463,11 @@ class AppNotifier extends ChangeNotifier {/// AppKit routes keys there without asking. This is for everything that has/// no pointer behind it: the dial's scroll and focus frames, and which agent/// the rail draws as current.- int? focusedPaneId;+ int? get focusedPaneId => activeSwarm.focusedPaneId;+ set focusedPaneId(int? value) => activeSwarm.focusedPaneId = value;/// The chosen shape for a grid of this size, or the shipped one.- final Map<int, PanePreset> panePresets = {};+ Map<int, PanePreset> get panePresets => activeSwarm.presets;PanePreset? presetFor(int paneCount) =>panePresets[paneCount] ?? PanePreset.defaultFor(paneCount);@@ -360,12 +484,12 @@ class AppNotifier extends ChangeNotifier {if (presetFor(paneCount) == preset) return;panePresets[paneCount] = preset;notifyListeners();- unawaited(_paneLayout?.savePresets(panePresets));+ _persistLayout();}int _nextPaneId = 1;- static const maxPanes = PaneLayoutStore.maxPanes;+ static const maxPanes = 64;// Set only while `harness login --force --json` is waiting for the user to finish SSO in their system// browser. It arrives PART WAY THROUGH the flow — the CLI has to start before it can hand one// over — so it says "the browser is open", not "a sign-in is running". Use [signingIn] for the@@ -402,7 +526,7 @@ class AppNotifier extends ChangeNotifier {// layout is remembered: with a layout store there is a state file, and// without one (the tests) nothing is written anywhere.dial = DialState(- paneLayoutStore == null ? null : HarnessFileStore.shared,+ paneLayoutStore?.storage,),session = authSession,_store = configStore,@@ -470,7 +594,7 @@ class AppNotifier extends ChangeNotifier {bool get canAddPane => panes.length < maxPanes;Iterable<TerminalPane> panesFor(String machineId) =>- panes.where((pane) => pane.machineId == machineId);+ allPanes.where((pane) => pane.machineId == machineId);TerminalPane? paneOfAgent(String machineId, String agentId) {for (final pane in panes) {@@ -636,13 +760,16 @@ class AppNotifier extends ChangeNotifier {void focusPane(int paneId) {if (!panes.any((pane) => pane.id == paneId)) return;- final moved = focusedPaneId != paneId;+ final moved = focusedPaneId != paneId || railFocused;+ railFocused = false;// Remembered only on a REAL move. Re-focusing the tile you are already on// happens constantly — see the note below about why it is announced anyway// — and recording it would make ⌘; a key that returns you to where you// already are, which is the same as a key that does nothing.if (moved) _previousPaneId = focusedPaneId;focusedPaneId = paneId;+ selectedMachineId = focusedPane?.machineId;+ if (zoomedPaneId != null) zoomedPaneId = paneId;// Announced even when this tile was ALREADY focused.//// The dial can be turned by hand, and then the two disagree with nobody@@ -661,7 +788,10 @@ class AppNotifier extends ChangeNotifier {// only side that can judge, because only it knows where the dial is._announceFocusToDial();// Only a real move is worth a rebuild.- if (moved) notifyListeners();+ if (moved) {+ _persistLayout();+ notifyListeners();+ }}/// Tell the local daemon which agent this window is looking at, so the dial follows it.@@ -1420,6 +1550,7 @@ class AppNotifier extends ChangeNotifier {}void _startUpdateChecking() {+ if (isHarnessV2 && desktopUpdater == null) return;_updateCheckTimer ??= (desktopUpdater ?? DesktopUpdater()).startChecking(onUpdateAvailable: _handleBackgroundUpdate,);@@ -1437,6 +1568,7 @@ class AppNotifier extends ChangeNotifier {/// A manual check deliberately returns a skipped version too, so the user/// can choose to install it from the account menu after changing their mind.Future<ManualUpdateCheck> checkForUpdates() async {+ if (isHarnessV2 && desktopUpdater == null) return const ManualUpdateCheck();if (isCheckingForUpdate) {return ManualUpdateCheck(update: availableUpdate);}@@ -1920,6 +2052,10 @@ class AppNotifier extends ChangeNotifier {prev.engineIconHint != agent.engineIconHint ||prev.codexHome != agent.codexHome ||prev.parentAgentId != agent.parentAgentId ||+ prev.project != agent.project ||+ prev.launchState != agent.launchState ||+ prev.launchError != agent.launchError ||+ prev.launchDetail != agent.launchDetail ||prev.status != agent.status ||prev.terminalAvailable != agent.terminalAvailable ||prev.terminalUnavailableReason != agent.terminalUnavailableReason) {@@ -2364,29 +2500,10 @@ class AppNotifier extends ChangeNotifier {/// load and guarded, rather than wired to one specific load, because which/// machine answers first is not something this side decides.void _autoPickFirstAgent() {- if (_autoPickedAgent || panes.isNotEmpty) return;-- // This computer first. A remote machine may well answer sooner, and- // opening a terminal on someone else's box because its list arrived first- // is a surprise, not a convenience.- MachineState? target;- for (final state in machineStates.values) {- if (state.isLocalMachine) {- target = state;- break;- }- }- target ??= machineStates.length == 1 ? machineStates.values.first : null;- if (target == null) return;- if (target.nodeOnline == false) return;- if (!target.terminalCapabilityAvailable) return;-- for (final agent in target.agents) {- if (!agent.terminalAvailable) continue;- _autoPickedAgent = true;- unawaited(selectAgent(target.machine.machineId, agent.id));- return;- }+ if (_autoPickedAgent) return;+ // V2 opens on the welcome screen; discovering an agent is not a request+ // to attach its terminal. Keep the startup gate settled for this run.+ _autoPickedAgent = true;}/// Ask a machine which engines it has.@@ -2569,12 +2686,11 @@ class AppNotifier extends ChangeNotifier {// `terminal_close`, which would be addressed to an agent the machine has// already destroyed.final machineId = machine.machine.machineId;- for (final pane in panes.toList()) {+ for (final pane in allPanes.toList()) {if (pane.machineId != machineId || pane.agentId != agentId) continue;await _detachSession(pane, sendClose: false);- panes.remove(pane);- if (focusedPaneId == pane.id) {- focusedPaneId = panes.isEmpty ? null : panes.first.id;+ for (final swarm in swarms) {+ swarm.remove(pane);}}_persistLayout();@@ -2791,35 +2907,53 @@ class AppNotifier extends ChangeNotifier {String? revision,}) async {final machine = machineStates[machineId];- if (machine == null || machine.needsLink || machine.nodeOnline == false ||+ if (machine == null ||+ machine.needsLink ||+ machine.nodeOnline == false ||machine.connectionStatus != ConnectionStatus.connected) {- throw const RemoteMediaException('This machine is disconnected. Reconnect and try opening the preview again.');+ throw const RemoteMediaException(+ 'This machine is disconnected. Reconnect and try opening the preview again.',+ );}if (!machine.mediaPreviewAvailable) {- throw const RemoteMediaException('Update the Harness CLI on this remote machine to open image and video previews.');+ throw const RemoteMediaException(+ 'Update the Harness CLI on this remote machine to open image and video previews.',+ );}final connection = _conn(machineId);if (!connection.isReady) {- throw const RemoteMediaException('This machine is disconnected. Reconnect and try opening the preview again.');+ throw const RemoteMediaException(+ 'This machine is disconnected. Reconnect and try opening the preview again.',+ );}try {- return await connection.request('agent_read_file', payload: {- 'agentId': agentId, 'path': target, 'media': true, 'offset': offset,- 'revision': ?revision,- }, timeout: const Duration(seconds: 15));+ return await connection.request(+ 'agent_read_file',+ payload: {+ 'agentId': agentId,+ 'path': target,+ 'media': true,+ 'offset': offset,+ 'revision': ?revision,+ },+ timeout: const Duration(seconds: 15),+ );} on WsRequestFailure catch (error) {throw RemoteMediaException(switch (error.code) {'MEDIA_NOT_FOUND' || 'NOT_FOUND' => 'This file is no longer available on the remote machine. It may have moved or been deleted.','MEDIA_TOO_LARGE' => 'Remote previews support files up to 512 MB. Use a smaller export or transfer this file separately.','MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.','MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',- 'MEDIA_INVALID_REQUEST' => 'Use a full path or a path inside this agent’s working folder.',+ 'MEDIA_INVALID_REQUEST' =>+ 'Use a full path or a path inside this agent’s working folder.','AGENT_NOT_FOUND' => 'This agent is no longer available. Reconnect to the agent and try again.','NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',_ => 'The remote machine could not read this file. Check that it is accessible and try again.',});} catch (_) {- throw const RemoteMediaException('The media download was interrupted. Check the connection and try again.');+ throw const RemoteMediaException(+ 'The media download was interrupted. Check the connection and try again.',+ );}}@@ -2889,7 +3023,13 @@ class AppNotifier extends ChangeNotifier {required String folder,bool bypassPermission = false,String? codexHome,+ String? swarmId,}) async {+ final targetId = swarmId ?? activeSwarmId;+ if (!swarms.any((s) => s.id == targetId)) return 'This swarm was closed';+ final target = swarms.firstWhere((s) => s.id == targetId);+ if (target.panes.length >= maxPanes)+ return 'This swarm is full. Open a new swarm to create an agent.';final machine = machineStates[machineId];if (machine == null) return 'Machine not found';if (codexHome != null) {@@ -2935,7 +3075,7 @@ class AppNotifier extends ChangeNotifier {// count of what this app launched.harnessStats.onAgentSpawned();notifyListeners();- await selectAgent(machineId, agent.id);+ await addAgentToSwarm(machineId, agent.id, swarmId: targetId);return null;}@@ -2973,8 +3113,12 @@ class AppNotifier extends ChangeNotifier {// Any tile still showing this machine would otherwise sit forever in the "waiting to answer"// busy state, since the machine can never be found again after this.for (final pane in panesFor(machineId).toList()) {- await closePane(pane.id, persist: false);+ for (final swarm in swarms) {+ swarm.remove(pane);+ }+ await _detachSession(pane, sendClose: true);}+ _persistLayout();_stopAgentSyncTimer(machineId);machineStates.remove(machineId);machines.removeWhere((m) => m.machineId == machineId);@@ -3255,7 +3399,7 @@ class AppNotifier extends ChangeNotifier {}return;}- await assignAgentToPane(focusedPane?.id, machineId, agentId);+ await addAgentToSwarm(machineId, agentId);}/// Show a MACHINE in the grid, for the states that belong to the machine@@ -3295,19 +3439,7 @@ class AppNotifier extends ChangeNotifier {notifyListeners();return;}- if (!canAddPane) {- // Full grid: reuse the focused tile rather than refusing. Someone who- // clicked "link required" asked to see it, and a click that did nothing- // at all would read as a broken row.- if (target != null) {- unawaited(_detachSession(target, sendClose: true));- target.machineId = machineId;- target.agentId = null;- _persistLayout();- notifyListeners();- }- return;- }+ if (!canAddPane) return;final pane = TerminalPane(id: _nextPaneId++, machineId: machineId);panes.add(pane);focusedPaneId = pane.id;@@ -3319,8 +3451,14 @@ class AppNotifier extends ChangeNotifier {Future<void> assignAgentToPane(int? paneId,String machineId,- String agentId,- ) async {+ String agentId, {+ String? swarmId,+ }) async {+ final target = swarms+ .where((s) => s.id == (swarmId ?? activeSwarmId))+ .firstOrNull;+ if (target == null || _disposed) return;+ final targetPanes = target.panes;final machine = machineStates[machineId];if (machine == null) return;@@ -3331,41 +3469,49 @@ class AppNotifier extends ChangeNotifier {break;}}- if (agent == null || !agent.terminalAvailable) return;+ if (agent == null) return;- // Moving an agent that is already somewhere else must not leave a copy- // behind, for the takeover reason above. Dropping a row onto a second tile- // is a MOVE.- final duplicate = paneOfAgent(machineId, agentId);- if (duplicate != null && duplicate.id != paneId) {- await closePane(duplicate.id, persist: false);+ final shared = allPanes+ .where((p) => p.machineId == machineId && p.agentId == agentId)+ .firstOrNull;+ final existing = targetPanes+ .where((p) => p.machineId == machineId && p.agentId == agentId)+ .firstOrNull;+ if (paneId == null && existing != null) {+ if (target == activeSwarm) focusPane(existing.id);+ return;}-- TerminalPane? pane;- if (paneId != null) {- for (final candidate in panes) {- if (candidate.id == paneId) {- pane = candidate;- break;- }- }+ final replaced = targetPanes.where((p) => p.id == paneId).firstOrNull;+ if (replaced == shared && shared != null) {+ if (target == activeSwarm) focusPane(shared.id);+ return;}- if (pane == null) {- if (!canAddPane) return;- pane = TerminalPane(- id: _nextPaneId++,- machineId: machineId,- agentId: agentId,- );- panes.add(pane);- } else {- await _detachSession(pane, sendClose: true);- pane.machineId = machineId;- pane.agentId = agentId;+ if (replaced == null &&+ existing == null &&+ targetPanes.length >= maxPanes) {+ _lastError =+ 'This swarm holds $maxPanes agents. Open another swarm to add more.';+ _lastErrorRetryable = false;+ notifyListeners();+ return;}-- focusedPaneId = pane.id;- selectedMachineId = machineId;+ final insertion = replaced == null+ ? targetPanes.length+ : targetPanes.indexOf(replaced);+ if (existing != null) target.remove(existing);+ if (replaced != null) target.remove(replaced);+ final pane =+ shared ??+ TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: agentId);+ targetPanes.insert(insertion.clamp(0, targetPanes.length), pane);+ if (replaced != null && !allPanes.contains(replaced)) {+ // Release just the desktop stream. The CLI agent process keeps running.+ unawaited(_detachSession(replaced, sendClose: true));+ }++ target.focusedPaneId = pane.id;+ target.zoomedPaneId = null;+ if (target == activeSwarm) selectedMachineId = machineId;_dismissedLinkPrompts.remove(machineId);machine.activeAgentId = agentId;_persistLayout();@@ -3382,7 +3528,7 @@ class AppNotifier extends ChangeNotifier {// After _persistLayout, so the daemon has the new tile roster before it is told to move onto it. A// duplicate with the inferred one is free: the daemon drops the second against where the dial// already is.- _announceFocusToDial();+ if (target == activeSwarm) _announceFocusToDial();if (machine.nodeOnline == false) {machine.pendingOfflineAgentId = agentId;@@ -3394,7 +3540,7 @@ class AppNotifier extends ChangeNotifier {machine.pendingOfflineAgentId = null;_stopOfflineRetry(machineId);notifyListeners();- await _attachSession(pane);+ if (target == activeSwarm || pane.session != null) await _attachSession(pane);}/// Open the stream for a tile that already knows what it wants.@@ -3403,7 +3549,7 @@ class AppNotifier extends ChangeNotifier {/// on its own, later, when its machine finally answers — the intent was/// settled at launch, and nothing about the selection should move again then.Future<void> _attachSession(TerminalPane pane) async {- if (pane.session != null) return;+ if (_disposed || !allPanes.contains(pane) || pane.session != null) return;final wantedAgentId = pane.agentId;if (wantedAgentId == null) return;final machine = machineStates[pane.machineId];@@ -3484,8 +3630,8 @@ class AppNotifier extends ChangeNotifier {// saying "here now", and a pinned tile displaced by another drag was still// put there deliberately — bouncing either back would make the drag look// broken while the state was in fact correct.- if (panes[to].isPinned) panes[to].pinnedSlot = to;- if (panes[from].isPinned) panes[from].pinnedSlot = from;+ if (isPanePinned(panes[to])) _setPin(panes[to], to);+ if (isPanePinned(panes[from])) _setPin(panes[from], from);_persistLayout();notifyListeners();}@@ -3495,7 +3641,10 @@ class AppNotifier extends ChangeNotifier {/// Only `auto` needs telling: it measures the window, so it is the one shape/// whose columns are not in its own description. Reported by the grid as it/// builds; null until then, and then the shape's own guess stands.- int? gridColumns;+ int? get gridColumns => activeSwarm.gridColumns;+ set gridColumns(int? value) => activeSwarm.gridColumns = value;++ bool hasNavigationRail = true;/// Focus the tile above or below the focused one — ⌘↑ / ⌘↓.///@@ -3579,7 +3728,7 @@ class AppNotifier extends ChangeNotifier {focusPane(panes[to].id);return;}- focusRail();+ if (hasNavigationRail) focusRail();// An EMPTY rail is not a seat, so the ring skips it rather than stopping on// it. focusRail refuses when there is nothing to put a cursor on — no// machines yet, or a list that has not loaded — and without this the key@@ -3656,7 +3805,8 @@ class AppNotifier extends ChangeNotifier {/// agents at a time is the shape most work actually has: a thing being built/// and a thing being watched. Walking a list to get back to the other one is/// the wrong motion, and it gets longer as the grid fills.- int? _previousPaneId;+ int? get _previousPaneId => activeSwarm.previousPaneId;+ set _previousPaneId(int? value) => activeSwarm.previousPaneId = value;void focusLastPane() {final back = _previousPaneId;@@ -3676,12 +3826,14 @@ class AppNotifier extends ChangeNotifier {/// usually breaks this: focus moving. Zoomed on tile 3 and then jumping to/// tile 5 shows tile 5 zoomed, which is what tmux does and what the eye/// expects; a boolean would have shown tile 3 while the focus was elsewhere.- int? zoomedPaneId;+ int? get zoomedPaneId => activeSwarm.zoomedPaneId;+ set zoomedPaneId(int? value) => activeSwarm.zoomedPaneId = value;void toggleZoomPane() {final id = focusedPaneId;if (id == null || panes.length < 2) return;zoomedPaneId = zoomedPaneId == id ? null : id;+ _persistLayout();notifyListeners();}@@ -3728,11 +3880,25 @@ class AppNotifier extends ChangeNotifier {/// Pinning records the CURRENT slot rather than asking for one: the tile the/// user is looking at is the answer they mean, and a dialog asking "which/// number?" would be arithmetic about a thing they can already see.+ int? pinnedSlotFor(TerminalPane pane) =>+ hasNavigationRail ? pane.pinnedSlot : activeSwarm.pinnedSlots[pane.id];++ bool isPanePinned(TerminalPane pane) => pinnedSlotFor(pane) != null;++ void _setPin(TerminalPane pane, int? slot) {+ if (slot == null) {+ activeSwarm.pinnedSlots.remove(pane.id);+ } else {+ activeSwarm.pinnedSlots[pane.id] = slot;+ }+ if (hasNavigationRail) pane.pinnedSlot = slot;+ }+void togglePinPane(int paneId) {final index = panes.indexWhere((pane) => pane.id == paneId);if (index == -1) return;final pane = panes[index];- pane.pinnedSlot = pane.isPinned ? null : index;+ _setPin(pane, isPanePinned(pane) ? null : index);_persistLayout();notifyListeners();}@@ -3749,10 +3915,10 @@ class AppNotifier extends ChangeNotifier {/// closed can come back, and forgetting the pin the moment the grid got small/// would quietly undo a choice the user never revisited.void _settlePins() {- final pinned = panes.where((pane) => pane.isPinned).toList()- ..sort((a, b) => a.pinnedSlot!.compareTo(b.pinnedSlot!));+ final pinned = panes.where(isPanePinned).toList()+ ..sort((a, b) => pinnedSlotFor(a)!.compareTo(pinnedSlotFor(b)!));for (final pane in pinned) {- final want = pane.pinnedSlot!;+ final want = pinnedSlotFor(pane)!;if (want >= panes.length) continue;final at = panes.indexOf(pane);if (at == want) continue;@@ -3762,58 +3928,36 @@ class AppNotifier extends ChangeNotifier {}Future<void> closePane(int paneId, {bool persist = true}) async {- final index = panes.indexWhere((pane) => pane.id == paneId);- if (index == -1) return;- final pane = panes.removeAt(index);- // A zoom belongs to a tile, so closing that tile ends it. Left set, the grid- // would try to fill itself with a pane that is no longer in the list and- // draw nothing at all.- if (zoomedPaneId == paneId) zoomedPaneId = null;- if (_previousPaneId == paneId) _previousPaneId = null;+ final pane = panes.where((p) => p.id == paneId).firstOrNull;+ if (pane == null) return;+ activeSwarm.remove(pane);_settlePins();- await _detachSession(pane, sendClose: true);- if (focusedPaneId == paneId) {- focusedPaneId = panes.isEmpty- ? null- : panes[index.clamp(0, panes.length - 1)].id;- }if (persist) _persistLayout();+ selectedMachineId = focusedPane?.machineId;+ _announceFocusToDial();notifyListeners();+ if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);}Future<void> _closeAllPanes({bool persist = true}) async {- final open = panes.toList();- panes.clear();- focusedPaneId = null;+ final open = allPanes.toList();+ for (final swarm in swarms) {+ swarm.panes.clear();+ swarm.focusedPaneId = null;+ swarm.zoomedPaneId = null;+ }for (final pane in open) {await _detachSession(pane, sendClose: true);}if (persist) _persistLayout();}+ int _layoutRevision = 0;+void _persistLayout() {- // The roster and the saved layout describe the same fact — which agents are- // on the grid — so they are announced and written from the same place.- // Before the early return below: a window with no layout store still has- // tiles, and the dial still has to know about them.+ _layoutRevision++;_announceOpenPanesToDial();- final store = _paneLayout;- if (store == null) return;- unawaited(- store.save([- for (final pane in panes)- // Machine tiles are deliberately not remembered: they are a prompt- // about a machine's state right now ("link required"), and reopening- // to a wall of prompts the user already answered would be noise.- if (pane.agentId case final agentId?)- PaneLayoutEntry(- machineId: pane.machineId,- agentId: agentId,- composerVisible: pane.composerVisible,- pinnedSlot: pane.pinnedSlot,- ),- ]),- );+ unawaited(_paneLayout?.saveSwarms(swarms, activeSwarmId, _nextWallpaper));}/// Rebuild the grid from disk as INTENT only — the tiles appear immediately,@@ -3826,11 +3970,102 @@ class AppNotifier extends ChangeNotifier {Future<void> _restorePaneLayout() async {final store = _paneLayout;if (store == null) return;+ final initialSwarm = activeSwarm;+ final revision = _layoutRevision;+ final saved = await store.loadSwarms();+ if (_disposed || revision != _layoutRevision) return;+ if (saved != null &&+ allPanes.isEmpty &&+ swarms.length == 1 &&+ activeSwarm == initialSwarm) {+ final restored = <Swarm>[];+ final pool = <String, TerminalPane>{};+ for (final raw in (saved['swarms'] as List).take(maxSwarms)) {+ if (raw is! Map || raw['id'] is! String || raw['panes'] is! List)+ continue;+ final id = raw['id'] as String;+ if (id.isEmpty || restored.any((s) => s.id == id)) continue;+ final swarm = Swarm(+ id: id,+ name:+ raw['name'] is String && (raw['name'] as String).trim().isNotEmpty+ ? (raw['name'] as String).substring(+ 0,+ (raw['name'] as String).length.clamp(0, 80),+ )+ : 'New swarm',+ wallpaper: raw['wallpaper'] is int+ ? (raw['wallpaper'] as int) % swarmWallpapers.length+ : 0,+ );+ for (final item in (raw['panes'] as List).take(maxPanes)) {+ final entry = PaneLayoutEntry.fromJson(item);+ if (entry == null) continue;+ final key = '${entry.machineId}\u0000${entry.agentId}';+ final pane = pool.putIfAbsent(+ key,+ () =>+ TerminalPane(+ id: _nextPaneId++,+ machineId: entry.machineId,+ agentId: entry.agentId,+ )+ ..composerVisible = entry.composerVisible+ ..pinnedSlot = entry.pinnedSlot,+ );+ if (!swarm.panes.contains(pane)) {+ swarm.panes.add(pane);+ if (entry.pinnedSlot != null) swarm.pinnedSlots[pane.id] = entry.pinnedSlot!;+ }+ }+ int? paneAt(Object? index) =>+ index is int && index >= 0 && index < swarm.panes.length+ ? swarm.panes[index].id+ : null;+ swarm.focusedPaneId =+ paneAt(raw['focus']) ?? swarm.panes.firstOrNull?.id;+ swarm.zoomedPaneId = paneAt(raw['zoom']);+ if (raw['presets'] case final Map presets) {+ for (final e in presets.entries) {+ final count = int.tryParse(e.key.toString());+ final preset = PanePreset.byId(e.value?.toString());+ if (count != null &&+ count >= 2 &&+ count <= maxPanes &&+ preset != null &&+ PanePreset.forCount(count).contains(preset)) {+ swarm.presets[count] = preset;+ }+ }+ }+ restored.add(swarm);+ }+ if (restored.isNotEmpty) {+ swarms+ ..clear()+ ..addAll(restored);+ _activeSwarmId = restored.any((s) => s.id == saved['activeId'])+ ? saved['activeId'] as String+ : restored.first.id;+ while (swarms.any((s) => s.id == 'swarm-$_nextSwarmId')) {+ _nextSwarmId++;+ }+ _nextWallpaper = saved['nextWallpaper'] is int+ ? saved['nextWallpaper'] as int+ : swarms.length;+ _autoPickedAgent = true;+ notifyListeners();+ return;+ }+ }// Read before the guards below: the dividers are remembered even for a// grid this run has not restored any agents into, so a window that opens// empty and is then filled by hand still comes up the shape it was left.panePresets.addAll(await store.loadPresets());- if (panes.isNotEmpty) return;+ if (allPanes.isNotEmpty ||+ swarms.length != 1 ||+ activeSwarm != initialSwarm)+ return;final entries = await store.load();if (entries.isEmpty) {if (panePresets.isNotEmpty) notifyListeners();@@ -3867,7 +4102,8 @@ class AppNotifier extends ChangeNotifier {/// to re-arrive at them.void _attachPendingPanes(MachineState machine) {final machineId = machine.machine.machineId;- for (final pane in panes.toList()) {+ for (final pane in allPanes.toList()) {+ if (!panes.contains(pane) && pane.session == null) continue;if (pane.machineId != machineId) continue;if (!_paneNeedsAttach(pane)) continue;// Covers a tile that never attached AND one holding a stream the machine@@ -4193,6 +4429,9 @@ class AppNotifier extends ChangeNotifier {/// The frames worth testing here have no terminal to route through and no/// socket to arrive on — what they exercise is the bookkeeping either side of/// that, which is exactly what a live socket makes hard to reach.+ @visibleForTesting+ Future<void> restorePaneLayoutForTest() => _restorePaneLayout();+@visibleForTestingFuture<void> handleMachineEventForTest(String machineId,@@ -4240,11 +4479,13 @@ class AppNotifier extends ChangeNotifier {_stopAllLinkRetries();_stopAllAgentSyncTimers();_clearAllTurnActivity();- for (final pane in panes) {+ for (final pane in allPanes) {pane.session?.removeListener(notifyListeners);pane.session?.dispose();}- panes.clear();+ for (final swarm in swarms) {+ swarm.panes.clear();+ }unawaited(_spokenTasks.close());super.dispose();}diff --git a/desktop/lib/state/pane_layout_store.dart b/desktop/lib/state/pane_layout_store.dartindex 8ca31b6de..3bb17b53b 100644--- a/desktop/lib/state/pane_layout_store.dart+++ b/desktop/lib/state/pane_layout_store.dart@@ -4,6 +4,7 @@ import '../core/harness_file_store.dart';import '../core/local_key_value_store.dart';import 'pane_preset.dart';import 'terminal_pane.dart';+import 'swarm.dart';/// Remembers which agents were on screen, so reopening the app returns to the/// desk it was left on rather than to whatever happens to load first.@@ -42,6 +43,7 @@ class PaneLayoutStore {static const maxPanes = 9;final LocalKeyValueStore _storage;+ LocalKeyValueStore get storage => _storage;/// Failure is silent and lands on an empty layout, which is exactly the/// first-run state. A corrupt state file is a reason to open the app the way@@ -115,6 +117,41 @@ class PaneLayoutStore {}}+ Future<Map<String, dynamic>?> loadSwarms() async {+ try {+ final value = await _storage.read('swarm_layout_v1');+ if (value == null) return null;+ final decoded = jsonDecode(value);+ if (decoded is! Map<String, dynamic> ||+ decoded['version'] != 1 ||+ decoded['swarms'] is! List)+ return null;+ return decoded;+ } catch (_) {+ return null;+ }+ }++ Future<void> saveSwarms(+ List<Swarm> swarms,+ String activeId,+ int nextWallpaper,+ ) async {+ try {+ await _storage.write(+ 'swarm_layout_v1',+ jsonEncode({+ 'version': 1,+ 'activeId': activeId,+ 'nextWallpaper': nextWallpaper,+ 'swarms': swarms.map((s) => s.toJson()).toList(),+ }),+ );+ } catch (_) {+ // Keep the current desk usable when storage is unavailable.+ }+ }+Future<void> save(List<PaneLayoutEntry> entries) async {try {final capped = entries.take(maxPanes).map((e) => e.toJson()).toList();diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartnew file mode 100644index 000000000..25f423101--- /dev/null+++ b/desktop/lib/state/swarm.dart@@ -0,0 +1,68 @@+import 'pane_preset.dart';+import 'terminal_pane.dart';++/// A named arrangement of agents. Membership never owns the agent process.+/// Shared agents reuse the same pane/session across swarms, so the daemon has+/// exactly one controller and switching tabs cannot take over our own stream.+class Swarm {+ Swarm({required this.id, this.name = 'New swarm', this.wallpaper = 0});++ final String id;+ String name;+ int wallpaper;+ final List<TerminalPane> panes = [];+ final Map<int, PanePreset> presets = {};+ int? focusedPaneId;+ int? zoomedPaneId;+ int? previousPaneId;+ int? gridColumns;+ final Map<int, int> pinnedSlots = {};++ void remove(TerminalPane pane) {+ final index = panes.indexOf(pane);+ if (index < 0) return;+ panes.removeAt(index);+ pinnedSlots.remove(pane.id);+ if (focusedPaneId == pane.id) {+ focusedPaneId = panes.isEmpty+ ? null+ : panes[index.clamp(0, panes.length - 1)].id;+ }+ if (zoomedPaneId == pane.id) zoomedPaneId = null;+ if (previousPaneId == pane.id) previousPaneId = null;+ }++ Map<String, Object?> toJson() => {+ 'id': id,+ 'name': name,+ 'wallpaper': wallpaper,+ 'focus': panes+ .where((p) => p.agentId != null)+ .toList()+ .indexWhere((p) => p.id == focusedPaneId),+ 'zoom': panes+ .where((p) => p.agentId != null)+ .toList()+ .indexWhere((p) => p.id == zoomedPaneId),+ 'presets': {for (final e in presets.entries) '${e.key}': e.value.id},+ 'panes': [+ for (final p in panes)+ if (p.agentId != null)+ PaneLayoutEntry(+ machineId: p.machineId,+ agentId: p.agentId!,+ composerVisible: p.composerVisible,+ pinnedSlot: pinnedSlots[p.id],+ ).toJson(),+ ],+ };+}++const swarmWallpapers = [+ 'dusk',+ 'abstract',+ 'ai',+ 'robots',+ 'ant-colony',+ 'associative-memory',+];diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dartnew file mode 100644index 000000000..998b2486e--- /dev/null+++ b/desktop/lib/state/swarm_catalog.dart@@ -0,0 +1,142 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';+import '../core/models.dart';+import 'app_state.dart';++class SwarmAgentRef {+ const SwarmAgentRef(this.machine, this.agent);+ final MachineState machine;+ final Agent agent;+ String get machineId => machine.machine.machineId;+ String get searchText => [+ agent.name,+ agent.engine,+ machine.machine.displayName,+ agent.project?.name,+ agent.project?.branch,+ agent.project?.cwd,+ ].whereType<String>().join(' ').toLowerCase();+}++List<SwarmAgentRef> swarmAgents(AppNotifier app, [String query = '']) {+ final terms = query+ .trim()+ .toLowerCase()+ .split(RegExp(r'\s+'))+ .where((t) => t.isNotEmpty);+ return [+ for (final machine in app.machineStates.values)+ for (final agent in machine.agents) SwarmAgentRef(machine, agent),+ ].where((entry) => terms.every(entry.searchText.contains)).toList();+}++class SavedSwarmProject {+ const SavedSwarmProject({+ required this.machineId,+ required this.path,+ required this.name,+ });+ final String machineId;+ final String path;+ final String name;+ String get id => '$machineId\u0000$path';+ Map<String, String> toJson() => {+ 'machineId': machineId,+ 'path': path,+ 'name': name,+ };+}++class SwarmProjectGroup {+ SwarmProjectGroup({required this.id, required this.name, this.saved});+ final String id;+ final String name;+ SavedSwarmProject? saved;+ final List<SwarmAgentRef> agents = [];+}++/// Repositories group across machines only when the owning CLI reports the same+/// canonical remote. Same-named folders/branches never establish that identity.+List<SwarmProjectGroup> swarmProjects(+ AppNotifier app,+ List<SavedSwarmProject> saved,+) {+ final groups = <String, SwarmProjectGroup>{};+ final folders = <String, String>{};+ for (final entry in swarmAgents(app)) {+ final project = entry.agent.project;+ if (project == null) continue;+ final id = project.identity(entry.machineId);+ final group = groups.putIfAbsent(+ id,+ () => SwarmProjectGroup(id: id, name: project.name),+ );+ group.agents.add(entry);+ folders['${entry.machineId}\u0000${project.cwd}'] = id;+ if (project.root != null)+ folders['${entry.machineId}\u0000${project.root}'] = id;+ }+ for (final item in saved) {+ final id = folders[item.id] ?? 'folder:${item.machineId}:${item.path}';+ groups+ .putIfAbsent(id, () => SwarmProjectGroup(id: id, name: item.name))+ .saved =+ item;+ }+ return groups.values.toList()+ ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));+}++class SwarmProjectStore extends ChangeNotifier {+ SwarmProjectStore({this.storage});+ final LocalKeyValueStore? storage;+ final List<SavedSwarmProject> projects = [];+ bool _disposed = false;+ Future<void> load() async {+ try {+ final raw = await storage?.read('swarm_projects_v1');+ if (raw == null || _disposed) return;+ final rows = jsonDecode(raw);+ if (rows is! List) return;+ for (final row in rows.take(256)) {+ if (row is! Map ||+ row['machineId'] is! String ||+ row['path'] is! String ||+ row['name'] is! String)+ continue;+ final item = SavedSwarmProject(+ machineId: row['machineId'],+ path: row['path'],+ name: row['name'],+ );+ if (item.path.isEmpty ||+ item.name.isEmpty ||+ projects.any((p) => p.id == item.id))+ continue;+ projects.add(item);+ }+ notifyListeners();+ } catch (_) {+ /* A damaged catalog does not prevent opening live agents. */+ }+ }++ Future<void> add(SavedSwarmProject project) async {+ projects.removeWhere((p) => p.id == project.id);+ projects.add(project);+ notifyListeners();+ await storage?.write(+ 'swarm_projects_v1',+ jsonEncode(projects.map((p) => p.toJson()).toList()),+ );+ }++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dartindex 9a07d1cf4..ceab4b648 100644--- a/desktop/lib/state/terminal_pane.dart+++ b/desktop/lib/state/terminal_pane.dart@@ -32,6 +32,9 @@ class TerminalPane {TerminalSession? session;+ /// Last visible geometry, retained while this controller is parked off screen.+ Size? lastViewSize;+/// The grid cell's widget key — a GlobalKey, and measured to be necessary.////// The layout puts cells in DIFFERENT parents depending on how many therediff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dartindex f9b811eb0..c353fe092 100644--- a/desktop/lib/update/desktop_updater.dart+++ b/desktop/lib/update/desktop_updater.dart@@ -175,7 +175,7 @@ class DesktopUpdater {),_launchDetached = launchDetached ?? _defaultLaunchDetached,_metadataUrlForInstance = metadataUrl ?? _metadataUrl,- _releaseMode = releaseMode ?? kReleaseMode,+ _releaseMode = releaseMode ?? false,_isLinux = isLinux ?? Platform.isLinux,_architecture = architecture ?? _currentArchitecture();diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex 8506c26f1..31799c5fe 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -39,6 +39,8 @@ Future<void> showNewAgentDialog(AppNotifier notifier,String machineId, {required String source,+ String? initialFolder,+ String? swarmId,}) {// Reported here rather than at each call site: the doors are four and// growing, and one that forgets to track is a hole in the funnel that only@@ -46,16 +48,27 @@ Future<void> showNewAgentDialog(analytics.newAgentOpened(source: source);return showAppDialog<void>(context: context,- builder: (context) =>- _NewAgentDialog(notifier: notifier, machineId: machineId),+ builder: (context) => _NewAgentDialog(+ notifier: notifier,+ machineId: machineId,+ initialFolder: initialFolder,+ swarmId: swarmId ?? notifier.activeSwarmId,+ ),);}class _NewAgentDialog extends StatefulWidget {final AppNotifier notifier;final String machineId;+ final String? initialFolder;+ final String swarmId;- const _NewAgentDialog({required this.notifier, required this.machineId});+ const _NewAgentDialog({+ required this.notifier,+ required this.machineId,+ this.initialFolder,+ required this.swarmId,+ });@overrideState<_NewAgentDialog> createState() => _NewAgentDialogState();@@ -63,7 +76,8 @@ class _NewAgentDialog extends StatefulWidget {class _NewAgentDialogState extends State<_NewAgentDialog> {late String _engine = allEngines.first.id;- String? _folder;+ late String _machineId = widget.machineId;+ late String? _folder = widget.initialFolder;LocalCodexProfile? _codexProfile;bool _codexProfilesBusy = true;bool _bypassPermission = false;@@ -90,7 +104,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {// a deliberate user action) and the stored rows keep rendering until the new// answer lands, so nothing blanks.WidgetsBinding.instance.addPostFrameCallback((_) {- unawaited(widget.notifier.probeEngines(widget.machineId, force: true));+ unawaited(widget.notifier.probeEngines(_machineId, force: true));});}@@ -102,7 +116,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {/// engine is absent on no evidence would send someone to install one they/// already have.EngineAvailability? _availability(String engine) {- final machine = widget.notifier.stateOf(widget.machineId);+ final machine = widget.notifier.stateOf(_machineId);if (machine == null || !machine.engines.loaded) return null;return machine.engines[engine];}@@ -151,7 +165,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {/// and until it is rendered the panel says "Ready to launch" over an engine/// nobody checked for, which the create then fails on at the far end.bool get _engineCheckFailed {- final machine = widget.notifier.stateOf(widget.machineId);+ final machine = widget.notifier.stateOf(_machineId);if (machine == null) return false;return !machine.engines.loaded && machine.engines.error != null;}@@ -194,7 +208,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {/// Read per build rather than cached: `localOnly`/`localEndpoint` are settled/// by `_refreshMachines`, which can land while this dialog is open.bool get _machineIsThisComputer =>- widget.notifier.stateOf(widget.machineId)?.isLocalMachine ?? false;+ widget.notifier.stateOf(_machineId)?.isLocalMachine ?? false;/// Create waits while the Codex profile list is still loading on a machine/// that can launch into one, so a click cannot land before the choice does.@@ -206,7 +220,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {/// [Machine.displayName], not `name` — the latter is nullable and a machine/// that never got one would title the dialog "New agent on null".String get _machineName =>- widget.notifier.stateOf(widget.machineId)?.machine.displayName ??+ widget.notifier.stateOf(_machineId)?.machine.displayName ??'this machine';Future<void> _browse() async {@@ -228,19 +242,20 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {// themselves select. That case keeps the in-app browser, which walks the// remote filesystem over the `fs_list_dir` RPC.setState(() => _picking = true);+ final pickingMachine = _machineId;try {final picked = _machineIsThisComputer? await getDirectoryPath(initialDirectory: _folder): await showRemoteFolderPicker(context,notifier: widget.notifier,- machineId: widget.machineId,+ machineId: _machineId,initialPath: _folder,);if (!mounted) return;setState(() {_picking = false;- if (picked != null) _folder = picked;+ if (picked != null && pickingMachine == _machineId) _folder = picked;});} catch (error) {if (!mounted) return;@@ -263,9 +278,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {_error = null;});final error = await widget.notifier.createAgent(- widget.machineId,+ _machineId,engine: engine,folder: folder,+ swarmId: widget.swarmId,bypassPermission: bypassPermission,// Keep the explicit choice even if machine discovery changes mid-submit.// The notifier must reject a now-remote target, never use its default login.@@ -369,6 +385,36 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: [+ const FieldLabel('Machine'),+ AppSelectField<String>(+ key: const Key('new-agent-machine-field'),+ value: _machineId,+ options: [+ for (final machine in widget.notifier.machineStates.values)+ SelectOption(+ value: machine.machine.machineId,+ label: machine.isLocalMachine+ ? 'Local'+ : machine.machine.displayName,+ note: machine.nodeOnline == false+ ? 'Offline'+ : machine.needsLink+ ? 'Link required'+ : null,+ ),+ ],+ onChanged: (id) {+ setState(() {+ _machineId = id;+ _folder = null;+ _codexProfile = null;+ _codexProfilesBusy = true;+ _error = null;+ });+ unawaited(widget.notifier.probeEngines(id, force: true));+ },+ ),+ const SizedBox(height: _gapField),const FieldLabel('Engine'),// The app's own picker, not `DropdownButtonFormField`.//@@ -475,12 +521,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {if (_availability('codex')?.supportsCodexHome == true)CodexProfileField(notifier: widget.notifier,- machineId: widget.machineId,+ machineId: _machineId,machineIsThisComputer: _machineIsThisComputer,value: _codexProfile,observedPaths: {for (final agent- in widget.notifier.stateOf(widget.machineId)!.agents)+ in widget.notifier.stateOf(_machineId)!.agents)if (agent.engine == 'codex' && agent.codexHome != null)agent.codexHome!,},diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 70168fdeb..540cbc896 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -36,9 +36,16 @@ import 'terminal_panel.dart';/// position is remembered per pane count (see [PaneSplits]) — which is the part/// of a split tree people actually reach for, without the tree.class PaneGrid extends StatelessWidget {- const PaneGrid({super.key, required this.notifier});+ const PaneGrid({+ super.key,+ required this.notifier,+ this.swarmMode = false,+ this.empty,+ });final AppNotifier notifier;+ final bool swarmMode;+ final Widget? empty;@overrideWidget build(BuildContext context) {@@ -46,49 +53,21 @@ class PaneGrid extends StatelessWidget {valueListenable: agentDrag,builder: (context, dragging, _) {final panes = notifier.panes;- if (panes.isEmpty) {- return _DropZone(- notifier: notifier,- paneId: null,- dragging: dragging,- child: _EmptyGrid(notifier: notifier),- );- }- // ZOOM SHORT-CIRCUITS THE SHAPE, it does not add one.- //- // tmux's `prefix z` is not a layout — it is the same pane list with one- // of them taking the room. Building it as a seventh arrangement would- // have meant every shape below learning about it; returning early means- // none of them do, and the grid comes back exactly as it was because it- // was never rearranged.- //- // The cell keeps its `cellKey`, so the terminal inside is the SAME- // widget — no detach, no reflow of the pty, no scrollback lost. A- // zoomed pane is one that moved, not one that was rebuilt.final zoomed = notifier.zoomedPaneId;- if (zoomed != null && panes.length > 1) {- for (final pane in panes) {- if (pane.id != zoomed) continue;- return _PaneCell(- key: pane.cellKey,- notifier: notifier,- pane: pane,- dragging: dragging,- );- }- }+ final visible = zoomed == null+ ? panes+ : panes.where((p) => p.id == zoomed).toList();+ Widget cell(TerminalPane pane, {bool visible = true}) => _PaneCell(+ key: pane.cellKey,+ notifier: notifier,+ pane: pane,+ dragging: dragging,+ visible: visible,+ swarmMode: swarmMode,+ );final cells = <Widget>[- for (final pane in panes)- _PaneCell(- key: pane.cellKey,-- notifier: notifier,- pane: pane,- dragging: dragging,- ),- // Revealed only mid-drag: a permanent "add a tile" cell would halve a- // single terminal for the whole session to advertise itself.- if (dragging != null && notifier.canAddPane)+ for (final pane in visible) cell(pane),+ if (!swarmMode && dragging != null && notifier.canAddPane)_DropZone(notifier: notifier,paneId: null,@@ -96,19 +75,39 @@ class PaneGrid extends StatelessWidget {child: const _AddSlot(),),];- // WRAPPED HERE, not inside one of the shapes.- //- // It was in the >4 branch, which is one of six: _arrange returns a- // different tree for one tile, two, three, four, five-with-a-main, and- // the lattice beyond that. The gaps come from _Axis and so appeared in- // all six; the field and the outer margin came from that one branch and- // so appeared in one. Two tiles — the common case — showed gaps the- // exact colour of the tiles either side of them, which is no gap at all.- // JUST THE TILES. The field behind them and the margin around them belong to the content row- // now (see home_screen), because the rail is a card on that same field — a gradient that- // started where the rail ended would be two backgrounds meeting at a seam, which is the thing- // being fixed.- return _arrange(cells);+ final canvas = panes.isEmpty+ ? empty ?? _EmptyGrid(notifier: notifier)+ : _arrange(cells);+ if (!swarmMode) return canvas;+ // A shared agent is mounted exactly once, including across tab changes.+ // Offstage keeps its renderer/selection/scroll position; the fixed old+ // size and disabled auto-resize keep hidden geometry off the wire.+ return Stack(+ fit: StackFit.expand,+ children: [+ Positioned.fill(child: canvas),+ for (final pane in notifier.allPanes)+ if (!visible.contains(pane) && pane.lastViewSize != null)+ Positioned.fill(+ child: Offstage(+ offstage: true,+ child: TickerMode(+ enabled: false,+ child: ExcludeFocus(+ child: OverflowBox(+ alignment: Alignment.topLeft,+ minWidth: pane.lastViewSize!.width,+ maxWidth: pane.lastViewSize!.width,+ minHeight: pane.lastViewSize!.height,+ maxHeight: pane.lastViewSize!.height,+ child: cell(pane, visible: false),+ ),+ ),+ ),+ ),+ ),+ ],+ );},);}@@ -514,18 +513,29 @@ class _PaneCell extends StatelessWidget {required this.notifier,required this.pane,required this.dragging,+ this.visible = true,+ this.swarmMode = false,});final AppNotifier notifier;final TerminalPane pane;final AgentDragRef? dragging;+ final bool visible;+ final bool swarmMode;bool get _single => notifier.panes.length == 1;@override- Widget build(BuildContext context) {+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) {+ if (visible) pane.lastViewSize = constraints.biggest;+ return _build(context);+ },+ );++ Widget _build(BuildContext context) {grid.AppTheme.watch(context);- final focused = notifier.isPaneFocused(pane.id);+ final focused = visible && notifier.isPaneFocused(pane.id);final agentId = pane.agentId;final blocked =agentId != null &&@@ -617,6 +627,8 @@ class _PaneCell extends StatelessWidget {notifier: notifier,pane: pane,single: _single,+ visible: visible,+ swarmMode: swarmMode,),),),@@ -634,11 +646,15 @@ class _PaneContent extends StatelessWidget {required this.notifier,required this.pane,required this.single,+ required this.visible,+ required this.swarmMode,});final AppNotifier notifier;final TerminalPane pane;final bool single;+ final bool visible;+ final bool swarmMode;@overrideWidget build(BuildContext context) {@@ -654,7 +670,7 @@ class _PaneContent extends StatelessWidget {title: wantedAgentId ?? pane.machineId,icon: Icons.hourglass_empty,message: 'Waiting for this machine to answer…',- onClose: single ? null : close,+ onClose: single && !swarmMode ? null : close,busy: true,);}@@ -677,7 +693,7 @@ class _PaneContent extends StatelessWidget {icon: Icons.link_off,message:'${machine.machine.displayName} is not linked to this computer yet.',- onClose: single ? null : close,+ onClose: single && !swarmMode ? null : close,);}@@ -686,7 +702,7 @@ class _PaneContent extends StatelessWidget {(machine.isLocalMachine && !machine.usesLocalTransport);if (offline) {return _Guide(- single: single,+ single: single && !swarmMode,onClose: close,title: agentName ?? machine.machine.displayName,compactMessage: machine.isLocalMachine@@ -722,13 +738,19 @@ class _PaneContent extends StatelessWidget {);}+ if (agent != null && !agent.terminalAvailable) {+ return _PaneStatus(title: agentName, icon: Icons.terminal,+ message: agent.terminalUnavailableReason ?? 'This agent has no available terminal.',+ onClose: close);+ }+final session = pane.session;if (session == null) {return _PaneStatus(title: agentName,icon: Icons.hourglass_empty,message: 'Attaching…',- onClose: single ? null : close,+ onClose: single && !swarmMode ? null : close,busy: true,);}@@ -744,14 +766,16 @@ class _PaneContent extends StatelessWidget {final terminal = TerminalPanel(notifier: notifier,session: session,- focused: notifier.isPaneFocused(pane.id),+ focused: visible && notifier.isPaneFocused(pane.id),+ visible: visible,+ compactHeader: swarmMode,composerVisible: !launchFailed && pane.composerVisible,readOnly: launchFailed,onToggleComposer: launchFailed? null: () => notifier.toggleComposer(pane.id),- onClose: single ? null : close,- pinned: pane.isPinned,+ onClose: single && !swarmMode ? null : close,+ pinned: notifier.isPanePinned(pane),onTogglePin: single ? null : () => notifier.togglePinPane(pane.id),onRendererFocus: () => notifier.focusPane(pane.id),paneDrag: singlediff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dartnew file mode 100644index 000000000..e9b119091--- /dev/null+++ b/desktop/lib/widgets/swarm_dialogs.dart@@ -0,0 +1,352 @@+import 'dart:async';++import 'package:file_selector/file_selector.dart';+import 'package:flutter/material.dart';++import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_select_field.dart';+import '../state/app_state.dart';+import '../state/swarm_catalog.dart';+import 'link_machine_dialog.dart';+import 'link_machine_screen.dart';+import 'remote_folder_picker.dart';+import 'swarm_welcome.dart';++Future<SwarmAgentRef?> showSwarmAgentPicker(+ BuildContext context,+ AppNotifier notifier,+ VoidCallback onNew,+) => showAppDialog<SwarmAgentRef>(+ context: context,+ builder: (_) => _AgentPicker(notifier: notifier, onNew: onNew),+);++class _AgentPicker extends StatefulWidget {+ const _AgentPicker({required this.notifier, required this.onNew});+ final AppNotifier notifier;+ final VoidCallback onNew;+ @override+ State<_AgentPicker> createState() => _AgentPickerState();+}++class _AgentPickerState extends State<_AgentPicker> {+ String query = '';+ @override+ Widget build(BuildContext context) => Dialog(+ child: SizedBox(+ width: 620,+ height: 520,+ child: Padding(+ padding: const EdgeInsets.all(22),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ const Text(+ 'Add agent',+ style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),+ ),+ const Spacer(),+ TextButton.icon(+ onPressed: () {+ widget.onNew();+ Navigator.pop(context);+ },+ icon: const Icon(Icons.add, size: 16),+ label: const Text('New agent'),+ ),+ IconButton(+ tooltip: 'Close agent picker',+ onPressed: () => Navigator.pop(context),+ icon: const Icon(Icons.close, size: 18),+ ),+ ],+ ),+ const SizedBox(height: 16),+ SwarmSearchField(+ autofocus: true,+ onChanged: (value) => setState(() => query = value),+ onSubmitted: (_) {+ final rows = swarmAgents(widget.notifier, query);+ if (rows.isNotEmpty) Navigator.pop(context, rows.first);+ },+ ),+ const SizedBox(height: 16),+ Expanded(+ child: ListenableBuilder(+ listenable: widget.notifier,+ builder: (_, _) => SwarmAgentRows(+ notifier: widget.notifier,+ agents: swarmAgents(widget.notifier, query),+ onAgent: (agent) => Navigator.pop(context, agent),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+}++Future<String?> showSwarmRenameDialog(BuildContext context, String name) async {+ final controller = TextEditingController(text: name)+ ..selection = TextSelection(baseOffset: 0, extentOffset: name.length);+ try {+ return await showAppDialog<String>(+ context: context,+ builder: (context) => AlertDialog(+ title: const Text('Rename swarm'),+ content: SizedBox(+ width: 360,+ child: TextField(+ controller: controller,+ autofocus: true,+ maxLength: 80,+ decoration: const InputDecoration(labelText: 'Name'),+ onSubmitted: (value) => Navigator.pop(context, value),+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(context, controller.text),+ child: const Text('Save'),+ ),+ ],+ ),+ );+ } finally {+ // The route's reverse transition may still be rendering the field.+ Future<void>.delayed(const Duration(milliseconds: 200), controller.dispose);+ }+}++Future<SavedSwarmProject?> showSwarmProjectDialog(+ BuildContext context,+ AppNotifier notifier,+) => showAppDialog<SavedSwarmProject>(+ context: context,+ builder: (_) => _ProjectDialog(notifier: notifier),+);++class _ProjectDialog extends StatefulWidget {+ const _ProjectDialog({required this.notifier});+ final AppNotifier notifier;+ @override+ State<_ProjectDialog> createState() => _ProjectDialogState();+}++class _ProjectDialogState extends State<_ProjectDialog> {+ late String? machineId =+ (widget.notifier.machineStates.values+ .where((m) => m.isLocalMachine)+ .firstOrNull ??+ widget.notifier.machineStates.values.firstOrNull)+ ?.machine+ .machineId;+ final name = TextEditingController();+ String? path;+ String? error;+ bool picking = false;+ @override+ void dispose() {+ name.dispose();+ super.dispose();+ }++ Future<void> browse() async {+ final id = machineId;+ if (id == null || picking) return;+ setState(() {+ picking = true;+ error = null;+ });+ try {+ final folder = widget.notifier.stateOf(id)?.isLocalMachine == true+ ? await getDirectoryPath(initialDirectory: path)+ : await showRemoteFolderPicker(+ context,+ notifier: widget.notifier,+ machineId: id,+ initialPath: path,+ );+ if (!mounted || machineId != id) return;+ setState(() {+ path = folder ?? path;+ if (folder != null && name.text.trim().isEmpty)+ name.text = folder.split('/').where((s) => s.isNotEmpty).last;+ });+ } catch (_) {+ if (mounted)+ setState(+ () =>+ error = 'Could not browse this machine. Reconnect and try again.',+ );+ } finally {+ if (mounted) setState(() => picking = false);+ }+ }++ @override+ Widget build(BuildContext context) => AlertDialog(+ title: const Text('Add project'),+ content: SizedBox(+ width: 460,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ 'Choose an existing working folder.',+ style: TextStyle(fontSize: 12, color: Colors.white60),+ ),+ const SizedBox(height: 20),+ if (machineId != null)+ AppSelectField<String>(+ value: machineId!,+ options: [+ for (final machine in widget.notifier.machineStates.values)+ SelectOption(+ value: machine.machine.machineId,+ label: machine.isLocalMachine+ ? 'Local'+ : machine.machine.displayName,+ ),+ ],+ onChanged: (value) => setState(() {+ machineId = value;+ path = null;+ }),+ ),+ const SizedBox(height: 16),+ OutlinedButton.icon(+ onPressed: machineId == null || picking ? null : browse,+ icon: const Icon(Icons.folder_open, size: 17),+ label: Text(+ path ?? 'Choose folder',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ const SizedBox(height: 16),+ TextField(+ controller: name,+ maxLength: 80,+ decoration: const InputDecoration(labelText: 'Project name'),+ onChanged: (_) => setState(() {}),+ ),+ if (error != null)+ Text(+ error!,+ style: const TextStyle(color: Colors.orangeAccent, fontSize: 12),+ ),+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: path == null || name.text.trim().isEmpty || picking+ ? null+ : () => Navigator.pop(+ context,+ SavedSwarmProject(+ machineId: machineId!,+ path: path!,+ name: name.text.trim(),+ ),+ ),+ child: const Text('Add project'),+ ),+ ],+ );+}++Future<void> showSwarmLinkDialog(+ BuildContext context,+ AppNotifier notifier,+) async {+ final selected = await showAppDialog<String>(+ context: context,+ builder: (context) => AlertDialog(+ title: const Text('Link machine'),+ content: SizedBox(+ width: 480,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ 'On the other machine, sign in to Harness and start the daemon:',+ ),+ const SizedBox(height: 14),+ const SelectableText(+ 'harness login\nharness start',+ style: TextStyle(fontFamily: 'monospace', fontSize: 13),+ ),+ const SizedBox(height: 18),+ const Text(+ 'Use the same account. Set a remote password on that machine, then choose it here to connect.',+ style: TextStyle(fontSize: 12, color: Colors.white60),+ ),+ const SizedBox(height: 12),+ ListenableBuilder(+ listenable: notifier,+ builder: (_, _) => Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final machine in notifier.machineStates.values.where(+ (m) => !m.isLocalMachine,+ ))+ ListTile(+ leading: const Icon(Icons.computer, size: 18),+ title: Text(machine.machine.displayName),+ subtitle: Text(+ machine.needsLink+ ? 'Link required'+ : machine.nodeOnline == false+ ? 'Offline'+ : 'Linked',+ ),+ onTap: () =>+ Navigator.pop(context, machine.machine.machineId),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ onPressed: notifier.refreshMachines,+ child: const Text('Refresh'),+ ),+ TextButton(+ onPressed: () => Navigator.pop(context, 'local-access'),+ child: const Text('This machine’s remote password'),+ ),+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Done'),+ ),+ ],+ ),+ );+ if (!context.mounted || selected == null) return;+ if (selected == 'local-access') {+ await showLinkMachineDialog(context, notifier);+ } else {+ await showLinkMachineScreenDialog(context, notifier, selected);+ }+}diff --git a/desktop/lib/widgets/swarm_welcome.dart b/desktop/lib/widgets/swarm_welcome.dartnew file mode 100644index 000000000..11697d6ef--- /dev/null+++ b/desktop/lib/widgets/swarm_welcome.dart@@ -0,0 +1,453 @@+import 'dart:ui' show ImageFilter;++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/skeleton.dart';+import '../state/app_state.dart';+import '../state/swarm.dart';+import '../state/swarm_catalog.dart';+import 'engine_identity.dart';++class SwarmWelcome extends StatefulWidget {+ const SwarmWelcome({+ super.key,+ required this.notifier,+ required this.projects,+ required this.onNewAgent,+ required this.onAddProject,+ required this.onLinkMachine,+ required this.onMachine,+ required this.onProject,+ required this.onAgent,+ });+ final AppNotifier notifier;+ final List<SavedSwarmProject> projects;+ final VoidCallback onNewAgent;+ final VoidCallback onAddProject;+ final VoidCallback onLinkMachine;+ final ValueChanged<MachineState> onMachine;+ final ValueChanged<SwarmProjectGroup> onProject;+ final ValueChanged<SwarmAgentRef> onAgent;+ @override+ State<SwarmWelcome> createState() => _SwarmWelcomeState();+}++class _SwarmWelcomeState extends State<SwarmWelcome> {+ String _query = '';+ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final app = widget.notifier;+ final groups = swarmProjects(app, widget.projects);+ final results = swarmAgents(app, _query);+ final wallpaper =+ swarmWallpapers[app.activeSwarm.wallpaper % swarmWallpapers.length];+ return ClipRRect(+ borderRadius: BorderRadius.circular(12),+ child: Stack(+ fit: StackFit.expand,+ children: [+ Image.asset(+ 'assets/swarm-wallpapers/swarm-welcome-$wallpaper.jpg',+ fit: BoxFit.cover,+ excludeFromSemantics: true,+ ),+ const DecoratedBox(+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ colors: [Color(0x1211111c), Color(0x750c111e)],+ ),+ ),+ ),+ LayoutBuilder(+ builder: (context, constraints) => SingleChildScrollView(+ child: ConstrainedBox(+ constraints: BoxConstraints(minHeight: constraints.maxHeight),+ child: Center(+ child: Container(+ constraints: const BoxConstraints(maxWidth: 1000),+ padding: const EdgeInsets.fromLTRB(56, 40, 56, 62),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text(+ 'Start a swarm',+ style: TextStyle(+ fontSize: 32,+ fontWeight: FontWeight.w500,+ letterSpacing: -0.7,+ color: Colors.white,+ shadows: [+ Shadow(blurRadius: 16, color: Colors.black54),+ ],+ ),+ ),+ const SizedBox(height: 10),+ const Text(+ 'Choose a machine or project, or add agents individually.',+ style: TextStyle(+ fontSize: 13,+ color: Color(0xffe0dce3),+ ),+ ),+ const SizedBox(height: 28),+ Row(+ children: [+ Expanded(+ child: SwarmSearchField(+ onChanged: (v) => setState(() => _query = v),+ onSubmitted: (_) {+ if (results.isNotEmpty)+ widget.onAgent(results.first);+ },+ ),+ ),+ const SizedBox(width: 12),+ FilledButton.icon(+ onPressed: widget.onNewAgent,+ icon: const Icon(Icons.add, size: 17),+ label: const Text('New agent'),+ style: FilledButton.styleFrom(+ minimumSize: const Size(126, 44),+ backgroundColor: grid.AppPalette.swarmAccent,+ foregroundColor: grid.AppPalette.swarmTabBar,+ ),+ ),+ ],+ ),+ const SizedBox(height: 34),+ _Glass(+ child: _query.trim().isNotEmpty+ ? SizedBox(+ height: 300,+ child: SwarmAgentRows(+ notifier: app,+ agents: results,+ onAgent: widget.onAgent,+ ),+ )+ : LayoutBuilder(+ builder: (context, size) {+ final machines = _section(+ 'Machines',+ 'Link machine',+ widget.onLinkMachine,+ [+ if (app.machinesLoading &&+ app.machineStates.isEmpty)+ const SkeletonList(rows: 3),+ for (final machine+ in app.machineStates.values)+ _StarterRow(+ icon: Icons.computer_outlined,+ name: machine.machine.displayName,+ note: machine.needsLink+ ? 'Link required'+ : machine.nodeOnline == false+ ? 'Offline'+ : machine.isLocalMachine+ ? 'Local'+ : null,+ count: machine.agents.length,+ onTap: () =>+ widget.onMachine(machine),+ ),+ if (!app.machinesLoading &&+ app.machineStates.isEmpty)+ const Padding(+ padding: EdgeInsets.symmetric(+ vertical: 18,+ ),+ child: Text(+ 'Link a machine to find its agents.',+ ),+ ),+ ],+ );+ final projects = _section(+ 'Projects',+ 'Add project',+ widget.onAddProject,+ [+ for (final group in groups)+ _StarterRow(+ icon: Icons.folder_outlined,+ name: group.name,+ count: group.agents.length,+ onTap: () =>+ widget.onProject(group),+ ),+ if (groups.isEmpty)+ const Padding(+ padding: EdgeInsets.symmetric(+ vertical: 18,+ ),+ child: Text(+ 'Add a working folder to start a project.',+ style: TextStyle(+ color: Color(0xffc5bece),+ fontSize: 12,+ ),+ ),+ ),+ ],+ );+ return size.maxWidth < 570+ ? Column(+ children: [+ machines,+ const SizedBox(height: 24),+ projects,+ ],+ )+ : Row(+ crossAxisAlignment:+ CrossAxisAlignment.start,+ children: [+ Expanded(child: machines),+ const SizedBox(width: 36),+ Expanded(child: projects),+ ],+ );+ },+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ Positioned(+ right: 14,+ bottom: 10,+ child: TextButton.icon(+ onPressed: app.nextSwarmWallpaper,+ icon: const Icon(Icons.wallpaper_outlined, size: 14),+ label: const Text(+ 'Next wallpaper',+ style: TextStyle(fontSize: 11),+ ),+ style: TextButton.styleFrom(foregroundColor: Colors.white70),+ ),+ ),+ ],+ ),+ );+ }++ Widget _section(+ String title,+ String action,+ VoidCallback onAction,+ List<Widget> children,+ ) => Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ children: [+ Text(+ title,+ style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600),+ ),+ const Spacer(),+ TextButton(+ onPressed: onAction,+ child: Text(action, style: const TextStyle(fontSize: 11)),+ ),+ ],+ ),+ const SizedBox(height: 8),+ ...children,+ ],+ );+}++class SwarmSearchField extends StatelessWidget {+ const SwarmSearchField({+ super.key,+ required this.onChanged,+ this.onSubmitted,+ this.autofocus = false,+ });+ final ValueChanged<String> onChanged;+ final ValueChanged<String>? onSubmitted;+ final bool autofocus;+ @override+ Widget build(BuildContext context) => TextField(+ autofocus: autofocus,+ onChanged: onChanged,+ onSubmitted: onSubmitted,+ style: const TextStyle(fontSize: 13),+ decoration: InputDecoration(+ hintText: 'Find an agent…',+ prefixIcon: const Icon(Icons.search, size: 18),+ filled: true,+ fillColor: const Color(0xa6111521),+ contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: const BorderSide(color: Colors.white24),+ ),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(8),+ borderSide: const BorderSide(color: Colors.white24),+ ),+ ),+ );+}++class SwarmAgentRows extends StatelessWidget {+ const SwarmAgentRows({+ super.key,+ required this.notifier,+ required this.agents,+ required this.onAgent,+ });+ final AppNotifier notifier;+ final List<SwarmAgentRef> agents;+ final ValueChanged<SwarmAgentRef> onAgent;+ @override+ Widget build(BuildContext context) {+ if (agents.isEmpty)+ return const Center(+ child: Text(+ 'No matching agents',+ style: TextStyle(color: Colors.white60),+ ),+ );+ return ListView.builder(+ itemCount: agents.length,+ itemBuilder: (context, index) {+ final entry = agents[index];+ final agent = entry.agent;+ final open = notifier.paneOfAgent(entry.machineId, agent.id) != null;+ final question = notifier.questionFor(entry.machineId, agent.id);+ final status = question != null+ ? 'Input needed'+ : entry.machine.nodeOnline == false+ ? 'Offline'+ : !agent.terminalAvailable+ ? 'Unavailable'+ : open+ ? 'In this swarm'+ : null;+ return ListTile(+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 10,+ vertical: 3,+ ),+ leading: EngineMark(engine: agent.engine, size: 22),+ title: Text(+ agent.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 13),+ ),+ subtitle: Text(+ [+ entry.machine.machine.displayName,+ if (agent.project != null) agent.project!.name,+ if (agent.project?.branch != null) agent.project!.branch!,+ ].join(' · '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 11, color: Colors.white54),+ ),+ trailing: status == null+ ? const Icon(Icons.add, size: 16, color: Colors.white54)+ : Text(+ status,+ style: TextStyle(+ fontSize: 10,+ color: question == null+ ? Colors.white54+ : grid.AppPalette.warn,+ ),+ ),+ onTap: () => onAgent(entry),+ );+ },+ );+ }+}++class _StarterRow extends StatelessWidget {+ const _StarterRow({+ required this.icon,+ required this.name,+ required this.count,+ required this.onTap,+ this.note,+ });+ final IconData icon;+ final String name;+ final int count;+ final VoidCallback onTap;+ final String? note;+ @override+ Widget build(BuildContext context) => Tooltip(+ message: name,+ child: InkWell(+ onTap: onTap,+ borderRadius: BorderRadius.circular(7),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 14),+ child: Row(+ children: [+ Icon(icon, size: 17, color: Colors.white60),+ const SizedBox(width: 11),+ Expanded(+ child: Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 12),+ ),+ ),+ if (note != null) ...[+ const SizedBox(width: 6),+ Text(+ note!,+ style: const TextStyle(fontSize: 10, color: Colors.white54),+ ),+ ],+ const SizedBox(width: 12),+ Text(+ '$count',+ style: const TextStyle(fontSize: 11, color: Colors.white54),+ ),+ const SizedBox(width: 8),+ const Icon(Icons.chevron_right, size: 14, color: Colors.white54),+ ],+ ),+ ),+ ),+ );+}++class _Glass extends StatelessWidget {+ const _Glass({required this.child});+ final Widget child;+ @override+ Widget build(BuildContext context) => ClipRRect(+ borderRadius: BorderRadius.circular(14),+ child: BackdropFilter(+ filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),+ child: Container(+ padding: const EdgeInsets.all(24),+ decoration: BoxDecoration(+ color: const Color(0x80111522),+ border: Border.all(color: Colors.white12),+ borderRadius: BorderRadius.circular(14),+ ),+ child: Material(type: MaterialType.transparency, child: child),+ ),+ ),+ );+}diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 0cccba8fa..a5466194b 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -47,6 +47,8 @@ class TerminalPanel extends StatefulWidget {/// Only the focused grid tile may claim keyboard focus on mount/rebuild.final bool focused;+ final bool visible;+ final bool compactHeader;/// Whether this tile's composer textbox is showing. Only consulted for a remote machine.final bool composerVisible;@@ -68,6 +70,8 @@ class TerminalPanel extends StatefulWidget {required this.notifier,required this.session,required this.focused,+ this.visible = true,+ this.compactHeader = false,this.composerVisible = false,this.readOnly = false,this.onToggleComposer,@@ -158,6 +162,11 @@ class _TerminalPanelState extends State<TerminalPanel>widget.session.setCursorBlinkPhase(true);_afterTerminalMounted();}+ if (oldWidget.visible && !widget.visible) {+ _focusNode.unfocus();+ _composerFocus.unfocus();+ _cancelDialInertia();+ }if (!oldWidget.focused && widget.focused) {_claimFocusAfterFrame();}@@ -304,7 +313,8 @@ class _TerminalPanelState extends State<TerminalPanel>void _advanceCursorBlink() {if (!mounted) return;- final shouldBlink = _focusNode.hasFocus && widget.session.acceptsInput;+ final shouldBlink =+ widget.visible && _focusNode.hasFocus && widget.session.acceptsInput;final next = shouldBlink ? !_cursorBlinkVisible : true;if (next == _cursorBlinkVisible) return;_cursorBlinkVisible = next;@@ -345,7 +355,7 @@ class _TerminalPanelState extends State<TerminalPanel>void _afterTerminalMounted({bool clearSelection = false}) {WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted) return;+ if (!mounted || !widget.visible) return;if (clearSelection) _controller.clearSelection();final view = _laidOutTerminalView();if (view == null) return;@@ -658,6 +668,7 @@ class _TerminalPanelState extends State<TerminalPanel>_TerminalHeader(notifier: widget.notifier,session: session,+ compact: widget.compactHeader,onClose: widget.onClose,pinned: widget.pinned,onTogglePin: widget.onTogglePin,@@ -681,6 +692,7 @@ class _TerminalPanelState extends State<TerminalPanel>session.terminal,key: _terminalViewKey,controller: _controller,+ autoResize: widget.visible,scrollController: _scrollController,focusNode: _focusNode,autofocus: widget.focused && !showComposer,@@ -778,7 +790,9 @@ class _TerminalPanelState extends State<TerminalPanel>),),// The grip is shown whether or not the box is: collapsed, it is the only way back.- if (remote && widget.onToggleComposer != null)+ if (!widget.compactHeader &&+ remote &&+ widget.onToggleComposer != null)ComposerGrip(expanded: widget.composerVisible,onPressed: widget.onToggleComposer!,@@ -796,6 +810,7 @@ class _TerminalHeader extends StatelessWidget {final TerminalSession session;final VoidCallback? onClose;final bool pinned;+ final bool compact;final VoidCallback? onTogglePin;/// This strip's drag gesture, or null when there is nothing to drag.@@ -813,6 +828,7 @@ class _TerminalHeader extends StatelessWidget {required this.session,this.onClose,this.pinned = false,+ this.compact = false,this.onTogglePin,this.paneDrag,});@@ -857,8 +873,17 @@ class _TerminalHeader extends StatelessWidget {decoration: BoxDecoration(color: color, shape: BoxShape.circle),),};+ final machine = notifier.stateOf(session.machineId);+ final agent = machine?.agents+ .where((a) => a.id == session.agentId)+ .firstOrNull;+ final project = agent?.project;+ final contextLabel = [+ if (project != null) project.name,+ if (project?.branch != null) project!.branch!,+ ].join(' / ');final strip = SizedBox(- height: 46,+ height: compact ? 38 : 46,child: Padding(padding: const EdgeInsets.symmetric(horizontal: _stripPadding),child: Row(@@ -905,10 +930,42 @@ class _TerminalHeader extends StatelessWidget {),),),+ if (compact && project != null) ...[+ const SizedBox(width: 12),+ Flexible(+ child: Tooltip(+ message:+ '${project.cwd}\n${project.remote ?? project.root ?? ""}',+ child: Text(+ contextLabel,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(fontSize: 11, color: AppColors.textSoft),+ ),+ ),+ ),+ ],+ if (compact) ...[+ const SizedBox(width: 12),+ Flexible(+ child: Tooltip(+ message: machine?.machine.displayName ?? session.machineId,+ child: Text(+ machine?.machine.displayName ?? session.machineId,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 11,+ color: AppColors.mutedStrong,+ ),+ ),+ ),+ ),+ ],const SizedBox(width: 6),- if (session.status == TerminalSessionStatus.controlling)+ if (!compact && session.status == TerminalSessionStatus.controlling)Padding(padding: const EdgeInsets.all(4), child: statusMark)- else+ else if (session.status != TerminalSessionStatus.controlling)Tooltip(message: statusLabel,child: Padding(@@ -923,16 +980,16 @@ class _TerminalHeader extends StatelessWidget {// the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to// a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original// meaning — the backend WebSocket — so an older CLI is never mislabelled.- if (session.linkMode case final mode?)+ if (!compact && session.linkMode != null)Padding(padding: const EdgeInsets.symmetric(horizontal: 2),- child: _LinkModeMark(mode: mode),+ child: _LinkModeMark(mode: session.linkMode!),),// Before the close button: pinning is the rarer act, and a control// that appears to the LEFT of the one people aim for by muscle// memory cannot shift it under their pointer.- if (onTogglePin case final toggle?)- PanePinButton(pinned: pinned, onPressed: toggle),+ if (!compact && onTogglePin != null)+ PanePinButton(pinned: pinned, onPressed: onTogglePin!),if (onClose != null) PaneCloseButton(onPressed: onClose!),],),diff --git a/desktop/macos/Runner.xcodeproj/project.pbxproj b/desktop/macos/Runner.xcodeproj/project.pbxprojindex bc3858177..b4e651cd8 100644--- a/desktop/macos/Runner.xcodeproj/project.pbxproj+++ b/desktop/macos/Runner.xcodeproj/project.pbxproj@@ -21,6 +21,7 @@/* End PBXAggregateTarget section *//* Begin PBXBuildFile section */+ B20100000000000000000001 /* SwarmTitlebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000002 /* SwarmTitlebar.swift */; };331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };@@ -61,6 +62,7 @@/* End PBXCopyFilesBuildPhase section *//* Begin PBXFileReference section */+ B20100000000000000000002 /* SwarmTitlebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwarmTitlebar.swift; sourceTree = "<group>"; };331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };@@ -168,6 +170,7 @@children = (33CC10F02044A3C60003C045 /* AppDelegate.swift */,33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,+ B20100000000000000000002 /* SwarmTitlebar.swift */,33E51913231747F40026EE4D /* DebugProfile.entitlements */,33E51914231749380026EE4D /* Release.entitlements */,33CC11242044D66E0003C045 /* Resources */,@@ -355,6 +358,7 @@buildActionMask = 2147483647;files = (33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,+ B20100000000000000000001 /* SwarmTitlebar.swift in Sources */,33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,);diff --git a/desktop/macos/Runner/Configs/AppInfo.xcconfig b/desktop/macos/Runner/Configs/AppInfo.xcconfigindex 1b411d43f..ecd8ccbff 100644--- a/desktop/macos/Runner/Configs/AppInfo.xcconfig+++ b/desktop/macos/Runner/Configs/AppInfo.xcconfig@@ -5,10 +5,10 @@// 'flutter create' template.// The application's name. By default this is also the title of the Flutter window.-PRODUCT_NAME = Harness+PRODUCT_NAME = Harness V2// The application's bundle identifier-PRODUCT_BUNDLE_IDENTIFIER = ai.autonomous.harness+PRODUCT_BUNDLE_IDENTIFIER = ai.autonomous.harness.v2// The copyright displayed in application informationPRODUCT_COPYRIGHT = Copyright © 2026 autonomous.ai. All rights reserved.diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swiftindex 7d74f4e05..c7d3e029d 100644--- a/desktop/macos/Runner/MainFlutterWindow.swift+++ b/desktop/macos/Runner/MainFlutterWindow.swift@@ -15,6 +15,7 @@ private let kMenuChannel = "harness/app_menu"private let kClipboardImageChannel = "harness/clipboard_image"class MainFlutterWindow: NSWindow {+ private var swarmTitlebar: SwarmTitlebar?private var menuChannel: FlutterMethodChannel?private var clipboardImageChannel: FlutterMethodChannel?@@ -30,6 +31,7 @@ class MainFlutterWindow: NSWindow {name: kMenuChannel,binaryMessenger: flutterViewController.engine.binaryMessenger)+ swarmTitlebar = SwarmTitlebar(window: self, messenger: flutterViewController.engine.binaryMessenger)installClipboardImageChannel(messenger: flutterViewController.engine.binaryMessenger)// Harness Desktop is dark-only. Flutter's own theme does not reach AppKit —@@ -117,15 +119,7 @@ class MainFlutterWindow: NSWindow {),at: at + 2)- appMenu.insertItem(- menuItem(- title: "Check for Updates…",- action: #selector(checkForUpdates(_:)),- symbol: "arrow.down.circle",- tag: updateMenuItemTag- ),- at: at + 3- )+}/// The Safari/Chrome/Terminal.app "Font" convention, in the SAME menu and the SAME order thosediff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftnew file mode 100644index 000000000..1bef0e2d4--- /dev/null+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -0,0 +1,270 @@+import Cocoa+import FlutterMacOS++/// Real AppKit controls in the title bar, beside the system traffic lights.+/// https://developer.apple.com/documentation/appkit/nstitlebaraccessoryviewcontroller/layoutattribute+final class SwarmTitlebar {+ private weak var window: NSWindow?+ private let channel: FlutterMethodChannel+ private let accessory = NSTitlebarAccessoryViewController()+ private let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))+ private var observers: [NSObjectProtocol] = []+ private var configured = false++ init(window: NSWindow, messenger: FlutterBinaryMessenger) {+ self.window = window+ channel = FlutterMethodChannel(name: "harness/swarm_tabs", binaryMessenger: messenger)+ strip.emit = { [weak self] method, args in self?.channel.invokeMethod(method, arguments: args) }+ channel.setMethodCallHandler { [weak self] call, result in+ guard let self else { result(nil); return }+ switch call.method {+ case "configure":+ self.configure()+ result(true)+ case "update":+ self.strip.update(call.arguments as? [String: Any] ?? [:])+ result(nil)+ default: result(FlutterMethodNotImplemented)+ }+ }+ for name in [NSWindow.didResizeNotification, NSWindow.didEnterFullScreenNotification,+ NSWindow.didExitFullScreenNotification] {+ observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) {+ [weak self] _ in self?.resize()+ })+ }+ }++ deinit { observers.forEach(NotificationCenter.default.removeObserver) }++ private func configure() {+ guard let window, !configured else { return }+ configured = true+ NSWindow.allowsAutomaticWindowTabbing = false+ window.tabbingMode = .disallowed+ window.title = "Harness V2"+ window.titleVisibility = .hidden+ window.titlebarAppearsTransparent = true+ window.styleMask.remove(.fullSizeContentView)+ window.backgroundColor = NSColor(srgbRed: 0.20, green: 0.16, blue: 0.21, alpha: 1)+ accessory.layoutAttribute = .right+ accessory.fullScreenMinHeight = 40+ accessory.view = strip+ window.addTitlebarAccessoryViewController(accessory)+ resize()+ installSwarmMenu()+ }++ private func resize() {+ guard let window else { return }+ strip.setFrameSize(NSSize(width: max(200, window.frame.width - 92), height: 40))+ strip.needsLayout = true+ }++ private func installSwarmMenu() {+ guard let main = NSApp.mainMenu, main.item(withTitle: "Swarm") == nil else { return }+ let menu = NSMenu(title: "Swarm")+ func add(_ title: String, _ key: String, _ action: String, _ modifiers: NSEvent.ModifierFlags = [.command]) {+ let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: key)+ item.keyEquivalentModifierMask = modifiers+ item.target = self+ item.representedObject = action+ menu.addItem(item)+ }+ add("New Swarm", "t", "new")+ add("Close Swarm", "w", "closeActive")+ add("Rename Swarm…", "r", "renameActive", [.command, .shift])+ menu.addItem(.separator())+ add("Next Swarm", "]", "next", [.command, .shift])+ add("Previous Swarm", "[", "previous", [.command, .shift])+ menu.addItem(.separator())+ add("Add Agent…", "f", "addAgent", [.command, .shift])+ add("Close Agent View", "w", "closePane", [.command, .shift])+ add("Settings…", ",", "settings")+ let item = NSMenuItem(title: "Swarm", action: nil, keyEquivalent: "")+ item.submenu = menu+ main.insertItem(item, at: min(2, main.numberOfItems))+ }++ @objc private func menuAction(_ sender: NSMenuItem) {+ guard let action = sender.representedObject as? String else { return }+ channel.invokeMethod(action, arguments: nil)+ }+}++private let swarmPasteboardType = NSPasteboard.PasteboardType("ai.autonomous.harness.v2.swarm")++private final class SwarmTabStrip: NSView {+ var emit: ((String, Any?) -> Void)?+ private let scroll = NSScrollView()+ private let document = NSView()+ private let newButton = NSButton()+ private let notifications = NSButton()+ private let settings = NSButton()+ private var tabs: [SwarmTabButton] = []+ private var activeId = ""+ override var mouseDownCanMoveWindow: Bool { true }++ override init(frame: NSRect) {+ super.init(frame: frame)+ wantsLayer = true+ scroll.drawsBackground = false+ scroll.hasHorizontalScroller = false+ scroll.hasVerticalScroller = false+ scroll.documentView = document+ addSubview(scroll)+ func button(_ button: NSButton, _ symbol: String, _ label: String, _ action: Selector) {+ button.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label)+ button.isBordered = false+ button.contentTintColor = NSColor(srgbRed: 0.80, green: 0.75, blue: 0.83, alpha: 1)+ button.target = self+ button.action = action+ button.toolTip = label+ button.setAccessibilityLabel(label)+ addSubview(button)+ }+ button(newButton, "plus", "New swarm (⌘T)", #selector(newSwarm))+ button(notifications, "bell", "Notifications", #selector(showNotifications))+ button(settings, "gearshape", "Settings (⌘,)", #selector(showSettings))+ registerForDraggedTypes([swarmPasteboardType])+ }+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }++ func update(_ state: [String: Any]) {+ let rows = state["tabs"] as? [[String: Any]] ?? []+ activeId = state["activeId"] as? String ?? ""+ let ids = rows.compactMap { $0["id"] as? String }+ for tab in tabs where !ids.contains(tab.swarmId) { tab.removeFromSuperview() }+ let previous = Dictionary(uniqueKeysWithValues: tabs.map { ($0.swarmId, $0) })+ tabs = rows.compactMap { row in+ guard let id = row["id"] as? String else { return nil }+ let tab = previous[id] ?? SwarmTabButton(id: id)+ tab.name = row["name"] as? String ?? "New swarm"+ tab.selected = id == activeId+ tab.attention = (row["attention"] as? Int ?? 0) > 0+ tab.emit = { [weak self] method, args in self?.emit?(method, args) }+ if tab.superview == nil { document.addSubview(tab) }+ tab.needsDisplay = true+ return tab+ }+ newButton.isEnabled = state["enabled"] as? Bool == true && tabs.count < 24+ let count = state["attention"] as? Int ?? 0+ notifications.image = NSImage(systemSymbolName: count > 0 ? "bell.badge" : "bell",+ accessibilityDescription: count > 0 ? "\(count) agents need input" : "Notifications")+ notifications.toolTip = count > 0 ? "\(count) agents need input" : "Notifications"+ notifications.setAccessibilityLabel(notifications.toolTip)+ needsLayout = true+ layoutSubtreeIfNeeded()+ if let active = tabs.first(where: { $0.swarmId == activeId }) { document.scrollToVisible(active.frame) }+ }++ override func layout() {+ super.layout()+ let available = max(120, bounds.width - 106)+ let width = min(204, max(124, available / CGFloat(max(1, tabs.count))))+ let occupied = min(available, CGFloat(tabs.count) * width)+ scroll.frame = NSRect(x: 0, y: 0, width: occupied, height: 40)+ document.frame = NSRect(x: 0, y: 0, width: max(occupied, CGFloat(tabs.count) * width), height: 40)+ for (index, tab) in tabs.enumerated() {+ tab.frame = NSRect(x: CGFloat(index) * width, y: 0, width: width - 2, height: 36)+ }+ newButton.frame = NSRect(x: occupied + 3, y: 4, width: 30, height: 30)+ notifications.frame = NSRect(x: bounds.width - 69, y: 4, width: 30, height: 30)+ settings.frame = NSRect(x: bounds.width - 35, y: 4, width: 30, height: 30)+ }+ override func mouseDown(with event: NSEvent) {+ if event.clickCount == 2 { window?.performZoom(nil) }+ else { window?.performDrag(with: event) }+ }+ @objc private func newSwarm() { emit?("new", nil) }+ @objc private func showNotifications() { emit?("notifications", nil) }+ @objc private func showSettings() { emit?("settings", nil) }+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { .move }+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { .move }+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {+ guard let id = sender.draggingPasteboard.string(forType: swarmPasteboardType),+ tabs.contains(where: { $0.swarmId == id }) else { return false }+ let point = document.convert(sender.draggingLocation, from: nil)+ let index = tabs.firstIndex(where: { point.x < $0.frame.midX }) ?? tabs.count+ let old = tabs.firstIndex(where: { $0.swarmId == id })!+ emit?("reorder", ["id": id, "index": max(0, index > old ? index - 1 : index)])+ return true+ }+}++private final class SwarmTabButton: NSButton, NSDraggingSource {+ let swarmId: String+ var name = "New swarm"+ var selected = false+ var attention = false+ var emit: ((String, Any?) -> Void)?+ private let closeButton = NSButton()+ private var downPoint = NSPoint.zero+ override var acceptsFirstResponder: Bool { false }+ override var mouseDownCanMoveWindow: Bool { false }++ init(id: String) {+ swarmId = id+ super.init(frame: .zero)+ isBordered = false+ closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close swarm")+ closeButton.imageScaling = .scaleProportionallyDown+ closeButton.isBordered = false+ closeButton.target = self+ closeButton.action = #selector(closeSwarm)+ closeButton.toolTip = "Close swarm"+ addSubview(closeButton)+ let menu = NSMenu()+ for (title, action) in [("Rename Swarm…", #selector(renameSwarm)), ("Close Swarm", #selector(closeSwarm))] {+ let item = NSMenuItem(title: title, action: action, keyEquivalent: "")+ item.target = self+ menu.addItem(item)+ }+ self.menu = menu+ }+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }+ override func layout() {+ super.layout()+ closeButton.frame = NSRect(x: bounds.width - 27, y: 9, width: 18, height: 18)+ }+ override func draw(_ dirtyRect: NSRect) {+ if selected {+ NSColor(srgbRed: 0.275, green: 0.216, blue: 0.275, alpha: 1).setFill()+ NSBezierPath(roundedRect: bounds, xRadius: 9, yRadius: 9).fill()+ }+ let paragraph = NSMutableParagraphStyle()+ paragraph.lineBreakMode = .byTruncatingTail+ (name as NSString).draw(in: NSRect(x: 13, y: 9, width: bounds.width - 45, height: 19),+ withAttributes: [.font: NSFont.systemFont(ofSize: 12, weight: selected ? .medium : .regular),+ .foregroundColor: selected ? NSColor.white : NSColor(white: 0.72, alpha: 1), .paragraphStyle: paragraph])+ if attention {+ NSColor.systemOrange.setFill()+ NSBezierPath(ovalIn: NSRect(x: 4, y: 16, width: 4, height: 4)).fill()+ }+ setAccessibilityLabel(name)+ setAccessibilityValue(selected ? "Selected" : "")+ toolTip = "\(name) — double-click to rename"+ closeButton.setAccessibilityLabel("Close \(name)")+ }+ override func mouseDown(with event: NSEvent) {+ downPoint = event.locationInWindow+ if event.clickCount == 2 { renameSwarm() }+ else { emit?("select", ["id": swarmId]) }+ }+ override func mouseDragged(with event: NSEvent) {+ if hypot(event.locationInWindow.x - downPoint.x, event.locationInWindow.y - downPoint.y) < 5 { return }+ let item = NSPasteboardItem()+ item.setString(swarmId, forType: swarmPasteboardType)+ let dragging = NSDraggingItem(pasteboardWriter: item)+ let snapshot = NSImage(size: bounds.size)+ snapshot.lockFocus()+ draw(bounds)+ snapshot.unlockFocus()+ dragging.setDraggingFrame(bounds, contents: snapshot)+ beginDraggingSession(with: [dragging], event: event, source: self)+ }+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .move }+ override func accessibilityPerformPress() -> Bool { emit?("select", ["id": swarmId]); return true }+ @objc private func closeSwarm() { emit?("close", ["id": swarmId]) }+ @objc private func renameSwarm() { emit?("rename", ["id": swarmId]) }+}diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex 502d126fa..6121f1f5d 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -90,6 +90,7 @@ flutter:uses-material-design: trueassets:- assets/engine-icons/+ - assets/swarm-wallpapers/# The real app icon, shown in Settings ▸ About. Copied from the macOS# icon set (`macos/Runner/Assets.xcassets/AppIcon.appiconset`) rather than# loaded from the bundle: Flutter can't read an .icns, and About should showdiff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dartindex 33272650c..d330a9d9d 100644--- a/desktop/test/agent_events_test.dart+++ b/desktop/test/agent_events_test.dart@@ -59,6 +59,7 @@ class FakeCreateAgentNotifier extends AppNotifier {required String folder,bool bypassPermission = false,String? codexHome,+ String? swarmId,}) async => null;}diff --git a/desktop/test/crash_log_test.dart b/desktop/test/crash_log_test.dartindex 746c49e6e..50dd8794c 100644--- a/desktop/test/crash_log_test.dart+++ b/desktop/test/crash_log_test.dart@@ -6,10 +6,10 @@ import 'package:harness/core/crash_log.dart';void main() {test('an error reaches the log with its stack', () {- final file = File(- '${Platform.environment['HOME']}/.harness/desktop-app/errors.log',- );- if (file.existsSync()) file.deleteSync();+ final directory = Directory.systemTemp.createTempSync('harness-v2-crash-test-');+ final file = File('${directory.path}/errors.log');+ CrashLog.testFile = file;+ addTearDown(() { CrashLog.testFile = null; directory.deleteSync(recursive: true); });CrashLog.record(TypeError(),diff --git a/desktop/test/dial_desk_test.dart b/desktop/test/dial_desk_test.dartindex a30480ea8..c44cf0566 100644--- a/desktop/test/dial_desk_test.dart+++ b/desktop/test/dial_desk_test.dart@@ -89,7 +89,7 @@ void main() {});test(- 'an agent with no tile takes the focused one, replacing nothing at an edge',+ 'a dial-selected agent adds a view without replacing swarm membership',() async {// The carousel cannot reach this agent any more, but the pull-down switcher still names it and the// window is still told. What happens then is ordinary selection — the focused tile becomes it —@@ -203,12 +203,12 @@ void main() {});expect(app.focusedPane?.agentId, 'a1');- expect(_desk(app), ['a2', 'a3', 'a1']);+ expect(_desk(app), ['a2', 'a3', 'a4', 'a1']);app.dispose();});test(- 'a dial_open frame opens a tile, where dial_focus would replace one',+ 'dial_open and dial_focus retain the other agent views',() async {// The two verbs side by side, driven through the app's own handler: the same// agent, one frame each, and the grid ends up a different size.@@ -225,19 +225,19 @@ void main() {'a1','a2','a5',- ], reason: 'focus replaces, open adds');+ ], reason: 'neither event removes a view');app.dispose();},);test(- 'a focus replaces the FOCUSED tile, which is what a rail click does',+ 'a dial focus adds a missing view while preserving existing members',() async {final app = await _withTiles(['a1', 'a2', 'a3']);app.focusPane(app.panes[1].id);await app.selectAgentFromDial('m1', 'a4');- expect(_desk(app), ['a1', 'a4', 'a3']);+ expect(_desk(app), ['a1', 'a2', 'a3', 'a4']);app.dispose();},);diff --git a/desktop/test/harness_file_store_test.dart b/desktop/test/harness_file_store_test.dartindex 50b80dfa6..89500e4ca 100644--- a/desktop/test/harness_file_store_test.dart+++ b/desktop/test/harness_file_store_test.dart@@ -26,7 +26,7 @@ void main() {environment: {'HOME': '/Users/tester'},);- expect(path, '/Users/tester/.harness/desktop-app');+ expect(path, '/Users/tester/.harness/desktop-app-v2');}, skip: Platform.isWindows);test(diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dartindex 8612393f1..42bd435f8 100644--- a/desktop/test/new_agent_codex_profile_test.dart+++ b/desktop/test/new_agent_codex_profile_test.dart@@ -97,6 +97,7 @@ class _Notifier extends AppNotifier {required String folder,bool bypassPermission = false,String? codexHome,+ String? swarmId,}) async {calls.add({'engine': engine, 'codexHome': codexHome, 'folder': folder});return null;diff --git a/desktop/test/pane_lattice_test.dart b/desktop/test/pane_lattice_test.dartindex 3e07548d1..01a1285ed 100644--- a/desktop/test/pane_lattice_test.dart+++ b/desktop/test/pane_lattice_test.dart@@ -40,7 +40,7 @@ Future<void> _pump(WidgetTester tester, int n, Size size) async {}void main() {- test('the ceiling is nine, which is as far as ⌘1–⌘9 reaches', () {+ test('machine starters can contain more than nine agents', () {expect(PaneLayoutStore.maxPanes, 9);expect(AppNotifier.maxPanes, PaneLayoutStore.maxPanes);});diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dartnew file mode 100644index 000000000..df2def140--- /dev/null+++ b/desktop/test/swarm_screen_test.dart@@ -0,0 +1,128 @@+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter/services.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/state/app_state.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/widgets/pane_grid.dart';+import 'package:harness/widgets/terminal_panel.dart';+import 'package:xterm/xterm.dart';++import 'swarm_state_test.dart' show createApp;++Future<void> mount(WidgetTester tester, AppNotifier app) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ await tester.pumpWidget(MaterialApp(theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(notifier: app, nativeTabs: false, projectStore: SwarmProjectStore())));+ await tester.pump(const Duration(milliseconds: 100));+}+TerminalSession terminal(String id, List<TerminalBinaryFrame> input) => TerminalSession(+ machineId: 'm', agentId: id, agentName: 'Session $id', engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (frame) async { if (frame.kind == TerminalBinaryKind.input) input.add(frame); return true; },+)..status = TerminalSessionStatus.controlling..streamId = 'stream-$id';++void main() {+ testWidgets('welcome, search and picker cancellation leave layout and zoom intact', (tester) async {+ final app = createApp();+ await mount(tester, app);+ expect(find.text('Start a swarm'), findsOneWidget);+ expect(find.text('Models'), findsNothing);+ expect(find.text('Machines'), findsOneWidget);+ await tester.enterText(find.byType(TextField), 'Agent 1');+ await tester.pump();+ expect(find.text('Agent 1').last, findsOneWidget);+ await tester.tap(find.text('Agent 1').last);+ await tester.pump();+ await app.addAgentToSwarm('m', 'a2');+ app.toggleZoomPane();+ await tester.pump();+ final zoom = app.zoomedPaneId;+ final before = tester.getSize(find.byType(PaneGrid));+ await tester.tap(find.byTooltip('Add agent (⌘⇧F)'));+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.text('Add agent'), findsOneWidget);+ expect(app.panes.length, 2);+ expect(app.zoomedPaneId, zoom);+ expect(tester.getSize(find.byType(PaneGrid)), before);+ await tester.tap(find.byTooltip('Close agent picker'));+ await tester.pump(const Duration(milliseconds: 300));+ expect(app.zoomedPaneId, zoom);+ expect(app.panes.length, 2);+ await tester.pumpWidget(const SizedBox()); app.dispose();+ });++ testWidgets('tab and zoom switches retain one renderer per session and preserve hidden geometry', (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final framesA = <TerminalBinaryFrame>[];+ final framesB = <TerminalBinaryFrame>[];+ final a = terminal('a0', framesA);+ final b = terminal('a1', framesB);+ app.adoptSessionForTest(a);+ app.adoptSessionForTest(b);+ final first = app.activeSwarmId;+ await mount(tester, app);+ await tester.pump(const Duration(milliseconds: 100));+ final rendererA = tester.state(find.byWidgetPredicate((w) => w is TerminalView && w.terminal == a.terminal));+ final rendererB = tester.state(find.byWidgetPredicate((w) => w is TerminalView && w.terminal == b.terminal));+ final geometryB = (b.terminal.viewWidth, b.terminal.viewHeight);+ app.newSwarm();+ await app.addAgentToSwarm('m', 'a0');+ await tester.pump(const Duration(milliseconds: 80));+ expect(find.byType(TerminalPanel), findsOneWidget);+ expect(find.byType(TerminalPanel, skipOffstage: false), findsNWidgets(2));+ expect(tester.state(find.byWidgetPredicate((w) => w is TerminalView && w.terminal == a.terminal)), same(rendererA));+ expect((b.terminal.viewWidth, b.terminal.viewHeight), geometryB);+ tester.view.physicalSize = const Size(1000, 700);+ await tester.pump(const Duration(milliseconds: 80));+ expect((b.terminal.viewWidth, b.terminal.viewHeight), geometryB);+ framesA.clear(); framesB.clear();+ expect(tester.testTextInput.hasAnyClients, isTrue);+ tester.testTextInput.updateEditingValue(const TextEditingValue(text: 'x', selection: TextSelection.collapsed(offset: 1)));+ await tester.pump(const Duration(milliseconds: 30));+ expect(utf8.decode(framesA.expand((f) => f.bytes).toList()), 'x');+ expect(framesB, isEmpty);+ app.selectSwarm(first);+ await tester.pump(const Duration(milliseconds: 80));+ expect(tester.state(find.byWidgetPredicate((w) => w is TerminalView && w.terminal == b.terminal)), same(rendererB));+ app.toggleZoomPane();+ await tester.pump(const Duration(milliseconds: 60));+ expect(find.byType(TerminalPanel, skipOffstage: false), findsNWidgets(2));+ app.toggleZoomPane();+ await tester.pump(const Duration(milliseconds: 60));+ expect(tester.state(find.byWidgetPredicate((w) => w is TerminalView && w.terminal == a.terminal)), same(rendererA));+ await tester.pumpWidget(const SizedBox()); app.dispose();+ });++ testWidgets('notifications show only current questions and navigate to their originating swarm', (tester) async {+ final app = createApp();+ await app.addAgentToSwarm('m', 'a0');+ final first = app.activeSwarmId;+ app.newSwarm();+ await app.handleEventForTest('m', {'type': 'commander_question', 'payload': {+ 'agentId': 'a0', 'requestId': 'question', 'questions': [{'q': 'Which folder?', 'options': ['A', 'B']}],+ }});+ await mount(tester, app);+ await tester.tap(find.byIcon(Icons.notifications_none));+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.text('Which folder?'), findsOneWidget);+ await tester.tap(find.text('Which folder?'));+ await tester.pump(const Duration(milliseconds: 300));+ expect(app.activeSwarmId, first);+ expect(app.focusedPane?.agentId, 'a0');+ await app.handleEventForTest('m', {'type': 'commander_question_close', 'payload': {'agentId': 'a0', 'requestId': 'question'}});+ await tester.tap(find.byIcon(Icons.notifications_none));+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.text('No agents need your input'), findsOneWidget);+ await tester.pumpWidget(const SizedBox()); app.dispose();+ });+}diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dartnew file mode 100644index 000000000..48affab4f--- /dev/null+++ b/desktop/test/swarm_state_test.dart@@ -0,0 +1,167 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/pane_preset.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_session.dart';++class MemoryStore implements LocalKeyValueStore {+ final values = <String, String>{};+ @override Future<String?> read(String key) async => values[key];+ @override Future<void> write(String key, String value) async { values[key] = value; }+ @override Future<void> delete(String key) async { values.remove(key); }+}+AppNotifier createApp({MemoryStore? store}) {+ final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null,+ paneLayoutStore: store == null ? null : PaneLayoutStore(storage: store))..hasNavigationRail = false;+ const machine = Machine(machineId: 'm', authMode: MachineAuthMode.remote, name: 'Test host');+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)..nodeOnline = false+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [for (var i = 0; i < 70; i++) Agent(id: 'a$i', name: 'Agent $i', engine: 'codex', terminalAvailable: true)];+ return app;+}+void main() {+ test('shared memberships own one controller and close only the final stream', () async {+ final app = createApp();+ final sent = <String>[];+ final session = TerminalSession(machineId: 'm', agentId: 'a0', agentName: 'A', engineId: 'codex',+ send: (type, payload) async { sent.add(type); return true; }, sendBinary: (_) async => true)+ ..status = TerminalSessionStatus.controlling..streamId = 'shared';+ final pane = app.adoptSessionForTest(session);+ final first = app.activeSwarmId;+ app.newSwarm();+ await app.addAgentToSwarm('m', 'a0');+ expect(app.panes.single, same(pane));+ expect(app.allPanes.length, 1);+ await app.closeSwarm(first);+ expect(app.panes.single.session, same(session));+ expect(sent, isNot(contains('terminal_close')));+ await app.closePane(pane.id);+ expect(sent.where((v) => v == 'terminal_close').length, 1);+ expect(sent, isNot(contains('agent_delete')));+ app.dispose();+ });++ test('replacement and pinning cannot change another swarm', () async {+ final app = createApp();+ await app.addAgentToSwarm('m', 'a0');+ await app.addAgentToSwarm('m', 'a1');+ final first = app.activeSwarm;+ final shared = first.panes.first;+ app.togglePinPane(shared.id);+ app.newSwarm();+ await app.addAgentToSwarm('m', 'a0');+ expect(app.isPanePinned(shared), isFalse);+ await app.assignAgentToPane(shared.id, 'm', 'a2');+ expect(app.panes.single.agentId, 'a2');+ expect(first.panes.first, same(shared));+ expect(shared.agentId, 'a0');+ app.selectSwarm(first.id);+ expect(app.isPanePinned(shared), isTrue);+ app.dispose();+ });++ test('seeding records every membership before any tab switch and exceeds nine', () async {+ final app = createApp();+ final first = app.activeSwarm;+ final work = app.seedSwarm('Fleet', [for (var i = 0; i < 20; i++) (machineId: 'm', agentId: 'a$i')]);+ app.newSwarm();+ await work;+ expect(first.panes.length, 20);+ expect(app.panes, isEmpty);+ await app.addAgentToSwarm('m', 'a22', swarmId: first.id);+ expect(first.panes.last.agentId, 'a22');+ expect(app.panes, isEmpty);+ await app.closeSwarm(first.id);+ await app.addAgentToSwarm('m', 'a23', swarmId: first.id);+ expect(app.panes, isEmpty);+ app.dispose();+ });++ test('starter capacity is explicit and never evicts selected agents', () async {+ final app = createApp();+ await app.seedSwarm('Large fleet', [for (var i = 0; i < 70; i++) (machineId: 'm', agentId: 'a$i')]);+ expect(app.panes.length, AppNotifier.maxPanes);+ expect(app.lastError, contains('Open another swarm'));+ expect(app.panes.first.agentId, 'a0');+ app.dispose();+ });++ test('all swarm intent, focus, zoom, wallpaper and shared identity restore offline', () async {+ final storage = MemoryStore();+ final app = createApp(store: storage);+ await app.addAgentToSwarm('m', 'a0');+ await app.addAgentToSwarm('m', 'a1');+ app.focusPane(app.panes.first.id);+ app.toggleZoomPane();+ app.setPreset(2, PanePreset.rows);+ app.togglePinPane(app.panes.first.id);+ app.renameSwarm(app.activeSwarmId, 'First');+ final first = app.activeSwarm;+ app.newSwarm(name: 'Second');+ await app.addAgentToSwarm('m', 'a0');+ app.nextSwarmWallpaper();+ final wallpaper = app.activeSwarm.wallpaper;+ await Future<void>.delayed(Duration.zero);+ final restored = createApp(store: storage);+ await restored.restorePaneLayoutForTest();+ expect(restored.swarms.map((s) => s.name), ['First', 'Second']);+ expect(restored.activeSwarm.wallpaper, wallpaper);+ expect(restored.swarms.first.panes.first, same(restored.swarms.last.panes.single));+ expect(restored.allPanes.every((p) => p.session == null), isTrue);+ expect(restored.isPanePinned(restored.panes.single), isFalse);+ restored.selectSwarm(first.id);+ expect(restored.zoomedPaneId, restored.focusedPaneId);+ expect(restored.presetFor(2), PanePreset.rows);+ expect(restored.isPanePinned(restored.panes.first), isTrue);+ app.dispose(); restored.dispose();+ });++ test('new tab ids cannot collide after reorder and gaps in saved ids', () async {+ final app = createApp();+ app.newSwarm(); app.newSwarm(); app.newSwarm();+ await app.closeSwarm('swarm-2');+ app.reorderSwarm('swarm-4', 0);+ app.newSwarm(); app.newSwarm();+ expect(app.swarms.map((s) => s.id).toSet().length, app.swarms.length);+ while (app.swarms.length > 1) { await app.closeSwarm(app.swarms.first.id); }+ await app.closeSwarm(app.activeSwarmId);+ expect(app.swarms.length, 1); expect(app.panes, isEmpty);+ app.dispose();+ });++ test('focus changes follow zoom and wrap without a hidden rail', () async {+ final app = createApp();+ await app.addAgentToSwarm('m', 'a0'); await app.addAgentToSwarm('m', 'a1');+ app.toggleZoomPane();+ app.focusPane(app.panes.first.id);+ expect(app.zoomedPaneId, app.panes.first.id);+ app.focusPaneHorizontally(-1);+ expect(app.railFocused, isFalse);+ expect(app.zoomedPaneId, app.focusedPaneId);+ app.dispose();+ });++ test('same remote groups across machines but matching folder names do not', () {+ final app = createApp();+ final remote = app.machineStates['m']!;+ const second = Machine(machineId: 'n', authMode: MachineAuthMode.remote);+ app.machineStates['n'] = MachineState(second);+ remote.agents = [const Agent(id: 'a', name: 'A', project: AgentProject(name: 'app', cwd: '/one/app', remote: 'github.com/org/app')),+ const Agent(id: 'b', name: 'B', project: AgentProject(name: 'private', cwd: '/one/private'))];+ app.machineStates['n']!.agents = [const Agent(id: 'c', name: 'C', project: AgentProject(name: 'app', cwd: '/two/app', remote: 'github.com/org/app')),+ const Agent(id: 'd', name: 'D', project: AgentProject(name: 'private', cwd: '/one/private'))];+ final groups = swarmProjects(app, []);+ expect(groups.length, 3);+ expect(groups.firstWhere((g) => g.name == 'app').agents.length, 2);+ expect(Agent.fromJson({'id': 'old', 'name': 'Older daemon'}).project, isNull);+ app.dispose();+ });+}diff --git a/desktop/test/terminal_pane_test.dart b/desktop/test/terminal_pane_test.dartindex 10e39dd45..18ce4edd0 100644--- a/desktop/test/terminal_pane_test.dart+++ b/desktop/test/terminal_pane_test.dart@@ -80,7 +80,7 @@ void main() {await app.selectAgent('m1', 'a');await app.selectAgent('m1', 'b');- expect(app.panes.length, 1, reason: 'a click replaces, it does not add');+ expect(app.panes.length, 2, reason: 'selecting adds a view without replacing the existing one');await app.assignAgentToPane(null, 'm1', 'a');expect(app.panes.length, 2);@@ -206,7 +206,8 @@ void main() {// Let the fire-and-forget writes land.await Future<void>.delayed(Duration.zero);- final saved = jsonDecode(storage.values['terminal_pane_layout']!) as List;+ final layout = jsonDecode(storage.values['swarm_layout_v1']!);+ final saved = layout['swarms'][0]['panes'] as List;expect(saved.length, 2, reason: 'the prompt tile is a moment, not a desk');expect(saved.map((e) => e['agentId']), ['a', 'b']);app.dispose();@@ -264,7 +265,7 @@ void main() {);test(- 'a pane keeps its identity when reassigned, so the grid cell survives',+ 'replacing a view gives the new session its own controller identity',() async {final app = _notifier();_machine(app, 'm1', ['a', 'b']);@@ -272,7 +273,7 @@ void main() {final id = app.panes.single.id;await app.assignAgentToPane(id, 'm1', 'b');- expect(app.panes.single.id, id);+ expect(app.panes.single.id, isNot(id));expect(app.panes.single.agentId, 'b');app.dispose();},@@ -402,8 +403,8 @@ void main() {expect(app.panes.single.composerVisible, isTrue);await Future<void>.delayed(Duration.zero);- final restored = await PaneLayoutStore(storage: storage).load();- expect(restored.single.composerVisible, isTrue);+ final restored = await PaneLayoutStore(storage: storage).loadSwarms();+ expect(restored!['swarms'][0]['panes'][0]['composerVisible'], isTrue);app.dispose();});diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdnew file mode 100644index 000000000..b17e24f5d--- /dev/null+++ b/docs/harness-v2-progress.md@@ -0,0 +1,206 @@+# Harness App V2 — development handoff++Updated 2026-09-12. This is a working preview, not a release or a finished implementation.++## Resume here++- Repository: https://github.com/autonomous-ai/autonomous-harness+- Branch: `app-v2`, tracking `origin/app-v2` in that repository.+- Resume folder: `/Users/ab/code/autonomous-harness`.+- Desktop: `desktop/`. CLI: `cli/`. Backend: `backend/`.+- The user reviewed the running native app, liked the direction, and requested that all work move into this monorepo branch. After branch creation and documentation, stop so the user can resume in that folder/branch.+- Continue implementation there. Do not create another repository or fork for V2.++```bash+cd /Users/ab/code/autonomous-harness+git status --short -b+git remote -v+git log -1 --oneline+```++The preview was developed from monorepo commit `9bd8cf1667310def711e8c491c9e6b317cdece78`, then the tip of `internal/monorepo-move`. `app-v2` preserves that history and the current implementation. At migration, `origin/main` was `84a23e5f8d358b78d24ba92ce185b482b5f97ebc`, three commits ahead of this base. Those commits add reboot restoration, change release CI, and fix terminal input sequence recovery; they have **not** been incorporated here. Bring main forward deliberately next session, especially `app_state.dart` and terminal recovery tests. This is already monorepo history, so a later merge requires no repository import.++The former preview folder `/Users/ab/code/harness-app-v2` is retained as a backup and contains the already-built app. Its `origin` now also points at the monorepo; the old personal fork remains under remote name `fork`. The old GitHub fork has not been deleted and is no longer the working destination. The existing `/Users/ab/code/autonomous-harness` checkout was clean before switching from `main` to `app-v2`.++## Product contract and design reference++Harness is one place to work with all your agents. Swarms are named, chosen collections of agent terminal views across machines and projects, shown as real native window tabs on macOS.++- No Models, Grid, permanent workspace sidebar, persistent workspace toolbar, or pane footer.+- Keep native traffic lights. Tabs sit beside them in the title bar, not in a Flutter row below a simulated title bar.+- Empty swarm: wallpaper, search, New agent, machine starters, project starters, Link machine, Add project.+- A machine/project starter seeds membership once. Discovery must not silently alter membership afterward.+- The same agent may belong to multiple swarms. Reuse one session/controller and buffer for it.+- Closing a pane or swarm removes views and must never stop/delete the agent.+- Per-swarm layout, focus, zoom, and wallpaper. Canceling Add agent preserves the view and zoom.+- Rounded dark panes with padding/gaps over plum. Compact header: original colored engine mark, agent, available project/branch, machine, close.+- Small Add agent `+` overlays a pane corner and opens a stable dialog.+- Preserve terminal input, clipboard, resize, remote transports, spoken tasks, and dial routing. Cmd+Enter zoom and Cmd+HJKL directional focus remain.+- Notifications reflect actual pending questions, never fabricated sample statuses.+- New agent uses real engine discovery, working folders, Codex profiles, and permissions. An agent name is not a submitted task prompt.++Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83b32338f44dd675e2ad668519e6d429342d9ff` on `ui-prototype`, pushed to `autonomous-ai/harness-app-landing-page`. Its `HARNESS.md` and `research/conversation-history.md` record product decisions. Six wallpapers were copied from `public/`. This reference informs the existing native Flutter app implementation.++## Implementation map++### Swarm and terminal state++- New `desktop/lib/state/swarm.dart`: tab ID/name/wallpaper, memberships, focus/zoom, presets, measured grid columns, pins.+- `AppNotifier`: swarm list/active swarm; `panes` is active membership, `allPanes` is the deduplicated session pool. Transport event fan-out uses all unique sessions.+- New/select/rename/reorder/close tabs, wallpaper cycling, add-to-swarm, and machine/project seeding.+- Replacing membership creates/reuses a different pane identity instead of mutating a pane shared with another swarm.+- Session detachment waits until the final membership closes. Sends terminal-close, never agent-delete.+- Seeding records membership synchronously before awaiting attachments. Agent creation captures its destination before the RPC completes, so tab switching cannot redirect results.+- Limits: 24 swarms, 64 panes per swarm. Normal add/seed paths report capacity explicitly; legacy migration retains the nine-pane storage limit. A dial capacity exception remains below.+- `PaneLayoutStore` writes `swarm_layout_v1`: tab order/selection/names, wallpaper, pane intent, focus/zoom, presets, per-swarm pins, composer visibility.+- Restore pools shared pane identity, keeps disconnected memberships, and defers initial attachment of inactive panes until shown. Previous focus and measured grid columns currently live in memory; audit whether they need persistence.+- Focus follows zoom and wraps without an invisible sidebar. Legacy `HomeScreen`/rail code remains but is no longer the authenticated V2 shell.+- Agent comparison considers project and launch-state metadata so polling can refresh those details.++### Retained terminal views++- `PaneGrid` swarm mode parks previously displayed inactive terminal widgets under Offstage with ticking/focus disabled and their last visible dimensions preserved.+- `TerminalPane.lastViewSize` retains geometry. Hidden `TerminalPanel` views stop auto-resizing/reporting viewport and release input focus.+- Compact headers remove routine transport/status/pin clutter, retaining exceptional states and offline/unavailable placeholders.+- Existing terminal sessions/transports/renderer and patched `third_party/xterm` are retained. One regression verifies renderer identity, hidden geometry during window resize, and input going only to the active view.+- The old composer grip is hidden in compact mode; add a discoverable replacement entry point.++### Shell and dialogs++- `desktop/lib/screens/swarm_screen.dart` is wired into the authenticated case in `main.dart`.+- `widgets/swarm_welcome.dart`: wallpapers, live search, real machines/projects, New agent. Wallpaper rotates for a new swarm, stays stable, and supports manual next.+- `widgets/swarm_dialogs.dart`: fixed-size Add agent picker, rename, Add project, Link machine entry points.+- Add project saves an **existing folder**, via native local picker or existing remote folder browser. It does not clone a GitHub URL.+- `NewAgentDialog`: machine chooser, initial folder, captured destination swarm; local default when available. Reuses engine probes, Codex profiles, advanced permission behavior, and remote browsing.+- `state/swarm_catalog.dart`: search, project grouping, saved folders (`swarm_projects_v1`). Group by canonical remote if supplied, otherwise owning machine and full folder path; matching basenames never establish identity.+- Notifications come from real blocked agents; selecting an existing membership navigates back to its swarm.+- Spoken-task subscription/reporting/window reveal and existing linking dialogs are retained. Settings is in the title bar.+- Non-macOS/tests use a Flutter reorderable tab-strip fallback. Linux/Windows have not been built or visually reviewed.++### Native macOS tabs++- `desktop/macos/Runner/SwarmTitlebar.swift`, registered in Xcode and owned by `MainFlutterWindow`.+- `NSTitlebarAccessoryViewController` with native scrollable tabs, new button, notification bell, settings. Automatic native window tabbing disabled; Flutter content begins below title bar.+- Method channel `harness/swarm_tabs`: Dart sends tab ID/name/selection/attention; Swift sends new/select/close/rename/reorder/navigation/settings/notifications.+- Native tab click, double-click rename, context menu, close, drag/drop reorder. Tab button instances are retained across refreshes.+- Native Swarm menu includes new/close/rename, previous/next, Add agent, close agent view, Settings.+- Real tabs alongside traffic lights were visually verified. Full native keyboard/drag/accessibility testing remains.++### CLI project metadata++- New `cli/src/lib/agentProject.ts`; `agentFrame.ts` includes its result in the common list/push agent payload.+- Reads cwd, Git root/origin/symbolic branch using bounded `execFile`, no shell/network/repository mutation. Detached HEAD returns no branch.+- Four concurrent folder inspections, 256-entry cache, 15-second TTL, subprocess timeout/output limit.+- Remote normalization strips credentials/transport syntax. Missing/non-Git metadata degrades gracefully; optional Dart `AgentProject` accepts older daemon payloads.+- Production CLI was **not** installed/restarted to expose these fields. Project/branch detail appears only when a daemon running this code reports it. Older daemons still work.++### V2 identity and isolation++- macOS name `Harness V2`, bundle ID `ai.autonomous.harness.v2`.+- Desktop state/log namespace `~/.harness/desktop-app-v2`, including setup logs. CLI transport/login identity remains shared.+- `core/build_identity.dart` marks V2. Default updater checks disabled in `AppNotifier`/`DesktopUpdater`; injected updater tests retain their test path. Native Check for Updates removed.+- Analytics category `harness-desktop-v2`; existing opt-out behavior retained.+- `debugShowCheckedModeBanner` is false in source; first built preview predates this small change.+- Cross-platform product names, About messaging, and manual updater entry points still need follow-up.++## Current shortcuts++| Action | Binding |+| --- | --- |+| New / close swarm | Cmd+T / Cmd+W |+| Rename swarm | Cmd+Shift+R |+| Previous / next swarm | Cmd+Shift+[ / ], Ctrl+Shift+Tab / Ctrl+Tab |+| Add agent picker / New agent | Cmd+Shift+F or Cmd+P / Cmd+N |+| Focus neighboring pane | Cmd+H/J/K/L or Cmd+arrow |+| Move pane | Cmd+Shift+H/J/K/L or Cmd+Shift+arrow |+| Previous / next agent view | Cmd+[ / ] |+| Zoom / previous focus | Cmd+Enter / Cmd+; |+| Focus index | Cmd+1 through Cmd+9 |+| Layout / pin | Cmd+S / Cmd+Shift+P |+| Task palette / reload machines | Cmd+B / Cmd+R |+| Settings / shortcut sheet | Cmd+, / Cmd+/ |+| Close agent view | Cmd+Shift+W in native macOS menu; Flutter binding still needed |++Swarm shortcuts are partly hardcoded in `SwarmScreen`; the old table in `shortcuts/app_shortcuts.dart` still powers help. Consolidate them: help is stale about sidebar, Cmd+W, and Ctrl+Tab. Preserve terminal clipboard/select-all and shell/TUI keys. Do not reintroduce AppKit menu key equivalents that intercept clipboard or Cmd+H/J before Flutter.++## Verification and limits++| Check | Result |+| --- | --- |+| macOS debug build | Passed; `Harness V2.app` launched and visually reviewed. Predates the final small source/test fixes; rebuild next session. |+| Swarm state tests | 8 passed: shared sessions, replacement/pins, async seeding, capacity, restore, tab IDs/close, focus/zoom, grouping. |+| Swarm widget tests | 3 passed: welcome/search/cancel, retained renderer and input isolation, real notification navigation. |+| Crash-log isolation tests | 2 passed. Rechecked with Swarms at migration: **13 passed total**. Widget tap hit-test warning still needs cleanup. |+| CLI typecheck | `npm run typecheck` passed for metadata changes. |+| CLI targeted tests | `agentFrame.spec.ts` + `agentProject.spec.ts`: 9 passed in 2 files. |+| Latest Flutter analyzer | **0 errors, 1 warning, 36 infos**, exits 1. Unused `harness_file_store.dart` import in `app_state.dart`; own brace/import/deprecation cleanup and existing vendored xterm infos. Not a clean pass. |+| Last full Flutter suite | **919 passed, 1 skipped, 21 failed** before subsequent expectation/isolation fixes. Not rerun in full afterward; do not call it green. |+| Production E2E / release | Not run. No release, installer, or production CLI update/restart for this preview. |++Full-suite failures: old replacement/nine-pane/persistence expectations; five boot-flow tests expecting removed sidebar; four dial expectations; old store/analytics namespace assertions; crash log; two Usage copy assertions; two shortcut-deck assertions. Some updates are in `terminal_pane_test.dart`, `pane_lattice_test.dart`, `dial_desk_test.dart`, and `harness_file_store_test.dart`; review and rerun. Do not call Usage/shortcut failures baseline without checking. The first updated dial test may still have an inconsistent pane-count assertion.++**Test isolation incident:** the original upstream crash-log test deleted real default `~/.harness/desktop-app/errors.log` if it existed. The suite ran before discovery, so the previous error log may have been removed; the user was informed. The test now uses a disposable temporary directory, and `CrashLog.record` skips test file I/O unless `CrashLog.testFile` is supplied. Do not rerun the original unisolated test or claim no production file could have been affected. No terminal data, agent processes, or user project files were intentionally modified by tests.++Evidence on this Mac under `/private/tmp`:++- `harness-v2-build.log`: first successful build.+- `harness-v2-cli-check.log`, `harness-v2-cli-tests.log`: CLI checks.+- `harness-v2-all-tests.log`: full-suite result above.+- `harness-v2-migration-analyze.log`: latest analyzer, 37 diagnostics.+- `harness-v2-migration-tests.log`: latest focused 13-test pass.+- `harness-v2-branch-migration.json`: SHA-256 inventory of all 45 changed/new files before migration; this handoff is intentionally rewritten afterward.++Older `harness-v2-analyze.log` and `harness-v2-swarm-tests.log` contain failures since fixed. Use migration logs for latest focused results. Temporary logs/toolchain are local conveniences, not committed artifacts.++## Remaining work, in recommended order++1. Review/incorporate current main, especially terminal sequence recovery; preserve Swarm fan-out in `app_state.dart`.+2. Remove unused import; format/lint changed Dart files; change fallback `onReorder` to `onReorderItem` with its already-adjusted index. Leave vendored xterm style alone.+3. Finish full-suite transition and rerun. Boot-flow tests must exercise Swarm welcome/settings/linking. Fix behavior, not just assertions. Investigate Usage/shortcut failures and widget tap warning.+4. Known bug: `openAgentFromDial` still replaces the last membership at capacity. Use explicit capacity handling or a deliberate new swarm, no silent eviction.+5. Centralize Swarm shortcuts/help; add Flutter Cmd+Shift+W; audit native menu conflicts and shortcuts while dialogs/settings are open.+6. Restore discoverable composer access in compact mode and account/sign-out access in Settings after removal of old sidebar footer.+7. About must say Harness V2 and accurately describe disabled updates. Audit manual/apply updater paths; finish Linux/Windows identity before testing those builds.+8. Add meaningful async launch tests for tab switch/close/disposal during RPC and machine change during folder/profile probes. Audit restore revision guard after legacy asynchronous loads, not just initial load.+9. Handle project-store write errors visibly; audit load/add races. Consider normalizing explicit default Git ports (SSH 22) across transports.+10. Native QA: drag/reorder, close-last-tab, rename, overflow, shortcuts, accessibility of tab close subbuttons. CUA exposed parent buttons; independently accessible close controls still need checking.+11. Rebuild/review final source; run justified local-only terminal integration checks with disposable fixtures and separate test identity. Never automatically take over a user's terminal or replace the review app with an integration runner.++Items 4–7 are known gaps; async/persistence/accessibility/cross-platform items include pending audits, not claims each path already failed.++## Toolchain and workflow++Read `desktop/CLAUDE.md`. No AGENTS.md was found in this checkout/ancestors during implementation. Some architecture/integration-test comments there are stale; prefer current source and analyzer evidence. This is a native app, not Sites. No subagents were requested.++Flutter **3.47.2 / Dart 3.13.2** lives at `/private/tmp/harness-v2-flutter`, matching release pin. Swift Package Manager is required. Tool settings are isolated under `/private/tmp/harness-v2-tool-config`; npm cache under `/private/tmp/harness-v2-npm-cache`.++```bash+cd /Users/ab/code/autonomous-harness/desktop+export XDG_CONFIG_HOME=/private/tmp/harness-v2-tool-config+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics config --enable-swift-package-manager+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics pub get --offline+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics analyze --no-pub+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics test --no-pub test/swarm_state_test.dart test/swarm_screen_test.dart test/crash_log_test.dart+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics test --no-pub+/private/tmp/harness-v2-flutter/bin/flutter --suppress-analytics build macos --debug --no-pub+open -n 'build/macos/Build/Products/Debug/Harness V2.app'+```++Use online `pub get` if packages are not cached. Enable SPM before pub get; do not accept CocoaPods fallback rewriting the project. Do not commit generated build/ephemeral files or caches. Analyzer currently needs cleanup; `--no-fatal-infos` is useful once warnings are resolved and does not erase remaining infos.++```bash+cd /Users/ab/code/autonomous-harness/cli+npm ci --ignore-scripts --cache /private/tmp/harness-v2-npm-cache --no-audit --no-fund+npm run typecheck+npx vitest run src/lib/agentFrame.spec.ts src/lib/agentProject.spec.ts+```++Some tests require permission to bind disposable loopback sockets. Inject memory/temp stores, skip real credential/usage pollers using `kUnderTest`, and never treat a real Harness home as a fixture. Keep patched `desktop/third_party/xterm`, not pub.dev xterm.++The app open for review was launched from `/Users/ab/code/harness-app-v2/desktop/build/macos/Build/Products/Debug/Harness V2.app`. It has the separate V2 bundle identity. The user has been interacting with it, opening swarms and saving a project; leave those views alone during migration. Another-app-controls-terminal is a real ownership state, not permission to take over. Building in the new folder does not move the running process; coordinate the next V2 relaunch and preserve saved state.++## Publishing boundaries++The user authorized publishing branch `app-v2` in `autonomous-ai/autonomous-harness` for later merging. This is not authorization to merge, release/tag, publish binaries, run production E2E, update/restart the production CLI, or delete the old fork. No PR is needed yet.++Workflow triggers were checked: CI runs for PRs/manual calls; internal desktop builds for `internal/**`; release/deployment for suffixed tags. A plain `app-v2` push does not trigger those release workflows. Keep future work/pushes on `app-v2` unless the user changes that instruction.